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

johnandersen777.bsky.social/vuln-notif

0
0
main
401 lines · 12.3 KB Raw History
//! npm source adapter: full history, scoped names, deprecations, tarballs.
//!
//! The adapter module is included with `#[path]` because `sources/mod.rs` is
//! owned by the integration wave. Every request goes through the scripted
//! [`FakeHttp`] seam; no test touches the live registry, and any HEAD or
//! download attempt fails loudly.

#![allow(dead_code)]

use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use async_trait::async_trait;
use serde_json::Value;

use vuln_notif::release::http::RegistryHttp;
use vuln_notif::release::source::{
    ArtifactInfo, ProjectRef, ReleaseSource, SourceCapabilities, StatusInfo, VersionInfo,
};

mod release {
    pub mod http {
        pub use vuln_notif::release::http::*;
    }
    pub mod source {
        pub use vuln_notif::release::source::*;
    }
    pub mod versioning {
        pub use vuln_notif::release::versioning::*;
    }
}

#[path = "../src/release/sources/npm.rs"]
mod npm;

use npm::NpmSource;

const REGISTRY_FIXTURE: &str = include_str!("fixtures/sources/npm/registry.json");
const SCOPED_FIXTURE: &str = include_str!("fixtures/sources/npm/scoped.json");

const REGISTRY_URL: &str = "https://registry.npmjs.org/acme-widget";
const SCOPED_URL: &str = "https://registry.npmjs.org/@acme%2Fscoped-widget";

// ---------------------------------------------------------------------------
// Local scripted registry HTTP fake
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
enum Reply {
    Json(Value),
    Error(String),
}

#[derive(Default)]
struct FakeHttp {
    replies: Mutex<HashMap<String, Reply>>,
    calls: Mutex<Vec<String>>,
}

impl FakeHttp {
    fn new(routes: Vec<(&str, Reply)>) -> Self {
        Self {
            replies: Mutex::new(
                routes
                    .into_iter()
                    .map(|(url, reply)| (url.to_owned(), reply))
                    .collect(),
            ),
            calls: Mutex::new(Vec::new()),
        }
    }

    fn calls(&self) -> Vec<String> {
        self.calls.lock().unwrap().clone()
    }

    fn take(&self, kind: &str, url: &str) -> anyhow::Result<Reply> {
        self.calls.lock().unwrap().push(format!("{kind} {url}"));
        self.replies
            .lock()
            .unwrap()
            .get(url)
            .cloned()
            .ok_or_else(|| anyhow::anyhow!("unexpected {kind} {url}"))
    }
}

#[async_trait]
impl RegistryHttp for FakeHttp {
    async fn get_json(&self, url: &str) -> anyhow::Result<Value> {
        match self.take("json", url)? {
            Reply::Json(value) => Ok(value),
            Reply::Error(message) => Err(anyhow::anyhow!(message)),
        }
    }

    async fn get_text(&self, url: &str) -> anyhow::Result<String> {
        Err(anyhow::anyhow!("unexpected text fetch for {url}"))
    }

    async fn head_size(&self, url: &str) -> anyhow::Result<u64> {
        Err(anyhow::anyhow!("unexpected HEAD for {url}"))
    }

