From 2cbd98e5c0d634883258c42f0c424e73032afccc Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Mon, 5 Oct 2026 14:05:19 +0000 Subject: [PATCH] feat(git): bounded clones, Git LFS made visible, app build output left out (#450) --- compliance-agent/src/pipeline/git.rs | 227 +++++++++++++++++- compliance-agent/src/pipeline/orchestrator.rs | 16 ++ compliance-agent/src/pipeline/vendor.rs | 76 +++++- compliance-core/src/models/scan.rs | 3 + compliance-dashboard/src/i18n/texts.rs | 12 + docs/guide/repositories.md | 14 ++ docs/reference/tools.md | 7 +- 7 files changed, 345 insertions(+), 10 deletions(-) diff --git a/compliance-agent/src/pipeline/git.rs b/compliance-agent/src/pipeline/git.rs index 9095599..60237f6 100644 --- a/compliance-agent/src/pipeline/git.rs +++ b/compliance-agent/src/pipeline/git.rs @@ -96,6 +96,74 @@ impl RepoCredentials { } } +/// 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, +} + +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::().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 { + 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. @@ -103,6 +171,8 @@ pub struct GitOps { 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, } impl GitOps { @@ -117,6 +187,59 @@ impl GitOps { tenant_id: tenant_id.to_string(), credentials, net_guard, + limits: CloneLimits::from_env(), + } + } + + /// The same operations with other limits (tests). + #[cfg(test)] + fn with_limits(mut self, limits: CloneLimits) -> Self { + self.limits = limits; + self + } + + /// 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>, + depth: Option, + ) -> 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>, + error: git2::Error, + ) -> AgentError { + match stopped.into_inner() { + Some(reason) => AgentError::Other(reason), + None => error.into(), } } @@ -170,7 +293,12 @@ impl GitOps { // an empty checkout behind for the next run to try to fetch. self.check_remote(git_url)?; std::fs::create_dir_all(&repo_path)?; - self.clone_repo(git_url, &repo_path)?; + if let Err(e) = self.clone_repo(git_url, &repo_path) { + // A half-cloned directory would be fetched, not cloned, next + // time. + let _ = std::fs::remove_dir_all(&repo_path); + return Err(e); + } tracing::info!("Cloned {git_url} to {}", repo_path.display()); } @@ -180,19 +308,25 @@ impl GitOps { #[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(); - let fetch_opts = self.credentials.fetch_options(); - builder.fetch_options(fetch_opts); - builder.clone(git_url, repo_path)?; - Ok(()) + 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 mut fetch_opts = self.credentials.fetch_options(); - remote.fetch(&[] as &[&str], Some(&mut fetch_opts), None)?; + 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")?; @@ -207,6 +341,22 @@ impl GitOps { 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 { + 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 { @@ -329,12 +479,51 @@ pub struct DiffFile { #[cfg(test)] #[allow(clippy::expect_used, clippy::unwrap_used)] mod tests { - use super::{clone_dir, reject_ssh_url, GitOps, RepoCredentials}; + 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); + } + + #[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"); @@ -426,6 +615,28 @@ mod tests { ) } + /// 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 = diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 38a0cbb..d02e37a 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -88,6 +88,22 @@ impl PipelineOrchestrator { self.net_guard, ); let repo_path = git_ops.clone_or_fetch(&repo.git_url, &repo.checkout)?; + let lfs = GitOps::lfs_patterns(&repo_path); + if !lfs.is_empty() { + self.skip_stage( + scan_run_id, + SkippedStage::new( + "lfs_objects", + SkipCode::LfsNotFetched, + format!( + "files stored in Git LFS were not downloaded and not scanned: {}", + lfs.join(", ") + ), + ) + .about(lfs.join(", ")), + ) + .await; + } // A scheduled or webhook scan of an unchanged repository has nothing // new to find; one a person started always runs (after an update of diff --git a/compliance-agent/src/pipeline/vendor.rs b/compliance-agent/src/pipeline/vendor.rs index 751d0a1..3391159 100644 --- a/compliance-agent/src/pipeline/vendor.rs +++ b/compliance-agent/src/pipeline/vendor.rs @@ -130,10 +130,47 @@ fn is_vendor_dir(name: &str, path: &Path) -> bool { } // STM32Cube generates `Core/` for the application and `Drivers/` for the // HAL, CMSIS and BSP. Only in that layout is `Drivers/` the vendor's. - name == "drivers" + if name == "drivers" && path .parent() .is_some_and(|parent| has_child_dir(parent, "core")) + { + return true; + } + is_mobile_build_dir(name, path) +} + +/// Unity's generated folders, next to its `ProjectSettings/`. +const UNITY_GENERATED: &[&str] = &["library", "temp", "obj", "logs", "builds", "usersettings"]; + +/// Whether the directory `name` (lower-cased) at `path` is build output, a +/// tool cache or installed third-party code of an Android, iOS or Unity +/// project, committed by mistake or by habit. Matched only beside the file +/// that makes it so, so a customer's own `build/` or `plugins/` stays theirs. +fn is_mobile_build_dir(name: &str, path: &Path) -> bool { + let Some(parent) = path.parent() else { + return false; + }; + let beside = |file: &str| parent.join(file).is_file(); + match name { + // Gradle's output and cache of a module or the root project. + "build" => beside("build.gradle") || beside("build.gradle.kts"), + ".gradle" => true, + // CocoaPods and Carthage install third-party code into the tree. + "pods" => beside("Podfile"), + "carthage" => beside("Cartfile"), + "deriveddata" => true, + // Unity: the editor's caches and builds, and Asset Store packages in + // `Assets/Plugins`. + _ if UNITY_GENERATED.contains(&name) => parent.join("ProjectSettings").is_dir(), + "plugins" => { + parent_is(path, "assets") + && parent + .parent() + .is_some_and(|project| project.join("ProjectSettings").is_dir()) + } + _ => false, + } } /// Whether `path` is one of ST's generated vendor folders, by ST's own @@ -284,6 +321,43 @@ mod tests { assert!(vendor_dirs(&t.0).is_empty()); } + #[test] + fn mobile_and_unity_build_output_is_left_out() { + let t = Tree::new(&[ + "app/build/intermediates", + "app/src/main/java", + ".gradle/8.0", + "ios/Pods/AFNetworking", + "game/Library/PackageCache", + "game/Temp", + "game/Assets/Plugins/Firebase", + "game/Assets/Scripts", + "game/ProjectSettings", + ]) + .with_files(&["app/build.gradle", "ios/Podfile"]); + assert_eq!( + vendor_dirs(&t.0), + [ + ".gradle", + "app/build", + "game/Assets/Plugins", + "game/Library", + "game/Temp", + "ios/Pods", + ] + ); + } + + #[test] + fn a_build_or_plugins_folder_outside_those_projects_is_the_customers() { + let t = Tree::new(&[ + "tools/build/scripts", + "src/plugins/export", + "Assets/Plugins/x", + ]); + assert!(vendor_dirs(&t.0).is_empty()); + } + #[test] fn a_customers_own_drivers_folder_is_kept() { // No generated Core/ beside it: these are the customer's drivers. diff --git a/compliance-core/src/models/scan.rs b/compliance-core/src/models/scan.rs index 3ed6714..14ce720 100644 --- a/compliance-core/src/models/scan.rs +++ b/compliance-core/src/models/scan.rs @@ -202,6 +202,9 @@ pub enum SkipCode { /// Some components were not matched against known vulnerabilities; /// `subject` names the lookup, and the components where known. CveLookupIncomplete, + /// Files kept in Git LFS were not downloaded (binary assets, not + /// analysed); `subject` lists the LFS patterns of `.gitattributes`. + LfsNotFetched, /// A scheduled or webhook scan found no new commits since the last scan, /// so nothing was scanned again. NoNewCommits, diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 70c33f6..87ed01b 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -427,6 +427,10 @@ pub mod scans { de: "Mobile-App-Analyse (mobsfscan)", en: "Mobile app analysis (mobsfscan)", }, + "lfs_objects" => Text { + de: "Git-LFS-Dateien", + en: "Git LFS files", + }, "sast_vendor_code" => Text { de: "Herstellercode (HAL, CMSIS, Drittanbieter)", en: "Vendor code (HAL, CMSIS, third party)", @@ -560,6 +564,14 @@ pub mod scans { ), (SkipCode::CveLookupIncomplete, Lang::De) => format!("Nicht abgeglichen: {subject}"), (SkipCode::CveLookupIncomplete, Lang::En) => format!("Not matched: {subject}"), + (SkipCode::LfsNotFetched, Lang::De) => format!( + "In Git LFS abgelegte Dateien wurden nicht heruntergeladen und nicht geprüft \ + (Binärdateien wie Grafiken, Modelle, Bibliotheken): {subject}" + ), + (SkipCode::LfsNotFetched, Lang::En) => format!( + "Files stored in Git LFS were not downloaded and not scanned (binary assets such \ + as graphics, models, libraries): {subject}" + ), (SkipCode::NoNewCommits, Lang::De) => { "Keine neuen Commits seit der letzten Prüfung, daher nicht erneut geprüft. \ „Prüfung starten“ prüft trotzdem vollständig." diff --git a/docs/guide/repositories.md b/docs/guide/repositories.md index 842b6d1..298735e 100644 --- a/docs/guide/repositories.md +++ b/docs/guide/repositories.md @@ -157,6 +157,20 @@ If your `.gitmodules` uses SSH URLs, change them to their HTTPS form, e.g. `git@github.com:org/lib.git` becomes `https://github.com/org/lib.git`. ::: +## Large Repositories and Git LFS + +A clone or fetch may take up to **30 minutes** and download up to **4 GB**. +A repository beyond that ends the scan with a message saying which limit it +hit; the operator can raise both (`GIT_CLONE_TIMEOUT_SECS`, +`GIT_CLONE_MAX_MB`). The full history is cloned, so the secret scan also finds +secrets in earlier commits. + +Files kept in **Git LFS** (`filter=lfs` in `.gitattributes`) are not +downloaded: they are usually binary assets (graphics, 3D models, libraries) +that the scanners do not read. The scan run lists the LFS patterns under +**Nicht ausgeführt** as **Git-LFS-Dateien**, so it stays visible that their +content was not checked. + ## The Target's Page A click on a target in the **Prüfobjekte** list opens its page. At the top are diff --git a/docs/reference/tools.md b/docs/reference/tools.md index ca50e49..f352be3 100644 --- a/docs/reference/tools.md +++ b/docs/reference/tools.md @@ -70,7 +70,12 @@ lint). What counts as vendor code: `_HAL_Driver` / `_StdPeriph_Driver`; - ST's generated layouts (`Drivers/` next to `Core/`, `Middlewares/`); - a vendored library wherever it sits, recognised by the files it always ships - (Mbed TLS, lwIP, the FreeRTOS kernel, wolfSSL, FatFs). + (Mbed TLS, lwIP, the FreeRTOS kernel, wolfSSL, FatFs); +- build output and installed third-party code of apps, when committed: + Gradle's `build/` beside a `build.gradle` and `.gradle/`, `Pods/` beside a + `Podfile`, `Carthage/` beside a `Cartfile`, `DerivedData/`, and in a Unity + project (beside `ProjectSettings/`) `Library/`, `Temp/`, `Obj/`, `Logs/`, + `Builds/`, `UserSettings/` and the Asset Store packages in `Assets/Plugins/`. Your own `src/drivers/` is not excluded. The scan run lists the excluded directories under **Nicht ausgeführt** as **Herstellercode (HAL, CMSIS,