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

johnandersen777.bsky.social/vuln-notif

0
0
main
622 lines · 20.5 KB Raw History
//! GitHub releases, tags, assets, and repository metadata.
//!
//! [`GithubSource`] implements the [`ReleaseSource`] contract against the
//! public REST API. The token is injected by the caller and only ever travels
//! in the `Authorization` header; it is never formatted into URLs, logs, or
//! errors.
//!
//! The transport seam [`GitHttp`] is shared with the GitLab and Bitbucket
//! adapters. It exposes the HTTP status and response headers so pagination
//! links and rate-limit headers survive the trip; [`RegistryHttp`] deliberately
//! hides both.
//!
//! [`RegistryHttp`]: crate::release::http::RegistryHttp

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

use anyhow::{Context, Result, anyhow, bail};
use async_trait::async_trait;
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode};
use serde_json::{Map, Value};

use crate::release::artifact::normalize_version;
use crate::release::http::{HTTP_TIMEOUT, USER_AGENT};
use crate::release::source::{
    ArtifactInfo, ProjectRef, ReleaseSource, SourceCapabilities, StatusInfo, UnsupportedReason,
    VersionInfo,
};

pub const GITHUB_API: &str = "https://api.github.com";
pub const GITHUB_ACCEPT: &str = "application/vnd.github+json";
const PER_PAGE: usize = 100;
/// Bound on followed pagination links; a misbehaving server cannot loop
/// forever.
const MAX_PAGES: usize = 100;

/// A response with the status and headers the release sources need.
#[derive(Debug, Clone, Default)]
pub struct GitResponse {
    pub status: u16,
    pub headers: BTreeMap<String, String>,
    pub body: Value,
}

/// One JSON GET against a git host. Tests inject a fake; production uses
/// [`ReqwestGitHttp`].
#[async_trait]
pub trait GitHttp: Send + Sync {
    async fn get_json(&self, url: &str, headers: &[(String, String)]) -> Result<GitResponse>;
}

/// Production transport for the git hosting APIs.
pub struct ReqwestGitHttp {
    client: reqwest::Client,
}

impl ReqwestGitHttp {
    pub fn new() -> Result<Self> {
        let client = reqwest::Client::builder()
            .timeout(HTTP_TIMEOUT)
            .user_agent(USER_AGENT)
            .redirect(reqwest::redirect::Policy::limited(10))
            .build()
            .context("build git host HTTP client")?;
        Ok(Self { client })
    }
}

#[async_trait]
impl GitHttp for ReqwestGitHttp {
    async fn get_json(&self, url: &str, headers: &[(String, String)]) -> Result<GitResponse> {
        let mut request = self.client.get(url);
        for (name, value) in headers {
            request = request.header(name.as_str(), value.as_str());
        }
        let response = request.send().await.with_context(|| format!("GET {url}"))?;
        let status = response.status().as_u16();
        let headers = response
            .headers()
            .iter()
            .map(|(name, value)| {
                (
                    name.as_str().to_owned(),
                    String::from_utf8_lossy(value.as_bytes()).into_owned(),
                )
            })
            .collect();
        let body = response.json::<Value>().await.unwrap_or(Value::Null);
        Ok(GitResponse {
            status,
            headers,
            body,
        })
    }
}

/// Header lookup that does not care about case.
pub(crate) fn header<'a>(response: &'a GitResponse, name: &str) -> Option<&'a str> {
    response
        .headers
        .iter()
        .find(|(key, _)| key.eq_ignore_ascii_case(name))
        .map(|(_, value)| value.as_str())
}

/// The `rel="next"` target from an RFC 8288 `Link` header.
pub(crate) fn link_next(response: &GitResponse) -> Option<String> {
    let link = header(response, "link")?;
    link.split(',').find_map(|part| {
        let part = part.trim();
        if !(part.contains("rel=\"next\"") || part.contains("rel=next")) {
            return None;
        }
        let start = part.find('<')? + 1;
        let end = part[start..].find('>')? + start;
        Some(part[start..end].to_owned())
    })
}

