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

johnandersen777.bsky.social/vuln-notif

0
0
main
283 lines · 9.3 KB Raw History
//! crates.io source: full version history, crate checksums, and yank state.
//!
//! Every JSON request is throttled to one per second per source instance;
//! crates.io asks crawlers to stay at or below 1 req/s, and the injected
//! [`RegistryHttp`] transport sends the shared user agent. Pagination follows
//! the keyset `meta.next_page` cursor because the API rejects page-number
//! queries. Declared checksums and sizes come from `/versions`, so artifacts
//! never need a download or HEAD.

use std::sync::Arc;
use std::time::Duration;

use anyhow::{Result, anyhow};
use async_trait::async_trait;
use serde_json::{Map, Value};
use tokio::sync::Mutex;
use tokio::time::Instant;

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://crates.io/api/v1/crates";
pub const STATIC_BASE: &str = "https://static.crates.io/crates";
pub const RATE_LIMIT_INTERVAL: Duration = Duration::from_secs(1);
const PER_PAGE: usize = 100;
/// ~100k versions; no real crate comes close.
const MAX_PAGES: usize = 1000;

pub struct CargoSource {
    http: Arc<dyn RegistryHttp>,
    min_interval: Duration,
    last_request: Mutex<Option<Instant>>,
}

impl CargoSource {
    pub fn new(http: Arc<dyn RegistryHttp>) -> Self {
        Self::with_interval(http, RATE_LIMIT_INTERVAL)
    }

    /// Override the per-host interval; tests use [`Duration::ZERO`].
    pub fn with_interval(http: Arc<dyn RegistryHttp>, min_interval: Duration) -> Self {
        Self {
            http,
            min_interval,
            last_request: Mutex::new(None),
        }
    }

    async fn throttle(&self) {
        let mut last_request = self.last_request.lock().await;
        if let Some(previous) = *last_request {
            let elapsed = previous.elapsed();
            if elapsed < self.min_interval {
                tokio::time::sleep(self.min_interval - elapsed).await;
            }
        }
        *last_request = Some(Instant::now());
    }

    async fn get_json(&self, url: &str) -> Result<Value> {
        self.throttle().await;
        self.http.get_json(url).await
    }

    async fn crate_json(&self, name: &str) -> Result<Value> {
        self.get_json(&format!("{API_BASE}/{name}")).await
    }

    async fn raw_versions(&self, name: &str) -> Result<Vec<Value>> {
        let mut all = Vec::new();
        let mut next_page: Option<String> = None;
        for _ in 0..MAX_PAGES {
            let url = match &next_page {
                Some(query) => format!("{API_BASE}/{name}/versions{query}"),
                None => format!("{API_BASE}/{name}/versions?per_page={PER_PAGE}"),
            };
            let payload = self.get_json(&url).await?;
            let versions = payload
                .get("versions")
                .and_then(Value::as_array)
                .ok_or_else(|| {
                    anyhow!("crates versions payload missing versions array for {name}")
                })?;
            let empty = versions.is_empty();
            all.extend(versions.iter().cloned());
            next_page = payload
                .get("meta")
                .and_then(|meta| meta.get("next_page"))
                .and_then(Value::as_str)
                .filter(|next| !next.is_empty())
                .map(str::to_owned);
            if empty || next_page.is_none() {
                break;
            }
        }
        Ok(all)
    }
}

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

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

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

    async fn artifacts(
        &self,
        project: &ProjectRef,
        version: &VersionInfo,
    ) -> Result<Vec<ArtifactInfo>> {
        let entries = self.raw_versions(&project.name).await?;
        let Some(entry) = version_entry(&entries, &version.raw) else {
            return Ok(Vec::new());
        };
        let name = text_field(entry, "crate").unwrap_or(project.name.as_str());
        let file_name = format!("{name}-{}.crate", version.raw);
        let url = format!("{STATIC_BASE}/{name}/{file_name}");
        Ok(vec![ArtifactInfo {
            file_name,
            url,
            sha256: text_field(entry, "checksum").map(str::to_owned),
            size: entry
                .get("crate_size")
                .and_then(Value::as_u64)
                .filter(|size| *size > 0),
            mime_type: Some("application/gzip".to_owned()),
        }])
    }

    async fn statuses(
        &self,
        project: &ProjectRef,
        version: &VersionInfo,
    ) -> Result<Vec<StatusInfo>> {
        let entries = self.raw_versions(&project.name).await?;
        let Some(entry) = version_entry(&entries, &version.raw) else {
            return Ok(Vec::new());
        };
        if !truthy(entry.get("yanked")) {
            return Ok(Vec::new());
        }
        let reason = text_field(entry, "yank_message")
            .unwrap_or_default()
            .to_owned();
        Ok(vec![StatusInfo {
            status: "yanked".to_owned(),
            kind: Some(status_kind(&reason).to_owned()),
            reason,
        }])
    }

    async fn project_meta(&self, project: &ProjectRef) -> Result<Value> {
        let payload = self.crate_json(&project.name).await?;
        let crate_obj = payload.get("crate").unwrap_or(&Value::Null);
        let versions = payload
            .get("versions")
            .and_then(Value::as_array)
            .map(Vec::as_slice)
            .unwrap_or(&[]);
        let newest = text_field(crate_obj, "newest_version")
            .or_else(|| text_field(crate_obj, "max_version"));
        let license = text_field(crate_obj, "license")
            .or_else(|| {
                newest.and_then(|newest| {
                    versions
                        .iter()
                        .find(|version| text_field(version, "num") == Some(newest))
                        .and_then(|version| text_field(version, "license"))
                })
            })
            .or_else(|| {
                versions
                    .iter()
                    .find_map(|version| text_field(version, "license"))
            });

        let mut meta = Map::new();
        insert_text(
            &mut meta,
            "name",
            Some(text_field(crate_obj, "name").unwrap_or(project.name.as_str())),
        );
        insert_text(
            &mut meta,
            "description",
            text_field(crate_obj, "description"),
        );
        insert_text(&mut meta, "homepage", text_field(crate_obj, "homepage"));
        insert_text(&mut meta, "repository", text_field(crate_obj, "repository"));
        insert_text(
            &mut meta,
            "documentation",
            text_field(crate_obj, "documentation"),
        );
        insert_text(&mut meta, "license", license);
        Ok(Value::Object(meta))
    }
}

fn version_entry<'a>(entries: &'a [Value], raw: &str) -> Option<&'a Value> {
    entries
        .iter()
        .find(|entry| text_field(entry, "num") == Some(raw))
}

fn version_infos(entries: &[Value]) -> Vec<VersionInfo> {
    let mut versions = entries
        .iter()
        .filter_map(|entry| {
            let raw = text_field(entry, "num")?;
            let yanked = truthy(entry.get("yanked"));
            Some(VersionInfo {
                raw: raw.to_owned(),
                version: normalize_version(raw).unwrap_or_else(|| raw.to_owned()),
                deprecated: yanked,
                reason: if yanked {
                    text_field(entry, "yank_message")
                        .unwrap_or_default()
                        .to_owned()
                } else {
                    String::new()
                },
            })
        })
        .collect::<Vec<_>>();
    versions.sort_by(|left, right| {
        compare(VersionScheme::Semver, &left.raw, &right.raw).then_with(|| left.raw.cmp(&right.raw))
    });
    versions
}

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 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 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()));
    }
}