ndaal-csaf-cli 1.6.32

ndaal CLI for CSAF CRUD operations: import, export, validate
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 Pierre Gronau, ndaal in Cologne

//! CLI for CSAF CRUD operations: import, export, validate.

#![allow(
    clippy::print_stdout,
    clippy::print_stderr,
    reason = "this crate IS a command-line tool: its results are stdout and its\
              diagnostics are stderr. Routing them through `tracing` instead\
              would send `stats` and `validate` output to a log file and leave\
              the terminal empty, which is the opposite of what the binary is\
              for. Scoped to this crate on purpose — the server crate keeps\
              the lint active everywhere except its own pre-logging\
              --help/--version path"
)]

// mimalloc in SECURE mode is the global allocator, per `skills/rust-hardening`.
//
// Secure mode adds heap-layout randomisation, guard pages, encrypted free
// lists, and detection of some double-frees and heap corruption. It turns a
// class of exploitable heap corruption into a clean crash.
//
// Honest accounting of what this buys HERE: this workspace is
// `unsafe_code = "deny"` with no FFI, so there is no in-tree code that can
// corrupt the heap in the first place. The protection is against the
// dependency tree -- every `unsafe` block below us, which `cargo geiger`
// counts and we do not own. That is the real exposure, and it is why this is
// enabled despite roughly 10% allocation overhead plus extra memory and
// binary size (upstream's figures; measure the real workload before treating
// them as this project's).
//
// Deliberately NOT in the library crates: a `#[global_allocator]` belongs to
// the final binary, and declaring one in a library would force the choice on
// every downstream consumer of `csaf-core` / `csaf-models`.
/// Process-wide allocator.
///
/// Absent on MSVC targets: cargo-xwin's sysroot has no C++ standard
/// library, which mimalloc.h needs. Those builds use the system allocator.
#[cfg(not(target_env = "msvc"))]
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;

use std::path::PathBuf;

use anyhow::{Context, bail};
use clap::{CommandFactory, Parser, Subcommand};
use csaf_core::config::AppConfig;
use csaf_core::storage::CsafStorage;
use csaf_core::update_cli::{self, UpdateFlags};

/// Release-asset name for this binary. This is the PACKAGE name
/// (`ndaal-csaf-cli`), not clap's display name (`csaf-cli`) — the release
/// pipeline and `[package.metadata.binstall]` both key off the package name,
/// so the updater must too.
const BIN_NAME: &str = "ndaal-csaf-cli";

/// CSAF CRUD CLI tool.
#[derive(Parser)]
#[command(
    name = "csaf-cli",
    version,
    about = "CSAF CRUD command-line interface",
    after_help = update_cli::help_fragment(),
)]
struct Cli {
    /// Path to configuration file.
    #[arg(short, long, default_value = "config/default.toml")]
    config: PathBuf,

    /// Report whether a newer release exists, then exit.
    #[arg(long)]
    check_update: bool,

    /// Download, verify and install the latest release, then exit.
    #[arg(long)]
    self_update: bool,
    /// Refuse `--self-update` (env: `CSAF_NO_SELF_UPDATE`).
    ///
    /// The environment fallback is applied by
    /// `csaf_core::update_cli::UpdateFlags::is_opted_out`, not by clap, so
    /// both binaries share one truthiness rule (`1`/`true`/`yes`/`on`).
    #[arg(long)]
    no_self_update: bool,

    /// Subcommand to execute.
    ///
    /// Optional because `--check-update` / `--self-update` are terminal
    /// actions that take no subcommand.
    #[command(subcommand)]
    command: Option<Commands>,
}

/// Available subcommands.
#[derive(Subcommand)]
enum Commands {
    /// Import CSAF documents from a directory.
    Import {
        /// Directory to import from (overrides config).
        #[arg(short, long)]
        directory: Option<PathBuf>,
    },

    /// Export all CSAF documents to a directory.
    Export {
        /// Directory to export to (overrides config).
        #[arg(short, long)]
        directory: Option<PathBuf>,
    },

    /// Validate a CSAF document file.
    Validate {
        /// Path to the CSAF JSON file.
        file: PathBuf,
    },

    /// Show storage statistics.
    Stats,
}

fn main() -> anyhow::Result<()> {
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
        )
        .init();

    let cli = Cli::parse();

    // --check-update / --self-update are terminal: act and exit before any
    // config is loaded, so a broken config file cannot block an update that
    // would fix it. Checking never fails on a network error.
    let flags = UpdateFlags {
        check_update: cli.check_update,
        self_update: cli.self_update,
        no_self_update: cli.no_self_update,
    };
    if let Some((message, code)) = update_cli::dispatch(flags, BIN_NAME, env!("CARGO_PKG_VERSION"))
    {
        println!("{message}");
        std::process::exit(code);
    }

    // `command` is optional only so the update flags can stand alone. Without
    // either, this is the same usage error clap raised before, with clap's
    // own exit code 2.
    let Some(command) = cli.command else {
        Cli::command().print_help()?;
        std::process::exit(2);
    };

    let config = AppConfig::load(&cli.config)?;

    match command {
        Commands::Import { directory } => cmd_import(&config, directory),
        Commands::Export { directory } => cmd_export(&config, directory),
        Commands::Validate { file } => cmd_validate(&file),
        Commands::Stats => cmd_stats(&config),
    }
}

