Files
pruefwerk/compliance-agent/tests/git_source.rs
T
sharangandClaude Opus 5.5 260d07c783
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Successful in 1m12s
CI / Deploy MCP (push) Successful in 4m22s
CI / Deploy Dashboard (push) Successful in 6m15s
CI / Deploy Agent (push) Successful in 7m42s
feat(agent): managed git source — auto targets and CRA issues (#439) (#444)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-10-05 10:39:19 +00:00

401 lines
13 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 and creates exactly one target per repository however often
//! (or concurrently) it is delivered, deletion archives, 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 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 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()
}
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: 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), (200, 200));
assert_eq!(
h.deliver(TENANT, "repository", &created_evt, Some(sig))
.await,
200
);
assert_eq!(h.managed_count(11).await, 1);
let target =
h.db.onboarded_targets()
.find_one(doc! { "source_repo.repo_id": 11_i64 })
.await
.unwrap()
.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");
// Another organisation's repository is ignored.
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,
200
);
let target =
h.db.onboarded_targets()
.find_one(doc! { "source_repo.repo_id": 11_i64 })
.await
.unwrap()
.unwrap();
assert!(target.archived_at.is_some());
// ── 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();
}