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

johnandersen777.bsky.social/vuln-notif

0
0
main
301 lines · 9.5 KB Raw History
//! Curated identity aliases, embedded at compile time.
//!
//! The table is the only supported merge mechanism: editing
//! `data/identity/aliases.json` is reviewable, while fuzzy matching is not.
//! Embedded data is validated when first used; invalid data panics with a
//! clear message naming every problem.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::marker::PhantomData;
use std::sync::LazyLock;

use serde::Deserialize;
use serde::de::{self, Deserializer, MapAccess, Visitor};

use super::IdentityClass;
use super::normalize_token;

/// Deserialize a set while rejecting duplicate entries.
fn unique_set<'de, D>(deserializer: D) -> Result<BTreeSet<String>, D::Error>
where
    D: Deserializer<'de>,
{
    struct UniqueSetVisitor;

    impl<'de> Visitor<'de> for UniqueSetVisitor {
        type Value = BTreeSet<String>;

        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("an array of unique strings")
        }

        fn visit_seq<A>(self, mut access: A) -> Result<Self::Value, A::Error>
        where
            A: de::SeqAccess<'de>,
        {
            let mut set = BTreeSet::new();
            while let Some(entry) = access.next_element::<String>()? {
                if !set.insert(entry.clone()) {
                    return Err(de::Error::custom(format!("duplicate entry `{entry}`")));
                }
            }
            Ok(set)
        }
    }

    deserializer.deserialize_seq(UniqueSetVisitor)
}

/// Deserialize a map while rejecting duplicate keys.
fn unique_map<'de, D, V>(deserializer: D) -> Result<BTreeMap<String, V>, D::Error>
where
    D: Deserializer<'de>,
    V: Deserialize<'de>,
{
    struct UniqueMapVisitor<V>(PhantomData<V>);

    impl<'de, V: Deserialize<'de>> Visitor<'de> for UniqueMapVisitor<V> {
        type Value = BTreeMap<String, V>;

        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("a map with unique string keys")
        }

        fn visit_map<A>(self, mut access: A) -> Result<Self::Value, A::Error>
        where
            A: MapAccess<'de>,
        {
            let mut map = BTreeMap::new();
            while let Some((key, value)) = access.next_entry::<String, V>()? {
                if map.insert(key.clone(), value).is_some() {
                    return Err(de::Error::custom(format!("duplicate key `{key}`")));
                }
            }
            Ok(map)
        }
    }

    deserializer.deserialize_map(UniqueMapVisitor(PhantomData))
}

/// Curated alias and class data used by canonicalization.
#[derive(Debug, Clone, Deserialize)]
pub struct AliasTable {
    /// Raw normalized vendor token -> canonical vendor.
    #[serde(deserialize_with = "unique_map")]
    pub vendors: BTreeMap<String, String>,
    /// Normalized product prefix -> canonical family. An entry matches the
    /// product exactly or a `-`-separated prefix of it.
    #[serde(deserialize_with = "unique_map")]
    pub products: BTreeMap<String, String>,
    /// Curated canonical family -> canonical vendor. Curated families own
    /// their base slug during collision resolution.
    #[serde(deserialize_with = "unique_map")]
    pub families: BTreeMap<String, String>,
    /// Families whose trailing text may be a stream/version.
    #[serde(deserialize_with = "unique_set")]
    pub versioned_families: BTreeSet<String>,
    /// Canonical family -> forced identity class.
    #[serde(deserialize_with = "unique_map")]
    pub class_overrides: BTreeMap<String, IdentityClass>,
}

impl AliasTable {
    /// Validate the table invariants. Returns every problem found so a loader
    /// can report all of them at once.
    pub fn validate(&self) -> Result<(), Vec<String>> {
        validate_table(self)
    }

    /// Deserialize and validate a table. The error is a single line suitable
    /// for a panic message; [`load`] panics with it for the embedded table.
    pub fn from_json(raw: &str) -> Result<Self, String> {
        let table: Self = serde_json::from_str(raw).map_err(|error| error.to_string())?;
        table.validate().map_err(|errors| errors.join("; "))?;
        Ok(table)
    }
}

static ALIASES: LazyLock<AliasTable> = LazyLock::new(load);

fn load() -> AliasTable {
    let raw = include_str!("../../data/identity/aliases.json");
    AliasTable::from_json(raw)
        .unwrap_or_else(|error| panic!("invalid embedded identity aliases: {error}"))
}

/// Validated alias table.
pub fn aliases() -> &'static AliasTable {
    &ALIASES
}

fn is_normalized(token: &str) -> bool {
    !token.is_empty() && normalize_token(token) == token
}

