From e448a33778c6aef144c6526ab38395d5eaf13ae3 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Fri, 11 Sep 2026 17:50:10 +0200 Subject: [PATCH] feat(agent): registry entitlements, platform endpoints, JWT aud/iss MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Prüfwerk M-MIG-6 slice (PRODUCT_INTEGRATION_SPEC 2.0): - core: tenant status ladder demo|trial|active|warning|restricted|frozen| halted|archived; blocks_writes()/is_halted(); status gate returns 402 for halted on every route, 410 for archived - core auth: JwksState::new(jwks_url, issuer, audience) — issuer pinned, audience validated (KEYCLOAK_AUDIENCE, default pruefwerk); validate_service_token() for client_credentials tokens (azp) - agent: RegistryClient (client_credentials token cache, entitlement check cached 60 s fail-closed, tenant list w/ cursor, api-key verify, usage push); require_entitlement middleware between JWT and status gate; registry answer overrides the tenant_status claim - agent: /api/v1/platform/{version,usage,tenants/{id}/provision|suspend| reactivate|terminate|export,tenants/{id}/data DELETE,tenants/demo/reset} behind service-token gate + PLATFORM_ALLOWED_CLIENTS allowlist - agent: CORS allowlist from CORS_ALLOWED_ORIGINS (permissive only when unset, logged) - agent: werkbank runner auth accepts registry API keys (bp_…, scope werkbank:runner) next to the static token; router mounted when either is available - agent: scheduler lists tenants via the registry client and skips restricted/frozen/halted/archived - smoke: use JwksState::new; .env.example documents the new variables Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB --- .env.example | 25 +- compliance-agent/src/agent.rs | 6 + compliance-agent/src/api/handlers/mod.rs | 1 + compliance-agent/src/api/handlers/platform.rs | 387 ++++++++++++++++++ .../src/api/handlers/werkbank_jobs.rs | 32 +- compliance-agent/src/api/server.rs | 175 ++++++-- compliance-agent/src/config.rs | 38 ++ compliance-agent/src/lib.rs | 1 + compliance-agent/src/pentest/cleanup.rs | 6 + compliance-agent/src/registry.rs | 338 +++++++++++++++ compliance-agent/src/scheduler.rs | 171 ++------ compliance-agent/tests/common/mod.rs | 6 + .../tests/tenant_status_middleware.rs | 47 +++ compliance-core/src/auth.rs | 104 ++++- compliance-core/src/config.rs | 15 + compliance-core/src/tenant.rs | 52 ++- compliance-smoke/src/main.rs | 14 +- 17 files changed, 1222 insertions(+), 196 deletions(-) create mode 100644 compliance-agent/src/api/handlers/platform.rs create mode 100644 compliance-agent/src/registry.rs diff --git a/.env.example b/.env.example index a8333a9..0d54e8a 100644 --- a/.env.example +++ b/.env.example @@ -48,10 +48,31 @@ PLC_RUNTIME_OPENPLC_USER=openplc PLC_RUNTIME_OPENPLC_PASSWORD=openplc # Werkbank runner API (/api/v1/werkbank/jobs/*, /api/v1/werkbank/artifacts/*). -# When set, mounts the runner-facing queue + artifact endpoints behind this -# bearer token; runners present the same token. Unset = endpoints not mounted. +# Mounted when this static token is set OR a tenant registry is configured +# (runners then present portal-issued `bp_…` API keys with scope +# werkbank:runner, verified via the registry). Unset + no registry = not mounted. WERKBANK_RUNNER_TOKEN= +# Breakpilot Platform (PRODUCT_INTEGRATION_SPEC 2.0) +# Catalog key this deployment serves; used for entitlement checks, usage +# events and the platform handshake. +PRODUCT_KEY=pruefwerk +# Tenant registry: entitlement authority (POST /v1/internal/entitlements/check, +# cached ≤60 s, fail-closed), tenant list for the scheduler, API-key verify. +# Unset = claims-only mode (dev). +TENANT_REGISTRY_URL= +# client_credentials for the registry (Keycloak client `pruefwerk-svc-`). +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). +KEYCLOAK_AUDIENCE=pruefwerk +# Browser origins allowed by CORS (csv). Unset = permissive (dev only). +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 +PLATFORM_ALLOWED_CLIENTS= + # Dashboard DASHBOARD_PORT=8080 AGENT_API_URL=http://localhost:3001 diff --git a/compliance-agent/src/agent.rs b/compliance-agent/src/agent.rs index fac9035..a953a17 100644 --- a/compliance-agent/src/agent.rs +++ b/compliance-agent/src/agent.rs @@ -9,6 +9,7 @@ use compliance_core::AgentConfig; use crate::database::DatabasePool; use crate::llm::LlmClient; use crate::pipeline::orchestrator::PipelineOrchestrator; +use crate::registry::RegistryClient; /// Default maximum concurrent pentest sessions. const DEFAULT_MAX_CONCURRENT_SESSIONS: usize = 5; @@ -28,6 +29,9 @@ pub struct ComplianceAgent { pub session_pause: Arc>>, /// Semaphore limiting concurrent pentest sessions. pub session_semaphore: Arc, + /// Platform tenant-registry client (entitlements, tenant list, API keys, + /// usage events). `None` when `TENANT_REGISTRY_URL` is unset (dev). + pub registry: Option>, } impl ComplianceAgent { @@ -43,6 +47,7 @@ impl ComplianceAgent { .connect_timeout(std::time::Duration::from_secs(10)) .build() .unwrap_or_default(); + let registry = RegistryClient::from_config(&config, http.clone()); Self { config, db_pool, @@ -51,6 +56,7 @@ impl ComplianceAgent { session_streams: Arc::new(DashMap::new()), session_pause: Arc::new(DashMap::new()), session_semaphore: Arc::new(Semaphore::new(DEFAULT_MAX_CONCURRENT_SESSIONS)), + registry, } } diff --git a/compliance-agent/src/api/handlers/mod.rs b/compliance-agent/src/api/handlers/mod.rs index 5406c78..a002624 100644 --- a/compliance-agent/src/api/handlers/mod.rs +++ b/compliance-agent/src/api/handlers/mod.rs @@ -12,6 +12,7 @@ pub mod notifications; pub mod onboarding; pub mod oscal; pub mod pentest_handlers; +pub mod platform; pub use pentest_handlers as pentest; pub mod sbom; pub mod scans; diff --git a/compliance-agent/src/api/handlers/platform.rs b/compliance-agent/src/api/handlers/platform.rs new file mode 100644 index 0000000..20add8e --- /dev/null +++ b/compliance-agent/src/api/handlers/platform.rs @@ -0,0 +1,387 @@ +//! Platform lifecycle + usage endpoints (`/api/v1/platform/*`, +//! PRODUCT_INTEGRATION_SPEC 2.0 §4.1). Called by the tenant-registry and the +//! portal with a platform SERVICE TOKEN (client_credentials JWT from the same +//! realm, `aud` = this product, `azp` in `PLATFORM_ALLOWED_CLIENTS`). +//! +//! Tenant ids are the registry UUIDs; the Mongo database per tenant is +//! `_`. + +use std::sync::Arc; + +use axum::extract::{Path, Query, Request, State}; +use axum::http::{header, StatusCode}; +use axum::middleware::Next; +use axum::response::{IntoResponse, Response}; +use axum::Json; +use futures_util::TryStreamExt; +use mongodb::bson::{doc, Document}; +use serde::{Deserialize, Serialize}; + +use compliance_core::auth::{validate_service_token, JwksState}; + +use crate::agent::ComplianceAgent; + +#[derive(Clone)] +pub struct PlatformState { + pub agent: Arc, + pub jwks: Option, +} + +/// Collection that records lifecycle markers per tenant database. +const STATE_COLLECTION: &str = "platform_state"; + +/// Service-token gate. Without Keycloak (dev) the endpoints are open and a +/// warning is logged once per request. +pub async fn require_platform_token( + State(st): State, + request: Request, + next: Next, +) -> Response { + let Some(jwks) = st.jwks.as_ref() else { + tracing::warn!("platform endpoints called without Keycloak configured (dev)"); + return next.run(request).await; + }; + let token = request + .headers() + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|s| s.strip_prefix("Bearer ")) + .map(str::trim) + .filter(|s| !s.is_empty()); + let Some(token) = token else { + return (StatusCode::UNAUTHORIZED, "Missing bearer token").into_response(); + }; + match validate_service_token(token, jwks).await { + Ok(claims) + if st + .agent + .config + .platform_allowed_clients + .iter() + .any(|c| c == &claims.azp) => + { + next.run(request).await + } + Ok(claims) => { + tracing::warn!(azp = %claims.azp, "client not allowed on platform endpoints"); + (StatusCode::FORBIDDEN, "client not allowed").into_response() + } + Err(e) => { + tracing::warn!("platform token rejected: {e}"); + (StatusCode::UNAUTHORIZED, "Invalid token").into_response() + } + } +} + +#[derive(Deserialize, Default)] +pub struct LifecycleBody { + #[serde(default)] + pub plan: Option, + #[serde(default)] + pub config: Option, + #[serde(default)] + pub reason: Option, + #[serde(default)] + pub scheduled_erasure_at: Option, + #[serde(default)] + pub confirm: Option, + #[serde(default)] + pub tenant_id: Option, +} + +async fn set_marker( + agent: &ComplianceAgent, + tenant_id: &str, + state: &str, + extra: Document, +) -> Result<(), StatusCode> { + let db = agent + .db_pool + .for_tenant_id(tenant_id) + .await + .map_err(internal)?; + let mut set = doc! { "state": state, "updated_at": mongodb::bson::DateTime::now() }; + set.extend(extra); + db.raw_collection(STATE_COLLECTION) + .update_one( + doc! { "_id": "lifecycle" }, + doc! { "$set": set, "$setOnInsert": { "created_at": mongodb::bson::DateTime::now() } }, + ) + .upsert(true) + .await + .map_err(internal)?; + if let Some(r) = &agent.registry { + r.invalidate(tenant_id); + } + Ok(()) +} + +fn internal(e: E) -> StatusCode { + tracing::error!("platform endpoint failed: {e}"); + StatusCode::INTERNAL_SERVER_ERROR +} + +/// `POST /api/v1/platform/tenants/{id}/provision` — idempotent: creates the +/// tenant database (indexes) and records the plan/limits. +pub async fn provision( + State(st): State, + Path(tenant_id): Path, + body: Option>, +) -> Result, StatusCode> { + let b = body.map(|Json(b)| b).unwrap_or_default(); + let mut extra = doc! {}; + if let Some(p) = &b.plan { + extra.insert("plan", p.clone()); + } + if let Some(c) = &b.config { + if let Ok(bs) = mongodb::bson::to_bson(c) { + extra.insert("limits", bs); + } + } + set_marker(&st.agent, &tenant_id, "provisioned", extra).await?; + Ok(Json( + serde_json::json!({ "status": "provisioned", "tenant_id": tenant_id }), + )) +} + +pub async fn suspend( + State(st): State, + Path(tenant_id): Path, + body: Option>, +) -> Result, StatusCode> { + let reason = body.and_then(|Json(b)| b.reason).unwrap_or_default(); + set_marker( + &st.agent, + &tenant_id, + "suspended", + doc! { "reason": reason }, + ) + .await?; + Ok(Json( + serde_json::json!({ "status": "suspended", "tenant_id": tenant_id }), + )) +} + +pub async fn reactivate( + State(st): State, + Path(tenant_id): Path, +) -> Result, StatusCode> { + set_marker(&st.agent, &tenant_id, "active", doc! {}).await?; + Ok(Json( + serde_json::json!({ "status": "active", "tenant_id": tenant_id }), + )) +} + +pub async fn terminate( + State(st): State, + Path(tenant_id): Path, + body: Option>, +) -> Result, StatusCode> { + let b = body.map(|Json(b)| b).unwrap_or_default(); + set_marker( + &st.agent, + &tenant_id, + "terminated", + doc! { "reason": b.reason.unwrap_or_default(), "scheduled_erasure_at": b.scheduled_erasure_at.unwrap_or_default() }, + ) + .await?; + Ok(Json( + serde_json::json!({ "status": "terminated", "tenant_id": tenant_id }), + )) +} + +/// `GET /api/v1/platform/tenants/{id}/export` — every collection of the +/// tenant database as one JSON document (`{collection: [docs…]}`). Good for +/// the export window sizes we expect on staging; large tenants get a +/// streamed archive later. +pub async fn export( + State(st): State, + Path(tenant_id): Path, +) -> Result { + let db = st + .agent + .db_pool + .for_tenant_id(&tenant_id) + .await + .map_err(internal)?; + let names = db.inner().list_collection_names().await.map_err(internal)?; + let mut out = serde_json::Map::new(); + for name in names { + let docs: Vec = db + .raw_collection(&name) + .find(doc! {}) + .await + .map_err(internal)? + .try_collect() + .await + .map_err(internal)?; + out.insert(name, serde_json::to_value(docs).map_err(internal)?); + } + let body = serde_json::json!({ + "tenant_id": tenant_id, + "product": st.agent.config.product_key, + "exported_at": chrono::Utc::now().to_rfc3339(), + "collections": out, + }); + Ok(( + [( + header::CONTENT_DISPOSITION, + format!( + "attachment; filename=\"{}-{}-export.json\"", + st.agent.config.product_key, tenant_id + ), + )], + Json(body), + ) + .into_response()) +} + +/// `DELETE /api/v1/platform/tenants/{id}/data` — GDPR erasure: drops the +/// tenant database. Requires `{"confirm": ""}`. +pub async fn delete_data( + State(st): State, + Path(tenant_id): Path, + body: Option>, +) -> Result, StatusCode> { + let confirm = body.and_then(|Json(b)| b.confirm).unwrap_or_default(); + if confirm.is_empty() { + return Err(StatusCode::BAD_REQUEST); + } + st.agent + .db_pool + .drop_tenant(&tenant_id) + .await + .map_err(internal)?; + if let Some(r) = &st.agent.registry { + r.invalidate(&tenant_id); + } + Ok(Json( + serde_json::json!({ "status": "deleted", "tenant_id": tenant_id }), + )) +} + +/// `POST /api/v1/platform/tenants/demo/reset` — drops and re-creates the +/// demo tenant database. Fixtures (platform/seed-data) are loaded later. +pub async fn demo_reset( + State(st): State, + body: Option>, +) -> Result, StatusCode> { + let tenant_id = body + .and_then(|Json(b)| b.tenant_id) + .unwrap_or_else(|| "demo".to_string()); + st.agent + .db_pool + .drop_tenant(&tenant_id) + .await + .map_err(internal)?; + st.agent + .db_pool + .for_tenant_id(&tenant_id) + .await + .map_err(internal)?; + Ok(Json( + serde_json::json!({ "status": "reset", "tenant_id": tenant_id }), + )) +} + +#[derive(Deserialize)] +pub struct UsageQuery { + pub tenant_id: String, + #[serde(default)] + pub from: Option, + #[serde(default)] + pub to: Option, +} + +#[derive(Serialize)] +pub struct UsageResponse { + pub tenant_id: String, + pub product: String, + pub period: serde_json::Value, + pub metrics: serde_json::Value, +} + +/// `GET /api/v1/platform/usage?tenant_id=&from=&to=` — dashboard metrics +/// (billing uses the pushed usage events, §9.2). +pub async fn usage( + State(st): State, + Query(q): Query, +) -> Result, StatusCode> { + let db = st + .agent + .db_pool + .for_tenant_id(&q.tenant_id) + .await + .map_err(internal)?; + let parse = |s: &Option| -> Result, StatusCode> { + match s { + None => Ok(None), + Some(v) => chrono::DateTime::parse_from_rfc3339(v) + .map(|d| { + Some(mongodb::bson::DateTime::from_chrono( + d.with_timezone(&chrono::Utc), + )) + }) + .map_err(|_| StatusCode::BAD_REQUEST), + } + }; + let (from, to) = (parse(&q.from)?, parse(&q.to)?); + let mut range = doc! {}; + if let Some(f) = from { + range.insert("$gte", f); + } + if let Some(t) = to { + range.insert("$lte", t); + } + let completed = if range.is_empty() { + doc! { "status": "completed" } + } else { + doc! { "status": "completed", "completed_at": range.clone() } + }; + let scans = db + .scan_runs() + .count_documents(completed.clone()) + .await + .map_err(internal)?; + let dast = db + .dast_scan_runs() + .count_documents(completed) + .await + .map_err(internal)?; + let targets = db + .onboarded_targets() + .count_documents(doc! {}) + .await + .map_err(internal)?; + let findings = db + .findings() + .count_documents(doc! {}) + .await + .map_err(internal)?; + let pentests = db + .pentest_sessions() + .count_documents(doc! {}) + .await + .map_err(internal)?; + Ok(Json(UsageResponse { + tenant_id: q.tenant_id, + product: st.agent.config.product_key.clone(), + period: serde_json::json!({ "from": q.from, "to": q.to }), + metrics: serde_json::json!({ + "scans_completed": scans, + "dast_scans_completed": dast, + "targets": targets, + "findings": findings, + "pentest_sessions": pentests, + }), + })) +} + +/// `GET /api/v1/platform/version` — contract handshake (§4.1 /version). +pub async fn version(State(st): State) -> Json { + Json(serde_json::json!({ + "product": st.agent.config.product_key, + "version": env!("CARGO_PKG_VERSION"), + "contract": "2.0", + })) +} diff --git a/compliance-agent/src/api/handlers/werkbank_jobs.rs b/compliance-agent/src/api/handlers/werkbank_jobs.rs index 212d668..0d66f6e 100644 --- a/compliance-agent/src/api/handlers/werkbank_jobs.rs +++ b/compliance-agent/src/api/handlers/werkbank_jobs.rs @@ -35,9 +35,6 @@ pub async fn require_runner_token( request: Request, next: Next, ) -> Response { - let Some(expected) = agent.config.werkbank_runner_token.as_ref() else { - return (StatusCode::NOT_FOUND, "werkbank runner API disabled").into_response(); - }; let presented = request .headers() .get(header::AUTHORIZATION) @@ -48,6 +45,35 @@ pub async fn require_runner_token( let Some(presented) = presented else { return (StatusCode::UNAUTHORIZED, "Missing bearer token").into_response(); }; + // Portal-issued API key (tenant-registry, scope werkbank:runner) — the + // platform way (contract 2.0 §5.B / add-on runners). + if presented.starts_with("bp_") { + let Some(registry) = agent.registry.as_ref() else { + return (StatusCode::UNAUTHORIZED, "API keys need a tenant registry").into_response(); + }; + return match registry.verify_api_key(presented).await { + Ok(v) + if v.valid + && (v.scopes.iter().any(|s| s == "werkbank:runner") + || v.product == registry.product()) => + { + next.run(request).await + } + Ok(_) => (StatusCode::UNAUTHORIZED, "Invalid or unscoped API key").into_response(), + Err(e) => { + tracing::error!("runner api-key verify unavailable: {e}"); + ( + StatusCode::SERVICE_UNAVAILABLE, + "API key verification unavailable", + ) + .into_response() + } + }; + } + // Static runner token (pre-platform deployments). + let Some(expected) = agent.config.werkbank_runner_token.as_ref() else { + return (StatusCode::UNAUTHORIZED, "Invalid runner token").into_response(); + }; if !constant_time_eq(presented, expected.expose_secret()) { return (StatusCode::UNAUTHORIZED, "Invalid runner token").into_response(); } diff --git a/compliance-agent/src/api/server.rs b/compliance-agent/src/api/server.rs index 50d8c3d..51d779a 100644 --- a/compliance-agent/src/api/server.rs +++ b/compliance-agent/src/api/server.rs @@ -1,13 +1,12 @@ use std::sync::Arc; -use axum::extract::{DefaultBodyLimit, Request}; -use axum::http::HeaderValue; +use axum::extract::{DefaultBodyLimit, Request, State}; +use axum::http::{HeaderValue, StatusCode}; use axum::middleware::Next; -use axum::response::Response; +use axum::response::{IntoResponse, Response}; use axum::routing::{delete, get, post}; -use axum::{middleware, Extension, Router}; -use tokio::sync::RwLock; -use tower_http::cors::CorsLayer; +use axum::{middleware, Extension, Json, Router}; +use tower_http::cors::{Any, CorsLayer}; use tower_http::set_header::SetResponseHeaderLayer; use tower_http::trace::TraceLayer; @@ -16,6 +15,7 @@ use compliance_core::{TenantContext, TenantStatus}; use crate::agent::ComplianceAgent; use crate::api::handlers; +use crate::api::handlers::platform::{self, PlatformState}; use crate::api::routes; use crate::error::AgentError; @@ -51,7 +51,131 @@ pub async fn inject_dev_tenant(mut request: Request, next: Next) -> Response { next.run(request).await } +/// Registry-backed entitlement gate (contract 2.0 §4.4). Runs after the JWT +/// middleware; with no registry configured (dev) it is a no-op. The +/// registry's answer is authoritative for the ladder status too, so a +/// stale `tenant_status` claim never widens access. +pub async fn require_entitlement( + State(agent): State>, + mut request: Request, + next: Next, +) -> Response { + let Some(registry) = agent.registry.as_ref() else { + return next.run(request).await; + }; + let Some(ctx) = request.extensions().get::().cloned() else { + return next.run(request).await; + }; + match registry.check_entitlement(&ctx.tenant_id, None).await { + Ok(check) if check.allowed => { + let mut ctx = ctx; + if let Some(st) = check.status.as_deref().and_then(TenantStatus::parse) { + ctx.status = st; + } + if check.read_only && !ctx.status.blocks_writes() && !ctx.status.is_halted() { + ctx.status = TenantStatus::Restricted; + } + request.extensions_mut().insert(ctx); + next.run(request).await + } + Ok(check) => ( + StatusCode::FORBIDDEN, + Json(serde_json::json!({ + "error": "not_entitled", + "product": registry.product(), + "reason": check.reason, + "status": check.status, + })), + ) + .into_response(), + Err(e) => { + tracing::error!(tenant_id = %ctx.tenant_id, "entitlement check unavailable: {e}"); + ( + StatusCode::SERVICE_UNAVAILABLE, + Json(serde_json::json!({ "error": "entitlement_unavailable" })), + ) + .into_response() + } + } +} + +fn cors_layer(origins: &[String]) -> CorsLayer { + if origins.is_empty() { + tracing::warn!("CORS_ALLOWED_ORIGINS not set — CORS is permissive (dev only)"); + return CorsLayer::permissive(); + } + let parsed: Vec = origins + .iter() + .filter_map(|o| HeaderValue::from_str(o).ok()) + .collect(); + CorsLayer::new() + .allow_origin(parsed) + .allow_methods(Any) + .allow_headers(Any) +} + pub async fn start_api_server(agent: ComplianceAgent, port: u16) -> Result<(), AgentError> { + let shared = Arc::new(agent.clone()); + let jwks_state = match (&agent.config.keycloak_url, &agent.config.keycloak_realm) { + (Some(kc_url), Some(kc_realm)) => { + let issuer = format!("{}/realms/{kc_realm}", kc_url.trim_end_matches('/')); + if agent.config.keycloak_audience.is_none() { + tracing::warn!( + "KEYCLOAK_AUDIENCE empty — JWT audience is not validated (dev only)" + ); + } + Some(JwksState::new( + format!("{issuer}/protocol/openid-connect/certs"), + Some(issuer), + agent.config.keycloak_audience.clone(), + )) + } + _ => None, + }; + + // Platform lifecycle + usage endpoints (contract 2.0 §4.1), service-token + // gated. Always mounted; without Keycloak they are open (dev, logged). + let platform_state = PlatformState { + agent: shared.clone(), + jwks: jwks_state.clone(), + }; + let platform_router: Router = Router::new() + .route("/api/v1/platform/version", get(platform::version)) + .route("/api/v1/platform/usage", get(platform::usage)) + .route( + "/api/v1/platform/tenants/demo/reset", + post(platform::demo_reset), + ) + .route( + "/api/v1/platform/tenants/{id}/provision", + post(platform::provision), + ) + .route( + "/api/v1/platform/tenants/{id}/suspend", + post(platform::suspend), + ) + .route( + "/api/v1/platform/tenants/{id}/reactivate", + post(platform::reactivate), + ) + .route( + "/api/v1/platform/tenants/{id}/terminate", + post(platform::terminate), + ) + .route( + "/api/v1/platform/tenants/{id}/export", + get(platform::export), + ) + .route( + "/api/v1/platform/tenants/{id}/data", + delete(platform::delete_data), + ) + .layer(middleware::from_fn_with_state( + platform_state.clone(), + platform::require_platform_token, + )) + .with_state(platform_state); + // Admin sub-router. Routes are only mounted when ADMIN_API_TOKEN is // configured — without it, the paths don't exist at all (404 rather // than 401), so an operator who hasn't opted in can't fingerprint @@ -72,11 +196,13 @@ pub async fn start_api_server(agent: ComplianceAgent, port: u16) -> Result<(), A Router::new() }; - // Werkbank runner API. Like admin, only mounted when its bearer token is - // configured; runners authenticate with WERKBANK_RUNNER_TOKEN (not a JWT). - let werkbank_router: Router = if agent.config.werkbank_runner_token.is_some() { + // Werkbank runner API. Mounted when a static runner token is configured OR + // a registry is available (runners then present portal-issued API keys). + let werkbank_router: Router = if agent.config.werkbank_runner_token.is_some() + || agent.registry.is_some() + { tracing::info!( - "Werkbank runner API enabled — /api/v1/werkbank/jobs/* behind WERKBANK_RUNNER_TOKEN" + "Werkbank runner API enabled — /api/v1/werkbank/jobs/* (static token and/or registry API keys)" ); Router::new() .route( @@ -109,11 +235,12 @@ pub async fn start_api_server(agent: ComplianceAgent, port: u16) -> Result<(), A let mut app = routes::build_router() .merge(admin_router) .merge(werkbank_router) + .merge(platform_router) // Allow large artifact uploads (PLC .projectarchive, firmware images, // mobile packages) — axum's default request-body limit is only 2 MiB. .layer(DefaultBodyLimit::max(512 * 1024 * 1024)) - .layer(Extension(Arc::new(agent.clone()))) - .layer(CorsLayer::permissive()) + .layer(Extension(shared.clone())) + .layer(cors_layer(&agent.config.cors_allowed_origins)) .layer(TraceLayer::new_for_http()) // Security headers (defense-in-depth, primary enforcement via Traefik) .layer(SetResponseHeaderLayer::overriding( @@ -133,20 +260,20 @@ pub async fn start_api_server(agent: ComplianceAgent, port: u16) -> Result<(), A HeaderValue::from_static("strict-origin-when-cross-origin"), )); - if let (Some(kc_url), Some(kc_realm)) = - (&agent.config.keycloak_url, &agent.config.keycloak_realm) - { - let jwks_url = format!("{kc_url}/realms/{kc_realm}/protocol/openid-connect/certs"); - let jwks_state = JwksState { - jwks: Arc::new(RwLock::new(None)), - jwks_url, - }; - tracing::info!("Keycloak JWT auth enabled for realm '{kc_realm}'"); - // Layers execute outermost-first. Extension(jwks_state) must run - // before require_jwt_auth so the middleware can read it; the - // status gate runs after JWT so TenantContext is in extensions. + if let Some(jwks_state) = jwks_state { + tracing::info!( + issuer = ?jwks_state.issuer, audience = ?jwks_state.audience, + registry = agent.registry.is_some(), + "Keycloak JWT auth enabled" + ); + // Layers execute outermost-first: Extension(jwks) → JWT → entitlement + // (registry) → status ladder → handlers. app = app .layer(middleware::from_fn(require_tenant_status)) + .layer(middleware::from_fn_with_state( + shared.clone(), + require_entitlement, + )) .layer(middleware::from_fn(require_jwt_auth)) .layer(Extension(jwks_state)); } else { diff --git a/compliance-agent/src/config.rs b/compliance-agent/src/config.rs index 5022b2b..91efbdb 100644 --- a/compliance-agent/src/config.rs +++ b/compliance-agent/src/config.rs @@ -67,9 +67,47 @@ pub fn load_config() -> Result { plc_runtime: load_plc_runtime_config(), werkbank_runner_token: env_secret_opt("WERKBANK_RUNNER_TOKEN"), breakpilot: load_breakpilot_config(), + product_key: env_var_opt("PRODUCT_KEY").unwrap_or_else(|| "pruefwerk".to_string()), + // Audience defaults to the product key; set KEYCLOAK_AUDIENCE="" to disable in dev. + keycloak_audience: match std::env::var("KEYCLOAK_AUDIENCE") { + Ok(v) if v.is_empty() => None, + Ok(v) => Some(v), + Err(_) => Some("pruefwerk".to_string()), + }, + tenant_registry_client_id: env_var_opt("TENANT_REGISTRY_CLIENT_ID"), + tenant_registry_client_secret: env_secret_opt("TENANT_REGISTRY_CLIENT_SECRET"), + cors_allowed_origins: env_csv("CORS_ALLOWED_ORIGINS"), + platform_allowed_clients: { + let v = env_csv("PLATFORM_ALLOWED_CLIENTS"); + if v.is_empty() { + [ + "tenant-registry-svc-stage", + "tenant-registry-svc-prod", + "portal-svc-stage", + "portal-svc-prod", + ] + .iter() + .map(|s| s.to_string()) + .collect() + } else { + v + } + }, }) } +fn env_csv(key: &str) -> Vec { + env_var_opt(key) + .map(|s| { + s.split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(String::from) + .collect() + }) + .unwrap_or_default() +} + /// Build the ephemeral soft-PLC provisioning config from the environment, /// falling back to [`PlcRuntimeConfig::default`] for any unset knob. Disabled /// unless `PLC_RUNTIME_ENABLED` is truthy — it requires Docker access. diff --git a/compliance-agent/src/lib.rs b/compliance-agent/src/lib.rs index 275440b..9133088 100644 --- a/compliance-agent/src/lib.rs +++ b/compliance-agent/src/lib.rs @@ -13,6 +13,7 @@ pub mod llm; pub mod pentest; pub mod pipeline; pub mod rag; +pub mod registry; pub mod scheduler; pub mod ssh; #[allow(dead_code)] diff --git a/compliance-agent/src/pentest/cleanup.rs b/compliance-agent/src/pentest/cleanup.rs index 1869581..c719861 100644 --- a/compliance-agent/src/pentest/cleanup.rs +++ b/compliance-agent/src/pentest/cleanup.rs @@ -345,6 +345,12 @@ mod tests { 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![], } } diff --git a/compliance-agent/src/registry.rs b/compliance-agent/src/registry.rs new file mode 100644 index 0000000..22e9136 --- /dev/null +++ b/compliance-agent/src/registry.rs @@ -0,0 +1,338 @@ +//! Tenant-registry client (PRODUCT_INTEGRATION_SPEC 2.0 §4.4, §9.2). +//! +//! The registry is the entitlement authority: the product asks it whether a +//! tenant may use `pruefwerk` (and which limits apply), enumerates tenants +//! for the scheduler, verifies portal-issued API keys for the Werkbank +//! runners, and pushes usage events. Answers are cached for ≤ 60 s and the +//! gate fails CLOSED when the registry is unreachable and no fresh answer is +//! cached. +//! +//! Authentication: a client_credentials token from the platform realm +//! (`TENANT_REGISTRY_CLIENT_ID/SECRET`, audience `tenant-registry`). Without +//! credentials the calls are sent unauthenticated (dev registry with +//! `AUTH_ENABLED=false`). + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use dashmap::DashMap; +use secrecy::ExposeSecret; +use serde::{Deserialize, Serialize}; +use tokio::sync::Mutex; + +use compliance_core::AgentConfig; + +/// How long an entitlement answer is trusted before it is re-fetched. +pub const ENTITLEMENT_TTL: Duration = Duration::from_secs(60); +/// Refresh the service token this long before it expires. +const TOKEN_MARGIN: Duration = Duration::from_secs(30); + +#[derive(Debug, Clone, Deserialize, Serialize, Default)] +pub struct EntitlementCheck { + pub allowed: bool, + #[serde(default)] + pub read_only: bool, + #[serde(default)] + pub status: Option, + #[serde(default)] + pub limits: Option, + #[serde(default)] + pub expires_at: Option, + #[serde(default)] + pub reason: Option, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct RegistryTenant { + pub id: String, + #[serde(default)] + pub slug: String, + #[serde(default)] + pub status: String, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct ApiKeyVerify { + pub valid: bool, + #[serde(default)] + pub tenant_id: String, + #[serde(default)] + pub product: String, + #[serde(default)] + pub scopes: Vec, +} + +#[derive(Debug, Clone, Serialize)] +pub struct UsageEvent { + pub idempotency_key: String, + pub tenant_id: String, + pub product: String, + pub metric: String, + pub quantity: f64, + pub occurred_at: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub properties: Option, +} + +struct CachedToken { + value: String, + expires_at: Instant, +} + +pub struct RegistryClient { + base_url: String, + product: String, + http: reqwest::Client, + token_url: Option, + client_id: Option, + client_secret: Option, + token: Mutex>, + cache: DashMap, +} + +impl std::fmt::Debug for RegistryClient { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RegistryClient") + .field("base_url", &self.base_url) + .field("product", &self.product) + .field("authenticated", &self.client_id.is_some()) + .finish() + } +} + +impl RegistryClient { + /// `None` when `TENANT_REGISTRY_URL` is unset — the agent then runs in + /// claims-only mode (dev) and logs it. + pub fn from_config(cfg: &AgentConfig, http: reqwest::Client) -> Option> { + let base_url = cfg.tenant_registry_url.clone()?; + let token_url = match (&cfg.keycloak_url, &cfg.keycloak_realm) { + (Some(u), Some(r)) => Some(format!( + "{}/realms/{r}/protocol/openid-connect/token", + u.trim_end_matches('/') + )), + _ => None, + }; + if cfg.tenant_registry_client_id.is_none() { + tracing::warn!( + "TENANT_REGISTRY_CLIENT_ID not set — registry calls are unauthenticated (dev only)" + ); + } + Some(Arc::new(Self { + base_url: base_url.trim_end_matches('/').to_string(), + product: cfg.product_key.clone(), + http, + token_url, + client_id: cfg.tenant_registry_client_id.clone(), + client_secret: cfg + .tenant_registry_client_secret + .as_ref() + .map(|s| s.expose_secret().to_string()), + token: Mutex::new(None), + cache: DashMap::new(), + })) + } + + pub fn product(&self) -> &str { + &self.product + } + + async fn bearer(&self) -> Result, String> { + let (Some(url), Some(id), Some(secret)) = + (&self.token_url, &self.client_id, &self.client_secret) + else { + return Ok(None); + }; + let mut guard = self.token.lock().await; + if let Some(t) = guard.as_ref() { + if Instant::now() + TOKEN_MARGIN < t.expires_at { + return Ok(Some(t.value.clone())); + } + } + #[derive(Deserialize)] + struct TokenResp { + access_token: String, + #[serde(default = "default_expiry")] + expires_in: u64, + } + fn default_expiry() -> u64 { + 300 + } + let resp = self + .http + .post(url) + .form(&[ + ("grant_type", "client_credentials"), + ("client_id", id.as_str()), + ("client_secret", secret.as_str()), + ]) + .send() + .await + .map_err(|e| format!("registry token request failed: {e}"))?; + if !resp.status().is_success() { + return Err(format!("registry token request returned {}", resp.status())); + } + let t: TokenResp = resp + .json() + .await + .map_err(|e| format!("registry token response invalid: {e}"))?; + let value = t.access_token; + *guard = Some(CachedToken { + value: value.clone(), + expires_at: Instant::now() + Duration::from_secs(t.expires_in), + }); + Ok(Some(value)) + } + + async fn request( + &self, + method: reqwest::Method, + path: &str, + ) -> Result { + let mut rb = self + .http + .request(method, format!("{}{path}", self.base_url)) + .timeout(Duration::from_secs(5)); + if let Some(tok) = self.bearer().await? { + rb = rb.bearer_auth(tok); + } + Ok(rb) + } + + /// Authoritative entitlement answer for this product, cached ≤ 60 s per + /// (tenant, addon). Errors mean "unknown" — callers fail closed. + pub async fn check_entitlement( + &self, + tenant_id: &str, + addon: Option<&str>, + ) -> Result { + let key = format!("{tenant_id}|{}", addon.unwrap_or("")); + if let Some(entry) = self.cache.get(&key) { + if entry.0.elapsed() < ENTITLEMENT_TTL { + return Ok(entry.1.clone()); + } + } + let body = serde_json::json!({ + "tenant_id": tenant_id, + "product": self.product, + "addon": addon, + }); + let resp = self + .request(reqwest::Method::POST, "/v1/internal/entitlements/check") + .await? + .json(&body) + .send() + .await + .map_err(|e| format!("entitlement check failed: {e}"))?; + if !resp.status().is_success() { + return Err(format!("entitlement check returned {}", resp.status())); + } + let check: EntitlementCheck = resp + .json() + .await + .map_err(|e| format!("entitlement response invalid: {e}"))?; + self.cache.insert(key, (Instant::now(), check.clone())); + Ok(check) + } + + /// Drop the cached answer for a tenant (after a platform lifecycle call). + pub fn invalidate(&self, tenant_id: &str) { + self.cache + .retain(|k, _| !k.starts_with(&format!("{tenant_id}|"))); + } + + /// Every tenant known to the registry (all statuses; the scheduler + /// applies the ladder filter). Follows `next_cursor` pagination. + pub async fn list_tenants(&self) -> Result, String> { + #[derive(Deserialize)] + struct Page { + items: Vec, + #[serde(default)] + next_cursor: Option, + } + let mut out = Vec::new(); + let mut cursor: Option = None; + for _ in 0..50 { + let mut path = "/v1/tenants?limit=200".to_string(); + if let Some(c) = &cursor { + path.push_str("&cursor="); + path.push_str(&urlencoding::encode(c)); + } + let resp = self + .request(reqwest::Method::GET, &path) + .await? + .send() + .await + .map_err(|e| format!("tenant list failed: {e}"))?; + if !resp.status().is_success() { + return Err(format!("tenant list returned {}", resp.status())); + } + let page: Page = resp + .json() + .await + .map_err(|e| format!("tenant list invalid: {e}"))?; + out.extend(page.items); + match page.next_cursor { + Some(c) if !c.is_empty() => cursor = Some(c), + _ => break, + } + } + Ok(out) + } + + /// Verify a portal-issued API key (`bp_…`). + pub async fn verify_api_key(&self, key: &str) -> Result { + let resp = self + .request(reqwest::Method::POST, "/v1/internal/api-keys/verify") + .await? + .json(&serde_json::json!({ "key": key })) + .send() + .await + .map_err(|e| format!("api-key verify failed: {e}"))?; + if !resp.status().is_success() { + return Err(format!("api-key verify returned {}", resp.status())); + } + resp.json() + .await + .map_err(|e| format!("api-key verify response invalid: {e}")) + } + + /// Push usage events (§9.2). Best-effort: the caller logs failures. + pub async fn push_usage_events(&self, events: &[UsageEvent]) -> Result<(), String> { + if events.is_empty() { + return Ok(()); + } + let resp = self + .request(reqwest::Method::POST, "/v1/usage/events") + .await? + .json(events) + .send() + .await + .map_err(|e| format!("usage push failed: {e}"))?; + if !resp.status().is_success() { + return Err(format!("usage push returned {}", resp.status())); + } + Ok(()) + } +} + +/// Ladder rungs on which scheduled work still makes sense. Restricted / +/// frozen / halted / archived tenants are skipped — the status gate would +/// refuse the writes anyway. +pub fn scheduler_runs_for(status: &str) -> bool { + matches!(status, "" | "active" | "trial" | "demo" | "warning") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ladder_filter() { + for s in ["active", "trial", "demo", "warning", ""] { + assert!(scheduler_runs_for(s), "{s} should run"); + } + for s in ["restricted", "frozen", "halted", "archived"] { + assert!(!scheduler_runs_for(s), "{s} should be skipped"); + } + } +} diff --git a/compliance-agent/src/scheduler.rs b/compliance-agent/src/scheduler.rs index 17fdd3c..ef51fc3 100644 --- a/compliance-agent/src/scheduler.rs +++ b/compliance-agent/src/scheduler.rs @@ -6,6 +6,7 @@ use compliance_core::models::ScanTrigger; use crate::agent::ComplianceAgent; use crate::database::Database; use crate::error::AgentError; +use crate::registry::scheduler_runs_for; /// Default tenant the scheduler runs against when neither the tenant /// registry nor `SCHEDULER_TENANT_IDS` are configured. Matches the @@ -13,12 +14,6 @@ use crate::error::AgentError; /// scanning whatever lives in `_dev`. const DEFAULT_SCHEDULER_TENANT_ID: &str = "dev"; -/// Request timeout when fetching the live tenant list from the -/// registry. Kept short — if the registry is slow we'd rather fall -/// back to env-configured ids and finish the tick than block the -/// scheduler loop. -const REGISTRY_FETCH_TIMEOUT_SECS: u64 = 5; - pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError> { let sched = JobScheduler::new() .await @@ -76,7 +71,7 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError> .map_err(|e| AgentError::Scheduler(format!("Failed to start scheduler: {e}")))?; let tenants = scheduler_tenants(agent).await; - let source = if agent.config.tenant_registry_url.is_some() { + let source = if agent.registry.is_some() { "tenant-registry (env fallback)" } else { "env (SCHEDULER_TENANT_IDS)" @@ -108,18 +103,21 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError> /// We never panic out of this function — the scheduler must keep /// firing even if the registry is offline. async fn scheduler_tenants(agent: &ComplianceAgent) -> Vec { - if let Some(url) = agent.config.tenant_registry_url.as_deref() { - match fetch_tenants_from_registry(&agent.http, url).await { - Ok(v) if !v.is_empty() => return v, - Ok(_) => { - tracing::warn!("tenant-registry returned empty list; falling back to env"); + if let Some(registry) = agent.registry.as_ref() { + match registry.list_tenants().await { + Ok(rows) => { + let v: Vec = rows + .into_iter() + .filter(|t| scheduler_runs_for(&t.status)) + .map(|t| t.id) + .collect(); + if !v.is_empty() { + return v; + } + tracing::warn!("tenant-registry returned no runnable tenants; falling back to env"); } Err(e) => { - tracing::warn!( - url = %url, - error = %e, - "tenant-registry fetch failed; falling back to env" - ); + tracing::warn!(error = %e, "tenant-registry fetch failed; falling back to env"); } } } @@ -140,136 +138,31 @@ fn tenants_from_env() -> Vec { .unwrap_or_else(|| vec![DEFAULT_SCHEDULER_TENANT_ID.to_string()]) } -/// Shape we accept from the registry. Liberal in what we accept: -/// the registry can return any field shape as long as either `id` or -/// `tenant_id` is present. Other fields are ignored. -#[derive(serde::Deserialize)] -struct RegistryTenant { - #[serde(alias = "tenant_id")] - id: String, - /// Filter out non-running tenants if status is present. Missing - /// status defaults to "active" so older registry deployments keep - /// working. - #[serde(default = "default_status")] - status: String, -} - -fn default_status() -> String { - "active".to_string() -} - -#[derive(serde::Deserialize)] -struct RegistryListResponse { - data: Vec, -} - -async fn fetch_tenants_from_registry( - http: &reqwest::Client, - base_url: &str, -) -> Result, String> { - let url = format!("{}/v1/tenants", base_url.trim_end_matches('/')); - let resp = http - .get(&url) - .timeout(std::time::Duration::from_secs(REGISTRY_FETCH_TIMEOUT_SECS)) - .send() - .await - .map_err(|e| format!("request failed: {e}"))?; - if !resp.status().is_success() { - return Err(format!("registry returned {}", resp.status())); - } - let body: RegistryListResponse = resp - .json() - .await - .map_err(|e| format!("invalid JSON: {e}"))?; - Ok(filter_active(body.data)) -} - -/// Frozen/Archived tenants don't need scheduled scans; the M7.1 -/// status gate would 402/410 anyway. Skip them so we don't waste -/// cycles. Active / trial / demo / anything-else-unknown all run. -fn filter_active(rows: Vec) -> Vec { - rows.into_iter() - .filter(|t| !matches!(t.status.as_str(), "frozen" | "archived")) - .map(|t| t.id) - .collect() -} - #[cfg(test)] mod tests { - use super::*; - - fn tenant(id: &str, status: &str) -> RegistryTenant { - RegistryTenant { - id: id.to_string(), - status: status.to_string(), - } - } + use crate::registry::scheduler_runs_for; #[test] - fn filter_active_keeps_running_skips_frozen_archived() { - let rows = vec![ - tenant("a", "active"), - tenant("b", "trial"), - tenant("c", "demo"), - tenant("d", "frozen"), - tenant("e", "archived"), - tenant("f", "weird-but-not-known-dead"), + fn ladder_filter_keeps_running_skips_read_only_and_dead() { + let rows = [ + ("a", "active"), + ("b", "trial"), + ("c", "demo"), + ("d", "warning"), + ("e", "restricted"), + ("f", "frozen"), + ("g", "halted"), + ("h", "archived"), ]; - let out = filter_active(rows); - assert_eq!(out, vec!["a", "b", "c", "f"]); - } - - #[test] - fn deserialize_registry_response_accepts_id_or_tenant_id() { - let body = r#"{"data":[ - {"id":"a","status":"active"}, - {"tenant_id":"b","status":"trial"}, - {"id":"c"} - ]}"#; - let parsed: RegistryListResponse = serde_json::from_str(body).unwrap(); - assert_eq!(parsed.data.len(), 3); - assert_eq!(parsed.data[0].id, "a"); - assert_eq!(parsed.data[1].id, "b"); - assert_eq!(parsed.data[2].id, "c"); - // Default status for the third entry should be "active" - assert_eq!(parsed.data[2].status, "active"); - } - - /// Combined into a single test: cargo runs tests in parallel and - /// env vars are process-global, so two separate tests touching - /// `SCHEDULER_TENANT_IDS` race each other. Doing both checks in - /// one test keeps them in a deterministic order. - #[test] - fn tenants_from_env_resolution() { - std::env::remove_var("SCHEDULER_TENANT_IDS"); - assert_eq!( - tenants_from_env(), - vec![DEFAULT_SCHEDULER_TENANT_ID.to_string()], - "unset → default" - ); - - std::env::set_var("SCHEDULER_TENANT_IDS", "acme, globex ,,hello"); - let out = tenants_from_env(); - std::env::remove_var("SCHEDULER_TENANT_IDS"); - assert_eq!( - out, - vec!["acme", "globex", "hello"], - "splits + trims + drops empty" - ); - - std::env::set_var("SCHEDULER_TENANT_IDS", ""); - let out = tenants_from_env(); - std::env::remove_var("SCHEDULER_TENANT_IDS"); - assert_eq!( - out, - vec![DEFAULT_SCHEDULER_TENANT_ID.to_string()], - "empty → default" - ); + let out: Vec<&str> = rows + .iter() + .filter(|(_, s)| scheduler_runs_for(s)) + .map(|(id, _)| *id) + .collect(); + assert_eq!(out, vec!["a", "b", "c", "d"]); } } -/// Resolve the per-tenant database. Logs and returns `None` on failure -/// so the loop in the caller can continue with other tenants. async fn tenant_db(agent: &ComplianceAgent, tenant_id: &str) -> Option { match agent.db_pool.for_tenant_id(tenant_id).await { Ok(db) => Some(db), diff --git a/compliance-agent/tests/common/mod.rs b/compliance-agent/tests/common/mod.rs index 9b45a56..3fe13bd 100644 --- a/compliance-agent/tests/common/mod.rs +++ b/compliance-agent/tests/common/mod.rs @@ -61,6 +61,12 @@ pub fn dev_config(mongodb_uri: String, db_name: String) -> AgentConfig { 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(), + keycloak_audience: None, + tenant_registry_client_id: None, + tenant_registry_client_secret: None, + cors_allowed_origins: vec![], + platform_allowed_clients: vec![], } } diff --git a/compliance-agent/tests/tenant_status_middleware.rs b/compliance-agent/tests/tenant_status_middleware.rs index 5ce0d9a..b1a2fec 100644 --- a/compliance-agent/tests/tenant_status_middleware.rs +++ b/compliance-agent/tests/tenant_status_middleware.rs @@ -120,3 +120,50 @@ async fn no_context_passes_through() { ); assert_eq!(call(r, Method::POST, "/w").await.status(), StatusCode::OK); } + +#[tokio::test] +async fn ladder_warning_passes_restricted_blocks_writes_halted_blocks_all() { + let r = call( + router_with_ctx(Some(ctx_with(TenantStatus::Warning))), + Method::POST, + "/w", + ) + .await; + assert_eq!(r.status(), StatusCode::OK, "warning keeps full access"); + let r = call( + router_with_ctx(Some(ctx_with(TenantStatus::Restricted))), + Method::GET, + "/r", + ) + .await; + assert_eq!(r.status(), StatusCode::OK, "restricted still reads"); + let r = call( + router_with_ctx(Some(ctx_with(TenantStatus::Restricted))), + Method::POST, + "/w", + ) + .await; + assert_eq!( + r.status(), + StatusCode::PAYMENT_REQUIRED, + "restricted blocks writes" + ); + let r = call( + router_with_ctx(Some(ctx_with(TenantStatus::Halted))), + Method::GET, + "/r", + ) + .await; + assert_eq!( + r.status(), + StatusCode::PAYMENT_REQUIRED, + "halted blocks reads too" + ); + let r = call( + router_with_ctx(Some(ctx_with(TenantStatus::Archived))), + Method::GET, + "/r", + ) + .await; + assert_eq!(r.status(), StatusCode::GONE); +} diff --git a/compliance-core/src/auth.rs b/compliance-core/src/auth.rs index e3bcc59..81376cf 100644 --- a/compliance-core/src/auth.rs +++ b/compliance-core/src/auth.rs @@ -31,10 +31,35 @@ use tokio::sync::RwLock; use crate::{OrgRole, TenantContext, TenantStatus}; /// Cached JWKS from Keycloak for token validation. +/// +/// `issuer` and `audience` are pinned when set (PRODUCT_INTEGRATION_SPEC 2.0 +/// §9.1: never skip iss/aud validation). `None` keeps the legacy dev +/// behaviour and is logged as a warning at startup. #[derive(Clone)] pub struct JwksState { pub jwks: Arc>>, pub jwks_url: String, + pub issuer: Option, + pub audience: Option, +} + +impl JwksState { + pub fn new(jwks_url: String, issuer: Option, audience: Option) -> Self { + Self { + jwks: Arc::new(RwLock::new(None)), + jwks_url, + issuer, + audience, + } + } +} + +/// Claims of a platform service token (client_credentials). `azp` is the +/// Keycloak client that obtained it — the platform endpoints allow-list it. +#[derive(Debug, Clone)] +pub struct ServiceClaims { + pub sub: String, + pub azp: String, } /// Raw shape of the JWT payload — matches the breakpilot-dev realm's @@ -59,6 +84,8 @@ struct Claims { plan: String, #[serde(default)] tenant_status: Option, + #[serde(default)] + azp: Option, } const PUBLIC_ENDPOINTS: &[&str] = &["/api/v1/health"]; @@ -68,7 +95,7 @@ const PUBLIC_ENDPOINTS: &[&str] = &["/api/v1/health"]; /// have their own static-bearer middleware and must not be routed through the /// customer-JWT path — a Keycloak token always carries a single tenant_id and /// would semantically conflict with these cross-tenant / machine operations. -const PUBLIC_PREFIXES: &[&str] = &["/api/v1/admin/", "/api/v1/werkbank/"]; +const PUBLIC_PREFIXES: &[&str] = &["/api/v1/admin/", "/api/v1/werkbank/", "/api/v1/platform/"]; /// Middleware that validates Bearer JWT tokens against Keycloak's JWKS /// and attaches a `TenantContext` extension on success. @@ -111,10 +138,12 @@ pub async fn require_jwt_auth(mut request: Request, next: Next) -> Response { } } -/// Middleware that enforces the M7.1 `tenant_status` contract. +/// Middleware that enforces the tenant status ladder (contract 2.0 §9.3). /// -/// * `Active` / `Trial` / `Demo` — pass through. -/// * `Frozen` — read-only after cancel / non-payment. Writes return 402. +/// * `Active` / `Trial` / `Demo` / `Warning` — pass through. +/// * `Restricted` / `Frozen` — read-only. Writes return 402. +/// * `Halted` — every request returns 402 (exports go through the platform +/// endpoints, which bypass this middleware). /// * `Archived` — data-retention window closed. Every request returns 410. /// /// Pass-through when no `TenantContext` is present (single-tenant dev or @@ -133,10 +162,18 @@ pub async fn require_tenant_status(request: Request, next: Next) -> Response { .into_response(); } - if ctx.status.is_frozen() && is_write(request.method()) { + if ctx.status.is_halted() { return ( StatusCode::PAYMENT_REQUIRED, - "Tenant frozen — read-only. Re-activate to resume writes.", + "Tenant halted — access suspended; data export remains available via the portal.", + ) + .into_response(); + } + + if ctx.status.blocks_writes() && is_write(request.method()) { + return ( + StatusCode::PAYMENT_REQUIRED, + "Tenant restricted — read-only. Settle the open invoice to resume writes.", ) .into_response(); } @@ -144,6 +181,24 @@ pub async fn require_tenant_status(request: Request, next: Next) -> Response { next.run(request).await } +/// Validate a platform service token (client_credentials JWT from the same +/// realm) for the `/api/v1/platform/*` endpoints. Signature, expiry, issuer +/// and audience are enforced like user tokens; `tenant_id` is NOT required. +pub async fn validate_service_token( + token: &str, + state: &JwksState, +) -> Result { + let claims = decode_claims(token, state).await?; + let azp = claims.azp.clone().unwrap_or_default(); + if azp.is_empty() { + return Err("service token is missing the azp claim".to_string()); + } + Ok(ServiceClaims { + sub: claims.sub, + azp, + }) +} + /// Treat anything other than GET/HEAD/OPTIONS as a write. Good enough for /// REST. The few exceptions (e.g. read-side POSTs) can opt out at the /// handler level once we have them. @@ -152,6 +207,12 @@ fn is_write(m: &Method) -> bool { } async fn validate_token(token: &str, state: &JwksState) -> Result { + claims_to_context(decode_claims(token, state).await?) +} + +/// Decode + verify a token against the cached JWKS (refreshing once on a +/// stale kid / signature) and return the raw claims. +async fn decode_claims(token: &str, state: &JwksState) -> Result { let header = decode_header(token).map_err(|e| format!("failed to decode JWT header: {e}"))?; let kid = header @@ -165,8 +226,8 @@ async fn validate_token(token: &str, state: &JwksState) -> Result Ok(ctx), + match try_validate(token, &header, &kid, &jwks, state) { + Ok(c) => Ok(c), Err(ValidationError::Permanent(e)) => Err(e), Err(ValidationError::Stale(reason)) => { tracing::info!( @@ -175,7 +236,7 @@ async fn validate_token(token: &str, state: &JwksState) -> Result s, }) } @@ -195,7 +256,8 @@ fn try_validate( header: &jsonwebtoken::Header, kid: &str, jwks: &JwkSet, -) -> Result { + state: &JwksState, +) -> Result { let jwk = match jwks .keys .iter() @@ -214,7 +276,13 @@ fn try_validate( let mut validation = Validation::new(header.alg); validation.validate_exp = true; - validation.validate_aud = false; + match state.audience.as_deref() { + Some(aud) => validation.set_audience(&[aud]), + None => validation.validate_aud = false, + } + if let Some(iss) = state.issuer.as_deref() { + validation.set_issuer(&[iss]); + } let data = match decode::(token, &decoding_key, &validation) { Ok(d) => d, @@ -232,7 +300,7 @@ fn try_validate( } }; - claims_to_context(data.claims).map_err(ValidationError::Permanent) + Ok(data.claims) } /// Map the decoded JWT payload into the platform-wide `TenantContext`. @@ -311,6 +379,7 @@ mod tests { products: vec!["compliance".to_string()], plan: "professional".to_string(), tenant_status: Some(TenantStatus::Active), + azp: Some("pruefwerk-dashboard-stage".to_string()), } } @@ -377,8 +446,15 @@ mod tests { kid: Some("kid-rotated-out".to_string()), ..Default::default() }; - let err = try_validate("ignored.token.value", &header, "kid-rotated-out", &jwks) - .expect_err("should fail"); + let state = JwksState::new("http://unused/certs".to_string(), None, None); + let err = try_validate( + "ignored.token.value", + &header, + "kid-rotated-out", + &jwks, + &state, + ) + .expect_err("should fail"); match err { ValidationError::Stale(s) => assert!(s.contains("no matching key")), ValidationError::Permanent(s) => panic!("must be Stale, got Permanent: {s}"), diff --git a/compliance-core/src/config.rs b/compliance-core/src/config.rs index e19a35d..bc5a434 100644 --- a/compliance-core/src/config.rs +++ b/compliance-core/src/config.rs @@ -62,6 +62,21 @@ pub struct AgentConfig { /// (drives the [`crate::traits::ControlsProvider`]). Disabled when /// `base_url` is `None`. pub breakpilot: BreakpilotConfig, + + // ── Platform integration (PRODUCT_INTEGRATION_SPEC 2.0, M-MIG-6) ── + /// Catalog key of this product in the tenant-registry (`pruefwerk`). + pub product_key: String, + /// Expected `aud` of user JWTs (the realm's `-audience` scope). + /// `None` skips audience validation (dev only; logged). + pub keycloak_audience: Option, + /// Service-account client used for registry calls (client_credentials + /// against `keycloak_url`/`keycloak_realm`). Optional in dev. + pub tenant_registry_client_id: Option, + pub tenant_registry_client_secret: Option, + /// Browser origins allowed by CORS. Empty ⇒ permissive (dev only; logged). + pub cors_allowed_origins: Vec, + /// Keycloak clients (JWT `azp`) allowed to call `/api/v1/platform/*`. + pub platform_allowed_clients: Vec, } /// Where to pull the OSCAL control catalog from breakpilot-compliance, and where diff --git a/compliance-core/src/tenant.rs b/compliance-core/src/tenant.rs index bf0ddf2..47a2a7e 100644 --- a/compliance-core/src/tenant.rs +++ b/compliance-core/src/tenant.rs @@ -12,12 +12,15 @@ use serde::{Deserialize, Serialize}; -/// Tenant lifecycle status from `PLATFORM_ARCHITECTURE.md §5c`. +/// Tenant status ladder (`PLATFORM_ARCHITECTURE.md §5c`, ERP/02). /// /// Drives the `tenant_status` middleware: -/// * `Demo` / `Trial` / `Active` — full access. -/// * `Frozen` — read-only after cancel / non-payment. Mutating endpoints -/// return 402. +/// * `Demo` / `Trial` / `Active` / `Warning` — full access (Warning = payment +/// overdue within grace; UIs show a banner). +/// * `Restricted` (Eingeschränkt) and the legacy `Frozen` — read-only: +/// mutating endpoints return 402, exports still work. +/// * `Halted` (Angehalten) — every request returns 402 except the platform +/// export path; data retained for the export window. /// * `Archived` — data-retention window closed. Every endpoint returns 410. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] @@ -25,14 +28,39 @@ pub enum TenantStatus { Demo, Trial, Active, + Warning, + Restricted, Frozen, + Halted, Archived, } impl TenantStatus { - /// True for statuses that block write paths. + /// Parse the registry / JWT string form. Unknown values → `None`. + pub fn parse(s: &str) -> Option { + Some(match s { + "demo" => Self::Demo, + "trial" => Self::Trial, + "active" => Self::Active, + "warning" => Self::Warning, + "restricted" => Self::Restricted, + "frozen" => Self::Frozen, + "halted" => Self::Halted, + "archived" => Self::Archived, + _ => return None, + }) + } + /// True for the read-only rungs of the ladder (writes return 402). + pub fn blocks_writes(&self) -> bool { + matches!(self, TenantStatus::Frozen | TenantStatus::Restricted) + } + /// Legacy name for [`Self::blocks_writes`]. pub fn is_frozen(&self) -> bool { - matches!(self, TenantStatus::Frozen) + self.blocks_writes() + } + /// True when every request except export is refused (402). + pub fn is_halted(&self) -> bool { + matches!(self, TenantStatus::Halted) } /// True for statuses that block every request. pub fn is_archived(&self) -> bool { @@ -51,7 +79,10 @@ impl std::fmt::Display for TenantStatus { Self::Demo => write!(f, "demo"), Self::Trial => write!(f, "trial"), Self::Active => write!(f, "active"), + Self::Warning => write!(f, "warning"), + Self::Restricted => write!(f, "restricted"), Self::Frozen => write!(f, "frozen"), + Self::Halted => write!(f, "halted"), Self::Archived => write!(f, "archived"), } } @@ -140,7 +171,16 @@ mod tests { #[test] fn tenant_status_predicates() { assert!(TenantStatus::Frozen.is_frozen()); + assert!(TenantStatus::Restricted.blocks_writes()); + assert!(!TenantStatus::Warning.blocks_writes()); + assert!(TenantStatus::Halted.is_halted()); assert!(!TenantStatus::Active.is_frozen()); + assert_eq!( + TenantStatus::parse("restricted"), + Some(TenantStatus::Restricted) + ); + assert_eq!(TenantStatus::parse("paid"), None); + assert_eq!(TenantStatus::Halted.to_string(), "halted"); assert!(TenantStatus::Archived.is_archived()); assert!(TenantStatus::Demo.is_demo()); assert!(!TenantStatus::Active.is_demo()); diff --git a/compliance-smoke/src/main.rs b/compliance-smoke/src/main.rs index fc14c3b..b4dfcaa 100644 --- a/compliance-smoke/src/main.rs +++ b/compliance-smoke/src/main.rs @@ -16,15 +16,12 @@ //! * `KEYCLOAK_REALM` — e.g. `certifai`. Required. //! * `SMOKE_PORT` — defaults to `3010`. -use std::sync::Arc; - use axum::{middleware, routing::get, Extension, Json, Router}; use compliance_core::{ auth::{require_jwt_auth, require_tenant_status, JwksState}, tenant_ctx::TenantCtx, }; use serde::Serialize; -use tokio::sync::RwLock; #[derive(Serialize)] struct EchoResponse { @@ -83,11 +80,12 @@ async fn main() -> Result<(), Box> { .and_then(|s| s.parse().ok()) .unwrap_or(3010); - let jwks_url = format!("{kc_url}/realms/{kc_realm}/protocol/openid-connect/certs"); - let jwks_state = JwksState { - jwks: Arc::new(RwLock::new(None)), - jwks_url: jwks_url.clone(), - }; + let issuer = format!("{}/realms/{kc_realm}", kc_url.trim_end_matches('/')); + let jwks_url = format!("{issuer}/protocol/openid-connect/certs"); + let audience = std::env::var("KEYCLOAK_AUDIENCE") + .ok() + .filter(|s| !s.is_empty()); + let jwks_state = JwksState::new(jwks_url.clone(), Some(issuer), audience); // Layers execute outermost-first. The Extension must be registered // before `require_jwt_auth` so the middleware can read JwksState; the