feat(security): bound memory on queries, archives and concurrent scans (#258) #297

Merged
sharang merged 2 commits from feat/resource-limits into main 2026-09-21 11:01:55 +00:00
19 changed files with 893 additions and 176 deletions

No files matched your search

+4
View File
@@ -30,6 +30,10 @@ NVD_API_KEY=
# Agent
AGENT_PORT=3001
# Scans (and PR reviews) running at once across all tenants; each is a clone
# plus semgrep and syft. Requests for a target already being scanned coalesce
# into one follow-up instead of running in parallel.
SCAN_CONCURRENCY=2
SCAN_SCHEDULE=0 0 */6 * * *
CVE_MONITOR_SCHEDULE=0 0 0 * * *
GIT_CLONE_BASE_PATH=/tmp/compliance-scanner/repos
+73 -3
View File
@@ -10,6 +10,7 @@ use crate::database::DatabasePool;
use crate::llm::LlmClient;
use crate::pipeline::orchestrator::PipelineOrchestrator;
use crate::registry::RegistryClient;
use crate::scan_gate::{Admission, HeldTarget, ScanGate};
/// Default maximum concurrent pentest sessions.
const DEFAULT_MAX_CONCURRENT_SESSIONS: usize = 5;
@@ -35,6 +36,8 @@ pub struct ComplianceAgent {
/// 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>,
}
impl ComplianceAgent {
@@ -52,6 +55,7 @@ impl ComplianceAgent {
.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));
Self {
config,
db_pool,
@@ -62,6 +66,7 @@ impl ComplianceAgent {
session_semaphore: Arc::new(Semaphore::new(DEFAULT_MAX_CONCURRENT_SESSIONS)),
registry,
net_guard,
scan_gate,
}
}
@@ -103,14 +108,72 @@ impl ComplianceAgent {
});
}
/// Alias for [`Self::run_scan`] — every scan runs the unified onboarded-target
/// pipeline. Kept as a distinct name for the `/targets/{id}/scan` endpoint's
/// intent.
/// 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(
@@ -140,6 +203,13 @@ impl ComplianceAgent {
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()))?;
+3 -3
View File
@@ -52,7 +52,7 @@ pub async fn list_targets(
) -> Result<Json<ApiResponse<Vec<DastTarget>>>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let db = &db;
let skip = (params.page.saturating_sub(1)) * params.limit as u64;
let skip = params.skip();
let total = db
.dast_targets()
.count_documents(doc! {})
@@ -205,7 +205,7 @@ pub async fn list_scan_runs(
) -> Result<Json<ApiResponse<Vec<DastScanRun>>>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let db = &db;
let skip = (params.page.saturating_sub(1)) * params.limit as u64;
let skip = params.skip();
let total = db
.dast_scan_runs()
.count_documents(doc! {})
@@ -243,7 +243,7 @@ pub async fn list_findings(
) -> Result<Json<ApiResponse<Vec<DastFinding>>>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let db = &db;
let skip = (params.page.saturating_sub(1)) * params.limit as u64;
let skip = params.skip();
let total = db
.dast_findings()
.count_documents(doc! {})
+159 -8
View File
@@ -3,14 +3,35 @@ use serde::{Deserialize, Serialize};
use compliance_core::models::ScanRun;
/// The largest page a caller may ask for.
///
/// `limit` and `page` arrive from the query string, so they are attacker-chosen
/// numbers that decide how much the agent loads into memory and hands back.
/// `?limit=10000000` used to be honoured. Both are clamped **while
/// deserializing**, so no handler can forget to do it.
pub const MAX_PAGE_SIZE: i64 = 200;
/// Upper bound on `page`, so `skip` cannot overflow or ask Mongo to walk an
/// absurd offset. At [`MAX_PAGE_SIZE`] this is still 20M documents deep.
pub const MAX_PAGE: u64 = 100_000;
#[derive(Deserialize)]
pub struct PaginationParams {
#[serde(default = "default_page")]
#[serde(default = "default_page", deserialize_with = "de_page")]
pub page: u64,
#[serde(default = "default_limit")]
#[serde(default = "default_limit", deserialize_with = "de_limit")]
pub limit: i64,
}
impl PaginationParams {
/// Documents to skip for this page. Bounded by construction.
pub fn skip(&self) -> u64 {
self.page
.saturating_sub(1)
.saturating_mul(self.limit as u64)
}
}
pub(crate) fn default_page() -> u64 {
1
}
@@ -18,6 +39,16 @@ pub(crate) fn default_limit() -> i64 {
50
}
/// Clamp a caller-supplied page number to `1..=MAX_PAGE`.
pub(crate) fn de_page<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
Ok(u64::deserialize(d)?.clamp(1, MAX_PAGE))
}
/// Clamp a caller-supplied page size to `1..=MAX_PAGE_SIZE`.
pub(crate) fn de_limit<'de, D: serde::Deserializer<'de>>(d: D) -> Result<i64, D::Error> {
Ok(i64::deserialize(d)?.clamp(1, MAX_PAGE_SIZE))
}
#[derive(Deserialize)]
pub struct FindingsFilter {
#[serde(default)]
@@ -34,12 +65,69 @@ pub struct FindingsFilter {
pub sort_by: Option<String>,
#[serde(default)]
pub sort_order: Option<String>,
#[serde(default = "default_page")]
#[serde(default = "default_page", deserialize_with = "de_page")]
pub page: u64,
#[serde(default = "default_limit")]
#[serde(default = "default_limit", deserialize_with = "de_limit")]
pub limit: i64,
}
impl FindingsFilter {
/// Documents to skip for this page. Bounded by construction.
pub fn skip(&self) -> u64 {
self.page
.saturating_sub(1)
.saturating_mul(self.limit as u64)
}
}
/// Fields a caller may sort findings by.
///
/// `sort_by` went into the sort document verbatim, so a caller could sort on
/// any field at all — unindexed ones cost a full collection scan plus an
/// in-memory sort, and a `$`-prefixed name is not a field. An unknown value
/// falls back to the default rather than erroring, so existing clients keep
/// working.
pub const SORTABLE_FINDING_FIELDS: &[&str] = &[
"created_at",
"updated_at",
"severity",
"scan_type",
"status",
"file_path",
"rule_id",
"repo_id",
"title",
"confidence",
];
/// The sort field to use, defaulting to `created_at`.
pub fn finding_sort_field(requested: Option<&str>) -> &'static str {
requested
.and_then(|r| SORTABLE_FINDING_FIELDS.iter().find(|f| **f == r))
.copied()
.unwrap_or("created_at")
}
/// The longest search term accepted.
pub const MAX_SEARCH_LEN: usize = 128;
/// Turn a caller's search term into a literal regex.
///
/// The term used to reach Mongo as a regex, so `(a+)+$` was a
/// catastrophic-backtracking denial of service and `.*` a full scan. Every
/// metacharacter is escaped, so the search means what a user expects — a
/// substring — and nothing more.
pub fn literal_regex(term: &str) -> String {
let mut out = String::with_capacity(term.len() + 8);
for c in term.chars().take(MAX_SEARCH_LEN) {
if "\\^$.|?*+()[]{}".contains(c) {
out.push('\\');
}
out.push(c);
}
out
}
#[derive(Serialize)]
pub struct ApiResponse<T: Serialize> {
pub data: T,
@@ -123,12 +211,21 @@ pub struct SbomFilter {
pub has_vulns: Option<bool>,
#[serde(default)]
pub license: Option<String>,
#[serde(default = "default_page")]
#[serde(default = "default_page", deserialize_with = "de_page")]
pub page: u64,
#[serde(default = "default_limit")]
#[serde(default = "default_limit", deserialize_with = "de_limit")]
pub limit: i64,
}
impl SbomFilter {
/// Documents to skip for this page. Bounded by construction.
pub fn skip(&self) -> u64 {
self.page
.saturating_sub(1)
.saturating_mul(self.limit as u64)
}
}
#[derive(Deserialize)]
pub struct SbomExportParams {
pub repo_id: String,
@@ -244,9 +341,63 @@ mod tests {
}
#[test]
fn pagination_params_zero_page() {
fn pagination_params_clamp_hostile_input() {
// Page 0 would make `skip` underflow; it becomes the first page.
let p: PaginationParams = serde_json::from_str(r#"{"page":0}"#).unwrap();
assert_eq!(p.page, 0);
assert_eq!(p.page, 1);
assert_eq!(p.skip(), 0);
// A caller cannot ask the agent to load ten million documents.
let p: PaginationParams = serde_json::from_str(r#"{"limit":10000000}"#).unwrap();
assert_eq!(p.limit, MAX_PAGE_SIZE);
let p: PaginationParams = serde_json::from_str(r#"{"limit":-5}"#).unwrap();
assert_eq!(p.limit, 1);
// And cannot push `skip` past what Mongo can reasonably serve.
let p: PaginationParams =
serde_json::from_str(r#"{"page":99999999999,"limit":200}"#).unwrap();
assert_eq!(p.page, MAX_PAGE);
assert_eq!(p.skip(), (MAX_PAGE - 1) * 200);
}
#[test]
fn sort_field_is_an_allowlist() {
assert_eq!(finding_sort_field(Some("severity")), "severity");
assert_eq!(finding_sort_field(None), "created_at");
// Not a field, an unindexed field, or an operator: all fall back.
assert_eq!(finding_sort_field(Some("$where")), "created_at");
assert_eq!(finding_sort_field(Some("description")), "created_at");
assert_eq!(finding_sort_field(Some("")), "created_at");
}
#[test]
fn search_terms_are_literal_not_regex() {
// A plain term is unchanged.
assert_eq!(literal_regex("openssl"), "openssl");
// The classic catastrophic-backtracking pattern becomes a literal.
assert_eq!(literal_regex("(a+)+$"), r"\(a\+\)\+\$");
// As does a match-everything scan.
assert_eq!(literal_regex(".*"), r"\.\*");
// Over-long terms are truncated rather than rejected.
let long = "x".repeat(MAX_SEARCH_LEN + 50);
assert_eq!(literal_regex(&long).len(), MAX_SEARCH_LEN);
}
#[test]
fn sbom_filter_clamps_the_same_way() {
let f: SbomFilter = serde_json::from_str(r#"{"limit":10000000,"page":0}"#).unwrap();
assert_eq!(f.limit, MAX_PAGE_SIZE);
assert_eq!(f.page, 1);
assert_eq!(f.skip(), 0);
}
#[test]
fn findings_filter_clamps_the_same_way() {
let f: FindingsFilter = serde_json::from_str(r#"{"limit":5000,"page":0}"#).unwrap();
assert_eq!(f.limit, MAX_PAGE_SIZE);
assert_eq!(f.page, 1);
assert_eq!(f.skip(), 0);
}
// ── FindingsFilter ───────────────────────────────────────────
@@ -31,7 +31,7 @@ pub async fn list_findings(
// Text search across title, description, file_path, rule_id
if let Some(q) = &filter.q {
if !q.is_empty() {
let regex = doc! { "$regex": q, "$options": "i" };
let regex = doc! { "$regex": super::dto::literal_regex(q), "$options": "i" };
query.insert(
"$or",
mongodb::bson::bson!([
@@ -45,14 +45,14 @@ pub async fn list_findings(
}
// Dynamic sort
let sort_field = filter.sort_by.as_deref().unwrap_or("created_at");
let sort_field = super::dto::finding_sort_field(filter.sort_by.as_deref());
let sort_dir: i32 = match filter.sort_order.as_deref() {
Some("asc") => 1,
_ => -1,
};
let sort_doc = doc! { sort_field: sort_dir };
let skip = (filter.page.saturating_sub(1)) * filter.limit as u64;
let skip = filter.skip();
let total = db
.findings()
.count_documents(query.clone())
+127 -55
View File
@@ -12,25 +12,46 @@ use compliance_core::tenant_ctx::TenantCtx;
use crate::agent::ComplianceAgent;
use super::dto::tenant_db;
use super::{collect_cursor_async, ApiResponse};
use super::{collect_cursor_async, ApiResponse, PaginationParams};
type AgentExt = Extension<Arc<ComplianceAgent>>;
/// The largest graph returned to the browser in one response.
///
/// A force-directed layout is unreadable well before this, and loading every
/// edge of a very large repository into agent memory was #63. Larger graphs are
/// truncated and say so; a community-level view is the follow-up for them.
pub const MAX_GRAPH_EDGES: i64 = 10_000;
/// The most members listed per community; `member_count` stays exact.
pub const MAX_COMMUNITY_MEMBERS: i64 = 50;
#[derive(Serialize)]
pub struct GraphData {
pub build: Option<GraphBuildRun>,
pub nodes: Vec<CodeNode>,
pub edges: Vec<CodeEdge>,
/// `true` when the graph has more than [`MAX_GRAPH_EDGES`] edges and only
/// the first of them (and the nodes they connect) are returned.
pub truncated: bool,
/// Edges in the full graph, so a truncated view can say "showing N of M".
pub total_edges: u64,
/// Nodes in the full graph.
pub total_nodes: u64,
}
#[derive(Deserialize)]
pub struct SearchParams {
pub q: String,
#[serde(default = "default_search_limit")]
pub limit: usize,
/// Clamped to `1..=MAX_PAGE_SIZE` while deserializing, like every list.
#[serde(
default = "default_search_limit",
deserialize_with = "super::dto::de_limit"
)]
pub limit: i64,
}
fn default_search_limit() -> usize {
fn default_search_limit() -> i64 {
50
}
@@ -52,19 +73,30 @@ pub async fn get_graph(
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let (nodes, edges) = if build.is_some() {
let (nodes, edges, truncated, total_edges, total_nodes) = if build.is_some() {
// Filter by repo_id only — delete_repo_graph clears old data before each rebuild,
// so there is only one set of nodes/edges per repo.
let filter = doc! { "repo_id": &repo_id };
let total_edges = db
.graph_edges()
.count_documents(filter.clone())
.await
.unwrap_or(0);
let total_nodes = db
.graph_nodes()
.count_documents(filter.clone())
.await
.unwrap_or(0);
let all_nodes: Vec<CodeNode> = match db.graph_nodes().find(filter.clone()).await {
Ok(cursor) => collect_cursor_async(cursor).await,
Err(e) => {
tracing::warn!("Failed to fetch graph nodes: {e}");
Vec::new()
}
};
let edges: Vec<CodeEdge> = match db.graph_edges().find(filter).await {
// Edges first and bounded; stable order so a truncated view is the same
// on every load.
let edges: Vec<CodeEdge> = match db
.graph_edges()
.find(filter)
.sort(doc! { "_id": 1 })
.limit(MAX_GRAPH_EDGES)
.await
{
Ok(cursor) => collect_cursor_async(cursor).await,
Err(e) => {
tracing::warn!("Failed to fetch graph edges: {e}");
@@ -72,19 +104,34 @@ pub async fn get_graph(
}
};
// Remove disconnected nodes (no edges) to keep the graph clean
let connected: std::collections::HashSet<&str> = edges
// Only the nodes those edges connect — disconnected nodes were dropped
// before as well — fetched by name instead of loading all of them.
let connected: Vec<&str> = edges
.iter()
.flat_map(|e| [e.source.as_str(), e.target.as_str()])
.collect();
let nodes = all_nodes
.collect::<std::collections::HashSet<_>>()
.into_iter()
.filter(|n| connected.contains(n.qualified_name.as_str()))
.collect();
let nodes: Vec<CodeNode> = if connected.is_empty() {
Vec::new()
} else {
match db
.graph_nodes()
.find(doc! { "repo_id": &repo_id, "qualified_name": { "$in": connected } })
.await
{
Ok(cursor) => collect_cursor_async(cursor).await,
Err(e) => {
tracing::warn!("Failed to fetch graph nodes: {e}");
Vec::new()
}
}
};
(nodes, edges)
let truncated = total_edges > edges.len() as u64;
(nodes, edges, truncated, total_edges, total_nodes)
} else {
(Vec::new(), Vec::new())
(Vec::new(), Vec::new(), false, 0, 0)
};
Ok(Json(ApiResponse {
@@ -92,6 +139,9 @@ pub async fn get_graph(
build,
nodes,
edges,
truncated,
total_edges,
total_nodes,
},
total: None,
page: None,
@@ -104,12 +154,26 @@ pub async fn get_nodes(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(repo_id): Path<String>,
Query(params): Query<PaginationParams>,
) -> Result<Json<ApiResponse<Vec<CodeNode>>>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let db = &db;
let filter = doc! { "repo_id": &repo_id };
let nodes: Vec<CodeNode> = match db.graph_nodes().find(filter).await {
// Documented as paginated but returned every node of the repository (#63).
let total = db
.graph_nodes()
.count_documents(filter.clone())
.await
.unwrap_or(0);
let nodes: Vec<CodeNode> = match db
.graph_nodes()
.find(filter)
.sort(doc! { "_id": 1 })
.skip(params.skip())
.limit(params.limit)
.await
{
Ok(cursor) => collect_cursor_async(cursor).await,
Err(e) => {
tracing::warn!("Failed to fetch graph nodes: {e}");
@@ -117,11 +181,10 @@ pub async fn get_nodes(
}
};
let total = nodes.len() as u64;
Ok(Json(ApiResponse {
data: nodes,
total: Some(total),
page: None,
page: Some(params.page),
}))
}
@@ -134,37 +197,50 @@ pub async fn get_communities(
) -> Result<Json<ApiResponse<Vec<CommunityInfo>>>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let db = &db;
let filter = doc! { "repo_id": &repo_id };
let nodes: Vec<CodeNode> = match db.graph_nodes().find(filter).await {
Ok(cursor) => collect_cursor_async(cursor).await,
// Grouped in Mongo rather than by loading every node of the repository into
// the agent (#63); `$firstN` keeps each member list bounded while
// `member_count` stays exact.
let pipeline = vec![
doc! { "$match": { "repo_id": &repo_id, "community_id": { "$ne": null } } },
doc! { "$group": {
"_id": "$community_id",
"member_count": { "$sum": 1 },
"members": { "$firstN": { "input": "$qualified_name", "n": MAX_COMMUNITY_MEMBERS } },
} },
doc! { "$sort": { "_id": 1 } },
];
// One aggregation row. BSON may carry the counts as Int32 or Int64 depending
// on size; deserializing into i64 accepts both.
#[derive(Deserialize)]
struct CommunityRow {
#[serde(rename = "_id")]
community_id: i64,
member_count: i64,
members: Vec<String>,
}
let result: Vec<CommunityInfo> = match db.graph_nodes().aggregate(pipeline).await {
Ok(cursor) => {
use futures_util::StreamExt;
cursor
.filter_map(|row| async move {
let row: CommunityRow = mongodb::bson::from_document(row.ok()?).ok()?;
Some(CommunityInfo {
community_id: u32::try_from(row.community_id).ok()?,
member_count: u32::try_from(row.member_count).ok()?,
members: row.members,
})
})
.collect()
.await
}
Err(e) => {
tracing::warn!("Failed to fetch graph nodes for communities: {e}");
tracing::warn!("Failed to aggregate graph communities: {e}");
Vec::new()
}
};
let mut communities: std::collections::HashMap<u32, Vec<String>> =
std::collections::HashMap::new();
for node in &nodes {
if let Some(cid) = node.community_id {
communities
.entry(cid)
.or_default()
.push(node.qualified_name.clone());
}
}
let mut result: Vec<CommunityInfo> = communities
.into_iter()
.map(|(id, members)| CommunityInfo {
community_id: id,
member_count: members.len() as u32,
members,
})
.collect();
result.sort_by_key(|c| c.community_id);
let total = result.len() as u64;
Ok(Json(ApiResponse {
data: result,
@@ -218,15 +294,11 @@ pub async fn search_symbols(
// Simple text search on qualified_name and name fields
let filter = doc! {
"repo_id": &repo_id,
"name": { "$regex": &params.q, "$options": "i" },
// Literal substring, not a caller-supplied regex (same fix as #64).
"name": { "$regex": super::dto::literal_regex(&params.q), "$options": "i" },
};
let nodes: Vec<CodeNode> = match db
.graph_nodes()
.find(filter)
.limit(params.limit as i64)
.await
{
let nodes: Vec<CodeNode> = match db.graph_nodes().find(filter).limit(params.limit).await {
Ok(cursor) => collect_cursor_async(cursor).await,
Err(e) => {
tracing::warn!("Failed to search graph nodes: {e}");
+1 -1
View File
@@ -14,7 +14,7 @@ pub async fn list_issues(
) -> ApiResult<Vec<TrackerIssue>> {
let db = tenant_db(&agent, &tenant).await?;
let db = &db;
let skip = (params.page.saturating_sub(1)) * params.limit as u64;
let skip = params.skip();
let total = db
.tracker_issues()
.count_documents(doc! {})
@@ -40,9 +40,14 @@ pub async fn list_notifications(
filter.insert("repo_id", repo_id.as_str());
}
let page = params.page.unwrap_or(1).max(1);
let limit = params.limit.unwrap_or(50).min(200);
let skip = (page - 1) * limit as u64;
// Same bounds as every other list: a negative limit or a huge page used to
// wrap `skip` into an enormous offset.
let page = params.page.unwrap_or(1).clamp(1, super::dto::MAX_PAGE);
let limit = params
.limit
.unwrap_or(50)
.clamp(1, super::dto::MAX_PAGE_SIZE);
let skip = (page - 1).saturating_mul(limit as u64);
let total = db
.cve_notifications()
@@ -99,7 +99,7 @@ pub async fn list_targets(
Query(params): Query<PaginationParams>,
) -> Result<Json<ApiResponse<Vec<OnboardedTarget>>>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let skip = (params.page.saturating_sub(1)) * params.limit as u64;
let skip = params.skip();
let total = db
.onboarded_targets()
.count_documents(doc! {})
@@ -754,6 +754,11 @@ pub async fn resume_session(
}))
}
/// The most attack-chain nodes returned for one session. A pentest run is
/// already bounded by its iteration budget; this keeps a runaway session from
/// being loaded whole into agent memory.
const MAX_ATTACK_CHAIN_NODES: i64 = 2_000;
/// GET /api/v1/pentest/sessions/:id/attack-chain — Get attack chain nodes for a session
#[tracing::instrument(skip_all, fields(session_id = %id))]
pub async fn get_attack_chain(
@@ -764,10 +769,20 @@ pub async fn get_attack_chain(
let _oid = mongodb::bson::oid::ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
let db = tenant_db(&agent, &tenant).await?;
// The dashboard draws the whole chain, so this is capped rather than paged
// (#66): `total` is the real count, and `total > data.len()` means the chain
// was truncated.
let filter = doc! { "session_id": &id };
let total = db
.attack_chain_nodes()
.count_documents(filter.clone())
.await
.unwrap_or(0);
let nodes = match db
.attack_chain_nodes()
.find(doc! { "session_id": &id })
.find(filter)
.sort(doc! { "started_at": 1 })
.limit(MAX_ATTACK_CHAIN_NODES)
.await
{
Ok(cursor) => collect_cursor_async(cursor).await,
@@ -777,7 +792,6 @@ pub async fn get_attack_chain(
}
};
let total = nodes.len() as u64;
Ok(Json(ApiResponse {
data: nodes,
total: Some(total),
+92 -50
View File
@@ -8,6 +8,14 @@ use super::dto::*;
use compliance_core::models::SbomEntry;
use compliance_core::tenant_ctx::TenantCtx;
/// Components above which an export is refused instead of built (#67). An
/// SBOM is a compliance document, so it is never truncated: a repository this
/// large gets a clear error, not a partial file.
const MAX_EXPORT_COMPONENTS: u64 = 100_000;
/// Package names listed per license in the summary; `count` stays exact.
const MAX_LICENSE_PACKAGES: i64 = 100;
const COPYLEFT_LICENSES: &[&str] = &[
"GPL-2.0",
"GPL-2.0-only",
@@ -79,7 +87,10 @@ pub async fn list_sbom(
}
if let Some(q) = &filter.q {
if !q.is_empty() {
query.insert("name", doc! { "$regex": q, "$options": "i" });
query.insert(
"name",
doc! { "$regex": super::dto::literal_regex(q), "$options": "i" },
);
}
}
if let Some(has_vulns) = filter.has_vulns {
@@ -93,7 +104,7 @@ pub async fn list_sbom(
query.insert("license", license);
}
let skip = (filter.page.saturating_sub(1)) * filter.limit as u64;
let skip = filter.skip();
let total = db
.sbom_entries()
.count_documents(query.clone())
@@ -130,6 +141,18 @@ pub async fn export_sbom(
) -> Result<impl IntoResponse, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let db = &db;
let components = db
.sbom_entries()
.count_documents(doc! { "repo_id": &params.repo_id })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if components > MAX_EXPORT_COMPONENTS {
tracing::warn!(
components,
"SBOM export refused: too large to build in memory"
);
return Err(StatusCode::PAYLOAD_TOO_LARGE);
}
let entries: Vec<SbomEntry> = match db
.sbom_entries()
.find(doc! { "repo_id": &params.repo_id })
@@ -253,35 +276,47 @@ pub async fn license_summary(
query.insert("repo_id", repo_id);
}
let entries: Vec<SbomEntry> = match db.sbom_entries().find(query).await {
Ok(cursor) => collect_cursor_async(cursor).await,
// Grouped in Mongo: this used to load every SBOM entry of the tenant (with
// its vulnerability list) into the agent when no repo was given (#67).
#[derive(serde::Deserialize)]
struct LicenseRow {
#[serde(rename = "_id")]
license: String,
count: i64,
packages: Vec<String>,
}
let pipeline = vec![
doc! { "$match": query },
doc! { "$group": {
"_id": { "$ifNull": ["$license", "Unknown"] },
"count": { "$sum": 1 },
"packages": { "$firstN": { "input": "$name", "n": MAX_LICENSE_PACKAGES } },
} },
];
let mut summaries: Vec<LicenseSummary> = match db.sbom_entries().aggregate(pipeline).await {
Ok(cursor) => {
use futures_util::StreamExt;
cursor
.filter_map(|row| async move {
let row: LicenseRow = mongodb::bson::from_document(row.ok()?).ok()?;
let upper = row.license.to_uppercase();
Some(LicenseSummary {
is_copyleft: COPYLEFT_LICENSES
.iter()
.any(|c| upper.contains(&c.to_uppercase())),
license: row.license,
count: u64::try_from(row.count).unwrap_or(0),
packages: row.packages,
})
})
.collect()
.await
}
Err(e) => {
tracing::warn!("Failed to fetch SBOM entries for license summary: {e}");
tracing::warn!("Failed to aggregate SBOM licenses: {e}");
Vec::new()
}
};
let mut license_map: std::collections::HashMap<String, Vec<String>> =
std::collections::HashMap::new();
for entry in &entries {
let lic = entry.license.as_deref().unwrap_or("Unknown").to_string();
license_map.entry(lic).or_default().push(entry.name.clone());
}
let mut summaries: Vec<LicenseSummary> = license_map
.into_iter()
.map(|(license, packages)| {
let is_copyleft = COPYLEFT_LICENSES
.iter()
.any(|c| license.to_uppercase().contains(&c.to_uppercase()));
LicenseSummary {
license,
count: packages.len() as u64,
is_copyleft,
packages,
}
})
.collect();
summaries.sort_by_key(|s| std::cmp::Reverse(s.count));
Ok(Json(ApiResponse {
@@ -300,29 +335,8 @@ pub async fn sbom_diff(
let db = tenant_db(&agent, &tenant).await?;
let db = &db;
let entries_a: Vec<SbomEntry> = match db
.sbom_entries()
.find(doc! { "repo_id": &params.repo_a })
.await
{
Ok(cursor) => collect_cursor_async(cursor).await,
Err(e) => {
tracing::warn!("Failed to fetch SBOM entries for repo_a: {e}");
Vec::new()
}
};
let entries_b: Vec<SbomEntry> = match db
.sbom_entries()
.find(doc! { "repo_id": &params.repo_b })
.await
{
Ok(cursor) => collect_cursor_async(cursor).await,
Err(e) => {
tracing::warn!("Failed to fetch SBOM entries for repo_b: {e}");
Vec::new()
}
};
let entries_a = diff_rows(db, &params.repo_a).await;
let entries_b = diff_rows(db, &params.repo_b).await;
// Build maps by (name, package_manager) -> version
let map_a: std::collections::HashMap<(String, String), String> = entries_a
@@ -388,3 +402,31 @@ pub async fn sbom_diff(
page: None,
}))
}
/// The three fields a diff compares, for one repository.
///
/// A diff must be complete, so it is not capped; instead it loads only
/// name, package manager and version, not whole entries with their
/// vulnerability lists (#67).
#[derive(serde::Deserialize)]
struct DiffRow {
name: String,
package_manager: String,
version: String,
}
async fn diff_rows(db: &crate::database::Database, repo_id: &str) -> Vec<DiffRow> {
match db
.sbom_entries()
.clone_with_type::<DiffRow>()
.find(doc! { "repo_id": repo_id })
.projection(doc! { "_id": 0, "name": 1, "package_manager": 1, "version": 1 })
.await
{
Ok(cursor) => collect_cursor_async(cursor).await,
Err(e) => {
tracing::warn!("Failed to fetch SBOM entries for diff: {e}");
Vec::new()
}
}
}
+1 -1
View File
@@ -14,7 +14,7 @@ pub async fn list_scan_runs(
) -> ApiResult<Vec<ScanRun>> {
let db = tenant_db(&agent, &tenant).await?;
let db = &db;
let skip = (params.page.saturating_sub(1)) * params.limit as u64;
let skip = params.skip();
let total = db.scan_runs().count_documents(doc! {}).await.unwrap_or(0);
let scans = match db
+4
View File
@@ -55,6 +55,10 @@ fn build_config(app_env: AppEnv) -> Result<AgentConfig, AgentError> {
agent_port: env_var_opt("AGENT_PORT")
.and_then(|p| p.parse().ok())
.unwrap_or(3001),
scan_concurrency: env_var_opt("SCAN_CONCURRENCY")
.and_then(|v| v.parse::<usize>().ok())
.filter(|n| *n > 0)
.unwrap_or(2),
scan_schedule: env_var_opt("SCAN_SCHEDULE").unwrap_or_else(|| "0 0 */6 * * *".to_string()),
cve_monitor_schedule: env_var_opt("CVE_MONITOR_SCHEDULE")
.unwrap_or_else(|| "0 0 * * * *".to_string()),
+134 -8
View File
@@ -86,13 +86,71 @@ pub fn store_file(base: &Path, src: &Path, sha: &str) -> Result<PathBuf, AgentEr
Ok(dest)
}
/// Extract a zip archive into `dest` (created if needed). `enclosed_name`
/// sanitizes each entry path, so this is safe against zip-slip traversal.
/// What one archive may expand to.
///
/// Extraction used to trust the archive completely: a few-kilobyte zip bomb
/// expands to terabytes and fills the node's disk. The limits are enforced on
/// bytes actually written, not on the sizes an entry declares about itself,
/// since those are attacker-controlled.
#[derive(Debug, Clone, Copy)]
pub struct ExtractLimits {
/// Most entries (files and directories) one archive may contain.
pub max_entries: usize,
/// Most bytes the whole archive may expand to on disk.
pub max_total_bytes: u64,
}
impl Default for ExtractLimits {
fn default() -> Self {
Self {
max_entries: 100_000,
max_total_bytes: 2 * 1024 * 1024 * 1024,
}
}
}
/// Extract a zip into `dest` under the default [`ExtractLimits`].
pub fn extract_zip(archive: &Path, dest: &Path) -> Result<(), AgentError> {
extract_zip_with(archive, dest, ExtractLimits::default())
}
/// Extract a zip into `dest` (created if needed), refusing archives that
/// exceed `limits`. `enclosed_name` sanitizes each entry path, so this is safe
/// against zip-slip traversal.
///
/// On any error the partly written `dest` is removed: callers fall back to
/// treating the file as a single blob, and must not find half an archive
/// (or half a bomb) left behind in the working directory.
///
/// # Errors
///
/// Returns an error when the file is not a zip, an entry cannot be read or
/// written, or the archive exceeds `limits`.
pub fn extract_zip_with(
archive: &Path,
dest: &Path,
limits: ExtractLimits,
) -> Result<(), AgentError> {
let result = extract_bounded(archive, dest, limits);
if result.is_err() {
let _ = fs::remove_dir_all(dest);
}
result
}
fn extract_bounded(archive: &Path, dest: &Path, limits: ExtractLimits) -> Result<(), AgentError> {
let file = File::open(archive)?;
let mut zip =
zip::ZipArchive::new(file).map_err(|e| AgentError::Other(format!("open zip: {e}")))?;
if zip.len() > limits.max_entries {
return Err(AgentError::Other(format!(
"archive has {} entries, more than the {} allowed",
zip.len(),
limits.max_entries
)));
}
fs::create_dir_all(dest)?;
let mut written_total: u64 = 0;
for i in 0..zip.len() {
let mut entry = zip
.by_index(i)
@@ -104,13 +162,23 @@ pub fn extract_zip(archive: &Path, dest: &Path) -> Result<(), AgentError> {
let out = dest.join(rel);
if entry.is_dir() {
fs::create_dir_all(&out)?;
} else {
if let Some(parent) = out.parent() {
fs::create_dir_all(parent)?;
}
let mut outfile = File::create(&out)?;
io::copy(&mut entry, &mut outfile)?;
continue;
}
if let Some(parent) = out.parent() {
fs::create_dir_all(parent)?;
}
// Read at most one byte past what is left of the budget: getting that
// byte proves the archive is over the limit, whatever its headers say.
let budget = limits.max_total_bytes - written_total;
let mut outfile = File::create(&out)?;
let written = io::copy(&mut (&mut entry).take(budget + 1), &mut outfile)?;
if written > budget {
return Err(AgentError::Other(format!(
"archive expands beyond {} bytes",
limits.max_total_bytes
)));
}
written_total += written;
}
Ok(())
}
@@ -228,4 +296,62 @@ mod tests {
"hi"
);
}
/// Build a zip in `dir` with `files` entries of `size` zero bytes each —
/// zeros compress to almost nothing, which is what makes a bomb.
fn zip_of_zeros(dir: &Path, files: usize, size: usize) -> PathBuf {
let archive = dir.join("bomb.zip");
let file = File::create(&archive).expect("create");
let mut w = zip::ZipWriter::new(file);
let opts: zip::write::SimpleFileOptions = Default::default();
let zeros = vec![0u8; size];
for i in 0..files {
w.start_file(format!("f{i}.bin"), opts).expect("start");
io::Write::write_all(&mut w, &zeros).expect("write");
}
w.finish().expect("finish");
archive
}
#[test]
fn an_archive_that_expands_past_the_budget_is_refused_and_cleaned_up() {
let base = Scratch::new();
// 3 x 1 MiB of zeros: a tiny file on disk, 3 MiB expanded.
let archive = zip_of_zeros(base.path(), 3, 1024 * 1024);
let dest = base.path().join("out");
let limits = ExtractLimits {
max_entries: 100,
max_total_bytes: 2 * 1024 * 1024,
};
let err = extract_zip_with(&archive, &dest, limits).expect_err("must refuse");
assert!(err.to_string().contains("expands beyond"), "{err}");
assert!(!dest.exists(), "partial output must be removed");
}
#[test]
fn an_archive_with_too_many_entries_is_refused() {
let base = Scratch::new();
let archive = zip_of_zeros(base.path(), 5, 1);
let dest = base.path().join("out");
let limits = ExtractLimits {
max_entries: 4,
max_total_bytes: u64::MAX / 2,
};
let err = extract_zip_with(&archive, &dest, limits).expect_err("must refuse");
assert!(err.to_string().contains("entries"), "{err}");
assert!(!dest.exists());
}
#[test]
fn an_archive_within_the_limits_extracts_whole() {
let base = Scratch::new();
let archive = zip_of_zeros(base.path(), 3, 1024);
let dest = base.path().join("out");
let limits = ExtractLimits {
max_entries: 3,
max_total_bytes: 3 * 1024,
};
extract_zip_with(&archive, &dest, limits).expect("exactly at the limit is fine");
assert_eq!(fs::read(dest.join("f2.bin")).expect("read").len(), 1024);
}
}
+1
View File
@@ -15,6 +15,7 @@ pub mod pentest;
pub mod pipeline;
pub mod rag;
pub mod registry;
pub mod scan_gate;
pub mod scheduler;
pub mod targets;
pub mod tenant_path;
+216
View File
@@ -0,0 +1,216 @@
//! How many scans run at once, and what happens to a scan requested while the
//! same target is already being scanned.
//!
//! Every scan used to be a bare `tokio::spawn` with no limit. A burst of pushes,
//! a scheduler tick and a few clicks could start any number of scans side by
//! side — each one a clone plus semgrep plus syft — on an 8 GB node, and two
//! scans of the same target shared one checkout directory and corrupted each
//! other. Two rules now apply to every trigger (click, webhook, scheduler):
//!
//! * **Global:** at most `SCAN_CONCURRENCY` scans run at a time; the rest wait
//! for a slot.
//! * **Per target — coalesce:** one scan runs and at most one more is pending.
//! A request that arrives while one is pending is dropped, because the pending
//! scan will pick up the latest code anyway. Ten pushes during a long scan
//! therefore cost two scans, not ten. Dropped requests are never billed: only
//! a scan that actually ran emits usage.
use std::sync::Arc;
use dashmap::mapref::entry::Entry;
use dashmap::DashMap;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use compliance_core::models::ScanTrigger;
/// What happened to a scan request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Admission {
/// Nothing was running for this target: the caller runs the scan now.
Run,
/// A scan is running; this request becomes the single pending follow-up,
/// run by the task that holds the target once it finishes.
Coalesced,
/// A scan is running and a follow-up is already pending: nothing to do.
Dropped,
}
/// Global scan slots plus the per-target coalescing state.
#[derive(Debug)]
pub struct ScanGate {
slots: Arc<Semaphore>,
/// Present while a scan of the key is running; the value is the pending
/// follow-up's trigger, if one was requested meanwhile.
running: DashMap<String, Option<ScanTrigger>>,
}
impl ScanGate {
/// A gate allowing `concurrency` scans at once (at least one).
pub fn new(concurrency: usize) -> Self {
Self {
slots: Arc::new(Semaphore::new(concurrency.max(1))),
running: DashMap::new(),
}
}
/// The key a target's scans are coalesced under.
pub fn key(tenant_id: &str, target_id: &str) -> String {
// NUL cannot appear in either id, so distinct pairs never collide.
format!("{tenant_id}\u{0}{target_id}")
}
/// Decide what to do with a scan request for `key`. Atomic per key, so two
/// simultaneous requests can never both be told to [`Admission::Run`].
pub fn admit(&self, key: &str, trigger: ScanTrigger) -> Admission {
match self.running.entry(key.to_string()) {
Entry::Vacant(v) => {
v.insert(None);
Admission::Run
}
Entry::Occupied(mut o) if o.get().is_none() => {
o.insert(Some(trigger));
Admission::Coalesced
}
Entry::Occupied(_) => Admission::Dropped,
}
}
/// Called by the task holding `key` after each scan. Returns the pending
/// follow-up to run next (the target stays held), or `None` once there is
/// nothing left, releasing the target.
pub fn finish(&self, key: &str) -> Option<ScanTrigger> {
match self.running.entry(key.to_string()) {
Entry::Occupied(mut o) => match o.get_mut().take() {
Some(next) => Some(next),
None => {
o.remove();
None
}
},
Entry::Vacant(_) => None,
}
}
/// Release `key` unconditionally, dropping any pending follow-up. Used when
/// the holding task dies, so the target does not stay "running" forever.
pub fn release(&self, key: &str) {
self.running.remove(key);
}
/// Wait for one of the global scan slots. The slot is freed when the
/// returned permit is dropped.
///
/// # Errors
///
/// Only if the semaphore was closed, which this gate never does.
pub async fn slot(&self) -> Result<OwnedSemaphorePermit, tokio::sync::AcquireError> {
self.slots.clone().acquire_owned().await
}
}
/// Releases a target when the task holding it ends abnormally (panic, or the
/// future being dropped at shutdown). A normal finish disarms it.
pub struct HeldTarget<'a> {
gate: &'a ScanGate,
key: String,
armed: bool,
}
impl<'a> HeldTarget<'a> {
/// Hold `key` on `gate` until [`Self::disarm`] or drop.
pub fn new(gate: &'a ScanGate, key: String) -> Self {
Self {
gate,
key,
armed: true,
}
}
/// The target was released through [`ScanGate::finish`]; nothing to undo.
pub fn disarm(mut self) {
self.armed = false;
}
}
impl Drop for HeldTarget<'_> {
fn drop(&mut self) {
if self.armed {
self.gate.release(&self.key);
}
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::{Admission, HeldTarget, ScanGate};
use compliance_core::models::ScanTrigger;
#[test]
fn a_burst_coalesces_into_one_run_and_one_follow_up() {
let gate = ScanGate::new(2);
let key = ScanGate::key("acme", "t1");
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Coalesced);
for _ in 0..8 {
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Dropped);
}
// The holder runs the one follow-up, then releases the target.
assert!(gate.finish(&key).is_some());
assert!(gate.finish(&key).is_none());
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
}
#[test]
fn targets_and_tenants_are_independent() {
let gate = ScanGate::new(2);
assert_eq!(
gate.admit(&ScanGate::key("acme", "t1"), ScanTrigger::Manual),
Admission::Run
);
assert_eq!(
gate.admit(&ScanGate::key("acme", "t2"), ScanTrigger::Manual),
Admission::Run
);
// Same target id in another tenant is another target.
assert_eq!(
gate.admit(&ScanGate::key("globex", "t1"), ScanTrigger::Manual),
Admission::Run
);
}
#[test]
fn a_dead_holder_does_not_leave_the_target_locked() {
let gate = ScanGate::new(1);
let key = ScanGate::key("acme", "t1");
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
{
// The holding task ends without calling finish (panic / shutdown).
let _held = HeldTarget::new(&gate, key.clone());
}
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
}
#[test]
fn a_disarmed_holder_leaves_the_state_to_finish() {
let gate = ScanGate::new(1);
let key = ScanGate::key("acme", "t1");
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
HeldTarget::new(&gate, key.clone()).disarm();
// Still held: disarm does not release, finish does.
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Coalesced);
}
#[tokio::test]
async fn slots_bound_how_many_scans_run_at_once() {
let gate = ScanGate::new(2);
let a = gate.slot().await.unwrap();
let _b = gate.slot().await.unwrap();
// A third slot is not available until one is freed.
let third = tokio::time::timeout(std::time::Duration::from_millis(50), gate.slot()).await;
assert!(third.is_err(), "a third concurrent scan must wait");
drop(a);
let third = tokio::time::timeout(std::time::Duration::from_millis(50), gate.slot()).await;
assert!(third.is_ok(), "a freed slot is reused");
}
}
+34 -38
View File
@@ -72,7 +72,7 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError>
let tenants = scheduler_tenants(agent).await;
let source = if agent.registry.is_some() {
"tenant-registry (env fallback)"
"tenant-registry"
} else {
"env (SCHEDULER_TENANT_IDS)"
};
@@ -220,38 +220,28 @@ async fn monitor_cves(agent: &ComplianceAgent, tenant_id: &str) {
None => return,
};
// Fetch all SBOM entries grouped by repo
let cursor = match db.sbom_entries().find(doc! {}).await {
Ok(c) => c,
// 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 entries for '{tenant_id}': {e}");
tracing::error!("CVE monitor: failed to list SBOM repos for '{tenant_id}': {e}");
return;
}
};
let entries: Vec<SbomEntry> = cursor.filter_map(|r| async { r.ok() }).collect().await;
if entries.is_empty() {
if repo_ids.is_empty() {
tracing::debug!("CVE monitor: no SBOM entries for tenant '{tenant_id}', skipping");
return;
}
tracing::info!(
"CVE monitor: checking {} dependencies for new CVEs (tenant '{tenant_id}')",
entries.len()
"CVE monitor: checking {} repositories for new CVEs (tenant '{tenant_id}')",
repo_ids.len()
);
// Build a repo_id → repo_name lookup
let repo_ids: std::collections::HashSet<String> =
entries.iter().map(|e| e.repo_id.clone()).collect();
let mut repo_names: std::collections::HashMap<String, String> =
std::collections::HashMap::new();
for rid in &repo_ids {
if let Ok(oid) = mongodb::bson::oid::ObjectId::parse_str(rid) {
if let Ok(Some(repo)) = db.onboarded_targets().find_one(doc! { "_id": oid }).await {
repo_names.insert(rid.clone(), repo.name.clone());
}
}
}
// Use the existing CveScanner to query OSV.dev
let nvd_key = agent.config.nvd_api_key.as_ref().map(|k| {
use secrecy::ExposeSecret;
@@ -263,23 +253,29 @@ async fn monitor_cves(agent: &ComplianceAgent, tenant_id: &str) {
nvd_key,
);
// Group entries by repo for scanning
let mut entries_by_repo: std::collections::HashMap<String, Vec<SbomEntry>> =
std::collections::HashMap::new();
for entry in entries {
entries_by_repo
.entry(entry.repo_id.clone())
.or_default()
.push(entry);
}
let mut new_notifications = 0u32;
for (repo_id, mut repo_entries) in entries_by_repo {
let repo_name = repo_names
.get(&repo_id)
.cloned()
.unwrap_or_else(|| repo_id.clone());
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
let alerts = match scanner.scan_dependencies(&repo_id, &mut repo_entries).await {
+5
View File
@@ -21,6 +21,10 @@ pub struct AgentConfig {
pub searxng_url: Option<String>,
pub nvd_api_key: Option<SecretString>,
pub agent_port: u16,
/// Most scans (and PR reviews) running at once across all tenants and
/// targets (`SCAN_CONCURRENCY`, default 2). Each is a clone plus semgrep and
/// syft, so this is what keeps a burst from exhausting the node's memory.
pub scan_concurrency: usize,
pub scan_schedule: String,
pub cve_monitor_schedule: String,
pub git_clone_base_path: String,
@@ -229,6 +233,7 @@ impl Default for AgentConfig {
searxng_url: None,
nvd_api_key: None,
agent_port: 3001,
scan_concurrency: 2,
scan_schedule: "0 0 */6 * * *".to_string(),
cve_monitor_schedule: "0 0 * * * *".to_string(),
git_clone_base_path: "/tmp/compliance-scanner/repos".to_string(),
+11
View File
@@ -32,6 +32,16 @@ Repositories are scanned automatically on a recurring schedule. By default, scan
When you configure a webhook in your Git hosting provider, scans are triggered automatically on push events. You can also get automated PR reviews. See [Webhooks & PR Reviews](/guide/webhooks) for setup instructions.
### When scans overlap
A deployment runs a limited number of scans at once (`SCAN_CONCURRENCY`, two by
default); further scans wait for a free slot. A target is never scanned twice in
parallel: if a scan is requested while one is already running for that target,
it is queued as a single follow-up, and any further requests while that
follow-up is waiting are dropped — the follow-up will scan the latest code
anyway. Ten pushes during one long scan therefore cost two scans, and only scans
that actually run are counted towards your plan.
## Scan Phases and Statuses
Each scan progresses through these statuses:
@@ -81,6 +91,7 @@ address is refused.
aimed at `10.x` PLCs on purpose, so it sets `PW_ALLOW_PRIVATE_TARGETS=1`. A
hardened cloud deployment ignores that variable — it shares a network with the
platform's own services.
## What the scanner runs on your code
Nearly every stage only *reads* your code: Semgrep, gitleaks, Syft, Ruff and the