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

johnandersen777.bsky.social/vuln-notif

0
0
main
635 lines · 20.4 KB Raw History
//! Distro/OS release source tests: RHEL lifecycle data (curated table, Red Hat
//! Product Life Cycle API, and endoflife.date), EUS/ELS/arch channel mapping,
//! public UBI OCI manifest artifacts, and typed unsupported reasons.
//!
//! The module is compiled into `sources` by the integration wave; until that
//! wiring lands this test includes it directly and provides the `crate::`
//! paths it uses. Every HTTP call goes through the scripted [`FakeHttp`] seam;
//! no test touches the network.

use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex};

use anyhow::anyhow;
use async_trait::async_trait;
use serde_json::{Value, json};

use vuln_notif::release::http::RegistryHttp;
use vuln_notif::release::source::{ProjectRef, ReleaseSource, UnsupportedReason, VersionInfo};

mod release {
    pub mod http {
        pub use vuln_notif::release::http::*;
    }
    pub mod source {
        pub use vuln_notif::release::source::*;
    }
}

#[path = "../src/release/sources/distro.rs"]
mod distro;

const ENDOFLIFE_BASE: &str = "https://endoflife.example/api/v1";
const PRODUCTS_URL: &str = "https://endoflife.example/api/v1/products";
const EOL_RHEL_URL: &str = "https://endoflife.example/api/v1/products/red-hat-enterprise-linux";
const LIFECYCLE_URL: &str =
    "https://lifecycle.example/api/v1/products?name=Red%20Hat%20Enterprise%20Linux";
const REGISTRY_BASE: &str = "https://registry.example";

const RHEL_LIFECYCLE: &str = include_str!("fixtures/sources/distro/rhel-lifecycle.json");
const ENDOFLIFE_RHEL: &str = include_str!("fixtures/sources/distro/endoflife-rhel.json");
const UBI_MANIFEST: &str = include_str!("fixtures/sources/distro/ubi-manifest.json");

fn fixture(raw: &str) -> Value {
    serde_json::from_str(raw).expect("fixture JSON")
}

// ---------------------------------------------------------------------------
// Scripted RegistryHttp + ManifestHttp fake
// ---------------------------------------------------------------------------

#[derive(Default)]
struct FakeHttp {
    json_routes: Mutex<HashMap<String, Value>>,
    json_errors: Mutex<HashMap<String, String>>,
    manifest_routes: Mutex<HashMap<String, VecDeque<distro::ManifestResponse>>>,
    get_calls: Mutex<Vec<String>>,
    manifest_calls: Mutex<Vec<(String, String)>>,
}

impl FakeHttp {
    fn json(&self, url: impl Into<String>, value: Value) {
        self.json_routes.lock().unwrap().insert(url.into(), value);
    }

    fn json_error(&self, url: impl Into<String>, message: &str) {
        self.json_errors
            .lock()
            .unwrap()
            .insert(url.into(), message.to_owned());
    }

    fn manifest(&self, url: impl Into<String>, status: u16, digest: Option<&str>, body: Value) {
        self.manifest_routes
            .lock()
            .unwrap()
            .entry(url.into())
            .or_default()
            .push_back(distro::ManifestResponse {
                status,
                digest: digest.map(str::to_owned),
                body,
            });
    }

    fn get_calls(&self) -> Vec<String> {
        self.get_calls.lock().unwrap().clone()
    }

    fn manifest_calls(&self) -> Vec<(String, String)> {
        self.manifest_calls.lock().unwrap().clone()
    }
}

#[async_trait]
impl RegistryHttp for FakeHttp {
    async fn get_json(&self, url: &str) -> anyhow::Result<Value> {
        self.get_calls.lock().unwrap().push(url.to_owned());
        if let Some(message) = self.json_errors.lock().unwrap().get(url) {
            return Err(anyhow!("{message}"));
        }
        if let Some(value) = self.json_routes.lock().unwrap().get(url) {
            return Ok(value.clone());
        }
        Err(anyhow!("HTTP 404 Not Found for {url}"))
    }

    async fn get_text(&self, _url: &str) -> anyhow::Result<String> {
        Err(anyhow!("unused"))
    }

    async fn head_size(&self, _url: &str) -> anyhow::Result<u64> {
        Err(anyhow!("unused"))
    }

    async fn download(&self, _url: &str) -> anyhow::Result<Vec<u8>> {
        Err(anyhow!("unused"))
    }
}

