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

johnandersen777.bsky.social/vuln-notif

0
0
main
1070 lines · 34.3 KB Raw History
//! Distro/OS release source for `rpm`, `deb`, and `apk` purls.
//!
//! Version and EOL data comes from a curated RHEL lifecycle table, the public
//! Red Hat Product Life Cycle API, and endoflife.date (v1 product and product
//! list endpoints). Channels are `X` and versions are `X.Y`; channel text has
//! dots replaced by hyphens because release channels cannot contain dots.
//!
//! RHEL/UBI artifacts are the public OCI manifest at
//! `registry.access.redhat.com/v2/ubi{major}/ubi/manifests/{stream}`. The
//! registry digest is the artifact hash and the digest URL is the artifact URL.
//! No subscription artifact is fabricated; an authenticated registry (401/403)
//! produces [`UnsupportedReason::Unavailable`] so callers emit version labels
//! only. Distro builds not published as UBI return [`UnsupportedReason::NoArtifacts`].
//!
//! [`ManifestHttp`] is a separate seam from [`RegistryHttp`] because the OCI
//! index fetch needs an `Accept` header and the returned digest header, which
//! the shared registry transport does not expose.

use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::sync::Arc;

use anyhow::{Context, Result};
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::{Value, json};

use crate::release::http::{HTTP_TIMEOUT, RegistryHttp, USER_AGENT};
use crate::release::source::{
    ArtifactInfo, ProjectRef, ReleaseSource, SourceCapabilities, StatusInfo, UnsupportedReason,
    VersionInfo,
};

pub const DEFAULT_ENDOFLIFE_BASE_URL: &str = "https://endoflife.date/api/v1";
pub const DEFAULT_RHEL_LIFECYCLE_URL: &str = "https://access.redhat.com/product-life-cycles/api/v1/products?name=Red%20Hat%20Enterprise%20Linux";
pub const DEFAULT_REGISTRY_BASE_URL: &str = "https://registry.access.redhat.com";
pub const OCI_INDEX_ACCEPT: &str = "application/vnd.oci.image.index.v1+json";

/// Canonical project slug for every Red Hat Enterprise Linux variant.
pub const RHEL_PROJECT: &str = "red-hat-enterprise-linux";

/// Curated RHEL major channels. Point releases always come from lifecycle data.
pub const RHEL_MAJORS: &[&str] = &["6", "7", "8", "9", "10"];

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

/// Architecture tokens that append to a channel. `x86_64` is the default and is
/// intentionally absent.
pub const RHEL_ARCHES: &[&str] = &["aarch64", "ppc64le", "ppc64", "s390x"];

/// One curated RHEL channel. `eol` is the published lifecycle end date; API
/// data replaces it when available.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CuratedChannel {
    pub major: &'static str,
    pub edition: Option<&'static str>,
    pub eol: Option<&'static str>,
}

/// Curated majors plus the edition channels the canonical identity model
/// expects (`6-els`, `8-eus`, ...). Point versions are deliberately absent:
/// they are only emitted when lifecycle data supplies them.
pub const RHEL_CURATED_CHANNELS: &[CuratedChannel] = &[
    CuratedChannel {
        major: "6",
        edition: None,
        eol: Some("2020-11-30"),
    },
    CuratedChannel {
        major: "6",
        edition: Some("els"),
        eol: Some("2024-06-30"),
    },
    CuratedChannel {
        major: "7",
        edition: None,
        eol: Some("2024-06-30"),
    },
    CuratedChannel {
        major: "7",
        edition: Some("els"),
        eol: Some("2026-06-30"),
    },
    CuratedChannel {
        major: "8",
        edition: None,
        eol: Some("2029-05-31"),
    },
    CuratedChannel {
        major: "8",
        edition: Some("eus"),
        eol: Some("2029-05-31"),
    },
    CuratedChannel {
        major: "9",
        edition: None,
        eol: Some("2032-05-31"),
    },
    CuratedChannel {
        major: "9",
        edition: Some("eus"),
        eol: Some("2032-05-31"),
    },
    CuratedChannel {
        major: "10",
        edition: None,
        eol: Some("2035-05-31"),
    },
];