/// A typed, non-retryable reason for a request a source cannot serve.
pub(crate) fn unavailable(detail: &'static str) -> anyhow::Error {
    anyhow!("{:?}: {detail}", UnsupportedReason::Unavailable(detail))
}

pub(crate) async fn get_response(
    http: &dyn GitHttp,
    url: &str,
    headers: &[(String, String)],
) -> Result<GitResponse> {
    http.get_json(url, headers)
        .await
        .with_context(|| format!("GET {url}"))
}

/// Reject non-2xx responses, surfacing rate-limit headers without ever echoing
/// request headers (where the token lives).
pub(crate) fn check_status(response: &GitResponse, url: &str, host: &str) -> Result<()> {
    let status = response.status;
    if (200..300).contains(&status) {
        return Ok(());
    }
    let remaining = header(response, "x-ratelimit-remaining");
    let reset = header(response, "x-ratelimit-reset");
    let retry = header(response, "retry-after");
    let mut details = Vec::new();
    if let Some(value) = remaining {
        details.push(format!("remaining={value}"));
    }
    if let Some(value) = reset {
        details.push(format!("reset={value}"));
    }
    if let Some(value) = retry {
        details.push(format!("retry-after={value}"));
    }
    let details = if details.is_empty() {
        String::new()
    } else {
        format!(" [{}]", details.join(", "))
    };
    if status == 429 || remaining == Some("0") || (status == 403 && retry.is_some()) {
        bail!("{host}: rate limit exceeded (HTTP {status}) for {url}{details}");
    }
    bail!("{host}: HTTP {status} for {url}{details}");
}

/// Check the status and decode a JSON body.
pub(crate) fn require_json(response: GitResponse, url: &str, host: &str) -> Result<Value> {
    check_status(&response, url, host)?;
    if response.body.is_null() {
        bail!("{host}: empty JSON body from {url}");
    }
    Ok(response.body)
}

/// Follow `Link` header pagination over JSON array pages.
pub(crate) async fn get_link_pages(
    http: &dyn GitHttp,
    start: &str,
    headers: &[(String, String)],
    host: &str,
) -> Result<Vec<Value>> {
    let mut items = Vec::new();
    let mut next = Some(start.to_owned());
    let mut pages = 0usize;
    while let Some(url) = next {
        pages += 1;
        if pages > MAX_PAGES {
            bail!("{host}: pagination exceeded {MAX_PAGES} pages");
        }
        let response = get_response(http, &url, headers).await?;
        check_status(&response, &url, host)?;
        let page = response
            .body
            .as_array()
            .ok_or_else(|| anyhow!("{host}: expected a JSON array from {url}"))?;
        items.extend(page.iter().cloned());
        next = link_next(&response);
    }
    Ok(items)
}

/// Purl path components for `pkg:{expected}/a/b[/c...]`.
pub(crate) fn purl_parts(project: &ProjectRef, expected: &str) -> Result<Vec<String>> {
    let raw = if project.purl.is_empty() {
        project.name.as_str()
    } else {
        project.purl.as_str()
    };
    let body = raw
        .strip_prefix("pkg:")
        .ok_or_else(|| unavailable("purl is missing the pkg: scheme"))?;
    let body = body.split(['#', '?']).next().unwrap_or("");
    let (purl_type, rest) = body
        .split_once('/')
        .ok_or_else(|| unavailable("purl is missing a type/name path"))?;
    if purl_type != expected {
        return Err(anyhow!(
            "{:?}",
            UnsupportedReason::UnknownPurlType(purl_type.to_owned())
        ));
    }
    let rest = rest.rsplit_once('@').map_or(rest, |(head, _)| head);
    let decoded = percent_decode_str(rest).decode_utf8_lossy();
    Ok(decoded
        .split('/')
        .filter(|part| !part.is_empty())
        .map(str::to_owned)
        .collect())
}

/// A repository path and its leaf name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RepoRef {
    /// `owner/repo` (GitHub, Bitbucket) or `group/subgroup/project` (GitLab).
    pub path: String,
    /// The leaf component, used for archive file names.
    pub repo: String,
}

