deps-core 6.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
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
//! Per-package diagnostic suppression (#1927, spec 094).
//!
//! A [`SuppressionSet`] is the typed, validated form of `diagnostics.suppress` in the shared
//! policy config. It is compiled against an ecosystem's name normalization once per diagnostics
//! run ([`SuppressionSet::resolve`]) and applied inside
//! [`generate_diagnostics_from_cache`](super::generate_diagnostics_from_cache), so every
//! ecosystem honors a rule identically.
//!
//! Only the closed [`SuppressionKind`] set is suppressible. Vulnerability advisories are never
//! suppressible: workspace settings can be controlled by the repository being opened, so a
//! repo-supplied rule must not be able to hide a security finding. The single exception is an
//! advisory classified as unmaintained, which is hidden together with the deprecation it
//! duplicates (FR-008).

use serde::Deserialize;

use super::{EcosystemFormatter, NormalizeName};
use crate::PackageName;
use crate::diagnostic::DiagnosticKind;
use crate::osv::{DependencyVulnerabilities, VulnSeverity};
use crate::package::NormalizedName;

/// A diagnostic kind a user may suppress for a package.
///
/// Deliberately narrower than [`DiagnosticKind`]; the mapping is the exhaustive match in
/// `SuppressedKinds::hides`.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::SuppressionKind;
///
/// let kind: SuppressionKind = serde_json::from_str("\"deprecated\"").unwrap();
/// assert_eq!(kind, SuppressionKind::Deprecated);
/// assert!(serde_json::from_str::<SuppressionKind>("\"vulnerability\"").is_err());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SuppressionKind {
    /// The package is deprecated, including its unmaintained advisories.
    Deprecated,
    /// A newer version is available.
    Outdated,
    /// The in-use or only-matching version is yanked.
    Yanked,
    /// The declared license violates the configured license policy.
    License,
}

impl SuppressionKind {
    /// Every variant, the single source of [`SuppressedKinds::ALL`]; the `every_kind_is_listed`
    /// test fails to compile when a variant is added without extending this list.
    const EVERY: [Self; 4] = [
        Self::Deprecated,
        Self::Outdated,
        Self::Yanked,
        Self::License,
    ];
}

/// A set of [`SuppressionKind`]s.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::{SuppressedKinds, SuppressionKind};
///
/// let kinds = SuppressedKinds::default().with(SuppressionKind::Yanked);
/// assert!(kinds.contains(SuppressionKind::Yanked));
/// assert!(!kinds.contains(SuppressionKind::Outdated));
/// ```
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SuppressedKinds(u8);

impl SuppressedKinds {
    const fn bit(kind: SuppressionKind) -> u8 {
        match kind {
            SuppressionKind::Deprecated => 1,
            SuppressionKind::Outdated => 2,
            SuppressionKind::Yanked => 4,
            SuppressionKind::License => 8,
        }
    }

    /// Every suppressible kind: what a whole-package ignore hides.
    pub const ALL: Self = Self::of(&SuppressionKind::EVERY);

    const fn of(kinds: &[SuppressionKind]) -> Self {
        match kinds {
            [first, rest @ ..] => Self::of(rest).with(*first),
            [] => Self(0),
        }
    }

    /// This set plus `kind`.
    #[must_use]
    pub const fn with(self, kind: SuppressionKind) -> Self {
        Self(self.0 | Self::bit(kind))
    }

    /// Every kind in either set.
    #[must_use]
    pub const fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    /// Whether `kind` is in the set.
    #[must_use]
    pub const fn contains(self, kind: SuppressionKind) -> bool {
        self.0 & Self::bit(kind) != 0
    }

