diff --git a/.env.example b/.env.example index 1e29c59..05e4c2f 100644 --- a/.env.example +++ b/.env.example @@ -54,6 +54,14 @@ PLC_RUNTIME_OPENPLC_PASSWORD=openplc WERKBANK_RUNNER_TOKEN= # Breakpilot Platform (PRODUCT_INTEGRATION_SPEC 2.0) +# Deployment environment: dev (default) | staging | production. +# Anything but dev is HARDENED: the agent, dashboard and MCP server refuse to +# start unless auth is fully configured, instead of quietly serving +# unauthenticated as the `dev` tenant. Required in staging/production: +# KEYCLOAK_URL, KEYCLOAK_REALM, KEYCLOAK_AUDIENCE, CORS_ALLOWED_ORIGINS, +# TENANT_REGISTRY_URL, TENANT_REGISTRY_CLIENT_ID/_SECRET, +# PLATFORM_ALLOWED_CLIENTS (+ MCP_PORT for compliance-mcp). +APP_ENV=dev # Catalog key this deployment serves; used for entitlement checks, usage # events and the platform handshake. PRODUCT_KEY=pruefwerk @@ -65,12 +73,15 @@ TENANT_REGISTRY_URL= TENANT_REGISTRY_CLIENT_ID= TENANT_REGISTRY_CLIENT_SECRET= # JWT audience that user/service tokens must carry (scope `pruefwerk-audience`). -# Default `pruefwerk`; set to an empty string to disable audience validation (dev). +# Default `pruefwerk`; an empty string disables audience validation — dev only, +# rejected at startup when APP_ENV is staging/production. KEYCLOAK_AUDIENCE=pruefwerk -# Browser origins allowed by CORS (csv). Unset = permissive (dev only). +# Browser origins allowed by CORS (csv). Unset = permissive — dev only, +# rejected at startup when APP_ENV is staging/production. CORS_ALLOWED_ORIGINS=https://app-stage.breakpilot.com,https://pruefwerk-stage.breakpilot.com # Keycloak client ids (azp) allowed on /api/v1/platform/* with a service token. -# Default: tenant-registry-svc-stage,tenant-registry-svc-prod,portal-svc-stage,portal-svc-prod +# The built-in default (tenant-registry-svc-{stage,prod},portal-svc-{stage,prod}) +# applies in dev only; staging/production must name its own clients. PLATFORM_ALLOWED_CLIENTS= # Dashboard diff --git a/compliance-agent/src/api/handlers/platform.rs b/compliance-agent/src/api/handlers/platform.rs index 38cbcae..e72e7e7 100644 --- a/compliance-agent/src/api/handlers/platform.rs +++ b/compliance-agent/src/api/handlers/platform.rs @@ -38,6 +38,12 @@ pub async fn require_platform_token( next: Next, ) -> Response { let Some(jwks) = st.jwks.as_ref() else { + if st.agent.config.app_env.is_hardened() { + // These endpoints export and delete a tenant's data; they are never + // open outside dev, whatever the rest of the configuration says. + tracing::error!("platform endpoints unavailable: no Keycloak in a hardened deployment"); + return (StatusCode::SERVICE_UNAVAILABLE, "auth not configured").into_response(); + } tracing::warn!("platform endpoints called without Keycloak configured (dev)"); return next.run(request).await; }; diff --git a/compliance-agent/src/api/server.rs b/compliance-agent/src/api/server.rs index 8983092..da56fb0 100644 --- a/compliance-agent/src/api/server.rs +++ b/compliance-agent/src/api/server.rs @@ -11,6 +11,7 @@ use tower_http::set_header::SetResponseHeaderLayer; use tower_http::trace::TraceLayer; use compliance_core::auth::{require_jwt_auth, require_tenant_status, JwksState}; +use compliance_core::config::AppEnv; use compliance_core::{TenantContext, TenantStatus}; use crate::agent::ComplianceAgent; @@ -61,6 +62,16 @@ pub async fn require_entitlement( next: Next, ) -> Response { let Some(registry) = agent.registry.as_ref() else { + if agent.config.app_env.is_hardened() { + // Unreachable after `validate_deployment`, but never widen access + // just because a registry client failed to build. + tracing::error!("no tenant registry configured in a hardened deployment — denying"); + return ( + StatusCode::SERVICE_UNAVAILABLE, + Json(serde_json::json!({ "error": "entitlement_unavailable" })), + ) + .into_response(); + } return next.run(request).await; }; let Some(ctx) = request.extensions().get::().cloned() else { @@ -99,8 +110,14 @@ pub async fn require_entitlement( } } -fn cors_layer(origins: &[String]) -> CorsLayer { +fn cors_layer(origins: &[String], app_env: AppEnv) -> CorsLayer { if origins.is_empty() { + if app_env.is_hardened() { + // Unreachable after `validate_deployment`; deny rather than fall + // back to permissive if it ever is reached. + tracing::error!("CORS_ALLOWED_ORIGINS empty in a hardened deployment — denying all"); + return CorsLayer::new(); + } tracing::warn!("CORS_ALLOWED_ORIGINS not set — CORS is permissive (dev only)"); return CorsLayer::permissive(); } @@ -244,7 +261,10 @@ pub async fn start_api_server(agent: ComplianceAgent, port: u16) -> Result<(), A // mobile packages) — axum's default request-body limit is only 2 MiB. .layer(DefaultBodyLimit::max(512 * 1024 * 1024)) .layer(Extension(shared.clone())) - .layer(cors_layer(&agent.config.cors_allowed_origins)) + .layer(cors_layer( + &agent.config.cors_allowed_origins, + agent.config.app_env, + )) .layer(TraceLayer::new_for_http()) // Security headers (defense-in-depth, primary enforcement via Traefik) .layer(SetResponseHeaderLayer::overriding( @@ -280,6 +300,15 @@ pub async fn start_api_server(agent: ComplianceAgent, port: u16) -> Result<(), A )) .layer(middleware::from_fn(require_jwt_auth)) .layer(Extension(jwks_state)); + } else if agent.config.app_env.is_hardened() { + // `validate_deployment` rejects this configuration at load time; this + // is the second lock on the same door, so no code path can ever mount + // the dev-tenant injector outside dev. + return Err(AgentError::Config(format!( + "APP_ENV={} requires Keycloak (KEYCLOAK_URL + KEYCLOAK_REALM); \ + refusing to serve unauthenticated", + agent.config.app_env.as_str() + ))); } else { let tenant_id = std::env::var("DEV_TENANT_ID").unwrap_or_else(|_| DEFAULT_DEV_TENANT_ID.to_string()); diff --git a/compliance-agent/src/config.rs b/compliance-agent/src/config.rs index 5d99df4..7a7ecef 100644 --- a/compliance-agent/src/config.rs +++ b/compliance-agent/src/config.rs @@ -1,4 +1,4 @@ -use compliance_core::config::{BreakpilotConfig, Features, PlcRuntimeConfig}; +use compliance_core::config::{AppEnv, BreakpilotConfig, Features, PlcRuntimeConfig}; use compliance_core::AgentConfig; use secrecy::SecretString; @@ -17,6 +17,20 @@ fn env_secret_opt(key: &str) -> Option { } pub fn load_config() -> Result { + let app_env = + AppEnv::parse(&env_var_opt("APP_ENV").unwrap_or_default()).map_err(AgentError::Config)?; + let config = build_config(app_env)?; + if let Err(problems) = config.validate_deployment() { + return Err(AgentError::Config(format!( + "refusing to start in {}:\n - {}", + app_env.as_str(), + problems.join("\n - ") + ))); + } + Ok(config) +} + +fn build_config(app_env: AppEnv) -> Result { Ok(AgentConfig { mongodb_uri: env_var("MONGODB_URI")?, mongodb_database: env_var_opt("MONGODB_DATABASE") @@ -78,8 +92,11 @@ pub fn load_config() -> Result { tenant_registry_client_secret: env_secret_opt("TENANT_REGISTRY_CLIENT_SECRET"), cors_allowed_origins: env_csv("CORS_ALLOWED_ORIGINS"), platform_allowed_clients: { + // Built-in defaults are a dev convenience only: a hardened + // deployment names the clients it trusts, so a prod agent never + // accepts a staging service token (validate_deployment enforces it). let v = env_csv("PLATFORM_ALLOWED_CLIENTS"); - if v.is_empty() { + if v.is_empty() && !app_env.is_hardened() { [ "tenant-registry-svc-stage", "tenant-registry-svc-prod", @@ -94,6 +111,7 @@ pub fn load_config() -> Result { } }, features: Features::parse(&env_var_opt("PW_FEATURES").unwrap_or_default()), + app_env, }) } diff --git a/compliance-agent/src/pentest/cleanup.rs b/compliance-agent/src/pentest/cleanup.rs index 575eaa8..02a19fc 100644 --- a/compliance-agent/src/pentest/cleanup.rs +++ b/compliance-agent/src/pentest/cleanup.rs @@ -306,52 +306,13 @@ mod tests { use secrecy::SecretString; fn make_config_no_keycloak() -> AgentConfig { + // Dev defaults: no Keycloak, so `cleanup_test_user` takes the + // "identity provider not configured" path. AgentConfig { - mongodb_uri: String::new(), - mongodb_database: String::new(), - litellm_url: String::new(), - litellm_api_key: SecretString::from(String::new()), - litellm_model: String::new(), - litellm_embed_model: String::new(), - github_token: None, - github_webhook_secret: None, - gitlab_url: None, - gitlab_token: None, - gitlab_webhook_secret: None, - jira_url: None, - jira_email: None, - jira_api_token: None, - jira_project_key: None, - searxng_url: None, - nvd_api_key: None, - agent_port: 3001, - scan_schedule: String::new(), - cve_monitor_schedule: String::new(), - git_clone_base_path: String::new(), - artifact_store_base_path: String::new(), - ssh_key_path: String::new(), keycloak_url: None, keycloak_realm: None, - keycloak_admin_username: None, - keycloak_admin_password: None, - pentest_verification_email: None, - pentest_imap_host: None, - pentest_imap_port: None, - pentest_imap_tls: true, - pentest_imap_username: None, - pentest_imap_password: None, - admin_api_token: None, - tenant_registry_url: None, - plc_runtime: compliance_core::PlcRuntimeConfig::default(), - werkbank_runner_token: None, - breakpilot: compliance_core::config::BreakpilotConfig::default(), - product_key: "pruefwerk".into(), keycloak_audience: None, - tenant_registry_client_id: None, - tenant_registry_client_secret: None, - cors_allowed_origins: vec![], - platform_allowed_clients: vec![], - features: compliance_core::Features::default(), + ..Default::default() } } diff --git a/compliance-agent/src/scheduler.rs b/compliance-agent/src/scheduler.rs index ef51fc3..f4a82b7 100644 --- a/compliance-agent/src/scheduler.rs +++ b/compliance-agent/src/scheduler.rs @@ -93,12 +93,12 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError> /// Resolution order: /// 1. **Tenant registry** at `agent.config.tenant_registry_url` /// (`GET /v1/tenants`). Fresh on every tick — picks up newly -/// provisioned tenants without an agent restart. -/// 2. **`SCHEDULER_TENANT_IDS`** env (comma-separated) — fallback when -/// the registry is unreachable, the response is malformed, or no -/// registry URL is configured. -/// 3. **`DEFAULT_SCHEDULER_TENANT_ID`** (`"dev"`) — last-ditch fallback -/// so the scheduler keeps doing something useful in dev. +/// provisioned tenants without an agent restart. Its answer is +/// authoritative: an empty list or a failed call **skips the tick**. +/// Falling back to env here used to mean a registry outage scanned +/// `_dev` with no ladder filter. +/// 2. **`SCHEDULER_TENANT_IDS`** env, then `DEFAULT_SCHEDULER_TENANT_ID` +/// (`"dev"`) — only when no registry is configured at all, i.e. dev. /// /// We never panic out of this function — the scheduler must keep /// firing even if the registry is offline. @@ -111,13 +111,18 @@ async fn scheduler_tenants(agent: &ComplianceAgent) -> Vec { .filter(|t| scheduler_runs_for(&t.status)) .map(|t| t.id) .collect(); - if !v.is_empty() { - return v; + if v.is_empty() { + tracing::info!("tenant-registry returned no runnable tenants; skipping tick"); } - tracing::warn!("tenant-registry returned no runnable tenants; falling back to env"); + // Authoritative, including when it is empty: every tenant may + // legitimately be restricted or halted. + return v; } Err(e) => { - tracing::warn!(error = %e, "tenant-registry fetch failed; falling back to env"); + // Never fall back to the dev tenant here. A registry outage + // must skip the tick, not scan `_dev` unfiltered. + tracing::error!(error = %e, "tenant-registry fetch failed; skipping this tick"); + return Vec::new(); } } } diff --git a/compliance-agent/tests/common/mod.rs b/compliance-agent/tests/common/mod.rs index 104d05b..d5ea3d9 100644 --- a/compliance-agent/tests/common/mod.rs +++ b/compliance-agent/tests/common/mod.rs @@ -26,48 +26,17 @@ pub fn dev_config(mongodb_uri: String, db_name: String) -> AgentConfig { mongodb_database: db_name, litellm_url: std::env::var("TEST_LITELLM_URL") .unwrap_or_else(|_| "http://localhost:4000".into()), - litellm_api_key: SecretString::from(String::new()), - litellm_model: "gpt-4o".into(), - litellm_embed_model: "text-embedding-3-small".into(), agent_port: 0, // not used — we bind ourselves scan_schedule: String::new(), cve_monitor_schedule: String::new(), git_clone_base_path: "/tmp/compliance-scanner-tests/repos".into(), artifact_store_base_path: "/tmp/compliance-scanner-tests/artifacts".into(), ssh_key_path: "/tmp/compliance-scanner-tests/ssh/id_ed25519".into(), - github_token: None, - github_webhook_secret: None, - gitlab_url: None, - gitlab_token: None, - gitlab_webhook_secret: None, - jira_url: None, - jira_email: None, - jira_api_token: None, - jira_project_key: None, - searxng_url: None, - nvd_api_key: None, - keycloak_url: None, - keycloak_realm: None, - keycloak_admin_username: None, - keycloak_admin_password: None, - pentest_verification_email: None, - pentest_imap_host: None, - pentest_imap_port: None, pentest_imap_tls: false, - pentest_imap_username: None, - pentest_imap_password: None, - admin_api_token: None, - tenant_registry_url: None, - plc_runtime: compliance_core::PlcRuntimeConfig::default(), werkbank_runner_token: Some(SecretString::from(TEST_RUNNER_TOKEN.to_string())), - breakpilot: compliance_core::config::BreakpilotConfig::default(), - product_key: "pruefwerk".into(), + // Unauthenticated dev: no Keycloak, no audience, no registry. keycloak_audience: None, - tenant_registry_client_id: None, - tenant_registry_client_secret: None, - cors_allowed_origins: vec![], - platform_allowed_clients: vec![], - features: compliance_core::Features::default(), + ..Default::default() } } diff --git a/compliance-core/src/auth.rs b/compliance-core/src/auth.rs index 81376cf..d5f0e5d 100644 --- a/compliance-core/src/auth.rs +++ b/compliance-core/src/auth.rs @@ -88,6 +88,11 @@ struct Claims { azp: Option, } +/// Upper bound on a JWKS fetch. The cache write lock is held for its +/// duration, so an unbounded call would queue every authenticated request +/// behind an unreachable Keycloak. +const JWKS_FETCH_TIMEOUT_SECS: u64 = 5; + const PUBLIC_ENDPOINTS: &[&str] = &["/api/v1/health"]; /// Path prefixes that bypass JWT validation. The admin sub-router @@ -349,7 +354,14 @@ async fn fetch_or_get_jwks(state: &JwksState, force: bool) -> Result Result { + match raw.trim().to_ascii_lowercase().as_str() { + "" | "dev" | "development" | "local" | "test" => Ok(Self::Dev), + "stage" | "staging" => Ok(Self::Staging), + "prod" | "production" => Ok(Self::Production), + other => Err(format!( + "unknown APP_ENV '{other}' (expected dev, staging or production)" + )), + } + } + + /// Whether the fail-closed rules apply. + pub fn is_hardened(self) -> bool { + !matches!(self, Self::Dev) + } + + pub fn as_str(self) -> &'static str { + match self { + Self::Dev => "dev", + Self::Staging => "staging", + Self::Production => "production", + } + } +} + +impl AgentConfig { + /// Check that a hardened deployment has everything it needs to enforce + /// authentication, tenancy and entitlements. Returns every problem at + /// once so an operator fixes one deploy instead of five. + /// + /// In [`AppEnv::Dev`] this is always `Ok`. + pub fn validate_deployment(&self) -> Result<(), Vec> { + if !self.app_env.is_hardened() { + return Ok(()); + } + let mut problems = Vec::new(); + let mut require = |present: bool, var: &str, why: &str| { + if !present { + problems.push(format!( + "{var} is required in {} — {why}", + self.app_env.as_str() + )); + } + }; + + require( + self.keycloak_url.is_some(), + "KEYCLOAK_URL", + "without it every request runs unauthenticated as the dev tenant", + ); + require( + self.keycloak_realm.is_some(), + "KEYCLOAK_REALM", + "without it every request runs unauthenticated as the dev tenant", + ); + require( + self.keycloak_audience.is_some(), + "KEYCLOAK_AUDIENCE", + "an empty audience disables `aud` validation, so any realm token is accepted", + ); + require( + !self.cors_allowed_origins.is_empty(), + "CORS_ALLOWED_ORIGINS", + "an empty allowlist falls back to permissive CORS", + ); + require( + self.tenant_registry_url.is_some(), + "TENANT_REGISTRY_URL", + "without it entitlements are never checked and the scheduler has no tenant list", + ); + require( + self.tenant_registry_client_id.is_some(), + "TENANT_REGISTRY_CLIENT_ID", + "registry calls would go out unauthenticated", + ); + require( + self.tenant_registry_client_secret.is_some(), + "TENANT_REGISTRY_CLIENT_SECRET", + "registry calls would go out unauthenticated", + ); + require( + !self.platform_allowed_clients.is_empty(), + "PLATFORM_ALLOWED_CLIENTS", + "the platform lifecycle endpoints would accept any service client", + ); + + if problems.is_empty() { + Ok(()) + } else { + Err(problems) + } + } +} + +/// Dev-shaped defaults, mirroring what the agent's loader falls back to when +/// an optional variable is unset. Handy for tests and for the few places that +/// build a config without the environment: `AgentConfig { mongodb_uri: uri, +/// ..Default::default() }`. +impl Default for AgentConfig { + fn default() -> Self { + Self { + mongodb_uri: "mongodb://localhost:27017".to_string(), + mongodb_database: "compliance_scanner".to_string(), + litellm_url: "http://localhost:4000".to_string(), + litellm_api_key: SecretString::from(String::new()), + litellm_model: "gpt-4o".to_string(), + litellm_embed_model: "text-embedding-3-small".to_string(), + github_token: None, + github_webhook_secret: None, + gitlab_url: None, + gitlab_token: None, + gitlab_webhook_secret: None, + jira_url: None, + jira_email: None, + jira_api_token: None, + jira_project_key: None, + searxng_url: None, + nvd_api_key: None, + agent_port: 3001, + scan_schedule: "0 0 */6 * * *".to_string(), + cve_monitor_schedule: "0 0 * * * *".to_string(), + git_clone_base_path: "/tmp/compliance-scanner/repos".to_string(), + artifact_store_base_path: "/data/compliance-scanner/artifacts".to_string(), + ssh_key_path: "/data/compliance-scanner/ssh/id_ed25519".to_string(), + keycloak_url: None, + keycloak_realm: None, + keycloak_admin_username: None, + keycloak_admin_password: None, + pentest_verification_email: None, + pentest_imap_host: None, + pentest_imap_port: None, + pentest_imap_tls: true, + pentest_imap_username: None, + pentest_imap_password: None, + admin_api_token: None, + tenant_registry_url: None, + plc_runtime: PlcRuntimeConfig::default(), + werkbank_runner_token: None, + breakpilot: BreakpilotConfig::default(), + product_key: "pruefwerk".to_string(), + keycloak_audience: Some("pruefwerk".to_string()), + tenant_registry_client_id: None, + tenant_registry_client_secret: None, + cors_allowed_origins: Vec::new(), + platform_allowed_clients: Vec::new(), + features: Features::default(), + app_env: AppEnv::Dev, + } + } +} + +#[cfg(test)] +mod app_env_tests { + use super::{AgentConfig, AppEnv}; + + #[test] + fn parses_known_environments_and_rejects_typos() { + assert_eq!(AppEnv::parse("").unwrap(), AppEnv::Dev); + assert_eq!(AppEnv::parse(" Dev ").unwrap(), AppEnv::Dev); + assert_eq!(AppEnv::parse("staging").unwrap(), AppEnv::Staging); + assert_eq!(AppEnv::parse("PROD").unwrap(), AppEnv::Production); + assert!(AppEnv::parse("produciton").is_err()); + assert!(!AppEnv::Dev.is_hardened()); + assert!(AppEnv::Staging.is_hardened()); + assert!(AppEnv::Production.is_hardened()); + } + + #[test] + fn dev_needs_nothing() { + assert!(AgentConfig::default().validate_deployment().is_ok()); + } + + #[test] + fn hardened_reports_every_missing_setting_at_once() { + let cfg = AgentConfig { + app_env: AppEnv::Production, + keycloak_audience: None, + ..Default::default() + }; + let problems = cfg.validate_deployment().unwrap_err(); + for var in [ + "KEYCLOAK_URL", + "KEYCLOAK_REALM", + "KEYCLOAK_AUDIENCE", + "CORS_ALLOWED_ORIGINS", + "TENANT_REGISTRY_URL", + "TENANT_REGISTRY_CLIENT_ID", + "TENANT_REGISTRY_CLIENT_SECRET", + "PLATFORM_ALLOWED_CLIENTS", + ] { + assert!( + problems.iter().any(|p| p.contains(var)), + "{var} missing from {problems:?}" + ); + } + } + + #[test] + fn fully_configured_staging_passes() { + let cfg = AgentConfig { + app_env: AppEnv::Staging, + keycloak_url: Some("https://auth.breakpilot.com".to_string()), + keycloak_realm: Some("breakpilot-stage".to_string()), + keycloak_audience: Some("pruefwerk".to_string()), + cors_allowed_origins: vec!["https://pruefwerk-stage.breakpilot.com".to_string()], + tenant_registry_url: Some("https://registry-stage.breakpilot.com".to_string()), + tenant_registry_client_id: Some("pruefwerk-svc-stage".to_string()), + tenant_registry_client_secret: Some(secrecy::SecretString::from("s3cret".to_string())), + platform_allowed_clients: vec!["tenant-registry-svc-stage".to_string()], + ..Default::default() + }; + assert!(cfg.validate_deployment().is_ok()); + } } /// Deployment feature flags (`PW_FEATURES`). diff --git a/compliance-dashboard/src/infrastructure/keycloak_config.rs b/compliance-dashboard/src/infrastructure/keycloak_config.rs index 1a89790..476b264 100644 --- a/compliance-dashboard/src/infrastructure/keycloak_config.rs +++ b/compliance-dashboard/src/infrastructure/keycloak_config.rs @@ -24,6 +24,26 @@ impl KeycloakConfig { }) } + /// Which of the five variables are missing. A partially configured + /// dashboard silently serves every page without a login, so a hardened + /// deployment turns this list into a startup failure. + pub fn missing_env() -> Vec<&'static str> { + [ + "KEYCLOAK_URL", + "KEYCLOAK_REALM", + "KEYCLOAK_CLIENT_ID", + "REDIRECT_URI", + "APP_URL", + ] + .into_iter() + .filter(|k| { + std::env::var(k) + .map(|v| v.trim().is_empty()) + .unwrap_or(true) + }) + .collect() + } + pub fn auth_endpoint(&self) -> String { format!( "{}/realms/{}/protocol/openid-connect/auth", diff --git a/compliance-dashboard/src/infrastructure/server.rs b/compliance-dashboard/src/infrastructure/server.rs index fb5c5a9..7621d90 100644 --- a/compliance-dashboard/src/infrastructure/server.rs +++ b/compliance-dashboard/src/infrastructure/server.rs @@ -5,6 +5,7 @@ use dioxus::prelude::*; use time::Duration; use tower_sessions::{cookie::Key, MemoryStore, SessionManagerLayer}; +use compliance_core::config::AppEnv; use compliance_core::models::{McpServerConfig, McpServerStatus, McpTransport}; use mongodb::bson::doc; @@ -29,8 +30,22 @@ pub fn server_start(app: fn() -> Element) -> Result<(), DashboardError> { // 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!("Keycloak configured for realm '{}'", kc.realm); + 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"); } diff --git a/compliance-mcp/src/main.rs b/compliance-mcp/src/main.rs index a98e680..cda0d96 100644 --- a/compliance-mcp/src/main.rs +++ b/compliance-mcp/src/main.rs @@ -5,6 +5,7 @@ mod tools; use std::sync::Arc; +use compliance_core::config::AppEnv; use database::DatabasePool; use rmcp::transport::{ streamable_http_server::session::local::LocalSessionManager, StreamableHttpServerConfig, @@ -23,6 +24,8 @@ async fn main() -> Result<(), Box> { ) .init(); + let app_env = AppEnv::parse(&std::env::var("APP_ENV").unwrap_or_default())?; + let mongo_uri = std::env::var("MONGODB_URI").unwrap_or_else(|_| "mongodb://localhost:27017".to_string()); // MONGODB_DATABASE is reused as the per-tenant DB-name prefix — @@ -70,6 +73,14 @@ async fn main() -> Result<(), Box> { let listener = tokio::net::TcpListener::bind(("0.0.0.0", port)).await?; tracing::info!("MCP HTTP server listening on 0.0.0.0:{port}"); axum::serve(listener, router).await?; + } else if app_env.is_hardened() { + // stdio synthesises a tenant with no bearer check at all, so a + // deployed MCP server must have a port. Fail instead of serving. + return Err(format!( + "APP_ENV={} requires MCP_PORT — the stdio transport has no tenant auth", + app_env.as_str() + ) + .into()); } else { // stdio transport — used when run as a local MCP server next // to the LLM client. There's no HTTP layer to do bearer auth, diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md index 5e7dedc..7f59e96 100644 --- a/docs/guide/getting-started.md +++ b/docs/guide/getting-started.md @@ -57,6 +57,26 @@ Once the scan completes, navigate to **Findings** to see everything that was dis - [Explore your SBOM](/guide/sbom) -- dependencies, licenses, and exports - [Connect your IDE](/features/mcp-server) -- query findings from an LLM client over MCP +## Deployment modes (`APP_ENV`) + +`APP_ENV` decides how strict the deployment is about authentication. + +| `APP_ENV` | Behaviour | +|---|---| +| `dev` (default) | Auth may be absent. Without Keycloak the API serves unauthenticated against a synthetic `dev` tenant, CORS is permissive, entitlements are not checked. For a laptop and CI only. | +| `staging`, `production` | *Hardened.* The agent, dashboard and MCP server refuse to start unless authentication is fully configured, and the dev-tenant, permissive-CORS and skip-entitlement paths are unreachable. | + +A hardened deployment requires `KEYCLOAK_URL`, `KEYCLOAK_REALM`, +`KEYCLOAK_AUDIENCE`, `CORS_ALLOWED_ORIGINS`, `TENANT_REGISTRY_URL`, +`TENANT_REGISTRY_CLIENT_ID`, `TENANT_REGISTRY_CLIENT_SECRET` and +`PLATFORM_ALLOWED_CLIENTS`; the MCP server additionally requires `MCP_PORT`, +since its stdio transport has no tenant authentication. Startup lists every +missing variable at once, so one corrected deploy is enough. + +The scheduler follows the same rule: where a tenant registry is configured, its +tenant list is authoritative, and a registry outage skips the tick instead of +falling back to the `dev` tenant. + ## Static-analysis-only environments Some deployments run with `PW_FEATURES=source_only` — the shared staging