1use anyhow::Result;
4use clap::{Parser, Subcommand};
5use std::path::{Path, PathBuf};
6
7use znippy_common::{VerifyReport, list_archive_contents, verify_archive_integrity};
8use znippy_common::plugin::PluginRegistry;
9use znippy_common::plugins::wasm_loader::WasmPlugin;
10use znippy_compress::compress_dir;
11use znippy_decompress::{decompress_archive, decompress_archive_filtered};
12
13pub mod handlers;
14
15pub const GIT_HASH: &str = env!("ZNIPPY_GIT_HASH");
20
21pub const VERSION_LINE: &str =
26 concat!("v", env!("CARGO_PKG_VERSION"), " (", env!("ZNIPPY_GIT_HASH"), ")");
27
28#[inline]
36fn functional_status(component: &str, check: &str, ok: bool, detail: &str) {
37 #[cfg(feature = "testmatrix")]
38 nornir_testmatrix::functional_status(component, check, ok, detail);
39 #[cfg(not(feature = "testmatrix"))]
40 {
41 let _ = (component, check, ok, detail);
42 }
43}
44
45#[derive(Parser)]
46#[command(name = "znippy")]
47#[command(version = VERSION_LINE)]
48#[command(about = "Znippy: fast archive format with per-file compression", long_about = None)]
49struct Cli {
50 #[command(subcommand)]
51 command: Commands,
52}
53
54#[derive(Subcommand)]
55enum Commands {
56 Compress {
58 #[arg(short, long)]
59 input: PathBuf,
60
61 #[arg(short, long)]
62 output: PathBuf,
63
64 #[arg(long)]
65 no_skip: bool,
66
67 #[arg(long, default_value = "rust")]
75 format: String,
76
77 #[arg(long, default_value = "arrow-ipc")]
82 meta_format: String,
83
84 #[arg(long)]
87 warehouse: Option<PathBuf>,
88
89 #[arg(long)]
91 plugin: Option<PathBuf>,
92
93 #[arg(long, default_value_t = 1)]
95 plugin_type_id: i8,
96
97 #[arg(long, value_name = "KEY")]
102 sign: Option<PathBuf>,
103
104 #[arg(long, value_name = "CERT")]
106 sign_cert: Option<PathBuf>,
107
108 #[arg(long, default_value = "p256")]
110 sign_alg: String,
111 },
112
113 Append {
126 #[arg(short, long)]
128 input: PathBuf,
129
130 #[arg(short, long)]
133 add: PathBuf,
134
135 #[arg(short, long, default_value_t = 3)]
137 level: i32,
138
139 #[arg(long = "meta", value_name = "PATH=KEY=VALUE")]
144 meta: Vec<String>,
145
146 #[arg(long = "meta-archive", value_name = "KEY=VALUE")]
149 meta_archive: Vec<String>,
150 },
151
152 Meta {
162 #[arg(short, long)]
164 input: PathBuf,
165
166 #[arg(short, long)]
168 key: Option<String>,
169
170 #[arg(short, long)]
172 prefix: Option<String>,
173
174 #[arg(long)]
177 paths_only: bool,
178 },
179
180 Decompress {
182 #[arg(short, long)]
183 input: PathBuf,
184
185 #[arg(short, long)]
186 output: PathBuf,
187
188 #[arg(long = "type")]
191 pkg_type: Option<String>,
192
193 #[arg(long)]
195 repo: Option<String>,
196 },
197
198 List {
200 #[arg(short, long)]
201 input: PathBuf,
202 },
203
204 Get {
207 #[arg(short, long)]
208 input: PathBuf,
209
210 #[arg(short, long)]
212 path: String,
213
214 #[arg(short, long)]
216 output: Option<PathBuf>,
217 },
218
219 Verify {
221 #[arg(short, long)]
222 input: PathBuf,
223
224 #[arg(long)]
229 signed: bool,
230
231 #[arg(long, value_name = "CA")]
233 root: Vec<PathBuf>,
234 },
235
236 Seal {
245 #[arg(short, long)]
248 input: PathBuf,
249
250 #[arg(long)]
252 warehouse: PathBuf,
253
254 #[arg(long)]
257 namespace: Option<String>,
258
259 #[arg(short, long)]
261 output: PathBuf,
262 },
263
264 Handlers,
266
267 Run {
269 format: String,
271 cmd: String,
273 args: Vec<String>,
275 },
276}
277
278fn build_meta_sink(
284 meta_format: &str,
285 warehouse: Option<PathBuf>,
286 output: &std::path::Path,
287) -> Result<Option<znippy_common::MetaSinkFactory>> {
288 match meta_format {
289 "arrow-ipc" => Ok(None),
290 "iceberg" => {
291 #[cfg(feature = "iceberg")]
292 {
293 let wh = warehouse.ok_or_else(|| {
294 anyhow::anyhow!("--warehouse <DIR> is required for --meta-format iceberg")
295 })?;
296 let namespace = output
297 .file_stem()
298 .map(|s| s.to_string_lossy().to_string())
299 .unwrap_or_else(|| "znippy".to_string());
300 println!(
301 "🧊 Metadata → Iceberg table (namespace `{namespace}`) in {}",
302 wh.display()
303 );
304 Ok(Some(Box::new(move |_file, _off| {
305 Box::new(znippy_iceberg::IcebergSink::new(wh, namespace))
306 as Box<dyn znippy_common::ArchiveMetaSink>
307 })))
308 }
309 #[cfg(not(feature = "iceberg"))]
310 {
311 let _ = (warehouse, output);
312 anyhow::bail!(
313 "iceberg metadata backend not compiled in; rebuild znippy-cli with `--features iceberg`"
314 )
315 }
316 }
317 other => anyhow::bail!("unknown --meta-format '{other}' (expected arrow-ipc|iceberg)"),
318 }
319}
320
321fn compress_reporting(
328 input: &PathBuf,
329 output: &PathBuf,
330 no_skip: bool,
331 registry: &PluginRegistry,
332 sink_factory: Option<znippy_common::MetaSinkFactory>,
333) -> Result<znippy_common::CompressionReport> {
334 match compress_dir(input, output, no_skip, Some(registry), None, sink_factory) {
335 Ok(report) => {
336 let ok = report.total_files > 0
343 && report.chunks > 0
344 && report.files_failed == 0;
345 functional_status(
346 "znippy-cli/compress",
347 "archive_written",
348 ok,
349 &format!(
350 "{} files ({} failed), {} chunks, {:.2}% ratio → {}",
351 report.total_files,
352 report.files_failed,
353 report.chunks,
354 report.compression_ratio,
355 output.display()
356 ),
357 );
358 if report.files_failed > 0 {
359 eprintln!(
360 "⚠️ {} av {} filer kunde inte läsas och utelämnades ur arkivet",
361 report.files_failed, report.total_files
362 );
363 }
364 Ok(report)
365 }
366 Err(e) => {
367 functional_status(
368 "znippy-cli/compress",
369 "archive_written",
370 false,
371 &format!("compress failed: {e}"),
372 );
373 Err(e)
374 }
375 }
376}
377
378fn verify_reporting(input: &Path) -> Result<VerifyReport> {
385 let report = match verify_archive_integrity(input) {
386 Ok(r) => r,
387 Err(e) => {
388 functional_status(
389 "znippy-cli/verify",
390 "integrity_checksum",
391 false,
392 &format!("verify failed: {e}"),
393 );
394 return Err(e);
395 }
396 };
397 functional_status(
401 "znippy-cli/format-version-guard",
402 "on_disk_version_supported",
403 true,
404 &format!("reader max v{}", znippy_common::index::ZNIPPY_FORMAT_VERSION),
405 );
406 let integrity_ok = report.corrupt_files == 0 && report.corrupt_bytes == 0;
407 functional_status(
408 "znippy-cli/verify",
409 "integrity_checksum",
410 integrity_ok,
411 &format!(
412 "{} verified, {} corrupt files",
413 report.verified_files, report.corrupt_files
414 ),
415 );
416 Ok(report)
417}
418
419fn decompress_reporting(
425 input: &PathBuf,
426 output: &PathBuf,
427 filter: &znippy_common::IndexFilter,
428 pkg_type: Option<&str>,
429 repo: Option<&str>,
430) -> Result<VerifyReport> {
431 let result = if filter.is_empty() {
432 decompress_archive(input, output)
433 } else {
434 println!(
435 "🔎 Selective extract: type={} repo={}",
436 pkg_type.unwrap_or("*"),
437 repo.unwrap_or("*"),
438 );
439 decompress_archive_filtered(input, output, filter)
440 };
441 let report = match result {
442 Ok(r) => r,
443 Err(e) => {
444 functional_status(
445 "znippy-cli/decompress",
446 "reconstruct_verify",
447 false,
448 &format!("decompress failed: {e}"),
449 );
450 return Err(e);
451 }
452 };
453 let integrity_ok = report.corrupt_files == 0 && report.corrupt_bytes == 0;
454 functional_status(
455 "znippy-cli/decompress",
456 "reconstruct_verify",
457 integrity_ok,
458 &format!(
459 "{} verified, {} corrupt files, {} corrupt bytes",
460 report.verified_files, report.corrupt_files, report.corrupt_bytes
461 ),
462 );
463 Ok(report)
464}
465
466#[cfg(feature = "sign")]
473fn build_signer(
474 sign: &Option<PathBuf>,
475 sign_cert: &Option<PathBuf>,
476 sign_alg: &str,
477) -> Result<Option<Box<dyn znippy_common::sign::ArchiveSigner + Send>>> {
478 let Some(key_path) = sign else { return Ok(None) };
479 let load = (|| -> Result<Box<dyn znippy_common::sign::ArchiveSigner + Send>> {
480 let cert_path = sign_cert.as_ref().ok_or_else(|| {
481 anyhow::anyhow!("--sign requires --sign-cert <CERT> (DER signer certificate)")
482 })?;
483 let alg = znippy_common::sign::SigAlg::from_name(sign_alg)?;
484 let key = std::fs::read(key_path)?;
485 let cert = std::fs::read(cert_path)?;
486 Ok(znippy_common::sign::signer_from_pkcs8(alg, &key, &cert)?)
487 })();
488 match load {
489 Ok(signer) => Ok(Some(signer)),
490 Err(e) => {
491 functional_status(
492 "znippy-cli/compress-sign",
493 "signer_loaded",
494 false,
495 &format!("signer load failed ({sign_alg}): {e}"),
496 );
497 Err(e)
498 }
499 }
500}
501
502#[cfg(feature = "sign")]
506fn sign_meta_factory(
507 signer: Box<dyn znippy_common::sign::ArchiveSigner + Send>,
508) -> znippy_common::MetaSinkFactory {
509 Box::new(move |file, off| {
510 Box::new(znippy_common::ArrowIpcSink::new(file, off).with_signer(signer))
511 as Box<dyn znippy_common::ArchiveMetaSink>
512 })
513}
514
515#[cfg(feature = "sign")]
522fn run_signed_verify(input: &std::path::Path, roots: &[PathBuf]) -> Result<()> {
523 match run_signed_verify_inner(input, roots) {
524 Ok(()) => Ok(()),
525 Err(e) => {
526 functional_status(
527 "znippy-cli/verify-signed",
528 "provenance_chain",
529 false,
530 &format!("provenance verify failed: {e}"),
531 );
532 Err(e)
533 }
534 }
535}
536
537#[cfg(feature = "sign")]
552pub fn provenance_is_verified(artifacts_verified: usize) -> bool {
553 artifacts_verified > 0
554}
555
556#[cfg(feature = "sign")]
557fn run_signed_verify_inner(input: &std::path::Path, roots: &[PathBuf]) -> Result<()> {
558 anyhow::ensure!(
559 !roots.is_empty(),
560 "--signed requires at least one --root <CA> (DER trusted root)"
561 );
562 let ders: Vec<Vec<u8>> = roots.iter().map(std::fs::read).collect::<std::io::Result<_>>()?;
563 let store = znippy_common::sign::CertStore::from_der_certs(&ders)?;
564 let report = znippy_common::sign::verify_archive(input, &store)?;
565 println!("\n🔏 Provenans verifierad:");
566 println!("✍️ Signerad av (CN): {}", report.signer.id.common_name);
567 println!("🪪 Subjekt: {}", report.signer.id.subject);
568 println!("🔑 Fingeravtryck (SHA-256): {}", report.signer.id.fingerprint_hex());
571 println!("📦 Verifierade artefakter: {}", report.artifacts_verified);
572 let ok = provenance_is_verified(report.artifacts_verified);
583 if !ok {
584 eprintln!(
585 "⚠️ arkivsignaturen kedjar till en betrodd rot, men NOLL artefakter \
586 verifierades — arkivet är antingen förseglat utan filer eller saknar \
587 sin per-artefakt-sektion"
588 );
589 }
590 functional_status(
591 "znippy-cli/verify-signed",
592 "provenance_chain",
593 ok,
594 &format!(
595 "CMS chained to root; signer={}, fp={}, artifacts={}",
596 report.signer.id.common_name,
597 report.signer.id.fingerprint_hex(),
598 report.artifacts_verified
599 ),
600 );
601 Ok(())
602}
603
604fn collect_files(root: &Path, dir: &Path, out: &mut Vec<(String, Vec<u8>)>) -> Result<()> {
609 let mut entries: Vec<_> = std::fs::read_dir(dir)?
610 .collect::<std::io::Result<Vec<_>>>()?;
611 entries.sort_by_key(|e| e.file_name());
613 for entry in entries {
614 let path = entry.path();
615 let ft = entry.file_type()?;
616 if ft.is_dir() {
617 collect_files(root, &path, out)?;
618 } else if ft.is_file() {
619 let rel = path
620 .strip_prefix(root)
621 .unwrap_or(&path)
622 .to_string_lossy()
623 .into_owned();
624 let bytes = std::fs::read(&path)?;
625 out.push((rel, bytes));
626 }
627 }
628 Ok(())
629}
630
631fn parse_meta_args(
639 entry_args: &[String],
640 archive_args: &[String],
641) -> Result<Option<znippy_common::MetaTable>> {
642 if entry_args.is_empty() && archive_args.is_empty() {
643 return Ok(None);
644 }
645 let mut table = znippy_common::MetaTable::new();
646 for raw in entry_args {
647 let (path, rest) = raw
648 .split_once('=')
649 .ok_or_else(|| anyhow::anyhow!("--meta {raw:?}: expected PATH=KEY=VALUE"))?;
650 let (key, value) = rest
651 .split_once('=')
652 .ok_or_else(|| anyhow::anyhow!("--meta {raw:?}: expected PATH=KEY=VALUE"))?;
653 table.insert(path, key, parse_meta_value(value)?);
654 }
655 for raw in archive_args {
656 let (key, value) = raw
657 .split_once('=')
658 .ok_or_else(|| anyhow::anyhow!("--meta-archive {raw:?}: expected KEY=VALUE"))?;
659 table.insert_archive(key, parse_meta_value(value)?);
660 }
661 Ok(Some(table))
662}
663
664fn parse_meta_value(raw: &str) -> Result<znippy_common::MetaValue> {
669 use znippy_common::MetaValue;
670 if let Some(file) = raw.strip_prefix('@') {
671 let bytes = std::fs::read(file)
672 .map_err(|e| anyhow::anyhow!("--meta value @{file}: {e}"))?;
673 return Ok(MetaValue::Bytes(bytes));
674 }
675 Ok(match raw {
676 "true" => MetaValue::Bool(true),
677 "false" => MetaValue::Bool(false),
678 _ => {
679 if let Ok(i) = raw.parse::<i64>() {
680 MetaValue::I64(i)
681 } else if let Ok(f) = raw.parse::<f64>() {
682 MetaValue::F64(f)
683 } else {
684 MetaValue::Str(raw.to_string())
685 }
686 }
687 })
688}
689
690fn run_meta_search(
698 input: &Path,
699 key: Option<&str>,
700 prefix: Option<&str>,
701 paths_only: bool,
702) -> Result<()> {
703 use std::io::Write;
704 use znippy_common::{ArchiveMeta, MetaValue, read_archive_meta};
705
706 let meta = read_archive_meta(input)?;
707 let index = match &meta {
708 ArchiveMeta::NoMetadata => {
709 if !paths_only {
710 eprintln!(
711 "ℹ️ {} carries NO metadata index — nothing was searched. \
712 (That is not the same as searching and finding nothing.)",
713 input.display()
714 );
715 }
716 functional_status(
717 "znippy-cli/meta",
718 "no_metadata_reported_distinctly",
719 true,
720 "archive has no __znippy_meta__ section; reported as NoMetadata, exit 2",
721 );
722 std::io::stdout().flush().ok();
723 std::process::exit(2);
724 }
725 ArchiveMeta::Index(i) => i,
726 };
727
728 let hits: &[znippy_common::MetaEntry] = match (key, prefix) {
729 (Some(k), _) => index.find_by_key(k),
730 (None, Some(p)) => index.find_by_prefix(p),
731 (None, None) => index.find_by_prefix(""),
732 };
733
734 if paths_only {
735 for h in hits {
736 if let Some(p) = h.path() {
737 println!("{p}");
738 }
739 }
740 } else {
741 println!(
742 "🔎 {} — metadata index: {} rows, {} distinct keys",
743 input.display(),
744 index.len(),
745 index.keys().len()
746 );
747 if hits.is_empty() {
748 println!(" (searched — no row matches)");
749 }
750 for h in hits {
751 let scope = h.path().unwrap_or("<archive>");
752 let shown = match &h.value {
753 MetaValue::Str(v) => format!("{v:?}"),
754 MetaValue::I64(v) => v.to_string(),
755 MetaValue::F64(v) => v.to_string(),
756 MetaValue::Bool(v) => v.to_string(),
757 MetaValue::Bytes(b) => format!("<{} bytes>", b.len()),
758 };
759 println!(" {scope} {} = {shown}", h.key);
760 }
761 }
762
763 functional_status(
764 "znippy-cli/meta",
765 "index_searched_without_payload_read",
766 true,
767 &format!("{} rows in index, {} hits", index.len(), hits.len()),
768 );
769 std::io::stdout().flush().ok();
770 if hits.is_empty() {
771 std::process::exit(1);
772 }
773 Ok(())
774}
775
776pub fn run() -> Result<()> {
777 env_logger::init();
778 let cli = Cli::parse();
779
780 match cli.command {
781 Commands::Compress {
782 input,
783 output,
784 no_skip,
785 format,
786 meta_format,
787 warehouse,
788 plugin,
789 plugin_type_id,
790 sign,
791 sign_cert,
792 sign_alg,
793 } => {
794 let registry = match plugin {
795 Some(wasm_path) => {
796 let wp = WasmPlugin::load(&wasm_path.to_string_lossy(), "wasm-plugin", plugin_type_id)?;
797 PluginRegistry::with_plugin(Box::new(wp))
798 }
799 None => {
800 let handler = handlers::find_handler(&format)?;
801 println!("🔌 Handler: {} (type_id {})", handler.meta().name, handler.type_id());
802 PluginRegistry::with_plugin(handler)
803 }
804 };
805 #[allow(unused_mut)]
807 let mut sink_factory = build_meta_sink(&meta_format, warehouse, &output)?;
808
809 #[cfg(feature = "sign")]
812 {
813 if let Some(signer) = build_signer(&sign, &sign_cert, &sign_alg)? {
814 anyhow::ensure!(
815 sink_factory.is_none(),
816 "--sign is only supported with --meta-format arrow-ipc"
817 );
818 println!("🔏 Signering aktiverad ({sign_alg})");
819 sink_factory = Some(sign_meta_factory(signer));
820 functional_status(
821 "znippy-cli/compress-sign",
822 "signer_loaded",
823 true,
824 &format!("detached CMS provenance armed ({sign_alg})"),
825 );
826 }
827 }
828 #[cfg(not(feature = "sign"))]
829 {
830 let _ = &sign_alg;
831 anyhow::ensure!(
832 sign.is_none() && sign_cert.is_none(),
833 "signing not compiled in; rebuild znippy-cli with `--features sign`"
834 );
835 }
836
837 let report = compress_reporting(&input, &output, no_skip, ®istry, sink_factory)?;
838 if report.files_failed == 0 {
839 println!("\n✅ Komprimering klar:");
840 } else {
841 println!("\n⚠️ Komprimering klar med fel:");
842 }
843 println!("📁 Totalt antal filer: {}", report.total_files);
844 println!("📁 Totalt antal chunks: {}", report.chunks);
845 println!("❌ Filer som misslyckades: {}", report.files_failed);
846
847 println!("📂 Totalt antal kataloger: {}", report.total_dirs);
848 println!("📦 Filer komprimerade: {}", report.compressed_files);
849 println!(
850 "📄 Filer ej komprimerade: {}",
851 report.uncompressed_files
852 );
853 println!("📥 Totalt inlästa bytes: {}", report.total_bytes_in);
854 println!("📤 Totalt skrivna bytes: {}", report.total_bytes_out);
855 println!("📉 Bytes som komprimerades: {}", report.compressed_bytes);
856 println!(
857 "📃 Bytes ej komprimerade: {}",
858 report.uncompressed_bytes
859 );
860 println!(
861 "📊 Komprimeringsgrad: {:.2}%",
862 report.compression_ratio
863 );
864 }
865
866 Commands::Append { input, add, level, meta, meta_archive } => {
867 let mut files = Vec::new();
868 collect_files(&add, &add, &mut files)?;
869 let file_count = files.len();
870 anyhow::ensure!(
871 file_count > 0,
872 "inga filer att lägga till hittades under {}",
873 add.display()
874 );
875 let meta_table = parse_meta_args(&meta, &meta_archive)?;
879 let meta_rows = meta_table.as_ref().map_or(0, |t| t.len());
880 let report =
881 znippy_common::append_files_with_meta(&input, &files, level, meta_table)?;
882 println!("\n✅ Append klar:");
883 println!("📦 Arkiv: {}", input.display());
884 println!("📁 Filer tillagda: {}", file_count);
885 println!("➕ Nya rader: {}", report.rows_added);
886 println!("📊 Rader innan: {}", report.rows_before);
887 println!("♻️ Ersatta rader: {}", report.rows_replaced);
888 println!("📍 Blob-append-offset: {}", report.blob_append_offset);
889 println!("📤 Nya blob-bytes: {}", report.blob_bytes_added);
890 println!("💾 Slutlig arkivstorlek: {}", report.sealed_total_bytes);
891 if meta_rows > 0 {
892 println!("🔎 Metadata-rader tillagda: {meta_rows}");
893 }
894 functional_status(
895 "znippy-cli/append",
896 "native_append",
897 report.rows_added >= file_count as u64,
898 &format!(
899 "appended {file_count} files ({} new rows) into {}",
900 report.rows_added,
901 input.display()
902 ),
903 );
904 }
905
906 Commands::Decompress { input, output, pkg_type, repo } => {
907 let filter = znippy_common::IndexFilter {
908 pkg_type: match &pkg_type {
909 Some(name) => Some(handlers::find_handler(name)?.type_id()),
910 None => None,
911 },
912 repo: repo.clone(),
913 };
914 let report: VerifyReport = decompress_reporting(
915 &input,
916 &output,
917 &filter,
918 pkg_type.as_deref(),
919 repo.as_deref(),
920 )?;
921 println!("\n✅ Dekomprimering och verifiering klar:");
922 println!("📁 Totala filer: {}", report.total_files);
923 println!("🔐 Verifierade filer: {}", report.verified_files);
924 println!("📥 chunks: {}", report.chunks);
925 println!("❌ Korrupta filer: {}", report.corrupt_files);
926 println!("📥 Totala bytes: {}", report.total_bytes);
927 println!("📤 Verifierade bytes: {}", report.verified_bytes);
928 println!("⚠️ Korrupta bytes: {}", report.corrupt_bytes);
929 if report.corrupt_files > 0 || report.corrupt_bytes > 0 {
932 anyhow::bail!(
933 "dekomprimering misslyckades: {} korrupta filer, {} korrupta bytes — utdata är ofullständig/otillförlitlig",
934 report.corrupt_files,
935 report.corrupt_bytes
936 );
937 }
938 }
939
940 Commands::List { input } => {
941 list_archive_contents(&input)?;
942 }
943
944 Commands::Meta { input, key, prefix, paths_only } => {
945 return run_meta_search(&input, key.as_deref(), prefix.as_deref(), paths_only);
946 }
947
948 Commands::Get { input, path, output } => {
949 let reader = znippy_common::ArchiveReader::open(&input)?;
954 let data = reader.read_file(&path)?;
955 match output {
956 Some(dest) => {
957 std::fs::write(&dest, &data)?;
958 eprintln!("📤 {} ({} bytes) → {}", path, data.len(), dest.display());
959 }
960 None => {
961 use std::io::Write;
962 std::io::stdout().write_all(&data)?;
963 }
964 }
965 }
966
967 Commands::Verify { input, signed, root } => {
968 let report: VerifyReport = verify_reporting(&input)?;
969 println!("\n🔍 Verifiering klar:");
970 println!("📁 Totala filer: {}", report.total_files);
971 println!("🔐 Verifierade filer: {}", report.verified_files);
972 println!("❌ Korrupta filer: {}", report.corrupt_files);
973 println!("📥 Totala bytes: {}", report.total_bytes);
974 println!("📤 Verifierade bytes: {}", report.verified_bytes);
975 println!("⚠️ Korrupta bytes: {}", report.corrupt_bytes);
976
977 if report.corrupt_files > 0 || report.corrupt_bytes > 0 {
983 anyhow::bail!(
984 "verifiering misslyckades: {} korrupta filer, {} korrupta bytes — arkivet är skadat",
985 report.corrupt_files,
986 report.corrupt_bytes
987 );
988 }
989
990 if signed {
991 #[cfg(feature = "sign")]
992 run_signed_verify(&input, &root)?;
993 #[cfg(not(feature = "sign"))]
994 {
995 let _ = &root;
996 anyhow::bail!(
997 "signature verification not compiled in; rebuild znippy-cli with `--features sign`"
998 );
999 }
1000 }
1001 }
1002
1003 Commands::Seal { input, warehouse, namespace, output } => {
1004 #[cfg(feature = "iceberg")]
1005 {
1006 let ns = namespace.unwrap_or_else(|| {
1007 input
1008 .file_stem()
1009 .map(|s| s.to_string_lossy().to_string())
1010 .unwrap_or_else(|| "znippy".to_string())
1011 });
1012 println!(
1013 "🧊→📦 Sealing iceberg archive (namespace `{ns}`) in {} → {}",
1014 warehouse.display(),
1015 output.display()
1016 );
1017 let report = znippy_iceberg::seal(&input, &warehouse, &ns, &output)?;
1018 println!("\n✅ Sealed (static native .znippy):");
1019 println!("📁 Filer: {}", report.files);
1020 println!("🧱 Chunk-rader: {}", report.rows);
1021 println!(
1022 "📤 Blob-bytes återanvända: {} (ingen omkomprimering)",
1023 report.blob_bytes_copied
1024 );
1025 println!("📦 Sealad total storlek: {}", report.sealed_total_bytes);
1026 println!(
1027 "📊 Metadata-svans + footer: {} bytes",
1028 report.sealed_total_bytes - report.blob_bytes_copied
1029 );
1030 }
1031 #[cfg(not(feature = "iceberg"))]
1032 {
1033 let _ = (input, warehouse, namespace, output);
1034 anyhow::bail!(
1035 "iceberg backend not compiled in; rebuild znippy-cli with `--features iceberg`"
1036 );
1037 }
1038 }
1039
1040 Commands::Handlers => {
1041 handlers::print_catalog();
1042 }
1043
1044 Commands::Run { format, cmd, args } => {
1045 let handler = handlers::find_handler(&format)?;
1046 let dispatch = handler.run_command(&cmd, &args);
1047 functional_status(
1048 "znippy-cli/run-dispatch",
1049 "handler_command",
1050 dispatch.is_ok(),
1051 &format!("handler `{}` cmd `{}`", handler.meta().name, cmd),
1052 );
1053 dispatch?;
1054 }
1055 }
1056
1057 Ok(())
1058}
1059
1060#[cfg(test)]
1065mod meta_cli_tests {
1066 use super::*;
1067 use znippy_common::MetaValue;
1068
1069 #[test]
1075 fn cli_meta_values_are_typed_by_shape_predictably() {
1076 assert_eq!(parse_meta_value("12").unwrap(), MetaValue::I64(12));
1077 assert_eq!(parse_meta_value("-3").unwrap(), MetaValue::I64(-3));
1078 assert_eq!(parse_meta_value("1.5").unwrap(), MetaValue::F64(1.5));
1079 assert_eq!(parse_meta_value("true").unwrap(), MetaValue::Bool(true));
1080 assert_eq!(parse_meta_value("false").unwrap(), MetaValue::Bool(false));
1081 assert_eq!(parse_meta_value("wasi-p2").unwrap(), MetaValue::Str("wasi-p2".into()));
1082 assert_eq!(parse_meta_value("1.0.2").unwrap(), MetaValue::Str("1.0.2".into()));
1083 assert_eq!(parse_meta_value("").unwrap(), MetaValue::Str(String::new()));
1084
1085 let dir = tempfile::tempdir().unwrap();
1088 let f = dir.path().join("m.wasm");
1089 std::fs::write(&f, b"\0asm\x01\0\0\0").unwrap();
1090 assert_eq!(
1091 parse_meta_value(&format!("@{}", f.display())).unwrap(),
1092 MetaValue::Bytes(b"\0asm\x01\0\0\0".to_vec())
1093 );
1094 assert!(parse_meta_value("@/nonexistent/x.wasm").is_err());
1095 }
1096
1097 #[test]
1102 fn absent_meta_flags_are_none_not_an_empty_table() {
1103 assert!(parse_meta_args(&[], &[]).unwrap().is_none(), "no flags must mean NO section");
1104
1105 let t = parse_meta_args(
1106 &["app/x.wasm=build-thing=@/dev/null".into()],
1107 &["producer=znippy".into()],
1108 )
1109 .unwrap()
1110 .expect("flags given → a table");
1111 assert_eq!(t.len(), 2);
1112 assert_eq!(t.rows()[0].path(), Some("app/x.wasm"));
1113 assert_eq!(t.rows()[1].path(), None, "--meta-archive is archive-scoped");
1114
1115 assert!(parse_meta_args(&["nokey".into()], &[]).is_err());
1117 assert!(parse_meta_args(&["path=keyonly".into()], &[]).is_err());
1118 assert!(parse_meta_args(&[], &["novalue".into()]).is_err());
1119 }
1120}
1121
1122#[cfg(all(test, feature = "testmatrix"))]
1123fn fs_test_lock() -> std::sync::MutexGuard<'static, ()> {
1124 use std::sync::{Mutex, OnceLock};
1125 static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
1126 LOCK.get_or_init(|| Mutex::new(()))
1127 .lock()
1128 .unwrap_or_else(|p| p.into_inner())
1129}
1130
1131#[cfg(all(test, feature = "sign"))]
1132mod sign_tests {
1133 use super::*;
1134 use znippy_common::sign;
1135
1136 #[test]
1139 fn compress_sign_then_verify_signed_round_trip() {
1140 let dir = tempfile::tempdir().unwrap();
1141 let input = dir.path().join("src");
1142 std::fs::create_dir_all(&input).unwrap();
1143 std::fs::write(input.join("a.txt"), b"hello znippy provenance").unwrap();
1144 std::fs::write(input.join("b.txt"), vec![7u8; 4096]).unwrap();
1145
1146 let (ca_key, ca_der) = sign::dev::mint_ca("Znippy CLI Test CA").unwrap();
1148 let signer = sign::dev::new_p256_signer(&ca_key, &ca_der, "cli-signer").unwrap();
1149
1150 let factory = sign_meta_factory(Box::new(signer));
1152 let registry = PluginRegistry::with_plugin(handlers::find_handler("rust").unwrap());
1153 let output = dir.path().join("out");
1154 compress_dir(&input, &output, false, Some(®istry), None, Some(factory)).unwrap();
1155 let archive = output.with_extension("znippy");
1156 assert!(archive.exists());
1157
1158 let ca_path = dir.path().join("ca.der");
1160 std::fs::write(&ca_path, &ca_der).unwrap();
1161 run_signed_verify(&archive, &[ca_path]).unwrap();
1162
1163 let (_other_key, other_der) = sign::dev::mint_ca("Rogue CA").unwrap();
1165 let rogue_path = dir.path().join("rogue.der");
1166 std::fs::write(&rogue_path, &other_der).unwrap();
1167 assert!(run_signed_verify(&archive, &[rogue_path]).is_err());
1168
1169 assert!(run_signed_verify(&archive, &[]).is_err());
1171 }
1172
1173 #[cfg(feature = "testmatrix")]
1177 #[test]
1178 fn build_signer_missing_cert_emits_red_row() {
1179 let _guard = super::fs_test_lock();
1180 let _ = nornir_testmatrix::drain_functional_rows();
1181 let dir = tempfile::tempdir().unwrap();
1182 let key = dir.path().join("k.pkcs8");
1183 std::fs::write(&key, b"not-a-real-key").unwrap();
1184 let out = build_signer(&Some(key), &None, "p256");
1186 assert!(out.is_err(), "missing --sign-cert must be an error");
1187 let rows = nornir_testmatrix::drain_functional_rows();
1188 let red = rows
1189 .iter()
1190 .find(|r| r.suite == "znippy-cli/compress-sign" && r.test_name == "signer_loaded")
1191 .expect("a signer_loaded row was emitted");
1192 assert_eq!(red.status, "fail", "broken signer config is a RED row");
1193 }
1194}
1195
1196#[cfg(all(test, feature = "testmatrix"))]
1200mod functional_status_tests {
1201 use super::*;
1202
1203 fn drained_status(suite: &str, check: &str) -> Option<String> {
1204 nornir_testmatrix::drain_functional_rows()
1205 .into_iter()
1206 .filter(|r| r.suite == suite && r.test_name == check)
1207 .next_back()
1208 .map(|r| r.status)
1209 }
1210
1211 #[test]
1215 fn green_roundtrip_then_red_on_corruption() {
1216 let _guard = super::fs_test_lock();
1217 let dir = tempfile::tempdir().unwrap();
1218 let input = dir.path().join("src");
1219 std::fs::create_dir_all(&input).unwrap();
1220 std::fs::write(input.join("a.txt"), vec![b'a'; 64 * 1024]).unwrap();
1222 std::fs::write(input.join("b.txt"), b"znippy functional status coverage").unwrap();
1223
1224 let registry = PluginRegistry::with_plugin(handlers::find_handler("rust").unwrap());
1225 let output = dir.path().join("out");
1226 let archive = output.with_extension("znippy");
1227
1228 let _ = nornir_testmatrix::drain_functional_rows();
1230 compress_reporting(&input, &output, false, ®istry, None).unwrap();
1231 assert_eq!(
1232 drained_status("znippy-cli/compress", "archive_written").as_deref(),
1233 Some("pass"),
1234 "clean compress records a GREEN row"
1235 );
1236
1237 let _ = nornir_testmatrix::drain_functional_rows();
1239 let vr = verify_reporting(&archive).unwrap();
1240 assert_eq!(vr.corrupt_files, 0, "clean archive has no corrupt files");
1241 assert_eq!(
1242 drained_status("znippy-cli/verify", "integrity_checksum").as_deref(),
1243 Some("pass"),
1244 "clean verify records a GREEN row"
1245 );
1246
1247 let _ = nornir_testmatrix::drain_functional_rows();
1249 let out_clean = dir.path().join("extract_clean");
1250 let filter = znippy_common::IndexFilter { pkg_type: None, repo: None };
1251 decompress_reporting(&archive, &out_clean, &filter, None, None).unwrap();
1252 assert_eq!(
1253 drained_status("znippy-cli/decompress", "reconstruct_verify").as_deref(),
1254 Some("pass"),
1255 "clean decompress records a GREEN row"
1256 );
1257
1258 let mut bytes = std::fs::read(&archive).unwrap();
1260 let flip = 16.min(bytes.len() - 1);
1261 bytes[flip] ^= 0xFF;
1262 std::fs::write(&archive, &bytes).unwrap();
1263
1264 let _ = nornir_testmatrix::drain_functional_rows();
1268 let _ = verify_reporting(&archive);
1269 assert_eq!(
1270 drained_status("znippy-cli/verify", "integrity_checksum").as_deref(),
1271 Some("fail"),
1272 "corrupt verify records a RED row"
1273 );
1274
1275 let _ = nornir_testmatrix::drain_functional_rows();
1277 let out_bad = dir.path().join("extract_bad");
1278 let _ = decompress_reporting(&archive, &out_bad, &filter, None, None);
1279 assert_eq!(
1280 drained_status("znippy-cli/decompress", "reconstruct_verify").as_deref(),
1281 Some("fail"),
1282 "corrupt decompress records a RED row"
1283 );
1284 }
1285}
1286
1287#[cfg(all(test, feature = "sign"))]
1288mod provenance_green_tests {
1289 #[test]
1294 fn zero_verified_artifacts_is_not_a_verified_chain() {
1295 assert!(
1296 !super::provenance_is_verified(0),
1297 "an archive with a valid ROOT signature but zero verified artifacts is not a \
1298 verified provenance chain — this is the hardcoded-true surface the compress \
1299 false-green fix already retired"
1300 );
1301 assert!(super::provenance_is_verified(1), "one verified artifact IS a chain");
1302 assert!(super::provenance_is_verified(9_999));
1303 }
1304}