Files
pruefwerk/compliance-agent/src/api/server.rs
T
sharang 0e7a138cd4
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 7m28s
CI / Deploy Dashboard (push) Successful in 5m12s
CI / Deploy MCP (push) Successful in 3m30s
feat(access): blocked workspace members are refused (portal#74) (#471)
2026-10-05 22:21:20 +00:00

548 lines
21 KiB
Rust

use std::sync::Arc;
use axum::extract::{DefaultBodyLimit, Request, State};
use axum::http::{HeaderValue, Method, StatusCode};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use axum::routing::{delete, get, post};
use axum::{middleware, Extension, Json, Router};
use tower_http::cors::{Any, CorsLayer};
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::shutdown::{self, Shutdown};
use compliance_core::{OrgRole, TenantContext, TenantStatus};
use crate::agent::ComplianceAgent;
use crate::api::handlers;
use crate::api::handlers::platform::{self, PlatformState};
use crate::api::{role_gate, routes};
use crate::error::AgentError;
/// Synthetic tenant id used when Keycloak isn't configured (local dev,
/// `cargo run` against a bare Mongo). Lets the handler stack stay
/// uniformly tenant-scoped without the operator having to spin up KC
/// just to poke at the API. Override via `DEV_TENANT_ID`.
const DEFAULT_DEV_TENANT_ID: &str = "dev";
/// Largest job result a Werkbank runner may post. Every other JSON route keeps
/// axum's 2 MiB default; only uploads (streamed) and this one go higher.
const RUNNER_RESULT_MAX_BYTES: usize = 32 * 1024 * 1024;
/// Inject a synthetic [`TenantContext`] for any request that lacks one.
/// Only mounted when Keycloak is NOT configured; with KC, the real
/// `require_jwt_auth` middleware owns this and we never reach here
/// without a context.
///
/// Public so the integration-test harness can mount it without
/// duplicating the synthetic-context shape.
pub async fn inject_dev_tenant(mut request: Request, next: Next) -> Response {
if request.extensions().get::<TenantContext>().is_none() {
let tenant_id =
std::env::var("DEV_TENANT_ID").unwrap_or_else(|_| DEFAULT_DEV_TENANT_ID.to_string());
let ctx = TenantContext {
tenant_slug: tenant_id.clone(),
tenant_id,
// The single local user administers the dev organisation.
org_roles: vec![OrgRole::ItAdmin],
products: vec![],
plan: "dev".to_string(),
status: TenantStatus::Active,
user_id: "dev-user".to_string(),
user_name: None,
staff: None,
};
request.extensions_mut().insert(ctx);
}
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<Arc<ComplianceAgent>>,
mut request: Request,
next: Next,
) -> Response {
// Support access names its tenant in a header: only the registry can
// confirm it exists, so without one there is no support access at all.
if let Some(ctx) = request
.extensions()
.get::<TenantContext>()
.filter(|c| c.staff.is_some())
.cloned()
{
let Some(registry) = agent.registry.as_ref() else {
tracing::error!("support access needs the tenant registry — denying");
return entitlement_unavailable();
};
return match registry.get_tenant(&ctx.tenant_id).await {
Ok(Some(tenant)) => {
request
.extensions_mut()
.insert(confirmed_support_context(ctx, &tenant));
next.run(request).await
}
Ok(None) => (
StatusCode::NOT_FOUND,
Json(serde_json::json!({ "error": "unknown_tenant" })),
)
.into_response(),
Err(e) => {
tracing::error!(tenant_id = %ctx.tenant_id, "support tenant lookup failed: {e}");
entitlement_unavailable()
}
};
}
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::<TenantContext>().cloned() else {
return next.run(request).await;
};
// A person's token (support took its own branch above; service tokens
// carry no tenant context here): the registry also says whether this
// member is blocked in the tenant.
let user = Some(ctx.user_id.as_str()).filter(|u| !u.is_empty());
match registry.check_entitlement(&ctx.tenant_id, None, user).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) if check.member_blocked() => (
StatusCode::FORBIDDEN,
Json(serde_json::json!({
"error": "MEMBER_BLOCKED",
"status": check.status,
})),
)
.into_response(),
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()
}
}
}
/// 503 when the registry cannot answer: access is never widened on doubt.
fn entitlement_unavailable() -> Response {
(
StatusCode::SERVICE_UNAVAILABLE,
Json(serde_json::json!({ "error": "entitlement_unavailable" })),
)
.into_response()
}
/// A support context once the registry has confirmed its tenant: the real
/// slug and ladder status replace the read-only placeholder. Support is not
/// held to the customer's plan limits, but the ladder still applies (a
/// halted or archived tenant stays closed).
fn confirmed_support_context(
mut ctx: TenantContext,
tenant: &crate::registry::RegistryTenant,
) -> TenantContext {
ctx.tenant_slug = tenant.slug.clone();
// An unknown status stays read-only.
ctx.status = TenantStatus::parse(&tenant.status).unwrap_or(TenantStatus::Restricted);
ctx
}
/// Record every change BreakPilot support makes in a tenant, refused ones
/// included, in the platform's audit log. Reads are not logged one by one;
/// opening a tenant is (`POST /api/v1/support/session`). Background and
/// best-effort: an unreachable registry never blocks support.
pub async fn audit_support_writes(
State(agent): State<Arc<ComplianceAgent>>,
request: Request,
next: Next,
) -> Response {
let staff_ctx = request
.extensions()
.get::<TenantContext>()
.filter(|c| c.staff.is_some())
.cloned();
let method = request.method().clone();
let path = request.uri().path().to_string();
let response = next.run(request).await;
let (Some(ctx), Some(registry)) = (staff_ctx, agent.registry.clone()) else {
return response;
};
if matches!(method, Method::GET | Method::HEAD | Method::OPTIONS) {
return response;
}
let entry = support_audit_entry(&ctx, method.as_str(), &path, response.status().as_u16());
tokio::spawn(async move {
if let Err(e) = registry.append_audit(&entry).await {
tracing::warn!(tenant_id = %entry.tenant_id, "support audit not recorded: {e}");
}
});
response
}
/// The audit entry for a support request. The path names the resource; the
/// query and body are left out, as they may carry customer data.
fn support_audit_entry(
ctx: &TenantContext,
method: &str,
path: &str,
status: u16,
) -> crate::registry::AuditEntry {
crate::registry::AuditEntry::by(
ctx,
"pruefwerk.support_access",
serde_json::json!({ "method": method, "path": path, "status": status }),
)
}
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();
}
let parsed: Vec<HeaderValue> = origins
.iter()
.filter_map(|o| HeaderValue::from_str(o).ok())
.collect();
CorsLayer::new()
.allow_origin(parsed)
.allow_methods(Any)
.allow_headers(Any)
}
/// Serve the REST API on `port` until `shutdown` fires, then drain in-flight
/// requests for at most [`shutdown::GRACE_PERIOD`].
///
/// # Errors
///
/// Returns an error if Keycloak is missing in a hardened environment, the port
/// cannot be bound, or serving fails.
pub async fn start_api_server(
agent: ComplianceAgent,
port: u16,
shutdown: Shutdown,
) -> 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/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),
)
// The portal's view of a tenant's targets (per project), through the
// registry. Read-only.
.route(
"/api/v1/platform/tenants/{id}/targets",
get(platform::list_targets),
)
.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),
)
// The tenant's managed git source (#439).
.route(
"/api/v1/platform/tenants/{id}/git-source",
get(platform::get_git_source)
.put(platform::put_git_source)
.delete(platform::delete_git_source),
)
.layer(middleware::from_fn_with_state(
platform_state.clone(),
platform::require_platform_token,
))
.with_state(platform_state.clone())
// The contract handshake is public (§4.1 /version): no token needed.
.route(
"/api/v1/platform/version",
get(platform::version).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
// the surface area.
let admin_router: Router = if agent.config.admin_api_token.is_some() {
tracing::info!("Admin API enabled — /api/v1/admin/* mounted behind ADMIN_API_TOKEN bearer");
Router::new()
.route(
"/api/v1/admin/tenants",
get(handlers::admin::list_tenant_dbs),
)
.route(
"/api/v1/admin/tenants/{tenant_id}",
delete(handlers::admin::drop_tenant_db),
)
.layer(middleware::from_fn(handlers::admin::require_admin_token))
} else {
Router::new()
};
// 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/* (static token and/or registry API keys)"
);
Router::new()
.route(
"/api/v1/werkbank/jobs/lease",
post(handlers::werkbank_jobs::lease),
)
.route(
"/api/v1/werkbank/jobs/heartbeat",
post(handlers::werkbank_jobs::heartbeat),
)
.route(
"/api/v1/werkbank/jobs/complete",
// A job's result carries all its findings as JSON, which can
// outgrow the 2 MiB default. The route is behind a runner key.
post(handlers::werkbank_jobs::complete)
.layer(DefaultBodyLimit::max(RUNNER_RESULT_MAX_BYTES)),
)
.route(
"/api/v1/werkbank/jobs/enqueue",
post(handlers::werkbank_jobs::enqueue),
)
.route(
"/api/v1/werkbank/artifacts/{hash}",
get(handlers::werkbank_jobs::serve_artifact),
)
.layer(middleware::from_fn(
handlers::werkbank_jobs::require_runner_token,
))
} else {
Router::new()
};
let mut app = routes::build_router()
.merge(admin_router)
.merge(werkbank_router)
.merge(platform_router)
.layer(Extension(shared.clone()))
.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(
axum::http::header::STRICT_TRANSPORT_SECURITY,
HeaderValue::from_static("max-age=31536000; includeSubDomains"),
))
.layer(SetResponseHeaderLayer::overriding(
axum::http::header::X_FRAME_OPTIONS,
HeaderValue::from_static("DENY"),
))
.layer(SetResponseHeaderLayer::overriding(
axum::http::header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
))
.layer(SetResponseHeaderLayer::overriding(
axum::http::header::REFERRER_POLICY,
HeaderValue::from_static("strict-origin-when-cross-origin"),
));
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 → org roles
// → entitlement (registry) → support audit → status ladder → handlers.
app = app
.layer(middleware::from_fn(require_tenant_status))
.layer(middleware::from_fn_with_state(
shared.clone(),
audit_support_writes,
))
.layer(middleware::from_fn_with_state(
shared.clone(),
require_entitlement,
))
.layer(middleware::from_fn(role_gate::require_org_role))
.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());
tracing::warn!(
tenant_id = %tenant_id,
"Keycloak not configured — running unauthenticated against the dev tenant. \
DO NOT use in any environment with real customer data."
);
app = app
.layer(middleware::from_fn(role_gate::require_org_role))
.layer(middleware::from_fn(inject_dev_tenant));
}
let addr = format!("0.0.0.0:{port}");
let listener = tokio::net::TcpListener::bind(&addr)
.await
.map_err(|e| AgentError::Other(format!("Failed to bind to {addr}: {e}")))?;
tracing::info!("REST API listening on {addr}");
shutdown::serve(listener, app, shutdown, shutdown::GRACE_PERIOD)
.await
.map_err(|e| AgentError::Other(format!("API server error: {e}")))?;
tracing::info!("REST API stopped");
Ok(())
}
#[cfg(test)]
mod support_tests {
use super::*;
fn support_ctx() -> TenantContext {
TenantContext {
tenant_id: "00000000-0000-0000-0000-000000000002".to_string(),
tenant_slug: String::new(),
org_roles: vec![OrgRole::ItAdmin],
products: Vec::new(),
plan: String::new(),
status: TenantStatus::Restricted,
user_id: "s-1".to_string(),
user_name: Some("Sharang".to_string()),
staff: Some(compliance_core::StaffAccess {
user_id: "s-1".to_string(),
user_name: Some("Sharang".to_string()),
}),
}
}
fn registry_tenant(status: &str) -> crate::registry::RegistryTenant {
crate::registry::RegistryTenant {
id: "00000000-0000-0000-0000-000000000002".to_string(),
slug: "faller".to_string(),
name: "Gebr. Faller".to_string(),
status: status.to_string(),
}
}
#[test]
fn the_registry_confirms_slug_and_status() {
let ctx = confirmed_support_context(support_ctx(), &registry_tenant("active"));
assert_eq!(ctx.tenant_slug, "faller");
assert_eq!(ctx.status, TenantStatus::Active);
}
#[test]
fn an_unknown_registry_status_stays_read_only() {
let ctx = confirmed_support_context(support_ctx(), &registry_tenant("something-new"));
assert_eq!(ctx.status, TenantStatus::Restricted);
}
#[test]
fn a_support_change_is_audited_without_its_content() {
let entry =
support_audit_entry(&support_ctx(), "PATCH", "/api/v1/findings/abc/status", 200);
assert_eq!(entry.tenant_id, "00000000-0000-0000-0000-000000000002");
assert_eq!(entry.action, "pruefwerk.support_access");
assert_eq!(entry.actor_id, "s-1");
assert_eq!(entry.actor_name, "BreakPilot-Support (Sharang)");
assert_eq!(
entry.metadata,
serde_json::json!({
"method": "PATCH",
"path": "/api/v1/findings/abc/status",
"status": 200
})
);
}
}