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

johnandersen777.bsky.social/vuln-notif

0
0
main
505 lines · 15.7 KB Raw History
//! Deterministic canonical software identity.
//!
//! One observation maps to at most one identity:
//!
//! ```text
//! identity = (class, canonical_vendor, canonical_family)
//! slug     = truncate64(join(canonical_vendor, canonical_family, '-'))
//! ```
//!
//! The CPE `part` is deliberately excluded from the identity key so the same
//! product observed as `a` and `o` (or as `Red Hat Enterprise Linux 8` text
//! and `cpe:2.3:o:redhat:enterprise_linux:8.0`) collapses to one project.
//! Merges are driven only by curated aliases in
//! `data/identity/aliases.json`; there is no fuzzy matching and no dependence
//! on input or batch order.

pub mod aliases;
pub mod cve_refs;
pub mod observe;

use std::collections::{BTreeMap, BTreeSet};

use data_encoding::HEXLOWER;
use serde::{Deserialize, Serialize};
use sha2::{Digest as _, Sha256};

pub use observe::{Cpe, observations_from_cve, parse_cpe};

/// Classification of a canonical identity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum IdentityClass {
    Os,
    App,
    Hardware,
    Firmware,
}

impl IdentityClass {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Os => "os",
            Self::App => "app",
            Self::Hardware => "hardware",
            Self::Firmware => "firmware",
        }
    }
}

/// One observation of a product from an upstream source.
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct ObservedProduct {
    pub source: String,
    pub part: Option<String>,
    pub vendor: String,
    pub product: String,
    pub version: Option<String>,
    pub update: Option<String>,
    pub edition: Option<String>,
    pub target_sw: Option<String>,
    pub target_hw: Option<String>,
    pub ranges: Vec<VersionRange>,
    pub cpes: Vec<String>,
    pub purls: Vec<String>,
}

/// Version range endpoints carried through from NVD CPE matches.
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct VersionRange {
    pub start_including: Option<String>,
    pub start_excluding: Option<String>,
    pub end_including: Option<String>,
    pub end_excluding: Option<String>,
}

/// Canonical project identity plus the optional channel/version reference.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
pub struct CanonicalIdentity {
    pub class: IdentityClass,
    pub canonical_vendor: String,
    pub canonical_family: String,
    pub slug: String,
    pub identity_key: String,
    pub channel: Option<String>,
    pub version: Option<String>,
}

/// Edition/stream tokens that become channel suffixes.
const EDITION_TOKENS: &[&str] = &[
    "eus",
    "aus",
    "tus",
    "sap",
    "els",
    "rt",
    "nfv",
    "av",
    "crb",
    "desktop",
    "workstation",
    "hpc",
];

/// Architecture tokens that become channel suffixes. `x86_64` is the default
/// and is intentionally absent.
const ARCH_TOKENS: &[&str] = &["aarch64", "ppc64le", "ppc64", "s390x"];

/// Lowercase ASCII token: CPE-unescaped, non-alphanumerics collapsed to `-`.
pub fn normalize_token(raw: &str) -> String {
    let mut out = String::with_capacity(raw.len());
    let mut pending_dash = false;
    let mut chars = raw.chars();
    while let Some(ch) = chars.next() {
        let ch = if ch == '\\' {
            chars.next().unwrap_or(ch)
        } else {
            ch
        };
        if ch.is_ascii_alphanumeric() {
            if pending_dash && !out.is_empty() {
                out.push('-');
            }
            pending_dash = false;
            out.push(ch.to_ascii_lowercase());
        } else {
            pending_dash = true;
        }
    }
    out
}

/// Join vendor and family into a slug without repeating a vendor prefix, and
/// truncate at a hyphen boundary to 64 characters.
pub fn canonical_slug(vendor: &str, family: &str) -> String {
    let vendor = normalize_token(vendor);
    let family = normalize_token(family);
    let raw = if vendor.is_empty() || family == vendor || family.starts_with(&format!("{vendor}-"))
    {
        family
    } else {
        format!("{vendor}-{family}")
    };
    truncate64(raw.trim_matches('-'))
}

