fix(cve): OSV and NVD lookups go through guarded_net (#469) #476
No files matched your search
@@ -198,14 +198,9 @@ impl ComplianceAgent {
|
||||
trigger: compliance_core::models::ScanTrigger,
|
||||
) -> Result<(), crate::error::AgentError> {
|
||||
let db = self.db_pool.for_tenant_id(tenant_id).await?;
|
||||
let orchestrator = PipelineOrchestrator::new(
|
||||
self.config.clone(),
|
||||
tenant_id,
|
||||
db.clone(),
|
||||
self.llm.clone(),
|
||||
self.http.clone(),
|
||||
)
|
||||
.with_nuget_license_cache(self.nuget_license_cache.clone());
|
||||
let orchestrator =
|
||||
PipelineOrchestrator::new(self.config.clone(), tenant_id, db.clone(), self.llm.clone())
|
||||
.with_nuget_license_cache(self.nuget_license_cache.clone());
|
||||
let started = chrono::Utc::now();
|
||||
orchestrator.run_target(target_id, trigger.clone()).await?;
|
||||
// Support's scans are ours, not the customer's usage.
|
||||
@@ -280,13 +275,8 @@ impl ComplianceAgent {
|
||||
})?;
|
||||
let repo = crate::pipeline::repo_view::RepoView::from_target(&target, code, &self.secrets);
|
||||
|
||||
let orchestrator = PipelineOrchestrator::new(
|
||||
self.config.clone(),
|
||||
tenant_id,
|
||||
db,
|
||||
self.llm.clone(),
|
||||
self.http.clone(),
|
||||
);
|
||||
let orchestrator =
|
||||
PipelineOrchestrator::new(self.config.clone(), tenant_id, db, self.llm.clone());
|
||||
orchestrator
|
||||
.run_pr_review(&repo, repo_id, pr_number, base_sha, head_sha)
|
||||
.await
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
|
||||
use compliance_core::models::{CveAlert, CveSource, SbomEntry, VulnRef};
|
||||
use compliance_core::net_guard::NetGuard;
|
||||
use compliance_core::CoreError;
|
||||
|
||||
use crate::pipeline::embedded_versions::{self, EMBEDDED_MANAGER};
|
||||
use crate::pipeline::nvd_cpe::{self, NvdCve, NvdProduct};
|
||||
use crate::pipeline::public_http::{read_body, read_json, PublicHttp};
|
||||
|
||||
/// OSV's API.
|
||||
const OSV_API: &str = "https://api.osv.dev";
|
||||
|
||||
/// Every CODESYS product: advisories key off the runtime's version.
|
||||
const CODESYS: NvdProduct = NvdProduct {
|
||||
@@ -12,24 +17,34 @@ const CODESYS: NvdProduct = NvdProduct {
|
||||
marker: ":codesys:",
|
||||
};
|
||||
|
||||
/// Matches SBOM components against OSV and NVD. Every request goes through
|
||||
/// the net guard (see [`crate::pipeline::public_http`], #469).
|
||||
pub struct CveScanner {
|
||||
http: reqwest::Client,
|
||||
#[allow(dead_code)]
|
||||
searxng_url: Option<String>,
|
||||
http: PublicHttp,
|
||||
nvd_api_key: Option<String>,
|
||||
/// OSV's API root ([`OSV_API`]; a stand-in in tests).
|
||||
osv_api: String,
|
||||
}
|
||||
|
||||
impl CveScanner {
|
||||
pub fn new(
|
||||
http: reqwest::Client,
|
||||
searxng_url: Option<String>,
|
||||
nvd_api_key: Option<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
http,
|
||||
searxng_url,
|
||||
/// A scanner whose requests `guard` checks.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`CoreError::Http`] if the HTTP client cannot be built.
|
||||
pub fn new(guard: NetGuard, nvd_api_key: Option<String>) -> Result<Self, CoreError> {
|
||||
Ok(Self {
|
||||
http: PublicHttp::new(guard)?,
|
||||
nvd_api_key,
|
||||
}
|
||||
osv_api: OSV_API.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Ask the OSV API at `api` instead of OSV's.
|
||||
#[cfg(test)]
|
||||
fn with_osv_api(mut self, api: String) -> Self {
|
||||
self.osv_api = api;
|
||||
self
|
||||
}
|
||||
|
||||
/// Match every SBOM entry with a purl against OSV, attaching the
|
||||
@@ -164,28 +179,28 @@ impl CveScanner {
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
|
||||
let resp = self
|
||||
.http
|
||||
.post("https://api.osv.dev/v1/querybatch")
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::warn!("OSV.dev API call failed: {e}");
|
||||
CoreError::Http(format!("OSV.dev request failed: {e}"))
|
||||
})?;
|
||||
let url = format!("{}/v1/querybatch", self.osv_api);
|
||||
let resp = match self.http.post(&url) {
|
||||
Ok(req) => req.json(&body).send().await.map_err(|e| e.to_string()),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
.map_err(|e| {
|
||||
tracing::warn!("OSV.dev API call failed: {e}");
|
||||
CoreError::Http(format!("OSV.dev request failed: {e}"))
|
||||
})?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
let status = resp.status();
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
let body = read_body(resp).await.unwrap_or_default();
|
||||
let body = String::from_utf8_lossy(&body);
|
||||
tracing::warn!("OSV.dev returned {status}: {body}");
|
||||
refused.extend(chunk.iter().map(|(i, _)| *i));
|
||||
continue;
|
||||
}
|
||||
|
||||
let result: OsvBatchResponse = resp.json().await.map_err(|e| {
|
||||
tracing::warn!("failed to parse OSV.dev response: {e}");
|
||||
CoreError::Http(format!("Failed to parse OSV.dev response: {e}"))
|
||||
let result: OsvBatchResponse = read_json(resp).await.map_err(|e| {
|
||||
tracing::warn!("failed to read OSV.dev response: {e}");
|
||||
CoreError::Http(format!("Failed to read OSV.dev response: {e}"))
|
||||
})?;
|
||||
|
||||
for ((index, _), answer) in chunk.iter().zip(result.results) {
|
||||
@@ -218,18 +233,17 @@ impl CveScanner {
|
||||
|
||||
futures_util::stream::iter(ids)
|
||||
.map(|id| async move {
|
||||
let url = format!("https://api.osv.dev/v1/vulns/{id}");
|
||||
let record: serde_json::Value = self
|
||||
let url = format!("{}/v1/vulns/{id}", self.osv_api);
|
||||
let resp = self
|
||||
.http
|
||||
.get(&url)
|
||||
.ok()?
|
||||
.send()
|
||||
.await
|
||||
.ok()?
|
||||
.error_for_status()
|
||||
.ok()?
|
||||
.json()
|
||||
.await
|
||||
.ok()?;
|
||||
let record: serde_json::Value = read_json(resp).await.ok()?;
|
||||
Some((id, OsvDetail::parse(&record)))
|
||||
})
|
||||
.buffer_unordered(CONCURRENT_LOOKUPS)
|
||||
@@ -243,8 +257,12 @@ impl CveScanner {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let url = format!("https://services.nvd.nist.gov/rest/json/cves/2.0?cveId={cve_id}");
|
||||
let mut req = self.http.get(&url);
|
||||
let mut req = self
|
||||
.http
|
||||
.get(nvd_cpe::NVD_CVES_URL)
|
||||
.map_err(|e| CoreError::Http(format!("NVD request refused: {e}")))?
|
||||
.query(&[("cveId", cve_id)])
|
||||
.timeout(nvd_cpe::NVD_REQUEST_TIMEOUT);
|
||||
|
||||
if let Some(key) = &self.nvd_api_key {
|
||||
req = req.header("apiKey", key.as_str());
|
||||
@@ -259,10 +277,9 @@ impl CveScanner {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let body: serde_json::Value = resp
|
||||
.json()
|
||||
let body: serde_json::Value = read_json(resp)
|
||||
.await
|
||||
.map_err(|e| CoreError::Http(format!("Failed to parse NVD response: {e}")))?;
|
||||
.map_err(|e| CoreError::Http(format!("Failed to read NVD response: {e}")))?;
|
||||
|
||||
// Extract CVSS v3.1 base score
|
||||
let score = body["vulnerabilities"]
|
||||
@@ -275,41 +292,6 @@ impl CveScanner {
|
||||
Ok(score)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub async fn search_context(&self, cve_id: &str) -> Result<Vec<String>, CoreError> {
|
||||
let Some(searxng_url) = &self.searxng_url else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
|
||||
let url = format!(
|
||||
"{}/search?q={cve_id}&format=json&engines=duckduckgo",
|
||||
searxng_url.trim_end_matches('/')
|
||||
);
|
||||
let resp = self
|
||||
.http
|
||||
.get(&url)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| CoreError::Http(format!("SearXNG request failed: {e}")))?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let body: serde_json::Value = resp.json().await.unwrap_or_default();
|
||||
let results = body["results"]
|
||||
.as_array()
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.take(5)
|
||||
.filter_map(|r| r["url"].as_str().map(String::from))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
/// Match the CODESYS **runtime** component against NVD by CPE.
|
||||
///
|
||||
/// CODESYS advisories (the CoDe16 cluster and friends) are indexed in NVD by
|
||||
@@ -542,8 +524,83 @@ struct OsvVuln {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A stand-in for OSV on loopback that finds one advisory for every
|
||||
/// query; it counts the requests.
|
||||
async fn fake_osv() -> (String, Arc<AtomicUsize>) {
|
||||
let hits = Arc::new(AtomicUsize::new(0));
|
||||
let counter = Arc::clone(&hits);
|
||||
let app = axum::Router::new()
|
||||
.route(
|
||||
"/v1/querybatch",
|
||||
axum::routing::post(move |body: axum::Json<serde_json::Value>| {
|
||||
let counter = Arc::clone(&counter);
|
||||
async move {
|
||||
counter.fetch_add(1, Ordering::SeqCst);
|
||||
let n = body["queries"].as_array().map_or(0, Vec::len);
|
||||
let results: Vec<_> = (0..n)
|
||||
.map(|_| serde_json::json!({"vulns": [{"id": "GHSA-test"}]}))
|
||||
.collect();
|
||||
axum::Json(serde_json::json!({ "results": results }))
|
||||
}
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/v1/vulns/{id}",
|
||||
axum::routing::get(|| async {
|
||||
axum::Json(serde_json::json!({"id": "GHSA-test", "summary": "test"}))
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("http://{}", listener.local_addr().unwrap());
|
||||
tokio::spawn(async move {
|
||||
let _ = axum::serve(listener, app).await;
|
||||
});
|
||||
(url, hits)
|
||||
}
|
||||
|
||||
fn with_purl(name: &str, purl: &str) -> SbomEntry {
|
||||
let mut e = entry(name, "1.0.0", "npm");
|
||||
e.purl = Some(purl.into());
|
||||
e
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn osv_on_an_internal_address_is_refused() {
|
||||
let (url, hits) = fake_osv().await;
|
||||
let scanner = CveScanner::new(NetGuard::public_only(), None)
|
||||
.unwrap()
|
||||
.with_osv_api(url);
|
||||
let mut entries = vec![with_purl("left-pad", "pkg:npm/left-pad@1.0.0")];
|
||||
|
||||
let result = scanner.scan_dependencies("t", &mut entries).await;
|
||||
|
||||
assert!(result.is_err());
|
||||
assert_eq!(hits.load(Ordering::SeqCst), 0, "a request reached it");
|
||||
assert!(entries[0].known_vulnerabilities.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn osv_answers_are_read_through_the_guarded_client() {
|
||||
// Where the guard allows the address (local development), the same
|
||||
// client reaches it.
|
||||
let (url, hits) = fake_osv().await;
|
||||
let scanner = CveScanner::new(NetGuard::allow_private(), None)
|
||||
.unwrap()
|
||||
.with_osv_api(url);
|
||||
let mut entries = vec![with_purl("left-pad", "pkg:npm/left-pad@1.0.0")];
|
||||
|
||||
let lookup = scanner.scan_dependencies("t", &mut entries).await.unwrap();
|
||||
|
||||
assert_eq!(hits.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(lookup.alerts.len(), 1);
|
||||
assert_eq!(lookup.alerts[0].summary.as_deref(), Some("test"));
|
||||
}
|
||||
|
||||
fn entry(name: &str, ver: &str, pm: &str) -> SbomEntry {
|
||||
SbomEntry::new("t".into(), name.into(), ver.into(), pm.into())
|
||||
|
||||
@@ -23,6 +23,7 @@ pub mod patterns;
|
||||
pub mod plan;
|
||||
pub mod plc;
|
||||
mod pr_review;
|
||||
mod public_http;
|
||||
pub mod repo_view;
|
||||
pub mod sbom;
|
||||
pub mod semgrep;
|
||||
|
||||
@@ -9,6 +9,8 @@ use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::pipeline::public_http::{read_json, PublicHttp};
|
||||
|
||||
/// A product as NVD names it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct NvdProduct {
|
||||
@@ -31,7 +33,7 @@ pub struct NvdCve {
|
||||
}
|
||||
|
||||
/// NVD's CVE API.
|
||||
const NVD_CVES_URL: &str = "https://services.nvd.nist.gov/rest/json/cves/2.0";
|
||||
pub(crate) 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
|
||||
@@ -47,6 +49,11 @@ const RETRY_DELAYS: [Duration; 3] = [
|
||||
/// FreeRTOS) must not spend the rate budget on the same question again.
|
||||
const CACHE_TTL: Duration = Duration::from_secs(6 * 60 * 60);
|
||||
|
||||
/// Time for one NVD request: NVD answers a product query with up to 2,000
|
||||
/// CVEs and is slow at times (more so without an API key), so it gets longer
|
||||
/// than the client's default.
|
||||
pub(crate) const NVD_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// NVD answers by product match string, with when they were fetched.
|
||||
type Cache = Mutex<HashMap<String, (Instant, Arc<serde_json::Value>)>>;
|
||||
|
||||
@@ -65,8 +72,8 @@ fn cache() -> &'static Cache {
|
||||
/// 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,
|
||||
pub(crate) async fn product_cves(
|
||||
http: &PublicHttp,
|
||||
api_key: Option<&str>,
|
||||
product: NvdProduct,
|
||||
version: &str,
|
||||
@@ -85,7 +92,7 @@ pub async fn product_cves(
|
||||
/// 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,
|
||||
http: &PublicHttp,
|
||||
base_url: &str,
|
||||
api_key: Option<&str>,
|
||||
match_string: &str,
|
||||
@@ -104,15 +111,17 @@ async fn product_body(
|
||||
);
|
||||
tokio::time::sleep(*wait).await;
|
||||
}
|
||||
// A URL the net guard refuses is refused for good: not retried.
|
||||
let mut req = http
|
||||
.get(base_url)
|
||||
.query(&[("virtualMatchString", match_string)]);
|
||||
.get(base_url)?
|
||||
.query(&[("virtualMatchString", match_string)])
|
||||
.timeout(NVD_REQUEST_TIMEOUT);
|
||||
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: serde_json::Value = read_json(resp).await?;
|
||||
let body = Arc::new(body);
|
||||
if let Ok(mut c) = cache().lock() {
|
||||
c.insert(
|
||||
@@ -271,6 +280,8 @@ mod tests {
|
||||
use std::cmp::Ordering::{Equal, Greater, Less};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use compliance_core::net_guard::NetGuard;
|
||||
|
||||
/// 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>) {
|
||||
@@ -317,7 +328,8 @@ mod tests {
|
||||
#[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 http =
|
||||
PublicHttp::new(NetGuard::allow_private()).unwrap_or_else(|e| panic!("client: {e}"));
|
||||
|
||||
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;
|
||||
@@ -331,7 +343,8 @@ mod tests {
|
||||
#[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 http =
|
||||
PublicHttp::new(NetGuard::allow_private()).unwrap_or_else(|e| panic!("client: {e}"));
|
||||
|
||||
let result = product_body(&http, &url, None, "cpe:test:limited", &NO_WAIT).await;
|
||||
|
||||
@@ -349,7 +362,8 @@ mod tests {
|
||||
#[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();
|
||||
let http =
|
||||
PublicHttp::new(NetGuard::allow_private()).unwrap_or_else(|e| panic!("client: {e}"));
|
||||
|
||||
assert!(
|
||||
product_body(&http, &url, None, "cpe:test:missing", &NO_WAIT)
|
||||
@@ -359,6 +373,20 @@ mod tests {
|
||||
assert_eq!(hits.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_internal_address_is_refused_and_not_retried() {
|
||||
// The stand-in listens on loopback: with the guard of a hardened
|
||||
// deployment, NVD's URL pointing there is refused before any request.
|
||||
let (url, hits) = fake_nvd(0, 200).await;
|
||||
let http =
|
||||
PublicHttp::new(NetGuard::public_only()).unwrap_or_else(|e| panic!("client: {e}"));
|
||||
|
||||
let result = product_body(&http, &url, None, "cpe:test:internal", &NO_WAIT).await;
|
||||
|
||||
assert!(result.is_err(), "{result:?}");
|
||||
assert_eq!(hits.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fatfs_revisions_match_nvds_ranges() {
|
||||
// The shape of CVE-2026-6682: FatFs R0.16 and earlier.
|
||||
|
||||
@@ -41,7 +41,6 @@ pub struct PipelineOrchestrator {
|
||||
pub(super) tenant_id: String,
|
||||
pub(super) db: Database,
|
||||
pub(super) llm: Arc<LlmClient>,
|
||||
pub(super) http: reqwest::Client,
|
||||
/// Opens the target's sealed credentials (git and tracker tokens).
|
||||
pub(super) secrets: SecretBox,
|
||||
/// Where clones and tracker calls may connect (#256, #294).
|
||||
@@ -51,13 +50,7 @@ pub struct PipelineOrchestrator {
|
||||
}
|
||||
|
||||
impl PipelineOrchestrator {
|
||||
pub fn new(
|
||||
config: AgentConfig,
|
||||
tenant_id: &str,
|
||||
db: Database,
|
||||
llm: Arc<LlmClient>,
|
||||
http: reqwest::Client,
|
||||
) -> Self {
|
||||
pub fn new(config: AgentConfig, tenant_id: &str, db: Database, llm: Arc<LlmClient>) -> Self {
|
||||
let secrets = SecretBox::from_config(&config);
|
||||
let net_guard = NetGuard::from_env(config.app_env);
|
||||
Self {
|
||||
@@ -65,7 +58,6 @@ impl PipelineOrchestrator {
|
||||
tenant_id: tenant_id.to_string(),
|
||||
db,
|
||||
llm,
|
||||
http,
|
||||
secrets,
|
||||
net_guard,
|
||||
nuget_license_cache: None,
|
||||
@@ -365,13 +357,12 @@ impl PipelineOrchestrator {
|
||||
tracing::info!("[{repo_id}] Stage 3: CVE Scanning");
|
||||
self.update_phase(scan_run_id, ScanPhase::CveScanning).await;
|
||||
let cve_scanner = CveScanner::new(
|
||||
self.http.clone(),
|
||||
self.config.searxng_url.clone(),
|
||||
self.net_guard,
|
||||
self.config.nvd_api_key.as_ref().map(|k| {
|
||||
use secrecy::ExposeSecret;
|
||||
k.expose_secret().to_string()
|
||||
}),
|
||||
);
|
||||
)?;
|
||||
// Whether every component was matched: only then is a CVE missing
|
||||
// from this scan known to be gone (and its issue closed).
|
||||
let mut cve_complete = true;
|
||||
@@ -1265,13 +1256,12 @@ impl PipelineOrchestrator {
|
||||
.await?;
|
||||
|
||||
let cve_scanner = CveScanner::new(
|
||||
self.http.clone(),
|
||||
self.config.searxng_url.clone(),
|
||||
self.net_guard,
|
||||
self.config.nvd_api_key.as_ref().map(|k| {
|
||||
use secrecy::ExposeSecret;
|
||||
k.expose_secret().to_string()
|
||||
}),
|
||||
);
|
||||
)?;
|
||||
let mut alerts = match tokio::time::timeout(
|
||||
std::time::Duration::from_secs(600),
|
||||
cve_scanner.scan_dependencies(target_id, &mut entries),
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
//! HTTP to the public vulnerability databases (OSV, NVD), guarded (#469).
|
||||
//!
|
||||
//! The CVE lookups go to fixed public hosts, but they leave the agent like
|
||||
//! any other request: over a [`guarded_client_builder`] client (the resolver
|
||||
//! returns only addresses the net guard approves, every redirect is
|
||||
//! re-checked, no proxy), with the first URL checked by
|
||||
//! [`NetGuard::check_url`] before it is sent, a per-request and a connect
|
||||
//! timeout, and a cap on the body read. The same pattern as the nuget.org
|
||||
//! license lookup (`sbom::nuget_license`).
|
||||
//!
|
||||
//! [`guarded_client_builder`]: compliance_core::guarded_net::guarded_client_builder
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use compliance_core::guarded_net::guarded_client_builder;
|
||||
use compliance_core::net_guard::NetGuard;
|
||||
use compliance_core::CoreError;
|
||||
|
||||
/// Default time for one request, connect to the last body byte.
|
||||
pub(crate) const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
/// Time to open the connection.
|
||||
pub(crate) const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
/// Most bytes a response body may have. NVD answers a product query with up
|
||||
/// to 2,000 CVEs (about 1 MB for every CODESYS CVE), an OSV batch of 500
|
||||
/// purls with ids only, an OSV record with its affected versions; 16 MiB is
|
||||
/// well above all of them and still bounds a scan's memory.
|
||||
pub(crate) const MAX_BODY_BYTES: usize = 16 * 1024 * 1024;
|
||||
|
||||
/// A guarded HTTP client for the public vulnerability databases.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct PublicHttp {
|
||||
http: reqwest::Client,
|
||||
guard: NetGuard,
|
||||
}
|
||||
|
||||
impl PublicHttp {
|
||||
/// A client checking every address with `guard`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`CoreError::Http`] if the HTTP client cannot be built.
|
||||
pub(crate) fn new(guard: NetGuard) -> Result<Self, CoreError> {
|
||||
let http = guarded_client_builder(guard)
|
||||
.timeout(REQUEST_TIMEOUT)
|
||||
.connect_timeout(CONNECT_TIMEOUT)
|
||||
.build()
|
||||
.map_err(|e| CoreError::Http(format!("HTTP client: {e}")))?;
|
||||
Ok(Self { http, guard })
|
||||
}
|
||||
|
||||
/// A GET to `url`, once the guard accepts it.
|
||||
pub(crate) fn get(&self, url: &str) -> Result<reqwest::RequestBuilder, String> {
|
||||
self.guard.check_url(url).map_err(|e| e.to_string())?;
|
||||
Ok(self.http.get(url))
|
||||
}
|
||||
|
||||
/// A POST to `url`, once the guard accepts it.
|
||||
pub(crate) fn post(&self, url: &str) -> Result<reqwest::RequestBuilder, String> {
|
||||
self.guard.check_url(url).map_err(|e| e.to_string())?;
|
||||
Ok(self.http.post(url))
|
||||
}
|
||||
}
|
||||
|
||||
/// The body of `resp`, refused once it exceeds [`MAX_BODY_BYTES`].
|
||||
pub(crate) async fn read_body(mut resp: reqwest::Response) -> Result<Vec<u8>, String> {
|
||||
if resp
|
||||
.content_length()
|
||||
.is_some_and(|n| n > MAX_BODY_BYTES as u64)
|
||||
{
|
||||
return Err(format!("response larger than {MAX_BODY_BYTES} bytes"));
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
while let Some(chunk) = resp.chunk().await.map_err(|e| e.to_string())? {
|
||||
if body.len() + chunk.len() > MAX_BODY_BYTES {
|
||||
return Err(format!("response larger than {MAX_BODY_BYTES} bytes"));
|
||||
}
|
||||
body.extend_from_slice(&chunk);
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
/// The JSON body of `resp`, within [`MAX_BODY_BYTES`].
|
||||
pub(crate) async fn read_json<T: serde::de::DeserializeOwned>(
|
||||
resp: reqwest::Response,
|
||||
) -> Result<T, String> {
|
||||
let body = read_body(resp).await?;
|
||||
serde_json::from_slice(&body).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn internal_addresses_are_refused_before_any_request() {
|
||||
let http = PublicHttp::new(NetGuard::public_only()).unwrap();
|
||||
for url in [
|
||||
"http://127.0.0.1:8080/v1/querybatch",
|
||||
"http://10.0.0.5/v1/vulns/GHSA-x",
|
||||
"http://169.254.169.254/latest/meta-data/",
|
||||
"http://[::1]/",
|
||||
"http://192.168.1.10/rest/json/cves/2.0",
|
||||
] {
|
||||
assert!(http.get(url).is_err(), "{url} was not refused");
|
||||
assert!(http.post(url).is_err(), "{url} was not refused");
|
||||
}
|
||||
assert!(http.get("https://api.osv.dev/v1/vulns/GHSA-x").is_ok());
|
||||
assert!(http
|
||||
.get("https://services.nvd.nist.gov/rest/json/cves/2.0")
|
||||
.is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_loopback_name_reaches_nothing() {
|
||||
// `localhost` is refused, by the URL check or by the guarded
|
||||
// resolver when it resolves to loopback: either way no connection.
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let http = PublicHttp::new(NetGuard::public_only()).unwrap();
|
||||
let sent = match http.get(&format!("http://localhost:{port}/")) {
|
||||
Ok(req) => req.send().await.map(|_| ()).map_err(|e| e.to_string()),
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
assert!(sent.is_err(), "a loopback connection was made");
|
||||
}
|
||||
}
|
||||
@@ -251,11 +251,13 @@ async fn monitor_cves(agent: &ComplianceAgent, tenant_id: &str) {
|
||||
use secrecy::ExposeSecret;
|
||||
k.expose_secret().to_string()
|
||||
});
|
||||
let scanner = crate::pipeline::cve::CveScanner::new(
|
||||
agent.http.clone(),
|
||||
agent.config.searxng_url.clone(),
|
||||
nvd_key,
|
||||
);
|
||||
let scanner = match crate::pipeline::cve::CveScanner::new(agent.net_guard, nvd_key) {
|
||||
Ok(scanner) => scanner,
|
||||
Err(e) => {
|
||||
tracing::error!("CVE monitor: no HTTP client for '{tenant_id}': {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let mut new_notifications = 0u32;
|
||||
|
||||
|
||||
@@ -109,6 +109,8 @@ Prüfwerk matches every SBOM component directly against two public vulnerability
|
||||
|
||||
Matches are stored as CVE alerts with CVSS scores and re-checked hourly, so newly published CVEs against an unchanged dependency still raise a notification.
|
||||
|
||||
Only package URLs (purl), CVE ids and CPE product prefixes are sent. Both sources are reached through the net guard like every other outbound request (see [Outbound connections](#outbound-connections-egress)).
|
||||
|
||||
## nuget.org -- NuGet Licenses
|
||||
|
||||
Licenses of NuGet packages that no `.nuspec` in the tree gives are read from the [nuget.org registration API](https://learn.microsoft.com/nuget/api/registration-base-url-resource) (`api.nuget.org`). Only the package id and version are sent, never for an id a `nuget.config` routes to another feed (see [.NET projects](/guide/dotnet-en)). The lookup is bounded per scan (8 requests at once, 10 s per request, 60 s and 300 uncached packages in total); answers are cached for all tenants. Set `NUGET_LICENSE_LOOKUP=false` to keep the agent from contacting nuget.org.
|
||||
@@ -182,6 +184,41 @@ Every new finding a scan stores -- regardless of which scanner produced it -- go
|
||||
The AI triage is a starting point, not a final verdict. Always review the rationale and code evidence before acting on a finding. See [Understanding Findings](/guide/findings#human-in-the-loop) for more on the human-in-the-loop workflow.
|
||||
:::
|
||||
|
||||
## Outbound connections (egress)
|
||||
|
||||
Every connection the agent opens, in one place. **Guarded** means: the HTTP client is built with `guarded_client_builder` (the resolver returns only addresses the net guard approves, every redirect hop is re-checked, no proxy) and the first URL is checked with `NetGuard::check_url` before it is sent. In a hardened deployment the guard refuses private, loopback, link-local and metadata addresses; `PW_ALLOW_PRIVATE_TARGETS=1` relaxes it outside hardened deployments only.
|
||||
|
||||
### Public data sources
|
||||
|
||||
| Destination | What is sent | Module | Guard | Limits | Switch |
|
||||
|---|---|---|---|---|---|
|
||||
| `api.osv.dev` (`/v1/querybatch`, `/v1/vulns/{id}`) | purls of SBOM components, advisory ids | `pipeline/cve.rs` | guarded | 10 s per request, 5 s connect, body ≤ 16 MiB, 8 advisory reads at once | none (CVE stage) |
|
||||
| `services.nvd.nist.gov` (`/rest/json/cves/2.0`) | CVE ids (CVSS score), CPE product prefixes (CODESYS, embedded libraries) | `pipeline/cve.rs`, `pipeline/nvd_cpe.rs` | guarded | 30 s per request, 5 s connect, body ≤ 16 MiB, 3 retries after 6/12/24 s, answers cached 6 h | `NVD_API_KEY` (optional, raises NVD's rate limit) |
|
||||
| `api.nuget.org` (registration, catalog) | NuGet package ids and versions, not for ids a `nuget.config` routes to another feed | `pipeline/sbom/nuget_license.rs` | guarded | 10 s per request, 5 s connect, body ≤ 2 MiB, 8 at once, 60 s and 300 uncached packages per scan | `NUGET_LICENSE_LOOKUP=false` |
|
||||
| Package registries (Go proxy, npm, PyPI, Maven Central) | package names and versions | Syft (`pipeline/sbom/syft.rs`, remote license lookups) and lockfile generation (`npm`, `cargo`, `pip-compile` in `pipeline/sbom/mod.rs`) | not guarded: subprocesses with their own HTTP | Syft 10 min per scan | lockfile generation follows the execution policy |
|
||||
|
||||
### Tenant-chosen addresses
|
||||
|
||||
| Destination | Module | Guard |
|
||||
|---|---|---|
|
||||
| Git remotes (clone, fetch, submodules, linked artifacts) | `pipeline/git.rs`, `ingest/` | `check_git_url` and the resolved address before every clone and fetch; redirects off |
|
||||
| Gitea API of a git source or tracker (managed Git) | `git_source/gitea.rs`, `trackers/gitea.rs` | guarded |
|
||||
| DAST and pentest targets | `api/handlers/dast.rs`, `pentest/orchestrator.rs`, `compliance-dast` | base URL checked with `check_url`; the DAST tools share a guarded client |
|
||||
|
||||
### Operator-configured services (not guarded)
|
||||
|
||||
These are set by the operator in the agent's environment, not by a tenant, and often live on the platform's internal network, which the guard refuses by design. They use plain clients.
|
||||
|
||||
| Destination | Module | Set by |
|
||||
|---|---|---|
|
||||
| LLM gateway (LiteLLM) | `llm/` | `LITELLM_URL` |
|
||||
| Tenant registry (entitlements, projects) | `registry.rs` | `TENANT_REGISTRY_URL` |
|
||||
| breakpilot-compliance OSCAL catalog | `controls/oscal_provider.rs` | `BREAKPILOT_BASE_URL` |
|
||||
| GitLab and Jira issue trackers | `trackers/gitlab.rs`, `trackers/jira.rs` | `GITLAB_URL`, `JIRA_URL` |
|
||||
| Identity providers for pentest test-user cleanup (Keycloak, Auth0, Okta) | `pentest/cleanup.rs` | `KEYCLOAK_URL`, `AUTH0_DOMAIN`, `OKTA_DOMAIN` |
|
||||
| Headless Chrome for PDF reports | `pentest/report/pdf.rs` | `CHROME_WS_URL` |
|
||||
| MongoDB | `database.rs` | `MONGODB_URI` |
|
||||
|
||||
## Planned integrations (decided 2026-08-31, not yet in the code)
|
||||
|
||||
The product spec keeps an **OSS-only** tooling policy and a control-mapping rule of *tools detect, the LLM judges*. Two deterministic detectors are therefore being added **underneath** the agentic DAST/pentest layer — the agents stay on top for context-seeded exploitation, chaining and explanation:
|
||||
|
||||
Reference in new issue
Block a user