fn validate_table(table: &AliasTable) -> Result<(), Vec<String>> {
    let mut errors = Vec::new();

    for (name, map) in [
        ("vendors", &table.vendors),
        ("products", &table.products),
        ("families", &table.families),
    ] {
        if map.is_empty() {
            errors.push(format!("{name} must not be empty"));
        }
        for (key, value) in map {
            if !is_normalized(key) {
                errors.push(format!("{name} key `{key}` is not normalized"));
            }
            if !is_normalized(value) {
                errors.push(format!(
                    "{name} value `{value}` for `{key}` is not normalized"
                ));
            }
        }
    }

    if table.versioned_families.is_empty() {
        errors.push("versioned_families must not be empty".to_owned());
    }
    for family in &table.versioned_families {
        if !is_normalized(family) {
            errors.push(format!("versioned family `{family}` is not normalized"));
        }
        if !table.families.contains_key(family) {
            errors.push(format!("versioned family `{family}` is not in families"));
        }
    }

    if table.class_overrides.is_empty() {
        errors.push("class_overrides must not be empty".to_owned());
    }
    for family in table.class_overrides.keys() {
        if !is_normalized(family) {
            errors.push(format!("class override `{family}` is not normalized"));
        }
    }

    for (alias, family) in &table.products {
        if !table.families.contains_key(family) {
            errors.push(format!(
                "product alias `{alias}` points at unknown family `{family}`"
            ));
        }
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors)
    }
}

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

    #[test]
    fn embedded_table_is_valid_and_covers_plan_aliases() {
        let table = aliases();
        assert_eq!(
            table.vendors.get("redhat").map(String::as_str),
            Some("red-hat")
        );
        assert_eq!(
            table.vendors.get("red-hat").map(String::as_str),
            Some("red-hat")
        );
        assert_eq!(
            table.vendors.get("fedoraproject").map(String::as_str),
            Some("fedora")
        );
        assert_eq!(
            table.vendors.get("gleam").map(String::as_str),
            Some("gleam-lang")
        );
        assert_eq!(table.vendors.get("ni").map(String::as_str), Some("ni"));
        assert_eq!(
            table.vendors.get("avb-disc-soft").map(String::as_str),
            Some("disc-soft")
        );
        assert_eq!(
            table.vendors.get("arm").map(String::as_str),
            Some("trustedfirmware")
        );
        assert_eq!(
            table.class_overrides.get("red-hat-enterprise-linux"),
            Some(&IdentityClass::Os)
        );
        assert!(table.families.contains_key("red-hat-enterprise-linux"));
        assert!(
            table
                .versioned_families
                .contains("red-hat-enterprise-linux")
        );
    }

    const MINIMAL_TABLE: &str = r#"{
        "vendors": {"acme": "acme"},
        "products": {"widget": "widget"},
        "families": {"widget": "acme"},
        "versioned_families": ["widget"],
        "class_overrides": {"widget": "app"}
    }"#;

    fn load_strict(raw: &str) -> AliasTable {
        AliasTable::from_json(raw)
            .unwrap_or_else(|error| panic!("invalid embedded identity aliases: {error}"))
    }

    #[test]
    fn minimal_table_is_valid() {
        let table = load_strict(MINIMAL_TABLE);
        assert_eq!(table.vendors.get("acme").map(String::as_str), Some("acme"));
        assert_eq!(table.validate(), Ok(()));
    }

    #[test]
    #[should_panic(expected = "duplicate key")]
    fn duplicate_alias_key_panics() {
        load_strict(
            r#"{
                "vendors": {"acme": "acme", "acme": "acme"},
                "products": {"widget": "widget"},
                "families": {"widget": "acme"},
                "versioned_families": ["widget"],
                "class_overrides": {"widget": "app"}
            }"#,
        );
    }

    #[test]
    #[should_panic(expected = "not normalized")]
    fn invalid_alias_key_panics() {
        load_strict(
            r#"{
                "vendors": {"Acme Inc": "acme"},
                "products": {"widget": "widget"},
                "families": {"widget": "acme"},
                "versioned_families": ["widget"],
                "class_overrides": {"widget": "app"}
            }"#,
        );
    }

    #[test]
    #[should_panic(expected = "duplicate entry")]
    fn duplicate_versioned_family_panics() {
        load_strict(
            r#"{
                "vendors": {"acme": "acme"},
                "products": {"widget": "widget"},
                "families": {"widget": "acme"},
                "versioned_families": ["widget", "widget"],
                "class_overrides": {"widget": "app"}
            }"#,
        );
    }
}