pub(crate) fn repo_ref(project: &ProjectRef, expected: &str, nested: bool) -> Result<RepoRef> {
    let parts = purl_parts(project, expected)?;
    let repo = parts
        .last()
        .cloned()
        .ok_or_else(|| unavailable("purl is missing a package name"))?;
    if nested {
        if parts.len() < 2 {
            return Err(unavailable("purl is missing a namespace component"));
        }
    } else if parts.len() < 2 {
        return Err(unavailable(
            "purl is missing a namespace or repository component",
        ));
    } else if parts.len() > 2 {
        return Err(unavailable("purl must be namespace/repository"));
    }
    Ok(RepoRef {
        path: parts.join("/"),
        repo,
    })
}

const SEGMENT: &AsciiSet = &NON_ALPHANUMERIC
    .remove(b'-')
    .remove(b'.')
    .remove(b'_')
    .remove(b'~');

/// Percent-encode one URL path segment (tags may contain `/`).
pub(crate) fn encode_segment(value: &str) -> String {
    utf8_percent_encode(value, SEGMENT).to_string()
}

/// Normalize a git tag: strip a single leading `v`/`V` before a digit, then
/// apply the release version grammar.
pub(crate) fn normalize_tag(raw: &str) -> Option<String> {
    let raw = raw.trim();
    let stripped = raw
        .strip_prefix(['v', 'V'])
        .filter(|rest| rest.starts_with(|character: char| character.is_ascii_digit()));
    normalize_version(stripped.unwrap_or(raw))
}

pub(crate) fn dedupe_artifacts(artifacts: Vec<ArtifactInfo>) -> Vec<ArtifactInfo> {
    let mut seen = HashSet::new();
    artifacts
        .into_iter()
        .filter(|artifact| seen.insert(artifact.url.clone()))
        .collect()
}

fn parse_sha256_digest(digest: &str) -> Option<String> {
    let hex = digest.strip_prefix("sha256:")?.trim().to_ascii_lowercase();
    (hex.len() == 64 && hex.bytes().all(|byte| byte.is_ascii_hexdigit())).then_some(hex)
}

fn asset_info(asset: &Value) -> Option<ArtifactInfo> {
    let url = asset
        .get("browser_download_url")
        .and_then(Value::as_str)
        .filter(|url| !url.is_empty())?;
    let file_name = asset
        .get("name")
        .and_then(Value::as_str)
        .filter(|name| !name.is_empty())
        .map(str::to_owned)
        .unwrap_or_else(|| url.rsplit('/').next().unwrap_or(url).to_owned());
    Some(ArtifactInfo {
        file_name,
        url: url.to_owned(),
        sha256: asset
            .get("digest")
            .and_then(Value::as_str)
            .and_then(parse_sha256_digest),
        size: asset.get("size").and_then(Value::as_u64),
        mime_type: asset
            .get("content_type")
            .and_then(Value::as_str)
            .map(str::to_owned),
    })
}

fn archive_info(repo: &RepoRef, raw: &str, url: &str, gzip: bool) -> ArtifactInfo {
    let (extension, mime_type) = if gzip {
        ("tar.gz", "application/gzip")
    } else {
        ("zip", "application/zip")
    };
    let safe = raw.replace('/', "-");
    ArtifactInfo {
        file_name: format!("{}-{safe}.{extension}", repo.repo),
        url: url.to_owned(),
        sha256: None,
        size: None,
        mime_type: Some(mime_type.to_owned()),
    }
}

fn fallback_archives(repo: &RepoRef, raw: &str) -> Vec<ArtifactInfo> {
    let tag = encode_segment(raw);
    let base = format!("{GITHUB_API}/repos/{}", repo.path);
    vec![
        archive_info(repo, raw, &format!("{base}/tarball/{tag}"), true),
        archive_info(repo, raw, &format!("{base}/zipball/{tag}"), false),
    ]
}

/// GitHub source adapter.
pub struct GithubSource {
    http: Arc<dyn GitHttp>,
    token: Option<String>,
    /// Repository metadata is reused by `statuses` and `project_meta`; one
    /// request per repository per adapter instance.
    repo_meta_cache: Mutex<HashMap<String, Value>>,
}

