Files
pruefwerk/compliance-agent/tests/git_source.rs
T
Sharang ParnerkarandClaude Opus 5.5 1a9af09bc4
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 7m23s
feat(agent): managed git source — auto targets and CRA issues (#439)
A tenant's managed Gitea organisation becomes a git source: every
repository in it is a target, scanned on push, with findings as
labelled issues.

- Git source per tenant (`git_sources`, one doc): https base URL whose
  host must match GIT_SOURCE_HOST_PATTERN, org, bot token and webhook
  secret sealed like other credentials. Platform API
  PUT/GET/DELETE /api/v1/platform/tenants/{id}/git-source; the secret
  is returned only when issued (first PUT or rotate_webhook_secret).
  Read-only GET /api/v1/git-source for IT admins and support.
- POST /webhook/{tenant_id}/gitea-source on the webhook server,
  X-Gitea-Signature checked before anything is created. repository
  created -> target (clone URL built from the source origin, bot token,
  Gitea tracker, type from detection) and first scan unless empty;
  deleted -> target archived; push to the default branch -> scan,
  creating the target if missing. Other orgs are ignored. Entitlement
  and ladder are checked as for scheduled work; usage events as usual.
- Targets get source_repo (unique per instance + repo id, so racing
  deliveries make one target) and archived_at; the scheduler skips
  archived targets.
- Sync job every GIT_SOURCE_SYNC_MINUTES (default 30): lists the org's
  repos (paginated), creates missing, refreshes renamed, archives gone.
- Managed repos get the labels pruefwerk, cra:annex-i and
  severity:* ensured once per run and attached by id; issue bodies name
  the CRA requirement(s) and link into Prüfwerk. User-configured
  trackers behave as before.
- Docs (DE/EN): connecting Managed Git and the bot's minimal rights.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-10-05 12:17:12 +02:00

376 lines
12 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);
// ── 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();
}