sbom-tools 0.1.19

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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
//! Summary report generator for shell output.
//!
//! Provides a compact, human-readable summary for terminal usage.

use super::{ReportConfig, ReportError, ReportFormat, ReportGenerator};
use crate::diff::DiffResult;
use crate::model::NormalizedSbom;

/// Apply ANSI color formatting if colored output is enabled.
fn ansi_color(text: &str, color: &str, colored: bool) -> String {
    if colored {
        match color {
            "red" => format!("\x1b[31m{text}\x1b[0m"),
            "green" => format!("\x1b[32m{text}\x1b[0m"),
            "yellow" => format!("\x1b[33m{text}\x1b[0m"),
            "cyan" => format!("\x1b[36m{text}\x1b[0m"),
            "bold" => format!("\x1b[1m{text}\x1b[0m"),
            "dim" => format!("\x1b[2m{text}\x1b[0m"),
            _ => text.to_string(),
        }
    } else {
        text.to_string()
    }
}

/// Summary reporter for shell output
pub struct SummaryReporter {
    /// Use colored output
    colored: bool,
}

impl SummaryReporter {
    /// Create a new summary reporter
    #[must_use]
    pub const fn new() -> Self {
        Self { colored: true }
    }

    /// Disable colored output
    #[must_use]
    pub const fn no_color(mut self) -> Self {
        self.colored = false;
        self
    }

    fn color(&self, text: &str, color: &str) -> String {
        ansi_color(text, color, self.colored)
    }
}

impl Default for SummaryReporter {
    fn default() -> Self {
        Self::new()
    }
}

impl ReportGenerator for SummaryReporter {
    fn generate_diff_report(
        &self,
        result: &DiffResult,
        old_sbom: &NormalizedSbom,
        new_sbom: &NormalizedSbom,
        _config: &ReportConfig,
    ) -> Result<String, ReportError> {
        let mut lines = Vec::new();

        // Header
        lines.push(self.color("SBOM Diff Summary", "bold"));
        lines.push(self.color("".repeat(40).as_str(), "dim"));

        // File info
        let old_name = old_sbom.document.name.as_deref().unwrap_or("old");
        let new_name = new_sbom.document.name.as_deref().unwrap_or("new");
        lines.push(format!(
            "{}  {}{}",
            self.color("Files:", "cyan"),
            old_name,
            new_name
        ));

        // Component counts
        lines.push(format!(
            "{}  {}{} components",
            self.color("Size:", "cyan"),
            old_sbom.component_count(),
            new_sbom.component_count()
        ));

        lines.push(String::new());

        // Changes
        lines.push(self.color("Changes:", "bold"));

        let added = result.summary.components_added;
        let removed = result.summary.components_removed;
        let modified = result.summary.components_modified;

        if added > 0 {
            lines.push(format!(
                "  {} {} added",
                self.color(&format!("+{added}"), "green"),
                if added == 1 {
                    "component"
                } else {
                    "components"
                }
            ));
        }
        if removed > 0 {
            lines.push(format!(
                "  {} {} removed",
                self.color(&format!("-{removed}"), "red"),
                if removed == 1 {
                    "component"
                } else {
                    "components"
                }
            ));
        }
        if modified > 0 {
            lines.push(format!(
                "  {} {} modified",
                self.color(&format!("~{modified}"), "yellow"),
                if modified == 1 {
                    "component"
                } else {
                    "components"
                }
            ));
        }
        if added == 0 && removed == 0 && modified == 0 {
            lines.push(format!("  {}", self.color("No changes", "dim")));
        }

        // Vulnerabilities
        let vulns_intro = result.summary.vulnerabilities_introduced;
        let vulns_resolved = result.summary.vulnerabilities_resolved;

        if vulns_intro > 0 || vulns_resolved > 0 {
            lines.push(String::new());
            lines.push(self.color("Vulnerabilities:", "bold"));

            if vulns_intro > 0 {
                lines.push(format!(
                    "  {} {} introduced",
                    self.color(&format!("!{vulns_intro}"), "red"),
                    if vulns_intro == 1 {
                        "vulnerability"
                    } else {
                        "vulnerabilities"
                    }
                ));
            }
            if vulns_resolved > 0 {
                lines.push(format!(
                    "  {} {} resolved",
                    self.color(&format!("{vulns_resolved}"), "green"),
                    if vulns_resolved == 1 {
                        "vulnerability"
                    } else {
                        "vulnerabilities"
                    }
                ));
            }
        }

        // End-of-life summary (from new SBOM)
        {
            let eol_counts = count_eol_statuses(new_sbom);
            if eol_counts.total > 0 {
                lines.push(String::new());
                lines.push(self.color("End-of-Life:", "bold"));
                let mut parts = Vec::new();
                if eol_counts.eol > 0 {
                    parts.push(self.color(&format!("{} EOL", eol_counts.eol), "red"));
                }
                if eol_counts.approaching > 0 {
                    parts.push(
                        self.color(&format!("{} approaching", eol_counts.approaching), "yellow"),
                    );
                }
                if eol_counts.supported > 0 {
                    parts.push(self.color(&format!("{} supported", eol_counts.supported), "green"));
                }
                if eol_counts.security_only > 0 {
                    parts.push(format!("{} security-only", eol_counts.security_only));
                }
                if eol_counts.unknown > 0 {
                    parts.push(format!("{} unknown", eol_counts.unknown));
                }
                lines.push(format!("  {}", parts.join(", ")));
            }
        }

        // Graph changes
        if let Some(ref summary) = result.graph_summary
            && summary.total_changes > 0
        {
            lines.push(String::new());
            lines.push(self.color("Graph Changes:", "bold"));
            lines.push(format!(
                "  {} added, {} removed, {} rel changed, {} reparented, {} depth changes",
                summary.dependencies_added,
                summary.dependencies_removed,
                summary.relationship_changed,
                summary.reparented,
                summary.depth_changed,
            ));

            // Impact breakdown
            let mut impact_parts = Vec::new();
            if summary.by_impact.critical > 0 {
                impact_parts
                    .push(self.color(&format!("{} critical", summary.by_impact.critical), "red"));
            }
            if summary.by_impact.high > 0 {
                impact_parts
                    .push(self.color(&format!("{} high", summary.by_impact.high), "yellow"));
            }
            if summary.by_impact.medium > 0 {
                impact_parts.push(format!("{} medium", summary.by_impact.medium));
            }
            if summary.by_impact.low > 0 {
                impact_parts.push(format!("{} low", summary.by_impact.low));
            }
            if !impact_parts.is_empty() {
                lines.push(format!("  By impact: {}", impact_parts.join(", ")));
            }
        }

        // Score
        lines.push(String::new());
        let score = result.semantic_score;
        let score_color = if score > 90.0 {
            "green"
        } else if score > 70.0 {
            "yellow"
        } else {
            "red"
        };
        lines.push(format!(
            "{}  {}",
            self.color("Similarity:", "cyan"),
            self.color(&format!("{score:.1}%"), score_color)
        ));

        Ok(lines.join("\n"))
    }