/// Truncate to at most 64 characters at a hyphen boundary.
pub fn truncate64(input: &str) -> String {
    truncate_at(input, 64)
}

fn truncate_at(input: &str, max: usize) -> String {
    let chars: Vec<char> = input.chars().collect();
    if chars.len() <= max {
        return input.to_owned();
    }
    let mut cut = max;
    if chars.get(max) != Some(&'-')
        && let Some(position) = chars[..max].iter().rposition(|ch| *ch == '-')
        && position > 0
    {
        cut = position;
    }
    chars[..cut]
        .iter()
        .collect::<String>()
        .trim_matches('-')
        .to_owned()
}

/// Split a version into a channel and an optional immutable version reference.
///
/// NVD uses `X` and single-digit `X.0` as major sentinels: those produce only
/// a channel. `X.Y` preserves the full version under channel `X`. Multi-digit
/// `X.0` values (for example RHEL `10.0`, Keycloak `26.0`) are real versions,
/// not sentinels. `ponytail:` single-digit heuristic; extend with a curated
/// sentinel policy if NVD starts emitting multi-digit sentinels.
pub fn split_channel_version(version: &str) -> (Option<String>, Option<String>) {
    let version = version.trim();
    if version.is_empty() {
        return (None, None);
    }
    let parts: Vec<&str> = version.split('.').collect();
    let numeric = parts
        .iter()
        .all(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit()));
    if !numeric {
        return (None, Some(version.to_owned()));
    }
    let major = parts[0].to_owned();
    if parts.len() == 1 {
        return (Some(major), None);
    }
    if parts.len() == 2 && parts[1] == "0" && major.len() == 1 {
        return (Some(major), None);
    }
    (Some(major), Some(version.to_owned()))
}

fn is_absent(token: &str) -> bool {
    token.is_empty() || matches!(token, "n-a" | "any" | "unknown")
}

fn clean_version(raw: &str) -> Option<String> {
    let trimmed = raw.trim();
    if trimmed.is_empty() || is_absent(&normalize_token(trimmed)) {
        None
    } else {
        Some(trimmed.to_owned())
    }
}

fn matches_prefix(product: &str, alias: &str) -> bool {
    product == alias
        || product
            .strip_prefix(alias)
            .is_some_and(|rest| rest.starts_with('-'))
}

/// Find the longest curated alias matching `product`, returning the canonical
/// family and the unconsumed suffix.
fn match_alias(product: &str, table: &aliases::AliasTable) -> Option<(String, String)> {
    let mut best: Option<(&str, &str)> = None;
    for (alias, family) in &table.products {
        if matches_prefix(product, alias) && is_better(alias, best) {
            best = Some((alias, family));
        }
    }
    for family in table.families.keys() {
        if matches_prefix(product, family) && is_better(family, best) {
            best = Some((family, family));
        }
    }
    best.map(|(alias, family)| {
        (
            family.to_owned(),
            product[alias.len()..].trim_start_matches('-').to_owned(),
        )
    })
}

fn is_better(alias: &str, best: Option<(&str, &str)>) -> bool {
    best.is_none_or(|(current, _)| alias.len() > current.len())
}

fn strip_prefix<'a>(product: &'a str, vendor: &str) -> Option<&'a str> {
    product
        .strip_prefix(vendor)
        .and_then(|rest| rest.strip_prefix('-'))
}

