Files
pruefwerk/compliance-agent/src/api/handlers/graph.rs
T
sharang 48b1a4a47d
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Dashboard (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Agent (push) Successful in 5m43s
feat(api): the OpenAPI description covers the code graph and chat routes (#1006) (#1017)
2026-11-16 17:40:52 +00:00

665 lines
22 KiB
Rust

use std::sync::Arc;
use axum::extract::{Extension, Path, Query};
use axum::http::StatusCode;
use axum::Json;
use mongodb::bson::doc;
use serde::{Deserialize, Serialize};
use compliance_core::models::graph::{
CodeEdge, CodeNode, GraphBuildRun, GraphBuildStatus, ImpactAnalysis,
};
use compliance_core::tenant_ctx::TenantCtx;
use crate::agent::ComplianceAgent;
use super::dto::tenant_db;
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,
}
/// A symbol search.
#[derive(Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
pub struct SearchParams {
/// The search text.
pub q: String,
/// Clamped to `1..=MAX_PAGE_SIZE` while deserializing, like every list.
#[serde(
default = "default_search_limit",
deserialize_with = "super::dto::de_limit"
)]
#[param(minimum = 1, maximum = 200)]
pub limit: i64,
}
fn default_search_limit() -> i64 {
50
}
/// A target's code graph: its latest build, nodes and edges.
///
/// Truncated past a size a browser can lay out, and says so.
#[utoipa::path(
get,
path = "/api/v1/graph/{repo_id}",
tag = "Code graph",
params(("repo_id" = String, Path, description = "The target's id")),
responses(
(status = 200, description = "The graph"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
pub async fn get_graph(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(repo_id): Path<String>,
) -> Result<Json<ApiResponse<GraphData>>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let db = &db;
// Get latest build
let build: Option<GraphBuildRun> = db
.graph_builds()
.find_one(doc! { "repo_id": &repo_id })
.sort(doc! { "started_at": -1 })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
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);
// 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}");
Vec::new()
}
};
// 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::<std::collections::HashSet<_>>()
.into_iter()
.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()
}
}
};
let truncated = total_edges > edges.len() as u64;
(nodes, edges, truncated, total_edges, total_nodes)
} else {
(Vec::new(), Vec::new(), false, 0, 0)
};
Ok(Json(ApiResponse {
data: GraphData {
build,
nodes,
edges,
truncated,
total_edges,
total_nodes,
},
total: None,
page: None,
}))
}
/// A target's code graph nodes, a page at a time.
#[utoipa::path(
get,
path = "/api/v1/graph/{repo_id}/nodes",
tag = "Code graph",
params(("repo_id" = String, Path, description = "The target's id"), PaginationParams),
responses(
(status = 200, description = "A page of nodes"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
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 };
// 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}");
Vec::new()
}
};
Ok(Json(ApiResponse {
data: nodes,
total: Some(total),
page: Some(params.page),
}))
}
/// What the target page shows of a code graph.
#[derive(Serialize)]
pub struct GraphSummary {
/// Declarations: functions, methods, types, PLC blocks (nodes that are
/// not files).
pub units: u32,
pub entry_points: u32,
/// Language codes, sorted (`c`, `csharp`, `structured_text`, …).
pub languages: Vec<String>,
/// Source files left out because they could not be read as text; 0 when
/// none were, or the build did not count them.
pub unreadable_files: u32,
}
impl GraphSummary {
/// The summary of a completed build; `None` for one still running, a
/// failed one, or one stored before its files and entry points were
/// counted.
fn of(build: GraphBuildRun) -> Option<Self> {
if build.status != GraphBuildStatus::Completed {
return None;
}
Some(Self {
units: build.node_count.saturating_sub(build.file_count?),
entry_points: build.entry_point_count?,
languages: build.languages_parsed,
// Not `?`: a build from before this count still shows its card.
unreadable_files: build.unreadable_file_count.unwrap_or(0),
})
}
}
/// The counts of a target's latest graph build, without loading any node.
///
/// `data` is `null` when there is none to show.
#[utoipa::path(
get,
path = "/api/v1/graph/{repo_id}/summary",
tag = "Code graph",
params(("repo_id" = String, Path, description = "The target's id")),
responses(
(status = 200, description = "The counts, or null"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
pub async fn get_summary(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(repo_id): Path<String>,
) -> Result<Json<ApiResponse<Option<GraphSummary>>>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let build = db
.graph_builds()
.find_one(doc! { "repo_id": &repo_id })
.sort(doc! { "started_at": -1 })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(ApiResponse {
data: build.and_then(GraphSummary::of),
total: None,
page: None,
}))
}
/// The communities detected in a target's code graph.
#[utoipa::path(
get,
path = "/api/v1/graph/{repo_id}/communities",
tag = "Code graph",
params(("repo_id" = String, Path, description = "The target's id")),
responses(
(status = 200, description = "The communities"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
pub async fn get_communities(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(repo_id): Path<String>,
) -> Result<Json<ApiResponse<Vec<CommunityInfo>>>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let db = &db;
// 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 aggregate graph communities: {e}");
Vec::new()
}
};
let total = result.len() as u64;
Ok(Json(ApiResponse {
data: result,
total: Some(total),
page: None,
}))
}
#[derive(Serialize)]
pub struct CommunityInfo {
pub community_id: u32,
pub member_count: u32,
pub members: Vec<String>,
}
/// What a finding reaches in a target's code graph.
#[utoipa::path(
get,
path = "/api/v1/graph/{repo_id}/impact/{finding_id}",
tag = "Code graph",
params(("repo_id" = String, Path, description = "The target's id"), ("finding_id" = String, Path, description = "The finding's id")),
responses(
(status = 200, description = "The impact analysis, or null"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(repo_id = %repo_id, finding_id = %finding_id))]
pub async fn get_impact(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path((repo_id, finding_id)): Path<(String, String)>,
) -> Result<Json<ApiResponse<Option<ImpactAnalysis>>>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let db = &db;
let filter = doc! { "repo_id": &repo_id, "finding_id": &finding_id };
let impact = db
.impact_analyses()
.find_one(filter)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(ApiResponse {
data: impact,
total: None,
page: None,
}))
}
/// Search a target's code graph for symbols (BM25).
#[utoipa::path(
get,
path = "/api/v1/graph/{repo_id}/search",
tag = "Code graph",
params(("repo_id" = String, Path, description = "The target's id"), SearchParams),
responses(
(status = 200, description = "The matching nodes"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(repo_id = %repo_id, query = %params.q))]
pub async fn search_symbols(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(repo_id): Path<String>,
Query(params): Query<SearchParams>,
) -> Result<Json<ApiResponse<Vec<CodeNode>>>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let db = &db;
// Simple text search on qualified_name and name fields
let filter = doc! {
"repo_id": &repo_id,
// 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).await {
Ok(cursor) => collect_cursor_async(cursor).await,
Err(e) => {
tracing::warn!("Failed to search graph nodes: {e}");
Vec::new()
}
};
let total = nodes.len() as u64;
Ok(Json(ApiResponse {
data: nodes,
total: Some(total),
page: None,
}))
}
/// A source file of a target's checkout.
#[utoipa::path(
get,
path = "/api/v1/graph/{repo_id}/file-content",
tag = "Code graph",
params(("repo_id" = String, Path, description = "The target's id"), FileContentParams),
responses(
(status = 200, description = "The file"),
(status = 403, description = "The path leaves the checkout"),
(status = 404, description = "No such target, checkout or file"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
pub async fn get_file_content(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(repo_id): Path<String>,
Query(params): Query<FileContentParams>,
) -> Result<Json<ApiResponse<FileContent>>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let db = &db;
// Look up the repository to find its checkout
let repo = db
.onboarded_targets()
.find_one(doc! { "_id": mongodb::bson::oid::ObjectId::parse_str(&repo_id).ok() })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::NOT_FOUND)?;
// The checkout is per tenant — read only from the caller's own. It is
// named after the code artifact, as ingest clones it.
let checkout = repo
.code_artifact()
.map(|code| code.id.as_str())
.ok_or(StatusCode::NOT_FOUND)?;
let repo_dir = crate::pipeline::git::clone_dir(
std::path::Path::new(&agent.config.git_clone_base_path),
&tenant.0.tenant_id,
checkout,
);
let file_path = repo_dir.join(&params.path);
// Security: ensure we don't escape the repo directory
let canonical = file_path
.canonicalize()
.map_err(|_| StatusCode::NOT_FOUND)?;
let base_canonical = repo_dir.canonicalize().map_err(|_| StatusCode::NOT_FOUND)?;
if !canonical.starts_with(&base_canonical) {
return Err(StatusCode::FORBIDDEN);
}
// Decoded as the graph read it, so a UTF-16 or Windows-1252 file opens.
let content =
compliance_core::encoding::read_source(&canonical).map_err(|_| StatusCode::NOT_FOUND)?;
// Cap at 10,000 lines
let truncated: String = content.lines().take(10_000).collect::<Vec<_>>().join("\n");
let language = params.path.rsplit('.').next().unwrap_or("").to_string();
Ok(Json(ApiResponse {
data: FileContent {
content: truncated,
path: params.path,
language,
},
total: None,
page: None,
}))
}
/// The file of [`get_file_content`].
#[derive(Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
pub struct FileContentParams {
/// The file's path in the checkout.
pub path: String,
}
#[derive(Serialize)]
pub struct FileContent {
pub content: String,
pub path: String,
pub language: String,
}
/// Rebuild a target's code graph in the background.
#[utoipa::path(
post,
path = "/api/v1/graph/{repo_id}/build",
tag = "Code graph",
params(("repo_id" = String, Path, description = "The target's id")),
responses(
(status = 200, description = "The build was started"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
pub async fn trigger_build(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(repo_id): Path<String>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let agent_clone = (*agent).clone();
// The detached task has no request context, so carry the tenant id with it —
// it selects the tenant's own checkout directory.
let tenant_id = tenant.0.tenant_id.clone();
tokio::spawn(async move {
let repo = match db
.onboarded_targets()
.find_one(doc! { "_id": mongodb::bson::oid::ObjectId::parse_str(&repo_id).ok() })
.await
{
Ok(Some(r)) => r,
_ => {
tracing::error!("Repository {repo_id} not found for graph build");
return;
}
};
let code = match repo.code_artifact() {
Some(c) => c,
None => {
tracing::error!("Target {repo_id} has no code artifact for graph build");
return;
}
};
let view =
crate::pipeline::repo_view::RepoView::from_target(&repo, code, &agent_clone.secrets);
let creds = crate::pipeline::git::GitOps::make_repo_credentials(&view);
let git_ops = crate::pipeline::git::GitOps::new(
&agent_clone.config.git_clone_base_path,
&tenant_id,
creds,
agent_clone.net_guard,
);
let repo_path = match git_ops.clone_or_fetch(&view.git_url, &view.checkout) {
Ok(p) => p,
Err(e) => {
tracing::error!("Failed to clone repo for graph build: {e}");
return;
}
};
// A PLC target's graph is its POUs, as the scan builds it.
let plc_files = crate::pipeline::plan::build_scan_plan(&repo)
.has(compliance_core::models::ScanType::PlcControlLogic)
.then(|| crate::pipeline::plc::read_tree(&repo_path));
let source = match &plc_files {
Some(files) => crate::pipeline::graph_build::GraphSource::Plc(files),
None => crate::pipeline::graph_build::GraphSource::Tree(&repo_path),
};
let graph_build_id = uuid::Uuid::new_v4().to_string();
match crate::pipeline::graph_build::build_graph(source, &repo_id, &graph_build_id) {
Ok((code_graph, build_run)) => {
let store = compliance_graph::graph::persistence::GraphStore::new(db.inner());
let _ = store.delete_repo_graph(&repo_id).await;
let _ = store
.store_graph(&build_run, &code_graph.nodes, &code_graph.edges)
.await;
tracing::info!(
"[{repo_id}] Graph rebuild complete: {} nodes, {} edges",
build_run.node_count,
build_run.edge_count
);
}
Err(e) => {
tracing::error!("[{repo_id}] Graph rebuild failed: {e}");
}
}
});
Ok(Json(
serde_json::json!({ "status": "graph_build_triggered" }),
))
}
#[cfg(test)]
mod tests {
use super::*;
fn completed(nodes: u32, files: Option<u32>, entry_points: Option<u32>) -> GraphBuildRun {
let mut build = GraphBuildRun::new("t".to_string());
build.status = GraphBuildStatus::Completed;
build.node_count = nodes;
build.file_count = files;
build.entry_point_count = entry_points;
build.languages_parsed = vec!["c".to_string()];
build
}
#[test]
fn a_completed_build_counts_its_declarations() {
let summary = GraphSummary::of(completed(120, Some(20), Some(7))).expect("shown");
assert_eq!((summary.units, summary.entry_points), (100, 7));
assert_eq!(summary.languages, ["c"]);
}
#[test]
fn running_failed_and_uncounted_builds_show_nothing() {
let mut running = completed(10, Some(2), Some(1));
running.status = GraphBuildStatus::Running;
assert!(GraphSummary::of(running).is_none());
let mut failed = completed(10, Some(2), Some(1));
failed.status = GraphBuildStatus::Failed;
assert!(GraphSummary::of(failed).is_none());
assert!(GraphSummary::of(completed(10, None, None)).is_none());
}
#[test]
fn unreadable_files_are_shown_and_an_uncounted_build_has_none() {
let mut build = completed(10, Some(2), Some(1));
build.unreadable_file_count = Some(3);
assert_eq!(GraphSummary::of(build).expect("shown").unreadable_files, 3);
let uncounted = completed(10, Some(2), Some(1));
assert_eq!(
GraphSummary::of(uncounted).expect("shown").unreadable_files,
0
);
}
}