#[async_trait]
impl distro::ManifestHttp for FakeHttp {
    async fn fetch_manifest(
        &self,
        url: &str,
        accept: &str,
    ) -> anyhow::Result<distro::ManifestResponse> {
        self.manifest_calls
            .lock()
            .unwrap()
            .push((url.to_owned(), accept.to_owned()));
        let mut routes = self.manifest_routes.lock().unwrap();
        match routes.get_mut(url).and_then(|queue| queue.pop_front()) {
            Some(response) => Ok(response),
            None => Err(anyhow!("HTTP 404 Not Found for {url}")),
        }
    }
}

// ---------------------------------------------------------------------------
// Builders
// ---------------------------------------------------------------------------

fn source(http: &Arc<FakeHttp>) -> distro::DistroSource {
    distro::DistroSource::with_clients(http.clone(), http.clone())
        .with_endpoints(ENDOFLIFE_BASE, LIFECYCLE_URL, REGISTRY_BASE)
        .with_reference_date("2026-11-11")
}

fn rhel_project() -> ProjectRef {
    ProjectRef {
        purl_type: "rpm".to_owned(),
        name: "redhat/enterprise_linux".to_owned(),
        purl: "pkg:rpm/redhat/enterprise_linux".to_owned(),
    }
}

fn project(purl_type: &str, namespace: &str, name: &str) -> ProjectRef {
    ProjectRef {
        purl_type: purl_type.to_owned(),
        name: format!("{namespace}/{name}"),
        purl: format!("pkg:{purl_type}/{namespace}/{name}"),
    }
}

fn version(text: &str) -> VersionInfo {
    VersionInfo {
        raw: text.to_owned(),
        version: text.to_owned(),
        deprecated: false,
        reason: String::new(),
    }
}

fn has(versions: &[VersionInfo], text: &str) -> bool {
    versions.iter().any(|version| version.version == text)
}

fn find<'a>(versions: &'a [VersionInfo], text: &str) -> &'a VersionInfo {
    versions
        .iter()
        .find(|version| version.version == text)
        .unwrap_or_else(|| panic!("missing version {text}"))
}

fn products_payload() -> Value {
    json!({
        "schema_version": "1.0.0",
        "total": 3,
        "result": [
            {"name": "debian", "aliases": ["debian"], "label": "Debian", "category": "os"},
            {"name": "alpine-linux", "aliases": ["alpine", "alpinelinux"], "label": "Alpine Linux", "category": "os"},
            {"name": "ubuntu", "aliases": ["ubuntu"], "label": "Ubuntu", "category": "os"},
            {"name": "red-hat-enterprise-linux", "aliases": ["rhel"], "label": "Red Hat Enterprise Linux", "category": "os"}
        ]
    })
}

// ---------------------------------------------------------------------------
// RHEL lifecycle, channels, and EOL
// ---------------------------------------------------------------------------

#[tokio::test]
async fn rhel_lifecycle_yields_channels_versions_and_eol_status() {
    let http = Arc::new(FakeHttp::default());
    http.json(LIFECYCLE_URL, fixture(RHEL_LIFECYCLE));
    http.json(PRODUCTS_URL, products_payload());
    http.json(EOL_RHEL_URL, fixture(ENDOFLIFE_RHEL));
    let source = source(&http);
    let project = rhel_project();

    let versions = source.versions(&project).await.expect("versions");

    // Channels come from the lifecycle product name; 9.4/9.5 come from the
    // lifecycle API's last/final minor release fields.
    assert!(has(&versions, "9"), "channel 9");
    assert!(has(&versions, "9.4"), "9.4");
    assert!(has(&versions, "9.5"), "9.5");
    assert!(has(&versions, "8"), "channel 8");
    assert!(has(&versions, "8.10"), "8.10");
    assert!(has(&versions, "10"), "channel 10");
    assert!(has(&versions, "6-els"), "curated ELS channel");
    assert!(has(&versions, "8-eus"), "curated EUS channel");

    let nine_four = find(&versions, "9.4");
    assert!(!nine_four.deprecated, "RHEL 9 is still supported");
    assert!(nine_four.reason.contains("2032-05-31"), "EOL date carried");

    let six = find(&versions, "6");
    assert!(six.deprecated, "RHEL 6 is past its EOL");
    assert!(six.reason.contains("2020-11-30"));

    let statuses = source
        .statuses(&project, find(&versions, "6"))
        .await
        .expect("statuses");
    assert_eq!(statuses.len(), 1);
    assert_eq!(statuses[0].status, "deprecated");
    assert_eq!(statuses[0].kind.as_deref(), Some("eol"));
    assert!(statuses[0].reason.contains("2020-11-30"));

    let active = source
        .statuses(&project, find(&versions, "9.5"))
        .await
        .expect("active statuses");
    assert!(active.is_empty(), "future EOL is not an EOL signal");
}

