feat(issues): a tracker issue follows its finding's status
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 10m44s

#444 opens an issue per finding in the managed repository, but nothing
updated it afterwards. Now, when a finding's status changes, by a person
(single or bulk) or by the scan (#443 closes and reopens), its issue
follows, in the background:
- resolved, false positive (rule or mapping) or ignored: a comment with
  the reason, then closed;
- accepted risk: the comment (with the person's reason) and, on Gitea,
  the new `risk:accepted` label, then closed;
- open, triaged or needs review again: reopened with a comment.

The sync reads the finding's current status when it runs, so a change in
between wins, and does nothing when the issue already matches. Comments
are German then English, like the labels. build_tracker is now a free
function the API can use; TrackerDispatch gains update_issue_status and
add_comment; GiteaTracker gains add_labels.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
This commit is contained in:
Sharang ParnerkarandClaude Opus 5.5 committed 2026-10-05 16:02:34 +02:00
1 parent 04d0ad5113
commit 8fff28b2db
11 files changed
+712 -79

No files matched your search

+17 -1
View File
@@ -190,6 +190,20 @@ fn status_update(
})
}
/// The issue sync for status changes in the tenant database `db`: a closed
/// finding closes its issue, a reopened one reopens it.
fn issue_sync(
agent: &crate::agent::ComplianceAgent,
db: crate::database::Database,
) -> crate::pipeline::issue_sync::IssueSync {
crate::pipeline::issue_sync::IssueSync {
db,
config: agent.config.clone(),
secrets: agent.secrets.clone(),
net_guard: agent.net_guard,
}
}
/// PATCH /api/v1/findings/{id}/status — change the status, recording who,
/// when and why. 404 when there is no such finding.
#[tracing::instrument(skip_all, fields(finding_id = %id))]
@@ -211,6 +225,7 @@ pub async fn update_finding_status(
if result.matched_count == 0 {
return Err(StatusCode::NOT_FOUND);
}
issue_sync(&agent, db).spawn(vec![oid]);
Ok(Json(serde_json::json!({ "status": "updated" })))
}
@@ -236,9 +251,10 @@ pub async fn bulk_update_finding_status(
let db = tenant_db(&agent, &tenant).await?;
let result = db
.findings()
.update_many(doc! { "_id": { "$in": oids } }, update)
.update_many(doc! { "_id": { "$in": oids.clone() } }, update)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
issue_sync(&agent, db).spawn(oids);
Ok(Json(
serde_json::json!({ "status": "updated", "modified_count": result.modified_count }),
+11 -2
View File
@@ -33,6 +33,8 @@ pub struct RunFindings {
/// Scanners (`Finding::scanner`) that completed in this run, so their
/// findings this run did not see are gone from the code.
completed: HashSet<String>,
/// Findings this run closed or reopened, for their issues.
status_changed: Vec<ObjectId>,
}
/// Statuses a scan may close: nobody has decided about the finding yet. A
@@ -52,6 +54,7 @@ impl RunFindings {
inserted: HashMap::new(),
earlier: HashSet::new(),
completed: HashSet::new(),
status_changed: Vec::new(),
}
}
@@ -257,7 +260,7 @@ impl RunFindings {
///
/// A database error.
pub async fn resolve_missing(
&self,
&mut self,
db: &Database,
target_id: &str,
vendor: &[String],
@@ -318,7 +321,7 @@ impl RunFindings {
/// with a history entry saying this run did it and why. The `from` guard
/// leaves alone a finding a person changed in the meantime.
async fn set_status(
&self,
&mut self,
db: &Database,
ids: &[ObjectId],
from: &[&str],
@@ -330,6 +333,7 @@ impl RunFindings {
}
let change = bson_of(&StatusChange::by_scan(to.clone(), kind, &self.scan_run_id))?;
let to = bson_of(&to)?;
self.status_changed.extend_from_slice(ids);
for chunk in ids.chunks(UPDATE_CHUNK) {
db.findings()
.update_many(
@@ -344,6 +348,11 @@ impl RunFindings {
Ok(())
}
/// The findings this run closed or reopened (their issues follow).
pub fn status_changed(&self) -> &[ObjectId] {
&self.status_changed
}
/// Give each finding this run saved its row id.
fn stamp_ids(&self, findings: &mut [Finding]) {
for finding in findings.iter_mut() {
+82 -67
View File
@@ -12,73 +12,7 @@ impl PipelineOrchestrator {
/// Build an issue tracker client from a repository's tracker configuration.
/// Returns `None` if the repo has no tracker configured.
pub(super) fn build_tracker(&self, repo: &RepoView) -> Option<TrackerDispatch> {
let tracker_type = repo.tracker_type.as_ref()?;
// Per-repo token takes precedence, fall back to global config
match tracker_type {
TrackerType::GitHub => {
let token = repo.tracker_token.clone().or_else(|| {
self.config.github_token.as_ref().map(|t| {
use secrecy::ExposeSecret;
t.expose_secret().to_string()
})
})?;
let secret = secrecy::SecretString::from(token);
match trackers::github::GitHubTracker::new(&secret) {
Ok(t) => Some(TrackerDispatch::GitHub(t)),
Err(e) => {
tracing::warn!("Failed to build GitHub tracker: {e}");
None
}
}
}
TrackerType::GitLab => {
let base_url = self
.config
.gitlab_url
.clone()
.unwrap_or_else(|| "https://gitlab.com".to_string());
let token = repo.tracker_token.clone().or_else(|| {
self.config.gitlab_token.as_ref().map(|t| {
use secrecy::ExposeSecret;
t.expose_secret().to_string()
})
})?;
let secret = secrecy::SecretString::from(token);
Some(TrackerDispatch::GitLab(
trackers::gitlab::GitLabTracker::new(base_url, secret),
))
}
TrackerType::Gitea => {
let token = repo.tracker_token.clone()?;
let base_url = extract_base_url(&repo.git_url)?;
let secret = secrecy::SecretString::from(token);
match trackers::gitea::GiteaTracker::new(base_url, secret, self.net_guard) {
Ok(t) => Some(TrackerDispatch::Gitea(t)),
Err(e) => {
tracing::warn!("Failed to build Gitea tracker: {e}");
None
}
}
}
TrackerType::Jira => {
let base_url = self.config.jira_url.clone()?;
let email = self.config.jira_email.clone()?;
let project_key = self.config.jira_project_key.clone()?;
let token = repo.tracker_token.clone().or_else(|| {
self.config.jira_api_token.as_ref().map(|t| {
use secrecy::ExposeSecret;
t.expose_secret().to_string()
})
})?;
let secret = secrecy::SecretString::from(token);
Some(TrackerDispatch::Jira(trackers::jira::JiraTracker::new(
base_url,
email,
secret,
project_key,
)))
}
}
build_tracker(&self.config, self.net_guard, repo)
}
/// Create tracker issues for new findings (severity >= Medium).
@@ -266,6 +200,87 @@ impl PipelineOrchestrator {
}
}
/// Build an issue tracker client from a repository's tracker configuration.
/// Returns `None` if the repo has no tracker configured.
///
/// # Arguments
///
/// * `config` - the agent configuration (global tracker tokens and URLs)
/// * `net_guard` - where a self-hosted tracker may connect
/// * `repo` - the target, with its own tracker settings and token
pub(crate) fn build_tracker(
config: &compliance_core::AgentConfig,
net_guard: compliance_core::NetGuard,
repo: &RepoView,
) -> Option<TrackerDispatch> {
let tracker_type = repo.tracker_type.as_ref()?;
// Per-repo token takes precedence, fall back to global config
match tracker_type {
TrackerType::GitHub => {
let token = repo.tracker_token.clone().or_else(|| {
config.github_token.as_ref().map(|t| {
use secrecy::ExposeSecret;
t.expose_secret().to_string()
})
})?;
let secret = secrecy::SecretString::from(token);
match trackers::github::GitHubTracker::new(&secret) {
Ok(t) => Some(TrackerDispatch::GitHub(t)),
Err(e) => {
tracing::warn!("Failed to build GitHub tracker: {e}");
None
}
}
}
TrackerType::GitLab => {
let base_url = config
.gitlab_url
.clone()
.unwrap_or_else(|| "https://gitlab.com".to_string());
let token = repo.tracker_token.clone().or_else(|| {
config.gitlab_token.as_ref().map(|t| {
use secrecy::ExposeSecret;
t.expose_secret().to_string()
})
})?;
let secret = secrecy::SecretString::from(token);
Some(TrackerDispatch::GitLab(
trackers::gitlab::GitLabTracker::new(base_url, secret),
))
}
TrackerType::Gitea => {
let token = repo.tracker_token.clone()?;
let base_url = extract_base_url(&repo.git_url)?;
let secret = secrecy::SecretString::from(token);
match trackers::gitea::GiteaTracker::new(base_url, secret, net_guard) {
Ok(t) => Some(TrackerDispatch::Gitea(t)),
Err(e) => {
tracing::warn!("Failed to build Gitea tracker: {e}");
None
}
}
}
TrackerType::Jira => {
let base_url = config.jira_url.clone()?;
let email = config.jira_email.clone()?;
let project_key = config.jira_project_key.clone()?;
let token = repo.tracker_token.clone().or_else(|| {
config.jira_api_token.as_ref().map(|t| {
use secrecy::ExposeSecret;
t.expose_secret().to_string()
})
})?;
let secret = secrecy::SecretString::from(token);
Some(TrackerDispatch::Jira(trackers::jira::JiraTracker::new(
base_url,
email,
secret,
project_key,
)))
}
}
}
/// Format a finding into a markdown issue body for the tracker.
pub(super) fn format_issue_body(finding: &Finding) -> String {
let mut body = String::new();
+485
View File
@@ -0,0 +1,485 @@
//! A finding's status, carried over to the issue opened for it.
//!
//! When a finding is closed in Prüfwerk (fixed, a false alarm, set aside, or
//! an accepted risk) its issue in the repository is closed with a comment
//! saying why; an accepted risk also gets the `risk:accepted` label on Gitea.
//! A finding that comes back (the scan finds it again, or a person reopens it)
//! reopens its issue. The sync reads each finding's status when it runs, so a
//! change made in between is the one carried over.
use mongodb::bson::{doc, oid::ObjectId};
use compliance_core::models::{
FindingStatus, IssueStatus, OnboardedTarget, ScanChangeKind, StatusChange, TrackerIssue,
};
use compliance_core::{AgentConfig, NetGuard};
use crate::database::Database;
use crate::pipeline::issue_creation::build_tracker;
use crate::pipeline::repo_view::RepoView;
use crate::pipeline::tracker_dispatch::TrackerDispatch;
use crate::secrets::SecretBox;
use crate::trackers::gitea::{pruefwerk_labels, LABEL_ACCEPTED_RISK};
/// What the sync needs from the agent, owned so it can run in the background.
#[derive(Clone)]
pub(crate) struct IssueSync {
pub db: Database,
pub config: AgentConfig,
pub secrets: SecretBox,
pub net_guard: NetGuard,
}
/// What a finding's status means for its issue.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum IssueAction {
/// Close it; `accepted_risk` also labels it.
Close {
accepted_risk: bool,
},
Reopen,
}
impl IssueAction {
/// The action for a finding with `status`.
fn for_status(status: &FindingStatus) -> Self {
match status {
FindingStatus::Open | FindingStatus::Triaged | FindingStatus::NeedsReview => {
Self::Reopen
}
FindingStatus::AcceptedRisk => Self::Close {
accepted_risk: true,
},
FindingStatus::Resolved
| FindingStatus::FalsePositive
| FindingStatus::WrongMapping
| FindingStatus::Ignored => Self::Close {
accepted_risk: false,
},
}
}
/// Whether the issue, in `status`, already reflects this action.
fn done(self, status: &IssueStatus) -> bool {
let closed = matches!(status, IssueStatus::Closed | IssueStatus::Resolved);
match self {
Self::Close { .. } => closed,
Self::Reopen => !closed,
}
}
}
impl IssueSync {
/// Carry the current status of the findings `ids` over to their issues,
/// in the background. Findings without an issue are skipped; a tracker
/// that cannot be reached is logged, and the next change tries again.
pub(crate) fn spawn(self, ids: Vec<ObjectId>) {
if ids.is_empty() {
return;
}
tokio::spawn(async move {
for id in ids {
if let Err(e) = self.sync_one(id).await {
tracing::warn!(finding = %id, error = %e, "issue status not synced");
}
}
});
}
/// Carry the status of finding `id` over to its issue, if it has one.
async fn sync_one(&self, id: ObjectId) -> Result<(), String> {
let Some(issue) = self
.db
.tracker_issues()
.find_one(doc! { "finding_id": id.to_hex() })
.await
.map_err(|e| e.to_string())?
else {
return Ok(());
};
let finding = self
.db
.findings()
.find_one(doc! { "_id": id })
.await
.map_err(|e| e.to_string())?
.ok_or("finding gone")?;
let action = IssueAction::for_status(&finding.status);
if action.done(&issue.status) {
return Ok(());
}
let target_id = ObjectId::parse_str(&finding.repo_id).map_err(|e| e.to_string())?;
let target: OnboardedTarget = self
.db
.onboarded_targets()
.find_one(doc! { "_id": target_id })
.await
.map_err(|e| e.to_string())?
.ok_or("target gone")?;
let code = target
.code_artifact()
.ok_or("target has no code artifact")?;
let repo = RepoView::from_target(&target, code, &self.secrets);
let tracker =
build_tracker(&self.config, self.net_guard, &repo).ok_or("no tracker configured")?;
let (Some(owner), Some(name)) =
(repo.tracker_owner.as_deref(), repo.tracker_repo.as_deref())
else {
return Err("tracker owner or repository not set".into());
};
let comment = comment(&finding.status, finding.status_history.last());
let number = issue.external_id.as_str();
tracker
.add_comment(owner, name, number, &comment)
.await
.map_err(|e| e.to_string())?;
if let IssueAction::Close {
accepted_risk: true,
} = action
{
label_accepted_risk(&tracker, owner, name, number).await;
}
let (state, status) = match action {
IssueAction::Close { .. } => ("closed", IssueStatus::Closed),
IssueAction::Reopen => ("open", IssueStatus::Open),
};
tracker
.update_issue_status(owner, name, number, state)
.await
.map_err(|e| e.to_string())?;
self.record(&issue, status).await
}
/// Store the issue's new state.
async fn record(&self, issue: &TrackerIssue, status: IssueStatus) -> Result<(), String> {
let Some(id) = issue.id else {
return Ok(());
};
let status = mongodb::bson::to_bson(&status).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() } },
)
.await
.map(drop)
.map_err(|e| e.to_string())
}
}
/// Put the `risk:accepted` label on a Gitea issue. Other trackers keep only
/// the comment; a label that cannot be set does not stop the close.
async fn label_accepted_risk(tracker: &TrackerDispatch, owner: &str, repo: &str, number: &str) {
let TrackerDispatch::Gitea(gitea) = tracker else {
return;
};
let labelled = async {
let ids = gitea
.ensure_labels(owner, repo, &pruefwerk_labels())
.await?;
let label: Vec<i64> = ids.get(LABEL_ACCEPTED_RISK).copied().into_iter().collect();
gitea.add_labels(owner, repo, number, &label).await
};
if let Err(e) = labelled.await {
tracing::warn!(error = %e, "could not label the accepted risk");
}
}
/// The comment explaining a change to `status`, German then English like the
/// labels, with the reason a person or the scan gave.
fn comment(status: &FindingStatus, change: Option<&StatusChange>) -> String {
let by_scan = change.and_then(|c| c.scan.as_ref()).map(|s| s.kind);
let (de, en) = match (status, by_scan) {
(FindingStatus::Resolved, Some(ScanChangeKind::NoLongerFound)) => (
"Bei der Prüfung nicht mehr gefunden, daher als behoben markiert.",
"No longer found by the scan, so marked resolved.",
),
(FindingStatus::Resolved, Some(ScanChangeKind::NowVendorCode)) => (
"Die Datei gilt jetzt als Herstellercode und ist von den Befunden ausgenommen.",
"The file now counts as vendor code, which is left out of the findings.",
),
(FindingStatus::Resolved, _) => (
"In Prüfwerk als behoben markiert.",
"Marked resolved in Prüfwerk.",
),
(FindingStatus::FalsePositive, _) => (
"In Prüfwerk als Fehlalarm (Regel) markiert.",
"Marked a false positive (rule) in Prüfwerk.",
),
(FindingStatus::WrongMapping, _) => (
"In Prüfwerk als Fehlalarm (Zuordnung) markiert: Die CRA-Anforderung trifft nicht zu.",
"Marked a false positive (mapping) in Prüfwerk: the CRA requirement does not apply.",
),
(FindingStatus::Ignored, _) => ("In Prüfwerk ignoriert.", "Ignored in Prüfwerk."),
(FindingStatus::AcceptedRisk, _) => (
"In Prüfwerk als akzeptiertes Risiko geschlossen, nicht behoben.",
"Closed in Prüfwerk as an accepted risk, not fixed.",
),
(_, Some(ScanChangeKind::FoundAgain)) => (
"Bei der Prüfung erneut gefunden, daher wieder geöffnet.",
"Found again by the scan, so reopened.",
),
_ => ("In Prüfwerk wieder geöffnet.", "Reopened in Prüfwerk."),
};
let mut text = format!("**Prüfwerk:** {de}\n\n{en}");
if let Some(reason) = change
.and_then(|c| c.reason.as_deref())
.filter(|r| !r.trim().is_empty())
{
text.push_str(&format!("\n\n> {}", reason.trim().replace('\n', "\n> ")));
}
text
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use std::sync::{Arc, Mutex};
use axum::extract::{Path, State};
use axum::routing::{get, patch, post};
use axum::{Json, Router};
use compliance_core::models::{
Artifact, Finding, IssueTrackerConfig, ScanType, Severity, TargetType, TrackerType,
};
/// The calls a fake Gitea received, as `"<what> <issue>: <detail>"`.
type Calls = Arc<Mutex<Vec<String>>>;
async fn fake_gitea(calls: Calls) -> String {
async fn labels() -> Json<serde_json::Value> {
// Every Prüfwerk label exists already; risk:accepted is id 42.
Json(serde_json::json!(pruefwerk_labels()
.iter()
.enumerate()
.map(|(i, l)| serde_json::json!({
"id": if l.name == LABEL_ACCEPTED_RISK { 42 } else { i as i64 },
"name": l.name,
"color": "ffffff",
}))
.collect::<Vec<_>>()))
}
async fn comment(
State(calls): State<Calls>,
Path((_o, _r, n)): Path<(String, String, String)>,
Json(body): Json<serde_json::Value>,
) -> axum::http::StatusCode {
let text = body["body"].as_str().unwrap_or_default();
calls.lock().unwrap().push(format!("comment {n}: {text}"));
axum::http::StatusCode::CREATED
}
async fn state(
State(calls): State<Calls>,
Path((_o, _r, n)): Path<(String, String, String)>,
Json(body): Json<serde_json::Value>,
) -> Json<serde_json::Value> {
calls
.lock()
.unwrap()
.push(format!("state {n}: {}", body["state"]));
Json(serde_json::json!({}))
}
async fn add_labels(
State(calls): State<Calls>,
Path((_o, _r, n)): Path<(String, String, String)>,
Json(body): Json<serde_json::Value>,
) -> Json<serde_json::Value> {
calls
.lock()
.unwrap()
.push(format!("labels {n}: {}", body["labels"]));
Json(serde_json::json!([]))
}
let app = Router::new()
.route("/api/v1/repos/{o}/{r}/labels", get(labels))
.route("/api/v1/repos/{o}/{r}/issues/{n}/comments", post(comment))
.route("/api/v1/repos/{o}/{r}/issues/{n}", patch(state))
.route("/api/v1/repos/{o}/{r}/issues/{n}/labels", post(add_labels))
.with_state(calls);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
format!("http://{addr}")
}
#[tokio::test]
async fn an_issue_follows_its_findings_status() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!("isync_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP issue_sync: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id("issue-sync").await.unwrap();
let calls: Calls = Arc::default();
let base = fake_gitea(calls.clone()).await;
// Arrange: a managed repository's target, a finding and its issue #12.
let mut target = OnboardedTarget::new("fw".into(), TargetType::BackendService);
target
.artifacts
.push(Artifact::git_repo(format!("{base}/kunde/fw.git"), "main"));
target.scan_config.issue_tracker = Some(IssueTrackerConfig {
tracker_type: Some(TrackerType::Gitea),
owner: Some("kunde".into()),
repo: Some("fw".into()),
token: Some("bot-token".into()),
});
let target_id = db
.onboarded_targets()
.insert_one(&target)
.await
.unwrap()
.inserted_id
.as_object_id()
.unwrap();
let mut finding = Finding::new(
target_id.to_hex(),
"fp-1".into(),
"semgrep".into(),
ScanType::Sast,
"strcpy".into(),
"d".into(),
Severity::High,
);
finding.status = FindingStatus::Resolved;
finding.status_history.push(StatusChange::by_scan(
FindingStatus::Resolved,
ScanChangeKind::NoLongerFound,
"run-1",
));
let finding_id = 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(),
format!("{base}/kunde/fw/issues/12"),
"strcpy".into(),
);
db.tracker_issues().insert_one(&issue).await.unwrap();
let sync = IssueSync {
db: db.clone(),
config: AgentConfig::default(),
secrets: SecretBox::without_key(),
net_guard: NetGuard::allow_private(),
};
let issue_status = || async {
db.tracker_issues()
.find_one(doc! { "finding_id": finding_id.to_hex() })
.await
.unwrap()
.unwrap()
.status
};
// Act + assert: the scan closed it, so the issue closes with a comment.
sync.sync_one(finding_id).await.unwrap();
assert_eq!(issue_status().await, IssueStatus::Closed);
{
let calls = calls.lock().unwrap();
assert!(calls[0]
.starts_with("comment 12: **Prüfwerk:** Bei der Prüfung nicht mehr gefunden"));
assert_eq!(calls[1], "state 12: \"closed\"");
}
// Synced again with no change: nothing more is sent.
sync.sync_one(finding_id).await.unwrap();
assert_eq!(calls.lock().unwrap().len(), 2);
// It comes back: the issue reopens.
db.findings()
.update_one(
doc! { "_id": finding_id },
doc! { "$set": { "status": "open" } },
)
.await
.unwrap();
sync.sync_one(finding_id).await.unwrap();
assert_eq!(issue_status().await, IssueStatus::Open);
assert_eq!(calls.lock().unwrap().last().unwrap(), "state 12: \"open\"");
// A person accepts the risk: labelled, then closed.
db.findings()
.update_one(
doc! { "_id": finding_id },
doc! { "$set": { "status": "accepted_risk" } },
)
.await
.unwrap();
sync.sync_one(finding_id).await.unwrap();
{
let calls = calls.lock().unwrap();
let tail: Vec<&str> = calls.iter().rev().take(2).map(String::as_str).collect();
assert_eq!(tail, ["state 12: \"closed\"", "labels 12: [42]"]);
}
pool.drop_tenant("issue-sync").await.ok();
}
fn by_scan(status: FindingStatus, kind: ScanChangeKind) -> StatusChange {
StatusChange::by_scan(status, kind, "run-1")
}
#[test]
fn closing_statuses_close_and_open_ones_reopen() {
assert_eq!(
IssueAction::for_status(&FindingStatus::Resolved),
IssueAction::Close {
accepted_risk: false
}
);
assert_eq!(
IssueAction::for_status(&FindingStatus::AcceptedRisk),
IssueAction::Close {
accepted_risk: true
}
);
assert_eq!(
IssueAction::for_status(&FindingStatus::NeedsReview),
IssueAction::Reopen
);
// Nothing to do when the issue already matches.
assert!(IssueAction::Reopen.done(&IssueStatus::Open));
assert!(IssueAction::Close {
accepted_risk: false
}
.done(&IssueStatus::Closed));
assert!(!IssueAction::Reopen.done(&IssueStatus::Closed));
}
#[test]
fn the_comment_says_why_in_german_and_english() {
let fixed = comment(
&FindingStatus::Resolved,
Some(&by_scan(
FindingStatus::Resolved,
ScanChangeKind::NoLongerFound,
)),
);
assert!(fixed.contains("nicht mehr gefunden") && fixed.contains("No longer found"));
let back = comment(
&FindingStatus::Open,
Some(&by_scan(FindingStatus::Open, ScanChangeKind::FoundAgain)),
);
assert!(back.contains("erneut gefunden"));
let mut risk = by_scan(FindingStatus::AcceptedRisk, ScanChangeKind::NoLongerFound);
risk.scan = None;
risk.reason = Some("Only reachable on the isolated machine network.".into());
let accepted = comment(&FindingStatus::AcceptedRisk, Some(&risk));
assert!(accepted.contains("akzeptiertes Risiko"));
assert!(accepted.ends_with("> Only reachable on the isolated machine network."));
}
}
+1
View File
@@ -10,6 +10,7 @@ pub mod git_submodules;
pub mod gitleaks;
mod graph_build;
mod issue_creation;
pub(crate) mod issue_sync;
pub mod languages;
pub mod lint;
pub mod mobsfscan;
@@ -577,6 +577,14 @@ impl PipelineOrchestrator {
run_findings
.resolve_missing(&self.db, &repo_id, &vendor)
.await?;
// Their issues follow: closed with a comment, or reopened.
crate::pipeline::issue_sync::IssueSync {
db: self.db.clone(),
config: self.config.clone(),
secrets: self.secrets.clone(),
net_guard: self.net_guard,
}
.spawn(run_findings.status_changed().to_vec());
// Replace this stage's SBOM entries (not the firmware or CODESYS ones,
// which their own steps own). Entries store the target id as a hex
@@ -37,6 +37,50 @@ impl TrackerDispatch {
}
}
/// Open or close the issue `external_id` (`"open"`, `"closed"`).
pub(crate) async fn update_issue_status(
&self,
owner: &str,
repo: &str,
external_id: &str,
status: &str,
) -> Result<(), compliance_core::error::CoreError> {
match self {
Self::GitHub(t) => {
t.update_issue_status(owner, repo, external_id, status)
.await
}
Self::GitLab(t) => {
t.update_issue_status(owner, repo, external_id, status)
.await
}
Self::Gitea(t) => {
t.update_issue_status(owner, repo, external_id, status)
.await
}
Self::Jira(t) => {
t.update_issue_status(owner, repo, external_id, status)
.await
}
}
}
/// Comment `body` on the issue `external_id`.
pub(crate) async fn add_comment(
&self,
owner: &str,
repo: &str,
external_id: &str,
body: &str,
) -> Result<(), compliance_core::error::CoreError> {
match self {
Self::GitHub(t) => t.add_comment(owner, repo, external_id, body).await,
Self::GitLab(t) => t.add_comment(owner, repo, external_id, body).await,
Self::Gitea(t) => t.add_comment(owner, repo, external_id, body).await,
Self::Jira(t) => t.add_comment(owner, repo, external_id, body).await,
}
}
pub(crate) async fn find_existing_issue(
&self,
owner: &str,
+46 -4
View File
@@ -126,6 +126,38 @@ impl GiteaTracker {
Ok(ids)
}
/// Attach the labels `label_ids` to the existing issue `external_id`.
///
/// # Errors
///
/// [`CoreError::IssueTracker`] if Gitea cannot be reached or refuses.
pub async fn add_labels(
&self,
owner: &str,
repo: &str,
external_id: &str,
label_ids: &[i64],
) -> Result<(), CoreError> {
let url = self.api_url(&format!(
"/repos/{owner}/{repo}/issues/{external_id}/labels"
));
let resp = self
.http
.post(&url)
.header("Authorization", self.auth())
.json(&serde_json::json!({ "labels": label_ids }))
.send()
.await
.map_err(|e| CoreError::IssueTracker(format!("Gitea add labels failed: {e}")))?;
if !resp.status().is_success() {
return Err(CoreError::IssueTracker(format!(
"Gitea add labels returned {}",
resp.status()
)));
}
Ok(())
}
/// Create an issue with the given labels attached by id (see
/// [`Self::ensure_labels`]).
///
@@ -227,6 +259,10 @@ pub const LABEL_CRA_ANNEX_I: &str = "cra:annex-i";
/// The labels of a managed repository (#439): `pruefwerk`, `cra:annex-i` and
/// one `severity:*` per severity that gets an issue.
/// The label of an issue whose finding is an accepted risk (closed in
/// Prüfwerk with a reason, not fixed).
pub const LABEL_ACCEPTED_RISK: &str = "risk:accepted";
pub fn pruefwerk_labels() -> Vec<LabelSpec> {
vec![
LabelSpec::new(
@@ -247,6 +283,11 @@ pub fn pruefwerk_labels() -> Vec<LabelSpec> {
LabelSpec::new("severity:high", "#d93f0b", "Schweregrad hoch / high"),
LabelSpec::new("severity:medium", "#fbca04", "Schweregrad mittel / medium"),
LabelSpec::new("severity:low", "#0e8a16", "Schweregrad niedrig / low"),
LabelSpec::new(
LABEL_ACCEPTED_RISK,
"#5319e7",
"Risiko akzeptiert, nicht behoben / accepted risk, not fixed",
),
]
}
@@ -522,7 +563,8 @@ mod tests {
"severity:critical",
"severity:high",
"severity:medium",
"severity:low"
"severity:low",
"risk:accepted"
]
);
assert!(wanted
@@ -589,13 +631,13 @@ mod tests {
let wanted = pruefwerk_labels();
let ids = tracker.ensure_labels("kunde", "fw", &wanted).await.unwrap();
assert_eq!(ids.len(), 6);
assert_eq!(ids.len(), 7);
assert_eq!(ids["pruefwerk"], 7);
assert_eq!(labels.lock().unwrap().len(), 6);
assert_eq!(labels.lock().unwrap().len(), 7);
// A second run finds them all and creates nothing.
let again = tracker.ensure_labels("kunde", "fw", &wanted).await.unwrap();
assert_eq!(again, ids);
assert_eq!(labels.lock().unwrap().len(), 6);
assert_eq!(labels.lock().unwrap().len(), 7);
}
}
+1 -1
View File
@@ -77,7 +77,7 @@ async fn a_scan_closes_what_it_no_longer_finds_and_reopens_what_returns() {
.unwrap();
// A run in which no scanner completed closes nothing.
let idle = RunFindings::new("run-idle");
let mut idle = RunFindings::new("run-idle");
assert_eq!(idle.resolve_missing(&db, TARGET, &[]).await.unwrap(), 0);
// Act: semgrep completes and reports only fp-kept.
+8 -2
View File
@@ -17,8 +17,14 @@ of an organisation in that instance automatically:
- **Findings as issues.** Findings of severity medium and above become issues
in the repository, with location, CWE, the CRA requirement concerned, the
remediation and a link into Prüfwerk. Prüfwerk creates the labels
`pruefwerk`, `cra:annex-i` and `severity:critical|high|medium|low` in the
repository for them.
`pruefwerk`, `cra:annex-i`, `severity:critical|high|medium|low` and
`risk:accepted` in the repository for them.
- **The issue follows the finding.** When the finding is closed in Prüfwerk —
the scan no longer finds it, or someone marks it resolved, a false alarm or
ignored — Prüfwerk comments on the issue why and closes it. An accepted risk
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.
- **Sync.** Every 30 minutes Prüfwerk compares the organisation's repositories
with its targets, in case a webhook delivery was lost.
+9 -2
View File
@@ -18,8 +18,15 @@ Repository-Organisation dieser Instanz automatisch prüfen:
- **Befunde als Issues.** Befunde ab Schweregrad „mittel“ erscheinen als Issue
im Repository, mit Fundstelle, CWE, der betroffenen CRA-Anforderung, der
Maßnahme und einem Link ins Prüfwerk. Prüfwerk legt dazu die Labels
`pruefwerk`, `cra:annex-i` und `severity:critical|high|medium|low` im
Repository an.
`pruefwerk`, `cra:annex-i`, `severity:critical|high|medium|low` und
`risk:accepted` im Repository an.
- **Das Issue folgt dem Befund.** Wird der Befund im Prüfwerk geschlossen –
die Prüfung findet ihn nicht mehr, oder jemand setzt ihn auf behoben,
Fehlalarm oder ignoriert –, kommentiert Prüfwerk im Issue den Grund und
schließt es. Ein akzeptiertes Risiko bekommt zusätzlich das Label
`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.
- **Abgleich.** Alle 30 Minuten gleicht Prüfwerk die Repository-Liste der
Organisation mit den Prüfobjekten ab, falls ein Webhook verloren ging.