/// Compose a channel name, replacing dots because the release channel rkey
/// grammar forbids them.
pub fn distro_channel(major: &str, edition: Option<&str>, arch: Option<&str>) -> String {
    [Some(major), edition, arch]
        .into_iter()
        .flatten()
        .map(|part| part.trim().replace('.', "-"))
        .filter(|part| !part.is_empty())
        .collect::<Vec<_>>()
        .join("-")
}

/// One lifecycle channel or version.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LifecycleEntry {
    pub channel: String,
    pub version: Option<String>,
    pub eol: Option<String>,
}

/// A recognized distro/OS product.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DistroProject {
    pub project: &'static str,
    pub vendor: &'static str,
    pub product: &'static str,
    pub lifecycle_url: &'static str,
    /// endoflife.date product slug, when the product is published there.
    pub product_slug: Option<&'static str>,
    pub rhel: bool,
}

const RHEL: DistroProject = DistroProject {
    project: RHEL_PROJECT,
    vendor: "Red Hat",
    product: "Red Hat Enterprise Linux",
    lifecycle_url: "https://access.redhat.com/product-life-cycles?product=Red%20Hat%20Enterprise%20Linux",
    product_slug: Some(RHEL_PROJECT),
    rhel: true,
};

const DEBIAN: DistroProject = DistroProject {
    project: "debian",
    vendor: "Debian",
    product: "Debian",
    lifecycle_url: "https://endoflife.date/debian",
    product_slug: Some("debian"),
    rhel: false,
};

const UBUNTU: DistroProject = DistroProject {
    project: "ubuntu",
    vendor: "Canonical",
    product: "Ubuntu",
    lifecycle_url: "https://endoflife.date/ubuntu",
    product_slug: Some("ubuntu"),
    rhel: false,
};

const ALPINE: DistroProject = DistroProject {
    project: "alpine-linux",
    vendor: "Alpine Linux",
    product: "Alpine Linux",
    lifecycle_url: "https://endoflife.date/alpine-linux",
    // The purl namespace says `alpine`; the all-products endpoint resolves
    // that alias to the canonical `alpine-linux` product slug.
    product_slug: Some("alpine"),
    rhel: false,
};

const FEDORA: DistroProject = DistroProject {
    project: "fedora",
    vendor: "Fedora Project",
    product: "Fedora Linux",
    lifecycle_url: "https://endoflife.date/fedora",
    product_slug: Some("fedora"),
    rhel: false,
};

const CENTOS_STREAM: DistroProject = DistroProject {
    project: "centos-stream",
    vendor: "CentOS",
    product: "CentOS Stream",
    lifecycle_url: "https://endoflife.date/centos-stream",
    product_slug: Some("centos-stream"),
    rhel: false,
};

const ORACLE_LINUX: DistroProject = DistroProject {
    project: "oracle-linux",
    vendor: "Oracle",
    product: "Oracle Linux",
    lifecycle_url: "https://endoflife.date/oracle-linux",
    product_slug: Some("oracle-linux"),
    rhel: false,
};

const AMAZON_LINUX: DistroProject = DistroProject {
    project: "amazon-linux",
    vendor: "Amazon",
    product: "Amazon Linux",
    lifecycle_url: "https://endoflife.date/amazon-linux",
    product_slug: Some("amazon-linux"),
    rhel: false,
};

/// Resolve a purl to an OS product. Package-level distro purls (`openssl`,
/// `kernel`, ...) are intentionally not recognized: their lifecycle is not the
/// distro lifecycle.
pub fn resolve_project(project: &ProjectRef) -> Option<DistroProject> {
    let (purl_type, namespace, name) = purl_parts(project);
    match purl_type.as_str() {
        "rpm" => match (namespace.as_str(), name.as_str()) {
            ("redhat", "enterprise_linux" | "enterprise-linux" | "rhel" | "rhel_els")
            | ("", "enterprise_linux" | "enterprise-linux" | "redhat-enterprise-linux") => {
                Some(RHEL)
            }
            ("fedora", "fedora") => Some(FEDORA),
            ("centos", "centos" | "centos-stream") => Some(CENTOS_STREAM),
            ("oracle", "oracle_linux" | "oracle-linux") => Some(ORACLE_LINUX),
            ("amazon", "amazon_linux" | "amazon-linux") => Some(AMAZON_LINUX),
            _ => None,
        },
        "deb" => match name.as_str() {
            "debian" => Some(DEBIAN),
            "ubuntu" => Some(UBUNTU),
            _ => None,
        },
        "apk" => match name.as_str() {
            "alpine" | "alpine-linux" => Some(ALPINE),
            _ => None,
        },
        _ => None,
    }
}

