1use crate::diff::VulnerabilityDetail;
4use crate::diff::result::VexStatusChange;
5use crate::diff::traits::{ChangeComputer, ComponentMatches, VulnerabilityChangeSet};
6use crate::model::{CanonicalId, NormalizedSbom};
7use std::collections::{HashMap, HashSet, VecDeque};
8
9pub struct VulnerabilityChangeComputer;
11
12impl VulnerabilityChangeComputer {
13 #[must_use]
15 pub const fn new() -> Self {
16 Self
17 }
18}
19
20impl Default for VulnerabilityChangeComputer {
21 fn default() -> Self {
22 Self::new()
23 }
24}
25
26fn compute_depths(sbom: &NormalizedSbom) -> HashMap<CanonicalId, u32> {
29 let mut depths = HashMap::with_capacity(sbom.components.len());
30
31 let mut edges: HashMap<&CanonicalId, Vec<&CanonicalId>> =
33 HashMap::with_capacity(sbom.components.len());
34 let mut has_parents: HashSet<&CanonicalId> = HashSet::with_capacity(sbom.components.len());
35
36 for edge in &sbom.edges {
37 edges.entry(&edge.from).or_default().push(&edge.to);
38 has_parents.insert(&edge.to);
39 }
40
41 let roots: Vec<&CanonicalId> = sbom
43 .components
44 .keys()
45 .filter(|id| !has_parents.contains(id))
46 .collect();
47
48 let mut queue: VecDeque<(&CanonicalId, u32)> = VecDeque::new();
50
51 for root in &roots {
53 queue.push_back((*root, 0));
54 }
55
56 while let Some((id, depth)) = queue.pop_front() {
57 if let Some(&existing) = depths.get(id)
59 && depth >= existing
60 {
61 continue;
62 }
63 depths.insert(id.clone(), depth);
64
65 if let Some(children) = edges.get(id) {
67 for child in children {
68 let child_depth = depth + 1;
69 if depths.get(*child).is_none_or(|&d| d > child_depth) {
71 queue.push_back((*child, child_depth));
72 }
73 }
74 }
75 }
76
77 depths
78}
79
80impl ChangeComputer for VulnerabilityChangeComputer {
81 type ChangeSet = VulnerabilityChangeSet;
82
83 fn compute(
84 &self,
85 old: &NormalizedSbom,
86 new: &NormalizedSbom,
87 _matches: &ComponentMatches,
88 ) -> VulnerabilityChangeSet {
89 let mut result = VulnerabilityChangeSet::new();
90
91 let old_depths = compute_depths(old);
93 let new_depths = compute_depths(new);
94
95 let old_vuln_count: usize = old
97 .components
98 .values()
99 .map(|c| c.vulnerabilities.len())
100 .sum();
101 let new_vuln_count: usize = new
102 .components
103 .values()
104 .map(|c| c.vulnerabilities.len())
105 .sum();
106
107 let mut old_vulns: HashMap<String, VulnerabilityDetail> =
109 HashMap::with_capacity(old_vuln_count);
110 for (id, comp) in &old.components {
111 let depth = old_depths.get(id).copied();
112 for vuln in &comp.vulnerabilities {
113 let key = format!("{}:{}", vuln.id, id);
114 old_vulns.insert(
115 key,
116 VulnerabilityDetail::from_ref_with_depth(vuln, comp, depth),
117 );
118 }
119 }
120
121 let mut new_vulns: HashMap<String, VulnerabilityDetail> =
123 HashMap::with_capacity(new_vuln_count);
124 for (id, comp) in &new.components {
125 let depth = new_depths.get(id).copied();
126 for vuln in &comp.vulnerabilities {
127 let key = format!("{}:{}", vuln.id, id);
128 new_vulns.insert(
129 key,
130 VulnerabilityDetail::from_ref_with_depth(vuln, comp, depth),
131 );
132 }
133 }
134
135 let old_ids: HashSet<&str> = old_vulns.values().map(|v| v.id.as_str()).collect();
140 let new_ids: HashSet<&str> = new_vulns.values().map(|v| v.id.as_str()).collect();
141
142 for detail in new_vulns.values() {
144 if !old_ids.contains(detail.id.as_str()) {
145 result.introduced.push(detail.clone());
146 }
147 }
148
149 for detail in old_vulns.values() {
151 if !new_ids.contains(detail.id.as_str()) {
152 result.resolved.push(detail.clone());
153 }
154 }
155
156 let mut vex_changes = Vec::new();
158 for (key, detail) in &new_vulns {
159 let exists_in_old = old_ids.contains(detail.id.as_str());
160 if exists_in_old {
161 result.persistent.push(detail.clone());
162
163 if let Some(old_detail) = old_vulns.get(key)
165 && old_detail.vex_state != detail.vex_state
166 {
167 vex_changes.push(VexStatusChange {
168 vuln_id: detail.id.clone(),
169 component_name: detail.component_name.clone(),
170 old_state: old_detail.vex_state.clone(),
171 new_state: detail.vex_state.clone(),
172 });
173 }
174 }
175 }
176 result.vex_changes = vex_changes;
177
178 result.sort_by_severity();
180
181 result
182 }
183
184 fn name(&self) -> &'static str {
185 "VulnerabilityChangeComputer"
186 }
187}
188
189#[cfg(test)]
190mod tests {
191 use super::*;
192
193 #[test]
194 fn test_vulnerability_change_computer_default() {
195 let computer = VulnerabilityChangeComputer;
196 assert_eq!(computer.name(), "VulnerabilityChangeComputer");
197 }
198
199 #[test]
200 fn test_empty_sboms() {
201 let computer = VulnerabilityChangeComputer;
202 let old = NormalizedSbom::default();
203 let new = NormalizedSbom::default();
204 let matches = ComponentMatches::new();
205
206 let result = computer.compute(&old, &new, &matches);
207 assert!(result.is_empty());
208 }
209
210 #[test]
211 fn test_vex_state_change_detection() {
212 use crate::model::{Component, VexState, VexStatus, VulnerabilityRef, VulnerabilitySource};
213
214 let computer = VulnerabilityChangeComputer;
215
216 let mut old_comp = Component::new("libfoo".to_string(), "pkg:npm/libfoo@1.0".to_string());
218 let old_vuln = VulnerabilityRef::new("CVE-2023-1234".to_string(), VulnerabilitySource::Osv)
219 .with_vex_status(VexStatus::new(VexState::NotAffected));
220 old_comp.vulnerabilities.push(old_vuln);
221
222 let mut old_sbom = NormalizedSbom::default();
223 let old_id = old_comp.canonical_id.clone();
224 old_sbom.components.insert(old_id, old_comp);
225
226 let mut new_comp = Component::new("libfoo".to_string(), "pkg:npm/libfoo@1.0".to_string());
228 let new_vuln = VulnerabilityRef::new("CVE-2023-1234".to_string(), VulnerabilitySource::Osv)
229 .with_vex_status(VexStatus::new(VexState::Affected));
230 new_comp.vulnerabilities.push(new_vuln);
231
232 let mut new_sbom = NormalizedSbom::default();
233 let new_id = new_comp.canonical_id.clone();
234 new_sbom.components.insert(new_id, new_comp);
235
236 let matches = ComponentMatches::new();
237 let result = computer.compute(&old_sbom, &new_sbom, &matches);
238
239 assert_eq!(result.persistent.len(), 1);
241 assert!(result.introduced.is_empty());
242 assert!(result.resolved.is_empty());
243
244 assert_eq!(result.vex_changes.len(), 1);
246 let change = &result.vex_changes[0];
247 assert_eq!(change.vuln_id, "CVE-2023-1234");
248 assert_eq!(change.component_name, "libfoo");
249 assert_eq!(change.old_state, Some(VexState::NotAffected));
250 assert_eq!(change.new_state, Some(VexState::Affected));
251 }
252
253 #[test]
254 fn test_no_vex_change_when_states_equal() {
255 use crate::model::{Component, VexState, VexStatus, VulnerabilityRef, VulnerabilitySource};
256
257 let computer = VulnerabilityChangeComputer;
258
259 let mut old_comp = Component::new("libbar".to_string(), "pkg:npm/libbar@2.0".to_string());
261 let old_vuln = VulnerabilityRef::new("CVE-2023-5678".to_string(), VulnerabilitySource::Nvd)
262 .with_vex_status(VexStatus::new(VexState::Fixed));
263 old_comp.vulnerabilities.push(old_vuln);
264
265 let mut old_sbom = NormalizedSbom::default();
266 let old_id = old_comp.canonical_id.clone();
267 old_sbom.components.insert(old_id, old_comp);
268
269 let mut new_comp = Component::new("libbar".to_string(), "pkg:npm/libbar@2.0".to_string());
270 let new_vuln = VulnerabilityRef::new("CVE-2023-5678".to_string(), VulnerabilitySource::Nvd)
271 .with_vex_status(VexStatus::new(VexState::Fixed));
272 new_comp.vulnerabilities.push(new_vuln);
273
274 let mut new_sbom = NormalizedSbom::default();
275 let new_id = new_comp.canonical_id.clone();
276 new_sbom.components.insert(new_id, new_comp);
277
278 let matches = ComponentMatches::new();
279 let result = computer.compute(&old_sbom, &new_sbom, &matches);
280
281 assert_eq!(result.persistent.len(), 1);
282 assert!(result.vex_changes.is_empty());
284 }
285
286 #[test]
287 fn test_vex_state_change_from_none_to_some() {
288 use crate::model::{Component, VexState, VexStatus, VulnerabilityRef, VulnerabilitySource};
289
290 let computer = VulnerabilityChangeComputer;
291
292 let mut old_comp = Component::new("libqux".to_string(), "pkg:npm/libqux@1.0".to_string());
294 let old_vuln =
295 VulnerabilityRef::new("CVE-2024-0001".to_string(), VulnerabilitySource::Ghsa);
296 old_comp.vulnerabilities.push(old_vuln);
297
298 let mut old_sbom = NormalizedSbom::default();
299 let old_id = old_comp.canonical_id.clone();
300 old_sbom.components.insert(old_id, old_comp);
301
302 let mut new_comp = Component::new("libqux".to_string(), "pkg:npm/libqux@1.0".to_string());
304 let new_vuln =
305 VulnerabilityRef::new("CVE-2024-0001".to_string(), VulnerabilitySource::Ghsa)
306 .with_vex_status(VexStatus::new(VexState::UnderInvestigation));
307 new_comp.vulnerabilities.push(new_vuln);
308
309 let mut new_sbom = NormalizedSbom::default();
310 let new_id = new_comp.canonical_id.clone();
311 new_sbom.components.insert(new_id, new_comp);
312
313 let matches = ComponentMatches::new();
314 let result = computer.compute(&old_sbom, &new_sbom, &matches);
315
316 assert_eq!(result.persistent.len(), 1);
317 assert_eq!(result.vex_changes.len(), 1);
318 let change = &result.vex_changes[0];
319 assert_eq!(change.vuln_id, "CVE-2024-0001");
320 assert_eq!(change.old_state, None);
321 assert_eq!(change.new_state, Some(VexState::UnderInvestigation));
322 }
323}