#[tokio::test]
async fn rhel_curated_channels_cover_majors_eus_els_and_arches() {
    let http = Arc::new(FakeHttp::default());
    let source = source(&http);

    // No lifecycle routes are scripted: only the curated table answers.
    let versions = source
        .versions(&rhel_project())
        .await
        .expect("curated versions");
    for major in distro::RHEL_MAJORS {
        assert!(has(&versions, major), "missing curated channel {major}");
    }
    assert!(has(&versions, "6-els"));
    assert!(has(&versions, "8-eus"));
    assert!(has(&versions, "9-eus"));
    assert!(
        versions
            .iter()
            .all(|version| !version.version.contains('.')),
        "curated table must not fabricate point versions"
    );

    assert_eq!(distro::distro_channel("9", Some("eus"), None), "9-eus");
    assert_eq!(distro::distro_channel("6", Some("els"), None), "6-els");
    assert_eq!(
        distro::distro_channel("9", None, Some("aarch64")),
        "9-aarch64"
    );
    assert_eq!(
        distro::distro_channel("8", Some("sap"), Some("ppc64le")),
        "8-sap-ppc64le"
    );
    assert_eq!(distro::distro_channel("20.04", None, None), "20-04");
    assert!(distro::RHEL_EDITIONS.contains(&"aus"));
    assert!(distro::RHEL_ARCHES.contains(&"s390x"));

    let unknown = source
        .statuses(&rhel_project(), &version("999"))
        .await
        .expect("unknown version statuses");
    assert!(
        unknown.is_empty(),
        "absence of lifecycle data is not a yank"
    );
}

// ---------------------------------------------------------------------------
// UBI OCI manifest artifacts
// ---------------------------------------------------------------------------

#[tokio::test]
async fn ubi_manifest_digest_becomes_artifact() {
    let http = Arc::new(FakeHttp::default());
    let manifest = fixture(UBI_MANIFEST);
    let amd64_digest = manifest["manifests"][0]["digest"]
        .as_str()
        .expect("amd64 digest");
    let arm64_digest = manifest["manifests"][1]["digest"]
        .as_str()
        .expect("arm64 digest");
    http.manifest(
        format!("{REGISTRY_BASE}/v2/ubi9/ubi/manifests/9.4"),
        200,
        None,
        manifest.clone(),
    );
    http.manifest(
        format!("{REGISTRY_BASE}/v2/ubi9/ubi/manifests/9"),
        200,
        None,
        manifest.clone(),
    );
    let source = source(&http);
    let project = rhel_project();

    let artifacts = source
        .artifacts(&project, &version("9.4"))
        .await
        .expect("artifacts");
    assert_eq!(artifacts.len(), 1);
    assert_eq!(
        artifacts[0].sha256.as_deref(),
        Some(amd64_digest.trim_start_matches("sha256:"))
    );
    assert_eq!(
        artifacts[0].url,
        format!("{REGISTRY_BASE}/v2/ubi9/ubi/manifests/{amd64_digest}")
    );
    assert_eq!(artifacts[0].size, Some(1234));
    assert_eq!(
        artifacts[0].mime_type.as_deref(),
        Some(distro::OCI_INDEX_ACCEPT)
    );
    assert_eq!(artifacts[0].file_name, "ubi9-ubi-9.4.oci.json");

    let artifacts = source
        .artifacts(&project, &version("9-aarch64"))
        .await
        .expect("aarch64 artifacts");
    assert_eq!(
        artifacts[0].sha256.as_deref(),
        Some(arm64_digest.trim_start_matches("sha256:"))
    );
    assert_eq!(
        artifacts[0].url,
        format!("{REGISTRY_BASE}/v2/ubi9/ubi/manifests/{arm64_digest}")
    );

    let calls = http.manifest_calls();
    assert_eq!(calls.len(), 2);
    assert_eq!(
        calls[0].0,
        format!("{REGISTRY_BASE}/v2/ubi9/ubi/manifests/9.4")
    );
    assert_eq!(calls[0].1, distro::OCI_INDEX_ACCEPT);
    assert_eq!(
        calls[1].0,
        format!("{REGISTRY_BASE}/v2/ubi9/ubi/manifests/9")
    );
}