impl GithubSource {
    pub fn new(http: Arc<dyn GitHttp>, token: Option<String>) -> Self {
        Self {
            http,
            token,
            repo_meta_cache: Mutex::new(HashMap::new()),
        }
    }

    fn headers(&self) -> Vec<(String, String)> {
        let mut headers = vec![("Accept".to_owned(), GITHUB_ACCEPT.to_owned())];
        if let Some(token) = self.token.as_deref().filter(|token| !token.is_empty()) {
            headers.push(("Authorization".to_owned(), format!("Bearer {token}")));
        }
        headers
    }

    fn repo_url(repo: &RepoRef) -> String {
        format!("{GITHUB_API}/repos/{}", repo.path)
    }

    async fn repo_meta(&self, repo: &RepoRef) -> Result<Value> {
        let cached = self
            .repo_meta_cache
            .lock()
            .expect("github repo cache")
            .get(&repo.path)
            .cloned();
        if let Some(cached) = cached {
            return Ok(cached);
        }
        let url = Self::repo_url(repo);
        let response = get_response(self.http.as_ref(), &url, &self.headers()).await?;
        let value = require_json(response, &url, "github")?;
        if !value.is_object() {
            bail!("github: expected a repository object from {url}");
        }
        self.repo_meta_cache
            .lock()
            .expect("github repo cache")
            .insert(repo.path.clone(), value.clone());
        Ok(value)
    }

    fn version_from_release(release: &Value) -> Option<VersionInfo> {
        let raw = release.get("tag_name").and_then(Value::as_str)?;
        let version = normalize_tag(raw)?;
        let draft = release
            .get("draft")
            .and_then(Value::as_bool)
            .unwrap_or(false);
        let prerelease = release
            .get("prerelease")
            .and_then(Value::as_bool)
            .unwrap_or(false);
        let (deprecated, reason) = match (draft, prerelease) {
            (true, true) => (true, "draft prerelease release"),
            (true, false) => (true, "draft release"),
            (false, true) => (true, "prerelease release"),
            (false, false) => (false, ""),
        };
        Some(VersionInfo {
            raw: raw.to_owned(),
            version,
            deprecated,
            reason: reason.to_owned(),
        })
    }

