From 1a9af09bc4843c4415536a6d2951fd8a651caee3 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Mon, 5 Oct 2026 12:17:12 +0200 Subject: [PATCH 1/2] =?UTF-8?q?feat(agent):=20managed=20git=20source=20?= =?UTF-8?q?=E2=80=94=20auto=20targets=20and=20CRA=20issues=20(#439)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB --- .env.example | 6 + compliance-agent/src/agent.rs | 9 + .../src/api/handlers/git_source.rs | 48 ++ compliance-agent/src/api/handlers/mod.rs | 1 + compliance-agent/src/api/handlers/platform.rs | 203 +++++ compliance-agent/src/api/routes.rs | 5 + compliance-agent/src/api/server.rs | 7 + compliance-agent/src/config.rs | 3 + compliance-agent/src/database.rs | 25 + compliance-agent/src/git_source/events.rs | 155 ++++ compliance-agent/src/git_source/gitea.rs | 244 ++++++ compliance-agent/src/git_source/mod.rs | 802 ++++++++++++++++++ compliance-agent/src/git_source/sync.rs | 123 +++ compliance-agent/src/lib.rs | 1 + .../src/pipeline/issue_creation.rs | 159 +++- compliance-agent/src/pipeline/repo_view.rs | 4 + compliance-agent/src/scheduler.rs | 31 +- compliance-agent/src/trackers/gitea.rs | 358 +++++++- compliance-agent/src/webhooks/gitea.rs | 2 +- compliance-agent/src/webhooks/gitea_source.rs | 133 +++ compliance-agent/src/webhooks/mod.rs | 1 + compliance-agent/src/webhooks/server.rs | 8 +- compliance-agent/src/werkbank/queue.rs | 2 +- compliance-agent/tests/git_source.rs | 375 ++++++++ compliance-core/src/models/git_source.rs | 149 ++++ compliance-core/src/models/mod.rs | 2 + compliance-core/src/models/onboarding.rs | 14 + docs/.vitepress/config.mts | 2 + docs/guide/managed-git-en.md | 73 ++ docs/guide/managed-git.md | 78 ++ 30 files changed, 2991 insertions(+), 32 deletions(-) create mode 100644 compliance-agent/src/api/handlers/git_source.rs create mode 100644 compliance-agent/src/git_source/events.rs create mode 100644 compliance-agent/src/git_source/gitea.rs create mode 100644 compliance-agent/src/git_source/mod.rs create mode 100644 compliance-agent/src/git_source/sync.rs create mode 100644 compliance-agent/src/webhooks/gitea_source.rs create mode 100644 compliance-agent/tests/git_source.rs create mode 100644 compliance-core/src/models/git_source.rs create mode 100644 docs/guide/managed-git-en.md create mode 100644 docs/guide/managed-git.md diff --git a/.env.example b/.env.example index 9e05358..b91325b 100644 --- a/.env.example +++ b/.env.example @@ -38,6 +38,12 @@ WEBHOOK_PORT=3002 SCAN_CONCURRENCY=2 SCAN_SCHEDULE=0 0 */6 * * * CVE_MONITOR_SCHEDULE=0 0 0 * * * +# Managed git sources (#439): hosts a tenant's Gitea may be on (anchored regex), +# minutes between syncs of the org's repositories, and the public origin of the +# webhook server for the webhook URL the platform API returns. +# GIT_SOURCE_HOST_PATTERN=^[a-z0-9-]+\.code(-stage)?\.breakpilot\.com$ +# GIT_SOURCE_SYNC_MINUTES=30 +# WEBHOOK_PUBLIC_URL=https://pruefwerk-hooks.example.com GIT_CLONE_BASE_PATH=/tmp/compliance-scanner/repos # Dynamic PLC testing — ephemeral soft-PLC provisioning (#183). Off unless diff --git a/compliance-agent/src/agent.rs b/compliance-agent/src/agent.rs index dadc9f5..13476f3 100644 --- a/compliance-agent/src/agent.rs +++ b/compliance-agent/src/agent.rs @@ -42,6 +42,8 @@ pub struct ComplianceAgent { /// Seals tenant credentials before they are stored and opens them where /// they are used (#260). pub secrets: SecretBox, + /// Managed git sources (#439): allowed hosts, sync interval, webhook origin. + pub git_source: Arc, } impl ComplianceAgent { @@ -61,6 +63,12 @@ impl ComplianceAgent { let net_guard = NetGuard::from_env(config.app_env); let scan_gate = Arc::new(ScanGate::new(config.scan_concurrency)); let secrets = SecretBox::from_config(&config); + // `load_config` already refused a malformed value; tests and tools that + // build a config by hand get the defaults. + let git_source = Arc::new(crate::git_source::Settings::from_env().unwrap_or_else(|e| { + tracing::error!("{e}; using the default git source settings"); + crate::git_source::Settings::default() + })); Self { config, db_pool, @@ -73,6 +81,7 @@ impl ComplianceAgent { net_guard, scan_gate, secrets, + git_source, } } diff --git a/compliance-agent/src/api/handlers/git_source.rs b/compliance-agent/src/api/handlers/git_source.rs new file mode 100644 index 0000000..3355abe --- /dev/null +++ b/compliance-agent/src/api/handlers/git_source.rs @@ -0,0 +1,48 @@ +//! `GET /api/v1/git-source` — the workspace's managed git source (#439), +//! read-only. The platform configures it (`/api/v1/platform/...`); the +//! organisation's IT administrator and BreakPilot support may look at it. + +use axum::http::StatusCode; +use axum::Json; + +use compliance_core::models::GitSourceView; +use compliance_core::tenant::OrgRole; +use compliance_core::tenant_ctx::TenantCtx; + +use super::dto::{tenant_db, AgentExt}; +use super::ApiResponse; + +/// Whether the caller may see the git source: IT administrators and support. +fn may_view(tenant: &TenantCtx) -> bool { + tenant.0.staff.is_some() || tenant.0.org_roles.contains(&OrgRole::ItAdmin) +} + +/// The source without secrets, plus the webhook URL; `data: null` when the +/// workspace has none. +pub async fn get_git_source( + axum::extract::Extension(agent): AgentExt, + tenant: TenantCtx, +) -> Result>>, StatusCode> { + if !may_view(&tenant) { + return Err(StatusCode::FORBIDDEN); + } + let db = tenant_db(&agent, &tenant).await?; + let source = crate::git_source::load_source(&db) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let data = source.map(|s| { + let mut v = serde_json::to_value(GitSourceView::from(&s)).unwrap_or_default(); + if let Some(obj) = v.as_object_mut() { + obj.insert( + "webhook_url".into(), + agent.git_source.webhook_url(&tenant.0.tenant_id).into(), + ); + } + v + }); + Ok(Json(ApiResponse { + data, + total: None, + page: None, + })) +} diff --git a/compliance-agent/src/api/handlers/mod.rs b/compliance-agent/src/api/handlers/mod.rs index cb034cc..40591a9 100644 --- a/compliance-agent/src/api/handlers/mod.rs +++ b/compliance-agent/src/api/handlers/mod.rs @@ -5,6 +5,7 @@ pub mod demo_seed; pub mod dto; pub mod evidence; pub mod findings; +pub mod git_source; pub mod graph; pub mod health; pub mod help_chat; diff --git a/compliance-agent/src/api/handlers/platform.rs b/compliance-agent/src/api/handlers/platform.rs index ff52cdf..7b5ff60 100644 --- a/compliance-agent/src/api/handlers/platform.rs +++ b/compliance-agent/src/api/handlers/platform.rs @@ -547,3 +547,206 @@ pub async fn list_targets( .collect(); Ok(Json(serde_json::json!({ "items": items }))) } + +/// The body of `PUT /api/v1/platform/tenants/{id}/git-source`. +#[derive(Debug, Deserialize)] +pub struct GitSourceBody { + /// `https://` of the tenant's Gitea; the host must match + /// `GIT_SOURCE_HOST_PATTERN`. + pub base_url: String, + /// The organisation whose repositories are checked. + pub org: String, + /// The bot user's access token. Required the first time; left out, the + /// stored one is kept. + #[serde(default)] + pub bot_token: Option, + /// Whether webhooks and the sync act on the source (default true). + #[serde(default)] + pub enabled: Option, + /// Issue a new webhook secret even though one is stored. + #[serde(default)] + pub rotate_webhook_secret: bool, +} + +/// `GET /api/v1/platform/tenants/{id}/git-source` — the tenant's managed git +/// source without its secrets, and the webhook URL to register. +pub async fn get_git_source( + State(st): State, + Path(tenant_id): Path, +) -> Result, StatusCode> { + let db = st.agent.db_pool.for_existing_tenant_id(&tenant_id); + let source = crate::git_source::load_source(&db) + .await + .map_err(internal)? + .ok_or(StatusCode::NOT_FOUND)?; + Ok(Json(git_source_json(&st.agent, &tenant_id, &source, None))) +} + +fn git_source_json( + agent: &ComplianceAgent, + tenant_id: &str, + source: &compliance_core::models::GitSource, + new_secret: Option, +) -> serde_json::Value { + let mut v = serde_json::to_value(compliance_core::models::GitSourceView::from(source)) + .unwrap_or_default(); + if let Some(obj) = v.as_object_mut() { + obj.insert( + "webhook_url".into(), + agent.git_source.webhook_url(tenant_id).into(), + ); + obj.insert( + "webhook_secret".into(), + new_secret.map_or(serde_json::Value::Null, Into::into), + ); + } + v +} + +/// `PUT /api/v1/platform/tenants/{id}/git-source` — create or replace the +/// tenant's managed git source. The webhook secret is returned only when it +/// is issued (first time, or `rotate_webhook_secret`); otherwise +/// `webhook_secret` is `null` and the registered webhook keeps working, so a +/// retried call breaks nothing. A sync starts right away. +pub async fn put_git_source( + State(st): State, + Path(tenant_id): Path, + Json(body): Json, +) -> Result, Response> { + use compliance_core::models::{GitSource, GIT_SOURCE_ID}; + + let bad = |msg: String| { + ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ "error": "invalid_git_source", "message": msg })), + ) + .into_response() + }; + let agent = &st.agent; + let base_url = agent + .git_source + .normalize_base_url(&body.base_url) + .map_err(bad)?; + let org = body.org.trim().to_string(); + if !crate::git_source::valid_org(&org) { + return Err(bad(format!("'{org}' is not a valid organisation name"))); + } + let db = agent + .db_pool + .for_tenant_id(&tenant_id) + .await + .map_err(|e| internal(e).into_response())?; + let stored = crate::git_source::load_source(&db) + .await + .map_err(|e| internal(e).into_response())?; + + let sealing_failed = |e: crate::secrets::SecretError| { + tracing::error!("storing a git source credential: {e}"); + StatusCode::SERVICE_UNAVAILABLE.into_response() + }; + let new_token = body + .bot_token + .as_deref() + .map(str::trim) + .filter(|t| !t.is_empty()); + let bot_token = match new_token { + Some(token) => Some(agent.secrets.seal(token).map_err(sealing_failed)?), + None => stored.as_ref().and_then(|s| s.bot_token.clone()), + }; + let Some(bot_token) = bot_token else { + return Err(bad("bot_token is required".into())); + }; + let (webhook_secret, issued) = match stored.as_ref().and_then(|s| s.webhook_secret.clone()) { + Some(secret) if !body.rotate_webhook_secret => (secret, None), + _ => { + let plain = crate::git_source::generate_webhook_secret(); + ( + agent.secrets.seal(&plain).map_err(sealing_failed)?, + Some(plain), + ) + } + }; + let now = chrono::Utc::now(); + let source = GitSource { + id: GIT_SOURCE_ID.to_string(), + base_url, + org, + bot_token: Some(bot_token.clone()), + webhook_secret: Some(webhook_secret), + enabled: body.enabled.unwrap_or(true), + created_at: stored.as_ref().map_or(now, |s| s.created_at), + updated_at: now, + last_sync_at: stored.as_ref().and_then(|s| s.last_sync_at), + }; + db.git_sources() + .replace_one(doc! { "_id": GIT_SOURCE_ID }, &source) + .upsert(true) + .await + .map_err(|e| internal(e).into_response())?; + + // The managed targets clone and open issues with the bot token: a new + // token goes onto them too, or they would keep using the old one. + if new_token.is_some() { + match crate::git_source::retoken_targets(&db, &source.base_url, &bot_token).await { + Ok(0) => {} + Ok(n) => tracing::info!( + tenant_id, + targets = n, + "git source token renewed on targets" + ), + Err(e) => tracing::error!(tenant_id, "renewing the git source token on targets: {e}"), + } + } + if let Some(r) = &agent.registry { + r.invalidate(&tenant_id); + } + tracing::info!(tenant_id, base_url = %source.base_url, org = %source.org, enabled = source.enabled, "git source configured"); + + if source.enabled { + let (agent, tenant) = ((*st.agent).clone(), tenant_id.clone()); + tokio::spawn(async move { + match crate::git_source::sync_tenant(&agent, &tenant).await { + Ok(report) => tracing::info!(tenant_id = tenant, ?report, "initial git sync"), + Err(e) => tracing::warn!(tenant_id = tenant, "initial git sync failed: {e}"), + } + }); + } + Ok(Json(git_source_json(agent, &tenant_id, &source, issued))) +} + +/// `DELETE /api/v1/platform/tenants/{id}/git-source` — remove the source. Its +/// targets are archived (kept with their findings, no longer scanned), since +/// the bot token may be revoked next. +pub async fn delete_git_source( + State(st): State, + Path(tenant_id): Path, +) -> Result, StatusCode> { + use compliance_core::models::GIT_SOURCE_ID; + + let probe = st.agent.db_pool.for_existing_tenant_id(&tenant_id); + let Some(source) = crate::git_source::load_source(&probe) + .await + .map_err(internal)? + else { + return Err(StatusCode::NOT_FOUND); + }; + let db = st + .agent + .db_pool + .for_tenant_id(&tenant_id) + .await + .map_err(internal)?; + db.git_sources() + .delete_one(doc! { "_id": GIT_SOURCE_ID }) + .await + .map_err(internal)?; + let archived = crate::git_source::archive_all(&db, &source.base_url) + .await + .map_err(internal)?; + tracing::info!(tenant_id, archived, "git source removed"); + Ok(Json(serde_json::json!({ + "status": "deleted", + "tenant_id": tenant_id, + "targets_archived": archived, + }))) +} diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index 9b81359..e6885aa 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -15,6 +15,11 @@ pub fn build_router() -> Router { .route("/api/v1/stats/overview", get(handlers::stats_overview)) // The tenant's projects (owned by the registry), for assigning targets. .route("/api/v1/projects", get(handlers::projects::list_projects)) + // The managed git source, read-only (IT admin and support). + .route( + "/api/v1/git-source", + get(handlers::git_source::get_git_source), + ) // BreakPilot support access: choose and open a customer's tenant. .route( "/api/v1/support/tenants", diff --git a/compliance-agent/src/api/server.rs b/compliance-agent/src/api/server.rs index 19c8283..feea978 100644 --- a/compliance-agent/src/api/server.rs +++ b/compliance-agent/src/api/server.rs @@ -310,6 +310,13 @@ pub async fn start_api_server( "/api/v1/platform/tenants/{id}/data", delete(platform::delete_data), ) + // The tenant's managed git source (#439). + .route( + "/api/v1/platform/tenants/{id}/git-source", + get(platform::get_git_source) + .put(platform::put_git_source) + .delete(platform::delete_git_source), + ) .layer(middleware::from_fn_with_state( platform_state.clone(), platform::require_platform_token, diff --git a/compliance-agent/src/config.rs b/compliance-agent/src/config.rs index 45c8d6f..0f5fd23 100644 --- a/compliance-agent/src/config.rs +++ b/compliance-agent/src/config.rs @@ -24,6 +24,9 @@ pub fn load_config() -> Result { // start in every environment, not only hardened ones. crate::secrets::SecretBox::check_config(&config) .map_err(|e| AgentError::Config(e.to_string()))?; + // Same for the managed git source settings: a bad host pattern must not + // leave every host (or none) allowed. + crate::git_source::Settings::from_env().map_err(AgentError::Config)?; if let Err(problems) = config.validate_deployment() { return Err(AgentError::Config(format!( "refusing to start in {}:\n - {}", diff --git a/compliance-agent/src/database.rs b/compliance-agent/src/database.rs index 106098f..8b154c3 100644 --- a/compliance-agent/src/database.rs +++ b/compliance-agent/src/database.rs @@ -505,6 +505,25 @@ impl Database { ) .await?; + // onboarded_targets: one target per managed-git repository (#439), so + // a `repository` and a `push` delivery racing each other cannot + // create two. Partial: user-onboarded targets have no source repo. + self.onboarded_targets() + .create_index( + IndexModel::builder() + .keys(doc! { "source_repo.base_url": 1, "source_repo.repo_id": 1 }) + .options( + IndexOptions::builder() + .unique(true) + .partial_filter_expression( + doc! { "source_repo.repo_id": { "$exists": true } }, + ) + .build(), + ) + .build(), + ) + .await?; + // werkbank_jobs: unique job id (idempotent enqueue by job id) self.werkbank_jobs() .create_index( @@ -592,6 +611,12 @@ impl Database { self.inner.collection("onboarded_targets") } + /// The tenant's managed git source (#439): at most one document, with id + /// [`compliance_core::models::GIT_SOURCE_ID`]. + pub fn git_sources(&self) -> Collection { + self.inner.collection("git_sources") + } + /// A typed handle to an arbitrary collection by name. For bookkeeping /// collections without a dedicated model (e.g. `schema_migrations`, /// `onboarding_migration_log`). diff --git a/compliance-agent/src/git_source/events.rs b/compliance-agent/src/git_source/events.rs new file mode 100644 index 0000000..2e7d4b7 --- /dev/null +++ b/compliance-agent/src/git_source/events.rs @@ -0,0 +1,155 @@ +//! What a system/org webhook delivery from a managed Gitea asks for. + +use super::gitea::GiteaRepo; + +/// The action a delivery maps to. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SourceAction { + /// A repository was created: make it a target, scan it unless it is empty. + Created(GiteaRepo), + /// A repository was deleted: archive its target. + Deleted(GiteaRepo), + /// A push to the default branch: scan the target, creating it first if + /// the `created` delivery was lost. + Push(GiteaRepo), + /// Nothing to do, and why. + Ignore(&'static str), +} + +/// A branch deletion pushes this as the new head. +const ZERO_SHA: &str = "0000000000000000000000000000000000000000"; + +/// Route a delivery: `event` is the `X-Gitea-Event` header, `org` the source's +/// organisation. Repositories of any other owner are ignored, so a system +/// webhook (which sees the whole instance) is safe to use. +pub fn route_event(event: &str, payload: &serde_json::Value, org: &str) -> SourceAction { + let Some(repo) = payload + .get("repository") + .cloned() + .and_then(|r| serde_json::from_value::(r).ok()) + else { + return match event { + "repository" | "push" => SourceAction::Ignore("payload without a repository"), + _ => SourceAction::Ignore("event not handled"), + }; + }; + if !matches!(event, "repository" | "push") { + return SourceAction::Ignore("event not handled"); + } + if !repo.in_org(org) { + return SourceAction::Ignore("repository outside the configured organisation"); + } + match event { + "repository" => match payload.get("action").and_then(|a| a.as_str()) { + Some("created") => SourceAction::Created(repo), + Some("deleted") => SourceAction::Deleted(repo), + _ => SourceAction::Ignore("repository action not handled"), + }, + _ => { + let git_ref = payload.get("ref").and_then(|r| r.as_str()).unwrap_or(""); + let after = payload.get("after").and_then(|a| a.as_str()).unwrap_or(""); + if after == ZERO_SHA { + SourceAction::Ignore("branch deleted") + } else if git_ref != format!("refs/heads/{}", repo.branch()) { + SourceAction::Ignore("push to another branch than the default") + } else { + SourceAction::Push(repo) + } + } + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use serde_json::json; + + use super::*; + + fn repository(owner: &str) -> serde_json::Value { + json!({ + "id": 42, "name": "fw", "full_name": format!("{owner}/fw"), + "owner": { "login": owner }, "default_branch": "main", "empty": true, + }) + } + + #[test] + fn created_and_deleted() { + let p = json!({ "action": "created", "repository": repository("kunde") }); + match route_event("repository", &p, "kunde") { + SourceAction::Created(r) => { + assert_eq!( + (r.id, r.full_name.as_str(), r.empty), + (42, "kunde/fw", true) + ); + } + other => panic!("{other:?}"), + } + let p = json!({ "action": "deleted", "repository": repository("kunde") }); + assert!(matches!( + route_event("repository", &p, "kunde"), + SourceAction::Deleted(r) if r.id == 42 + )); + let p = json!({ "action": "renamed", "repository": repository("kunde") }); + assert!(matches!( + route_event("repository", &p, "kunde"), + SourceAction::Ignore(_) + )); + } + + #[test] + fn push_to_the_default_branch_only() { + let push = |git_ref: &str, after: &str| json!({ "ref": git_ref, "after": after, "repository": repository("kunde") }); + assert!(matches!( + route_event("push", &push("refs/heads/main", "abc"), "kunde"), + SourceAction::Push(r) if r.id == 42 + )); + assert_eq!( + route_event("push", &push("refs/heads/feature", "abc"), "kunde"), + SourceAction::Ignore("push to another branch than the default") + ); + assert_eq!( + route_event("push", &push("refs/tags/v1", "abc"), "kunde"), + SourceAction::Ignore("push to another branch than the default") + ); + assert_eq!( + route_event("push", &push("refs/heads/main", ZERO_SHA), "kunde"), + SourceAction::Ignore("branch deleted") + ); + } + + #[test] + fn other_orgs_are_ignored_case_insensitively_matched() { + let p = json!({ "action": "created", "repository": repository("andere") }); + assert_eq!( + route_event("repository", &p, "kunde"), + SourceAction::Ignore("repository outside the configured organisation") + ); + let p = json!({ "action": "created", "repository": repository("Kunde") }); + assert!(matches!( + route_event("repository", &p, "kunde"), + SourceAction::Created(_) + )); + } + + #[test] + fn unknown_events_and_bad_payloads_are_ignored() { + let p = json!({ "action": "opened", "repository": repository("kunde") }); + assert_eq!( + route_event("pull_request", &p, "kunde"), + SourceAction::Ignore("event not handled") + ); + assert_eq!( + route_event("issues", &json!({}), "kunde"), + SourceAction::Ignore("event not handled") + ); + assert_eq!( + route_event("push", &json!({ "ref": "refs/heads/main" }), "kunde"), + SourceAction::Ignore("payload without a repository") + ); + assert_eq!( + route_event("", &json!({ "repository": repository("kunde") }), "kunde"), + SourceAction::Ignore("event not handled") + ); + } +} diff --git a/compliance-agent/src/git_source/gitea.rs b/compliance-agent/src/git_source/gitea.rs new file mode 100644 index 0000000..3a7ac35 --- /dev/null +++ b/compliance-agent/src/git_source/gitea.rs @@ -0,0 +1,244 @@ +//! The bits of the Gitea API a managed git source needs: the organisation's +//! repository list, and the repository shape shared with webhook payloads. + +use compliance_core::guarded_net::guarded_client_builder; +use compliance_core::NetGuard; +use secrecy::{ExposeSecret, SecretString}; +use serde::Deserialize; + +use crate::error::AgentError; + +/// Repositories per page when listing an organisation. +const PAGE_SIZE: usize = 50; +/// Upper bound on pages (10 000 repositories), so a misbehaving server cannot +/// keep the sync looping. +const MAX_PAGES: usize = 200; + +/// A repository as Gitea describes it, in the org repository list and in the +/// `repository` and `push` webhook payloads. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub struct GiteaRepo { + /// Gitea's id: stable across renames and transfers. + pub id: i64, + pub name: String, + pub full_name: String, + #[serde(default)] + pub owner: Option, + #[serde(default)] + pub default_branch: String, + /// A repository without any commit yet. + #[serde(default)] + pub empty: bool, + /// Archived (read-only) in Gitea. + #[serde(default)] + pub archived: bool, +} + +/// A repository owner (user or organisation). +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub struct GiteaOwner { + #[serde(default)] + pub login: String, +} + +impl GiteaRepo { + /// The owner's login: from `owner`, else the first part of `full_name`. + pub fn owner_login(&self) -> &str { + match &self.owner { + Some(o) if !o.login.is_empty() => &o.login, + _ => self.full_name.split('/').next().unwrap_or_default(), + } + } + + /// Whether the repository belongs to `org` (Gitea logins are + /// case-insensitive). + pub fn in_org(&self, org: &str) -> bool { + self.owner_login().eq_ignore_ascii_case(org) + } + + /// The branch scans follow; `main` when Gitea does not say. + pub fn branch(&self) -> &str { + if self.default_branch.is_empty() { + "main" + } else { + &self.default_branch + } + } +} + +/// Something that can list an organisation's repositories. The sync works +/// against this, so it can be tested without a Gitea. +pub trait RepoLister { + /// Every repository of `org`. + fn list_org_repos( + &self, + org: &str, + ) -> impl std::future::Future, AgentError>> + Send; +} + +/// The bot's client for one Gitea instance. Guarded like every other call to +/// a tenant-chosen address (#294). +pub struct SourceClient { + base_url: String, + token: SecretString, + http: reqwest::Client, +} + +impl SourceClient { + /// A client for `base_url` acting with the bot `token`. + /// + /// # Errors + /// + /// Returns an error if the HTTP client cannot be built. + pub fn new(base_url: &str, token: SecretString, guard: NetGuard) -> Result { + let http = guarded_client_builder(guard) + .timeout(std::time::Duration::from_secs(30)) + .build() + .map_err(|e| AgentError::Other(format!("Gitea client: {e}")))?; + Ok(Self { + base_url: base_url.trim_end_matches('/').to_string(), + token, + http, + }) + } +} + +impl RepoLister for SourceClient { + async fn list_org_repos(&self, org: &str) -> Result, AgentError> { + let mut repos = Vec::new(); + for page in 1..=MAX_PAGES { + let url = format!( + "{}/api/v1/orgs/{}/repos?page={page}&limit={PAGE_SIZE}", + self.base_url, + urlencoding::encode(org) + ); + let resp = self + .http + .get(&url) + .header( + "Authorization", + format!("token {}", self.token.expose_secret()), + ) + .send() + .await?; + if !resp.status().is_success() { + return Err(AgentError::Other(format!( + "Gitea listing the repositories of '{org}' returned {}", + resp.status() + ))); + } + let batch: Vec = resp.json().await?; + let last = batch.len() < PAGE_SIZE; + repos.extend(batch); + if last { + return Ok(repos); + } + } + Err(AgentError::Other(format!( + "'{org}' lists more than {} repositories; sync stopped", + PAGE_SIZE * MAX_PAGES + ))) + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use std::sync::{Arc, Mutex}; + + use axum::extract::{Path, Query}; + use axum::http::HeaderMap; + use axum::routing::get; + use axum::{Json, Router}; + + use super::*; + + fn repo(id: i64, full_name: &str) -> serde_json::Value { + let (owner, name) = full_name.split_once('/').unwrap(); + serde_json::json!({ + "id": id, "name": name, "full_name": full_name, + "owner": { "login": owner }, "default_branch": "main", + "empty": false, "archived": false, + "clone_url": format!("https://elsewhere.invalid/{full_name}.git"), + }) + } + + /// A fake Gitea serving `total` repositories of org `kunde`, paginated. + async fn fake_gitea(total: i64, seen: Arc>>) -> String { + let app = Router::new().route( + "/api/v1/orgs/{org}/repos", + get( + move |Path(org): Path, + Query(q): Query>, + headers: HeaderMap| { + let seen = seen.clone(); + async move { + seen.lock().unwrap().push(format!( + "{org} page={} auth={}", + q["page"], + headers["authorization"].to_str().unwrap() + )); + let page: i64 = q["page"].parse().unwrap(); + let limit: i64 = q["limit"].parse().unwrap(); + let from = (page - 1) * limit + 1; + let to = (page * limit).min(total); + let items: Vec<_> = (from..=to) + .map(|i| repo(i, &format!("kunde/r{i}"))) + .collect(); + Json(items) + } + }, + ), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + format!("http://{addr}") + } + + #[tokio::test] + async fn lists_every_page_with_the_bot_token() { + let seen = Arc::new(Mutex::new(Vec::new())); + let base = fake_gitea(120, seen.clone()).await; + let client = SourceClient::new( + &base, + SecretString::from("bot-tok"), + NetGuard::allow_private(), + ) + .unwrap(); + let repos = client.list_org_repos("kunde").await.unwrap(); + assert_eq!(repos.len(), 120); + assert_eq!(repos[119].full_name, "kunde/r120"); + let seen = seen.lock().unwrap(); + assert_eq!( + *seen, + [ + "kunde page=1 auth=token bot-tok", + "kunde page=2 auth=token bot-tok", + "kunde page=3 auth=token bot-tok", + ] + ); + } + + #[tokio::test] + async fn an_exact_multiple_of_the_page_size_ends_on_an_empty_page() { + let seen = Arc::new(Mutex::new(Vec::new())); + let base = fake_gitea(50, seen.clone()).await; + let client = + SourceClient::new(&base, SecretString::from("t"), NetGuard::allow_private()).unwrap(); + assert_eq!(client.list_org_repos("kunde").await.unwrap().len(), 50); + assert_eq!(seen.lock().unwrap().len(), 2); + } + + #[test] + fn owner_falls_back_to_the_full_name() { + let r: GiteaRepo = serde_json::from_value(serde_json::json!({ + "id": 1, "name": "a", "full_name": "Kunde/a" + })) + .unwrap(); + assert_eq!(r.owner_login(), "Kunde"); + assert!(r.in_org("kunde")); + assert!(!r.in_org("other")); + assert_eq!(r.branch(), "main"); + } +} diff --git a/compliance-agent/src/git_source/mod.rs b/compliance-agent/src/git_source/mod.rs new file mode 100644 index 0000000..b3f59ba --- /dev/null +++ b/compliance-agent/src/git_source/mod.rs @@ -0,0 +1,802 @@ +//! Managed git (#439): every repository of a tenant's Gitea organisation +//! becomes a target, is scanned on push, and gets its findings as issues. +//! +//! * [`Settings`] — which hosts a source may point at, the sync interval and +//! the public webhook origin (environment). +//! * [`events`] — what a system/org webhook delivery asks for. +//! * [`sync`] — the periodic diff of the organisation against the targets. +//! * here — creating, refreshing and archiving the targets, and the +//! entitlement check automated triggers go through. + +pub mod events; +pub mod gitea; +pub mod sync; + +use std::time::Duration; + +use mongodb::bson::{doc, to_bson, Document}; +use regex::Regex; +use secrecy::SecretString; + +use compliance_core::models::{ + default_compliance_profile, Artifact, ArtifactAuth, GitSource, IssueTrackerConfig, + OnboardedTarget, ScanTrigger, SourceRepo, TargetType, TrackerType, GIT_SOURCE_ID, +}; + +use crate::agent::ComplianceAgent; +use crate::database::Database; +use crate::error::AgentError; +use events::SourceAction; +use gitea::{GiteaRepo, RepoLister, SourceClient}; + +/// Hosts a git source may point at unless `GIT_SOURCE_HOST_PATTERN` says +/// otherwise: the managed instances, production and staging. +pub const DEFAULT_HOST_PATTERN: &str = r"^[a-z0-9-]+\.code(-stage)?\.breakpilot\.com$"; +/// Minutes between syncs unless `GIT_SOURCE_SYNC_MINUTES` says otherwise. +pub const DEFAULT_SYNC_MINUTES: u64 = 30; +/// The webhook path of a tenant's source, below the webhook server's origin. +pub fn webhook_path(tenant_id: &str) -> String { + format!("/webhook/{tenant_id}/gitea-source") +} + +/// Deployment settings of the managed git sources. +#[derive(Debug, Clone)] +pub struct Settings { + host_pattern: Regex, + /// Time between two syncs of every tenant's source. + pub sync_interval: Duration, + /// The public origin of the webhook server (`WEBHOOK_PUBLIC_URL`), for the + /// webhook URL an operator registers in Gitea. + pub webhook_public_url: Option, +} + +impl Default for Settings { + fn default() -> Self { + match Self::parse(None, None, None) { + Ok(settings) => settings, + // The defaults are constants, covered by the tests below. + Err(e) => unreachable!("default git source settings: {e}"), + } + } +} + +impl Settings { + /// Read `GIT_SOURCE_HOST_PATTERN`, `GIT_SOURCE_SYNC_MINUTES` and + /// `WEBHOOK_PUBLIC_URL`. + /// + /// # Errors + /// + /// A malformed pattern or interval: startup refuses it rather than run + /// with no or every host allowed. + pub fn from_env() -> Result { + let var = |k: &str| std::env::var(k).ok().filter(|v| !v.trim().is_empty()); + Self::parse( + var("GIT_SOURCE_HOST_PATTERN").as_deref(), + var("GIT_SOURCE_SYNC_MINUTES").as_deref(), + var("WEBHOOK_PUBLIC_URL").as_deref(), + ) + } + + /// Build the settings from raw values (`None` = default). + /// + /// # Errors + /// + /// See [`Self::from_env`]. + pub fn parse( + host_pattern: Option<&str>, + sync_minutes: Option<&str>, + webhook_public_url: Option<&str>, + ) -> Result { + let pattern = host_pattern.unwrap_or(DEFAULT_HOST_PATTERN).trim(); + // Anchored whatever the operator wrote: the whole host must match. + let host_pattern = Regex::new(&format!("^(?:{pattern})$")) + .map_err(|e| format!("GIT_SOURCE_HOST_PATTERN is not a valid regex: {e}"))?; + let minutes = match sync_minutes { + None => DEFAULT_SYNC_MINUTES, + Some(m) => m + .trim() + .parse::() + .ok() + .filter(|m| *m > 0) + .ok_or_else(|| { + format!("GIT_SOURCE_SYNC_MINUTES must be a positive number, got '{m}'") + })?, + }; + let webhook_public_url = match webhook_public_url { + None => None, + Some(u) if u.starts_with("https://") || u.starts_with("http://") => { + Some(u.trim().trim_end_matches('/').to_string()) + } + Some(u) => { + return Err(format!( + "WEBHOOK_PUBLIC_URL must be an http(s) URL, got '{u}'" + )) + } + }; + Ok(Self { + host_pattern, + sync_interval: Duration::from_secs(minutes * 60), + webhook_public_url, + }) + } + + /// The canonical `https://` of a source URL, if it may be used: https + /// only, no credentials, port, path, query or fragment, and a host the + /// allowlist pattern matches. + /// + /// # Errors + /// + /// Why the URL is refused. + pub fn normalize_base_url(&self, raw: &str) -> Result { + let url = reqwest::Url::parse(raw.trim()).map_err(|_| "not a URL".to_string())?; + if url.scheme() != "https" { + return Err("only https is allowed".into()); + } + if !url.username().is_empty() || url.password().is_some() { + return Err("credentials in the URL are not allowed".into()); + } + if url.port().is_some() { + return Err("a port is not allowed".into()); + } + if !matches!(url.path(), "" | "/") || url.query().is_some() || url.fragment().is_some() { + return Err("only the instance origin is allowed, without a path".into()); + } + let host = url.host_str().unwrap_or_default(); + if !self.host_pattern.is_match(host) { + return Err(format!("host '{host}' is not an allowed git source host")); + } + Ok(format!("https://{host}")) + } + + /// The URL to register in Gitea for `tenant_id`: absolute when + /// `WEBHOOK_PUBLIC_URL` is set, else only the path. + pub fn webhook_url(&self, tenant_id: &str) -> String { + format!( + "{}{}", + self.webhook_public_url.as_deref().unwrap_or_default(), + webhook_path(tenant_id) + ) + } +} + +/// Whether `org` is a plausible Gitea organisation name. +pub fn valid_org(org: &str) -> bool { + !org.is_empty() + && org.len() <= 40 + && org + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) +} + +/// A fresh webhook secret: 32 random bytes, hex. +pub fn generate_webhook_secret() -> String { + use rand::RngCore; + let mut bytes = [0u8; 32]; + rand::rng().fill_bytes(&mut bytes); + hex::encode(bytes) +} + +/// Whether automated work (webhook, sync) may change and scan `tenant_id`'s +/// targets now. The same answer the API's entitlement gate and the scheduler +/// give: entitled, not read-only, and on a running rung of the ladder. No +/// registry means dev; a hardened deployment without one refuses. +/// +/// # Errors +/// +/// Why not. +pub async fn automation_allowed(agent: &ComplianceAgent, tenant_id: &str) -> Result<(), String> { + let Some(registry) = agent.registry.as_ref() else { + if agent.config.app_env.is_hardened() { + return Err("no tenant registry in a hardened deployment".into()); + } + return Ok(()); + }; + let check = registry.check_entitlement(tenant_id, None).await?; + if !check.allowed { + return Err(format!( + "not entitled: {}", + check.reason.unwrap_or_else(|| "no reason given".into()) + )); + } + let status = check.status.unwrap_or_default(); + if check.read_only || !crate::registry::scheduler_runs_for(&status) { + return Err(format!("tenant is read-only (status '{status}')")); + } + Ok(()) +} + +/// The tenant's source, if one is configured. +/// +/// # Errors +/// +/// Returns an error if the database cannot be read. +pub async fn load_source(db: &Database) -> Result, AgentError> { + Ok(db + .git_sources() + .find_one(doc! { "_id": GIT_SOURCE_ID }) + .await?) +} + +/// The clone URL of a repository: built from the source's own origin, never +/// taken from a payload, so the clone, the bot token and the issue tracker all +/// go to the instance the source names. +pub fn clone_url(base_url: &str, full_name: &str) -> String { + format!("{base_url}/{full_name}.git") +} + +/// The target for a new repository of a source. `sealed_token` is the source's +/// bot token as stored (sealed); it authenticates the clone and the issues. +pub fn target_for_repo(base_url: &str, repo: &GiteaRepo, sealed_token: String) -> OnboardedTarget { + // A placeholder until detection runs; the scan classifies from the code. + let mut target = OnboardedTarget::new(repo.full_name.clone(), TargetType::BackendService); + let mut artifact = Artifact::git_repo(clone_url(base_url, &repo.full_name), repo.branch()); + artifact.display_name = Some(repo.full_name.clone()); + artifact.auth = Some(ArtifactAuth { + method: "token".to_string(), + secret: Some(sealed_token.clone()), + ..Default::default() + }); + target.artifacts.push(artifact); + target.scan_config.issue_tracker = Some(IssueTrackerConfig { + tracker_type: Some(TrackerType::Gitea), + owner: Some(repo.owner_login().to_string()), + repo: Some(repo.name.clone()), + token: Some(sealed_token), + }); + target.source_repo = Some(SourceRepo { + base_url: base_url.to_string(), + repo_id: repo.id, + full_name: repo.full_name.clone(), + }); + target +} + +/// The update that brings a managed target in line with its repository +/// (renamed, other default branch, archived and back), with the array filters +/// it needs; `None` when it already is. +pub fn refresh_update( + target: &OnboardedTarget, + base_url: &str, + repo: &GiteaRepo, +) -> Option<(Document, Vec)> { + let mut set = Document::new(); + let mut filters = Vec::new(); + if target.name != repo.full_name { + set.insert("name", &repo.full_name); + } + if target + .source_repo + .as_ref() + .is_some_and(|s| s.full_name != repo.full_name) + { + set.insert("source_repo.full_name", &repo.full_name); + } + if let Some(code) = target.code_artifact() { + let url = clone_url(base_url, &repo.full_name); + let branch = code.git.as_ref().map(|g| g.default_branch.as_str()); + if code.source_ref != url { + set.insert("artifacts.$[code].source_ref", url); + } + if branch.is_some_and(|b| b != repo.branch()) { + set.insert("artifacts.$[code].git.default_branch", repo.branch()); + } + if set.keys().any(|k| k.starts_with("artifacts.")) { + filters.push(doc! { "code.id": &code.id }); + } + } + if let Some(tracker) = &target.scan_config.issue_tracker { + if tracker.owner.as_deref() != Some(repo.owner_login()) { + set.insert("scan_config.issue_tracker.owner", repo.owner_login()); + } + if tracker.repo.as_deref() != Some(repo.name.as_str()) { + set.insert("scan_config.issue_tracker.repo", &repo.name); + } + } + let unarchive = target.archived_at.is_some(); + if set.is_empty() && !unarchive { + return None; + } + set.insert("updated_at", mongodb::bson::DateTime::now()); + let mut update = doc! { "$set": set }; + if unarchive { + update.insert("$unset", doc! { "archived_at": "" }); + } + Some((update, filters)) +} + +/// The filter for the target of `repo_id` in the source at `base_url`. +fn repo_filter(base_url: &str, repo_id: i64) -> Document { + doc! { "source_repo.base_url": base_url, "source_repo.repo_id": repo_id } +} + +/// A managed target after [`ensure_target`]. +#[derive(Debug, Clone)] +pub struct Ensured { + pub target_id: String, + /// Created by this call (so it has never been scanned). + pub created: bool, +} + +/// The target of `repo`: found (and refreshed if the repository changed), or +/// created and classified. Idempotent: the same repository id always maps to +/// the same target, also when two deliveries race (unique index). +/// +/// # Errors +/// +/// Returns an error if the source has no bot token or the database fails. +pub async fn ensure_target( + agent: &ComplianceAgent, + db: &Database, + tenant_id: &str, + source: &GitSource, + repo: &GiteaRepo, +) -> Result { + let filter = repo_filter(&source.base_url, repo.id); + if let Some(existing) = db.onboarded_targets().find_one(filter.clone()).await? { + return refresh(db, existing, &source.base_url, repo).await; + } + let token = source + .bot_token + .clone() + .ok_or_else(|| AgentError::Other("the git source has no bot token".into()))?; + let target = target_for_repo(&source.base_url, repo, token); + let created = match crate::targets::create_target(agent, db, tenant_id, target).await { + Ok(created) => created, + Err(AgentError::Database(e)) if crate::werkbank::queue::is_duplicate_key(&e) => { + // Another delivery created it a moment ago. + let existing = db + .onboarded_targets() + .find_one(filter) + .await? + .ok_or_else(|| AgentError::Other("managed target vanished".into()))?; + return refresh(db, existing, &source.base_url, repo).await; + } + Err(e) => return Err(e), + }; + let oid = created + .id + .ok_or_else(|| AgentError::Other("created target has no id".into()))?; + // The type from the detection step, as the onboarding wizard suggests it. + if let Some(detected) = crate::targets::detect_target(db, oid).await? { + if let Some(c) = &detected.classification { + let profile = to_bson(&default_compliance_profile(c.suggested)) + .map_err(|e| AgentError::Other(e.to_string()))?; + let target_type = + to_bson(&c.suggested).map_err(|e| AgentError::Other(e.to_string()))?; + db.onboarded_targets() + .update_one( + doc! { "_id": oid }, + doc! { "$set": { "target_type": target_type, "compliance_profile": profile } }, + ) + .await?; + } + } + tracing::info!( + tenant_id, + target_id = %oid.to_hex(), + repo = %repo.full_name, + "managed git: target created" + ); + Ok(Ensured { + target_id: oid.to_hex(), + created: true, + }) +} + +async fn refresh( + db: &Database, + existing: OnboardedTarget, + base_url: &str, + repo: &GiteaRepo, +) -> Result { + let oid = existing + .id + .ok_or_else(|| AgentError::Other("stored target has no id".into()))?; + if let Some((update, filters)) = refresh_update(&existing, base_url, repo) { + let targets = db.onboarded_targets(); + let mut op = targets.update_one(doc! { "_id": oid }, update); + if !filters.is_empty() { + op = op.array_filters(filters); + } + op.await?; + tracing::info!(target_id = %oid.to_hex(), repo = %repo.full_name, "managed git: target refreshed"); + } + Ok(Ensured { + target_id: oid.to_hex(), + created: false, + }) +} + +/// Archive the target of a deleted repository: kept with its findings, no +/// longer scanned. `Ok(false)` when there is none or it already is archived. +/// +/// # Errors +/// +/// Returns an error if the database fails. +pub async fn archive_target( + db: &Database, + base_url: &str, + repo_id: i64, +) -> Result { + let mut filter = repo_filter(base_url, repo_id); + filter.insert("archived_at", mongodb::bson::Bson::Null); + archive_where(db, filter).await +} + +async fn archive_where(db: &Database, filter: Document) -> Result { + let now = mongodb::bson::DateTime::now(); + let res = db + .onboarded_targets() + .update_one( + filter, + doc! { "$set": { "archived_at": now, "updated_at": now } }, + ) + .await?; + Ok(res.modified_count > 0) +} + +/// Run a scan of `target_id` in the background (through the scan gate, which +/// emits the usage event). +pub fn spawn_scan(agent: &ComplianceAgent, tenant_id: &str, target_id: &str, trigger: ScanTrigger) { + let (agent, tenant_id, target_id) = + (agent.clone(), tenant_id.to_string(), target_id.to_string()); + tokio::spawn(async move { + if let Err(e) = agent.run_target_scan(&tenant_id, &target_id, trigger).await { + tracing::error!(tenant_id, target_id, "managed git scan failed: {e}"); + } + }); +} + +/// What a webhook delivery did. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Outcome { + /// A target was created (or found) and a scan queued if there is code. + Ensured { target_id: String, scan: bool }, + /// The repository's target was archived (`false`: there was none). + Archived(bool), + /// Nothing done. + Ignored(&'static str), +} + +/// Carry out a routed delivery for `tenant_id`. +/// +/// # Errors +/// +/// Returns an error if the target cannot be ensured or archived. +pub async fn apply_action( + agent: &ComplianceAgent, + db: &Database, + tenant_id: &str, + source: &GitSource, + action: SourceAction, +) -> Result { + match action { + SourceAction::Ignore(why) => Ok(Outcome::Ignored(why)), + SourceAction::Deleted(repo) => Ok(Outcome::Archived( + archive_target(db, &source.base_url, repo.id).await?, + )), + SourceAction::Created(repo) => { + let ensured = ensure_target(agent, db, tenant_id, source, &repo).await?; + // An empty repository has nothing to scan; its first push will. + let scan = ensured.created && !repo.empty; + if scan { + spawn_scan(agent, tenant_id, &ensured.target_id, ScanTrigger::Webhook); + } + Ok(Outcome::Ensured { + target_id: ensured.target_id, + scan, + }) + } + SourceAction::Push(repo) => { + let ensured = ensure_target(agent, db, tenant_id, source, &repo).await?; + spawn_scan(agent, tenant_id, &ensured.target_id, ScanTrigger::Webhook); + Ok(Outcome::Ensured { + target_id: ensured.target_id, + scan: true, + }) + } + } +} + +/// What one sync of a tenant did. +#[derive(Debug, Default, Clone, PartialEq, Eq, serde::Serialize)] +pub struct SyncReport { + pub repos: usize, + pub created: usize, + pub refreshed: usize, + pub archived: usize, +} + +/// Sync `tenant_id`'s source, if it has an enabled one and automation is +/// allowed. `Ok(None)` when there is nothing to sync. +/// +/// # Errors +/// +/// Returns an error if the source cannot be read or listed. +pub async fn sync_tenant( + agent: &ComplianceAgent, + tenant_id: &str, +) -> Result, AgentError> { + // Read without creating anything: most tenants have no source. + let probe = agent.db_pool.for_existing_tenant_id(tenant_id); + let Some(source) = load_source(&probe).await? else { + return Ok(None); + }; + if !source.enabled { + return Ok(None); + } + if let Err(why) = automation_allowed(agent, tenant_id).await { + tracing::info!(tenant_id, "managed git sync skipped: {why}"); + return Ok(None); + } + let db = agent.db_pool.for_tenant_id(tenant_id).await?; + let token = agent + .secrets + .open_opt(source.bot_token.as_ref(), "git source bot token") + .ok_or_else(|| AgentError::Other("the git source has no usable bot token".into()))?; + let client = SourceClient::new(&source.base_url, SecretString::from(token), agent.net_guard)?; + let report = sync_with(agent, &db, tenant_id, &source, &client).await?; + db.git_sources() + .update_one( + doc! { "_id": GIT_SOURCE_ID }, + doc! { "$set": { "last_sync_at": mongodb::bson::DateTime::now() } }, + ) + .await?; + Ok(Some(report)) +} + +/// One sync against `lister`. +/// +/// # Errors +/// +/// Returns an error if the repositories cannot be listed or the targets read. +/// A single repository that cannot be ensured is logged and skipped. +pub async fn sync_with( + agent: &ComplianceAgent, + db: &Database, + tenant_id: &str, + source: &GitSource, + lister: &L, +) -> Result { + use futures_util::TryStreamExt; + + let repos = lister.list_org_repos(&source.org).await?; + let targets: Vec = db + .onboarded_targets() + .find(doc! { "source_repo.base_url": &source.base_url }) + .await? + .try_collect() + .await?; + let plan = sync::plan_sync(&repos, &targets, &source.base_url, &source.org); + let mut report = SyncReport { + repos: repos.len(), + ..Default::default() + }; + for repo in &plan.ensure { + match ensure_target(agent, db, tenant_id, source, repo).await { + Ok(e) if e.created => { + report.created += 1; + if !repo.empty { + spawn_scan(agent, tenant_id, &e.target_id, ScanTrigger::Scheduled); + } + } + Ok(_) => report.refreshed += 1, + Err(err) => { + tracing::warn!(tenant_id, repo = %repo.full_name, "managed git sync: {err}"); + } + } + } + for oid in &plan.archive { + let filter = doc! { "_id": *oid, "archived_at": mongodb::bson::Bson::Null }; + if archive_where(db, filter).await? { + report.archived += 1; + } + } + Ok(report) +} + +/// Archive every managed target of `base_url`: the source was removed, so +/// nothing may scan with its (possibly revoked) token any more. +/// +/// # Errors +/// +/// Returns an error if the database fails. +pub async fn archive_all(db: &Database, base_url: &str) -> Result { + let now = mongodb::bson::DateTime::now(); + let res = db + .onboarded_targets() + .update_many( + doc! { "source_repo.base_url": base_url, "archived_at": mongodb::bson::Bson::Null }, + doc! { "$set": { "archived_at": now, "updated_at": now } }, + ) + .await?; + Ok(res.modified_count) +} + +/// Put a new sealed bot token on every managed target of `base_url` (clone +/// credentials and issue tracker), after the source's token was replaced. +/// +/// # Errors +/// +/// Returns an error if the database fails. +pub async fn retoken_targets( + db: &Database, + base_url: &str, + sealed_token: &str, +) -> Result { + let res = db + .onboarded_targets() + .update_many( + doc! { "source_repo.base_url": base_url }, + doc! { "$set": { + "artifacts.$[git].auth.secret": sealed_token, + "scan_config.issue_tracker.token": sealed_token, + "updated_at": mongodb::bson::DateTime::now(), + } }, + ) + .array_filters(vec![doc! { "git.kind": "git_repo" }]) + .await?; + Ok(res.modified_count) +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + + const BASE: &str = "https://kunde.code.breakpilot.com"; + + fn repo(id: i64, full_name: &str, branch: &str) -> GiteaRepo { + serde_json::from_value(serde_json::json!({ + "id": id, "name": full_name.split('/').nth(1).unwrap(), + "full_name": full_name, "owner": { "login": full_name.split('/').next().unwrap() }, + "default_branch": branch, + })) + .unwrap() + } + + #[test] + fn host_allowlist_default() { + let s = Settings::default(); + assert_eq!( + s.normalize_base_url("https://kunde.code.breakpilot.com/") + .unwrap(), + BASE + ); + assert_eq!( + s.normalize_base_url("https://BP-Test.code-stage.breakpilot.com") + .unwrap(), + "https://bp-test.code-stage.breakpilot.com" + ); + for bad in [ + "http://kunde.code.breakpilot.com", + "https://kunde.code.breakpilot.com.evil.com", + "https://evil.com/kunde.code.breakpilot.com", + "https://a.b.code.breakpilot.com", + "https://git.breakpilot.com", + "https://user:pw@kunde.code.breakpilot.com", + "https://kunde.code.breakpilot.com:8443", + "https://kunde.code.breakpilot.com/sub", + "https://kunde.code.breakpilot.com/?x=1", + "ssh://git@kunde.code.breakpilot.com", + "kunde.code.breakpilot.com", + "", + ] { + assert!(s.normalize_base_url(bad).is_err(), "{bad} must be refused"); + } + } + + #[test] + fn host_allowlist_from_the_environment_is_anchored() { + let s = Settings::parse(Some(r"git\.breakpilot\.com"), None, None).unwrap(); + assert!(s.normalize_base_url("https://git.breakpilot.com").is_ok()); + assert!(s.normalize_base_url("https://xgit.breakpilot.com").is_err()); + assert!(s + .normalize_base_url("https://git.breakpilot.com.evil.com") + .is_err()); + assert!(Settings::parse(Some("("), None, None).is_err()); + } + + #[test] + fn settings_parse_interval_and_webhook_origin() { + let s = Settings::default(); + assert_eq!(s.sync_interval, Duration::from_secs(30 * 60)); + assert_eq!(s.webhook_url("t1"), "/webhook/t1/gitea-source"); + let s = Settings::parse(None, Some("5"), Some("https://hooks.example.com/")).unwrap(); + assert_eq!(s.sync_interval, Duration::from_secs(300)); + assert_eq!( + s.webhook_url("t1"), + "https://hooks.example.com/webhook/t1/gitea-source" + ); + assert!(Settings::parse(None, Some("0"), None).is_err()); + assert!(Settings::parse(None, Some("x"), None).is_err()); + assert!(Settings::parse(None, None, Some("hooks.example.com")).is_err()); + } + + #[test] + fn orgs_and_secrets() { + assert!(valid_org("bp-test")); + assert!(valid_org("Kunde_1.x")); + assert!(!valid_org("")); + assert!(!valid_org("a/b")); + assert!(!valid_org("a b")); + let a = generate_webhook_secret(); + assert_eq!(a.len(), 64); + assert_ne!(a, generate_webhook_secret()); + } + + #[test] + fn a_repo_becomes_a_managed_target_on_its_own_instance() { + let mut r = repo(7, "kunde/firmware", "develop"); + r.owner = None; + let t = target_for_repo(BASE, &r, "enc:v1:tok".into()); + assert_eq!(t.name, "kunde/firmware"); + let code = t.code_artifact().unwrap(); + assert_eq!( + code.source_ref, + "https://kunde.code.breakpilot.com/kunde/firmware.git" + ); + assert_eq!(code.git.as_ref().unwrap().default_branch, "develop"); + let auth = code.auth.as_ref().unwrap(); + assert_eq!( + (auth.method.as_str(), auth.secret.as_deref()), + ("token", Some("enc:v1:tok")) + ); + let it = t.scan_config.issue_tracker.as_ref().unwrap(); + assert_eq!(it.tracker_type, Some(TrackerType::Gitea)); + assert_eq!( + (it.owner.as_deref(), it.repo.as_deref()), + (Some("kunde"), Some("firmware")) + ); + assert_eq!(it.token.as_deref(), Some("enc:v1:tok")); + assert_eq!( + t.source_repo, + Some(SourceRepo { + base_url: BASE.into(), + repo_id: 7, + full_name: "kunde/firmware".into() + }) + ); + assert!(!t.webhook_enabled && t.webhook_secret.is_none()); + } + + #[test] + fn the_same_repo_again_needs_no_change() { + // Idempotency at the record level: ensuring a repository whose target + // exists and matches changes nothing (the unique index covers races). + let r = repo(7, "kunde/fw", "main"); + let t = target_for_repo(BASE, &r, "enc".into()); + assert!(refresh_update(&t, BASE, &r).is_none()); + } + + #[test] + fn a_rename_branch_change_or_unarchive_is_refreshed() { + let t = target_for_repo(BASE, &repo(7, "kunde/fw", "main"), "enc".into()); + let (update, filters) = refresh_update(&t, BASE, &repo(7, "kunde/fw2", "dev")).unwrap(); + let set = update.get_document("$set").unwrap(); + assert_eq!(set.get_str("name").unwrap(), "kunde/fw2"); + assert_eq!(set.get_str("source_repo.full_name").unwrap(), "kunde/fw2"); + assert_eq!( + set.get_str("artifacts.$[code].source_ref").unwrap(), + "https://kunde.code.breakpilot.com/kunde/fw2.git" + ); + assert_eq!( + set.get_str("artifacts.$[code].git.default_branch").unwrap(), + "dev" + ); + assert_eq!( + set.get_str("scan_config.issue_tracker.repo").unwrap(), + "fw2" + ); + assert!(!set.contains_key("scan_config.issue_tracker.owner")); + assert!(!update.contains_key("$unset")); + assert_eq!(filters.len(), 1); + + let mut archived = t.clone(); + archived.archived_at = Some(chrono::Utc::now()); + let (update, filters) = + refresh_update(&archived, BASE, &repo(7, "kunde/fw", "main")).unwrap(); + assert!(update.contains_key("$unset")); + assert!(filters.is_empty()); + } +} diff --git a/compliance-agent/src/git_source/sync.rs b/compliance-agent/src/git_source/sync.rs new file mode 100644 index 0000000..7773eec --- /dev/null +++ b/compliance-agent/src/git_source/sync.rs @@ -0,0 +1,123 @@ +//! The periodic sync's diff: the organisation's repositories against the +//! tenant's managed targets. A safety net for lost webhook deliveries. + +use mongodb::bson::oid::ObjectId; + +use compliance_core::models::OnboardedTarget; + +use super::gitea::GiteaRepo; + +/// What a sync does. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct SyncPlan { + /// Repositories whose target is missing, archived or out of date + /// (renamed, other default branch): ensured. + pub ensure: Vec, + /// Targets whose repository is gone: archived. + pub archive: Vec, +} + +/// Diff `repos` (the organisation's repositories now) against `targets` (the +/// tenant's managed targets of this source, archived ones included). +pub fn plan_sync( + repos: &[GiteaRepo], + targets: &[OnboardedTarget], + base_url: &str, + org: &str, +) -> SyncPlan { + let repos: Vec<&GiteaRepo> = repos.iter().filter(|r| r.in_org(org)).collect(); + let target_of = |id: i64| { + targets.iter().find(|t| { + t.source_repo + .as_ref() + .is_some_and(|s| s.repo_id == id && s.base_url == base_url) + }) + }; + let ensure = repos + .iter() + .filter(|r| match target_of(r.id) { + None => true, + Some(t) => super::refresh_update(t, base_url, r).is_some(), + }) + .map(|r| (*r).clone()) + .collect(); + let archive = targets + .iter() + .filter(|t| t.archived_at.is_none()) + .filter_map(|t| { + let source = t.source_repo.as_ref()?; + let gone = source.base_url == base_url && !repos.iter().any(|r| r.id == source.repo_id); + if gone { + t.id + } else { + None + } + }) + .collect(); + SyncPlan { ensure, archive } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + use crate::git_source::target_for_repo; + + const BASE: &str = "https://kunde.code.breakpilot.com"; + + fn repo(id: i64, full_name: &str) -> GiteaRepo { + serde_json::from_value(serde_json::json!({ + "id": id, "name": full_name.split('/').nth(1).unwrap(), + "full_name": full_name, "owner": { "login": full_name.split('/').next().unwrap() }, + "default_branch": "main", + })) + .unwrap() + } + + fn target(id: i64, full_name: &str) -> OnboardedTarget { + let mut t = target_for_repo(BASE, &repo(id, full_name), "enc:v1:x".into()); + t.id = Some(ObjectId::new()); + t + } + + #[test] + fn creates_missing_archives_gone_and_leaves_the_rest() { + let repos = [repo(1, "kunde/a"), repo(2, "kunde/b"), repo(3, "andere/c")]; + let gone = target(9, "kunde/old"); + let targets = vec![target(1, "kunde/a"), gone.clone()]; + let plan = plan_sync(&repos, &targets, BASE, "kunde"); + assert_eq!(plan.ensure, vec![repo(2, "kunde/b")]); + assert_eq!(plan.archive, vec![gone.id.unwrap()]); + } + + #[test] + fn a_second_sync_of_the_same_state_does_nothing() { + let repos = [repo(1, "kunde/a"), repo(2, "kunde/b")]; + let targets = vec![target(1, "kunde/a"), target(2, "kunde/b")]; + assert_eq!( + plan_sync(&repos, &targets, BASE, "kunde"), + SyncPlan::default() + ); + } + + #[test] + fn renamed_and_reappeared_repos_are_ensured() { + let mut archived = target(2, "kunde/b"); + archived.archived_at = Some(chrono::Utc::now()); + let targets = vec![target(1, "kunde/a"), archived]; + let repos = [repo(1, "kunde/a-neu"), repo(2, "kunde/b")]; + let plan = plan_sync(&repos, &targets, BASE, "kunde"); + assert_eq!(plan.ensure, repos.to_vec()); + assert!(plan.archive.is_empty()); + } + + #[test] + fn archived_targets_are_not_archived_again_and_other_instances_untouched() { + let mut archived = target(5, "kunde/x"); + archived.archived_at = Some(chrono::Utc::now()); + let mut elsewhere = target(6, "kunde/y"); + elsewhere.source_repo.as_mut().unwrap().base_url = "https://alt.code.breakpilot.com".into(); + let plan = plan_sync(&[], &[archived, elsewhere], BASE, "kunde"); + assert_eq!(plan, SyncPlan::default()); + } +} diff --git a/compliance-agent/src/lib.rs b/compliance-agent/src/lib.rs index 78b641b..71bf4ff 100644 --- a/compliance-agent/src/lib.rs +++ b/compliance-agent/src/lib.rs @@ -10,6 +10,7 @@ pub mod demo_seed; pub mod error; pub mod evidence; pub mod fixtures; +pub mod git_source; pub mod import; pub mod ingest; pub mod lifecycle; diff --git a/compliance-agent/src/pipeline/issue_creation.rs b/compliance-agent/src/pipeline/issue_creation.rs index 53dd2a0..78a4df4 100644 --- a/compliance-agent/src/pipeline/issue_creation.rs +++ b/compliance-agent/src/pipeline/issue_creation.rs @@ -135,6 +135,28 @@ impl PipelineOrchestrator { tracker.name() ); + // A managed repository (#439) gets its labels created once per run + // and attached by id. If that fails (no permission), the issues are + // still opened, with the label names in the body as before. + let managed_labels = match (&tracker, repo.managed) { + (TrackerDispatch::Gitea(gitea), true) => match gitea + .ensure_labels( + owner, + tracker_repo_name, + &trackers::gitea::pruefwerk_labels(), + ) + .await + { + Ok(ids) => Some(ids), + Err(e) => { + tracing::warn!("[{repo_id}] Could not ensure the Prüfwerk labels: {e}"); + None + } + }, + _ => None, + }; + let dashboard = std::env::var("DASHBOARD_PUBLIC_URL").unwrap_or_default(); + let mut created = 0u32; for finding in actionable { let title = format!( @@ -167,17 +189,43 @@ impl PipelineOrchestrator { if found_existing { continue; } - let body = format_issue_body(finding); + let mut body = format_issue_body(finding); + if repo.managed { + if let Some(link) = finding_link(&dashboard, repo_id) { + body.push_str(&format!( + "\n[Open in Prüfwerk / In Prüfwerk öffnen]({link})" + )); + } + } let labels = vec![ format!("severity:{}", finding.severity), format!("scanner:{}", finding.scanner), "compliance-scanner".to_string(), ]; - match tracker - .create_issue(owner, tracker_repo_name, &title, &body, &labels) - .await - { + let result = match (&tracker, &managed_labels) { + (TrackerDispatch::Gitea(gitea), Some(ids)) => { + let label_ids = label_ids( + ids, + &trackers::gitea::issue_label_names(&finding.severity.to_string()), + ); + gitea + .create_issue_with_label_ids( + owner, + tracker_repo_name, + &title, + &body, + &label_ids, + ) + .await + } + _ => { + tracker + .create_issue(owner, tracker_repo_name, &title, &body, &labels) + .await + } + }; + match result { Ok(mut issue) => { issue.finding_id = finding .id @@ -232,6 +280,9 @@ pub(super) fn format_issue_body(finding: &Finding) -> String { if let Some(cwe) = &finding.cwe { body.push_str(&format!("**CWE:** {}\n", cwe)); } + for requirement in cra_requirements(&finding.control_refs) { + body.push_str(&format!("**CRA:** {requirement}\n")); + } body.push_str(&format!("\n### Description\n\n{}\n", finding.description)); @@ -262,3 +313,101 @@ pub(super) fn format_issue_body(finding: &Finding) -> String { body } + +/// The CRA requirements a finding is evidence for, as `cra-ai-8 — `, +/// from its stamped `control_refs`. Titles come from the CRA control map. +fn cra_requirements(control_refs: &[String]) -> Vec<String> { + let map = control_map::ControlMap::cra().ok(); + control_refs + .iter() + .filter(|id| id.starts_with("cra-")) + .map(|id| { + match map + .as_ref() + .and_then(|m| m.coverage(id)) + .map(|c| c.title.as_str()) + .filter(|t| !t.is_empty()) + { + Some(title) => format!("{id} — {title} (Annex I)"), + None => format!("{id} (Annex I)"), + } + }) + .collect() +} + +/// The finding list of a target in the Prüfwerk dashboard; `None` unless the +/// dashboard's public origin is an https URL. +fn finding_link(dashboard: &str, target_id: &str) -> Option<String> { + let dashboard = dashboard.trim_end_matches('/'); + dashboard + .starts_with("https://") + .then(|| format!("{dashboard}/findings?target={target_id}")) +} + +/// The ids of `names` among the ensured labels; a name without an id is left +/// out. +fn label_ids(ids: &std::collections::HashMap<String, i64>, names: &[String]) -> Vec<i64> { + names.iter().filter_map(|n| ids.get(n).copied()).collect() +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + + #[test] + fn cra_requirements_name_the_control() { + let refs = vec!["cra-ai-1".to_string(), "iec-x".to_string()]; + let lines = cra_requirements(&refs); + assert_eq!(lines.len(), 1); + assert!(lines[0].starts_with("cra-ai-1 — "), "{lines:?}"); + assert!(lines[0].ends_with("(Annex I)")); + assert_eq!( + cra_requirements(&["cra-unknown".to_string()]), + ["cra-unknown (Annex I)"] + ); + } + + #[test] + fn the_body_carries_cwe_and_cra() { + let mut f = Finding::new( + "r".into(), + "fp1".into(), + "semgrep".into(), + ScanType::Sast, + "SQL injection".into(), + "desc".into(), + Severity::High, + ); + f.cwe = Some("CWE-89".into()); + f.control_refs = vec!["cra-ai-1".into()]; + let body = format_issue_body(&f); + assert!(body.contains("**CWE:** CWE-89")); + assert!(body.contains("**CRA:** cra-ai-1")); + assert!(body.contains("`fp1`")); + } + + #[test] + fn links_only_to_an_https_dashboard() { + assert_eq!( + finding_link("https://pruefwerk.breakpilot.com/", "t1").as_deref(), + Some("https://pruefwerk.breakpilot.com/findings?target=t1") + ); + assert_eq!(finding_link("", "t1"), None); + assert_eq!(finding_link("http://x", "t1"), None); + } + + #[test] + fn label_ids_follow_the_names() { + let ids = std::collections::HashMap::from([ + ("pruefwerk".to_string(), 1), + ("cra:annex-i".to_string(), 2), + ("severity:high".to_string(), 5), + ]); + let names = crate::trackers::gitea::issue_label_names("high"); + assert_eq!(label_ids(&ids, &names), vec![1, 2, 5]); + // a label that could not be ensured is simply left off + let names = crate::trackers::gitea::issue_label_names("low"); + assert_eq!(label_ids(&ids, &names), vec![1, 2]); + } +} diff --git a/compliance-agent/src/pipeline/repo_view.rs b/compliance-agent/src/pipeline/repo_view.rs index eb80f64..f2ecbeb 100644 --- a/compliance-agent/src/pipeline/repo_view.rs +++ b/compliance-agent/src/pipeline/repo_view.rs @@ -37,6 +37,9 @@ pub struct RepoView { pub auth_username: Option<String>, pub last_scanned_commit: Option<String>, pub findings_count: u32, + /// Created by a managed git source (#439): its Gitea issues get the + /// Prüfwerk/CRA labels and a link into Prüfwerk. + pub managed: bool, } impl RepoView { @@ -63,6 +66,7 @@ impl RepoView { auth_username: None, last_scanned_commit: None, findings_count: target.findings_count, + managed: target.source_repo.is_some(), }; if let Some(git) = &code.git { view.default_branch = git.default_branch.clone(); diff --git a/compliance-agent/src/scheduler.rs b/compliance-agent/src/scheduler.rs index 0ca7f29..fb47b87 100644 --- a/compliance-agent/src/scheduler.rs +++ b/compliance-agent/src/scheduler.rs @@ -65,6 +65,29 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError> .await .map_err(|e| AgentError::Scheduler(format!("Failed to add CVE monitor job: {e}")))?; + // Managed git sync (#439): the organisation's repositories against the + // targets, a safety net for lost webhook deliveries. + let sync_agent = agent.clone(); + let sync_job = Job::new_repeated_async(agent.git_source.sync_interval, move |_uuid, _lock| { + let agent = sync_agent.clone(); + Box::pin(async move { + for tenant_id in scheduler_tenants(&agent).await { + match crate::git_source::sync_tenant(&agent, &tenant_id).await { + Ok(Some(report)) => { + tracing::info!(tenant_id, ?report, "managed git sync done"); + } + Ok(None) => {} + Err(e) => tracing::warn!(tenant_id, "managed git sync failed: {e}"), + } + } + }) + }) + .map_err(|e| AgentError::Scheduler(format!("Failed to create git sync job: {e}")))?; + sched + .add(sync_job) + .await + .map_err(|e| AgentError::Scheduler(format!("Failed to add git sync job: {e}")))?; + sched .start() .await @@ -161,7 +184,13 @@ async fn scan_all_repos(agent: &ComplianceAgent, tenant_id: &str) { None => return, }; - let cursor = match db.onboarded_targets().find(doc! {}).await { + // Archived targets (their managed repository was deleted) keep their + // findings but are not scanned any more. + let cursor = match db + .onboarded_targets() + .find(doc! { "archived_at": null }) + .await + { Ok(c) => c, Err(e) => { tracing::error!("Failed to list targets for tenant '{tenant_id}': {e}"); diff --git a/compliance-agent/src/trackers/gitea.rs b/compliance-agent/src/trackers/gitea.rs index 659d1a5..1ad1a78 100644 --- a/compliance-agent/src/trackers/gitea.rs +++ b/compliance-agent/src/trackers/gitea.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; + use compliance_core::error::CoreError; use compliance_core::guarded_net::guarded_client_builder; use compliance_core::models::{TrackerIssue, TrackerType}; @@ -35,42 +37,129 @@ impl GiteaTracker { fn api_url(&self, path: &str) -> String { format!("{}/api/v1{}", self.base_url, path) } -} -impl IssueTracker for GiteaTracker { - fn name(&self) -> &str { - "gitea" + fn auth(&self) -> String { + format!("token {}", self.token.expose_secret()) } - async fn create_issue( + /// Every label of a repository, all pages. + /// + /// # Errors + /// + /// [`CoreError::IssueTracker`] if Gitea cannot be asked or answers with an + /// error. + pub async fn list_labels(&self, owner: &str, repo: &str) -> Result<Vec<GiteaLabel>, CoreError> { + let mut labels = Vec::new(); + for page in 1..=MAX_LABEL_PAGES { + let url = self.api_url(&format!( + "/repos/{owner}/{repo}/labels?page={page}&limit={LABEL_PAGE_SIZE}" + )); + let resp = self + .http + .get(&url) + .header("Authorization", self.auth()) + .send() + .await + .map_err(|e| CoreError::IssueTracker(format!("Gitea list labels failed: {e}")))?; + if !resp.status().is_success() { + let status = resp.status(); + return Err(CoreError::IssueTracker(format!( + "Gitea list labels returned {status}" + ))); + } + let batch: Vec<GiteaLabel> = resp.json().await.map_err(|e| { + CoreError::IssueTracker(format!("Failed to parse Gitea labels: {e}")) + })?; + let last = batch.len() < LABEL_PAGE_SIZE; + labels.extend(batch); + if last { + break; + } + } + Ok(labels) + } + + /// Make sure the repository has every label in `wanted`, creating the + /// missing ones, and return the id of each by name. Needs write access to + /// the repository's issues, nothing more. + /// + /// # Errors + /// + /// [`CoreError::IssueTracker`] if the labels cannot be listed or a missing + /// one cannot be created. + pub async fn ensure_labels( + &self, + owner: &str, + repo: &str, + wanted: &[LabelSpec], + ) -> Result<HashMap<String, i64>, CoreError> { + let existing = self.list_labels(owner, repo).await?; + let mut ids: HashMap<String, i64> = + existing.iter().map(|l| (l.name.clone(), l.id)).collect(); + for spec in missing_labels(&existing, wanted) { + let url = self.api_url(&format!("/repos/{owner}/{repo}/labels")); + let resp = self + .http + .post(&url) + .header("Authorization", self.auth()) + .json(&serde_json::json!({ + "name": spec.name, + "color": spec.color, + "description": spec.description, + })) + .send() + .await + .map_err(|e| CoreError::IssueTracker(format!("Gitea create label failed: {e}")))?; + if !resp.status().is_success() { + let status = resp.status(); + return Err(CoreError::IssueTracker(format!( + "Gitea create label '{}' returned {status}", + spec.name + ))); + } + let label: GiteaLabel = resp.json().await.map_err(|e| { + CoreError::IssueTracker(format!("Failed to parse Gitea label: {e}")) + })?; + ids.insert(label.name, label.id); + } + Ok(ids) + } + + /// Create an issue with the given labels attached by id (see + /// [`Self::ensure_labels`]). + /// + /// # Errors + /// + /// [`CoreError::IssueTracker`] if Gitea refuses the issue. + pub async fn create_issue_with_label_ids( &self, owner: &str, repo: &str, title: &str, body: &str, - labels: &[String], + label_ids: &[i64], + ) -> Result<TrackerIssue, CoreError> { + self.post_issue( + owner, + repo, + title, + serde_json::json!({ "title": title, "body": body, "labels": label_ids }), + ) + .await + } + + async fn post_issue( + &self, + owner: &str, + repo: &str, + title: &str, + payload: serde_json::Value, ) -> Result<TrackerIssue, CoreError> { let url = self.api_url(&format!("/repos/{owner}/{repo}/issues")); - - // Gitea expects label IDs (integers), not names. Append label names - // to the body instead since resolving IDs would require extra API calls. - let mut full_body = body.to_string(); - if !labels.is_empty() { - full_body.push_str("\n\n**Labels:** "); - full_body.push_str(&labels.join(", ")); - } - let payload = serde_json::json!({ - "title": title, - "body": full_body, - }); - let resp = self .http .post(&url) - .header( - "Authorization", - format!("token {}", self.token.expose_secret()), - ) + .header("Authorization", self.auth()) .json(&payload) .send() .await @@ -97,6 +186,116 @@ impl IssueTracker for GiteaTracker { title.to_string(), )) } +} + +/// Labels per page when listing a repository's labels. +const LABEL_PAGE_SIZE: usize = 50; +/// Upper bound on label pages, so a misbehaving server cannot loop us. +const MAX_LABEL_PAGES: usize = 20; + +/// A repository label as Gitea returns it. +#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)] +pub struct GiteaLabel { + pub id: i64, + pub name: String, +} + +/// A label Prüfwerk puts on the issues it opens in a managed repository. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LabelSpec { + pub name: String, + /// `#rrggbb`. + pub color: String, + pub description: String, +} + +impl LabelSpec { + fn new(name: &str, color: &str, description: &str) -> Self { + Self { + name: name.to_string(), + color: color.to_string(), + description: description.to_string(), + } + } +} + +/// The label every Prüfwerk issue in a managed repository carries. +pub const LABEL_PRUEFWERK: &str = "pruefwerk"; +/// The CRA label: the essential cybersecurity requirements of Annex I. +pub const LABEL_CRA_ANNEX_I: &str = "cra:annex-i"; + +/// The labels of a managed repository (#439): `pruefwerk`, `cra:annex-i` and +/// one `severity:*` per severity that gets an issue. +pub fn pruefwerk_labels() -> Vec<LabelSpec> { + vec![ + LabelSpec::new( + LABEL_PRUEFWERK, + "#1f6feb", + "Befund aus Prüfwerk / Prüfwerk finding", + ), + LabelSpec::new( + LABEL_CRA_ANNEX_I, + "#6e40c9", + "CRA Anhang I, wesentliche Cybersicherheitsanforderungen / CRA Annex I", + ), + LabelSpec::new( + "severity:critical", + "#b60205", + "Schweregrad kritisch / critical", + ), + LabelSpec::new("severity:high", "#d93f0b", "Schweregrad hoch / high"), + LabelSpec::new("severity:medium", "#fbca04", "Schweregrad mittel / medium"), + LabelSpec::new("severity:low", "#0e8a16", "Schweregrad niedrig / low"), + ] +} + +/// The labels of `wanted` that `existing` does not have (by exact name). +pub fn missing_labels<'a>(existing: &[GiteaLabel], wanted: &'a [LabelSpec]) -> Vec<&'a LabelSpec> { + wanted + .iter() + .filter(|w| !existing.iter().any(|e| e.name == w.name)) + .collect() +} + +/// The label names for an issue about a finding of `severity` (`info` has no +/// severity label). +pub fn issue_label_names(severity: &str) -> Vec<String> { + let mut names = vec![LABEL_PRUEFWERK.to_string(), LABEL_CRA_ANNEX_I.to_string()]; + if matches!(severity, "critical" | "high" | "medium" | "low") { + names.push(format!("severity:{severity}")); + } + names +} + +impl IssueTracker for GiteaTracker { + fn name(&self) -> &str { + "gitea" + } + + async fn create_issue( + &self, + owner: &str, + repo: &str, + title: &str, + body: &str, + labels: &[String], + ) -> Result<TrackerIssue, CoreError> { + // Gitea expects label IDs (integers), not names. A tracker the user + // configured gets the names in the body; a managed repository has its + // labels ensured and attached by id (`create_issue_with_label_ids`). + let mut full_body = body.to_string(); + if !labels.is_empty() { + full_body.push_str("\n\n**Labels:** "); + full_body.push_str(&labels.join(", ")); + } + self.post_issue( + owner, + repo, + title, + serde_json::json!({ "title": title, "body": full_body }), + ) + .await + } async fn update_issue_status( &self, @@ -286,3 +485,116 @@ impl IssueTracker for GiteaTracker { } } } + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use std::sync::{Arc, Mutex}; + + use axum::extract::{Path, State}; + use axum::routing::get; + use axum::{Json, Router}; + + use super::*; + + #[test] + fn missing_labels_by_exact_name() { + let existing = vec![ + GiteaLabel { + id: 1, + name: "pruefwerk".into(), + }, + GiteaLabel { + id: 2, + name: "Severity:High".into(), + }, + ]; + let wanted = pruefwerk_labels(); + let missing: Vec<&str> = missing_labels(&existing, &wanted) + .iter() + .map(|l| l.name.as_str()) + .collect(); + assert_eq!( + missing, + [ + "cra:annex-i", + "severity:critical", + "severity:high", + "severity:medium", + "severity:low" + ] + ); + assert!(wanted + .iter() + .all(|l| l.color.len() == 7 && l.color.starts_with('#'))); + } + + #[test] + fn issue_labels_per_severity() { + assert_eq!( + issue_label_names("critical"), + ["pruefwerk", "cra:annex-i", "severity:critical"] + ); + assert_eq!(issue_label_names("info"), ["pruefwerk", "cra:annex-i"]); + } + + type Labels = Arc<Mutex<Vec<(i64, String)>>>; + + /// A fake Gitea holding the labels of one repository. + async fn fake_gitea(labels: Labels) -> String { + async fn list( + State(labels): State<Labels>, + Path((_o, _r)): Path<(String, String)>, + ) -> Json<serde_json::Value> { + let all = labels.lock().unwrap().clone(); + Json(serde_json::json!(all + .iter() + .map(|(id, name)| serde_json::json!({ "id": id, "name": name, "color": "ffffff" })) + .collect::<Vec<_>>())) + } + async fn create( + State(labels): State<Labels>, + Path((_o, _r)): Path<(String, String)>, + Json(body): Json<serde_json::Value>, + ) -> (axum::http::StatusCode, Json<serde_json::Value>) { + let mut all = labels.lock().unwrap(); + let id = 100 + all.len() as i64; + let name = body["name"].as_str().unwrap().to_string(); + assert!(body["color"].as_str().unwrap().starts_with('#')); + all.push((id, name.clone())); + ( + axum::http::StatusCode::CREATED, + Json(serde_json::json!({ "id": id, "name": name })), + ) + } + let app = Router::new() + .route( + "/api/v1/repos/{owner}/{repo}/labels", + get(list).post(create), + ) + .with_state(labels); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + format!("http://{addr}") + } + + #[tokio::test] + async fn ensure_labels_creates_only_the_missing_ones_once() { + let labels: Labels = Arc::new(Mutex::new(vec![(7, "pruefwerk".to_string())])); + let base = fake_gitea(labels.clone()).await; + let tracker = + GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap(); + let wanted = pruefwerk_labels(); + + let ids = tracker.ensure_labels("kunde", "fw", &wanted).await.unwrap(); + assert_eq!(ids.len(), 6); + assert_eq!(ids["pruefwerk"], 7); + assert_eq!(labels.lock().unwrap().len(), 6); + + // A second run finds them all and creates nothing. + let again = tracker.ensure_labels("kunde", "fw", &wanted).await.unwrap(); + assert_eq!(again, ids); + assert_eq!(labels.lock().unwrap().len(), 6); + } +} diff --git a/compliance-agent/src/webhooks/gitea.rs b/compliance-agent/src/webhooks/gitea.rs index 072a0e9..0b841e5 100644 --- a/compliance-agent/src/webhooks/gitea.rs +++ b/compliance-agent/src/webhooks/gitea.rs @@ -135,7 +135,7 @@ async fn handle_pull_request( StatusCode::OK } -fn verify_signature(secret: &str, body: &[u8], signature: &str) -> bool { +pub(crate) fn verify_signature(secret: &str, body: &[u8], signature: &str) -> bool { // Gitea sends raw hex (no sha256= prefix) let sig_bytes = match hex::decode(signature) { Ok(b) => b, diff --git a/compliance-agent/src/webhooks/gitea_source.rs b/compliance-agent/src/webhooks/gitea_source.rs new file mode 100644 index 0000000..b9df851 --- /dev/null +++ b/compliance-agent/src/webhooks/gitea_source.rs @@ -0,0 +1,133 @@ +//! `POST /webhook/{tenant_id}/gitea-source` — the system/org webhook of a +//! tenant's managed Gitea (#439). +//! +//! Authenticated by `X-Gitea-Signature`: HMAC-SHA256 of the body under the +//! source's webhook secret. Until that is verified nothing is created: the +//! source is read through a handle that cannot conjure a tenant database. + +use std::sync::Arc; + +use axum::body::Bytes; +use axum::extract::{Extension, Path}; +use axum::http::{HeaderMap, StatusCode}; + +use crate::agent::ComplianceAgent; +use crate::git_source::{self, events}; + +pub async fn handle_gitea_source_webhook( + Extension(agent): Extension<Arc<ComplianceAgent>>, + Path(tenant_id): Path<String>, + headers: HeaderMap, + body: Bytes, +) -> StatusCode { + let probe = agent.db_pool.for_existing_tenant_id(&tenant_id); + let source = match git_source::load_source(&probe).await { + Ok(Some(source)) if source.enabled => source, + Ok(_) => { + tracing::warn!("Gitea source webhook: no enabled git source in tenant '{tenant_id}'"); + return StatusCode::NOT_FOUND; + } + Err(e) => { + tracing::error!("Gitea source webhook: reading the git source failed: {e}"); + return StatusCode::INTERNAL_SERVER_ERROR; + } + }; + + // Fail closed: a source whose secret cannot be opened accepts nothing. + let Some(secret) = agent + .secrets + .open_opt(source.webhook_secret.as_ref(), "git source webhook secret") + else { + tracing::warn!( + "Gitea source webhook: tenant '{tenant_id}' has no webhook secret; rejected" + ); + return StatusCode::UNAUTHORIZED; + }; + let signature = header(&headers, "x-gitea-signature"); + if !super::gitea::verify_signature(&secret, &body, signature) { + tracing::warn!("Gitea source webhook: invalid signature for tenant '{tenant_id}'"); + return StatusCode::UNAUTHORIZED; + } + + let event = header(&headers, "x-gitea-event"); + let payload: serde_json::Value = match serde_json::from_slice(&body) { + Ok(v) => v, + Err(e) => { + tracing::warn!("Gitea source webhook: invalid JSON: {e}"); + return StatusCode::BAD_REQUEST; + } + }; + let action = events::route_event(event, &payload, &source.org); + if let events::SourceAction::Ignore(why) = action { + tracing::debug!(tenant_id, event, "Gitea source webhook ignored: {why}"); + return StatusCode::OK; + } + + // Automated work follows the same entitlement and ladder rules as the + // scheduler. Refused visibly, so the delivery log in Gitea shows it. + if let Err(why) = git_source::automation_allowed(&agent, &tenant_id).await { + tracing::info!(tenant_id, "Gitea source webhook refused: {why}"); + return StatusCode::FORBIDDEN; + } + let db = match agent.db_pool.for_tenant_id(&tenant_id).await { + Ok(db) => db, + Err(e) => { + tracing::error!("Gitea source webhook: tenant database: {e}"); + return StatusCode::INTERNAL_SERVER_ERROR; + } + }; + match git_source::apply_action(&agent, &db, &tenant_id, &source, action).await { + Ok(outcome) => { + tracing::info!(tenant_id, event, ?outcome, "Gitea source webhook handled"); + StatusCode::OK + } + Err(e) => { + tracing::error!(tenant_id, event, "Gitea source webhook failed: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + } + } +} + +fn header<'a>(headers: &'a HeaderMap, name: &str) -> &'a str { + headers + .get(name) + .and_then(|v| v.to_str().ok()) + .unwrap_or("") +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use hmac::{Hmac, Mac}; + use sha2::Sha256; + + use crate::webhooks::gitea::verify_signature; + + 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()) + } + + #[test] + fn signature_valid_invalid_missing() { + let body = br#"{"action":"created"}"#; + let good = sign("s3cret", body); + assert!(verify_signature("s3cret", body, &good)); + // another secret, another body, a tampered or non-hex signature + assert!(!verify_signature("other", body, &good)); + assert!(!verify_signature( + "s3cret", + br#"{"action":"deleted"}"#, + &good + )); + let mut tampered = good.clone(); + tampered.replace_range(0..1, if good.starts_with('0') { "1" } else { "0" }); + assert!(!verify_signature("s3cret", body, &tampered)); + assert!(!verify_signature("s3cret", body, "zz")); + // GitHub-style prefix is not Gitea's format + assert!(!verify_signature("s3cret", body, &format!("sha256={good}"))); + // missing header + assert!(!verify_signature("s3cret", body, "")); + } +} diff --git a/compliance-agent/src/webhooks/mod.rs b/compliance-agent/src/webhooks/mod.rs index d31c808..52ac300 100644 --- a/compliance-agent/src/webhooks/mod.rs +++ b/compliance-agent/src/webhooks/mod.rs @@ -1,4 +1,5 @@ pub mod gitea; +pub mod gitea_source; pub mod github; pub mod gitlab; pub mod server; diff --git a/compliance-agent/src/webhooks/server.rs b/compliance-agent/src/webhooks/server.rs index cc633b5..871d44f 100644 --- a/compliance-agent/src/webhooks/server.rs +++ b/compliance-agent/src/webhooks/server.rs @@ -7,7 +7,7 @@ use compliance_core::shutdown::{self, Shutdown}; use crate::agent::ComplianceAgent; use crate::error::AgentError; -use crate::webhooks::{gitea, github, gitlab}; +use crate::webhooks::{gitea, gitea_source, github, gitlab}; /// Serve the webhook receivers on `agent.config.webhook_port` until `shutdown` /// fires, then drain in-flight deliveries for at most @@ -38,6 +38,12 @@ pub async fn start_webhook_server( "/webhook/{tenant_id}/gitea/{repo_id}", post(gitea::handle_gitea_webhook), ) + // The managed git source's system/org webhook (#439): one per tenant, + // HMAC-verified with the source's secret. + .route( + "/webhook/{tenant_id}/gitea-source", + post(gitea_source::handle_gitea_source_webhook), + ) .layer(Extension(Arc::new(agent.clone()))); let addr = format!("0.0.0.0:{}", agent.config.webhook_port); diff --git a/compliance-agent/src/werkbank/queue.rs b/compliance-agent/src/werkbank/queue.rs index 8c1197e..b23356a 100644 --- a/compliance-agent/src/werkbank/queue.rs +++ b/compliance-agent/src/werkbank/queue.rs @@ -279,7 +279,7 @@ fn bson_dt(dt: DateTime<Utc>) -> BsonDateTime { /// Whether a Mongo error is a duplicate-key (E11000) violation — a job with this /// id is already enqueued. -fn is_duplicate_key(e: &mongodb::error::Error) -> bool { +pub(crate) fn is_duplicate_key(e: &mongodb::error::Error) -> bool { match &*e.kind { ErrorKind::Write(WriteFailure::WriteError(we)) => we.code == 11000, _ => false, diff --git a/compliance-agent/tests/git_source.rs b/compliance-agent/tests/git_source.rs new file mode 100644 index 0000000..3a344b3 --- /dev/null +++ b/compliance-agent/tests/git_source.rs @@ -0,0 +1,375 @@ +//! 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(); +} diff --git a/compliance-core/src/models/git_source.rs b/compliance-core/src/models/git_source.rs new file mode 100644 index 0000000..645a25e --- /dev/null +++ b/compliance-core/src/models/git_source.rs @@ -0,0 +1,149 @@ +//! A tenant's managed git source (#439). +//! +//! BreakPilot runs one Gitea instance per customer. A [`GitSource`] names that +//! instance and the organisation whose repositories Prüfwerk checks: every +//! repository in it becomes a target automatically (by system/org webhook and +//! by a periodic sync), and findings come back as issues in the repository. +//! +//! One source per tenant, stored in the tenant database under a fixed id. + +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; + +use super::credentials::Credentials; + +/// The `_id` of a tenant's (single) git source document. +pub const GIT_SOURCE_ID: &str = "default"; + +/// The managed git instance of a tenant, as stored. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct GitSource { + /// Always [`GIT_SOURCE_ID`]: one source per tenant. + #[serde(rename = "_id")] + pub id: String, + /// The instance origin, `https://<host>` without a path or trailing slash. + pub base_url: String, + /// The organisation whose repositories are checked. + pub org: String, + /// The bot user's access token, sealed at rest. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub bot_token: Option<String>, + /// The HMAC secret of the system/org webhook, sealed at rest. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub webhook_secret: Option<String>, + /// Whether webhooks and the periodic sync act on this source. + #[serde(default)] + pub enabled: bool, + /// When the source was first configured. + #[serde( + default = "chrono::Utc::now", + with = "super::serde_helpers::bson_datetime" + )] + pub created_at: DateTime<Utc>, + /// When the source was last changed. + #[serde( + default = "chrono::Utc::now", + with = "super::serde_helpers::bson_datetime" + )] + pub updated_at: DateTime<Utc>, + /// When the periodic sync last listed the organisation's repositories. + #[serde(default, with = "super::serde_helpers::opt_bson_datetime")] + pub last_sync_at: Option<DateTime<Utc>>, +} + +impl Credentials for GitSource { + fn credentials_mut(&mut self) -> Vec<&mut Option<String>> { + vec![&mut self.bot_token, &mut self.webhook_secret] + } +} + +/// A git source as the API shows it: no credentials, only whether they are set. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct GitSourceView { + pub base_url: String, + pub org: String, + pub enabled: bool, + pub has_bot_token: bool, + pub has_webhook_secret: bool, + pub created_at: DateTime<Utc>, + pub updated_at: DateTime<Utc>, + pub last_sync_at: Option<DateTime<Utc>>, +} + +impl From<&GitSource> for GitSourceView { + fn from(s: &GitSource) -> Self { + Self { + base_url: s.base_url.clone(), + org: s.org.clone(), + enabled: s.enabled, + has_bot_token: s.bot_token.is_some(), + has_webhook_secret: s.webhook_secret.is_some(), + created_at: s.created_at, + updated_at: s.updated_at, + last_sync_at: s.last_sync_at, + } + } +} + +/// The repository a target was created for by a git source. Its presence is +/// what makes a target "managed": created, renamed and archived by the source, +/// with CRA-labelled issues. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SourceRepo { + /// The source's `base_url` when the target was created. + pub base_url: String, + /// Gitea's repository id: stable across renames and transfers. + pub repo_id: i64, + /// `owner/name` as last seen. + pub full_name: String, +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + + fn source() -> GitSource { + let now = Utc::now(); + GitSource { + id: GIT_SOURCE_ID.into(), + base_url: "https://kunde.code.breakpilot.com".into(), + org: "kunde".into(), + bot_token: Some("sec-token".into()), + webhook_secret: Some("sec-hook".into()), + enabled: true, + created_at: now, + updated_at: now, + last_sync_at: None, + } + } + + #[test] + fn both_secrets_are_credentials() { + let mut s = source(); + let mut v: Vec<String> = s + .credentials_mut() + .into_iter() + .filter_map(|slot| slot.clone()) + .collect(); + v.sort(); + assert_eq!(v, ["sec-hook", "sec-token"]); + } + + #[test] + fn the_view_carries_no_secret() { + let view = GitSourceView::from(&source()); + let json = serde_json::to_string(&view).unwrap(); + assert!(!json.contains("sec-"), "{json}"); + assert!(view.has_bot_token && view.has_webhook_secret); + } + + #[test] + fn bson_round_trip() { + let s = source(); + let b = bson::to_bson(&s).unwrap(); + let back: GitSource = bson::from_bson(b).unwrap(); + assert_eq!(back.base_url, s.base_url); + assert_eq!(back.bot_token, s.bot_token); + } +} diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index ee98805..acccb10 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -5,6 +5,7 @@ pub mod cve; pub mod dast; pub mod embedding; pub mod finding; +pub mod git_source; pub mod graph; pub mod issue; pub mod mcp; @@ -31,6 +32,7 @@ pub use dast::{ }; pub use embedding::{CodeEmbedding, EmbeddingBuildRun, EmbeddingBuildStatus}; pub use finding::{Finding, FindingStatus, Severity, StatusChange}; +pub use git_source::{GitSource, GitSourceView, SourceRepo, GIT_SOURCE_ID}; pub use graph::{ CodeEdge, CodeEdgeKind, CodeNode, CodeNodeKind, GraphBuildRun, GraphBuildStatus, ImpactAnalysis, }; diff --git a/compliance-core/src/models/onboarding.rs b/compliance-core/src/models/onboarding.rs index a7b55ad..d825833 100644 --- a/compliance-core/src/models/onboarding.rs +++ b/compliance-core/src/models/onboarding.rs @@ -594,6 +594,18 @@ pub struct OnboardedTarget { /// what gets checked follows `compliance_profile`. #[serde(default)] pub project_ids: Vec<String>, + /// The managed-git repository this target was created for (#439); `None` + /// for a target a user onboarded. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source_repo: Option<super::git_source::SourceRepo>, + /// When the target was archived because its repository was deleted. + /// Archived targets keep their findings but are no longer scanned. + #[serde( + default, + skip_serializing_if = "Option::is_none", + with = "super::serde_helpers::opt_bson_datetime" + )] + pub archived_at: Option<DateTime<Utc>>, /// Creation timestamp. #[serde( default = "chrono::Utc::now", @@ -629,6 +641,8 @@ impl OnboardedTarget { webhook_secret: None, findings_count: 0, project_ids: Vec::new(), + source_repo: None, + archived_at: None, created_at: now, updated_at: now, } diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index 9852b6e..a0d4ffa 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -58,6 +58,8 @@ export default withMermaid(defineConfig({ { text: 'MCP-Schnittstelle', link: '/features/mcp-server' }, { text: 'Tickets', link: '/guide/issues' }, { text: 'Webhooks und PR-Reviews', link: '/guide/webhooks' }, + { text: 'Managed Git anbinden', link: '/guide/managed-git' }, + { text: 'Connecting Managed Git (English)', link: '/guide/managed-git-en' }, { text: 'Getting Started (English)', link: '/guide/getting-started-en' }, ], }, diff --git a/docs/guide/managed-git-en.md b/docs/guide/managed-git-en.md new file mode 100644 index 0000000..6d2a4af --- /dev/null +++ b/docs/guide/managed-git-en.md @@ -0,0 +1,73 @@ +--- +title: Connecting Managed Git +--- + +# Connecting Managed Git + +With Managed Git, BreakPilot runs a Gitea instance for your company +(`https://<company>.code.breakpilot.com`). Prüfwerk can check every repository +of an organisation in that instance automatically: + +- **New repository → new target.** When a repository is created, Prüfwerk + creates a target for it and scans it after the first push. +- **Push to the default branch → scan.** Pushes to other branches and tags do + not start a scan. +- **Repository deleted → target archived.** Findings and evidence are kept; + the target is no longer scanned. +- **Findings as issues.** Findings of severity medium and above become issues + in the repository, with location, CWE, the CRA requirement concerned, the + remediation and a link into Prüfwerk. Prüfwerk creates the labels + `pruefwerk`, `cra:annex-i` and `severity:critical|high|medium|low` in the + repository for them. +- **Sync.** Every 30 minutes Prüfwerk compares the organisation's repositories + with its targets, in case a webhook delivery was lost. + +BreakPilot sets the connection up during provisioning; there is nothing for you +to configure. IT administrators can see it in the workspace (read-only). + +::: tip Deleted a target? +A target that belongs to a repository of the connected organisation is created +again by the next sync. To exclude a repository, move it to another +organisation. +::: + +## The bot user's rights + +Prüfwerk acts in Gitea as the bot user **`pruefwerk`** — never as an +administrator: + +- The bot is a member of a dedicated team of the organisation (e.g. + "Prüfwerk") that has only the units **Code: Read** and **Issues: Write**. No + administration, no write access to code, no wiki, release or package rights. +- Its access token has only the scopes `read:organization` (repository list), + `read:repository` (clone) and `write:issue` (issues, comments and labels). +- Prüfwerk stores the token encrypted and never returns it. + +Removing the bot from the team ends its access immediately. + +## For operations (BreakPilot) + +The platform configures the source through the platform API (service token, +like the other `/api/v1/platform/*` calls): + +```http +PUT /api/v1/platform/tenants/{tenant_id}/git-source +{ "base_url": "https://kunde.code.breakpilot.com", "org": "kunde", + "bot_token": "<the bot's token>" } +``` + +The response carries `webhook_url` and — only the first time, or with +`"rotate_webhook_secret": true` — `webhook_secret`. With these, register an +organisation or system webhook in Gitea (type Gitea, `application/json`) for +the **Repository** and **Push** events. A repeated `PUT` without `bot_token` +keeps the stored token, and without `rotate_webhook_secret` the secret. `GET` +returns the source without secrets; `DELETE` removes it and archives its +targets. + +Agent environment: `GIT_SOURCE_HOST_PATTERN` (allowed hosts, default +`^[a-z0-9-]+\.code(-stage)?\.breakpilot\.com$`), `GIT_SOURCE_SYNC_MINUTES` +(default 30), `WEBHOOK_PUBLIC_URL` (public origin of the webhook server, for +`webhook_url`). The Gitea instance's `[webhook] ALLOWED_HOST_LIST` must allow +the Prüfwerk host. + +[Deutsche Fassung](./managed-git) diff --git a/docs/guide/managed-git.md b/docs/guide/managed-git.md new file mode 100644 index 0000000..7e701cf --- /dev/null +++ b/docs/guide/managed-git.md @@ -0,0 +1,78 @@ +--- +title: Managed Git anbinden +--- + +# Managed Git anbinden + +Mit Managed Git betreibt BreakPilot für Ihr Unternehmen eine eigene +Gitea-Instanz (`https://<firma>.code.breakpilot.com`). Prüfwerk kann jede +Repository-Organisation dieser Instanz automatisch prüfen: + +- **Neues Repository → neues Prüfobjekt.** Sobald ein Repository angelegt + wird, legt Prüfwerk ein Prüfobjekt dafür an und prüft es nach dem ersten + Push. +- **Push auf den Standard-Branch → Prüfung.** Pushes auf andere Branches und + Tags lösen keine Prüfung aus. +- **Repository gelöscht → Prüfobjekt archiviert.** Befunde und Nachweise + bleiben erhalten; das Prüfobjekt wird nicht mehr geprüft. +- **Befunde als Issues.** Befunde ab Schweregrad „mittel“ erscheinen als Issue + im Repository, mit Fundstelle, CWE, der betroffenen CRA-Anforderung, der + Maßnahme und einem Link ins Prüfwerk. Prüfwerk legt dazu die Labels + `pruefwerk`, `cra:annex-i` und `severity:critical|high|medium|low` im + Repository an. +- **Abgleich.** Alle 30 Minuten gleicht Prüfwerk die Repository-Liste der + Organisation mit den Prüfobjekten ab, falls ein Webhook verloren ging. + +Die Anbindung richtet BreakPilot bei der Bereitstellung ein; Sie müssen nichts +konfigurieren. IT-Administratoren sehen die Anbindung im Arbeitsbereich +(nur lesend). + +::: tip Prüfobjekt gelöscht? +Ein Prüfobjekt, das zu einem Repository der angebundenen Organisation gehört, +legt der nächste Abgleich wieder an. Soll ein Repository nicht geprüft werden, +verschieben Sie es in eine andere Organisation. +::: + +## Rechte des Bot-Benutzers + +Prüfwerk arbeitet in Gitea als Bot-Benutzer **`pruefwerk`** – nie mit +Administratorrechten: + +- Der Bot ist Mitglied eines eigenen Teams der Organisation (z. B. + „Prüfwerk“), das nur die Einheiten **Code: Lesen** und **Issues: Schreiben** + hat. Keine Administration, kein Schreibzugriff auf Code, keine Wiki-, + Release- oder Paketrechte. +- Sein Zugriffstoken hat nur die Bereiche `read:organization` + (Repository-Liste), `read:repository` (Klonen) und `write:issue` (Issues, + Kommentare und Labels). +- Das Token wird in Prüfwerk verschlüsselt gespeichert und nie wieder + ausgegeben. + +Entziehen Sie dem Bot die Teammitgliedschaft, endet der Zugriff sofort. + +## Für den Betrieb (BreakPilot) + +Die Plattform richtet die Quelle über die Plattform-API ein (Service-Token wie +die übrigen `/api/v1/platform/*`-Aufrufe): + +```http +PUT /api/v1/platform/tenants/{tenant_id}/git-source +{ "base_url": "https://kunde.code.breakpilot.com", "org": "kunde", + "bot_token": "<token des Bots>" } +``` + +Die Antwort enthält `webhook_url` und – nur beim ersten Mal oder mit +`"rotate_webhook_secret": true` – `webhook_secret`. Damit wird in Gitea ein +Organisations- oder System-Webhook (Typ Gitea, `application/json`) mit den +Ereignissen **Repository** und **Push** angelegt. Ein erneuter `PUT` ohne +`bot_token` behält das gespeicherte Token, ohne `rotate_webhook_secret` das +Secret. `GET` liefert die Quelle ohne Geheimnisse, `DELETE` entfernt sie und +archiviert ihre Prüfobjekte. + +Umgebungsvariablen des Agents: `GIT_SOURCE_HOST_PATTERN` (erlaubte Hosts, +Standard `^[a-z0-9-]+\.code(-stage)?\.breakpilot\.com$`), +`GIT_SOURCE_SYNC_MINUTES` (Standard 30), `WEBHOOK_PUBLIC_URL` (öffentlicher +Ursprung des Webhook-Servers für die `webhook_url`). In der Gitea-Instanz muss +`[webhook] ALLOWED_HOST_LIST` den Prüfwerk-Host zulassen. + +[English version](./managed-git-en) -- 2.54.1 From aa90fab2a0b636cbf6a05729894da5972419daa9 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Mon, 5 Oct 2026 12:25:51 +0200 Subject: [PATCH 2/2] fix(agent): git source pagination ends on an empty page only (#439) A Gitea with MAX_RESPONSE_ITEMS below 50 returns short pages; taking the first short page for the last one would have made the sync archive every repository after it. Same for the label listing. A token renewal skips git artifacts without credentials instead of failing, and the guides say the source is readable through the API (no UI yet). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB --- compliance-agent/src/git_source/gitea.rs | 28 ++++++++++++++++++------ compliance-agent/src/git_source/mod.rs | 6 ++++- compliance-agent/src/trackers/gitea.rs | 7 +++--- compliance-agent/tests/git_source.rs | 25 +++++++++++++++++++++ docs/guide/managed-git-en.md | 3 ++- docs/guide/managed-git.md | 4 ++-- 6 files changed, 59 insertions(+), 14 deletions(-) diff --git a/compliance-agent/src/git_source/gitea.rs b/compliance-agent/src/git_source/gitea.rs index 3a7ac35..17b560e 100644 --- a/compliance-agent/src/git_source/gitea.rs +++ b/compliance-agent/src/git_source/gitea.rs @@ -128,11 +128,14 @@ impl RepoLister for SourceClient { ))); } let batch: Vec<GiteaRepo> = resp.json().await?; - let last = batch.len() < PAGE_SIZE; - repos.extend(batch); - if last { + // Only an empty page ends the list: an instance may cap the page + // size below `PAGE_SIZE` (`[api] MAX_RESPONSE_ITEMS`), and taking + // a short page for the last one would archive every repository + // after it. + if batch.is_empty() { return Ok(repos); } + repos.extend(batch); } Err(AgentError::Other(format!( "'{org}' lists more than {} repositories; sync stopped", @@ -164,7 +167,7 @@ mod tests { } /// A fake Gitea serving `total` repositories of org `kunde`, paginated. - async fn fake_gitea(total: i64, seen: Arc<Mutex<Vec<String>>>) -> String { + async fn fake_gitea(total: i64, cap: i64, seen: Arc<Mutex<Vec<String>>>) -> String { let app = Router::new().route( "/api/v1/orgs/{org}/repos", get( @@ -179,7 +182,7 @@ mod tests { headers["authorization"].to_str().unwrap() )); let page: i64 = q["page"].parse().unwrap(); - let limit: i64 = q["limit"].parse().unwrap(); + let limit: i64 = q["limit"].parse::<i64>().unwrap().min(cap); let from = (page - 1) * limit + 1; let to = (page * limit).min(total); let items: Vec<_> = (from..=to) @@ -199,7 +202,7 @@ mod tests { #[tokio::test] async fn lists_every_page_with_the_bot_token() { let seen = Arc::new(Mutex::new(Vec::new())); - let base = fake_gitea(120, seen.clone()).await; + let base = fake_gitea(120, 50, seen.clone()).await; let client = SourceClient::new( &base, SecretString::from("bot-tok"), @@ -216,6 +219,7 @@ mod tests { "kunde page=1 auth=token bot-tok", "kunde page=2 auth=token bot-tok", "kunde page=3 auth=token bot-tok", + "kunde page=4 auth=token bot-tok", ] ); } @@ -223,13 +227,23 @@ mod tests { #[tokio::test] async fn an_exact_multiple_of_the_page_size_ends_on_an_empty_page() { let seen = Arc::new(Mutex::new(Vec::new())); - let base = fake_gitea(50, seen.clone()).await; + let base = fake_gitea(50, 50, seen.clone()).await; let client = SourceClient::new(&base, SecretString::from("t"), NetGuard::allow_private()).unwrap(); assert_eq!(client.list_org_repos("kunde").await.unwrap().len(), 50); assert_eq!(seen.lock().unwrap().len(), 2); } + #[tokio::test] + async fn a_capped_page_size_is_not_taken_for_the_end() { + // An instance with MAX_RESPONSE_ITEMS=30 answers 30 per page. + let seen = Arc::new(Mutex::new(Vec::new())); + let base = fake_gitea(70, 30, seen.clone()).await; + let client = + SourceClient::new(&base, SecretString::from("t"), NetGuard::allow_private()).unwrap(); + assert_eq!(client.list_org_repos("kunde").await.unwrap().len(), 70); + } + #[test] fn owner_falls_back_to_the_full_name() { let r: GiteaRepo = serde_json::from_value(serde_json::json!({ diff --git a/compliance-agent/src/git_source/mod.rs b/compliance-agent/src/git_source/mod.rs index b3f59ba..c207127 100644 --- a/compliance-agent/src/git_source/mod.rs +++ b/compliance-agent/src/git_source/mod.rs @@ -634,7 +634,11 @@ pub async fn retoken_targets( "updated_at": mongodb::bson::DateTime::now(), } }, ) - .array_filters(vec![doc! { "git.kind": "git_repo" }]) + // Only git artifacts that have credentials: setting a field inside a + // `null` auth would fail the whole update. + .array_filters(vec![ + doc! { "git.kind": "git_repo", "git.auth": { "$type": "object" } }, + ]) .await?; Ok(res.modified_count) } diff --git a/compliance-agent/src/trackers/gitea.rs b/compliance-agent/src/trackers/gitea.rs index 1ad1a78..8e2b6f2 100644 --- a/compliance-agent/src/trackers/gitea.rs +++ b/compliance-agent/src/trackers/gitea.rs @@ -70,11 +70,12 @@ impl GiteaTracker { let batch: Vec<GiteaLabel> = resp.json().await.map_err(|e| { CoreError::IssueTracker(format!("Failed to parse Gitea labels: {e}")) })?; - let last = batch.len() < LABEL_PAGE_SIZE; - labels.extend(batch); - if last { + // Only an empty page ends the list (the instance may cap the + // page size below ours). + if batch.is_empty() { break; } + labels.extend(batch); } Ok(labels) } diff --git a/compliance-agent/tests/git_source.rs b/compliance-agent/tests/git_source.rs index 3a344b3..691700a 100644 --- a/compliance-agent/tests/git_source.rs +++ b/compliance-agent/tests/git_source.rs @@ -352,6 +352,31 @@ async fn platform_api_webhook_and_sync() { ); 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 diff --git a/docs/guide/managed-git-en.md b/docs/guide/managed-git-en.md index 6d2a4af..4e76f2b 100644 --- a/docs/guide/managed-git-en.md +++ b/docs/guide/managed-git-en.md @@ -23,7 +23,8 @@ of an organisation in that instance automatically: with its targets, in case a webhook delivery was lost. BreakPilot sets the connection up during provisioning; there is nothing for you -to configure. IT administrators can see it in the workspace (read-only). +to configure. IT administrators can read it through the API +(`GET /api/v1/git-source`); a view in the interface will follow. ::: tip Deleted a target? A target that belongs to a repository of the connected organisation is created diff --git a/docs/guide/managed-git.md b/docs/guide/managed-git.md index 7e701cf..3fe7da4 100644 --- a/docs/guide/managed-git.md +++ b/docs/guide/managed-git.md @@ -24,8 +24,8 @@ Repository-Organisation dieser Instanz automatisch prüfen: Organisation mit den Prüfobjekten ab, falls ein Webhook verloren ging. Die Anbindung richtet BreakPilot bei der Bereitstellung ein; Sie müssen nichts -konfigurieren. IT-Administratoren sehen die Anbindung im Arbeitsbereich -(nur lesend). +konfigurieren. IT-Administratoren können sie über die API lesen +(`GET /api/v1/git-source`); eine Ansicht in der Oberfläche folgt. ::: tip Prüfobjekt gelöscht? Ein Prüfobjekt, das zu einem Repository der angebundenen Organisation gehört, -- 2.54.1