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, ScanGate}; use crate::secrets::SecretBox; /// 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, pub http: reqwest::Client, /// Per-session broadcast senders for SSE streaming. pub session_streams: Arc>>, /// Per-session pause controls (true = paused). pub session_pause: Arc>>, /// Semaphore limiting concurrent pentest sessions. pub session_semaphore: Arc, /// Platform tenant-registry client (entitlements, tenant list, API keys, /// usage events). `None` when `TENANT_REGISTRY_URL` is unset (dev). pub registry: Option>, /// 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, /// Seals tenant credentials before they are stored and opens them where /// they are used (#260). pub secrets: SecretBox, } impl ComplianceAgent { pub fn new(config: AgentConfig, db_pool: DatabasePool) -> Self { let llm = Arc::new(LlmClient::new( config.litellm_url.clone(), config.litellm_api_key.clone(), config.litellm_model.clone(), config.litellm_embed_model.clone(), )); 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); 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, } } 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, ) { 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: 1.0, 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}"); } }); } /// Scan a target, through the [`ScanGate`]: at most `SCAN_CONCURRENCY` scans /// run at once, and a request for a target that is already being scanned is /// coalesced — it becomes the one pending follow-up that this task runs next, /// or it is dropped if a follow-up is already pending. Every trigger /// (click, webhook, scheduler, demo seed) comes through here. /// /// # 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> { let key = ScanGate::key(tenant_id, target_id); match self.scan_gate.admit(&key, trigger.clone()) { Admission::Run => {} Admission::Coalesced => { tracing::info!( tenant_id, target_id, "scan already running; follow-up queued" ); return Ok(()); } Admission::Dropped => { tracing::info!( tenant_id, target_id, "scan and follow-up already queued; dropped" ); return Ok(()); } } // Released on panic or cancellation; a normal finish disarms it. let held = HeldTarget::new(&self.scan_gate, key.clone()); let mut trigger = trigger; let result = loop { let outcome = { let _slot = self .scan_gate .slot() .await .map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?; self.run_one_target_scan(tenant_id, target_id, trigger.clone()) .await }; if let Err(e) = &outcome { tracing::error!(tenant_id, target_id, "scan failed: {e}"); } match self.scan_gate.finish(&key) { Some(next) => trigger = next, None => break outcome, } }; held.disarm(); result } /// One scan of a target, with no gating: the pipeline plus its usage event. async fn run_one_target_scan( &self, tenant_id: &str, target_id: &str, trigger: compliance_core::models::ScanTrigger, ) -> Result<(), crate::error::AgentError> { let db = self.db_pool.for_tenant_id(tenant_id).await?; let orchestrator = PipelineOrchestrator::new( self.config.clone(), tenant_id, db.clone(), self.llm.clone(), self.http.clone(), ); let started = chrono::Utc::now(); orchestrator.run_target(target_id, trigger.clone()).await?; // Support's scans are ours, not the customer's usage. if 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:?}") }), ); } 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, ) { 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() .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(), self.http.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 { 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> { 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 { 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); } } /// 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, ) -> Result, 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, 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, "" ); } }