/// Distro purl types this source answers for.
pub fn is_distro_purl_type(purl_type: &str) -> bool {
    matches!(
        purl_type.trim().to_ascii_lowercase().as_str(),
        "rpm" | "deb" | "apk"
    )
}

fn purl_parts(project: &ProjectRef) -> (String, String, String) {
    let purl_type = project.purl_type.trim().to_ascii_lowercase();
    let raw = project.purl.trim();
    let raw = raw.strip_prefix("pkg:").unwrap_or(raw);
    let raw = raw.split(['?', '#']).next().unwrap_or(raw);
    let raw = raw.split('@').next().unwrap_or(raw);
    let mut segments: Vec<&str> = raw.split('/').filter(|part| !part.is_empty()).collect();
    if segments
        .first()
        .is_some_and(|first| first.eq_ignore_ascii_case(&purl_type))
    {
        segments.remove(0);
    }
    if segments.is_empty() {
        return match project.name.trim().split_once('/') {
            Some((namespace, name)) => (
                purl_type,
                namespace.trim().to_ascii_lowercase(),
                name.trim().to_ascii_lowercase(),
            ),
            None => (
                purl_type,
                String::new(),
                project.name.trim().to_ascii_lowercase(),
            ),
        };
    }
    let name = segments.pop().unwrap_or_default().to_ascii_lowercase();
    let namespace = segments.pop().unwrap_or_default().to_ascii_lowercase();
    (purl_type, namespace, name)
}

/// Typed unsupported failure carried through [`anyhow::Error`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DistroUnsupported {
    pub reason: UnsupportedReason,
}

impl std::fmt::Display for DistroUnsupported {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            formatter,
            "unsupported distro source request: {:?}",
            self.reason
        )
    }
}

impl std::error::Error for DistroUnsupported {}

fn unsupported(reason: UnsupportedReason) -> anyhow::Error {
    anyhow::Error::new(DistroUnsupported { reason })
}

/// Recover the typed reason from an error returned by this source.
pub fn unsupported_reason(error: &anyhow::Error) -> Option<UnsupportedReason> {
    error
        .downcast_ref::<DistroUnsupported>()
        .map(|error| error.reason.clone())
}

/// OCI registry response, including the digest header the shared transport
/// does not expose.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ManifestResponse {
    pub status: u16,
    pub digest: Option<String>,
    pub body: Value,
}

/// Header-aware manifest transport. Production sends the OCI index `Accept`
/// value; tests inject a fake.
#[async_trait]
pub trait ManifestHttp: Send + Sync {
    async fn fetch_manifest(&self, url: &str, accept: &str) -> Result<ManifestResponse>;
}

pub struct ReqwestManifestHttp {
    client: reqwest::Client,
}

impl ReqwestManifestHttp {
    pub fn new() -> Result<Self> {
        let client = reqwest::Client::builder()
            .timeout(HTTP_TIMEOUT)
            .user_agent(USER_AGENT)
            .redirect(reqwest::redirect::Policy::limited(10))
            .build()
            .context("build manifest HTTP client")?;
        Ok(Self { client })
    }
}

#[async_trait]
impl ManifestHttp for ReqwestManifestHttp {
    async fn fetch_manifest(&self, url: &str, accept: &str) -> Result<ManifestResponse> {
        let response = self
            .client
            .get(url)
            .header(reqwest::header::ACCEPT, accept)
            .send()
            .await
            .with_context(|| format!("fetch OCI manifest {url}"))?;
        let status = response.status().as_u16();
        let digest = response
            .headers()
            .get("docker-content-digest")
            .and_then(|value| value.to_str().ok())
            .map(str::to_owned);
        let body = if status == 200 {
            response.json::<Value>().await.unwrap_or(Value::Null)
        } else {
            Value::Null
        };
        Ok(ManifestResponse {
            status,
            digest,
            body,
        })
    }
}

/// Distro/OS release source.
pub struct DistroSource {
    http: Arc<dyn RegistryHttp>,
    manifest_http: Arc<dyn ManifestHttp>,
    endoflife_base_url: String,
    rhel_lifecycle_url: String,
    registry_base_url: String,
    reference_date: String,
}

