Files
pruefwerk/compliance-dashboard/src/infrastructure/server.rs
T
sharang 808b6ab3aa
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Canceled after 0s
CI / Deploy Agent (push) Canceled after 0s
fix(mcp): MCP server cards per tenant, not shared by all (#454)
2026-10-05 18:19:04 +00:00

241 lines
9.7 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 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, auth_staff_login, logout, require_auth, PendingOAuthStore};
/// The docs site when `DOCS_URL` is unset: served on the dashboard host.
/// Keep the trailing slash: the docs route matches `/docs/*`, and a plain
/// `/docs` lands on the dashboard's "route not found" page.
const DEFAULT_DOCS_URL: &str = "/docs/";
/// An optional setting from the environment, trimmed; unset or blank is `None`.
fn env_setting(name: &str) -> Option<String> {
non_blank(std::env::var(name).ok())
}
/// `value` trimmed, or `None` when it is missing or blank.
fn non_blank(value: Option<String>) -> Option<String> {
value
.map(|v| v.trim().to_string())
.filter(|v| !v.is_empty())
}
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?;
retire_global_mcp_servers(&db).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 = env_setting("MCP_HEALTH_URL");
let portal_url = env_setting("PORTAL_URL");
// Read at runtime: staging and production share one image but
// not one docs site.
let docs_url = env_setting("DOCS_URL").unwrap_or_else(|| DEFAULT_DOCS_URL.to_string());
// 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,
portal_url,
docs_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" }),
)
// The BreakPilot chevron at the paths browsers and tools ask
// for; `/favicon.ico` too, since browsers read an SVG there.
.route("/favicon.svg", get(favicon))
.route("/favicon.ico", get(favicon))
// Geist and Geist Mono, self-hosted: main.css loads them from
// here, so no page makes a request to a third-party font CDN.
.route("/fonts/geist.woff2", get(font_geist))
.route("/fonts/geist-mono.woff2", get(font_geist_mono))
.route("/auth", get(auth_login))
.route("/auth/staff", get(auth_staff_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(())
})
}
/// Remove the MCP server cards the dashboard used to keep for every tenant
/// at once (#432). They now live in each tenant's database at the agent, which
/// creates the default cards per tenant; the old shared ones cannot be told
/// apart by tenant, so they are dropped.
async fn retire_global_mcp_servers(db: &Database) {
let old = db
.inner()
.collection::<mongodb::bson::Document>("mcp_servers");
match old.count_documents(doc! {}).await {
Ok(0) | Err(_) => {}
Ok(count) => match old.drop().await {
Ok(()) => tracing::info!(
"Removed {count} MCP server cards shared by all tenants; each tenant now has its own"
),
Err(e) => tracing::warn!("Could not remove the shared MCP server cards: {e}"),
},
}
}
/// The BreakPilot chevron, the icon the portal and the website use.
const FAVICON_SVG: &str = include_str!("../../assets/favicon.svg");
/// The favicon: the chevron as SVG, cacheable for a day.
async fn favicon() -> impl axum::response::IntoResponse {
(
[
(axum::http::header::CONTENT_TYPE, "image/svg+xml"),
(axum::http::header::CACHE_CONTROL, "public, max-age=86400"),
],
FAVICON_SVG,
)
}
/// Geist (SIL OFL 1.1, `assets/fonts/OFL-Geist.txt`), weights 100–900.
const GEIST_WOFF2: &[u8] = include_bytes!("../../assets/fonts/Geist-Variable.woff2");
/// Geist Mono (SIL OFL 1.1), weights 100–900.
const GEIST_MONO_WOFF2: &[u8] = include_bytes!("../../assets/fonts/GeistMono-Variable.woff2");
/// A bundled font file, cacheable for a week.
fn woff2(bytes: &'static [u8]) -> impl axum::response::IntoResponse {
(
[
(axum::http::header::CONTENT_TYPE, "font/woff2"),
(axum::http::header::CACHE_CONTROL, "public, max-age=604800"),
],
bytes,
)
}
async fn font_geist() -> impl axum::response::IntoResponse {
woff2(GEIST_WOFF2)
}
async fn font_geist_mono() -> impl axum::response::IntoResponse {
woff2(GEIST_MONO_WOFF2)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn blank_settings_count_as_unset() {
assert_eq!(
non_blank(Some(" https://docs.breakpilot.com/pruefwerk/ ".into())).as_deref(),
Some("https://docs.breakpilot.com/pruefwerk/")
);
assert_eq!(non_blank(Some(" ".into())), None);
assert_eq!(non_blank(None), None);
}
#[test]
fn the_favicon_is_the_breakpilot_chevron() {
assert!(FAVICON_SVG.contains("M12 44 L32 20 L52 44"));
assert!(FAVICON_SVG.contains("#4F46E5"));
}
#[test]
fn the_fonts_are_self_hosted_woff2() {
assert!(GEIST_WOFF2.starts_with(b"wOF2"));
assert!(GEIST_MONO_WOFF2.starts_with(b"wOF2"));
let css = include_str!("../../assets/main.css");
assert!(css.contains("url('/fonts/geist.woff2')"));
assert!(css.contains("url('/fonts/geist-mono.woff2')"));
for host in ["googleapis", "gstatic"] {
assert!(!css.contains(host), "main.css references {host}");
}
}
}