feat(support): BreakPilot support can open any tenant, attributed and audited (#425)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 4m24s
CI / Deploy Dashboard (push) Successful in 6m0s
CI / Deploy Agent (push) Successful in 7m22s

This commit was merged in pull request #425.
This commit is contained in:
sharang committed 2026-09-29 07:37:12 +00:00
1 parent 6d8e63c226
commit 96d97ae6eb
33 files changed
+1465 -58

No files matched your search

+77 -12
View File
@@ -140,10 +140,34 @@ pub async fn get_finding(
/// The `$set` and `$push` of a status change by `user`, or 422 when a status
/// that needs a reason (an accepted risk, a wrong CRA mapping) comes without
/// one.
/// Who changes a finding, as its history records it.
struct Actor<'a> {
/// The Keycloak user id.
id: &'a str,
/// The name the customer reads; "BreakPilot-Support (name)" for support.
name: Option<String>,
/// BreakPilot support rather than one of the tenant's users.
support: bool,
}
impl<'a> Actor<'a> {
/// The requester of `ctx`.
fn of(ctx: &'a compliance_core::TenantContext) -> Self {
Self {
id: &ctx.user_id,
name: match &ctx.staff {
Some(staff) => Some(staff.label()),
None => ctx.user_name.clone(),
},
support: ctx.staff.is_some(),
}
}
}
fn status_update(
status: &FindingStatus,
reason: Option<&str>,
user: &str,
actor: &Actor<'_>,
) -> Result<mongodb::bson::Document, StatusCode> {
let reason = reason.map(str::trim).filter(|r| !r.is_empty());
if status.needs_reason() && reason.is_none() {
@@ -151,7 +175,9 @@ fn status_update(
}
let change = StatusChange {
status: status.clone(),
by: user.to_string(),
by: actor.id.to_string(),
by_name: actor.name.clone(),
support: actor.support,
at: chrono::Utc::now(),
reason: reason.map(String::from),
};
@@ -173,7 +199,7 @@ pub async fn update_finding_status(
Json(req): Json<UpdateStatusRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let oid = mongodb::bson::oid::ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
let update = status_update(&req.status, req.reason.as_deref(), &tenant.0.user_id)?;
let update = status_update(&req.status, req.reason.as_deref(), &Actor::of(&tenant.0))?;
let db = tenant_db(&agent, &tenant).await?;
let result = db
@@ -204,7 +230,7 @@ pub async fn bulk_update_finding_status(
if oids.is_empty() {
return Err(StatusCode::BAD_REQUEST);
}
let update = status_update(&req.status, req.reason.as_deref(), &tenant.0.user_id)?;
let update = status_update(&req.status, req.reason.as_deref(), &Actor::of(&tenant.0))?;
let db = tenant_db(&agent, &tenant).await?;
let result = db
@@ -246,26 +272,65 @@ mod tests {
#[test]
fn an_accepted_risk_needs_a_reason() {
assert_eq!(
status_update(&FindingStatus::AcceptedRisk, None, "u").err(),
status_update(&FindingStatus::AcceptedRisk, None, &user("u")).err(),
Some(StatusCode::UNPROCESSABLE_ENTITY)
);
assert_eq!(
status_update(&FindingStatus::AcceptedRisk, Some(" "), "u").err(),
status_update(&FindingStatus::AcceptedRisk, Some(" "), &user("u")).err(),
Some(StatusCode::UNPROCESSABLE_ENTITY)
);
assert!(status_update(&FindingStatus::AcceptedRisk, Some("isolated network"), "u").is_ok());
assert!(status_update(
&FindingStatus::AcceptedRisk,
Some("isolated network"),
&user("u")
)
.is_ok());
assert_eq!(
status_update(&FindingStatus::WrongMapping, None, "u").err(),
status_update(&FindingStatus::WrongMapping, None, &user("u")).err(),
Some(StatusCode::UNPROCESSABLE_ENTITY)
);
assert!(status_update(&FindingStatus::FalsePositive, None, "u").is_ok());
assert!(status_update(&FindingStatus::Resolved, None, "u").is_ok());
assert!(status_update(&FindingStatus::FalsePositive, None, &user("u")).is_ok());
assert!(status_update(&FindingStatus::Resolved, None, &user("u")).is_ok());
}
fn user(id: &str) -> Actor<'_> {
Actor {
id,
name: None,
support: false,
}
}
#[test]
fn a_change_by_support_is_marked_as_such() {
let actor = Actor {
id: "s-1",
name: Some("BreakPilot-Support (Sharang)".to_string()),
support: true,
};
let update = status_update(&FindingStatus::WrongMapping, Some("wrong control"), &actor)
.unwrap_or_default();
let change = update
.get_document("$push")
.and_then(|p| p.get_document("status_history"))
.cloned()
.unwrap_or_default();
assert_eq!(change.get_str("by").ok(), Some("s-1"));
assert_eq!(
change.get_str("by_name").ok(),
Some("BreakPilot-Support (Sharang)")
);
assert_eq!(change.get_bool("support").ok(), Some(true));
}
#[test]
fn a_change_sets_the_status_and_records_who_and_why() {
let update = status_update(&FindingStatus::AcceptedRisk, Some(" isolated "), "u-7")
.unwrap_or_default();
let update = status_update(
&FindingStatus::AcceptedRisk,
Some(" isolated "),
&user("u-7"),
)
.unwrap_or_default();
let set = update.get_document("$set").cloned().unwrap_or_default();
assert_eq!(set.get_str("status").ok(), Some("accepted_risk"));
let change = update
@@ -138,6 +138,8 @@ pub async fn create_finding(
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
let db = tenant_db(&agent, &tenant).await?;
// Shown on the finding: a name, or "BreakPilot-Support (name)".
let reported_by = tenant.0.actor_label();
require_target(&db, &id).await?;
let tool = req
.tool
@@ -147,7 +149,7 @@ pub async fn create_finding(
target_id: &id,
scan_type: req.kind.into(),
scanner: &tool,
reported_by: &tenant.0.user_id,
reported_by: &reported_by,
});
if !insert_new(&db, &mut finding).await? {
return Err(StatusCode::CONFLICT);
@@ -187,6 +189,8 @@ pub async fn import_findings(
StatusCode::UNPROCESSABLE_ENTITY
})?;
let db = tenant_db(&agent, &tenant).await?;
// Shown on the finding: a name, or "BreakPilot-Support (name)".
let reported_by = tenant.0.actor_label();
require_target(&db, &id).await?;
let mut summary = ImportSummary {
@@ -199,7 +203,7 @@ pub async fn import_findings(
target_id: &id,
scan_type: params.kind.into(),
scanner: &tool,
reported_by: &tenant.0.user_id,
reported_by: &reported_by,
});
if insert_new(&db, &mut finding).await? {
summary.imported += 1;
@@ -229,6 +233,7 @@ mod tests {
status: TenantStatus::Active,
user_id: "u".into(),
user_name: None,
staff: None,
})
}
+1
View File
@@ -19,6 +19,7 @@ pub mod platform;
pub use pentest_handlers as pentest;
pub mod sbom;
pub mod scans;
pub mod support;
pub mod target_input;
pub mod werkbank_jobs;
@@ -916,18 +916,17 @@ pub async fn trigger_target_scan(
let agent_clone = (*agent).clone();
let tenant_id = tenant.0.tenant_id.clone();
// A scan support starts is not the customer's usage.
let trigger = if tenant.0.staff.is_some() {
compliance_core::models::ScanTrigger::Support
} else {
compliance_core::models::ScanTrigger::Manual
};
tokio::spawn(async move {
// Always the unified target pipeline — this endpoint is about an
// onboarded target by construction, independent of the global
// `unified_pipeline` transition flag used by the legacy paths.
if let Err(e) = agent_clone
.run_target_scan(
&tenant_id,
&id,
compliance_core::models::ScanTrigger::Manual,
)
.await
{
if let Err(e) = agent_clone.run_target_scan(&tenant_id, &id, trigger).await {
tracing::error!("Manual target scan failed for {id}: {e}");
}
});
@@ -0,0 +1,103 @@
//! BreakPilot support access: the tenants support may open, and opening one.
//!
//! Support staff (Keycloak realm roles [`compliance_core::SUPPORT_ROLES`])
//! choose a tenant in the dashboard, which then names it in every request
//! (`X-Pruefwerk-Tenant`). The JWT middleware and `require_entitlement`
//! confirm the choice; these routes only list and open.
use axum::extract::Extension;
use axum::http::StatusCode;
use axum::Json;
use serde::Serialize;
use compliance_core::tenant_ctx::{StaffCtx, TenantCtx};
use super::dto::AgentExt;
use crate::registry::RegistryTenant;
/// A tenant as the support picker lists it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SupportTenant {
pub id: String,
pub slug: String,
pub name: String,
pub status: String,
}
impl From<RegistryTenant> for SupportTenant {
fn from(t: RegistryTenant) -> Self {
Self {
id: t.id,
slug: t.slug,
name: t.name,
status: t.status,
}
}
}
/// Order the picker by name (then slug), case-insensitively.
fn picker_order(mut tenants: Vec<SupportTenant>) -> Vec<SupportTenant> {
tenants.sort_by_cached_key(|t| (t.name.to_lowercase(), t.slug.clone()));
tenants
}
/// GET /api/v1/support/tenants — every tenant, for support to choose from.
/// 403 for anyone but support; 503 without a registry.
#[tracing::instrument(skip_all)]
pub async fn list_tenants(
Extension(agent): AgentExt,
StaffCtx(_staff): StaffCtx,
) -> Result<Json<serde_json::Value>, StatusCode> {
let registry = agent
.registry
.as_ref()
.ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
let tenants = registry.list_tenants().await.map_err(|e| {
tracing::error!("support tenant list failed: {e}");
StatusCode::SERVICE_UNAVAILABLE
})?;
let tenants = picker_order(tenants.into_iter().map(SupportTenant::from).collect());
Ok(Json(serde_json::json!({ "data": tenants })))
}
/// POST /api/v1/support/session — open the tenant named in the header. The
/// middleware has confirmed it with the registry and records the opening in
/// the audit log; this answers what was opened. 403 for anyone but support.
#[tracing::instrument(skip_all)]
pub async fn open_session(tenant: TenantCtx) -> Result<Json<serde_json::Value>, StatusCode> {
if tenant.0.staff.is_none() {
return Err(StatusCode::FORBIDDEN);
}
Ok(Json(serde_json::json!({
"data": {
"tenant_id": tenant.0.tenant_id,
"slug": tenant.0.tenant_slug,
"status": tenant.0.status,
}
})))
}
#[cfg(test)]
mod tests {
use super::*;
fn tenant(name: &str, slug: &str) -> SupportTenant {
SupportTenant {
id: format!("id-{slug}"),
slug: slug.to_string(),
name: name.to_string(),
status: "active".to_string(),
}
}
#[test]
fn the_picker_lists_tenants_by_name() {
let ordered = picker_order(vec![
tenant("Gebr. Faller", "faller"),
tenant("acme", "acme"),
tenant("Breakpilot Demo", "demo"),
]);
let names: Vec<&str> = ordered.iter().map(|t| t.name.as_str()).collect();
assert_eq!(names, ["acme", "Breakpilot Demo", "Gebr. Faller"]);
}
}
+9
View File
@@ -13,6 +13,15 @@ pub fn build_router() -> Router {
.route("/api/v1/health", get(handlers::health))
.route("/api/v1/oscal/assess", post(handlers::oscal::assess_target))
.route("/api/v1/stats/overview", get(handlers::stats_overview))
// BreakPilot support access: choose and open a customer's tenant.
.route(
"/api/v1/support/tenants",
get(handlers::support::list_tenants),
)
.route(
"/api/v1/support/session",
post(handlers::support::open_session),
)
// Unified onboarding targets (#131).
.route(
"/api/v1/targets",
+171 -2
View File
@@ -1,7 +1,7 @@
use std::sync::Arc;
use axum::extract::{DefaultBodyLimit, Request, State};
use axum::http::{HeaderValue, StatusCode};
use axum::http::{HeaderValue, Method, StatusCode};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use axum::routing::{delete, get, post};
@@ -52,6 +52,7 @@ pub async fn inject_dev_tenant(mut request: Request, next: Next) -> Response {
status: TenantStatus::Active,
user_id: "dev-user".to_string(),
user_name: None,
staff: None,
};
request.extensions_mut().insert(ctx);
}
@@ -67,6 +68,36 @@ pub async fn require_entitlement(
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
@@ -116,6 +147,78 @@ pub async fn require_entitlement(
}
}
/// 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 {
tenant_id: ctx.tenant_id.clone(),
action: "pruefwerk.support_access".to_string(),
actor_id: ctx.user_id.clone(),
actor_name: ctx.actor_label(),
metadata: 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() {
@@ -308,9 +411,13 @@ pub async fn start_api_server(
"Keycloak JWT auth enabled"
);
// Layers execute outermost-first: Extension(jwks) → JWT → entitlement
// (registry) → status ladder → handlers.
// (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,
@@ -350,3 +457,65 @@ pub async fn start_api_server(
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
})
);
}
}