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

johnandersen777.bsky.social/vuln-notif

0
0
main
510 lines · 15.7 KB Raw History
//! Release artifact parsing and per-ecosystem registry fetchers.
//!
//! Purl parsing and selection,
//! version normalization, and the npm/PyPI/cargo/gem/Maven/NuGet/Go fetchers.
//! Declared digests and sizes are trusted when the registry provides them;
//! otherwise the artifact is downloaded once, hashed, and discarded.

use std::sync::OnceLock;

use anyhow::{Context, Result, anyhow, bail};
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode};
use regex::Regex;
use roxmltree::Document;
use serde_json::Value;

use crate::constants::{DEPSDEV_URL, release_priority, release_system};
use crate::records::{cidv1_raw, sha256_hex};
use crate::release::http::RegistryHttp;

/// `urllib.parse.quote(value)` (safe `/`).
const QUOTE: &AsciiSet = &NON_ALPHANUMERIC
    .remove(b'-')
    .remove(b'.')
    .remove(b'_')
    .remove(b'~')
    .remove(b'/');

/// `urllib.parse.quote(value, safe='@/')`.
const QUOTE_AT: &AsciiSet = &QUOTE.remove(b'@');

/// `urllib.parse.quote(value, safe='')`.
const QUOTE_NONE: &AsciiSet = &NON_ALPHANUMERIC
    .remove(b'-')
    .remove(b'.')
    .remove(b'_')
    .remove(b'~');

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Purl {
    pub r#type: String,
    pub name: String,
    pub raw: String,
}

#[derive(Debug, Clone)]
pub struct Artifact {
    pub file_name: String,
    pub url: String,
    pub sha256: String,
    pub size: u64,
    pub mime_type: String,
}

impl Artifact {
    /// Raw-codec CIDv1 over the artifact's sha256 digest.
    pub fn cid(&self) -> String {
        cidv1_raw(&self.sha256)
    }
}

fn quote(value: &str, set: &'static AsciiSet) -> String {
    utf8_percent_encode(value, set).to_string()
}

fn regex(slot: &'static OnceLock<Regex>, pattern: &'static str) -> &'static Regex {
    slot.get_or_init(|| Regex::new(pattern).expect("static release regex"))
}

/// Map a registry version onto the `software.release.version` grammar.
pub fn normalize_version(raw: &str) -> Option<String> {
    static SEPARATORS: OnceLock<Regex> = OnceLock::new();
    static INVALID: OnceLock<Regex> = OnceLock::new();
    static DASHES: OnceLock<Regex> = OnceLock::new();
    static GRAMMAR: OnceLock<Regex> = OnceLock::new();

    if raw.is_empty() || raw.contains(':') || raw.contains('!') {
        return None;
    }
    let value = raw.trim().to_lowercase();
    let value = regex(&SEPARATORS, r"[+_~\s^=()\[\],;/]+").replace_all(&value, "-");
    let value = regex(&INVALID, r"[^a-z0-9.-]+").replace_all(&value, "-");
    let value = regex(&DASHES, r"-{2,}").replace_all(&value, "-");
    let value = value.trim_matches(|character| character == '-' || character == '.');
    if value.is_empty() || value.chars().count() > 64 {
        return None;
    }
    regex(&GRAMMAR, r"^[a-z0-9]+(?:[.-][a-z0-9]+)*$")
        .is_match(value)
        .then(|| value.to_owned())
}

/// Parse a purl into `(type, name)` for the seven release ecosystems.
pub fn parse_purl(raw: &str) -> Option<Purl> {
    let body = raw.strip_prefix("pkg:")?;
    let body = body.split('#').next().unwrap_or("");
    let body = body.split('?').next().unwrap_or("");
    let (purl_type, rest) = body.split_once('/')?;
    release_system(purl_type)?;
    let rest = match rest.rsplit_once('@') {
        Some((head, _version)) => head,
        None => rest,
    };
    let name = percent_decode_str(rest).decode_utf8_lossy().into_owned();
    if name.is_empty() {
        return None;
    }
    let name = if purl_type == "maven" {
        name.replacen('/', ":", 1)
    } else {
        name
    };
    Some(Purl {
        r#type: purl_type.to_owned(),
        name,
        raw: raw.to_owned(),
    })
}

