sbom-tools 0.1.22

Semantic SBOM diff and analysis tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! View command handler.
//!
//! Implements the `view` subcommand for viewing a single SBOM.

use crate::config::ViewConfig;
use crate::model::{BomProfile, NormalizedSbom, Severity};
use crate::pipeline::{
    OutputTarget, auto_detect_format, parse_sbom_with_context, should_use_color, write_output,
};
use crate::reports::{ReportConfig, ReportFormat, create_reporter_with_options};
use crate::tui::{ViewApp, run_view_tui};
use anyhow::Result;

/// Run the view command
#[allow(clippy::needless_pass_by_value)]
pub fn run_view(config: ViewConfig) -> Result<i32> {
    let mut parsed = parse_sbom_with_context(&config.sbom_path, false)?;

    // Enrich with OSV vulnerability data if enabled
    #[cfg(feature = "enrichment")]
    let mut enrichment_warnings: Vec<&str> = Vec::new();

    #[cfg(feature = "enrichment")]
    if config.enrichment.enabled {
        let osv_config = crate::pipeline::build_enrichment_config(&config.enrichment);
        if crate::pipeline::enrich_sbom(parsed.sbom_mut(), &osv_config, false).is_none() {
            enrichment_warnings.push("OSV vulnerability enrichment failed");
        }
    }

    // Enrich with end-of-life data if enabled
    #[cfg(feature = "enrichment")]
    if config.enrichment.enable_eol {
        let eol_config = crate::enrichment::EolClientConfig {
            cache_dir: config
                .enrichment
                .cache_dir
                .clone()
                .unwrap_or_else(crate::pipeline::dirs::eol_cache_dir),
            cache_ttl: std::time::Duration::from_secs(config.enrichment.cache_ttl_hours * 3600),
            bypass_cache: config.enrichment.bypass_cache,
            timeout: std::time::Duration::from_secs(config.enrichment.timeout_secs),
            ..Default::default()
        };
        if crate::pipeline::enrich_eol(parsed.sbom_mut(), &eol_config, false).is_none() {
            enrichment_warnings.push("EOL enrichment failed");
        }
    }

    // Enrich with CISA KEV catalog (flags actively exploited vulnerabilities)
    #[cfg(feature = "enrichment")]
    if config.enrichment.enable_kev {
        let mut kev_config = crate::enrichment::KevClientConfig {
            cache_dir: config
                .enrichment
                .cache_dir
                .clone()
                .unwrap_or_else(crate::pipeline::dirs::kev_cache_dir),
            cache_ttl: std::time::Duration::from_secs(config.enrichment.cache_ttl_hours * 3600),
            bypass_cache: config.enrichment.bypass_cache,
            timeout: std::time::Duration::from_secs(config.enrichment.timeout_secs),
            ..Default::default()
        };
        if let Some(ref url) = config.enrichment.kev_url {
            kev_config.kev_url = url.clone();
        }
        if crate::pipeline::enrich_kev(parsed.sbom_mut(), &kev_config, false).is_none() {
            enrichment_warnings.push("KEV enrichment failed");
        }
    }

    // Enrich with FIRST EPSS exploit-probability scores
    #[cfg(feature = "enrichment")]
    if config.enrichment.enable_epss {
        let mut epss_config = crate::enrichment::EpssClientConfig {
            cache_dir: config
                .enrichment
                .cache_dir
                .clone()
                .unwrap_or_else(crate::pipeline::dirs::epss_cache_dir),
            cache_ttl: std::time::Duration::from_secs(config.enrichment.cache_ttl_hours * 3600),
            bypass_cache: config.enrichment.bypass_cache,
            timeout: std::time::Duration::from_secs(config.enrichment.timeout_secs),
            ..Default::default()
        };
        if let Some(ref url) = config.enrichment.epss_url {
            epss_config.epss_url = url.clone();
        }
        if crate::pipeline::enrich_epss(parsed.sbom_mut(), &epss_config, false).is_none() {
            enrichment_warnings.push("EPSS enrichment failed");
        }
    }

    // Enrich with dependency staleness data
    #[cfg(feature = "enrichment")]
    if config.enrichment.enable_staleness {
        let staleness_config = crate::enrichment::RegistryConfig {
            cache_dir: config
                .enrichment
                .cache_dir
                .clone()
                .unwrap_or_else(crate::pipeline::dirs::staleness_cache_dir),
            cache_ttl: std::time::Duration::from_secs(config.enrichment.cache_ttl_hours * 3600),
            bypass_cache: config.enrichment.bypass_cache,
            timeout: std::time::Duration::from_secs(config.enrichment.timeout_secs),
            ..Default::default()
        };
        if crate::pipeline::enrich_staleness(parsed.sbom_mut(), &staleness_config, false).is_none()
        {
            enrichment_warnings.push("Staleness enrichment failed");
        }
    }

    // Enrich ML-model components with HuggingFace Hub data (weight hashes, task)
    #[cfg(feature = "enrichment")]
    if config.enrichment.enable_huggingface {
        let mut hf_config = crate::enrichment::HuggingFaceConfig {
            cache_dir: config
                .enrichment
                .cache_dir
                .clone()
                .unwrap_or_else(crate::pipeline::dirs::huggingface_cache_dir),
            cache_ttl: std::time::Duration::from_secs(config.enrichment.cache_ttl_hours * 3600),
            bypass_cache: config.enrichment.bypass_cache,
            timeout: std::time::Duration::from_secs(config.enrichment.timeout_secs),
            ..Default::default()
        };
        if let Some(ref url) = config.enrichment.huggingface_url {
            hf_config.api_url = url.clone();
        }
        if crate::pipeline::enrich_huggingface(parsed.sbom_mut(), &hf_config, false).is_none() {
            enrichment_warnings.push("HuggingFace enrichment failed");
        }
    }

    // Enrich with VEX data if VEX documents provided
    #[cfg(feature = "enrichment")]
    if !config.enrichment.vex_paths.is_empty()
        && crate::pipeline::enrich_vex(parsed.sbom_mut(), &config.enrichment.vex_paths, false)
            .is_none()
    {
        enrichment_warnings.push("VEX enrichment failed");
    }

    // Warn if enrichment requested but feature not enabled
    #[cfg(not(feature = "enrichment"))]
    if config.enrichment.enabled
        || config.enrichment.enable_eol
        || config.enrichment.enable_kev
        || config.enrichment.enable_epss
        || config.enrichment.enable_staleness
    {
        eprintln!(
            "Warning: enrichment requested but the 'enrichment' feature is not enabled. \
             Rebuild with: cargo build --features enrichment"
        );
    }

    // Apply filters to SBOM
    let filtered_count = apply_view_filters(parsed.sbom_mut(), &config);
    if filtered_count > 0 {
        tracing::info!(
            "Filtered to {} components (removed {})",
            parsed.sbom().component_count(),
            filtered_count
        );
    }

    // Run NTIA validation if requested
    if config.validate_ntia {
        super::validate::validate_ntia_elements(parsed.sbom())?;
    }

    // Output the result
    let output_target = OutputTarget::from_option(config.output.file.clone());
    let effective_output = auto_detect_format(config.output.format, &output_target);

    // Check for vulnerabilities before rendering (for --fail-on-vuln exit code)
    let vuln_count: usize = parsed
        .sbom()
        .components
        .values()
        .map(|c| c.vulnerabilities.len())
        .sum();

    // Resolve BOM profile (CLI override or auto-detect)
    let bom_profile = config
        .bom_profile
        .unwrap_or_else(|| BomProfile::detect(parsed.sbom()));
    tracing::info!("BOM profile: {bom_profile}");

    if effective_output == ReportFormat::Tui {
        // Resolve sidecar so the compliance tab's OSS-Steward / EUCC /
        // Article 14 / product-class checks render against the same
        // metadata the CLI uses (auto-discovered next to the SBOM when
        // `--cra-sidecar` is omitted).
        let tui_sidecar = match &config.cra_sidecar_path {
            Some(p) => crate::model::CraSidecarMetadata::from_file(p).ok(),
            None => crate::model::CraSidecarMetadata::find_for_sbom(&config.sbom_path),
        };
        let (sbom, raw_content) = parsed.into_parts();
        let mut app = ViewApp::new(sbom, &raw_content, bom_profile);
        if let Some(sc) = tui_sidecar {
            app = app.with_cra_sidecar(sc);
        }
        app.export_template = config.output.export_template.clone();

        // Show enrichment warnings in TUI footer
        #[cfg(feature = "enrichment")]
        if !enrichment_warnings.is_empty() {
            app.set_status_message(format!("Warning: {}", enrichment_warnings.join(", ")));
            app.status_sticky = true;
        }

        run_view_tui(&mut app)?;
    } else {
        parsed.drop_raw_content();
        output_view_report(&config, parsed.sbom(), &output_target)?;
    }

    if config.fail_on_vuln && vuln_count > 0 {
        return Ok(crate::pipeline::exit_codes::VULNS_INTRODUCED);
    }

    Ok(crate::pipeline::exit_codes::SUCCESS)
}