/// Import CSAF documents from a directory.
fn cmd_import(config: &AppConfig, directory: Option<PathBuf>) -> anyhow::Result<()> {
    let storage = open_storage(config)?;
    let settings = storage.get_settings().unwrap_or_default();

    // Pass the operator-supplied override or the configured directory
    // straight through; `import_directory` opens it as a capability handle
    // and confines the walk.
    let result = match directory {
        Some(dir) => csaf_core::import::import_directory(&dir, &storage),
        None => csaf_core::import::import_directory(&settings.import_directory, &storage),
    }
    .context("Import failed")?;

    println!(
        "Import complete: {} imported, {} skipped",
        result.imported, result.skipped
    );
    for err in &result.errors {
        eprintln!("  Error: {err}");
    }

    Ok(())
}

/// Export all CSAF documents.
fn cmd_export(config: &AppConfig, directory: Option<PathBuf>) -> anyhow::Result<()> {
    let storage = open_storage(config)?;
    let mut settings = storage.get_settings().unwrap_or_default();

    if let Some(dir) = directory {
        settings.export_directory = dir.to_string_lossy().to_string();
    }

    let meta_list = storage
        .list_meta(10000, 0)
        .context("Failed to list documents")?;

    let mut exported = 0;
    let mut errors = 0;

    for meta in &meta_list {
        match storage.get_document(&meta.tracking_id) {
            Ok(Some(doc)) => match csaf_core::export::export_document(&doc, &settings) {
                Ok(_) => exported += 1,
                Err(e) => {
                    eprintln!("Export error for {}: {e}", meta.tracking_id);
                    errors += 1;
                },
            },
            Ok(None) => {
                eprintln!("Document {} not found in storage", meta.tracking_id);
                errors += 1;
            },
            Err(e) => {
                eprintln!("Read error for {}: {e}", meta.tracking_id);
                errors += 1;
            },
        }
    }

    // Export provider metadata if available.
    if let Ok(Some(provider_meta)) = storage.get_provider_metadata()
        && let Err(e) =
            csaf_core::export::export_provider_metadata(&provider_meta, &settings.export_directory)
    {
        eprintln!("Failed to export provider metadata: {e}");
    }

    println!("Export complete: {exported} exported, {errors} errors");
    Ok(())
}

/// Validate a single CSAF file.
fn cmd_validate(file: &std::path::Path) -> anyhow::Result<()> {
    let content = std::fs::read_to_string(file)
        .with_context(|| format!("Failed to read file: {}", file.display()))?;

    let doc: csaf_models::csaf_document::CsafDocument =
        serde_json::from_str(&content).context("Failed to parse CSAF JSON")?;

    let errors = csaf_core::validation::validate(&doc);

    if errors.is_empty() {
        println!("Valid: {} ({})", doc.tracking_id(), doc.category());
    } else {
        println!(
            "Validation findings for {} ({}):",
            doc.tracking_id(),
            doc.category()
        );
        let mut has_errors = false;
        for err in &errors {
            let severity = match err.severity {
                csaf_core::validation::Severity::Error => {
                    has_errors = true;
                    "ERROR"
                },
                csaf_core::validation::Severity::Warning => "WARN",
            };
            println!("  [{severity}] {}: {}", err.path, err.message);
        }

        if has_errors {
            bail!("Validation found hard errors in {}", doc.tracking_id());
        }
    }

    #[cfg(feature = "oasis-validator")]
    {
        println!("OASIS (csaf-rs) mandatory tests:");
        match csaf_core::oasis::validate_oasis_json(&content) {
            Ok(findings) if findings.is_empty() => println!("  all mandatory tests passed"),
            Ok(findings) => {
                let mut oasis_errors = false;
                for f in &findings {
                    let sev = match f.severity {
                        csaf_core::validation::Severity::Error => {
                            oasis_errors = true;
                            "ERROR"
                        },
                        csaf_core::validation::Severity::Warning => "WARN",
                    };
                    println!("  [{sev}] {}: {}", f.path, f.message);
                }
                if oasis_errors {
                    bail!(
                        "OASIS validation found hard errors in {}",
                        doc.tracking_id()
                    );
                }
            },
            Err(e) => println!("  could not run OASIS validation: {e}"),
        }
    }

    Ok(())
}

/// Show storage statistics.
fn cmd_stats(config: &AppConfig) -> anyhow::Result<()> {
    let storage = open_storage(config)?;

    let count = storage.count_documents().unwrap_or(0);
    let settings = storage.get_settings().unwrap_or_default();

    println!("CSAF Storage Statistics");
    println!("  Documents: {count}");
    println!("  CSAF Mode: {}", settings.csaf_mode);
    println!("  Import Dir: {}", settings.import_directory);
    println!("  Export Dir: {}", settings.export_directory);
    println!(
        "  Sidecar SHA-256: {}",
        if settings.sidecar_sha256 { "yes" } else { "no" }
    );
    println!(
        "  Sidecar SHA3-512: {}",
        if settings.sidecar_sha3_512 {
            "yes"
        } else {
            "no"
        }
    );

    Ok(())
}

/// Open the redb storage from config.
fn open_storage(config: &AppConfig) -> anyhow::Result<CsafStorage> {
    CsafStorage::open(&config.redb_path()).context("Failed to open storage")
}