~ knotless Search/
↑↓ move↵ open⇧↵ all results

johnandersen777.bsky.social/vuln-notif

0
0
main
466 lines · 14.8 KB Raw History
//! 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)
}