/// Apply view filters to the SBOM, returns number of components removed
pub fn apply_view_filters(sbom: &mut NormalizedSbom, config: &ViewConfig) -> usize {
    let original_count = sbom.component_count();

    // Parse minimum severity if provided
    let min_severity = config.min_severity.as_ref().map(|s| parse_severity(s));

    // Parse ecosystem filter if provided
    let ecosystem_filter = config.ecosystem_filter.as_ref().map(|e| e.to_lowercase());

    // Collect keys to remove
    let keys_to_remove: Vec<_> = sbom
        .components
        .iter()
        .filter_map(|(key, comp)| {
            // Check vulnerable_only filter
            if config.vulnerable_only && comp.vulnerabilities.is_empty() {
                return Some(key.clone());
            }

            // Check severity filter
            if let Some(min_sev) = &min_severity {
                let has_matching_vuln = comp.vulnerabilities.iter().any(|v| {
                    v.severity
                        .as_ref()
                        .is_some_and(|s| severity_meets_minimum(s, min_sev))
                });
                if !has_matching_vuln && !comp.vulnerabilities.is_empty() {
                    return Some(key.clone());
                }
                // If vulnerable_only is set and min_severity is set, only keep vulns meeting threshold
                if config.vulnerable_only && !has_matching_vuln {
                    return Some(key.clone());
                }
            }

            // Check ecosystem filter
            if let Some(eco_filter) = &ecosystem_filter {
                let comp_eco = comp
                    .ecosystem
                    .as_ref()
                    .map(|e| format!("{e:?}").to_lowercase())
                    .unwrap_or_default();
                if !comp_eco.contains(eco_filter) {
                    return Some(key.clone());
                }
            }

            None
        })
        .collect();

    // Remove filtered components
    for key in &keys_to_remove {
        sbom.components.shift_remove(key);
    }

    original_count - sbom.component_count()
}