    /// Whether no kind is in the set.
    #[must_use]
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }

    /// `dv` without the unmaintained (Informational) advisories when `deprecated` is in the set,
    /// borrowed unchanged otherwise. The one definition of FR-008 for diagnostics and hover.
    pub(crate) fn visible_advisories(
        self,
        dv: &DependencyVulnerabilities,
    ) -> std::borrow::Cow<'_, DependencyVulnerabilities> {
        if self.contains(SuppressionKind::Deprecated) {
            std::borrow::Cow::Owned(dv.without_informational())
        } else {
            std::borrow::Cow::Borrowed(dv)
        }
    }

    /// Whether a diagnostic of `kind` for a package with this suppression set must be dropped.
    ///
    /// `vulnerabilities` is that package's resolved OSV finding; an advisory is hidden only when
    /// the deprecated kind is suppressed and the advisory is typed
    /// [`VulnSeverity::Informational`], which only the unmaintained allowlist produces. Neither
    /// `Diagnostic::severity` nor message text is consulted.
    pub(crate) fn hides(
        self,
        kind: &DiagnosticKind,
        vulnerabilities: Option<&DependencyVulnerabilities>,
    ) -> bool {
        match kind {
            DiagnosticKind::Outdated => self.contains(SuppressionKind::Outdated),
            DiagnosticKind::Yanked => self.contains(SuppressionKind::Yanked),
            DiagnosticKind::LicensePolicy => self.contains(SuppressionKind::License),
            DiagnosticKind::Deprecated => self.contains(SuppressionKind::Deprecated),
            DiagnosticKind::Advisory(id) => {
                self.contains(SuppressionKind::Deprecated)
                    && vulnerabilities.is_some_and(|dv| {
                        dv.advisories
                            .items()
                            .iter()
                            .any(|a| a.id() == id && a.severity == VulnSeverity::Informational)
                    })
            }
            // The overflow line is never hidden itself; its count already excludes hidden
            // advisories (#1960, `push_vulnerability_diagnostics`).
            DiagnosticKind::FlaggedLatest
            | DiagnosticKind::UnverifiedLatest
            | DiagnosticKind::AdvisoryOverflow
            | DiagnosticKind::AdvisoryExempted
            | DiagnosticKind::Unsatisfiable
            | DiagnosticKind::Typosquat
            | DiagnosticKind::MutableRefPin(_)
            | DiagnosticKind::ShaCommentMismatch
            | DiagnosticKind::UnknownRef
            | DiagnosticKind::UnresolvedGitlabHost
            | DiagnosticKind::DuplicateDefaultCatalog
            | DiagnosticKind::Notice => false,
        }
    }
}

/// Why a package pattern was rejected.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum PatternError {
    /// The pattern is the empty string.
    #[error("package pattern must not be empty")]
    Empty,
    /// The pattern is a bare `*`, which would match every package.
    #[error("a bare `*` package pattern is not allowed")]
    BareWildcard,
    /// A `*` that is not the only leading or only trailing character.
    #[error("`*` is only supported as a single leading or trailing wildcard")]
    UnsupportedWildcard,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum PatternShape {
    Exact(String),
    Prefix(String),
    Suffix(String),
}

/// A validated package name or single-wildcard glob (`name`, `prefix*`, `*suffix`).
///
/// Matching is linear-time string comparison, never a regex.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::PackagePattern;
///
/// assert!(PackagePattern::parse("@types/*").is_ok());
/// assert!(PackagePattern::parse("*").is_err());
/// assert!(PackagePattern::parse("a*b").is_err());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(try_from = "String")]
pub struct PackagePattern(PatternShape);

impl PackagePattern {
    /// Parses `raw` into a pattern.
    ///
    /// # Errors
    ///
    /// [`PatternError`] when `raw` is empty, a bare `*`, or has a `*` anywhere but as the single
    /// leading or trailing character.
    pub fn parse(raw: &str) -> Result<Self, PatternError> {
        if raw.is_empty() {
            return Err(PatternError::Empty);
        }
        if raw == "*" {
            return Err(PatternError::BareWildcard);
        }
        let stars = raw.matches('*').count();
        let shape = match (stars, raw.strip_suffix('*'), raw.strip_prefix('*')) {
            (0, _, _) => PatternShape::Exact(raw.to_owned()),
            (1, Some(prefix), _) => PatternShape::Prefix(prefix.to_owned()),
            (1, None, Some(suffix)) => PatternShape::Suffix(suffix.to_owned()),
            _ => return Err(PatternError::UnsupportedWildcard),
        };
        Ok(Self(shape))
    }

    fn resolve(&self, formatter: &dyn EcosystemFormatter) -> ResolvedPattern {
        let normalize = |literal: &str| {
            formatter
                .normalize_package_name(&PackageName::new(literal))
                .into_string()
        };
        ResolvedPattern(match &self.0 {
            PatternShape::Exact(s) => PatternShape::Exact(normalize(s)),
            PatternShape::Prefix(s) => PatternShape::Prefix(normalize(s)),
            PatternShape::Suffix(s) => PatternShape::Suffix(normalize(s)),
        })
    }
}

impl TryFrom<String> for PackagePattern {
    type Error = PatternError;

    fn try_from(raw: String) -> Result<Self, Self::Error> {
        Self::parse(&raw)
    }
}

/// A [`PackagePattern`] whose literal parts went through one ecosystem's name normalization.
#[derive(Debug, Clone)]
struct ResolvedPattern(PatternShape);

impl ResolvedPattern {
    fn matches(&self, name: &NormalizedName) -> bool {
        let name = name.as_str();
        match &self.0 {
            PatternShape::Exact(s) => name == s,
            PatternShape::Prefix(s) => name.starts_with(s.as_str()),
            PatternShape::Suffix(s) => name.ends_with(s.as_str()),
        }
    }
}

