deps-core 5.0.0

Core abstractions for deps-lsp: caching, errors, and traits
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
//! Fan-out of a [`ScanTarget`] over its lock-file alternatives (#1981).
//!
//! A lock file can hold several entries that satisfy one dependency's requirement, and it
//! cannot say which one the package manager installed. [`expand`] turns each alternative into an
//! internal sub-target under a synthetic key, and [`merge`] folds the sub-outcomes back into one
//! outcome per real key, so no synthetic key ever reaches a caller.

use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use super::types::{
    Advisory, AlternativeCoverage, Capped, DependencyVulnerabilities, MatchOrigin, MatchedTags,
    OsvId, OsvVersion, ScanOutcome, ScanTarget, SiblingMatches, SkipReason, VulnKey,
    VulnerabilityMap,
};
use super::{LockPresence, MAX_ADVISORY_RECORDS, MAX_LOCK_ALTERNATIVES};
use crate::ConcreteVersion;

/// The sub-targets one real target fanned out into.
pub(super) struct Fan {
    key: VulnKey,
    version: OsvVersion,
    alternatives: Vec<(VulnKey, ConcreteVersion)>,
    coverage: AlternativeCoverage,
}

/// Returns `targets` followed by one sub-target per scanned lock alternative, plus the
/// bookkeeping [`merge`] needs. Only the first target per key fans out, as duplicate keys share
/// one result.
pub(super) fn expand(targets: &[ScanTarget]) -> (Vec<ScanTarget>, Vec<Fan>) {
    let mut expanded = targets.to_vec();
    let mut fans = Vec::new();
    let mut seen: HashSet<&VulnKey> = HashSet::with_capacity(targets.len());
    for target in targets {
        if target.lock_alternatives().is_empty() || !seen.insert(&target.key) {
            continue;
        }
        let scanned = target
            .lock_alternatives()
            .iter()
            .take(MAX_LOCK_ALTERNATIVES)
            .enumerate();
        let mut alternatives = Vec::new();
        for (index, alternative) in scanned {
            let key = target.key.lock_alternative(index);
            expanded.push(ScanTarget::new(
                key.clone(),
                target.osv_name.clone(),
                alternative.version().clone(),
                alternative.display_version().clone(),
            ));
            alternatives.push((key, alternative.display_version().clone()));
        }
        fans.push(Fan {
            key: target.key.clone(),
            version: target.version.clone(),
            alternatives,
            coverage: target.alternative_coverage(),
        });
    }
    (expanded, fans)
}

/// Replaces each fanned-out key's outcome in `outcomes` with the merge of its sub-outcomes and
/// drops every synthetic key.
pub(super) fn merge(outcomes: &mut VulnerabilityMap, fans: Vec<Fan>) {
    for fan in fans {
        let alternatives = fan
            .alternatives
            .into_iter()
            .map(|(key, version)| {
                let outcome = outcomes
                    .remove(&key)
                    .unwrap_or(ScanOutcome::Skipped(SkipReason::QueryFailed));
                (version, outcome)
            })
            .collect();
        let primary = outcomes
            .remove(&fan.key)
            .unwrap_or(ScanOutcome::Skipped(SkipReason::QueryFailed));
        outcomes.insert(
            fan.key,
            merge_outcomes(primary, &fan.version, alternatives, fan.coverage),
        );
    }
}

