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

johnandersen777.bsky.social/vuln-notif

0
0
main
221 lines · 7.2 KB Raw History
//! Bitbucket Cloud tags, downloads, and repository metadata.
//!
//! Bitbucket has no release objects, so versions come from tags. Downloads are
//! repository-scoped rather than version-scoped; assets are matched to a
//! version by file name. The downloads listing supplies size and URL but never
//! a digest, so `sha256` stays `None` and the download fallback in
//! `release::artifact` hashes the bytes.

use std::sync::Arc;

use anyhow::{Result, anyhow, bail};
use async_trait::async_trait;
use serde_json::{Map, Value};

use super::github::{
    GitHttp, RepoRef, check_status, dedupe_artifacts, get_response, normalize_tag, repo_ref,
};
use crate::release::source::{
    ArtifactInfo, ProjectRef, ReleaseSource, SourceCapabilities, StatusInfo, UnsupportedReason,
    VersionInfo,
};

pub const BITBUCKET_API: &str = "https://api.bitbucket.org/2.0";
const PAGE_LEN: usize = 100;
const MAX_PAGES: usize = 100;

fn tag_date(tag: &Value) -> String {
    tag.pointer("/target/date")
        .and_then(Value::as_str)
        .unwrap_or("")
        .to_owned()
}

fn download_url(download: &Value) -> Option<&str> {
    download
        .pointer("/links/self/href")
        .and_then(Value::as_str)
        .filter(|url| !url.is_empty())
}

fn names_version(file_name: &str, version: &VersionInfo) -> bool {
    let file_name = file_name.to_ascii_lowercase();
    [version.raw.as_str(), version.version.as_str()]
        .into_iter()
        .filter(|candidate| !candidate.is_empty())
        .any(|candidate| file_name.contains(&candidate.to_ascii_lowercase()))
}

/// Bitbucket Cloud source adapter.
pub struct BitbucketSource {
    http: Arc<dyn GitHttp>,
}

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

    fn repo_url(repo: &RepoRef, suffix: &str) -> String {
        format!("{BITBUCKET_API}/repositories/{}{suffix}", repo.path)
    }

    /// Follow body-level `next` links until exhausted.
    async fn pages(&self, start: &str) -> Result<Vec<Value>> {
        let mut values = 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!("bitbucket: pagination exceeded {MAX_PAGES} pages");
            }
            let response = get_response(self.http.as_ref(), &url, &[]).await?;
            check_status(&response, &url, "bitbucket")?;
            let body = response.body;
            let page = body
                .get("values")
                .and_then(Value::as_array)
                .ok_or_else(|| anyhow!("bitbucket: missing values array from {url}"))?;
            values.extend(page.iter().cloned());
            next = body.get("next").and_then(Value::as_str).map(str::to_owned);
        }
        Ok(values)
    }
}

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

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

    async fn versions(&self, project: &ProjectRef) -> Result<Vec<VersionInfo>> {
        let repo = repo_ref(project, "bitbucket", false)?;
        let tags = self
            .pages(&Self::repo_url(
                &repo,
                &format!("/refs/tags?pagelen={PAGE_LEN}"),
            ))
            .await?;
        let mut dated: Vec<(String, String)> = tags
            .iter()
            .filter_map(|tag| {
                let name = tag.get("name").and_then(Value::as_str)?;
                Some((tag_date(tag), name.to_owned()))
            })
            .collect();
        dated.sort_by(|left, right| right.0.cmp(&left.0));

        let mut versions = Vec::new();
        let mut seen = std::collections::HashSet::new();
        for (_, raw) in dated {
            let Some(version) = normalize_tag(&raw) else {
                continue;
            };
            if seen.insert(version.clone()) {
                versions.push(VersionInfo {
                    raw,
                    version,
                    deprecated: false,
                    reason: String::new(),
                });
            }
        }
        Ok(versions)
    }

    async fn artifacts(
        &self,
        project: &ProjectRef,
        version: &VersionInfo,
    ) -> Result<Vec<ArtifactInfo>> {
        let repo = repo_ref(project, "bitbucket", false)?;
        let downloads = self
            .pages(&Self::repo_url(
                &repo,
                &format!("/downloads?pagelen={PAGE_LEN}"),
            ))
            .await?;
        // ponytail: downloads are repository-scoped, so a version is matched by
        // substring in the file name. Upgrade to per-version metadata if
        // Bitbucket ever exposes it.
        let artifacts = downloads
            .iter()
            .filter_map(|download| {
                let name = download.get("name").and_then(Value::as_str)?;
                if !names_version(name, version) {
                    return None;
                }
                let url = download_url(download)?;
                Some(ArtifactInfo {
                    file_name: name.to_owned(),
                    url: url.to_owned(),
                    sha256: None,
                    size: download.get("size").and_then(Value::as_u64),
                    mime_type: None,
                })
            })
            .collect();
        Ok(dedupe_artifacts(artifacts))
    }

    async fn statuses(
        &self,
        _project: &ProjectRef,
        _version: &VersionInfo,
    ) -> Result<Vec<StatusInfo>> {
        Err(anyhow!(
            "{:?}: bitbucket exposes no release status signals",
            UnsupportedReason::NoStatuses
        ))
    }

    async fn project_meta(&self, project: &ProjectRef) -> Result<Value> {
        let repo = repo_ref(project, "bitbucket", false)?;
        let url = Self::repo_url(&repo, "");
        let response = get_response(self.http.as_ref(), &url, &[]).await?;
        let meta = require_object(response, &url)?;
        let mut out = Map::new();
        if let Some(value) = meta
            .pointer("/links/html/href")
            .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
            .pointer("/links/website/href")
            .and_then(Value::as_str)
            .filter(|value| !value.is_empty())
        {
            out.insert("homepage".to_owned(), Value::String(value.to_owned()));
        }
        // Bitbucket Cloud exposes no license field.
        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))
    }
}

fn require_object(response: super::github::GitResponse, url: &str) -> Result<Value> {
    check_status(&response, url, "bitbucket")?;
    if !response.body.is_object() {
        bail!("bitbucket: expected a repository object from {url}");
    }
    Ok(response.body)
}