From 66f96695ba754bde32e9b2d79884a59cfd77b524 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Fri, 9 Oct 2026 15:18:14 +0200 Subject: [PATCH] feat(webhooks): the target page shows its last webhook deliveries, refused ones too The managed Gitea source webhook answers 202 and decides about entitlement in the background, so Gitea's delivery log cannot tell a refused delivery from a handled one. Every verified delivery that asks for work is now recorded (time, event, handled/refused/failed with the reason, elapsed ms) in a capped per-tenant collection, read by a new GET /api/v1/targets/{id}/webhook-deliveries and shown in a box on the target page. A managed-source delivery carries its repository (base_url + repo_id), so one refused before its target exists still shows on the target once the sync creates it. The per-target GitHub/GitLab/Gitea receivers record the push or PR review they queue. Recording never fails a webhook; errors are logged. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- .../src/api/handlers/onboarding.rs | 38 ++++- compliance-agent/src/api/routes.rs | 4 + compliance-agent/src/database.rs | 84 +++++++++++ compliance-agent/src/git_source/events.rs | 20 +++ compliance-agent/src/webhooks/deliveries.rs | 101 +++++++++++++ compliance-agent/src/webhooks/gitea.rs | 15 ++ compliance-agent/src/webhooks/gitea_source.rs | 134 ++++++++++++++++-- compliance-agent/src/webhooks/github.rs | 15 ++ compliance-agent/src/webhooks/gitlab.rs | 15 ++ compliance-agent/src/webhooks/mod.rs | 1 + compliance-agent/tests/git_source.rs | 104 +++++++++++++- compliance-core/src/models/mod.rs | 2 + .../src/models/webhook_delivery.rs | 131 +++++++++++++++++ compliance-dashboard/assets/main.css | 31 ++++ compliance-dashboard/src/components/mod.rs | 1 + .../src/components/webhook_deliveries.rs | 77 ++++++++++ compliance-dashboard/src/i18n/texts.rs | 37 +++++ .../src/infrastructure/onboarding.rs | 22 +++ compliance-dashboard/src/pages/target.rs | 6 + 19 files changed, 822 insertions(+), 16 deletions(-) create mode 100644 compliance-agent/src/webhooks/deliveries.rs create mode 100644 compliance-core/src/models/webhook_delivery.rs create mode 100644 compliance-dashboard/src/components/webhook_deliveries.rs diff --git a/compliance-agent/src/api/handlers/onboarding.rs b/compliance-agent/src/api/handlers/onboarding.rs index 1e1dd99..bc4074d 100644 --- a/compliance-agent/src/api/handlers/onboarding.rs +++ b/compliance-agent/src/api/handlers/onboarding.rs @@ -13,7 +13,7 @@ use serde::{Deserialize, Serialize}; use compliance_core::models::{ ArtifactKind, ComplianceProfile, Credentials, DetectedFact, Finding, OnboardedTarget, - PlcFormat, ScanRun, TargetType, + PlcFormat, ScanRun, TargetType, WebhookDelivery, DELIVERIES_SHOWN, }; use compliance_core::scan_matrix::{applicable_scans, supports_pentest}; use compliance_core::tenant_ctx::TenantCtx; @@ -308,6 +308,42 @@ pub async fn get_target( })) } +/// GET /api/v1/targets/{id}/webhook-deliveries — the target's newest +/// webhook deliveries, refused and failed ones included; for a managed +/// target also those of its repository from before the target existed. +#[tracing::instrument(skip_all, fields(target_id = %id))] +pub async fn list_webhook_deliveries( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path(id): Path, +) -> Result>>, StatusCode> { + let oid = parse_oid(&id)?; + let db = tenant_db(&agent, &tenant).await?; + let target = db + .onboarded_targets() + .find_one(doc! { "_id": oid }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + let filter = crate::webhooks::deliveries::target_filter(&id, target.source_repo.as_ref()); + let cursor = db + .webhook_deliveries() + .find(filter) + .sort(doc! { "received_at": -1 }) + .limit(DELIVERIES_SHOWN) + .await + .map_err(|e| { + tracing::warn!("Failed to list webhook deliveries: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + let deliveries = collect_cursor_async(cursor).await; + Ok(Json(ApiResponse { + total: Some(deliveries.len() as u64), + data: deliveries, + page: None, + })) +} + /// PATCH /api/v1/targets/{id} — update mutable fields. #[tracing::instrument(skip_all, fields(target_id = %id))] pub async fn update_target( diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index d074f2e..34fb69d 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -55,6 +55,10 @@ pub fn build_router() -> Router { "/api/v1/targets/{id}/artifacts", post(handlers::onboarding::add_artifact), ) + .route( + "/api/v1/targets/{id}/webhook-deliveries", + get(handlers::onboarding::list_webhook_deliveries), + ) .route( "/api/v1/targets/{id}/artifacts/upload", // The one route that takes large bodies — and it streams them to diff --git a/compliance-agent/src/database.rs b/compliance-agent/src/database.rs index 173e7e8..229912b 100644 --- a/compliance-agent/src/database.rs +++ b/compliance-agent/src/database.rs @@ -1,6 +1,7 @@ use std::sync::Arc; use dashmap::DashMap; +use futures_util::StreamExt; use mongodb::bson::doc; use mongodb::options::IndexOptions; use mongodb::{Client, Collection, IndexModel}; @@ -25,6 +26,22 @@ const HASH_HEX_LEN: usize = 32; /// fits in the 63-byte cap: `prefix + "_" + 32 hex chars`. const MAX_PREFIX_LEN: usize = MAX_DB_NAME_LEN - 1 - HASH_HEX_LEN; +/// The collection of [`Database::webhook_deliveries`]. +const WEBHOOK_DELIVERIES: &str = "webhook_deliveries"; + +/// Deliveries kept per tenant: the target page shows the newest +/// [`DELIVERIES_SHOWN`] of a target, so this keeps them for 50 busy targets. +const WEBHOOK_DELIVERIES_MAX: u64 = 1_000; + +/// The byte cap the capped collection needs as well; a delivery is well +/// under 1 KiB, so the document cap is the one that bites. +const WEBHOOK_DELIVERIES_BYTES: u64 = 2 * 1024 * 1024; + +/// `create_collection` on a name that exists (Mongo error code 48). +fn is_namespace_exists(e: &mongodb::error::Error) -> bool { + matches!(&*e.kind, mongodb::error::ErrorKind::Command(c) if c.code == 48) +} + /// Per-tenant Mongo connection broker (M7.2 isolation model). /// /// Holds one [`Client`] and hands out [`Database`] handles physically @@ -552,10 +569,71 @@ impl Database { ) .await?; + // webhook_deliveries: capped, then the target page's two lookups + self.ensure_capped( + WEBHOOK_DELIVERIES, + WEBHOOK_DELIVERIES_BYTES, + WEBHOOK_DELIVERIES_MAX, + ) + .await?; + self.webhook_deliveries() + .create_index( + IndexModel::builder() + .keys(doc! { "target_id": 1, "received_at": -1 }) + .build(), + ) + .await?; + self.webhook_deliveries() + .create_index( + IndexModel::builder() + .keys(doc! { + "source_repo.base_url": 1, + "source_repo.repo_id": 1, + "received_at": -1, + }) + .build(), + ) + .await?; + tracing::info!("Database indexes ensured"); Ok(()) } + /// Make `name` a capped collection of at most `bytes` and `max` documents, + /// so Mongo drops the oldest itself. An existing plain collection (written + /// before this ran) is converted; `convertToCapped` takes no document cap, + /// so that one is bounded by size only. + async fn ensure_capped(&self, name: &str, bytes: u64, max: u64) -> Result<(), AgentError> { + let created = self + .inner + .create_collection(name) + .capped(true) + .size(bytes) + .max(max) + .await; + match created { + Ok(()) => return Ok(()), + Err(e) if is_namespace_exists(&e) => {} + Err(e) => return Err(e.into()), + } + let mut specs = self + .inner + .list_collections() + .filter(doc! { "name": name }) + .await?; + let capped = match specs.next().await { + Some(spec) => spec?.options.capped.unwrap_or(false), + None => false, + }; + if !capped { + self.inner + .run_command(doc! { "convertToCapped": name, "size": bytes as i64 }) + .await?; + tracing::info!(collection = name, "converted to a capped collection"); + } + Ok(()) + } + pub fn findings(&self) -> Collection { self.inner.collection("findings") } @@ -661,6 +739,12 @@ impl Database { self.inner.collection("pentest_messages") } + /// The tenant's recent webhook deliveries: a capped collection (see + /// [`Self::ensure_capped`]), newest per target shown on the target page. + pub fn webhook_deliveries(&self) -> Collection { + self.inner.collection(WEBHOOK_DELIVERIES) + } + /// The Werkbank job queue (WB-02): declarative dynamic-execution jobs the /// control plane enqueues and runners lease. pub fn werkbank_jobs(&self) -> Collection { diff --git a/compliance-agent/src/git_source/events.rs b/compliance-agent/src/git_source/events.rs index 2e7d4b7..f2bb342 100644 --- a/compliance-agent/src/git_source/events.rs +++ b/compliance-agent/src/git_source/events.rs @@ -16,6 +16,16 @@ pub enum SourceAction { 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::Ignore(_) => None, + } + } +} + /// A branch deletion pushes this as the new head. const ZERO_SHA: &str = "0000000000000000000000000000000000000000"; @@ -73,6 +83,16 @@ mod tests { }) } + #[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") }); diff --git a/compliance-agent/src/webhooks/deliveries.rs b/compliance-agent/src/webhooks/deliveries.rs new file mode 100644 index 0000000..0d4d3cf --- /dev/null +++ b/compliance-agent/src/webhooks/deliveries.rs @@ -0,0 +1,101 @@ +//! Recording webhook deliveries for the target page (see +//! [`compliance_core::models::webhook_delivery`]). +//! +//! Deliveries live in a capped per-tenant collection: one insert per delivery, +//! Mongo drops the oldest, and a delivery refused before its target exists +//! needs no target to be stored. The target page finds its deliveries by +//! target id or, for a managed repository, by the repository. + +use compliance_core::models::{DeliveryResult, SourceRepo, WebhookDelivery}; +use mongodb::bson::{doc, Document}; + +use crate::agent::ComplianceAgent; + +/// Store `delivery` in the tenant's database. Never fails the webhook: an +/// error is logged and the delivery is lost. +pub async fn record(agent: &ComplianceAgent, tenant_id: &str, delivery: &WebhookDelivery) { + let db = match agent.db_pool.for_tenant_id(tenant_id).await { + Ok(db) => db, + Err(e) => { + tracing::warn!(tenant_id, "webhook delivery not recorded: {e}"); + return; + } + }; + if let Err(e) = db.webhook_deliveries().insert_one(delivery).await { + tracing::warn!(tenant_id, "webhook delivery not recorded: {e}"); + } +} + +/// [`record`] in the background, so the sender's answer does not wait for it. +pub fn spawn_record(agent: &ComplianceAgent, tenant_id: &str, delivery: WebhookDelivery) { + let (agent, tenant_id) = (agent.clone(), tenant_id.to_string()); + tokio::spawn(async move { record(&agent, &tenant_id, &delivery).await }); +} + +/// A per-target webhook (`receiver`) queued work (`detail`) for `target_id`. +/// The scan or review itself shows in the scan runs; this shows that the +/// delivery arrived and was accepted. +pub fn queued(receiver: &str, event: &str, target_id: &str, detail: &str) -> WebhookDelivery { + let mut delivery = WebhookDelivery::new(receiver, event, DeliveryResult::Handled, detail); + delivery.target_id = Some(target_id.to_string()); + delivery +} + +/// The filter for the deliveries of target `target_id`: its own, and for a +/// managed target also those of its repository (a delivery refused before the +/// target was created carries only the repository). +pub fn target_filter(target_id: &str, source_repo: Option<&SourceRepo>) -> Document { + let mut any = vec![doc! { "target_id": target_id }]; + if let Some(repo) = source_repo { + any.push(doc! { + "source_repo.base_url": &repo.base_url, + "source_repo.repo_id": repo.repo_id, + }); + } + doc! { "$or": any } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + + #[test] + fn a_queued_delivery_is_handled_for_its_target() { + let d = queued("github", "push", "abc", "scan queued"); + assert_eq!(d.result, DeliveryResult::Handled); + assert_eq!(d.target_id.as_deref(), Some("abc")); + assert_eq!((d.source.as_str(), d.event.as_str()), ("github", "push")); + } + + #[test] + fn a_plain_target_matches_by_id_only() { + let f = target_filter("abc", None); + let any = f.get_array("$or").unwrap(); + assert_eq!(any.len(), 1); + assert_eq!( + any[0].as_document().unwrap().get_str("target_id").unwrap(), + "abc" + ); + } + + #[test] + fn a_managed_target_also_matches_its_repository() { + let repo = SourceRepo { + base_url: "https://git.example".into(), + repo_id: 42, + full_name: "kunde/fw".into(), + }; + let f = target_filter("abc", Some(&repo)); + let any = f.get_array("$or").unwrap(); + assert_eq!(any.len(), 2); + let by_repo = any[1].as_document().unwrap(); + assert_eq!( + by_repo.get_str("source_repo.base_url").unwrap(), + "https://git.example" + ); + assert_eq!(by_repo.get_i64("source_repo.repo_id").unwrap(), 42); + // the name changes on a rename; the id does not + assert!(by_repo.get("source_repo.full_name").is_none()); + } +} diff --git a/compliance-agent/src/webhooks/gitea.rs b/compliance-agent/src/webhooks/gitea.rs index 0b841e5..6374eea 100644 --- a/compliance-agent/src/webhooks/gitea.rs +++ b/compliance-agent/src/webhooks/gitea.rs @@ -69,6 +69,11 @@ pub async fn handle_gitea_webhook( match event { "push" => { + super::deliveries::spawn_record( + &agent, + &tenant_id, + super::deliveries::queued("gitea", "push", &repo_id, "scan queued"), + ); let agent_clone = (*agent).clone(); let repo_id = repo_id.clone(); let tenant_id = tenant_id.clone(); @@ -117,6 +122,16 @@ async fn handle_pull_request( return StatusCode::BAD_REQUEST; } + super::deliveries::spawn_record( + &agent, + tenant_id, + super::deliveries::queued( + "gitea", + "pull_request", + repo_id, + "pull request review queued", + ), + ); let repo_id = repo_id.to_string(); let tenant_id = tenant_id.to_string(); let head_sha = head_sha.to_string(); diff --git a/compliance-agent/src/webhooks/gitea_source.rs b/compliance-agent/src/webhooks/gitea_source.rs index 05435cd..52ce667 100644 --- a/compliance-agent/src/webhooks/gitea_source.rs +++ b/compliance-agent/src/webhooks/gitea_source.rs @@ -8,6 +8,8 @@ //! A verified delivery that asks for work is answered `202 Accepted` at once; //! the entitlement check, the target and the scan follow in the background, //! so a slow registry or Keycloak never runs into Gitea's delivery timeout. +//! What became of it (handled, refused, failed) is recorded for the target +//! page, since Gitea's delivery log only ever sees the `202`. use std::sync::Arc; use std::time::Instant; @@ -15,10 +17,14 @@ use std::time::Instant; use axum::body::Bytes; use axum::extract::{Extension, Path}; use axum::http::{HeaderMap, StatusCode}; -use compliance_core::models::GitSource; +use compliance_core::models::{DeliveryResult, GitSource, SourceRepo, WebhookDelivery}; +use super::deliveries; use crate::agent::ComplianceAgent; -use crate::git_source::{self, events}; +use crate::git_source::{self, events, Outcome}; + +/// This receiver's name in the delivery records. +const SOURCE: &str = "gitea-source"; /// Answer one delivery and log how long the answer took. /// @@ -96,15 +102,20 @@ async fn answer( let tenant_id = tenant_id.to_string(); let event = event.to_string(); tokio::spawn(async move { - let started = Instant::now(); + let (received_at, started) = (chrono::Utc::now(), Instant::now()); + let repo = action.repo().map(|repo| SourceRepo { + base_url: source.base_url.clone(), + repo_id: repo.id, + full_name: repo.full_name.clone(), + }); let result = process(&agent, &tenant_id, &source, action).await; let elapsed_ms = started.elapsed().as_millis() as u64; - match result { + match &result { Ok(outcome) => tracing::info!( tenant_id, event, elapsed_ms, - %outcome, + ?outcome, "Gitea source webhook handled" ), Err(why) => tracing::warn!( @@ -114,15 +125,38 @@ async fn answer( "Gitea source webhook not handled: {why}" ), } + let mut delivery = delivery_of(&event, &result); + delivery.received_at = received_at; + delivery.elapsed_ms = elapsed_ms; + delivery.source_repo = repo; + deliveries::record(&agent, &tenant_id, &delivery).await; }); StatusCode::ACCEPTED } +/// Why a verified delivery did no work. +#[derive(Debug, Clone, PartialEq, Eq)] +enum NotHandled { + /// Automation refused for the tenant: entitlement, read-only. + Refused(String), + /// The tenant database or the action failed. + Failed(String), +} + +impl std::fmt::Display for NotHandled { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Refused(why) => write!(f, "refused: {why}"), + Self::Failed(why) => write!(f, "{why}"), + } + } +} + /// The work a verified delivery asks for: entitlement, target, scan. /// /// # Returns /// -/// The outcome for the log. +/// What was done. /// /// # Errors /// @@ -134,19 +168,44 @@ async fn process( tenant_id: &str, source: &GitSource, action: events::SourceAction, -) -> Result { +) -> Result { git_source::automation_allowed(agent, tenant_id) .await - .map_err(|why| format!("refused: {why}"))?; + .map_err(NotHandled::Refused)?; let db = agent .db_pool .for_tenant_id(tenant_id) .await - .map_err(|e| format!("tenant database: {e}"))?; - let outcome = git_source::apply_action(agent, &db, tenant_id, source, action) + .map_err(|e| NotHandled::Failed(format!("tenant database: {e}")))?; + git_source::apply_action(agent, &db, tenant_id, source, action) .await - .map_err(|e| e.to_string())?; - Ok(format!("{outcome:?}")) + .map_err(|e| NotHandled::Failed(e.to_string())) +} + +/// The record of a delivery of `event` that came to `result`; the target is +/// set when the delivery created or found one. +fn delivery_of(event: &str, result: &Result) -> WebhookDelivery { + let (outcome, detail, target_id) = match result { + Ok(Outcome::Ensured { target_id, scan }) => ( + DeliveryResult::Handled, + if *scan { + "scan queued" + } else { + "target ready, nothing to scan yet" + }, + Some(target_id.clone()), + ), + Ok(Outcome::Archived(true)) => (DeliveryResult::Handled, "target archived", None), + Ok(Outcome::Archived(false)) => { + (DeliveryResult::Handled, "no active target to archive", None) + } + Ok(Outcome::Ignored(why)) => (DeliveryResult::Handled, *why, None), + Err(NotHandled::Refused(why)) => (DeliveryResult::Refused, why.as_str(), None), + Err(NotHandled::Failed(why)) => (DeliveryResult::Failed, why.as_str(), None), + }; + let mut delivery = WebhookDelivery::new(SOURCE, event, outcome, detail); + delivery.target_id = target_id; + delivery } fn header<'a>(headers: &'a HeaderMap, name: &str) -> &'a str { @@ -162,8 +221,59 @@ mod tests { use hmac::{Hmac, Mac}; use sha2::Sha256; + use super::*; use crate::webhooks::gitea::verify_signature; + #[test] + fn a_refusal_is_recorded_with_its_reason_and_no_target() { + let d = delivery_of( + "push", + &Err(NotHandled::Refused("not entitled: no licence".into())), + ); + assert_eq!(d.result, DeliveryResult::Refused); + assert_eq!(d.detail, "not entitled: no licence"); + assert_eq!((d.source.as_str(), d.event.as_str()), (SOURCE, "push")); + assert!(d.target_id.is_none()); + } + + #[test] + fn a_failure_and_the_handled_outcomes_are_recorded() { + let d = delivery_of("push", &Err(NotHandled::Failed("db down".into()))); + assert_eq!( + (d.result, d.detail.as_str()), + (DeliveryResult::Failed, "db down") + ); + + let ensured = |scan| Outcome::Ensured { + target_id: "t1".into(), + scan, + }; + let d = delivery_of("push", &Ok(ensured(true))); + assert_eq!( + (d.result, d.detail.as_str()), + (DeliveryResult::Handled, "scan queued") + ); + assert_eq!(d.target_id.as_deref(), Some("t1")); + let d = delivery_of("repository", &Ok(ensured(false))); + assert_eq!(d.detail, "target ready, nothing to scan yet"); + + let d = delivery_of("repository", &Ok(Outcome::Archived(true))); + assert_eq!( + (d.result, d.detail.as_str()), + (DeliveryResult::Handled, "target archived") + ); + assert!(d.target_id.is_none()); + } + + #[test] + fn a_refusal_reads_as_one_in_the_log() { + assert_eq!( + NotHandled::Refused("read-only".into()).to_string(), + "refused: read-only" + ); + assert_eq!(NotHandled::Failed("db".into()).to_string(), "db"); + } + fn sign(secret: &str, body: &[u8]) -> String { let mut mac = Hmac::::new_from_slice(secret.as_bytes()).unwrap(); mac.update(body); diff --git a/compliance-agent/src/webhooks/github.rs b/compliance-agent/src/webhooks/github.rs index 0b9f6c1..b3e85a4 100644 --- a/compliance-agent/src/webhooks/github.rs +++ b/compliance-agent/src/webhooks/github.rs @@ -69,6 +69,11 @@ pub async fn handle_github_webhook( match event { "push" => { + super::deliveries::spawn_record( + &agent, + &tenant_id, + super::deliveries::queued("github", "push", &repo_id, "scan queued"), + ); let agent_clone = (*agent).clone(); let repo_id = repo_id.clone(); let tenant_id = tenant_id.clone(); @@ -116,6 +121,16 @@ async fn handle_pull_request( return StatusCode::BAD_REQUEST; } + super::deliveries::spawn_record( + &agent, + tenant_id, + super::deliveries::queued( + "github", + "pull_request", + repo_id, + "pull request review queued", + ), + ); let repo_id = repo_id.to_string(); let tenant_id = tenant_id.to_string(); let head_sha = head_sha.to_string(); diff --git a/compliance-agent/src/webhooks/gitlab.rs b/compliance-agent/src/webhooks/gitlab.rs index b65e88d..cb417dd 100644 --- a/compliance-agent/src/webhooks/gitlab.rs +++ b/compliance-agent/src/webhooks/gitlab.rs @@ -64,6 +64,11 @@ pub async fn handle_gitlab_webhook( match event_type { "push" => { + super::deliveries::spawn_record( + &agent, + &tenant_id, + super::deliveries::queued("gitlab", "push", &repo_id, "scan queued"), + ); let agent_clone = (*agent).clone(); let repo_id = repo_id.clone(); let tenant_id = tenant_id.clone(); @@ -114,6 +119,16 @@ async fn handle_merge_request( return StatusCode::BAD_REQUEST; } + super::deliveries::spawn_record( + &agent, + tenant_id, + super::deliveries::queued( + "gitlab", + "merge_request", + repo_id, + "merge request review queued", + ), + ); let repo_id = repo_id.to_string(); let tenant_id = tenant_id.to_string(); let head_sha = head_sha.to_string(); diff --git a/compliance-agent/src/webhooks/mod.rs b/compliance-agent/src/webhooks/mod.rs index 52ac300..3245746 100644 --- a/compliance-agent/src/webhooks/mod.rs +++ b/compliance-agent/src/webhooks/mod.rs @@ -1,3 +1,4 @@ +pub mod deliveries; pub mod gitea; pub mod gitea_source; pub mod github; diff --git a/compliance-agent/tests/git_source.rs b/compliance-agent/tests/git_source.rs index 92364f2..0404317 100644 --- a/compliance-agent/tests/git_source.rs +++ b/compliance-agent/tests/git_source.rs @@ -2,8 +2,8 @@ //! 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, and the sync diffs a mocked Gitea listing. Skips cleanly when no -//! Mongo is reachable. +//! 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. @@ -15,6 +15,7 @@ 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; @@ -25,7 +26,7 @@ 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::OnboardedTarget; +use compliance_core::models::{DeliveryResult, OnboardedTarget, WebhookDelivery}; use common::dev_config; @@ -309,6 +310,55 @@ async fn platform_api_webhook_and_sync() { ); 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 = + 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") }); @@ -333,6 +383,15 @@ async fn platform_api_webhook_and_sync() { 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); @@ -423,3 +482,42 @@ async fn platform_api_webhook_and_sync() { 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(); +} diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index a5f31e9..af95301 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -21,6 +21,7 @@ pub mod sbom; pub mod scan; pub(crate) mod serde_helpers; pub mod vex; +pub mod webhook_delivery; pub mod werkbank; pub use auth::{AuthInfo, SupportTenant}; @@ -69,6 +70,7 @@ pub use scan::{ RunErrorCode, ScanPhase, ScanRun, ScanRunStatus, ScanStep, ScanType, SkipCode, SkippedStage, }; pub use vex::{VexAssessment, VexError, VexJustification, VexStatus}; +pub use webhook_delivery::{DeliveryResult, WebhookDelivery, DELIVERIES_SHOWN}; pub use werkbank::{ CompleteRequest, CompleteResponse, DastCollect, Executor, HeartbeatAck, HeartbeatRequest, InputRef, Job, JobCollect, JobRecord, JobResult, JobRuntime, JobStatus, JobType, LeaseRequest, diff --git a/compliance-core/src/models/webhook_delivery.rs b/compliance-core/src/models/webhook_delivery.rs new file mode 100644 index 0000000..3e3a79f --- /dev/null +++ b/compliance-core/src/models/webhook_delivery.rs @@ -0,0 +1,131 @@ +//! The recent webhook deliveries of a tenant, as the target page shows them. +//! +//! A webhook answers its sender before the work is done (the managed Gitea +//! source answers `202` and decides about entitlement in the background), so +//! the sender's delivery log cannot tell a refused delivery from a handled +//! one. Each verified delivery that asks for work is recorded here with what +//! became of it. + +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; + +use super::git_source::SourceRepo; + +/// Deliveries shown per target. +pub const DELIVERIES_SHOWN: i64 = 20; + +/// The longest `detail` stored, in characters: a refusal reason or an error +/// fits, a runaway error message does not bloat the collection. +pub const MAX_DETAIL_CHARS: usize = 300; + +/// What became of a delivery. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum DeliveryResult { + /// The work was done or queued. + Handled, + /// Not done on purpose: no entitlement, a read-only tenant. + Refused, + /// Not done because something broke: the database, the git source. + Failed, +} + +/// One webhook delivery. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct WebhookDelivery { + #[serde(rename = "_id", default, skip_serializing_if = "Option::is_none")] + pub id: Option, + /// When the delivery arrived. + #[serde(with = "super::serde_helpers::bson_datetime")] + pub received_at: DateTime, + /// The receiver: `gitea-source`, `gitea`, `github` or `gitlab`. + pub source: String, + /// The sender's event name (`push`, `repository`, `pull_request`, ...). + pub event: String, + pub result: DeliveryResult, + /// What was done, or why not. + #[serde(default)] + pub detail: String, + /// How long the handling took (background work included). + #[serde(default)] + pub elapsed_ms: u64, + /// The target, when it is known. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub target_id: Option, + /// The repository of a managed git source. A delivery refused before its + /// target exists has only this; the target shows it once it does. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source_repo: Option, +} + +impl WebhookDelivery { + /// A delivery received now; `detail` is cut to [`MAX_DETAIL_CHARS`]. + pub fn new(source: &str, event: &str, result: DeliveryResult, detail: &str) -> Self { + Self { + id: None, + received_at: Utc::now(), + source: source.to_string(), + event: event.to_string(), + result, + detail: clip(detail, MAX_DETAIL_CHARS), + elapsed_ms: 0, + target_id: None, + source_repo: None, + } + } +} + +/// `text` cut to at most `max` characters (never inside a character), with +/// an ellipsis when it was cut. +fn clip(text: &str, max: usize) -> String { + match text.char_indices().nth(max) { + // `nth(max)` is the first character past the limit: keep max - 1 and + // the ellipsis, so the result is exactly `max` characters. + Some(_) => { + let keep: String = text.chars().take(max.saturating_sub(1)).collect(); + format!("{keep}…") + } + None => text.to_string(), + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + + #[test] + fn a_short_detail_is_kept_as_is() { + let d = WebhookDelivery::new("gitea", "push", DeliveryResult::Handled, "scan queued"); + assert_eq!(d.detail, "scan queued"); + assert_eq!(d.elapsed_ms, 0); + assert!(d.target_id.is_none() && d.source_repo.is_none()); + } + + #[test] + fn a_long_detail_is_clipped_on_a_character_boundary() { + let long = "ä".repeat(MAX_DETAIL_CHARS + 50); + let d = WebhookDelivery::new("gitea", "push", DeliveryResult::Failed, &long); + assert_eq!(d.detail.chars().count(), MAX_DETAIL_CHARS); + assert!(d.detail.ends_with('…')); + // exactly at the limit: nothing cut + let exact = "x".repeat(MAX_DETAIL_CHARS); + assert_eq!(clip(&exact, MAX_DETAIL_CHARS), exact); + } + + #[test] + fn results_are_snake_case_and_round_trip() { + let mut d = WebhookDelivery::new("gitea-source", "push", DeliveryResult::Refused, "no"); + d.source_repo = Some(SourceRepo { + base_url: "https://git.example".into(), + repo_id: 7, + full_name: "acme/fw".into(), + }); + let json = serde_json::to_value(&d).unwrap(); + assert_eq!(json["result"], "refused"); + assert!(json.get("target_id").is_none()); + let back: WebhookDelivery = serde_json::from_value(json).unwrap(); + assert_eq!(back.source_repo, d.source_repo); + assert_eq!(back.result, DeliveryResult::Refused); + } +} diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index 3e3591e..93b8de6 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -5004,6 +5004,37 @@ tbody tr:last-child td { color: var(--text-tertiary); } +/* Webhook deliveries on the target page: one line each, the reason wraps. */ +.webhook-deliveries { + list-style: none; + display: grid; + gap: 6px; + margin-top: 10px; + font-size: 12.5px; +} + +.webhook-deliveries li { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 4px 10px; +} + +.webhook-deliveries code, +.webhook-delivery-time, +.webhook-delivery-elapsed { + font-family: var(--font-mono); + font-size: 11.5px; + color: var(--text-tertiary); +} + +.webhook-delivery-detail { + flex: 1 1 200px; + min-width: 0; + overflow-wrap: anywhere; + color: var(--text-secondary); +} + .vex-head { display: flex; flex-wrap: wrap; diff --git a/compliance-dashboard/src/components/mod.rs b/compliance-dashboard/src/components/mod.rs index 9d69b21..6a9d9b6 100644 --- a/compliance-dashboard/src/components/mod.rs +++ b/compliance-dashboard/src/components/mod.rs @@ -26,3 +26,4 @@ pub mod support; pub mod theme_toggle; pub mod toast; pub mod vex_panel; +pub mod webhook_deliveries; diff --git a/compliance-dashboard/src/components/webhook_deliveries.rs b/compliance-dashboard/src/components/webhook_deliveries.rs new file mode 100644 index 0000000..912d307 --- /dev/null +++ b/compliance-dashboard/src/components/webhook_deliveries.rs @@ -0,0 +1,77 @@ +//! On a target: its latest webhook deliveries and what became of them. The +//! git server's own delivery log shows a delivery as successful once it is +//! accepted; a refusal (no entitlement, a read-only tenant) shows only here. + +use dioxus::prelude::*; + +use compliance_core::models::DeliveryResult; + +use crate::i18n::texts::{common, webhooks as tx}; +use crate::i18n::{format_time, use_lang, Text}; +use crate::infrastructure::onboarding::fetch_webhook_deliveries; + +/// The badge class and label of a result: amber for refused, red for failed. +fn result_badge(result: DeliveryResult) -> (&'static str, Text) { + match result { + DeliveryResult::Handled => ("badge badge-success", tx::HANDLED), + DeliveryResult::Refused => ("badge badge-medium", tx::REFUSED), + DeliveryResult::Failed => ("badge badge-danger", tx::FAILED), + } +} + +/// The deliveries box of target `target_id`. +#[component] +pub fn WebhookDeliveries(target_id: String) -> Element { + let lang = use_lang()(); + let id = use_signal(|| target_id.clone()); + let deliveries = use_resource(move || async move { fetch_webhook_deliveries(id()).await }); + + rsx! { + p { class: "target-muted", {tx::HINT.get(lang)} } + match &*deliveries.read() { + None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } }, + Some(Err(_)) => rsx! { p { class: "target-muted", {tx::LOAD_FAILED.get(lang)} } }, + Some(Ok(list)) if list.is_empty() => rsx! { p { class: "target-muted", {tx::NONE.get(lang)} } }, + Some(Ok(list)) => rsx! { + ul { class: "webhook-deliveries", + for d in list.iter() { + { + let (class, label) = result_badge(d.result); + rsx! { + li { + span { class: "webhook-delivery-time", {format_time(&d.received_at, lang)} } + span { class: "{class}", {label.get(lang)} } + code { "{d.event}" } + span { class: "webhook-delivery-detail", "{d.detail}" } + span { class: "webhook-delivery-elapsed", "{d.elapsed_ms} ms" } + } + } + } + } + } + }, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn each_result_has_its_badge_in_both_languages() { + for result in [ + DeliveryResult::Handled, + DeliveryResult::Refused, + DeliveryResult::Failed, + ] { + let (class, label) = result_badge(result); + assert!(class.starts_with("badge badge-")); + assert!(!label.de.is_empty() && !label.en.is_empty()); + } + assert_ne!( + result_badge(DeliveryResult::Refused).0, + result_badge(DeliveryResult::Handled).0 + ); + } +} diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 8340f6a..ed0e571 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -3432,3 +3432,40 @@ pub mod access { en: "Read-only: your role can view and export results, but not change anything.", }; } + +/// The webhook deliveries box on the target page. +pub mod webhooks { + use super::Text; + + pub const TITLE: Text = Text { + de: "Webhook-Zustellungen", + en: "Webhook deliveries", + }; + pub const HINT: Text = Text { + de: "Die letzten Zustellungen von Git-Webhooks an dieses Prüfobjekt. Der Git-Server \ + zeigt jede angenommene Zustellung als erfolgreich an; ob sie verarbeitet oder \ + abgelehnt wurde, steht hier.", + en: "The latest git webhook deliveries for this target. The git server shows every \ + accepted delivery as successful; whether it was handled or refused is shown here.", + }; + pub const NONE: Text = Text { + de: "Noch keine Zustellungen.", + en: "No deliveries yet.", + }; + pub const LOAD_FAILED: Text = Text { + de: "Die Zustellungen konnten nicht geladen werden.", + en: "The deliveries could not be loaded.", + }; + pub const HANDLED: Text = Text { + de: "Verarbeitet", + en: "Handled", + }; + pub const REFUSED: Text = Text { + de: "Abgelehnt", + en: "Refused", + }; + pub const FAILED: Text = Text { + de: "Fehlgeschlagen", + en: "Failed", + }; +} diff --git a/compliance-dashboard/src/infrastructure/onboarding.rs b/compliance-dashboard/src/infrastructure/onboarding.rs index 082049e..4f86282 100644 --- a/compliance-dashboard/src/infrastructure/onboarding.rs +++ b/compliance-dashboard/src/infrastructure/onboarding.rs @@ -561,6 +561,28 @@ pub async fn fetch_applicable_scans(id: String) -> Result, +} + +/// The newest webhook deliveries of target `id`, refused and failed ones +/// included. +#[server] +pub async fn fetch_webhook_deliveries( + id: String, +) -> Result, ServerFnError> { + let resp = super::agent_client::agent_get(&format!("/api/v1/targets/{id}/webhook-deliveries")) + .await? + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + let body: DeliveriesResponse = super::agent_client::json_or_error(resp).await?; + Ok(body.data) +} + /// Delete a target (and cascade its findings / SBOM / scan runs / CVE alerts). #[server] pub async fn delete_target(id: String) -> Result { diff --git a/compliance-dashboard/src/pages/target.rs b/compliance-dashboard/src/pages/target.rs index 8335291..e0d744e 100644 --- a/compliance-dashboard/src/pages/target.rs +++ b/compliance-dashboard/src/pages/target.rs @@ -18,6 +18,7 @@ use crate::components::scan_runs::ScanRunList; use crate::components::severity_badge::SeverityBadge; use crate::components::toast::{ToastType, Toasts}; use crate::components::vex_panel::VexPanel; +use crate::components::webhook_deliveries::WebhookDeliveries; use crate::i18n::texts::{common, kinds, targets as tx}; use crate::i18n::use_lang; use crate::infrastructure::evidence::{fetch_compliance, CraCounts}; @@ -308,6 +309,11 @@ pub fn TargetPage(id: String) -> Element { } } + section { class: "card target-webhooks", + div { class: "target-card-head", h3 { {crate::i18n::texts::webhooks::TITLE.get(lang)} } } + div { class: "target-card-body", WebhookDeliveries { target_id: id.clone() } } + } + section { class: "card target-manual", div { class: "target-card-head", h3 { {crate::i18n::texts::manual::TITLE.get(lang)} } -- 2.54.1