/// Pick the preferred purl: leaf name match first, then ecosystem priority.
pub fn choose_purl(raw_purls: &[String], product: &str) -> Option<Purl> {
    let product_lower = product.to_lowercase().replace('_', "-");
    let candidates = raw_purls
        .iter()
        .filter_map(|raw| parse_purl(raw))
        .collect::<Vec<_>>();
    candidates.into_iter().min_by(|left, right| {
        let key = |purl: &Purl| {
            let leaf = purl
                .name
                .rsplit('/')
                .next()
                .unwrap_or("")
                .rsplit(':')
                .next()
                .unwrap_or("")
                .to_lowercase();
            let name_match = u8::from(leaf != product_lower);
            (
                name_match,
                release_priority(&purl.r#type).unwrap_or(u8::MAX),
                purl.raw.clone(),
            )
        };
        key(left).cmp(&key(right))
    })
}

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 absent_or_empty(value: Option<&Value>) -> bool {
    !json_truthy(value)
}

fn string_field<'a>(value: &'a Value, key: &str) -> Option<&'a str> {
    value.get(key).and_then(Value::as_str)
}

fn payload_size(value: Option<&Value>) -> u64 {
    match value {
        Some(Value::Number(number)) => number
            .as_u64()
            .or_else(|| number.as_i64().map(|value| value.max(0) as u64))
            .or_else(|| number.as_f64().map(|value| value.max(0.0) as u64))
            .unwrap_or(0),
        Some(Value::String(value)) => value.parse::<i64>().map(|v| v.max(0) as u64).unwrap_or(0),
        _ => 0,
    }
}

fn artifact_from_payload(
    file_name: &str,
    url: &str,
    sha256: &str,
    size: u64,
    mime_type: &str,
) -> Result<Artifact> {
    if sha256.is_empty() || size == 0 {
        bail!("missing artifact digest/size: {url}");
    }
    Ok(Artifact {
        file_name: file_name.to_owned(),
        url: url.to_owned(),
        sha256: sha256.to_owned(),
        size,
        mime_type: mime_type.to_owned(),
    })
}

async fn download_artifact(
    http: &dyn RegistryHttp,
    url: &str,
    file_name: &str,
    mime_type: &str,
) -> Result<Artifact> {
    let bytes = http.download(url).await?;
    if bytes.is_empty() {
        bail!("empty artifact: {url}");
    }
    Ok(Artifact {
        file_name: file_name.to_owned(),
        url: url.to_owned(),
        sha256: sha256_hex(&bytes),
        size: bytes.len() as u64,
        mime_type: mime_type.to_owned(),
    })
}

pub async fn npm_artifact(
    http: &dyn RegistryHttp,
    name: &str,
    raw_version: &str,
) -> Result<Artifact> {
    let url = format!("https://registry.npmjs.org/{}", quote(name, QUOTE_AT));
    let meta = http.get_json(&url).await?;
    let tarball = meta
        .get("versions")
        .and_then(|versions| versions.get(raw_version))
        .and_then(|version| version.get("dist"))
        .and_then(|dist| dist.get("tarball"))
        .and_then(Value::as_str)
        .filter(|tarball| !tarball.is_empty())
        .ok_or_else(|| anyhow!("npm artifact missing: {name}@{raw_version}"))?;
    let file_name = tarball.rsplit('/').next().unwrap_or(tarball);
    download_artifact(http, tarball, file_name, "application/gzip").await
}