/// Merges the primary's outcome with its alternatives' (lowest version first).
///
/// In order:
/// 1. Any `Vulnerable` sub-outcome wins: the result is the deduplicated union of advisories,
///    and an advisory only an alternative matched carries [`MatchOrigin::LockEntry`] tags. The
///    list is marked incomplete when any other sub-outcome was skipped or alternatives
///    were truncated.
/// 2. Otherwise a skipped primary keeps its own reason.
/// 3. Otherwise the first skipped alternative's reason stands when it is a coverage gap, else
///    [`SkipReason::LockAlternativesUnchecked`], so a structural reason cannot make the
///    dependency vanish from both "clean" and "unchecked".
/// 4. Otherwise overflow alone is [`SkipReason::LockAlternativesUnchecked`]; it only ever turns
///    a clean answer into a skip.
fn merge_outcomes(
    primary: ScanOutcome,
    primary_version: &OsvVersion,
    alternatives: Vec<(ConcreteVersion, ScanOutcome)>,
    coverage: AlternativeCoverage,
) -> ScanOutcome {
    let overflowed = coverage == AlternativeCoverage::Truncated;
    let mut primary_vulnerable = None;
    let mut primary_skip = None;
    match primary {
        ScanOutcome::Clean => {}
        ScanOutcome::Vulnerable(dv) => primary_vulnerable = Some(dv),
        ScanOutcome::Skipped(reason) => primary_skip = Some(reason),
    }
    let mut vulnerable_alternatives = Vec::new();
    let mut first_alternative_skip = None;
    for (version, outcome) in alternatives {
        match outcome {
            ScanOutcome::Clean => {}
            ScanOutcome::Vulnerable(dv) => vulnerable_alternatives.push((version, dv)),
            ScanOutcome::Skipped(reason) => {
                first_alternative_skip.get_or_insert(reason);
            }
        }
    }

    if primary_vulnerable.is_none() && vulnerable_alternatives.is_empty() {
        return match (primary_skip, first_alternative_skip, overflowed) {
            (Some(reason), _, _) => ScanOutcome::Skipped(reason),
            (None, Some(reason), _) => ScanOutcome::Skipped(
                reason
                    .coverage_gap(LockPresence::Found)
                    .map_or(SkipReason::LockAlternativesUnchecked, |_| reason),
            ),
            (None, None, true) => ScanOutcome::Skipped(SkipReason::LockAlternativesUnchecked),
            (None, None, false) => ScanOutcome::Clean,
        };
    }

    let incomplete = primary_skip.is_some() || first_alternative_skip.is_some() || overflowed;
    ScanOutcome::Vulnerable(union_advisories(
        primary_vulnerable.as_ref(),
        &vulnerable_alternatives,
        primary_version,
        incomplete,
    ))
}

