Compare commits

...
5 Commits
Author SHA1 Message Date
sharang 6a150b4aee fix(dashboard): favicon at /favicon.svg, and the crates at version 0.4.2 (#429)
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 4m25s
CI / Deploy Dashboard (push) Successful in 6m6s
CI / Deploy Agent (push) Successful in 7m29s
CI / Check (push) Skipped
2026-09-29 15:56:00 +00:00
sharang 001ab17b47 feat(audit): record project assignments in the workspace audit log (#428)
CI / Deploy Dashboard (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Agent (push) Successful in 4m54s
CI / Check (push) Skipped
2026-09-29 14:34:34 +00:00
sharang 202f5ea325 feat(projects): assign targets to the tenant's projects (#427)
CI / Check (push) Skipped
CI / Deploy Agent (push) Successful in 7m20s
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 4m18s
CI / Deploy Dashboard (push) Successful in 5m59s
2026-09-29 14:13:01 +00:00
sharang ec5a68a982 fix(dashboard): staff sign in directly, and old history entries read as people (#426)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Agent (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Successful in 3m17s
2026-09-29 08:23:35 +00:00
sharang 96d97ae6eb feat(support): BreakPilot support can open any tenant, attributed and audited (#425)
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 4m24s
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Successful in 6m0s
CI / Deploy Agent (push) Successful in 7m22s
2026-09-29 07:37:12 +00:00
57 changed files with 2561 additions and 101 deletions

No files matched your search

Generated
+9 -9
View File
@@ -663,7 +663,7 @@ dependencies = [
[[package]] [[package]]
name = "compliance-agent" name = "compliance-agent"
version = "0.1.0" version = "0.4.2"
dependencies = [ dependencies = [
"axum", "axum",
"base64", "base64",
@@ -714,7 +714,7 @@ dependencies = [
[[package]] [[package]]
name = "compliance-core" name = "compliance-core"
version = "0.1.0" version = "0.4.2"
dependencies = [ dependencies = [
"aes-gcm", "aes-gcm",
"axum", "axum",
@@ -744,7 +744,7 @@ dependencies = [
[[package]] [[package]]
name = "compliance-dashboard" name = "compliance-dashboard"
version = "0.1.0" version = "0.4.2"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"axum", "axum",
@@ -784,7 +784,7 @@ dependencies = [
[[package]] [[package]]
name = "compliance-dast" name = "compliance-dast"
version = "0.1.0" version = "0.4.2"
dependencies = [ dependencies = [
"base64", "base64",
"bollard", "bollard",
@@ -810,7 +810,7 @@ dependencies = [
[[package]] [[package]]
name = "compliance-graph" name = "compliance-graph"
version = "0.1.0" version = "0.4.2"
dependencies = [ dependencies = [
"bson", "bson",
"chrono", "chrono",
@@ -834,7 +834,7 @@ dependencies = [
[[package]] [[package]]
name = "compliance-mcp" name = "compliance-mcp"
version = "0.1.0" version = "0.4.2"
dependencies = [ dependencies = [
"axum", "axum",
"bson", "bson",
@@ -858,7 +858,7 @@ dependencies = [
[[package]] [[package]]
name = "compliance-smoke" name = "compliance-smoke"
version = "0.1.0" version = "0.4.2"
dependencies = [ dependencies = [
"axum", "axum",
"compliance-core", "compliance-core",
@@ -985,7 +985,7 @@ dependencies = [
[[package]] [[package]]
name = "control-map" name = "control-map"
version = "0.1.0" version = "0.4.2"
dependencies = [ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
@@ -6793,7 +6793,7 @@ dependencies = [
[[package]] [[package]]
name = "werkbank-exec" name = "werkbank-exec"
version = "0.1.0" version = "0.4.2"
dependencies = [ dependencies = [
"compliance-core", "compliance-core",
"compliance-dast", "compliance-dast",
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "compliance-agent" name = "compliance-agent"
version = "0.1.0" version = "0.4.2"
edition = "2021" edition = "2021"
[lints] [lints]
+9 -6
View File
@@ -191,12 +191,15 @@ impl ComplianceAgent {
); );
let started = chrono::Utc::now(); let started = chrono::Utc::now();
orchestrator.run_target(target_id, trigger.clone()).await?; orchestrator.run_target(target_id, trigger.clone()).await?;
self.emit_usage( // Support's scans are ours, not the customer's usage.
tenant_id, if trigger != compliance_core::models::ScanTrigger::Support {
"scan.completed", self.emit_usage(
format!("scan:{tenant_id}:{target_id}:{}", started.timestamp()), tenant_id,
serde_json::json!({ "target_id": target_id, "trigger": format!("{trigger:?}") }), "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); self.notify_new_findings(tenant_id, target_id, &db, started);
Ok(()) Ok(())
} }
+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 /// 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 /// that needs a reason (an accepted risk, a wrong CRA mapping) comes without
/// one. /// 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( fn status_update(
status: &FindingStatus, status: &FindingStatus,
reason: Option<&str>, reason: Option<&str>,
user: &str, actor: &Actor<'_>,
) -> Result<mongodb::bson::Document, StatusCode> { ) -> Result<mongodb::bson::Document, StatusCode> {
let reason = reason.map(str::trim).filter(|r| !r.is_empty()); let reason = reason.map(str::trim).filter(|r| !r.is_empty());
if status.needs_reason() && reason.is_none() { if status.needs_reason() && reason.is_none() {
@@ -151,7 +175,9 @@ fn status_update(
} }
let change = StatusChange { let change = StatusChange {
status: status.clone(), status: status.clone(),
by: user.to_string(), by: actor.id.to_string(),
by_name: actor.name.clone(),
support: actor.support,
at: chrono::Utc::now(), at: chrono::Utc::now(),
reason: reason.map(String::from), reason: reason.map(String::from),
}; };
@@ -173,7 +199,7 @@ pub async fn update_finding_status(
Json(req): Json<UpdateStatusRequest>, Json(req): Json<UpdateStatusRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> { ) -> Result<Json<serde_json::Value>, StatusCode> {
let oid = mongodb::bson::oid::ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?; 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 db = tenant_db(&agent, &tenant).await?;
let result = db let result = db
@@ -204,7 +230,7 @@ pub async fn bulk_update_finding_status(
if oids.is_empty() { if oids.is_empty() {
return Err(StatusCode::BAD_REQUEST); 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 db = tenant_db(&agent, &tenant).await?;
let result = db let result = db
@@ -246,26 +272,65 @@ mod tests {
#[test] #[test]
fn an_accepted_risk_needs_a_reason() { fn an_accepted_risk_needs_a_reason() {
assert_eq!( assert_eq!(
status_update(&FindingStatus::AcceptedRisk, None, "u").err(), status_update(&FindingStatus::AcceptedRisk, None, &user("u")).err(),
Some(StatusCode::UNPROCESSABLE_ENTITY) Some(StatusCode::UNPROCESSABLE_ENTITY)
); );
assert_eq!( assert_eq!(
status_update(&FindingStatus::AcceptedRisk, Some(" "), "u").err(), status_update(&FindingStatus::AcceptedRisk, Some(" "), &user("u")).err(),
Some(StatusCode::UNPROCESSABLE_ENTITY) 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!( assert_eq!(
status_update(&FindingStatus::WrongMapping, None, "u").err(), status_update(&FindingStatus::WrongMapping, None, &user("u")).err(),
Some(StatusCode::UNPROCESSABLE_ENTITY) Some(StatusCode::UNPROCESSABLE_ENTITY)
); );
assert!(status_update(&FindingStatus::FalsePositive, None, "u").is_ok()); assert!(status_update(&FindingStatus::FalsePositive, None, &user("u")).is_ok());
assert!(status_update(&FindingStatus::Resolved, None, "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] #[test]
fn a_change_sets_the_status_and_records_who_and_why() { fn a_change_sets_the_status_and_records_who_and_why() {
let update = status_update(&FindingStatus::AcceptedRisk, Some(" isolated "), "u-7") let update = status_update(
.unwrap_or_default(); &FindingStatus::AcceptedRisk,
Some(" isolated "),
&user("u-7"),
)
.unwrap_or_default();
let set = update.get_document("$set").cloned().unwrap_or_default(); let set = update.get_document("$set").cloned().unwrap_or_default();
assert_eq!(set.get_str("status").ok(), Some("accepted_risk")); assert_eq!(set.get_str("status").ok(), Some("accepted_risk"));
let change = update let change = update
+1 -1
View File
@@ -12,7 +12,7 @@ pub async fn health() -> Json<serde_json::Value> {
/// Findings that still need someone's attention: not resolved, not a false /// Findings that still need someone's attention: not resolved, not a false
/// positive, not an accepted risk and not ignored. /// positive, not an accepted risk and not ignored.
const OPEN_STATUSES: [&str; 3] = ["open", "triaged", "needs_review"]; pub(crate) const OPEN_STATUSES: [&str; 3] = ["open", "triaged", "needs_review"];
/// How many open findings there are of each severity, by severity name. /// How many open findings there are of each severity, by severity name.
async fn open_findings_by_severity( async fn open_findings_by_severity(
@@ -138,6 +138,8 @@ pub async fn create_finding(
return Err(StatusCode::UNPROCESSABLE_ENTITY); return Err(StatusCode::UNPROCESSABLE_ENTITY);
} }
let db = tenant_db(&agent, &tenant).await?; 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?; require_target(&db, &id).await?;
let tool = req let tool = req
.tool .tool
@@ -147,7 +149,7 @@ pub async fn create_finding(
target_id: &id, target_id: &id,
scan_type: req.kind.into(), scan_type: req.kind.into(),
scanner: &tool, scanner: &tool,
reported_by: &tenant.0.user_id, reported_by: &reported_by,
}); });
if !insert_new(&db, &mut finding).await? { if !insert_new(&db, &mut finding).await? {
return Err(StatusCode::CONFLICT); return Err(StatusCode::CONFLICT);
@@ -187,6 +189,8 @@ pub async fn import_findings(
StatusCode::UNPROCESSABLE_ENTITY StatusCode::UNPROCESSABLE_ENTITY
})?; })?;
let db = tenant_db(&agent, &tenant).await?; 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?; require_target(&db, &id).await?;
let mut summary = ImportSummary { let mut summary = ImportSummary {
@@ -199,7 +203,7 @@ pub async fn import_findings(
target_id: &id, target_id: &id,
scan_type: params.kind.into(), scan_type: params.kind.into(),
scanner: &tool, scanner: &tool,
reported_by: &tenant.0.user_id, reported_by: &reported_by,
}); });
if insert_new(&db, &mut finding).await? { if insert_new(&db, &mut finding).await? {
summary.imported += 1; summary.imported += 1;
@@ -229,6 +233,7 @@ mod tests {
status: TenantStatus::Active, status: TenantStatus::Active,
user_id: "u".into(), user_id: "u".into(),
user_name: None, user_name: None,
staff: None,
}) })
} }
+2
View File
@@ -16,9 +16,11 @@ pub mod onboarding;
pub mod oscal; pub mod oscal;
pub mod pentest_handlers; pub mod pentest_handlers;
pub mod platform; pub mod platform;
pub mod projects;
pub use pentest_handlers as pentest; pub use pentest_handlers as pentest;
pub mod sbom; pub mod sbom;
pub mod scans; pub mod scans;
pub mod support;
pub mod target_input; pub mod target_input;
pub mod werkbank_jobs; pub mod werkbank_jobs;
+91 -22
View File
@@ -47,6 +47,9 @@ pub struct UpdateTargetRequest {
pub scan_config: Option<ScanConfigUpdate>, pub scan_config: Option<ScanConfigUpdate>,
pub compliance_profile: Option<ComplianceProfile>, pub compliance_profile: Option<ComplianceProfile>,
pub scan_schedule: Option<String>, pub scan_schedule: Option<String>,
/// The tenant's projects this target belongs to; replaces the stored
/// list. Each must be one of the tenant's projects in the registry.
pub project_ids: Option<Vec<String>>,
/// The target's artifacts (the dashboard editor sends all of them). Each /// The target's artifacts (the dashboard editor sends all of them). Each
/// keeps the token and uploaded file of the stored artifact it matches. /// keeps the token and uploaded file of the stored artifact it matches.
#[serde(default)] #[serde(default)]
@@ -80,17 +83,19 @@ pub async fn list_targets(
Extension(agent): AgentExt, Extension(agent): AgentExt,
tenant: TenantCtx, tenant: TenantCtx,
Query(params): Query<PaginationParams>, Query(params): Query<PaginationParams>,
Query(filter): Query<TargetFilter>,
) -> Result<Json<ApiResponse<Vec<TargetListItem>>>, StatusCode> { ) -> Result<Json<ApiResponse<Vec<TargetListItem>>>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?; let db = tenant_db(&agent, &tenant).await?;
let skip = params.skip(); let skip = params.skip();
let query = filter.to_query();
let total = db let total = db
.onboarded_targets() .onboarded_targets()
.count_documents(doc! {}) .count_documents(query.clone())
.await .await
.unwrap_or(0); .unwrap_or(0);
let targets = match db let targets = match db
.onboarded_targets() .onboarded_targets()
.find(doc! {}) .find(query)
.skip(skip) .skip(skip)
.limit(params.limit) .limit(params.limit)
.await .await
@@ -143,8 +148,31 @@ pub struct TargetListItem {
pub last_scan: Option<ScanRun>, pub last_scan: Option<ScanRun>,
} }
/// Which targets a list shows (`?project=<id>`).
#[derive(Debug, Default, serde::Deserialize)]
pub struct TargetFilter {
/// Only the targets that belong to this project.
#[serde(default)]
pub project: Option<String>,
}
impl TargetFilter {
/// The Mongo filter for these targets.
pub fn to_query(&self) -> mongodb::bson::Document {
match self
.project
.as_deref()
.map(str::trim)
.filter(|p| !p.is_empty())
{
Some(project) => doc! { "project_ids": project },
None => doc! {},
}
}
}
/// The newest scan run of each target in `target_ids`, in one query. /// The newest scan run of each target in `target_ids`, in one query.
async fn latest_scan_runs( pub(crate) async fn latest_scan_runs(
runs: &mongodb::Collection<ScanRun>, runs: &mongodb::Collection<ScanRun>,
target_ids: Vec<String>, target_ids: Vec<String>,
) -> HashMap<String, ScanRun> { ) -> HashMap<String, ScanRun> {
@@ -294,17 +322,18 @@ pub async fn update_target(
); );
} }
// Both merge with what is stored, so the stored target is read once. // Both merge with what is stored, so the stored target is read once.
let stored = if req.scan_config.is_some() || req.artifacts.is_some() { let stored =
Some( if req.scan_config.is_some() || req.artifacts.is_some() || req.project_ids.is_some() {
db.onboarded_targets() Some(
.find_one(doc! { "_id": oid }) db.onboarded_targets()
.await .find_one(doc! { "_id": oid })
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? .await
.ok_or(StatusCode::NOT_FOUND)?, .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
) .ok_or(StatusCode::NOT_FOUND)?,
} else { )
None } else {
}; None
};
let credential_error = |e: SecretError| { let credential_error = |e: SecretError| {
tracing::error!("storing a credential: {e}"); tracing::error!("storing a credential: {e}");
StatusCode::SERVICE_UNAVAILABLE StatusCode::SERVICE_UNAVAILABLE
@@ -327,6 +356,20 @@ pub async fn update_target(
if let Some(ss) = req.scan_schedule { if let Some(ss) = req.scan_schedule {
set.insert("scan_schedule", ss); set.insert("scan_schedule", ss);
} }
// Written to the audit log once the change is stored.
let mut projects_audit = None;
if let (Some(requested), Some(stored)) = (req.project_ids, stored.as_ref()) {
let known = super::projects::tenant_projects(&agent, &tenant.0.tenant_id).await?;
let ids = super::projects::validated_project_ids(&requested, &known)?;
projects_audit = super::projects::projects_changed_entry(
&tenant.0,
(&id, &stored.name),
&stored.project_ids,
&ids,
&known,
);
set.insert("project_ids", ids);
}
if let (Some(arts), Some(stored)) = (req.artifacts, stored.as_ref()) { if let (Some(arts), Some(stored)) = (req.artifacts, stored.as_ref()) {
let built = let built =
merge_artifacts(&agent.secrets, &arts, &stored.artifacts).map_err(credential_error)?; merge_artifacts(&agent.secrets, &arts, &stored.artifacts).map_err(credential_error)?;
@@ -340,6 +383,15 @@ pub async fn update_target(
.update_one(doc! { "_id": oid }, doc! { "$set": set }) .update_one(doc! { "_id": oid }, doc! { "$set": set })
.await .await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
// Background and best-effort: the registry being down never fails the
// change itself.
if let (Some(entry), Some(registry)) = (projects_audit, agent.registry.clone()) {
tokio::spawn(async move {
if let Err(e) = registry.append_audit(&entry).await {
tracing::warn!(target_id = %entry.target_id, "project change not audited: {e}");
}
});
}
get_target(Extension(agent), tenant, Path(id)).await get_target(Extension(agent), tenant, Path(id)).await
} }
@@ -916,20 +968,37 @@ pub async fn trigger_target_scan(
let agent_clone = (*agent).clone(); let agent_clone = (*agent).clone();
let tenant_id = tenant.0.tenant_id.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 { tokio::spawn(async move {
// Always the unified target pipeline — this endpoint is about an // Always the unified target pipeline — this endpoint is about an
// onboarded target by construction, independent of the global // onboarded target by construction, independent of the global
// `unified_pipeline` transition flag used by the legacy paths. // `unified_pipeline` transition flag used by the legacy paths.
if let Err(e) = agent_clone if let Err(e) = agent_clone.run_target_scan(&tenant_id, &id, trigger).await {
.run_target_scan(
&tenant_id,
&id,
compliance_core::models::ScanTrigger::Manual,
)
.await
{
tracing::error!("Manual target scan failed for {id}: {e}"); tracing::error!("Manual target scan failed for {id}: {e}");
} }
}); });
Ok(Json(serde_json::json!({ "status": "scan_triggered" }))) Ok(Json(serde_json::json!({ "status": "scan_triggered" })))
} }
#[cfg(test)]
mod filter_tests {
use super::*;
#[test]
fn a_project_filter_matches_its_targets() {
let filter = TargetFilter {
project: Some(" p1 ".to_string()),
};
assert_eq!(filter.to_query(), doc! { "project_ids": "p1" });
assert_eq!(TargetFilter::default().to_query(), doc! {});
let blank = TargetFilter {
project: Some(String::new()),
};
assert_eq!(blank.to_query(), doc! {});
}
}
@@ -443,3 +443,107 @@ pub async fn version(State(st): State<PlatformState>) -> Json<serde_json::Value>
"features": st.agent.config.features.flags(), "features": st.agent.config.features.flags(),
})) }))
} }
/// A target as the portal lists it for a project.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct PlatformTarget {
pub id: String,
pub name: String,
pub target_type: compliance_core::models::TargetType,
/// When its newest scan started; `None` before the first.
pub last_scan_at: Option<chrono::DateTime<chrono::Utc>>,
/// Findings that still need attention.
pub open_findings: u64,
/// Its projects that the registry still lists.
pub project_ids: Vec<String>,
}
/// Open findings of each target in `target_ids`, in one query.
async fn open_findings_counts(
db: &crate::database::Database,
target_ids: Vec<String>,
) -> Result<std::collections::HashMap<String, u64>, StatusCode> {
let pipeline = vec![
doc! { "$match": {
"repo_id": { "$in": target_ids },
"status": { "$in": super::health::OPEN_STATUSES.to_vec() },
} },
doc! { "$group": { "_id": "$repo_id", "n": { "$sum": 1 } } },
];
let rows: Vec<Document> = db
.findings()
.aggregate(pipeline)
.await
.map_err(internal)?
.try_collect()
.await
.map_err(internal)?;
Ok(rows
.iter()
.filter_map(|row| {
let id = row.get_str("_id").ok()?.to_string();
let n = row
.get_i32("n")
.map(i64::from)
.or_else(|_| row.get_i64("n"))
.ok()?;
Some((id, u64::try_from(n).ok()?))
})
.collect())
}
/// `GET /api/v1/platform/tenants/{id}/targets?project=<id>` — the tenant's
/// targets (one project's, with `project`), for the portal through the
/// registry. Read-only. Project ids the registry no longer lists are left
/// out; when it cannot be asked, the stored ids are returned as they are.
pub async fn list_targets(
State(st): State<PlatformState>,
Path(tenant_id): Path<String>,
Query(filter): Query<super::onboarding::TargetFilter>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let db = st
.agent
.db_pool
.for_tenant_id(&tenant_id)
.await
.map_err(internal)?;
let targets: Vec<compliance_core::models::OnboardedTarget> = db
.onboarded_targets()
.find(filter.to_query())
.await
.map_err(internal)?
.try_collect()
.await
.map_err(internal)?;
let ids: Vec<String> = targets
.iter()
.filter_map(|t| t.id.map(|id| id.to_hex()))
.collect();
let runs = db.scan_runs();
let (mut last_scans, open) = tokio::join!(
super::onboarding::latest_scan_runs(&runs, ids.clone()),
open_findings_counts(&db, ids),
);
let open = open?;
let known = super::projects::tenant_projects(&st.agent, &tenant_id)
.await
.ok();
let items: Vec<PlatformTarget> = targets
.into_iter()
.map(|t| {
let id = t.id.map(|id| id.to_hex()).unwrap_or_default();
PlatformTarget {
last_scan_at: last_scans.remove(&id).map(|run| run.started_at),
open_findings: open.get(&id).copied().unwrap_or(0),
project_ids: match known.as_deref() {
Some(known) => super::projects::known_project_ids(&t.project_ids, known),
None => t.project_ids,
},
name: t.name,
target_type: t.target_type,
id,
}
})
.collect();
Ok(Json(serde_json::json!({ "items": items })))
}
@@ -0,0 +1,225 @@
//! A tenant's projects, which the platform registry owns: listing them for
//! the dashboard, and checking assignments against them.
//!
//! Targets store the ids of the projects they belong to (`project_ids`). A
//! project deleted in the registry drops out of its list, and readers show
//! only ids they still find there.
use std::collections::HashSet;
use axum::extract::Extension;
use axum::http::StatusCode;
use axum::Json;
use compliance_core::models::Project;
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::AgentExt;
use crate::agent::ComplianceAgent;
/// The tenant's projects from the registry. Empty without a registry (dev).
///
/// # Errors
///
/// `503` when the registry could not answer.
pub async fn tenant_projects(
agent: &ComplianceAgent,
tenant_id: &str,
) -> Result<Vec<Project>, StatusCode> {
let Some(registry) = agent.registry.as_ref() else {
return Ok(Vec::new());
};
registry.list_projects(tenant_id).await.map_err(|e| {
tracing::error!(tenant_id, "project list unavailable: {e}");
StatusCode::SERVICE_UNAVAILABLE
})
}
/// `requested` as stored: trimmed, without duplicates, in the given order.
///
/// # Errors
///
/// `422` when an id is not one of the tenant's projects (`known`).
pub fn validated_project_ids(
requested: &[String],
known: &[Project],
) -> Result<Vec<String>, StatusCode> {
let known: HashSet<&str> = known.iter().map(|p| p.id.as_str()).collect();
let mut seen = HashSet::with_capacity(requested.len());
let mut ids = Vec::with_capacity(requested.len());
for id in requested.iter().map(|id| id.trim()) {
if !known.contains(id) {
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
if seen.insert(id) {
ids.push(id.to_string());
}
}
Ok(ids)
}
/// The ids in `ids` that are still one of the tenant's projects.
pub fn known_project_ids(ids: &[String], known: &[Project]) -> Vec<String> {
ids.iter()
.filter(|id| known.iter().any(|p| &p.id == *id))
.cloned()
.collect()
}
/// The audit entry for a change of target `target_id`'s projects from
/// `before` to `after`, naming each project from `known` (a deleted one with
/// an empty name). `None` when nothing changed.
pub fn projects_changed_entry(
ctx: &compliance_core::TenantContext,
(target_id, target_name): (&str, &str),
before: &[String],
after: &[String],
known: &[Project],
) -> Option<crate::registry::AuditEntry> {
let named = |id: &String| {
let name = known
.iter()
.find(|p| &p.id == id)
.map_or("", |p| p.name.as_str());
serde_json::json!({ "id": id, "name": name })
};
let added: Vec<_> = after
.iter()
.filter(|id| !before.contains(id))
.map(named)
.collect();
let removed: Vec<_> = before
.iter()
.filter(|id| !after.contains(id))
.map(named)
.collect();
if added.is_empty() && removed.is_empty() {
return None;
}
Some(
crate::registry::AuditEntry::by(
ctx,
"target.projects_changed",
serde_json::json!({ "added": added, "removed": removed }),
)
.about_target(target_id, target_name),
)
}
/// GET /api/v1/projects — the tenant's projects, for choosing and showing
/// them in the dashboard.
#[tracing::instrument(skip_all)]
pub async fn list_projects(
Extension(agent): AgentExt,
tenant: TenantCtx,
) -> Result<Json<serde_json::Value>, StatusCode> {
let projects = tenant_projects(&agent, &tenant.0.tenant_id).await?;
Ok(Json(serde_json::json!({ "data": projects })))
}
#[cfg(test)]
mod tests {
use super::*;
use compliance_core::models::ProjectKind;
fn project(id: &str) -> Project {
Project {
id: id.to_string(),
name: format!("Projekt {id}"),
kind: ProjectKind::Product,
description: String::new(),
}
}
#[test]
fn assignments_are_trimmed_and_deduplicated() {
let known = [project("p1"), project("p2")];
let ids = validated_project_ids(
&["p2".to_string(), " p1 ".to_string(), "p2".to_string()],
&known,
);
assert_eq!(ids, Ok(vec!["p2".to_string(), "p1".to_string()]));
}
#[test]
fn an_unknown_project_is_refused() {
let known = [project("p1")];
assert_eq!(
validated_project_ids(&["p9".to_string()], &known),
Err(StatusCode::UNPROCESSABLE_ENTITY)
);
assert_eq!(validated_project_ids(&[], &known), Ok(Vec::new()));
}
fn ctx(staff: bool) -> compliance_core::TenantContext {
compliance_core::TenantContext {
tenant_id: "t-1".to_string(),
tenant_slug: "faller".to_string(),
org_roles: Vec::new(),
products: Vec::new(),
plan: String::new(),
status: compliance_core::TenantStatus::Active,
user_id: "u-1".to_string(),
user_name: Some("Anna Faller".to_string()),
staff: staff.then(|| compliance_core::StaffAccess {
user_id: "u-1".to_string(),
user_name: Some("Sharang".to_string()),
}),
}
}
#[test]
fn a_projects_change_is_audited_with_names() {
let known = [project("p1"), project("p2")];
let entry = projects_changed_entry(
&ctx(false),
("abc", "Lok-Steuerung"),
&["p1".to_string(), "gone".to_string()],
&["p1".to_string(), "p2".to_string()],
&known,
)
.expect("a change");
assert_eq!(entry.action, "target.projects_changed");
assert_eq!(entry.actor_type, "user");
assert_eq!(entry.actor_name, "Anna Faller");
assert_eq!(
(entry.target_type.as_str(), entry.target_id.as_str()),
("target", "abc")
);
assert_eq!(entry.target_name, "Lok-Steuerung");
assert_eq!(
entry.metadata,
serde_json::json!({
"added": [{ "id": "p2", "name": "Projekt p2" }],
"removed": [{ "id": "gone", "name": "" }]
})
);
}
#[test]
fn support_is_audited_as_staff_and_no_change_as_nothing() {
let known = [project("p1")];
let entry =
projects_changed_entry(&ctx(true), ("abc", "x"), &[], &["p1".to_string()], &known)
.expect("a change");
assert_eq!(entry.actor_type, "staff");
assert_eq!(entry.actor_name, "BreakPilot-Support (Sharang)");
assert!(projects_changed_entry(
&ctx(false),
("abc", "x"),
&["p1".to_string()],
&["p1".to_string()],
&known
)
.is_none());
}
#[test]
fn deleted_projects_drop_out_on_read() {
let known = [project("p1")];
assert_eq!(
known_project_ids(&["p1".to_string(), "gone".to_string()], &known),
["p1".to_string()]
);
}
}
@@ -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"]);
}
}
+11
View File
@@ -13,6 +13,17 @@ pub fn build_router() -> Router {
.route("/api/v1/health", get(handlers::health)) .route("/api/v1/health", get(handlers::health))
.route("/api/v1/oscal/assess", post(handlers::oscal::assess_target)) .route("/api/v1/oscal/assess", post(handlers::oscal::assess_target))
.route("/api/v1/stats/overview", get(handlers::stats_overview)) .route("/api/v1/stats/overview", get(handlers::stats_overview))
// The tenant's projects (owned by the registry), for assigning targets.
.route("/api/v1/projects", get(handlers::projects::list_projects))
// 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). // Unified onboarding targets (#131).
.route( .route(
"/api/v1/targets", "/api/v1/targets",
+175 -2
View File
@@ -1,7 +1,7 @@
use std::sync::Arc; use std::sync::Arc;
use axum::extract::{DefaultBodyLimit, Request, State}; use axum::extract::{DefaultBodyLimit, Request, State};
use axum::http::{HeaderValue, StatusCode}; use axum::http::{HeaderValue, Method, StatusCode};
use axum::middleware::Next; use axum::middleware::Next;
use axum::response::{IntoResponse, Response}; use axum::response::{IntoResponse, Response};
use axum::routing::{delete, get, post}; 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, status: TenantStatus::Active,
user_id: "dev-user".to_string(), user_id: "dev-user".to_string(),
user_name: None, user_name: None,
staff: None,
}; };
request.extensions_mut().insert(ctx); request.extensions_mut().insert(ctx);
} }
@@ -67,6 +68,36 @@ pub async fn require_entitlement(
mut request: Request, mut request: Request,
next: Next, next: Next,
) -> Response { ) -> 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 { let Some(registry) = agent.registry.as_ref() else {
if agent.config.app_env.is_hardened() { if agent.config.app_env.is_hardened() {
// Unreachable after `validate_deployment`, but never widen access // Unreachable after `validate_deployment`, but never widen access
@@ -116,6 +147,76 @@ 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::by(
ctx,
"pruefwerk.support_access",
serde_json::json!({ "method": method, "path": path, "status": status }),
)
}
fn cors_layer(origins: &[String], app_env: AppEnv) -> CorsLayer { fn cors_layer(origins: &[String], app_env: AppEnv) -> CorsLayer {
if origins.is_empty() { if origins.is_empty() {
if app_env.is_hardened() { if app_env.is_hardened() {
@@ -183,6 +284,12 @@ pub async fn start_api_server(
"/api/v1/platform/tenants/{id}/provision", "/api/v1/platform/tenants/{id}/provision",
post(platform::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( .route(
"/api/v1/platform/tenants/{id}/suspend", "/api/v1/platform/tenants/{id}/suspend",
post(platform::suspend), post(platform::suspend),
@@ -308,9 +415,13 @@ pub async fn start_api_server(
"Keycloak JWT auth enabled" "Keycloak JWT auth enabled"
); );
// Layers execute outermost-first: Extension(jwks) → JWT → entitlement // Layers execute outermost-first: Extension(jwks) → JWT → entitlement
// (registry) → status ladder → handlers. // (registry) → support audit → status ladder → handlers.
app = app app = app
.layer(middleware::from_fn(require_tenant_status)) .layer(middleware::from_fn(require_tenant_status))
.layer(middleware::from_fn_with_state(
shared.clone(),
audit_support_writes,
))
.layer(middleware::from_fn_with_state( .layer(middleware::from_fn_with_state(
shared.clone(), shared.clone(),
require_entitlement, require_entitlement,
@@ -350,3 +461,65 @@ pub async fn start_api_server(
Ok(()) 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
})
);
}
}
+9
View File
@@ -478,6 +478,15 @@ impl Database {
) )
.await?; .await?;
// onboarded_targets: multikey on project ids (the `?project=` filter)
self.onboarded_targets()
.create_index(
IndexModel::builder()
.keys(doc! { "project_ids": 1 })
.build(),
)
.await?;
// onboarded_targets: multikey on artifact kind // onboarded_targets: multikey on artifact kind
self.onboarded_targets() self.onboarded_targets()
.create_index( .create_index(
@@ -91,7 +91,7 @@ impl PipelineOrchestrator {
// A scheduled or webhook scan of an unchanged repository has nothing // A scheduled or webhook scan of an unchanged repository has nothing
// new to find; one a person started always runs (after an update of // 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). // 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())? && !GitOps::has_new_commits(&repo_path, repo.last_scanned_commit.as_deref())?
{ {
tracing::info!("[{repo_id}] No new commits, skipping scan"); tracing::info!("[{repo_id}] No new commits, skipping scan");
+139
View File
@@ -47,10 +47,66 @@ pub struct RegistryTenant {
pub id: String, pub id: String,
#[serde(default)] #[serde(default)]
pub slug: String, pub slug: String,
/// The organisation's name, for the support tenant picker.
#[serde(default)]
pub name: String,
#[serde(default)] #[serde(default)]
pub status: String, 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,
/// The product that wrote it (`pruefwerk`).
pub product: String,
/// What happened, e.g. `pruefwerk.support_access`.
pub action: String,
/// `user`, or `staff` for BreakPilot support.
pub actor_type: String,
pub actor_id: String,
pub actor_name: String,
/// What it happened to (e.g. `target`), when it concerns one object.
#[serde(skip_serializing_if = "String::is_empty")]
pub target_type: String,
#[serde(skip_serializing_if = "String::is_empty")]
pub target_id: String,
#[serde(skip_serializing_if = "String::is_empty")]
pub target_name: String,
pub metadata: serde_json::Value,
}
impl AuditEntry {
/// An entry about `ctx`'s requester, with no object yet.
pub fn by(
ctx: &compliance_core::TenantContext,
action: &str,
metadata: serde_json::Value,
) -> Self {
Self {
tenant_id: ctx.tenant_id.clone(),
product: "pruefwerk".to_string(),
action: action.to_string(),
actor_type: if ctx.staff.is_some() { "staff" } else { "user" }.to_string(),
actor_id: ctx.user_id.clone(),
actor_name: ctx.actor_label(),
target_type: String::new(),
target_id: String::new(),
target_name: String::new(),
metadata,
}
}
/// The same entry, about the target `id` named `name`.
#[must_use]
pub fn about_target(mut self, id: &str, name: &str) -> Self {
self.target_type = "target".to_string();
self.target_id = id.to_string();
self.target_name = name.to_string();
self
}
}
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
pub struct ApiKeyVerify { pub struct ApiKeyVerify {
pub valid: bool, pub valid: bool,
@@ -88,6 +144,8 @@ pub struct RegistryClient {
client_secret: Option<String>, client_secret: Option<String>,
token: Mutex<Option<CachedToken>>, token: Mutex<Option<CachedToken>>,
cache: DashMap<String, (Instant, EntitlementCheck)>, cache: DashMap<String, (Instant, EntitlementCheck)>,
/// Each tenant's projects, for [`ENTITLEMENT_TTL`].
projects: DashMap<String, (Instant, Vec<compliance_core::models::Project>)>,
} }
impl std::fmt::Debug for RegistryClient { impl std::fmt::Debug for RegistryClient {
@@ -129,6 +187,7 @@ impl RegistryClient {
.map(|s| s.expose_secret().to_string()), .map(|s| s.expose_secret().to_string()),
token: Mutex::new(None), token: Mutex::new(None),
cache: DashMap::new(), cache: DashMap::new(),
projects: DashMap::new(),
})) }))
} }
@@ -279,6 +338,86 @@ impl RegistryClient {
Ok(out) 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<Option<RegistryTenant>, 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(())
}
/// The tenant's active projects (`GET /v1/tenants/{id}/projects`),
/// cached ≤ 60 s. A deleted project is simply no longer listed.
///
/// # Errors
///
/// The registry could not be asked, or answered with an error.
pub async fn list_projects(
&self,
tenant_id: &str,
) -> Result<Vec<compliance_core::models::Project>, String> {
if let Some(entry) = self.projects.get(tenant_id) {
if entry.0.elapsed() < ENTITLEMENT_TTL {
return Ok(entry.1.clone());
}
}
#[derive(Deserialize)]
struct Page {
#[serde(default)]
items: Vec<compliance_core::models::Project>,
}
let resp = self
.request(
reqwest::Method::GET,
&format!("/v1/tenants/{}/projects", urlencoding::encode(tenant_id)),
)
.await?
.send()
.await
.map_err(|e| format!("project list failed: {e}"))?;
if !resp.status().is_success() {
return Err(format!("project list returned {}", resp.status()));
}
let page: Page = resp
.json()
.await
.map_err(|e| format!("project list invalid: {e}"))?;
self.projects
.insert(tenant_id.to_string(), (Instant::now(), page.items.clone()));
Ok(page.items)
}
/// Verify a portal-issued API key (`bp_…`). /// Verify a portal-issued API key (`bp_…`).
pub async fn verify_api_key(&self, key: &str) -> Result<ApiKeyVerify, String> { pub async fn verify_api_key(&self, key: &str) -> Result<ApiKeyVerify, String> {
let resp = self let resp = self
@@ -25,6 +25,7 @@ fn ctx(tenant_id: &str, slug: &str) -> TenantContext {
status: TenantStatus::Active, status: TenantStatus::Active,
user_id: "u-1".to_string(), user_id: "u-1".to_string(),
user_name: None, user_name: None,
staff: None,
} }
} }
@@ -28,6 +28,7 @@ fn ctx_with(status: TenantStatus) -> TenantContext {
status, status,
user_id: "u-1".to_string(), user_id: "u-1".to_string(),
user_name: None, user_name: None,
staff: None,
} }
} }
@@ -167,3 +168,51 @@ async fn ladder_warning_passes_restricted_blocks_writes_halted_blocks_all() {
.await; .await;
assert_eq!(r.status(), StatusCode::GONE); 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);
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "compliance-core" name = "compliance-core"
version = "0.1.0" version = "0.4.2"
edition = "2021" edition = "2021"
[lints] [lints]
+174 -5
View File
@@ -14,6 +14,13 @@
//! * Signature / expiry invalid → 401. //! * Signature / expiry invalid → 401.
//! * Claims present but tenant_id missing → 401 (treated as a malformed //! * Claims present but tenant_id missing → 401 (treated as a malformed
//! token; the realm must always issue tenant_id). //! 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; use std::sync::Arc;
@@ -28,7 +35,8 @@ use reqwest::StatusCode;
use serde::Deserialize; use serde::Deserialize;
use tokio::sync::RwLock; 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. /// Cached JWKS from Keycloak for token validation.
/// ///
@@ -86,6 +94,25 @@ struct Claims {
tenant_status: Option<TenantStatus>, tenant_status: Option<TenantStatus>,
#[serde(default)] #[serde(default)]
azp: Option<String>, azp: Option<String>,
/// Keycloak realm roles; staff roles live here, not in `org_roles`.
#[serde(default)]
realm_access: Option<RealmAccess>,
}
/// The `realm_access` claim.
#[derive(Debug, Default, Deserialize)]
struct RealmAccess {
#[serde(default)]
roles: Vec<String>,
}
/// 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 /// 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(), _ => return (StatusCode::UNAUTHORIZED, "Invalid authorization header").into_response(),
}; };
match validate_token(token, &jwks_state).await { let requested_tenant = request
Ok(ctx) => { .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); request.extensions_mut().insert(ctx);
next.run(request).await next.run(request).await
} }
Ok(Authenticated::StaffWithoutTenant(staff)) => {
request.extensions_mut().insert(staff);
next.run(request).await
}
Err(e) => { Err(e) => {
tracing::warn!("JWT validation failed: {e}"); tracing::warn!("JWT validation failed: {e}");
(StatusCode::UNAUTHORIZED, "Invalid token").into_response() (StatusCode::UNAUTHORIZED, "Invalid token").into_response()
@@ -211,8 +247,70 @@ fn is_write(m: &Method) -> bool {
!matches!(m, &Method::GET | &Method::HEAD | &Method::OPTIONS) !matches!(m, &Method::GET | &Method::HEAD | &Method::OPTIONS)
} }
async fn validate_token(token: &str, state: &JwksState) -> Result<TenantContext, String> { async fn validate_token(
claims_to_context(decode_claims(token, state).await?) token: &str,
state: &JwksState,
requested_tenant: Option<&str>,
) -> Result<Authenticated, String> {
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<Authenticated, String> {
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 /// Decode + verify a token against the cached JWKS (refreshing once on a
@@ -332,6 +430,7 @@ fn claims_to_context(c: Claims) -> Result<TenantContext, String> {
status, status,
user_id: c.sub, user_id: c.sub,
user_name: c.name.or(c.preferred_username), user_name: c.name.or(c.preferred_username),
staff: None,
}) })
} }
@@ -392,6 +491,76 @@ mod tests {
plan: "professional".to_string(), plan: "professional".to_string(),
tenant_status: Some(TenantStatus::Active), tenant_status: Some(TenantStatus::Active),
azp: Some("pruefwerk-dashboard-stage".to_string()), 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}");
} }
} }
+1
View File
@@ -46,6 +46,7 @@ mod tests {
status: TenantStatus::Active, status: TenantStatus::Active,
user_id: "u-1".to_string(), user_id: "u-1".to_string(),
user_name: None, user_name: None,
staff: None,
} }
} }
+3 -1
View File
@@ -27,4 +27,6 @@ pub use config::{AgentConfig, AppEnv, DashboardConfig, Features, PlcRuntimeConfi
pub use error::CoreError; pub use error::CoreError;
pub use exec_policy::ExecPolicy; pub use exec_policy::ExecPolicy;
pub use net_guard::{NetGuard, NetGuardError}; pub use net_guard::{NetGuard, NetGuardError};
pub use tenant::{OrgRole, TenantContext, TenantStatus}; pub use tenant::{
OrgRole, StaffAccess, TenantContext, TenantStatus, SUPPORT_ROLES, SUPPORT_TENANT_HEADER,
};
+16
View File
@@ -18,4 +18,20 @@ pub struct AuthInfo {
/// The docs site this deployment links to from the sidebar. /// The docs site this deployment links to from the sidebar.
#[serde(default)] #[serde(default)]
pub docs_url: String, 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<SupportTenant>,
}
/// 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,
} }
+7
View File
@@ -77,6 +77,13 @@ pub struct StatusChange {
pub status: FindingStatus, pub status: FindingStatus,
/// The user id of whoever changed it. /// The user id of whoever changed it.
pub by: String, 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<String>,
/// Made by BreakPilot support rather than one of the tenant's users.
#[serde(default)]
pub support: bool,
#[serde(with = "super::serde_helpers::bson_datetime")] #[serde(with = "super::serde_helpers::bson_datetime")]
pub at: DateTime<Utc>, pub at: DateTime<Utc>,
/// Why; required when a risk is accepted. /// Why; required when a risk is accepted.
+3 -1
View File
@@ -14,13 +14,14 @@ pub mod onboarding;
pub mod oscal; pub mod oscal;
pub mod oscal_assessment; pub mod oscal_assessment;
pub mod pentest; pub mod pentest;
pub mod project;
pub mod repository; pub mod repository;
pub mod sbom; pub mod sbom;
pub mod scan; pub mod scan;
pub(crate) mod serde_helpers; pub(crate) mod serde_helpers;
pub mod werkbank; pub mod werkbank;
pub use auth::AuthInfo; pub use auth::{AuthInfo, SupportTenant};
pub use chat::{ChatMessage, ChatRequest, ChatResponse, SourceReference}; pub use chat::{ChatMessage, ChatRequest, ChatResponse, SourceReference};
pub use credentials::Credentials; pub use credentials::Credentials;
pub use cve::{CveAlert, CveSource}; pub use cve::{CveAlert, CveSource};
@@ -51,6 +52,7 @@ pub use pentest::{
PentestStatus, PentestStrategy, SeverityDistribution, TestUserRecord, TesterInfo, PentestStatus, PentestStrategy, SeverityDistribution, TestUserRecord, TesterInfo,
ToolCallRecord, ToolCallRecord,
}; };
pub use project::{Project, ProjectKind};
pub use repository::ScanTrigger; pub use repository::ScanTrigger;
pub use sbom::{SbomEntry, VulnRef}; pub use sbom::{SbomEntry, VulnRef};
pub use scan::{ pub use scan::{
+6
View File
@@ -589,6 +589,11 @@ pub struct OnboardedTarget {
/// Cached count of findings across this target's scans. /// Cached count of findings across this target's scans.
#[serde(default)] #[serde(default)]
pub findings_count: u32, pub findings_count: u32,
/// The tenant's projects (registry ids) this target belongs to: a
/// product or machine, or a topic such as the CRA. Organisational only;
/// what gets checked follows `compliance_profile`.
#[serde(default)]
pub project_ids: Vec<String>,
/// Creation timestamp. /// Creation timestamp.
#[serde( #[serde(
default = "chrono::Utc::now", default = "chrono::Utc::now",
@@ -623,6 +628,7 @@ impl OnboardedTarget {
webhook_enabled: false, webhook_enabled: false,
webhook_secret: None, webhook_secret: None,
findings_count: 0, findings_count: 0,
project_ids: Vec::new(),
created_at: now, created_at: now,
updated_at: now, updated_at: now,
} }
+46
View File
@@ -0,0 +1,46 @@
//! A tenant's projects, owned by the platform registry.
//!
//! A project groups targets organisationally: a customer's product or
//! machine, or a topic such as the CRA or the Data Act. It never changes what
//! gets checked. Targets refer to projects by the registry's id.
use serde::{Deserialize, Serialize};
/// What a project stands for.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProjectKind {
/// A customer's product or machine.
Product,
/// A topic such as the CRA or the Data Act.
Topic,
}
/// One of a tenant's projects, as the registry lists it
/// (`GET /v1/tenants/{id}/projects`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Project {
/// The registry's id (a UUID).
pub id: String,
pub name: String,
pub kind: ProjectKind,
#[serde(default)]
pub description: String,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_registry_project_reads() {
let p: Project = serde_json::from_value(serde_json::json!({
"id": "0b7d51aa-9f1c-4e33-8a1f-2d8c1e0f9a77",
"name": "Rangierlok 3000",
"kind": "product"
}))
.expect("deserialize");
assert_eq!(p.kind, ProjectKind::Product);
assert_eq!(p.description, "");
}
}
+14
View File
@@ -7,4 +7,18 @@ pub enum ScanTrigger {
Scheduled, Scheduled,
Webhook, Webhook,
Manual, 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,
}
}
} }
+42
View File
@@ -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<String>,
}
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 /// Everything we know about the requesting tenant at the moment a request
/// lands. Cheap to clone (every field is owned + small). /// lands. Cheap to clone (every field is owned + small).
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
@@ -143,9 +170,23 @@ pub struct TenantContext {
/// Optional user-facing name from the `name` / `preferred_username` /// Optional user-facing name from the `name` / `preferred_username`
/// claim. Only used in audit + log lines. /// claim. Only used in audit + log lines.
pub user_name: Option<String>, pub user_name: Option<String>,
/// 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<StaffAccess>,
} }
impl TenantContext { 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. /// True if the caller holds at least one of the listed roles.
pub fn has_any_role(&self, roles: &[OrgRole]) -> bool { pub fn has_any_role(&self, roles: &[OrgRole]) -> bool {
self.org_roles.iter().any(|r| roles.contains(r)) self.org_roles.iter().any(|r| roles.contains(r))
@@ -197,6 +238,7 @@ mod tests {
status: TenantStatus::Active, status: TenantStatus::Active,
user_id: "u".into(), user_id: "u".into(),
user_name: None, user_name: None,
staff: None,
}; };
assert!(ctx.has_any_role(&[OrgRole::ItAdmin])); assert!(ctx.has_any_role(&[OrgRole::ItAdmin]));
assert!(ctx.has_any_role(&[OrgRole::Cxo, OrgRole::ItAdmin])); assert!(ctx.has_any_role(&[OrgRole::Cxo, OrgRole::ItAdmin]));
+107 -5
View File
@@ -20,24 +20,79 @@ use axum::{
response::{IntoResponse, Response}, 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)] #[derive(Debug, Clone)]
pub struct TenantCtx(pub TenantContext); pub struct TenantCtx(pub TenantContext);
/// Why a tenant-scoped route refused the request.
#[derive(Debug)] #[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 { 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 { fn into_response(self) -> Response {
( (
StatusCode::UNAUTHORIZED, StatusCode::FORBIDDEN,
"Missing tenant context — request was not authenticated", axum::Json(serde_json::json!({ "error": "support_only" })),
) )
.into_response() .into_response()
} }
} }
impl<S> FromRequestParts<S> for StaffCtx
where
S: Send + Sync,
{
type Rejection = StaffCtxRejection;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let chosen = parts
.extensions
.get::<TenantContext>()
.and_then(|ctx| ctx.staff.clone());
chosen
.or_else(|| parts.extensions.get::<StaffAccess>().cloned())
.map(StaffCtx)
.ok_or(StaffCtxRejection)
}
}
impl<S> FromRequestParts<S> for TenantCtx impl<S> FromRequestParts<S> for TenantCtx
where where
S: Send + Sync, S: Send + Sync,
@@ -50,7 +105,13 @@ where
.get::<TenantContext>() .get::<TenantContext>()
.cloned() .cloned()
.map(TenantCtx) .map(TenantCtx)
.ok_or(TenantCtxRejection) .ok_or_else(|| {
if parts.extensions.get::<StaffAccess>().is_some() {
TenantCtxRejection::TenantNotSelected
} else {
TenantCtxRejection::Unauthenticated
}
})
} }
} }
@@ -71,6 +132,7 @@ mod tests {
status: TenantStatus::Active, status: TenantStatus::Active,
user_id: "u-1".to_string(), user_id: "u-1".to_string(),
user_name: None, user_name: None,
staff: None,
} }
} }
@@ -92,4 +154,44 @@ mod tests {
let err = TenantCtx::from_request_parts(&mut parts, &()).await; let err = TenantCtx::from_request_parts(&mut parts, &()).await;
assert!(err.is_err()); 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());
}
} }
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "compliance-dashboard" name = "compliance-dashboard"
version = "0.1.0" version = "0.4.2"
edition = "2021" edition = "2021"
default-run = "compliance-dashboard" default-run = "compliance-dashboard"
+247
View File
@@ -5204,3 +5204,250 @@ input[type="file"] {
color: var(--text-secondary); color: var(--text-secondary);
font-size: 13px; 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;
}
/* ═══════════════════════════════════════════════════════════════
PROJECTS — chips, the list filter and the picker in the editor
═══════════════════════════════════════════════════════════════ */
.project-chips {
display: inline-flex;
flex-wrap: wrap;
gap: 4px;
margin-left: 8px;
vertical-align: middle;
}
.target-head-text .project-chips {
margin: 4px 0 0;
display: flex;
}
.project-chip {
display: inline-block;
padding: 1px 8px;
border-radius: 999px;
background: var(--accent-muted);
color: var(--accent);
font-size: 11px;
font-weight: 600;
white-space: nowrap;
}
.project-filter {
margin-left: auto;
display: inline-flex;
align-items: center;
gap: 8px;
font-size: 13px;
color: var(--text-secondary);
}
.project-filter select {
min-width: 180px;
padding: 6px 10px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--bg-elevated);
color: var(--text-primary);
font: inherit;
}
.project-picker {
margin: 12px 0 0;
padding: 10px 12px;
border: 1px solid var(--border);
border-radius: 10px;
}
.project-picker legend {
padding: 0 4px;
font-size: 13px;
font-weight: 600;
}
.project-picker-list {
display: grid;
gap: 4px;
max-height: 200px;
overflow-y: auto;
}
.project-picker-item {
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
cursor: pointer;
}
.project-picker-kind {
margin-left: auto;
font-size: 12px;
color: var(--text-tertiary);
}
.project-picker-hint {
margin: 8px 0 0;
font-size: 12px;
color: var(--text-tertiary);
}
@media (max-width: 560px) {
.project-filter { margin-left: 0; width: 100%; }
.project-filter select { flex: 1; min-width: 0; }
}
+2 -2
View File
@@ -55,7 +55,6 @@ pub enum Route {
McpTokensPage {}, McpTokensPage {},
} }
const FAVICON: Asset = asset!("/assets/favicon.svg");
const MAIN_CSS: Asset = asset!("/assets/main.css"); const MAIN_CSS: Asset = asset!("/assets/main.css");
const TAILWIND_CSS: Asset = asset!("/assets/tailwind.css"); const TAILWIND_CSS: Asset = asset!("/assets/tailwind.css");
const VIS_NETWORK_JS: Asset = asset!("/assets/vis-network.min.js"); const VIS_NETWORK_JS: Asset = asset!("/assets/vis-network.min.js");
@@ -66,7 +65,8 @@ pub fn App() -> Element {
// Also sent as the X-Robots-Tag header; in the markup it is visible // Also sent as the X-Robots-Tag header; in the markup it is visible
// in the page source and honoured by crawlers that read only HTML. // in the page source and honoured by crawlers that read only HTML.
document::Meta { name: "robots", content: "noindex, nofollow" } document::Meta { name: "robots", content: "noindex, nofollow" }
document::Link { rel: "icon", href: FAVICON } // The BreakPilot chevron, at a fixed path (served by the server).
document::Link { rel: "icon", r#type: "image/svg+xml", href: "/favicon.svg" }
document::Link { rel: "stylesheet", href: TAILWIND_CSS } document::Link { rel: "stylesheet", href: TAILWIND_CSS }
document::Link { rel: "stylesheet", href: MAIN_CSS } document::Link { rel: "stylesheet", href: MAIN_CSS }
document::Script { src: VIS_NETWORK_JS } document::Script { src: VIS_NETWORK_JS }
@@ -4,6 +4,7 @@ use crate::app::Route;
use crate::components::help_chat::HelpChat; use crate::components::help_chat::HelpChat;
use crate::components::notification_bell::NotificationBell; use crate::components::notification_bell::NotificationBell;
use crate::components::sidebar::Sidebar; use crate::components::sidebar::Sidebar;
use crate::components::support::{SupportBanner, SupportPicker};
use crate::components::toast::{ToastContainer, Toasts}; use crate::components::toast::{ToastContainer, Toasts};
use crate::infrastructure::auth_check::check_auth; use crate::infrastructure::auth_check::check_auth;
use crate::infrastructure::platform::fetch_platform_info; use crate::infrastructure::platform::fetch_platform_info;
@@ -41,12 +42,23 @@ pub fn AppShell() -> Element {
}); });
match auth() { 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 => { Some(Ok(info)) if info.authenticated => {
use_context_provider(|| Signal::new(info.clone())); use_context_provider(|| Signal::new(info.clone()));
rsx! { rsx! {
div { class: "app-shell", div { class: "app-shell",
Sidebar {} Sidebar {}
main { class: "main-content", main { class: "main-content",
if let Some(tenant) = info.support_tenant.clone() {
SupportBanner { tenant }
}
Outlet::<Route> {} Outlet::<Route> {}
} }
NotificationBell {} NotificationBell {}
@@ -16,9 +16,11 @@ pub mod notification_bell;
pub mod page_header; pub mod page_header;
pub mod pagination; pub mod pagination;
pub mod pentest_wizard; pub mod pentest_wizard;
pub mod projects;
pub mod scan_coverage; pub mod scan_coverage;
pub mod scan_runs; pub mod scan_runs;
pub mod severity_badge; pub mod severity_badge;
pub mod sidebar; pub mod sidebar;
pub mod support;
pub mod theme_toggle; pub mod theme_toggle;
pub mod toast; pub mod toast;
@@ -0,0 +1,75 @@
//! A target's projects: shown as chips, chosen with a checkbox list.
use compliance_core::models::Project;
use dioxus::prelude::*;
use crate::i18n::texts::projects as tx;
use crate::i18n::use_lang;
use crate::infrastructure::projects::projects_named;
/// The projects a target belongs to, as small chips. Nothing when it
/// belongs to none (or only to deleted ones).
#[component]
pub fn ProjectChips(ids: Vec<String>, projects: Vec<Project>) -> Element {
let lang = use_lang()();
let shown = projects_named(&ids, &projects);
if shown.is_empty() {
return rsx! {};
}
rsx! {
span { class: "project-chips",
for p in shown {
span {
key: "{p.id}",
class: "project-chip",
title: "{tx::kind(p.kind).get(lang)}",
"{p.name}"
}
}
}
}
}
/// Choose a target's projects from the tenant's list.
#[component]
pub fn ProjectPicker(projects: Vec<Project>, mut selected: Signal<Vec<String>>) -> Element {
let lang = use_lang()();
rsx! {
fieldset { class: "project-picker",
legend { {tx::TITLE.get(lang)} }
if projects.is_empty() {
p { class: "project-picker-hint", {tx::NONE_YET.get(lang)} }
} else {
div { class: "project-picker-list",
for p in projects {
{
let id = p.id.clone();
let checked = selected.read().contains(&id);
rsx! {
label { key: "{p.id}", class: "project-picker-item",
input {
r#type: "checkbox",
checked,
onchange: move |e| {
let mut ids = selected.write();
if e.checked() {
if !ids.contains(&id) {
ids.push(id.clone());
}
} else {
ids.retain(|x| x != &id);
}
},
}
span { class: "project-picker-name", "{p.name}" }
span { class: "project-picker-kind", {tx::kind(p.kind).get(lang)} }
}
}
}
}
}
p { class: "project-picker-hint", {tx::HINT.get(lang)} }
}
}
}
}
@@ -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::<String>::None);
let mut error = use_signal(|| Option::<String>::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<SupportTenantRow> =
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)}
}
}
}
}
+105
View File
@@ -1653,6 +1653,11 @@ pub mod findings {
de: "Verlauf", de: "Verlauf",
en: "History", en: "History",
}; };
/// A user of the tenant whose name is not known.
pub const SOMEONE: Text = Text {
de: "Benutzer",
en: "User",
};
pub const REASON: Text = Text { pub const REASON: Text = Text {
de: "Begründung", de: "Begründung",
en: "Reason", en: "Reason",
@@ -2397,6 +2402,106 @@ pub mod demo {
} }
/// What each scan does and why it cannot run, for the applicable-scans list. /// What each scan does and why it cannot run, for the applicable-scans list.
/// The tenant's projects: products, machines or topics that group targets.
pub mod projects {
use super::Text;
use compliance_core::models::ProjectKind;
pub const TITLE: Text = Text {
de: "Projekte",
en: "Projects",
};
pub const FILTER: Text = Text {
de: "Projekt",
en: "Project",
};
pub const ALL: Text = Text {
de: "Alle Projekte",
en: "All projects",
};
pub const HINT: Text = Text {
de: "Projekte legen Sie im Portal an. Sie ordnen Prüfobjekte nur; was geprüft \
wird, ändert sich dadurch nicht.",
en: "Projects are created in the portal. They only group targets; what gets \
checked does not change.",
};
pub const NONE_YET: Text = Text {
de: "Noch keine Projekte. Legen Sie sie im Portal an.",
en: "No projects yet. Create them in the portal.",
};
pub const LOAD_FAILED: Text = Text {
de: "Die Projekte konnten nicht geladen werden",
en: "The projects could not be loaded",
};
pub const NONE_IN_PROJECT: Text = Text {
de: "Diesem Projekt ist noch kein Prüfobjekt zugeordnet.",
en: "No target belongs to this project yet.",
};
/// What kind of project it is. Exhaustive: a new kind needs both
/// languages.
pub fn kind(kind: ProjectKind) -> Text {
match kind {
ProjectKind::Product => Text {
de: "Produkt",
en: "Product",
},
ProjectKind::Topic => Text {
de: "Thema",
en: "Topic",
},
}
}
}
/// 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. /// The help assistant.
pub mod help { pub mod help {
use super::Text; use super::Text;
@@ -213,11 +213,26 @@ async fn attach_token(
} }
let session: tower_sessions::Session = FullstackContext::extract().await?; let session: tower_sessions::Session = FullstackContext::extract().await?;
match current_user(state, &session).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)), 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 /// Decode the JWT's payload (no signature verification — the agent
/// does that) and check the `exp` claim. Treats malformed tokens as /// does that) and check the `exp` claim. Treats malformed tokens as
/// expired so the refresh path runs. /// expired so the refresh path runs.
@@ -16,7 +16,7 @@ use url::Url;
use super::{ use super::{
error::DashboardError, error::DashboardError,
server_state::ServerState, 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"; pub const LOGGED_IN_USER_SESS_KEY: &str = "logged-in-user";
@@ -126,6 +126,30 @@ pub async fn auth_login(
Extension(pending): Extension<PendingOAuthStore>, Extension(pending): Extension<PendingOAuthStore>,
Query(params): Query<HashMap<String, String>>, Query(params): Query<HashMap<String, String>>,
) -> Result<impl IntoResponse, DashboardError> { ) -> Result<impl IntoResponse, DashboardError> {
start_login(state, &pending, &params, false)
}
/// `GET /auth/staff`: the sign-in for BreakPilot staff, straight to the
/// company login (`kc_idp_hint`, as the portal's staff sign-in does). The
/// realm's own login form does not offer it. Without `STAFF_IDP_HINT` this
/// is the ordinary sign-in.
#[axum::debug_handler]
pub async fn auth_staff_login(
Extension(state): Extension<ServerState>,
Extension(pending): Extension<PendingOAuthStore>,
Query(params): Query<HashMap<String, String>>,
) -> Result<impl IntoResponse, DashboardError> {
start_login(state, &pending, &params, true)
}
/// Send the browser to Keycloak's login; with `staff`, to the staff
/// identity provider when one is configured.
fn start_login(
state: ServerState,
pending: &PendingOAuthStore,
params: &HashMap<String, String>,
staff: bool,
) -> Result<Redirect, DashboardError> {
let kc = state let kc = state
.keycloak .keycloak
.ok_or(DashboardError::Other("Keycloak not configured".into()))?; .ok_or(DashboardError::Other("Keycloak not configured".into()))?;
@@ -157,6 +181,9 @@ pub async fn auth_login(
.append_pair("state", &csrf_state) .append_pair("state", &csrf_state)
.append_pair("code_challenge", &code_challenge) .append_pair("code_challenge", &code_challenge)
.append_pair("code_challenge_method", "S256"); .append_pair("code_challenge_method", "S256");
if let Some(hint) = kc.staff_idp_hint.as_deref().filter(|_| staff) {
url.query_pairs_mut().append_pair("kc_idp_hint", hint);
}
Ok(Redirect::temporary(url.as_str())) Ok(Redirect::temporary(url.as_str()))
} }
@@ -241,9 +268,12 @@ pub async fn auth_callback(
.unwrap_or_default(); .unwrap_or_default();
let tenant_slug = tenant_slug_from_token(&tokens.access_token); let tenant_slug = tenant_slug_from_token(&tokens.access_token);
let staff = has_support_role(&tokens.access_token);
let user_state = UserStateInner { let user_state = UserStateInner {
sub: userinfo.sub, sub: userinfo.sub,
tenant_slug, tenant_slug,
staff,
support_tenant: None,
access_token: tokens.access_token, access_token: tokens.access_token,
refresh_token: tokens.refresh_token.unwrap_or_default(), refresh_token: tokens.refresh_token.unwrap_or_default(),
user: User { user: User {
@@ -52,7 +52,14 @@ pub async fn check_auth() -> Result<AuthInfo, ServerFnError> {
match user_state { match user_state {
Some(u) => Ok(AuthInfo { Some(u) => Ok(AuthInfo {
authenticated: true, 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(), docs_url: state.docs_url.clone(),
sub: u.sub, sub: u.sub,
email: u.user.email, email: u.user.email,
@@ -6,6 +6,9 @@ pub struct KeycloakConfig {
pub client_id: String, pub client_id: String,
pub redirect_uri: String, pub redirect_uri: String,
pub app_url: String, pub app_url: String,
/// The identity provider BreakPilot staff sign in with (`STAFF_IDP_HINT`,
/// as for the portal); `/auth/staff` goes straight to it.
pub staff_idp_hint: Option<String>,
} }
impl KeycloakConfig { impl KeycloakConfig {
@@ -15,12 +18,17 @@ impl KeycloakConfig {
let client_id = std::env::var("KEYCLOAK_CLIENT_ID").ok()?; let client_id = std::env::var("KEYCLOAK_CLIENT_ID").ok()?;
let redirect_uri = std::env::var("REDIRECT_URI").ok()?; let redirect_uri = std::env::var("REDIRECT_URI").ok()?;
let app_url = std::env::var("APP_URL").ok()?; let app_url = std::env::var("APP_URL").ok()?;
let staff_idp_hint = std::env::var("STAFF_IDP_HINT")
.ok()
.map(|h| h.trim().to_string())
.filter(|h| !h.is_empty());
Some(Self { Some(Self {
url, url,
realm, realm,
client_id, client_id,
redirect_uri, redirect_uri,
app_url, app_url,
staff_idp_hint,
}) })
} }
@@ -15,10 +15,12 @@ pub mod notifications;
pub mod onboarding; pub mod onboarding;
pub mod pentest; pub mod pentest;
pub mod platform; pub mod platform;
pub mod projects;
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
pub mod sbom; pub mod sbom;
pub mod scans; pub mod scans;
pub mod stats; pub mod stats;
pub mod support;
// Server-only modules // Server-only modules
#[cfg(feature = "server")] #[cfg(feature = "server")]
@@ -45,7 +47,7 @@ mod session_store;
mod user_state; mod user_state;
#[cfg(feature = "server")] #[cfg(feature = "server")]
pub use auth::{auth_callback, auth_login, logout, PendingOAuthStore}; pub use auth::{auth_callback, auth_login, auth_staff_login, logout, PendingOAuthStore};
#[cfg(feature = "server")] #[cfg(feature = "server")]
pub use auth_middleware::require_auth; pub use auth_middleware::require_auth;
#[cfg(feature = "server")] #[cfg(feature = "server")]
@@ -311,8 +311,17 @@ pub fn validate_artifact_ref(kind: &str, source_ref: &str) -> Option<String> {
/// List onboarded targets. /// List onboarded targets.
#[server] #[server]
pub async fn fetch_targets() -> Result<TargetsResponse, ServerFnError> { pub async fn fetch_targets() -> Result<TargetsResponse, ServerFnError> {
let resp = super::agent_client::agent_get("/api/v1/targets") fetch_targets_in(None).await
.await? }
/// The targets, only those of `project` when given (`?project=`).
#[server]
pub async fn fetch_targets_in(project: Option<String>) -> Result<TargetsResponse, ServerFnError> {
let mut req = super::agent_client::agent_get("/api/v1/targets").await?;
if let Some(project) = project.filter(|p| !p.is_empty()) {
req = req.query(&[("project", project)]);
}
let resp = req
.send() .send()
.await .await
.map_err(|e| ServerFnError::new(e.to_string()))?; .map_err(|e| ServerFnError::new(e.to_string()))?;
@@ -0,0 +1,89 @@
//! The tenant's projects (owned by the platform registry) and the targets'
//! assignments to them.
use compliance_core::models::Project;
use dioxus::prelude::*;
/// The tenant's projects (`GET /api/v1/projects`).
#[server]
pub async fn fetch_projects() -> Result<Vec<Project>, ServerFnError> {
let resp = super::agent_client::agent_get("/api/v1/projects")
.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()))
}
/// Replace the projects target `id` belongs to.
///
/// # Errors
///
/// The agent refused, e.g. an id that is no longer one of the tenant's
/// projects (422).
#[server]
pub async fn set_target_projects(
id: String,
project_ids: Vec<String>,
) -> Result<(), ServerFnError> {
let resp = super::agent_client::agent_request(
reqwest::Method::PATCH,
&format!("/api/v1/targets/{id}"),
)
.await?
.json(&serde_json::json!({ "project_ids": project_ids }))
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
super::agent_client::ok_or_error(resp).await
}
/// The ids in a target's JSON (`project_ids`), as the agent returned it.
pub fn project_ids_of(target: &serde_json::Value) -> Vec<String> {
target
.get("project_ids")
.and_then(|ids| ids.as_array())
.map(|ids| {
ids.iter()
.filter_map(|id| id.as_str().map(str::to_owned))
.collect()
})
.unwrap_or_default()
}
/// The projects among `projects` that `ids` name, in the projects' order.
/// Ids of deleted projects are left out.
pub fn projects_named<'a>(ids: &[String], projects: &'a [Project]) -> Vec<&'a Project> {
projects.iter().filter(|p| ids.contains(&p.id)).collect()
}
#[cfg(test)]
mod tests {
use super::*;
use compliance_core::models::ProjectKind;
fn project(id: &str, name: &str) -> Project {
Project {
id: id.to_string(),
name: name.to_string(),
kind: ProjectKind::Product,
description: String::new(),
}
}
#[test]
fn a_targets_project_ids_are_read() {
let t = serde_json::json!({ "name": "fw", "project_ids": ["p1", "p2"] });
assert_eq!(project_ids_of(&t), ["p1", "p2"]);
assert!(project_ids_of(&serde_json::json!({ "name": "old" })).is_empty());
}
#[test]
fn deleted_projects_are_not_shown() {
let projects = [project("p1", "Lok"), project("p2", "CRA")];
let shown = projects_named(&["p2".to_string(), "gone".to_string()], &projects);
let names: Vec<&str> = shown.iter().map(|p| p.name.as_str()).collect();
assert_eq!(names, ["CRA"]);
}
}
@@ -15,7 +15,7 @@ use super::error::DashboardError;
use super::keycloak_config::KeycloakConfig; use super::keycloak_config::KeycloakConfig;
use super::server_state::{ServerState, ServerStateInner}; use super::server_state::{ServerState, ServerStateInner};
use super::session_store::{load_session_key, MongoSessionStore}; use super::session_store::{load_session_key, MongoSessionStore};
use super::{auth_callback, auth_login, logout, require_auth, PendingOAuthStore}; use super::{auth_callback, auth_login, auth_staff_login, logout, require_auth, PendingOAuthStore};
/// The docs site when `DOCS_URL` is unset: served on the dashboard host. /// The docs site when `DOCS_URL` is unset: served on the dashboard host.
/// Keep the trailing slash: the docs route matches `/docs/*`, and a plain /// Keep the trailing slash: the docs route matches `/docs/*`, and a plain
@@ -117,7 +117,12 @@ pub fn server_start(app: fn() -> Element) -> Result<(), DashboardError> {
"/robots.txt", "/robots.txt",
get(|| async { "User-agent: *\nDisallow: /\n" }), get(|| async { "User-agent: *\nDisallow: /\n" }),
) )
// The BreakPilot chevron at the paths browsers and tools ask
// for; `/favicon.ico` too, since browsers read an SVG there.
.route("/favicon.svg", get(favicon))
.route("/favicon.ico", get(favicon))
.route("/auth", get(auth_login)) .route("/auth", get(auth_login))
.route("/auth/staff", get(auth_staff_login))
.route("/auth/callback", get(auth_callback)) .route("/auth/callback", get(auth_callback))
.route("/logout", get(logout)) .route("/logout", get(logout))
.serve_dioxus_application(ServeConfig::new(), app) .serve_dioxus_application(ServeConfig::new(), app)
@@ -211,6 +216,20 @@ async fn seed_default_mcp_servers(db: &Database, mcp_endpoint_url: Option<&str>)
} }
} }
/// The BreakPilot chevron, the icon the portal and the website use.
const FAVICON_SVG: &str = include_str!("../../assets/favicon.svg");
/// The favicon: the chevron as SVG, cacheable for a day.
async fn favicon() -> impl axum::response::IntoResponse {
(
[
(axum::http::header::CONTENT_TYPE, "image/svg+xml"),
(axum::http::header::CACHE_CONTROL, "public, max-age=86400"),
],
FAVICON_SVG,
)
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -224,4 +243,10 @@ mod tests {
assert_eq!(non_blank(Some(" ".into())), None); assert_eq!(non_blank(Some(" ".into())), None);
assert_eq!(non_blank(None), None); assert_eq!(non_blank(None), None);
} }
#[test]
fn the_favicon_is_the_breakpilot_chevron() {
assert!(FAVICON_SVG.contains("M12 44 L32 20 L52 44"));
assert!(FAVICON_SVG.contains("#4F46E5"));
}
} }
@@ -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<Vec<SupportTenantRow>, 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");
}
}
@@ -1,3 +1,4 @@
use compliance_core::models::SupportTenant;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
/// Per-session user data stored in the tower-sessions session store. /// 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. /// portal. Empty in sessions from before it was stored.
#[serde(default)] #[serde(default)]
pub tenant_slug: String, 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<SupportTenant>,
} }
/// Basic user profile stored alongside the session. /// 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 /// The signature is not checked: the token comes straight from Keycloak's
/// token endpoint, and the slug only builds a link. /// token endpoint, and the slug only builds a link.
pub fn tenant_slug_from_token(access_token: &str) -> String { pub fn tenant_slug_from_token(access_token: &str) -> String {
use base64::Engine; token_claims(access_token)
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::<serde_json::Value>(&json).ok())
.and_then(|claims| claims.get("tenant_slug")?.as_str().map(str::to_owned)) .and_then(|claims| claims.get("tenant_slug")?.as_str().map(str::to_owned))
.unwrap_or_default() .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<serde_json::Value> {
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 /// 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. /// 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"), ""); 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] #[test]
fn the_link_goes_to_the_workspace_when_the_slug_is_plain() { fn the_link_goes_to_the_workspace_when_the_slug_is_plain() {
let portal = Some("https://app-stage.breakpilot.com/"); let portal = Some("https://app-stage.breakpilot.com/");
@@ -24,6 +24,7 @@ enum SaveState {
#[component] #[component]
pub fn FindingDetailPage(id: String) -> Element { pub fn FindingDetailPage(id: String) -> Element {
let lang = use_lang()(); let lang = use_lang()();
let me = use_context::<Signal<compliance_core::models::AuthInfo>>()();
let finding_id = id.clone(); let finding_id = id.clone();
let mut status_save = use_signal(|| SaveState::Idle); let mut status_save = use_signal(|| SaveState::Idle);
let mut feedback_save = use_signal(|| SaveState::Idle); let mut feedback_save = use_signal(|| SaveState::Idle);
@@ -332,7 +333,11 @@ pub fn FindingDetailPage(id: String) -> Element {
for change in f.status_history.iter().rev() { for change in f.status_history.iter().rev() {
li { style: "margin-bottom: 4px;", li { style: "margin-bottom: 4px;",
strong { {tx::status(&change.status).get(lang)} } 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" },
{changed_by(change, &me, lang)}
}
" · {format_time(&change.at, lang)}"
if let Some(reason) = &change.reason { if let Some(reason) = &change.reason {
div { style: "color: var(--text-secondary);", "{tx::REASON.get(lang)}: {reason}" } div { style: "color: var(--text-secondary);", "{tx::REASON.get(lang)}: {reason}" }
} }
@@ -433,3 +438,70 @@ fn CatalogControls(ids: Vec<String>) -> Element {
} }
} }
} }
/// Who made a status change, in words. Changes from before names were
/// recorded carry only a user id: the reader's own reads as their name,
/// anyone else's as "Benutzer" and the start of the id.
fn changed_by(
change: &compliance_core::models::finding::StatusChange,
me: &compliance_core::models::AuthInfo,
lang: crate::i18n::Lang,
) -> String {
if let Some(name) = change.by_name.as_deref().filter(|n| !n.trim().is_empty()) {
return name.to_string();
}
if !me.sub.is_empty() && change.by == me.sub && !me.name.trim().is_empty() {
return me.name.clone();
}
let short: String = change.by.chars().take(8).collect();
format!("{} {short}", tx::SOMEONE.get(lang))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::i18n::Lang;
use compliance_core::models::{AuthInfo, StatusChange};
fn change(by: &str, by_name: Option<&str>) -> StatusChange {
StatusChange {
status: FindingStatus::FalsePositive,
by: by.to_string(),
by_name: by_name.map(String::from),
support: false,
at: chrono::Utc::now(),
reason: None,
}
}
fn me() -> AuthInfo {
AuthInfo {
authenticated: true,
sub: "14e9a93b-3abb-4358-b5d8-c34a0f800a16".to_string(),
name: "Sharang Parnerkar".to_string(),
..Default::default()
}
}
#[test]
fn a_recorded_name_is_shown() {
let c = change("x", Some("BreakPilot-Support (Sharang)"));
assert_eq!(
changed_by(&c, &me(), Lang::De),
"BreakPilot-Support (Sharang)"
);
}
#[test]
fn an_old_change_of_ones_own_shows_ones_name() {
let c = change("14e9a93b-3abb-4358-b5d8-c34a0f800a16", None);
assert_eq!(changed_by(&c, &me(), Lang::De), "Sharang Parnerkar");
}
#[test]
fn an_old_change_of_someone_else_shows_a_short_id() {
let c = change("0b7d51aa-9f1c-4e33-8a1f-2d8c1e0f9a77", None);
assert_eq!(changed_by(&c, &me(), Lang::De), "Benutzer 0b7d51aa");
assert_eq!(changed_by(&c, &me(), Lang::En), "User 0b7d51aa");
}
}
+26 -2
View File
@@ -11,6 +11,7 @@ use crate::components::artifact_upload::ArtifactUpload;
use crate::components::cra_bar::CraBar; use crate::components::cra_bar::CraBar;
use crate::components::evidence_button::EvidencePackButton; use crate::components::evidence_button::EvidencePackButton;
use crate::components::manual_findings::ManualFindingsPanel; use crate::components::manual_findings::ManualFindingsPanel;
use crate::components::projects::{ProjectChips, ProjectPicker};
use crate::components::scan_coverage::ScanCoverage; use crate::components::scan_coverage::ScanCoverage;
use crate::components::scan_runs::ScanRunList; use crate::components::scan_runs::ScanRunList;
use crate::components::severity_badge::SeverityBadge; use crate::components::severity_badge::SeverityBadge;
@@ -25,6 +26,7 @@ use crate::infrastructure::onboarding::{
ArchivePassword, ArtifactInputDto, PasswordOutcome, ArchivePassword, ArtifactInputDto, PasswordOutcome,
}; };
use crate::infrastructure::platform::{use_source_only, SourceOnlyNote}; use crate::infrastructure::platform::{use_source_only, SourceOnlyNote};
use crate::infrastructure::projects::{fetch_projects, project_ids_of, set_target_projects};
/// Open findings listed on the page; the rest are one click away. /// Open findings listed on the page; the rest are one click away.
const OPEN_SHOWN: usize = 5; const OPEN_SHOWN: usize = 5;
@@ -94,6 +96,7 @@ pub fn TargetPage(id: String) -> Element {
let mut adding_manual = use_signal(|| false); let mut adding_manual = use_signal(|| false);
let mut starting = use_signal(|| false); let mut starting = use_signal(|| false);
let mut scans_started = use_signal(|| 0u32); let mut scans_started = use_signal(|| 0u32);
let projects = use_resource(fetch_projects);
let snapshot = target.read().clone(); let snapshot = target.read().clone();
let Some(Some(resp)) = snapshot else { let Some(Some(resp)) = snapshot else {
@@ -134,6 +137,9 @@ pub fn TargetPage(id: String) -> Element {
header { class: "target-head", header { class: "target-head",
div { class: "target-head-text", div { class: "target-head-text",
h2 { "{name}" } h2 { "{name}" }
if let Some(Ok(projects)) = projects.read().clone() {
ProjectChips { ids: project_ids_of(&t), projects }
}
p { class: "target-head-meta", p { class: "target-head-meta",
span { "{type_label}" } span { "{type_label}" }
for a in artifacts.iter() { for a in artifacts.iter() {
@@ -411,6 +417,10 @@ fn TargetEditor(
let mut edit_type = use_signal(|| str_at(&target, "target_type").to_string()); let mut edit_type = use_signal(|| str_at(&target, "target_type").to_string());
let mut edit_arts = use_signal(|| editable_artifacts(&target)); let mut edit_arts = use_signal(|| editable_artifacts(&target));
let mut edit_saving = use_signal(|| false); let mut edit_saving = use_signal(|| false);
// Projects are saved apart from the rest, and only when they changed.
let stored_projects = project_ids_of(&target);
let edit_projects = use_signal(|| stored_projects.clone());
let projects = use_resource(fetch_projects);
// The dialog's "add artifact" row. // The dialog's "add artifact" row.
let mut e_kind = use_signal(|| "git_repo".to_string()); let mut e_kind = use_signal(|| "git_repo".to_string());
let mut e_source = use_signal(String::new); let mut e_source = use_signal(String::new);
@@ -576,6 +586,13 @@ fn TargetEditor(
on_saved.call(()); on_saved.call(());
}, },
} }
match projects.read().clone() {
Some(Ok(list)) => rsx! { ProjectPicker { projects: list, selected: edit_projects } },
Some(Err(e)) => rsx! {
p { class: "project-picker-hint", "{crate::i18n::texts::projects::LOAD_FAILED.get(lang)}: {e}" }
},
None => rsx! {},
}
div { class: "modal-actions", div { class: "modal-actions",
button { button {
class: "btn btn-secondary", class: "btn btn-secondary",
@@ -590,10 +607,17 @@ fn TargetEditor(
let nm = edit_name(); let nm = edit_name();
let tt = edit_type(); let tt = edit_type();
let arts = edit_arts(); let arts = edit_arts();
let chosen = edit_projects();
let projects_changed = chosen != stored_projects;
edit_saving.set(true); edit_saving.set(true);
spawn(async move { spawn(async move {
match update_target(id, Some(nm), Some(tt), Some(arts)).await { let saved = match update_target(id.clone(), Some(nm), Some(tt), Some(arts)).await {
Ok(_) => { Ok(_) if projects_changed => set_target_projects(id, chosen).await,
Ok(_) => Ok(()),
Err(e) => Err(e),
};
match saved {
Ok(()) => {
toasts.push(ToastType::Success, tx::UPDATED.get(lang)); toasts.push(ToastType::Success, tx::UPDATED.get(lang));
on_saved.call(()); on_saved.call(());
} }
+36 -2
View File
@@ -10,13 +10,15 @@ use crate::app::Route;
use crate::components::cra_bar::CraBar; use crate::components::cra_bar::CraBar;
use crate::components::demo_targets::DemoTargetsButton; use crate::components::demo_targets::DemoTargetsButton;
use crate::components::page_header::PageHeader; use crate::components::page_header::PageHeader;
use crate::components::projects::ProjectChips;
use crate::components::scan_runs::status_badge; use crate::components::scan_runs::status_badge;
use crate::components::toast::{ToastType, Toasts}; use crate::components::toast::{ToastType, Toasts};
use crate::i18n::texts::{common, kinds, scans as scan_texts, targets as tx}; use crate::i18n::texts::{common, kinds, scans as scan_texts, targets as tx};
use crate::i18n::{format_ago, use_lang, Lang}; use crate::i18n::{format_ago, use_lang, Lang};
use crate::infrastructure::auth_check::{go_to_login, is_session_expired}; use crate::infrastructure::auth_check::{go_to_login, is_session_expired};
use crate::infrastructure::evidence::fetch_compliance_summary; use crate::infrastructure::evidence::fetch_compliance_summary;
use crate::infrastructure::onboarding::{fetch_targets, trigger_target_scan}; use crate::infrastructure::onboarding::{fetch_targets_in, trigger_target_scan};
use crate::infrastructure::projects::{fetch_projects, project_ids_of};
use compliance_core::models::{ScanRun, ScanRunStatus}; use compliance_core::models::{ScanRun, ScanRunStatus};
/// How often the list refreshes while a scan is running, in milliseconds. /// How often the list refreshes while a scan is running, in milliseconds.
@@ -66,10 +68,14 @@ pub fn TargetsPage() -> Element {
let mut toasts = use_context::<Toasts>(); let mut toasts = use_context::<Toasts>();
let navigator = use_navigator(); let navigator = use_navigator();
let mut scanning_ids = use_signal(Vec::<String>::new); let mut scanning_ids = use_signal(Vec::<String>::new);
// The chosen project filter (`None`: every target); the list reloads when
// it changes, since the resource reads it.
let mut project = use_signal(|| Option::<String>::None);
let projects = use_resource(fetch_projects);
// A failure keeps its reason, to show it; an expired sign-in goes to the // A failure keeps its reason, to show it; an expired sign-in goes to the
// login instead. // login instead.
let mut targets = use_resource(move || async move { let mut targets = use_resource(move || async move {
fetch_targets().await.map_err(|e| { fetch_targets_in(project()).await.map_err(|e| {
if is_session_expired(&e) { if is_session_expired(&e) {
go_to_login(); go_to_login();
} }
@@ -105,6 +111,26 @@ pub fn TargetsPage() -> Element {
Link { to: Route::OnboardingPage {}, class: "btn btn-primary", Link { to: Route::OnboardingPage {}, class: "btn btn-primary",
{tx::ADD.get(lang)} {tx::ADD.get(lang)}
} }
if let Some(Ok(list)) = projects.read().clone().filter(|p| p.as_ref().is_ok_and(|l| !l.is_empty())) {
label { class: "project-filter",
span { {crate::i18n::texts::projects::FILTER.get(lang)} }
select {
onchange: move |e| {
let v = e.value();
project.set((!v.is_empty()).then_some(v));
},
option { value: "", selected: project().is_none(), {crate::i18n::texts::projects::ALL.get(lang)} }
for p in list {
option {
key: "{p.id}",
value: "{p.id}",
selected: project().as_deref() == Some(p.id.as_str()),
"{p.name}"
}
}
}
}
}
} }
{ {
@@ -118,6 +144,11 @@ pub fn TargetsPage() -> Element {
.and_then(|r| r.counts) .and_then(|r| r.counts)
}; };
match &targets_snapshot { match &targets_snapshot {
Some(Ok(resp)) if resp.data.is_empty() && project().is_some() => rsx! {
div { class: "card targets-empty",
p { {crate::i18n::texts::projects::NONE_IN_PROJECT.get(lang)} }
}
},
Some(Ok(resp)) if resp.data.is_empty() => rsx! { Some(Ok(resp)) if resp.data.is_empty() => rsx! {
div { class: "card targets-empty", div { class: "card targets-empty",
p { {tx::EMPTY.get(lang)} } p { {tx::EMPTY.get(lang)} }
@@ -169,6 +200,9 @@ pub fn TargetsPage() -> Element {
"{name}" "{name}"
} }
span { class: "targets-type", "{ttype}" } span { class: "targets-type", "{ttype}" }
if let Some(Ok(all)) = projects.read().clone() {
ProjectChips { ids: project_ids_of(t), projects: all }
}
} }
td { class: "targets-scan", td { class: "targets-scan",
match last_scan { match last_scan {
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "compliance-dast" name = "compliance-dast"
version = "0.1.0" version = "0.4.2"
edition = "2021" edition = "2021"
[lints] [lints]
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "compliance-graph" name = "compliance-graph"
version = "0.1.0" version = "0.4.2"
edition = "2021" edition = "2021"
[lints] [lints]
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "compliance-mcp" name = "compliance-mcp"
version = "0.1.0" version = "0.4.2"
edition = "2021" edition = "2021"
[dependencies] [dependencies]
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "compliance-smoke" name = "compliance-smoke"
version = "0.1.0" version = "0.4.2"
edition = "2021" edition = "2021"
description = "Tiny Axum service exercising compliance-core M7.1 tenant gating. Run smoke.sh against it before merging anything that touches the auth/tenant path." description = "Tiny Axum service exercising compliance-core M7.1 tenant gating. Run smoke.sh against it before merging anything that touches the auth/tenant path."
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "control-map" name = "control-map"
version = "0.1.0" version = "0.4.2"
edition = "2021" edition = "2021"
[lints] [lints]
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "werkbank-exec" name = "werkbank-exec"
version = "0.1.0" version = "0.4.2"
edition = "2021" edition = "2021"
description = "Shared dynamic-execution logic: soft-PLC provisioning + industrial-protocol probing, used by the compliance agent and the Werkbank runner." description = "Shared dynamic-execution logic: soft-PLC provisioning + industrial-protocol probing, used by the compliance agent and the Werkbank runner."