Files
pruefwerk/compliance-dashboard/src/infrastructure/server.rs
T
sharangandClaude Opus 5.5 492247625e
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Agent (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Successful in 2m48s
fix(dashboard): keep the dashboard out of search indexes (#361)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-09-23 22:03:42 +00:00

193 lines
7.9 KiB
Rust

use axum::routing::get;
use axum::{middleware, Extension};
use dioxus::prelude::*;
use time::Duration;
use tower_http::set_header::SetResponseHeaderLayer;
use tower_sessions::SessionManagerLayer;
use compliance_core::config::AppEnv;
use compliance_core::models::{McpServerConfig, McpServerStatus, McpTransport};
use mongodb::bson::doc;
use super::config;
use super::database::Database;
use super::error::DashboardError;
use super::keycloak_config::KeycloakConfig;
use super::server_state::{ServerState, ServerStateInner};
use super::session_store::{load_session_key, MongoSessionStore};
use super::{auth_callback, auth_login, logout, require_auth, PendingOAuthStore};
pub fn server_start(app: fn() -> Element) -> Result<(), DashboardError> {
tokio::runtime::Runtime::new()
.map_err(|e| DashboardError::Other(e.to_string()))?
.block_on(async move {
dotenvy::dotenv().ok();
let config = config::load_config()?;
let keycloak: Option<&'static KeycloakConfig> =
KeycloakConfig::from_env().map(|kc| &*Box::leak(Box::new(kc)));
let db = Database::connect(&config.mongodb_uri, &config.mongodb_database).await?;
// Seed default MCP server configs
seed_default_mcp_servers(&db, config.mcp_endpoint_url.as_deref()).await;
let app_env = AppEnv::parse(&std::env::var("APP_ENV").unwrap_or_default())
.map_err(DashboardError::Other)?;
if let Some(kc) = keycloak {
tracing::info!(
app_env = app_env.as_str(),
"Keycloak configured for realm '{}'",
kc.realm
);
} else if app_env.is_hardened() {
// Without every variable the auth middleware waves all
// `/api/` calls through, so refuse to serve instead.
return Err(DashboardError::Other(format!(
"APP_ENV={} requires Keycloak; missing: {}",
app_env.as_str(),
KeycloakConfig::missing_env().join(", ")
)));
} else {
tracing::warn!("Keycloak not configured - dashboard is unprotected");
}
// Explicit MCP health URL — needed where an ingress strips the
// `/mcp` prefix (staging: `…/mcp/health` → compliance-mcp `/health`).
let mcp_health_url = std::env::var("MCP_HEALTH_URL")
.ok()
.map(|v| v.trim().to_string())
.filter(|v| !v.is_empty());
// Sessions survive a redeploy: signed with a key from the
// environment, stored sealed in Mongo (#260).
let key = load_session_key(app_env)?;
let store = MongoSessionStore::new(db.inner(), &key).await?;
let session = SessionManagerLayer::new(store)
// HTTPS-only outside dev; a local dashboard is plain http.
.with_secure(app_env.is_hardened())
.with_http_only(true)
.with_same_site(tower_sessions::cookie::SameSite::Lax)
.with_expiry(tower_sessions::Expiry::OnInactivity(Duration::hours(24)))
.with_signed(key);
let server_state: ServerState = ServerStateInner {
agent_api_url: config.agent_api_url.clone(),
db,
config,
keycloak,
mcp_health_url,
}
.into();
let port = dioxus_cli_config::server_port().unwrap_or(8080);
let addr = std::net::SocketAddr::from(([0, 0, 0, 0], port));
let listener = tokio::net::TcpListener::bind(addr)
.await
.map_err(|e| DashboardError::Other(format!("Failed to bind: {e}")))?;
tracing::info!("Dashboard server listening on {addr}");
let router = axum::Router::new()
// Liveness for the container healthcheck; outside `/api/`, so
// it needs no session.
.route("/health", get(|| async { "ok" }))
// A signed-in application: nothing here belongs in a search
// index (the orca agent adds no headers of its own).
.route(
"/robots.txt",
get(|| async { "User-agent: *\nDisallow: /\n" }),
)
.route("/auth", get(auth_login))
.route("/auth/callback", get(auth_callback))
.route("/logout", get(logout))
.serve_dioxus_application(ServeConfig::new(), app)
// No raised body limit: uploads stream through `FileStream`, which
// reads the raw body, so every other server function keeps axum's
// 2 MiB default instead of accepting 512 MiB JSON.
.layer(Extension(PendingOAuthStore::default()))
.layer(middleware::from_fn(require_auth))
.layer(Extension(server_state))
.layer(session)
.layer(SetResponseHeaderLayer::overriding(
axum::http::HeaderName::from_static("x-robots-tag"),
axum::http::HeaderValue::from_static("noindex, nofollow"),
));
axum::serve(listener, router.into_make_service())
.await
.map_err(|e| DashboardError::Other(format!("Server error: {e}")))?;
Ok(())
})
}
/// Seed three default MCP server configs (Findings, SBOM, DAST) if they don't already exist.
async fn seed_default_mcp_servers(db: &Database, mcp_endpoint_url: Option<&str>) {
let endpoint = mcp_endpoint_url.unwrap_or("http://localhost:8090");
let defaults = [
(
"Findings MCP",
"Exposes security findings, triage data, and finding summaries to LLM agents",
vec!["list_findings", "get_finding", "findings_summary"],
),
(
"SBOM MCP",
"Exposes software bill of materials and vulnerability reports to LLM agents",
vec!["list_sbom_packages", "sbom_vuln_report"],
),
(
"DAST MCP",
"Exposes DAST scan findings and scan summaries to LLM agents",
vec!["list_dast_findings", "dast_scan_summary"],
),
];
let collection = db.mcp_servers();
let expected_url = format!("{endpoint}/mcp");
for (name, description, tools) in defaults {
// If it already exists, update the endpoint URL if it changed
if let Ok(Some(existing)) = collection.find_one(doc! { "name": name }).await {
if existing.endpoint_url != expected_url {
let _ = collection
.update_one(
doc! { "name": name },
doc! { "$set": { "endpoint_url": &expected_url } },
)
.await;
tracing::info!(
"Updated MCP server '{name}' endpoint: {} -> {expected_url}",
existing.endpoint_url
);
}
continue;
}
let now = chrono::Utc::now();
let token = format!("mcp_{}", uuid::Uuid::new_v4().to_string().replace('-', ""));
let server = McpServerConfig {
id: None,
name: name.to_string(),
endpoint_url: format!("{endpoint}/mcp"),
transport: McpTransport::Http,
port: Some(8090),
status: McpServerStatus::Stopped,
access_token: token,
tools_enabled: tools.into_iter().map(|s| s.to_string()).collect(),
description: Some(description.to_string()),
mongodb_uri: None,
mongodb_database: None,
created_at: now,
updated_at: now,
};
match collection.insert_one(server).await {
Ok(_) => tracing::info!("Seeded default MCP server: {name}"),
Err(e) => tracing::warn!("Failed to seed MCP server '{name}': {e}"),
}
}
}