impl DistroSource {
    pub fn new(http: Arc<dyn RegistryHttp>) -> Result<Self> {
        Ok(Self::with_clients(
            http,
            Arc::new(ReqwestManifestHttp::new()?),
        ))
    }

    pub fn with_clients(http: Arc<dyn RegistryHttp>, manifest_http: Arc<dyn ManifestHttp>) -> Self {
        Self {
            http,
            manifest_http,
            endoflife_base_url: DEFAULT_ENDOFLIFE_BASE_URL.to_owned(),
            rhel_lifecycle_url: DEFAULT_RHEL_LIFECYCLE_URL.to_owned(),
            registry_base_url: DEFAULT_REGISTRY_BASE_URL.to_owned(),
            reference_date: chrono::Utc::now().format("%Y-%m-%d").to_string(),
        }
    }

    /// Override endpoints (tests and mirrors).
    pub fn with_endpoints(
        mut self,
        endoflife_base_url: impl Into<String>,
        rhel_lifecycle_url: impl Into<String>,
        registry_base_url: impl Into<String>,
    ) -> Self {
        self.endoflife_base_url = endoflife_base_url.into().trim_end_matches('/').to_owned();
        self.rhel_lifecycle_url = rhel_lifecycle_url.into();
        self.registry_base_url = registry_base_url.into().trim_end_matches('/').to_owned();
        self
    }

    /// Reference date for EOL comparisons (`YYYY-MM-DD`). Tests pin it.
    pub fn with_reference_date(mut self, date: impl Into<String>) -> Self {
        self.reference_date = date.into();
        self
    }

    fn resolve(&self, project: &ProjectRef) -> Result<DistroProject> {
        let purl_type = project.purl_type.trim().to_ascii_lowercase();
        if !is_distro_purl_type(&purl_type) {
            return Err(unsupported(UnsupportedReason::UnknownPurlType(purl_type)));
        }
        resolve_project(project).ok_or_else(|| unsupported(UnsupportedReason::NoVersions))
    }

    async fn lifecycle(&self, distro: DistroProject) -> (Vec<LifecycleEntry>, bool) {
        let mut entries = BTreeMap::new();
        let mut retired = false;
        if distro.rhel {
            for channel in RHEL_CURATED_CHANNELS {
                push_entry(
                    &mut entries,
                    LifecycleEntry {
                        channel: distro_channel(channel.major, channel.edition, None),
                        version: None,
                        eol: channel.eol.map(str::to_owned),
                    },
                );
            }
            if let Ok(Some((plc_entries, is_retired))) = self.redhat_lifecycle().await {
                retired = is_retired;
                for entry in plc_entries {
                    push_entry(&mut entries, entry);
                }
            }
        }
        if let Some(hint) = distro.product_slug {
            // ponytail: the all-products list is fetched per lifecycle call;
            // cache the slug map if ingestion starts calling this in a loop.
            let slug = self.endoflife_slug(hint).await;
            if let Ok(releases) = self.endoflife_releases(&slug).await {
                for entry in releases {
                    push_entry(&mut entries, entry);
                }
            }
        }
        // Every lifecycle version implies its channel (`X.Y` also yields `X`,
        // or the curated dotless Ubuntu channel). Statuses and versions both
        // read this merged view.
        let channels: Vec<(String, Option<String>)> = entries
            .values()
            .map(|entry| (entry.channel.clone(), entry.eol.clone()))
            .collect();
        for (channel, eol) in channels {
            push_entry(
                &mut entries,
                LifecycleEntry {
                    channel,
                    version: None,
                    eol,
                },
            );
        }
        (entries.into_values().collect(), retired)
    }

