1#[allow(dead_code, unused_imports)]
3use anyhow::{Context, Result};
4use clap::Parser;
5use serde::Serialize;
6use serde_json::Value;
7use sha2::{Digest, Sha256};
8use std::collections::{BTreeMap, BTreeSet};
9use std::fs::{self, File};
10use std::io::Read;
11use std::path::{Component, Path, PathBuf};
12use zip::ZipArchive;
13
14#[derive(Debug, Clone, Parser)]
16#[command(name = "lean-ctx verify", about = "Verify an evidence bundle offline")]
17pub struct VerifyCommand {
18 #[arg(value_name = "BUNDLE_PATH", value_hint = clap::ValueHint::FilePath)]
20 pub bundle_path: PathBuf,
21
22 #[arg(
24 long = "public-key",
25 alias = "pubkey",
26 value_name = "PATH",
27 value_hint = clap::ValueHint::FilePath
28 )]
29 pub public_key: Option<PathBuf>,
30
31 #[arg(short, long)]
33 pub verbose: bool,
34
35 #[arg(long = "json-output", alias = "json")]
37 pub json_output: bool,
38}
39
40#[derive(Debug, Clone, Serialize)]
41pub struct VerifyResult {
42 pub bundle_valid: bool,
43 pub manifest_intact: bool,
44 pub signature_valid: bool,
45 pub files_verified: Vec<FileVerification>,
46 pub errors: Vec<String>,
47 pub warnings: Vec<String>,
48}
49
50#[derive(Debug, Clone, Serialize)]
51pub struct FileVerification {
52 pub path: String,
53 pub expected_hash: String,
54 pub actual_hash: String,
55 pub valid: bool,
56}
57
58pub fn execute_verify(cmd: &VerifyCommand) -> Result<VerifyResult> {
60 let mut result = VerifyResult {
61 bundle_valid: false,
62 manifest_intact: false,
63 signature_valid: false,
64 files_verified: Vec::new(),
65 errors: Vec::new(),
66 warnings: Vec::new(),
67 };
68
69 let entries = match read_zip_entries(&cmd.bundle_path) {
70 Ok(entries) => entries,
71 Err(error) => {
72 result
73 .errors
74 .push(format!("cannot open evidence bundle: {error:#}"));
75 return Ok(result);
76 }
77 };
78
79 let Some(manifest_bytes) = entries.get("manifest.json") else {
80 result.errors.push("missing manifest.json".to_string());
81 return Ok(result);
82 };
83
84 let manifest: Value = match serde_json::from_slice(manifest_bytes) {
85 Ok(manifest) => manifest,
86 Err(error) => {
87 result
88 .errors
89 .push(format!("manifest.json is not valid JSON: {error}"));
90 return Ok(result);
91 }
92 };
93
94 validate_manifest_shape(&manifest, &mut result.errors);
95 let listed_paths = manifest_file_paths(&manifest);
96 result.manifest_intact = verify_manifest_files(
97 &manifest,
98 &entries,
99 &mut result.files_verified,
100 &mut result.errors,
101 );
102
103 for path in entries.keys() {
104 if path != "manifest.json" && !listed_paths.contains(path) {
105 result
106 .warnings
107 .push(format!("unlisted file in bundle: {path}"));
108 }
109 }
110
111 result.signature_valid = verify_manifest_signature(
112 &manifest,
113 cmd.public_key.as_deref(),
114 &mut result.errors,
115 &mut result.warnings,
116 );
117 result.bundle_valid =
118 result.manifest_intact && result.signature_valid && result.errors.is_empty();
119
120 Ok(result)
121}
122
123fn read_zip_entries(path: &Path) -> Result<BTreeMap<String, Vec<u8>>> {
124 let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
125 let mut archive = ZipArchive::new(file).context("read ZIP archive")?;
126 let mut entries = BTreeMap::new();
127
128 for index in 0..archive.len() {
129 let mut entry = archive
130 .by_index(index)
131 .with_context(|| format!("read ZIP entry {index}"))?;
132 if entry.is_dir() {
133 continue;
134 }
135
136 let name = entry
137 .name()
138 .with_context(|| format!("read ZIP entry {index} name"))?
139 .into_owned();
140 if entries.contains_key(&name) {
141 anyhow::bail!("duplicate ZIP entry: {name}");
142 }
143
144 let mut bytes = Vec::new();
145 entry
146 .read_to_end(&mut bytes)
147 .with_context(|| format!("read ZIP entry {name}"))?;
148 entries.insert(name, bytes);
149 }
150
151 Ok(entries)
152}
153
154fn validate_manifest_shape(manifest: &Value, errors: &mut Vec<String>) -> bool {
155 let mut valid = true;
156 if manifest.get("bundle").and_then(Value::as_str) != Some("evidence-bundle") {
157 errors.push("manifest bundle must be \"evidence-bundle\"".to_string());
158 valid = false;
159 }
160 if manifest.get("version").and_then(Value::as_u64) != Some(1) {
161 errors.push("unsupported or missing evidence-bundle manifest version".to_string());
162 valid = false;
163 }
164 if !manifest.get("files").is_some_and(Value::is_array) {
165 errors.push("manifest files must be an array".to_string());
166 valid = false;
167 }
168 valid
169}
170
171fn manifest_file_paths(manifest: &Value) -> BTreeSet<String> {
172 manifest
173 .get("files")
174 .and_then(Value::as_array)
175 .into_iter()
176 .flatten()
177 .filter_map(|file| file.get("path").and_then(Value::as_str))
178 .map(str::to_owned)
179 .collect()
180}
181
182fn verify_manifest_files(
183 manifest: &Value,
184 entries: &BTreeMap<String, Vec<u8>>,
185 files_verified: &mut Vec<FileVerification>,
186 errors: &mut Vec<String>,
187) -> bool {
188 let Some(files) = manifest.get("files").and_then(Value::as_array) else {
189 return false;
190 };
191
192 let mut valid = true;
193 let mut seen = BTreeSet::new();
194 for file in files {
195 let Some(path) = file.get("path").and_then(Value::as_str) else {
196 errors.push("manifest file entry is missing a path".to_string());
197 valid = false;
198 continue;
199 };
200 let expected_hash = file
201 .get("sha256")
202 .and_then(Value::as_str)
203 .unwrap_or_default()
204 .to_string();
205
206 if !seen.insert(path.to_string()) {
207 errors.push(format!("duplicate manifest file entry: {path}"));
208 valid = false;
209 }
210 if !safe_bundle_path(path) {
211 errors.push(format!("unsafe manifest file path: {path}"));
212 files_verified.push(FileVerification {
213 path: path.to_string(),
214 expected_hash,
215 actual_hash: String::new(),
216 valid: false,
217 });
218 valid = false;
219 continue;
220 }
221
222 let Some(bytes) = entries.get(path) else {
223 errors.push(format!("missing file listed in manifest: {path}"));
224 files_verified.push(FileVerification {
225 path: path.to_string(),
226 expected_hash,
227 actual_hash: String::new(),
228 valid: false,
229 });
230 valid = false;
231 continue;
232 };
233
234 let actual_hash = sha256_hex(bytes);
235 let hash_format_valid = expected_hash.len() == 64
236 && lean_ctx::core::agent_identity::hex_decode(&expected_hash).is_ok();
237 let file_valid = hash_format_valid && expected_hash.eq_ignore_ascii_case(&actual_hash);
238 if !hash_format_valid {
239 errors.push(format!("invalid SHA-256 hash for manifest file: {path}"));
240 } else if !file_valid {
241 errors.push(format!(
242 "hash mismatch for {path}: expected {expected_hash}, got {actual_hash}"
243 ));
244 }
245 if !file_valid {
246 valid = false;
247 }
248 files_verified.push(FileVerification {
249 path: path.to_string(),
250 expected_hash,
251 actual_hash,
252 valid: file_valid,
253 });
254 }
255
256 valid
257}
258
259fn safe_bundle_path(path: &str) -> bool {
260 let path = Path::new(path);
261 !path.is_absolute()
262 && !path
263 .components()
264 .any(|component| matches!(component, Component::ParentDir))
265}
266
267fn verify_manifest_signature(
268 manifest: &Value,
269 external_public_key: Option<&Path>,
270 errors: &mut Vec<String>,
271 warnings: &mut Vec<String>,
272) -> bool {
273 let Some(signing) = manifest.get("signing").and_then(Value::as_object) else {
274 errors.push("manifest signing section is missing".to_string());
275 return false;
276 };
277 if signing.get("algorithm").and_then(Value::as_str) != Some("ed25519") {
278 errors.push("manifest signing algorithm is not ed25519".to_string());
279 }
280
281 let embedded_key = if let Some(value) = signing.get("public_key").and_then(Value::as_str) {
282 match lean_ctx::core::agent_identity::hex_decode(value) {
283 Ok(bytes) if bytes.len() == 32 => Some(bytes),
284 Ok(_) => {
285 if external_public_key.is_none() {
286 errors.push("manifest Ed25519 public key must contain 32 bytes".to_string());
287 } else {
288 warnings.push("embedded manifest public key is invalid".to_string());
289 }
290 None
291 }
292 Err(error) => {
293 if external_public_key.is_none() {
294 errors.push(format!("invalid manifest public key: {error}"));
295 } else {
296 warnings.push(format!("embedded manifest public key is invalid: {error}"));
297 }
298 None
299 }
300 }
301 } else {
302 if external_public_key.is_none() {
303 errors.push("manifest public key is missing".to_string());
304 } else {
305 warnings.push("manifest has no embedded public key".to_string());
306 }
307 None
308 };
309
310 let public_key = match external_public_key {
311 Some(path) => match read_public_key(path) {
312 Ok(bytes) => {
313 if let Some(embedded) = &embedded_key {
314 if embedded != &bytes {
315 warnings.push(
316 "external public key differs from the embedded public key".to_string(),
317 );
318 }
319 }
320 warnings.push("signature checked with external public key".to_string());
321 bytes
322 }
323 Err(error) => {
324 errors.push(format!("cannot read external public key: {error:#}"));
325 return false;
326 }
327 },
328 None => match embedded_key {
329 Some(bytes) => bytes,
330 None => return false,
331 },
332 };
333
334 let Some(expected_digest) = signing.get("signed_digest").and_then(Value::as_str) else {
335 errors.push("manifest signed_digest is missing".to_string());
336 return false;
337 };
338 let Some(signature_hex) = signing.get("signature").and_then(Value::as_str) else {
339 errors.push("manifest signature is missing".to_string());
340 return false;
341 };
342
343 let mut unsigned_manifest = manifest.clone();
344 let Some(unsigned_signing) = unsigned_manifest
345 .get_mut("signing")
346 .and_then(Value::as_object_mut)
347 else {
348 errors.push("manifest signing section is malformed".to_string());
349 return false;
350 };
351 unsigned_signing.insert("signed_digest".to_string(), Value::String(String::new()));
353 unsigned_signing.insert("signature".to_string(), Value::String(String::new()));
354
355 let canonical_manifest = lean_ctx::core::canonical::canonical_json_bytes(&unsigned_manifest);
356 let computed_digest = sha256_hex(&canonical_manifest);
357 let digest_valid = expected_digest.eq_ignore_ascii_case(&computed_digest);
358 if !digest_valid {
359 errors.push(format!(
360 "manifest digest mismatch: expected {expected_digest}, got {computed_digest}"
361 ));
362 }
363
364 let signature = match decode_signature(signature_hex) {
365 Ok(sig) => sig,
366 Err(error) => {
367 errors.push(format!("invalid manifest signature: {error}"));
368 return false;
369 }
370 };
371 let cryptographically_valid =
374 lean_ctx::core::canonical::verify_manifest_signature(manifest, &public_key)
375 .unwrap_or(false)
376 || {
377 let canon_v2 = lean_ctx::core::canonical::canonical_serialize(&unsigned_manifest);
379 lean_ctx::core::agent_identity::verify_signature(&public_key, &canon_v2, &signature)
380 }
381 || lean_ctx::core::agent_identity::verify_signature(
382 &public_key,
383 &canonical_manifest,
384 &signature,
385 )
386 || lean_ctx::core::agent_identity::verify_signature(
387 &public_key,
388 computed_digest.as_bytes(),
389 &signature,
390 );
391 if !cryptographically_valid {
392 errors.push("manifest signature verification failed".to_string());
393 }
394
395 digest_valid && cryptographically_valid
396}
397
398fn decode_signature(encoded: &str) -> Result<Vec<u8>, String> {
399 use base64::Engine;
400 if let Ok(bytes) = lean_ctx::core::agent_identity::hex_decode(encoded) {
401 if bytes.len() == 64 {
402 return Ok(bytes);
403 }
404 }
405 if let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(encoded) {
406 if bytes.len() == 64 {
407 return Ok(bytes);
408 }
409 }
410 Err(format!(
411 "signature must be 64 bytes (hex or base64), got {} chars",
412 encoded.len()
413 ))
414}
415
416fn read_public_key(path: &Path) -> Result<Vec<u8>> {
417 let bytes = fs::read(path).with_context(|| format!("read {}", path.display()))?;
418 if bytes.len() == 32 {
419 return Ok(bytes);
420 }
421 let text = std::str::from_utf8(&bytes)
422 .context("public key is neither 32 raw bytes nor UTF-8 hexadecimal")?;
423 let decoded = lean_ctx::core::agent_identity::hex_decode(text.trim())
424 .map_err(|error| anyhow::anyhow!("decode hexadecimal public key: {error}"))?;
425 if decoded.len() != 32 {
426 anyhow::bail!("public key must contain 32 bytes");
427 }
428 Ok(decoded)
429}
430
431fn sha256_hex(bytes: &[u8]) -> String {
432 let mut hasher = Sha256::new();
433 hasher.update(bytes);
434 lean_ctx::core::agent_identity::hex_encode(&hasher.finalize())
435}
436
437pub(crate) fn looks_like_bundle_command(args: &[String]) -> bool {
440 let mut consumes_next = false;
441 for arg in args {
442 if consumes_next {
443 consumes_next = false;
444 continue;
445 }
446 match arg.as_str() {
447 "--public-key" | "--pubkey" | "--format" => {
448 consumes_next = true;
449 }
450 "--" => return true,
451 "--json" | "--json-output" | "--verbose" | "-v" => {}
452 _ if arg.starts_with("--public-key=")
453 || arg.starts_with("--pubkey=")
454 || arg.starts_with("--format=") => {}
455 _ if arg.starts_with('-') => {}
456 _ => return true,
457 }
458 }
459 false
460}
461
462pub(crate) fn run(args: &[String]) -> i32 {
464 let mut argv = Vec::with_capacity(args.len() + 1);
465 argv.push("lean-ctx".to_string());
466 argv.extend(args.iter().cloned());
467
468 let command = match VerifyCommand::try_parse_from(argv) {
469 Ok(command) => command,
470 Err(error) => {
471 let code = error.exit_code();
472 eprint!("{error}");
473 return code;
474 }
475 };
476
477 match execute_verify(&command) {
478 Ok(result) => {
479 let valid = result.bundle_valid;
480 if command.json_output {
481 match serde_json::to_string_pretty(&result) {
482 Ok(json) => println!("{json}"),
483 Err(error) => {
484 eprintln!("verify: cannot serialize result: {error}");
485 return 1;
486 }
487 }
488 } else {
489 print_human_result(&result, command.verbose);
490 }
491 i32::from(!valid)
492 }
493 Err(error) => {
494 eprintln!("verify: {error:#}");
495 1
496 }
497 }
498}
499
500fn print_human_result(result: &VerifyResult, verbose: bool) {
501 println!(
502 "Evidence bundle: {}",
503 if result.bundle_valid {
504 "VALID"
505 } else {
506 "INVALID"
507 }
508 );
509 println!("Manifest intact: {}", result.manifest_intact);
510 println!("Signature valid: {}", result.signature_valid);
511 println!("Files verified: {}", result.files_verified.len());
512 if verbose {
513 for file in &result.files_verified {
514 println!(
515 " {}: {} (expected {}, actual {})",
516 file.path, file.valid, file.expected_hash, file.actual_hash
517 );
518 }
519 }
520 for error in &result.errors {
521 eprintln!("ERROR: {error}");
522 }
523 for warning in &result.warnings {
524 eprintln!("WARNING: {warning}");
525 }
526}
527
528#[cfg(test)]
529mod tests {
530 use super::*;
531 use serde_json::json;
532 use std::io::{Cursor, Write};
533
534 #[allow(clippy::fn_params_excessive_bools)]
535 fn fixture(
536 name: &str,
537 tamper_file: bool,
538 tamper_manifest: bool,
539 extra_file: bool,
540 missing_file: bool,
541 ) -> PathBuf {
542 let payload = b"audit-entry\n";
543 let key = ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]);
544 let mut manifest = json!({
545 "bundle": "evidence-bundle",
546 "version": 1,
547 "files": [{
548 "path": "audit/trail.jsonl",
549 "sha256": sha256_hex(payload)
550 }],
551 "signing": {
552 "algorithm": "ed25519",
553 "public_key": lean_ctx::core::agent_identity::hex_encode(
554 key.verifying_key().as_bytes()
555 ),
556 "signed_digest": "",
557 "signature": ""
558 }
559 });
560 let digest = sha256_hex(&lean_ctx::core::canonical::canonical_json_bytes(&manifest));
561 let signature = lean_ctx::core::agent_identity::sign_bytes_with(&key, digest.as_bytes());
562 manifest["signing"]["signed_digest"] = Value::String(digest);
563 manifest["signing"]["signature"] =
564 Value::String(lean_ctx::core::agent_identity::hex_encode(&signature));
565 if tamper_manifest {
566 manifest["subject"] = json!({"project": "tampered"});
567 }
568
569 let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
570 let options = zip::write::SimpleFileOptions::default();
571 zip.start_file("manifest.json", options).unwrap();
572 zip.write_all(&lean_ctx::core::canonical::canonical_json_bytes(&manifest))
573 .unwrap();
574 if !missing_file {
575 zip.start_file("audit/trail.jsonl", options).unwrap();
576 zip.write_all(if tamper_file { b"tampered\n" } else { payload })
577 .unwrap();
578 }
579 if extra_file {
580 zip.start_file("extra.txt", options).unwrap();
581 zip.write_all(b"extra").unwrap();
582 }
583 let bytes = zip.finish().unwrap().into_inner();
584 let path =
585 std::env::temp_dir().join(format!("lean-ctx-verify-{name}-{}.zip", std::process::id()));
586 fs::write(&path, bytes).unwrap();
587 path
588 }
589
590 fn command(path: PathBuf) -> VerifyCommand {
591 VerifyCommand {
592 bundle_path: path,
593 public_key: None,
594 verbose: false,
595 json_output: false,
596 }
597 }
598
599 #[test]
600 fn valid_bundle_passes() {
601 let path = fixture("valid", false, false, false, false);
602 let result = execute_verify(&command(path.clone())).unwrap();
603 let _ = fs::remove_file(path);
604 assert!(result.bundle_valid, "{result:?}");
605 assert!(result.manifest_intact);
606 assert!(result.signature_valid);
607 }
608
609 #[test]
610 fn unicode_signature_material_is_rejected() {
611 let dir = tempfile::tempdir().unwrap();
612 let path = dir.path().join("unicode-bundle.zip");
613 for field in ["public_key", "signature"] {
614 for malformed in ["\u{1f512}", "0\u{20ac}", "\u{e9}\u{e9}"] {
615 let mut manifest = json!({
616 "bundle": "evidence-bundle",
617 "version": 1,
618 "files": [],
619 "signing": {
620 "algorithm": "ed25519",
621 "public_key": "00".repeat(32),
622 "signed_digest": "",
623 "signature": ""
624 }
625 });
626 if field == "public_key" {
627 manifest["signing"][field] = json!(malformed);
628 }
629 let digest =
630 sha256_hex(&lean_ctx::core::canonical::canonical_json_bytes(&manifest));
631 manifest["signing"]["signed_digest"] = json!(digest);
632 manifest["signing"]["signature"] = json!("00".repeat(64));
633 manifest["signing"][field] = json!(malformed);
634 let mut zip = zip::ZipWriter::new(File::create(&path).unwrap());
635 zip.start_file("manifest.json", zip::write::SimpleFileOptions::default())
636 .unwrap();
637 zip.write_all(&lean_ctx::core::canonical::canonical_json_bytes(&manifest))
638 .unwrap();
639 zip.finish().unwrap();
640
641 let result = execute_verify(&command(path.clone())).unwrap();
642 assert!(result.manifest_intact, "{result:?}");
643 assert!(!result.bundle_valid);
644 assert!(!result.signature_valid);
645 let expected = if field == "public_key" {
646 "invalid manifest public key: non-ASCII hex string".to_string()
647 } else {
648 format!(
649 "invalid manifest signature: signature must be 64 bytes (hex or base64), got {} chars",
650 malformed.len()
651 )
652 };
653 assert_eq!(result.errors, vec![expected]);
654 assert!(result.warnings.is_empty(), "{:?}", result.warnings);
655 }
656 }
657 }
658
659 #[test]
660 fn tampered_file_fails_hash_check() {
661 let path = fixture("tampered-file", true, false, false, false);
662 let result = execute_verify(&command(path.clone())).unwrap();
663 let _ = fs::remove_file(path);
664 assert!(!result.bundle_valid);
665 assert!(!result.manifest_intact);
666 assert!(
667 result
668 .errors
669 .iter()
670 .any(|error| error.contains("hash mismatch"))
671 );
672 }
673
674 #[test]
675 fn tampered_manifest_fails_signature_check() {
676 let path = fixture("tampered-manifest", false, true, false, false);
677 let result = execute_verify(&command(path.clone())).unwrap();
678 let _ = fs::remove_file(path);
679 assert!(!result.bundle_valid);
680 assert!(!result.signature_valid);
681 assert!(
682 result
683 .errors
684 .iter()
685 .any(|error| error.contains("signature"))
686 );
687 }
688
689 #[test]
690 fn extra_file_is_a_warning() {
691 let path = fixture("extra", false, false, true, false);
692 let result = execute_verify(&command(path.clone())).unwrap();
693 let _ = fs::remove_file(path);
694 assert!(result.bundle_valid, "{result:?}");
695 assert!(
696 result
697 .warnings
698 .iter()
699 .any(|warning| warning.contains("extra.txt"))
700 );
701 }
702
703 #[test]
704 fn missing_file_is_an_error() {
705 let path = fixture("missing", false, false, false, true);
706 let result = execute_verify(&command(path.clone())).unwrap();
707 let _ = fs::remove_file(path);
708 assert!(!result.bundle_valid);
709 assert!(!result.manifest_intact);
710 assert!(
711 result
712 .errors
713 .iter()
714 .any(|error| error.contains("missing file"))
715 );
716 }
717}