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

johnandersen777.bsky.social/vuln-notif

0
0
main
277 lines · 9.7 KB Raw History
//! RubyGems source: full version history and per-platform `.gem` artifacts.
//!
//! Version entries come from `/api/v1/versions/{name}.json`, which carries the
//! per-platform `sha` and (when the registry reports it) `size`. Artifact URLs
//! are the declared `gem_uri` or derived from the name/version/platform. The
//! version-detail endpoint (`/api/v2/rubygems/{name}/versions/{version}.json`)
//! is consulted only when the list omits a digest or size, and a HEAD supplies
//! a size only when both omit it. (RubyGems has no working
//! `/api/v1/gems/{name}-{version}.json` endpoint; that path returns 404.)

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

use anyhow::{Result, anyhow};
use async_trait::async_trait;
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://rubygems.org/api/v1";
pub const VERSION_DETAIL_BASE: &str = "https://rubygems.org/api/v2/rubygems";
pub const GEMS_BASE: &str = "https://rubygems.org/gems";

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

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

    async fn version_entries(&self, name: &str) -> Result<Vec<Value>> {
        let url = format!("{API_BASE}/versions/{name}.json");
        let payload = self.http.get_json(&url).await?;
        payload
            .as_array()
            .cloned()
            .ok_or_else(|| anyhow!("rubygems versions payload is not an array for {name}"))
    }

    async fn version_detail(&self, name: &str, raw: &str) -> Result<Value> {
        let url = format!("{VERSION_DETAIL_BASE}/{name}/versions/{raw}.json");
        self.http.get_json(&url).await
    }
}

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

    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.version_entries(&project.name).await?;
        Ok(version_infos(&entries))
    }

    async fn artifacts(
        &self,
        project: &ProjectRef,
        version: &VersionInfo,
    ) -> Result<Vec<ArtifactInfo>> {
        let entries = self.version_entries(&project.name).await?;
        let matching = matching_entries(&entries, &version.raw);
        if matching.is_empty() {
            return Ok(Vec::new());
        }

        let mut detail: Option<Value> = None;
        let mut by_url = BTreeMap::new();
        for entry in matching {
            let platform = text_field(entry, "platform").unwrap_or("ruby");
            let url = text_field(entry, "gem_uri")
                .map(str::to_owned)
                .unwrap_or_else(|| gem_url(&project.name, &version.raw, platform));
            let mut sha256 = text_field(entry, "sha").map(str::to_owned);
            let mut size = entry
                .get("size")
                .and_then(Value::as_u64)
                .filter(|size| *size > 0);
            if sha256.is_none() || size.is_none() {
                if detail.is_none() {
                    // Advisory enrichment: a failed detail leaves the field unset.
                    detail = self.version_detail(&project.name, &version.raw).await.ok();
                }
                if let Some(detail) = &detail {
                    let detail_platform = text_field(detail, "platform").unwrap_or("ruby");
                    if platform == detail_platform {
                        if sha256.is_none() {
                            sha256 = text_field(detail, "sha").map(str::to_owned);
                        }
                        if size.is_none() {
                            size = detail
                                .get("size")
                                .and_then(Value::as_u64)
                                .filter(|size| *size > 0);
                        }
                    }
                }
            }
            if size.is_none() {
                size = Some(self.http.head_size(&url).await?);
            }
            let file_name = url.rsplit('/').next().unwrap_or(&url).to_owned();
            by_url.insert(
                url.clone(),
                ArtifactInfo {
                    file_name,
                    url,
                    sha256,
                    size,
                    mime_type: Some("application/gzip".to_owned()),
                },
            );
        }
        Ok(by_url.into_values().collect())
    }

    async fn statuses(
        &self,
        project: &ProjectRef,
        version: &VersionInfo,
    ) -> Result<Vec<StatusInfo>> {
        let entries = self.version_entries(&project.name).await?;
        let matching = matching_entries(&entries, &version.raw);
        if matching.is_empty() || !matching.iter().all(|entry| truthy(entry.get("yanked"))) {
            return Ok(Vec::new());
        }
        Ok(vec![StatusInfo {
            status: "yanked".to_owned(),
            kind: Some("registry".to_owned()),
            reason: first_text(&matching, "yanked_reason"),
        }])
    }

    async fn project_meta(&self, project: &ProjectRef) -> Result<Value> {
        let url = format!("{API_BASE}/gems/{}.json", project.name);
        let payload = self.http.get_json(&url).await?;
        let mut meta = Map::new();
        insert_text(
            &mut meta,
            "name",
            Some(text_field(&payload, "name").unwrap_or(project.name.as_str())),
        );
        insert_text(&mut meta, "description", text_field(&payload, "info"));
        insert_text(&mut meta, "homepage", text_field(&payload, "homepage_uri"));
        insert_text(
            &mut meta,
            "repository",
            text_field(&payload, "source_code_uri"),
        );
        let license = payload
            .get("licenses")
            .and_then(Value::as_array)
            .map(|licenses| {
                licenses
                    .iter()
                    .filter_map(Value::as_str)
                    .filter(|license| !license.is_empty())
                    .collect::<Vec<_>>()
                    .join(", ")
            })
            .filter(|license| !license.is_empty());
        insert_text(&mut meta, "license", license.as_deref());
        // A native gem platform (`x86_64-linux`) names a runtime target.
        // Pure-Ruby (`ruby`) and JVM (`java`) gems carry no OS/arch fact.
        if let Some(target) = platform_target(text_field(&payload, "platform")) {
            meta.insert("target".to_owned(), target);
        }
        Ok(Value::Object(meta))
    }
}