    async fn redhat_lifecycle(&self) -> Result<Option<(Vec<LifecycleEntry>, bool)>> {
        let payload = self.http.get_json(&self.rhel_lifecycle_url).await?;
        let envelope: PlcEnvelope =
            serde_json::from_value(payload).context("decode Red Hat lifecycle response")?;
        let product = envelope.data.into_iter().find(|product| {
            normalize_name(&product.name) == "red hat enterprise linux"
                || product
                    .former_names
                    .iter()
                    .any(|name| normalize_name(name) == "red hat enterprise linux")
        });
        let Some(product) = product else {
            return Ok(None);
        };
        let mut entries = Vec::new();
        for version in &product.versions {
            let eol = plc_eol(version);
            if let Some(entry) = cycle_entry(&product.slug(), &version.name, eol.clone()) {
                entries.push(entry);
            }
            let mut minors = Vec::new();
            for minor in [
                version.last_minor_release.as_deref(),
                version.final_minor_release.as_deref(),
            ]
            .into_iter()
            .flatten()
            {
                if !minor.is_empty() && !minors.contains(&minor) {
                    minors.push(minor);
                }
            }
            for minor in minors {
                if minor == version.name {
                    continue;
                }
                if let Some(entry) = cycle_entry(&product.slug(), minor, eol.clone()) {
                    entries.push(entry);
                }
            }
        }
        Ok(Some((entries, product.is_retired)))
    }

    async fn endoflife_slug(&self, hint: &str) -> String {
        let url = format!("{}/products", self.endoflife_base_url);
        let Ok(payload) = self.http.get_json(&url).await else {
            return hint.to_owned();
        };
        let Ok(products) = serde_json::from_value::<EolProducts>(payload) else {
            return hint.to_owned();
        };
        let target = normalize_name(hint);
        products
            .result
            .iter()
            .find(|product| {
                normalize_name(&product.name) == target
                    || product
                        .aliases
                        .iter()
                        .any(|alias| normalize_name(alias) == target)
            })
            .map(|product| product.name.clone())
            .unwrap_or(hint.to_owned())
    }

    async fn endoflife_releases(&self, slug: &str) -> Result<Vec<LifecycleEntry>> {
        let url = format!("{}/products/{}", self.endoflife_base_url, slug);
        let payload = self.http.get_json(&url).await?;
        let envelope: EolEnvelope =
            serde_json::from_value(payload).context("decode endoflife.date response")?;
        let releases = if envelope.result.releases.is_empty() {
            envelope.result.release_cycles
        } else {
            envelope.result.releases
        };
        let mut entries = Vec::new();
        for release in releases {
            let date = release.eol_from.as_deref().and_then(date_prefix);
            let eol: Option<String> = if release.is_eol == Some(true) {
                Some(date.unwrap_or_default().to_owned())
            } else {
                date.map(str::to_owned)
            };
            if let Some(entry) = cycle_entry(slug, &release.name, eol.clone()) {
                entries.push(entry);
            }
            if let Some(latest) = release.latest
                && !latest.name.is_empty()
                && latest.name != release.name
                && let Some(entry) = cycle_entry(slug, &latest.name, eol)
            {
                entries.push(entry);
            }
        }
        Ok(entries)
    }

    fn version_info(&self, entry: LifecycleEntry) -> VersionInfo {
        let eol = entry.eol.unwrap_or_default();
        let deprecated = !eol.is_empty() && eol <= self.reference_date;
        VersionInfo {
            raw: entry
                .version
                .clone()
                .unwrap_or_else(|| entry.channel.clone()),
            version: entry.version.unwrap_or(entry.channel),
            deprecated,
            reason: if eol.is_empty() {
                String::new()
            } else {
                format!("eol {eol}")
            },
        }
    }
}

