Files
pruefwerk/compliance-agent/src/git_source/events.rs
T
sharangandClaude Opus 5.5 f1123e1adb
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Successful in 1m8s
CI / Deploy MCP (push) Successful in 4m56s
CI / Deploy Dashboard (push) Successful in 6m54s
CI / Deploy Agent (push) Successful in 8m53s
feat(issues): closing or reopening a Prüfwerk issue in Gitea updates the finding (#953) (#960)
The managed Git source's org webhook now handles `issues` events. A
person closing an issue Prüfwerk opened resolves the undecided finding,
recorded as "closed in the ticket" with the Gitea login; reopening it
makes the finding open again. A decision already made in Prüfwerk is
kept. Events whose sender is the issue's author (Prüfwerk's bot user,
which opened it) are ignored, and the back-sync never calls Gitea, so
nothing loops; the issue record is updated first, so the outbound sync
has nothing left to comment or close.

CVE issues closed in Gitea only record the close and who did it, no VEX
status. The scan leaves such an issue closed while the CVE is still
found, and forgets the close once a complete scan no longer finds it, so
a CVE that comes back reopens the issue as before.

The platform API names the events the webhook needs (`webhook_events`);
Prüfwerk cannot change the webhook itself, so existing webhooks need
the Issues event added in Gitea. The finding history shows
"Im Ticket geschlossen von <login>".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:22:29 +00:00

317 lines
12 KiB
Rust

//! What a system/org webhook delivery from a managed Gitea asks for.
use super::gitea::GiteaRepo;
/// The action a delivery maps to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SourceAction {
/// A repository was created: make it a target, scan it unless it is empty.
Created(GiteaRepo),
/// A repository was deleted: archive its target.
Deleted(GiteaRepo),
/// 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),
}
impl SourceAction {
/// The repository the action is about; `None` for [`Self::Ignore`].
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";
/// Route a delivery: `event` is the `X-Gitea-Event` header, `org` the source's
/// 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::<GiteaRepo>(r).ok())
else {
return SourceAction::Ignore("payload without a repository");
};
if !repo.in_org(org) {
return SourceAction::Ignore("repository outside the configured organisation");
}
match event {
"repository" => match payload.get("action").and_then(|a| a.as_str()) {
Some("created") => SourceAction::Created(repo),
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("");
if after == ZERO_SHA {
SourceAction::Ignore("branch deleted")
} else if git_ref != format!("refs/heads/{}", repo.branch()) {
SourceAction::Ignore("push to another branch than the default")
} else {
SourceAction::Push(repo)
}
}
}
}
/// 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 {
use serde_json::json;
use super::*;
fn repository(owner: &str) -> serde_json::Value {
json!({
"id": 42, "name": "fw", "full_name": format!("{owner}/fw"),
"owner": { "login": owner }, "default_branch": "main", "empty": true,
})
}
#[test]
fn an_action_names_its_repository_unless_ignored() {
let p = json!({ "action": "created", "repository": repository("kunde") });
assert_eq!(
route_event("repository", &p, "kunde").repo().map(|r| r.id),
Some(42)
);
assert!(SourceAction::Ignore("x").repo().is_none());
}
#[test]
fn created_and_deleted() {
let p = json!({ "action": "created", "repository": repository("kunde") });
match route_event("repository", &p, "kunde") {
SourceAction::Created(r) => {
assert_eq!(
(r.id, r.full_name.as_str(), r.empty),
(42, "kunde/fw", true)
);
}
other => panic!("{other:?}"),
}
let p = json!({ "action": "deleted", "repository": repository("kunde") });
assert!(matches!(
route_event("repository", &p, "kunde"),
SourceAction::Deleted(r) if r.id == 42
));
let p = json!({ "action": "renamed", "repository": repository("kunde") });
assert!(matches!(
route_event("repository", &p, "kunde"),
SourceAction::Ignore(_)
));
}
#[test]
fn push_to_the_default_branch_only() {
let push = |git_ref: &str, after: &str| json!({ "ref": git_ref, "after": after, "repository": repository("kunde") });
assert!(matches!(
route_event("push", &push("refs/heads/main", "abc"), "kunde"),
SourceAction::Push(r) if r.id == 42
));
assert_eq!(
route_event("push", &push("refs/heads/feature", "abc"), "kunde"),
SourceAction::Ignore("push to another branch than the default")
);
assert_eq!(
route_event("push", &push("refs/tags/v1", "abc"), "kunde"),
SourceAction::Ignore("push to another branch than the default")
);
assert_eq!(
route_event("push", &push("refs/heads/main", ZERO_SHA), "kunde"),
SourceAction::Ignore("branch deleted")
);
}
#[test]
fn other_orgs_are_ignored_case_insensitively_matched() {
let p = json!({ "action": "created", "repository": repository("andere") });
assert_eq!(
route_event("repository", &p, "kunde"),
SourceAction::Ignore("repository outside the configured organisation")
);
let p = json!({ "action": "created", "repository": repository("Kunde") });
assert!(matches!(
route_event("repository", &p, "kunde"),
SourceAction::Created(_)
));
}
#[test]
fn unknown_events_and_bad_payloads_are_ignored() {
let p = json!({ "action": "opened", "repository": repository("kunde") });
assert_eq!(
route_event("pull_request", &p, "kunde"),
SourceAction::Ignore("event not handled")
);
assert_eq!(
route_event("issues", &json!({}), "kunde"),
SourceAction::Ignore("payload without a repository")
);
assert_eq!(
route_event("push", &json!({ "ref": "refs/heads/main" }), "kunde"),
SourceAction::Ignore("payload without a repository")
);
assert_eq!(
route_event("", &json!({ "repository": repository("kunde") }), "kunde"),
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")
);
}
}