/// Why a suppression rule was rejected.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum RuleError {
    /// `kinds` was an empty list.
    #[error("suppression rule must list at least one kind")]
    NoKinds,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawRule {
    package: PackagePattern,
    kinds: Vec<SuppressionKind>,
}

/// One user-declared exemption: a package pattern and the kinds it silences.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::{SuppressionKind, SuppressionRule};
///
/// let rule: SuppressionRule =
///     serde_json::from_str(r#"{"package":"request","kinds":["deprecated"]}"#).unwrap();
/// assert!(rule.kinds().contains(SuppressionKind::Deprecated));
/// assert!(serde_json::from_str::<SuppressionRule>(r#"{"package":"x","kinds":[]}"#).is_err());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(try_from = "RawRule")]
pub struct SuppressionRule {
    package: PackagePattern,
    kinds: SuppressedKinds,
}

impl SuppressionRule {
    /// The kinds this rule silences; never empty.
    #[must_use]
    pub const fn kinds(&self) -> SuppressedKinds {
        self.kinds
    }
}

impl TryFrom<RawRule> for SuppressionRule {
    type Error = RuleError;

    fn try_from(raw: RawRule) -> Result<Self, Self::Error> {
        if raw.kinds.is_empty() {
            return Err(RuleError::NoKinds);
        }
        let kinds = raw
            .kinds
            .into_iter()
            .fold(SuppressedKinds::default(), SuppressedKinds::with);
        Ok(Self {
            package: raw.package,
            kinds,
        })
    }
}

/// The compiled `diagnostics.suppress` rule list, in declaration order.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::SuppressionSet;
///
/// let set: SuppressionSet =
///     serde_json::from_str(r#"[{"package":"@types/*","kinds":["outdated"]}]"#).unwrap();
/// assert!(!set.is_empty());
/// assert!(SuppressionSet::default().is_empty());
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(transparent)]
pub struct SuppressionSet {
    rules: Vec<SuppressionRule>,
    #[serde(skip)]
    ignored: Vec<PackagePattern>,
}

impl SuppressionSet {
    /// Builds a set from already-validated rules.
    #[must_use]
    pub const fn new(rules: Vec<SuppressionRule>) -> Self {
        Self {
            rules,
            ignored: Vec::new(),
        }
    }

    /// This set plus whole-package ignore patterns (`diagnostics.ignore`).
    #[must_use]
    pub fn with_ignored(mut self, ignored: Vec<PackagePattern>) -> Self {
        self.ignored = ignored;
        self
    }

    /// Whether neither a rule nor an ignore pattern is configured.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.rules.is_empty() && self.ignored.is_empty()
    }

    /// Normalizes every pattern through `formatter` once, for repeated per-dependency lookups.
    #[must_use]
    pub fn resolve(&self, formatter: &dyn EcosystemFormatter) -> ResolvedSuppression {
        ResolvedSuppression {
            rules: self
                .rules
                .iter()
                .map(|rule| (rule.package.resolve(formatter), rule.kinds))
                .collect(),
            ignored: self
                .ignored
                .iter()
                .map(|pattern| pattern.resolve(formatter))
                .collect(),
        }
    }
}

/// The suppression that applies to one package: a kind subset or the whole package.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PackageSuppression {
    /// Only these kinds are hidden.
    Kinds(SuppressedKinds),
    /// Every suppressible kind is hidden (`diagnostics.ignore`).
    Ignored,
}

impl PackageSuppression {
    /// The suppressible kinds this suppression hides; `Ignored` hides all of them.
    #[must_use]
    pub const fn kinds(self) -> SuppressedKinds {
        match self {
            Self::Kinds(kinds) => kinds,
            Self::Ignored => SuppressedKinds::ALL,
        }
    }

    /// Whether the package's `Outdated` diagnostics and hints are hidden.
    #[must_use]
    pub const fn hides_outdated(self) -> bool {
        self.kinds().contains(SuppressionKind::Outdated)
    }
}

/// A [`SuppressionSet`] normalized for one ecosystem.
#[derive(Debug, Clone, Default)]
pub struct ResolvedSuppression {
    rules: Vec<(ResolvedPattern, SuppressedKinds)>,
    ignored: Vec<ResolvedPattern>,
}

impl ResolvedSuppression {
    /// The suppression for `name`, with a whole-package ignore taking precedence.
    #[must_use]
    pub fn for_package(&self, name: &NormalizedName) -> PackageSuppression {
        if self.ignored.iter().any(|pattern| pattern.matches(name)) {
            PackageSuppression::Ignored
        } else {
            PackageSuppression::Kinds(self.kinds_for(name))
        }
    }

