diff --git a/compliance-agent/src/api/handlers/findings.rs b/compliance-agent/src/api/handlers/findings.rs index 573ce59..0a2b437 100644 --- a/compliance-agent/src/api/handlers/findings.rs +++ b/compliance-agent/src/api/handlers/findings.rs @@ -231,6 +231,7 @@ fn status_update( at: chrono::Utc::now(), reason: reason.map(String::from), scan: None, + tracker: None, }; let status = mongodb::bson::to_bson(status).map_err(|_| StatusCode::BAD_REQUEST)?; let change = mongodb::bson::to_bson(&change).map_err(|_| StatusCode::BAD_REQUEST)?; diff --git a/compliance-agent/src/api/handlers/platform.rs b/compliance-agent/src/api/handlers/platform.rs index 702d6a0..4e136e6 100644 --- a/compliance-agent/src/api/handlers/platform.rs +++ b/compliance-agent/src/api/handlers/platform.rs @@ -640,6 +640,10 @@ fn git_source_json( "webhook_secret".into(), new_secret.map_or(serde_json::Value::Null, Into::into), ); + obj.insert( + "webhook_events".into(), + crate::git_source::WEBHOOK_EVENTS.as_slice().into(), + ); } v } diff --git a/compliance-agent/src/git_source/events.rs b/compliance-agent/src/git_source/events.rs index f2bb342..aefb484 100644 --- a/compliance-agent/src/git_source/events.rs +++ b/compliance-agent/src/git_source/events.rs @@ -12,6 +12,9 @@ pub enum SourceAction { /// A push to the default branch: scan the target, creating it first if /// the `created` delivery was lost. Push(GiteaRepo), + /// A person closed or reopened an issue (#953): carry it over to the + /// finding or CVE the issue was opened for, if Prüfwerk opened it. + Issue(IssueEvent), /// Nothing to do, and why. Ignore(&'static str), } @@ -21,11 +24,40 @@ impl SourceAction { pub fn repo(&self) -> Option<&GiteaRepo> { match self { Self::Created(repo) | Self::Deleted(repo) | Self::Push(repo) => Some(repo), + Self::Issue(event) => Some(&event.repo), Self::Ignore(_) => None, } } } +/// What happened to an issue. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum IssueChange { + Closed, + Reopened, +} + +/// An issue closed or reopened in a repository of the organisation. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IssueEvent { + pub repo: GiteaRepo, + /// The issue number in the repository (`TrackerIssue::external_id`). + pub number: i64, + pub change: IssueChange, + /// The login of the user who closed or reopened it. + pub sender: String, +} + +/// Whether Prüfwerk itself caused an issue event: the sender is the issue's +/// author. Prüfwerk opens its issues as the source's bot user and closes and +/// reopens them as that user, so an author acting on their own issue is the +/// bot. The bot token cannot read its own user (`read:user` is not among its +/// scopes), so the author stands in for it. Gitea logins are +/// case-insensitive. +pub fn is_own_event(sender: &str, author: &str) -> bool { + !sender.is_empty() && sender.eq_ignore_ascii_case(author) +} + /// A branch deletion pushes this as the new head. const ZERO_SHA: &str = "0000000000000000000000000000000000000000"; @@ -33,19 +65,16 @@ const ZERO_SHA: &str = "0000000000000000000000000000000000000000"; /// organisation. Repositories of any other owner are ignored, so a system /// webhook (which sees the whole instance) is safe to use. pub fn route_event(event: &str, payload: &serde_json::Value, org: &str) -> SourceAction { + if !super::WEBHOOK_EVENTS.contains(&event) { + return SourceAction::Ignore("event not handled"); + } let Some(repo) = payload .get("repository") .cloned() .and_then(|r| serde_json::from_value::(r).ok()) else { - return match event { - "repository" | "push" => SourceAction::Ignore("payload without a repository"), - _ => SourceAction::Ignore("event not handled"), - }; + return SourceAction::Ignore("payload without a repository"); }; - if !matches!(event, "repository" | "push") { - return SourceAction::Ignore("event not handled"); - } if !repo.in_org(org) { return SourceAction::Ignore("repository outside the configured organisation"); } @@ -55,6 +84,7 @@ pub fn route_event(event: &str, payload: &serde_json::Value, org: &str) -> Sourc Some("deleted") => SourceAction::Deleted(repo), _ => SourceAction::Ignore("repository action not handled"), }, + "issues" => route_issue(payload, repo), _ => { let git_ref = payload.get("ref").and_then(|r| r.as_str()).unwrap_or(""); let after = payload.get("after").and_then(|a| a.as_str()).unwrap_or(""); @@ -69,6 +99,41 @@ pub fn route_event(event: &str, payload: &serde_json::Value, org: &str) -> Sourc } } +/// Route an `issues` delivery of `repo`: a close or reopen by someone other +/// than Prüfwerk's bot user. +fn route_issue(payload: &serde_json::Value, repo: GiteaRepo) -> SourceAction { + let change = match payload.get("action").and_then(|a| a.as_str()) { + Some("closed") => IssueChange::Closed, + Some("reopened") => IssueChange::Reopened, + _ => return SourceAction::Ignore("issue action not handled"), + }; + let issue = payload.get("issue"); + let Some(number) = payload + .get("number") + .or_else(|| issue.and_then(|i| i.get("number"))) + .and_then(serde_json::Value::as_i64) + else { + return SourceAction::Ignore("issue without a number"); + }; + // `user.login` of the sender and of the issue's author. + let login = |user: Option<&serde_json::Value>| { + user.and_then(|u| u.get("login")) + .and_then(|l| l.as_str()) + .unwrap_or_default() + .to_string() + }; + let sender = login(payload.get("sender")); + if is_own_event(&sender, &login(issue.and_then(|i| i.get("user")))) { + return SourceAction::Ignore("issue changed by Prüfwerk's bot user"); + } + SourceAction::Issue(IssueEvent { + repo, + number, + change, + sender, + }) +} + #[cfg(test)] #[allow(clippy::expect_used, clippy::unwrap_used)] mod tests { @@ -161,7 +226,7 @@ mod tests { ); assert_eq!( route_event("issues", &json!({}), "kunde"), - SourceAction::Ignore("event not handled") + SourceAction::Ignore("payload without a repository") ); assert_eq!( route_event("push", &json!({ "ref": "refs/heads/main" }), "kunde"), @@ -172,4 +237,80 @@ mod tests { SourceAction::Ignore("event not handled") ); } + + fn issue_event(action: &str, sender: &str, author: &str) -> serde_json::Value { + json!({ + "action": action, "number": 12, + "issue": { "number": 12, "state": "closed", "user": { "login": author } }, + "sender": { "login": sender }, + "repository": repository("kunde"), + }) + } + + #[test] + fn a_person_closing_or_reopening_an_issue_is_carried_over() { + let closed = issue_event("closed", "dev-anna", "pruefwerk"); + match route_event("issues", &closed, "kunde") { + SourceAction::Issue(e) => assert_eq!( + (e.repo.id, e.number, e.change, e.sender.as_str()), + (42, 12, IssueChange::Closed, "dev-anna") + ), + other => panic!("{other:?}"), + } + let reopened = issue_event("reopened", "dev-anna", "pruefwerk"); + assert!(matches!( + route_event("issues", &reopened, "kunde"), + SourceAction::Issue(IssueEvent { + change: IssueChange::Reopened, + .. + }) + )); + // The number from the issue when the payload has none on top. + let mut p = issue_event("closed", "dev-anna", "pruefwerk"); + p.as_object_mut().unwrap().remove("number"); + assert!(matches!( + route_event("issues", &p, "kunde"), + SourceAction::Issue(IssueEvent { number: 12, .. }) + )); + } + + #[test] + fn pruefwerks_own_changes_are_ignored_so_nothing_loops() { + // The bot closed or reopened the issue it opened. + for action in ["closed", "reopened"] { + let p = issue_event(action, "pruefwerk", "pruefwerk"); + assert_eq!( + route_event("issues", &p, "kunde"), + SourceAction::Ignore("issue changed by Prüfwerk's bot user") + ); + } + assert!(is_own_event("Pruefwerk", "pruefwerk")); + assert!(!is_own_event("dev-anna", "pruefwerk")); + // A payload without a sender is not taken for the bot's. + assert!(!is_own_event("", "")); + } + + #[test] + fn other_issue_events_are_ignored() { + for action in ["opened", "edited", "label_updated", "assigned"] { + let p = issue_event(action, "dev-anna", "pruefwerk"); + assert_eq!( + route_event("issues", &p, "kunde"), + SourceAction::Ignore("issue action not handled") + ); + } + let mut p = issue_event("closed", "dev-anna", "pruefwerk"); + p.as_object_mut().unwrap().remove("number"); + p["issue"].as_object_mut().unwrap().remove("number"); + assert_eq!( + route_event("issues", &p, "kunde"), + SourceAction::Ignore("issue without a number") + ); + let mut p = issue_event("closed", "dev-anna", "pruefwerk"); + p["repository"] = repository("andere"); + assert_eq!( + route_event("issues", &p, "kunde"), + SourceAction::Ignore("repository outside the configured organisation") + ); + } } diff --git a/compliance-agent/src/git_source/mod.rs b/compliance-agent/src/git_source/mod.rs index 982a948..4f91120 100644 --- a/compliance-agent/src/git_source/mod.rs +++ b/compliance-agent/src/git_source/mod.rs @@ -34,6 +34,10 @@ use gitea::{GiteaRepo, RepoLister, SourceClient}; pub const DEFAULT_HOST_PATTERN: &str = r"^[a-z0-9-]+\.code(-stage)?\.breakpilot\.com$"; /// Minutes between syncs unless `GIT_SOURCE_SYNC_MINUTES` says otherwise. pub const DEFAULT_SYNC_MINUTES: u64 = 30; +/// The Gitea events the organisation or system webhook must send: Prüfwerk +/// cannot register or change the webhook itself (the bot has no +/// administration rights), so the platform API names them for provisioning. +pub const WEBHOOK_EVENTS: [&str; 3] = ["repository", "push", "issues"]; /// The webhook path of a tenant's source, below the webhook server's origin. pub fn webhook_path(tenant_id: &str) -> String { format!("/webhook/{tenant_id}/gitea-source") @@ -454,6 +458,11 @@ pub enum Outcome { Ensured { target_id: String, scan: bool }, /// The repository's target was archived (`false`: there was none). Archived(bool), + /// An issue closed or reopened in Gitea was carried back (#953). + Issue { + target_id: String, + detail: &'static str, + }, /// Nothing done. Ignored(&'static str), } @@ -495,6 +504,24 @@ pub async fn apply_action( scan: true, }) } + SourceAction::Issue(event) => { + // Only the repository's existing target: an issue event never + // creates one. + let Some(target_id) = db + .onboarded_targets() + .find_one(repo_filter(&source.base_url, event.repo.id)) + .await? + .and_then(|t| t.id) + else { + return Ok(Outcome::Ignored("repository has no target")); + }; + let target_id = target_id.to_hex(); + let done = crate::pipeline::issue_backsync::apply(db, &target_id, &event).await?; + Ok(Outcome::Issue { + target_id, + detail: done.detail(event.change), + }) + } } } diff --git a/compliance-agent/src/pipeline/cve_issues.rs b/compliance-agent/src/pipeline/cve_issues.rs index 8ebdcd8..02bb595 100644 --- a/compliance-agent/src/pipeline/cve_issues.rs +++ b/compliance-agent/src/pipeline/cve_issues.rs @@ -7,6 +7,12 @@ //! updated or removed), the issue is closed with a comment; when it comes back, //! it is reopened. //! +//! An issue a person closed in Gitea (#953) stays closed while the scan still +//! finds its CVE: closing it was that person's call, and no VEX statement is +//! made from it (one needs a justification). Once a complete scan no longer +//! finds the CVE, that close is forgotten, so a CVE that comes back reopens +//! the issue as usual. +//! //! 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 @@ -189,6 +195,8 @@ pub(crate) async fn sync_cve_issues( .filter(|(_, a)| !a.is_resolved_by_vex() && issue_worthy(a, target.epss_percentile)) { match existing.get(key) { + // A person closed it in Gitea while the CVE is unchanged. + Some(issue) if issue.closed_in_tracker.is_some() => {} Some(issue) if is_closed(&issue.status) => { let comment = "**Prüfwerk:** Bei der Prüfung erneut gefunden, daher wieder geöffnet.\n\nFound again by the scan, so reopened."; if set_state(target, issue, comment, "open").await { @@ -218,7 +226,14 @@ pub(crate) async fn sync_cve_issues( if complete { for (key, issue) in &existing { - if present.contains_key(key) || is_closed(&issue.status) { + if present.contains_key(key) { + continue; + } + if is_closed(&issue.status) { + // Gone now: if it comes back, it is found again. + if issue.closed_in_tracker.is_some() { + record(target.db, issue, IssueStatus::Closed).await?; + } continue; } let comment = "**Prüfwerk:** Die Prüfung findet diese Schwachstelle nicht mehr: Die Abhängigkeit wurde aktualisiert oder entfernt.\n\nThe scan no longer finds this vulnerability: the dependency was updated or removed."; @@ -498,12 +513,10 @@ async fn record( let Some(id) = issue.id else { return Ok(()); }; - let status = mongodb::bson::to_bson(&status).map_err(|e| AgentError::Other(e.to_string()))?; + let update = crate::pipeline::issue_sync::issue_state_update(&status, None) + .map_err(|e| AgentError::Other(e.to_string()))?; db.tracker_issues() - .update_one( - doc! { "_id": id }, - doc! { "$set": { "status": status, "updated_at": mongodb::bson::DateTime::now() } }, - ) + .update_one(doc! { "_id": id }, update) .await?; Ok(()) } @@ -784,7 +797,9 @@ mod tests { // It comes back: reopened, not opened twice. assert_eq!( - sync_cve_issues(&target, &[okhttp], true).await.unwrap(), + sync_cve_issues(&target, std::slice::from_ref(&okhttp), true) + .await + .unwrap(), CveIssueCounts { reopened: 1, ..Default::default() @@ -792,6 +807,46 @@ mod tests { ); assert_eq!(calls.lock().unwrap().last().unwrap(), "state 100: \"open\""); + // A person closes it in Gitea (#953): the scan that still finds the + // CVE leaves it closed and sends nothing. + let key = format!("cve:target-1:okhttp:{}", okhttp.cve()); + db.tracker_issues() + .update_one( + doc! { "finding_id": &key }, + doc! { "$set": { "status": "closed", "closed_in_tracker": "dev-anna" } }, + ) + .await + .unwrap(); + let sent = calls.lock().unwrap().len(); + assert_eq!( + sync_cve_issues(&target, std::slice::from_ref(&okhttp), true) + .await + .unwrap(), + CveIssueCounts::default() + ); + assert_eq!(calls.lock().unwrap().len(), sent); + + // Updated away, the close is forgotten; back again, it reopens. + sync_cve_issues(&target, &[], true).await.unwrap(); + let stored = db + .tracker_issues() + .find_one(doc! { "finding_id": &key }) + .await + .unwrap() + .unwrap(); + assert_eq!( + (stored.status, stored.closed_in_tracker), + (IssueStatus::Closed, None) + ); + assert_eq!(calls.lock().unwrap().len(), sent, "already closed"); + assert_eq!( + sync_cve_issues(&target, &[okhttp], true) + .await + .unwrap() + .reopened, + 1 + ); + pool.drop_tenant("cve-issues").await.ok(); } diff --git a/compliance-agent/src/pipeline/issue_backsync.rs b/compliance-agent/src/pipeline/issue_backsync.rs new file mode 100644 index 0000000..c979baf --- /dev/null +++ b/compliance-agent/src/pipeline/issue_backsync.rs @@ -0,0 +1,443 @@ +//! A person closing or reopening a Prüfwerk issue in Gitea, carried back to +//! the finding (#953). +//! +//! * Closed: an undecided finding becomes resolved, recorded as "closed in the +//! ticket" with the Gitea user's login. The next scan confirms it (not found: +//! it stays resolved) or reopens finding and issue as for any resolved +//! finding found again. A finding a person had already decided keeps that +//! decision; only the issue's state is recorded. +//! * Reopened: a decided finding becomes undecided again (`open`). +//! * CVE issues: only the issue's state and who closed it are recorded. No +//! VEX statement is set, since one needs a justification; the scan leaves +//! the issue closed while the CVE is still there +//! ([`crate::pipeline::cve_issues`]). +//! +//! Nothing here calls the tracker: the issue already is in the state the +//! event reports, and the issue record says so, so the status sync +//! ([`crate::pipeline::issue_sync`]) has nothing to carry over either. + +use futures_util::TryStreamExt; +use mongodb::bson::{doc, oid::ObjectId, to_bson, Bson, Document}; + +use compliance_core::models::{ + FindingStatus, IssueStatus, StatusChange, TrackerChangeKind, TrackerIssue, TrackerType, +}; + +use crate::database::Database; +use crate::error::AgentError; +use crate::git_source::events::{IssueChange, IssueEvent}; +use crate::pipeline::issue_creation::ISSUE_STATUSES; +use crate::pipeline::issue_sync::issue_state_update; + +/// What carrying an issue event back did, for the delivery record. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum BackSynced { + /// The issue is not one Prüfwerk opened in this repository. + NotOurs, + /// The finding's status changed. + Finding, + /// Only the issue's state was recorded: the finding already had a + /// matching status (a person had decided it, or it was undecided). + IssueOnly, + /// A CVE issue's state was recorded. + Cve, +} + +impl BackSynced { + /// The delivery record's detail for this result of `change`. + pub(crate) fn detail(self, change: IssueChange) -> &'static str { + match (self, change) { + (Self::NotOurs, _) => "issue not opened by Prüfwerk", + (Self::Finding, IssueChange::Closed) => "finding resolved: issue closed in Gitea", + (Self::Finding, IssueChange::Reopened) => "finding reopened: issue reopened in Gitea", + (Self::IssueOnly, _) => "issue state recorded; the finding's status already matched", + (Self::Cve, _) => "CVE issue state recorded", + } + } +} + +/// The finding statuses `change` moves a finding away from: the undecided +/// ones ([`ISSUE_STATUSES`]) for a close, every other for a reopen. +fn statuses_changed_by(change: IssueChange) -> Document { + let undecided: Vec = ISSUE_STATUSES.iter().map(ToString::to_string).collect(); + match change { + IssueChange::Closed => doc! { "$in": undecided }, + IssueChange::Reopened => doc! { "$nin": undecided }, + } +} + +/// The status a finding moves to and how its history records `change`. +fn new_status(change: IssueChange) -> (FindingStatus, TrackerChangeKind) { + match change { + IssueChange::Closed => (FindingStatus::Resolved, TrackerChangeKind::ClosedInTracker), + IssueChange::Reopened => (FindingStatus::Open, TrackerChangeKind::ReopenedInTracker), + } +} + +/// Carry `event` back for the managed target `target_id`. +/// +/// # Arguments +/// +/// * `db` - the tenant database +/// * `target_id` - the target of the event's repository +/// * `event` - the close or reopen, by someone other than Prüfwerk's bot +/// +/// # Returns +/// +/// What was changed. +/// +/// # Errors +/// +/// A database error. +pub(crate) async fn apply( + db: &Database, + target_id: &str, + event: &IssueEvent, +) -> Result { + let Some(issue) = find_issue(db, target_id, event.number).await? else { + return Ok(BackSynced::NotOurs); + }; + let (status, closed_by) = match event.change { + IssueChange::Closed => (IssueStatus::Closed, Some(event.sender.as_str())), + IssueChange::Reopened => (IssueStatus::Open, None), + }; + // The issue first: once it reads closed, a status sync running meanwhile + // finds nothing to close (and no comment to write) for the finding. + if let Some(id) = issue.id { + let update = + issue_state_update(&status, closed_by).map_err(|e| AgentError::Other(e.to_string()))?; + let mut filter = doc! { "_id": id }; + if closed_by.is_some() { + // A record that already reads closed was closed by Prüfwerk (by + // a bot user other than the issue's author, after a token + // change): there is no person's close to keep. + filter.insert("status", doc! { "$nin": ["closed", "resolved"] }); + } + db.tracker_issues().update_one(filter, update).await?; + } + if issue.finding_id.starts_with("cve:") { + return Ok(BackSynced::Cve); + } + let Ok(finding_id) = ObjectId::parse_str(&issue.finding_id) else { + return Ok(BackSynced::IssueOnly); + }; + let (new, kind) = new_status(event.change); + let change = StatusChange::by_tracker(new.clone(), kind, &event.sender); + let to_bson_err = |e: mongodb::bson::ser::Error| AgentError::Other(e.to_string()); + // One conditional update, like the scan's status changes: a decision a + // person makes meanwhile is not overwritten. + let res = db + .findings() + .update_one( + doc! { "_id": finding_id, "status": statuses_changed_by(event.change) }, + doc! { + "$set": { + "status": to_bson(&new).map_err(to_bson_err)?, + "updated_at": mongodb::bson::DateTime::now(), + }, + "$push": { "status_history": to_bson(&change).map_err(to_bson_err)? }, + }, + ) + .await?; + Ok(if res.modified_count > 0 { + BackSynced::Finding + } else { + BackSynced::IssueOnly + }) +} + +/// The issue Prüfwerk opened as number `number` in the repository of target +/// `target_id`. Issue numbers repeat across repositories, so a record counts +/// only if it belongs to the target: a CVE issue by its key, a finding issue +/// by its finding. +async fn find_issue( + db: &Database, + target_id: &str, + number: i64, +) -> Result, AgentError> { + let tracker = to_bson(&TrackerType::Gitea).map_err(|e| AgentError::Other(e.to_string()))?; + let candidates: Vec = db + .tracker_issues() + .find(doc! { "external_id": number.to_string(), "tracker_type": tracker }) + .await? + .try_collect() + .await?; + let cve_prefix = format!("cve:{target_id}:"); + if let Some(cve) = candidates + .iter() + .find(|i| i.finding_id.starts_with(&cve_prefix)) + { + return Ok(Some(cve.clone())); + } + let ids: Vec = candidates + .iter() + .filter_map(|i| ObjectId::parse_str(&i.finding_id).ok()) + .map(Bson::ObjectId) + .collect(); + if ids.is_empty() { + return Ok(None); + } + let Some(row) = db + .findings() + .clone_with_type::() + .find_one(doc! { "_id": { "$in": ids }, "repo_id": target_id }) + .projection(doc! { "_id": 1 }) + .await? + else { + return Ok(None); + }; + let Ok(id) = row.get_object_id("_id") else { + return Ok(None); + }; + let id = id.to_hex(); + Ok(candidates.into_iter().find(|i| i.finding_id == id)) +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + use compliance_core::models::{Finding, ScanType, Severity}; + + use crate::git_source::gitea::GiteaRepo; + + #[test] + fn a_close_resolves_undecided_findings_and_a_reopen_reopens_decided_ones() { + assert_eq!( + new_status(IssueChange::Closed), + (FindingStatus::Resolved, TrackerChangeKind::ClosedInTracker) + ); + assert_eq!( + new_status(IssueChange::Reopened), + (FindingStatus::Open, TrackerChangeKind::ReopenedInTracker) + ); + let closed = statuses_changed_by(IssueChange::Closed); + let moved: Vec<&str> = closed + .get_array("$in") + .unwrap() + .iter() + .filter_map(Bson::as_str) + .collect(); + assert_eq!(moved, ["open", "triaged", "needs_review"]); + assert!(statuses_changed_by(IssueChange::Reopened).contains_key("$nin")); + } + + #[test] + fn the_delivery_record_says_what_happened() { + assert_eq!( + BackSynced::Finding.detail(IssueChange::Closed), + "finding resolved: issue closed in Gitea" + ); + assert_eq!( + BackSynced::NotOurs.detail(IssueChange::Reopened), + "issue not opened by Prüfwerk" + ); + } + + fn event(change: IssueChange) -> IssueEvent { + let repo: GiteaRepo = serde_json::from_value(serde_json::json!({ + "id": 7, "name": "fw", "full_name": "kunde/fw", + })) + .unwrap(); + IssueEvent { + repo, + number: 12, + change, + sender: "dev-anna".into(), + } + } + + #[tokio::test] + async fn closing_and_reopening_in_gitea_moves_the_finding() { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let prefix = format!( + "ibsync_{}", + &uuid::Uuid::new_v4().simple().to_string()[..10] + ); + let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else { + eprintln!("SKIP issue_backsync: no MongoDB reachable at {uri}"); + return; + }; + let db = pool.for_tenant_id("issue-backsync").await.unwrap(); + let target = ObjectId::new().to_hex(); + let other_target = ObjectId::new().to_hex(); + + // Arrange: issue #12 of this target's finding, and #12 of another + // repository's finding (numbers repeat across repositories). + let insert = |repo_id: String, status: FindingStatus| { + let db = db.clone(); + async move { + let mut f = Finding::new( + repo_id, + format!("fp-{}", ObjectId::new()), + "semgrep".into(), + ScanType::Sast, + "strcpy".into(), + "d".into(), + Severity::High, + ); + f.status = status; + let id = db + .findings() + .insert_one(&f) + .await + .unwrap() + .inserted_id + .as_object_id() + .unwrap(); + let issue = TrackerIssue::new( + id.to_hex(), + TrackerType::Gitea, + "12".into(), + "https://kunde.code.breakpilot.com/kunde/fw/issues/12".into(), + "strcpy".into(), + ); + db.tracker_issues().insert_one(&issue).await.unwrap(); + id + } + }; + let other = insert(other_target, FindingStatus::Open).await; + let ours = insert(target.clone(), FindingStatus::NeedsReview).await; + let finding = |id: ObjectId| { + let db = db.clone(); + async move { + db.findings() + .find_one(doc! { "_id": id }) + .await + .unwrap() + .unwrap() + } + }; + let issue_of = |id: ObjectId| { + let db = db.clone(); + async move { + db.tracker_issues() + .find_one(doc! { "finding_id": id.to_hex() }) + .await + .unwrap() + .unwrap() + } + }; + + // Act: closed in Gitea. + let done = apply(&db, &target, &event(IssueChange::Closed)) + .await + .unwrap(); + + // Assert: resolved, recorded as closed in the ticket by the user. + assert_eq!(done, BackSynced::Finding); + let f = finding(ours).await; + assert_eq!(f.status, FindingStatus::Resolved); + let last = f.status_history.last().unwrap(); + assert_eq!(last.tracker, Some(TrackerChangeKind::ClosedInTracker)); + assert_eq!(last.by_name.as_deref(), Some("dev-anna")); + let issue = issue_of(ours).await; + assert_eq!(issue.status, IssueStatus::Closed); + assert_eq!(issue.closed_in_tracker.as_deref(), Some("dev-anna")); + // The other repository's #12 is untouched. + assert_eq!(finding(other).await.status, FindingStatus::Open); + assert_eq!(issue_of(other).await.status, IssueStatus::Open); + + // The same delivery again changes nothing more. + let again = apply(&db, &target, &event(IssueChange::Closed)) + .await + .unwrap(); + assert_eq!(again, BackSynced::IssueOnly); + assert_eq!(finding(ours).await.status_history.len(), 1); + + // Reopened in Gitea: undecided again, the closer forgotten. + let done = apply(&db, &target, &event(IssueChange::Reopened)) + .await + .unwrap(); + assert_eq!(done, BackSynced::Finding); + let f = finding(ours).await; + assert_eq!(f.status, FindingStatus::Open); + assert_eq!( + f.status_history.last().unwrap().tracker, + Some(TrackerChangeKind::ReopenedInTracker) + ); + let issue = issue_of(ours).await; + assert_eq!(issue.status, IssueStatus::Open); + assert!(issue.closed_in_tracker.is_none()); + + // A decision a person made in Prüfwerk is kept on a close. + db.findings() + .update_one( + doc! { "_id": ours }, + doc! { "$set": { "status": "accepted_risk" } }, + ) + .await + .unwrap(); + db.tracker_issues() + .update_one( + doc! { "finding_id": ours.to_hex() }, + doc! { "$set": { "status": "open" } }, + ) + .await + .unwrap(); + let done = apply(&db, &target, &event(IssueChange::Closed)) + .await + .unwrap(); + assert_eq!(done, BackSynced::IssueOnly); + assert_eq!(finding(ours).await.status, FindingStatus::AcceptedRisk); + assert_eq!(issue_of(ours).await.status, IssueStatus::Closed); + + // An issue Prüfwerk did not open (no record) is not ours. + let mut stranger = event(IssueChange::Closed); + stranger.number = 99; + assert_eq!( + apply(&db, &target, &stranger).await.unwrap(), + BackSynced::NotOurs + ); + + // A CVE issue: only the record, with who closed it. + let key = format!("cve:{target}:openssl:CVE-2024-0001"); + let mut cve = TrackerIssue::new( + key.clone(), + TrackerType::Gitea, + "30".into(), + "https://kunde.code.breakpilot.com/kunde/fw/issues/30".into(), + "[CVE] openssl@3.0.0: CVE-2024-0001".into(), + ); + cve.status = IssueStatus::Open; + db.tracker_issues().insert_one(&cve).await.unwrap(); + let mut closed = event(IssueChange::Closed); + closed.number = 30; + assert_eq!(apply(&db, &target, &closed).await.unwrap(), BackSynced::Cve); + let stored = db + .tracker_issues() + .find_one(doc! { "finding_id": &key }) + .await + .unwrap() + .unwrap(); + assert_eq!(stored.status, IssueStatus::Closed); + assert_eq!(stored.closed_in_tracker.as_deref(), Some("dev-anna")); + + // Prüfwerk closed it already (the event comes from a bot user other + // than the issue's author, after a token change): no person's close + // is recorded, so a CVE that comes back still reopens it. + let key = format!("cve:{target}:zlib:CVE-2024-0002"); + let mut cve = TrackerIssue::new( + key.clone(), + TrackerType::Gitea, + "31".into(), + "https://kunde.code.breakpilot.com/kunde/fw/issues/31".into(), + "[CVE] zlib@1.2.0: CVE-2024-0002".into(), + ); + cve.status = IssueStatus::Closed; + db.tracker_issues().insert_one(&cve).await.unwrap(); + closed.number = 31; + closed.sender = "pruefwerk-neu".into(); + apply(&db, &target, &closed).await.unwrap(); + let stored = db + .tracker_issues() + .find_one(doc! { "finding_id": &key }) + .await + .unwrap() + .unwrap(); + assert!(stored.closed_in_tracker.is_none()); + + pool.drop_tenant("issue-backsync").await.ok(); + } +} diff --git a/compliance-agent/src/pipeline/issue_sync.rs b/compliance-agent/src/pipeline/issue_sync.rs index c6f2b60..054ff30 100644 --- a/compliance-agent/src/pipeline/issue_sync.rs +++ b/compliance-agent/src/pipeline/issue_sync.rs @@ -170,19 +170,40 @@ impl IssueSync { let Some(id) = issue.id else { return Ok(()); }; - let status = mongodb::bson::to_bson(&status).map_err(|e| e.to_string())?; + let update = issue_state_update(&status, None).map_err(|e| e.to_string())?; self.db .tracker_issues() - .update_one( - doc! { "_id": id }, - doc! { "$set": { "status": status, "updated_at": mongodb::bson::DateTime::now() } }, - ) + .update_one(doc! { "_id": id }, update) .await .map(drop) .map_err(|e| e.to_string()) } } +/// The update that stores an issue's new `status`. `closed_by` is the +/// tracker user who closed it there (#953); when Prüfwerk changes the state, +/// or the issue is reopened, it is `None` and an earlier closer is cleared. +/// +/// # Errors +/// +/// The status cannot be written as BSON. +pub(crate) fn issue_state_update( + status: &IssueStatus, + closed_by: Option<&str>, +) -> Result { + let mut set = doc! { + "status": mongodb::bson::to_bson(status)?, + "updated_at": mongodb::bson::DateTime::now(), + }; + Ok(match closed_by { + Some(login) => { + set.insert("closed_in_tracker", login); + doc! { "$set": set } + } + None => doc! { "$set": set, "$unset": { "closed_in_tracker": "" } }, + }) +} + /// The `risk:accepted` label id per target (`Finding::repo_id`), once /// resolved; `None` for a target whose repository has no such label. type RiskLabels = HashMap>; @@ -492,6 +513,69 @@ mod tests { assert_eq!(tail, ["state 12: \"closed\"", "labels 12: [42]"]); } + // Reopened, then a person closes the issue in Gitea (#953): the + // back-sync resolves the finding and records the issue closed, so the + // sync neither comments nor closes it again. + db.findings() + .update_one( + doc! { "_id": finding_id }, + doc! { "$set": { "status": "open" } }, + ) + .await + .unwrap(); + sync.sync_one(finding_id, &mut RiskLabels::new()) + .await + .unwrap(); + assert_eq!(issue_status().await, IssueStatus::Open); + let event = crate::git_source::events::IssueEvent { + repo: serde_json::from_value(serde_json::json!({ + "id": 7, "name": "fw", "full_name": "kunde/fw", + })) + .unwrap(), + number: 12, + change: crate::git_source::events::IssueChange::Closed, + sender: "dev-anna".into(), + }; + crate::pipeline::issue_backsync::apply(&db, &target_id.to_hex(), &event) + .await + .unwrap(); + let before = calls.lock().unwrap().len(); + sync.sync_one(finding_id, &mut RiskLabels::new()) + .await + .unwrap(); + assert_eq!(calls.lock().unwrap().len(), before, "nothing sent to Gitea"); + assert_eq!(issue_status().await, IssueStatus::Closed); + + // Found again by the next scan: reopened with the usual comment. + db.findings() + .update_one( + doc! { "_id": finding_id }, + doc! { + "$set": { "status": "open" }, + "$push": { "status_history": mongodb::bson::to_bson(&by_scan( + FindingStatus::Open, + ScanChangeKind::FoundAgain, + )).unwrap() }, + }, + ) + .await + .unwrap(); + sync.sync_one(finding_id, &mut RiskLabels::new()) + .await + .unwrap(); + { + let calls = calls.lock().unwrap(); + assert!(calls[before].contains("erneut gefunden")); + assert_eq!(calls[before + 1], "state 12: \"open\""); + } + let reopened = db + .tracker_issues() + .find_one(doc! { "finding_id": finding_id.to_hex() }) + .await + .unwrap() + .unwrap(); + assert!(reopened.closed_in_tracker.is_none()); + pool.drop_tenant("issue-sync").await.ok(); } @@ -526,6 +610,20 @@ mod tests { StatusChange::by_scan(status, kind, "run-1") } + #[test] + fn the_issue_state_keeps_who_closed_it_in_the_tracker_until_it_reopens() { + let closed = issue_state_update(&IssueStatus::Closed, Some("dev-anna")).unwrap(); + let set = closed.get_document("$set").unwrap(); + assert_eq!(set.get_str("status").unwrap(), "closed"); + assert_eq!(set.get_str("closed_in_tracker").unwrap(), "dev-anna"); + assert!(!closed.contains_key("$unset")); + let by_pruefwerk = issue_state_update(&IssueStatus::Open, None).unwrap(); + assert!(by_pruefwerk + .get_document("$unset") + .unwrap() + .contains_key("closed_in_tracker")); + } + #[test] fn closing_statuses_close_and_open_ones_reopen() { assert_eq!( diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index 85eb6b7..85dad55 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -26,6 +26,7 @@ pub mod gitleaks; pub(crate) mod graph_build; pub mod grouping; pub mod ios_config; +pub(crate) mod issue_backsync; mod issue_catchup; pub(crate) mod issue_creation; pub(crate) mod issue_sync; diff --git a/compliance-agent/src/webhooks/gitea_source.rs b/compliance-agent/src/webhooks/gitea_source.rs index 52ce667..a2b2840 100644 --- a/compliance-agent/src/webhooks/gitea_source.rs +++ b/compliance-agent/src/webhooks/gitea_source.rs @@ -6,7 +6,9 @@ //! source is read through a handle that cannot conjure a tenant database. //! //! A verified delivery that asks for work is answered `202 Accepted` at once; -//! the entitlement check, the target and the scan follow in the background, +//! the entitlement check, the target and the scan (or, for an issue closed +//! or reopened by a person, the finding's new status, #953) follow in the +//! background, //! so a slow registry or Keycloak never runs into Gitea's delivery timeout. //! What became of it (handled, refused, failed) is recorded for the target //! page, since Gitea's delivery log only ever sees the `202`. @@ -199,6 +201,9 @@ fn delivery_of(event: &str, result: &Result) -> WebhookDeli Ok(Outcome::Archived(false)) => { (DeliveryResult::Handled, "no active target to archive", None) } + Ok(Outcome::Issue { target_id, detail }) => { + (DeliveryResult::Handled, *detail, Some(target_id.clone())) + } Ok(Outcome::Ignored(why)) => (DeliveryResult::Handled, *why, None), Err(NotHandled::Refused(why)) => (DeliveryResult::Refused, why.as_str(), None), Err(NotHandled::Failed(why)) => (DeliveryResult::Failed, why.as_str(), None), @@ -257,6 +262,20 @@ mod tests { let d = delivery_of("repository", &Ok(ensured(false))); assert_eq!(d.detail, "target ready, nothing to scan yet"); + let issue = Outcome::Issue { + target_id: "t1".into(), + detail: "finding resolved: issue closed in Gitea", + }; + let d = delivery_of("issues", &Ok(issue)); + assert_eq!( + (d.result, d.detail.as_str(), d.target_id.as_deref()), + ( + DeliveryResult::Handled, + "finding resolved: issue closed in Gitea", + Some("t1") + ) + ); + let d = delivery_of("repository", &Ok(Outcome::Archived(true))); assert_eq!( (d.result, d.detail.as_str()), diff --git a/compliance-agent/tests/git_source.rs b/compliance-agent/tests/git_source.rs index 0404317..c40391b 100644 --- a/compliance-agent/tests/git_source.rs +++ b/compliance-agent/tests/git_source.rs @@ -483,6 +483,155 @@ async fn platform_api_webhook_and_sync() { h.pool.drop_tenant(TENANT).await.ok(); } +/// An issue a person closes or reopens in Gitea moves its finding (#953); +/// the same done by Prüfwerk's bot user is ignored, so nothing loops. +#[tokio::test] +async fn an_issue_closed_or_reopened_in_gitea_moves_its_finding() { + use compliance_core::models::{ + Finding, FindingStatus, IssueStatus, ScanType, Severity, TrackerChangeKind, TrackerIssue, + TrackerType, + }; + + let Some(h) = start().await else { return }; + let (status, created) = h + .put_source(serde_json::json!({ + "base_url": "https://kunde.code.breakpilot.com", "org": "kunde", + "bot_token": "bot-pat", "enabled": false + })) + .await; + assert_eq!(status, 200, "{created}"); + assert_eq!( + created["webhook_events"], + serde_json::json!(["repository", "push", "issues"]) + ); + let secret = created["webhook_secret"].as_str().unwrap().to_string(); + h.db.git_sources() + .update_one(doc! {}, doc! { "$set": { "enabled": true } }) + .await + .unwrap(); + let send = |event: &'static str, body: serde_json::Value| { + let sig = sign(&secret, &serde_json::to_vec(&body).unwrap()); + let h = &h; + async move { h.deliver(TENANT, event, &body, Some(sig)).await } + }; + + // Arrange: the repository's target, a finding and its issue #12. + let repo = repo_json(21, "kunde", "fw"); + assert_eq!( + send( + "repository", + serde_json::json!({ "action": "created", "repository": repo }) + ) + .await, + 202 + ); + Harness::eventually("the target", || async { h.target(21).await.is_some() }).await; + let target_id = h.target(21).await.unwrap().id.unwrap().to_hex(); + let mut finding = Finding::new( + target_id.clone(), + "fp-backsync".into(), + "semgrep".into(), + ScanType::Sast, + "strcpy".into(), + "d".into(), + Severity::High, + ); + finding.status = FindingStatus::NeedsReview; + let finding_id = + h.db.findings() + .insert_one(&finding) + .await + .unwrap() + .inserted_id + .as_object_id() + .unwrap(); + let issue = TrackerIssue::new( + finding_id.to_hex(), + TrackerType::Gitea, + "12".into(), + "https://kunde.code.breakpilot.com/kunde/fw/issues/12".into(), + "strcpy".into(), + ); + h.db.tracker_issues().insert_one(&issue).await.unwrap(); + let issue_event = |action: &str, sender: &str| { + serde_json::json!({ + "action": action, "number": 12, + "issue": { "number": 12, "user": { "login": "pruefwerk" } }, + "sender": { "login": sender }, + "repository": repo, + }) + }; + let stored = || async { + let f = + h.db.findings() + .find_one(doc! { "_id": finding_id }) + .await + .unwrap() + .unwrap(); + let i = + h.db.tracker_issues() + .find_one(doc! { "finding_id": finding_id.to_hex() }) + .await + .unwrap() + .unwrap(); + (f, i) + }; + + // Prüfwerk's own close (the bot opened the issue): answered at once, + // nothing changes. + assert_eq!( + send("issues", issue_event("closed", "pruefwerk")).await, + 200 + ); + + // A person closes it: resolved, as closed in the ticket by them. + assert_eq!(send("issues", issue_event("closed", "dev-anna")).await, 202); + Harness::eventually("the resolved finding", || async { + stored().await.0.status == FindingStatus::Resolved + }) + .await; + let (f, i) = stored().await; + let change = f.status_history.last().unwrap(); + assert_eq!(change.tracker, Some(TrackerChangeKind::ClosedInTracker)); + assert_eq!(change.by_name.as_deref(), Some("dev-anna")); + assert_eq!(f.status_history.len(), 1, "the bot's close changed nothing"); + assert_eq!( + (i.status, i.closed_in_tracker.as_deref()), + (IssueStatus::Closed, Some("dev-anna")) + ); + let for_target = compliance_agent::webhooks::deliveries::target_filter(&target_id, None); + Harness::eventually("the recorded issue delivery", || async { + h.db.webhook_deliveries() + .count_documents({ + let mut f = for_target.clone(); + f.insert("detail", "finding resolved: issue closed in Gitea"); + f + }) + .await + .unwrap() + == 1 + }) + .await; + + // Reopened: undecided again. + assert_eq!( + send("issues", issue_event("reopened", "dev-anna")).await, + 202 + ); + Harness::eventually("the reopened finding", || async { + stored().await.0.status == FindingStatus::Open + }) + .await; + let (f, i) = stored().await; + assert_eq!( + f.status_history.last().unwrap().tracker, + Some(TrackerChangeKind::ReopenedInTracker) + ); + assert_eq!((i.status, i.closed_in_tracker), (IssueStatus::Open, None)); + + h.pool.drop_tenant(TENANT).await.ok(); +} + /// A deliveries collection written before the indexes were ensured (a plain /// one) is converted to a capped one. #[tokio::test] diff --git a/compliance-core/src/models/finding.rs b/compliance-core/src/models/finding.rs index a8fe55c..5f7db00 100644 --- a/compliance-core/src/models/finding.rs +++ b/compliance-core/src/models/finding.rs @@ -93,6 +93,10 @@ pub struct StatusChange { /// which run. #[serde(default, skip_serializing_if = "Option::is_none")] pub scan: Option, + /// Set when the finding's issue was closed or reopened in the issue + /// tracker (#953); `by_name` is the tracker user who did it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tracker: Option, } impl StatusChange { @@ -118,8 +122,45 @@ impl StatusChange { kind, scan_run_id: scan_run_id.to_string(), }), + tracker: None, } } + + /// The `by` of every change carried over from the issue tracker. + pub const TRACKER_ACTOR: &'static str = "pruefwerk-tracker"; + + /// A change carried over from the issue tracker, where the user `login` + /// closed or reopened the finding's issue. + /// + /// # Arguments + /// + /// * `status` - the status the finding moves to + /// * `kind` - what happened to the issue + /// * `login` - the tracker user who did it, shown as who changed it + pub fn by_tracker(status: FindingStatus, kind: TrackerChangeKind, login: &str) -> Self { + Self { + status, + by: Self::TRACKER_ACTOR.to_string(), + by_name: Some(login.to_string()), + support: false, + at: Utc::now(), + reason: None, + scan: None, + tracker: Some(kind), + } + } +} + +/// What happened to a finding's issue in the issue tracker that changed the +/// finding's status. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum TrackerChangeKind { + /// A person closed the issue: the finding counts as resolved until a + /// scan finds it again. + ClosedInTracker, + /// A person reopened the issue: the finding is undecided again. + ReopenedInTracker, } /// Why a scan changed a finding's status. @@ -309,6 +350,27 @@ impl Finding { mod tests { use super::*; + #[test] + fn a_tracker_change_names_the_tracker_user_and_no_scan() { + let change = StatusChange::by_tracker( + FindingStatus::Resolved, + TrackerChangeKind::ClosedInTracker, + "dev-anna", + ); + assert_eq!(change.by, StatusChange::TRACKER_ACTOR); + assert_eq!(change.by_name.as_deref(), Some("dev-anna")); + let wire = serde_json::to_value(&change).unwrap_or_default(); + assert_eq!(wire["tracker"], "closed_in_tracker"); + assert!(wire.get("scan").is_none()); + // A change stored before #953 has no `tracker` and still reads. + let mut old = wire.clone(); + if let Some(o) = old.as_object_mut() { + o.remove("tracker"); + } + let back: Option = serde_json::from_value(old).ok(); + assert!(back.is_some_and(|c| c.tracker.is_none())); + } + #[test] fn needs_review_reads_and_writes_as_needs_review() { let wire = serde_json::to_string(&FindingStatus::NeedsReview).unwrap_or_default(); diff --git a/compliance-core/src/models/issue.rs b/compliance-core/src/models/issue.rs index 8f1448a..30d5519 100644 --- a/compliance-core/src/models/issue.rs +++ b/compliance-core/src/models/issue.rs @@ -51,6 +51,10 @@ pub struct TrackerIssue { pub external_url: String, pub title: String, pub status: IssueStatus, + /// The tracker user who closed the issue there (#953), while it stays + /// closed: a person's decision the scan does not undo on its own. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub closed_in_tracker: Option, #[serde(with = "super::serde_helpers::bson_datetime")] pub created_at: DateTime, #[serde(with = "super::serde_helpers::bson_datetime")] @@ -74,6 +78,7 @@ impl TrackerIssue { external_url, title, status: IssueStatus::Open, + closed_in_tracker: None, created_at: now, updated_at: now, } diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index d80b6a4..3db5be3 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -46,6 +46,7 @@ pub use exclude_paths::{ }; pub use finding::{ Finding, FindingStatus, Occurrence, ScanChangeKind, ScanStatusChange, Severity, StatusChange, + TrackerChangeKind, }; pub use git_source::{GitSource, GitSourceView, SourceRepo, GIT_SOURCE_ID}; pub use graph::{ diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 95cc78b..3665e57 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -2233,6 +2233,22 @@ pub mod findings { } } + /// What happened to a finding's issue in the tracker, followed by the + /// tracker user's login. + pub fn tracker_change(kind: compliance_core::models::TrackerChangeKind) -> Text { + use compliance_core::models::TrackerChangeKind; + match kind { + TrackerChangeKind::ClosedInTracker => Text { + de: "Im Ticket geschlossen von", + en: "Closed in the ticket by", + }, + TrackerChangeKind::ReopenedInTracker => Text { + de: "Im Ticket wieder geöffnet von", + en: "Reopened in the ticket by", + }, + } + } + /// The name of the tool that reported a finding (`Finding::scanner`), in /// words; an unknown tool keeps its own name. pub fn tool_name(scanner: &str, lang: super::super::Lang) -> String { diff --git a/compliance-dashboard/src/pages/finding_detail.rs b/compliance-dashboard/src/pages/finding_detail.rs index 0e1e7d8..63d48df 100644 --- a/compliance-dashboard/src/pages/finding_detail.rs +++ b/compliance-dashboard/src/pages/finding_detail.rs @@ -392,6 +392,9 @@ pub fn FindingDetailPage(id: String) -> Element { if let Some(scan) = &change.scan { div { style: "color: var(--text-secondary);", {tx::scan_change(scan.kind).get(lang)} } } + if let Some(note) = tracker_note(change, lang) { + div { style: "color: var(--text-secondary);", "{note}" } + } if let Some(reason) = &change.reason { div { style: "color: var(--text-secondary);", "{tx::REASON.get(lang)}: {reason}" } } @@ -515,6 +518,18 @@ fn changed_by( format!("{} {short}", tx::SOMEONE.get(lang)) } +/// What happened to the finding's issue in the tracker, with the tracker +/// user who did it ("Im Ticket geschlossen von dev-anna"); `None` for a +/// change made in Prüfwerk. +fn tracker_note( + change: &compliance_core::models::finding::StatusChange, + lang: crate::i18n::Lang, +) -> Option { + let kind = change.tracker?; + let login = change.by_name.as_deref().unwrap_or_default(); + Some(format!("{} {login}", tx::tracker_change(kind).get(lang))) +} + #[cfg(test)] mod tests { use super::*; @@ -530,6 +545,7 @@ mod tests { at: chrono::Utc::now(), reason: None, scan: None, + tracker: None, } } @@ -568,6 +584,31 @@ mod tests { assert_eq!(changed_by(&c, &me(), Lang::En), "Prüfwerk scan"); } + #[test] + fn a_change_from_the_ticket_names_the_tracker_user() { + use compliance_core::models::TrackerChangeKind; + let c = StatusChange::by_tracker( + FindingStatus::Resolved, + TrackerChangeKind::ClosedInTracker, + "dev-anna", + ); + assert_eq!(changed_by(&c, &me(), Lang::De), "dev-anna"); + assert_eq!( + tracker_note(&c, Lang::De).as_deref(), + Some("Im Ticket geschlossen von dev-anna") + ); + let c = StatusChange::by_tracker( + FindingStatus::Open, + TrackerChangeKind::ReopenedInTracker, + "dev-anna", + ); + assert_eq!( + tracker_note(&c, Lang::En).as_deref(), + Some("Reopened in the ticket by dev-anna") + ); + assert!(tracker_note(&change("x", Some("y")), Lang::De).is_none()); + } + #[test] fn an_old_change_of_someone_else_shows_a_short_id() { let c = change("0b7d51aa-9f1c-4e33-8a1f-2d8c1e0f9a77", None); diff --git a/docs/guide/managed-git-en.md b/docs/guide/managed-git-en.md index 7a3a12b..6817933 100644 --- a/docs/guide/managed-git-en.md +++ b/docs/guide/managed-git-en.md @@ -31,6 +31,14 @@ of an organisation in that instance automatically: also gets the label `risk:accepted`, with the reason in the comment. When the finding comes back (the scan finds it again, or it is reopened), the issue is reopened. +- **The finding follows the issue.** When someone closes a Prüfwerk issue in + Gitea, a finding still open counts as resolved; its history reads "Closed + in the ticket by *Gitea user*". The next scan confirms that, or it finds the + finding again and reopens it and the issue with a comment. When the issue + is reopened in Gitea, the finding is open again. A decision already made in + Prüfwerk (an accepted risk, say) stays when the issue is closed. A CVE + issue someone closes stays closed while the scan finds the vulnerability + unchanged; it does not set a VEX status. - **Sync.** Every 30 minutes Prüfwerk compares the organisation's repositories with its targets, in case a webhook delivery was lost. @@ -72,7 +80,10 @@ PUT /api/v1/platform/tenants/{tenant_id}/git-source The response carries `webhook_url` and — only the first time, or with `"rotate_webhook_secret": true` — `webhook_secret`. With these, register an organisation or system webhook in Gitea (type Gitea, `application/json`) for -the **Repository** and **Push** events. A repeated `PUT` without `bot_token` +the **Repository**, **Push** and **Issues** events; the response names them in +`webhook_events`. Prüfwerk cannot create or change the webhook itself (the bot +has no administration rights): a webhook registered before issues synced back +needs the **Issues** event added in Gitea. A repeated `PUT` without `bot_token` keeps the stored token, and without `rotate_webhook_secret` the secret. `GET` returns the source without secrets; `DELETE` removes it and archives its targets. diff --git a/docs/guide/managed-git.md b/docs/guide/managed-git.md index fcacbe2..b413ceb 100644 --- a/docs/guide/managed-git.md +++ b/docs/guide/managed-git.md @@ -34,6 +34,15 @@ Repository-Organisation dieser Instanz automatisch prüfen: `risk:accepted`, mit der Begründung im Kommentar. Kommt der Befund wieder (die Prüfung findet ihn erneut, oder er wird wieder geöffnet), wird das Issue wieder geöffnet. +- **Der Befund folgt dem Issue.** Schließt jemand ein Prüfwerk-Issue in Gitea, + gilt ein noch offener Befund als behoben; im Verlauf steht „Im Ticket + geschlossen von *Gitea-Benutzer*“. Die nächste Prüfung bestätigt das, oder + sie findet den Befund erneut und öffnet ihn und das Issue mit Kommentar + wieder. Wird das Issue in Gitea wieder geöffnet, ist der Befund wieder + offen. Eine Entscheidung, die schon im Prüfwerk getroffen wurde (etwa ein + akzeptiertes Risiko), bleibt beim Schließen bestehen. Ein CVE-Issue, das + jemand schließt, bleibt geschlossen, solange die Prüfung die Schwachstelle + unverändert findet; einen VEX-Status setzt das nicht. - **Abgleich.** Alle 30 Minuten gleicht Prüfwerk die Repository-Liste der Organisation mit den Prüfobjekten ab, falls ein Webhook verloren ging. @@ -78,7 +87,11 @@ PUT /api/v1/platform/tenants/{tenant_id}/git-source Die Antwort enthält `webhook_url` und – nur beim ersten Mal oder mit `"rotate_webhook_secret": true` – `webhook_secret`. Damit wird in Gitea ein Organisations- oder System-Webhook (Typ Gitea, `application/json`) mit den -Ereignissen **Repository** und **Push** angelegt. Ein erneuter `PUT` ohne +Ereignissen **Repository**, **Push** und **Issues** angelegt; die Antwort +nennt sie in `webhook_events`. Prüfwerk kann den Webhook nicht selbst anlegen +oder ändern (der Bot hat keine Administrationsrechte): Bei einem Webhook, der +vor dem Abgleich der Issues angelegt wurde, muss das Ereignis **Issues** in +Gitea nachgetragen werden. Ein erneuter `PUT` ohne `bot_token` behält das gespeicherte Token, ohne `rotate_webhook_secret` das Secret. `GET` liefert die Quelle ohne Geheimnisse, `DELETE` entfernt sie und archiviert ihre Prüfobjekte.