    async fn download(&self, url: &str) -> anyhow::Result<Vec<u8>> {
        Err(anyhow::anyhow!("unexpected download for {url}"))
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn fixture(text: &str) -> Value {
    serde_json::from_str(text).expect("fixture JSON")
}

fn project(name: &str) -> ProjectRef {
    ProjectRef {
        purl_type: "npm".to_owned(),
        name: name.to_owned(),
        purl: format!("pkg:npm/{name}"),
    }
}

fn version(raw: &str) -> VersionInfo {
    VersionInfo {
        raw: raw.to_owned(),
        version: raw.to_owned(),
        deprecated: false,
        reason: String::new(),
    }
}

// ---------------------------------------------------------------------------
// Versions
// ---------------------------------------------------------------------------

#[tokio::test]
async fn npm_versions_include_prereleases_and_deprecation_reasons() {
    let http = Arc::new(FakeHttp::new(vec![(
        REGISTRY_URL,
        Reply::Json(fixture(REGISTRY_FIXTURE)),
    )]));
    let source = NpmSource::new(http.clone());
    let project = project("acme-widget");

    let versions = source.versions(&project).await.expect("npm versions");
    assert_eq!(
        versions
            .iter()
            .map(|entry| {
                (
                    entry.raw.as_str(),
                    entry.version.as_str(),
                    entry.deprecated,
                    entry.reason.as_str(),
                )
            })
            .collect::<Vec<_>>(),
        vec![
            ("2.0.0-rc.1", "2.0.0-rc.1", false, ""),
            ("1.5.0-beta.2", "1.5.0-beta.2", false, ""),
            ("1.4.0", "1.4.0", false, ""),
            ("1.3.0", "1.3.0", false, ""),
            (
                "1.2.0",
                "1.2.0",
                true,
                "Deprecated due to a security vulnerability; upgrade to 1.4.0",
            ),
            ("1.1.0-beta.1", "1.1.0-beta.1", false, ""),
            ("1.0.0", "1.0.0", false, ""),
            ("0.9.0", "0.9.0", true, "use 1.x"),
        ]
    );
    assert_eq!(http.calls(), vec![format!("json {REGISTRY_URL}")]);

    let again = source.versions(&project).await.expect("repeat versions");
    assert_eq!(again, versions, "newest-first order is deterministic");
}

// ---------------------------------------------------------------------------
// Artifacts
// ---------------------------------------------------------------------------

#[tokio::test]
async fn npm_artifacts_use_tarball_metadata_and_never_relabel_digests() {
    let http = Arc::new(FakeHttp::new(vec![(
        REGISTRY_URL,
        Reply::Json(fixture(REGISTRY_FIXTURE)),
    )]));
    let source = NpmSource::new(http.clone());
    let project = project("acme-widget");

    assert_eq!(
        source.artifacts(&project, &version("1.4.0")).await.unwrap(),
        vec![ArtifactInfo {
            file_name: "acme-widget-1.4.0.tgz".to_owned(),
            url: "https://registry.npmjs.org/acme-widget/-/acme-widget-1.4.0.tgz".to_owned(),
            sha256: None,
            size: Some(456789),
            mime_type: Some("application/gzip".to_owned()),
        }]
    );

    for raw in ["1.0.0", "1.3.0"] {
        let artifacts = source.artifacts(&project, &version(raw)).await.unwrap();
        assert_eq!(artifacts.len(), 1, "{raw}");
        assert_eq!(
            artifacts[0].sha256, None,
            "{raw}: SHA-1/SHA-512 must not be relabeled as SHA-256"
        );
    }

    assert!(
        source
            .artifacts(&project, &version("9.9.9"))
            .await
            .unwrap()
            .is_empty()
    );
    assert!(
        http.calls().iter().all(|call| call.starts_with("json ")),
        "declared metadata needs no HEAD or download: {:?}",
        http.calls()
    );
}

// ---------------------------------------------------------------------------
// Statuses
// ---------------------------------------------------------------------------

#[tokio::test]
async fn npm_statuses_report_deprecation_with_registry_kind() {
    let http = Arc::new(FakeHttp::new(vec![(
        REGISTRY_URL,
        Reply::Json(fixture(REGISTRY_FIXTURE)),
    )]));
    let source = NpmSource::new(http);
    let project = project("acme-widget");

    assert_eq!(
        source.statuses(&project, &version("1.2.0")).await.unwrap(),
        vec![StatusInfo {
            status: "deprecated".to_owned(),
            kind: Some("registry".to_owned()),
            reason: "Deprecated due to a security vulnerability; upgrade to 1.4.0".to_owned(),
        }],
        "a security-looking message is still a registry deprecation"
    );
    assert_eq!(
        source.statuses(&project, &version("0.9.0")).await.unwrap(),
        vec![StatusInfo {
            status: "deprecated".to_owned(),
            kind: Some("registry".to_owned()),
            reason: "use 1.x".to_owned(),
        }]
    );
    assert!(
        source
            .statuses(&project, &version("1.4.0"))
            .await
            .unwrap()
            .is_empty()
    );
    assert!(
        source
            .statuses(&project, &version("9.9.9"))
            .await
            .unwrap()
            .is_empty()
    );
}

// ---------------------------------------------------------------------------
// Project metadata
// ---------------------------------------------------------------------------

#[tokio::test]
async fn npm_project_meta_exposes_dist_tags_as_channels() {
    let http = Arc::new(FakeHttp::new(vec![(
        REGISTRY_URL,
        Reply::Json(fixture(REGISTRY_FIXTURE)),
    )]));
    let source = NpmSource::new(http);
    let meta = source
        .project_meta(&project("acme-widget"))
        .await
        .expect("npm meta");

    assert_eq!(meta["name"], "acme-widget");
    assert_eq!(
        meta["description"],
        "Synthetic npm package for source tests"
    );
    assert_eq!(meta["homepage"], "https://example.invalid/acme-widget");
    assert_eq!(
        meta["repository"],
        "git+https://example.invalid/acme-widget.git"
    );
    assert_eq!(meta["license"], "MIT");
    assert_eq!(meta["channels"]["latest"], "1.4.0");
    assert_eq!(meta["channels"]["next"], "2.0.0-rc.1");
    assert_eq!(meta["channels"]["beta"], "1.5.0-beta.2");
}

// ---------------------------------------------------------------------------
// Scoped names
// ---------------------------------------------------------------------------

#[tokio::test]
async fn npm_scoped_names_are_percent_encoded_and_keep_display_name() {
    assert_eq!(NpmSource::registry_url("acme-widget"), REGISTRY_URL);
    assert_eq!(
        NpmSource::registry_url("@acme/scoped-widget"),
        SCOPED_URL,
        "the scope separator must be percent-encoded"
    );

    let http = Arc::new(FakeHttp::new(vec![(
        SCOPED_URL,
        Reply::Json(fixture(SCOPED_FIXTURE)),
    )]));
    let source = NpmSource::new(http.clone());
    let project = project("@acme/scoped-widget");

    let versions = source.versions(&project).await.expect("scoped versions");
    assert_eq!(
        versions
            .iter()
            .map(|entry| { (entry.raw.as_str(), entry.deprecated, entry.reason.as_str(),) })
            .collect::<Vec<_>>(),
        vec![
            ("1.1.0-canary.0", true, "canary builds are unsupported"),
            ("1.0.0", false, ""),
        ]
    );
    assert_eq!(http.calls(), vec![format!("json {SCOPED_URL}")]);

    let meta = source.project_meta(&project).await.expect("scoped meta");
    assert_eq!(meta["name"], "@acme/scoped-widget");
    assert_eq!(
        meta["repository"],
        "https://example.invalid/scoped-widget.git"
    );
    assert_eq!(meta["license"], "Apache-2.0");
    assert_eq!(meta["channels"]["latest"], "1.0.0");
    assert_eq!(meta["channels"]["canary"], "1.1.0-canary.0");

    let artifacts = source
        .artifacts(&project, &version("1.0.0"))
        .await
        .expect("scoped artifacts");
    assert_eq!(
        artifacts,
        vec![ArtifactInfo {
            file_name: "scoped-widget-1.0.0.tgz".to_owned(),
            url: "https://registry.npmjs.org/@acme/scoped-widget/-/scoped-widget-1.0.0.tgz"
                .to_owned(),
            sha256: None,
            size: Some(2222),
            mime_type: Some("application/gzip".to_owned()),
        }]
    );
}

// ---------------------------------------------------------------------------
// Transport behavior
// ---------------------------------------------------------------------------

#[tokio::test]
async fn npm_propagates_transport_errors() {
    let http = Arc::new(FakeHttp::new(vec![(
        REGISTRY_URL,
        Reply::Error("HTTP 503 Service Unavailable for https://registry.npmjs.org".to_owned()),
    )]));
    let source = NpmSource::new(http.clone());
    let error = source
        .versions(&project("acme-widget"))
        .await
        .expect_err("transport errors propagate");
    assert!(error.to_string().contains("503"));
    assert_eq!(http.calls(), vec![format!("json {REGISTRY_URL}")]);
}

#[test]
fn npm_advertises_full_history_capabilities() {
    let http: Arc<dyn RegistryHttp> = Arc::new(FakeHttp::default());
    let source = NpmSource::new(http);
    assert_eq!(source.name(), "npm");
    assert_eq!(
        source.capabilities(),
        SourceCapabilities {
            versions: true,
            artifacts: true,
            statuses: true,
            project_meta: true,
        }
    );
}