#[async_trait]
impl ReleaseSource for DistroSource {
    fn name(&self) -> &'static str {
        "distro"
    }

    fn capabilities(&self) -> SourceCapabilities {
        SourceCapabilities {
            versions: true,
            artifacts: true,
            statuses: true,
            project_meta: true,
        }
    }

    async fn versions(&self, project: &ProjectRef) -> Result<Vec<VersionInfo>> {
        let distro = self.resolve(project)?;
        let (entries, _) = self.lifecycle(distro).await;
        if entries.is_empty() {
            return Err(unsupported(UnsupportedReason::NoVersions));
        }
        let mut versions: Vec<VersionInfo> = entries
            .into_iter()
            .map(|entry| self.version_info(entry))
            .collect();
        versions.sort_by(|left, right| {
            compare_channel_text(&left.version, &right.version)
                .then_with(|| left.version.cmp(&right.version))
        });
        Ok(versions)
    }

    async fn artifacts(
        &self,
        project: &ProjectRef,
        version: &VersionInfo,
    ) -> Result<Vec<ArtifactInfo>> {
        let distro = self.resolve(project)?;
        if !distro.rhel {
            return Err(unsupported(UnsupportedReason::NoArtifacts));
        }
        let (major, stream, arch) = ubi_target(&version.version)?;
        let url = format!(
            "{}/v2/ubi{major}/ubi/manifests/{stream}",
            self.registry_base_url
        );
        let response = self
            .manifest_http
            .fetch_manifest(&url, OCI_INDEX_ACCEPT)
            .await?;
        match response.status {
            200 => {}
            401 | 403 => {
                return Err(unsupported(UnsupportedReason::Unavailable(
                    "redhat registry requires authentication",
                )));
            }
            _ => return Err(unsupported(UnsupportedReason::NoArtifacts)),
        }
        let digest = match arch.as_deref() {
            Some(arch) => select_manifest(&response.body, Some(arch))
                .or_else(|| valid_digest(response.digest.as_deref())),
            None => valid_digest(response.digest.as_deref())
                .or_else(|| select_manifest(&response.body, None)),
        };
        let Some(digest) = digest else {
            return Err(unsupported(UnsupportedReason::NoArtifacts));
        };
        let sha256 = digest.strip_prefix("sha256:").unwrap_or(&digest).to_owned();
        if !is_sha256_hex(&sha256) {
            return Err(unsupported(UnsupportedReason::NoArtifacts));
        }
        Ok(vec![ArtifactInfo {
            file_name: format!("ubi{major}-ubi-{stream}.oci.json"),
            url: format!(
                "{}/v2/ubi{major}/ubi/manifests/{digest}",
                self.registry_base_url
            ),
            sha256: Some(sha256),
            size: manifest_size(&response.body, &digest),
            mime_type: Some(
                response
                    .body
                    .get("mediaType")
                    .and_then(Value::as_str)
                    .unwrap_or(OCI_INDEX_ACCEPT)
                    .to_owned(),
            ),
        }])
    }

    async fn statuses(
        &self,
        project: &ProjectRef,
        version: &VersionInfo,
    ) -> Result<Vec<StatusInfo>> {
        let distro = self.resolve(project)?;
        let (entries, retired) = self.lifecycle(distro).await;
        if retired {
            return Ok(vec![StatusInfo {
                status: "archived".to_owned(),
                kind: Some("eol".to_owned()),
                reason: "product retired".to_owned(),
            }]);
        }
        let target = version.version.trim();
        let Some(entry) = entries
            .iter()
            .find(|entry| entry_matches(entry, target, distro.product))
        else {
            return Ok(Vec::new());
        };
        let Some(eol) = entry.eol.as_deref() else {
            return Ok(Vec::new());
        };
        let passed = eol.is_empty() || eol <= self.reference_date.as_str();
        if !passed {
            return Ok(Vec::new());
        }
        Ok(vec![StatusInfo {
            status: "deprecated".to_owned(),
            kind: Some("eol".to_owned()),
            reason: if eol.is_empty() {
                "eol".to_owned()
            } else {
                format!("eol {eol}")
            },
        }])
    }

    async fn project_meta(&self, project: &ProjectRef) -> Result<Value> {
        let distro = self.resolve(project)?;
        Ok(json!({
            "source": "distro",
            "vendor": distro.vendor,
            "product": distro.product,
            "project": distro.project,
            "purlType": project.purl_type.trim().to_ascii_lowercase(),
            "lifecycle": distro.lifecycle_url,
            "target": {"os": "linux"},
        }))
    }
}

#[derive(Debug, Deserialize)]
struct PlcEnvelope {
    #[serde(default)]
    data: Vec<PlcProduct>,
}

#[derive(Debug, Deserialize)]
struct PlcProduct {
    #[serde(default)]
    name: String,
    #[serde(default)]
    former_names: Vec<String>,
    #[serde(default)]
    is_retired: bool,
    #[serde(default)]
    versions: Vec<PlcVersion>,
}

impl PlcProduct {
    fn slug(&self) -> String {
        normalize_name(&self.name).replace(' ', "-")
    }
}

#[derive(Debug, Deserialize)]
struct PlcVersion {
    #[serde(default)]
    name: String,
    #[serde(default, rename = "type")]
    kind: String,
    #[serde(default)]
    final_minor_release: Option<String>,
    #[serde(default)]
    last_minor_release: Option<String>,
    #[serde(default)]
    phases: Vec<PlcPhase>,
}

