sbom-tools 0.2.0

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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
//! Validate command handler.
//!
//! Implements the `validate` subcommand for validating SBOMs against compliance standards.

use crate::model::NormalizedSbom;
use crate::pipeline::{OutputTarget, exit_codes, parse_sbom_with_context, write_output};
use crate::quality::{
    ComplianceChecker, ComplianceLevel, ComplianceResult, StandardSelector, ViolationSeverity,
};
use crate::reports::{ReportFormat, generate_compliance_sarif};
use anyhow::Result;
use std::path::PathBuf;

/// Output formats the `validate` command has a real renderer for.
/// `auto`/`summary` render the plain-text report; everything else here is a
/// dedicated machine-readable emitter. All other [`ReportFormat`] values are
/// rejected up front instead of silently falling back to text.
pub const VALIDATE_OUTPUT_FORMATS: &[ReportFormat] = &[
    ReportFormat::Auto,
    ReportFormat::Summary,
    ReportFormat::Json,
    ReportFormat::Sarif,
    ReportFormat::OscalJson,
];

/// Run the validate command, returning the desired exit code.
///
/// # Exit codes
/// - [`exit_codes::SUCCESS`] (0): compliant (no errors; no warnings when
///   `--fail-on-warning` is set)
/// - [`exit_codes::COMPLIANCE_ERRORS`] (1): one or more compliance errors found
/// - [`exit_codes::COMPLIANCE_WARNINGS`] (2): warnings found with
///   `--fail-on-warning`
///
/// These gate codes only apply to runs that completed a validation. A
/// usage/configuration error surfaced from this function (unsupported output
/// format, invalid `--as-of` or `--cra-product-class`, broken explicit
/// sidecar) propagates as an `Err`, which the binary's `main()` maps to
/// process exit code 1 (and clap parse errors exit 2) — the same numbers as
/// the gate codes above. CI pipelines must therefore not interpret a nonzero
/// exit as a compliance verdict unless the expected report was produced.
///
/// The caller is responsible for calling `std::process::exit()` with the
/// returned code when it is non-zero.
#[allow(clippy::needless_pass_by_value, clippy::too_many_arguments)]
pub fn run_validate(
    sbom_path: PathBuf,
    standards: Vec<StandardSelector>,
    output: ReportFormat,
    output_file: Option<PathBuf>,
    fail_on_warning: bool,
    summary: bool,
    cra_sidecar_path: Option<PathBuf>,
    cra_product_class: Option<String>,
    as_of: Option<&str>,
) -> Result<i32> {
    // `--summary` overrides `--output` (documented on the flag), so the
    // requested format is never rendered and must not be gated.
    if !summary {
        super::ensure_output_format_supported("validate", output, VALIDATE_OUTPUT_FORMATS)?;
    }
    // Pinned evaluation clock for deadline-sensitive checks (shared parser
    // with `quality --as-of`).
    let as_of: Option<chrono::DateTime<chrono::Utc>> = as_of.map(super::parse_as_of).transpose()?;
    anyhow::ensure!(
        !standards.is_empty(),
        "no compliance standard selected; pass --standard (valid values: {})",
        StandardSelector::valid_values()
    );

    let parsed = parse_sbom_with_context(&sbom_path, false)?;

    // Load CRA sidecar — an explicit path is a hard error when broken,
    // otherwise auto-discover next to the SBOM (best-effort).
    let cra_sidecar = super::load_cra_sidecar(cra_sidecar_path.as_deref(), &sbom_path)?;

    // Resolve effective product class: sidecar wins; otherwise CLI flag.
    // An explicitly passed unrecognized class is a hard error (strict parse).
    // Mismatch between explicit CLI flag and sidecar is reported as a Warning
    // on stderr (not turned into a Violation — sidecar is authoritative).
    let cli_class = super::parse_cra_product_class(cra_product_class.as_deref())?;
    let sidecar_class = cra_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 results = Vec::new();

    for selector in &standards {
        let level = selector.level();
        let mut checker = ComplianceChecker::new(level);
        if let Some(now) = as_of {
            checker = checker.with_as_of(now);
        }
        // Sidecar metadata feeds the CRA family (manufacturer/disclosure/
        // lifecycle fields), EUCC (certificate references), and the AI Act
        // profile (the is_high_risk_ai flag escalates Annex IV findings).
        if matches!(
            level,
            ComplianceLevel::CraPhase1
                | ComplianceLevel::CraPhase2
                | ComplianceLevel::CraOssSteward
                | ComplianceLevel::EuccSubstantial
                | ComplianceLevel::EuAiAct
        ) && let Some(sc) = cra_sidecar.clone()
        {
            checker = checker.with_sidecar(sc);
        }
        // Product class drives severity calibration for the CRA phase checks.
        if matches!(
            level,
            ComplianceLevel::CraPhase1 | ComplianceLevel::CraPhase2
        ) && let Some(c) = effective_class
        {
            checker = checker.with_product_class(c);
        }
        results.push(checker.check(parsed.sbom()));
    }

    if results.len() == 1 {
        let result = &results[0];
        if summary {
            write_compliance_summary(result, output_file)?;
        } else {
            write_compliance_output(result, output, output_file)?;
        }

        if result.error_count > 0 {
            return Ok(exit_codes::COMPLIANCE_ERRORS);
        }
        if fail_on_warning && result.warning_count > 0 {
            return Ok(exit_codes::COMPLIANCE_WARNINGS);
        }
    } else {
        // Multi-standard: merge results for output
        if summary {
            write_multi_compliance_summary(&results, output_file)?;
        } else {
            write_multi_compliance_output(&results, output, output_file)?;
        }

        let has_errors = results.iter().any(|r| r.error_count > 0);
        let has_warnings = results.iter().any(|r| r.warning_count > 0);
        if has_errors {
            return Ok(exit_codes::COMPLIANCE_ERRORS);
        }
        if fail_on_warning && has_warnings {
            return Ok(exit_codes::COMPLIANCE_WARNINGS);
        }
    }

    Ok(exit_codes::SUCCESS)
}

