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

johnandersen777.bsky.social/vuln-notif

0
0
main
278 lines · 8.7 KB Raw History
//! PyPI source: full release history with file-level artifact metadata.
//!
//! Name lookups use PEP 503 normalization (the simple-index name rule); the
//! display name reported by the JSON API is preserved in metadata. The JSON
//! API reports every release key, including releases whose files were deleted
//! (empty artifact lists). A release is yanked when every file is yanked,
//! matching PyPI's per-file PEP 592 semantics. Declared digests, sizes, and
//! yank reasons come from the release file entries; nothing is downloaded.

use std::collections::BTreeMap;
use std::sync::{Arc, OnceLock};

use anyhow::{Result, anyhow};
use async_trait::async_trait;
use regex::Regex;
use serde_json::{Map, Value, json};

use crate::release::http::RegistryHttp;
use crate::release::source::{
    ArtifactInfo, ProjectRef, ReleaseSource, SourceCapabilities, StatusInfo, VersionInfo,
};
use crate::release::versioning::{VersionScheme, compare, normalize_version};

pub const API_BASE: &str = "https://pypi.org/pypi";
pub const SIMPLE_BASE: &str = "https://pypi.org/simple";

/// PEP 503 project-name normalization: runs of `-`, `_`, and `.` collapse to
/// a single `-`, then the name is lowercased.
pub fn pep503_name(name: &str) -> String {
    static SEPARATORS: OnceLock<Regex> = OnceLock::new();
    let separators =
        SEPARATORS.get_or_init(|| Regex::new(r"[-_.]+").expect("static PEP 503 regex"));
    separators.replace_all(name, "-").to_lowercase()
}

pub struct PyPiSource {
    http: Arc<dyn RegistryHttp>,
}

impl PyPiSource {
    pub fn new(http: Arc<dyn RegistryHttp>) -> Self {
        Self { http }
    }

    async fn project_json(&self, project: &ProjectRef) -> Result<Value> {
        let url = format!("{API_BASE}/{}/json", pep503_name(&project.name));
        self.http.get_json(&url).await
    }
}

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

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

    async fn versions(&self, project: &ProjectRef) -> Result<Vec<VersionInfo>> {
        let payload = self.project_json(project).await?;
        version_infos(&payload)
    }

    async fn artifacts(
        &self,
        project: &ProjectRef,
        version: &VersionInfo,
    ) -> Result<Vec<ArtifactInfo>> {
        let payload = self.project_json(project).await?;
        Ok(artifacts_for(&payload, &version.raw))
    }

    async fn statuses(
        &self,
        project: &ProjectRef,
        version: &VersionInfo,
    ) -> Result<Vec<StatusInfo>> {
        let payload = self.project_json(project).await?;
        Ok(statuses_for(&payload, &version.raw))
    }

    async fn project_meta(&self, project: &ProjectRef) -> Result<Value> {
        let payload = self.project_json(project).await?;
        Ok(project_meta_value(&payload, &project.name))
    }
}

fn truthy(value: Option<&Value>) -> bool {
    match value {
        Some(Value::Bool(value)) => *value,
        Some(Value::String(value)) => !value.is_empty(),
        Some(Value::Number(number)) => number.as_f64().is_some_and(|value| value != 0.0),
        Some(Value::Array(values)) => !values.is_empty(),
        Some(Value::Object(values)) => !values.is_empty(),
        Some(Value::Null) | None => false,
    }
}

fn text_field<'a>(value: &'a Value, key: &str) -> Option<&'a str> {
    value
        .get(key)
        .and_then(Value::as_str)
        .filter(|text| !text.is_empty())
}

fn release_files<'a>(payload: &'a Value, raw: &str) -> &'a [Value] {
    payload
        .get("releases")
        .and_then(Value::as_object)
        .and_then(|releases| releases.get(raw))
        .and_then(Value::as_array)
        .map(Vec::as_slice)
        .unwrap_or(&[])
}

fn release_yanked(files: &[Value]) -> bool {
    !files.is_empty() && files.iter().all(|file| truthy(file.get("yanked")))
}

fn yanked_reason(files: &[Value]) -> String {
    files
        .iter()
        .filter(|file| truthy(file.get("yanked")))
        .find_map(|file| text_field(file, "yanked_reason"))
        .unwrap_or_default()
        .to_owned()
}

fn status_kind(reason: &str) -> &'static str {
    let reason = reason.to_ascii_lowercase();
    if ["security", "malware", "cve", "vulnerab"]
        .iter()
        .any(|needle| reason.contains(needle))
    {
        "security"
    } else {
        "registry"
    }
}