fn union_advisories(
    primary: Option<&DependencyVulnerabilities>,
    alternatives: &[(ConcreteVersion, DependencyVulnerabilities)],
    primary_version: &OsvVersion,
    incomplete: bool,
) -> DependencyVulnerabilities {
    let primary_ids: HashSet<&OsvId> = primary
        .into_iter()
        .flat_map(|dv| dv.advisories.items())
        .map(|advisory| advisory.id())
        .collect();
    let mut advisories: Vec<Arc<Advisory>> = Vec::new();
    let mut seen: HashSet<OsvId> = HashSet::new();
    let mut alternative_only: HashMap<OsvId, Vec<ConcreteVersion>> = HashMap::new();
    let mut unfetched = 0usize;

    if let Some(dv) = primary {
        unfetched += dv.advisories.remaining();
        for advisory in dv.advisories.items() {
            if seen.insert(advisory.id().clone()) {
                advisories.push(Arc::clone(advisory));
            }
        }
    }
    for (version, dv) in alternatives {
        unfetched += dv.advisories.remaining();
        for advisory in dv.advisories.items() {
            if !primary_ids.contains(advisory.id()) {
                alternative_only
                    .entry(advisory.id().clone())
                    .or_default()
                    .push(version.clone());
            }
            if seen.insert(advisory.id().clone()) {
                advisories.push(Arc::clone(advisory));
            }
        }
    }

    let total = advisories.len() + unfetched;
    advisories.truncate(MAX_ADVISORY_RECORDS);

    let mut matches = SiblingMatches::new(primary_version.clone());
    for advisory in &advisories {
        if let Some(versions) = alternative_only.remove(advisory.id())
            && let Some(tags) = MatchedTags::from_versions(MatchOrigin::LockEntry, versions)
        {
            matches.insert(advisory.id().clone(), tags);
        }
    }
    let counted = Capped::new(advisories, total);
    let counted = if incomplete {
        counted.with_total_as_lower_bound()
    } else {
        counted
    };
    let merged = DependencyVulnerabilities::new(counted);
    if matches.is_empty() {
        merged
    } else {
        merged.with_sibling_matches(matches)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::osv::{OsvPackageName, OsvQueryName, VulnSeverity};
    use std::assert_matches;

    fn vulnerable(ids: &[&str]) -> ScanOutcome {
        let advisories: Vec<Arc<Advisory>> = ids
            .iter()
            .map(|id| {
                Arc::new(
                    Advisory::new(
                        (*id).to_string(),
                        "2023-01-01T00:00:00Z".into(),
                        VulnSeverity::High,
                    )
                    .unwrap(),
                )
            })
            .collect();
        let total = advisories.len();
        ScanOutcome::Vulnerable(DependencyVulnerabilities::new(Capped::new(
            advisories, total,
        )))
    }

    fn merged(
        primary: ScanOutcome,
        alternatives: Vec<(&str, ScanOutcome)>,
        overflowed: bool,
    ) -> ScanOutcome {
        let alternatives = alternatives
            .into_iter()
            .map(|(v, outcome)| (ConcreteVersion::new(v), outcome))
            .collect();
        merge_outcomes(
            primary,
            &OsvVersion::new("1.2.8"),
            alternatives,
            if overflowed {
                AlternativeCoverage::Truncated
            } else {
                AlternativeCoverage::Complete
            },
        )
    }

    fn dv(outcome: &ScanOutcome) -> &DependencyVulnerabilities {
        match outcome {
            ScanOutcome::Vulnerable(dv) => dv,
            other => panic!("expected Vulnerable, got {other:?}"),
        }
    }

    fn skip(outcome: &ScanOutcome) -> SkipReason {
        match outcome {
            ScanOutcome::Skipped(reason) => *reason,
            other => panic!("expected Skipped, got {other:?}"),
        }
    }

    fn ids(outcome: &ScanOutcome) -> Vec<&str> {
        dv(outcome)
            .advisories
            .items()
            .iter()
            .map(|a| a.id().as_str())
            .collect()
    }

    fn names(tags: &MatchedTags) -> Vec<&str> {
        tags.iter().map(ConcreteVersion::as_str).collect()
    }

    #[test]
    fn clean_everywhere_is_clean() {
        let outcome = merged(
            ScanOutcome::Clean,
            vec![("1.2.5", ScanOutcome::Clean)],
            false,
        );
        assert_matches!(outcome, ScanOutcome::Clean);
    }

    #[test]
    fn advisory_only_an_alternative_matched_carries_lock_entry_tags() {
        let outcome = merged(
            ScanOutcome::Clean,
            vec![("1.2.5", vulnerable(&["GHSA-aaaa-bbbb-cccc"]))],
            false,
        );

        let id = crate::test_util::osv_id("GHSA-aaaa-bbbb-cccc");
        let tags = dv(&outcome)
            .sibling_match(&id)
            .expect("alternative-only match");
        assert_eq!(tags.origin(), MatchOrigin::LockEntry);
        assert_eq!(names(tags), ["1.2.5"]);
        assert!(dv(&outcome).advisories.is_complete());
        assert_eq!(
            dv(&outcome).sibling_only_tags().map(|t| t.origin()),
            Some(MatchOrigin::LockEntry)
        );
    }

    #[test]
    fn advisory_matching_primary_and_alternative_is_deduplicated_without_a_lock_entry_note() {
        let outcome = merged(
            vulnerable(&["GHSA-aaaa-bbbb-cccc"]),
            vec![
                (
                    "1.2.5",
                    vulnerable(&["GHSA-aaaa-bbbb-cccc", "GHSA-dddd-eeee-ffff"]),
                ),
                ("1.2.6", vulnerable(&["GHSA-dddd-eeee-ffff"])),
            ],
            false,
        );

        assert_eq!(
            ids(&outcome),
            ["GHSA-aaaa-bbbb-cccc", "GHSA-dddd-eeee-ffff"]
        );
        let shared = crate::test_util::osv_id("GHSA-aaaa-bbbb-cccc");
        assert!(dv(&outcome).sibling_match(&shared).is_none());
        let only = crate::test_util::osv_id("GHSA-dddd-eeee-ffff");
        let tags = dv(&outcome).sibling_match(&only).unwrap();
        assert_eq!(names(tags), ["1.2.5", "1.2.6"]);
    }

    #[test]
    fn vulnerable_primary_with_a_failed_alternative_stays_vulnerable_but_incomplete() {
        let outcome = merged(
            vulnerable(&["GHSA-aaaa-bbbb-cccc"]),
            vec![("1.2.5", ScanOutcome::Skipped(SkipReason::QueryFailed))],
            false,
        );

        assert_eq!(ids(&outcome), ["GHSA-aaaa-bbbb-cccc"]);
        assert!(!dv(&outcome).advisories.is_complete());
    }

    #[test]
    fn failed_alternative_keeps_the_known_total_and_reports_a_lower_bound() {
        let outcome = merged(
            vulnerable(&["GHSA-aaaa-bbbb-cccc"]),
            vec![("1.2.5", ScanOutcome::Skipped(SkipReason::QueryFailed))],
            false,
        );

        let advisories = &dv(&outcome).advisories;
        assert_eq!(advisories.total(), 1);
        assert_eq!(
            advisories.overflow(),
            Some(crate::osv::AdvisoryCount::AtLeast(0))
        );
    }

    #[test]
    fn fully_scanned_alternatives_report_an_exact_count() {
        let outcome = merged(vulnerable(&["GHSA-aaaa-bbbb-cccc"]), vec![], false);
        assert_eq!(dv(&outcome).advisories.overflow(), None);
    }

    #[test]
    fn clean_primary_with_a_failed_alternative_is_query_failed() {
        let outcome = merged(
            ScanOutcome::Clean,
            vec![("1.2.5", ScanOutcome::Skipped(SkipReason::QueryFailed))],
            false,
        );
        assert_eq!(skip(&outcome), SkipReason::QueryFailed);
    }

    #[test]
    fn clean_primary_with_a_structurally_skipped_alternative_is_lock_alternatives_unchecked() {
        let outcome = merged(
            ScanOutcome::Clean,
            vec![(
                "1.2.5",
                ScanOutcome::Skipped(SkipReason::UnmatchableVersion),
            )],
            false,
        );
        assert_eq!(skip(&outcome), SkipReason::LockAlternativesUnchecked);
    }

    #[test]
    fn skipped_primary_keeps_its_own_reason() {
        let outcome = merged(
            ScanOutcome::Skipped(SkipReason::Truncated),
            vec![("1.2.5", ScanOutcome::Skipped(SkipReason::QueryFailed))],
            false,
        );
        assert_eq!(skip(&outcome), SkipReason::Truncated);
    }

    #[test]
    fn first_skipped_alternative_in_version_order_decides() {
        let outcome = merged(
            ScanOutcome::Clean,
            vec![
                ("1.2.3", ScanOutcome::Skipped(SkipReason::Truncated)),
                ("1.2.5", ScanOutcome::Skipped(SkipReason::QueryFailed)),
            ],
            false,
        );
        assert_eq!(skip(&outcome), SkipReason::Truncated);
    }

    #[test]
    fn overflow_turns_clean_into_unchecked() {
        let outcome = merged(
            ScanOutcome::Clean,
            vec![("1.2.5", ScanOutcome::Clean)],
            true,
        );
        assert_eq!(skip(&outcome), SkipReason::LockAlternativesUnchecked);
    }

    #[test]
    fn overflow_never_overrides_vulnerable() {
        let outcome = merged(
            ScanOutcome::Clean,
            vec![("1.2.5", vulnerable(&["GHSA-aaaa-bbbb-cccc"]))],
            true,
        );
        assert_eq!(ids(&outcome), ["GHSA-aaaa-bbbb-cccc"]);
        assert!(!dv(&outcome).advisories.is_complete());
    }

    fn target_with_alternatives(count: usize, coverage: AlternativeCoverage) -> ScanTarget {
        let versions: Vec<ConcreteVersion> = (0..count)
            .map(|n| ConcreteVersion::new(format!("1.0.{n}")))
            .collect();
        let in_use = crate::lsp_helpers::InUseVersions::for_test_with_alternative_coverage(
            ConcreteVersion::new("2.0.0"),
            versions,
            coverage,
        );
        ScanTarget::from_native(
            crate::test_util::vuln_key("pkg"),
            OsvQueryName::Confirmed(OsvPackageName::new("pkg").unwrap()),
            ConcreteVersion::new("2.0.0"),
            &crate::test_util::StubFormatter::DEFAULT,
        )
        .with_lock_alternatives(&in_use, &crate::test_util::StubFormatter::DEFAULT)
    }

    #[test]
    fn expand_scans_every_listed_alternative_and_truncation_turns_clean_into_unchecked() {
        let target =
            target_with_alternatives(MAX_LOCK_ALTERNATIVES, AlternativeCoverage::Truncated);
        let (expanded, fans) = expand(std::slice::from_ref(&target));

        assert_eq!(expanded.len(), 1 + MAX_LOCK_ALTERNATIVES);
        assert_eq!(fans.len(), 1);
        let distinct: HashSet<&VulnKey> = expanded.iter().map(|t| &t.key).collect();
        assert_eq!(distinct.len(), expanded.len());

        let mut outcomes: VulnerabilityMap = expanded
            .iter()
            .map(|t| (t.key.clone(), ScanOutcome::Clean))
            .collect();
        merge(&mut outcomes, fans);

        assert_eq!(outcomes.len(), 1);
        assert_eq!(
            skip(&outcomes[&target.key]),
            SkipReason::LockAlternativesUnchecked
        );
    }

    #[test]
    fn expand_fans_out_only_the_first_target_of_a_duplicate_key() {
        let target = target_with_alternatives(2, AlternativeCoverage::Complete);
        let (expanded, fans) = expand(&[target.clone(), target]);

        assert_eq!(expanded.len(), 2 + 2);
        assert_eq!(fans.len(), 1);
    }
}