pub async fn pypi_artifact(
    http: &dyn RegistryHttp,
    name: &str,
    raw_version: &str,
) -> Result<Artifact> {
    let url = format!("https://pypi.org/pypi/{}/json", quote(name, QUOTE));
    let meta = http.get_json(&url).await?;
    let mut files = meta
        .get("releases")
        .and_then(|releases| releases.get(raw_version))
        .and_then(Value::as_array)
        .map(|files| {
            files
                .iter()
                .filter(|item| absent_or_empty(item.get("yanked")))
                .filter(|item| !absent_or_empty(item.get("digests").and_then(|d| d.get("sha256"))))
                .cloned()
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();
    if files.is_empty() {
        bail!("pypi artifact missing: {name}@{raw_version}");
    }
    files.sort_by_key(|item| u8::from(string_field(item, "packagetype") != Some("bdist_wheel")));
    let item = &files[0];
    let file_name = string_field(item, "filename")
        .ok_or_else(|| anyhow!("pypi artifact missing filename: {name}@{raw_version}"))?;
    let file_url = string_field(item, "url")
        .ok_or_else(|| anyhow!("pypi artifact missing url: {name}@{raw_version}"))?;
    let sha256 = item
        .get("digests")
        .and_then(|digests| digests.get("sha256"))
        .and_then(Value::as_str)
        .unwrap_or("");
    artifact_from_payload(
        file_name,
        file_url,
        sha256,
        payload_size(item.get("size")),
        "application/zip",
    )
}

pub async fn cargo_artifact(
    http: &dyn RegistryHttp,
    name: &str,
    raw_version: &str,
) -> Result<Artifact> {
    let url = format!("https://crates.io/api/v1/crates/{}", quote(name, QUOTE));
    let meta = http.get_json(&url).await?;
    let item = meta
        .get("versions")
        .and_then(Value::as_array)
        .and_then(|versions| {
            versions
                .iter()
                .find(|version| string_field(version, "num") == Some(raw_version))
        });
    let item = match item {
        Some(item) if absent_or_empty(item.get("yanked")) => item,
        _ => bail!("crates artifact missing: {name}@{raw_version}"),
    };
    let url = format!(
        "https://static.crates.io/crates/{}/{}-{}.crate",
        quote(name, QUOTE),
        quote(name, QUOTE),
        quote(raw_version, QUOTE)
    );
    artifact_from_payload(
        &format!("{name}-{raw_version}.crate"),
        &url,
        string_field(item, "checksum").unwrap_or(""),
        payload_size(item.get("crate_size")),
        "application/gzip",
    )
}

pub async fn gem_artifact(
    http: &dyn RegistryHttp,
    name: &str,
    raw_version: &str,
) -> Result<Artifact> {
    let url = format!(
        "https://rubygems.org/api/v1/versions/{}.json",
        quote(name, QUOTE)
    );
    let meta = http.get_json(&url).await?;
    let versions = meta
        .as_array()
        .ok_or_else(|| anyhow!("rubygems versions payload is not an array"))?;
    let item = versions
        .iter()
        .find(|version| string_field(version, "number") == Some(raw_version));
    let item = match item {
        Some(item) if absent_or_empty(item.get("yanked")) => item,
        _ => bail!("rubygems artifact missing: {name}@{raw_version}"),
    };
    let url = string_field(item, "gem_uri").unwrap_or("");
    let mut size = payload_size(item.get("size"));
    if size == 0 && !url.is_empty() {
        size = http.head_size(url).await?;
    }
    artifact_from_payload(
        url.rsplit('/').next().unwrap_or(""),
        url,
        string_field(item, "sha").unwrap_or(""),
        size,
        "application/gzip",
    )
}

pub async fn maven_artifact(
    http: &dyn RegistryHttp,
    name: &str,
    raw_version: &str,
) -> Result<Artifact> {
    let (group, artifact) = name
        .split_once(':')
        .ok_or_else(|| anyhow!("maven coordinate missing group: {name}"))?;
    let base = format!(
        "https://repo1.maven.org/maven2/{}/{}",
        group.replace('.', "/"),
        artifact
    );
    // Metadata is advisory: missing metadata still falls through to the
    // authoritative direct URL. Malformed XML, however, is a real error.
    if let Ok(metadata) = http.get_text(&format!("{base}/maven-metadata.xml")).await {
        let document = Document::parse(&metadata).context("parse maven-metadata.xml")?;
        let root = document.root_element();
        let versions = root
            .children()
            .filter(|node| node.has_tag_name("versioning"))
            .flat_map(|node| node.children())
            .filter(|node| node.has_tag_name("versions"))
            .flat_map(|node| node.children())
            .filter(|node| node.has_tag_name("version"))
            .filter_map(|node| node.text())
            .collect::<Vec<_>>();
        if !versions.is_empty() && !versions.contains(&raw_version) {
            bail!("maven version missing: {name}@{raw_version}");
        }
    }
    let url = format!(
        "{base}/{}/{}-{}.jar",
        quote(raw_version, QUOTE),
        quote(artifact, QUOTE),
        quote(raw_version, QUOTE)
    );
    download_artifact(
        http,
        &url,
        &format!("{artifact}-{raw_version}.jar"),
        "application/java-archive",
    )
    .await
}

pub async fn nuget_artifact(
    http: &dyn RegistryHttp,
    name: &str,
    raw_version: &str,
) -> Result<Artifact> {
    let lower = name.to_lowercase();
    let version_lower = raw_version.to_lowercase();
    let url = format!(
        "https://api.nuget.org/v3-flatcontainer/{}/index.json",
        quote(&lower, QUOTE)
    );
    let meta = http.get_json(&url).await?;
    let versions = meta
        .get("versions")
        .and_then(Value::as_array)
        .map(|items| {
            items
                .iter()
                .map(|item| match item {
                    Value::String(value) => value.clone(),
                    other => other.to_string(),
                })
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();
    if !versions.is_empty()
        && !versions
            .iter()
            .any(|version| version.to_lowercase() == version_lower)
    {
        bail!("nuget version missing: {name}@{raw_version}");
    }
    let url = format!(
        "https://api.nuget.org/v3-flatcontainer/{}/{}/{}.{}.nupkg",
        quote(&lower, QUOTE),
        quote(&version_lower, QUOTE),
        quote(&lower, QUOTE),
        quote(&version_lower, QUOTE)
    );
    download_artifact(
        http,
        &url,
        &format!("{lower}.{version_lower}.nupkg"),
        "application/zip",
    )
    .await
}

/// Go module proxy escaping: uppercase letters become `!` + lowercase.
pub fn go_escape(module: &str) -> String {
    let mut escaped = String::with_capacity(module.len());
    for character in module.chars() {
        if character.is_uppercase() {
            escaped.push('!');
            escaped.extend(character.to_lowercase());
        } else {
            escaped.push(character);
        }
    }
    escaped
}

pub async fn golang_artifact(
    http: &dyn RegistryHttp,
    name: &str,
    raw_version: &str,
) -> Result<Artifact> {
    let url = format!(
        "https://proxy.golang.org/{}/@v/{}.zip",
        go_escape(name),
        quote(raw_version, QUOTE)
    );
    download_artifact(
        http,
        &url,
        &format!(
            "{}-{raw_version}.zip",
            name.rsplit('/').next().unwrap_or(name)
        ),
        "application/zip",
    )
    .await
}

pub async fn artifact_for(
    http: &dyn RegistryHttp,
    purl: &Purl,
    raw_version: &str,
) -> Result<Artifact> {
    match purl.r#type.as_str() {
        "npm" => npm_artifact(http, &purl.name, raw_version).await,
        "pypi" => pypi_artifact(http, &purl.name, raw_version).await,
        "cargo" => cargo_artifact(http, &purl.name, raw_version).await,
        "gem" => gem_artifact(http, &purl.name, raw_version).await,
        "maven" => maven_artifact(http, &purl.name, raw_version).await,
        "nuget" => nuget_artifact(http, &purl.name, raw_version).await,
        "golang" => golang_artifact(http, &purl.name, raw_version).await,
        other => bail!("unsupported release ecosystem: {other}"),
    }
}

/// deps.dev package versions for one ecosystem package.
pub async fn depsdev_versions(
    http: &dyn RegistryHttp,
    system: &str,
    name: &str,
) -> Result<Vec<Value>> {
    let url = format!(
        "{DEPSDEV_URL}/v3/systems/{system}/packages/{}",
        quote(name, QUOTE_NONE)
    );
    let payload = http.get_json(&url).await?;
    Ok(payload
        .get("versions")
        .and_then(Value::as_array)
        .cloned()
        .unwrap_or_default())
}