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
//! Release version selection and CVE-affected version planning.
//!
//! [`select_release`] picks the deps.dev default/deprecated version for latest
//! ingestion. [`plan_versions`] evaluates OSV-shaped advisories against a
//! source version catalog for one CVE/project. It never fabricates records:
//! versions that are not in the catalog are reported through
//! [`VersionPlan::version_labels`] and [`VersionPlan::affected_ranges`].
use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::release::versioning::normalize_version;
use super::SelectedRelease;
fn json_truthy(value: Option<&Value>) -> bool {
match value {
None | Some(Value::Null) => false,
Some(Value::Bool(value)) => *value,
Some(Value::Number(number)) => number.as_f64().is_none_or(|value| value != 0.0),
Some(Value::String(value)) => !value.is_empty(),
Some(Value::Array(value)) => !value.is_empty(),
Some(Value::Object(value)) => !value.is_empty(),
}
}
fn text_or_empty(value: Option<&Value>) -> String {
match value {
Some(Value::String(value)) => value.clone(),
Some(Value::Null) | None => String::new(),
Some(other) => other.to_string(),
}
}
/// Deps.dev default/deprecated ordering, then the first representable version.
pub fn select_release(versions: &[Value]) -> Option<SelectedRelease> {
let default = versions
.iter()
.position(|version| json_truthy(version.get("isDefault")));
let contains =
|ordered: &[usize], value: &Value| ordered.iter().any(|&index| &versions[index] == value);
let mut ordered: Vec<usize> = Vec::new();
if let Some(index) = default
&& !json_truthy(versions[index].get("isDeprecated"))
{
ordered.push(index);
}
for index in (0..versions.len()).rev() {
if Some(index) != default && !json_truthy(versions[index].get("isDeprecated")) {
ordered.push(index);
}
}
if let Some(index) = default
&& !contains(&ordered, &versions[index])
{
ordered.push(index);
}
for index in (0..versions.len()).rev() {
if !contains(&ordered, &versions[index]) {
ordered.push(index);
}
}
for index in ordered {
let item = &versions[index];
let Some(raw) = item
.get("versionKey")
.and_then(|key| key.get("version"))
.and_then(Value::as_str)
else {
continue;
};
let Some(version) = normalize_version(raw) else {
continue;
};
return Some(SelectedRelease {
raw: raw.to_owned(),
version,
deprecated: json_truthy(item.get("isDeprecated")),
reason: text_or_empty(item.get("deprecatedReason")),
});
}
None
}
// ---------------------------------------------------------------------------
// Affected version planning
// ---------------------------------------------------------------------------
/// Ecosystem version ordering injected by the source adapter.
pub trait VersionCompare {
fn compare(&self, a: &str, b: &str) -> Ordering;
fn scheme(&self) -> &'static str;
}
/// Lexical ordering for tests only. Production injects the P2-A comparator.
#[derive(Debug, Clone, Copy, Default)]
pub struct LexicalCompare;
impl VersionCompare for LexicalCompare {
fn compare(&self, a: &str, b: &str) -> Ordering {
a.cmp(b)
}
fn scheme(&self) -> &'static str {
"lexical"
}
}
/// One advisory, shaped like an OSV entry but independent of any source
/// adapter's types.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Advisory {
pub id: String,
pub aliases: Vec<String>,
pub modified: Option<String>,
pub affected: Vec<AffectedPackage>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct AffectedPackage {
pub ecosystem: String,
pub name: String,
pub purl: Option<String>,
pub ranges: Vec<AffectedRange>,
pub versions: Vec<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct AffectedRange {
#[serde(rename = "type")]
pub kind: String,
pub events: Vec<RangeEvent>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct RangeEvent {
pub introduced: Option<String>,
pub fixed: Option<String>,
pub last_affected: Option<String>,
pub limit: Option<String>,
}
/// One version in the source catalog. `deprecated` is retained for callers,
/// but planning deliberately includes deprecated versions.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct CatalogVersion {
pub raw: String,
pub normalized: String,
pub deprecated: bool,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlannedVersion {
pub version: String,
pub raw: String,
pub affected: bool,
pub fixed_in: Option<String>,
pub range_label: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct VersionPlan {
pub project_slug: String,
pub purl: String,
pub versions: Vec<PlannedVersion>,
pub version_labels: Vec<String>,
pub affected_ranges: Vec<String>,
pub skipped_reason: Option<String>,
}
/// Exact affected versions from OSV advisories for one CVE and project.
///
/// `cve_id` selects advisories by id or alias; pass an empty string when the
/// caller already pre-filtered the advisory list. Advisories that match no
/// catalog version still produce `version_labels`/`affected_ranges`; they
/// never produce fabricated [`PlannedVersion`] entries. With no advisory or
/// alias match the plan is empty and `skipped_reason` is `no_osv_match`, so
/// NVD-only CVEs never get inferred versions.
pub fn plan_versions(
cve_id: &str,
project_slug: &str,
purl: &str,
catalog: &[CatalogVersion],
advisories: &[Advisory],
scheme: &dyn VersionCompare,
) -> VersionPlan {
let mut plan = VersionPlan {
project_slug: project_slug.to_owned(),
purl: purl.to_owned(),
..VersionPlan::default()
};
let mut matched = false;
let mut intervals: Vec<Interval> = Vec::new();
let mut affected_ranges: BTreeSet<String> = BTreeSet::new();
let mut endpoints: BTreeSet<String> = BTreeSet::new();
let mut exact_versions: BTreeSet<String> = BTreeSet::new();
for advisory in advisories {
if !advisory_matches_cve(advisory, cve_id) {
continue;
}
for package in &advisory.affected {
if !package_matches_purl(package, purl) {
continue;
}
matched = true;
for range in &package.ranges {
for interval in intervals_from(range) {
if let Some(introduced) = &interval.introduced {
endpoints.insert(introduced.clone());
}
match &interval.end {
Some(End::Fixed(version) | End::Limit(version)) => {
endpoints.insert(version.clone());
}
Some(End::LastAffected(version)) => {
endpoints.insert(version.clone());
}
None => {}
}
affected_ranges.insert(interval_label(&interval));
intervals.push(interval);
}
}
for version in &package.versions {
endpoints.insert(version.clone());
exact_versions.insert(version.clone());
}
}
}
if !matched {
plan.skipped_reason = Some("no_osv_match".to_owned());
return plan;
}
let mut planned: BTreeMap<String, PlannedVersion> = BTreeMap::new();
for entry in catalog {
let version = if entry.normalized.is_empty() {
entry.raw.as_str()
} else {
entry.normalized.as_str()
};
let mut labels: Vec<String> = Vec::new();
let mut fixed_in: Vec<String> = Vec::new();
for interval in &intervals {
if interval_contains(interval, version, scheme) {
labels.push(interval_label(interval));
if let Some(fixed) = interval_fixed_in(interval) {
fixed_in.push(fixed.to_owned());
}
}
}
for requested in &exact_versions {
if catalog_version_matches(requested, entry) {
labels.push(format!("= {requested}"));
}
}
if labels.is_empty() {
continue;
}
labels.sort();
labels.dedup();
fixed_in.sort();
fixed_in.dedup();
planned.entry(version.to_owned()).or_insert(PlannedVersion {
version: version.to_owned(),
raw: entry.raw.clone(),
affected: true,
fixed_in: fixed_in.into_iter().next(),
range_label: labels.join("; "),
});
}
plan.versions = planned.into_values().collect();
plan.versions.sort_by(|left, right| {
scheme
.compare(&left.version, &right.version)
.then_with(|| left.version.cmp(&right.version))
.then_with(|| left.raw.cmp(&right.raw))
});
plan.affected_ranges = affected_ranges.into_iter().collect();
let mut version_labels: Vec<String> = endpoints
.into_iter()
.filter(|endpoint| !catalog_contains(catalog, endpoint))
.collect();
version_labels.sort_by(|left, right| scheme.compare(left, right).then_with(|| left.cmp(right)));
plan.version_labels = version_labels;
plan
}
/// One `[introduced, end)` interval parsed from an OSV event list. `None`
/// `introduced` means OSV's `"0"` sentinel: affected from the beginning.
#[derive(Debug, Clone)]
struct Interval {
introduced: Option<String>,
end: Option<End>,
}
#[derive(Debug, Clone)]
enum End {
Fixed(String),
LastAffected(String),
Limit(String),
}
fn intervals_from(range: &AffectedRange) -> Vec<Interval> {
let mut intervals = Vec::new();
let mut open: Option<Option<String>> = None;
for event in &range.events {
if let Some(introduced) = event.introduced.as_deref()
&& open.is_none()
{
open = Some(normalize_introduced(introduced));
}
let end = if let Some(fixed) = &event.fixed {
Some(End::Fixed(fixed.clone()))
} else if let Some(last_affected) = &event.last_affected {
Some(End::LastAffected(last_affected.clone()))
} else {
event.limit.as_ref().map(|limit| End::Limit(limit.clone()))
};
if let Some(end) = end {
intervals.push(Interval {
introduced: open.take().unwrap_or_default(),
end: Some(end),
});
}
}
if let Some(introduced) = open {
intervals.push(Interval {
introduced,
end: None,
});
}
intervals
}
fn normalize_introduced(introduced: &str) -> Option<String> {
if introduced.is_empty() || introduced == "0" {
None
} else {
Some(introduced.to_owned())
}
}
fn interval_contains(interval: &Interval, version: &str, scheme: &dyn VersionCompare) -> bool {
if let Some(introduced) = &interval.introduced
&& scheme.compare(version, introduced) == Ordering::Less
{
return false;
}
match &interval.end {
None => true,
Some(End::Fixed(fixed) | End::Limit(fixed)) => {
scheme.compare(version, fixed) == Ordering::Less
}
Some(End::LastAffected(last_affected)) => {
scheme.compare(version, last_affected) != Ordering::Greater
}
}
}
fn interval_fixed_in(interval: &Interval) -> Option<&str> {
match &interval.end {
Some(End::Fixed(fixed) | End::Limit(fixed)) => Some(fixed),
Some(End::LastAffected(_)) | None => None,
}
}
fn interval_label(interval: &Interval) -> String {
let end = match &interval.end {
None => None,
Some(End::Fixed(version) | End::Limit(version)) => Some(format!("< {version}")),
Some(End::LastAffected(version)) => Some(format!("<= {version}")),
};
match (&interval.introduced, end) {
(None, None) => "*".to_owned(),
(None, Some(end)) => end,
(Some(introduced), None) => format!(">= {introduced}"),
(Some(introduced), Some(end)) => format!(">= {introduced}, {end}"),
}
}
fn advisory_matches_cve(advisory: &Advisory, cve_id: &str) -> bool {
cve_id.is_empty()
|| advisory.id.eq_ignore_ascii_case(cve_id)
|| advisory
.aliases
.iter()
.any(|alias| alias.eq_ignore_ascii_case(cve_id))
}
/// Whether any affected package in `advisory` names `purl`. Used to filter an
/// offline bulk dump down to the purls a project actually asks for.
pub fn advisory_affects_purl(advisory: &Advisory, purl: &str) -> bool {
advisory
.affected
.iter()
.any(|package| package_matches_purl(package, purl))
}
fn package_matches_purl(package: &AffectedPackage, purl: &str) -> bool {
let wanted = purl_name(purl);
if let Some(candidate) = package.purl.as_deref() {
if candidate.eq_ignore_ascii_case(purl) {
return true;
}
let candidate_name = purl_name(candidate);
if !candidate_name.is_empty() && candidate_name.eq_ignore_ascii_case(&wanted) {
return true;
}
}
let name = package.name.trim();
if name.is_empty() {
return false;
}
name.eq_ignore_ascii_case(&wanted)
|| wanted
.rsplit('/')
.next()
.is_some_and(|leaf| name.eq_ignore_ascii_case(leaf))
}
fn purl_name(purl: &str) -> String {
let body = purl.strip_prefix("pkg:").unwrap_or(purl);
let body = body.split('#').next().unwrap_or(body);
let body = body.split('?').next().unwrap_or(body);
let Some((_, path)) = body.split_once('/') else {
return String::new();
};
match path.rsplit_once('@') {
Some((name, _version)) => name.to_owned(),
None => path.to_owned(),
}
}
fn catalog_contains(catalog: &[CatalogVersion], version: &str) -> bool {
catalog
.iter()
.any(|entry| catalog_version_matches(version, entry))
}
fn catalog_version_matches(requested: &str, entry: &CatalogVersion) -> bool {
if requested.eq_ignore_ascii_case(&entry.raw)
|| requested.eq_ignore_ascii_case(&entry.normalized)
{
return true;
}
if entry.normalized.is_empty() {
return false;
}
normalize_version(requested).is_some_and(|normalized| normalized == entry.normalized)
}