Files
pruefwerk/compliance-agent/tests/git_source.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

673 lines
22 KiB
Rust

//! Managed git source (#439) against a live Mongo: the platform API stores the
//! source sealed and hands out the webhook secret once, the org webhook is
//! HMAC-checked, answers 202 and creates exactly one target per repository in
//! the background however often (or concurrently) it is delivered, deletion
//! archives, every handled delivery is recorded for the target page, and the
//! sync diffs a mocked Gitea listing. Skips cleanly when no Mongo is reachable.
//!
//! Every repository here is empty, so no scan (and no clone) is started.
#![allow(clippy::expect_used, clippy::unwrap_used)]
mod common;
use std::sync::Arc;
use axum::routing::{get, post};
use axum::{Extension, Router};
use futures_util::TryStreamExt;
use hmac::{Hmac, Mac};
use mongodb::bson::doc;
use sha2::Sha256;
use compliance_agent::agent::ComplianceAgent;
use compliance_agent::api::handlers::platform::{self, PlatformState};
use compliance_agent::database::{Database, DatabasePool};
use compliance_agent::error::AgentError;
use compliance_agent::git_source::gitea::{GiteaRepo, RepoLister};
use compliance_agent::webhooks::gitea_source::handle_gitea_source_webhook;
use compliance_core::models::{DeliveryResult, OnboardedTarget, WebhookDelivery};
use common::dev_config;
const TENANT: &str = "gitsrc";
struct Harness {
base_url: String,
client: reqwest::Client,
pool: DatabasePool,
db: Database,
agent: Arc<ComplianceAgent>,
}
async fn start() -> Option<Harness> {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db_name = format!("gs_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]);
let Ok(pool) = DatabasePool::connect(&uri, &db_name).await else {
eprintln!("SKIP git_source: no MongoDB reachable at {uri}");
return None;
};
let db = pool.for_tenant_id(TENANT).await.expect("tenant db");
let agent = Arc::new(ComplianceAgent::new(dev_config(uri, db_name), pool.clone()));
let state = PlatformState {
agent: agent.clone(),
jwks: None,
};
let app = Router::new()
.route(
"/api/v1/platform/tenants/{id}/git-source",
get(platform::get_git_source)
.put(platform::put_git_source)
.delete(platform::delete_git_source),
)
.with_state(state)
.route(
"/webhook/{tenant_id}/gitea-source",
post(handle_gitea_source_webhook),
)
.layer(Extension(agent.clone()));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move {
axum::serve(listener, app).await.ok();
});
Some(Harness {
base_url: format!("http://127.0.0.1:{port}"),
client: reqwest::Client::new(),
pool,
db,
agent,
})
}
fn sign(secret: &str, body: &[u8]) -> String {
let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).unwrap();
mac.update(body);
hex::encode(mac.finalize().into_bytes())
}
fn repo_json(id: i64, owner: &str, name: &str) -> serde_json::Value {
serde_json::json!({
"id": id, "name": name, "full_name": format!("{owner}/{name}"),
"owner": { "login": owner }, "default_branch": "main", "empty": true,
})
}
impl Harness {
async fn put_source(&self, body: serde_json::Value) -> (u16, serde_json::Value) {
let resp = self
.client
.put(format!(
"{}/api/v1/platform/tenants/{TENANT}/git-source",
self.base_url
))
.json(&body)
.send()
.await
.unwrap();
let status = resp.status().as_u16();
(status, resp.json().await.unwrap_or_default())
}
async fn deliver(
&self,
tenant: &str,
event: &str,
body: &serde_json::Value,
sig: Option<String>,
) -> u16 {
let bytes = serde_json::to_vec(body).unwrap();
let mut req = self
.client
.post(format!("{}/webhook/{tenant}/gitea-source", self.base_url))
.header("X-Gitea-Event", event)
.header("Content-Type", "application/json");
if let Some(sig) = sig {
req = req.header("X-Gitea-Signature", sig);
}
req.body(bytes).send().await.unwrap().status().as_u16()
}
/// Poll `check` until it holds: the webhook's work runs after its answer.
async fn eventually<F, Fut>(what: &str, mut check: F)
where
F: FnMut() -> Fut,
Fut: std::future::Future<Output = bool>,
{
for _ in 0..100 {
if check().await {
return;
}
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
panic!("{what} did not happen within 5 s");
}
async fn target(&self, repo_id: i64) -> Option<OnboardedTarget> {
self.db
.onboarded_targets()
.find_one(doc! { "source_repo.repo_id": repo_id })
.await
.unwrap()
}
async fn managed_count(&self, repo_id: i64) -> u64 {
self.db
.onboarded_targets()
.count_documents(doc! { "source_repo.repo_id": repo_id })
.await
.unwrap()
}
}
#[tokio::test]
async fn platform_api_webhook_and_sync() {
let Some(h) = start().await else { return };
// ── platform API ────────────────────────────────────────────────────
let (status, body) = h
.put_source(serde_json::json!({
"base_url": "https://evil.example.com", "org": "kunde", "bot_token": "t"
}))
.await;
assert_eq!(status, 400, "{body}");
let (status, _) = h
.put_source(serde_json::json!({
"base_url": "https://kunde.code.breakpilot.com", "org": "kunde"
}))
.await;
assert_eq!(status, 400, "a first PUT needs the bot token");
// Disabled first, so the PUT's own sync does not reach out to the host.
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}");
let secret = created["webhook_secret"].as_str().unwrap().to_string();
assert_eq!(secret.len(), 64);
assert_eq!(created["webhook_url"], "/webhook/gitsrc/gitea-source");
assert_eq!(created["base_url"], "https://kunde.code.breakpilot.com");
assert!(!created.to_string().contains("bot-pat"));
let stored =
h.db.raw_collection("git_sources")
.find_one(doc! {})
.await
.unwrap()
.unwrap();
assert!(stored.get_str("bot_token").unwrap().starts_with("enc:v1:"));
let sealed_secret = stored.get_str("webhook_secret").unwrap().to_string();
assert!(sealed_secret.starts_with("enc:v1:"));
// A retried PUT keeps the secret (and does not show it again).
let (status, again) = h
.put_source(serde_json::json!({
"base_url": "https://kunde.code.breakpilot.com", "org": "kunde", "enabled": false
}))
.await;
assert_eq!(status, 200);
assert!(again["webhook_secret"].is_null());
let stored =
h.db.raw_collection("git_sources")
.find_one(doc! {})
.await
.unwrap()
.unwrap();
assert_eq!(stored.get_str("webhook_secret").unwrap(), sealed_secret);
let got: serde_json::Value = h
.client
.get(format!(
"{}/api/v1/platform/tenants/{TENANT}/git-source",
h.base_url
))
.send()
.await
.unwrap()
.json()
.await
.unwrap();
assert_eq!(got["has_bot_token"], true);
assert!(got["webhook_secret"].is_null());
assert!(!got.to_string().contains("enc:v1"));
// ── webhook ─────────────────────────────────────────────────────────
let created_evt =
serde_json::json!({ "action": "created", "repository": repo_json(11, "kunde", "fw") });
let body = serde_json::to_vec(&created_evt).unwrap();
// disabled source: not there
assert_eq!(
h.deliver(
TENANT,
"repository",
&created_evt,
Some(sign(&secret, &body))
)
.await,
404
);
h.db.git_sources()
.update_one(doc! {}, doc! { "$set": { "enabled": true } })
.await
.unwrap();
assert_eq!(
h.deliver(TENANT, "repository", &created_evt, None).await,
401
);
assert_eq!(
h.deliver(
TENANT,
"repository",
&created_evt,
Some(sign("wrong", &body))
)
.await,
401
);
assert_eq!(
h.deliver(
"no-such-tenant",
"repository",
&created_evt,
Some(sign(&secret, &body))
)
.await,
404
);
assert_eq!(h.managed_count(11).await, 0);
// Twice at once and once more: accepted at once, one target.
let sig = sign(&secret, &body);
let (a, b) = tokio::join!(
h.deliver(TENANT, "repository", &created_evt, Some(sig.clone())),
h.deliver(TENANT, "repository", &created_evt, Some(sig.clone())),
);
assert_eq!((a, b), (202, 202));
Harness::eventually("the first target", || async {
h.target(11)
.await
.is_some_and(|t| t.classification.is_some())
})
.await;
assert_eq!(
h.deliver(TENANT, "repository", &created_evt, Some(sig))
.await,
202
);
// Let the third delivery's refresh finish before the deletion below.
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
assert_eq!(h.managed_count(11).await, 1);
let target = h.target(11).await.unwrap();
assert_eq!(target.name, "kunde/fw");
assert_eq!(
target.code_artifact().unwrap().source_ref,
"https://kunde.code.breakpilot.com/kunde/fw.git"
);
assert!(target.classification.is_some(), "detection ran");
// Each of the three deliveries is recorded for the target page, in a
// capped collection.
let target_id = target.id.unwrap().to_hex();
let for_target = compliance_agent::webhooks::deliveries::target_filter(
&target_id,
target.source_repo.as_ref(),
);
Harness::eventually("three recorded deliveries", || async {
h.db.webhook_deliveries()
.count_documents(for_target.clone())
.await
.unwrap()
== 3
})
.await;
let recorded: Vec<WebhookDelivery> =
h.db.webhook_deliveries()
.find(for_target.clone())
.await
.unwrap()
.try_collect()
.await
.unwrap();
assert!(recorded.iter().all(|d| d.result == DeliveryResult::Handled
&& d.source == "gitea-source"
&& d.event == "repository"
&& d.target_id.as_deref() == Some(target_id.as_str())));
assert_eq!(
recorded
.iter()
.filter(|d| d.detail == "target ready, nothing to scan yet")
.count(),
3,
"an empty repository is not scanned"
);
let spec = h
.pool
.client()
.database(&h.pool.tenant_db_name(TENANT))
.list_collections()
.filter(doc! { "name": "webhook_deliveries" })
.await
.unwrap()
.try_next()
.await
.unwrap()
.unwrap();
assert_eq!(spec.options.capped, Some(true));
// Another organisation's repository is ignored, and said so at once.
let other =
serde_json::json!({ "action": "created", "repository": repo_json(12, "andere", "x") });
let ob = serde_json::to_vec(&other).unwrap();
assert_eq!(
h.deliver(TENANT, "repository", &other, Some(sign(&secret, &ob)))
.await,
200
);
assert_eq!(h.managed_count(12).await, 0);
// Deleted: archived, not removed.
let deleted =
serde_json::json!({ "action": "deleted", "repository": repo_json(11, "kunde", "fw") });
let db_ = serde_json::to_vec(&deleted).unwrap();
assert_eq!(
h.deliver(TENANT, "repository", &deleted, Some(sign(&secret, &db_)))
.await,
202
);
Harness::eventually("the archive", || async {
h.target(11).await.is_some_and(|t| t.archived_at.is_some())
})
.await;
// The deletion carries no target id; it is the target's by repository.
Harness::eventually("the recorded deletion", || async {
h.db.webhook_deliveries()
.count_documents(for_target.clone())
.await
.unwrap()
== 4
})
.await;
// ── sync against a mocked listing ───────────────────────────────────
struct Listing(Vec<GiteaRepo>);
impl RepoLister for Listing {
async fn list_org_repos(&self, _org: &str) -> Result<Vec<GiteaRepo>, AgentError> {
Ok(self.0.clone())
}
}
let repo =
|id, name| serde_json::from_value::<GiteaRepo>(repo_json(id, "kunde", name)).unwrap();
let source = compliance_agent::git_source::load_source(&h.db)
.await
.unwrap()
.unwrap();
// fw (11) is back, docs (13) is new.
let listing = Listing(vec![repo(11, "fw"), repo(13, "docs")]);
let report =
compliance_agent::git_source::sync_with(&h.agent, &h.db, TENANT, &source, &listing)
.await
.unwrap();
assert_eq!(
(report.created, report.refreshed, report.archived),
(1, 1, 0)
);
// docs gone again: archived; a second identical sync changes nothing.
let listing = Listing(vec![repo(11, "fw")]);
let report =
compliance_agent::git_source::sync_with(&h.agent, &h.db, TENANT, &source, &listing)
.await
.unwrap();
assert_eq!(
(report.created, report.refreshed, report.archived),
(0, 0, 1)
);
let report =
compliance_agent::git_source::sync_with(&h.agent, &h.db, TENANT, &source, &listing)
.await
.unwrap();
assert_eq!(
(report.created, report.refreshed, report.archived),
(0, 0, 0)
);
assert_eq!(h.managed_count(11).await + h.managed_count(13).await, 2);
// ── a new bot token reaches the managed targets ─────────────────────
let (status, _) = h
.put_source(serde_json::json!({
"base_url": "https://kunde.code.breakpilot.com", "org": "kunde",
"bot_token": "bot-pat-2", "enabled": false
}))
.await;
assert_eq!(status, 200);
let target =
h.db.onboarded_targets()
.find_one(doc! { "source_repo.repo_id": 11_i64 })
.await
.unwrap()
.unwrap();
let tracker_token = target.scan_config.issue_tracker.unwrap().token.unwrap();
let git_token = target.artifacts[0]
.auth
.as_ref()
.unwrap()
.secret
.clone()
.unwrap();
assert_eq!(h.agent.secrets.open(&tracker_token).unwrap(), "bot-pat-2");
assert_eq!(h.agent.secrets.open(&git_token).unwrap(), "bot-pat-2");
// ── delete: the source goes, its targets are archived ───────────────
let resp: serde_json::Value = h
.client
.delete(format!(
"{}/api/v1/platform/tenants/{TENANT}/git-source",
h.base_url
))
.send()
.await
.unwrap()
.json()
.await
.unwrap();
assert_eq!(resp["targets_archived"], 1);
assert!(compliance_agent::git_source::load_source(&h.db)
.await
.unwrap()
.is_none());
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]
async fn a_plain_deliveries_collection_becomes_capped() {
let Some(h) = start().await else { return };
const PLAIN: &str = "gitsrc-plain";
let early = WebhookDelivery::new("gitea", "push", DeliveryResult::Handled, "scan queued");
h.pool
.for_existing_tenant_id(PLAIN)
.webhook_deliveries()
.insert_one(&early)
.await
.unwrap();
let db = h.pool.for_tenant_id(PLAIN).await.expect("ensured");
let spec = h
.pool
.client()
.database(&h.pool.tenant_db_name(PLAIN))
.list_collections()
.filter(doc! { "name": "webhook_deliveries" })
.await
.unwrap()
.try_next()
.await
.unwrap()
.unwrap();
assert_eq!(spec.options.capped, Some(true));
assert_eq!(
db.webhook_deliveries()
.count_documents(doc! {})
.await
.unwrap(),
1,
"the early delivery is kept"
);
h.pool.drop_tenant(PLAIN).await.ok();
h.pool.drop_tenant(TENANT).await.ok();
}