This commit was merged in pull request #390.
This commit is contained in:
1 parent
e6e5b14a04
commit
e399cea0b6
6 files changed
+409
-54
No files matched your search
@@ -38,6 +38,20 @@ pub enum NotAssessedReason {
|
||||
NoRuleForLanguages { languages: Vec<String> },
|
||||
/// The scan predates language detection; a new scan tells.
|
||||
LanguagesUnknown,
|
||||
/// A tool that checks it did not complete in the last scan (semgrep,
|
||||
/// cppcheck, or the CVE lookup), so nothing can be claimed either way.
|
||||
ToolFailed { tools: Vec<String> },
|
||||
}
|
||||
|
||||
/// The tool a skipped stage of a scan run stands for, when that stage is one
|
||||
/// a control's binding relies on.
|
||||
pub fn tool_of_stage(stage: &str) -> Option<&'static str> {
|
||||
match stage {
|
||||
"sast" => Some("semgrep"),
|
||||
"sast_c_cpp" => Some("cppcheck"),
|
||||
"cve_lookup" => Some("osv"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A finding as the compliance view lists it.
|
||||
@@ -77,12 +91,15 @@ fn counts(finding: &Finding) -> bool {
|
||||
///
|
||||
/// `scanned_languages` holds the source languages of the last completed scan,
|
||||
/// `None` before any scan completed. A control is "no violation found" only
|
||||
/// if one of its rules covers one of those languages; a scan of C code says
|
||||
/// nothing about a control only Python rules check.
|
||||
/// if one of its rules covers one of those languages, and none of the tools
|
||||
/// that apply is in `failed_tools` (see [`tool_of_stage`]): a scan of C code
|
||||
/// says nothing about a control only Python rules check, and a CVE lookup
|
||||
/// that failed says nothing about the components' CVEs.
|
||||
pub fn control_statuses(
|
||||
map: &ControlMap,
|
||||
findings: &[Finding],
|
||||
scanned_languages: Option<&[String]>,
|
||||
failed_tools: &[&str],
|
||||
) -> Vec<ControlStatus> {
|
||||
map.controls
|
||||
.iter()
|
||||
@@ -115,7 +132,23 @@ pub fn control_statuses(
|
||||
Some(NotAssessedReason::NotScanned),
|
||||
),
|
||||
(Coverage::Covered, Some(languages)) if entry.checked_for(languages) => {
|
||||
(ControlState::NoViolationFound, None)
|
||||
let mut failed: Vec<String> = entry
|
||||
.scans
|
||||
.iter()
|
||||
.filter(|b| b.applies_to(languages))
|
||||
.map(|b| b.tool.as_str())
|
||||
.filter(|tool| failed_tools.contains(tool))
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
failed.dedup();
|
||||
if failed.is_empty() {
|
||||
(ControlState::NoViolationFound, None)
|
||||
} else {
|
||||
(
|
||||
ControlState::NotAssessed,
|
||||
Some(NotAssessedReason::ToolFailed { tools: failed }),
|
||||
)
|
||||
}
|
||||
}
|
||||
(Coverage::Covered, Some([])) => (
|
||||
ControlState::NotAssessed,
|
||||
@@ -186,7 +219,7 @@ mod tests {
|
||||
#[test]
|
||||
fn every_control_gets_exactly_one_state() {
|
||||
let map = ControlMap::cra().expect("map");
|
||||
let statuses = control_statuses(&map, &[], Some(&python()));
|
||||
let statuses = control_statuses(&map, &[], Some(&python()), &[]);
|
||||
assert_eq!(statuses.len(), map.controls.len());
|
||||
assert_eq!(
|
||||
state_of(&statuses, "cra-ai-8"),
|
||||
@@ -206,7 +239,7 @@ mod tests {
|
||||
finding("cra-ai-13", FindingStatus::FalsePositive),
|
||||
finding("cra-ai-16", FindingStatus::Resolved),
|
||||
];
|
||||
let statuses = control_statuses(&map, &findings, Some(&c_only()));
|
||||
let statuses = control_statuses(&map, &findings, Some(&c_only()), &[]);
|
||||
assert_eq!(state_of(&statuses, "cra-ai-8"), ControlState::NotSatisfied);
|
||||
assert_eq!(
|
||||
state_of(&statuses, "cra-ai-13"),
|
||||
@@ -230,7 +263,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_c_scan_claims_nothing_for_controls_only_python_rules_check() {
|
||||
let map = ControlMap::cra().expect("map");
|
||||
let statuses = control_statuses(&map, &[], Some(&c_only()));
|
||||
let statuses = control_statuses(&map, &[], Some(&c_only()), &[]);
|
||||
|
||||
// Our C rules and cppcheck checked memory safety; gitleaks, secrets.
|
||||
assert_eq!(
|
||||
@@ -256,7 +289,7 @@ mod tests {
|
||||
fn a_mixed_scan_counts_every_language() {
|
||||
let map = ControlMap::cra().expect("map");
|
||||
let mixed = vec!["c".to_string(), "python".to_string()];
|
||||
let statuses = control_statuses(&map, &[], Some(&mixed));
|
||||
let statuses = control_statuses(&map, &[], Some(&mixed), &[]);
|
||||
assert_eq!(
|
||||
state_of(&statuses, "cra-ai-1"),
|
||||
ControlState::NoViolationFound
|
||||
@@ -270,7 +303,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_scan_without_recorded_languages_only_trusts_language_independent_tools() {
|
||||
let map = ControlMap::cra().expect("map");
|
||||
let statuses = control_statuses(&map, &[], Some(&[]));
|
||||
let statuses = control_statuses(&map, &[], Some(&[]), &[]);
|
||||
assert_eq!(
|
||||
state_of(&statuses, "cra-ai-9"),
|
||||
ControlState::NoViolationFound
|
||||
@@ -281,10 +314,30 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_cve_lookup_claims_nothing_about_component_cves() {
|
||||
let map = ControlMap::cra().expect("map");
|
||||
let statuses = control_statuses(&map, &[], Some(&c_only()), &["osv"]);
|
||||
// cra-ai-22 relies on the CVE lookup (osv) and the SBOM (syft).
|
||||
assert_eq!(
|
||||
status_of(&statuses, "cra-ai-22").reason,
|
||||
Some(NotAssessedReason::ToolFailed {
|
||||
tools: vec!["osv".into()]
|
||||
})
|
||||
);
|
||||
// Memory safety does not depend on it.
|
||||
assert_eq!(
|
||||
state_of(&statuses, "cra-ai-20"),
|
||||
ControlState::NoViolationFound
|
||||
);
|
||||
assert_eq!(tool_of_stage("cve_lookup"), Some("osv"));
|
||||
assert_eq!(tool_of_stage("sast_vendor_code"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_is_passed_before_a_scan() {
|
||||
let map = ControlMap::cra().expect("map");
|
||||
let statuses = control_statuses(&map, &[], None);
|
||||
let statuses = control_statuses(&map, &[], None, &[]);
|
||||
assert_eq!(state_of(&statuses, "cra-ai-8"), ControlState::NotAssessed);
|
||||
assert_eq!(
|
||||
status_of(&statuses, "cra-ai-8").reason,
|
||||
|
||||
@@ -161,10 +161,28 @@ pub fn scanned_languages(inputs: &EvidenceInputs) -> Option<&[String]> {
|
||||
.map(|run| run.languages.as_slice())
|
||||
}
|
||||
|
||||
/// The tools that did not complete in the target's last scan (a skipped
|
||||
/// stage a control relies on: semgrep, cppcheck, the CVE lookup).
|
||||
pub fn failed_tools(inputs: &EvidenceInputs) -> Vec<&'static str> {
|
||||
inputs
|
||||
.last_run
|
||||
.iter()
|
||||
.flat_map(|run| &run.skipped_stages)
|
||||
.filter_map(|s| compliance::tool_of_stage(&s.stage))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The target's state against every CRA Annex I control.
|
||||
pub fn compliance_of(inputs: &EvidenceInputs) -> Vec<compliance::ControlStatus> {
|
||||
control_map::ControlMap::cra()
|
||||
.map(|map| compliance::control_statuses(&map, &inputs.findings, scanned_languages(inputs)))
|
||||
.map(|map| {
|
||||
compliance::control_statuses(
|
||||
&map,
|
||||
&inputs.findings,
|
||||
scanned_languages(inputs),
|
||||
&failed_tools(inputs),
|
||||
)
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
|
||||
@@ -221,32 +221,39 @@ impl CveScanner {
|
||||
/// the internal `Cmp*`/`Sys*` library names OSV-by-purl would look up. So we
|
||||
/// find the runtime SBOM entry, pull every `cpe:2.3:a:codesys:*` CVE from NVD,
|
||||
/// and keep the ones whose affected-version range covers our runtime version.
|
||||
/// Best-effort: returns empty without an NVD key, on a network error, or when
|
||||
/// no CODESYS runtime component is present.
|
||||
pub async fn scan_codesys(&self, repo_id: &str, entries: &mut [SbomEntry]) -> Vec<CveAlert> {
|
||||
/// Nothing is looked up when no CODESYS runtime component is present; a
|
||||
/// lookup that fails is reported in [`CveLookup::unchecked`].
|
||||
pub async fn scan_codesys(&self, repo_id: &str, entries: &mut [SbomEntry]) -> CveLookup {
|
||||
let Some((name, version)) = codesys_runtime(entries) else {
|
||||
return Vec::new();
|
||||
return CveLookup::default();
|
||||
};
|
||||
let matched =
|
||||
match nvd_cpe::product_cves(&self.http, self.nvd_api_key.as_deref(), CODESYS, &version)
|
||||
.await
|
||||
{
|
||||
Ok(matched) => matched,
|
||||
Err(e) => {
|
||||
tracing::warn!("CODESYS NVD lookup failed: {e}");
|
||||
return Vec::new();
|
||||
match nvd_cpe::product_cves(&self.http, self.nvd_api_key.as_deref(), CODESYS, &version)
|
||||
.await
|
||||
{
|
||||
Ok(matched) => {
|
||||
let alerts = record_nvd(repo_id, entries, &name, &version, matched);
|
||||
tracing::info!(runtime = %name, version = %version, cves = alerts.len(), "CODESYS CVE match");
|
||||
CveLookup {
|
||||
alerts,
|
||||
unchecked: Vec::new(),
|
||||
}
|
||||
};
|
||||
let alerts = record_nvd(repo_id, entries, &name, &version, matched);
|
||||
tracing::info!(runtime = %name, version = %version, cves = alerts.len(), "CODESYS CVE match");
|
||||
alerts
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("CODESYS NVD lookup failed: {e}");
|
||||
CveLookup {
|
||||
alerts: Vec::new(),
|
||||
unchecked: vec![format!("{name} {version}")],
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Match the libraries found by their headers (FreeRTOS, lwIP, mbedTLS,
|
||||
/// wolfSSL; see [`embedded_versions`]) against NVD by CPE: copied into a
|
||||
/// firmware tree, they have no purl OSV could look up. Best-effort per
|
||||
/// library, as for CODESYS.
|
||||
pub async fn scan_embedded(&self, repo_id: &str, entries: &mut [SbomEntry]) -> Vec<CveAlert> {
|
||||
/// firmware tree, they have no purl OSV could look up. A library whose
|
||||
/// lookup fails is reported in [`CveLookup::unchecked`]; the others are
|
||||
/// still matched.
|
||||
pub async fn scan_embedded(&self, repo_id: &str, entries: &mut [SbomEntry]) -> CveLookup {
|
||||
let found: Vec<(String, String, NvdProduct)> = entries
|
||||
.iter()
|
||||
.filter(|e| e.package_manager == EMBEDDED_MANAGER)
|
||||
@@ -255,19 +262,34 @@ impl CveScanner {
|
||||
.map(|p| (e.name.clone(), e.version.clone(), p))
|
||||
})
|
||||
.collect();
|
||||
let mut alerts = Vec::new();
|
||||
let mut lookup = CveLookup::default();
|
||||
for (name, version, product) in found {
|
||||
match nvd_cpe::product_cves(&self.http, self.nvd_api_key.as_deref(), product, &version)
|
||||
.await
|
||||
{
|
||||
Ok(cves) => alerts.extend(record_nvd(repo_id, entries, &name, &version, cves)),
|
||||
Err(e) => tracing::warn!(library = %name, "NVD lookup failed: {e}"),
|
||||
Ok(cves) => lookup
|
||||
.alerts
|
||||
.extend(record_nvd(repo_id, entries, &name, &version, cves)),
|
||||
Err(e) => {
|
||||
tracing::warn!(library = %name, "NVD lookup failed: {e}");
|
||||
lookup.unchecked.push(format!("{name} {version}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
alerts
|
||||
lookup
|
||||
}
|
||||
}
|
||||
|
||||
/// What an NVD lookup found, and what it could not check.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct CveLookup {
|
||||
/// The CVEs that affect the components in use.
|
||||
pub alerts: Vec<CveAlert>,
|
||||
/// Components whose lookup failed (`"lwIP 2.1.2"`): not known to be free
|
||||
/// of CVEs, only unchecked.
|
||||
pub unchecked: Vec<String>,
|
||||
}
|
||||
|
||||
/// Attach NVD `cves` to the SBOM entry `name@version` and make an alert for
|
||||
/// each.
|
||||
fn record_nvd(
|
||||
|
||||
@@ -5,6 +5,10 @@
|
||||
//! versions as ranges. So every CVE of the product is fetched once, and the
|
||||
//! ranges are matched here against the version in use.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// A product as NVD names it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct NvdProduct {
|
||||
@@ -26,31 +30,121 @@ pub struct NvdCve {
|
||||
pub cvss: Option<f64>,
|
||||
}
|
||||
|
||||
/// NVD's CVE API.
|
||||
const NVD_CVES_URL: &str = "https://services.nvd.nist.gov/rest/json/cves/2.0";
|
||||
|
||||
/// Waits before each retry of a failed NVD request. NVD asks for about six
|
||||
/// seconds between requests, and answers 403/429 when a key's budget is
|
||||
/// spent; three retries ride out a short limit without stalling a scan.
|
||||
const RETRY_DELAYS: [Duration; 3] = [
|
||||
Duration::from_secs(6),
|
||||
Duration::from_secs(12),
|
||||
Duration::from_secs(24),
|
||||
];
|
||||
|
||||
/// How long an NVD answer for a product is reused. CVEs are published daily,
|
||||
/// and repeated scans (a nightly corpus, several targets with the same
|
||||
/// FreeRTOS) must not spend the rate budget on the same question again.
|
||||
const CACHE_TTL: Duration = Duration::from_secs(6 * 60 * 60);
|
||||
|
||||
/// NVD answers by product match string, with when they were fetched.
|
||||
type Cache = Mutex<HashMap<String, (Instant, Arc<serde_json::Value>)>>;
|
||||
|
||||
fn cache() -> &'static Cache {
|
||||
static CACHE: OnceLock<Cache> = OnceLock::new();
|
||||
CACHE.get_or_init(Cache::default)
|
||||
}
|
||||
|
||||
/// The CVEs of `product` whose affected range covers `version`.
|
||||
///
|
||||
/// NVD is asked once per product and [`CACHE_TTL`]; a rate-limited or failed
|
||||
/// request is retried after [`RETRY_DELAYS`].
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Why NVD could not be asked (network, status, body), for the log.
|
||||
/// Why NVD could not be asked (network, status, body) after the retries. The
|
||||
/// caller records it on the scan run: a lookup that failed must not read as a
|
||||
/// product without CVEs.
|
||||
pub async fn product_cves(
|
||||
http: &reqwest::Client,
|
||||
api_key: Option<&str>,
|
||||
product: NvdProduct,
|
||||
version: &str,
|
||||
) -> Result<Vec<NvdCve>, String> {
|
||||
let mut req = http
|
||||
.get("https://services.nvd.nist.gov/rest/json/cves/2.0")
|
||||
.query(&[("virtualMatchString", product.match_string)]);
|
||||
if let Some(key) = api_key {
|
||||
req = req.header("apiKey", key);
|
||||
}
|
||||
let resp = req.send().await.map_err(|e| e.to_string())?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(format!("NVD returned {}", resp.status()));
|
||||
}
|
||||
let body: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?;
|
||||
let body = product_body(
|
||||
http,
|
||||
NVD_CVES_URL,
|
||||
api_key,
|
||||
product.match_string,
|
||||
&RETRY_DELAYS,
|
||||
)
|
||||
.await?;
|
||||
Ok(parse(&body, product.marker, version))
|
||||
}
|
||||
|
||||
/// NVD's answer for `match_string`: cached, or fetched from `base_url` with
|
||||
/// a retry after each of `delays`.
|
||||
async fn product_body(
|
||||
http: &reqwest::Client,
|
||||
base_url: &str,
|
||||
api_key: Option<&str>,
|
||||
match_string: &str,
|
||||
delays: &[Duration],
|
||||
) -> Result<Arc<serde_json::Value>, String> {
|
||||
if let Some(body) = cached(match_string) {
|
||||
return Ok(body);
|
||||
}
|
||||
let mut last_error = String::new();
|
||||
for attempt in 0..=delays.len() {
|
||||
if let Some(wait) = attempt.checked_sub(1).and_then(|i| delays.get(i)) {
|
||||
tracing::info!(
|
||||
match_string,
|
||||
attempt,
|
||||
"retrying NVD after {wait:?}: {last_error}"
|
||||
);
|
||||
tokio::time::sleep(*wait).await;
|
||||
}
|
||||
let mut req = http
|
||||
.get(base_url)
|
||||
.query(&[("virtualMatchString", match_string)]);
|
||||
if let Some(key) = api_key {
|
||||
req = req.header("apiKey", key);
|
||||
}
|
||||
match req.send().await {
|
||||
Ok(resp) if resp.status().is_success() => {
|
||||
let body: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?;
|
||||
let body = Arc::new(body);
|
||||
if let Ok(mut c) = cache().lock() {
|
||||
c.insert(
|
||||
match_string.to_string(),
|
||||
(Instant::now(), Arc::clone(&body)),
|
||||
);
|
||||
}
|
||||
return Ok(body);
|
||||
}
|
||||
Ok(resp) if is_transient(resp.status()) => {
|
||||
last_error = format!("NVD returned {}", resp.status());
|
||||
}
|
||||
Ok(resp) => return Err(format!("NVD returned {}", resp.status())),
|
||||
Err(e) => last_error = e.to_string(),
|
||||
}
|
||||
}
|
||||
Err(last_error)
|
||||
}
|
||||
|
||||
/// A fresh cached answer for `match_string`, if there is one.
|
||||
fn cached(match_string: &str) -> Option<Arc<serde_json::Value>> {
|
||||
let cache = cache().lock().ok()?;
|
||||
let (at, body) = cache.get(match_string)?;
|
||||
(at.elapsed() < CACHE_TTL).then(|| Arc::clone(body))
|
||||
}
|
||||
|
||||
/// Whether NVD may answer differently when asked again: a spent rate budget
|
||||
/// (403, 429) or a server error.
|
||||
fn is_transient(status: reqwest::StatusCode) -> bool {
|
||||
matches!(status.as_u16(), 403 | 429 | 500 | 502 | 503 | 504)
|
||||
}
|
||||
|
||||
/// The CVEs in an NVD response with a vulnerable CPE containing `marker`
|
||||
/// whose range covers `version`.
|
||||
pub fn parse(body: &serde_json::Value, marker: &str, version: &str) -> Vec<NvdCve> {
|
||||
@@ -161,6 +255,95 @@ fn cmp_dotted(a: &str, b: &str) -> std::cmp::Ordering {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cmp::Ordering::{Equal, Greater, Less};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
/// A stand-in for NVD answering `fail` times with `status`, then 200; it
|
||||
/// counts the requests.
|
||||
async fn fake_nvd(fail: usize, status: u16) -> (String, Arc<AtomicUsize>) {
|
||||
let hits = Arc::new(AtomicUsize::new(0));
|
||||
let counter = Arc::clone(&hits);
|
||||
let app = axum::Router::new().route(
|
||||
"/",
|
||||
axum::routing::get(move || {
|
||||
let counter = Arc::clone(&counter);
|
||||
async move {
|
||||
let n = counter.fetch_add(1, Ordering::SeqCst);
|
||||
if n < fail {
|
||||
(
|
||||
axum::http::StatusCode::from_u16(status)
|
||||
.unwrap_or(axum::http::StatusCode::FORBIDDEN),
|
||||
String::new(),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
axum::http::StatusCode::OK,
|
||||
r#"{"vulnerabilities":[]}"#.to_string(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("bind: {e}"));
|
||||
let url = format!(
|
||||
"http://{}/",
|
||||
listener
|
||||
.local_addr()
|
||||
.unwrap_or_else(|e| panic!("addr: {e}"))
|
||||
);
|
||||
tokio::spawn(async move {
|
||||
let _ = axum::serve(listener, app).await;
|
||||
});
|
||||
(url, hits)
|
||||
}
|
||||
|
||||
const NO_WAIT: [Duration; 3] = [Duration::ZERO; 3];
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_rate_limited_lookup_is_retried_and_then_cached() {
|
||||
let (url, hits) = fake_nvd(2, 403).await;
|
||||
let http = reqwest::Client::new();
|
||||
|
||||
let first = product_body(&http, &url, None, "cpe:test:retry", &NO_WAIT).await;
|
||||
let again = product_body(&http, &url, None, "cpe:test:retry", &NO_WAIT).await;
|
||||
|
||||
assert!(first.is_ok(), "{first:?}");
|
||||
assert!(again.is_ok());
|
||||
// Two refusals, one answer, and the second ask came from the cache.
|
||||
assert_eq!(hits.load(Ordering::SeqCst), 3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_lasting_limit_is_an_error_not_an_empty_answer() {
|
||||
let (url, hits) = fake_nvd(usize::MAX, 429).await;
|
||||
let http = reqwest::Client::new();
|
||||
|
||||
let result = product_body(&http, &url, None, "cpe:test:limited", &NO_WAIT).await;
|
||||
|
||||
assert_eq!(
|
||||
result.err().as_deref(),
|
||||
Some("NVD returned 429 Too Many Requests")
|
||||
);
|
||||
assert_eq!(
|
||||
hits.load(Ordering::SeqCst),
|
||||
4,
|
||||
"the first try and three retries"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_request_nvd_refuses_for_good_is_not_retried() {
|
||||
let (url, hits) = fake_nvd(usize::MAX, 404).await;
|
||||
let http = reqwest::Client::new();
|
||||
|
||||
assert!(
|
||||
product_body(&http, &url, None, "cpe:test:missing", &NO_WAIT)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(hits.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dotted_version_comparison() {
|
||||
|
||||
@@ -261,22 +261,39 @@ impl PipelineOrchestrator {
|
||||
Ok(Ok(alerts)) => alerts,
|
||||
Ok(Err(e)) => {
|
||||
tracing::warn!("[{repo_id}] CVE scanning failed: {e}");
|
||||
self.record_cve_gap(scan_run_id, &format!("OSV: {e}")).await;
|
||||
Vec::new()
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::warn!("[{repo_id}] CVE scanning timed out after 10 minutes");
|
||||
self.record_cve_gap(scan_run_id, "OSV: timed out after 10 minutes")
|
||||
.await;
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
// OSV has no ecosystem for them: match the embedded libraries in NVD.
|
||||
// Room for NVD's rate-limit retries on a few libraries.
|
||||
match tokio::time::timeout(
|
||||
std::time::Duration::from_secs(120),
|
||||
std::time::Duration::from_secs(300),
|
||||
cve_scanner.scan_embedded(&repo_id, &mut sbom_entries),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(alerts) => cve_alerts.extend(alerts),
|
||||
Err(_) => tracing::warn!("[{repo_id}] embedded-library CVE match timed out"),
|
||||
Ok(lookup) => {
|
||||
cve_alerts.extend(lookup.alerts);
|
||||
if !lookup.unchecked.is_empty() {
|
||||
self.record_cve_gap(
|
||||
scan_run_id,
|
||||
&format!("NVD, not checked: {}", lookup.unchecked.join(", ")),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::warn!("[{repo_id}] embedded-library CVE match timed out");
|
||||
self.record_cve_gap(scan_run_id, "NVD: timed out after 5 minutes")
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
// Stage 4: Pattern Scanning (GDPR + OAuth)
|
||||
@@ -872,7 +889,7 @@ impl PipelineOrchestrator {
|
||||
|
||||
if !all_sbom.is_empty() {
|
||||
if let Err(e) = self
|
||||
.persist_control_app_sbom(target_id, &target.name, all_sbom)
|
||||
.persist_control_app_sbom(target_id, scan_run_id, &target.name, all_sbom)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(target_id, error = %e, "control-app SBOM persist failed");
|
||||
@@ -1041,6 +1058,7 @@ impl PipelineOrchestrator {
|
||||
async fn persist_control_app_sbom(
|
||||
&self,
|
||||
target_id: &str,
|
||||
scan_run_id: &str,
|
||||
target_name: &str,
|
||||
mut entries: Vec<SbomEntry>,
|
||||
) -> Result<(), AgentError> {
|
||||
@@ -1069,24 +1087,39 @@ impl PipelineOrchestrator {
|
||||
Ok(Ok(a)) => a,
|
||||
Ok(Err(e)) => {
|
||||
tracing::warn!(target_id, error = %e, "control-app CVE scan failed");
|
||||
self.record_cve_gap(scan_run_id, &format!("OSV: {e}")).await;
|
||||
Vec::new()
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::warn!(target_id, "control-app CVE scan timed out");
|
||||
self.record_cve_gap(scan_run_id, "OSV: timed out after 10 minutes")
|
||||
.await;
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
// OSV can't match `pkg:codesys/*` (no such ecosystem); CODESYS advisories
|
||||
// live in NVD keyed by CPE + runtime version. Add those (best-effort).
|
||||
if let Ok(codesys) = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(120),
|
||||
match tokio::time::timeout(
|
||||
std::time::Duration::from_secs(300),
|
||||
cve_scanner.scan_codesys(target_id, &mut entries),
|
||||
)
|
||||
.await
|
||||
{
|
||||
alerts.extend(codesys);
|
||||
} else {
|
||||
tracing::warn!(target_id, "CODESYS CVE match timed out");
|
||||
Ok(lookup) => {
|
||||
alerts.extend(lookup.alerts);
|
||||
if !lookup.unchecked.is_empty() {
|
||||
self.record_cve_gap(
|
||||
scan_run_id,
|
||||
&format!("NVD, not checked: {}", lookup.unchecked.join(", ")),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::warn!(target_id, "CODESYS CVE match timed out");
|
||||
self.record_cve_gap(scan_run_id, "NVD: timed out after 5 minutes")
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
for entry in &entries {
|
||||
@@ -1502,6 +1535,12 @@ impl PipelineOrchestrator {
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Record that CVE matching is incomplete for this run, and why: a lookup
|
||||
/// that failed must not read as components without CVEs.
|
||||
async fn record_cve_gap(&self, scan_run_id: &str, reason: &str) {
|
||||
self.skip_stage(scan_run_id, CVE_LOOKUP_STAGE, reason).await;
|
||||
}
|
||||
|
||||
pub(super) async fn update_phase(&self, scan_run_id: &str, phase: ScanPhase) {
|
||||
let Ok(phase) = mongodb::bson::to_bson(&phase) else {
|
||||
return;
|
||||
@@ -1579,6 +1618,9 @@ fn planned_phases(
|
||||
phases
|
||||
}
|
||||
|
||||
/// The skipped-stage id recorded when CVE matching is incomplete.
|
||||
pub const CVE_LOOKUP_STAGE: &str = "cve_lookup";
|
||||
|
||||
/// Extract the scheme + host from a git URL.
|
||||
/// e.g. "https://gitea.example.com/owner/repo.git" -> "https://gitea.example.com"
|
||||
/// e.g. "ssh://git@gitea.example.com:22/owner/repo.git" -> "https://gitea.example.com"
|
||||
|
||||
@@ -347,6 +347,10 @@ pub mod scans {
|
||||
de: "Archiv-Passwort falsch (unter „Prüfobjekte“ ändern)",
|
||||
en: "Archive password wrong (change it under Targets)",
|
||||
},
|
||||
"cve_lookup" => Text {
|
||||
de: "CVE-Abgleich unvollständig",
|
||||
en: "CVE lookup incomplete",
|
||||
},
|
||||
"code_scan" => Text {
|
||||
de: "Codeanalyse",
|
||||
en: "Code analysis",
|
||||
@@ -1706,6 +1710,15 @@ pub mod compliance {
|
||||
de: "Geprüfte Sprachen",
|
||||
en: "Languages checked",
|
||||
};
|
||||
/// Followed by the tools, e.g. "CVE-Abgleich".
|
||||
pub const TOOL_FAILED: Text = Text {
|
||||
de: "Bei der letzten Prüfung nicht vollständig gelaufen:",
|
||||
en: "Did not complete in the last scan:",
|
||||
};
|
||||
pub const CVE_LOOKUP: Text = Text {
|
||||
de: "CVE-Abgleich",
|
||||
en: "CVE lookup",
|
||||
};
|
||||
pub const NOT_CODE_CHECKABLE: Text = Text {
|
||||
de: "Nicht im Code prüfbar",
|
||||
en: "Not checkable in code",
|
||||
@@ -1797,6 +1810,21 @@ pub mod compliance {
|
||||
)
|
||||
),
|
||||
"languages_unknown" => LANGUAGES_UNKNOWN.get(lang).to_string(),
|
||||
"tool_failed" => format!(
|
||||
"{} {}",
|
||||
TOOL_FAILED.get(lang),
|
||||
reason["tools"]
|
||||
.as_array()
|
||||
.map_or(&[][..], Vec::as_slice)
|
||||
.iter()
|
||||
.filter_map(serde_json::Value::as_str)
|
||||
.map(|tool| match tool {
|
||||
"osv" => CVE_LOOKUP.get(lang),
|
||||
other => other,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -1806,6 +1834,15 @@ pub mod compliance {
|
||||
use super::super::super::Lang;
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_reason_names_the_tools_that_did_not_complete() {
|
||||
let reason = serde_json::json!({ "kind": "tool_failed", "tools": ["osv", "semgrep"] });
|
||||
assert_eq!(
|
||||
not_assessed_reason(&reason, Lang::De).as_deref(),
|
||||
Some("Bei der letzten Prüfung nicht vollständig gelaufen: CVE-Abgleich, semgrep")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_reason_names_the_languages_no_rule_covers() {
|
||||
let reason = serde_json::json!({
|
||||
|
||||
Reference in new issue
Block a user