    fn generate_view_report(
        &self,
        sbom: &NormalizedSbom,
        _config: &ReportConfig,
    ) -> Result<String, ReportError> {
        let mut lines = Vec::new();

        // Header
        lines.push(self.color("SBOM Summary", "bold"));
        lines.push(self.color("".repeat(40).as_str(), "dim"));

        // Basic info
        if let Some(name) = &sbom.document.name {
            lines.push(format!("{}  {}", self.color("Name:", "cyan"), name));
        }
        lines.push(format!(
            "{}  {}",
            self.color("Format:", "cyan"),
            sbom.document.format
        ));
        lines.push(format!(
            "{}  {}",
            self.color("Components:", "cyan"),
            sbom.component_count()
        ));
        lines.push(format!(
            "{}  {}",
            self.color("Dependencies:", "cyan"),
            sbom.edges.len()
        ));

        // Ecosystems
        let ecosystems: Vec<_> = sbom
            .ecosystems()
            .iter()
            .map(std::string::ToString::to_string)
            .collect();
        if !ecosystems.is_empty() {
            lines.push(format!(
                "{}  {}",
                self.color("Ecosystems:", "cyan"),
                ecosystems.join(", ")
            ));
        }

        // Vulnerabilities
        let counts = sbom.vulnerability_counts();
        let total_vulns = counts.critical + counts.high + counts.medium + counts.low;
        if total_vulns > 0 {
            lines.push(String::new());
            lines.push(self.color("Vulnerabilities:", "bold"));
            if counts.critical > 0 {
                lines.push(format!(
                    "  {}",
                    self.color(&format!("Critical: {}", counts.critical), "red")
                ));
            }
            if counts.high > 0 {
                lines.push(format!(
                    "  {}",
                    self.color(&format!("High: {}", counts.high), "red")
                ));
            }
            if counts.medium > 0 {
                lines.push(format!(
                    "  {}",
                    self.color(&format!("Medium: {}", counts.medium), "yellow")
                ));
            }
            if counts.low > 0 {
                lines.push(format!(
                    "  {}",
                    self.color(&format!("Low: {}", counts.low), "dim")
                ));
            }
        }

        // Crypto summary (if crypto components exist)
        let crypto_metrics = crate::quality::CryptographyMetrics::from_sbom(sbom);
        if crypto_metrics.has_data() {
            lines.push(String::new());
            lines.push(self.color(
                &format!("Crypto: {} assets", crypto_metrics.total_crypto_components),
                "bold",
            ));
            lines.push(format!(
                "  Algorithms: {} | Certificates: {} | Keys: {} | Protocols: {}",
                crypto_metrics.algorithms_count,
                crypto_metrics.certificates_count,
                crypto_metrics.keys_count,
                crypto_metrics.protocols_count,
            ));
            if crypto_metrics.algorithms_count > 0 {
                let readiness = crypto_metrics.quantum_readiness_score();
                let color = if readiness >= 80.0 {
                    "green"
                } else if readiness >= 40.0 {
                    "yellow"
                } else {
                    "red"
                };
                lines.push(format!(
                    "  {}",
                    self.color(&format!("Quantum readiness: {readiness:.0}%"), color)
                ));
            }
            if crypto_metrics.weak_algorithm_count > 0 {
                lines.push(format!(
                    "  {}",
                    self.color(
                        &format!("Weak algorithms: {}", crypto_metrics.weak_algorithm_count),
                        "red"
                    )
                ));
            }
            if crypto_metrics.expired_certificates > 0 {
                lines.push(format!(
                    "  {}",
                    self.color(
                        &format!(
                            "Expired certificates: {}",
                            crypto_metrics.expired_certificates
                        ),
                        "red"
                    )
                ));
            }
            if crypto_metrics.compromised_keys > 0 {
                lines.push(format!(
                    "  {}",
                    self.color(
                        &format!("Compromised keys: {}", crypto_metrics.compromised_keys),
                        "red"
                    )
                ));
            }
        }

        Ok(lines.join("\n"))
    }