    fn date(release: &Value) -> String {
        release
            .get("published_at")
            .and_then(Value::as_str)
            .or_else(|| release.get("created_at").and_then(Value::as_str))
            .unwrap_or("")
            .to_owned()
    }
}

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

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

    async fn versions(&self, project: &ProjectRef) -> Result<Vec<VersionInfo>> {
        let repo = repo_ref(project, "github", false)?;
        let headers = self.headers();
        let base = Self::repo_url(&repo);
        let releases = get_link_pages(
            self.http.as_ref(),
            &format!("{base}/releases?per_page={PER_PAGE}"),
            &headers,
            "github",
        )
        .await?;
        let tags = get_link_pages(
            self.http.as_ref(),
            &format!("{base}/tags?per_page={PER_PAGE}"),
            &headers,
            "github",
        )
        .await?;

        let mut dated: Vec<(String, VersionInfo)> = releases
            .iter()
            .filter_map(|release| {
                Self::version_from_release(release).map(|info| (Self::date(release), info))
            })
            .collect();
        dated.sort_by(|left, right| right.0.cmp(&left.0));

        let mut versions = Vec::new();
        let mut seen = HashSet::new();
        for (_, info) in dated {
            if seen.insert(info.version.clone()) {
                versions.push(info);
            }
        }
        for tag in tags {
            let Some(raw) = tag.get("name").and_then(Value::as_str) else {
                continue;
            };
            let Some(version) = normalize_tag(raw) else {
                continue;
            };
            if seen.insert(version.clone()) {
                versions.push(VersionInfo {
                    raw: raw.to_owned(),
                    version,
                    deprecated: false,
                    reason: String::new(),
                });
            }
        }
        Ok(versions)
    }

    async fn artifacts(
        &self,
        project: &ProjectRef,
        version: &VersionInfo,
    ) -> Result<Vec<ArtifactInfo>> {
        let repo = repo_ref(project, "github", false)?;
        let raw = if version.raw.is_empty() {
            version.version.as_str()
        } else {
            version.raw.as_str()
        };
        let url = format!(
            "{}/releases/tags/{}",
            Self::repo_url(&repo),
            encode_segment(raw)
        );
        let response = get_response(self.http.as_ref(), &url, &self.headers()).await?;
        if response.status == 404 {
            return Ok(dedupe_artifacts(fallback_archives(&repo, raw)));
        }
        let release = require_json(response, &url, "github")?;
        let mut artifacts = release
            .get("assets")
            .and_then(Value::as_array)
            .map(|assets| assets.iter().filter_map(asset_info).collect::<Vec<_>>())
            .unwrap_or_default();
        if let Some(tarball) = release.get("tarball_url").and_then(Value::as_str) {
            artifacts.push(archive_info(&repo, raw, tarball, true));
        }
        if let Some(zipball) = release.get("zipball_url").and_then(Value::as_str) {
            artifacts.push(archive_info(&repo, raw, zipball, false));
        }
        if artifacts.is_empty() {
            artifacts = fallback_archives(&repo, raw);
        }
        Ok(dedupe_artifacts(artifacts))
    }

    async fn statuses(
        &self,
        project: &ProjectRef,
        version: &VersionInfo,
    ) -> Result<Vec<StatusInfo>> {
        let repo = repo_ref(project, "github", false)?;
        let mut statuses = Vec::new();
        if version.deprecated {
            let has_draft = version.reason.contains("draft");
            let has_prerelease = version.reason.contains("prerelease");
            if has_draft {
                statuses.push(StatusInfo {
                    status: "deprecated".to_owned(),
                    kind: Some("draft".to_owned()),
                    reason: "draft release".to_owned(),
                });
            }
            if has_prerelease {
                statuses.push(StatusInfo {
                    status: "deprecated".to_owned(),
                    kind: Some("prerelease".to_owned()),
                    reason: "prerelease release".to_owned(),
                });
            }
            if !has_draft && !has_prerelease {
                statuses.push(StatusInfo {
                    status: "deprecated".to_owned(),
                    kind: None,
                    reason: version.reason.clone(),
                });
            }
        }
        let meta = self.repo_meta(&repo).await?;
        if meta.get("archived").and_then(Value::as_bool) == Some(true) {
            statuses.push(StatusInfo {
                status: "archived".to_owned(),
                kind: Some("archived".to_owned()),
                reason: "repository is archived".to_owned(),
            });
        }
        Ok(statuses)
    }

    async fn project_meta(&self, project: &ProjectRef) -> Result<Value> {
        let repo = repo_ref(project, "github", false)?;
        let meta = self.repo_meta(&repo).await?;
        let mut out = Map::new();
        if let Some(value) = meta
            .get("html_url")
            .and_then(Value::as_str)
            .filter(|value| !value.is_empty())
        {
            out.insert("repository".to_owned(), Value::String(value.to_owned()));
        }
        if let Some(value) = meta
            .get("homepage")
            .and_then(Value::as_str)
            .filter(|value| !value.is_empty())
        {
            out.insert("homepage".to_owned(), Value::String(value.to_owned()));
        }
        let license = meta.get("license").and_then(|license| {
            license
                .get("spdx_id")
                .and_then(Value::as_str)
                .filter(|value| !value.is_empty() && *value != "NOASSERTION")
                .or_else(|| license.get("name").and_then(Value::as_str))
        });
        if let Some(value) = license.filter(|value| !value.is_empty()) {
            out.insert("license".to_owned(), Value::String(value.to_owned()));
        }
        if let Some(value) = meta
            .get("description")
            .and_then(Value::as_str)
            .filter(|value| !value.is_empty())
        {
            out.insert("description".to_owned(), Value::String(value.to_owned()));
        }
        Ok(Value::Object(out))
    }
}