Files
pruefwerk/compliance-agent/src/git_source/mod.rs
T
sharang 1df32d5e1a
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 2m52s
CI / Deploy Dashboard (push) Successful in 5m31s
CI / Deploy Agent (push) Successful in 7m28s
feat(metering): a plan can allow no extra targets (entry plan) (#1079)
2026-11-28 22:09:18 +00:00

849 lines
31 KiB
Rust

//! 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 Gitea events the organisation or system webhook must send: Prüfwerk
/// cannot register or change the webhook itself (the bot has no
/// administration rights), so the platform API names them for provisioning.
pub const WEBHOOK_EVENTS: [&str; 3] = ["repository", "push", "issues"];
/// 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<String>,
}
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<Self, String> {
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<Self, String> {
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::<u64>()
.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://<host>` 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<String, String> {
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, 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<Option<GitSource>, 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<Document>)> {
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<Ensured, AgentError> {
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<Ensured, AgentError> {
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<bool, AgentError> {
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<bool, AgentError> {
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),
/// An issue closed or reopened in Gitea was carried back (#953).
Issue {
target_id: String,
detail: &'static str,
},
/// Nothing done.
Ignored(&'static str),
}
/// Why a delivery for a repository without a target makes none: the plan's
/// targets are all active (`extra_targets: 0`).
const NO_ROOM: &str = "the plan allows no further active target";
/// 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<Outcome, AgentError> {
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 = match ensure_target(agent, db, tenant_id, source, &repo).await {
Err(AgentError::TargetLimit(_)) => return Ok(Outcome::Ignored(NO_ROOM)),
ensured => ensured?,
};
// 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 = match ensure_target(agent, db, tenant_id, source, &repo).await {
Err(AgentError::TargetLimit(_)) => return Ok(Outcome::Ignored(NO_ROOM)),
ensured => ensured?,
};
spawn_scan(agent, tenant_id, &ensured.target_id, ScanTrigger::Webhook);
Ok(Outcome::Ensured {
target_id: ensured.target_id,
scan: true,
})
}
SourceAction::Issue(event) => {
// Only the repository's existing target: an issue event never
// creates one.
let Some(target_id) = db
.onboarded_targets()
.find_one(repo_filter(&source.base_url, event.repo.id))
.await?
.and_then(|t| t.id)
else {
return Ok(Outcome::Ignored("repository has no target"));
};
let target_id = target_id.to_hex();
let done = crate::pipeline::issue_backsync::apply(db, &target_id, &event).await?;
Ok(Outcome::Issue {
target_id,
detail: done.detail(event.change),
})
}
}
}
/// 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<Option<SyncReport>, 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<L: RepoLister>(
agent: &ComplianceAgent,
db: &Database,
tenant_id: &str,
source: &GitSource,
lister: &L,
) -> Result<SyncReport, AgentError> {
use futures_util::TryStreamExt;
let repos = lister.list_org_repos(&source.org).await?;
let targets: Vec<OnboardedTarget> = 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,
// Not an error: the next sync tries again, once a target is
// archived or the plan changed.
Err(AgentError::TargetLimit(cap)) => {
tracing::info!(tenant_id, repo = %repo.full_name, cap, "managed git sync: no target, the plan's targets are all active");
}
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<u64, AgentError> {
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<u64, AgentError> {
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(),
} },
)
// 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)
}
#[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());
}
}