#[derive(Debug, Deserialize)]
struct PlcPhase {
    #[serde(default)]
    name: String,
    #[serde(default)]
    end_date: Option<String>,
}

fn plc_eol(version: &PlcVersion) -> Option<String> {
    let phase_date = |wanted: &str| {
        version
            .phases
            .iter()
            .find(|phase| phase.name.eq_ignore_ascii_case(wanted))
            .and_then(|phase| phase.end_date.as_deref())
            .and_then(date_prefix)
    };
    if let Some(date) = phase_date("Maintenance support") {
        return Some(date.to_owned());
    }
    if let Some(date) = phase_date("End of Life") {
        return Some(date.to_owned());
    }
    if version.kind.to_ascii_lowercase().contains("end of life") {
        return Some(String::new());
    }
    let mut dates: Vec<&str> = version
        .phases
        .iter()
        .filter(|phase| !phase.name.eq_ignore_ascii_case("general availability"))
        .filter_map(|phase| phase.end_date.as_deref())
        .filter_map(date_prefix)
        .collect();
    dates.sort_unstable();
    dates.last().map(|date| (*date).to_owned())
}

#[derive(Debug, Default, Deserialize)]
struct EolEnvelope {
    #[serde(default)]
    result: EolProduct,
}

#[derive(Debug, Default, Deserialize)]
struct EolProduct {
    #[serde(default)]
    releases: Vec<EolRelease>,
    #[serde(default, rename = "releaseCycles")]
    release_cycles: Vec<EolRelease>,
}

#[derive(Debug, Default, Deserialize)]
struct EolRelease {
    #[serde(default)]
    name: String,
    #[serde(default, rename = "isEol")]
    is_eol: Option<bool>,
    #[serde(default, rename = "eolFrom")]
    eol_from: Option<String>,
    #[serde(default)]
    latest: Option<EolLatest>,
}

#[derive(Debug, Default, Deserialize)]
struct EolLatest {
    #[serde(default)]
    name: String,
}

#[derive(Debug, Default, Deserialize)]
struct EolProducts {
    #[serde(default)]
    result: Vec<EolProductSummary>,
}

#[derive(Debug, Default, Deserialize)]
struct EolProductSummary {
    #[serde(default)]
    name: String,
    #[serde(default)]
    aliases: Vec<String>,
}

fn normalize_name(raw: &str) -> String {
    raw.trim()
        .to_ascii_lowercase()
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
}

fn date_prefix(raw: &str) -> Option<&str> {
    let date = raw.get(..10)?;
    let valid = date.bytes().enumerate().all(|(index, byte)| match index {
        4 | 7 => byte == b'-',
        _ => byte.is_ascii_digit(),
    });
    valid.then_some(date)
}

/// Split a lifecycle cycle name into channel and version. `X.Y` is a version
/// under channel `X`; Ubuntu point releases are their own dotless channel
/// (`20.04` -> `20-04`) because the channel grammar forbids dots.
fn cycle_entry(slug: &str, name: &str, eol: Option<String>) -> Option<LifecycleEntry> {
    let name = name.trim();
    if name.is_empty() {
        return None;
    }
    if name.contains('.') {
        let channel = if slug == "ubuntu" {
            ubuntu_channel(name)
        } else {
            name.split('.').next().unwrap_or(name).to_owned()
        };
        return Some(LifecycleEntry {
            channel,
            version: Some(name.to_owned()),
            eol,
        });
    }
    Some(LifecycleEntry {
        channel: distro_channel(name, None, None),
        version: None,
        eol,
    })
}

fn push_entry(
    entries: &mut BTreeMap<(String, Option<String>), LifecycleEntry>,
    entry: LifecycleEntry,
) {
    match entries.entry((entry.channel.clone(), entry.version.clone())) {
        std::collections::btree_map::Entry::Occupied(mut occupied) => {
            let has_date = entry.eol.as_deref().is_some_and(|eol| !eol.is_empty());
            if has_date || occupied.get().eol.is_none() {
                occupied.get_mut().eol = entry.eol;
            }
        }
        std::collections::btree_map::Entry::Vacant(vacant) => {
            vacant.insert(entry);
        }
    }
}