#[tokio::test]
async fn ubi_registry_auth_maps_to_typed_unavailable() {
    for status in [401, 403] {
        let http = Arc::new(FakeHttp::default());
        http.manifest(
            format!("{REGISTRY_BASE}/v2/ubi9/ubi/manifests/9.4"),
            status,
            None,
            json!({}),
        );
        let source = source(&http);
        let error = source
            .artifacts(&rhel_project(), &version("9.4"))
            .await
            .expect_err("registry auth failure");
        assert_eq!(
            distro::unsupported_reason(&error),
            Some(UnsupportedReason::Unavailable(
                "redhat registry requires authentication"
            )),
            "HTTP {status}"
        );
    }
}

// ---------------------------------------------------------------------------
// endoflife.date v1 payloads and product aliases
// ---------------------------------------------------------------------------

#[tokio::test]
async fn endoflife_v1_payload_parses_cycles_versions_and_eol() {
    let http = Arc::new(FakeHttp::default());
    http.json(PRODUCTS_URL, products_payload());
    http.json(EOL_RHEL_URL, fixture(ENDOFLIFE_RHEL));
    let source = source(&http);

    let versions = source
        .versions(&rhel_project())
        .await
        .expect("endoflife versions");

    let seven = find(&versions, "7.9");
    assert!(seven.deprecated, "isEol cycle is deprecated");
    assert!(seven.reason.contains("2024-06-30"));
    assert!(has(&versions, "9.5"));
    assert!(has(&versions, "8.10"));
    assert!(has(&versions, "10.0"));

    let statuses = source
        .statuses(&rhel_project(), find(&versions, "7.9"))
        .await
        .expect("statuses");
    assert_eq!(statuses[0].status, "deprecated");
    assert_eq!(statuses[0].kind.as_deref(), Some("eol"));
}

#[tokio::test]
async fn endoflife_product_list_resolves_deb_and_apk_aliases() {
    let http = Arc::new(FakeHttp::default());
    http.json(PRODUCTS_URL, products_payload());
    http.json(
        format!("{ENDOFLIFE_BASE}/products/debian"),
        json!({
            "schema_version": "1.0.0",
            "result": {
                "name": "debian",
                "releases": [
                    {"name": "13", "isEol": false, "eolFrom": "2030-06-30", "latest": {"name": "13.7"}},
                    {"name": "10", "isEol": true, "eolFrom": "2024-06-30", "latest": {"name": "10.13"}}
                ]
            }
        }),
    );
    http.json(
        format!("{ENDOFLIFE_BASE}/products/alpine-linux"),
        json!({
            "schema_version": "1.0.0",
            "result": {
                "name": "alpine-linux",
                "releases": [
                    {"name": "3.24", "isEol": false, "eolFrom": "2028-06-01", "latest": {"name": "3.24.4"}}
                ]
            }
        }),
    );
    http.json(
        format!("{ENDOFLIFE_BASE}/products/ubuntu"),
        json!({
            "schema_version": "1.0.0",
            "result": {
                "name": "ubuntu",
                "releases": [
                    {"name": "24.04", "isEol": false, "eolFrom": "2036-04-23", "latest": {"name": "24.04.3"}}
                ]
            }
        }),
    );
    let source = source(&http);

    let debian = source
        .versions(&project("deb", "debian", "debian"))
        .await
        .expect("debian versions");
    assert!(has(&debian, "13"));
    assert!(has(&debian, "13.7"));
    assert!(find(&debian, "10").deprecated);
    assert!(find(&debian, "10").reason.contains("2024-06-30"));

    let alpine = source
        .versions(&project("apk", "alpine", "alpine"))
        .await
        .expect("alpine versions");
    assert!(has(&alpine, "3.24"));
    assert!(has(&alpine, "3.24.4"));

    let ubuntu = source
        .versions(&project("deb", "ubuntu", "ubuntu"))
        .await
        .expect("ubuntu versions");
    assert!(has(&ubuntu, "24-04"), "dotless Ubuntu point channel");
    assert!(has(&ubuntu, "24.04"));
    assert!(has(&ubuntu, "24.04.3"));

    assert!(
        http.get_calls()
            .iter()
            .any(|url| url == &format!("{ENDOFLIFE_BASE}/products/alpine-linux")),
        "purl alias `alpine` resolved through the all-products endpoint"
    );
}

