Skip to main content

lean_ctx/core/
evidence_bundle.rs

1//! Evidence bundle generator (`evidence-bundle-v1`, GL #425, H3 Epic A).
2//!
3//! Composes the engine's evidence surfaces — audit-chain segment, resolved
4//! policy pack, coverage reports — into one deterministic, offline-
5//! verifiable ZIP. The independent verifier lives in
6//! `packages/leanctx-verify/` and implements the contract
7//! (`docs/contracts/evidence-bundle-v1.md`), not this code.
8//!
9//! Determinism: identical inputs ⇒ byte-identical archive (sorted entry
10//! order, Stored compression, ZIP-epoch timestamps, canonical JSON, no
11//! wall-clock fields in the manifest).
12
13use serde_json::{Value, json};
14use std::io::Write;
15use std::path::{Path, PathBuf};
16
17use super::audit_trail::AuditEntry;
18use super::canonical::{canonical_serialize, sign_manifest};
19
20const SIGNING_AGENT: &str = "lean-ctx";
21
22pub struct BundleSpec {
23    /// RFC 3339 inclusive lower bound.
24    pub from: String,
25    /// RFC 3339 inclusive upper bound.
26    pub to: String,
27    /// Framework mapping to include a coverage report for.
28    pub framework: Option<String>,
29    /// Pack name/path override; defaults to the framework reference pack,
30    /// the project pack, or `baseline` (first match wins).
31    pub pack: Option<String>,
32    pub out: Option<PathBuf>,
33}
34
35#[derive(Debug)]
36pub struct BundleResult {
37    pub path: PathBuf,
38    pub sha256: String,
39    pub entries: usize,
40    pub files: Vec<String>,
41}
42
43/// Build a signed evidence bundle from already-materialized run artifacts.
44///
45/// Unlike [`generate`], this does not infer an audit period or policy pack.
46/// It is for flows that have already captured their complete evidence set and
47/// need an offline-verifiable archive containing those exact bytes.
48pub fn generate_artifact_bundle(
49    out: &Path,
50    mut files: Vec<(String, Vec<u8>)>,
51    run_metadata: &Value,
52    signing_key: &super::canonical::AgentIdentity,
53) -> Result<BundleResult, String> {
54    if files.is_empty() {
55        return Err("evidence artifact bundle requires at least one file".to_string());
56    }
57
58    files.sort_by(|left, right| left.0.cmp(&right.0));
59    let mut seen_paths = std::collections::BTreeSet::new();
60    for (path, _) in &files {
61        if path == "manifest.json" || !safe_artifact_path(path) {
62            return Err(format!("unsafe evidence artifact path: {path}"));
63        }
64        if !seen_paths.insert(path) {
65            return Err(format!("duplicate evidence artifact path: {path}"));
66        }
67    }
68
69    let project = std::env::current_dir()
70        .ok()
71        .and_then(|dir| {
72            dir.file_name()
73                .map(|name| name.to_string_lossy().into_owned())
74        })
75        .unwrap_or_else(|| "unknown".to_string());
76    let file_hashes: Vec<Value> = files
77        .iter()
78        .map(|(path, bytes)| json!({ "path": path, "sha256": sha256_hex(bytes) }))
79        .collect();
80    let public_key =
81        crate::core::agent_identity::hex_encode(signing_key.verifying_key().as_bytes());
82    let mut manifest = json!({
83        "bundle": "evidence-bundle",
84        "version": 1,
85        "subject": { "agent_id": SIGNING_AGENT, "project": project },
86        "run": run_metadata,
87        "files": file_hashes,
88        "signing": {
89            "algorithm": "ed25519",
90            "public_key": public_key,
91            "signed_digest": "",
92            "signature": "",
93        },
94    });
95
96    // The offline verifier signs the canonical SHA-256 digest with both
97    // signing fields reset to empty strings.  Preserve that contract here.
98    let digest = sha256_hex(&canonical_serialize(&manifest));
99    manifest["signing"]["signed_digest"] = Value::String(digest.clone());
100    let signature = crate::core::agent_identity::hex_encode(
101        &crate::core::agent_identity::sign_bytes_with(signing_key, digest.as_bytes()),
102    );
103    manifest["signing"]["signature"] = Value::String(signature);
104
105    files.push(("manifest.json".to_string(), canonical_serialize(&manifest)));
106    files.sort_by(|left, right| left.0.cmp(&right.0));
107
108    let mut bytes = Vec::new();
109    {
110        let mut zip = zip::ZipWriter::new(std::io::Cursor::new(&mut bytes));
111        let options: zip::write::SimpleFileOptions = zip::write::SimpleFileOptions::default()
112            .compression_method(zip::CompressionMethod::Stored)
113            .last_modified_time(zip::DateTime::default());
114        for (path, contents) in &files {
115            zip.start_file(path, options)
116                .map_err(|error| error.to_string())?;
117            zip.write_all(contents).map_err(|error| error.to_string())?;
118        }
119        zip.finish().map_err(|error| error.to_string())?;
120    }
121    std::fs::write(out, &bytes).map_err(|error| format!("write {}: {error}", out.display()))?;
122
123    Ok(BundleResult {
124        path: out.to_path_buf(),
125        sha256: sha256_hex(&bytes),
126        entries: files.len() - 1,
127        files: files.into_iter().map(|(path, _)| path).collect(),
128    })
129}
130
131fn safe_artifact_path(path: &str) -> bool {
132    let path = Path::new(path);
133    !path.is_absolute()
134        && !path
135            .components()
136            .any(|component| matches!(component, std::path::Component::ParentDir))
137}
138
139fn sha256_hex(bytes: &[u8]) -> String {
140    use sha2::{Digest, Sha256};
141    let mut hasher = Sha256::new();
142    hasher.update(bytes);
143    crate::core::agent_identity::hex_encode(&hasher.finalize())
144}
145
146/// Generate the bundle. Fails loudly on every inconsistency — an evidence
147/// artifact with silently missing parts would be worse than none.
148pub fn generate(spec: &BundleSpec) -> Result<BundleResult, String> {
149    let from = chrono::DateTime::parse_from_rfc3339(&spec.from)
150        .map_err(|e| format!("--from is not RFC 3339: {e}"))?;
151    let to = chrono::DateTime::parse_from_rfc3339(&spec.to)
152        .map_err(|e| format!("--to is not RFC 3339: {e}"))?;
153    if from > to {
154        return Err("--from must not be after --to".to_string());
155    }
156
157    // ── audit segment (original lines preserved — hash-stable) ──────────
158    let trail_path = crate::core::data_dir::lean_ctx_data_dir()
159        .map_err(|e| format!("data dir: {e}"))?
160        .join("audit")
161        .join("trail.jsonl");
162    let trail_raw = std::fs::read_to_string(&trail_path)
163        .map_err(|e| format!("no audit trail at {}: {e}", trail_path.display()))?;
164
165    let mut segment_lines: Vec<String> = Vec::new();
166    let mut anchor_prev_hash: Option<String> = None;
167    let mut head_hash = String::new();
168    for (lineno, line) in trail_raw.lines().enumerate() {
169        // Concurrent appends have historically produced lines holding two
170        // back-to-back JSON objects (`…}{…`). A stream deserializer splits
171        // them losslessly — entry hashes are untouched, so the chain still
172        // proves integrity. Lines that don't parse AT ALL are tolerated
173        // only outside the attested window; inside it they are a hard
174        // error — an evidence artifact must never paper over a gap.
175        let mut stream = serde_json::Deserializer::from_str(line).into_iter::<serde_json::Value>();
176        let mut parsed_any = false;
177        loop {
178            let value = match stream.next() {
179                None => break,
180                Some(Ok(v)) => v,
181                Some(Err(e)) => {
182                    if segment_lines.is_empty() && !parsed_any {
183                        break; // pre-window garbage
184                    }
185                    return Err(format!(
186                        "corrupt trail line {} inside the attested period: {e}",
187                        lineno + 1
188                    ));
189                }
190            };
191            parsed_any = true;
192            let entry: AuditEntry = match serde_json::from_value(value) {
193                Ok(e) => e,
194                Err(e) => {
195                    if segment_lines.is_empty() {
196                        continue;
197                    }
198                    return Err(format!("malformed audit entry at line {}: {e}", lineno + 1));
199                }
200            };
201            let ts = chrono::DateTime::parse_from_rfc3339(&entry.timestamp)
202                .map_err(|e| format!("corrupt trail timestamp at line {}: {e}", lineno + 1))?;
203            if ts < from || ts > to {
204                continue;
205            }
206            if anchor_prev_hash.is_none() {
207                anchor_prev_hash = Some(entry.prev_hash.clone());
208            }
209            head_hash.clone_from(&entry.entry_hash);
210            // Re-serialize one-object-per-line; field order is the struct's
211            // declaration order, identical to what `record()` writes.
212            segment_lines.push(serde_json::to_string(&entry).map_err(|e| e.to_string())?);
213        }
214    }
215    if segment_lines.is_empty() {
216        return Err(format!(
217            "no audit entries between {} and {} — nothing to attest",
218            spec.from, spec.to
219        ));
220    }
221    let audit_jsonl = format!("{}\n", segment_lines.join("\n"));
222    let anchor_prev_hash = anchor_prev_hash.expect("non-empty segment");
223
224    // ── policy pack (resolved view) ──────────────────────────────────────
225    let pack_name = spec.pack.clone().unwrap_or_else(|| {
226        spec.framework
227            .as_deref()
228            .and_then(|fw| crate::core::compliance::get(fw))
229            .map_or_else(
230                || {
231                    if Path::new(".lean-ctx/policy.toml").exists() {
232                        ".lean-ctx/policy.toml".to_string()
233                    } else {
234                        "baseline".to_string()
235                    }
236                },
237                |m| m.reference_pack.clone(),
238            )
239    });
240    let pack = if Path::new(&pack_name)
241        .extension()
242        .is_some_and(|e| e.eq_ignore_ascii_case("toml"))
243    {
244        crate::core::policy::parse_file(Path::new(&pack_name))
245            .map_err(|e| format!("pack {pack_name}: {e}"))?
246    } else {
247        crate::core::policy::builtin::get(&pack_name)
248            .ok_or_else(|| format!("unknown builtin pack '{pack_name}'"))?
249    };
250    let resolved =
251        crate::core::policy::resolve(&pack).map_err(|e| format!("pack {pack_name}: {e}"))?;
252    let resolved_value = serde_json::to_value(&resolved).map_err(|e| e.to_string())?;
253    let policy_file = (
254        format!("policies/{}.resolved.json", resolved.name),
255        canonical_serialize(&resolved_value),
256    );
257
258    // ── coverage reports ─────────────────────────────────────────────────
259    let cgb_checks = crate::core::policy::coverage::assess(&resolved);
260    let cgb_doc = json!({
261        "benchmark": crate::core::policy::coverage::BENCHMARK_ID,
262        "pack": { "name": resolved.name, "version": resolved.version },
263        "checks": serde_json::to_value(&cgb_checks).map_err(|e| e.to_string())?,
264        "summary": serde_json::to_value(crate::core::policy::coverage::summarize(&cgb_checks))
265            .map_err(|e| e.to_string())?,
266    });
267    let mut files: Vec<(String, Vec<u8>)> = vec![
268        ("audit/trail.jsonl".to_string(), audit_jsonl.into_bytes()),
269        policy_file,
270        (
271            "coverage/cgb.json".to_string(),
272            canonical_serialize(&cgb_doc),
273        ),
274    ];
275
276    if let Some(fw) = &spec.framework {
277        let mapping = crate::core::compliance::get(fw).ok_or_else(|| {
278            format!(
279                "unknown framework '{fw}' (supported: {})",
280                crate::core::compliance::names().join(", ")
281            )
282        })?;
283        let report = crate::core::compliance::report(mapping, Some(&resolved));
284        let value = serde_json::to_value(&report).map_err(|e| e.to_string())?;
285        files.push((format!("coverage/{fw}.json"), canonical_serialize(&value)));
286    }
287
288    files.sort_by(|a, b| a.0.cmp(&b.0));
289
290    // ── manifest ─────────────────────────────────────────────────────────
291    let project = std::env::current_dir()
292        .ok()
293        .and_then(|d| d.file_name().map(|n| n.to_string_lossy().into_owned()))
294        .unwrap_or_else(|| "unknown".to_string());
295
296    let file_hashes: Vec<Value> = files
297        .iter()
298        .map(|(path, bytes)| json!({ "path": path, "sha256": sha256_hex(bytes) }))
299        .collect();
300
301    // Resolve the keypair once: the public key goes into the manifest and the
302    // signature is computed over the canonical manifest — both must come from
303    // the same key or the embedded key can never verify the signature.
304    let signing_key = crate::core::agent_identity::get_or_create_keypair(SIGNING_AGENT)
305        .map_err(|e| format!("signing identity: {e}"))?;
306    let public_key =
307        crate::core::agent_identity::hex_encode(signing_key.verifying_key().as_bytes());
308
309    let mut manifest = json!({
310        "bundle": "evidence-bundle",
311        "version": 1,
312        "period": { "from": spec.from, "to": spec.to },
313        "subject": { "agent_id": SIGNING_AGENT, "project": project },
314        "framework": spec.framework,
315        "files": file_hashes,
316        "chain": {
317            "entries": segment_lines.len(),
318            "anchor_prev_hash": anchor_prev_hash,
319            "head_hash": head_hash,
320        },
321        "signing": {
322            "algorithm": "ed25519",
323            "public_key": public_key,
324            "signed_digest": "",
325            "signature": "",
326        }
327    });
328
329    let digest = sha256_hex(&canonical_serialize(&manifest));
330    manifest["signing"]["signed_digest"] = Value::String(digest);
331    let signature =
332        sign_manifest(&manifest, &signing_key).map_err(|e| format!("manifest signature: {e}"))?;
333    manifest["signing"]["signature"] = Value::String(signature);
334
335    // manifest.json sorts first lexicographically anyway, but be explicit.
336    files.insert(
337        0,
338        ("manifest.json".to_string(), canonical_serialize(&manifest)),
339    );
340    files.sort_by(|a, b| a.0.cmp(&b.0));
341
342    // ── deterministic ZIP ────────────────────────────────────────────────
343    let out_path = spec.out.clone().unwrap_or_else(|| {
344        PathBuf::from(format!(
345            "evidence-bundle_{}_{}.zip",
346            spec.from.replace(':', ""),
347            spec.to.replace(':', "")
348        ))
349    });
350    let mut buf: Vec<u8> = Vec::new();
351    {
352        let mut zip = zip::ZipWriter::new(std::io::Cursor::new(&mut buf));
353        let options: zip::write::SimpleFileOptions = zip::write::SimpleFileOptions::default()
354            .compression_method(zip::CompressionMethod::Stored)
355            .last_modified_time(zip::DateTime::default());
356        for (path, bytes) in &files {
357            zip.start_file(path, options).map_err(|e| e.to_string())?;
358            zip.write_all(bytes).map_err(|e| e.to_string())?;
359        }
360        zip.finish().map_err(|e| e.to_string())?;
361    }
362    std::fs::write(&out_path, &buf).map_err(|e| format!("write {}: {e}", out_path.display()))?;
363
364    Ok(BundleResult {
365        path: out_path,
366        sha256: sha256_hex(&buf),
367        entries: segment_lines.len(),
368        files: files.into_iter().map(|(p, _)| p).collect(),
369    })
370}