From 96d97ae6ebbacc9544e9f0f4cd7ccc2bfb45a1f6 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Tue, 29 Sep 2026 07:37:12 +0000 Subject: [PATCH] feat(support): BreakPilot support can open any tenant, attributed and audited (#425) --- compliance-agent/src/agent.rs | 15 +- compliance-agent/src/api/handlers/findings.rs | 89 +++++++-- .../src/api/handlers/manual_findings.rs | 9 +- compliance-agent/src/api/handlers/mod.rs | 1 + .../src/api/handlers/onboarding.rs | 15 +- compliance-agent/src/api/handlers/support.rs | 103 ++++++++++ compliance-agent/src/api/routes.rs | 9 + compliance-agent/src/api/server.rs | 173 ++++++++++++++++- compliance-agent/src/pipeline/orchestrator.rs | 2 +- compliance-agent/src/registry.rs | 53 ++++++ compliance-agent/tests/tenant_isolation.rs | 1 + .../tests/tenant_status_middleware.rs | 49 +++++ compliance-core/src/auth.rs | 179 +++++++++++++++++- compliance-core/src/db.rs | 1 + compliance-core/src/lib.rs | 4 +- compliance-core/src/models/auth.rs | 16 ++ compliance-core/src/models/finding.rs | 7 + compliance-core/src/models/mod.rs | 2 +- compliance-core/src/models/repository.rs | 14 ++ compliance-core/src/tenant.rs | 42 ++++ compliance-core/src/tenant_ctx.rs | 112 ++++++++++- compliance-dashboard/assets/main.css | 167 ++++++++++++++++ .../src/components/app_shell.rs | 12 ++ compliance-dashboard/src/components/mod.rs | 1 + .../src/components/support.rs | 144 ++++++++++++++ compliance-dashboard/src/i18n/texts.rs | 48 +++++ .../src/infrastructure/agent_client.rs | 17 +- .../src/infrastructure/auth.rs | 5 +- .../src/infrastructure/auth_check.rs | 9 +- .../src/infrastructure/mod.rs | 1 + .../src/infrastructure/support.rs | 144 ++++++++++++++ .../src/infrastructure/user_state.rs | 73 +++++-- .../src/pages/finding_detail.rs | 6 +- 33 files changed, 1465 insertions(+), 58 deletions(-) create mode 100644 compliance-agent/src/api/handlers/support.rs create mode 100644 compliance-dashboard/src/components/support.rs create mode 100644 compliance-dashboard/src/infrastructure/support.rs diff --git a/compliance-agent/src/agent.rs b/compliance-agent/src/agent.rs index 5dfb499..dadc9f5 100644 --- a/compliance-agent/src/agent.rs +++ b/compliance-agent/src/agent.rs @@ -191,12 +191,15 @@ impl ComplianceAgent { ); let started = chrono::Utc::now(); orchestrator.run_target(target_id, trigger.clone()).await?; - self.emit_usage( - tenant_id, - "scan.completed", - format!("scan:{tenant_id}:{target_id}:{}", started.timestamp()), - serde_json::json!({ "target_id": target_id, "trigger": format!("{trigger:?}") }), - ); + // Support's scans are ours, not the customer's usage. + if trigger != compliance_core::models::ScanTrigger::Support { + self.emit_usage( + tenant_id, + "scan.completed", + format!("scan:{tenant_id}:{target_id}:{}", started.timestamp()), + serde_json::json!({ "target_id": target_id, "trigger": format!("{trigger:?}") }), + ); + } self.notify_new_findings(tenant_id, target_id, &db, started); Ok(()) } diff --git a/compliance-agent/src/api/handlers/findings.rs b/compliance-agent/src/api/handlers/findings.rs index 1314458..b605669 100644 --- a/compliance-agent/src/api/handlers/findings.rs +++ b/compliance-agent/src/api/handlers/findings.rs @@ -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, + /// 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 { 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, ) -> Result, 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 diff --git a/compliance-agent/src/api/handlers/manual_findings.rs b/compliance-agent/src/api/handlers/manual_findings.rs index 8da3830..e0d4a17 100644 --- a/compliance-agent/src/api/handlers/manual_findings.rs +++ b/compliance-agent/src/api/handlers/manual_findings.rs @@ -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, }) } diff --git a/compliance-agent/src/api/handlers/mod.rs b/compliance-agent/src/api/handlers/mod.rs index 25f47d8..bda9acf 100644 --- a/compliance-agent/src/api/handlers/mod.rs +++ b/compliance-agent/src/api/handlers/mod.rs @@ -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; diff --git a/compliance-agent/src/api/handlers/onboarding.rs b/compliance-agent/src/api/handlers/onboarding.rs index 874192a..96c0431 100644 --- a/compliance-agent/src/api/handlers/onboarding.rs +++ b/compliance-agent/src/api/handlers/onboarding.rs @@ -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}"); } }); diff --git a/compliance-agent/src/api/handlers/support.rs b/compliance-agent/src/api/handlers/support.rs new file mode 100644 index 0000000..5ebb86d --- /dev/null +++ b/compliance-agent/src/api/handlers/support.rs @@ -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 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) -> Vec { + 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, 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, 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"]); + } +} diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index fcb46f6..1405e86 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -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", diff --git a/compliance-agent/src/api/server.rs b/compliance-agent/src/api/server.rs index 56ab651..b5a8037 100644 --- a/compliance-agent/src/api/server.rs +++ b/compliance-agent/src/api/server.rs @@ -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::() + .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>, + request: Request, + next: Next, +) -> Response { + let staff_ctx = request + .extensions() + .get::() + .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(), ®istry_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(), ®istry_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 + }) + ); + } +} diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 84c77b8..fecdf91 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -91,7 +91,7 @@ impl PipelineOrchestrator { // A scheduled or webhook scan of an unchanged repository has nothing // new to find; one a person started always runs (after an update of // Prüfwerk itself, or a changed setting, it can find something else). - if *trigger != ScanTrigger::Manual + if !trigger.started_by_person() && !GitOps::has_new_commits(&repo_path, repo.last_scanned_commit.as_deref())? { tracing::info!("[{repo_id}] No new commits, skipping scan"); diff --git a/compliance-agent/src/registry.rs b/compliance-agent/src/registry.rs index 2a87a04..6a8c6cc 100644 --- a/compliance-agent/src/registry.rs +++ b/compliance-agent/src/registry.rs @@ -47,10 +47,24 @@ pub struct RegistryTenant { pub id: String, #[serde(default)] pub slug: String, + /// The organisation's name, for the support tenant picker. + #[serde(default)] + pub name: String, #[serde(default)] pub status: String, } +/// One entry of the platform's audit log (`POST /v1/audit`). +#[derive(Debug, Clone, PartialEq, serde::Serialize)] +pub struct AuditEntry { + pub tenant_id: String, + /// What happened, e.g. `pruefwerk.support_access`. + pub action: String, + pub actor_id: String, + pub actor_name: String, + pub metadata: serde_json::Value, +} + #[derive(Debug, Clone, Deserialize)] pub struct ApiKeyVerify { pub valid: bool, @@ -279,6 +293,45 @@ impl RegistryClient { Ok(out) } + /// One tenant (`GET /v1/tenants/{id}`); `Ok(None)` when the registry + /// does not know it. Errors mean "unknown": callers fail closed. + pub async fn get_tenant(&self, tenant_id: &str) -> Result, String> { + let resp = self + .request( + reqwest::Method::GET, + &format!("/v1/tenants/{}", urlencoding::encode(tenant_id)), + ) + .await? + .send() + .await + .map_err(|e| format!("tenant lookup failed: {e}"))?; + if resp.status() == reqwest::StatusCode::NOT_FOUND { + return Ok(None); + } + if !resp.status().is_success() { + return Err(format!("tenant lookup returned {}", resp.status())); + } + resp.json() + .await + .map(Some) + .map_err(|e| format!("tenant lookup invalid: {e}")) + } + + /// Append to the platform's audit log. + pub async fn append_audit(&self, entry: &AuditEntry) -> Result<(), String> { + let resp = self + .request(reqwest::Method::POST, "/v1/audit") + .await? + .json(entry) + .send() + .await + .map_err(|e| format!("audit append failed: {e}"))?; + if !resp.status().is_success() { + return Err(format!("audit append returned {}", resp.status())); + } + Ok(()) + } + /// Verify a portal-issued API key (`bp_…`). pub async fn verify_api_key(&self, key: &str) -> Result { let resp = self diff --git a/compliance-agent/tests/tenant_isolation.rs b/compliance-agent/tests/tenant_isolation.rs index d9f0f12..0186a16 100644 --- a/compliance-agent/tests/tenant_isolation.rs +++ b/compliance-agent/tests/tenant_isolation.rs @@ -25,6 +25,7 @@ fn ctx(tenant_id: &str, slug: &str) -> TenantContext { status: TenantStatus::Active, user_id: "u-1".to_string(), user_name: None, + staff: None, } } diff --git a/compliance-agent/tests/tenant_status_middleware.rs b/compliance-agent/tests/tenant_status_middleware.rs index b1a2fec..248707e 100644 --- a/compliance-agent/tests/tenant_status_middleware.rs +++ b/compliance-agent/tests/tenant_status_middleware.rs @@ -28,6 +28,7 @@ fn ctx_with(status: TenantStatus) -> TenantContext { status, user_id: "u-1".to_string(), user_name: None, + staff: None, } } @@ -167,3 +168,51 @@ async fn ladder_warning_passes_restricted_blocks_writes_halted_blocks_all() { .await; assert_eq!(r.status(), StatusCode::GONE); } + +fn support_ctx(status: TenantStatus) -> TenantContext { + TenantContext { + staff: Some(compliance_core::StaffAccess { + user_id: "s-1".to_string(), + user_name: Some("Support".to_string()), + }), + ..ctx_with(status) + } +} + +/// Support access follows the tenant's ladder like its own users: an +/// archived tenant is gone, a halted one closed, a restricted one read-only. +#[tokio::test] +async fn support_access_follows_the_ladder() { + let archived = call( + router_with_ctx(Some(support_ctx(TenantStatus::Archived))), + Method::GET, + "/r", + ) + .await; + assert_eq!(archived.status(), StatusCode::GONE); + + let halted = call( + router_with_ctx(Some(support_ctx(TenantStatus::Halted))), + Method::GET, + "/r", + ) + .await; + assert_eq!(halted.status(), StatusCode::PAYMENT_REQUIRED); + + // The placeholder before the registry confirms the tenant is read-only. + let unconfirmed = call( + router_with_ctx(Some(support_ctx(TenantStatus::Restricted))), + Method::POST, + "/w", + ) + .await; + assert_eq!(unconfirmed.status(), StatusCode::PAYMENT_REQUIRED); + + let active = call( + router_with_ctx(Some(support_ctx(TenantStatus::Active))), + Method::POST, + "/w", + ) + .await; + assert_eq!(active.status(), StatusCode::OK); +} diff --git a/compliance-core/src/auth.rs b/compliance-core/src/auth.rs index d5f0e5d..b26de7d 100644 --- a/compliance-core/src/auth.rs +++ b/compliance-core/src/auth.rs @@ -14,6 +14,13 @@ //! * Signature / expiry invalid → 401. //! * Claims present but tenant_id missing → 401 (treated as a malformed //! token; the realm must always issue tenant_id). +//! +//! Support access: a token carrying one of [`SUPPORT_ROLES`] (BreakPilot +//! staff) may name the tenant to act in with the [`SUPPORT_TENANT_HEADER`]. +//! The context is then marked as staff access and left read-only until the +//! agent has confirmed the tenant with the registry. Staff without a chosen +//! tenant get only a [`StaffAccess`] extension, which no tenant-scoped handler +//! accepts. For every other token the header is ignored. use std::sync::Arc; @@ -28,7 +35,8 @@ use reqwest::StatusCode; use serde::Deserialize; use tokio::sync::RwLock; -use crate::{OrgRole, TenantContext, TenantStatus}; +use crate::tenant::SUPPORT_TENANT_HEADER; +use crate::{OrgRole, StaffAccess, TenantContext, TenantStatus, SUPPORT_ROLES}; /// Cached JWKS from Keycloak for token validation. /// @@ -86,6 +94,25 @@ struct Claims { tenant_status: Option, #[serde(default)] azp: Option, + /// Keycloak realm roles; staff roles live here, not in `org_roles`. + #[serde(default)] + realm_access: Option, +} + +/// The `realm_access` claim. +#[derive(Debug, Default, Deserialize)] +struct RealmAccess { + #[serde(default)] + roles: Vec, +} + +/// What a validated token grants. +#[derive(Debug)] +enum Authenticated { + /// Access to one tenant: the user's own, or the one support chose. + Tenant(TenantContext), + /// A staff member who has not chosen a tenant yet. + StaffWithoutTenant(StaffAccess), } /// Upper bound on a JWKS fetch. The cache write lock is held for its @@ -131,11 +158,20 @@ pub async fn require_jwt_auth(mut request: Request, next: Next) -> Response { _ => return (StatusCode::UNAUTHORIZED, "Invalid authorization header").into_response(), }; - match validate_token(token, &jwks_state).await { - Ok(ctx) => { + let requested_tenant = request + .headers() + .get(SUPPORT_TENANT_HEADER) + .and_then(|v| v.to_str().ok()) + .map(str::to_owned); + match validate_token(token, &jwks_state, requested_tenant.as_deref()).await { + Ok(Authenticated::Tenant(ctx)) => { request.extensions_mut().insert(ctx); next.run(request).await } + Ok(Authenticated::StaffWithoutTenant(staff)) => { + request.extensions_mut().insert(staff); + next.run(request).await + } Err(e) => { tracing::warn!("JWT validation failed: {e}"); (StatusCode::UNAUTHORIZED, "Invalid token").into_response() @@ -211,8 +247,70 @@ fn is_write(m: &Method) -> bool { !matches!(m, &Method::GET | &Method::HEAD | &Method::OPTIONS) } -async fn validate_token(token: &str, state: &JwksState) -> Result { - claims_to_context(decode_claims(token, state).await?) +async fn validate_token( + token: &str, + state: &JwksState, + requested_tenant: Option<&str>, +) -> Result { + authenticate(decode_claims(token, state).await?, requested_tenant) +} + +/// Decide what validated `claims` grant, given the tenant a support user +/// asked for (`requested_tenant`, from [`SUPPORT_TENANT_HEADER`]). +/// +/// # Errors +/// +/// A customer token without a tenant, or a support request naming something +/// that is not a registry tenant id. +fn authenticate(c: Claims, requested_tenant: Option<&str>) -> Result { + let is_staff = c.realm_access.as_ref().is_some_and(|r| { + r.roles + .iter() + .any(|role| SUPPORT_ROLES.contains(&role.as_str())) + }); + if !is_staff { + if requested_tenant.is_some_and(|t| t != c.tenant_id) { + tracing::warn!(sub = %c.sub, "tenant header from a non-support token ignored"); + } + return claims_to_context(c).map(Authenticated::Tenant); + } + let staff = StaffAccess { + user_id: c.sub.clone(), + user_name: c.name.clone().or_else(|| c.preferred_username.clone()), + }; + match requested_tenant { + Some(tenant_id) => { + // It becomes part of a database name: only a registry id passes. + if !is_registry_id(tenant_id) { + return Err("support tenant header is not a tenant id".to_string()); + } + Ok(Authenticated::Tenant(TenantContext { + tenant_id: tenant_id.to_string(), + // Filled in, with the real status, once the agent has asked + // the registry; until then nothing may be written. + tenant_slug: String::new(), + org_roles: vec![OrgRole::ItAdmin], + products: Vec::new(), + plan: String::new(), + status: TenantStatus::Restricted, + user_id: staff.user_id.clone(), + user_name: staff.user_name.clone(), + staff: Some(staff), + })) + } + // Staff who also belong to a tenant work in it like anyone else. + None if !c.tenant_id.is_empty() => claims_to_context(c).map(Authenticated::Tenant), + None => Ok(Authenticated::StaffWithoutTenant(staff)), + } +} + +/// Whether `s` has the shape of a registry tenant id (a UUID). +fn is_registry_id(s: &str) -> bool { + s.len() == 36 + && s.char_indices().all(|(i, c)| match i { + 8 | 13 | 18 | 23 => c == '-', + _ => c.is_ascii_hexdigit(), + }) } /// Decode + verify a token against the cached JWKS (refreshing once on a @@ -332,6 +430,7 @@ fn claims_to_context(c: Claims) -> Result { status, user_id: c.sub, user_name: c.name.or(c.preferred_username), + staff: None, }) } @@ -392,6 +491,76 @@ mod tests { plan: "professional".to_string(), tenant_status: Some(TenantStatus::Active), azp: Some("pruefwerk-dashboard-stage".to_string()), + realm_access: None, + } + } + + const OTHER_TENANT: &str = "00000000-0000-0000-0000-000000000002"; + + fn staff_claims() -> Claims { + let mut c = base_claims(); + c.tenant_id = String::new(); + c.tenant_slug = String::new(); + c.org_roles = Vec::new(); + c.name = Some("Sharang Parnerkar".to_string()); + c.realm_access = Some(RealmAccess { + roles: vec!["offline_access".to_string(), "SUPPORT_ENGINEER".to_string()], + }); + c + } + + #[test] + fn a_customer_cannot_switch_tenants_with_the_header() { + let outcome = authenticate(base_claims(), Some(OTHER_TENANT)).expect("should map"); + let Authenticated::Tenant(ctx) = outcome else { + panic!("expected the customer's own tenant"); + }; + assert_eq!(ctx.tenant_id, "00000000-0000-0000-0000-000000000001"); + assert_eq!(ctx.staff, None); + } + + #[test] + fn support_opens_the_tenant_it_names_read_only_until_confirmed() { + let outcome = authenticate(staff_claims(), Some(OTHER_TENANT)).expect("should map"); + let Authenticated::Tenant(ctx) = outcome else { + panic!("expected a tenant context"); + }; + assert_eq!(ctx.tenant_id, OTHER_TENANT); + assert_eq!(ctx.status, TenantStatus::Restricted); + assert_eq!(ctx.user_id, "user-123"); + let staff = ctx.staff.expect("marked as support"); + assert_eq!(staff.label(), "BreakPilot-Support (Sharang Parnerkar)"); + } + + #[test] + fn both_staff_roles_grant_support_access() { + for role in SUPPORT_ROLES { + let mut c = staff_claims(); + c.realm_access = Some(RealmAccess { + roles: vec![role.to_string()], + }); + assert!(matches!( + authenticate(c, Some(OTHER_TENANT)), + Ok(Authenticated::Tenant(TenantContext { staff: Some(_), .. })) + )); + } + } + + #[test] + fn support_without_a_chosen_tenant_gets_no_tenant() { + let outcome = authenticate(staff_claims(), None).expect("should map"); + assert!(matches!(outcome, Authenticated::StaffWithoutTenant(_))); + } + + #[test] + fn a_malformed_tenant_header_is_refused() { + for bad in [ + "../admin", + "acme", + "00000000-0000-0000-0000-00000000000g", + "", + ] { + assert!(authenticate(staff_claims(), Some(bad)).is_err(), "{bad}"); } } diff --git a/compliance-core/src/db.rs b/compliance-core/src/db.rs index f9d550f..80e3bcd 100644 --- a/compliance-core/src/db.rs +++ b/compliance-core/src/db.rs @@ -46,6 +46,7 @@ mod tests { status: TenantStatus::Active, user_id: "u-1".to_string(), user_name: None, + staff: None, } } diff --git a/compliance-core/src/lib.rs b/compliance-core/src/lib.rs index 0b4b83a..303902c 100644 --- a/compliance-core/src/lib.rs +++ b/compliance-core/src/lib.rs @@ -27,4 +27,6 @@ pub use config::{AgentConfig, AppEnv, DashboardConfig, Features, PlcRuntimeConfi pub use error::CoreError; pub use exec_policy::ExecPolicy; pub use net_guard::{NetGuard, NetGuardError}; -pub use tenant::{OrgRole, TenantContext, TenantStatus}; +pub use tenant::{ + OrgRole, StaffAccess, TenantContext, TenantStatus, SUPPORT_ROLES, SUPPORT_TENANT_HEADER, +}; diff --git a/compliance-core/src/models/auth.rs b/compliance-core/src/models/auth.rs index 08046c0..f1c1dab 100644 --- a/compliance-core/src/models/auth.rs +++ b/compliance-core/src/models/auth.rs @@ -18,4 +18,20 @@ pub struct AuthInfo { /// The docs site this deployment links to from the sidebar. #[serde(default)] pub docs_url: String, + /// Holds a BreakPilot support role, so may open any tenant. + #[serde(default)] + pub staff: bool, + /// The customer tenant support has opened; `None` for everyone else and + /// for support before choosing one. + #[serde(default)] + pub support_tenant: Option, +} + +/// A customer tenant opened by BreakPilot support. +#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)] +pub struct SupportTenant { + /// The registry's tenant id, sent to the agent with every request. + pub id: String, + pub slug: String, + pub name: String, } diff --git a/compliance-core/src/models/finding.rs b/compliance-core/src/models/finding.rs index 96da184..36c8ade 100644 --- a/compliance-core/src/models/finding.rs +++ b/compliance-core/src/models/finding.rs @@ -77,6 +77,13 @@ pub struct StatusChange { pub status: FindingStatus, /// The user id of whoever changed it. pub by: String, + /// How the customer reads who it was: a name, or "BreakPilot-Support + /// (name)"; absent in changes from before it was recorded. + #[serde(default)] + pub by_name: Option, + /// Made by BreakPilot support rather than one of the tenant's users. + #[serde(default)] + pub support: bool, #[serde(with = "super::serde_helpers::bson_datetime")] pub at: DateTime, /// Why; required when a risk is accepted. diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index fdabbce..bc8cb61 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -20,7 +20,7 @@ pub mod scan; pub(crate) mod serde_helpers; pub mod werkbank; -pub use auth::AuthInfo; +pub use auth::{AuthInfo, SupportTenant}; pub use chat::{ChatMessage, ChatRequest, ChatResponse, SourceReference}; pub use credentials::Credentials; pub use cve::{CveAlert, CveSource}; diff --git a/compliance-core/src/models/repository.rs b/compliance-core/src/models/repository.rs index fe5212e..df190fa 100644 --- a/compliance-core/src/models/repository.rs +++ b/compliance-core/src/models/repository.rs @@ -7,4 +7,18 @@ pub enum ScanTrigger { Scheduled, Webhook, Manual, + /// Started by BreakPilot support in the customer's tenant; not counted + /// as the customer's usage. + Support, +} + +impl ScanTrigger { + /// Whether a person started the scan (the customer or support), so it + /// runs even when nothing changed since the last one. + pub fn started_by_person(&self) -> bool { + match self { + Self::Manual | Self::Support => true, + Self::Scheduled | Self::Webhook => false, + } + } } diff --git a/compliance-core/src/tenant.rs b/compliance-core/src/tenant.rs index 47a2a7e..9f7b37a 100644 --- a/compliance-core/src/tenant.rs +++ b/compliance-core/src/tenant.rs @@ -118,6 +118,33 @@ impl OrgRole { } } +/// Keycloak realm roles of BreakPilot staff who may open any tenant for +/// support (covered by the AVV). Granted through the company sign-in. +pub const SUPPORT_ROLES: &[&str] = &["BREAKPILOT_ADMIN", "SUPPORT_ENGINEER"]; + +/// Header in which a BreakPilot support user names the tenant to act in. +pub const SUPPORT_TENANT_HEADER: &str = "x-pruefwerk-tenant"; + +/// A BreakPilot staff member acting in a customer's tenant (support access). +/// Everything they change is recorded under their own identity. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct StaffAccess { + /// Keycloak user id of the staff member (`sub`). + pub user_id: String, + /// Their name, for the history and the audit log. + pub user_name: Option, +} + +impl StaffAccess { + /// How the customer sees this person in a finding's history. + pub fn label(&self) -> String { + match self.user_name.as_deref().filter(|n| !n.trim().is_empty()) { + Some(name) => format!("BreakPilot-Support ({name})"), + None => "BreakPilot-Support".to_string(), + } + } +} + /// Everything we know about the requesting tenant at the moment a request /// lands. Cheap to clone (every field is owned + small). #[derive(Debug, Clone, Serialize, Deserialize)] @@ -143,9 +170,23 @@ pub struct TenantContext { /// Optional user-facing name from the `name` / `preferred_username` /// claim. Only used in audit + log lines. pub user_name: Option, + /// Set when BreakPilot support opened this tenant, rather than one of + /// its own users. `user_id` is then the staff member's id. + #[serde(default)] + pub staff: Option, } impl TenantContext { + /// Who did something, as the customer reads it: the support label for + /// staff, else the user's name, else their id. + pub fn actor_label(&self) -> String { + match (&self.staff, self.user_name.as_deref()) { + (Some(staff), _) => staff.label(), + (None, Some(name)) if !name.trim().is_empty() => name.to_string(), + (None, _) => self.user_id.clone(), + } + } + /// True if the caller holds at least one of the listed roles. pub fn has_any_role(&self, roles: &[OrgRole]) -> bool { self.org_roles.iter().any(|r| roles.contains(r)) @@ -197,6 +238,7 @@ mod tests { status: TenantStatus::Active, user_id: "u".into(), user_name: None, + staff: None, }; assert!(ctx.has_any_role(&[OrgRole::ItAdmin])); assert!(ctx.has_any_role(&[OrgRole::Cxo, OrgRole::ItAdmin])); diff --git a/compliance-core/src/tenant_ctx.rs b/compliance-core/src/tenant_ctx.rs index d528fa3..f6f9201 100644 --- a/compliance-core/src/tenant_ctx.rs +++ b/compliance-core/src/tenant_ctx.rs @@ -20,24 +20,79 @@ use axum::{ response::{IntoResponse, Response}, }; -use crate::TenantContext; +use crate::{StaffAccess, TenantContext}; + +/// What a support user without a chosen tenant is told by a tenant-scoped +/// route. Distinct from an expired sign-in, so the dashboard asks for a +/// tenant instead of sending the user back to the login. +pub const TENANT_NOT_SELECTED: &str = "tenant_not_selected"; #[derive(Debug, Clone)] pub struct TenantCtx(pub TenantContext); +/// Why a tenant-scoped route refused the request. #[derive(Debug)] -pub struct TenantCtxRejection; +pub enum TenantCtxRejection { + /// No authenticated tenant at all. + Unauthenticated, + /// BreakPilot support, signed in, with no tenant chosen yet. + TenantNotSelected, +} impl IntoResponse for TenantCtxRejection { + fn into_response(self) -> Response { + match self { + Self::Unauthenticated => ( + StatusCode::UNAUTHORIZED, + "Missing tenant context — request was not authenticated", + ) + .into_response(), + Self::TenantNotSelected => ( + StatusCode::PRECONDITION_REQUIRED, + axum::Json(serde_json::json!({ "error": TENANT_NOT_SELECTED })), + ) + .into_response(), + } + } +} + +/// A BreakPilot support user, with or without a chosen tenant. For the +/// support routes (the tenant list); 403 for everyone else. +#[derive(Debug, Clone)] +pub struct StaffCtx(pub StaffAccess); + +/// A request that is not from BreakPilot support. +#[derive(Debug)] +pub struct StaffCtxRejection; + +impl IntoResponse for StaffCtxRejection { fn into_response(self) -> Response { ( - StatusCode::UNAUTHORIZED, - "Missing tenant context — request was not authenticated", + StatusCode::FORBIDDEN, + axum::Json(serde_json::json!({ "error": "support_only" })), ) .into_response() } } +impl FromRequestParts for StaffCtx +where + S: Send + Sync, +{ + type Rejection = StaffCtxRejection; + + async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result { + let chosen = parts + .extensions + .get::() + .and_then(|ctx| ctx.staff.clone()); + chosen + .or_else(|| parts.extensions.get::().cloned()) + .map(StaffCtx) + .ok_or(StaffCtxRejection) + } +} + impl FromRequestParts for TenantCtx where S: Send + Sync, @@ -50,7 +105,13 @@ where .get::() .cloned() .map(TenantCtx) - .ok_or(TenantCtxRejection) + .ok_or_else(|| { + if parts.extensions.get::().is_some() { + TenantCtxRejection::TenantNotSelected + } else { + TenantCtxRejection::Unauthenticated + } + }) } } @@ -71,6 +132,7 @@ mod tests { status: TenantStatus::Active, user_id: "u-1".to_string(), user_name: None, + staff: None, } } @@ -92,4 +154,44 @@ mod tests { let err = TenantCtx::from_request_parts(&mut parts, &()).await; assert!(err.is_err()); } + + fn staff() -> StaffAccess { + StaffAccess { + user_id: "s-1".to_string(), + user_name: Some("Support".to_string()), + } + } + + #[tokio::test] + async fn support_without_a_tenant_is_asked_to_choose_one() { + let mut req = Request::new(()); + req.extensions_mut().insert(staff()); + let (mut parts, _) = req.into_parts(); + let err = TenantCtx::from_request_parts(&mut parts, &()).await; + assert!(matches!(err, Err(TenantCtxRejection::TenantNotSelected))); + } + + #[tokio::test] + async fn only_support_passes_the_staff_extractor() { + let mut customer = Request::new(()); + customer.extensions_mut().insert(ctx()); + let (mut parts, _) = customer.into_parts(); + assert!(StaffCtx::from_request_parts(&mut parts, &()).await.is_err()); + + let mut chosen = Request::new(()); + chosen.extensions_mut().insert(TenantContext { + staff: Some(staff()), + ..ctx() + }); + let (mut parts, _) = chosen.into_parts(); + let StaffCtx(found) = StaffCtx::from_request_parts(&mut parts, &()) + .await + .expect("support with a tenant"); + assert_eq!(found.user_id, "s-1"); + + let mut unchosen = Request::new(()); + unchosen.extensions_mut().insert(staff()); + let (mut parts, _) = unchosen.into_parts(); + assert!(StaffCtx::from_request_parts(&mut parts, &()).await.is_ok()); + } } diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index 3550b69..5a158d9 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -5204,3 +5204,170 @@ input[type="file"] { color: var(--text-secondary); font-size: 13px; } + +/* ═══════════════════════════════════════════════════════════════ + SUPPORT ACCESS — tenant picker and banner for BreakPilot staff + ═══════════════════════════════════════════════════════════════ */ +.support-picker { + min-height: 100vh; + display: flex; + align-items: flex-start; + justify-content: center; + padding: 64px 16px; + background: var(--bg-primary); +} +.support-picker-card { + width: 100%; + max-width: 640px; + background: var(--bg-secondary); + border: 1px solid var(--border); + border-radius: 16px; + padding: 28px; + box-shadow: var(--shadow-pop); +} +.support-picker-head { + display: flex; + align-items: center; + gap: 10px; +} +.support-picker-head h1 { + margin: 0; + font-family: var(--font-display); + font-size: 22px; +} +.support-picker-mark { + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + border-radius: 10px; + background: var(--accent-muted); + color: var(--accent); +} +.support-picker-intro { + color: var(--text-secondary); + font-size: 14px; + margin: 10px 0 18px; +} +.support-picker-search { + display: flex; + align-items: center; + gap: 8px; + border: 1px solid var(--border); + border-radius: 10px; + padding: 0 12px; + background: var(--bg-elevated); + color: var(--text-tertiary); +} +.support-picker-search:focus-within { + border-color: var(--accent); +} +.support-picker-search input { + flex: 1; + border: none; + background: transparent; + padding: 10px 0; + font: inherit; + color: var(--text-primary); + outline: none; +} +.support-picker-list { + list-style: none; + margin: 14px 0 0; + padding: 0; + display: grid; + gap: 6px; + max-height: 60vh; + overflow-y: auto; +} +.support-picker-row { + width: 100%; + display: grid; + grid-template-columns: 1fr auto auto auto; + align-items: center; + gap: 12px; + text-align: left; + background: var(--bg-elevated); + border: 1px solid var(--border); + border-radius: 10px; + padding: 10px 14px; + font: inherit; + color: var(--text-primary); + cursor: pointer; + transition: border-color 0.15s, background 0.15s; +} +.support-picker-row:not(:disabled):hover { + border-color: var(--accent); + background: var(--accent-muted); +} +.support-picker-row:disabled { + cursor: wait; + opacity: 0.7; +} +.support-picker-name { + font-weight: 600; +} +.support-picker-slug, +.support-picker-status { + font-family: var(--font-mono); + font-size: 12px; + color: var(--text-tertiary); +} +.support-picker-open { + color: var(--accent); + font-size: 13px; + font-weight: 600; +} +.support-picker-note { + color: var(--text-secondary); + font-size: 14px; +} +.support-picker-error { + color: var(--danger); + font-size: 14px; +} +@media (max-width: 560px) { + .support-picker-row { grid-template-columns: 1fr auto; } + .support-picker-slug, + .support-picker-status { display: none; } +} + +.support-banner { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 8px 12px; + margin: -8px 0 16px; + padding: 8px 14px; + border-radius: 10px; + background: var(--warning-bg, var(--accent-muted)); + border: 1px solid color-mix(in oklch, var(--warning, var(--accent)) 45%, var(--border)); + color: var(--text-primary); + font-size: 13px; +} +.support-banner-note { + color: var(--text-secondary); +} +.support-banner-switch { + margin-left: auto; + display: inline-flex; + align-items: center; + gap: 6px; + background: var(--bg-secondary); + border: 1px solid var(--border); + border-radius: 8px; + padding: 4px 10px; + font: inherit; + font-size: 12px; + color: var(--text-primary); + cursor: pointer; +} +.support-banner-switch:hover { + border-color: var(--accent); +} + +.history-by-support { + color: var(--accent); + font-weight: 600; +} diff --git a/compliance-dashboard/src/components/app_shell.rs b/compliance-dashboard/src/components/app_shell.rs index 764f641..92e54b3 100644 --- a/compliance-dashboard/src/components/app_shell.rs +++ b/compliance-dashboard/src/components/app_shell.rs @@ -4,6 +4,7 @@ use crate::app::Route; use crate::components::help_chat::HelpChat; use crate::components::notification_bell::NotificationBell; use crate::components::sidebar::Sidebar; +use crate::components::support::{SupportBanner, SupportPicker}; use crate::components::toast::{ToastContainer, Toasts}; use crate::infrastructure::auth_check::check_auth; use crate::infrastructure::platform::fetch_platform_info; @@ -41,12 +42,23 @@ pub fn AppShell() -> Element { }); match auth() { + // BreakPilot support chooses a tenant first: every page asks the agent + // for one, and without it would only be refused. + Some(Ok(info)) if info.authenticated && info.staff && info.support_tenant.is_none() => { + rsx! { + SupportPicker {} + ToastContainer {} + } + } Some(Ok(info)) if info.authenticated => { use_context_provider(|| Signal::new(info.clone())); rsx! { div { class: "app-shell", Sidebar {} main { class: "main-content", + if let Some(tenant) = info.support_tenant.clone() { + SupportBanner { tenant } + } Outlet:: {} } NotificationBell {} diff --git a/compliance-dashboard/src/components/mod.rs b/compliance-dashboard/src/components/mod.rs index 0a5a010..e3589b7 100644 --- a/compliance-dashboard/src/components/mod.rs +++ b/compliance-dashboard/src/components/mod.rs @@ -20,5 +20,6 @@ pub mod scan_coverage; pub mod scan_runs; pub mod severity_badge; pub mod sidebar; +pub mod support; pub mod theme_toggle; pub mod toast; diff --git a/compliance-dashboard/src/components/support.rs b/compliance-dashboard/src/components/support.rs new file mode 100644 index 0000000..3687c75 --- /dev/null +++ b/compliance-dashboard/src/components/support.rs @@ -0,0 +1,144 @@ +//! BreakPilot support access in the dashboard: the tenant picker a support +//! user sees before choosing a tenant, and the banner while one is open. + +use compliance_core::models::SupportTenant; +use dioxus::prelude::*; +use dioxus_free_icons::icons::bs_icons::{BsArrowLeftRight, BsSearch, BsShieldLock}; +use dioxus_free_icons::Icon; + +use crate::i18n::texts::{common, support as tx}; +use crate::i18n::use_lang; +use crate::infrastructure::support::{ + fetch_support_tenants, leave_support_tenant, open_support_tenant, SupportTenantRow, +}; + +/// Reload the app from its start page, so every page asks the agent again +/// for the tenant now open (the browser only). +fn reload_app() { + #[cfg(feature = "web")] + if let Some(window) = web_sys::window() { + let _ = window.location().assign("/"); + } +} + +/// The tenant picker: every tenant, searchable; choosing one opens it. +#[component] +pub fn SupportPicker() -> Element { + let lang = use_lang()(); + let tenants = use_resource(fetch_support_tenants); + let mut query = use_signal(String::new); + let mut opening = use_signal(|| Option::::None); + let mut error = use_signal(|| Option::::None); + + let mut open = move |row: SupportTenantRow| { + opening.set(Some(row.id.clone())); + error.set(None); + spawn(async move { + let tenant = SupportTenant { + id: row.id, + slug: row.slug, + name: row.name, + }; + match open_support_tenant(tenant).await { + Ok(()) => reload_app(), + Err(e) => { + error.set(Some(format!("{}: {e}", tx::OPEN_FAILED.get(lang)))); + opening.set(None); + } + } + }); + }; + + rsx! { + main { class: "support-picker", + div { class: "support-picker-card", + div { class: "support-picker-head", + span { class: "support-picker-mark", Icon { icon: BsShieldLock, width: 18, height: 18 } } + h1 { {tx::PICKER_TITLE.get(lang)} } + } + p { class: "support-picker-intro", {tx::PICKER_INTRO.get(lang)} } + label { class: "support-picker-search", + Icon { icon: BsSearch, width: 14, height: 14 } + input { + r#type: "search", + placeholder: tx::SEARCH.get(lang), + "aria-label": tx::SEARCH.get(lang), + value: "{query}", + oninput: move |e| query.set(e.value()), + } + } + if let Some(message) = error() { + p { class: "support-picker-error", role: "alert", "{message}" } + } + match &*tenants.read() { + None => rsx! { p { class: "support-picker-note", {common::LOADING.get(lang)} } }, + Some(Err(e)) => rsx! { + p { class: "support-picker-error", role: "alert", "{tx::LOAD_FAILED.get(lang)}: {e}" } + }, + Some(Ok(rows)) => { + let shown: Vec = + rows.iter().filter(|r| r.matches(&query())).cloned().collect(); + rsx! { + if shown.is_empty() { + p { class: "support-picker-note", {tx::NONE_FOUND.get(lang)} } + } + ul { class: "support-picker-list", + for row in shown { + li { key: "{row.id}", + button { + class: "support-picker-row", + disabled: opening().is_some(), + onclick: { + let row = row.clone(); + move |_| open(row.clone()) + }, + span { class: "support-picker-name", "{row.display_name()}" } + span { class: "support-picker-slug", "{row.slug}" } + span { class: "support-picker-status", "{row.status}" } + span { class: "support-picker-open", + if opening().as_deref() == Some(row.id.as_str()) { + span { class: "spinner" } + } else { + {tx::OPEN.get(lang)} + } + } + } + } + } + } + } + } + } + } + } + } +} + +/// The banner shown while support has a customer's tenant open. +#[component] +pub fn SupportBanner(tenant: SupportTenant) -> Element { + let lang = use_lang()(); + let name = if tenant.name.trim().is_empty() { + tenant.slug.clone() + } else { + tenant.name.clone() + }; + rsx! { + div { class: "support-banner", role: "status", + Icon { icon: BsShieldLock, width: 14, height: 14 } + strong { "{tx::BANNER.get(lang)}: {name}" } + span { class: "support-banner-note", {tx::BANNER_NOTE.get(lang)} } + button { + class: "support-banner-switch", + onclick: move |_| { + spawn(async move { + let _ = leave_support_tenant().await; + reload_app(); + }); + }, + Icon { icon: BsArrowLeftRight, width: 12, height: 12 } + {tx::SWITCH.get(lang)} + } + } + } +} diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 5e75735..3835e1d 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -2397,6 +2397,54 @@ pub mod demo { } /// What each scan does and why it cannot run, for the applicable-scans list. +/// BreakPilot support access: the tenant picker and the banner. +pub mod support { + use super::Text; + + pub const PICKER_TITLE: Text = Text { + de: "Mandant öffnen", + en: "Open a tenant", + }; + pub const PICKER_INTRO: Text = Text { + de: "Als BreakPilot-Support können Sie jeden Mandanten öffnen. Jede Änderung \ + wird unter Ihrem Namen im Verlauf des Befunds und im Audit-Log festgehalten.", + en: "As BreakPilot support you can open any tenant. Every change is recorded \ + under your name in the finding's history and in the audit log.", + }; + pub const SEARCH: Text = Text { + de: "Name oder Kürzel suchen …", + en: "Search name or slug...", + }; + pub const NONE_FOUND: Text = Text { + de: "Kein Mandant gefunden.", + en: "No tenant found.", + }; + pub const LOAD_FAILED: Text = Text { + de: "Die Mandanten konnten nicht geladen werden", + en: "The tenants could not be loaded", + }; + pub const OPEN: Text = Text { + de: "Öffnen", + en: "Open", + }; + pub const OPEN_FAILED: Text = Text { + de: "Der Mandant konnte nicht geöffnet werden", + en: "The tenant could not be opened", + }; + pub const BANNER: Text = Text { + de: "Support-Zugriff", + en: "Support access", + }; + pub const BANNER_NOTE: Text = Text { + de: "Änderungen werden unter Ihrem Namen protokolliert.", + en: "Changes are logged under your name.", + }; + pub const SWITCH: Text = Text { + de: "Mandant wechseln", + en: "Switch tenant", + }; +} + /// The help assistant. pub mod help { use super::Text; diff --git a/compliance-dashboard/src/infrastructure/agent_client.rs b/compliance-dashboard/src/infrastructure/agent_client.rs index eb0b9c4..463fa76 100644 --- a/compliance-dashboard/src/infrastructure/agent_client.rs +++ b/compliance-dashboard/src/infrastructure/agent_client.rs @@ -213,11 +213,26 @@ async fn attach_token( } let session: tower_sessions::Session = FullstackContext::extract().await?; match current_user(state, &session).await? { - Some(user) => Ok(req.bearer_auth(user.access_token)), + Some(user) => Ok(with_support_tenant( + req.bearer_auth(&user.access_token), + &user, + )), None => Err(ServerFnError::new(super::auth_check::SESSION_EXPIRED)), } } +/// Name the tenant BreakPilot support has opened, when it has; the agent +/// honours the header only for a support role. +fn with_support_tenant( + req: reqwest::RequestBuilder, + user: &UserStateInner, +) -> reqwest::RequestBuilder { + match &user.support_tenant { + Some(tenant) => req.header(compliance_core::SUPPORT_TENANT_HEADER, &tenant.id), + None => req, + } +} + /// Decode the JWT's payload (no signature verification — the agent /// does that) and check the `exp` claim. Treats malformed tokens as /// expired so the refresh path runs. diff --git a/compliance-dashboard/src/infrastructure/auth.rs b/compliance-dashboard/src/infrastructure/auth.rs index a0c2f2c..c7a671d 100644 --- a/compliance-dashboard/src/infrastructure/auth.rs +++ b/compliance-dashboard/src/infrastructure/auth.rs @@ -16,7 +16,7 @@ use url::Url; use super::{ error::DashboardError, server_state::ServerState, - user_state::{tenant_slug_from_token, User, UserStateInner}, + user_state::{has_support_role, tenant_slug_from_token, User, UserStateInner}, }; pub const LOGGED_IN_USER_SESS_KEY: &str = "logged-in-user"; @@ -241,9 +241,12 @@ pub async fn auth_callback( .unwrap_or_default(); let tenant_slug = tenant_slug_from_token(&tokens.access_token); + let staff = has_support_role(&tokens.access_token); let user_state = UserStateInner { sub: userinfo.sub, tenant_slug, + staff, + support_tenant: None, access_token: tokens.access_token, refresh_token: tokens.refresh_token.unwrap_or_default(), user: User { diff --git a/compliance-dashboard/src/infrastructure/auth_check.rs b/compliance-dashboard/src/infrastructure/auth_check.rs index cd7551e..66d5695 100644 --- a/compliance-dashboard/src/infrastructure/auth_check.rs +++ b/compliance-dashboard/src/infrastructure/auth_check.rs @@ -52,7 +52,14 @@ pub async fn check_auth() -> Result { match user_state { Some(u) => Ok(AuthInfo { authenticated: true, - portal_url: portal_link(state.portal_url.as_deref(), &u.tenant_slug), + // Support is not a member of the tenant it opened: the portal's + // start page, not the workspace's. + portal_url: portal_link( + state.portal_url.as_deref(), + if u.staff { "" } else { &u.tenant_slug }, + ), + staff: u.staff, + support_tenant: u.support_tenant, docs_url: state.docs_url.clone(), sub: u.sub, email: u.user.email, diff --git a/compliance-dashboard/src/infrastructure/mod.rs b/compliance-dashboard/src/infrastructure/mod.rs index e25af2c..8147b90 100644 --- a/compliance-dashboard/src/infrastructure/mod.rs +++ b/compliance-dashboard/src/infrastructure/mod.rs @@ -19,6 +19,7 @@ pub mod platform; pub mod sbom; pub mod scans; pub mod stats; +pub mod support; // Server-only modules #[cfg(feature = "server")] diff --git a/compliance-dashboard/src/infrastructure/support.rs b/compliance-dashboard/src/infrastructure/support.rs new file mode 100644 index 0000000..656bb6d --- /dev/null +++ b/compliance-dashboard/src/infrastructure/support.rs @@ -0,0 +1,144 @@ +//! BreakPilot support access: list the tenants, open one, leave it. +//! +//! The opened tenant lives in the session and is named to the agent with +//! every request; the agent checks the support role and the tenant, and +//! records each change in the platform's audit log. + +use compliance_core::models::SupportTenant; +use dioxus::prelude::*; +use serde::{Deserialize, Serialize}; + +/// A tenant in the support picker, as the agent lists it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SupportTenantRow { + pub id: String, + pub slug: String, + #[serde(default)] + pub name: String, + #[serde(default)] + pub status: String, +} + +impl SupportTenantRow { + /// The organisation's name, or its slug when it has none. + pub fn display_name(&self) -> &str { + if self.name.trim().is_empty() { + &self.slug + } else { + &self.name + } + } + + /// Whether the row matches what was typed in the picker's search. + pub fn matches(&self, query: &str) -> bool { + let query = query.trim().to_lowercase(); + query.is_empty() + || self.name.to_lowercase().contains(&query) + || self.slug.to_lowercase().contains(&query) + } +} + +/// Every tenant support may open (`GET /api/v1/support/tenants`). +#[server] +pub async fn fetch_support_tenants() -> Result, ServerFnError> { + let resp = super::agent_client::agent_get("/api/v1/support/tenants") + .await? + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + let body: serde_json::Value = super::agent_client::json_or_error(resp).await?; + serde_json::from_value(body["data"].clone()).map_err(|e| ServerFnError::new(e.to_string())) +} + +/// Open `tenant` for support: the agent confirms it (and logs the opening), +/// then the session names it in every later request. +/// +/// # Errors +/// +/// The user is not support, the sign-in has run out, or the agent refused +/// the tenant. +#[server] +pub async fn open_support_tenant(tenant: SupportTenant) -> Result<(), ServerFnError> { + use super::auth::LOGGED_IN_USER_SESS_KEY; + use super::server_state::ServerState; + use dioxus_fullstack::FullstackContext; + + let state: ServerState = FullstackContext::extract().await?; + let session: tower_sessions::Session = FullstackContext::extract().await?; + let Some(mut user) = super::agent_client::current_user(&state, &session).await? else { + return Err(ServerFnError::new(super::auth_check::SESSION_EXPIRED)); + }; + if !user.staff { + return Err(ServerFnError::new("support_only")); + } + // Named explicitly: the tenant opened before, if any, must not be sent. + let resp = reqwest::Client::new() + .post(format!("{}/api/v1/support/session", state.agent_api_url)) + .bearer_auth(&user.access_token) + .header(compliance_core::SUPPORT_TENANT_HEADER, &tenant.id) + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + let body: serde_json::Value = super::agent_client::json_or_error(resp).await?; + let slug = body["data"]["slug"] + .as_str() + .filter(|s| !s.is_empty()) + .map_or_else(|| tenant.slug.clone(), str::to_owned); + user.support_tenant = Some(SupportTenant { slug, ..tenant }); + session + .insert(LOGGED_IN_USER_SESS_KEY, &user) + .await + .map_err(|e| ServerFnError::new(format!("session write failed: {e}"))) +} + +/// Leave the opened tenant; the picker shows again. +/// +/// # Errors +/// +/// The session could not be read or written. +#[server] +pub async fn leave_support_tenant() -> Result<(), ServerFnError> { + use super::auth::LOGGED_IN_USER_SESS_KEY; + use super::server_state::ServerState; + use dioxus_fullstack::FullstackContext; + + let state: ServerState = FullstackContext::extract().await?; + let session: tower_sessions::Session = FullstackContext::extract().await?; + let Some(mut user) = super::agent_client::current_user(&state, &session).await? else { + return Ok(()); + }; + user.support_tenant = None; + session + .insert(LOGGED_IN_USER_SESS_KEY, &user) + .await + .map_err(|e| ServerFnError::new(format!("session write failed: {e}"))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn row(name: &str, slug: &str) -> SupportTenantRow { + SupportTenantRow { + id: format!("id-{slug}"), + slug: slug.to_string(), + name: name.to_string(), + status: "active".to_string(), + } + } + + #[test] + fn the_search_matches_name_or_slug() { + let faller = row("Gebr. Faller GmbH", "faller"); + assert!(faller.matches("")); + assert!(faller.matches("gebr")); + assert!(faller.matches("FALL")); + assert!(!faller.matches("acme")); + } + + #[test] + fn a_tenant_without_a_name_shows_its_slug() { + assert_eq!(row("", "faller").display_name(), "faller"); + assert_eq!(row("Gebr. Faller", "faller").display_name(), "Gebr. Faller"); + } +} diff --git a/compliance-dashboard/src/infrastructure/user_state.rs b/compliance-dashboard/src/infrastructure/user_state.rs index ee63c94..f24a4e0 100644 --- a/compliance-dashboard/src/infrastructure/user_state.rs +++ b/compliance-dashboard/src/infrastructure/user_state.rs @@ -1,3 +1,4 @@ +use compliance_core::models::SupportTenant; use serde::{Deserialize, Serialize}; /// Per-session user data stored in the tower-sessions session store. @@ -11,6 +12,14 @@ pub struct UserStateInner { /// portal. Empty in sessions from before it was stored. #[serde(default)] pub tenant_slug: String, + /// Holds a BreakPilot support role (`realm_access.roles`): decides whether + /// the tenant picker shows. The agent checks the role itself. + #[serde(default)] + pub staff: bool, + /// The customer tenant support has opened, named to the agent with + /// every request. + #[serde(default)] + pub support_tenant: Option, } /// Basic user profile stored alongside the session. @@ -26,21 +35,41 @@ pub struct User { /// The signature is not checked: the token comes straight from Keycloak's /// token endpoint, and the slug only builds a link. pub fn tenant_slug_from_token(access_token: &str) -> String { - use base64::Engine; - - access_token - .split('.') - .nth(1) - .and_then(|payload| { - base64::engine::general_purpose::URL_SAFE_NO_PAD - .decode(payload.trim_end_matches('=')) - .ok() - }) - .and_then(|json| serde_json::from_slice::(&json).ok()) + token_claims(access_token) .and_then(|claims| claims.get("tenant_slug")?.as_str().map(str::to_owned)) .unwrap_or_default() } +/// Whether a Keycloak access token carries a BreakPilot support role. Not +/// verified, as for the slug: it only decides what the dashboard shows; the +/// agent verifies the token before granting anything. +pub fn has_support_role(access_token: &str) -> bool { + token_claims(access_token) + .and_then(|claims| { + let roles = claims + .get("realm_access")? + .get("roles")? + .as_array()? + .clone(); + Some(roles.iter().any(|role| { + role.as_str() + .is_some_and(|r| compliance_core::SUPPORT_ROLES.contains(&r)) + })) + }) + .unwrap_or(false) +} + +/// The payload of a JWT, unverified. +fn token_claims(access_token: &str) -> Option { + use base64::Engine; + + let payload = access_token.split('.').nth(1)?; + let json = base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(payload.trim_end_matches('=')) + .ok()?; + serde_json::from_slice(&json).ok() +} + /// The link back to the platform: the workspace's portal dashboard, or the /// portal's start page when the slug is unknown. Empty without a portal URL. /// @@ -85,6 +114,28 @@ mod tests { assert_eq!(tenant_slug_from_token("not-a-jwt"), ""); } + #[test] + fn support_roles_are_read_from_the_access_token() { + let staff = token(&serde_json::json!({ + "sub": "s1", + "realm_access": { "roles": ["offline_access", "SUPPORT_ENGINEER"] } + })); + let admin = token(&serde_json::json!({ + "sub": "s2", + "realm_access": { "roles": ["BREAKPILOT_ADMIN"] } + })); + let customer = token(&serde_json::json!({ + "sub": "u1", + "realm_access": { "roles": ["offline_access"] }, + "org_roles": ["IT_ADMIN"] + })); + + assert!(has_support_role(&staff)); + assert!(has_support_role(&admin)); + assert!(!has_support_role(&customer)); + assert!(!has_support_role("not-a-jwt")); + } + #[test] fn the_link_goes_to_the_workspace_when_the_slug_is_plain() { let portal = Some("https://app-stage.breakpilot.com/"); diff --git a/compliance-dashboard/src/pages/finding_detail.rs b/compliance-dashboard/src/pages/finding_detail.rs index 8a73aea..b5f1a79 100644 --- a/compliance-dashboard/src/pages/finding_detail.rs +++ b/compliance-dashboard/src/pages/finding_detail.rs @@ -332,7 +332,11 @@ pub fn FindingDetailPage(id: String) -> Element { for change in f.status_history.iter().rev() { li { style: "margin-bottom: 4px;", strong { {tx::status(&change.status).get(lang)} } - " · {change.by} · {format_time(&change.at, lang)}" + " · " + span { class: if change.support { "history-by history-by-support" } else { "history-by" }, + {change.by_name.as_deref().unwrap_or(&change.by)} + } + " · {format_time(&change.at, lang)}" if let Some(reason) = &change.reason { div { style: "color: var(--text-secondary);", "{tx::REASON.get(lang)}: {reason}" } }