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.name().to_string();
136 if entries.contains_key(&name) {
137 anyhow::bail!("duplicate ZIP entry: {name}");
138 }
139
140 let mut bytes = Vec::new();
141 entry
142 .read_to_end(&mut bytes)
143 .with_context(|| format!("read ZIP entry {name}"))?;
144 entries.insert(name, bytes);
145 }
146
147 Ok(entries)
148}
149
150fn validate_manifest_shape(manifest: &Value, errors: &mut Vec<String>) -> bool {
151 let mut valid = true;
152 if manifest.get("bundle").and_then(Value::as_str) != Some("evidence-bundle") {
153 errors.push("manifest bundle must be \"evidence-bundle\"".to_string());
154 valid = false;
155 }
156 if manifest.get("version").and_then(Value::as_u64) != Some(1) {
157 errors.push("unsupported or missing evidence-bundle manifest version".to_string());
158 valid = false;
159 }
160 if !manifest.get("files").is_some_and(Value::is_array) {
161 errors.push("manifest files must be an array".to_string());
162 valid = false;
163 }
164 valid
165}
166
167fn manifest_file_paths(manifest: &Value) -> BTreeSet<String> {
168 manifest
169 .get("files")
170 .and_then(Value::as_array)
171 .into_iter()
172 .flatten()
173 .filter_map(|file| file.get("path").and_then(Value::as_str))
174 .map(str::to_owned)
175 .collect()
176}
177
178fn verify_manifest_files(
179 manifest: &Value,
180 entries: &BTreeMap<String, Vec<u8>>,
181 files_verified: &mut Vec<FileVerification>,
182 errors: &mut Vec<String>,
183) -> bool {
184 let Some(files) = manifest.get("files").and_then(Value::as_array) else {
185 return false;
186 };
187
188 let mut valid = true;
189 let mut seen = BTreeSet::new();
190 for file in files {
191 let Some(path) = file.get("path").and_then(Value::as_str) else {
192 errors.push("manifest file entry is missing a path".to_string());
193 valid = false;
194 continue;
195 };
196 let expected_hash = file
197 .get("sha256")
198 .and_then(Value::as_str)
199 .unwrap_or_default()
200 .to_string();
201
202 if !seen.insert(path.to_string()) {
203 errors.push(format!("duplicate manifest file entry: {path}"));
204 valid = false;
205 }
206 if !safe_bundle_path(path) {
207 errors.push(format!("unsafe manifest file path: {path}"));
208 files_verified.push(FileVerification {
209 path: path.to_string(),
210 expected_hash,
211 actual_hash: String::new(),
212 valid: false,
213 });
214 valid = false;
215 continue;
216 }
217
218 let Some(bytes) = entries.get(path) else {
219 errors.push(format!("missing file listed in manifest: {path}"));
220 files_verified.push(FileVerification {
221 path: path.to_string(),
222 expected_hash,
223 actual_hash: String::new(),
224 valid: false,
225 });
226 valid = false;
227 continue;
228 };
229
230 let actual_hash = sha256_hex(bytes);
231 let hash_format_valid = expected_hash.len() == 64
232 && crate::core::agent_identity::hex_decode(&expected_hash).is_ok();
233 let file_valid = hash_format_valid && expected_hash.eq_ignore_ascii_case(&actual_hash);
234 if !hash_format_valid {
235 errors.push(format!("invalid SHA-256 hash for manifest file: {path}"));
236 } else if !file_valid {
237 errors.push(format!(
238 "hash mismatch for {path}: expected {expected_hash}, got {actual_hash}"
239 ));
240 }
241 if !file_valid {
242 valid = false;
243 }
244 files_verified.push(FileVerification {
245 path: path.to_string(),
246 expected_hash,
247 actual_hash,
248 valid: file_valid,
249 });
250 }
251
252 valid
253}
254
255fn safe_bundle_path(path: &str) -> bool {
256 let path = Path::new(path);
257 !path.is_absolute()
258 && !path
259 .components()
260 .any(|component| matches!(component, Component::ParentDir))
261}
262
263fn verify_manifest_signature(
264 manifest: &Value,
265 external_public_key: Option<&Path>,
266 errors: &mut Vec<String>,
267 warnings: &mut Vec<String>,
268) -> bool {
269 let Some(signing) = manifest.get("signing").and_then(Value::as_object) else {
270 errors.push("manifest signing section is missing".to_string());
271 return false;
272 };
273 if signing.get("algorithm").and_then(Value::as_str) != Some("ed25519") {
274 errors.push("manifest signing algorithm is not ed25519".to_string());
275 }
276
277 let embedded_key = if let Some(value) = signing.get("public_key").and_then(Value::as_str) {
278 match crate::core::agent_identity::hex_decode(value) {
279 Ok(bytes) if bytes.len() == 32 => Some(bytes),
280 Ok(_) => {
281 if external_public_key.is_none() {
282 errors.push("manifest Ed25519 public key must contain 32 bytes".to_string());
283 } else {
284 warnings.push("embedded manifest public key is invalid".to_string());
285 }
286 None
287 }
288 Err(error) => {
289 if external_public_key.is_none() {
290 errors.push(format!("invalid manifest public key: {error}"));
291 } else {
292 warnings.push(format!("embedded manifest public key is invalid: {error}"));
293 }
294 None
295 }
296 }
297 } else {
298 if external_public_key.is_none() {
299 errors.push("manifest public key is missing".to_string());
300 } else {
301 warnings.push("manifest has no embedded public key".to_string());
302 }
303 None
304 };
305
306 let public_key = match external_public_key {
307 Some(path) => match read_public_key(path) {
308 Ok(bytes) => {
309 if let Some(embedded) = &embedded_key {
310 if embedded != &bytes {
311 warnings.push(
312 "external public key differs from the embedded public key".to_string(),
313 );
314 }
315 }
316 warnings.push("signature checked with external public key".to_string());
317 bytes
318 }
319 Err(error) => {
320 errors.push(format!("cannot read external public key: {error:#}"));
321 return false;
322 }
323 },
324 None => match embedded_key {
325 Some(bytes) => bytes,
326 None => return false,
327 },
328 };
329
330 let Some(expected_digest) = signing.get("signed_digest").and_then(Value::as_str) else {
331 errors.push("manifest signed_digest is missing".to_string());
332 return false;
333 };
334 let Some(signature_hex) = signing.get("signature").and_then(Value::as_str) else {
335 errors.push("manifest signature is missing".to_string());
336 return false;
337 };
338
339 let mut unsigned_manifest = manifest.clone();
340 let Some(unsigned_signing) = unsigned_manifest
341 .get_mut("signing")
342 .and_then(Value::as_object_mut)
343 else {
344 errors.push("manifest signing section is malformed".to_string());
345 return false;
346 };
347 unsigned_signing.insert("signed_digest".to_string(), Value::String(String::new()));
349 unsigned_signing.insert("signature".to_string(), Value::String(String::new()));
350
351 let canonical_manifest = match canonical_json(&unsigned_manifest) {
352 Ok(bytes) => bytes,
353 Err(error) => {
354 errors.push(format!("cannot canonicalize manifest: {error:#}"));
355 return false;
356 }
357 };
358 let computed_digest = sha256_hex(&canonical_manifest);
359 let digest_valid = expected_digest.eq_ignore_ascii_case(&computed_digest);
360 if !digest_valid {
361 errors.push(format!(
362 "manifest digest mismatch: expected {expected_digest}, got {computed_digest}"
363 ));
364 }
365
366 let signature = match decode_signature(signature_hex) {
367 Ok(sig) => sig,
368 Err(error) => {
369 errors.push(format!("invalid manifest signature: {error}"));
370 return false;
371 }
372 };
373 let cryptographically_valid =
376 crate::core::canonical::verify_manifest_signature(manifest, &public_key).unwrap_or(false)
377 || {
378 let canon_v2 = crate::core::canonical::canonical_serialize(&unsigned_manifest);
380 crate::core::agent_identity::verify_signature(&public_key, &canon_v2, &signature)
381 }
382 || crate::core::agent_identity::verify_signature(
383 &public_key,
384 &canonical_manifest,
385 &signature,
386 )
387 || crate::core::agent_identity::verify_signature(
388 &public_key,
389 computed_digest.as_bytes(),
390 &signature,
391 );
392 if !cryptographically_valid {
393 errors.push("manifest signature verification failed".to_string());
394 }
395
396 digest_valid && cryptographically_valid
397}
398
399fn decode_signature(encoded: &str) -> Result<Vec<u8>, String> {
400 use base64::Engine;
401 if let Ok(bytes) = crate::core::agent_identity::hex_decode(encoded) {
402 if bytes.len() == 64 {
403 return Ok(bytes);
404 }
405 }
406 if let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(encoded) {
407 if bytes.len() == 64 {
408 return Ok(bytes);
409 }
410 }
411 Err(format!(
412 "signature must be 64 bytes (hex or base64), got {} chars",
413 encoded.len()
414 ))
415}
416
417fn read_public_key(path: &Path) -> Result<Vec<u8>> {
418 let bytes = fs::read(path).with_context(|| format!("read {}", path.display()))?;
419 if bytes.len() == 32 {
420 return Ok(bytes);
421 }
422 let text = std::str::from_utf8(&bytes)
423 .context("public key is neither 32 raw bytes nor UTF-8 hexadecimal")?;
424 let decoded = crate::core::agent_identity::hex_decode(text.trim())
425 .map_err(|error| anyhow::anyhow!("decode hexadecimal public key: {error}"))?;
426 if decoded.len() != 32 {
427 anyhow::bail!("public key must contain 32 bytes");
428 }
429 Ok(decoded)
430}
431
432fn canonical_json(value: &Value) -> Result<Vec<u8>> {
433 let mut output = Vec::new();
434 write_canonical_json(value, &mut output)?;
435 Ok(output)
436}
437
438fn write_canonical_json(value: &Value, output: &mut Vec<u8>) -> Result<()> {
439 match value {
440 Value::Object(map) => {
441 output.push(b'{');
442 let mut keys: Vec<&String> = map.keys().collect();
443 keys.sort_unstable();
444 for (index, key) in keys.iter().enumerate() {
445 if index > 0 {
446 output.push(b',');
447 }
448 serde_json::to_writer(&mut *output, key)?;
449 output.push(b':');
450 write_canonical_json(map.get(*key).expect("key came from object"), output)?;
451 }
452 output.push(b'}');
453 }
454 Value::Array(values) => {
455 output.push(b'[');
456 for (index, value) in values.iter().enumerate() {
457 if index > 0 {
458 output.push(b',');
459 }
460 write_canonical_json(value, output)?;
461 }
462 output.push(b']');
463 }
464 _ => serde_json::to_writer(&mut *output, value)?,
465 }
466 Ok(())
467}
468
469fn sha256_hex(bytes: &[u8]) -> String {
470 let mut hasher = Sha256::new();
471 hasher.update(bytes);
472 crate::core::agent_identity::hex_encode(&hasher.finalize())
473}
474
475pub(crate) fn looks_like_bundle_command(args: &[String]) -> bool {
478 let mut consumes_next = false;
479 for arg in args {
480 if consumes_next {
481 consumes_next = false;
482 continue;
483 }
484 match arg.as_str() {
485 "--public-key" | "--pubkey" | "--format" => {
486 consumes_next = true;
487 }
488 "--" => return true,
489 "--json" | "--json-output" | "--verbose" | "-v" => {}
490 _ if arg.starts_with("--public-key=")
491 || arg.starts_with("--pubkey=")
492 || arg.starts_with("--format=") => {}
493 _ if arg.starts_with('-') => {}
494 _ => return true,
495 }
496 }
497 false
498}
499
500pub(crate) fn run(args: &[String]) -> i32 {
502 let mut argv = Vec::with_capacity(args.len() + 1);
503 argv.push("lean-ctx".to_string());
504 argv.extend(args.iter().cloned());
505
506 let command = match VerifyCommand::try_parse_from(argv) {
507 Ok(command) => command,
508 Err(error) => {
509 let code = error.exit_code();
510 eprint!("{error}");
511 return code;
512 }
513 };
514
515 match execute_verify(&command) {
516 Ok(result) => {
517 let valid = result.bundle_valid;
518 if command.json_output {
519 match serde_json::to_string_pretty(&result) {
520 Ok(json) => println!("{json}"),
521 Err(error) => {
522 eprintln!("verify: cannot serialize result: {error}");
523 return 1;
524 }
525 }
526 } else {
527 print_human_result(&result, command.verbose);
528 }
529 i32::from(!valid)
530 }
531 Err(error) => {
532 eprintln!("verify: {error:#}");
533 1
534 }
535 }
536}
537
538fn print_human_result(result: &VerifyResult, verbose: bool) {
539 println!(
540 "Evidence bundle: {}",
541 if result.bundle_valid {
542 "VALID"
543 } else {
544 "INVALID"
545 }
546 );
547 println!("Manifest intact: {}", result.manifest_intact);
548 println!("Signature valid: {}", result.signature_valid);
549 println!("Files verified: {}", result.files_verified.len());
550 if verbose {
551 for file in &result.files_verified {
552 println!(
553 " {}: {} (expected {}, actual {})",
554 file.path, file.valid, file.expected_hash, file.actual_hash
555 );
556 }
557 }
558 for error in &result.errors {
559 eprintln!("ERROR: {error}");
560 }
561 for warning in &result.warnings {
562 eprintln!("WARNING: {warning}");
563 }
564}
565
566#[cfg(test)]
567mod tests {
568 use super::*;
569 use serde_json::json;
570 use std::io::{Cursor, Write};
571
572 #[allow(clippy::fn_params_excessive_bools)]
573 fn fixture(
574 name: &str,
575 tamper_file: bool,
576 tamper_manifest: bool,
577 extra_file: bool,
578 missing_file: bool,
579 ) -> PathBuf {
580 let payload = b"audit-entry\n";
581 let key = ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]);
582 let mut manifest = json!({
583 "bundle": "evidence-bundle",
584 "version": 1,
585 "files": [{
586 "path": "audit/trail.jsonl",
587 "sha256": sha256_hex(payload)
588 }],
589 "signing": {
590 "algorithm": "ed25519",
591 "public_key": crate::core::agent_identity::hex_encode(
592 key.verifying_key().as_bytes()
593 ),
594 "signed_digest": "",
595 "signature": ""
596 }
597 });
598 let digest = sha256_hex(&canonical_json(&manifest).unwrap());
599 let signature = crate::core::agent_identity::sign_bytes_with(&key, digest.as_bytes());
600 manifest["signing"]["signed_digest"] = Value::String(digest);
601 manifest["signing"]["signature"] =
602 Value::String(crate::core::agent_identity::hex_encode(&signature));
603 if tamper_manifest {
604 manifest["subject"] = json!({"project": "tampered"});
605 }
606
607 let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
608 let options = zip::write::SimpleFileOptions::default();
609 zip.start_file("manifest.json", options).unwrap();
610 zip.write_all(&canonical_json(&manifest).unwrap()).unwrap();
611 if !missing_file {
612 zip.start_file("audit/trail.jsonl", options).unwrap();
613 zip.write_all(if tamper_file { b"tampered\n" } else { payload })
614 .unwrap();
615 }
616 if extra_file {
617 zip.start_file("extra.txt", options).unwrap();
618 zip.write_all(b"extra").unwrap();
619 }
620 let bytes = zip.finish().unwrap().into_inner();
621 let path =
622 std::env::temp_dir().join(format!("lean-ctx-verify-{name}-{}.zip", std::process::id()));
623 fs::write(&path, bytes).unwrap();
624 path
625 }
626
627 fn command(path: PathBuf) -> VerifyCommand {
628 VerifyCommand {
629 bundle_path: path,
630 public_key: None,
631 verbose: false,
632 json_output: false,
633 }
634 }
635
636 #[test]
637 fn valid_bundle_passes() {
638 let path = fixture("valid", false, false, false, false);
639 let result = execute_verify(&command(path.clone())).unwrap();
640 let _ = fs::remove_file(path);
641 assert!(result.bundle_valid, "{result:?}");
642 assert!(result.manifest_intact);
643 assert!(result.signature_valid);
644 }
645
646 #[test]
647 fn tampered_file_fails_hash_check() {
648 let path = fixture("tampered-file", true, false, false, false);
649 let result = execute_verify(&command(path.clone())).unwrap();
650 let _ = fs::remove_file(path);
651 assert!(!result.bundle_valid);
652 assert!(!result.manifest_intact);
653 assert!(
654 result
655 .errors
656 .iter()
657 .any(|error| error.contains("hash mismatch"))
658 );
659 }
660
661 #[test]
662 fn tampered_manifest_fails_signature_check() {
663 let path = fixture("tampered-manifest", false, true, false, false);
664 let result = execute_verify(&command(path.clone())).unwrap();
665 let _ = fs::remove_file(path);
666 assert!(!result.bundle_valid);
667 assert!(!result.signature_valid);
668 assert!(
669 result
670 .errors
671 .iter()
672 .any(|error| error.contains("signature"))
673 );
674 }
675
676 #[test]
677 fn extra_file_is_a_warning() {
678 let path = fixture("extra", false, false, true, false);
679 let result = execute_verify(&command(path.clone())).unwrap();
680 let _ = fs::remove_file(path);
681 assert!(result.bundle_valid, "{result:?}");
682 assert!(
683 result
684 .warnings
685 .iter()
686 .any(|warning| warning.contains("extra.txt"))
687 );
688 }
689
690 #[test]
691 fn missing_file_is_an_error() {
692 let path = fixture("missing", false, false, false, true);
693 let result = execute_verify(&command(path.clone())).unwrap();
694 let _ = fs::remove_file(path);
695 assert!(!result.bundle_valid);
696 assert!(!result.manifest_intact);
697 assert!(
698 result
699 .errors
700 .iter()
701 .any(|error| error.contains("missing file"))
702 );
703 }
704}