//! The bits of the Gitea API a managed git source needs: the organisation's //! repository list, and the repository shape shared with webhook payloads. use compliance_core::guarded_net::guarded_client_builder; use compliance_core::NetGuard; use secrecy::{ExposeSecret, SecretString}; use serde::Deserialize; use crate::error::AgentError; /// Repositories per page when listing an organisation. const PAGE_SIZE: usize = 50; /// Upper bound on pages (10 000 repositories), so a misbehaving server cannot /// keep the sync looping. const MAX_PAGES: usize = 200; /// A repository as Gitea describes it, in the org repository list and in the /// `repository` and `push` webhook payloads. #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub struct GiteaRepo { /// Gitea's id: stable across renames and transfers. pub id: i64, pub name: String, pub full_name: String, #[serde(default)] pub owner: Option, #[serde(default)] pub default_branch: String, /// A repository without any commit yet. #[serde(default)] pub empty: bool, /// Archived (read-only) in Gitea. #[serde(default)] pub archived: bool, } /// A repository owner (user or organisation). #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub struct GiteaOwner { #[serde(default)] pub login: String, } impl GiteaRepo { /// The owner's login: from `owner`, else the first part of `full_name`. pub fn owner_login(&self) -> &str { match &self.owner { Some(o) if !o.login.is_empty() => &o.login, _ => self.full_name.split('/').next().unwrap_or_default(), } } /// Whether the repository belongs to `org` (Gitea logins are /// case-insensitive). pub fn in_org(&self, org: &str) -> bool { self.owner_login().eq_ignore_ascii_case(org) } /// The branch scans follow; `main` when Gitea does not say. pub fn branch(&self) -> &str { if self.default_branch.is_empty() { "main" } else { &self.default_branch } } } /// Something that can list an organisation's repositories. The sync works /// against this, so it can be tested without a Gitea. pub trait RepoLister { /// Every repository of `org`. fn list_org_repos( &self, org: &str, ) -> impl std::future::Future, AgentError>> + Send; } /// The bot's client for one Gitea instance. Guarded like every other call to /// a tenant-chosen address (#294). pub struct SourceClient { base_url: String, token: SecretString, http: reqwest::Client, } impl SourceClient { /// A client for `base_url` acting with the bot `token`. /// /// # Errors /// /// Returns an error if the HTTP client cannot be built. pub fn new(base_url: &str, token: SecretString, guard: NetGuard) -> Result { let http = guarded_client_builder(guard) .timeout(std::time::Duration::from_secs(30)) .build() .map_err(|e| AgentError::Other(format!("Gitea client: {e}")))?; Ok(Self { base_url: base_url.trim_end_matches('/').to_string(), token, http, }) } } impl RepoLister for SourceClient { async fn list_org_repos(&self, org: &str) -> Result, AgentError> { let mut repos = Vec::new(); for page in 1..=MAX_PAGES { let url = format!( "{}/api/v1/orgs/{}/repos?page={page}&limit={PAGE_SIZE}", self.base_url, urlencoding::encode(org) ); // One of the instance's two request slots, shared with the issue // tracker, held until the page has been read. let _permit = crate::trackers::gitea_limit::acquire(&self.base_url) .await .map_err(|e| AgentError::Other(format!("Gitea request slot: {e}")))?; let resp = self .http .get(&url) .header( "Authorization", format!("token {}", self.token.expose_secret()), ) .send() .await?; if !resp.status().is_success() { return Err(AgentError::Other(format!( "Gitea listing the repositories of '{org}' returned {}", resp.status() ))); } let batch: Vec = resp.json().await?; // Only an empty page ends the list: an instance may cap the page // size below `PAGE_SIZE` (`[api] MAX_RESPONSE_ITEMS`), and taking // a short page for the last one would archive every repository // after it. if batch.is_empty() { return Ok(repos); } repos.extend(batch); } Err(AgentError::Other(format!( "'{org}' lists more than {} repositories; sync stopped", PAGE_SIZE * MAX_PAGES ))) } } #[cfg(test)] #[allow(clippy::expect_used, clippy::unwrap_used)] mod tests { use std::sync::{Arc, Mutex}; use axum::extract::{Path, Query}; use axum::http::HeaderMap; use axum::routing::get; use axum::{Json, Router}; use super::*; fn repo(id: i64, full_name: &str) -> serde_json::Value { let (owner, name) = full_name.split_once('/').unwrap(); serde_json::json!({ "id": id, "name": name, "full_name": full_name, "owner": { "login": owner }, "default_branch": "main", "empty": false, "archived": false, "clone_url": format!("https://elsewhere.invalid/{full_name}.git"), }) } /// A fake Gitea serving `total` repositories of org `kunde`, paginated. async fn fake_gitea(total: i64, cap: i64, seen: Arc>>) -> String { let app = Router::new().route( "/api/v1/orgs/{org}/repos", get( move |Path(org): Path, Query(q): Query>, headers: HeaderMap| { let seen = seen.clone(); async move { seen.lock().unwrap().push(format!( "{org} page={} auth={}", q["page"], headers["authorization"].to_str().unwrap() )); let page: i64 = q["page"].parse().unwrap(); let limit: i64 = q["limit"].parse::().unwrap().min(cap); let from = (page - 1) * limit + 1; let to = (page * limit).min(total); let items: Vec<_> = (from..=to) .map(|i| repo(i, &format!("kunde/r{i}"))) .collect(); Json(items) } }, ), ); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); format!("http://{addr}") } #[tokio::test] async fn lists_every_page_with_the_bot_token() { let seen = Arc::new(Mutex::new(Vec::new())); let base = fake_gitea(120, 50, seen.clone()).await; let client = SourceClient::new( &base, SecretString::from("bot-tok"), NetGuard::allow_private(), ) .unwrap(); let repos = client.list_org_repos("kunde").await.unwrap(); assert_eq!(repos.len(), 120); assert_eq!(repos[119].full_name, "kunde/r120"); let seen = seen.lock().unwrap(); assert_eq!( *seen, [ "kunde page=1 auth=token bot-tok", "kunde page=2 auth=token bot-tok", "kunde page=3 auth=token bot-tok", "kunde page=4 auth=token bot-tok", ] ); } #[tokio::test] async fn an_exact_multiple_of_the_page_size_ends_on_an_empty_page() { let seen = Arc::new(Mutex::new(Vec::new())); let base = fake_gitea(50, 50, seen.clone()).await; let client = SourceClient::new(&base, SecretString::from("t"), NetGuard::allow_private()).unwrap(); assert_eq!(client.list_org_repos("kunde").await.unwrap().len(), 50); assert_eq!(seen.lock().unwrap().len(), 2); } #[tokio::test] async fn a_capped_page_size_is_not_taken_for_the_end() { // An instance with MAX_RESPONSE_ITEMS=30 answers 30 per page. let seen = Arc::new(Mutex::new(Vec::new())); let base = fake_gitea(70, 30, seen.clone()).await; let client = SourceClient::new(&base, SecretString::from("t"), NetGuard::allow_private()).unwrap(); assert_eq!(client.list_org_repos("kunde").await.unwrap().len(), 70); } #[test] fn owner_falls_back_to_the_full_name() { let r: GiteaRepo = serde_json::from_value(serde_json::json!({ "id": 1, "name": "a", "full_name": "Kunde/a" })) .unwrap(); assert_eq!(r.owner_login(), "Kunde"); assert!(r.in_org("kunde")); assert!(!r.in_org("other")); assert_eq!(r.branch(), "main"); } }