fn platform_target(platform: Option<&str>) -> Option<Value> {
    let (arch, os) = platform?.trim().rsplit_once('-')?;
    let os = match os {
        "linux" => "linux",
        "darwin" | "macos" => "macos",
        "mingw" | "mswin" | "windows" => "windows",
        _ => return None,
    };
    if arch.is_empty() || arch == "ruby" || arch == "java" {
        return None;
    }
    Some(json!({"os": os, "architectures": [arch]}))
}

fn matching_entries<'a>(entries: &'a [Value], raw: &str) -> Vec<&'a Value> {
    entries
        .iter()
        .filter(|entry| text_field(entry, "number") == Some(raw))
        .collect()
}

fn version_infos(entries: &[Value]) -> Vec<VersionInfo> {
    let mut groups: BTreeMap<&str, Vec<&Value>> = BTreeMap::new();
    for entry in entries {
        if let Some(number) = text_field(entry, "number") {
            groups.entry(number).or_default().push(entry);
        }
    }
    let mut versions = groups
        .into_iter()
        .map(|(raw, entries)| {
            let yanked = entries.iter().all(|entry| truthy(entry.get("yanked")));
            VersionInfo {
                raw: raw.to_owned(),
                version: normalize_version(raw).unwrap_or_else(|| raw.to_owned()),
                deprecated: yanked,
                reason: if yanked {
                    first_text(&entries, "yanked_reason")
                } else {
                    String::new()
                },
            }
        })
        .collect::<Vec<_>>();
    versions.sort_by(|left, right| {
        compare(VersionScheme::RubyGems, &left.raw, &right.raw)
            .then_with(|| left.raw.cmp(&right.raw))
    });
    versions
}

fn gem_url(name: &str, raw: &str, platform: &str) -> String {
    if platform.is_empty() || platform == "ruby" {
        format!("{GEMS_BASE}/{name}-{raw}.gem")
    } else {
        format!("{GEMS_BASE}/{name}-{raw}-{platform}.gem")
    }
}

fn first_text(entries: &[&Value], key: &str) -> String {
    entries
        .iter()
        .find_map(|entry| text_field(entry, key))
        .unwrap_or_default()
        .to_owned()
}

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