Skip to main content

znippy_cli/
lib.rs

1// znippy-cli/src/main.rs
2
3use 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
15/// Short git commit hash the binary was built from, stamped by `build.rs` at
16/// build time via **pure `std::fs`** (no shellout — the zero-shell law). `env!`
17/// (not `option_env!`) because `build.rs` emits `ZNIPPY_GIT_HASH` on every
18/// build; `unknown` off a git checkout.
19pub const GIT_HASH: &str = env!("ZNIPPY_GIT_HASH");
20
21/// The canonical version-identity line: `v<CARGO_PKG_VERSION> (<git hash>)`.
22/// The ONE source of truth for the `znippy` binary's identity string — printed
23/// by `znippy --version` / `-V`. Combined with clap's command name `znippy`,
24/// the version flag emits `znippy v<version> (<hash>)`.
25pub const VERSION_LINE: &str =
26    concat!("v", env!("CARGO_PKG_VERSION"), " (", env!("ZNIPPY_GIT_HASH"), ")");
27
28/// **Introspection / emit marker** — record one functional-status row for the
29/// nornir test matrix. Wraps `nornir_testmatrix::functional_status` behind the
30/// `testmatrix` feature (a compiled-out `#[inline]` no-op otherwise, with no
31/// nornir dep). `component` is the reporting surface (e.g. `"znippy-cli/verify"`),
32/// `check` what it verified, `ok` the verdict, `detail` a short human note. The
33/// CLI signing/verify/run verbs call this so `nornir test --features testmatrix`
34/// SEES each surface's health.
35#[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 a directory into a .znippy archive
57    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        /// Package handler to use: a name or alias (`rust`/`cargo`, `python`,
68        /// `maven`, …), or `generic` (aliases `none`/`raw`/`plain`/`blob`) for a
69        /// tree that is not a package registry at all — a container-registry
70        /// mirror, a build output, a data dump. `generic` extracts no metadata and
71        /// claims no package type; the default `rust` would record `pkg_type = 1`
72        /// over such a tree and every `--type rust` consumer would believe it.
73        /// One archive carries one package type. `znippy handlers` lists them.
74        #[arg(long, default_value = "rust")]
75        format: String,
76
77        /// Where the metadata index is written: `arrow-ipc` (default — inline in
78        /// the .znippy container) or `iceberg` (a real Iceberg table in
79        /// --warehouse; blobs stay in the .znippy sidecar). The iceberg backend
80        /// requires the CLI to be built with `--features iceberg`.
81        #[arg(long, default_value = "arrow-ipc")]
82        meta_format: String,
83
84        /// Warehouse directory for `--meta-format iceberg`. Required for, and
85        /// only used by, the iceberg backend.
86        #[arg(long)]
87        warehouse: Option<PathBuf>,
88
89        /// Path to a .wasm plugin for metadata extraction (overrides --format).
90        #[arg(long)]
91        plugin: Option<PathBuf>,
92
93        /// DenseUnion type_id for the WASM plugin given via --plugin.
94        #[arg(long, default_value_t = 1)]
95        plugin_type_id: i8,
96
97        /// Provenance signing (feature `sign`): PKCS#8 (DER) private key of the
98        /// signer. Emits detached CMS signatures as reserved manifest sections —
99        /// the archive stays byte-compatible and the blob/compress path is
100        /// untouched. Requires `--sign-cert`. Build with `--features sign`.
101        #[arg(long, value_name = "KEY")]
102        sign: Option<PathBuf>,
103
104        /// X.509 signer certificate (DER) whose public key matches `--sign`.
105        #[arg(long, value_name = "CERT")]
106        sign_cert: Option<PathBuf>,
107
108        /// Signature algorithm for `--sign`: `p256` (default) or `ed25519`.
109        #[arg(long, default_value = "p256")]
110        sign_alg: String,
111    },
112
113    /// Append files from a directory into an existing sealed .znippy archive.
114    ///
115    /// Reuses every existing blob byte verbatim (no recompression — blobs are
116    /// content-addressed by blake3) and re-seals the merged lookup + trie +
117    /// manifest + footer over old+new rows. The grown archive opens with the
118    /// ordinary reader. This is the CLI front-end for the native blob-append
119    /// primitive (`znippy_common::append_files`, arrow-ipc idea C).
120    ///
121    /// A path that is ALREADY in the archive is REPLACED (last writer wins): its
122    /// old index rows are dropped and its old blob bytes become unreferenced dead
123    /// payload. Re-running an append over a changed directory is therefore safe —
124    /// it never leaves two live copies of a path.
125    Append {
126        /// Existing sealed .znippy archive to grow.
127        #[arg(short, long)]
128        input: PathBuf,
129
130        /// Directory whose files are compressed and appended. Relative paths are
131        /// taken from this root, matching how `compress` derives `relative_path`.
132        #[arg(short, long)]
133        add: PathBuf,
134
135        /// Codec level for the newly-appended blobs (existing blobs are untouched).
136        #[arg(short, long, default_value_t = 3)]
137        level: i32,
138
139        /// Attach a searchable metadata fact to an appended entry:
140        /// `--meta <relative_path>=<key>=<value>` (repeatable). The value is
141        /// typed by shape — `12` is an i64, `1.5` an f64, `true`/`false` a bool,
142        /// `@<file>` the raw bytes of that file, anything else a string.
143        #[arg(long = "meta", value_name = "PATH=KEY=VALUE")]
144        meta: Vec<String>,
145
146        /// Archive-level metadata fact: `--meta-archive <key>=<value>`
147        /// (repeatable, same value typing as `--meta`).
148        #[arg(long = "meta-archive", value_name = "KEY=VALUE")]
149        meta_archive: Vec<String>,
150    },
151
152    /// Search an archive's metadata index **without decompressing anything**.
153    ///
154    /// Reads the footer, the manifest and the `__znippy_meta__` sub-index only,
155    /// so the cost is set by the size of the metadata and not by the payload.
156    ///
157    /// Reports the three outcomes distinctly, because they are three different
158    /// facts: the archive has NO metadata index (exit 2 — nothing was searched);
159    /// it has one and nothing matched (exit 1 — searched, found nothing); it has
160    /// one and these entries matched (exit 0).
161    Meta {
162        /// Archive to search.
163        #[arg(short, long)]
164        input: PathBuf,
165
166        /// Exact key to look for. Omit to list the whole index.
167        #[arg(short, long)]
168        key: Option<String>,
169
170        /// Key prefix to look for (e.g. `build-thing` matches `build-thing.abi`).
171        #[arg(short, long)]
172        prefix: Option<String>,
173
174        /// Print only the matching `relative_path`s — the entries a caller would
175        /// then `znippy get`, one per line, ready to pipe.
176        #[arg(long)]
177        paths_only: bool,
178    },
179
180    /// Decompress a .znippy archive
181    Decompress {
182        #[arg(short, long)]
183        input: PathBuf,
184
185        #[arg(short, long)]
186        output: PathBuf,
187
188        /// Selective extract: only files of this package type (a handler
189        /// name/alias, e.g. `maven`/`rust`/`python`). Omit to extract all types.
190        #[arg(long = "type")]
191        pkg_type: Option<String>,
192
193        /// Selective extract: only files from this repo. Omit to extract all repos.
194        #[arg(long)]
195        repo: Option<String>,
196    },
197
198    /// List contents of a .znippy archive
199    List {
200        #[arg(short, long)]
201        input: PathBuf,
202    },
203
204    /// Random-access read of one file by its relative path (O(log n)/O(key) via
205    /// the lookup sub-index + trie). Writes to --output, or stdout if omitted.
206    Get {
207        #[arg(short, long)]
208        input: PathBuf,
209
210        /// Relative path of the file inside the archive.
211        #[arg(short, long)]
212        path: String,
213
214        /// Destination file. When omitted, the bytes are written to stdout.
215        #[arg(short, long)]
216        output: Option<PathBuf>,
217    },
218
219    /// Verify archive integrity (checksum)
220    Verify {
221        #[arg(short, long)]
222        input: PathBuf,
223
224        /// Also verify provenance signatures (feature `sign`): recompute every
225        /// artifact + archive digest from the index and check the detached CMS
226        /// against the trusted roots. Requires at least one `--root`. Build with
227        /// `--features sign`.
228        #[arg(long)]
229        signed: bool,
230
231        /// Trusted root CA certificate (DER) for `--signed`. Repeatable.
232        #[arg(long, value_name = "CA")]
233        root: Vec<PathBuf>,
234    },
235
236    /// Seal a dynamic, iceberg-backed archive into a static, immutable native
237    /// `.znippy` (inline Arrow-IPC sub-indexes + lookup + trie + footer).
238    ///
239    /// Reads the archive metadata from the skade-iceberg `--warehouse` and
240    /// writes it as the v0.7 inline container, REUSING the blob bytes already in
241    /// the `--input` `.znippy` sidecar (no recompress, content-addressed). The
242    /// sealed artifact opens with the ordinary reader — the warehouse is no
243    /// longer needed to read it. Requires `--features iceberg`.
244    Seal {
245        /// The `.znippy` blob sidecar written when the archive was compressed
246        /// with `--meta-format iceberg` (pure blobs, no footer).
247        #[arg(short, long)]
248        input: PathBuf,
249
250        /// The skade-iceberg warehouse holding the archive metadata tables.
251        #[arg(long)]
252        warehouse: PathBuf,
253
254        /// Iceberg namespace of the archive (its file stem). Defaults to the
255        /// `--input` file stem, matching how `compress` derives it.
256        #[arg(long)]
257        namespace: Option<String>,
258
259        /// Destination for the sealed native `.znippy`.
260        #[arg(short, long)]
261        output: PathBuf,
262    },
263
264    /// List the available package handlers (the compiled-in register).
265    Handlers,
266
267    /// Run a handler-specific subcommand, e.g. `znippy run rust coords foo.crate`.
268    Run {
269        /// Handler name/alias to dispatch to.
270        format: String,
271        /// Subcommand advertised by the handler's meta().
272        cmd: String,
273        /// Arguments passed to the subcommand.
274        args: Vec<String>,
275    },
276}
277
278/// Build the metadata-sink factory for `--meta-format` / `--warehouse`.
279/// `arrow-ipc` (default) → `None`, so `compress_dir` uses the inline
280/// `ArrowIpcSink`. `iceberg` (CLI feature `iceberg`) → a factory that builds an
281/// `IcebergSink` over `--warehouse`; the namespace is the archive's file stem.
282/// Blobs always stay in the `.znippy` file; only the index location changes.
283fn 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
321/// Compress `input` → `output`, recording the CLI **compress** surface's
322/// functional status: GREEN `archive_written` on success (files/chunks/ratio in
323/// the detail), RED with the error text on failure — so `nornir test
324/// --features testmatrix` SEES a broken compress as a RED matrix row instead of
325/// just a non-zero exit. Threads the ready `compress_dir` untouched; the emit is
326/// the only addition and is a compiled-out no-op in the default build.
327fn 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            // GREEN only on a REAL committed result: files enumerated, at least
337            // one chunk written, and NO file silently dropped after an open/read
338            // failure. Mirrors the append path, which gates on
339            // `report.rows_added >= file_count`. Without this a run where every
340            // file failed to open — or an all-dirs input — would still light
341            // `archive_written` green over "0 chunks".
342            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
378/// Verify an archive's integrity, recording the CLI **verify** surface's
379/// functional status: RED `integrity_checksum` on a hard read error, GREEN when
380/// every file's blake3 checksum reconciled, RED when any file/byte is corrupt.
381/// The `format-version-guard` row still confirms the reader accepted the on-disk
382/// format version (reaching here at all means the version guard passed). Emits
383/// are compiled-out no-ops in the default build.
384fn 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    // Reaching Ok here means znippy-common's reader accepted the archive's
398    // recorded on-disk format version (the `check_format_version` guard):
399    // an unsupported version would have errored out above, never here.
400    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
419/// Decompress `input` → `output` (optionally filtered), recording the CLI
420/// **decompress** surface's functional status: RED `reconstruct_verify` on a
421/// hard read error, GREEN when every reconstructed file's checksum reconciled,
422/// RED when any file/byte is corrupt. Returns the report so the caller can print
423/// it and decide the exit code; the RED row is emitted even on the corrupt path.
424fn 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/// Build a boxed provenance signer from the `--sign` / `--sign-cert` / `--sign-alg`
467/// flags, reading the PKCS#8 key + DER cert from disk and handing the bytes to the
468/// ready `znippy-common` loader. `Ok(None)` when `--sign` is absent. On a load
469/// failure (missing cert, bad key/alg) records a RED `signer_loaded` row for the
470/// CLI **sign** surface before propagating — the GREEN counterpart is emitted at
471/// the call site once the signer is armed.
472#[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/// Wrap a signer in the inline Arrow-IPC sink factory so [`compress_dir`] seals a
503/// signed archive (detached CMS in reserved sections; blob/compress path
504/// unchanged). The hot path never sees the signer — it runs at `finish()`.
505#[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/// Verify an archive's provenance: load the DER roots, chain + check every
516/// detached CMS via the ready `verify_archive`, and print the report. Records the
517/// CLI **verify --signed** surface's functional status: GREEN `provenance_chain`
518/// when the CMS chains to a trusted root, RED (with the reason) on any failure —
519/// no roots, an unreadable CA, or a chain that doesn't verify. So a tampered or
520/// wrongly-rooted archive shows up as a RED matrix row, not a bare exit code.
521#[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/// Inner provenance verify: does the work and emits the GREEN `provenance_chain`
538/// row on success. [`run_signed_verify`] wraps it to turn any error into the RED
539/// counterpart before propagating.
540/// **Is a provenance chain genuinely verified?** The archive-root signature is a real
541/// cryptographic gate and `verify_archive` errors out if it does not chain to a trusted
542/// root — but it says nothing about any individual artifact. `verify_archive` walks
543/// `sigs.artifacts`, and an EMPTY map never enters the loop: no error, and the count
544/// stays 0. Two states produce that, and neither is a verified chain — an archive sealed
545/// over zero files, and an archive whose `__znippy_sign_artifacts__` section is absent
546/// (`read_archive_signatures` turns a missing section into an empty map).
547///
548/// Kept as a pure function on purpose: the decision has to be assertable on its own, or
549/// the guard is a local `bool` nobody can drive red. Same lesson as the compress
550/// false-green — a surface that reports success over work that did not happen.
551#[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    // The fingerprint is the identity a trust policy is written against — the
569    // subject is only a label, and a CA may issue it twice.
570    println!("🔑 Fingeravtryck (SHA-256): {}", report.signer.id.fingerprint_hex());
571    println!("📦 Verifierade artefakter: {}", report.artifacts_verified);
572    // GREEN only on a REAL verified result. The archive-root signature above is a
573    // genuine cryptographic gate — reaching here means it chained to a trusted root
574    // — but it says nothing about any individual artifact. `verify_archive` walks
575    // `sigs.artifacts` and an EMPTY map simply never enters the loop: no error, and
576    // `artifacts_verified` stays 0. Two things produce that, and neither is a
577    // verified provenance chain: an archive sealed over zero files, and an archive
578    // whose `__znippy_sign_artifacts__` section is absent (which
579    // `read_archive_signatures` turns into an empty map). Same shape as the compress
580    // false-green fixed in "gate green on the REAL committed result": a surface that
581    // reports success over work that did not happen.
582    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
604/// Recursively collect every regular file under `dir` into `(relative_path,
605/// bytes)` pairs, deriving `relative_path` from `root` exactly as the compress
606/// path does (`path.strip_prefix(root).to_string_lossy()`, `slot_packer.rs`), so
607/// an appended tree lands under the same keys a fresh `compress` would produce.
608fn 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    // Stable, reproducible ordering independent of the filesystem's readdir order.
612    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
631/// Parse `--meta PATH=KEY=VALUE` / `--meta-archive KEY=VALUE` into a table.
632///
633/// Returns `None` when the caller gave neither, which is NOT the same as an
634/// empty table: `None` leaves the archive's metadata exactly as it was (possibly
635/// absent), while an empty table would seal a present-but-empty index. The
636/// distinction is the whole point of the feature, so it is preserved right at
637/// the CLI boundary rather than flattened here.
638fn 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
664/// Type a CLI-supplied value by shape: `@file` → the file's raw bytes,
665/// `true`/`false` → bool, an integer → i64, a decimal → f64, else a string.
666/// Deliberately narrow and documented rather than clever — the typed columns
667/// exist so a consumer can rely on the type, so guessing must be predictable.
668fn 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
690/// `znippy meta` — search the metadata index without decompressing anything.
691///
692/// Exit codes carry the distinction the API is built around, so a shell script
693/// gets it too:
694///   0 — there is an index and these entries matched
695///   1 — there is an index and nothing matched ("searched, found nothing")
696///   2 — there is NO index ("nothing was searched"), which is not the same thing
697fn 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            // `mut` is only exercised under feature `sign` (the signing rebind).
806            #[allow(unused_mut)]
807            let mut sink_factory = build_meta_sink(&meta_format, warehouse, &output)?;
808
809            // Provenance signing rides in via the metadata sink (the `finish()`
810            // tail), never the blob/compress hot path.
811            #[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, &registry, 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            // `None` when the caller said nothing about metadata — which leaves
876            // the archive's existing index exactly as it was, including having
877            // none. Only an explicit --meta/--meta-archive creates or grows one.
878            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            // Never present a corrupt/incomplete extraction as success: fail with
930            // a non-zero exit so callers don't trust the output as good.
931            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            // Route through the cached ArchiveReader (arrow-ipc idea B): open the
950            // manifest + lookup + trie once, then serve the file from the held-open
951            // handle. For a single Get this matches get_file; the point is that this
952            // is now the canonical selective-restore path callers reuse across files.
953            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            // `verify` is documented as a CI integrity gate (`znippy verify -i A &&
978            // ship`), and the exit status is the only machine-readable signal such a
979            // gate consumes — the Swedish stdout text is not. Reporting corruption on
980            // stdout and still returning 0 makes the gate pass on a corrupt archive.
981            // Mirror the Decompress arm and fail with a non-zero exit.
982            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/// Test-only serialization lock for the process-global functional-status buffer.
1061/// Every test that DRAINS `nornir_testmatrix::drain_functional_rows()` takes it
1062/// first so a concurrent drain in another test can't steal its rows (cargo runs
1063/// tests in parallel; the buffer is one process-global).
1064#[cfg(test)]
1065mod meta_cli_tests {
1066    use super::*;
1067    use znippy_common::MetaValue;
1068
1069    /// The CLI's value typing is a GUESS, so it has to be a predictable one —
1070    /// a consumer that relies on `size` being an i64 must get an i64. Inject each
1071    /// shape, assert the exact variant, including the two that are easy to get
1072    /// wrong: a bare `1` must not become an f64, and a version-looking `1.0.2`
1073    /// must stay a string rather than half-parse.
1074    #[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        // `@file` reads real bytes, and a missing file is an error rather than a
1086        // silent empty value — an empty build-thing would be worse than none.
1087        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    /// NO metadata flags must yield `None`, not an empty table: `None` leaves an
1098    /// archive's index untouched, an empty table would seal a present-but-empty
1099    /// one. Flattening those here would reintroduce the exact conflation the
1100    /// whole feature is shaped to prevent.
1101    #[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        // A malformed pair is refused rather than half-applied.
1116        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    /// End-to-end CLI wiring: `compress --sign` (via the sink factory) seals a
1137    /// signed archive, then `verify --signed` chains + checks every detached CMS.
1138    #[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        // One dev CA + a P-256 signer (the ready lib bootstrap path).
1147        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        // Drive the SAME factory the Compress arm builds.
1151        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(&registry), None, Some(factory)).unwrap();
1155        let archive = output.with_extension("znippy");
1156        assert!(archive.exists());
1157
1158        // The CLI verify helper, against a DER root written to disk.
1159        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        // A wrong root must fail to chain.
1164        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        // `--signed` with no roots is a clear error, not a silent pass.
1170        assert!(run_signed_verify(&archive, &[]).is_err());
1171    }
1172
1173    /// The signing surface RED path: a signer that can't load (missing
1174    /// `--sign-cert`) must both error AND record a RED `signer_loaded` row, so
1175    /// `nornir test` sees the broken signing config as a RED matrix row.
1176    #[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        // --sign given, --sign-cert omitted → build_signer must fail + emit RED.
1185        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/// Red-when-broken coverage for the CLI compress / decompress / verify surfaces:
1197/// a clean round-trip records GREEN functional rows, a corrupted archive records
1198/// RED ones. Gated on `testmatrix` so the rows are actually recorded/drained.
1199#[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    /// Whole compress → verify → decompress round trip is GREEN; corrupting a blob
1212    /// byte flips verify + decompress to RED. One serial test (the functional
1213    /// buffer is process-global): each step drains right after it emits.
1214    #[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        // Plenty of highly-compressible bytes so a blob actually exists to corrupt.
1221        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        // ── compress: GREEN archive_written ──
1229        let _ = nornir_testmatrix::drain_functional_rows();
1230        compress_reporting(&input, &output, false, &registry, 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        // ── verify (clean): GREEN integrity_checksum ──
1238        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        // ── decompress (clean): GREEN reconstruct_verify ──
1248        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        // ── corrupt a blob byte (blobs live at the front; index/footer at the end) ──
1259        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        // ── verify (corrupt): RED integrity_checksum ──
1265        // The flipped blob byte surfaces EITHER as a corrupt-checksum report OR as
1266        // a hard codec/read error — both must record a RED row (that's the point).
1267        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        // ── decompress (corrupt): RED reconstruct_verify (bails, but emits first) ──
1276        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    /// RED against the pre-fix surface, which passed a hardcoded `true`: an archive
1290    /// whose root signature chains to a trusted root but which carries ZERO verified
1291    /// artifacts must NOT light `provenance_chain` green. Drive the decision itself —
1292    /// a `bool` computed inline in the reporting arm cannot be driven at all.
1293    #[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}