CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Canceled after 6m28s
Git tokens, tracker tokens, webhook secrets and pentest passwords were stored
in plain text and returned by the API. The old crypto helper fell back to
plain text when no key was set.
- `secrets::SecretBox`: AES-256-GCM under `SECRETS_ENCRYPTION_KEY`, with sealed
values stored as `enc:v1:…`. With no key it refuses to seal instead of
storing plain text. The key is required when APP_ENV is hardened, and a
malformed key stops startup in every environment. It replaces
`pentest/crypto.rs`.
- `compliance_core::models::Credentials` lists each record's credential fields
once. The agent seals them before a write and redacts them from every target,
DAST target and pentest-session response, including the MCP pentest tools.
- `PATCH /targets/{id}`: a credential left out keeps its stored value, an
empty string clears it, and a new one is sealed. A client echoing a redacted
record back therefore cannot erase a token.
- Pentest sessions are sealed before the first insert. Previously they were
inserted in plain text and encrypted afterwards.
- On startup the agent seals credentials that were stored in plain text.
- Webhook receivers fail closed: a target without a usable secret gets 401
instead of unsigned acceptance. GitLab tokens are compared in constant time.
New targets no longer get a webhook secret at creation; issuing one comes
back with the webhook work.
Part 1 of #260 (agent). Dashboard session hardening, the open redirect and
the webhook proxy follow in a separate PR.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
457 lines
15 KiB
Rust
457 lines
15 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, 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,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
pub struct SearchParams {
|
|
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"
|
|
)]
|
|
pub limit: i64,
|
|
}
|
|
|
|
fn default_search_limit() -> i64 {
|
|
50
|
|
}
|
|
|
|
/// GET /api/v1/graph/:repo_id — Full graph data
|
|
#[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,
|
|
}))
|
|
}
|
|
|
|
/// GET /api/v1/graph/:repo_id/nodes — List nodes (paginated)
|
|
#[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),
|
|
}))
|
|
}
|
|
|
|
/// GET /api/v1/graph/:repo_id/communities — List detected communities
|
|
#[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>,
|
|
}
|
|
|
|
/// GET /api/v1/graph/:repo_id/impact/:finding_id — Impact analysis
|
|
#[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,
|
|
}))
|
|
}
|
|
|
|
/// GET /api/v1/graph/:repo_id/search — BM25 symbol search
|
|
#[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(¶ms.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,
|
|
}))
|
|
}
|
|
|
|
/// GET /api/v1/graph/:repo_id/file-content — Read source file from cloned repo
|
|
#[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 get repo name
|
|
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.
|
|
let repo_dir = crate::pipeline::git::clone_dir(
|
|
std::path::Path::new(&agent.config.git_clone_base_path),
|
|
&tenant.0.tenant_id,
|
|
&repo.name,
|
|
);
|
|
let file_path = repo_dir.join(¶ms.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);
|
|
}
|
|
|
|
let content = std::fs::read_to_string(&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,
|
|
}))
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
pub struct FileContentParams {
|
|
pub path: String,
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
pub struct FileContent {
|
|
pub content: String,
|
|
pub path: String,
|
|
pub language: String,
|
|
}
|
|
|
|
/// POST /api/v1/graph/:repo_id/build — Trigger graph rebuild
|
|
#[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,
|
|
);
|
|
let repo_path = match git_ops.clone_or_fetch(&view.git_url, &view.name) {
|
|
Ok(p) => p,
|
|
Err(e) => {
|
|
tracing::error!("Failed to clone repo for graph build: {e}");
|
|
return;
|
|
}
|
|
};
|
|
|
|
let graph_build_id = uuid::Uuid::new_v4().to_string();
|
|
let engine = compliance_graph::GraphEngine::new(50_000);
|
|
|
|
match engine.build_graph(&repo_path, &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" }),
|
|
))
|
|
}
|