fix(cve): notifications and tracker issues respect VEX not_affected and fixed (#555)
This commit was merged in pull request #555.
This commit is contained in:
1 parent
8d6be32c83
commit
42b25719ec
16 files changed
+901
-120
No files matched your search
@@ -54,6 +54,10 @@ CVE_MONITOR_SCHEDULE=0 0 0 * * *
|
||||
# that never got an issue are linked to their existing issue or get a new one,
|
||||
# at most 20 new per target and scan. off (default) | dry_run (log counts only) | on
|
||||
# ISSUE_CATCHUP=off
|
||||
# Closing CVE issues a VEX statement settles (not_affected or fixed), with a
|
||||
# comment, at most 20 per target and scan; no new issue is opened for such a
|
||||
# CVE either way. off (default) | dry_run (log counts per VEX status) | on
|
||||
# ISSUE_AUTOCLOSE=off
|
||||
GIT_CLONE_BASE_PATH=/tmp/compliance-scanner/repos
|
||||
# NuGet licenses (#467): look up licenses the tree's .nuspec files do not give
|
||||
# on api.nuget.org (package id and version only; never for ids a nuget.config
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use compliance_core::config::{AppEnv, BreakpilotConfig, Features, IssueCatchup, PlcRuntimeConfig};
|
||||
use compliance_core::config::{
|
||||
AppEnv, BreakpilotConfig, Features, IssueAutoclose, IssueCatchup, PlcRuntimeConfig,
|
||||
};
|
||||
use compliance_core::AgentConfig;
|
||||
use secrecy::SecretString;
|
||||
|
||||
@@ -128,6 +130,15 @@ fn build_config(app_env: AppEnv) -> Result<AgentConfig, AgentError> {
|
||||
features: Features::parse(&env_var_opt("PW_FEATURES").unwrap_or_default()),
|
||||
app_env,
|
||||
issue_catchup: load_issue_catchup(),
|
||||
issue_autoclose: load_issue_autoclose(),
|
||||
})
|
||||
}
|
||||
|
||||
/// `ISSUE_AUTOCLOSE`; an unknown value is logged and leaves closing off.
|
||||
fn load_issue_autoclose() -> IssueAutoclose {
|
||||
IssueAutoclose::parse(&env_var_opt("ISSUE_AUTOCLOSE").unwrap_or_default()).unwrap_or_else(|e| {
|
||||
tracing::warn!("{e}; CVE issues settled by VEX stay open");
|
||||
IssueAutoclose::Off
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,13 @@
|
||||
//! updated or removed), the issue is closed with a comment; when it comes back,
|
||||
//! it is reopened.
|
||||
//!
|
||||
//! A CVE a VEX statement settles (`not_affected` or `fixed`, by a person, the
|
||||
//! scan or an imported VEX document) gets no issue. Its open issue is closed
|
||||
//! with a comment naming the status and the reason when `ISSUE_AUTOCLOSE` is
|
||||
//! `on` (at most [`AUTOCLOSE_PER_SCAN`] per target and scan), only counted
|
||||
//! with `dry_run`, and left open with `off`, the default. When the statement
|
||||
//! is withdrawn, the issue is reopened (or opened) as for a CVE found again.
|
||||
//!
|
||||
//! What is known about a CVE's exploitation (#493) moves the threshold: a CVE
|
||||
//! in CISA's KEV catalog always gets an issue, rated at least high, and one
|
||||
//! whose EPSS percentile reaches [`epss_percentile`] is rated one step higher
|
||||
@@ -16,8 +23,9 @@ use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
use mongodb::bson::doc;
|
||||
|
||||
use compliance_core::config::IssueAutoclose;
|
||||
use compliance_core::models::notification::{parse_severity, NotificationSeverity};
|
||||
use compliance_core::models::{CveAlert, IssueStatus, TrackerIssue};
|
||||
use compliance_core::models::{CveAlert, IssueStatus, TrackerIssue, VexAssessment, VexStatus};
|
||||
|
||||
use crate::database::Database;
|
||||
use crate::error::AgentError;
|
||||
@@ -30,6 +38,8 @@ const CVE_CONTROLS: [&str; 2] = ["cra-ai-22", "cra-ai-33"];
|
||||
/// Where the issues of one target go.
|
||||
pub(crate) struct CveIssueTarget<'a> {
|
||||
pub db: &'a Database,
|
||||
/// The tenant, for the log lines.
|
||||
pub tenant_id: &'a str,
|
||||
pub tracker: &'a TrackerDispatch,
|
||||
pub owner: &'a str,
|
||||
pub repo: &'a str,
|
||||
@@ -40,6 +50,9 @@ pub(crate) struct CveIssueTarget<'a> {
|
||||
/// From this EPSS percentile (0 to 1) on a CVE is rated one step higher;
|
||||
/// `None` leaves EPSS out (see [`epss_percentile`]).
|
||||
pub epss_percentile: Option<f64>,
|
||||
/// Whether open issues a VEX statement settles are closed
|
||||
/// (`ISSUE_AUTOCLOSE`).
|
||||
pub autoclose: IssueAutoclose,
|
||||
}
|
||||
|
||||
/// The EPSS percentile from which a CVE is rated one step higher.
|
||||
@@ -136,7 +149,9 @@ fn issue_worthy(alert: &CveAlert, epss_percentile: Option<f64>) -> bool {
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `target` - where the issues go
|
||||
/// * `alerts` - every CVE the scan found in the target's components
|
||||
/// * `alerts` - every CVE the scan found in the target's components, with
|
||||
/// its stored VEX statement
|
||||
/// ([`crate::pipeline::vex_lifecycle::attach_stored_vex`])
|
||||
/// * `complete` - whether every component was matched; only then is a CVE
|
||||
/// that is missing from `alerts` known to be gone, and its issue closed
|
||||
///
|
||||
@@ -171,7 +186,7 @@ pub(crate) async fn sync_cve_issues(
|
||||
|
||||
for (key, alert) in present
|
||||
.iter()
|
||||
.filter(|(_, a)| issue_worthy(a, target.epss_percentile))
|
||||
.filter(|(_, a)| !a.is_resolved_by_vex() && issue_worthy(a, target.epss_percentile))
|
||||
{
|
||||
match existing.get(key) {
|
||||
Some(issue) if is_closed(&issue.status) => {
|
||||
@@ -190,6 +205,17 @@ pub(crate) async fn sync_cve_issues(
|
||||
}
|
||||
}
|
||||
|
||||
// A VEX statement settles the CVE whether or not the scan was complete.
|
||||
let settled: Vec<(&TrackerIssue, &VexAssessment)> = present
|
||||
.iter()
|
||||
.filter_map(|(key, alert)| {
|
||||
let vex = alert.vex.as_ref().filter(|_| alert.is_resolved_by_vex())?;
|
||||
let issue = existing.get(key).filter(|i| !is_closed(&i.status))?;
|
||||
Some((issue, vex))
|
||||
})
|
||||
.collect();
|
||||
counts.closed += autoclose(target, &settled).await?;
|
||||
|
||||
if complete {
|
||||
for (key, issue) in &existing {
|
||||
if present.contains_key(key) || is_closed(&issue.status) {
|
||||
@@ -205,6 +231,86 @@ pub(crate) async fn sync_cve_issues(
|
||||
Ok(counts)
|
||||
}
|
||||
|
||||
/// Open issues closed per target and scan because a VEX statement settles
|
||||
/// their CVE; the rest follow in the next scans.
|
||||
const AUTOCLOSE_PER_SCAN: usize = 20;
|
||||
|
||||
/// Close the open issues in `settled` (each with the VEX statement that
|
||||
/// settles its CVE) as `ISSUE_AUTOCLOSE` says: not at all, only counted, or
|
||||
/// at most [`AUTOCLOSE_PER_SCAN`] with a comment. Every Gitea request waits
|
||||
/// for its instance's slot ([`crate::trackers::gitea_limit`]). Unless off,
|
||||
/// logs one line per target and scan with counts only, also when there is
|
||||
/// nothing to close, so "ran, nothing to close" shows in the log.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// How many issues were closed.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// A database error.
|
||||
async fn autoclose(
|
||||
target: &CveIssueTarget<'_>,
|
||||
settled: &[(&TrackerIssue, &VexAssessment)],
|
||||
) -> Result<u32, AgentError> {
|
||||
let tenant_id = target.tenant_id;
|
||||
let target_id = target.target_id;
|
||||
match target.autoclose {
|
||||
IssueAutoclose::Off => Ok(0),
|
||||
IssueAutoclose::DryRun => {
|
||||
let not_affected = settled
|
||||
.iter()
|
||||
.filter(|(_, vex)| vex.status == VexStatus::NotAffected)
|
||||
.count();
|
||||
tracing::info!(
|
||||
tenant_id,
|
||||
target_id,
|
||||
would_close = settled.len(),
|
||||
not_affected,
|
||||
fixed = settled.len() - not_affected,
|
||||
"CVE issues settled by VEX (dry run, nothing changed)"
|
||||
);
|
||||
Ok(0)
|
||||
}
|
||||
IssueAutoclose::On => {
|
||||
let (mut closed, mut failed) = (0u32, 0u32);
|
||||
for (issue, vex) in settled.iter().take(AUTOCLOSE_PER_SCAN) {
|
||||
if set_state(target, issue, &vex_comment(vex), "closed").await {
|
||||
record(target.db, issue, IssueStatus::Closed).await?;
|
||||
closed += 1;
|
||||
} else {
|
||||
failed += 1;
|
||||
}
|
||||
}
|
||||
tracing::info!(
|
||||
tenant_id,
|
||||
target_id,
|
||||
closed,
|
||||
deferred = settled.len().saturating_sub(AUTOCLOSE_PER_SCAN),
|
||||
failed,
|
||||
"CVE issues settled by VEX closed"
|
||||
);
|
||||
Ok(closed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The comment an issue is closed with when a VEX statement settles its CVE:
|
||||
/// the status and the justification, or the reason in words.
|
||||
fn vex_comment(vex: &VexAssessment) -> String {
|
||||
let reason = match (vex.justification, vex.impact_statement.as_deref()) {
|
||||
(Some(justification), _) => format!(" ({})", justification.as_str()),
|
||||
(None, Some(statement)) if !statement.trim().is_empty() => {
|
||||
format!(": {}", statement.trim())
|
||||
}
|
||||
(None, _) => String::new(),
|
||||
};
|
||||
let status = vex.status.as_str();
|
||||
format!(
|
||||
"**Prüfwerk:** VEX-Status `{status}`{reason}. Geschlossen, solange diese Aussage gilt.\n\nVEX status `{status}`{reason}. Closed while this statement stands."
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether an issue is closed.
|
||||
fn is_closed(status: &IssueStatus) -> bool {
|
||||
matches!(status, IssueStatus::Closed | IssueStatus::Resolved)
|
||||
@@ -411,7 +517,7 @@ mod tests {
|
||||
use axum::extract::{Path, State};
|
||||
use axum::routing::{get, patch, post};
|
||||
use axum::{Json, Router};
|
||||
use compliance_core::models::CveSource;
|
||||
use compliance_core::models::{CveSource, VexJustification, VexStatus};
|
||||
use compliance_core::NetGuard;
|
||||
use secrecy::SecretString;
|
||||
|
||||
@@ -420,22 +526,22 @@ mod tests {
|
||||
/// The calls a fake Gitea received.
|
||||
type Calls = Arc<Mutex<Vec<String>>>;
|
||||
|
||||
async fn fake_gitea(calls: Calls) -> String {
|
||||
async fn labels(
|
||||
axum::extract::Query(page): axum::extract::Query<
|
||||
std::collections::HashMap<String, String>,
|
||||
>,
|
||||
) -> Json<serde_json::Value> {
|
||||
// One page of labels: a later page is empty, as Gitea ends a list.
|
||||
if page.get("page").map(String::as_str) != Some("1") {
|
||||
return Json(serde_json::json!([]));
|
||||
}
|
||||
Json(serde_json::json!(pruefwerk_labels()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, l)| serde_json::json!({ "id": i as i64 + 1, "name": l.name, "color": "fff" }))
|
||||
.collect::<Vec<_>>()))
|
||||
/// The Prüfwerk labels, all present.
|
||||
async fn labels(
|
||||
axum::extract::Query(page): axum::extract::Query<std::collections::HashMap<String, String>>,
|
||||
) -> Json<serde_json::Value> {
|
||||
// One page of labels: a later page is empty, as Gitea ends a list.
|
||||
if page.get("page").map(String::as_str) != Some("1") {
|
||||
return Json(serde_json::json!([]));
|
||||
}
|
||||
Json(serde_json::json!(pruefwerk_labels()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, l)| serde_json::json!({ "id": i as i64 + 1, "name": l.name, "color": "fff" }))
|
||||
.collect::<Vec<_>>()))
|
||||
}
|
||||
|
||||
async fn fake_gitea(calls: Calls) -> String {
|
||||
async fn create(
|
||||
State(calls): State<Calls>,
|
||||
Json(body): Json<serde_json::Value>,
|
||||
@@ -461,8 +567,12 @@ mod tests {
|
||||
async fn comment(
|
||||
State(calls): State<Calls>,
|
||||
Path((_o, _r, n)): Path<(String, String, String)>,
|
||||
Json(body): Json<serde_json::Value>,
|
||||
) -> axum::http::StatusCode {
|
||||
calls.lock().unwrap().push(format!("comment {n}"));
|
||||
calls.lock().unwrap().push(format!(
|
||||
"comment {n}: {}",
|
||||
body["body"].as_str().unwrap_or_default()
|
||||
));
|
||||
axum::http::StatusCode::CREATED
|
||||
}
|
||||
async fn state(
|
||||
@@ -488,6 +598,27 @@ mod tests {
|
||||
format!("http://{addr}")
|
||||
}
|
||||
|
||||
/// A Gitea that lists its labels and refuses (and records) every other
|
||||
/// call: a dry run must not write.
|
||||
async fn read_only_gitea(calls: Calls) -> String {
|
||||
async fn refuse(
|
||||
State(calls): State<Calls>,
|
||||
method: axum::http::Method,
|
||||
uri: axum::http::Uri,
|
||||
) -> axum::http::StatusCode {
|
||||
calls.lock().unwrap().push(format!("{method} {uri}"));
|
||||
axum::http::StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
let app = Router::new()
|
||||
.route("/api/v1/repos/{o}/{r}/labels", get(labels))
|
||||
.fallback(refuse)
|
||||
.with_state(calls);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
format!("http://{addr}")
|
||||
}
|
||||
|
||||
fn exploited(kev: bool, percentile: Option<f64>) -> compliance_core::models::Exploitation {
|
||||
compliance_core::models::Exploitation {
|
||||
kev: kev.then(|| compliance_core::models::KevEntry {
|
||||
@@ -593,12 +724,14 @@ mod tests {
|
||||
let tracker = TrackerDispatch::Gitea(gitea);
|
||||
let target = CveIssueTarget {
|
||||
db: &db,
|
||||
tenant_id: "cve-issues",
|
||||
tracker: &tracker,
|
||||
owner: "kunde",
|
||||
repo: "app",
|
||||
target_id: "target-1",
|
||||
dashboard: "https://pruefwerk.example",
|
||||
epss_percentile: Some(0.95),
|
||||
autoclose: IssueAutoclose::Off,
|
||||
};
|
||||
let okhttp = alert("okhttp", "3.12.0", "GHSA-3cqm-mf7h-prrj", "HIGH");
|
||||
let minor = alert("gson", "2.8.8", "GHSA-4jrv-ppp4-jm57", "MODERATE");
|
||||
@@ -661,4 +794,303 @@ mod tests {
|
||||
|
||||
pool.drop_tenant("cve-issues").await.ok();
|
||||
}
|
||||
|
||||
fn vex(status: VexStatus) -> VexAssessment {
|
||||
VexAssessment {
|
||||
status,
|
||||
justification: (status == VexStatus::NotAffected)
|
||||
.then_some(VexJustification::VulnerableCodeNotInExecutePath),
|
||||
impact_statement: None,
|
||||
action_statement: None,
|
||||
by: "u1".into(),
|
||||
by_name: None,
|
||||
at: chrono::Utc::now(),
|
||||
by_scan: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_vex_comment_names_the_status_and_the_reason() {
|
||||
let comment = vex_comment(&vex(VexStatus::NotAffected));
|
||||
assert!(
|
||||
comment.contains("VEX status `not_affected` (vulnerable_code_not_in_execute_path)."),
|
||||
"{comment}"
|
||||
);
|
||||
let mut stated = vex(VexStatus::NotAffected);
|
||||
stated.justification = None;
|
||||
stated.impact_statement = Some(" The parser is not built. ".into());
|
||||
assert!(vex_comment(&stated).contains("`not_affected`: The parser is not built."));
|
||||
assert!(vex_comment(&vex(VexStatus::Fixed)).contains("VEX status `fixed`. Closed"));
|
||||
}
|
||||
|
||||
/// A tenant database for one test, or `None` (the test skips) without
|
||||
/// MongoDB.
|
||||
async fn test_db(tenant: &str) -> Option<(crate::database::DatabasePool, Database)> {
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let prefix = format!(
|
||||
"cvevex_{}",
|
||||
&uuid::Uuid::new_v4().simple().to_string()[..10]
|
||||
);
|
||||
let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else {
|
||||
eprintln!("SKIP cve_issues: no MongoDB reachable at {uri}");
|
||||
return None;
|
||||
};
|
||||
let db = pool.for_tenant_id(tenant).await.unwrap();
|
||||
Some((pool, db))
|
||||
}
|
||||
|
||||
fn tracker_at(base: String) -> TrackerDispatch {
|
||||
TrackerDispatch::Gitea(
|
||||
GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
fn vex_target<'a>(
|
||||
db: &'a Database,
|
||||
tracker: &'a TrackerDispatch,
|
||||
autoclose: IssueAutoclose,
|
||||
) -> CveIssueTarget<'a> {
|
||||
CveIssueTarget {
|
||||
db,
|
||||
tenant_id: "cve-issues-vex",
|
||||
tracker,
|
||||
owner: "kunde",
|
||||
repo: "app",
|
||||
target_id: "target-1",
|
||||
dashboard: "",
|
||||
epss_percentile: None,
|
||||
autoclose,
|
||||
}
|
||||
}
|
||||
|
||||
fn closed(n: u32) -> CveIssueCounts {
|
||||
CveIssueCounts {
|
||||
closed: n,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_vex_not_affected_or_fixed_closes_the_issue_until_it_is_withdrawn() {
|
||||
let Some((pool, db)) = test_db("cve-issues-vex").await else {
|
||||
return;
|
||||
};
|
||||
let calls: Calls = Arc::default();
|
||||
let tracker = tracker_at(fake_gitea(calls.clone()).await);
|
||||
let target = vex_target(&db, &tracker, IssueAutoclose::On);
|
||||
let mut okhttp = alert("okhttp", "3.12.0", "GHSA-3cqm-mf7h-prrj", "HIGH");
|
||||
let mut settled = alert("log4j-core", "2.14.1", "GHSA-jfh8-c2jp-5v3q", "CRITICAL");
|
||||
settled.aliases = vec!["CVE-2021-44228".into()];
|
||||
settled.vex = Some(vex(VexStatus::Fixed));
|
||||
|
||||
// A settled CVE opens no issue; the unsettled one opens one.
|
||||
let counts = sync_cve_issues(&target, &[okhttp.clone(), settled.clone()], true)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
counts,
|
||||
CveIssueCounts {
|
||||
created: 1,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
assert!(calls.lock().unwrap()[0].contains("okhttp@3.12.0"));
|
||||
|
||||
// Stated not_affected: closed with the status and the reason, even
|
||||
// after an incomplete scan, and only once.
|
||||
okhttp.vex = Some(vex(VexStatus::NotAffected));
|
||||
let both = [okhttp.clone(), settled.clone()];
|
||||
assert_eq!(
|
||||
sync_cve_issues(&target, &both, false).await.unwrap(),
|
||||
closed(1)
|
||||
);
|
||||
{
|
||||
let calls = calls.lock().unwrap();
|
||||
let comment = &calls[calls.len() - 2];
|
||||
assert!(comment.starts_with("comment 100: "), "{comment}");
|
||||
assert!(
|
||||
comment.contains("`not_affected` (vulnerable_code_not_in_execute_path)"),
|
||||
"{comment}"
|
||||
);
|
||||
assert_eq!(calls.last().unwrap(), "state 100: \"closed\"");
|
||||
}
|
||||
assert_eq!(
|
||||
sync_cve_issues(&target, &both, true).await.unwrap(),
|
||||
CveIssueCounts::default()
|
||||
);
|
||||
|
||||
// Withdrawn (back under investigation): the same issue is reopened,
|
||||
// not opened twice.
|
||||
okhttp.vex = Some(vex(VexStatus::UnderInvestigation));
|
||||
assert_eq!(
|
||||
sync_cve_issues(&target, &[okhttp.clone(), settled], true)
|
||||
.await
|
||||
.unwrap(),
|
||||
CveIssueCounts {
|
||||
reopened: 1,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
assert_eq!(calls.lock().unwrap().last().unwrap(), "state 100: \"open\"");
|
||||
assert_eq!(
|
||||
db.tracker_issues().count_documents(doc! {}).await.unwrap(),
|
||||
1
|
||||
);
|
||||
|
||||
pool.drop_tenant("cve-issues-vex").await.ok();
|
||||
}
|
||||
|
||||
/// Log lines written while the returned guard lives (on this thread; a
|
||||
/// `#[tokio::test]` runs on one).
|
||||
fn capture_logs() -> (Arc<Mutex<Vec<u8>>>, tracing::subscriber::DefaultGuard) {
|
||||
let buffer: Arc<Mutex<Vec<u8>>> = Arc::default();
|
||||
let writer = buffer.clone();
|
||||
let subscriber = tracing_subscriber::fmt()
|
||||
.with_ansi(false)
|
||||
.with_max_level(tracing::Level::INFO)
|
||||
.with_writer(move || LogWriter(writer.clone()))
|
||||
.finish();
|
||||
(buffer, tracing::subscriber::set_default(subscriber))
|
||||
}
|
||||
|
||||
struct LogWriter(Arc<Mutex<Vec<u8>>>);
|
||||
|
||||
impl std::io::Write for LogWriter {
|
||||
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||
self.0.lock().unwrap().extend_from_slice(bytes);
|
||||
Ok(bytes.len())
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The autoclose summary lines logged into `logs`.
|
||||
fn summaries(logs: &Mutex<Vec<u8>>) -> Vec<String> {
|
||||
String::from_utf8_lossy(&logs.lock().unwrap())
|
||||
.lines()
|
||||
.filter(|l| l.contains("CVE issues settled by VEX"))
|
||||
.map(str::to_owned)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn autoclose_off_and_dry_run_leave_the_issue_open() {
|
||||
let Some((pool, db)) = test_db("cve-issues-vex-off").await else {
|
||||
return;
|
||||
};
|
||||
let (logs, _guard) = capture_logs();
|
||||
let calls: Calls = Arc::default();
|
||||
let tracker = tracker_at(fake_gitea(calls.clone()).await);
|
||||
let mut okhttp = alert("okhttp", "3.12.0", "GHSA-3cqm-mf7h-prrj", "HIGH");
|
||||
let open = vex_target(&db, &tracker, IssueAutoclose::Off);
|
||||
assert_eq!(
|
||||
sync_cve_issues(&open, std::slice::from_ref(&okhttp), true)
|
||||
.await
|
||||
.unwrap()
|
||||
.created,
|
||||
1
|
||||
);
|
||||
let before = calls.lock().unwrap().len();
|
||||
|
||||
// Off: the settled CVE's issue stays open, nothing is called.
|
||||
okhttp.vex = Some(vex(VexStatus::Fixed));
|
||||
let found = std::slice::from_ref(&okhttp);
|
||||
assert_eq!(
|
||||
sync_cve_issues(&open, found, true).await.unwrap(),
|
||||
CveIssueCounts::default()
|
||||
);
|
||||
assert_eq!(calls.lock().unwrap().len(), before);
|
||||
// Off logs no summary.
|
||||
assert!(summaries(&logs).is_empty());
|
||||
|
||||
// Dry run, against a Gitea that refuses every write: only counted,
|
||||
// and a target with nothing to close says so too.
|
||||
let writes: Calls = Arc::default();
|
||||
let read_only = tracker_at(read_only_gitea(writes.clone()).await);
|
||||
let dry = vex_target(&db, &read_only, IssueAutoclose::DryRun);
|
||||
assert_eq!(
|
||||
sync_cve_issues(&dry, found, true).await.unwrap(),
|
||||
CveIssueCounts::default()
|
||||
);
|
||||
assert!(writes.lock().unwrap().is_empty(), "{:?}", writes.lock());
|
||||
let other = CveIssueTarget {
|
||||
target_id: "target-2",
|
||||
..vex_target(&db, &read_only, IssueAutoclose::DryRun)
|
||||
};
|
||||
sync_cve_issues(&other, &[], true).await.unwrap();
|
||||
let lines = summaries(&logs);
|
||||
assert_eq!(lines.len(), 2, "{lines:?}");
|
||||
assert!(
|
||||
lines[0].contains("tenant_id=\"cve-issues-vex\"")
|
||||
&& lines[0].contains("target_id=\"target-1\"")
|
||||
&& lines[0].contains("would_close=1 not_affected=0 fixed=1"),
|
||||
"{}",
|
||||
lines[0]
|
||||
);
|
||||
assert!(
|
||||
lines[1].contains("target_id=\"target-2\"") && lines[1].contains("would_close=0"),
|
||||
"{}",
|
||||
lines[1]
|
||||
);
|
||||
// No title or path in the line.
|
||||
assert!(!lines[0].contains("okhttp"), "{}", lines[0]);
|
||||
assert_eq!(
|
||||
db.tracker_issues()
|
||||
.count_documents(doc! { "status": "open" })
|
||||
.await
|
||||
.unwrap(),
|
||||
1
|
||||
);
|
||||
|
||||
pool.drop_tenant("cve-issues-vex-off").await.ok();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn autoclose_closes_at_most_twenty_per_scan() {
|
||||
let Some((pool, db)) = test_db("cve-issues-vex-many").await else {
|
||||
return;
|
||||
};
|
||||
let calls: Calls = Arc::default();
|
||||
let tracker = tracker_at(fake_gitea(calls.clone()).await);
|
||||
let target = vex_target(&db, &tracker, IssueAutoclose::On);
|
||||
let mut alerts: Vec<CveAlert> = (0..22)
|
||||
.map(|i| {
|
||||
let mut a = alert(
|
||||
&format!("lib{i:02}"),
|
||||
"1.0",
|
||||
&format!("CVE-2026-{i:04}"),
|
||||
"HIGH",
|
||||
);
|
||||
a.aliases.clear();
|
||||
a
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
sync_cve_issues(&target, &alerts, true)
|
||||
.await
|
||||
.unwrap()
|
||||
.created,
|
||||
22
|
||||
);
|
||||
|
||||
for a in &mut alerts {
|
||||
a.vex = Some(vex(VexStatus::NotAffected));
|
||||
}
|
||||
assert_eq!(
|
||||
sync_cve_issues(&target, &alerts, true).await.unwrap(),
|
||||
closed(20)
|
||||
);
|
||||
assert_eq!(
|
||||
sync_cve_issues(&target, &alerts, true).await.unwrap(),
|
||||
closed(2)
|
||||
);
|
||||
assert_eq!(
|
||||
sync_cve_issues(&target, &alerts, true).await.unwrap(),
|
||||
CveIssueCounts::default()
|
||||
);
|
||||
|
||||
pool.drop_tenant("cve-issues-vex-many").await.ok();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
//! A notification for every CVE a target's components newly carry, shared by
|
||||
//! the scans (every SBOM source: source, firmware, CODESYS libraries and
|
||||
//! runtime) and the hourly CVE monitor.
|
||||
//!
|
||||
//! One notification per CVE, target, package and version. An alert a VEX
|
||||
//! statement settles (`not_affected` or `fixed`, see
|
||||
//! [`CveAlert::is_resolved_by_vex`]) raises none; once the statement is
|
||||
//! withdrawn, the next scan or monitor run raises it as for any new CVE.
|
||||
|
||||
use mongodb::bson::doc;
|
||||
|
||||
use compliance_core::models::notification::{parse_severity, CveNotification};
|
||||
use compliance_core::models::CveAlert;
|
||||
|
||||
use crate::database::Database;
|
||||
|
||||
/// Create the notifications `alerts` of the target `repo_id` (named
|
||||
/// `repo_name`) do not have yet. The alerts carry their stored VEX statement
|
||||
/// ([`crate::pipeline::vex_lifecycle::attach_stored_vex`]).
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// How many notifications were created. A notification that cannot be stored
|
||||
/// is logged and skipped.
|
||||
pub async fn notify_new_cves(
|
||||
db: &Database,
|
||||
repo_id: &str,
|
||||
repo_name: &str,
|
||||
alerts: &[CveAlert],
|
||||
) -> u32 {
|
||||
let mut created = 0;
|
||||
for alert in alerts.iter().filter(|a| !a.is_resolved_by_vex()) {
|
||||
let filter = doc! {
|
||||
"cve_id": &alert.cve_id,
|
||||
"repo_id": &alert.repo_id,
|
||||
"package_name": &alert.affected_package,
|
||||
"package_version": &alert.affected_version,
|
||||
};
|
||||
let severity = parse_severity(alert.severity.as_deref(), alert.cvss_score);
|
||||
let mut notification = CveNotification::new(
|
||||
alert.cve_id.clone(),
|
||||
repo_id.to_string(),
|
||||
repo_name.to_string(),
|
||||
alert.affected_package.clone(),
|
||||
alert.affected_version.clone(),
|
||||
severity,
|
||||
);
|
||||
notification.cvss_score = alert.cvss_score;
|
||||
notification.summary = alert.summary.clone();
|
||||
notification.url = Some(format!("https://osv.dev/vulnerability/{}", alert.cve_id));
|
||||
let notification = match mongodb::bson::to_bson(¬ification) {
|
||||
Ok(n) => n,
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
cve = alert.cve_id,
|
||||
"could not encode the CVE notification: {e}"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
// Inserted only when missing (`$setOnInsert`), so a notification
|
||||
// that was read or dismissed stays as it is.
|
||||
match db
|
||||
.cve_notifications()
|
||||
.update_one(filter, doc! { "$setOnInsert": notification })
|
||||
.upsert(true)
|
||||
.await
|
||||
{
|
||||
Ok(result) if result.upserted_id.is_some() => created += 1,
|
||||
Ok(_) => {}
|
||||
Err(e) => tracing::warn!(
|
||||
cve = alert.cve_id,
|
||||
"could not store the CVE notification: {e}"
|
||||
),
|
||||
}
|
||||
}
|
||||
created
|
||||
}
|
||||
@@ -43,6 +43,7 @@ impl PipelineOrchestrator {
|
||||
let dashboard = std::env::var("DASHBOARD_PUBLIC_URL").unwrap_or_default();
|
||||
let target = crate::pipeline::cve_issues::CveIssueTarget {
|
||||
db: &self.db,
|
||||
tenant_id: &self.tenant_id,
|
||||
tracker: &tracker,
|
||||
owner,
|
||||
repo: name,
|
||||
@@ -51,6 +52,7 @@ impl PipelineOrchestrator {
|
||||
epss_percentile: crate::pipeline::cve_issues::epss_percentile(
|
||||
std::env::var("CVE_ISSUE_EPSS_PERCENTILE").ok().as_deref(),
|
||||
),
|
||||
autoclose: self.config.issue_autoclose,
|
||||
};
|
||||
let counts =
|
||||
crate::pipeline::cve_issues::sync_cve_issues(&target, alerts, complete).await?;
|
||||
|
||||
@@ -11,6 +11,7 @@ pub(crate) mod csaf_match;
|
||||
pub mod cve;
|
||||
pub(crate) mod cve_enrichment;
|
||||
pub(crate) mod cve_issues;
|
||||
pub mod cve_notify;
|
||||
pub mod dedup;
|
||||
pub mod devskim;
|
||||
pub mod dotnet;
|
||||
|
||||
@@ -945,15 +945,12 @@ impl PipelineOrchestrator {
|
||||
.await?;
|
||||
}
|
||||
|
||||
// Persist CVE alerts and create notifications (shared with the PLC path).
|
||||
let new_notif_count = self
|
||||
.persist_cve_alerts(&repo_id, &repo.name, &cve_alerts)
|
||||
.await?;
|
||||
if new_notif_count > 0 {
|
||||
tracing::info!("[{repo_id}] Created {new_notif_count} CVE notification(s)");
|
||||
}
|
||||
// Persist CVE alerts (shared with the PLC path).
|
||||
self.persist_cve_alerts(&cve_alerts).await?;
|
||||
// What the recipes say about their CVEs (CVE_STATUS, `CVE:` patches),
|
||||
// stated again after the alerts were stored, never over a person's.
|
||||
// stated again after the alerts were stored, never over a person's,
|
||||
// and before the notifications, which a `not_affected` or `fixed`
|
||||
// suppresses.
|
||||
let statements = yocto_inventory::vex_statements(&yocto_recipes, &cve_alerts);
|
||||
if !statements.is_empty() {
|
||||
match crate::pipeline::vex_lifecycle::apply_scan_statements(
|
||||
@@ -967,6 +964,12 @@ impl PipelineOrchestrator {
|
||||
Err(e) => tracing::warn!("[{repo_id}] VEX statements from Yocto recipes: {e}"),
|
||||
}
|
||||
}
|
||||
let new_notif_count = self
|
||||
.notify_cves(&repo_id, &repo.name, &mut cve_alerts)
|
||||
.await?;
|
||||
if new_notif_count > 0 {
|
||||
tracing::info!("[{repo_id}] Created {new_notif_count} CVE notification(s)");
|
||||
}
|
||||
|
||||
// Stage 6: Issue Creation
|
||||
tracing::info!("[{repo_id}] Stage 6: Issue Creation");
|
||||
@@ -1717,8 +1720,9 @@ impl PipelineOrchestrator {
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
self.persist_cve_alerts(&alerts).await?;
|
||||
let new_notifs = self
|
||||
.persist_cve_alerts(target_id, &target.name, &alerts)
|
||||
.notify_cves(target_id, &target.name, &mut alerts)
|
||||
.await?;
|
||||
// What the code pipeline does at its end: a complete lookup resolves
|
||||
// the alerts it no longer reports, and a managed repository's CVE
|
||||
@@ -1769,57 +1773,32 @@ impl PipelineOrchestrator {
|
||||
}
|
||||
}
|
||||
|
||||
/// Upsert CVE alerts for a target and create dedup'd CVE notifications;
|
||||
/// returns the number of newly-created notifications. Shared by the SAST
|
||||
/// pipeline and the PLC control-app SBOM path, so every SBOM source (source,
|
||||
/// firmware, CODESYS libraries/runtime) raises the same notifications.
|
||||
async fn persist_cve_alerts(
|
||||
/// Store the CVE alerts a scan of a target found. Shared by the SAST
|
||||
/// pipeline and the PLC control-app SBOM path.
|
||||
async fn persist_cve_alerts(&self, alerts: &[CveAlert]) -> Result<(), AgentError> {
|
||||
for alert in alerts {
|
||||
crate::pipeline::vex_lifecycle::upsert_reported(&self.db, alert).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Give the stored alerts' VEX statements to `alerts` and create the CVE
|
||||
/// notifications that are new (none for an alert `not_affected` or
|
||||
/// `fixed`); returns how many were created. Run after
|
||||
/// [`Self::persist_cve_alerts`] and the scan's own VEX statements, so
|
||||
/// every SBOM source (source, firmware, CODESYS libraries/runtime) raises
|
||||
/// the same notifications and the issue sync sees the statements.
|
||||
async fn notify_cves(
|
||||
&self,
|
||||
repo_id: &str,
|
||||
repo_name: &str,
|
||||
alerts: &[CveAlert],
|
||||
alerts: &mut [CveAlert],
|
||||
) -> Result<u32, AgentError> {
|
||||
use compliance_core::models::notification::{parse_severity, CveNotification};
|
||||
|
||||
let mut new_notif = 0u32;
|
||||
for alert in alerts {
|
||||
crate::pipeline::vex_lifecycle::upsert_reported(&self.db, alert).await?;
|
||||
|
||||
// Dedup notifications by cve + repo + package + version.
|
||||
let notif_filter = doc! {
|
||||
"cve_id": &alert.cve_id,
|
||||
"repo_id": &alert.repo_id,
|
||||
"package_name": &alert.affected_package,
|
||||
"package_version": &alert.affected_version,
|
||||
};
|
||||
let severity = parse_severity(alert.severity.as_deref(), alert.cvss_score);
|
||||
let mut notification = CveNotification::new(
|
||||
alert.cve_id.clone(),
|
||||
repo_id.to_string(),
|
||||
repo_name.to_string(),
|
||||
alert.affected_package.clone(),
|
||||
alert.affected_version.clone(),
|
||||
severity,
|
||||
);
|
||||
notification.cvss_score = alert.cvss_score;
|
||||
notification.summary = alert.summary.clone();
|
||||
notification.url = Some(format!("https://osv.dev/vulnerability/{}", alert.cve_id));
|
||||
let notif_update = doc! {
|
||||
"$setOnInsert": mongodb::bson::to_bson(¬ification).unwrap_or_default()
|
||||
};
|
||||
if let Ok(result) = self
|
||||
.db
|
||||
.cve_notifications()
|
||||
.update_one(notif_filter, notif_update)
|
||||
.upsert(true)
|
||||
.await
|
||||
{
|
||||
if result.upserted_id.is_some() {
|
||||
new_notif += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(new_notif)
|
||||
crate::pipeline::vex_lifecycle::attach_stored_vex(&self.db, repo_id, alerts).await?;
|
||||
Ok(
|
||||
crate::pipeline::cve_notify::notify_new_cves(&self.db, repo_id, repo_name, alerts)
|
||||
.await,
|
||||
)
|
||||
}
|
||||
|
||||
/// Ingest the target's artifacts, classify (Firmwerk for firmware/RTOS/Yocto,
|
||||
|
||||
@@ -209,6 +209,46 @@ fn scan_may_state(repo_id: &str, cve_id: &str) -> mongodb::bson::Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// Give the alerts a scan found (which carry no VEX statement) the statement
|
||||
/// stored on `repo_id`'s alert of the same CVE, or none, so that
|
||||
/// [`CveAlert::is_resolved_by_vex`] tells whether they notify and keep an
|
||||
/// issue. Run after the alerts were stored and the scan's own statements set
|
||||
/// ([`upsert_reported`], [`apply_scan_statements`]).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// A database error.
|
||||
pub async fn attach_stored_vex(
|
||||
db: &Database,
|
||||
repo_id: &str,
|
||||
alerts: &mut [CveAlert],
|
||||
) -> Result<(), AgentError> {
|
||||
if alerts.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let ids: Vec<&str> = alerts.iter().map(|a| a.cve_id.as_str()).collect();
|
||||
let stored: Vec<CveAlert> = db
|
||||
.cve_alerts()
|
||||
.find(doc! {
|
||||
"repo_id": repo_id,
|
||||
"cve_id": { "$in": ids },
|
||||
"vex": { "$exists": true },
|
||||
})
|
||||
.await?
|
||||
.try_collect()
|
||||
.await?;
|
||||
let statements: std::collections::HashMap<String, VexAssessment> = stored
|
||||
.into_iter()
|
||||
.filter_map(|alert| Some((alert.cve_id, alert.vex?)))
|
||||
.collect();
|
||||
for alert in alerts {
|
||||
// Cloned, not taken: one CVE can be listed for two versions of a
|
||||
// package.
|
||||
alert.vex = statements.get(&alert.cve_id).cloned();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Mark resolved the stored alerts of `repo_id` a complete lookup
|
||||
/// (`complete`) no longer reports in `current`.
|
||||
///
|
||||
|
||||
@@ -242,7 +242,6 @@ async fn scan_all_repos(agent: &ComplianceAgent, tenant_id: &str) {
|
||||
}
|
||||
|
||||
async fn monitor_cves(agent: &ComplianceAgent, tenant_id: &str) {
|
||||
use compliance_core::models::notification::{parse_severity, CveNotification};
|
||||
use compliance_core::models::SbomEntry;
|
||||
use futures_util::StreamExt;
|
||||
|
||||
@@ -382,46 +381,15 @@ async fn monitor_cves(agent: &ComplianceAgent, tenant_id: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
// Create notifications for NEW CVEs (dedup against existing notifications)
|
||||
for alert in &alerts {
|
||||
let filter = doc! {
|
||||
"cve_id": &alert.cve_id,
|
||||
"repo_id": &alert.repo_id,
|
||||
"package_name": &alert.affected_package,
|
||||
"package_version": &alert.affected_version,
|
||||
};
|
||||
// Only insert if not already exists (upsert with $setOnInsert)
|
||||
let severity = parse_severity(alert.severity.as_deref(), alert.cvss_score);
|
||||
let mut notification = CveNotification::new(
|
||||
alert.cve_id.clone(),
|
||||
repo_id.clone(),
|
||||
repo_name.clone(),
|
||||
alert.affected_package.clone(),
|
||||
alert.affected_version.clone(),
|
||||
severity,
|
||||
);
|
||||
notification.cvss_score = alert.cvss_score;
|
||||
notification.summary = alert.summary.clone();
|
||||
notification.url = Some(format!("https://osv.dev/vulnerability/{}", alert.cve_id));
|
||||
|
||||
let update = doc! {
|
||||
"$setOnInsert": mongodb::bson::to_bson(¬ification).unwrap_or_default()
|
||||
};
|
||||
match db
|
||||
.cve_notifications()
|
||||
.update_one(filter, update)
|
||||
.upsert(true)
|
||||
.await
|
||||
{
|
||||
Ok(result) if result.upserted_id.is_some() => {
|
||||
new_notifications += 1;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("CVE monitor: failed to create notification: {e}");
|
||||
}
|
||||
_ => {} // Already exists
|
||||
}
|
||||
// Notifications for new CVEs, none for one a VEX statement settles.
|
||||
if let Err(e) =
|
||||
crate::pipeline::vex_lifecycle::attach_stored_vex(&db, &repo_id, &mut alerts).await
|
||||
{
|
||||
tracing::warn!("CVE monitor: failed to read the VEX statements of {repo_name}: {e}");
|
||||
continue;
|
||||
}
|
||||
new_notifications +=
|
||||
crate::pipeline::cve_notify::notify_new_cves(&db, &repo_id, &repo_name, &alerts).await;
|
||||
}
|
||||
|
||||
if new_notifications > 0 {
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
//! #498: a CVE alert's VEX status follows the scans. Gone after a complete
|
||||
//! lookup, an unassessed or affected alert is `fixed` by the scan, a
|
||||
//! person's `not_affected` stays; reported again, the scan's `fixed` is
|
||||
//! withdrawn. A stored alert gets its component's purl on a later scan.
|
||||
//! withdrawn. A stored alert gets its component's purl on a later scan. An
|
||||
//! alert `not_affected` or `fixed` raises no notification until the
|
||||
//! statement is withdrawn.
|
||||
//! Runs against a live Mongo (`TEST_MONGODB_URI`) and skips
|
||||
//! cleanly without one.
|
||||
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
use compliance_agent::database::{Database, DatabasePool};
|
||||
use compliance_agent::pipeline::cve_notify::notify_new_cves;
|
||||
use compliance_agent::pipeline::vex_lifecycle::{
|
||||
apply_scan_statements, backfill_purls, resolve_gone, upsert_reported,
|
||||
apply_scan_statements, attach_stored_vex, backfill_purls, resolve_gone, upsert_reported,
|
||||
};
|
||||
use compliance_agent::pipeline::yocto_inventory::{self, CveStatus, Patch, Recipe};
|
||||
use compliance_core::models::{
|
||||
@@ -376,3 +379,92 @@ async fn a_recipe_states_vex_each_scan_but_never_over_a_person() {
|
||||
|
||||
pool.drop_tenant(tenant).await.ok();
|
||||
}
|
||||
|
||||
/// What a scan does: store the alerts, set its own statements, then give the
|
||||
/// alerts their stored statements and notify.
|
||||
async fn scan_and_notify(
|
||||
db: &Database,
|
||||
found: &[CveAlert],
|
||||
statements: &[(String, VexAssessment)],
|
||||
) -> u32 {
|
||||
for alert in found {
|
||||
upsert_reported(db, alert).await.unwrap();
|
||||
}
|
||||
apply_scan_statements(db, TARGET, statements).await.unwrap();
|
||||
let mut found = found.to_vec();
|
||||
attach_stored_vex(db, TARGET, &mut found).await.unwrap();
|
||||
notify_new_cves(db, TARGET, "app", &found).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn not_affected_and_fixed_raise_no_notification_until_withdrawn() {
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let prefix = format!(
|
||||
"vexnotif_{}",
|
||||
&uuid::Uuid::new_v4().simple().to_string()[..10]
|
||||
);
|
||||
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
|
||||
eprintln!("SKIP vex_lifecycle: no MongoDB reachable at {uri}");
|
||||
return;
|
||||
};
|
||||
let tenant = "vex-notifications";
|
||||
let Ok(db) = pool.for_tenant_id(tenant).await else {
|
||||
eprintln!("SKIP vex_lifecycle: MongoDB at {uri} not usable");
|
||||
return;
|
||||
};
|
||||
let found: Vec<CveAlert> = ["CVE-1", "CVE-2", "CVE-3", "CVE-4", "CVE-5"]
|
||||
.into_iter()
|
||||
.map(alert)
|
||||
.collect();
|
||||
for alert in &found {
|
||||
upsert_reported(&db, alert).await.unwrap();
|
||||
}
|
||||
// A person settles CVE-2 and CVE-3 and confirms CVE-4; a recipe says
|
||||
// CVE-5 is not affected.
|
||||
for (id, status) in [
|
||||
("CVE-2", VexStatus::NotAffected),
|
||||
("CVE-3", VexStatus::Fixed),
|
||||
("CVE-4", VexStatus::Affected),
|
||||
] {
|
||||
let vex = mongodb::bson::to_bson(&by_person(status)).unwrap();
|
||||
db.cve_alerts()
|
||||
.update_one(doc! { "cve_id": id }, doc! { "$set": { "vex": vex } })
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let mut recipe_says = by_person(VexStatus::NotAffected);
|
||||
recipe_says.by_scan = true;
|
||||
let recipe = vec![("CVE-5".to_string(), recipe_says)];
|
||||
|
||||
// Only the unsettled CVEs notify, and only once.
|
||||
assert_eq!(scan_and_notify(&db, &found, &recipe).await, 2);
|
||||
assert_eq!(scan_and_notify(&db, &found, &recipe).await, 0);
|
||||
let mut notified: Vec<String> = db
|
||||
.cve_notifications()
|
||||
.distinct("cve_id", doc! {})
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.filter_map(|id| id.as_str().map(str::to_owned))
|
||||
.collect();
|
||||
notified.sort();
|
||||
assert_eq!(notified, ["CVE-1", "CVE-4"]);
|
||||
|
||||
// The person withdraws CVE-2's statement and the recipe no longer
|
||||
// assesses CVE-5: both notify now; CVE-3 stays fixed and silent.
|
||||
db.cve_alerts()
|
||||
.update_one(doc! { "cve_id": "CVE-2" }, doc! { "$unset": { "vex": "" } })
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(scan_and_notify(&db, &found, &[]).await, 2);
|
||||
assert_eq!(
|
||||
db.cve_notifications()
|
||||
.count_documents(doc! { "cve_id": "CVE-3" })
|
||||
.await
|
||||
.unwrap(),
|
||||
0
|
||||
);
|
||||
|
||||
pool.drop_tenant(tenant).await.ok();
|
||||
}
|
||||
@@ -98,6 +98,52 @@ pub struct AgentConfig {
|
||||
/// Whether a scan files the missing Gitea issues of a target's older
|
||||
/// open findings (`ISSUE_CATCHUP`, default off).
|
||||
pub issue_catchup: IssueCatchup,
|
||||
/// Whether a scan closes the open CVE issues a VEX statement settles
|
||||
/// (`ISSUE_AUTOCLOSE`, default off).
|
||||
pub issue_autoclose: IssueAutoclose,
|
||||
}
|
||||
|
||||
/// Closing open CVE issues whose CVE a VEX statement settles
|
||||
/// (`ISSUE_AUTOCLOSE`): `not_affected` or `fixed`. Opening no new issue for
|
||||
/// such a CVE does not depend on it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum IssueAutoclose {
|
||||
/// Leave the open issues open.
|
||||
#[default]
|
||||
Off,
|
||||
/// Count the issues it would close, per VEX status; change nothing.
|
||||
DryRun,
|
||||
/// Close them with a comment, a few per target and scan.
|
||||
On,
|
||||
}
|
||||
|
||||
impl IssueAutoclose {
|
||||
/// Parse `ISSUE_AUTOCLOSE`: `off`, `dry_run` or `on`, any case. Empty is
|
||||
/// [`IssueAutoclose::Off`].
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Any other value, with a message naming it (the caller falls back to
|
||||
/// off).
|
||||
pub fn parse(raw: &str) -> Result<Self, String> {
|
||||
match raw.trim().to_ascii_lowercase().as_str() {
|
||||
"" | "off" => Ok(Self::Off),
|
||||
"dry_run" => Ok(Self::DryRun),
|
||||
"on" => Ok(Self::On),
|
||||
other => Err(format!(
|
||||
"unknown ISSUE_AUTOCLOSE '{other}' (expected off, dry_run or on)"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The value as `ISSUE_AUTOCLOSE` spells it.
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Off => "off",
|
||||
Self::DryRun => "dry_run",
|
||||
Self::On => "on",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The issue catch-up (`ISSUE_CATCHUP`): after a scan's own issues, a Gitea
|
||||
@@ -321,6 +367,7 @@ impl Default for AgentConfig {
|
||||
features: Features::default(),
|
||||
app_env: AppEnv::Dev,
|
||||
issue_catchup: IssueCatchup::Off,
|
||||
issue_autoclose: IssueAutoclose::Off,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -357,6 +404,22 @@ mod app_env_tests {
|
||||
assert_eq!(IssueCatchup::DryRun.as_str(), "dry_run");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn issue_autoclose_is_off_unless_named() {
|
||||
use super::IssueAutoclose;
|
||||
assert_eq!(IssueAutoclose::parse("").unwrap(), IssueAutoclose::Off);
|
||||
assert_eq!(IssueAutoclose::parse("OFF").unwrap(), IssueAutoclose::Off);
|
||||
assert_eq!(
|
||||
IssueAutoclose::parse(" dry_run ").unwrap(),
|
||||
IssueAutoclose::DryRun
|
||||
);
|
||||
assert_eq!(IssueAutoclose::parse("on").unwrap(), IssueAutoclose::On);
|
||||
assert!(IssueAutoclose::parse("true").is_err());
|
||||
assert!(IssueAutoclose::parse("dry-run").is_err());
|
||||
assert_eq!(AgentConfig::default().issue_autoclose, IssueAutoclose::Off);
|
||||
assert_eq!(IssueAutoclose::DryRun.as_str(), "dry_run");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dev_needs_nothing() {
|
||||
assert!(AgentConfig::default().validate_deployment().is_ok());
|
||||
|
||||
@@ -203,6 +203,15 @@ impl CveAlert {
|
||||
ids
|
||||
}
|
||||
|
||||
/// Whether a VEX statement settles the alert: `not_affected` or `fixed`,
|
||||
/// stated by a person, by the scan or in an imported VEX document. Such an
|
||||
/// alert raises no notification and keeps no open tracker issue; once the
|
||||
/// statement is withdrawn (back to `affected`, `under_investigation` or
|
||||
/// none) it counts again.
|
||||
pub fn is_resolved_by_vex(&self) -> bool {
|
||||
self.vex.as_ref().is_some_and(|vex| vex.status.resolves())
|
||||
}
|
||||
|
||||
pub fn new(
|
||||
cve_id: String,
|
||||
repo_id: String,
|
||||
@@ -251,6 +260,31 @@ mod tests {
|
||||
a
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_not_affected_and_fixed_resolve_an_alert() {
|
||||
use crate::models::vex::{VexAssessment, VexStatus};
|
||||
let mut a = alert("CVE-2021-44228", &[]);
|
||||
assert!(!a.is_resolved_by_vex());
|
||||
for (status, resolved) in [
|
||||
(VexStatus::UnderInvestigation, false),
|
||||
(VexStatus::Affected, false),
|
||||
(VexStatus::NotAffected, true),
|
||||
(VexStatus::Fixed, true),
|
||||
] {
|
||||
a.vex = Some(VexAssessment {
|
||||
status,
|
||||
justification: None,
|
||||
impact_statement: None,
|
||||
action_statement: None,
|
||||
by: "u1".into(),
|
||||
by_name: None,
|
||||
at: Utc::now(),
|
||||
by_scan: false,
|
||||
});
|
||||
assert_eq!(a.is_resolved_by_vex(), resolved, "{status:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cve_is_strictly_recognised() {
|
||||
assert!(is_cve("CVE-2021-44228"));
|
||||
|
||||
@@ -24,6 +24,27 @@ pub enum VexStatus {
|
||||
Fixed,
|
||||
}
|
||||
|
||||
impl VexStatus {
|
||||
/// Whether the status settles the vulnerability for the product:
|
||||
/// `not_affected` or `fixed`.
|
||||
pub fn resolves(self) -> bool {
|
||||
match self {
|
||||
Self::NotAffected | Self::Fixed => true,
|
||||
Self::UnderInvestigation | Self::Affected => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The status as OpenVEX names it (`not_affected`).
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::UnderInvestigation => "under_investigation",
|
||||
Self::Affected => "affected",
|
||||
Self::NotAffected => "not_affected",
|
||||
Self::Fixed => "fixed",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the product is not affected (OpenVEX's five justifications).
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
@@ -35,6 +56,21 @@ pub enum VexJustification {
|
||||
InlineMitigationsAlreadyExist,
|
||||
}
|
||||
|
||||
impl VexJustification {
|
||||
/// The justification as OpenVEX names it (`vulnerable_code_not_present`).
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::ComponentNotPresent => "component_not_present",
|
||||
Self::VulnerableCodeNotPresent => "vulnerable_code_not_present",
|
||||
Self::VulnerableCodeNotInExecutePath => "vulnerable_code_not_in_execute_path",
|
||||
Self::VulnerableCodeCannotBeControlledByAdversary => {
|
||||
"vulnerable_code_cannot_be_controlled_by_adversary"
|
||||
}
|
||||
Self::InlineMitigationsAlreadyExist => "inline_mitigations_already_exist",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One VEX statement on an alert: the status, its reasons, and who made it.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct VexAssessment {
|
||||
@@ -133,4 +169,30 @@ mod tests {
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_names_are_openvex_s() {
|
||||
use VexJustification as J;
|
||||
use VexStatus as S;
|
||||
for status in [S::UnderInvestigation, S::Affected, S::NotAffected, S::Fixed] {
|
||||
assert_eq!(
|
||||
serde_json::to_value(status).ok(),
|
||||
Some(serde_json::json!(status.as_str()))
|
||||
);
|
||||
}
|
||||
for justification in [
|
||||
J::ComponentNotPresent,
|
||||
J::VulnerableCodeNotPresent,
|
||||
J::VulnerableCodeNotInExecutePath,
|
||||
J::VulnerableCodeCannotBeControlledByAdversary,
|
||||
J::InlineMitigationsAlreadyExist,
|
||||
] {
|
||||
assert_eq!(
|
||||
serde_json::to_value(justification).ok(),
|
||||
Some(serde_json::json!(justification.as_str()))
|
||||
);
|
||||
}
|
||||
assert!(S::NotAffected.resolves() && S::Fixed.resolves());
|
||||
assert!(!S::Affected.resolves() && !S::UnderInvestigation.resolves());
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ A scan opens issues only for the findings it finds new, so a finding whose issue
|
||||
|
||||
### CVE issues (managed repositories)
|
||||
|
||||
For a repository from a managed git source, known vulnerabilities in its dependencies become issues too: one per package and CVE, labelled `cve`. A critical or high CVE opens one, and so does any CVE in CISA's Known Exploited Vulnerabilities catalog (rated at least high). A CVE whose EPSS percentile reaches `CVE_ISSUE_EPSS_PERCENTILE` (default `0.95`) is rated one step higher, so a medium one opens an issue as high. The issue names the KEV entry, the EPSS score with its attribution, and CISA's SSVC exploitation where known. When a complete scan no longer finds the CVE, the issue is closed; when it comes back, it is reopened.
|
||||
For a repository from a managed git source, known vulnerabilities in its dependencies become issues too: one per package and CVE, labelled `cve`. A critical or high CVE opens one, and so does any CVE in CISA's Known Exploited Vulnerabilities catalog (rated at least high). A CVE whose EPSS percentile reaches `CVE_ISSUE_EPSS_PERCENTILE` (default `0.95`) is rated one step higher, so a medium one opens an issue as high. The issue names the KEV entry, the EPSS score with its attribution, and CISA's SSVC exploitation where known. When a complete scan no longer finds the CVE, the issue is closed; when it comes back, it is reopened. A CVE with the VEX status `not_affected` or `fixed` gets no new issue. Its issue that is already open is closed only with `ISSUE_AUTOCLOSE=on`: with a comment naming the status and the justification, at most 20 per target and scan (the rest follow in the next scans). `ISSUE_AUTOCLOSE=dry_run` only logs, per target, how many issues it would close per VEX status, and changes nothing; the default is `off`. When the statement is withdrawn, a closed issue is reopened.
|
||||
|
||||
## Issues List
|
||||
|
||||
|
||||
@@ -48,6 +48,13 @@ removed or updated), it is marked fixed and "Stated by" shows **Scan**. A
|
||||
"Not affected" or "Fixed" stated by a person is never changed by a scan. If
|
||||
the vulnerability comes back, the scan withdraws its "Fixed".
|
||||
|
||||
A vulnerability that is "Not affected" or "Fixed" (stated by a person, by the
|
||||
scan or in an imported VEX document) raises no notification and gets no issue
|
||||
in the repository's tracker; with `ISSUE_AUTOCLOSE=on` an open issue for
|
||||
it is closed with a comment naming the status and the reason. If the statement is withdrawn, it notifies
|
||||
and its issue is reopened as before. Notifications raised before the
|
||||
statement stay in the list until they are dismissed.
|
||||
|
||||
## Downloading
|
||||
|
||||
**Download OpenVEX** and **Download CycloneDX VEX** save the target's
|
||||
|
||||
@@ -50,6 +50,14 @@ zeigt dann **Prüfung**. Eine Aussage „Nicht betroffen“ oder „Behoben“,
|
||||
eine Person gemacht hat, ändert die Prüfung nie. Taucht die Schwachstelle
|
||||
wieder auf, nimmt die Prüfung ihr „Behoben“ zurück.
|
||||
|
||||
Eine Schwachstelle mit „Nicht betroffen“ oder „Behoben“ (von einer Person,
|
||||
der Prüfung oder aus einem importierten VEX-Dokument) löst keine
|
||||
Benachrichtigung aus und bekommt kein Issue im Tracker des Repositorys; mit
|
||||
`ISSUE_AUTOCLOSE=on` wird ein offenes Issue dazu mit einem Kommentar
|
||||
geschlossen, der Status und Begründung nennt. Wird die Aussage zurückgenommen, benachrichtigt sie wieder
|
||||
und ihr Issue wird wieder geöffnet. Benachrichtigungen von vor der Aussage
|
||||
bleiben in der Liste, bis sie verworfen werden.
|
||||
|
||||
## Herunterladen
|
||||
|
||||
**OpenVEX herunterladen** und **CycloneDX VEX herunterladen** speichern die
|
||||
|
||||
Reference in new issue
Block a user