/// Parse severity string into Severity enum
fn parse_severity(s: &str) -> Severity {
    match s.to_lowercase().as_str() {
        "critical" => Severity::Critical,
        "high" => Severity::High,
        "medium" => Severity::Medium,
        "low" => Severity::Low,
        _ => Severity::Unknown,
    }
}

/// Check if a severity meets the minimum threshold
pub fn severity_meets_minimum(severity: &Severity, minimum: &Severity) -> bool {
    let severity_order = |s: &Severity| match s {
        Severity::Critical => 4,
        Severity::High => 3,
        Severity::Medium => 2,
        Severity::Low => 1,
        Severity::Info | Severity::None | Severity::Unknown => 0,
    };

    severity_order(severity) >= severity_order(minimum)
}

/// Output view report to file or stdout
fn output_view_report(
    config: &ViewConfig,
    sbom: &NormalizedSbom,
    output_target: &OutputTarget,
) -> Result<()> {
    let effective_output = auto_detect_format(config.output.format, output_target);

    // Pre-compute CRA compliance once for reporters.
    // Honour explicit --cra-sidecar; otherwise auto-discover next to the SBOM.
    let sidecar = match &config.cra_sidecar_path {
        Some(p) => crate::model::CraSidecarMetadata::from_file(p).ok(),
        None => crate::model::CraSidecarMetadata::find_for_sbom(&config.sbom_path),
    };
    let cli_class = config
        .cra_product_class
        .as_deref()
        .and_then(crate::model::CraProductClass::parse_cli);
    let sidecar_class = sidecar.as_ref().and_then(|s| s.product_class);
    if let (Some(cli), Some(side)) = (cli_class, sidecar_class)
        && cli != side
    {
        tracing::warn!(
            "CRA product class mismatch: --cra-product-class={} but sidecar says {}; using sidecar.",
            cli.label(),
            side.label()
        );
    }
    let effective_class = sidecar_class.or(cli_class);

    let mut checker =
        crate::quality::ComplianceChecker::new(crate::quality::ComplianceLevel::CraPhase2);
    if let Some(sc) = sidecar {
        checker = checker.with_sidecar(sc);
    }
    if let Some(c) = effective_class {
        checker = checker.with_product_class(c);
    }
    let cra_result = checker.check(sbom);

    let report_config = ReportConfig {
        report_types: vec![config.output.report_types],
        metadata: crate::reports::ReportMetadata {
            old_sbom_path: Some(config.sbom_path.to_string_lossy().to_string()),
            ..Default::default()
        },
        view_cra_compliance: Some(cra_result),
        ..Default::default()
    };

    let use_color = should_use_color(config.output.no_color);
    let reporter = create_reporter_with_options(effective_output, use_color);
    let report = reporter.generate_view_report(sbom, &report_config)?;

    write_output(&report, output_target, false)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_severity() {
        assert!(matches!(parse_severity("critical"), Severity::Critical));
        assert!(matches!(parse_severity("HIGH"), Severity::High));
        assert!(matches!(parse_severity("Medium"), Severity::Medium));
        assert!(matches!(parse_severity("low"), Severity::Low));
        assert!(matches!(parse_severity("unknown"), Severity::Unknown));
        assert!(matches!(parse_severity("invalid"), Severity::Unknown));
    }

    #[test]
    fn test_severity_meets_minimum() {
        assert!(severity_meets_minimum(&Severity::Critical, &Severity::High));
        assert!(severity_meets_minimum(&Severity::High, &Severity::High));
        assert!(!severity_meets_minimum(&Severity::Medium, &Severity::High));
        assert!(!severity_meets_minimum(&Severity::Low, &Severity::High));
    }

    #[test]
    fn test_severity_order() {
        assert!(severity_meets_minimum(&Severity::Critical, &Severity::Low));
        assert!(severity_meets_minimum(
            &Severity::Critical,
            &Severity::Medium
        ));
        assert!(severity_meets_minimum(&Severity::Critical, &Severity::High));
        assert!(severity_meets_minimum(
            &Severity::Critical,
            &Severity::Critical
        ));
    }

    #[test]
    fn test_apply_view_filters_no_filters() {
        let mut sbom = NormalizedSbom::default();
        let config = ViewConfig {
            sbom_path: std::path::PathBuf::from("test.json"),
            output: crate::config::OutputConfig {
                format: ReportFormat::Summary,
                file: None,
                report_types: crate::reports::ReportType::All,
                no_color: false,
                streaming: crate::config::StreamingConfig::default(),
                export_template: None,
            },
            validate_ntia: false,
            min_severity: None,
            vulnerable_only: false,
            ecosystem_filter: None,
            fail_on_vuln: false,
            bom_profile: None,
            enrichment: crate::config::EnrichmentConfig::default(),
            cra_sidecar_path: None,
            cra_product_class: None,
        };

        let removed = apply_view_filters(&mut sbom, &config);
        assert_eq!(removed, 0);
    }
}