fn entry_matches(entry: &LifecycleEntry, target: &str, product: &str) -> bool {
    if entry.version.as_deref() == Some(target) || entry.channel == target {
        return true;
    }
    if let Some((major, _)) = target.split_once('.') {
        return if product == "Ubuntu" {
            entry.channel == ubuntu_channel(target)
        } else {
            entry.channel == major
        };
    }
    false
}

/// Ubuntu point releases name their own dotless channel (`20.04` -> `20-04`);
/// patch releases belong to the matching minor channel.
fn ubuntu_channel(name: &str) -> String {
    let mut parts = name.split('.');
    let major = parts.next().unwrap_or(name);
    match parts.next() {
        Some(minor) => distro_channel(&format!("{major}.{minor}"), None, None),
        None => major.to_owned(),
    }
}

/// Numeric-aware ordering for channel and version text (`9` < `10`).
fn compare_channel_text(left: &str, right: &str) -> Ordering {
    let mut left_parts = left.split('.');
    let mut right_parts = right.split('.');
    loop {
        match (left_parts.next(), right_parts.next()) {
            (None, None) => return Ordering::Equal,
            (None, Some(_)) => return Ordering::Less,
            (Some(_), None) => return Ordering::Greater,
            (Some(left), Some(right)) => {
                let ordering = match (left.parse::<u64>(), right.parse::<u64>()) {
                    (Ok(left), Ok(right)) => left.cmp(&right),
                    _ => left.cmp(right),
                };
                if ordering != Ordering::Equal {
                    return ordering;
                }
            }
        }
    }
}

fn ubi_target(version: &str) -> Result<(String, String, Option<String>)> {
    let raw = version.trim();
    if raw.is_empty() {
        return Err(unsupported(UnsupportedReason::NoArtifacts));
    }
    let tokens: Vec<&str> = raw.split('-').filter(|token| !token.is_empty()).collect();
    let Some(first) = tokens.first() else {
        return Err(unsupported(UnsupportedReason::NoArtifacts));
    };
    let major = first.split('.').next().unwrap_or(first);
    if major.is_empty() || major.len() > 2 || !major.bytes().all(|byte| byte.is_ascii_digit()) {
        return Err(unsupported(UnsupportedReason::NoArtifacts));
    }
    let arch = tokens
        .iter()
        .skip(1)
        .find(|token| RHEL_ARCHES.contains(token))
        .map(|token| (*token).to_owned());
    let stream = if raw
        .strip_prefix(major)
        .is_some_and(|rest| rest.starts_with('.'))
    {
        let end = raw.find('-').unwrap_or(raw.len());
        &raw[..end]
    } else {
        major
    };
    let valid = !stream.is_empty()
        && stream
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'));
    if !valid {
        return Err(unsupported(UnsupportedReason::NoArtifacts));
    }
    Ok((major.to_owned(), stream.to_owned(), arch))
}

fn valid_digest(digest: Option<&str>) -> Option<String> {
    let digest = digest?.trim();
    let hex = digest.strip_prefix("sha256:")?;
    is_sha256_hex(hex).then(|| digest.to_owned())
}

fn is_sha256_hex(value: &str) -> bool {
    value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit())
}

fn select_manifest(body: &Value, arch: Option<&str>) -> Option<String> {
    let manifests = body.get("manifests")?.as_array()?;
    let wanted = match arch {
        Some("aarch64") => "arm64",
        Some("x86_64") | None => "amd64",
        Some(arch) => arch,
    };
    let matching = manifests.iter().find(|manifest| {
        manifest
            .get("platform")
            .and_then(|platform| platform.get("architecture"))
            .and_then(Value::as_str)
            .is_some_and(|value| value == wanted || (wanted == "amd64" && value == "x86_64"))
            && manifest
                .get("platform")
                .and_then(|platform| platform.get("os"))
                .and_then(Value::as_str)
                .is_none_or(|os| os == "linux")
    });
    let manifest = matching.or_else(|| manifests.first());
    valid_digest(
        manifest
            .and_then(|manifest| manifest.get("digest"))
            .and_then(Value::as_str),
    )
}

fn manifest_size(body: &Value, digest: &str) -> Option<u64> {
    body.get("manifests")?
        .as_array()?
        .iter()
        .find(|manifest| manifest.get("digest").and_then(Value::as_str) == Some(digest))
        .and_then(|manifest| manifest.get("size"))
        .and_then(Value::as_u64)
}