fn write_compliance_output(
    result: &ComplianceResult,
    output: ReportFormat,
    output_file: Option<PathBuf>,
) -> Result<()> {
    let target = OutputTarget::from_option(output_file);

    let content = match output {
        ReportFormat::Json => serde_json::to_string_pretty(result)
            .map_err(|e| anyhow::anyhow!("Failed to serialize compliance JSON: {e}"))?,
        ReportFormat::Sarif => generate_compliance_sarif(result)?,
        ReportFormat::OscalJson => {
            crate::reports::oscal::generate_assessment_results(std::slice::from_ref(result))?
        }
        _ => format_compliance_text(result),
    };

    write_output(&content, &target, false)?;
    Ok(())
}

/// Compact summary for CI badge generation
#[derive(serde::Serialize)]
struct ComplianceSummary {
    standard: String,
    /// Whether the standard actually evaluated the SBOM. When false,
    /// `compliant` is the documented always-true N/A contract and `score`
    /// is null — dashboards must not read either as a pass.
    applicable: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    not_applicable_reason: Option<String>,
    compliant: bool,
    score: Option<u8>,
    errors: usize,
    warnings: usize,
    info: usize,
}

fn compliance_summary(result: &ComplianceResult) -> ComplianceSummary {
    let not_applicable_reason = match &result.applicability {
        crate::quality::Applicability::NotApplicable(reason) => Some(reason.clone()),
        crate::quality::Applicability::Applicable => None,
    };
    ComplianceSummary {
        standard: result.level.name().to_string(),
        applicable: result.is_applicable(),
        not_applicable_reason,
        compliant: result.is_compliant,
        score: result.score(),
        errors: result.error_count,
        warnings: result.warning_count,
        info: result.info_count,
    }
}

fn write_compliance_summary(result: &ComplianceResult, output_file: Option<PathBuf>) -> Result<()> {
    let target = OutputTarget::from_option(output_file);
    let summary = compliance_summary(result);
    let content = serde_json::to_string(&summary)
        .map_err(|e| anyhow::anyhow!("Failed to serialize summary: {e}"))?;
    write_output(&content, &target, false)?;
    Ok(())
}

