//! Release source contract. //! //! Phase 2+ adapters implement [`ReleaseSource`] and register themselves in //! [`SOURCE_REGISTRY`]. This wave only establishes the types and the registry; //! ingestion still goes through deps.dev and the registry fetchers in //! `crate::release::artifact`, so behavior is unchanged. use std::sync::Arc; use anyhow::Result; use async_trait::async_trait; use serde_json::Value; use crate::release::http::RegistryHttp; use crate::release::sources::{ apache::ApacheSource, bitbucket::BitbucketSource, cargo::CargoSource, composer::ComposerSource, cpan::CpanSource, distro::{DistroSource, ManifestHttp, ReqwestManifestHttp}, docker::{DockerHttp, DockerSource, ReqwestDockerHttp}, gem::GemSource, gitee::GiteeSource, github::{GitHttp, GithubSource, ReqwestGitHttp}, gitlab::GitlabSource, gnu::GnuSource, golang::GolangSource, maven::MavenSource, npm::NpmSource, nuget::NugetSource, pypi::PyPiSource, sourceforge::SourceforgeSource, }; /// A source-neutral package reference derived from a purl. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ProjectRef { pub purl_type: String, pub name: String, pub purl: String, } /// One version offered by a source, normalized for the release records. #[derive(Debug, Clone, PartialEq, Eq)] pub struct VersionInfo { pub raw: String, pub version: String, pub deprecated: bool, pub reason: String, } /// Artifact metadata before any download or hashing fallback. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ArtifactInfo { pub file_name: String, pub url: String, pub sha256: Option, pub size: Option, pub mime_type: Option, } /// A registry status signal for one version. #[derive(Debug, Clone, PartialEq, Eq)] pub struct StatusInfo { pub status: String, pub kind: Option, pub reason: String, } /// What a source can answer without fabricating data. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct SourceCapabilities { pub versions: bool, pub artifacts: bool, pub statuses: bool, pub project_meta: bool, } /// Typed reason a source cannot answer a request. #[derive(Debug, Clone, PartialEq, Eq)] pub enum UnsupportedReason { UnknownPurlType(String), NoVersions, NoArtifacts, NoStatuses, Unavailable(&'static str), } /// Source adapter contract. Implementations are injected with an HTTP client /// and must not call the network from tests directly. #[async_trait] pub trait ReleaseSource: Send + Sync { fn name(&self) -> &'static str; fn capabilities(&self) -> SourceCapabilities; async fn versions(&self, project: &ProjectRef) -> Result>; async fn artifacts( &self, project: &ProjectRef, version: &VersionInfo, ) -> Result>; async fn statuses( &self, project: &ProjectRef, version: &VersionInfo, ) -> Result>; async fn project_meta(&self, project: &ProjectRef) -> Result; } /// One purl type's source adapter and deps.dev/deps.dev-style system name. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct SourceRegistration { pub purl_type: &'static str, pub source: &'static str, pub release_system: &'static str, } /// Every registered purl type. deps.dev systems exist for the first seven; /// the rest are source adapters that do not use deps.dev. pub const SOURCE_REGISTRY: &[SourceRegistration] = &[ SourceRegistration { purl_type: "npm", source: "npm", release_system: "NPM", }, SourceRegistration { purl_type: "pypi", source: "pypi", release_system: "PYPI", }, SourceRegistration { purl_type: "maven", source: "maven", release_system: "MAVEN", }, SourceRegistration { purl_type: "nuget", source: "nuget", release_system: "NUGET", }, SourceRegistration { purl_type: "gem", source: "gem", release_system: "RUBYGEMS", }, SourceRegistration { purl_type: "cargo", source: "cargo", release_system: "CARGO", }, SourceRegistration { purl_type: "golang", source: "golang", release_system: "GO", }, SourceRegistration { purl_type: "rpm", source: "distro", release_system: "", }, SourceRegistration { purl_type: "deb", source: "distro", release_system: "", }, SourceRegistration { purl_type: "apk", source: "distro", release_system: "", }, SourceRegistration { purl_type: "github", source: "github", release_system: "", }, SourceRegistration { purl_type: "gitlab", source: "gitlab", release_system: "", }, SourceRegistration { purl_type: "bitbucket", source: "bitbucket", release_system: "", }, SourceRegistration { purl_type: "composer", source: "composer", release_system: "", }, SourceRegistration { purl_type: "cpan", source: "cpan", release_system: "", }, SourceRegistration { purl_type: "apache", source: "apache", release_system: "", }, SourceRegistration { purl_type: "gitee", source: "gitee", release_system: "", }, SourceRegistration { purl_type: "docker", source: "docker", release_system: "", }, SourceRegistration { purl_type: "oci", source: "docker", release_system: "", }, SourceRegistration { purl_type: "sourceforge", source: "sourceforge", release_system: "", }, SourceRegistration { purl_type: "gnu", source: "gnu", release_system: "", }, ]; pub fn source_for(purl_type: &str) -> Option<&'static SourceRegistration> { SOURCE_REGISTRY .iter() .find(|entry| entry.purl_type == purl_type) } /// Credentials for source adapters. Values are never logged. #[derive(Clone, Default)] pub struct ReleaseTokens { pub github: Option, pub gitlab: Option, pub gitee: Option, } /// Factory options: credentials plus the optional local/mirror base URL used /// by the adapters that expose a configurable endpoint. #[derive(Clone, Default)] pub struct SourceOptions { pub tokens: ReleaseTokens, pub base_url: Option, } impl SourceOptions { fn base_url(&self) -> Option<&str> { self.base_url .as_deref() .map(str::trim) .filter(|url| !url.is_empty()) } } /// Transports for the adapters that expose a custom HTTP seam. `build_source` /// fills every field with the production transport; tests inject fakes. #[derive(Clone, Default)] pub struct SourceTransports { pub git: Option>, pub manifest: Option>, pub docker: Option>, } impl SourceTransports { /// Production transports for git hosting, OCI manifests, and Docker Hub. pub fn production() -> Result { Ok(Self { git: Some(Arc::new(ReqwestGitHttp::new()?)), manifest: Some(Arc::new(ReqwestManifestHttp::new()?)), docker: Some(Arc::new(ReqwestDockerHttp::new()?)), }) } fn git(&self) -> Result, UnsupportedReason> { self.git.clone().ok_or(UnsupportedReason::Unavailable( "git transport is not configured", )) } fn manifest(&self) -> Result, UnsupportedReason> { self.manifest.clone().ok_or(UnsupportedReason::Unavailable( "manifest transport is not configured", )) } fn docker(&self) -> Result, UnsupportedReason> { self.docker.clone().ok_or(UnsupportedReason::Unavailable( "docker transport is not configured", )) } } /// Construct the adapter for one purl type with production transports. pub fn build_source( purl_type: &str, http: Arc, options: &SourceOptions, ) -> Result, UnsupportedReason> { let transports = SourceTransports::production() .map_err(|_| UnsupportedReason::Unavailable("source transport is unavailable"))?; build_source_with_transports(purl_type, http, options, &transports) } /// Construct the adapter for one purl type with injected transports. /// /// Every registered adapter is constructed here; unknown and not-yet-adapted /// purl types return a typed [`UnsupportedReason`]. pub fn build_source_with_transports( purl_type: &str, http: Arc, options: &SourceOptions, transports: &SourceTransports, ) -> Result, UnsupportedReason> { let Some(registration) = source_for(purl_type) else { return Err(UnsupportedReason::UnknownPurlType(purl_type.to_owned())); }; let base = options.base_url(); let source: Box = match registration.source { "pypi" => Box::new(PyPiSource::new(http)), "cargo" => Box::new(CargoSource::new(http)), "gem" => Box::new(GemSource::new(http)), "github" => Box::new(GithubSource::new( transports.git()?, options.tokens.github.clone(), )), "gitlab" => Box::new(GitlabSource::new( transports.git()?, options.tokens.gitlab.clone(), )), "bitbucket" => Box::new(BitbucketSource::new(transports.git()?)), "distro" => Box::new(DistroSource::with_clients(http, transports.manifest()?)), "composer" => Box::new(match base { Some(base) => ComposerSource::with_base_url(http, base), None => ComposerSource::new(http), }), "cpan" => Box::new(match base { Some(base) => CpanSource::with_base_url(http, base), None => CpanSource::new(http), }), "apache" => Box::new(match base { Some(base) => ApacheSource::with_bases(http, base, base), None => ApacheSource::new(http), }), "gitee" => { let source = match base { Some(base) => GiteeSource::with_base_url(http, base), None => GiteeSource::new(http), }; Box::new(match options.tokens.gitee.clone() { Some(token) => source.with_token(token), None => source, }) } "gnu" => Box::new(match base { Some(base) => GnuSource::with_base_url(http, base), None => GnuSource::new(http), }), "docker" => Box::new(DockerSource::new(transports.docker()?)), "sourceforge" => Box::new(match base { Some(base) => SourceforgeSource::with_bases(http, base, base), None => SourceforgeSource::new(http), }), "npm" => Box::new(NpmSource::new(http)), "maven" => Box::new(MavenSource::new(http)), "nuget" => Box::new(NugetSource::new(http)), "golang" => Box::new(GolangSource::new(http)), other => return Err(UnsupportedReason::UnknownPurlType(other.to_owned())), }; Ok(source) } #[cfg(test)] mod tests { use super::*; use crate::constants::{RELEASE_SYSTEMS, release_system}; #[test] fn registry_covers_release_systems_and_adapters() { // Every deps.dev-backed release system has a registry entry. for (purl_type, system) in RELEASE_SYSTEMS { let entry = source_for(purl_type).unwrap_or_else(|| panic!("missing {purl_type}")); assert_eq!(entry.release_system, *system, "{purl_type}"); } for entry in SOURCE_REGISTRY { assert_eq!(source_for(entry.purl_type), Some(entry)); if entry.release_system.is_empty() { assert_eq!(release_system(entry.purl_type), None, "{}", entry.purl_type); } else { assert_eq!( release_system(entry.purl_type), Some(entry.release_system), "{}", entry.purl_type ); } } assert!(source_for("unknown-ecosystem").is_none()); } }