fn version_infos(payload: &Value) -> Result<Vec<VersionInfo>> {
    let releases = payload
        .get("releases")
        .and_then(Value::as_object)
        .ok_or_else(|| anyhow!("pypi payload missing releases"))?;
    let mut versions = releases
        .iter()
        .map(|(raw, files)| {
            let files = files.as_array().map(Vec::as_slice).unwrap_or(&[]);
            let yanked = release_yanked(files);
            VersionInfo {
                raw: raw.clone(),
                version: normalize_version(raw).unwrap_or_else(|| raw.clone()),
                deprecated: yanked,
                reason: if yanked {
                    yanked_reason(files)
                } else {
                    String::new()
                },
            }
        })
        .collect::<Vec<_>>();
    versions.sort_by(|left, right| {
        compare(VersionScheme::Pep440, &left.raw, &right.raw).then_with(|| left.raw.cmp(&right.raw))
    });
    Ok(versions)
}

fn artifacts_for(payload: &Value, raw: &str) -> Vec<ArtifactInfo> {
    let mut by_url = BTreeMap::new();
    for file in release_files(payload, raw) {
        let Some(url) = text_field(file, "url") else {
            continue;
        };
        let file_name = text_field(file, "filename")
            .map(str::to_owned)
            .unwrap_or_else(|| url.rsplit('/').next().unwrap_or(url).to_owned());
        let sha256 = file
            .get("digests")
            .and_then(|digests| digests.get("sha256"))
            .and_then(Value::as_str)
            .filter(|digest| !digest.is_empty())
            .map(str::to_owned);
        let size = file
            .get("size")
            .and_then(Value::as_u64)
            .filter(|size| *size > 0);
        by_url.insert(
            url.to_owned(),
            ArtifactInfo {
                file_name: file_name.clone(),
                url: url.to_owned(),
                sha256,
                size,
                mime_type: Some(mime_for(&file_name).to_owned()),
            },
        );
    }
    by_url.into_values().collect()
}

fn statuses_for(payload: &Value, raw: &str) -> Vec<StatusInfo> {
    let files = release_files(payload, raw);
    if !release_yanked(files) {
        return Vec::new();
    }
    let reason = yanked_reason(files);
    vec![StatusInfo {
        status: "yanked".to_owned(),
        kind: Some(status_kind(&reason).to_owned()),
        reason,
    }]
}

fn project_meta_value(payload: &Value, requested: &str) -> Value {
    let info = payload.get("info").unwrap_or(&Value::Null);
    let mut meta = Map::new();
    insert_text(
        &mut meta,
        "name",
        Some(text_field(info, "name").unwrap_or(requested)),
    );
    insert_text(&mut meta, "description", text_field(info, "summary"));
    insert_text(
        &mut meta,
        "homepage",
        text_field(info, "home_page").or_else(|| project_url(info, &["Homepage", "Home"])),
    );
    insert_text(
        &mut meta,
        "repository",
        project_url(info, &["Source", "Repository", "Code", "Source Code"]),
    );
    insert_text(&mut meta, "license", text_field(info, "license"));
    meta.insert(
        "simple_index".to_owned(),
        json!(format!("{SIMPLE_BASE}/{}/", pep503_name(requested))),
    );
    Value::Object(meta)
}

fn project_url<'a>(info: &'a Value, keys: &[&str]) -> Option<&'a str> {
    let urls = info.get("project_urls")?.as_object()?;
    keys.iter().find_map(|key| {
        urls.iter()
            .find(|(name, _)| name.eq_ignore_ascii_case(key))
            .and_then(|(_, value)| value.as_str())
            .filter(|value| !value.is_empty())
    })
}

fn insert_text(meta: &mut Map<String, Value>, key: &str, value: Option<&str>) {
    if let Some(value) = value.filter(|value| !value.is_empty()) {
        meta.insert(key.to_owned(), Value::String(value.to_owned()));
    }
}

fn mime_for(file_name: &str) -> &'static str {
    let lower = file_name.to_ascii_lowercase();
    if lower.ends_with(".tar.gz") || lower.ends_with(".tgz") {
        "application/gzip"
    } else if lower.ends_with(".tar.bz2") {
        "application/x-bzip2"
    } else if lower.ends_with(".tar.xz") {
        "application/x-xz"
    } else if lower.ends_with(".whl") || lower.ends_with(".zip") || lower.ends_with(".egg") {
        "application/zip"
    } else {
        "application/octet-stream"
    }
}