feat(git): check out submodules, each URL held to the remote's checks (#347)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Successful in 5m54s
CI / Deploy Agent (push) Successful in 7m29s

This commit was merged in pull request #347.
This commit is contained in:
sharang committed 2026-09-23 14:29:05 +00:00
1 parent fe318c2b85
commit 338849d050
6 files changed
+224 -3

No files matched your search

+8 -1
View File
@@ -154,6 +154,13 @@ fn ingest_git(
let creds = credentials_for(artifact, &ctx.secrets);
let git_ops = GitOps::new(ctx.git_clone_base, ctx.tenant_id, creds, ctx.net_guard);
let repo_path = git_ops.clone_or_fetch(&artifact.source_ref, &artifact.id)?;
// Classification needs the submodules too: a build system or RTOS may
// live in one.
let facts = git_ops
.update_submodules(&repo_path, &artifact.source_ref)
.into_iter()
.map(|skipped| DetectedFact::new("submodule_skipped", skipped, "ingest"))
.collect();
let head = GitOps::get_head_sha(&repo_path).ok();
Ok(IngestedArtifact {
artifact_id: artifact.id.clone(),
@@ -161,7 +168,7 @@ fn ingest_git(
working_path: Some(repo_path),
content_hash: head,
size_bytes: None,
facts: Vec::new(),
facts,
})
}
+12 -2
View File
@@ -81,7 +81,7 @@ impl RepoCredentials {
callbacks
}
fn fetch_options(&self) -> FetchOptions<'_> {
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);
@@ -128,7 +128,7 @@ impl GitOps {
/// 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.
fn check_remote(&self, git_url: &str) -> Result<(), AgentError> {
pub(crate) fn check_remote(&self, git_url: &str) -> Result<(), AgentError> {
let remote = self
.net_guard
.check_git_url(git_url)
@@ -141,6 +141,16 @@ impl GitOps {
.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)
@@ -0,0 +1,188 @@
//! Git submodules of a scanned repository.
//!
//! Firmware repositories pull their HAL, RTOS or protocol stack in as
//! submodules; without them the scan misses code the product ships. Each
//! submodule URL passes the same checks as the main remote (HTTPS only, a
//! public host, no redirects), and the repository's token is offered only to
//! the main remote's own host. A submodule that is refused or cannot be
//! fetched is left out and reported, so the scan says what it did not see.
use std::path::Path;
use git2::{Repository, Submodule, SubmoduleUpdateOptions};
use crate::error::AgentError;
use crate::pipeline::git::{reject_ssh_url, GitOps, RepoCredentials};
/// Most levels of nested submodules that are checked out.
const MAX_DEPTH: usize = 3;
impl GitOps {
/// Check out the submodules of the checkout at `repo_path` (whose remote is
/// `origin_url`), and theirs, up to [`MAX_DEPTH`] levels.
///
/// # Returns
///
/// One line per submodule that was left out, naming it and saying why;
/// empty when there were none or all were checked out.
pub fn update_submodules(&self, repo_path: &Path, origin_url: &str) -> Vec<String> {
let main_host = self.remote_host(origin_url);
let mut skipped = Vec::new();
self.update_level(repo_path, origin_url, main_host.as_deref(), 0, &mut skipped);
skipped
}
fn update_level(
&self,
repo_path: &Path,
parent_url: &str,
main_host: Option<&str>,
depth: usize,
skipped: &mut Vec<String>,
) {
let Ok(repo) = Repository::open(repo_path) else {
return;
};
let Ok(submodules) = repo.submodules() else {
return;
};
for mut submodule in submodules {
let name = submodule.name().unwrap_or("?").to_string();
let Some(url) = submodule.url().and_then(|raw| resolve_url(parent_url, raw)) else {
skipped.push(format!("{name}: no usable URL in .gitmodules"));
continue;
};
if let Err(e) = self.fetch_one(&repo, &mut submodule, &name, &url, main_host) {
skipped.push(format!("{name} ({url}): {e}"));
continue;
}
if depth + 1 < MAX_DEPTH {
let nested = repo_path.join(submodule.path());
self.update_level(&nested, &url, main_host, depth + 1, skipped);
}
}
}
/// Check `url`, point the submodule at exactly that URL, and check it out.
fn fetch_one(
&self,
repo: &Repository,
submodule: &mut Submodule<'_>,
name: &str,
url: &str,
main_host: Option<&str>,
) -> Result<(), AgentError> {
reject_ssh_url(url)?;
self.check_remote(url)?;
// The URL that was checked is the one fetched: set it in the local
// config, where the update reads it, rather than trusting what
// libgit2 would resolve on its own.
submodule.init(true)?;
repo.config()?
.set_str(&format!("submodule.{name}.url"), url)?;
let mut submodule = repo.find_submodule(name)?;
// The repository's token belongs to its own host; a submodule on
// another host gets no credentials.
let same_host = main_host.is_some() && self.remote_host(url).as_deref() == main_host;
let anonymous = RepoCredentials::default();
let credentials = if same_host {
self.credentials()
} else {
&anonymous
};
let mut options = SubmoduleUpdateOptions::new();
options.fetch(credentials.fetch_options());
submodule.update(true, Some(&mut options))?;
Ok(())
}
}
/// A submodule URL made absolute. Relative URLs (`../lib.git`, `./sub.git`)
/// are relative to the parent's remote as if it were a directory, as git
/// resolves them. `None` when it would climb above the host.
fn resolve_url(parent: &str, raw: &str) -> Option<String> {
let raw = raw.trim();
if !(raw.starts_with("./") || raw.starts_with("../")) {
return (!raw.is_empty()).then(|| raw.to_string());
}
let (scheme, rest) = parent.trim_end_matches('/').split_once("://")?;
let mut segments: Vec<&str> = rest.split('/').collect();
let mut remainder = raw;
loop {
if let Some(r) = remainder.strip_prefix("./") {
remainder = r;
} else if let Some(r) = remainder.strip_prefix("../") {
// The host is the first segment and cannot be climbed past.
if segments.len() <= 1 {
return None;
}
segments.pop();
remainder = r;
} else {
break;
}
}
Some(format!("{scheme}://{}/{remainder}", segments.join("/")))
}
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use super::*;
use compliance_core::NetGuard;
#[test]
fn relative_urls_resolve_like_git() {
let parent = "https://git.example.com/acme/firmware.git";
assert_eq!(
resolve_url(parent, "../hal.git").as_deref(),
Some("https://git.example.com/acme/hal.git")
);
assert_eq!(
resolve_url(parent, "./vendor.git").as_deref(),
Some("https://git.example.com/acme/firmware.git/vendor.git")
);
assert_eq!(
resolve_url(parent, "../../other/lib.git").as_deref(),
Some("https://git.example.com/other/lib.git")
);
assert_eq!(resolve_url(parent, "../../../../x.git"), None);
assert_eq!(
resolve_url(parent, "https://github.com/FreeRTOS/FreeRTOS-Kernel.git").as_deref(),
Some("https://github.com/FreeRTOS/FreeRTOS-Kernel.git")
);
}
#[test]
fn refused_submodules_are_reported_and_not_fetched() {
let base = std::env::temp_dir().join(format!("cs-sub-{}", uuid::Uuid::new_v4()));
let ops = GitOps::new(
&base.to_string_lossy(),
"tenant-a",
RepoCredentials::default(),
NetGuard::public_only(),
);
let path = ops.clone_path("fw");
let repo = Repository::init(&path).expect("init");
// `submodule()` only records the entry; nothing is fetched here.
repo.submodule("git@github.com:acme/hal.git", Path::new("hal"), true)
.expect("ssh submodule");
repo.submodule("http://10.0.0.5/rtos.git", Path::new("rtos"), true)
.expect("private submodule");
let skipped = ops.update_submodules(&path, "https://git.example.com/acme/fw.git");
assert_eq!(skipped.len(), 2, "{skipped:?}");
assert!(skipped
.iter()
.any(|s| s.starts_with("hal") && s.contains("HTTPS")));
assert!(skipped
.iter()
.any(|s| s.starts_with("rtos") && s.contains("10.0.0.5")));
// Nothing was checked out: the submodule has no commit in its workdir.
let rtos = repo.find_submodule("rtos").expect("rtos entry");
assert!(rtos.workdir_id().is_none(), "rtos must not be fetched");
let _ = std::fs::remove_dir_all(&base);
}
}
+1
View File
@@ -4,6 +4,7 @@ pub mod cve;
pub mod dedup;
pub mod firmware_sbom;
pub mod git;
pub mod git_submodules;
pub mod gitleaks;
mod graph_build;
mod issue_creation;
@@ -88,6 +88,17 @@ impl PipelineOrchestrator {
return Ok(0);
}
// Submodules are part of what the product ships (a HAL, an RTOS).
let skipped = git_ops.update_submodules(&repo_path, &repo.git_url);
if !skipped.is_empty() {
self.skip_stage(
scan_run_id,
"git_submodules",
&format!("not checked out, so not scanned: {}", skipped.join("; ")),
)
.await;
}
self.scan_tree(&repo_path, repo, scan_run_id).await
}
+4
View File
@@ -277,6 +277,10 @@ pub mod scans {
de: "Einlesen der Dateien",
en: "Reading the upload",
},
"git_submodules" => Text {
de: "Git-Submodule",
en: "Git submodules",
},
"code_scan" => Text {
de: "Codeanalyse",
en: "Code analysis",