Skip to main content

libtea_core/
vers.rs

1//! `vers` version ranges (the version-range notation CLE and PURL use),
2//! parsed in full and evaluated for SemVer versions only.
3//!
4//! **Experimental:** may change in a 0.x minor release.
5//!
6//! [`VersRange::parse`] checks the syntax of any `vers:<type>/<constraints>`
7//! string. [`VersRange::contains_semver`] then evaluates it when its type
8//! compares versions as SemVer 2.0 ([`VersRange::is_semver_type`]): `semver`,
9//! and `npm`, whose registered `vers` type uses node-semver versions. Every
10//! other type is reported as unsupported, never guessed.
11//!
12//! The rules are from the `vers` specification, release `v1.2.1` of
13//! <https://github.com/package-url/vers-spec> (`docs/specification/`):
14//! constraints are sorted by version, each version occurs once, `*` stands
15//! alone, and outside `!=` the comparators alternate between lower and upper
16//! bounds. A range that breaks these rules is an error, not corrected.
17
18use std::cmp::Ordering;
19
20use thiserror::Error;
21
22/// Inputs longer than this are rejected with [`VersError::TooLong`].
23pub const MAX_VERS_BYTES: usize = 4096;
24
25/// Why a string is not a valid `vers` range, or could not be evaluated.
26///
27/// **Experimental:** may change in a 0.x minor release.
28#[derive(Debug, Clone, PartialEq, Eq, Error)]
29#[non_exhaustive]
30pub enum VersError {
31    /// Longer than [`MAX_VERS_BYTES`].
32    #[error("vers range is longer than {MAX_VERS_BYTES} bytes")]
33    TooLong,
34    /// The scheme is missing or is not lowercase `vers`.
35    #[error("vers range must start with `vers:`")]
36    Scheme,
37    /// The type is missing, not lowercase, does not start with a letter, or
38    /// has characters other than ASCII letters, digits, `.` and `-`.
39    #[error("vers type is missing or invalid")]
40    Type,
41    /// Nothing after `vers:<type>/`.
42    #[error("vers constraints are empty")]
43    Empty,
44    /// Literal ASCII whitespace anywhere in the string, or a decoded version
45    /// with whitespace other than a space.
46    #[error("vers range contains whitespace")]
47    Whitespace,
48    /// A leading, trailing or repeated `|`.
49    #[error("vers constraints have an empty segment")]
50    EmptyConstraint,
51    /// A constraint starts with `=`; equality is a bare version.
52    #[error("vers constraint starts with `=`")]
53    LeadingEquals,
54    /// A comparator with no version after it.
55    #[error("vers constraint has no version")]
56    EmptyVersion,
57    /// `*` together with other constraints, or `*` followed by a version.
58    #[error("vers `*` must stand alone")]
59    Asterisk,
60    /// A `%` not followed by two hex digits, decoded bytes that are not UTF-8,
61    /// or an unencoded character the specification reserves.
62    #[error("vers version has an invalid percent-encoding")]
63    Encoding,
64    /// The type does not compare versions as SemVer.
65    #[error("vers type is not evaluated as SemVer")]
66    UnsupportedType,
67    /// A constraint version is not a SemVer 2.0 version.
68    #[error("vers version is not a SemVer version")]
69    NotSemver,
70    /// Constraints are not sorted by version, or a version occurs twice.
71    #[error("vers constraints are not sorted by version or repeat one")]
72    Order,
73    /// Comparators do not alternate between lower and upper bounds.
74    #[error("vers constraints have an invalid comparator sequence")]
75    Sequence,
76}
77
78/// The comparator of one constraint.
79///
80/// **Experimental:** may change in a 0.x minor release.
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
82#[non_exhaustive]
83pub enum Comparator {
84    /// A bare version: equal to it.
85    Equal,
86    /// `!=`: excluded.
87    NotEqual,
88    /// `<`.
89    Less,
90    /// `<=`.
91    LessOrEqual,
92    /// `>`.
93    Greater,
94    /// `>=`.
95    GreaterOrEqual,
96}
97
98impl Comparator {
99    /// The comparator as written in a range (empty for [`Self::Equal`]).
100    #[must_use]
101    pub fn as_str(self) -> &'static str {
102        match self {
103            Self::Equal => "",
104            Self::NotEqual => "!=",
105            Self::Less => "<",
106            Self::LessOrEqual => "<=",
107            Self::Greater => ">",
108            Self::GreaterOrEqual => ">=",
109        }
110    }
111
112    fn is_upper(self) -> bool {
113        matches!(self, Self::Less | Self::LessOrEqual)
114    }
115
116    fn is_lower(self) -> bool {
117        matches!(self, Self::Greater | Self::GreaterOrEqual)
118    }
119}
120
121/// One constraint: a comparator and a percent-decoded version.
122///
123/// **Experimental:** may change in a 0.x minor release.
124#[derive(Debug, Clone, PartialEq, Eq, Hash)]
125pub struct Constraint {
126    comparator: Comparator,
127    version: String,
128}
129
130impl Constraint {
131    /// The comparator.
132    #[must_use]
133    pub fn comparator(&self) -> Comparator {
134        self.comparator
135    }
136
137    /// The version, percent-decoded once.
138    #[must_use]
139    pub fn version(&self) -> &str {
140        &self.version
141    }
142}
143
144/// A parsed `vers` range.
145///
146/// **Experimental:** may change in a 0.x minor release.
147///
148/// ```
149/// use libtea_core::vers::VersRange;
150///
151/// let range = VersRange::parse("vers:npm/>=1.0.0|!=1.2.0|<2.0.0").unwrap();
152/// let v = |s: &str| semver::Version::parse(s).unwrap();
153/// assert_eq!(range.contains_semver(&v("1.5.0")), Ok(true));
154/// assert_eq!(range.contains_semver(&v("1.2.0")), Ok(false));
155/// assert_eq!(range.contains_semver(&v("2.0.0")), Ok(false));
156/// assert_eq!(range.contains_semver(&v("2.0.0-rc.1")), Ok(true));
157/// ```
158#[derive(Debug, Clone, PartialEq, Eq, Hash)]
159pub struct VersRange {
160    version_type: String,
161    any: bool,
162    constraints: Vec<Constraint>,
163}
164
165impl VersRange {
166    /// Parse `vers:<type>/<constraints>` as the specification's
167    /// "How to parse" describes. Ordering and comparator rules depend on how
168    /// the type compares versions, so they are checked by
169    /// [`Self::contains_semver`], not here.
170    ///
171    /// # Errors
172    ///
173    /// Returns [`VersError`] for a missing or wrong scheme or type, empty
174    /// constraints or constraint segments, whitespace, a leading `=`, an empty
175    /// version, a misplaced `*`, invalid percent-encoding, or a string longer
176    /// than [`MAX_VERS_BYTES`].
177    pub fn parse(text: &str) -> Result<Self, VersError> {
178        if text.len() > MAX_VERS_BYTES {
179            return Err(VersError::TooLong);
180        }
181        if text.bytes().any(|b| b.is_ascii_whitespace()) {
182            return Err(VersError::Whitespace);
183        }
184        let (scheme, specifier) = text.split_once(':').ok_or(VersError::Scheme)?;
185        if scheme != "vers" {
186            return Err(VersError::Scheme);
187        }
188        let (version_type, constraints) = specifier.split_once('/').ok_or(VersError::Type)?;
189        if !valid_type(version_type) {
190            return Err(VersError::Type);
191        }
192        if constraints.is_empty() {
193            return Err(VersError::Empty);
194        }
195        if constraints == "*" {
196            return Ok(Self {
197                version_type: version_type.to_owned(),
198                any: true,
199                constraints: Vec::new(),
200            });
201        }
202        let mut parsed = Vec::new();
203        for segment in constraints.split('|') {
204            if segment.is_empty() {
205                return Err(VersError::EmptyConstraint);
206            }
207            if segment.contains('*') {
208                return Err(VersError::Asterisk);
209            }
210            let (comparator, rest) = split_comparator(segment)?;
211            if rest.is_empty() {
212                return Err(VersError::EmptyVersion);
213            }
214            if rest.contains(['<', '>', '=', '!']) {
215                return Err(VersError::Encoding);
216            }
217            let version = percent_decode(rest)?;
218            // Only an encoded space is allowed; `%09` is still a tab.
219            if version
220                .bytes()
221                .any(|b| b.is_ascii_whitespace() && b != b' ')
222            {
223                return Err(VersError::Whitespace);
224            }
225            parsed.push(Constraint {
226                comparator,
227                version,
228            });
229        }
230        Ok(Self {
231            version_type: version_type.to_owned(),
232            any: false,
233            constraints: parsed,
234        })
235    }
236
237    /// The `vers` type, such as `npm` or `semver`.
238    #[must_use]
239    pub fn version_type(&self) -> &str {
240        &self.version_type
241    }
242
243    /// Whether the range is `*` (every version).
244    #[must_use]
245    pub fn is_any(&self) -> bool {
246        self.any
247    }
248
249    /// The constraints in the order written. Empty for `*`.
250    #[must_use]
251    pub fn constraints(&self) -> &[Constraint] {
252        &self.constraints
253    }
254
255    /// Whether this type's versions are compared as SemVer 2.0 here:
256    /// `semver`, and `npm` (node-semver versions).
257    #[must_use]
258    pub fn is_semver_type(&self) -> bool {
259        matches!(self.version_type.as_str(), "semver" | "npm")
260    }
261
262    /// Whether `version` is in the range, comparing as SemVer 2.0 (build
263    /// metadata ignored, pre-releases ordered before their release).
264    ///
265    /// The range is validated first: constraint versions must be SemVer,
266    /// sorted, unique, and in a valid comparator sequence.
267    ///
268    /// # Errors
269    ///
270    /// [`VersError::UnsupportedType`] when [`Self::is_semver_type`] is false,
271    /// [`VersError::NotSemver`] for a constraint version that does not parse,
272    /// and [`VersError::Order`] or [`VersError::Sequence`] for a range the
273    /// specification calls invalid.
274    pub fn contains_semver(&self, version: &semver::Version) -> Result<bool, VersError> {
275        if !self.is_semver_type() {
276            return Err(VersError::UnsupportedType);
277        }
278        if self.any {
279            return Ok(true);
280        }
281        let mut bounds = Vec::with_capacity(self.constraints.len());
282        for constraint in &self.constraints {
283            let parsed =
284                semver::Version::parse(&constraint.version).map_err(|_| VersError::NotSemver)?;
285            bounds.push((constraint.comparator, parsed));
286        }
287        validate(&bounds)?;
288
289        // Equality first: an inclusive constraint on the version includes it,
290        // a `!=` on it excludes it. Versions are unique, so these never clash.
291        for (comparator, bound) in &bounds {
292            if precedence(version, bound) == Ordering::Equal {
293                // `!=` excludes it; `<` and `>` do not include their own version.
294                return Ok(!matches!(
295                    comparator,
296                    Comparator::NotEqual | Comparator::Less | Comparator::Greater
297                ));
298            }
299        }
300        // Then the intervals the remaining bounds describe, in version order.
301        let ranges: Vec<_> = bounds
302            .iter()
303            .filter(|(comparator, _)| comparator.is_lower() || comparator.is_upper())
304            .collect();
305        for (index, (comparator, bound)) in ranges.iter().enumerate() {
306            let below = precedence(version, bound) == Ordering::Less;
307            if comparator.is_upper() {
308                // An upper bound opens the range when it is the first bound,
309                // or closes the interval the previous lower bound opened.
310                let opened = match index.checked_sub(1).map(|i| ranges[i]) {
311                    None => true,
312                    Some((previous, lower)) => {
313                        previous.is_lower() && precedence(version, lower) == Ordering::Greater
314                    }
315                };
316                if opened && below {
317                    return Ok(true);
318                }
319            } else if index + 1 == ranges.len() && precedence(version, bound) == Ordering::Greater {
320                // A lower bound with nothing after it is open to the top.
321                return Ok(true);
322            }
323        }
324        Ok(false)
325    }
326}
327
328/// SemVer 2.0 precedence: build metadata does not count.
329fn precedence(a: &semver::Version, b: &semver::Version) -> Ordering {
330    (a.major, a.minor, a.patch, &a.pre).cmp(&(b.major, b.minor, b.patch, &b.pre))
331}
332
333/// Specification section 5.4: sorted and unique, then the comparator rules
334/// for contiguous constraints.
335fn validate(bounds: &[(Comparator, semver::Version)]) -> Result<(), VersError> {
336    if bounds
337        .windows(2)
338        .any(|pair| precedence(&pair[0].1, &pair[1].1) != Ordering::Less)
339    {
340        return Err(VersError::Order);
341    }
342    let without_unequal: Vec<_> = bounds
343        .iter()
344        .map(|(comparator, _)| *comparator)
345        .filter(|comparator| *comparator != Comparator::NotEqual)
346        .collect();
347    // A bare version is followed only by a bare version or a lower bound, and
348    // a lower bound is never followed by a bare version (it would be inside
349    // the interval already, which "How to parse" calls redundant).
350    for pair in without_unequal.windows(2) {
351        if (pair[0] == Comparator::Equal && pair[1].is_upper())
352            || (pair[0].is_lower() && pair[1] == Comparator::Equal)
353        {
354            return Err(VersError::Sequence);
355        }
356    }
357    let bounds_only: Vec<_> = without_unequal
358        .iter()
359        .filter(|comparator| **comparator != Comparator::Equal)
360        .collect();
361    for pair in bounds_only.windows(2) {
362        if pair[0].is_upper() == pair[1].is_upper() {
363            return Err(VersError::Sequence);
364        }
365    }
366    Ok(())
367}
368
369fn split_comparator(segment: &str) -> Result<(Comparator, &str), VersError> {
370    for (prefix, comparator) in [
371        (">=", Comparator::GreaterOrEqual),
372        ("<=", Comparator::LessOrEqual),
373        ("!=", Comparator::NotEqual),
374        ("<", Comparator::Less),
375        (">", Comparator::Greater),
376    ] {
377        if let Some(rest) = segment.strip_prefix(prefix) {
378            return Ok((comparator, rest));
379        }
380    }
381    if segment.starts_with('=') {
382        return Err(VersError::LeadingEquals);
383    }
384    Ok((Comparator::Equal, segment))
385}
386
387/// Section 5.3.2: lowercase ASCII letters, digits, `.` and `-`, starting with a letter.
388fn valid_type(version_type: &str) -> bool {
389    let mut chars = version_type.chars();
390    chars.next().is_some_and(|c| c.is_ascii_lowercase())
391        && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '-'))
392}
393
394fn percent_decode(text: &str) -> Result<String, VersError> {
395    let bytes = text.as_bytes();
396    let mut out = Vec::with_capacity(bytes.len());
397    let mut index = 0;
398    while index < bytes.len() {
399        if bytes[index] == b'%' {
400            let digit = |offset: usize| {
401                bytes
402                    .get(index + offset)
403                    .and_then(|b| char::from(*b).to_digit(16))
404            };
405            let (Some(high), Some(low)) = (digit(1), digit(2)) else {
406                return Err(VersError::Encoding);
407            };
408            out.push((high * 16 + low) as u8);
409            index += 3;
410        } else {
411            out.push(bytes[index]);
412            index += 1;
413        }
414    }
415    String::from_utf8(out).map_err(|_| VersError::Encoding)
416}
417
418#[cfg(test)]
419mod tests {
420    use super::*;
421
422    fn v(text: &str) -> semver::Version {
423        semver::Version::parse(text).unwrap()
424    }
425
426    fn contains(range: &str, version: &str) -> bool {
427        VersRange::parse(range)
428            .unwrap()
429            .contains_semver(&v(version))
430            .unwrap()
431    }
432
433    #[test]
434    fn single_bounds_and_equality() {
435        assert!(contains("vers:semver/>=1.0.0", "1.0.0"));
436        assert!(contains("vers:semver/>=1.0.0", "9.0.0"));
437        assert!(!contains("vers:semver/>=1.0.0", "0.9.9"));
438        assert!(!contains("vers:semver/>1.0.0", "1.0.0"));
439        assert!(contains("vers:semver/<2.0.0", "0.0.1"));
440        assert!(!contains("vers:semver/<2.0.0", "2.0.0"));
441        assert!(contains("vers:semver/<=2.0.0", "2.0.0"));
442        assert!(contains("vers:semver/1.2.3", "1.2.3"));
443        assert!(!contains("vers:semver/1.2.3", "1.2.4"));
444        assert!(contains("vers:semver/*", "0.0.0"));
445    }
446
447    #[test]
448    fn several_intervals_exclusions_and_points() {
449        let range = "vers:npm/<1.4.1|>=2.0.0|<2.17.2";
450        assert!(contains(range, "1.0.0"));
451        assert!(!contains(range, "1.4.1"));
452        assert!(!contains(range, "1.9.0"));
453        assert!(contains(range, "2.0.0"));
454        assert!(contains(range, "2.17.1"));
455        assert!(!contains(range, "2.17.2"));
456        let gaps = "vers:npm/>=2.2.6|<2.47.0|>2.51.0|<=2.67.0";
457        assert!(!contains(gaps, "2.51.0"));
458        assert!(contains(gaps, "2.60.0"));
459        assert!(contains(gaps, "2.67.0"));
460        assert!(!contains(gaps, "2.68.0"));
461        let points = "vers:semver/1.0.0|1.1.0|>=2.0.0";
462        assert!(contains(points, "1.1.0"));
463        assert!(!contains(points, "1.0.5"));
464        assert!(contains(points, "3.0.0"));
465        let excluded = "vers:semver/>=1.0.0|!=1.5.0|<2.0.0";
466        assert!(!contains(excluded, "1.5.0"));
467        assert!(contains(excluded, "1.5.1"));
468    }
469
470    #[test]
471    fn prerelease_and_build_metadata() {
472        assert!(contains("vers:semver/<1.0.0", "1.0.0-rc.1"));
473        assert!(contains("vers:semver/>=1.0.0-rc.1|<1.0.0", "1.0.0-rc.2"));
474        // Build metadata is not part of precedence.
475        assert!(contains("vers:semver/1.0.0", "1.0.0+build.7"));
476        assert!(contains("vers:semver/1.0.0+a", "1.0.0"));
477    }
478
479    #[test]
480    fn invalid_ranges_are_errors_not_corrected() {
481        let check = |range: &str| {
482            VersRange::parse(range)
483                .and_then(|r| r.contains_semver(&v("1.0.0")))
484                .unwrap_err()
485        };
486        assert_eq!(check("vers:semver/<2.0.0|>=1.0.0"), VersError::Order);
487        assert_eq!(check("vers:semver/>=1.0.0|<1.0.0"), VersError::Order);
488        assert_eq!(check("vers:semver/>=1.0.0|>=2.0.0"), VersError::Sequence);
489        assert_eq!(check("vers:semver/<1.0.0|<2.0.0"), VersError::Sequence);
490        assert_eq!(check("vers:semver/1.0.0|<2.0.0"), VersError::Sequence);
491        assert_eq!(check("vers:semver/>=1.0.0|1.5.0"), VersError::Sequence);
492        assert_eq!(
493            check("vers:semver/>=1.0.0|1.5.0|<2.0.0"),
494            VersError::Sequence
495        );
496        assert_eq!(check("vers:semver/1.0"), VersError::NotSemver);
497        assert_eq!(check("vers:pypi/>=1.0"), VersError::UnsupportedType);
498    }
499
500    #[test]
501    fn syntax_errors() {
502        let cases: &[(&str, VersError)] = &[
503            ("npm/>=1.0.0", VersError::Scheme),
504            ("VERS:npm/1.0.0", VersError::Scheme),
505            ("vers:NPM/1.0.0", VersError::Type),
506            ("vers:1npm/1.0.0", VersError::Type),
507            ("vers:npm", VersError::Type),
508            ("vers:npm/", VersError::Empty),
509            ("vers:npm/>=1.0.0| <2.0.0", VersError::Whitespace),
510            ("vers:npm/|1.0.0", VersError::EmptyConstraint),
511            ("vers:npm/1.0.0|", VersError::EmptyConstraint),
512            ("vers:npm/1.0.0||2.0.0", VersError::EmptyConstraint),
513            ("vers:npm/=1.0.0", VersError::LeadingEquals),
514            ("vers:npm/>=", VersError::EmptyVersion),
515            ("vers:npm/*|1.0.0", VersError::Asterisk),
516            ("vers:npm/>=*", VersError::Asterisk),
517            ("vers:npm/1.0%zz", VersError::Encoding),
518            ("vers:npm/>==1.0.0", VersError::Encoding),
519        ];
520        for (range, error) in cases {
521            assert_eq!(
522                VersRange::parse(range).as_ref().err(),
523                Some(error),
524                "{range}"
525            );
526        }
527    }
528
529    #[test]
530    fn versions_are_decoded_once() {
531        let range = VersRange::parse("vers:generic/1.0%2520a").unwrap();
532        assert_eq!(range.constraints()[0].version(), "1.0%20a");
533        assert_eq!(range.constraints()[0].comparator().as_str(), "");
534    }
535}