CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 9m57s
A git host that restarts answers 502 or refuses connections for a few seconds, and every scan cloning in that window failed with "unexpected http status code: 502". A clone, fetch or submodule fetch that fails with a 5xx status, a timeout or a network error is now tried again after 5, 15 and 30 seconds. Authentication failures, 403, 404, bad references and the download limits fail at once, as before. Each retry is logged at WARN with the attempt and the wait; the wait hands the worker's other tasks to another worker (block_in_place), so a waiting retry does not stall them. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
191 lines
7.1 KiB
Rust
191 lines
7.1 KiB
Rust
//! 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
|
|
};
|
|
self.backoff().retry("submodule fetch", || {
|
|
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);
|
|
}
|
|
}
|