    /// The union of the kinds of every rule matching `name`.
    #[must_use]
    pub fn kinds_for(&self, name: &NormalizedName) -> SuppressedKinds {
        self.rules
            .iter()
            .filter(|(pattern, _)| pattern.matches(name))
            .fold(SuppressedKinds::default(), |acc, (_, kinds)| {
                acc.union(*kinds)
            })
    }
}

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

    const FORMATTER: StubFormatter = StubFormatter::new().with_package_url_prefix("");

    fn set(json: &str) -> SuppressionSet {
        serde_json::from_str(json).unwrap()
    }

    fn kinds(set: &SuppressionSet, name: &str) -> SuppressedKinds {
        set.resolve(&FORMATTER)
            .kinds_for(&NormalizedName::for_test(name))
    }

    #[test]
    fn every_kind_is_listed() {
        let listed = |kind: SuppressionKind| match kind {
            SuppressionKind::Deprecated
            | SuppressionKind::Outdated
            | SuppressionKind::Yanked
            | SuppressionKind::License => SuppressionKind::EVERY.contains(&kind),
        };
        assert!(SuppressionKind::EVERY.into_iter().all(listed));
        assert!(
            SuppressionKind::EVERY
                .into_iter()
                .all(|k| SuppressedKinds::ALL.contains(k))
        );
    }

    #[test]
    fn pattern_shapes_are_validated() {
        assert_eq!(PackagePattern::parse(""), Err(PatternError::Empty));
        assert_eq!(PackagePattern::parse("*"), Err(PatternError::BareWildcard));
        assert_eq!(
            PackagePattern::parse("a*b"),
            Err(PatternError::UnsupportedWildcard)
        );
        assert_eq!(
            PackagePattern::parse("**"),
            Err(PatternError::UnsupportedWildcard)
        );
        assert_eq!(
            PackagePattern::parse("*a*"),
            Err(PatternError::UnsupportedWildcard)
        );
        assert!(PackagePattern::parse("*-sys").is_ok());
    }

    #[test]
    fn exact_prefix_and_suffix_match() {
        let s = set(r#"[
                {"package":"request","kinds":["deprecated"]},
                {"package":"@types/*","kinds":["outdated"]},
                {"package":"*-sys","kinds":["yanked"]}
            ]"#);
        assert!(kinds(&s, "request").contains(SuppressionKind::Deprecated));
        assert!(kinds(&s, "requests").is_empty());
        assert!(kinds(&s, "@types/node").contains(SuppressionKind::Outdated));
        assert!(kinds(&s, "types-extra").is_empty());
        assert!(kinds(&s, "openssl-sys").contains(SuppressionKind::Yanked));
    }

    #[test]
    fn overlapping_rules_union_their_kinds() {
        let s = set(r#"[
                {"package":"left-pad","kinds":["outdated"]},
                {"package":"left-*","kinds":["yanked"]}
            ]"#);
        let k = kinds(&s, "left-pad");
        assert!(k.contains(SuppressionKind::Outdated));
        assert!(k.contains(SuppressionKind::Yanked));
        assert!(!k.contains(SuppressionKind::Deprecated));
    }

    #[test]
    fn invalid_rules_are_rejected() {
        for bad in [
            r#"[{"package":"x","kinds":[]}]"#,
            r#"[{"package":"x","kinds":["vulnerability"]}]"#,
            r#"[{"package":"*","kinds":["outdated"]}]"#,
            r#"[{"package":"x","kinds":["outdated"],"extra":1}]"#,
            r#"[{"kinds":["outdated"]}]"#,
        ] {
            assert!(
                serde_json::from_str::<SuppressionSet>(bad).is_err(),
                "{bad}"
            );
        }
    }

    #[test]
    fn hides_maps_every_suppressible_kind_and_nothing_else() {
        let all = [
            SuppressionKind::Deprecated,
            SuppressionKind::Outdated,
            SuppressionKind::Yanked,
            SuppressionKind::License,
        ]
        .into_iter()
        .fold(SuppressedKinds::default(), SuppressedKinds::with);
        for (kind, hidden) in [
            (DiagnosticKind::Outdated, true),
            (DiagnosticKind::Yanked, true),
            (DiagnosticKind::LicensePolicy, true),
            (DiagnosticKind::Deprecated, true),
            (DiagnosticKind::FlaggedLatest, false),
            (DiagnosticKind::UnverifiedLatest, false),
            (DiagnosticKind::AdvisoryOverflow, false),
            (DiagnosticKind::AdvisoryExempted, false),
            (DiagnosticKind::Unsatisfiable, false),
            (DiagnosticKind::Typosquat, false),
            (DiagnosticKind::Notice, false),
        ] {
            assert_eq!(all.hides(&kind, None), hidden, "{kind:?}");
            assert!(!SuppressedKinds::default().hides(&kind, None), "{kind:?}");
        }
    }
}