/// Split leading numeric tokens into a dotted version; remaining tokens are
/// stream/edition candidates.
fn split_trailing_version(trailing: &str) -> (Option<String>, Vec<String>) {
    let tokens: Vec<&str> = trailing
        .split('-')
        .filter(|token| !token.is_empty())
        .collect();
    let version_end = tokens
        .iter()
        .position(|token| !token.bytes().all(|byte| byte.is_ascii_digit()))
        .unwrap_or(tokens.len());
    let version = if version_end == 0 {
        None
    } else {
        Some(tokens[..version_end].join("."))
    };
    let rest = tokens[version_end..]
        .iter()
        .map(|token| (*token).to_owned())
        .collect();
    (version, rest)
}

fn add_variant(variants: &mut BTreeSet<String>, token: &str) {
    if EDITION_TOKENS.contains(&token) || ARCH_TOKENS.contains(&token) {
        variants.insert(token.to_owned());
    }
}

/// Add every curated edition/arch token found in a normalized value.
fn add_variants_from(variants: &mut BTreeSet<String>, value: &str) {
    let token = normalize_token(value);
    for part in token.split('-').filter(|part| !part.is_empty()) {
        add_variant(variants, part);
    }
}

fn split_for_family(family: &str, version: &str) -> (Option<String>, Option<String>) {
    if family == "ubuntu" && version.contains('.') {
        return (Some(version.replace('.', "-")), Some(version.to_owned()));
    }
    split_channel_version(version)
}

fn identity_class(family: &str, part: Option<&str>, table: &aliases::AliasTable) -> IdentityClass {
    if let Some(class) = table.class_overrides.get(family) {
        return *class;
    }
    match part {
        Some("o") => IdentityClass::Os,
        Some("h") => IdentityClass::Hardware,
        _ => IdentityClass::App,
    }
}

/// Canonicalize one observation. Returns `None` for placeholder identities
/// (`n/a`, `any`, `unknown`, `*`, `-`).
///
/// Collision suffixes are batch-level and applied by [`canonicalize_all`];
/// this function always returns the base slug.
pub fn canonicalize(observed: &ObservedProduct) -> Option<CanonicalIdentity> {
    let table = aliases::aliases();
    let vendor_raw = normalize_token(&observed.vendor);
    let product_raw = normalize_token(&observed.product);
    if is_absent(&vendor_raw) || is_absent(&product_raw) {
        return None;
    }

    let canonical_vendor = table
        .vendors
        .get(&vendor_raw)
        .cloned()
        .unwrap_or_else(|| vendor_raw.clone());
    if is_absent(&canonical_vendor) {
        return None;
    }

    // Try the full product first so products that legitimately repeat the
    // vendor (for example `centos-stream`) keep their longer curated alias.
    // Only a prefix strip that reaches a curated alias counts, so
    // `Canonical` + `Ubuntu Linux` cannot become `linux`.
    let mut search = product_raw.clone();
    let mut matched = match_alias(&search, table);
    if matched.is_none() {
        for vendor in [&vendor_raw, &canonical_vendor] {
            let Some(stripped) = strip_prefix(&product_raw, vendor) else {
                continue;
            };
            if stripped == search {
                continue;
            }
            if let Some(found) = match_alias(stripped, table) {
                search = stripped.to_owned();
                matched = Some(found);
                break;
            }
        }
    }

    // A redundant vendor prefix is stripped even when no curated alias
    // matches, so the same product observed with `redhat`, `red-hat`, or
    // `Red Hat` keeps one identity key.
    let (canonical_family, trailing) = match matched {
        Some((family, trailing)) => (family, trailing),
        None => (
            strip_prefix(&product_raw, &vendor_raw)
                .or_else(|| strip_prefix(&product_raw, &canonical_vendor))
                .unwrap_or(&product_raw)
                .to_owned(),
            String::new(),
        ),
    };
    if is_absent(&canonical_family) {
        return None;
    }

    let versioned = table.versioned_families.contains(&canonical_family);
    let (trailing_version, trailing_tokens) = if versioned {
        split_trailing_version(&trailing)
    } else {
        (None, Vec::new())
    };

    let explicit_version = observed.version.as_deref().and_then(clean_version);
    let (mut channel, version) = match explicit_version.or(trailing_version) {
        Some(version) => split_for_family(&canonical_family, &version),
        None => (None, None),
    };

    let mut variants = BTreeSet::new();
    for value in [
        observed.edition.as_deref(),
        observed.update.as_deref(),
        observed.target_hw.as_deref(),
    ]
    .into_iter()
    .flatten()
    {
        add_variants_from(&mut variants, value);
    }
    if versioned {
        for token in trailing_tokens {
            add_variant(&mut variants, &token);
        }
        for token in search.split('-') {
            add_variant(&mut variants, token);
        }
    }
    if !variants.is_empty() {
        let suffix = variants.into_iter().collect::<Vec<_>>().join("-");
        channel = Some(match channel {
            Some(channel) => format!("{channel}-{suffix}"),
            None => suffix,
        });
    }

    let class = identity_class(&canonical_family, observed.part.as_deref(), table);
    let slug = canonical_slug(&canonical_vendor, &canonical_family);
    let identity_key = format!(
        "{}:{}:{}",
        class.as_str(),
        canonical_vendor,
        canonical_family
    );
    Some(CanonicalIdentity {
        class,
        canonical_vendor,
        canonical_family,
        slug,
        identity_key,
        channel,
        version,
    })
}