    fn format(&self) -> ReportFormat {
        ReportFormat::Summary
    }
}

/// Table reporter for terminal output with aligned columns
pub struct TableReporter {
    /// Use colored output
    colored: bool,
}

impl TableReporter {
    /// Create a new table reporter
    #[must_use]
    pub const fn new() -> Self {
        Self { colored: true }
    }

    /// Disable colored output
    #[must_use]
    pub const fn no_color(mut self) -> Self {
        self.colored = false;
        self
    }

    fn color(&self, text: &str, color: &str) -> String {
        ansi_color(text, color, self.colored)
    }
}

impl Default for TableReporter {
    fn default() -> Self {
        Self::new()
    }
}

impl ReportGenerator for TableReporter {
    fn generate_diff_report(
        &self,
        result: &DiffResult,
        _old_sbom: &NormalizedSbom,
        _new_sbom: &NormalizedSbom,
        _config: &ReportConfig,
    ) -> Result<String, ReportError> {
        let mut lines = Vec::new();

        // Header
        lines.push(format!(
            "{:<12} {:<40} {:<15} {:<15}",
            self.color("STATUS", "bold"),
            self.color("COMPONENT", "bold"),
            self.color("OLD VERSION", "bold"),
            self.color("NEW VERSION", "bold")
        ));
        lines.push("".repeat(85));

        // Added components
        for comp in &result.components.added {
            let version = comp.new_version.as_deref().unwrap_or("-");
            lines.push(format!(
                "{:<12} {:<40} {:<15} {:<15}",
                self.color("+ Added", "green"),
                truncate(&comp.name, 40),
                "-",
                version
            ));
        }

        // Removed components
        for comp in &result.components.removed {
            let version = comp.old_version.as_deref().unwrap_or("-");
            lines.push(format!(
                "{:<12} {:<40} {:<15} {:<15}",
                self.color("- Removed", "red"),
                truncate(&comp.name, 40),
                version,
                "-"
            ));
        }

        // Modified components
        for comp in &result.components.modified {
            let old_ver = comp.old_version.as_deref().unwrap_or("-");
            let new_ver = comp.new_version.as_deref().unwrap_or("-");
            lines.push(format!(
                "{:<12} {:<40} {:<15} {:<15}",
                self.color("~ Modified", "yellow"),
                truncate(&comp.name, 40),
                old_ver,
                new_ver
            ));
        }

        // Vulnerabilities section
        if !result.vulnerabilities.introduced.is_empty() {
            lines.push(String::new());
            lines.push(format!(
                "{:<12} {:<20} {:<10} {:<40}",
                self.color("VULNS", "bold"),
                self.color("ID", "bold"),
                self.color("SEVERITY", "bold"),
                self.color("COMPONENT", "bold")
            ));
            lines.push("".repeat(85));

            for vuln in &result.vulnerabilities.introduced {
                let severity_colored = match vuln.severity.to_lowercase().as_str() {
                    "critical" | "high" => self.color(&vuln.severity, "red"),
                    "medium" => self.color(&vuln.severity, "yellow"),
                    _ => vuln.severity.clone(),
                };
                lines.push(format!(
                    "{:<12} {:<20} {:<10} {:<40}",
                    self.color("! NEW", "red"),
                    truncate(&vuln.id, 20),
                    severity_colored,
                    truncate(&vuln.component_name, 40)
                ));
            }
        }

        // Summary footer
        lines.push(String::new());
        lines.push(format!(
            "Total: {} added, {} removed, {} modified | Vulns: {} new, {} resolved | Similarity: {:.1}%",
            result.summary.components_added,
            result.summary.components_removed,
            result.summary.components_modified,
            result.summary.vulnerabilities_introduced,
            result.summary.vulnerabilities_resolved,
            result.semantic_score
        ));

        Ok(lines.join("\n"))
    }

