CI / Check (pull_request) Successful in 9m27s
CI / Detect Changes (pull_request) Has been skipped
CI / Deploy Agent (pull_request) Has been skipped
CI / Deploy Dashboard (pull_request) Has been skipped
CI / Deploy Docs (pull_request) Has been skipped
CI / Deploy MCP (pull_request) Has been skipped
Final slice of M7.2. Removes the transitional single-database handle that M7.2-A introduced alongside the pool, so the compliance-agent now has a single source of truth for storage: every code path obtains a tenant-scoped Database from `agent.db_pool.for_tenant_id(...)` or `for_tenant(&ctx)`. There is no shared "default" database anywhere. Changes - ComplianceAgent: `db: Database` field removed. ComplianceAgent::new now takes only `(config, db_pool)`. Verified by an earlier grep during M7.2-C that no remaining call site reads `agent.db`. - main.rs: stops constructing the legacy Database. Only the pool is built at startup. - TestServer: same — drops Database::connect/ensure_indexes, builds only the pool. cleanup() now drops every `<db_name>_*` per-tenant database (no longer touches a bare `<db_name>`). - DatabasePool::list_tenant_db_names() — lists Mongo databases matching the pool's prefix. For admin endpoints + scheduler tenant enumeration in a future M7.3 (this PR keeps SCHEDULER_TENANT_IDS env config — registry integration is a separate concern). - DatabasePool::drop_tenant(&str) — idempotent tenant offboarding. Drops the per-tenant database and evicts the in-memory `ensured` marker so a later re-provision re-runs ensure_indexes. Test plan - cargo fmt --all clean - cargo clippy --workspace --exclude compliance-dashboard -- -D warnings clean - cargo test -p compliance-core --lib — 7 pass - cargo test -p compliance-agent --lib — 228 pass - cargo test -p compliance-agent --test tenant_isolation — 6 pass including new `admin_helpers_list_and_drop_tenant_dbs` - cargo test -p compliance-agent --test tenant_status_middleware — 6 pass M7.2 closeout state after this lands - M7.1 (auth + status) — done - M7.2-A (pool) — done - M7.2-B (handlers) — done - M7.2-C (background paths) — done - M7.2-D (legacy db removed, admin helpers) — done (this PR) - Future M7.3: scheduler pulls tenants from tenant-registry instead of SCHEDULER_TENANT_IDS env; cross-tenant admin HTTP endpoints built on list_tenant_db_names / drop_tenant. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
147 lines
5.1 KiB
Rust
147 lines
5.1 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;
|
|
|
|
use crate::database::DatabasePool;
|
|
use crate::llm::LlmClient;
|
|
use crate::pipeline::orchestrator::PipelineOrchestrator;
|
|
|
|
/// 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>,
|
|
}
|
|
|
|
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();
|
|
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)),
|
|
}
|
|
}
|
|
|
|
pub async fn run_scan(
|
|
&self,
|
|
tenant_id: &str,
|
|
repo_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(), db, self.llm.clone(), self.http.clone());
|
|
orchestrator.run(repo_id, trigger).await
|
|
}
|
|
|
|
/// 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> {
|
|
let db = self.db_pool.for_tenant_id(tenant_id).await?;
|
|
let repo = db
|
|
.repositories()
|
|
.find_one(mongodb::bson::doc! {
|
|
"_id": mongodb::bson::oid::ObjectId::parse_str(repo_id)
|
|
.map_err(|e| crate::error::AgentError::Other(e.to_string()))?
|
|
})
|
|
.await?
|
|
.ok_or_else(|| {
|
|
crate::error::AgentError::Other(format!("Repository {repo_id} not found"))
|
|
})?;
|
|
|
|
let orchestrator =
|
|
PipelineOrchestrator::new(self.config.clone(), 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<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);
|
|
}
|
|
}
|