feat(cve): closing CVE issues settled by VEX behind ISSUE_AUTOCLOSE (off by default)

No new notification or issue for a not_affected/fixed CVE stays always on.
Closing an issue that is already open now depends on ISSUE_AUTOCLOSE
(off | dry_run | on, unknown -> off with a warning), like ISSUE_CATCHUP:
dry_run logs one line per target with the counts per VEX status and makes
no tracker call; on closes at most 20 per target and scan (every Gitea
request waits for its instance's slot) and logs closed/deferred/failed.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
This commit is contained in:
Sharang ParnerkarandClaude Opus 5.5 committed 2026-10-09 18:53:52 +02:00
1 parent f15d1e5066
commit f552a6a72a
8 files changed
+347 -53

No files matched your search

+4
View File
@@ -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
+12 -1
View File
@@ -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
})
}
+260 -46
View File
@@ -8,8 +8,10 @@
//! 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, and its open issue is
//! closed with a comment naming the status and the reason. When the statement
//! 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
@@ -21,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, VexAssessment};
use compliance_core::models::{CveAlert, IssueStatus, TrackerIssue, VexAssessment, VexStatus};
use crate::database::Database;
use crate::error::AgentError;
@@ -35,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,
@@ -45,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.
@@ -198,18 +206,15 @@ pub(crate) async fn sync_cve_issues(
}
// A VEX statement settles the CVE whether or not the scan was complete.
for (key, alert) in present.iter().filter(|(_, a)| a.is_resolved_by_vex()) {
let (Some(vex), Some(issue)) = (alert.vex.as_ref(), existing.get(key)) else {
continue;
};
if is_closed(&issue.status) {
continue;
}
if set_state(target, issue, &vex_comment(vex), "closed").await {
record(target.db, issue, IssueStatus::Closed).await?;
counts.closed += 1;
}
}
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 {
@@ -226,6 +231,72 @@ 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`]). Logs one line
/// per target with counts only.
///
/// # Returns
///
/// How many issues were closed.
///
/// # Errors
///
/// A database error.
async fn autoclose(
target: &CveIssueTarget<'_>,
settled: &[(&TrackerIssue, &VexAssessment)],
) -> Result<u32, AgentError> {
if settled.is_empty() {
return Ok(0);
}
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 {
@@ -457,22 +528,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>,
@@ -529,6 +600,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 {
@@ -634,12 +726,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");
@@ -731,8 +825,9 @@ mod tests {
assert!(vex_comment(&vex(VexStatus::Fixed)).contains("VEX status `fixed`. Closed"));
}
#[tokio::test]
async fn a_vex_not_affected_or_fixed_closes_the_issue_until_it_is_withdrawn() {
/// 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!(
@@ -741,23 +836,51 @@ mod tests {
);
let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP cve_issues: no MongoDB reachable at {uri}");
return;
return None;
};
let db = pool.for_tenant_id("cve-issues-vex").await.unwrap();
let calls: Calls = Arc::default();
let base = fake_gitea(calls.clone()).await;
let gitea =
GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap();
let tracker = TrackerDispatch::Gitea(gitea);
let target = CveIssueTarget {
db: &db,
tracker: &tracker,
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()];
@@ -782,10 +905,7 @@ mod tests {
let both = [okhttp.clone(), settled.clone()];
assert_eq!(
sync_cve_issues(&target, &both, false).await.unwrap(),
CveIssueCounts {
closed: 1,
..Default::default()
}
closed(1)
);
{
let calls = calls.lock().unwrap();
@@ -822,4 +942,98 @@ mod tests {
pool.drop_tenant("cve-issues-vex").await.ok();
}
#[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 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);
// Dry run, against a Gitea that refuses every write: only counted.
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());
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();
}
}
@@ -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?;
+63
View File
@@ -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());
+1 -1
View File
@@ -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. A CVE with the VEX status `not_affected` or `fixed` gets no issue, and its open issue is closed with a comment naming the status and the justification; when the statement is withdrawn, the issue 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
+2 -2
View File
@@ -50,8 +50,8 @@ 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; an open issue for it is closed with a comment
naming the status and the reason. If the statement is withdrawn, it notifies
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.
+3 -3
View File
@@ -52,9 +52,9 @@ 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; ein
offenes Issue dazu wird mit einem Kommentar geschlossen, der Status und
Begründung nennt. Wird die Aussage zurückgenommen, benachrichtigt sie wieder
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.