Files
pruefwerk/compliance-agent/tests/git_source.rs
T
sharang 7f2b128efd
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Skipped
CI / Deploy Dashboard (push) Successful in 5m29s
CI / Deploy MCP (push) Successful in 3m28s
CI / Deploy Agent (push) Successful in 9m6s
feat(webhooks): the target page shows its last webhook deliveries, refused ones too (#544)
2026-10-09 13:51:47 +00:00

524 lines
17 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();
}
/// 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();
}