Files
pruefwerk/compliance-agent/src/pipeline/git.rs
T
sharang cc5b667870
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Dashboard (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Agent (push) Successful in 6m28s
fix(scheduler): scheduled scans are spread out and at most two clones run per git host (#547)
2026-10-09 14:37:22 +00:00

916 lines
35 KiB
Rust

use std::path::{Path, PathBuf};
use git2::{Cred, FetchOptions, RemoteCallbacks, RemoteRedirect, Repository};
use compliance_core::NetGuard;
use crate::error::AgentError;
use crate::pipeline::git_retry::Backoff;
use crate::tenant_path::{name_segment, tenant_segment};
/// The directory a tenant's checkout of `repo_name` lives in.
///
/// **The single clone-path convention.** Every producer and every consumer of a
/// checkout path goes through here — the orchestrator, PR review, ingest, the
/// graph build, the chat embedding build and the file-content reader. A second
/// convention is how two tenants end up sharing one checkout: before this, both
/// resolved to `<base>/<name>`, so the second tenant to scan a target with the
/// same name fetched the first tenant's `origin` instead of cloning its own.
///
/// Both segments are collapsed to one safe path component, so traversal in
/// either the tenant id or the target name cannot escape `base`.
pub fn clone_dir(base: &Path, tenant_id: &str, repo_name: &str) -> PathBuf {
base.join(tenant_segment(tenant_id))
.join(name_segment(repo_name))
}
/// Reject a git URL that would authenticate with an SSH key.
///
/// At MVP the agent holds no git SSH key at all: it used to authenticate every
/// tenant's clone with one shared deploy key, which is a cross-tenant read
/// primitive (tenant A adds the agent's key to a repo, tenant B names that repo
/// and the agent happily clones it). Per-tenant key management is R1; until
/// then git access is HTTPS-with-a-token only, and an SSH URL fails loudly
/// rather than silently borrowing somebody else's credential.
pub fn reject_ssh_url(git_url: &str) -> Result<(), AgentError> {
let url = git_url.trim();
let is_ssh = url.starts_with("ssh://")
|| url.starts_with("git+ssh://")
// scp-style `git@host:org/repo.git` (no scheme, user before a `:`).
|| url
.split_once('@')
.is_some_and(|(user, rest)| !user.contains("://") && rest.contains(':'));
if is_ssh {
return Err(AgentError::Other(format!(
"SSH git URLs are not supported: '{git_url}'. Use an HTTPS clone URL \
(https://host/org/repo.git) with a personal access token or deploy \
token in the target's credentials."
)));
}
Ok(())
}
/// Credentials for accessing a private repository. HTTPS token only — see
/// [`reject_ssh_url`].
#[derive(Debug, Clone, Default)]
pub struct RepoCredentials {
/// Auth token / password (for HTTPS URLs)
pub auth_token: Option<String>,
/// Username for HTTPS auth (defaults to "x-access-token")
pub auth_username: Option<String>,
}
impl RepoCredentials {
pub(crate) fn make_callbacks(&self) -> RemoteCallbacks<'_> {
let mut callbacks = RemoteCallbacks::new();
let token = self.auth_token.clone();
let username = self.auth_username.clone();
callbacks.credentials(move |_url, _username_from_url, allowed_types| {
// HTTPS userpass authentication. There is deliberately no SSH branch:
// the agent has no key to offer.
if allowed_types.contains(git2::CredentialType::USER_PASS_PLAINTEXT) {
if let Some(ref tok) = token {
let user = username.as_deref().unwrap_or("x-access-token");
return Cred::userpass_plaintext(user, tok);
}
}
Cred::default()
});
callbacks
}
pub(crate) fn fetch_options(&self) -> FetchOptions<'_> {
let mut fetch_opts = FetchOptions::new();
// A redirect could lead anywhere, past the check in `GitOps::check_remote`.
fetch_opts.follow_redirects(RemoteRedirect::None);
if self.has_credentials() {
fetch_opts.remote_callbacks(self.make_callbacks());
}
fetch_opts
}
fn has_credentials(&self) -> bool {
self.auth_token.is_some()
}
}
/// Limits on one clone or fetch, so a huge or slow repository ends the scan
/// with a reason instead of holding a scan slot indefinitely.
///
/// Set per deployment: `GIT_CLONE_TIMEOUT_SECS` (default 1800),
/// `GIT_CLONE_MAX_MB` (default 4096) and `GIT_CLONE_DEPTH` (unset: the full
/// history, which the secret scan of earlier commits and PR reviews need).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CloneLimits {
/// How long the transfer of one clone or fetch may take.
pub timeout: std::time::Duration,
/// How many bytes one clone or fetch may receive.
pub max_bytes: usize,
/// Clone only this many commits of history; `None` clones all of it.
pub depth: Option<i32>,
}
impl Default for CloneLimits {
fn default() -> Self {
Self {
timeout: std::time::Duration::from_secs(1800),
max_bytes: 4096 * 1024 * 1024,
depth: None,
}
}
}
impl CloneLimits {
/// The limits this deployment sets, the defaults where it sets none or
/// an unreadable value.
pub fn from_env() -> Self {
let read = |key: &str| {
std::env::var(key)
.ok()
.and_then(|v| v.trim().parse::<u64>().ok())
};
let defaults = Self::default();
Self {
timeout: read("GIT_CLONE_TIMEOUT_SECS")
.filter(|s| *s > 0)
.map_or(defaults.timeout, std::time::Duration::from_secs),
max_bytes: read("GIT_CLONE_MAX_MB")
.filter(|mb| *mb > 0)
.and_then(|mb| usize::try_from(mb.saturating_mul(1024 * 1024)).ok())
.unwrap_or(defaults.max_bytes),
depth: read("GIT_CLONE_DEPTH")
.filter(|d| *d > 0)
.and_then(|d| i32::try_from(d).ok()),
}
}
/// Why a transfer that has run for `elapsed` and received `bytes` must
/// stop, if it must.
fn exceeded(&self, elapsed: std::time::Duration, bytes: usize) -> Option<String> {
if elapsed > self.timeout {
return Some(format!(
"the repository did not download within {} minutes (GIT_CLONE_TIMEOUT_SECS)",
self.timeout.as_secs() / 60
));
}
(bytes > self.max_bytes).then(|| {
format!(
"the repository is larger than the download limit of {} MB (GIT_CLONE_MAX_MB)",
self.max_bytes / (1024 * 1024)
)
})
}
}
pub struct GitOps {
base_path: PathBuf,
/// The tenant every checkout this instance makes belongs to.
tenant_id: String,
credentials: RepoCredentials,
/// Where a clone or fetch may connect (#256, #294).
net_guard: NetGuard,
/// How long and how large a clone or fetch may be.
limits: CloneLimits,
/// When a clone or fetch the host failed briefly is tried again.
backoff: Backoff,
}
impl GitOps {
pub fn new(
base_path: &str,
tenant_id: &str,
credentials: RepoCredentials,
net_guard: NetGuard,
) -> Self {
Self {
base_path: PathBuf::from(base_path),
tenant_id: tenant_id.to_string(),
credentials,
net_guard,
limits: CloneLimits::from_env(),
backoff: Backoff::default(),
}
}
/// The same operations with other limits (tests).
#[cfg(test)]
fn with_limits(mut self, limits: CloneLimits) -> Self {
self.limits = limits;
self
}
/// The same operations with another retry schedule (tests).
#[cfg(test)]
fn with_backoff(mut self, backoff: Backoff) -> Self {
self.backoff = backoff;
self
}
/// When this instance tries a failed clone or fetch again.
pub(crate) fn backoff(&self) -> &Backoff {
&self.backoff
}
/// Fetch options for one bounded transfer: the credentials, no
/// redirects, and a progress check that stops the transfer once it
/// exceeds [`CloneLimits`], leaving the reason in `stopped`.
fn limited_fetch_options<'a>(
&'a self,
stopped: &'a std::cell::RefCell<Option<String>>,
depth: Option<i32>,
) -> FetchOptions<'a> {
let mut callbacks = if self.credentials.has_credentials() {
self.credentials.make_callbacks()
} else {
RemoteCallbacks::new()
};
let started = std::time::Instant::now();
let limits = self.limits;
callbacks.transfer_progress(move |progress| {
match limits.exceeded(started.elapsed(), progress.received_bytes()) {
Some(reason) => {
*stopped.borrow_mut() = Some(reason);
false
}
None => true,
}
});
let mut fetch_opts = FetchOptions::new();
// A redirect could lead anywhere, past the check in `check_remote`.
fetch_opts.follow_redirects(RemoteRedirect::None);
fetch_opts.remote_callbacks(callbacks);
if let Some(depth) = depth {
fetch_opts.depth(depth);
}
fetch_opts
}
/// `error`, or the limit that stopped the transfer if one did.
fn transfer_error(
stopped: std::cell::RefCell<Option<String>>,
error: git2::Error,
) -> AgentError {
match stopped.into_inner() {
Some(reason) => AgentError::Other(reason),
None => error.into(),
}
}
/// Refuse a remote whose host is internal or resolves to a non-public
/// address, right before connecting to it.
///
/// libgit2 resolves the host itself and cannot be given a pinned address,
/// so a name that changes its answer between this check and libgit2's own
/// lookup (DNS rebinding at near-zero TTL) is not covered; redirects are
/// off, so the connection cannot be sent anywhere else. Checked on every
/// fetch too, because a remote's DNS can change after the clone.
pub(crate) fn check_remote(&self, git_url: &str) -> Result<(), AgentError> {
let remote = self
.net_guard
.check_git_url(git_url)
.map_err(|e| AgentError::Other(e.to_string()))?;
let port = remote
.port
.unwrap_or(if remote.scheme == "http" { 80 } else { 443 });
self.net_guard
.check_resolved(&remote.host, port)
.map_err(|e| AgentError::Other(e.to_string()))
}
/// The host of a git URL, if it is one this deployment may reach.
pub(crate) fn remote_host(&self, git_url: &str) -> Option<String> {
self.net_guard.check_git_url(git_url).ok().map(|r| r.host)
}
/// The credentials this instance clones with.
pub(crate) fn credentials(&self) -> &RepoCredentials {
&self.credentials
}
/// Where this instance's tenant keeps its checkout of `repo_name`.
pub fn clone_path(&self, repo_name: &str) -> PathBuf {
clone_dir(&self.base_path, &self.tenant_id, repo_name)
}
#[tracing::instrument(skip_all, fields(tenant = %self.tenant_id, repo_name = %repo_name))]
pub fn clone_or_fetch(&self, git_url: &str, repo_name: &str) -> Result<PathBuf, AgentError> {
reject_ssh_url(git_url)?;
// At most two clones or fetches per git host, held to the end of this
// one; a refused remote has no host and fails below anyway.
let _host_slot = self
.remote_host(git_url)
.map(|host| crate::pipeline::clone_limit::CLONE_SLOTS.acquire(&host));
// Per tenant: two tenants with the same target name get two checkouts.
let repo_path = self.clone_path(repo_name);
// A cache entry a redeploy interrupted (an empty directory, a
// half-written reference, a lock) is cloned again, never left to fail
// every scan after it (#486).
if repo_path.exists() && prepare_entry(&repo_path) {
tracing::info!("fetching updates for existing repo");
// A 502 is retried before it can be taken for a broken entry.
match self.backoff.retry("fetch", || self.fetch(&repo_path)) {
Ok(()) => return Ok(repo_path),
Err(AgentError::Git(e)) if is_corruption(&e) => {
tracing::warn!(
tenant_id = %self.tenant_id,
target = %repo_name,
error = %e,
"clone cache entry is broken; cloning it again"
);
std::fs::remove_dir_all(&repo_path)?;
}
Err(e) => return Err(e),
}
} else if repo_path.exists() {
tracing::warn!(
tenant_id = %self.tenant_id,
target = %repo_name,
"clone cache entry is not a usable repository; cloning it again"
);
std::fs::remove_dir_all(&repo_path)?;
}
// Before creating anything: a refused remote must not leave an entry
// behind for the next run to try to fetch.
self.check_remote(git_url)?;
self.backoff
.retry("clone", || self.clone_atomically(git_url, &repo_path))?;
tracing::info!("Cloned {git_url} to {}", repo_path.display());
Ok(repo_path)
}
/// Clone into a directory next to `repo_path` and move it into place, so
/// an interrupted clone never leaves a half entry. Directories an earlier
/// interrupted clone left are removed first.
fn clone_atomically(&self, git_url: &str, repo_path: &Path) -> Result<(), AgentError> {
let parent = repo_path
.parent()
.ok_or_else(|| AgentError::Other("clone path has no parent".to_string()))?;
std::fs::create_dir_all(parent)?;
let prefix = temp_prefix(repo_path);
for leftover in std::fs::read_dir(parent)?.filter_map(Result::ok) {
if leftover.file_name().to_string_lossy().starts_with(&prefix) {
let _ = std::fs::remove_dir_all(leftover.path());
}
}
let temp = parent.join(format!("{prefix}{}", uuid::Uuid::new_v4()));
if let Err(e) = self.clone_repo(git_url, &temp) {
let _ = std::fs::remove_dir_all(&temp);
return Err(e);
}
if let Err(e) = std::fs::rename(&temp, repo_path) {
let _ = std::fs::remove_dir_all(&temp);
return Err(e.into());
}
Ok(())
}
#[tracing::instrument(skip_all)]
fn clone_repo(&self, git_url: &str, repo_path: &Path) -> Result<(), AgentError> {
tracing::info!("cloning repo from {}", git_url);
let stopped = std::cell::RefCell::new(None);
let mut builder = git2::build::RepoBuilder::new();
builder.fetch_options(self.limited_fetch_options(&stopped, self.limits.depth));
let cloned = builder.clone(git_url, repo_path);
drop(builder);
cloned
.map(drop)
.map_err(|e| Self::transfer_error(stopped, e))
}
fn fetch(&self, repo_path: &Path) -> Result<(), AgentError> {
let repo = Repository::open(repo_path)?;
let mut remote = repo.find_remote("origin")?;
self.check_remote(remote.url().unwrap_or_default())?;
let stopped = std::cell::RefCell::new(None);
let mut fetch_opts = self.limited_fetch_options(&stopped, None);
let fetched = remote.fetch(&[] as &[&str], Some(&mut fetch_opts), None);
drop(fetch_opts);
fetched.map_err(|e| Self::transfer_error(stopped, e))?;
// Fast-forward to origin/HEAD
let fetch_head = repo.find_reference("FETCH_HEAD")?;
let fetch_commit = repo.reference_to_annotated_commit(&fetch_head)?;
let head_ref = repo.head()?;
let head_name = head_ref.name().unwrap_or("HEAD");
repo.reference(head_name, fetch_commit.id(), true, "fast-forward")?;
repo.checkout_head(Some(git2::build::CheckoutBuilder::default().force()))?;
tracing::info!("Fetched and fast-forwarded {}", repo_path.display());
Ok(())
}
/// The patterns `.gitattributes` keeps in Git LFS (`*.psd filter=lfs …`).
/// libgit2 runs no LFS filter, so those files stay pointer files in the
/// checkout: their content is neither downloaded nor scanned.
pub fn lfs_patterns(repo_path: &Path) -> Vec<String> {
std::fs::read_to_string(repo_path.join(".gitattributes"))
.map(|text| {
text.lines()
.filter(|line| line.contains("filter=lfs"))
.filter_map(|line| line.split_whitespace().next())
.filter(|pattern| !pattern.starts_with('#'))
.map(str::to_string)
.collect()
})
.unwrap_or_default()
}
/// Build credentials from a repo view's own HTTPS token. There is no
/// agent-wide fallback credential any more — see [`reject_ssh_url`].
pub fn make_repo_credentials(repo: &crate::pipeline::repo_view::RepoView) -> RepoCredentials {
RepoCredentials {
auth_token: repo.auth_token.clone(),
auth_username: repo.auth_username.clone(),
}
}
pub fn get_head_sha(repo_path: &Path) -> Result<String, AgentError> {
let repo = Repository::open(repo_path)?;
let head = repo.head()?;
let commit = head.peel_to_commit()?;
Ok(commit.id().to_string())
}
pub fn has_new_commits(repo_path: &Path, last_sha: Option<&str>) -> Result<bool, AgentError> {
let current_sha = Self::get_head_sha(repo_path)?;
match last_sha {
Some(sha) if sha == current_sha => Ok(false),
_ => Ok(true),
}
}
/// Extract structured diff content between two commits
pub fn get_diff_content(
repo_path: &Path,
old_sha: &str,
new_sha: &str,
) -> Result<Vec<DiffFile>, AgentError> {
let repo = Repository::open(repo_path)?;
let old_commit = repo.find_commit(git2::Oid::from_str(old_sha)?)?;
let new_commit = repo.find_commit(git2::Oid::from_str(new_sha)?)?;
let old_tree = old_commit.tree()?;
let new_tree = new_commit.tree()?;
let diff = repo.diff_tree_to_tree(Some(&old_tree), Some(&new_tree), None)?;
let mut diff_files: Vec<DiffFile> = Vec::new();
diff.print(git2::DiffFormat::Patch, |delta, _hunk, line| {
let file_path = delta
.new_file()
.path()
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_default();
// Find or create the DiffFile entry
let idx = if let Some(pos) = diff_files.iter().position(|f| f.path == file_path) {
pos
} else {
diff_files.push(DiffFile {
path: file_path,
hunks: String::new(),
});
diff_files.len() - 1
};
let diff_file = &mut diff_files[idx];
let prefix = match line.origin() {
'+' => "+",
'-' => "-",
' ' => " ",
_ => "",
};
let content = std::str::from_utf8(line.content()).unwrap_or("");
diff_file.hunks.push_str(prefix);
diff_file.hunks.push_str(content);
true
})?;
// Filter out binary files and very large diffs
diff_files.retain(|f| !f.hunks.is_empty() && f.hunks.len() < 50_000);
Ok(diff_files)
}
#[allow(dead_code)]
pub fn get_changed_files(
repo_path: &Path,
old_sha: &str,
new_sha: &str,
) -> Result<Vec<String>, AgentError> {
let repo = Repository::open(repo_path)?;
let old_commit = repo.find_commit(git2::Oid::from_str(old_sha)?)?;
let new_commit = repo.find_commit(git2::Oid::from_str(new_sha)?)?;
let old_tree = old_commit.tree()?;
let new_tree = new_commit.tree()?;
let diff = repo.diff_tree_to_tree(Some(&old_tree), Some(&new_tree), None)?;
let mut files = Vec::new();
diff.foreach(
&mut |delta, _| {
if let Some(path) = delta.new_file().path() {
files.push(path.to_string_lossy().to_string());
}
true
},
None,
None,
None,
)?;
Ok(files)
}
}
/// A file changed between two commits with its diff content
#[derive(Debug, Clone)]
pub struct DiffFile {
pub path: String,
pub hunks: String,
}
/// The name prefix of the directory a clone of `repo_path` is made in.
fn temp_prefix(repo_path: &Path) -> String {
let name = repo_path
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_default();
format!(".{name}.cloning-")
}
/// Make a clone cache entry ready to fetch into: remove what an interrupted
/// fetch leaves (`FETCH_HEAD`, which every fetch writes anew, and `*.lock`
/// files; a target's scans never overlap, so no other git holds them), then
/// check that it opens as a repository with an `origin`.
///
/// # Returns
///
/// `false` when the entry is not a usable repository (an empty directory
/// from an interrupted clone, a broken `.git`): the caller clones it again.
fn prepare_entry(repo_path: &Path) -> bool {
let git_dir = repo_path.join(".git");
let _ = std::fs::remove_file(git_dir.join("FETCH_HEAD"));
let locks = walkdir::WalkDir::new(&git_dir)
.max_depth(6)
.into_iter()
.filter_map(Result::ok)
.filter(|e| e.file_type().is_file() && e.file_name().to_string_lossy().ends_with(".lock"));
for lock in locks {
tracing::warn!(path = %lock.path().display(), "removing a lock an interrupted git left");
let _ = std::fs::remove_file(lock.path());
}
// Only what the fetch needs to start: whatever else is broken shows as a
// corruption error there, after the stored remote was checked again.
Repository::open(repo_path)
.and_then(|repo| repo.find_remote("origin").map(drop))
.is_ok()
}
/// Whether a git error means the cache entry itself is broken (a missing or
/// corrupt repository, reference or object), not the network or the remote.
fn is_corruption(error: &git2::Error) -> bool {
use git2::ErrorClass;
matches!(
error.class(),
ErrorClass::Repository
| ErrorClass::Reference
| ErrorClass::Odb
| ErrorClass::Object
| ErrorClass::Index
| ErrorClass::Checkout
)
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::{clone_dir, reject_ssh_url, CloneLimits, GitOps, RepoCredentials};
use compliance_core::NetGuard;
use std::path::Path;
const BASE: &str = "/data/repos";
#[test]
fn a_transfer_stops_past_its_time_or_size() {
let limits = CloneLimits {
timeout: std::time::Duration::from_secs(60),
max_bytes: 1024,
depth: None,
};
let second = std::time::Duration::from_secs(1);
assert_eq!(limits.exceeded(second, 512), None);
assert!(limits
.exceeded(second, 2048)
.is_some_and(|r| r.contains("GIT_CLONE_MAX_MB")));
assert!(limits
.exceeded(std::time::Duration::from_secs(61), 0)
.is_some_and(|r| r.contains("GIT_CLONE_TIMEOUT_SECS")));
}
#[test]
fn the_defaults_clone_the_full_history_within_limits() {
let limits = CloneLimits::default();
assert_eq!(limits.depth, None);
assert_eq!(limits.max_bytes, 4096 * 1024 * 1024);
assert_eq!(limits.timeout.as_secs(), 1800);
}
/// A repository with one commit and an `origin`, in a fresh directory.
fn source_repo() -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("cs-src-{}", uuid::Uuid::new_v4()));
let repo = git2::Repository::init(&dir).unwrap();
std::fs::write(dir.join("README.md"), "pump controller").unwrap();
let mut index = repo.index().unwrap();
index.add_path(Path::new("README.md")).unwrap();
index.write().unwrap();
let tree = repo.find_tree(index.write_tree().unwrap()).unwrap();
let sig = git2::Signature::now("t", "t@example.com").unwrap();
repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[])
.unwrap();
repo.remote("origin", "https://git.example.com/pumps/ctl.git")
.unwrap();
dir
}
#[test]
fn a_broken_cache_entry_is_recognised_and_leftovers_cleared() {
// An interrupted clone: the directory exists, the repository does not.
let empty = std::env::temp_dir().join(format!("cs-empty-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&empty).unwrap();
assert!(!super::prepare_entry(&empty));
let Err(opened) = git2::Repository::open(&empty) else {
panic!("an empty directory opened as a repository");
};
assert!(super::is_corruption(&opened));
std::fs::remove_dir_all(&empty).unwrap();
// An interrupted fetch: a half-written FETCH_HEAD and locks.
let repo = source_repo();
let git = repo.join(".git");
std::fs::write(git.join("FETCH_HEAD"), "\0garbage").unwrap();
std::fs::write(git.join("index.lock"), "").unwrap();
std::fs::write(git.join("refs/heads/main.lock"), "").unwrap();
assert!(super::prepare_entry(&repo));
assert!(!git.join("FETCH_HEAD").exists());
assert!(!git.join("index.lock").exists());
assert!(!git.join("refs/heads/main.lock").exists());
std::fs::remove_dir_all(&repo).unwrap();
// The network or the remote are not the entry's fault.
let net = git2::Error::new(
git2::ErrorCode::GenericError,
git2::ErrorClass::Net,
"connection reset",
);
assert!(!super::is_corruption(&net));
}
#[test]
fn a_clone_appears_whole_or_not_at_all() {
let source = source_repo();
let base = std::env::temp_dir().join(format!("cs-cache-{}", uuid::Uuid::new_v4()));
let ops = GitOps::new(
base.to_str().unwrap(),
"tenant-a",
RepoCredentials::default(),
NetGuard::allow_private(),
);
let entry = ops.clone_path("pump-ctl");
// What an earlier interrupted clone left beside the entry.
let leftover = entry
.parent()
.unwrap()
.join(format!("{}stale", super::temp_prefix(&entry)));
std::fs::create_dir_all(&leftover).unwrap();
ops.clone_atomically(source.to_str().unwrap(), &entry)
.unwrap();
assert!(entry.join("README.md").is_file());
assert!(!leftover.exists());
let siblings: Vec<String> = std::fs::read_dir(entry.parent().unwrap())
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().to_string())
.collect();
assert_eq!(siblings.len(), 1, "{siblings:?}");
// A clone that fails leaves nothing behind.
let missing = ops.clone_path("missing");
assert!(ops
.clone_atomically("/nonexistent/repository", &missing)
.is_err());
assert!(!missing.exists());
let _ = std::fs::remove_dir_all(&base);
let _ = std::fs::remove_dir_all(&source);
}
#[test]
fn lfs_patterns_come_from_gitattributes() {
let dir = std::env::temp_dir().join(format!("cs-lfs-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join(".gitattributes"),
"*.psd filter=lfs diff=lfs merge=lfs -text\n*.txt text\nAssets/**/*.fbx filter=lfs diff=lfs merge=lfs -text\n",
)
.unwrap();
assert_eq!(GitOps::lfs_patterns(&dir), ["*.psd", "Assets/**/*.fbx"]);
std::fs::remove_dir_all(&dir).unwrap();
assert!(GitOps::lfs_patterns(&dir).is_empty());
}
#[test]
fn same_target_name_in_two_tenants_gets_two_directories() {
let a = clone_dir(Path::new(BASE), "tenant-a", "acme-firmware");
let b = clone_dir(Path::new(BASE), "tenant-b", "acme-firmware");
assert_ne!(a, b, "two tenants must not share a checkout");
assert_eq!(a, Path::new("/data/repos/tenant-a/acme-firmware"));
assert_eq!(b, Path::new("/data/repos/tenant-b/acme-firmware"));
}
#[test]
fn clone_dir_is_stable_for_the_same_tenant_and_name() {
assert_eq!(
clone_dir(Path::new(BASE), "t1", "repo"),
clone_dir(Path::new(BASE), "t1", "repo")
);
}
#[test]
fn clone_dir_sanitises_traversal_in_the_target_name() {
let p = clone_dir(Path::new(BASE), "t1", "../../etc/passwd");
assert_eq!(p, Path::new("/data/repos/t1/etc_passwd"));
assert!(p.starts_with("/data/repos/t1"));
assert_eq!(
clone_dir(
Path::new(BASE),
"t1",
"ChristianRinn/bare_metal_stm32f411xe"
),
Path::new("/data/repos/t1/ChristianRinn_bare_metal_stm32f411xe")
);
}
#[test]
fn clone_dir_sanitises_traversal_in_the_tenant_id() {
let p = clone_dir(Path::new(BASE), "../../../etc", "repo");
assert!(
p.starts_with("/data/repos"),
"{} escaped the clone base",
p.display()
);
// Exactly base + two components: nothing nested, nothing climbed.
assert_eq!(
p.components().count(),
Path::new(BASE).components().count() + 2
);
}
#[test]
fn ssh_urls_are_rejected_with_an_https_hint() {
for url in [
"ssh://git@github.com/org/repo.git",
"git@github.com:org/repo.git",
"git+ssh://git@git.example.com/org/repo.git",
" git@gitlab.com:org/repo.git ",
] {
let msg = match reject_ssh_url(url) {
Err(e) => e.to_string(),
Ok(()) => panic!("{url} should be rejected"),
};
assert!(msg.contains("HTTPS"), "{url}: {msg}");
}
}
#[test]
fn https_urls_are_accepted() {
for url in [
"https://github.com/org/repo.git",
"https://x-access-token:tok@github.com/org/repo.git",
"http://internal.example.com/org/repo.git",
] {
assert!(reject_ssh_url(url).is_ok(), "{url} should be accepted");
}
}
/// A scratch clone base, removed on drop.
struct Scratch(std::path::PathBuf);
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn git_ops(base: &Path) -> GitOps {
GitOps::new(
&base.to_string_lossy(),
"tenant-a",
RepoCredentials::default(),
NetGuard::public_only(),
)
}
/// Against a real public repository; run with `--ignored` and network.
#[test]
#[ignore = "needs network"]
fn a_clone_past_its_size_limit_stops_and_leaves_nothing_behind() {
let scratch =
Scratch(std::env::temp_dir().join(format!("cs-git-{}", uuid::Uuid::new_v4())));
let ops = git_ops(&scratch.0).with_limits(CloneLimits {
max_bytes: 64 * 1024,
..CloneLimits::default()
});
let err = ops
.clone_or_fetch("https://github.com/github/gitignore.git", "big")
.expect_err("over the limit");
assert!(err.to_string().contains("GIT_CLONE_MAX_MB"), "{err}");
assert!(!ops.clone_path("big").exists(), "no half-cloned directory");
let small = git_ops(&scratch.0)
.clone_or_fetch("https://github.com/octocat/Hello-World.git", "small")
.expect("within the limits");
assert!(small.join("README").exists());
}
#[test]
fn a_remote_on_a_private_address_is_refused_before_connecting() {
let scratch =
Scratch(std::env::temp_dir().join(format!("cs-git-{}", uuid::Uuid::new_v4())));
let ops = git_ops(&scratch.0);
let err = ops
.clone_or_fetch("http://169.254.169.254/latest/x.git", "metadata")
.expect_err("metadata address must be refused");
assert!(err.to_string().contains("not a public address"), "{err}");
assert!(
!ops.clone_path("metadata").exists(),
"a refused clone leaves no checkout behind"
);
}
#[test]
fn a_clone_the_host_answers_with_502_is_tried_four_times() {
// A git host that answers every request with 502, counting them.
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
let port = listener.local_addr().expect("addr").port();
let requests = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let counted = std::sync::Arc::clone(&requests);
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(mut stream) = stream else { break };
counted.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let mut buf = [0u8; 4096];
let _ = std::io::Read::read(&mut stream, &mut buf);
let _ = std::io::Write::write_all(
&mut stream,
b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
);
}
});
let scratch =
Scratch(std::env::temp_dir().join(format!("cs-git-{}", uuid::Uuid::new_v4())));
let ops = GitOps::new(
&scratch.0.to_string_lossy(),
"tenant-a",
RepoCredentials::default(),
NetGuard::allow_private(),
)
.with_backoff(crate::pipeline::git_retry::Backoff::immediate());
let err = ops
.clone_or_fetch(&format!("http://127.0.0.1:{port}/org/repo.git"), "flaky")
.expect_err("the host never recovers");
assert!(err.to_string().contains("502"), "{err}");
assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 4);
assert!(!ops.clone_path("flaky").exists());
}
#[test]
fn a_fetch_rechecks_the_stored_remote() {
// An existing checkout whose `origin` now points somewhere private (a
// remote's DNS or config can change after the clone): the fetch must
// be refused, not trusted because the clone once passed.
let scratch =
Scratch(std::env::temp_dir().join(format!("cs-git-{}", uuid::Uuid::new_v4())));
let ops = git_ops(&scratch.0);
let path = ops.clone_path("existing");
let repo = git2::Repository::init(&path).expect("init");
repo.remote("origin", "http://10.0.0.5/internal.git")
.expect("set origin");
let err = ops
.clone_or_fetch("https://example.com/org/repo.git", "existing")
.expect_err("private origin must be refused");
assert!(err.to_string().contains("10.0.0.5"), "{err}");
}
}