Files
pruefwerk/compliance-agent/src/agent.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

700 lines
27 KiB
Rust

use std::sync::Arc;
use dashmap::DashMap;
use tokio::sync::{broadcast, watch, Semaphore};
use compliance_core::models::pentest::PentestEvent;
use compliance_core::{AgentConfig, NetGuard};
use crate::database::DatabasePool;
use crate::llm::LlmClient;
use crate::pipeline::orchestrator::PipelineOrchestrator;
use crate::registry::RegistryClient;
use crate::scan_gate::{Admission, HeldTarget, Job, Priority, ScanGate};
use crate::secrets::SecretBox;
/// A target whose billing changed, with its new billing (t72).
pub type BillingChange = (
mongodb::bson::oid::ObjectId,
compliance_core::models::TargetBilling,
);
/// Default maximum concurrent pentest sessions.
const DEFAULT_MAX_CONCURRENT_SESSIONS: usize = 5;
#[derive(Clone)]
pub struct ComplianceAgent {
pub config: AgentConfig,
/// Per-tenant Mongo broker. Every code path must obtain a
/// tenant-scoped [`crate::database::Database`] from this pool —
/// there is no single shared database any more.
pub db_pool: DatabasePool,
pub llm: Arc<LlmClient>,
pub http: reqwest::Client,
/// Per-session broadcast senders for SSE streaming.
pub session_streams: Arc<DashMap<String, broadcast::Sender<PentestEvent>>>,
/// Per-session pause controls (true = paused).
pub session_pause: Arc<DashMap<String, watch::Sender<bool>>>,
/// Semaphore limiting concurrent pentest sessions.
pub session_semaphore: Arc<Semaphore>,
/// Platform tenant-registry client (entitlements, tenant list, API keys,
/// usage events). `None` when `TENANT_REGISTRY_URL` is unset (dev).
pub registry: Option<Arc<RegistryClient>>,
/// Where tenants may point a scan (SSRF policy). Public-only unless an
/// on-premise deployment opts in via `PW_ALLOW_PRIVATE_TARGETS`.
pub net_guard: NetGuard,
/// Global scan slots and per-target coalescing (#258).
pub scan_gate: Arc<ScanGate>,
/// 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<crate::git_source::Settings>,
/// NuGet licenses looked up on nuget.org, for every tenant (#467): public
/// metadata keyed by package and version, in the admin database.
pub(crate) nuget_license_cache: Arc<crate::pipeline::sbom::MongoLicenseCache>,
/// KEV, EPSS and SSVC answers per CVE, for every tenant (#493): public
/// data keyed by CVE id, in the admin database, kept a day.
pub(crate) exploit_cache: Arc<crate::pipeline::cve_enrichment::MongoExploitCache>,
/// The vendor CSAF advisories the scans match against (#515).
pub(crate) advisory_index: Arc<crate::pipeline::csaf_feed::MongoAdvisoryStore>,
}
impl ComplianceAgent {
pub fn new(config: AgentConfig, db_pool: DatabasePool) -> Self {
if config.litellm_model.is_empty() || config.litellm_embed_model.is_empty() {
tracing::warn!(
chat = !config.litellm_model.is_empty(),
embeddings = !config.litellm_embed_model.is_empty(),
"LITELLM_MODEL / LITELLM_EMBED_MODEL not set: those LLM parts are off"
);
}
let llm = Arc::new(
LlmClient::new(
config.litellm_url.clone(),
config.litellm_api_key.clone(),
config.litellm_model.clone(),
config.litellm_embed_model.clone(),
)
.with_timeout(std::time::Duration::from_secs(config.llm_timeout_secs)),
);
let http = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(30))
.connect_timeout(std::time::Duration::from_secs(10))
.build()
.unwrap_or_default();
let registry = RegistryClient::from_config(&config, http.clone());
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()
}));
let nuget_license_cache = Arc::new(crate::pipeline::sbom::MongoLicenseCache::new(
&db_pool.admin_db(),
));
let exploit_cache = Arc::new(crate::pipeline::cve_enrichment::MongoExploitCache::new(
&db_pool.admin_db(),
));
let advisory_index = Arc::new(crate::pipeline::csaf_feed::MongoAdvisoryStore::new(
&db_pool.admin_db(),
));
Self {
config,
db_pool,
llm,
http,
session_streams: Arc::new(DashMap::new()),
session_pause: Arc::new(DashMap::new()),
session_semaphore: Arc::new(Semaphore::new(DEFAULT_MAX_CONCURRENT_SESSIONS)),
registry,
net_guard,
scan_gate,
secrets,
git_source,
nuget_license_cache,
exploit_cache,
advisory_index,
}
}
pub async fn run_scan(
&self,
tenant_id: &str,
repo_id: &str,
trigger: compliance_core::models::ScanTrigger,
) -> Result<(), crate::error::AgentError> {
self.run_target_scan(tenant_id, repo_id, trigger).await
}
/// Push one usage event to the tenant-registry (PRODUCT_INTEGRATION_SPEC
/// 2.0 §9.2) in the background. `key` makes retries idempotent; the
/// registry forwards the event to ERPNext. No-op without a registry.
pub fn emit_usage(
&self,
tenant_id: &str,
metric: &str,
key: String,
properties: serde_json::Value,
) {
self.emit_usage_quantity(tenant_id, metric, key, 1.0, properties);
}
/// [`Self::emit_usage`] with a `quantity` other than one, such as the
/// month's peak of extra targets (t72).
pub fn emit_usage_quantity(
&self,
tenant_id: &str,
metric: &str,
key: String,
quantity: f64,
properties: serde_json::Value,
) {
let Some(registry) = self.registry.clone() else {
return;
};
let event = crate::registry::UsageEvent {
idempotency_key: key,
tenant_id: tenant_id.to_string(),
product: registry.product().to_string(),
metric: metric.to_string(),
quantity,
occurred_at: chrono::Utc::now().to_rfc3339(),
properties: Some(properties),
};
tokio::spawn(async move {
if let Err(e) = registry.push_usage_events(&[event]).await {
tracing::warn!("usage event push failed: {e}");
}
});
}
/// Store which of the tenant's targets are the plan's included ones and
/// which are extra (t72), from the plan's `included_targets`; a plan that
/// allows no extra target includes them all. Without a registry every
/// target is included. Best-effort: when the plan cannot
/// be read or the targets not updated, the stored split stays.
///
/// # Returns
///
/// The targets whose billing changed, with their new billing.
pub async fn refresh_billing(
&self,
tenant_id: &str,
db: &crate::database::Database,
) -> Vec<BillingChange> {
match self.plan(tenant_id).await {
Some(plan) => {
self.assign_billing(tenant_id, db, plan.billed_included())
.await
}
None => Vec::new(),
}
}
/// The tenant's plan for metering (t72), from its entitlement; without
/// a registry, no limits at all. `None` when the registry did not
/// answer: then the stored billing stays, and counted Prüfungen are
/// neither checked nor charged.
pub async fn plan(&self, tenant_id: &str) -> Option<crate::metering::Plan> {
let Some(registry) = &self.registry else {
return Some(crate::metering::Plan::default());
};
match registry.check_entitlement(tenant_id, None, None).await {
Ok(check) => Some(crate::metering::Plan {
included_targets: check.included_targets(),
extra_targets: check.extra_targets(),
limits: check.plan_limits(),
}),
Err(e) => {
tracing::warn!(tenant_id, "plan not read, metering waits: {e}");
None
}
}
}
/// Store the billing of the tenant's targets for a plan that includes
/// `included` targets; best-effort.
pub(crate) async fn assign_billing(
&self,
tenant_id: &str,
db: &crate::database::Database,
included: Option<u32>,
) -> Vec<BillingChange> {
let changes = match crate::metering::assign_billing(db, included).await {
Ok(changes) => {
if !changes.is_empty() {
tracing::info!(tenant_id, changed = changes.len(), "target billing updated");
}
changes
}
Err(e) => {
tracing::warn!(tenant_id, "target billing not updated: {e}");
return Vec::new();
}
};
self.report_extra_peak(tenant_id, db).await;
changes
}
/// Send the month's peak of extra targets as `target.extra` when it
/// rose, and once a day besides (t72). The key carries the peak, so the
/// registry keeps every rise and drops the daily re-send as a duplicate;
/// billing takes the highest quantity per tenant-month. Count only: no
/// target names leave Prüfwerk. Best-effort.
async fn report_extra_peak(&self, tenant_id: &str, db: &crate::database::Database) {
let now = chrono::Utc::now();
match crate::metering::record_extra_peak(db, now).await {
Ok(Some(peak)) => {
let (month, _) = crate::metering::berlin_period(now);
self.emit_usage_quantity(
tenant_id,
"target.extra",
format!("target-extra:{tenant_id}:{month}:{peak}"),
f64::from(peak),
serde_json::json!({ "month": month }),
);
}
Ok(None) => {}
Err(e) => tracing::warn!(tenant_id, "extra targets not recorded: {e}"),
}
}
/// Scan a target, through the [`ScanGate`]: at most `SCAN_CONCURRENCY` scans
/// run at once, a person's before scheduled and webhook ones, and a request
/// for a target that is already queued or being scanned is coalesced — it
/// becomes the one pending follow-up that this task runs next, it takes over
/// a queued scan that was not a person's, or it is dropped as covered. A
/// scheduled scan first waits a random [`crate::scan_gate::start_delay`].
/// Every trigger (click, webhook, scheduler, demo seed) comes through here.
///
/// Each request is recorded at once as a `queued` run, which shows that it
/// waits for a slot (t84); a request that will not run has its queued run
/// removed again.
///
/// # Errors
///
/// Returns the last scan's error. A coalesced or dropped request is `Ok`.
pub async fn run_target_scan(
&self,
tenant_id: &str,
target_id: &str,
trigger: compliance_core::models::ScanTrigger,
) -> Result<(), crate::error::AgentError> {
// Scheduled scans spread out before they take a slot or the target.
let delay = crate::scan_gate::start_delay(&trigger);
if !delay.is_zero() {
tracing::debug!(
tenant_id,
target_id,
delay_ms = delay.as_millis(),
"scheduled scan waits"
);
tokio::time::sleep(delay).await;
}
let db = self.db_pool.for_tenant_id(tenant_id).await?;
let run_id = queue_run(&db, target_id, &trigger).await;
let key = ScanGate::key(tenant_id, target_id);
match self
.scan_gate
.admit(&key, Job::new(trigger, run_id.clone()))
{
Admission::Run => {}
Admission::Coalesced { replaced } => {
tracing::info!(
tenant_id,
target_id,
took_over = replaced.is_some(),
"scan already running; follow-up queued"
);
discard_queued_run(&db, replaced.as_deref()).await;
return Ok(());
}
Admission::Dropped => {
tracing::info!(
tenant_id,
target_id,
"scan and follow-up already queued; dropped"
);
discard_queued_run(&db, run_id.as_deref()).await;
return Ok(());
}
}
// Released on panic or cancellation; a normal finish disarms it.
let held = HeldTarget::new(&self.scan_gate, key.clone());
let result = loop {
// The scan to run is the one current when the slot is granted: a
// person's request may have taken it over while it waited.
let (slot, job) = self
.scan_gate
.start(&key)
.await
.map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?;
let outcome = self.run_one_target_scan(tenant_id, target_id, &job).await;
drop(slot);
if let Err(e) = &outcome {
tracing::error!(tenant_id, target_id, "scan failed: {e}");
fail_queued_run(&db, job.run_id.as_deref(), e).await;
}
if !self.scan_gate.finish(&key) {
break outcome;
}
};
held.disarm();
result
}
/// One scan of a target, with no gating: the pipeline plus its usage event,
/// recorded on the run that waited for it and charged as `job` says.
async fn run_one_target_scan(
&self,
tenant_id: &str,
target_id: &str,
job: &Job,
) -> Result<(), crate::error::AgentError> {
let trigger = job.trigger.clone();
let db = self.db_pool.for_tenant_id(tenant_id).await?;
// Whether this target is included or extra decides whether its scan
// counts, and the plan's limits whether a counted one may run (t72).
let plan = self.plan(tenant_id).await;
if let Some(plan) = &plan {
self.assign_billing(tenant_id, &db, plan.billed_included())
.await;
}
let orchestrator =
PipelineOrchestrator::new(self.config.clone(), tenant_id, db.clone(), self.llm.clone())
.with_nuget_license_cache(self.nuget_license_cache.clone())
.with_exploit_cache(self.exploit_cache.clone())
.with_advisory_index(self.advisory_index.clone())
.with_plan_limits(plan.map(|p| p.limits))
.with_charged_as(job.charged_as.clone());
let started = chrono::Utc::now();
let outcome = orchestrator
.run_target(target_id, trigger.clone(), job.run_id.as_deref())
.await?;
// Support's scans are ours, not the customer's usage; a scheduled scan
// skipped because nothing changed scanned nothing (#465).
if outcome.scanned && trigger != compliance_core::models::ScanTrigger::Support {
self.emit_usage(
tenant_id,
"scan.completed",
format!("scan:{tenant_id}:{target_id}:{}", started.timestamp()),
serde_json::json!({
"target_id": target_id,
"trigger": format!("{trigger:?}"),
"attribution": outcome.attribution,
"counted": outcome.chargeable,
}),
);
}
if let Some(day) = &outcome.booked_prueftag {
self.emit_usage(
tenant_id,
"prueftag.booked",
format!("prueftag:{tenant_id}:{target_id}:{day}"),
serde_json::json!({ "target_id": target_id, "day": day }),
);
}
self.notify_new_findings(tenant_id, target_id, &db, started);
Ok(())
}
/// Tell the workspace (by mail, through the platform) when a scan found
/// something that was not there before. "New" is what the pipeline
/// inserted during this scan: it only inserts a finding whose fingerprint
/// is not stored yet. Background and best-effort; no registry, no mail.
fn notify_new_findings(
&self,
tenant_id: &str,
target_id: &str,
db: &crate::database::Database,
started: chrono::DateTime<chrono::Utc>,
) {
let Some(registry) = self.registry.clone() else {
return;
};
let (db, tenant_id, target_id) = (db.clone(), tenant_id.to_string(), target_id.to_string());
tokio::spawn(async move {
match new_findings_summary(&db, &tenant_id, &target_id, started).await {
Ok(Some(n)) => {
if let Err(e) = registry.notify_new_findings(&n).await {
tracing::warn!(tenant_id, target_id, "findings notification failed: {e}");
}
}
Ok(None) => {}
Err(e) => tracing::warn!(tenant_id, target_id, "findings summary failed: {e}"),
}
});
}
/// Run a PR review: scan the diff and post review comments.
pub async fn run_pr_review(
&self,
tenant_id: &str,
repo_id: &str,
pr_number: u64,
base_sha: &str,
head_sha: &str,
) -> Result<(), crate::error::AgentError> {
// A PR review clones and runs semgrep like a scan, so it takes a scan
// slot too. Each PR is distinct work, so it is not coalesced.
let _slot = self
.scan_gate
.slot(Priority::Background)
.await
.map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?;
let db = self.db_pool.for_tenant_id(tenant_id).await?;
let oid = mongodb::bson::oid::ObjectId::parse_str(repo_id)
.map_err(|e| crate::error::AgentError::Other(e.to_string()))?;
let target = db
.onboarded_targets()
.find_one(mongodb::bson::doc! { "_id": oid })
.await?
.ok_or_else(|| {
crate::error::AgentError::Other(format!("Target {repo_id} not found"))
})?;
let code = target.code_artifact().ok_or_else(|| {
crate::error::AgentError::Other(format!("Target {repo_id} has no code artifact"))
})?;
let repo = crate::pipeline::repo_view::RepoView::from_target(&target, code, &self.secrets);
let orchestrator =
PipelineOrchestrator::new(self.config.clone(), tenant_id, db, self.llm.clone());
orchestrator
.run_pr_review(&repo, repo_id, pr_number, base_sha, head_sha)
.await
}
// ── Session stream management ──────────────────────────────────
/// Register a broadcast sender for a session. Returns the sender.
pub fn register_session_stream(&self, session_id: &str) -> broadcast::Sender<PentestEvent> {
let (tx, _) = broadcast::channel(256);
self.session_streams
.insert(session_id.to_string(), tx.clone());
tx
}
/// Subscribe to a session's broadcast stream.
pub fn subscribe_session(&self, session_id: &str) -> Option<broadcast::Receiver<PentestEvent>> {
self.session_streams
.get(session_id)
.map(|tx| tx.subscribe())
}
// ── Session pause/resume management ────────────────────────────
/// Register a pause control for a session. Returns the watch receiver.
pub fn register_pause_control(&self, session_id: &str) -> watch::Receiver<bool> {
let (tx, rx) = watch::channel(false);
self.session_pause.insert(session_id.to_string(), tx);
rx
}
/// Pause a session.
pub fn pause_session(&self, session_id: &str) -> bool {
if let Some(tx) = self.session_pause.get(session_id) {
tx.send(true).is_ok()
} else {
false
}
}
/// Resume a session.
pub fn resume_session(&self, session_id: &str) -> bool {
if let Some(tx) = self.session_pause.get(session_id) {
tx.send(false).is_ok()
} else {
false
}
}
/// Clean up all per-session resources.
pub fn cleanup_session(&self, session_id: &str) {
self.session_streams.remove(session_id);
self.session_pause.remove(session_id);
}
}
/// Record a scan request for `target_id` as a run waiting for a slot (t84),
/// so it shows at once. Returns its id, or `None` when it could not be
/// written: the scan then runs on a run of its own when it starts.
async fn queue_run(
db: &crate::database::Database,
target_id: &str,
trigger: &compliance_core::models::ScanTrigger,
) -> Option<String> {
let run = compliance_core::models::ScanRun::queued(target_id.to_string(), trigger.clone());
match db.scan_runs().insert_one(&run).await {
Ok(insert) => insert.inserted_id.as_object_id().map(|id| id.to_hex()),
Err(e) => {
tracing::warn!(target_id, "queued scan run not recorded: {e}");
None
}
}
}
/// Remove the queued run `run_id` of a request that will not run, because
/// another queued scan covers it or took it over. A run that has started
/// meanwhile is kept.
async fn discard_queued_run(db: &crate::database::Database, run_id: Option<&str>) {
let Some(oid) = run_id.and_then(|id| mongodb::bson::oid::ObjectId::parse_str(id).ok()) else {
return;
};
if let Err(e) = db
.scan_runs()
.delete_one(mongodb::bson::doc! { "_id": oid, "status": "queued" })
.await
{
tracing::warn!(run_id = %oid, "queued scan run not removed: {e}");
}
}
/// Close the queued run `run_id` as failed when its scan ended with `error`
/// before it started (an unknown target, an unreachable database), so it does
/// not stay queued. A run the scan started records its own outcome.
async fn fail_queued_run(
db: &crate::database::Database,
run_id: Option<&str>,
error: &crate::error::AgentError,
) {
let Some(oid) = run_id.and_then(|id| mongodb::bson::oid::ObjectId::parse_str(id).ok()) else {
return;
};
let (code, message) = error.run_failure();
if let Err(e) = db
.scan_runs()
.update_one(
mongodb::bson::doc! { "_id": oid, "status": "queued" },
mongodb::bson::doc! { "$set": {
"status": "failed",
"error_message": message,
"error_code": mongodb::bson::to_bson(&code).unwrap_or_default(),
"completed_at": mongodb::bson::DateTime::now(),
} },
)
.await
{
tracing::warn!(run_id = %oid, "queued scan run not closed: {e}");
}
}
/// Findings of `target_id` first stored since `since`, by severity; `None`
/// when there are none.
async fn new_findings_summary(
db: &crate::database::Database,
tenant_id: &str,
target_id: &str,
since: chrono::DateTime<chrono::Utc>,
) -> Result<Option<crate::registry::FindingsNotification>, mongodb::error::Error> {
use mongodb::bson::doc;
let since_bson = mongodb::bson::DateTime::from_chrono(since);
let mut counts = [0u64; 5]; // critical, high, medium, low, info
for (i, sev) in ["critical", "high", "medium", "low", "info"]
.iter()
.enumerate()
{
counts[i] = db
.findings()
.count_documents(doc! { "repo_id": target_id, "severity": *sev, "created_at": { "$gte": since_bson } })
.await?;
}
let total: u64 = counts.iter().sum();
if total == 0 {
return Ok(None);
}
let name = match mongodb::bson::oid::ObjectId::parse_str(target_id) {
Ok(oid) => db
.onboarded_targets()
.find_one(doc! { "_id": oid })
.await?
.map(|t| t.name)
.unwrap_or_else(|| target_id.to_string()),
Err(_) => target_id.to_string(),
};
Ok(Some(findings_notification(
tenant_id,
target_id,
name,
counts,
since,
dashboard_url(),
)))
}
/// The public dashboard origin (DASHBOARD_PUBLIC_URL), for the mail's link.
fn dashboard_url() -> String {
std::env::var("DASHBOARD_PUBLIC_URL").unwrap_or_default()
}
fn findings_notification(
tenant_id: &str,
target_id: &str,
target_name: String,
counts: [u64; 5],
since: chrono::DateTime<chrono::Utc>,
dashboard: String,
) -> crate::registry::FindingsNotification {
let dashboard = dashboard.trim_end_matches('/');
crate::registry::FindingsNotification {
tenant_id: tenant_id.to_string(),
key: format!("findings:{tenant_id}:{target_id}:{}", since.timestamp()),
target_name,
new_count: counts.iter().sum(),
critical: counts[0],
high: counts[1],
medium: counts[2],
low: counts[3] + counts[4],
url: if dashboard.starts_with("https://") {
format!("{dashboard}/findings?target={target_id}")
} else {
String::new()
},
}
}
#[cfg(test)]
mod notification_tests {
use super::*;
#[test]
fn summary_counts_and_link() {
let since = chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap();
let n = findings_notification(
"t1",
"tg1",
"Pump".into(),
[1, 2, 0, 3, 4],
since,
"https://pruefwerk.breakpilot.com/".into(),
);
assert_eq!(n.new_count, 10);
assert_eq!((n.critical, n.high, n.medium, n.low), (1, 2, 0, 7));
assert_eq!(n.key, "findings:t1:tg1:1700000000");
assert_eq!(
n.url,
"https://pruefwerk.breakpilot.com/findings?target=tg1"
);
// no or non-https dashboard: the platform links its own page
assert_eq!(
findings_notification("t", "g", "x".into(), [0, 0, 1, 0, 0], since, String::new()).url,
""
);
assert_eq!(
findings_notification(
"t",
"g",
"x".into(),
[0, 0, 1, 0, 0],
since,
"http://x".into()
)
.url,
""
);
}
}