fn write_multi_compliance_output(
    results: &[ComplianceResult],
    output: ReportFormat,
    output_file: Option<PathBuf>,
) -> Result<()> {
    let target = OutputTarget::from_option(output_file);

    let content = match output {
        ReportFormat::Json => serde_json::to_string_pretty(results)
            .map_err(|e| anyhow::anyhow!("Failed to serialize compliance JSON: {e}"))?,
        ReportFormat::Sarif => crate::reports::generate_multi_compliance_sarif(results)?,
        ReportFormat::OscalJson => crate::reports::oscal::generate_assessment_results(results)?,
        _ => {
            let mut parts = Vec::new();
            for result in results {
                parts.push(format_compliance_text(result));
            }
            parts.join("\n---\n\n")
        }
    };

    write_output(&content, &target, false)?;
    Ok(())
}

fn write_multi_compliance_summary(
    results: &[ComplianceResult],
    output_file: Option<PathBuf>,
) -> Result<()> {
    let target = OutputTarget::from_option(output_file);
    let summaries: Vec<ComplianceSummary> = results.iter().map(compliance_summary).collect();

    let content = serde_json::to_string(&summaries)
        .map_err(|e| anyhow::anyhow!("Failed to serialize multi-standard summary: {e}"))?;
    write_output(&content, &target, false)?;
    Ok(())
}

fn format_compliance_text(result: &ComplianceResult) -> String {
    let mut lines = Vec::new();
    lines.push(format!("Compliance ({})", result.level.name()));
    if let crate::quality::Applicability::NotApplicable(reason) = &result.applicability {
        lines.push(format!("Status: NOT APPLICABLE — {reason}"));
    } else {
        lines.push(format!(
            "Status: {} ({} errors, {} warnings, {} info)",
            if result.is_compliant {
                "COMPLIANT"
            } else {
                "NON-COMPLIANT"
            },
            result.error_count,
            result.warning_count,
            result.info_count
        ));
    }
    lines.push(String::new());

    if result.violations.is_empty() {
        lines.push("No violations found.".to_string());
        return lines.join("\n");
    }

    for v in &result.violations {
        let severity = match v.severity {
            ViolationSeverity::Error => "ERROR",
            ViolationSeverity::Warning => "WARN",
            ViolationSeverity::Info => "INFO",
        };
        let element = v.element.as_deref().unwrap_or("-");
        lines.push(format!(
            "[{}] {} | {} | {}",
            severity,
            v.category.name(),
            v.requirement,
            element
        ));
        lines.push(format!("  {}", v.message));
    }

    lines.join("\n")
}