#[tokio::test]
async fn endoflife_product_list_failure_falls_back_to_direct_slug() {
    let http = Arc::new(FakeHttp::default());
    http.json_error(PRODUCTS_URL, "HTTP 500 Internal Server Error");
    http.json(
        format!("{ENDOFLIFE_BASE}/products/debian"),
        json!({
            "schema_version": "1.0.0",
            "result": {
                "name": "debian",
                "releases": [{"name": "13", "isEol": false, "latest": {"name": "13.7"}}]
            }
        }),
    );
    let source = source(&http);

    let debian = source
        .versions(&project("deb", "debian", "debian"))
        .await
        .expect("debian versions");
    assert!(has(&debian, "13"));
    assert!(has(&debian, "13.7"));
}

// ---------------------------------------------------------------------------
// Capability flags, typed unsupported reasons, and metadata
// ---------------------------------------------------------------------------

#[tokio::test]
async fn production_constructor_builds_the_manifest_transport() {
    let source =
        distro::DistroSource::new(Arc::new(FakeHttp::default())).expect("production distro source");
    assert_eq!(source.name(), "distro");
    assert!(source.capabilities().versions);
}

#[tokio::test]
async fn capability_flags_and_unsupported_reasons_are_typed() {
    let http = Arc::new(FakeHttp::default());
    let source = source(&http);

    let capabilities = source.capabilities();
    assert!(capabilities.versions);
    assert!(capabilities.artifacts);
    assert!(capabilities.statuses);
    assert!(capabilities.project_meta);

    let npm = ProjectRef {
        purl_type: "npm".to_owned(),
        name: "left-pad".to_owned(),
        purl: "pkg:npm/left-pad".to_owned(),
    };
    let error = source.versions(&npm).await.expect_err("unknown purl type");
    assert_eq!(
        distro::unsupported_reason(&error),
        Some(UnsupportedReason::UnknownPurlType("npm".to_owned()))
    );

    let error = source
        .artifacts(&project("deb", "debian", "debian"), &version("13"))
        .await
        .expect_err("deb has no public artifact source");
    assert_eq!(
        distro::unsupported_reason(&error),
        Some(UnsupportedReason::NoArtifacts)
    );

    let error = source
        .artifacts(&project("apk", "alpine", "alpine"), &version("3.24"))
        .await
        .expect_err("apk has no public artifact source");
    assert_eq!(
        distro::unsupported_reason(&error),
        Some(UnsupportedReason::NoArtifacts)
    );

    let error = source
        .versions(&project("deb", "debian", "openssl"))
        .await
        .expect_err("package lifecycle is not distro lifecycle");
    assert_eq!(
        distro::unsupported_reason(&error),
        Some(UnsupportedReason::NoVersions)
    );

    let error = source
        .artifacts(&rhel_project(), &version("not-a-stream"))
        .await
        .expect_err("invalid UBI stream");
    assert_eq!(
        distro::unsupported_reason(&error),
        Some(UnsupportedReason::NoArtifacts)
    );
    assert!(
        http.manifest_calls().is_empty(),
        "invalid streams must not reach the registry"
    );
}

#[tokio::test]
async fn project_meta_maps_enterprise_linux_and_distros() {
    let http = Arc::new(FakeHttp::default());
    let source = source(&http);

    let meta = source
        .project_meta(&rhel_project())
        .await
        .expect("rhel meta");
    assert_eq!(meta["vendor"], "Red Hat");
    assert_eq!(meta["product"], "Red Hat Enterprise Linux");
    assert_eq!(meta["project"], "red-hat-enterprise-linux");
    assert!(
        meta["lifecycle"]
            .as_str()
            .expect("lifecycle URL")
            .contains("access.redhat.com")
    );

    let meta = source
        .project_meta(&ProjectRef {
            purl_type: "rpm".to_owned(),
            name: "redhat/enterprise_linux".to_owned(),
            purl: String::new(),
        })
        .await
        .expect("name fallback");
    assert_eq!(meta["project"], "red-hat-enterprise-linux");

    let meta = source
        .project_meta(&project("deb", "debian", "debian"))
        .await
        .expect("debian meta");
    assert_eq!(meta["vendor"], "Debian");
    assert_eq!(meta["lifecycle"], "https://endoflife.date/debian");
}