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

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

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

150 lines
4.9 KiB
Rust

//! 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);
}
}