/// Run the engine's NtiaMinimum check and print a compact PASSED/FAILED
/// summary. Used by `view --validate-ntia`; gating errors are listed,
/// warnings go to the log.
pub fn print_ntia_validation(sbom: &NormalizedSbom) {
    let result = ComplianceChecker::new(ComplianceLevel::NtiaMinimum).check(sbom);
    for v in result.violations_by_severity(ViolationSeverity::Warning) {
        tracing::warn!("{}", v.message);
    }
    if result.is_compliant {
        tracing::info!("SBOM passes NTIA minimum elements validation");
        println!("NTIA Validation: PASSED");
    } else {
        tracing::warn!("SBOM has {} NTIA validation errors", result.error_count);
        println!("NTIA Validation: FAILED");
        for v in result.violations_by_severity(ViolationSeverity::Error) {
            println!("  - {}", v.message);
        }
    }
}

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

    #[test]
    fn print_ntia_validation_does_not_panic_on_empty_sbom() {
        print_ntia_validation(&NormalizedSbom::default());
    }

    #[test]
    fn rejects_unsupported_output_format_before_reading_sbom() {
        // html/markdown/etc. used to silently fall through to the text
        // renderer; they must now fail fast (before the SBOM is even read —
        // the path here does not exist).
        for format in [
            ReportFormat::Html,
            ReportFormat::Markdown,
            ReportFormat::Csv,
            ReportFormat::Ndjson,
            ReportFormat::Table,
            ReportFormat::SideBySide,
            ReportFormat::Tui,
        ] {
            let err = run_validate(
                PathBuf::from("/nonexistent/never-read.cdx.json"),
                vec![StandardSelector::Ntia],
                format,
                None,
                false,
                false,
                None,
                None,
                None,
            )
            .expect_err("unsupported format must be rejected");
            let msg = err.to_string();
            assert!(
                msg.contains("not supported by `sbom-tools validate`"),
                "unexpected error for {format}: {msg}"
            );
            assert!(
                msg.contains("oscal-json") && msg.contains("sarif"),
                "error must list the supported formats: {msg}"
            );
        }
    }

    #[test]
    fn rejects_empty_standard_list() {
        let err = run_validate(
            PathBuf::from("/nonexistent/never-read.cdx.json"),
            Vec::new(),
            ReportFormat::Summary,
            None,
            false,
            false,
            None,
            None,
            None,
        )
        .expect_err("empty standard list must be rejected");
        assert!(err.to_string().contains("no compliance standard selected"));
    }

    #[test]
    fn summary_overrides_output_and_skips_the_format_gate() {
        // `--summary` is documented as "(overrides --output)", so a stray
        // `-o html` must not hard-error; the compact JSON summary is written.
        let dir = tempfile::tempdir().unwrap();
        let sbom_path = dir.path().join("app.cdx.json");
        std::fs::write(
            &sbom_path,
            r#"{"bomFormat":"CycloneDX","specVersion":"1.5","components":[]}"#,
        )
        .unwrap();
        let out = dir.path().join("summary.json");
        run_validate(
            sbom_path,
            vec![StandardSelector::Ntia],
            ReportFormat::Html, // rejected without --summary; ignored with it
            Some(out.clone()),
            false,
            true,
            None,
            None,
            None,
        )
        .expect("--summary must override -o html instead of hard-erroring");
        let content = std::fs::read_to_string(out).unwrap();
        let json: serde_json::Value =
            serde_json::from_str(content.trim()).expect("compact summary JSON");
        assert!(json["standard"].is_string(), "summary JSON shape: {json}");
    }

    #[test]
    fn typod_cra_product_class_is_a_hard_error() {
        // Regression: `--cra-product-class critcal` used to be silently
        // dropped (scored as Default class), flipping the CRA verdict.
        let dir = tempfile::tempdir().unwrap();
        let sbom_path = dir.path().join("app.cdx.json");
        std::fs::write(
            &sbom_path,
            r#"{"bomFormat":"CycloneDX","specVersion":"1.5","components":[]}"#,
        )
        .unwrap();
        let err = run_validate(
            sbom_path,
            vec![StandardSelector::Cra],
            ReportFormat::Summary,
            None,
            false,
            true,
            None,
            Some("critcal".to_string()),
            None,
        )
        .expect_err("typo'd --cra-product-class must be a hard error");
        let msg = err.to_string();
        assert!(msg.contains("critcal"), "must name the bad value: {msg}");
        assert!(
            msg.contains("important-class-2") && msg.contains("critical"),
            "must list the valid values: {msg}"
        );
    }

    #[test]
    fn as_of_accepts_offsetless_datetime() {
        // Regression: "2027-01-01T00:00:00" used to fail with a misleading
        // "trailing input" error; it now parses as UTC.
        let dir = tempfile::tempdir().unwrap();
        let sbom_path = dir.path().join("app.cdx.json");
        std::fs::write(
            &sbom_path,
            r#"{"bomFormat":"CycloneDX","specVersion":"1.5","components":[]}"#,
        )
        .unwrap();
        run_validate(
            sbom_path,
            vec![StandardSelector::Cra],
            ReportFormat::Summary,
            Some(dir.path().join("out.json")),
            false,
            true,
            None,
            None,
            Some("2027-01-01T00:00:00"),
        )
        .expect("offset-less --as-of datetime must parse (assumed UTC)");
    }

    #[test]
    fn explicit_missing_sidecar_is_a_hard_error() {
        // Regression guard for the loader contract: an explicitly passed
        // sidecar path that cannot be loaded must abort validation.
        let dir = tempfile::tempdir().unwrap();
        let sbom_path = dir.path().join("app.cdx.json");
        std::fs::write(
            &sbom_path,
            r#"{"bomFormat":"CycloneDX","specVersion":"1.5","components":[]}"#,
        )
        .unwrap();
        let err = run_validate(
            sbom_path,
            vec![StandardSelector::Cra],
            ReportFormat::Summary,
            None,
            false,
            true,
            Some(dir.path().join("missing.cra.json")),
            None,
            None,
        )
        .expect_err("broken explicit sidecar must be a hard error");
        assert!(err.to_string().contains("Failed to load CRA sidecar"));
    }
}