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

johnandersen777.bsky.social/vuln-notif

0
0
main
307 lines · 10.4 KB Raw History
//! OSV.dev source: online query endpoints, offline bulk dumps, and the local
//! advisory cache.
//!
//! Advisory payloads keep the wire shape (`aliases`, `affected[].ranges[].
//! events[]`) so planners can evaluate `introduced`/`fixed`/`last_affected`
//! without a second parse. The cache stores the fields `release_osv` has
//! columns for (aliases, affected, modified); `summary` and `severity` are
//! advisory-only metadata and are not persisted.

use std::path::Path;
use std::sync::Arc;

use anyhow::{Context, Result, anyhow};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

use crate::db::DbHandle;
use crate::db::model::ReleaseOsvMark;
use crate::release::http::RegistryHttp;

pub const DEFAULT_OSV_BASE_URL: &str = "https://api.osv.dev";
/// OSV rejects `querybatch` requests with more than 1000 queries.
pub const OSV_QUERYBATCH_LIMIT: usize = 1000;

/// One `querybatch` entry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OsvQuery {
    pub purl: String,
    pub version: Option<String>,
}

/// An OSV advisory, trimmed to the fields release ingestion uses.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Advisory {
    #[serde(default)]
    pub id: String,
    #[serde(default)]
    pub aliases: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub modified: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub severity: Vec<Value>,
    #[serde(default)]
    pub affected: Vec<AffectedPackage>,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct AffectedPackage {
    #[serde(default)]
    pub package: OsvPackage,
    #[serde(default)]
    pub ranges: Vec<AffectedRange>,
    #[serde(default)]
    pub versions: Vec<String>,
    #[serde(default)]
    pub ecosystem_specific: Value,
    #[serde(default)]
    pub database_specific: Value,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct OsvPackage {
    #[serde(default)]
    pub ecosystem: String,
    #[serde(default)]
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub purl: Option<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct AffectedRange {
    /// `SEMVER`, `ECOSYSTEM`, or `GIT`.
    #[serde(rename = "type", default)]
    pub kind: String,
    #[serde(default)]
    pub events: Vec<RangeEvent>,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct RangeEvent {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fixed: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_affected: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<String>,
}

#[derive(Debug, Default, Deserialize)]
struct QueryResponse {
    #[serde(default)]
    vulns: Vec<Advisory>,
}

#[derive(Debug, Default, Deserialize)]
struct BatchResponse {
    #[serde(default)]
    results: Vec<BatchResult>,
}

#[derive(Debug, Default, Deserialize)]
struct BatchResult {
    #[serde(default)]
    vulns: Vec<Advisory>,
}

/// OSV API and bulk-dump client.
pub struct OsvClient {
    http: Arc<dyn RegistryHttp>,
    base_url: String,
}

impl OsvClient {
    pub fn new(http: Arc<dyn RegistryHttp>) -> Self {
        Self::with_base_url(http, DEFAULT_OSV_BASE_URL)
    }

    pub fn with_base_url(http: Arc<dyn RegistryHttp>, base_url: impl Into<String>) -> Self {
        Self {
            http,
            base_url: base_url.into().trim_end_matches('/').to_owned(),
        }
    }

    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    fn url(&self, path: &str) -> String {
        format!("{}{path}", self.base_url)
    }

    /// `POST /v1/query` for one purl (optionally pinned to a version).
    pub async fn query(&self, purl: &str, version: Option<&str>) -> Result<Vec<Advisory>> {
        let body = query_body(&OsvQuery {
            purl: purl.to_owned(),
            version: version.map(str::to_owned),
        });
        let payload = self.http.post_json(&self.url("/v1/query"), &body).await?;
        let response: QueryResponse =
            serde_json::from_value(payload).context("decode OSV query response")?;
        Ok(response.vulns)
    }

    /// `POST /v1/querybatch`, split into batches of at most
    /// [`OSV_QUERYBATCH_LIMIT`] queries. Results preserve query order.
    pub async fn querybatch(&self, queries: &[OsvQuery]) -> Result<Vec<Vec<Advisory>>> {
        let mut results = Vec::with_capacity(queries.len());
        for batch in queries.chunks(OSV_QUERYBATCH_LIMIT) {
            let body = serde_json::json!({
                "queries": batch.iter().map(query_body).collect::<Vec<_>>(),
            });
            let payload = self
                .http
                .post_json(&self.url("/v1/querybatch"), &body)
                .await?;
            let mut response: BatchResponse =
                serde_json::from_value(payload).context("decode OSV querybatch response")?;
            response
                .results
                .resize_with(batch.len(), BatchResult::default);
            results.extend(
                response
                    .results
                    .into_iter()
                    .take(batch.len())
                    .map(|result| result.vulns),
            );
        }
        Ok(results)
    }

    /// `GET /v1/vulns/{id}`.
    pub async fn get_vuln(&self, id: &str) -> Result<Advisory> {
        if id.is_empty()
            || !id
                .bytes()
                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
        {
            return Err(anyhow!("invalid OSV advisory id: {id}"));
        }
        let payload = self
            .http
            .get_json(&self.url(&format!("/v1/vulns/{id}")))
            .await?;
        serde_json::from_value(payload).with_context(|| format!("decode OSV advisory {id}"))
    }

    /// Load an offline OSV bulk dump: every `*.json` file in `dir` is one
    /// advisory. Files are read in sorted order and no network is touched.
    pub fn load_bulk_dir(&self, dir: &Path) -> Result<Vec<Advisory>> {
        let entries = std::fs::read_dir(dir)
            .with_context(|| format!("read OSV bulk dir {}", dir.display()))?;
        let mut paths = Vec::new();
        for entry in entries {
            let path = entry
                .with_context(|| format!("read OSV bulk dir {}", dir.display()))?
                .path();
            if path.is_file()
                && path
                    .extension()
                    .is_some_and(|extension| extension == "json")
            {
                paths.push(path);
            }
        }
        paths.sort();
        let mut advisories = Vec::with_capacity(paths.len());
        for path in paths {
            let raw = std::fs::read_to_string(&path)
                .with_context(|| format!("read OSV advisory {}", path.display()))?;
            let advisory = serde_json::from_str(&raw)
                .with_context(|| format!("decode OSV advisory {}", path.display()))?;
            advisories.push(advisory);
        }
        Ok(advisories)
    }

    /// Upsert `release_osv` rows for `purl`.
    pub async fn hydrate(
        &self,
        db: &DbHandle,
        repo_did: &str,
        purl: &str,
        advisories: &[Advisory],
    ) -> Result<()> {
        for advisory in advisories {
            if advisory.id.is_empty() {
                return Err(anyhow!("OSV advisory without an id"));
            }
            let aliases_json =
                serde_json::to_string(&advisory.aliases).context("serialize OSV aliases")?;
            let affected_json =
                serde_json::to_string(&advisory.affected).context("serialize OSV affected")?;
            db.mark_release_osv(ReleaseOsvMark {
                repo_did: repo_did.to_owned(),
                purl: purl.to_owned(),
                osv_id: advisory.id.clone(),
                aliases_json: Some(aliases_json),
                affected_json: Some(affected_json),
                modified: advisory.modified.clone(),
            })
            .await?;
        }
        Ok(())
    }

    /// Read cached advisories for `purl`. `summary` and `severity` are not
    /// part of the cache schema and come back empty.
    pub async fn cached(&self, db: &DbHandle, repo_did: &str, purl: &str) -> Result<Vec<Advisory>> {
        let rows = db.list_release_osv(repo_did, purl).await?;
        rows.into_iter()
            .map(|row| {
                let aliases = row
                    .aliases_json
                    .as_deref()
                    .map(serde_json::from_str::<Vec<String>>)
                    .transpose()
                    .context("decode cached OSV aliases")?
                    .unwrap_or_default();
                let affected = row
                    .affected_json
                    .as_deref()
                    .map(serde_json::from_str::<Vec<AffectedPackage>>)
                    .transpose()
                    .context("decode cached OSV affected")?
                    .unwrap_or_default();
                Ok(Advisory {
                    id: row.osv_id,
                    aliases,
                    modified: row.modified,
                    summary: None,
                    severity: Vec::new(),
                    affected,
                })
            })
            .collect()
    }
}

/// Whether `identifier` (a CVE, GHSA, or OSV id) names this advisory.
/// Matching is case-insensitive across the id and every alias.
pub fn advisory_matches_cve(advisory: &Advisory, identifier: &str) -> bool {
    let identifier = identifier.trim();
    if identifier.is_empty() {
        return false;
    }
    std::iter::once(advisory.id.as_str())
        .chain(advisory.aliases.iter().map(String::as_str))
        .any(|candidate| candidate.eq_ignore_ascii_case(identifier))
}

fn query_body(query: &OsvQuery) -> Value {
    let mut package = Map::new();
    package.insert("purl".to_owned(), Value::String(query.purl.clone()));
    let mut body = Map::new();
    body.insert("package".to_owned(), Value::Object(package));
    if let Some(version) = &query.version {
        body.insert("version".to_owned(), Value::String(version.clone()));
    }
    Value::Object(body)
}