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