From e382746cfb7331b55cd711fc9f44b369bbe6726d Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Fri, 9 Oct 2026 16:08:23 +0000 Subject: [PATCH] feat(issues): a catch-up files Gitea issues for open findings that never got one (off by default) (#553) --- .env.example | 4 + compliance-agent/src/config.rs | 11 +- .../src/pipeline/issue_catchup.rs | 563 ++++++++++++++++++ .../src/pipeline/issue_creation.rs | 412 ++++++++----- compliance-agent/src/pipeline/mod.rs | 1 + compliance-agent/src/trackers/gitea.rs | 3 + compliance-core/src/config.rs | 63 ++ docs/guide/issues.md | 4 + 8 files changed, 912 insertions(+), 149 deletions(-) create mode 100644 compliance-agent/src/pipeline/issue_catchup.rs diff --git a/.env.example b/.env.example index 8c31667..b5ec417 100644 --- a/.env.example +++ b/.env.example @@ -50,6 +50,10 @@ CVE_MONITOR_SCHEDULE=0 0 0 * * * # FINDING_GROUP_THRESHOLD=5 # FINDING_GROUP_SCANNERS=mobsfscan=5,gitleaks=off # FINDING_GROUP_SEVERITIES=low,info +# Issue catch-up (Gitea only): after a scan's own issues, open medium+ findings +# 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 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 diff --git a/compliance-agent/src/config.rs b/compliance-agent/src/config.rs index 98ba561..cb6aaf8 100644 --- a/compliance-agent/src/config.rs +++ b/compliance-agent/src/config.rs @@ -1,4 +1,4 @@ -use compliance_core::config::{AppEnv, BreakpilotConfig, Features, PlcRuntimeConfig}; +use compliance_core::config::{AppEnv, BreakpilotConfig, Features, IssueCatchup, PlcRuntimeConfig}; use compliance_core::AgentConfig; use secrecy::SecretString; @@ -127,6 +127,15 @@ fn build_config(app_env: AppEnv) -> Result { }, features: Features::parse(&env_var_opt("PW_FEATURES").unwrap_or_default()), app_env, + issue_catchup: load_issue_catchup(), + }) +} + +/// `ISSUE_CATCHUP`; an unknown value is logged and leaves the catch-up off. +fn load_issue_catchup() -> IssueCatchup { + IssueCatchup::parse(&env_var_opt("ISSUE_CATCHUP").unwrap_or_default()).unwrap_or_else(|e| { + tracing::warn!("{e}; the issue catch-up stays off"); + IssueCatchup::Off }) } diff --git a/compliance-agent/src/pipeline/issue_catchup.rs b/compliance-agent/src/pipeline/issue_catchup.rs new file mode 100644 index 0000000..156b944 --- /dev/null +++ b/compliance-agent/src/pipeline/issue_catchup.rs @@ -0,0 +1,563 @@ +//! The issue catch-up (`ISSUE_CATCHUP`). +//! +//! A scan opens issues only for the findings it stores new, so a finding +//! whose issue could not be opened (a failed listing, a refused create) +//! never got one later. After a scan's own issues, the catch-up goes through +//! the target's open medium+ findings without an issue: one that has an issue +//! already (by fingerprint marker, then title, as in +//! [`super::issue_creation`]) is linked to it, the others get a new one, at +//! most [`MAX_NEW_ISSUES`] per scan, highest severity and oldest first. The +//! rest wait for the next scans. Gitea only: it matches against the listing +//! the scan made anyway; the other trackers would need a search per finding. + +use std::collections::{BTreeMap, HashSet}; + +use compliance_core::config::IssueCatchup; +use compliance_core::models::{Finding, Severity}; +use futures_util::TryStreamExt; +use mongodb::bson::doc; + +use super::issue_creation::{ + issue_title, wants_issue, ExistingIssues, IssueSink, KnownIssue, ISSUE_SEVERITIES, + ISSUE_STATUSES, +}; +use crate::error::AgentError; + +/// New issues the catch-up opens per target and scan; links are not counted. +pub(super) const MAX_NEW_ISSUES: usize = 20; + +/// A count per severity, highest first when shown. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub(super) struct SeverityCounts(BTreeMap); + +impl SeverityCounts { + /// Count one finding of `severity`. + fn add(&mut self, severity: &Severity) { + *self.0.entry(severity.clone()).or_default() += 1; + } + + /// All counted. + pub(super) fn total(&self) -> u32 { + self.0.values().sum() + } +} + +impl std::fmt::Display for SeverityCounts { + /// `critical=1 high=3`, or `-` when nothing was counted. + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + if self.0.is_empty() { + return f.write_str("-"); + } + let parts: Vec = self + .0 + .iter() + .rev() + .map(|(severity, n)| format!("{severity}={n}")) + .collect(); + f.write_str(&parts.join(" ")) + } +} + +/// What a catch-up does, decided before any request. +#[derive(Debug, Default)] +struct CatchupPlan<'a> { + /// Findings whose issue exists, with it. + link: Vec<(&'a Finding, &'a KnownIssue)>, + /// Findings that get a new issue, at most the cap. + create: Vec<&'a Finding>, + /// Findings past the cap: their issues wait for the next scans. + deferred: SeverityCounts, +} + +/// What a catch-up did on one target (in a dry run: would do). +#[derive(Debug, Default, PartialEq, Eq)] +pub(super) struct CatchupSummary { + pub(super) mode: IssueCatchup, + pub(super) created: SeverityCounts, + pub(super) linked: SeverityCounts, + pub(super) deferred: SeverityCounts, + /// Issues the tracker refused. + pub(super) failed: u32, +} + +impl CatchupSummary { + /// Log the one line per target: counts and severities, never a title or + /// a path. + pub(super) fn log(&self, tenant_id: &str, target_id: &str) { + let what = match self.mode { + IssueCatchup::DryRun => "issue catch-up (dry run, nothing changed)", + IssueCatchup::Off | IssueCatchup::On => "issue catch-up", + }; + tracing::info!( + tenant_id, + target_id, + mode = self.mode.as_str(), + created = self.created.total(), + created_severities = %self.created, + linked = self.linked.total(), + linked_severities = %self.linked, + deferred = self.deferred.total(), + deferred_severities = %self.deferred, + failed = self.failed, + "{what}" + ); + } +} + +/// Run the catch-up for the target of `sink` against `index`, the listing +/// of its repository's issues (with the scan's new issues added). +/// +/// # Errors +/// +/// The target's findings cannot be read. +pub(super) async fn catch_up( + sink: &IssueSink<'_>, + index: &ExistingIssues, + mode: IssueCatchup, +) -> Result { + let candidates = select(load_candidates(sink).await?); + Ok(run(sink, &candidates, index, mode).await) +} + +/// The target's open medium+ findings without an issue, as stored. +async fn load_candidates(sink: &IssueSink<'_>) -> Result, AgentError> { + let severities: Vec = ISSUE_SEVERITIES.iter().map(Severity::to_string).collect(); + let statuses: Vec = ISSUE_STATUSES.iter().map(ToString::to_string).collect(); + // `tracker_issue_url: null` matches a missing field too. + let findings = sink + .db + .findings() + .find(doc! { + "repo_id": sink.repo_id, + "tracker_issue_url": null, + "severity": { "$in": severities }, + "status": { "$in": statuses }, + }) + .await? + .try_collect() + .await?; + Ok(findings) +} + +/// The findings that want an issue and have none, highest severity first, +/// then oldest first. +fn select(findings: Vec) -> Vec { + let mut candidates: Vec = findings + .into_iter() + .filter(|f| wants_issue(f) && f.tracker_issue_url.is_none()) + .collect(); + candidates.sort_by(|a, b| { + b.severity + .cmp(&a.severity) + .then(a.created_at.cmp(&b.created_at)) + }); + candidates +} + +/// Decide for each of `candidates` (in order): link it to its issue in +/// `index`, give it a new one while fewer than `cap` are planned, or defer +/// it. A single finding with the title of an issue planned here is left for +/// the next scan, which links it to that issue (as the scan's own issue +/// creation never opens two issues of one title). +fn plan<'a>(candidates: &'a [Finding], index: &'a ExistingIssues, cap: usize) -> CatchupPlan<'a> { + let mut plan = CatchupPlan::default(); + let mut planned_titles = HashSet::new(); + for finding in candidates { + let title = issue_title(finding); + if let Some(known) = index.find(finding, &title) { + plan.link.push((finding, known)); + } else if finding.occurrences.is_empty() && planned_titles.contains(&title) { + continue; + } else if plan.create.len() < cap { + planned_titles.insert(title); + plan.create.push(finding); + } else { + plan.deferred.add(&finding.severity); + } + } + plan +} + +/// Plan the catch-up of `candidates` and, when `mode` is on, carry it out. +async fn run( + sink: &IssueSink<'_>, + candidates: &[Finding], + index: &ExistingIssues, + mode: IssueCatchup, +) -> CatchupSummary { + let plan = plan(candidates, index, MAX_NEW_ISSUES); + let mut summary = CatchupSummary { + mode, + deferred: plan.deferred, + ..CatchupSummary::default() + }; + match mode { + IssueCatchup::Off => {} + IssueCatchup::DryRun => { + plan.link + .iter() + .for_each(|(f, _)| summary.linked.add(&f.severity)); + plan.create + .iter() + .for_each(|f| summary.created.add(&f.severity)); + } + IssueCatchup::On => { + for (finding, known) in plan.link { + sink.link(finding, &issue_title(finding), known).await; + summary.linked.add(&finding.severity); + } + for finding in plan.create { + match sink.open(finding, &issue_title(finding)).await { + Ok(_) => summary.created.add(&finding.severity), + Err(e) => { + summary.failed += 1; + tracing::warn!( + "[{}] Catch-up issue for {} not created: {e}", + sink.repo_id, + finding.fingerprint + ); + } + } + } + } + } + summary +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use std::sync::{Arc, Mutex}; + + use axum::extract::State; + use axum::routing::get; + use axum::{Json, Router}; + use chrono::{Duration, Utc}; + use compliance_core::models::{FindingStatus, ScanType, TrackerIssue}; + use compliance_core::NetGuard; + use secrecy::SecretString; + + use super::*; + use crate::database::Database; + use crate::pipeline::issue_creation::format_issue_body; + use crate::pipeline::tracker_dispatch::TrackerDispatch; + use crate::trackers::gitea::{GiteaIssue, GiteaTracker}; + + /// A finding of `severity`, `age_days` old. + fn finding(fingerprint: &str, severity: Severity, age_days: i64) -> Finding { + let mut f = Finding::new( + "target-1".into(), + fingerprint.into(), + "semgrep".into(), + ScanType::Sast, + format!("rule {fingerprint}"), + "desc".into(), + severity, + ); + f.created_at = Utc::now() - Duration::days(age_days); + f + } + + fn fingerprints(findings: &[&Finding]) -> Vec { + findings.iter().map(|f| f.fingerprint.clone()).collect() + } + + /// A listed issue whose body carries `finding`'s fingerprint marker. + fn issue_of(number: i64, finding: &Finding) -> GiteaIssue { + GiteaIssue { + number, + title: "renamed since".into(), + body: Some(format_issue_body(finding)), + html_url: format!("https://gitea.invalid/o/r/issues/{number}"), + state: "open".into(), + } + } + + #[test] + fn only_undecided_medium_and_above_without_an_issue_are_caught_up() { + let mut linked = finding("linked", Severity::High, 1); + linked.tracker_issue_url = Some("https://gitea.invalid/o/r/issues/1".into()); + let mut decided = finding("decided", Severity::Critical, 1); + decided.status = FindingStatus::AcceptedRisk; + let mut triaged = finding("triaged", Severity::Medium, 1); + triaged.status = FindingStatus::Triaged; + let selected = select(vec![ + finding("low", Severity::Low, 1), + finding("info", Severity::Info, 1), + linked, + decided, + triaged, + finding("open", Severity::High, 1), + ]); + let names: Vec<&str> = selected.iter().map(|f| f.fingerprint.as_str()).collect(); + assert_eq!(names, ["open", "triaged"]); + } + + #[test] + fn highest_severity_first_then_oldest() { + let selected = select(vec![ + finding("medium-old", Severity::Medium, 30), + finding("high-new", Severity::High, 1), + finding("critical-new", Severity::Critical, 1), + finding("high-old", Severity::High, 10), + finding("critical-old", Severity::Critical, 5), + ]); + let names: Vec<&str> = selected.iter().map(|f| f.fingerprint.as_str()).collect(); + assert_eq!( + names, + [ + "critical-old", + "critical-new", + "high-old", + "high-new", + "medium-old" + ] + ); + } + + #[test] + fn at_most_twenty_new_issues_and_the_rest_are_deferred() { + let mut all: Vec = (0..22) + .map(|i| finding(&format!("high-{i}"), Severity::High, 100 - i)) + .collect(); + all.extend((0..3).map(|i| finding(&format!("medium-{i}"), Severity::Medium, 1))); + let candidates = select(all); + let index = ExistingIssues::default(); + + let plan = plan(&candidates, &index, MAX_NEW_ISSUES); + + assert_eq!(plan.create.len(), 20); + assert!(plan.link.is_empty()); + // The oldest highs first; two highs and the mediums wait. + assert_eq!(plan.create[0].fingerprint, "high-0"); + assert_eq!(plan.create[19].fingerprint, "high-19"); + assert_eq!(plan.deferred.total(), 5); + assert_eq!(plan.deferred.to_string(), "high=2 medium=3"); + } + + #[test] + fn a_finding_with_an_issue_is_linked_and_not_counted() { + let candidates = select( + (0..21) + .map(|i| finding(&format!("fp-{i}"), Severity::High, 50 - i)) + .collect(), + ); + // fp-0 has its issue (found by its marker, under another title). + let index = ExistingIssues::new(&[issue_of(7, &candidates[0])]); + + let plan = plan(&candidates, &index, MAX_NEW_ISSUES); + + assert_eq!(plan.link.len(), 1); + assert_eq!(plan.link[0].0.fingerprint, "fp-0"); + assert_eq!(plan.link[0].1.url, "https://gitea.invalid/o/r/issues/7"); + assert_eq!(plan.create.len(), 20, "the link does not use the cap"); + assert!(!fingerprints(&plan.create).contains(&"fp-0".to_string())); + assert_eq!(plan.deferred.total(), 0); + } + + #[test] + fn one_new_issue_per_title() { + let first = finding("fp-a", Severity::High, 2); + let mut second = finding("fp-b", Severity::High, 1); + second.title = first.title.clone(); + let candidates = select(vec![first, second]); + let index = ExistingIssues::default(); + let plan = plan(&candidates, &index, MAX_NEW_ISSUES); + assert_eq!(fingerprints(&plan.create), ["fp-a"]); + assert_eq!(plan.deferred.total(), 0); + } + + /// Requests a fake Gitea saw, as `METHOD path`. + type Seen = Arc>>; + + /// A fake Gitea whose repository has `issues`; a created issue gets + /// number 100 and up. + async fn fake_gitea(issues: Vec, seen: Seen) -> String { + async fn list( + State((issues, seen)): State<(Arc>, Seen)>, + axum::extract::Query(params): axum::extract::Query< + std::collections::HashMap, + >, + ) -> Json { + seen.lock().unwrap().push("GET issues".into()); + if params.get("page").map(String::as_str) != Some("1") { + return Json(serde_json::json!([])); + } + Json(serde_json::json!(*issues)) + } + async fn create( + State((_, seen)): State<(Arc>, Seen)>, + ) -> (axum::http::StatusCode, Json) { + let mut seen = seen.lock().unwrap(); + seen.push("POST issues".into()); + let number = 99 + seen.iter().filter(|s| s.starts_with("POST")).count(); + ( + axum::http::StatusCode::CREATED, + Json(serde_json::json!({ + "number": number, + "html_url": format!("https://gitea.invalid/o/r/issues/{number}"), + })), + ) + } + let issues: Vec = issues + .iter() + .map(|i| { + serde_json::json!({ + "number": i.number, + "title": i.title, + "body": i.body, + "html_url": i.html_url, + "state": i.state, + }) + }) + .collect(); + let app = Router::new() + .route("/api/v1/repos/{o}/{r}/issues", get(list).post(create)) + .with_state((Arc::new(issues), seen)); + 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 sink<'a>(db: &'a Database, tracker: &'a TrackerDispatch, repo_id: &'a str) -> IssueSink<'a> { + IssueSink { + db, + tracker, + owner: "kunde", + repo: "fw", + repo_id, + managed: false, + dashboard: String::new(), + labels: tokio::sync::OnceCell::new(), + } + } + + fn posts(seen: &Seen) -> usize { + seen.lock() + .unwrap() + .iter() + .filter(|s| s.starts_with("POST")) + .count() + } + + #[tokio::test] + async fn a_dry_run_counts_but_creates_and_links_nothing() { + let seen: Seen = Arc::default(); + let with_issue = finding("fp-old", Severity::High, 9); + let index = ExistingIssues::new(&[issue_of(7, &with_issue)]); + let base = fake_gitea(Vec::new(), seen.clone()).await; + let tracker = TrackerDispatch::Gitea( + GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap(), + ); + // Never reached: a dry run writes nothing (the client connects lazily). + let client = + mongodb::Client::with_uri_str("mongodb://127.0.0.1:1/?serverSelectionTimeoutMS=100") + .await + .unwrap(); + let db = Database::from_database(client.database("unused")); + let sink = sink(&db, &tracker, "target-1"); + let candidates = select(vec![ + with_issue, + finding("fp-new", Severity::Critical, 1), + finding("fp-medium", Severity::Medium, 1), + ]); + + let summary = run(&sink, &candidates, &index, IssueCatchup::DryRun).await; + + assert_eq!(summary.created.to_string(), "critical=1 medium=1"); + assert_eq!(summary.linked.to_string(), "high=1"); + assert_eq!(summary.deferred.total(), 0); + assert!(seen.lock().unwrap().is_empty(), "no request to Gitea"); + } + + #[tokio::test] + async fn on_links_by_marker_and_opens_the_others() { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let prefix = format!( + "catchup_{}", + &uuid::Uuid::new_v4().simple().to_string()[..10] + ); + let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else { + eprintln!("SKIP issue_catchup: no MongoDB reachable at {uri}"); + return; + }; + let db = pool.for_tenant_id("issue-catchup").await.unwrap(); + + // Arrange: one finding whose issue exists (#7, matched by its + // marker), one without, one already linked, and a low one. + let old = finding("fp-old", Severity::High, 9); + let fresh = finding("fp-new", Severity::Critical, 1); + let mut linked = finding("fp-linked", Severity::High, 3); + linked.tracker_issue_url = Some("https://gitea.invalid/o/r/issues/2".into()); + let low = finding("fp-low", Severity::Low, 3); + let seen: Seen = Arc::default(); + let base = fake_gitea(vec![issue_of(7, &old)], seen.clone()).await; + let gitea = + GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap(); + db.findings() + .insert_many([&old, &fresh, &linked, &low]) + .await + .unwrap(); + let index = ExistingIssues::new(&gitea.list_issues("kunde", "fw").await.unwrap()); + let tracker = TrackerDispatch::Gitea(gitea); + let sink = sink(&db, &tracker, "target-1"); + let url_of = |fp: &'static str| { + let db = db.clone(); + async move { + db.findings() + .find_one(doc! { "fingerprint": fp }) + .await + .unwrap() + .unwrap() + .tracker_issue_url + } + }; + + // A dry run changes nothing. + let dry = catch_up(&sink, &index, IssueCatchup::DryRun).await.unwrap(); + assert_eq!((dry.created.total(), dry.linked.total()), (1, 1)); + assert_eq!(posts(&seen), 0); + assert_eq!(url_of("fp-old").await, None); + + // On: the old finding is linked to #7 without a request, the new + // one gets an issue, the others are left alone. + let done = catch_up(&sink, &index, IssueCatchup::On).await.unwrap(); + + assert_eq!(done.linked.to_string(), "high=1"); + assert_eq!(done.created.to_string(), "critical=1"); + assert_eq!(done.failed, 0); + assert_eq!(posts(&seen), 1, "one create, for the new finding only"); + assert_eq!( + url_of("fp-old").await.as_deref(), + Some("https://gitea.invalid/o/r/issues/7") + ); + assert_eq!( + url_of("fp-new").await.as_deref(), + Some("https://gitea.invalid/o/r/issues/100") + ); + assert_eq!(url_of("fp-low").await, None); + let old_id = db + .findings() + .find_one(doc! { "fingerprint": "fp-old" }) + .await + .unwrap() + .unwrap() + .id + .unwrap(); + let record: TrackerIssue = db + .tracker_issues() + .find_one(doc! { "finding_id": old_id.to_hex() }) + .await + .unwrap() + .expect("the link is recorded for the status sync"); + assert_eq!(record.external_id, "7"); + + // The next scan finds nothing left to do. + let again = catch_up(&sink, &index, IssueCatchup::On).await.unwrap(); + assert_eq!((again.created.total(), again.linked.total()), (0, 0)); + assert_eq!(posts(&seen), 1); + pool.drop_tenant("issue-catchup").await.ok(); + } +} diff --git a/compliance-agent/src/pipeline/issue_creation.rs b/compliance-agent/src/pipeline/issue_creation.rs index 12faddb..a535579 100644 --- a/compliance-agent/src/pipeline/issue_creation.rs +++ b/compliance-agent/src/pipeline/issue_creation.rs @@ -2,8 +2,11 @@ use std::collections::HashMap; use mongodb::bson::doc; +use crate::database::Database; use crate::pipeline::repo_view::RepoView; use crate::trackers::gitea::GiteaIssue; +use compliance_core::config::IssueCatchup; +use compliance_core::error::CoreError; use compliance_core::models::*; use super::orchestrator::{extract_base_url, PipelineOrchestrator}; @@ -63,7 +66,8 @@ impl PipelineOrchestrator { /// Create tracker issues for new findings (severity >= Medium). /// Skips a finding whose issue exists (by fingerprint, then title): on /// Gitea matched against one listing of the repository's issues, on other - /// trackers by a search per finding. + /// trackers by a search per finding. On Gitea the issue catch-up + /// ([`crate::pipeline::issue_catchup`]) follows, on the same listing. #[tracing::instrument(skip_all, fields(repo_id = %repo_id))] pub(super) async fn create_tracker_issues( &self, @@ -94,36 +98,22 @@ impl PipelineOrchestrator { } }; - // Only create issues for medium+ severity findings nobody has decided - // about (a group can take over its places' decision, #483). - let actionable: Vec<&Finding> = new_findings - .iter() - .filter(|f| { - matches!( - f.severity, - Severity::Medium | Severity::High | Severity::Critical - ) && matches!( - f.status, - FindingStatus::Open | FindingStatus::Triaged | FindingStatus::NeedsReview - ) - }) - .collect(); + let actionable: Vec<&Finding> = new_findings.iter().filter(|f| wants_issue(f)).collect(); + // Only Gitea has the listing the catch-up matches against. + let catchup = match &tracker { + TrackerDispatch::Gitea(_) => self.config.issue_catchup, + _ => IssueCatchup::Off, + }; - if actionable.is_empty() { + if actionable.is_empty() && catchup == IssueCatchup::Off { tracing::info!("[{repo_id}] No medium+ findings, skipping issue creation"); return Ok(()); } - tracing::info!( - "[{repo_id}] Creating issues for {} findings via {}", - actionable.len(), - tracker.name() - ); - // A Gitea lists its issues once and the findings are matched here, not // searched one by one (a burst of searches took a small instance - // down). A listing that fails stops the sync for this repository; - // the next scan tries again. + // down). A listing that fails stops the sync for this repository, + // the catch-up included; the next scan tries again. let mut existing = match &tracker { TrackerDispatch::Gitea(gitea) => { let issues = gitea.list_issues(owner, tracker_repo_name).await?; @@ -132,35 +122,31 @@ impl PipelineOrchestrator { _ => None, }; - // A managed repository (#439) gets its labels created once per run - // and attached by id. If that fails (no permission), the issues are - // still opened, with the label names in the body as before. - let managed_labels = match (&tracker, repo.managed) { - (TrackerDispatch::Gitea(gitea), true) => match gitea - .ensure_labels( - owner, - tracker_repo_name, - &trackers::gitea::pruefwerk_labels(), - ) - .await - { - Ok(ids) => Some(ids), - Err(e) => { - tracing::warn!("[{repo_id}] Could not ensure the Prüfwerk labels: {e}"); - None - } - }, - _ => None, + let sink = IssueSink { + db: &self.db, + tracker: &tracker, + owner, + repo: tracker_repo_name, + repo_id, + managed: repo.managed, + dashboard: std::env::var("DASHBOARD_PUBLIC_URL").unwrap_or_default(), + labels: tokio::sync::OnceCell::new(), }; - let dashboard = std::env::var("DASHBOARD_PUBLIC_URL").unwrap_or_default(); + if !actionable.is_empty() { + tracing::info!( + "[{repo_id}] Creating issues for {} findings via {}", + actionable.len(), + tracker.name() + ); + } let mut created = 0u32; for finding in actionable { let title = issue_title(finding); // Check if an issue already exists by fingerprint first, then by title let found_existing = match &existing { - Some(index) => index.find(finding, &title).map(str::to_string), + Some(index) => index.find(finding, &title).map(|known| known.url.clone()), None => search_existing(&tracker, owner, tracker_repo_name, finding, &title) .await .map(|issue| issue.external_url), @@ -172,72 +158,12 @@ impl PipelineOrchestrator { ); continue; } - let mut body = format_issue_body(finding); - if repo.managed { - if let Some(link) = finding_link(&dashboard, repo_id) { - body.push_str(&format!( - "\n[Open in Prüfwerk / In Prüfwerk öffnen]({link})" - )); - } - } - let labels = vec![ - format!("severity:{}", finding.severity), - format!("scanner:{}", finding.scanner), - "compliance-scanner".to_string(), - ]; - - let result = match (&tracker, &managed_labels) { - (TrackerDispatch::Gitea(gitea), Some(ids)) => { - let label_ids = label_ids( - ids, - &trackers::gitea::issue_label_names(&finding.severity.to_string()), - ); - gitea - .create_issue_with_label_ids( - owner, - tracker_repo_name, - &title, - &body, - &label_ids, - ) - .await - } - _ => { - tracker - .create_issue(owner, tracker_repo_name, &title, &body, &labels) - .await - } - }; - match result { - Ok(mut issue) => { - issue.finding_id = finding - .id - .as_ref() - .map(|id| id.to_hex()) - .unwrap_or_default(); - - // Update the finding with the issue URL - if let Some(finding_id) = &finding.id { - let _ = self - .db - .findings() - .update_one( - doc! { "_id": finding_id }, - doc! { "$set": { "tracker_issue_url": &issue.external_url } }, - ) - .await; - } - + match sink.open(finding, &title).await { + Ok(issue) => { // Later findings of this run with the same title find it. if let Some(index) = existing.as_mut() { - index.insert(&finding.fingerprint, &title, &issue.external_url); + index.insert(&finding.fingerprint, &title, &issue); } - - // Store the tracker issue record - if let Err(e) = self.db.tracker_issues().insert_one(&issue).await { - tracing::warn!("[{repo_id}] Failed to store tracker issue: {e}"); - } - created += 1; } Err(e) => { @@ -248,8 +174,12 @@ impl PipelineOrchestrator { } } } - tracing::info!("[{repo_id}] Created {created} tracker issues"); + + if let (Some(index), IssueCatchup::DryRun | IssueCatchup::On) = (&existing, catchup) { + let summary = crate::pipeline::issue_catchup::catch_up(&sink, index, catchup).await?; + summary.log(&self.tenant_id, repo_id); + } Ok(()) } } @@ -368,59 +298,236 @@ fn body_fingerprint(body: &str) -> Option<&str> { .filter(|fp| !fp.is_empty()) } +/// An issue of the repository: what a finding linked to it records. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct KnownIssue { + /// The issue number. + pub(super) external_id: String, + pub(super) url: String, + /// Closed on the tracker. + pub(super) closed: bool, +} + /// The issues a repository already has, by fingerprint and by title, built /// from one listing so each finding is matched without a request. #[derive(Debug, Default)] -struct ExistingIssues { - /// Fingerprint (from the body's marker) to issue URL. - by_fingerprint: HashMap, - /// Exact title to issue URL. - by_title: HashMap, +pub(super) struct ExistingIssues { + /// Fingerprint (from the body's marker) to issue. + by_fingerprint: HashMap, + /// Exact title to issue. + by_title: HashMap, } impl ExistingIssues { /// Index `issues`; where two share a fingerprint or title, the first /// listed (Gitea lists the newest first) wins. - fn new(issues: &[GiteaIssue]) -> Self { + pub(super) fn new(issues: &[GiteaIssue]) -> Self { let mut index = Self::default(); for issue in issues { + let known = KnownIssue { + external_id: issue.number.to_string(), + url: issue.html_url.clone(), + closed: issue.state == "closed", + }; if let Some(fp) = issue.body.as_deref().and_then(body_fingerprint) { index .by_fingerprint .entry(fp.to_string()) - .or_insert_with(|| issue.html_url.clone()); + .or_insert_with(|| known.clone()); } - index - .by_title - .entry(issue.title.clone()) - .or_insert_with(|| issue.html_url.clone()); + index.by_title.entry(issue.title.clone()).or_insert(known); } index } - /// The URL of `finding`'s issue: by fingerprint, then by `title` (not - /// for a group, see [`issue_search_terms`]). - fn find(&self, finding: &Finding, title: &str) -> Option<&str> { - self.by_fingerprint - .get(&finding.fingerprint) - .or_else(|| { - finding - .occurrences - .is_empty() - .then(|| self.by_title.get(title)) - .flatten() - }) - .map(String::as_str) + /// `finding`'s issue: by fingerprint, then by `title` (not for a group, + /// see [`issue_search_terms`]). + pub(super) fn find(&self, finding: &Finding, title: &str) -> Option<&KnownIssue> { + self.by_fingerprint.get(&finding.fingerprint).or_else(|| { + finding + .occurrences + .is_empty() + .then(|| self.by_title.get(title)) + .flatten() + }) } /// Add an issue opened during this run. - fn insert(&mut self, fingerprint: &str, title: &str, url: &str) { + fn insert(&mut self, fingerprint: &str, title: &str, issue: &TrackerIssue) { + let known = KnownIssue { + external_id: issue.external_id.clone(), + url: issue.external_url.clone(), + closed: false, + }; self.by_fingerprint .entry(fingerprint.to_string()) - .or_insert_with(|| url.to_string()); - self.by_title - .entry(title.to_string()) - .or_insert_with(|| url.to_string()); + .or_insert_with(|| known.clone()); + self.by_title.entry(title.to_string()).or_insert(known); + } +} + +/// The severities a finding gets an issue at. +pub(super) const ISSUE_SEVERITIES: [Severity; 3] = + [Severity::Medium, Severity::High, Severity::Critical]; + +/// The statuses of findings nobody has decided about (a group can take over +/// its places' decision, #483): only those get an issue. +pub(super) const ISSUE_STATUSES: [FindingStatus; 3] = [ + FindingStatus::Open, + FindingStatus::Triaged, + FindingStatus::NeedsReview, +]; + +/// Whether `finding` should have an issue: medium or above and undecided. +pub(super) fn wants_issue(finding: &Finding) -> bool { + ISSUE_SEVERITIES.contains(&finding.severity) && ISSUE_STATUSES.contains(&finding.status) +} + +/// Where a target's finding issues are opened, and what each one gets. +pub(super) struct IssueSink<'a> { + pub(super) db: &'a Database, + pub(super) tracker: &'a TrackerDispatch, + pub(super) owner: &'a str, + pub(super) repo: &'a str, + /// The target the findings belong to. + pub(super) repo_id: &'a str, + /// From a managed git source (#439): its issues get the Prüfwerk labels + /// and a link into Prüfwerk. + pub(super) managed: bool, + /// The dashboard's public origin (`DASHBOARD_PUBLIC_URL`). + pub(super) dashboard: String, + /// The ids of the Prüfwerk labels, ensured once, when the first issue + /// is opened (`None` inside: they could not be ensured). A `OnceCell` + /// runs its async initialiser at most once, like a cached property. + pub(super) labels: tokio::sync::OnceCell>>, +} + +impl IssueSink<'_> { + /// The label ids of a managed Gitea repository, ensured on first use. + /// If that fails (no permission), issues are still opened, with the + /// label names in the body as before. + async fn label_ids(&self) -> Option<&HashMap> { + let TrackerDispatch::Gitea(gitea) = self.tracker else { + return None; + }; + if !self.managed { + return None; + } + self.labels + .get_or_init(|| async { + match gitea + .ensure_labels(self.owner, self.repo, &trackers::gitea::pruefwerk_labels()) + .await + { + Ok(ids) => Some(ids), + Err(e) => { + tracing::warn!( + "[{}] Could not ensure the Prüfwerk labels: {e}", + self.repo_id + ); + None + } + } + }) + .await + .as_ref() + } + + /// Open the issue of `finding`, titled `title`, and record it. + /// + /// # Errors + /// + /// The tracker refused the issue; nothing is recorded then. + pub(super) async fn open( + &self, + finding: &Finding, + title: &str, + ) -> Result { + let mut body = format_issue_body(finding); + if self.managed { + if let Some(link) = finding_link(&self.dashboard, self.repo_id) { + body.push_str(&format!( + "\n[Open in Prüfwerk / In Prüfwerk öffnen]({link})" + )); + } + } + let mut issue = match (self.tracker, self.label_ids().await) { + (TrackerDispatch::Gitea(gitea), Some(ids)) => { + let label_ids = label_ids( + ids, + &trackers::gitea::issue_label_names(&finding.severity.to_string()), + ); + gitea + .create_issue_with_label_ids(self.owner, self.repo, title, &body, &label_ids) + .await? + } + _ => { + let labels = [ + format!("severity:{}", finding.severity), + format!("scanner:{}", finding.scanner), + "compliance-scanner".to_string(), + ]; + self.tracker + .create_issue(self.owner, self.repo, title, &body, &labels) + .await? + } + }; + issue.finding_id = finding + .id + .as_ref() + .map(|id| id.to_hex()) + .unwrap_or_default(); + self.record(finding, &issue).await; + Ok(issue) + } + + /// Link `finding` to its Gitea issue `known`, which exists already. + pub(super) async fn link(&self, finding: &Finding, title: &str, known: &KnownIssue) { + let mut issue = TrackerIssue::new( + finding + .id + .as_ref() + .map(|id| id.to_hex()) + .unwrap_or_default(), + TrackerType::Gitea, + known.external_id.clone(), + known.url.clone(), + title.to_string(), + ); + if known.closed { + issue.status = IssueStatus::Closed; + } + self.record(finding, &issue).await; + } + + /// Put the issue's URL on the finding and store the issue record (one + /// per finding, replacing an older one), which the status sync + /// ([`crate::pipeline::issue_sync`]) finds the issue by. A failed write + /// is logged: the issue exists either way. + async fn record(&self, finding: &Finding, issue: &TrackerIssue) { + let Some(finding_id) = &finding.id else { + return; + }; + if let Err(e) = self + .db + .findings() + .update_one( + doc! { "_id": finding_id }, + doc! { "$set": { "tracker_issue_url": &issue.external_url } }, + ) + .await + { + tracing::warn!("[{}] Failed to link the issue: {e}", self.repo_id); + } + if let Err(e) = self + .db + .tracker_issues() + .replace_one(doc! { "finding_id": &issue.finding_id }, issue) + .upsert(true) + .await + { + tracing::warn!("[{}] Failed to store tracker issue: {e}", self.repo_id); + } } } @@ -439,7 +546,7 @@ fn issue_search_terms<'a>(finding: &'a Finding, title: &'a str) -> Vec<&'a str> /// A finding's issue title: severity, scanner, the app variant when there /// are several (the same flaw in the phone and the tablet app is two /// issues, and the title is what an issue is found by), and its title. -fn issue_title(finding: &Finding) -> String { +pub(super) fn issue_title(finding: &Finding) -> String { match &finding.variant { Some(variant) => format!( "[{}] {} ({variant}): {}", @@ -637,9 +744,15 @@ mod tests { title: title.into(), body: body.map(str::to_string), html_url: format!("https://gitea.invalid/o/r/issues/{number}"), + state: "open".into(), } } + /// The URL of `finding`'s issue in `index`. + fn url<'a>(index: &'a ExistingIssues, finding: &Finding, title: &str) -> Option<&'a str> { + index.find(finding, title).map(|known| known.url.as_str()) + } + fn high(fingerprint: &str, title: &str) -> Finding { Finding::new( "r".into(), @@ -670,7 +783,7 @@ mod tests { listed(7, "[high] semgrep: old name", Some(&body)), ]); assert_eq!( - index.find(&finding, &issue_title(&finding)), + url(&index, &finding, &issue_title(&finding)), Some("https://gitea.invalid/o/r/issues/7") ); } @@ -681,7 +794,7 @@ mod tests { let title = issue_title(&finding); let index = ExistingIssues::new(&[listed(4, &title, None)]); assert_eq!( - index.find(&finding, &title), + url(&index, &finding, &title), Some("https://gitea.invalid/o/r/issues/4") ); // A group is found by its fingerprint only. @@ -694,7 +807,7 @@ mod tests { decision: None, }) .collect(); - assert_eq!(index.find(&group, &title), None); + assert_eq!(url(&index, &group, &title), None); } #[test] @@ -702,18 +815,21 @@ mod tests { let first = high("fp-3", "Hardcoded key"); let title = issue_title(&first); let mut index = ExistingIssues::new(&[listed(1, "[high] semgrep: other", Some("x"))]); - assert_eq!(index.find(&first, &title), None); + assert_eq!(url(&index, &first, &title), None); // Opened during this run: the next finding with that title (or the // same fingerprint) is not opened twice. - index.insert( - &first.fingerprint, - &title, - "https://gitea.invalid/o/r/issues/9", + let opened = TrackerIssue::new( + String::new(), + TrackerType::Gitea, + "9".into(), + "https://gitea.invalid/o/r/issues/9".into(), + title.clone(), ); + index.insert(&first.fingerprint, &title, &opened); let same_title = high("fp-4", "Hardcoded key"); assert_eq!( - index.find(&same_title, &title), + url(&index, &same_title, &title), Some("https://gitea.invalid/o/r/issues/9") ); assert!(index.find(&first, "another title").is_some()); diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index 95af293..9e79b21 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -24,6 +24,7 @@ pub mod gitleaks; mod graph_build; pub mod grouping; pub mod ios_config; +mod issue_catchup; mod issue_creation; pub(crate) mod issue_sync; pub mod languages; diff --git a/compliance-agent/src/trackers/gitea.rs b/compliance-agent/src/trackers/gitea.rs index 60e1679..edc5c3a 100644 --- a/compliance-agent/src/trackers/gitea.rs +++ b/compliance-agent/src/trackers/gitea.rs @@ -298,6 +298,9 @@ pub struct GiteaIssue { pub body: Option, #[serde(default)] pub html_url: String, + /// `open` or `closed`. + #[serde(default)] + pub state: String, } /// A repository label as Gitea returns it. diff --git a/compliance-core/src/config.rs b/compliance-core/src/config.rs index a2b3733..abd2258 100644 --- a/compliance-core/src/config.rs +++ b/compliance-core/src/config.rs @@ -95,6 +95,52 @@ pub struct AgentConfig { /// below stop being optional and a missing one fails startup instead of /// silently disabling the check. pub app_env: AppEnv, + /// Whether a scan files the missing Gitea issues of a target's older + /// open findings (`ISSUE_CATCHUP`, default off). + pub issue_catchup: IssueCatchup, +} + +/// The issue catch-up (`ISSUE_CATCHUP`): after a scan's own issues, a Gitea +/// target's open medium+ findings without an issue get one (or are linked to +/// the one that exists), at most a few new issues per scan. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum IssueCatchup { + /// No catch-up. + #[default] + Off, + /// Count what the catch-up would create and link, change nothing. + DryRun, + /// Create and link. + On, +} + +impl IssueCatchup { + /// Parse `ISSUE_CATCHUP`: `off`, `dry_run` or `on`, any case. Empty is + /// [`IssueCatchup::Off`]. + /// + /// # Errors + /// + /// Any other value, with a message naming it (the caller falls back to + /// off). + pub fn parse(raw: &str) -> Result { + 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_CATCHUP '{other}' (expected off, dry_run or on)" + )), + } + } + + /// The value as `ISSUE_CATCHUP` spells it. + pub fn as_str(self) -> &'static str { + match self { + Self::Off => "off", + Self::DryRun => "dry_run", + Self::On => "on", + } + } } /// Deployment environment (`APP_ENV`). @@ -274,6 +320,7 @@ impl Default for AgentConfig { platform_allowed_clients: Vec::new(), features: Features::default(), app_env: AppEnv::Dev, + issue_catchup: IssueCatchup::Off, } } } @@ -294,6 +341,22 @@ mod app_env_tests { assert!(AppEnv::Production.is_hardened()); } + #[test] + fn issue_catchup_is_off_unless_named() { + use super::IssueCatchup; + assert_eq!(IssueCatchup::parse("").unwrap(), IssueCatchup::Off); + assert_eq!(IssueCatchup::parse("off").unwrap(), IssueCatchup::Off); + assert_eq!( + IssueCatchup::parse(" DRY_RUN ").unwrap(), + IssueCatchup::DryRun + ); + assert_eq!(IssueCatchup::parse("On").unwrap(), IssueCatchup::On); + assert!(IssueCatchup::parse("yes").is_err()); + assert!(IssueCatchup::parse("dry-run").is_err()); + assert_eq!(AgentConfig::default().issue_catchup, IssueCatchup::Off); + assert_eq!(IssueCatchup::DryRun.as_str(), "dry_run"); + } + #[test] fn dev_needs_nothing() { assert!(AgentConfig::default().validate_deployment().is_ok()); diff --git a/docs/guide/issues.md b/docs/guide/issues.md index 3b635ab..6e8d731 100644 --- a/docs/guide/issues.md +++ b/docs/guide/issues.md @@ -13,6 +13,10 @@ When a scan discovers new findings, the following happens automatically: This means every actionable finding gets tracked in the same system your developers already use. +### Catch-up for findings without an issue (Gitea) + +A scan opens issues only for the findings it finds new, so a finding whose issue could not be opened at the time (Gitea unreachable, the issue refused) stays without one. With `ISSUE_CATCHUP=on`, every scan of a Gitea target then also goes through its open, triaged and to-review findings of severity medium or above that have no issue: one whose issue exists (found by the fingerprint in its body, then by title; a grouped finding by fingerprint only) is linked to it, the others get a new issue. At most 20 new issues per target and scan, highest severity and oldest first; the rest follow in the next scans. `ISSUE_CATCHUP=dry_run` only logs how many issues it would open and link, per severity, and changes nothing. The default is `off`; GitHub, GitLab and Jira are not caught up. + ### 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.