Files
pruefwerk/compliance-agent/src/api/server.rs
T
Sharang ParnerkarandClaude Opus 5.5 5ec891fa28
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 5m16s
CI / Check (pull_request) Successful in 22m0s
feat(supplier): the portal invites a supplier for one component (#1027)
Phase 3 of the supplier SBOM epic: the platform API the portal calls with its
service token to invite a supplier, list the tenant's invites and withdraw one.

- An invite is kept in the tenant's own database (`supplier_invites`), so the
  tenant export and erasure cover it, the supplier's address included. The
  portal owns the secret link and the mail and keys its link by the invite id.
- Only a supplier component (a target with `supplier`) can be invited for;
  any other answers 422, an unknown target or tenant 404, and a lookup in an
  unknown tenant creates no database.
- An invite is valid for 90 days and its state is `active`, `expired` or
  `withdrawn`; a second withdrawal keeps the first.
- Deleting a target deletes its invites.
- The portal's target list names each supplier component's `supplier`.

The upload through an invite follows in its own PR.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-18 11:35:50 +01:00

625 lines
24 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::handlers::supplier_invites;
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,
api_key: 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;
};
// An API key: the registry's verify answer already intersected its
// scopes with the tenant's entitlements and carried the ladder status.
if ctx.api_key.is_some() {
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 or an API key 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 either.
pub async fn audit_delegated_writes(
State(agent): State<Arc<ComplianceAgent>>,
request: Request,
next: Next,
) -> Response {
let staff_ctx = request
.extensions()
.get::<TenantContext>()
.filter(|c| c.staff.is_some() || c.api_key.is_some())
.cloned();
let method = request.method().clone();
let path = request.uri().path().to_string();
// Only the API host's proxy sets this header, and it overwrites whatever
// the caller sent; support requests arrive through the dashboard.
let client_ip = staff_ctx
.as_ref()
.filter(|c| c.api_key.is_some())
.and_then(|_| client_ip(request.headers()));
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 mut entry = delegated_audit_entry(&ctx, method.as_str(), &path, response.status().as_u16());
entry.source_ip = client_ip.map(|ip| ip.to_string()).unwrap_or_default();
tokio::spawn(async move {
if let Err(e) = registry.append_audit(&entry).await {
tracing::warn!(tenant_id = %entry.tenant_id, "write audit not recorded: {e}");
}
});
response
}
/// The header the API host's proxy puts the caller's address in
/// (orca-platform `pruefwerk-*/api-proxy.conf`).
const CLIENT_IP_HEADER: &str = "x-bp-client-ip";
/// The caller's address from [`CLIENT_IP_HEADER`], or `None` when it is
/// missing or not an IP address (the registry stores it as Postgres `inet`,
/// which would refuse the whole entry).
fn client_ip(headers: &axum::http::HeaderMap) -> Option<std::net::IpAddr> {
headers
.get(CLIENT_IP_HEADER)?
.to_str()
.ok()?
.trim()
.parse()
.ok()
}
/// The audit entry for a support or API-key request. The path names the
/// resource; the query and body are left out, as they may carry customer
/// data.
fn delegated_audit_entry(
ctx: &TenantContext,
method: &str,
path: &str,
status: u16,
) -> crate::registry::AuditEntry {
let action = if ctx.api_key.is_some() {
"pruefwerk.api_key_write"
} else {
"pruefwerk.support_access"
};
crate::registry::AuditEntry::by(
ctx,
action,
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),
)
// Supplier invites (#1027): the portal invites a supplier to upload
// one component's SBOM.
.route(
"/api/v1/platform/tenants/{id}/supplier-invites",
get(supplier_invites::list_invites).post(supplier_invites::create_invite),
)
.route(
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/withdraw",
post(supplier_invites::withdraw_invite),
)
.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()
.make_span_with(crate::api::trace::make_span)
.on_response(crate::api::trace::on_response),
)
// 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) → API key → JWT →
// org roles / key scopes → entitlement (registry) → support and key
// audit → status ladder → handlers.
app = app
.layer(middleware::from_fn(require_tenant_status))
.layer(middleware::from_fn_with_state(
shared.clone(),
audit_delegated_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(middleware::from_fn_with_state(
shared.clone(),
super::api_key_gate::require_api_key,
))
.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()),
}),
api_key: None,
}
}
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 the_client_ip_is_taken_only_when_it_is_an_address() {
let headers = |value: &str| {
let mut map = axum::http::HeaderMap::new();
map.insert(CLIENT_IP_HEADER, HeaderValue::from_str(value).unwrap());
map
};
assert_eq!(
client_ip(&headers(" 203.0.113.7 ")).map(|ip| ip.to_string()),
Some("203.0.113.7".to_string())
);
assert_eq!(
client_ip(&headers("2001:db8::1")).map(|ip| ip.to_string()),
Some("2001:db8::1".to_string())
);
assert_eq!(client_ip(&headers("203.0.113.7, 10.0.0.1")), None);
assert_eq!(client_ip(&headers("evil")), None);
assert_eq!(client_ip(&axum::http::HeaderMap::new()), None);
}
#[test]
fn a_support_change_is_audited_without_its_content() {
let entry =
delegated_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
})
);
}
}