    fn generate_view_report(
        &self,
        sbom: &NormalizedSbom,
        _config: &ReportConfig,
    ) -> Result<String, ReportError> {
        let mut lines = Vec::new();

        // Header
        lines.push(format!(
            "{:<40} {:<15} {:<20} {:<10}",
            self.color("COMPONENT", "bold"),
            self.color("VERSION", "bold"),
            self.color("LICENSE", "bold"),
            self.color("VULNS", "bold")
        ));
        lines.push("".repeat(90));

        // Components (limit to 50 for readability)
        let mut components: Vec<_> = sbom.components.values().collect();
        components.sort_by(|a, b| a.name.cmp(&b.name));

        for comp in components.iter().take(50) {
            let version = comp.version.as_deref().unwrap_or("-");
            let license = comp
                .licenses
                .declared
                .first()
                .map_or("-", |l| l.expression.as_str());
            let vulns = comp.vulnerabilities.len();
            let vuln_display = if vulns > 0 {
                self.color(&vulns.to_string(), "red")
            } else {
                "0".to_string()
            };

            lines.push(format!(
                "{:<40} {:<15} {:<20} {:<10}",
                truncate(&comp.name, 40),
                truncate(version, 15),
                truncate(license, 20),
                vuln_display
            ));
        }

        if components.len() > 50 {
            lines.push(self.color(
                &format!("... and {} more components", components.len() - 50),
                "dim",
            ));
        }

        // Summary
        lines.push(String::new());
        let counts = sbom.vulnerability_counts();
        let unknown_str = if counts.unknown > 0 {
            format!(", {} unknown", counts.unknown)
        } else {
            String::new()
        };
        lines.push(format!(
            "Total: {} components, {} dependencies | Vulns: {} critical, {} high, {} medium, {} low{}",
            sbom.component_count(),
            sbom.edges.len(),
            counts.critical,
            counts.high,
            counts.medium,
            counts.low,
            unknown_str
        ));

        Ok(lines.join("\n"))
    }

    fn format(&self) -> ReportFormat {
        ReportFormat::Table
    }
}

/// Truncate a string to fit within `max_len` (UTF-8 safe)
fn truncate(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else if max_len > 3 {
        let end = floor_char_boundary(s, max_len - 3);
        format!("{}...", &s[..end])
    } else {
        let end = floor_char_boundary(s, max_len);
        s[..end].to_string()
    }
}

/// EOL status counts for summary display.
struct EolCounts {
    total: usize,
    eol: usize,
    approaching: usize,
    supported: usize,
    security_only: usize,
    unknown: usize,
}

/// Count EOL statuses across all components in an SBOM.
fn count_eol_statuses(sbom: &NormalizedSbom) -> EolCounts {
    use crate::model::EolStatus;

    let mut counts = EolCounts {
        total: 0,
        eol: 0,
        approaching: 0,
        supported: 0,
        security_only: 0,
        unknown: 0,
    };

    for comp in sbom.components.values() {
        if let Some(eol) = &comp.eol {
            counts.total += 1;
            match eol.status {
                EolStatus::EndOfLife => counts.eol += 1,
                EolStatus::ApproachingEol => counts.approaching += 1,
                EolStatus::Supported => counts.supported += 1,
                EolStatus::SecurityOnly => counts.security_only += 1,
                EolStatus::Unknown => counts.unknown += 1,
            }
        }
    }

    counts
}

/// Find the largest byte index <= `index` that is a valid UTF-8 char boundary.
const fn floor_char_boundary(s: &str, index: usize) -> usize {
    if index >= s.len() {
        s.len()
    } else {
        let mut i = index;
        while i > 0 && !s.is_char_boundary(i) {
            i -= 1;
        }
        i
    }
}