249 lines
8.9 KiB
Rust
249 lines
8.9 KiB
Rust
//! Comparing versions as vendors write them, and version ranges in the purl
|
|
//! specification's `vers` notation (`vers:intdot/>=3.1.6|<3.1.7`), as CSAF
|
|
//! advisories state which product versions are affected (#515).
|
|
|
|
use std::cmp::Ordering;
|
|
|
|
/// Compare two dotted versions (`4.17.0.0` vs `4.9.0.0`); a missing
|
|
/// component counts as 0.
|
|
///
|
|
/// A leading `r`/`v` is ignored (FatFs `r0.14b`, `V10.4.6`), and a component
|
|
/// is its number then any letter suffix, so `14` < `14b` < `15`.
|
|
pub fn cmp_dotted(a: &str, b: &str) -> Ordering {
|
|
let parts = |v: &str| -> Vec<(u64, String)> {
|
|
v.trim()
|
|
.trim_start_matches(['r', 'R', 'v', 'V'])
|
|
.split('.')
|
|
.map(|part| {
|
|
let digits =
|
|
part.len() - part.trim_start_matches(|c: char| c.is_ascii_digit()).len();
|
|
(
|
|
part[..digits].parse().unwrap_or(0),
|
|
part[digits..].to_ascii_lowercase(),
|
|
)
|
|
})
|
|
.collect()
|
|
};
|
|
let (pa, pb) = (parts(a), parts(b));
|
|
let zero = (0, String::new());
|
|
for i in 0..pa.len().max(pb.len()) {
|
|
match pa.get(i).unwrap_or(&zero).cmp(pb.get(i).unwrap_or(&zero)) {
|
|
Ordering::Equal => continue,
|
|
other => return other,
|
|
}
|
|
}
|
|
Ordering::Equal
|
|
}
|
|
|
|
/// A comparator of a `vers` constraint.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
enum Comparator {
|
|
Eq,
|
|
Ne,
|
|
Lt,
|
|
Le,
|
|
Gt,
|
|
Ge,
|
|
}
|
|
|
|
/// A version range in `vers` notation. Versions compare as
|
|
/// [`cmp_dotted`] does, whatever the scheme (`generic`, `intdot`, `semver`):
|
|
/// vendor advisories use dotted numbers.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct Vers {
|
|
/// Every version (`vers:all/*`, or a `*` constraint).
|
|
all: bool,
|
|
/// The constraints in their order.
|
|
constraints: Vec<(Comparator, String)>,
|
|
}
|
|
|
|
impl Vers {
|
|
/// Parse `text`; `None` for anything that is not a range with at least
|
|
/// one constraint.
|
|
///
|
|
/// Vendors do not always write `vers` as specified, so two forms CERT@VDE
|
|
/// advisories use are read too: constraints without the `vers:<scheme>/`
|
|
/// prefix (`<4.17.0.0`), and a range written `4.15.0.0<4.21.0.0` (for
|
|
/// `>=4.15.0.0|<4.21.0.0`). A plain version without a comparator is not
|
|
/// a range.
|
|
pub fn parse(text: &str) -> Option<Self> {
|
|
let text = text.trim();
|
|
let constraints = match text.strip_prefix("vers:") {
|
|
Some(rest) => rest.split_once('/')?.1,
|
|
None if text.contains(['<', '>', '=', '|', '*']) => text,
|
|
None => return None,
|
|
};
|
|
// `A<B` / `A<=B`: from A (inclusive) to below / up to B.
|
|
let mut raws: Vec<String> = Vec::new();
|
|
for raw in constraints
|
|
.split('|')
|
|
.map(str::trim)
|
|
.filter(|c| !c.is_empty())
|
|
{
|
|
let lead = raw
|
|
.chars()
|
|
.next()
|
|
.is_some_and(|c| c.is_ascii_alphanumeric());
|
|
match raw.find('<').filter(|_| lead) {
|
|
Some(at) => {
|
|
raws.push(format!(">={}", &raw[..at]));
|
|
raws.push(raw[at..].to_string());
|
|
}
|
|
None => raws.push(raw.to_string()),
|
|
}
|
|
}
|
|
let mut all = false;
|
|
let mut parsed = Vec::new();
|
|
for raw in raws.iter().map(|r| r.trim()) {
|
|
if raw == "*" {
|
|
all = true;
|
|
continue;
|
|
}
|
|
let (comparator, version) = [
|
|
(">=", Comparator::Ge),
|
|
("<=", Comparator::Le),
|
|
("!=", Comparator::Ne),
|
|
(">", Comparator::Gt),
|
|
("<", Comparator::Lt),
|
|
("=", Comparator::Eq),
|
|
]
|
|
.iter()
|
|
.find_map(|(prefix, c)| raw.strip_prefix(prefix).map(|v| (*c, v)))
|
|
.unwrap_or((Comparator::Eq, raw));
|
|
let version = version.trim();
|
|
if version.is_empty() {
|
|
return None;
|
|
}
|
|
parsed.push((comparator, version.to_string()));
|
|
}
|
|
(all || !parsed.is_empty()).then_some(Self {
|
|
all,
|
|
constraints: parsed,
|
|
})
|
|
}
|
|
|
|
/// Whether `version` is in the range.
|
|
///
|
|
/// Equality constraints decide first (`!=` excludes, `=` includes); the
|
|
/// bounds, sorted by version, form intervals: a lower bound (`>`, `>=`)
|
|
/// opens one, the next upper bound (`<`, `<=`) closes it, an upper bound
|
|
/// without a lower one is open below, a lower one without an upper one
|
|
/// open above.
|
|
pub fn contains(&self, version: &str) -> bool {
|
|
let eq = |v: &str| cmp_dotted(version, v) == Ordering::Equal;
|
|
if self
|
|
.constraints
|
|
.iter()
|
|
.any(|(c, v)| *c == Comparator::Ne && eq(v))
|
|
{
|
|
return false;
|
|
}
|
|
if self.all
|
|
|| self
|
|
.constraints
|
|
.iter()
|
|
.any(|(c, v)| *c == Comparator::Eq && eq(v))
|
|
{
|
|
return true;
|
|
}
|
|
let mut bounds: Vec<&(Comparator, String)> = self
|
|
.constraints
|
|
.iter()
|
|
.filter(|(c, _)| !matches!(c, Comparator::Eq | Comparator::Ne))
|
|
.collect();
|
|
bounds.sort_by(|a, b| cmp_dotted(&a.1, &b.1));
|
|
let above = |c: Comparator, v: &str| match c {
|
|
Comparator::Gt => cmp_dotted(version, v) == Ordering::Greater,
|
|
_ => cmp_dotted(version, v) != Ordering::Less,
|
|
};
|
|
let below = |c: Comparator, v: &str| match c {
|
|
Comparator::Lt => cmp_dotted(version, v) == Ordering::Less,
|
|
_ => cmp_dotted(version, v) != Ordering::Greater,
|
|
};
|
|
let mut lower: Option<&(Comparator, String)> = None;
|
|
let mut open_below = true;
|
|
for bound in bounds {
|
|
match bound.0 {
|
|
Comparator::Gt | Comparator::Ge => {
|
|
lower = Some(bound);
|
|
open_below = false;
|
|
}
|
|
_ => {
|
|
let in_lower = lower.is_none_or(|(c, v)| above(*c, v));
|
|
if (open_below || lower.is_some()) && in_lower && below(bound.0, &bound.1) {
|
|
return true;
|
|
}
|
|
lower = None;
|
|
open_below = false;
|
|
}
|
|
}
|
|
}
|
|
lower.is_some_and(|(c, v)| above(*c, v))
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::cmp::Ordering::{Equal, Greater, Less};
|
|
|
|
fn vers(text: &str) -> Vers {
|
|
Vers::parse(text).unwrap_or_else(|| Vers {
|
|
all: false,
|
|
constraints: Vec::new(),
|
|
})
|
|
}
|
|
|
|
#[test]
|
|
fn dotted_versions_compare_by_number() {
|
|
assert_eq!(cmp_dotted("4.17.0.0", "4.9.0.0"), Greater);
|
|
assert_eq!(cmp_dotted("4.9.0.0", "4.17.0.0"), Less);
|
|
assert_eq!(cmp_dotted("3.5.18.0", "3.5.18.0"), Equal);
|
|
assert_eq!(cmp_dotted("4.2", "4.2.0.0"), Equal);
|
|
assert_eq!(cmp_dotted("r0.14b", "r0.16"), Less);
|
|
assert_eq!(cmp_dotted("V10.4.6", "10.4.6"), Equal);
|
|
}
|
|
|
|
#[test]
|
|
fn ranges_as_vendor_advisories_write_them() {
|
|
// CODESYS: a closed range.
|
|
let codesys = vers("vers:generic/>=3.0.0.0|<3.5.22.40");
|
|
assert!(codesys.contains("3.5.16.0"));
|
|
assert!(codesys.contains("3.0.0.0"));
|
|
assert!(!codesys.contains("3.5.22.40"));
|
|
assert!(!codesys.contains("4.17.0.0"));
|
|
// Siemens: open above.
|
|
let siemens = vers("vers:intdot/>=3.1.6");
|
|
assert!(siemens.contains("3.2"));
|
|
assert!(!siemens.contains("3.1.5"));
|
|
// CISA: open below.
|
|
let cisa = vers("vers:intdot/<=1.5");
|
|
assert!(cisa.contains("1.5"));
|
|
assert!(cisa.contains("0.9"));
|
|
assert!(!cisa.contains("1.6"));
|
|
// As CERT@VDE's vendors also write them.
|
|
let sloppy = vers("vers:generic/4.15.0.0<4.21.0.0");
|
|
assert!(sloppy.contains("4.16.0.0"));
|
|
assert!(!sloppy.contains("4.14.0.0") && !sloppy.contains("4.21.0.0"));
|
|
assert!(vers("4.16.0.0<4.17.0.0").contains("4.16.5.0"));
|
|
assert!(vers("<4.17.0.0").contains("3.5.16.0"));
|
|
assert!(!vers("<4.17.0.0").contains("4.17.0.0"));
|
|
// Two intervals, an exclusion, a single version, everything.
|
|
let two = vers("vers:generic/>=1.0|<1.4|>=2.0|<2.2");
|
|
assert!(two.contains("1.2") && two.contains("2.1"));
|
|
assert!(!two.contains("1.5") && !two.contains("2.2"));
|
|
assert!(!vers("vers:generic/>=1.0|!=1.3|<2.0").contains("1.3"));
|
|
assert!(vers("vers:generic/1.3.2").contains("1.3.2"));
|
|
assert!(!vers("vers:generic/1.3.2").contains("1.3.3"));
|
|
assert!(vers("vers:all/*").contains("9.9"));
|
|
}
|
|
|
|
#[test]
|
|
fn what_is_not_a_range_is_refused() {
|
|
assert_eq!(Vers::parse("3.5.16.0"), None);
|
|
assert_eq!(Vers::parse("4.15.0.0<"), None);
|
|
assert_eq!(Vers::parse("vers:generic/"), None);
|
|
assert_eq!(Vers::parse("vers:generic/>="), None);
|
|
}
|
|
}
|