feat(issues): poll Gitea for issues a person closed or reopened (#953) #972
No files matched your search
@@ -13,7 +13,7 @@
|
||||
//! ([`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
|
||||
//! event (or the poll, [`crate::pipeline::issue_poll`]) 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;
|
||||
@@ -94,11 +94,40 @@ pub(crate) async fn apply(
|
||||
target_id: &str,
|
||||
event: &IssueEvent,
|
||||
) -> Result<BackSynced, AgentError> {
|
||||
let Some(issue) = find_issue(db, target_id, event.number).await? else {
|
||||
apply_change(db, target_id, event.number, event.change, &event.sender).await
|
||||
}
|
||||
|
||||
/// Carry a close or reopen of issue `number` back for target `target_id`,
|
||||
/// however it was learnt: a webhook delivery ([`apply`]) or the poll
|
||||
/// ([`crate::pipeline::issue_poll`]).
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `db` - the tenant database
|
||||
/// * `target_id` - the target of the issue's repository
|
||||
/// * `number` - the issue number in that repository
|
||||
/// * `change` - closed or reopened
|
||||
/// * `sender` - the login of the person who did it, not Prüfwerk's bot
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// What was changed.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// A database error.
|
||||
pub(crate) async fn apply_change(
|
||||
db: &Database,
|
||||
target_id: &str,
|
||||
number: i64,
|
||||
change: IssueChange,
|
||||
sender: &str,
|
||||
) -> Result<BackSynced, AgentError> {
|
||||
let Some(issue) = find_issue(db, target_id, number).await? else {
|
||||
return Ok(BackSynced::NotOurs);
|
||||
};
|
||||
let (status, closed_by) = match event.change {
|
||||
IssueChange::Closed => (IssueStatus::Closed, Some(event.sender.as_str())),
|
||||
let (status, closed_by) = match change {
|
||||
IssueChange::Closed => (IssueStatus::Closed, Some(sender)),
|
||||
IssueChange::Reopened => (IssueStatus::Open, None),
|
||||
};
|
||||
// The issue first: once it reads closed, a status sync running meanwhile
|
||||
@@ -121,21 +150,21 @@ pub(crate) async fn apply(
|
||||
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 (new, kind) = new_status(change);
|
||||
let history = StatusChange::by_tracker(new.clone(), kind, 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! { "_id": finding_id, "status": statuses_changed_by(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)? },
|
||||
"$push": { "status_history": to_bson(&history).map_err(to_bson_err)? },
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -298,6 +298,7 @@ mod tests {
|
||||
body: Some(format_issue_body(finding)),
|
||||
html_url: format!("https://gitea.invalid/o/r/issues/{number}"),
|
||||
state: "open".into(),
|
||||
user: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -819,6 +819,7 @@ mod tests {
|
||||
body: body.map(str::to_string),
|
||||
html_url: format!("https://gitea.invalid/o/r/issues/{number}"),
|
||||
state: "open".into(),
|
||||
user: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,455 @@
|
||||
//! Issues closed or reopened in Gitea, learnt by polling (#953).
|
||||
//!
|
||||
//! The back-sync ([`super::issue_backsync`]) first came from the managed git
|
||||
//! source's organisation webhook. Most targets have no such webhook: they are
|
||||
//! repositories with a Gitea issue tracker. So at every sync interval the poll
|
||||
//! lists the issues of each target that has Prüfwerk issues (one listing per
|
||||
//! repository, as a scan makes), compares their state with Prüfwerk's records
|
||||
//! and, for each that differs, reads from the issue's timeline who closed or
|
||||
//! reopened it. A person's change is carried back as a webhook delivery is;
|
||||
//! Prüfwerk's own (its bot user opened the issue) is left alone. Where a
|
||||
//! webhook delivered the change already, the records match and the poll has
|
||||
//! nothing to do.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use futures_util::TryStreamExt;
|
||||
use mongodb::bson::{doc, Bson};
|
||||
|
||||
use compliance_core::models::issue::cve_issue_prefix;
|
||||
use compliance_core::models::{OnboardedTarget, TrackerIssue, TrackerType};
|
||||
use compliance_core::{AgentConfig, NetGuard};
|
||||
|
||||
use crate::agent::ComplianceAgent;
|
||||
use crate::database::Database;
|
||||
use crate::error::AgentError;
|
||||
use crate::git_source::events::{is_own_event, IssueChange};
|
||||
use crate::pipeline::issue_backsync::{apply_change, BackSynced};
|
||||
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::GiteaIssue;
|
||||
|
||||
/// What one poll of a tenant did: counts only, for the log.
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct PollSummary {
|
||||
/// Targets whose issues were listed.
|
||||
pub targets: u32,
|
||||
/// Findings resolved or reopened.
|
||||
pub findings: u32,
|
||||
/// Issues whose state was recorded without a finding change (a decision
|
||||
/// a person had made stays; a CVE issue).
|
||||
pub recorded: u32,
|
||||
/// Targets whose tracker could not be read.
|
||||
pub failed: u32,
|
||||
}
|
||||
|
||||
/// What the poll of one target needs, owned by the agent.
|
||||
#[derive(Clone, Copy)]
|
||||
struct PollContext<'a> {
|
||||
db: &'a Database,
|
||||
config: &'a AgentConfig,
|
||||
net_guard: NetGuard,
|
||||
secrets: &'a SecretBox,
|
||||
}
|
||||
|
||||
/// The issues of `listed` whose state differs from Prüfwerk's record of it
|
||||
/// (`records`: number to closed), with the change and the issue's author.
|
||||
/// Issues Prüfwerk has no record of are not its own and left out.
|
||||
fn changes<'a>(
|
||||
records: &HashMap<i64, bool>,
|
||||
listed: &'a [GiteaIssue],
|
||||
) -> Vec<(i64, IssueChange, &'a str)> {
|
||||
listed
|
||||
.iter()
|
||||
.filter_map(
|
||||
|issue| match (records.get(&issue.number)?, issue.is_closed()) {
|
||||
(false, true) => Some((issue.number, IssueChange::Closed, issue.author())),
|
||||
(true, false) => Some((issue.number, IssueChange::Reopened, issue.author())),
|
||||
(true, true) | (false, false) => None,
|
||||
},
|
||||
)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Prüfwerk's Gitea issues of target `target_id`, by number: whether each
|
||||
/// is closed. A finding's issue is found through the finding (storing an
|
||||
/// issue sets the finding's `tracker_issue_url`), a CVE issue by its key.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// A database error.
|
||||
async fn records(db: &Database, target_id: &str) -> Result<HashMap<i64, bool>, AgentError> {
|
||||
let ticketed = db
|
||||
.findings()
|
||||
.distinct(
|
||||
"_id",
|
||||
doc! { "repo_id": target_id, "tracker_issue_url": { "$ne": Bson::Null } },
|
||||
)
|
||||
.await?;
|
||||
let finding_ids: Vec<String> = ticketed
|
||||
.iter()
|
||||
.filter_map(Bson::as_object_id)
|
||||
.map(|id| id.to_hex())
|
||||
.collect();
|
||||
let cve = format!("^{}", regex::escape(&cve_issue_prefix(target_id)));
|
||||
let issues: Vec<TrackerIssue> = db
|
||||
.tracker_issues()
|
||||
.find(doc! {
|
||||
"tracker_type": TrackerType::Gitea.to_string(),
|
||||
"$or": [
|
||||
{ "finding_id": { "$in": finding_ids } },
|
||||
{ "finding_id": { "$regex": cve } },
|
||||
],
|
||||
})
|
||||
.await?
|
||||
.try_collect()
|
||||
.await?;
|
||||
Ok(issues
|
||||
.iter()
|
||||
.filter_map(|i| Some((i.external_id.parse().ok()?, i.status.is_closed())))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Poll the issues of `target` and carry a person's closes and reopens
|
||||
/// back. A target without a Gitea tracker or without Prüfwerk issues is
|
||||
/// skipped without asking Gitea anything.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The records cannot be read, or Gitea cannot be listed or asked for a
|
||||
/// timeline: the next poll tries again.
|
||||
async fn poll_target(
|
||||
ctx: PollContext<'_>,
|
||||
target: &OnboardedTarget,
|
||||
summary: &mut PollSummary,
|
||||
) -> Result<(), AgentError> {
|
||||
let (Some(id), Some(code)) = (target.id.map(|id| id.to_hex()), target.code_artifact()) else {
|
||||
return Ok(());
|
||||
};
|
||||
let repo = RepoView::from_target(target, code, ctx.secrets);
|
||||
let Some(TrackerDispatch::Gitea(gitea)) = build_tracker(ctx.config, ctx.net_guard, &repo)
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let (Some(owner), Some(name)) = (repo.tracker_owner.as_deref(), repo.tracker_repo.as_deref())
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let records = records(ctx.db, &id).await?;
|
||||
if records.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
summary.targets += 1;
|
||||
let listed = gitea.list_issues(owner, name).await?;
|
||||
for (number, change, author) in changes(&records, &listed) {
|
||||
let closed = change == IssueChange::Closed;
|
||||
let Some(by) = gitea
|
||||
.last_state_change_by(owner, name, number, closed)
|
||||
.await?
|
||||
.filter(|by| !is_own_event(by, author))
|
||||
else {
|
||||
// Prüfwerk's own change whose record was not written, or a
|
||||
// timeline without the entry: nothing a person decided.
|
||||
continue;
|
||||
};
|
||||
match apply_change(ctx.db, &id, number, change, &by).await? {
|
||||
BackSynced::Finding => summary.findings += 1,
|
||||
BackSynced::IssueOnly | BackSynced::Cve => summary.recorded += 1,
|
||||
BackSynced::NotOurs => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Poll every active target of tenant `tenant_id`, one after the other so a
|
||||
/// small Gitea sees one listing at a time.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Automation is not allowed for the tenant (the same entitlement and
|
||||
/// ladder rules as the webhook), or its targets cannot be read. A target
|
||||
/// that fails is counted in [`PollSummary::failed`] and logged.
|
||||
pub(crate) async fn poll_tenant(
|
||||
agent: &ComplianceAgent,
|
||||
tenant_id: &str,
|
||||
) -> Result<PollSummary, AgentError> {
|
||||
crate::git_source::automation_allowed(agent, tenant_id)
|
||||
.await
|
||||
.map_err(AgentError::Other)?;
|
||||
let db = agent.db_pool.for_tenant_id(tenant_id).await?;
|
||||
let targets: Vec<OnboardedTarget> = db
|
||||
.onboarded_targets()
|
||||
.find(doc! { "archived_at": null })
|
||||
.await?
|
||||
.try_collect()
|
||||
.await?;
|
||||
let ctx = PollContext {
|
||||
db: &db,
|
||||
config: &agent.config,
|
||||
net_guard: agent.net_guard,
|
||||
secrets: &agent.secrets,
|
||||
};
|
||||
let mut summary = PollSummary::default();
|
||||
for target in &targets {
|
||||
if let Err(e) = poll_target(ctx, target, &mut summary).await {
|
||||
summary.failed += 1;
|
||||
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
|
||||
tracing::warn!(tenant_id, target_id, "issue poll failed: {e}");
|
||||
}
|
||||
}
|
||||
Ok(summary)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use axum::extract::{Path, Query};
|
||||
use axum::routing::get;
|
||||
use axum::{Json, Router};
|
||||
use compliance_core::models::{
|
||||
Artifact, Finding, FindingStatus, IssueStatus, IssueTrackerConfig, ScanType, Severity,
|
||||
TargetType, TrackerChangeKind,
|
||||
};
|
||||
use mongodb::bson::oid::ObjectId;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A fake Gitea: issue #12 closed by a person, #13 closed by the bot
|
||||
/// that opened it, #14 reopened by a person, #15 not Prüfwerk's. Every
|
||||
/// list ends with an empty page, as Gitea's do.
|
||||
async fn fake_gitea() -> String {
|
||||
fn page<T: Into<serde_json::Value>>(
|
||||
q: &HashMap<String, String>,
|
||||
items: T,
|
||||
) -> Json<serde_json::Value> {
|
||||
if q.get("page").map(String::as_str) == Some("1") {
|
||||
Json(items.into())
|
||||
} else {
|
||||
Json(serde_json::json!([]))
|
||||
}
|
||||
}
|
||||
async fn issues(
|
||||
Path((_o, _r)): Path<(String, String)>,
|
||||
Query(q): Query<HashMap<String, String>>,
|
||||
) -> Json<serde_json::Value> {
|
||||
let issue = |n: i64, state: &str| serde_json::json!({ "number": n, "title": "t", "state": state, "user": { "login": "pruefwerk-bot" } });
|
||||
page(
|
||||
&q,
|
||||
serde_json::json!([
|
||||
issue(12, "closed"),
|
||||
issue(13, "closed"),
|
||||
issue(14, "open"),
|
||||
issue(15, "closed")
|
||||
]),
|
||||
)
|
||||
}
|
||||
async fn timeline(
|
||||
Path((_o, _r, n)): Path<(String, String, i64)>,
|
||||
Query(q): Query<HashMap<String, String>>,
|
||||
) -> Json<serde_json::Value> {
|
||||
let event = |kind: &str, login: &str| serde_json::json!({ "type": kind, "user": { "login": login } });
|
||||
let events = match n {
|
||||
12 => serde_json::json!([
|
||||
event("comment", "pruefwerk-bot"),
|
||||
event("close", "dev-anna")
|
||||
]),
|
||||
13 => serde_json::json!([
|
||||
event("close", "dev-anna"),
|
||||
event("reopen", "dev-anna"),
|
||||
event("close", "Pruefwerk-Bot")
|
||||
]),
|
||||
14 => {
|
||||
serde_json::json!([event("close", "pruefwerk-bot"), event("reopen", "dev-ben")])
|
||||
}
|
||||
_ => serde_json::json!([event("close", "dev-anna")]),
|
||||
};
|
||||
page(&q, events)
|
||||
}
|
||||
let app = Router::new()
|
||||
.route("/api/v1/repos/{o}/{r}/issues", get(issues))
|
||||
.route("/api/v1/repos/{o}/{r}/issues/{n}/timeline", get(timeline));
|
||||
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 a_persons_close_or_reopen_in_gitea_is_carried_back_and_the_bots_is_not() {
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let prefix = format!("ipoll_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
|
||||
let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else {
|
||||
eprintln!("SKIP issue_poll: no MongoDB reachable at {uri}");
|
||||
return;
|
||||
};
|
||||
let db = pool.for_tenant_id("issue-poll").await.unwrap();
|
||||
let base = fake_gitea().await;
|
||||
|
||||
// Arrange: a target with a Gitea tracker, two open findings with
|
||||
// issues #12 and #13, and the CVE issue #14 (closed by Prüfwerk).
|
||||
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();
|
||||
target.id = Some(target_id);
|
||||
let target_hex = target_id.to_hex();
|
||||
let with_issue = |number: &str| {
|
||||
let db = db.clone();
|
||||
let target_hex = target_hex.clone();
|
||||
let base = base.clone();
|
||||
let number = number.to_string();
|
||||
async move {
|
||||
let url = format!("{base}/kunde/fw/issues/{number}");
|
||||
let mut f = Finding::new(
|
||||
target_hex,
|
||||
format!("fp-{number}"),
|
||||
"semgrep".into(),
|
||||
ScanType::Sast,
|
||||
"strcpy".into(),
|
||||
"d".into(),
|
||||
Severity::High,
|
||||
);
|
||||
f.tracker_issue_url = Some(url.clone());
|
||||
let id = db
|
||||
.findings()
|
||||
.insert_one(&f)
|
||||
.await
|
||||
.unwrap()
|
||||
.inserted_id
|
||||
.as_object_id()
|
||||
.unwrap();
|
||||
let issue = TrackerIssue::new(
|
||||
id.to_hex(),
|
||||
TrackerType::Gitea,
|
||||
number,
|
||||
url,
|
||||
"strcpy".into(),
|
||||
);
|
||||
db.tracker_issues().insert_one(&issue).await.unwrap();
|
||||
id
|
||||
}
|
||||
};
|
||||
let closed_by_anna = with_issue("12").await;
|
||||
let closed_by_bot = with_issue("13").await;
|
||||
let mut cve = TrackerIssue::new(
|
||||
format!("{}openssl:CVE-2026-1", cve_issue_prefix(&target_hex)),
|
||||
TrackerType::Gitea,
|
||||
"14".into(),
|
||||
format!("{base}/kunde/fw/issues/14"),
|
||||
"CVE-2026-1".into(),
|
||||
);
|
||||
cve.status = IssueStatus::Closed;
|
||||
db.tracker_issues().insert_one(&cve).await.unwrap();
|
||||
let ctx = PollContext {
|
||||
db: &db,
|
||||
config: &AgentConfig::default(),
|
||||
net_guard: NetGuard::allow_private(),
|
||||
secrets: &SecretBox::without_key(),
|
||||
};
|
||||
|
||||
// Act
|
||||
let mut summary = PollSummary::default();
|
||||
poll_target(ctx, &target, &mut summary).await.unwrap();
|
||||
|
||||
// Assert: Anna's close resolved her finding, the bot's left the
|
||||
// other alone, Ben's reopen of the CVE issue is recorded.
|
||||
assert_eq!(
|
||||
summary,
|
||||
PollSummary {
|
||||
targets: 1,
|
||||
findings: 1,
|
||||
recorded: 1,
|
||||
failed: 0
|
||||
}
|
||||
);
|
||||
let finding = |id: ObjectId| {
|
||||
let db = db.clone();
|
||||
async move {
|
||||
db.findings()
|
||||
.find_one(doc! { "_id": id })
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
}
|
||||
};
|
||||
let resolved = finding(closed_by_anna).await;
|
||||
assert_eq!(resolved.status, FindingStatus::Resolved);
|
||||
let last = resolved.status_history.last().unwrap();
|
||||
assert_eq!(
|
||||
(last.tracker, last.by_name.as_deref()),
|
||||
(Some(TrackerChangeKind::ClosedInTracker), Some("dev-anna"))
|
||||
);
|
||||
assert_eq!(finding(closed_by_bot).await.status, FindingStatus::Open);
|
||||
let issue = |number: &str| {
|
||||
let db = db.clone();
|
||||
let number = number.to_string();
|
||||
async move {
|
||||
db.tracker_issues()
|
||||
.find_one(doc! { "external_id": number })
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
}
|
||||
};
|
||||
let twelve = issue("12").await;
|
||||
assert_eq!(
|
||||
(twelve.status, twelve.closed_in_tracker.as_deref()),
|
||||
(IssueStatus::Closed, Some("dev-anna"))
|
||||
);
|
||||
assert_eq!(issue("13").await.status, IssueStatus::Open);
|
||||
assert_eq!(issue("14").await.status, IssueStatus::Open);
|
||||
|
||||
// A second poll finds the records matching (the bot's close aside,
|
||||
// which stays a person's to decide): nothing more changes.
|
||||
let mut again = PollSummary::default();
|
||||
poll_target(ctx, &target, &mut again).await.unwrap();
|
||||
assert_eq!((again.findings, again.recorded), (0, 0));
|
||||
|
||||
pool.drop_tenant("issue-poll").await.ok();
|
||||
}
|
||||
|
||||
fn listed(number: i64, state: &str, author: &str) -> GiteaIssue {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"number": number, "title": "t", "state": state,
|
||||
"user": { "login": author },
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_issues_whose_state_differs_from_the_record_are_changes() {
|
||||
let records: HashMap<i64, bool> = [(1, false), (2, true), (3, false), (4, true)].into();
|
||||
let issues = [
|
||||
listed(1, "closed", "bot"),
|
||||
listed(2, "open", "bot"),
|
||||
listed(3, "open", "bot"),
|
||||
listed(4, "closed", "bot"),
|
||||
// Not Prüfwerk's: no record.
|
||||
listed(5, "closed", "dev-anna"),
|
||||
];
|
||||
assert_eq!(
|
||||
changes(&records, &issues),
|
||||
[
|
||||
(1, IssueChange::Closed, "bot"),
|
||||
(2, IssueChange::Reopened, "bot")
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,7 @@ pub mod ios_config;
|
||||
pub(crate) mod issue_backsync;
|
||||
mod issue_catchup;
|
||||
pub(crate) mod issue_creation;
|
||||
pub(crate) mod issue_poll;
|
||||
pub(crate) mod issue_sync;
|
||||
pub mod languages;
|
||||
pub mod license_policy;
|
||||
|
||||
@@ -126,6 +126,34 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError>
|
||||
.await
|
||||
.map_err(|e| AgentError::Scheduler(format!("Failed to add git sync job: {e}")))?;
|
||||
|
||||
// Issues a person closed or reopened in Gitea (#953), for the targets no
|
||||
// webhook reports them for; at the managed git sync's interval.
|
||||
let poll_agent = agent.clone();
|
||||
let poll_job = Job::new_repeated_async(agent.git_source.sync_interval, move |_uuid, _lock| {
|
||||
let agent = poll_agent.clone();
|
||||
Box::pin(async move {
|
||||
for tenant_id in scheduler_tenants(&agent).await {
|
||||
match crate::pipeline::issue_poll::poll_tenant(&agent, &tenant_id).await {
|
||||
Ok(s) if s.targets > 0 => tracing::info!(
|
||||
tenant_id,
|
||||
targets = s.targets,
|
||||
findings = s.findings,
|
||||
recorded = s.recorded,
|
||||
failed = s.failed,
|
||||
"issue poll done"
|
||||
),
|
||||
Ok(_) => {}
|
||||
Err(e) => tracing::warn!(tenant_id, "issue poll skipped: {e}"),
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
.map_err(|e| AgentError::Scheduler(format!("Failed to create issue poll job: {e}")))?;
|
||||
sched
|
||||
.add(poll_job)
|
||||
.await
|
||||
.map_err(|e| AgentError::Scheduler(format!("Failed to add issue poll job: {e}")))?;
|
||||
|
||||
sched
|
||||
.start()
|
||||
.await
|
||||
|
||||
@@ -176,6 +176,39 @@ impl GiteaTracker {
|
||||
.await
|
||||
}
|
||||
|
||||
/// The login of whoever last closed (`closed`) or reopened issue `number`,
|
||||
/// from its timeline; `None` if the timeline has no such entry. The issue
|
||||
/// itself does not say who closed it.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`CoreError::IssueTracker`] if the timeline cannot be read, or has more
|
||||
/// than `MAX_TIMELINE_PAGES` pages.
|
||||
pub async fn last_state_change_by(
|
||||
&self,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
number: i64,
|
||||
closed: bool,
|
||||
) -> Result<Option<String>, CoreError> {
|
||||
let kind = if closed { "close" } else { "reopen" };
|
||||
let events: Vec<GiteaTimelineEvent> = self
|
||||
.list_all(
|
||||
"issue timeline",
|
||||
&format!("/repos/{owner}/{repo}/issues/{number}/timeline"),
|
||||
MAX_TIMELINE_PAGES,
|
||||
)
|
||||
.await?;
|
||||
// Oldest first: the last matching entry is the current state's.
|
||||
Ok(events
|
||||
.into_iter()
|
||||
.rev()
|
||||
.find(|e| e.kind == kind)
|
||||
.and_then(|e| e.user)
|
||||
.map(|u| u.login)
|
||||
.filter(|login| !login.is_empty()))
|
||||
}
|
||||
|
||||
/// Make sure the repository has every label in `wanted`, creating the
|
||||
/// missing ones, and return the id of each by name. Needs write access to
|
||||
/// the repository's issues, nothing more.
|
||||
@@ -287,6 +320,25 @@ const LIST_PAGE_SIZE: usize = 50;
|
||||
const MAX_LABEL_PAGES: usize = 20;
|
||||
/// Upper bound on issue pages (10 000 issues).
|
||||
const MAX_ISSUE_PAGES: usize = 200;
|
||||
/// Upper bound on the timeline pages of one issue (1 000 entries).
|
||||
const MAX_TIMELINE_PAGES: usize = 20;
|
||||
|
||||
/// A Gitea user, by login.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
|
||||
pub struct GiteaUser {
|
||||
#[serde(default)]
|
||||
pub login: String,
|
||||
}
|
||||
|
||||
/// An entry of an issue's timeline, with what a close or reopen needs:
|
||||
/// `type` is `close`, `reopen`, `comment`, ...
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
|
||||
struct GiteaTimelineEvent {
|
||||
#[serde(rename = "type", default)]
|
||||
kind: String,
|
||||
#[serde(default)]
|
||||
user: Option<GiteaUser>,
|
||||
}
|
||||
|
||||
/// An issue as Gitea lists it, with what an issue is matched by.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
|
||||
@@ -301,6 +353,21 @@ pub struct GiteaIssue {
|
||||
/// `open` or `closed`.
|
||||
#[serde(default)]
|
||||
pub state: String,
|
||||
/// Who opened it: Prüfwerk's issues are opened by its bot user.
|
||||
#[serde(default)]
|
||||
pub user: Option<GiteaUser>,
|
||||
}
|
||||
|
||||
impl GiteaIssue {
|
||||
/// The login of whoever opened the issue, empty if Gitea did not say.
|
||||
pub fn author(&self) -> &str {
|
||||
self.user.as_ref().map_or("", |u| u.login.as_str())
|
||||
}
|
||||
|
||||
/// Whether the issue is closed.
|
||||
pub fn is_closed(&self) -> bool {
|
||||
self.state == "closed"
|
||||
}
|
||||
}
|
||||
|
||||
/// A repository label as Gitea returns it.
|
||||
|
||||
@@ -21,6 +21,23 @@ A scan opens issues only for the findings it finds new, so a finding whose issue
|
||||
|
||||
For a repository from a managed git source, known vulnerabilities in its dependencies become issues too: one per package and CVE, labelled `cve`. A critical or high CVE opens one, and so does any CVE in CISA's Known Exploited Vulnerabilities catalog (rated at least high). A CVE whose EPSS percentile reaches `CVE_ISSUE_EPSS_PERCENTILE` (default `0.95`) is rated one step higher, so a medium one opens an issue as high. The issue names the KEV entry, the EPSS score with its attribution, and CISA's SSVC exploitation where known. When a complete scan no longer finds the CVE, the issue is closed; when it comes back, it is reopened. A CVE with the VEX status `not_affected` or `fixed` gets no new issue. Its issue that is already open is closed only with `ISSUE_AUTOCLOSE=on`: with a comment naming the status and the justification, at most 20 per target and scan (the rest follow in the next scans). `ISSUE_AUTOCLOSE=dry_run` only logs, per target, how many issues it would close per VEX status, and changes nothing; the default is `off`. When the statement is withdrawn, a closed issue is reopened.
|
||||
|
||||
### Closing an issue in Gitea
|
||||
|
||||
Closing a Prüfwerk issue in Gitea resolves its finding, if no one has decided
|
||||
on the finding yet; its history reads "Im Ticket geschlossen von *Gitea
|
||||
user*" (closed in the ticket by). Reopening the issue reopens the finding. A
|
||||
decision already made in Prüfwerk (an accepted risk, say) stays. A CVE issue
|
||||
someone closes stays closed while the scan finds the vulnerability unchanged;
|
||||
it does not set a VEX status. The next scan confirms a resolved finding or
|
||||
finds it again and reopens it and its issue.
|
||||
|
||||
Prüfwerk checks the state of its Gitea issues every 30 minutes
|
||||
(`GIT_SOURCE_SYNC_MINUTES`): one listing per repository, and for an issue whose
|
||||
state changed, its timeline, to see who changed it. Changes Prüfwerk's own bot
|
||||
user made are left alone. A managed repository whose webhook sends the
|
||||
**Issues** event gets the change at once. GitHub, GitLab and Jira issues are
|
||||
not read back.
|
||||
|
||||
## Issues List
|
||||
|
||||
Open **Tickets** (Issues) in the sidebar to see all tracker issues across your targets.
|
||||
|
||||
@@ -38,7 +38,9 @@ of an organisation in that instance automatically:
|
||||
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.
|
||||
unchanged; it does not set a VEX status. Prüfwerk checks its issues itself
|
||||
every 30 minutes; with the **Issues** event in the webhook a change arrives
|
||||
at once.
|
||||
- **Sync.** Every 30 minutes Prüfwerk compares the organisation's repositories
|
||||
with its targets, in case a webhook delivery was lost.
|
||||
|
||||
@@ -82,8 +84,9 @@ The response carries `webhook_url` and — only the first time, or with
|
||||
organisation or system webhook in Gitea (type Gitea, `application/json`) for
|
||||
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`
|
||||
has no administration rights). An older webhook without the **Issues** event
|
||||
still gets closed and reopened issues across, at the next check (every 30
|
||||
minutes); with the event added they arrive at once. 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.
|
||||
|
||||
@@ -42,7 +42,9 @@ Repository-Organisation dieser Instanz automatisch prüfen:
|
||||
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.
|
||||
unverändert findet; einen VEX-Status setzt das nicht. Prüfwerk fragt den
|
||||
Stand seiner Issues alle 30 Minuten selbst ab; mit dem Ereignis **Issues**
|
||||
im Webhook kommt eine Änderung sofort an.
|
||||
- **Abgleich.** Alle 30 Minuten gleicht Prüfwerk die Repository-Liste der
|
||||
Organisation mit den Prüfobjekten ab, falls ein Webhook verloren ging.
|
||||
|
||||
@@ -89,9 +91,10 @@ Die Antwort enthält `webhook_url` und – nur beim ersten Mal oder mit
|
||||
Organisations- oder System-Webhook (Typ Gitea, `application/json`) mit den
|
||||
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
|
||||
oder ändern (der Bot hat keine Administrationsrechte). Fehlt einem älteren
|
||||
Webhook das Ereignis **Issues**, kommen geschlossene und wieder geöffnete
|
||||
Issues trotzdem an, beim nächsten Abfragen (alle 30 Minuten); nachgetragen
|
||||
kommen sie sofort. 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.
|
||||
|
||||
Reference in new issue
Block a user