/// Identity key (`class:vendor:family`) for one observation without resolving
/// the display slug or batch-level collision suffixes. One product has exactly
/// one key across all of its channels and versions.
pub fn identity_key_for(observed: &ObservedProduct) -> Option<String> {
    canonicalize(observed).map(|identity| identity.identity_key)
}

fn is_curated(table: &aliases::AliasTable, identity_key: &str) -> bool {
    identity_key
        .splitn(3, ':')
        .nth(2)
        .is_some_and(|family| table.families.contains_key(family))
}

fn suffixed_slug(base: &str, identity_key: &str) -> String {
    let prefix = truncate_at(base, 57);
    let prefix = prefix.trim_matches('-');
    let digest = Sha256::digest(identity_key.as_bytes());
    let hash = HEXLOWER.encode(&digest[..3]);
    if prefix.is_empty() {
        hash
    } else {
        format!("{prefix}-{hash}")
    }
}

/// Canonicalize a batch and resolve slug collisions deterministically.
///
/// Curated families own their base slug; otherwise the lexicographically
/// smallest identity key owns it and every other identity gets a stable
/// `-<sha256(identity_key)[:6]>` suffix. Results are deduplicated and sorted,
/// so input order never changes the output.
pub fn canonicalize_all(observations: &[ObservedProduct]) -> Vec<CanonicalIdentity> {
    let table = aliases::aliases();
    let identities: BTreeSet<CanonicalIdentity> =
        observations.iter().filter_map(canonicalize).collect();

    let mut keys_by_slug: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    for identity in &identities {
        keys_by_slug
            .entry(identity.slug.clone())
            .or_default()
            .insert(identity.identity_key.clone());
    }

    let mut slug_for_key: BTreeMap<String, String> = BTreeMap::new();
    for (slug, keys) in &keys_by_slug {
        if keys.len() == 1 {
            if let Some(key) = keys.first() {
                slug_for_key.insert(key.clone(), slug.clone());
            }
            continue;
        }
        let owner = keys
            .iter()
            .find(|key| is_curated(table, key))
            .or_else(|| keys.first())
            .expect("keys_by_slug groups are non-empty");
        for key in keys {
            let assigned = if key == owner {
                slug.clone()
            } else {
                suffixed_slug(slug, key)
            };
            slug_for_key.insert(key.clone(), assigned);
        }
    }

    let mut result: Vec<CanonicalIdentity> = identities
        .into_iter()
        .map(|mut identity| {
            if let Some(slug) = slug_for_key.get(&identity.identity_key) {
                identity.slug = slug.clone();
            }
            identity
        })
        .collect();
    result.sort();
    result
}