CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Dashboard (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Agent (push) Successful in 5m54s
425 lines
15 KiB
Rust
425 lines
15 KiB
Rust
use mongodb::bson::doc;
|
|
use tokio_cron_scheduler::{Job, JobScheduler};
|
|
|
|
use compliance_core::models::ScanTrigger;
|
|
|
|
use crate::agent::ComplianceAgent;
|
|
use crate::database::Database;
|
|
use crate::error::AgentError;
|
|
use crate::registry::scheduler_runs_for;
|
|
|
|
/// Default tenant the scheduler runs against when neither the tenant
|
|
/// registry nor `SCHEDULER_TENANT_IDS` are configured. Matches the
|
|
/// dev-injector default so a bare `cargo run` has the scheduler
|
|
/// scanning whatever lives in `<prefix>_dev`.
|
|
const DEFAULT_SCHEDULER_TENANT_ID: &str = "dev";
|
|
|
|
pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError> {
|
|
let sched = JobScheduler::new()
|
|
.await
|
|
.map_err(|e| AgentError::Scheduler(format!("Failed to create scheduler: {e}")))?;
|
|
|
|
// Periodic scan job
|
|
let scan_agent = agent.clone();
|
|
let scan_schedule = agent.config.scan_schedule.clone();
|
|
let scan_job = Job::new_async(scan_schedule.as_str(), move |_uuid, _lock| {
|
|
let agent = scan_agent.clone();
|
|
Box::pin(async move {
|
|
tracing::info!("Scheduled scan triggered");
|
|
let tenants = scheduler_tenants(&agent).await;
|
|
tracing::debug!(
|
|
tenant_count = tenants.len(),
|
|
"Scheduled scan: tenants resolved"
|
|
);
|
|
// Every tenant and target at once: each scan waits for one of the
|
|
// `SCAN_CONCURRENCY` slots, so a slow repository holds one slot,
|
|
// not the whole tick (#61).
|
|
futures_util::future::join_all(
|
|
tenants
|
|
.iter()
|
|
.map(|tenant_id| scan_all_repos(&agent, tenant_id)),
|
|
)
|
|
.await;
|
|
})
|
|
})
|
|
.map_err(|e| AgentError::Scheduler(format!("Failed to create scan job: {e}")))?;
|
|
sched
|
|
.add(scan_job)
|
|
.await
|
|
.map_err(|e| AgentError::Scheduler(format!("Failed to add scan job: {e}")))?;
|
|
|
|
// CVE monitor job (daily)
|
|
let cve_agent = agent.clone();
|
|
let cve_schedule = agent.config.cve_monitor_schedule.clone();
|
|
let cve_job = Job::new_async(cve_schedule.as_str(), move |_uuid, _lock| {
|
|
let agent = cve_agent.clone();
|
|
Box::pin(async move {
|
|
tracing::info!("CVE monitor triggered");
|
|
let tenants = scheduler_tenants(&agent).await;
|
|
tracing::debug!(
|
|
tenant_count = tenants.len(),
|
|
"CVE monitor: tenants resolved"
|
|
);
|
|
for tenant_id in &tenants {
|
|
monitor_cves(&agent, tenant_id).await;
|
|
}
|
|
// Components only NVD knows (by CPE), incrementally; `NVD_MONITOR=off`
|
|
// turns it off.
|
|
if crate::pipeline::nvd_monitor::enabled(std::env::var("NVD_MONITOR").ok().as_deref()) {
|
|
crate::pipeline::nvd_monitor::run(&agent, &tenants).await;
|
|
}
|
|
})
|
|
})
|
|
.map_err(|e| AgentError::Scheduler(format!("Failed to create CVE monitor job: {e}")))?;
|
|
sched
|
|
.add(cve_job)
|
|
.await
|
|
.map_err(|e| AgentError::Scheduler(format!("Failed to add CVE monitor job: {e}")))?;
|
|
|
|
// Vendor CSAF advisories (#515), shared by all tenants: daily, and once
|
|
// shortly after start so a new deployment does not wait a night.
|
|
let csaf_schedule =
|
|
std::env::var("CSAF_FEED_SCHEDULE").unwrap_or_else(|_| "0 30 3 * * *".to_string());
|
|
let csaf_agent = agent.clone();
|
|
let csaf_job = Job::new_async(csaf_schedule.as_str(), move |_uuid, _lock| {
|
|
let agent = csaf_agent.clone();
|
|
Box::pin(async move {
|
|
crate::pipeline::csaf_feed::refresh_index(&agent.db_pool.admin_db(), agent.net_guard)
|
|
.await;
|
|
})
|
|
})
|
|
.map_err(|e| AgentError::Scheduler(format!("Failed to create CSAF job: {e}")))?;
|
|
sched
|
|
.add(csaf_job)
|
|
.await
|
|
.map_err(|e| AgentError::Scheduler(format!("Failed to add CSAF job: {e}")))?;
|
|
let startup_agent = agent.clone();
|
|
tokio::spawn(async move {
|
|
tokio::time::sleep(std::time::Duration::from_secs(120)).await;
|
|
crate::pipeline::csaf_feed::refresh_index(
|
|
&startup_agent.db_pool.admin_db(),
|
|
startup_agent.net_guard,
|
|
)
|
|
.await;
|
|
});
|
|
|
|
// Managed git sync (#439): the organisation's repositories against the
|
|
// targets, a safety net for lost webhook deliveries.
|
|
let sync_agent = agent.clone();
|
|
let sync_job = Job::new_repeated_async(agent.git_source.sync_interval, move |_uuid, _lock| {
|
|
let agent = sync_agent.clone();
|
|
Box::pin(async move {
|
|
for tenant_id in scheduler_tenants(&agent).await {
|
|
match crate::git_source::sync_tenant(&agent, &tenant_id).await {
|
|
Ok(Some(report)) => {
|
|
tracing::info!(tenant_id, ?report, "managed git sync done");
|
|
}
|
|
Ok(None) => {}
|
|
Err(e) => tracing::warn!(tenant_id, "managed git sync failed: {e}"),
|
|
}
|
|
}
|
|
})
|
|
})
|
|
.map_err(|e| AgentError::Scheduler(format!("Failed to create git sync job: {e}")))?;
|
|
sched
|
|
.add(sync_job)
|
|
.await
|
|
.map_err(|e| AgentError::Scheduler(format!("Failed to add git sync job: {e}")))?;
|
|
|
|
sched
|
|
.start()
|
|
.await
|
|
.map_err(|e| AgentError::Scheduler(format!("Failed to start scheduler: {e}")))?;
|
|
|
|
let tenants = scheduler_tenants(agent).await;
|
|
let source = if agent.registry.is_some() {
|
|
"tenant-registry"
|
|
} else {
|
|
"env (SCHEDULER_TENANT_IDS)"
|
|
};
|
|
tracing::info!(
|
|
"Scheduler started: scans='{}', CVE monitor='{}', tenant source={source}, tenants={tenants:?}",
|
|
agent.config.scan_schedule,
|
|
agent.config.cve_monitor_schedule,
|
|
);
|
|
|
|
// Keep scheduler alive
|
|
loop {
|
|
tokio::time::sleep(tokio::time::Duration::from_secs(3600)).await;
|
|
}
|
|
}
|
|
|
|
/// Tenants the scheduler iterates each tick.
|
|
///
|
|
/// Resolution order:
|
|
/// 1. **Tenant registry** at `agent.config.tenant_registry_url`
|
|
/// (`GET /v1/tenants`). Fresh on every tick — picks up newly
|
|
/// provisioned tenants without an agent restart. Its answer is
|
|
/// authoritative: an empty list or a failed call **skips the tick**.
|
|
/// Falling back to env here used to mean a registry outage scanned
|
|
/// `<prefix>_dev` with no ladder filter.
|
|
/// 2. **`SCHEDULER_TENANT_IDS`** env, then `DEFAULT_SCHEDULER_TENANT_ID`
|
|
/// (`"dev"`) — only when no registry is configured at all, i.e. dev.
|
|
///
|
|
/// We never panic out of this function — the scheduler must keep
|
|
/// firing even if the registry is offline.
|
|
pub(crate) async fn scheduler_tenants(agent: &ComplianceAgent) -> Vec<String> {
|
|
if let Some(registry) = agent.registry.as_ref() {
|
|
match registry.list_tenants().await {
|
|
Ok(rows) => {
|
|
let v: Vec<String> = rows
|
|
.into_iter()
|
|
.filter(|t| scheduler_runs_for(&t.status))
|
|
.map(|t| t.id)
|
|
.collect();
|
|
if v.is_empty() {
|
|
tracing::info!("tenant-registry returned no runnable tenants; skipping tick");
|
|
}
|
|
// Authoritative, including when it is empty: every tenant may
|
|
// legitimately be restricted or halted.
|
|
return v;
|
|
}
|
|
Err(e) => {
|
|
// Never fall back to the dev tenant here. A registry outage
|
|
// must skip the tick, not scan `<prefix>_dev` unfiltered.
|
|
tracing::error!(error = %e, "tenant-registry fetch failed; skipping this tick");
|
|
return Vec::new();
|
|
}
|
|
}
|
|
}
|
|
tenants_from_env()
|
|
}
|
|
|
|
fn tenants_from_env() -> Vec<String> {
|
|
std::env::var("SCHEDULER_TENANT_IDS")
|
|
.ok()
|
|
.map(|s| {
|
|
s.split(',')
|
|
.map(str::trim)
|
|
.filter(|s| !s.is_empty())
|
|
.map(String::from)
|
|
.collect::<Vec<_>>()
|
|
})
|
|
.filter(|v| !v.is_empty())
|
|
.unwrap_or_else(|| vec![DEFAULT_SCHEDULER_TENANT_ID.to_string()])
|
|
}
|
|
|
|
async fn tenant_db(agent: &ComplianceAgent, tenant_id: &str) -> Option<Database> {
|
|
match agent.db_pool.for_tenant_id(tenant_id).await {
|
|
Ok(db) => Some(db),
|
|
Err(e) => {
|
|
tracing::error!("Scheduler: cannot open tenant database '{tenant_id}': {e}");
|
|
None
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn scan_all_repos(agent: &ComplianceAgent, tenant_id: &str) {
|
|
use futures_util::StreamExt;
|
|
|
|
let db = match tenant_db(agent, tenant_id).await {
|
|
Some(db) => db,
|
|
None => return,
|
|
};
|
|
|
|
// Archived targets (their managed repository was deleted) keep their
|
|
// findings but are not scanned any more.
|
|
let cursor = match db
|
|
.onboarded_targets()
|
|
.find(doc! { "archived_at": null })
|
|
.await
|
|
{
|
|
Ok(c) => c,
|
|
Err(e) => {
|
|
tracing::error!("Failed to list targets for tenant '{tenant_id}': {e}");
|
|
return;
|
|
}
|
|
};
|
|
|
|
let targets: Vec<_> = cursor.filter_map(|r| async { r.ok() }).collect().await;
|
|
|
|
// Started together; the scan slots (`SCAN_CONCURRENCY`) decide how many
|
|
// run, and each scan's start jitter spreads them out.
|
|
futures_util::stream::iter(targets)
|
|
.for_each_concurrent(None, |target| async move {
|
|
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
|
|
if let Err(e) = agent
|
|
.run_target_scan(tenant_id, &target_id, ScanTrigger::Scheduled)
|
|
.await
|
|
{
|
|
tracing::error!(
|
|
"Scheduled scan failed for {} (tenant '{tenant_id}'): {e}",
|
|
target.name
|
|
);
|
|
}
|
|
})
|
|
.await;
|
|
}
|
|
|
|
async fn monitor_cves(agent: &ComplianceAgent, tenant_id: &str) {
|
|
use compliance_core::models::SbomEntry;
|
|
use futures_util::StreamExt;
|
|
|
|
let db = match tenant_db(agent, tenant_id).await {
|
|
Some(db) => db,
|
|
None => return,
|
|
};
|
|
|
|
// One repository at a time: peak memory is one repo's SBOM, not the whole
|
|
// tenant's. This used to collect every SBOM entry of the tenant into one
|
|
// Vec before grouping it, hourly (#62).
|
|
let repo_ids: Vec<String> = match db.sbom_entries().distinct("repo_id", doc! {}).await {
|
|
Ok(ids) => ids
|
|
.into_iter()
|
|
.filter_map(|b| b.as_str().map(str::to_owned))
|
|
.collect(),
|
|
Err(e) => {
|
|
tracing::error!("CVE monitor: failed to list SBOM repos for '{tenant_id}': {e}");
|
|
return;
|
|
}
|
|
};
|
|
if repo_ids.is_empty() {
|
|
tracing::debug!("CVE monitor: no SBOM entries for tenant '{tenant_id}', skipping");
|
|
return;
|
|
}
|
|
tracing::info!(
|
|
"CVE monitor: checking {} repositories for new CVEs (tenant '{tenant_id}')",
|
|
repo_ids.len()
|
|
);
|
|
|
|
// Use the existing CveScanner to query OSV.dev
|
|
let nvd_key = agent.config.nvd_api_key.as_ref().map(|k| {
|
|
use secrecy::ExposeSecret;
|
|
k.expose_secret().to_string()
|
|
});
|
|
let scanner = match crate::pipeline::cve::CveScanner::new(agent.net_guard, nvd_key) {
|
|
Ok(scanner) => scanner,
|
|
Err(e) => {
|
|
tracing::error!("CVE monitor: no HTTP client for '{tenant_id}': {e}");
|
|
return;
|
|
}
|
|
};
|
|
|
|
let enricher = crate::pipeline::cve_enrichment::CveEnricher::new(
|
|
agent.net_guard,
|
|
Some(agent.exploit_cache.clone()),
|
|
)
|
|
.map_err(|e| tracing::warn!("CVE monitor: no exploitation lookups: {e}"))
|
|
.ok();
|
|
|
|
let mut new_notifications = 0u32;
|
|
|
|
for repo_id in repo_ids {
|
|
let repo_name = match mongodb::bson::oid::ObjectId::parse_str(&repo_id) {
|
|
Ok(oid) => db
|
|
.onboarded_targets()
|
|
.find_one(doc! { "_id": oid })
|
|
.await
|
|
.ok()
|
|
.flatten()
|
|
.map(|repo| repo.name),
|
|
Err(_) => None,
|
|
}
|
|
.unwrap_or_else(|| repo_id.clone());
|
|
|
|
let mut repo_entries: Vec<SbomEntry> =
|
|
match db.sbom_entries().find(doc! { "repo_id": &repo_id }).await {
|
|
Ok(cursor) => cursor.filter_map(|r| async { r.ok() }).collect().await,
|
|
Err(e) => {
|
|
tracing::warn!("CVE monitor: failed to load SBOM for {repo_name}: {e}");
|
|
continue;
|
|
}
|
|
};
|
|
|
|
// Scan dependencies for CVEs
|
|
// The periodic monitor only refreshes alerts; a scan records which
|
|
// components could not be checked.
|
|
let mut alerts = match scanner.scan_dependencies(&repo_id, &mut repo_entries).await {
|
|
Ok(lookup) => lookup.alerts,
|
|
Err(e) => {
|
|
tracing::warn!("CVE monitor: scan failed for {repo_name}: {e}");
|
|
continue;
|
|
}
|
|
};
|
|
|
|
// Whether each CVE is exploited (KEV, EPSS, SSVC; #493): cached for
|
|
// a day, so the hourly monitor asks the sources at most daily.
|
|
if let Some(enricher) = &enricher {
|
|
enricher.enrich(&mut alerts, &mut repo_entries).await;
|
|
}
|
|
|
|
// New alerts are stored; an existing alert's exploitation is
|
|
// refreshed.
|
|
for alert in &alerts {
|
|
if let Err(e) = crate::pipeline::vex_lifecycle::store_monitored(&db, alert).await {
|
|
tracing::warn!(
|
|
cve = alert.cve_id,
|
|
"CVE monitor: storing the alert failed: {e}"
|
|
);
|
|
}
|
|
}
|
|
|
|
// Update SBOM entries with discovered vulnerabilities
|
|
for entry in &repo_entries {
|
|
if entry.known_vulnerabilities.is_empty() {
|
|
continue;
|
|
}
|
|
if let Some(entry_id) = &entry.id {
|
|
let _ = db
|
|
.sbom_entries()
|
|
.update_one(
|
|
doc! { "_id": entry_id },
|
|
doc! { "$set": {
|
|
"known_vulnerabilities": mongodb::bson::to_bson(&entry.known_vulnerabilities).unwrap_or_default(),
|
|
"updated_at": mongodb::bson::DateTime::now(),
|
|
}},
|
|
)
|
|
.await;
|
|
}
|
|
}
|
|
|
|
// Notifications for new CVEs, none for one a VEX statement settles.
|
|
if let Err(e) =
|
|
crate::pipeline::vex_lifecycle::attach_stored_vex(&db, &repo_id, &mut alerts).await
|
|
{
|
|
tracing::warn!("CVE monitor: failed to read the VEX statements of {repo_name}: {e}");
|
|
continue;
|
|
}
|
|
new_notifications +=
|
|
crate::pipeline::cve_notify::notify_new_cves(&db, &repo_id, &repo_name, &alerts).await;
|
|
}
|
|
|
|
if new_notifications > 0 {
|
|
tracing::info!(
|
|
"CVE monitor: created {new_notifications} new notification(s) for tenant '{tenant_id}'"
|
|
);
|
|
} else {
|
|
tracing::info!("CVE monitor: no new CVEs found for tenant '{tenant_id}'");
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use crate::registry::scheduler_runs_for;
|
|
|
|
#[test]
|
|
fn ladder_filter_keeps_running_skips_read_only_and_dead() {
|
|
let rows = [
|
|
("a", "active"),
|
|
("b", "trial"),
|
|
("c", "demo"),
|
|
("d", "warning"),
|
|
("e", "restricted"),
|
|
("f", "frozen"),
|
|
("g", "halted"),
|
|
("h", "archived"),
|
|
];
|
|
let out: Vec<&str> = rows
|
|
.iter()
|
|
.filter(|(_, s)| scheduler_runs_for(s))
|
|
.map(|(id, _)| *id)
|
|
.collect();
|
|
assert_eq!(out, vec!["a", "b", "c", "d"]);
|
|
}
|
|
}
|