Compare commits

...
7 Commits
Author SHA1 Message Date
sharangandClaude Opus 5.5 5429ff6f0e fix(auth): enforce tenant org roles; crates at 0.4.4 (#431)
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Successful in 1m11s
CI / Deploy MCP (push) Successful in 4m19s
CI / Deploy Dashboard (push) Successful in 6m7s
CI / Deploy Agent (push) Successful in 7m27s
CI / Check (push) Skipped
Every member of a tenant could use Prüfwerk fully, whatever their org
role: nothing but manual findings checked org_roles. A FINANCE user
could create and delete targets, start scans and triage findings.

Now, as decided on 30.09.2026:
- IT_ADMIN, USER: read and write.
- CXO, LEGAL: read only. GET/HEAD/OPTIONS plus the POSTs that only
  read (OSCAL assess, pentest report export, code chat, help chat).
- FINANCE or no role: no access.

- Agent: one middleware (api::role_gate) right after the JWT one
  refuses with 403 {"error":"forbidden_role","access":...}. It is
  classified by route template, so ids do not matter. Support sessions
  (TenantContext.staff) and requests without a tenant context
  (platform service API, Werkbank runner and admin APIs, health) are
  unchanged. Manual findings stay IT_ADMIN-only.
- Core: ProductAccess and TenantContext::product_access.
- Dashboard: a role without access sees a "no access" page (DE/EN)
  with a link back to the portal, and no server function runs for it.
  Read-only roles get a read-only note, and write actions (add target,
  scan, edit, delete, triage, tokens, MCP servers, pentest control,
  graph/embedding builds, notification dismiss) are hidden. The direct
  MCP server functions check the role, and access tokens are withheld
  from read-only roles.
- MCP server: unchanged. Its tokens are tenant-bound and carry no
  roles, its tools only read, and creating a token now needs write
  access.
- Docs: the roles table in Getting Started.
- The crates are at version 0.4.4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-09-30 21:59:07 +00:00
sharangandClaude Opus 5.5 77164c2050 fix: self-host fonts (no Google Fonts request) and crates at 0.4.3 (#430)
CI / Detect Changes (push) Successful in 6s
CI / Deploy Dashboard (push) Successful in 12m37s
CI / Check (push) Skipped
CI / Deploy Docs (push) Successful in 1m29s
CI / Deploy Agent (push) Successful in 9m53s
CI / Deploy MCP (push) Successful in 4m46s
The dashboard, the docs site and the pentest report no longer load
Google Fonts, so no visitor's IP goes to Google (platform/portal#65,
privacy release gate 4).

- Dashboard: Geist and Geist Mono (variable woff2, SIL OFL 1.1) are
  embedded and served at /fonts/geist.woff2 and /fonts/geist-mono.woff2;
  main.css declares them with @font-face under the same family names.
- Docs: the same woff2 files are bundled by Vite from the theme; the
  Google Fonts links in config.mts are gone.
- Pentest report: preconnects and the Google Fonts stylesheet removed;
  a system font stack instead, with a test that the report references
  no external resource.
- The crates are at version 0.4.3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-09-30 20:48:02 +00:00
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
87 changed files with 3975 additions and 408 deletions

No files matched your search

Generated
+9 -9
View File
@@ -663,7 +663,7 @@ dependencies = [
[[package]]
name = "compliance-agent"
version = "0.1.0"
version = "0.4.4"
dependencies = [
"axum",
"base64",
@@ -714,7 +714,7 @@ dependencies = [
[[package]]
name = "compliance-core"
version = "0.1.0"
version = "0.4.4"
dependencies = [
"aes-gcm",
"axum",
@@ -744,7 +744,7 @@ dependencies = [
[[package]]
name = "compliance-dashboard"
version = "0.1.0"
version = "0.4.4"
dependencies = [
"async-trait",
"axum",
@@ -784,7 +784,7 @@ dependencies = [
[[package]]
name = "compliance-dast"
version = "0.1.0"
version = "0.4.4"
dependencies = [
"base64",
"bollard",
@@ -810,7 +810,7 @@ dependencies = [
[[package]]
name = "compliance-graph"
version = "0.1.0"
version = "0.4.4"
dependencies = [
"bson",
"chrono",
@@ -834,7 +834,7 @@ dependencies = [
[[package]]
name = "compliance-mcp"
version = "0.1.0"
version = "0.4.4"
dependencies = [
"axum",
"bson",
@@ -858,7 +858,7 @@ dependencies = [
[[package]]
name = "compliance-smoke"
version = "0.1.0"
version = "0.4.4"
dependencies = [
"axum",
"compliance-core",
@@ -985,7 +985,7 @@ dependencies = [
[[package]]
name = "control-map"
version = "0.1.0"
version = "0.4.4"
dependencies = [
"serde",
"serde_json",
@@ -6793,7 +6793,7 @@ dependencies = [
[[package]]
name = "werkbank-exec"
version = "0.1.0"
version = "0.4.4"
dependencies = [
"compliance-core",
"compliance-dast",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-agent"
version = "0.1.0"
version = "0.4.4"
edition = "2021"
[lints]
+9 -6
View File
@@ -191,12 +191,15 @@ impl ComplianceAgent {
);
let started = chrono::Utc::now();
orchestrator.run_target(target_id, trigger.clone()).await?;
self.emit_usage(
tenant_id,
"scan.completed",
format!("scan:{tenant_id}:{target_id}:{}", started.timestamp()),
serde_json::json!({ "target_id": target_id, "trigger": format!("{trigger:?}") }),
);
// Support's scans are ours, not the customer's usage.
if trigger != compliance_core::models::ScanTrigger::Support {
self.emit_usage(
tenant_id,
"scan.completed",
format!("scan:{tenant_id}:{target_id}:{}", started.timestamp()),
serde_json::json!({ "target_id": target_id, "trigger": format!("{trigger:?}") }),
);
}
self.notify_new_findings(tenant_id, target_id, &db, started);
Ok(())
}
+77 -12
View File
@@ -140,10 +140,34 @@ pub async fn get_finding(
/// The `$set` and `$push` of a status change by `user`, or 422 when a status
/// that needs a reason (an accepted risk, a wrong CRA mapping) comes without
/// one.
/// Who changes a finding, as its history records it.
struct Actor<'a> {
/// The Keycloak user id.
id: &'a str,
/// The name the customer reads; "BreakPilot-Support (name)" for support.
name: Option<String>,
/// BreakPilot support rather than one of the tenant's users.
support: bool,
}
impl<'a> Actor<'a> {
/// The requester of `ctx`.
fn of(ctx: &'a compliance_core::TenantContext) -> Self {
Self {
id: &ctx.user_id,
name: match &ctx.staff {
Some(staff) => Some(staff.label()),
None => ctx.user_name.clone(),
},
support: ctx.staff.is_some(),
}
}
}
fn status_update(
status: &FindingStatus,
reason: Option<&str>,
user: &str,
actor: &Actor<'_>,
) -> Result<mongodb::bson::Document, StatusCode> {
let reason = reason.map(str::trim).filter(|r| !r.is_empty());
if status.needs_reason() && reason.is_none() {
@@ -151,7 +175,9 @@ fn status_update(
}
let change = StatusChange {
status: status.clone(),
by: user.to_string(),
by: actor.id.to_string(),
by_name: actor.name.clone(),
support: actor.support,
at: chrono::Utc::now(),
reason: reason.map(String::from),
};
@@ -173,7 +199,7 @@ pub async fn update_finding_status(
Json(req): Json<UpdateStatusRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let oid = mongodb::bson::oid::ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
let update = status_update(&req.status, req.reason.as_deref(), &tenant.0.user_id)?;
let update = status_update(&req.status, req.reason.as_deref(), &Actor::of(&tenant.0))?;
let db = tenant_db(&agent, &tenant).await?;
let result = db
@@ -204,7 +230,7 @@ pub async fn bulk_update_finding_status(
if oids.is_empty() {
return Err(StatusCode::BAD_REQUEST);
}
let update = status_update(&req.status, req.reason.as_deref(), &tenant.0.user_id)?;
let update = status_update(&req.status, req.reason.as_deref(), &Actor::of(&tenant.0))?;
let db = tenant_db(&agent, &tenant).await?;
let result = db
@@ -246,26 +272,65 @@ mod tests {
#[test]
fn an_accepted_risk_needs_a_reason() {
assert_eq!(
status_update(&FindingStatus::AcceptedRisk, None, "u").err(),
status_update(&FindingStatus::AcceptedRisk, None, &user("u")).err(),
Some(StatusCode::UNPROCESSABLE_ENTITY)
);
assert_eq!(
status_update(&FindingStatus::AcceptedRisk, Some(" "), "u").err(),
status_update(&FindingStatus::AcceptedRisk, Some(" "), &user("u")).err(),
Some(StatusCode::UNPROCESSABLE_ENTITY)
);
assert!(status_update(&FindingStatus::AcceptedRisk, Some("isolated network"), "u").is_ok());
assert!(status_update(
&FindingStatus::AcceptedRisk,
Some("isolated network"),
&user("u")
)
.is_ok());
assert_eq!(
status_update(&FindingStatus::WrongMapping, None, "u").err(),
status_update(&FindingStatus::WrongMapping, None, &user("u")).err(),
Some(StatusCode::UNPROCESSABLE_ENTITY)
);
assert!(status_update(&FindingStatus::FalsePositive, None, "u").is_ok());
assert!(status_update(&FindingStatus::Resolved, None, "u").is_ok());
assert!(status_update(&FindingStatus::FalsePositive, None, &user("u")).is_ok());
assert!(status_update(&FindingStatus::Resolved, None, &user("u")).is_ok());
}
fn user(id: &str) -> Actor<'_> {
Actor {
id,
name: None,
support: false,
}
}
#[test]
fn a_change_by_support_is_marked_as_such() {
let actor = Actor {
id: "s-1",
name: Some("BreakPilot-Support (Sharang)".to_string()),
support: true,
};
let update = status_update(&FindingStatus::WrongMapping, Some("wrong control"), &actor)
.unwrap_or_default();
let change = update
.get_document("$push")
.and_then(|p| p.get_document("status_history"))
.cloned()
.unwrap_or_default();
assert_eq!(change.get_str("by").ok(), Some("s-1"));
assert_eq!(
change.get_str("by_name").ok(),
Some("BreakPilot-Support (Sharang)")
);
assert_eq!(change.get_bool("support").ok(), Some(true));
}
#[test]
fn a_change_sets_the_status_and_records_who_and_why() {
let update = status_update(&FindingStatus::AcceptedRisk, Some(" isolated "), "u-7")
.unwrap_or_default();
let update = status_update(
&FindingStatus::AcceptedRisk,
Some(" isolated "),
&user("u-7"),
)
.unwrap_or_default();
let set = update.get_document("$set").cloned().unwrap_or_default();
assert_eq!(set.get_str("status").ok(), Some("accepted_risk"));
let change = update
+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
/// 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.
async fn open_findings_by_severity(
@@ -138,6 +138,8 @@ pub async fn create_finding(
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
let db = tenant_db(&agent, &tenant).await?;
// Shown on the finding: a name, or "BreakPilot-Support (name)".
let reported_by = tenant.0.actor_label();
require_target(&db, &id).await?;
let tool = req
.tool
@@ -147,7 +149,7 @@ pub async fn create_finding(
target_id: &id,
scan_type: req.kind.into(),
scanner: &tool,
reported_by: &tenant.0.user_id,
reported_by: &reported_by,
});
if !insert_new(&db, &mut finding).await? {
return Err(StatusCode::CONFLICT);
@@ -187,6 +189,8 @@ pub async fn import_findings(
StatusCode::UNPROCESSABLE_ENTITY
})?;
let db = tenant_db(&agent, &tenant).await?;
// Shown on the finding: a name, or "BreakPilot-Support (name)".
let reported_by = tenant.0.actor_label();
require_target(&db, &id).await?;
let mut summary = ImportSummary {
@@ -199,7 +203,7 @@ pub async fn import_findings(
target_id: &id,
scan_type: params.kind.into(),
scanner: &tool,
reported_by: &tenant.0.user_id,
reported_by: &reported_by,
});
if insert_new(&db, &mut finding).await? {
summary.imported += 1;
@@ -229,6 +233,7 @@ mod tests {
status: TenantStatus::Active,
user_id: "u".into(),
user_name: None,
staff: None,
})
}
+2
View File
@@ -16,9 +16,11 @@ pub mod onboarding;
pub mod oscal;
pub mod pentest_handlers;
pub mod platform;
pub mod projects;
pub use pentest_handlers as pentest;
pub mod sbom;
pub mod scans;
pub mod support;
pub mod target_input;
pub mod werkbank_jobs;
+91 -22
View File
@@ -47,6 +47,9 @@ pub struct UpdateTargetRequest {
pub scan_config: Option<ScanConfigUpdate>,
pub compliance_profile: Option<ComplianceProfile>,
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
/// keeps the token and uploaded file of the stored artifact it matches.
#[serde(default)]
@@ -80,17 +83,19 @@ pub async fn list_targets(
Extension(agent): AgentExt,
tenant: TenantCtx,
Query(params): Query<PaginationParams>,
Query(filter): Query<TargetFilter>,
) -> Result<Json<ApiResponse<Vec<TargetListItem>>>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let skip = params.skip();
let query = filter.to_query();
let total = db
.onboarded_targets()
.count_documents(doc! {})
.count_documents(query.clone())
.await
.unwrap_or(0);
let targets = match db
.onboarded_targets()
.find(doc! {})
.find(query)
.skip(skip)
.limit(params.limit)
.await
@@ -143,8 +148,31 @@ pub struct TargetListItem {
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.
async fn latest_scan_runs(
pub(crate) async fn latest_scan_runs(
runs: &mongodb::Collection<ScanRun>,
target_ids: Vec<String>,
) -> 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.
let stored = if req.scan_config.is_some() || req.artifacts.is_some() {
Some(
db.onboarded_targets()
.find_one(doc! { "_id": oid })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::NOT_FOUND)?,
)
} else {
None
};
let stored =
if req.scan_config.is_some() || req.artifacts.is_some() || req.project_ids.is_some() {
Some(
db.onboarded_targets()
.find_one(doc! { "_id": oid })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::NOT_FOUND)?,
)
} else {
None
};
let credential_error = |e: SecretError| {
tracing::error!("storing a credential: {e}");
StatusCode::SERVICE_UNAVAILABLE
@@ -327,6 +356,20 @@ pub async fn update_target(
if let Some(ss) = req.scan_schedule {
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()) {
let built =
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 })
.await
.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
}
@@ -916,20 +968,37 @@ pub async fn trigger_target_scan(
let agent_clone = (*agent).clone();
let tenant_id = tenant.0.tenant_id.clone();
// A scan support starts is not the customer's usage.
let trigger = if tenant.0.staff.is_some() {
compliance_core::models::ScanTrigger::Support
} else {
compliance_core::models::ScanTrigger::Manual
};
tokio::spawn(async move {
// Always the unified target pipeline — this endpoint is about an
// onboarded target by construction, independent of the global
// `unified_pipeline` transition flag used by the legacy paths.
if let Err(e) = agent_clone
.run_target_scan(
&tenant_id,
&id,
compliance_core::models::ScanTrigger::Manual,
)
.await
{
if let Err(e) = agent_clone.run_target_scan(&tenant_id, &id, trigger).await {
tracing::error!("Manual target scan failed for {id}: {e}");
}
});
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(),
}))
}
/// 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"]);
}
}
+1
View File
@@ -1,4 +1,5 @@
pub mod handlers;
pub mod role_gate;
pub mod routes;
pub mod server;
+124
View File
@@ -0,0 +1,124 @@
//! Org-role enforcement for the customer API (decided 2026-09-30).
//!
//! One middleware for every tenant-scoped route, so no handler can forget it:
//!
//! * `IT_ADMIN`, `USER` — read and write.
//! * `CXO`, `LEGAL` — read only: `GET` / `HEAD` / `OPTIONS`, plus the few
//! `POST` routes that only read ([`READ_ONLY_POSTS`]).
//! * `FINANCE`, or none of these roles — nothing; every request is refused.
//!
//! Refusals are `403 {"error": "forbidden_role", "access": "none" | "read_only"}`.
//!
//! Not judged by org roles, as before:
//! * BreakPilot support ([`compliance_core::TenantContext::staff`]) — the
//! support rules apply (read-only until confirmed, every change audited).
//! * Requests without a [`TenantContext`]: the platform service API, the
//! Werkbank runner and admin APIs (their own token middleware), the health
//! check, and support staff who have not chosen a tenant yet.
//!
//! Handlers may still be stricter (manual findings stay `IT_ADMIN`-only).
use axum::{
extract::{MatchedPath, Request},
http::{Method, StatusCode},
middleware::Next,
response::{IntoResponse, Response},
Json,
};
use compliance_core::{ProductAccess, TenantContext};
/// The JSON `error` of a refusal.
pub const FORBIDDEN_ROLE: &str = "forbidden_role";
/// `POST` routes that only read: a query or an export with a body. Matched
/// against the route template, so an id in the path does not matter. Every
/// other `POST`, `PUT`, `PATCH` and `DELETE` is a write.
pub const READ_ONLY_POSTS: &[&str] = &[
// OSCAL assessment-results for a target's findings (computed, not stored).
"/api/v1/oscal/assess",
// The encrypted pentest report archive (the body carries its password).
"/api/v1/pentest/sessions/{id}/export",
// Questions about a repository's code (RAG); nothing is stored.
"/api/v1/chat/{repo_id}",
// The documentation assistant; nothing is stored.
"/api/v1/help/chat",
];
/// Whether a request with `method` to the route `template` changes anything.
/// A request that matched no route counts by its method alone.
pub fn is_write(method: &Method, template: Option<&str>) -> bool {
if matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS) {
return false;
}
!(*method == Method::POST && template.is_some_and(|t| READ_ONLY_POSTS.contains(&t)))
}
/// Why a request is refused, if it is.
pub fn refusal(
ctx: &TenantContext,
method: &Method,
template: Option<&str>,
) -> Option<ProductAccess> {
match ctx.product_access() {
ProductAccess::Full => None,
ProductAccess::ReadOnly if !is_write(method, template) => None,
denied => Some(denied),
}
}
/// The middleware. Runs after the JWT middleware has attached the
/// [`TenantContext`]; passes every request that has none.
pub async fn require_org_role(request: Request, next: Next) -> Response {
let Some(ctx) = request.extensions().get::<TenantContext>() else {
return next.run(request).await;
};
let template = request
.extensions()
.get::<MatchedPath>()
.map(MatchedPath::as_str);
let Some(access) = refusal(ctx, request.method(), template) else {
return next.run(request).await;
};
tracing::info!(
tenant_id = %ctx.tenant_id,
user_id = %ctx.user_id,
roles = ?ctx.org_roles,
method = %request.method(),
route = template.unwrap_or("-"),
"request refused by org role"
);
(
StatusCode::FORBIDDEN,
Json(serde_json::json!({ "error": FORBIDDEN_ROLE, "access": access })),
)
.into_response()
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod router_tests;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_and_read_only_posts_are_not_writes() {
assert!(!is_write(&Method::GET, Some("/api/v1/targets")));
assert!(!is_write(&Method::HEAD, None));
assert!(!is_write(&Method::OPTIONS, None));
for t in READ_ONLY_POSTS {
assert!(!is_write(&Method::POST, Some(t)), "{t}");
// Only POST is exempt on these routes.
assert!(is_write(&Method::DELETE, Some(t)), "{t}");
}
assert!(is_write(&Method::POST, Some("/api/v1/targets")));
assert!(is_write(&Method::POST, None));
assert!(is_write(
&Method::PATCH,
Some("/api/v1/findings/{id}/status")
));
assert!(is_write(&Method::PUT, None));
assert!(is_write(&Method::DELETE, Some("/api/v1/targets/{id}")));
}
}
@@ -0,0 +1,213 @@
//! Org-role enforcement through the real customer router.
//!
//! Role × method × representative route. The handlers have no agent in
//! these tests, so a request the gate lets through fails later (500, missing
//! extension); what is checked is only whether the gate refused it.
use super::{require_org_role, READ_ONLY_POSTS};
use crate::api::routes::build_router;
use axum::{
body::{to_bytes, Body},
extract::Request,
http::{Method, StatusCode},
middleware::{from_fn, Next},
Router,
};
use compliance_core::{OrgRole, StaffAccess, TenantContext, TenantStatus};
use tower::ServiceExt;
/// Who is calling.
#[derive(Debug, Clone, Copy)]
enum Caller {
ItAdmin,
User,
Cxo,
Legal,
Finance,
NoRoles,
/// BreakPilot support in a customer's tenant (no org roles of its own).
Staff,
/// A service / machine client: no tenant context reaches the gate.
Service,
}
fn ctx(caller: Caller) -> Option<TenantContext> {
let roles = match caller {
Caller::ItAdmin => vec![OrgRole::ItAdmin],
Caller::User => vec![OrgRole::User],
Caller::Cxo => vec![OrgRole::Cxo],
Caller::Legal => vec![OrgRole::Legal],
Caller::Finance => vec![OrgRole::Finance],
Caller::NoRoles | Caller::Staff => vec![],
Caller::Service => return None,
};
Some(TenantContext {
tenant_id: "00000000-0000-0000-0000-000000000001".to_string(),
tenant_slug: "acme".to_string(),
org_roles: roles,
products: vec![],
plan: "professional".to_string(),
status: TenantStatus::Active,
user_id: "u-1".to_string(),
user_name: None,
staff: matches!(caller, Caller::Staff).then(|| StaffAccess {
user_id: "u-1".to_string(),
user_name: None,
}),
})
}
fn router(caller: Caller) -> Router {
let ctx = ctx(caller);
let injector = move |mut req: Request, next: Next| {
let ctx = ctx.clone();
async move {
if let Some(c) = ctx {
req.extensions_mut().insert(c);
}
next.run(req).await
}
};
// Same order as the server: the context is attached, then the gate.
build_router()
.layer(from_fn(require_org_role))
.layer(from_fn(injector))
}
/// Whether the gate refused the request (403 `forbidden_role`).
async fn refused(caller: Caller, method: Method, path: &str) -> bool {
let req = Request::builder()
.method(method)
.uri(path)
.header("content-type", "application/json")
.body(Body::from("{}"))
.expect("request");
let resp = router(caller).oneshot(req).await.expect("oneshot");
if resp.status() != StatusCode::FORBIDDEN {
return false;
}
let body = to_bytes(resp.into_body(), 64 * 1024).await.expect("body");
let json: serde_json::Value = serde_json::from_slice(&body).unwrap_or_default();
json["error"] == "forbidden_role"
}
const ID: &str = "65f000000000000000000001";
/// (method, path, is a write).
fn routes() -> Vec<(Method, String, bool)> {
vec![
(Method::GET, "/api/v1/targets".into(), false),
(Method::POST, "/api/v1/targets".into(), true),
(Method::GET, format!("/api/v1/targets/{ID}"), false),
(Method::PATCH, format!("/api/v1/targets/{ID}"), true),
(Method::DELETE, format!("/api/v1/targets/{ID}"), true),
(Method::POST, format!("/api/v1/targets/{ID}/scan"), true),
(Method::POST, format!("/api/v1/targets/{ID}/detect"), true),
(Method::POST, "/api/v1/targets/demo-seed".into(), true),
(Method::GET, "/api/v1/findings".into(), false),
(Method::GET, format!("/api/v1/findings/{ID}"), false),
(Method::PATCH, format!("/api/v1/findings/{ID}/status"), true),
(Method::PATCH, "/api/v1/findings/bulk-status".into(), true),
(
Method::PATCH,
format!("/api/v1/findings/{ID}/feedback"),
true,
),
(Method::POST, format!("/api/v1/targets/{ID}/findings"), true),
(
Method::POST,
format!("/api/v1/targets/{ID}/findings/import"),
true,
),
(
Method::GET,
format!("/api/v1/targets/{ID}/evidence-pack"),
false,
),
(Method::GET, "/api/v1/sbom/export".into(), false),
(Method::POST, "/api/v1/mcp-tokens".into(), true),
(Method::DELETE, format!("/api/v1/mcp-tokens/{ID}"), true),
(Method::POST, "/api/v1/notifications/read-all".into(), true),
(Method::POST, "/api/v1/pentest/sessions".into(), true),
// POSTs that only read.
(Method::POST, "/api/v1/oscal/assess".into(), false),
(
Method::POST,
format!("/api/v1/pentest/sessions/{ID}/export"),
false,
),
(Method::POST, format!("/api/v1/chat/{ID}"), false),
(Method::POST, "/api/v1/help/chat".into(), false),
]
}
#[tokio::test]
async fn roles_decide_reads_and_writes() {
// (caller, may read, may write)
let matrix = [
(Caller::ItAdmin, true, true),
(Caller::User, true, true),
(Caller::Cxo, true, false),
(Caller::Legal, true, false),
(Caller::Finance, false, false),
(Caller::NoRoles, false, false),
(Caller::Staff, true, true),
(Caller::Service, true, true),
];
for (caller, may_read, may_write) in matrix {
for (method, path, write) in routes() {
let allowed = if write { may_write } else { may_read };
assert_eq!(
refused(caller, method.clone(), &path).await,
!allowed,
"{caller:?} {method} {path}"
);
}
}
}
#[tokio::test]
async fn every_read_only_post_is_a_real_route() {
// A template that no longer matches a route would silently turn back
// into a write: each must be reachable by a read-only role.
for template in READ_ONLY_POSTS {
let path = template.replace("{id}", ID).replace("{repo_id}", ID);
assert!(
!refused(Caller::Cxo, Method::POST, &path).await,
"{template}"
);
}
}
#[tokio::test]
async fn a_refusal_says_which_access_the_role_has() {
let req = |method: Method| {
Request::builder()
.method(method)
.uri("/api/v1/targets")
.body(Body::empty())
.expect("request")
};
let resp = router(Caller::Legal)
.oneshot(req(Method::POST))
.await
.expect("oneshot");
assert_eq!(resp.status(), StatusCode::FORBIDDEN);
let body = to_bytes(resp.into_body(), 4096).await.expect("body");
let json: serde_json::Value = serde_json::from_slice(&body).expect("json");
assert_eq!(
json,
serde_json::json!({ "error": "forbidden_role", "access": "read_only" })
);
let resp = router(Caller::Finance)
.oneshot(req(Method::GET))
.await
.expect("oneshot");
let body = to_bytes(resp.into_body(), 4096).await.expect("body");
let json: serde_json::Value = serde_json::from_slice(&body).expect("json");
assert_eq!(
json,
serde_json::json!({ "error": "forbidden_role", "access": "none" })
);
}
+11
View File
@@ -13,6 +13,17 @@ pub fn build_router() -> Router {
.route("/api/v1/health", get(handlers::health))
.route("/api/v1/oscal/assess", post(handlers::oscal::assess_target))
.route("/api/v1/stats/overview", get(handlers::stats_overview))
// 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).
.route(
"/api/v1/targets",
+181 -5
View File
@@ -1,7 +1,7 @@
use std::sync::Arc;
use axum::extract::{DefaultBodyLimit, Request, State};
use axum::http::{HeaderValue, StatusCode};
use axum::http::{HeaderValue, Method, StatusCode};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use axum::routing::{delete, get, post};
@@ -18,7 +18,7 @@ use compliance_core::{OrgRole, TenantContext, TenantStatus};
use crate::agent::ComplianceAgent;
use crate::api::handlers;
use crate::api::handlers::platform::{self, PlatformState};
use crate::api::routes;
use crate::api::{role_gate, routes};
use crate::error::AgentError;
/// Synthetic tenant id used when Keycloak isn't configured (local dev,
@@ -52,6 +52,7 @@ pub async fn inject_dev_tenant(mut request: Request, next: Next) -> Response {
status: TenantStatus::Active,
user_id: "dev-user".to_string(),
user_name: None,
staff: None,
};
request.extensions_mut().insert(ctx);
}
@@ -67,6 +68,36 @@ pub async fn require_entitlement(
mut request: Request,
next: Next,
) -> Response {
// Support access names its tenant in a header: only the registry can
// confirm it exists, so without one there is no support access at all.
if let Some(ctx) = request
.extensions()
.get::<TenantContext>()
.filter(|c| c.staff.is_some())
.cloned()
{
let Some(registry) = agent.registry.as_ref() else {
tracing::error!("support access needs the tenant registry — denying");
return entitlement_unavailable();
};
return match registry.get_tenant(&ctx.tenant_id).await {
Ok(Some(tenant)) => {
request
.extensions_mut()
.insert(confirmed_support_context(ctx, &tenant));
next.run(request).await
}
Ok(None) => (
StatusCode::NOT_FOUND,
Json(serde_json::json!({ "error": "unknown_tenant" })),
)
.into_response(),
Err(e) => {
tracing::error!(tenant_id = %ctx.tenant_id, "support tenant lookup failed: {e}");
entitlement_unavailable()
}
};
}
let Some(registry) = agent.registry.as_ref() else {
if agent.config.app_env.is_hardened() {
// Unreachable after `validate_deployment`, but never widen access
@@ -116,6 +147,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 {
if origins.is_empty() {
if app_env.is_hardened() {
@@ -183,6 +284,12 @@ pub async fn start_api_server(
"/api/v1/platform/tenants/{id}/provision",
post(platform::provision),
)
// The portal's view of a tenant's targets (per project), through the
// registry. Read-only.
.route(
"/api/v1/platform/tenants/{id}/targets",
get(platform::list_targets),
)
.route(
"/api/v1/platform/tenants/{id}/suspend",
post(platform::suspend),
@@ -307,14 +414,19 @@ pub async fn start_api_server(
registry = agent.registry.is_some(),
"Keycloak JWT auth enabled"
);
// Layers execute outermost-first: Extension(jwks) → JWT → entitlement
// (registry) → status ladder → handlers.
// Layers execute outermost-first: Extension(jwks) → JWT → org roles
// → entitlement (registry) → support audit → status ladder → handlers.
app = app
.layer(middleware::from_fn(require_tenant_status))
.layer(middleware::from_fn_with_state(
shared.clone(),
audit_support_writes,
))
.layer(middleware::from_fn_with_state(
shared.clone(),
require_entitlement,
))
.layer(middleware::from_fn(role_gate::require_org_role))
.layer(middleware::from_fn(require_jwt_auth))
.layer(Extension(jwks_state));
} else if agent.config.app_env.is_hardened() {
@@ -334,7 +446,9 @@ pub async fn start_api_server(
"Keycloak not configured — running unauthenticated against the dev tenant. \
DO NOT use in any environment with real customer data."
);
app = app.layer(middleware::from_fn(inject_dev_tenant));
app = app
.layer(middleware::from_fn(role_gate::require_org_role))
.layer(middleware::from_fn(inject_dev_tenant));
}
let addr = format!("0.0.0.0:{port}");
@@ -350,3 +464,65 @@ pub async fn start_api_server(
Ok(())
}
#[cfg(test)]
mod support_tests {
use super::*;
fn support_ctx() -> TenantContext {
TenantContext {
tenant_id: "00000000-0000-0000-0000-000000000002".to_string(),
tenant_slug: String::new(),
org_roles: vec![OrgRole::ItAdmin],
products: Vec::new(),
plan: String::new(),
status: TenantStatus::Restricted,
user_id: "s-1".to_string(),
user_name: Some("Sharang".to_string()),
staff: Some(compliance_core::StaffAccess {
user_id: "s-1".to_string(),
user_name: Some("Sharang".to_string()),
}),
}
}
fn registry_tenant(status: &str) -> crate::registry::RegistryTenant {
crate::registry::RegistryTenant {
id: "00000000-0000-0000-0000-000000000002".to_string(),
slug: "faller".to_string(),
name: "Gebr. Faller".to_string(),
status: status.to_string(),
}
}
#[test]
fn the_registry_confirms_slug_and_status() {
let ctx = confirmed_support_context(support_ctx(), &registry_tenant("active"));
assert_eq!(ctx.tenant_slug, "faller");
assert_eq!(ctx.status, TenantStatus::Active);
}
#[test]
fn an_unknown_registry_status_stays_read_only() {
let ctx = confirmed_support_context(support_ctx(), &registry_tenant("something-new"));
assert_eq!(ctx.status, TenantStatus::Restricted);
}
#[test]
fn a_support_change_is_audited_without_its_content() {
let entry =
support_audit_entry(&support_ctx(), "PATCH", "/api/v1/findings/abc/status", 200);
assert_eq!(entry.tenant_id, "00000000-0000-0000-0000-000000000002");
assert_eq!(entry.action, "pruefwerk.support_access");
assert_eq!(entry.actor_id, "s-1");
assert_eq!(entry.actor_name, "BreakPilot-Support (Sharang)");
assert_eq!(
entry.metadata,
serde_json::json!({
"method": "PATCH",
"path": "/api/v1/findings/abc/status",
"status": 200
})
);
}
}
+9
View File
@@ -478,6 +478,15 @@ impl Database {
)
.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
self.onboarded_targets()
.create_index(
@@ -124,9 +124,6 @@ pub(super) fn build_html_report(ctx: &ReportContext) -> String {
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Penetration Test Report — {target_name}</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Libre+Baskerville:ital,wght@0,400;0,700;1,400&family=Source+Sans+3:ital,wght@0,300;0,400;0,600;0,700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
{styles_html}
</head>
<body>
@@ -412,6 +409,29 @@ mod tests {
assert!(html.contains("https://example.com"));
}
#[test]
fn report_loads_nothing_from_a_third_party() {
let ctx = make_report_context(
vec![make_finding(Severity::High, "SQL Injection", true)],
vec![make_attack_node("sqlmap")],
);
let html = build_html_report(&ctx);
for needle in [
"googleapis",
"gstatic",
"preconnect",
"<link",
"@import",
"url(http",
"src=\"http",
] {
assert!(!html.contains(needle), "report contains {needle:?}");
}
// The fonts come from the reader's system, with generic fallbacks.
assert!(html.contains("--font-sans:"));
assert!(html.contains("sans-serif;"));
}
#[test]
fn report_contains_requester_info() {
let ctx = make_report_context(vec![], vec![]);
@@ -27,9 +27,11 @@ pub(super) fn styles() -> String {
--sev-medium: #a16207;
--sev-low: #1d4ed8;
--sev-info: #4b5563;
--font-serif: 'Libre Baskerville', 'Georgia', serif;
--font-sans: 'Source Sans 3', 'Helvetica Neue', sans-serif;
--font-mono: 'JetBrains Mono', 'Consolas', monospace;
/* System fonts only: the report is a standalone file and fetches
nothing from a font CDN. The named faces apply where installed. */
--font-serif: 'Libre Baskerville', Georgia, 'Times New Roman', serif;
--font-sans: 'Source Sans 3', system-ui, -apple-system, 'Segoe UI', 'Helvetica Neue', Arial, sans-serif;
--font-mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace;
}
body {
@@ -642,7 +644,7 @@ table.tools-table td:first-child {
border: 1px solid #fecaca;
border-left: 3px solid #dc2626;
padding: 8px 10px;
font-family: 'JetBrains Mono', monospace;
font-family: var(--font-mono);
font-size: 8pt;
line-height: 1.5;
white-space: pre-wrap;
@@ -655,7 +657,7 @@ table.tools-table td:first-child {
border: 1px solid #bbf7d0;
border-left: 3px solid #16a34a;
padding: 8px 10px;
font-family: 'JetBrains Mono', monospace;
font-family: var(--font-mono);
font-size: 8pt;
line-height: 1.5;
white-space: pre-wrap;
@@ -91,7 +91,7 @@ impl PipelineOrchestrator {
// A scheduled or webhook scan of an unchanged repository has nothing
// new to find; one a person started always runs (after an update of
// Prüfwerk itself, or a changed setting, it can find something else).
if *trigger != ScanTrigger::Manual
if !trigger.started_by_person()
&& !GitOps::has_new_commits(&repo_path, repo.last_scanned_commit.as_deref())?
{
tracing::info!("[{repo_id}] No new commits, skipping scan");
+139
View File
@@ -47,10 +47,66 @@ pub struct RegistryTenant {
pub id: String,
#[serde(default)]
pub slug: String,
/// The organisation's name, for the support tenant picker.
#[serde(default)]
pub name: String,
#[serde(default)]
pub status: String,
}
/// One entry of the platform's audit log (`POST /v1/audit`).
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct AuditEntry {
pub tenant_id: String,
/// 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)]
pub struct ApiKeyVerify {
pub valid: bool,
@@ -88,6 +144,8 @@ pub struct RegistryClient {
client_secret: Option<String>,
token: Mutex<Option<CachedToken>>,
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 {
@@ -129,6 +187,7 @@ impl RegistryClient {
.map(|s| s.expose_secret().to_string()),
token: Mutex::new(None),
cache: DashMap::new(),
projects: DashMap::new(),
}))
}
@@ -279,6 +338,86 @@ impl RegistryClient {
Ok(out)
}
/// One tenant (`GET /v1/tenants/{id}`); `Ok(None)` when the registry
/// does not know it. Errors mean "unknown": callers fail closed.
pub async fn get_tenant(&self, tenant_id: &str) -> Result<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_…`).
pub async fn verify_api_key(&self, key: &str) -> Result<ApiKeyVerify, String> {
let resp = self
@@ -25,6 +25,7 @@ fn ctx(tenant_id: &str, slug: &str) -> TenantContext {
status: TenantStatus::Active,
user_id: "u-1".to_string(),
user_name: None,
staff: None,
}
}
@@ -28,6 +28,7 @@ fn ctx_with(status: TenantStatus) -> TenantContext {
status,
user_id: "u-1".to_string(),
user_name: None,
staff: None,
}
}
@@ -167,3 +168,51 @@ async fn ladder_warning_passes_restricted_blocks_writes_halted_blocks_all() {
.await;
assert_eq!(r.status(), StatusCode::GONE);
}
fn support_ctx(status: TenantStatus) -> TenantContext {
TenantContext {
staff: Some(compliance_core::StaffAccess {
user_id: "s-1".to_string(),
user_name: Some("Support".to_string()),
}),
..ctx_with(status)
}
}
/// Support access follows the tenant's ladder like its own users: an
/// archived tenant is gone, a halted one closed, a restricted one read-only.
#[tokio::test]
async fn support_access_follows_the_ladder() {
let archived = call(
router_with_ctx(Some(support_ctx(TenantStatus::Archived))),
Method::GET,
"/r",
)
.await;
assert_eq!(archived.status(), StatusCode::GONE);
let halted = call(
router_with_ctx(Some(support_ctx(TenantStatus::Halted))),
Method::GET,
"/r",
)
.await;
assert_eq!(halted.status(), StatusCode::PAYMENT_REQUIRED);
// The placeholder before the registry confirms the tenant is read-only.
let unconfirmed = call(
router_with_ctx(Some(support_ctx(TenantStatus::Restricted))),
Method::POST,
"/w",
)
.await;
assert_eq!(unconfirmed.status(), StatusCode::PAYMENT_REQUIRED);
let active = call(
router_with_ctx(Some(support_ctx(TenantStatus::Active))),
Method::POST,
"/w",
)
.await;
assert_eq!(active.status(), StatusCode::OK);
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-core"
version = "0.1.0"
version = "0.4.4"
edition = "2021"
[lints]
+174 -5
View File
@@ -14,6 +14,13 @@
//! * Signature / expiry invalid → 401.
//! * Claims present but tenant_id missing → 401 (treated as a malformed
//! token; the realm must always issue tenant_id).
//!
//! Support access: a token carrying one of [`SUPPORT_ROLES`] (BreakPilot
//! staff) may name the tenant to act in with the [`SUPPORT_TENANT_HEADER`].
//! The context is then marked as staff access and left read-only until the
//! agent has confirmed the tenant with the registry. Staff without a chosen
//! tenant get only a [`StaffAccess`] extension, which no tenant-scoped handler
//! accepts. For every other token the header is ignored.
use std::sync::Arc;
@@ -28,7 +35,8 @@ use reqwest::StatusCode;
use serde::Deserialize;
use tokio::sync::RwLock;
use crate::{OrgRole, TenantContext, TenantStatus};
use crate::tenant::SUPPORT_TENANT_HEADER;
use crate::{OrgRole, StaffAccess, TenantContext, TenantStatus, SUPPORT_ROLES};
/// Cached JWKS from Keycloak for token validation.
///
@@ -86,6 +94,25 @@ struct Claims {
tenant_status: Option<TenantStatus>,
#[serde(default)]
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
@@ -131,11 +158,20 @@ pub async fn require_jwt_auth(mut request: Request, next: Next) -> Response {
_ => return (StatusCode::UNAUTHORIZED, "Invalid authorization header").into_response(),
};
match validate_token(token, &jwks_state).await {
Ok(ctx) => {
let requested_tenant = request
.headers()
.get(SUPPORT_TENANT_HEADER)
.and_then(|v| v.to_str().ok())
.map(str::to_owned);
match validate_token(token, &jwks_state, requested_tenant.as_deref()).await {
Ok(Authenticated::Tenant(ctx)) => {
request.extensions_mut().insert(ctx);
next.run(request).await
}
Ok(Authenticated::StaffWithoutTenant(staff)) => {
request.extensions_mut().insert(staff);
next.run(request).await
}
Err(e) => {
tracing::warn!("JWT validation failed: {e}");
(StatusCode::UNAUTHORIZED, "Invalid token").into_response()
@@ -211,8 +247,70 @@ fn is_write(m: &Method) -> bool {
!matches!(m, &Method::GET | &Method::HEAD | &Method::OPTIONS)
}
async fn validate_token(token: &str, state: &JwksState) -> Result<TenantContext, String> {
claims_to_context(decode_claims(token, state).await?)
async fn validate_token(
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
@@ -332,6 +430,7 @@ fn claims_to_context(c: Claims) -> Result<TenantContext, String> {
status,
user_id: c.sub,
user_name: c.name.or(c.preferred_username),
staff: None,
})
}
@@ -392,6 +491,76 @@ mod tests {
plan: "professional".to_string(),
tenant_status: Some(TenantStatus::Active),
azp: Some("pruefwerk-dashboard-stage".to_string()),
realm_access: None,
}
}
const OTHER_TENANT: &str = "00000000-0000-0000-0000-000000000002";
fn staff_claims() -> Claims {
let mut c = base_claims();
c.tenant_id = String::new();
c.tenant_slug = String::new();
c.org_roles = Vec::new();
c.name = Some("Sharang Parnerkar".to_string());
c.realm_access = Some(RealmAccess {
roles: vec!["offline_access".to_string(), "SUPPORT_ENGINEER".to_string()],
});
c
}
#[test]
fn a_customer_cannot_switch_tenants_with_the_header() {
let outcome = authenticate(base_claims(), Some(OTHER_TENANT)).expect("should map");
let Authenticated::Tenant(ctx) = outcome else {
panic!("expected the customer's own tenant");
};
assert_eq!(ctx.tenant_id, "00000000-0000-0000-0000-000000000001");
assert_eq!(ctx.staff, None);
}
#[test]
fn support_opens_the_tenant_it_names_read_only_until_confirmed() {
let outcome = authenticate(staff_claims(), Some(OTHER_TENANT)).expect("should map");
let Authenticated::Tenant(ctx) = outcome else {
panic!("expected a tenant context");
};
assert_eq!(ctx.tenant_id, OTHER_TENANT);
assert_eq!(ctx.status, TenantStatus::Restricted);
assert_eq!(ctx.user_id, "user-123");
let staff = ctx.staff.expect("marked as support");
assert_eq!(staff.label(), "BreakPilot-Support (Sharang Parnerkar)");
}
#[test]
fn both_staff_roles_grant_support_access() {
for role in SUPPORT_ROLES {
let mut c = staff_claims();
c.realm_access = Some(RealmAccess {
roles: vec![role.to_string()],
});
assert!(matches!(
authenticate(c, Some(OTHER_TENANT)),
Ok(Authenticated::Tenant(TenantContext { staff: Some(_), .. }))
));
}
}
#[test]
fn support_without_a_chosen_tenant_gets_no_tenant() {
let outcome = authenticate(staff_claims(), None).expect("should map");
assert!(matches!(outcome, Authenticated::StaffWithoutTenant(_)));
}
#[test]
fn a_malformed_tenant_header_is_refused() {
for bad in [
"../admin",
"acme",
"00000000-0000-0000-0000-00000000000g",
"",
] {
assert!(authenticate(staff_claims(), Some(bad)).is_err(), "{bad}");
}
}
+1
View File
@@ -46,6 +46,7 @@ mod tests {
status: TenantStatus::Active,
user_id: "u-1".to_string(),
user_name: None,
staff: None,
}
}
+4 -1
View File
@@ -27,4 +27,7 @@ pub use config::{AgentConfig, AppEnv, DashboardConfig, Features, PlcRuntimeConfi
pub use error::CoreError;
pub use exec_policy::ExecPolicy;
pub use net_guard::{NetGuard, NetGuardError};
pub use tenant::{OrgRole, TenantContext, TenantStatus};
pub use tenant::{
OrgRole, ProductAccess, StaffAccess, TenantContext, TenantStatus, SUPPORT_ROLES,
SUPPORT_TENANT_HEADER,
};
+21
View File
@@ -18,4 +18,25 @@ pub struct AuthInfo {
/// The docs site this deployment links to from the sidebar.
#[serde(default)]
pub docs_url: String,
/// Holds a BreakPilot support role, so may open any tenant.
#[serde(default)]
pub staff: bool,
/// The customer tenant support has opened; `None` for everyone else and
/// for support before choosing one.
#[serde(default)]
pub support_tenant: Option<SupportTenant>,
/// What the user's org roles allow in Prüfwerk; decides whether the
/// app shows at all and whether write actions show. The agent enforces
/// the same rule on every request.
#[serde(default)]
pub access: crate::ProductAccess,
}
/// 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,
/// The user id of whoever changed it.
pub by: String,
/// How the customer reads who it was: a name, or "BreakPilot-Support
/// (name)"; absent in changes from before it was recorded.
#[serde(default)]
pub by_name: Option<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")]
pub at: DateTime<Utc>,
/// Why; required when a risk is accepted.
+3 -1
View File
@@ -14,13 +14,14 @@ pub mod onboarding;
pub mod oscal;
pub mod oscal_assessment;
pub mod pentest;
pub mod project;
pub mod repository;
pub mod sbom;
pub mod scan;
pub(crate) mod serde_helpers;
pub mod werkbank;
pub use auth::AuthInfo;
pub use auth::{AuthInfo, SupportTenant};
pub use chat::{ChatMessage, ChatRequest, ChatResponse, SourceReference};
pub use credentials::Credentials;
pub use cve::{CveAlert, CveSource};
@@ -51,6 +52,7 @@ pub use pentest::{
PentestStatus, PentestStrategy, SeverityDistribution, TestUserRecord, TesterInfo,
ToolCallRecord,
};
pub use project::{Project, ProjectKind};
pub use repository::ScanTrigger;
pub use sbom::{SbomEntry, VulnRef};
pub use scan::{
+6
View File
@@ -589,6 +589,11 @@ pub struct OnboardedTarget {
/// Cached count of findings across this target's scans.
#[serde(default)]
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.
#[serde(
default = "chrono::Utc::now",
@@ -623,6 +628,7 @@ impl OnboardedTarget {
webhook_enabled: false,
webhook_secret: None,
findings_count: 0,
project_ids: Vec::new(),
created_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,
Webhook,
Manual,
/// Started by BreakPilot support in the customer's tenant; not counted
/// as the customer's usage.
Support,
}
impl ScanTrigger {
/// Whether a person started the scan (the customer or support), so it
/// runs even when nothing changed since the last one.
pub fn started_by_person(&self) -> bool {
match self {
Self::Manual | Self::Support => true,
Self::Scheduled | Self::Webhook => false,
}
}
}
+149
View File
@@ -118,6 +118,84 @@ impl OrgRole {
}
}
/// What an organisation member may do in Prüfwerk, by their org roles
/// (decided 2026-09-30):
///
/// * `IT_ADMIN`, `USER` — [`ProductAccess::Full`]: read and write.
/// * `CXO`, `LEGAL` — [`ProductAccess::ReadOnly`]: findings, reports, SBOM,
/// evidence and exports, but no change of any kind.
/// * `FINANCE`, or none of these roles — [`ProductAccess::None`].
///
/// The strongest role a user holds wins. BreakPilot support sessions are not
/// judged by org roles (see [`TenantContext::product_access`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ProductAccess {
/// Read and write.
Full,
/// Read only: every write is refused.
ReadOnly,
/// No access at all. The default, so a missing value never grants access.
#[default]
None,
}
impl ProductAccess {
/// The access the org `roles` grant.
pub fn for_roles(roles: &[OrgRole]) -> Self {
if roles
.iter()
.any(|r| matches!(r, OrgRole::ItAdmin | OrgRole::User))
{
Self::Full
} else if roles
.iter()
.any(|r| matches!(r, OrgRole::Cxo | OrgRole::Legal))
{
Self::ReadOnly
} else {
Self::None
}
}
/// Whether anything may be read.
pub fn can_read(self) -> bool {
!matches!(self, Self::None)
}
/// Whether anything may be changed.
pub fn can_write(self) -> bool {
matches!(self, Self::Full)
}
}
/// 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
/// lands. Cheap to clone (every field is owned + small).
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -143,9 +221,33 @@ pub struct TenantContext {
/// Optional user-facing name from the `name` / `preferred_username`
/// claim. Only used in audit + log lines.
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 {
/// 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(),
}
}
/// What this request may do in Prüfwerk. BreakPilot support keeps its
/// own rules (read-only until the registry confirms the tenant, every
/// change audited), so it is not judged by org roles.
pub fn product_access(&self) -> ProductAccess {
if self.staff.is_some() {
return ProductAccess::Full;
}
ProductAccess::for_roles(&self.org_roles)
}
/// True if the caller holds at least one of the listed roles.
pub fn has_any_role(&self, roles: &[OrgRole]) -> bool {
self.org_roles.iter().any(|r| roles.contains(r))
@@ -186,6 +288,52 @@ mod tests {
assert!(!TenantStatus::Active.is_demo());
}
#[test]
fn product_access_follows_the_strongest_role() {
use OrgRole::*;
let cases: &[(&[OrgRole], ProductAccess)] = &[
(&[ItAdmin], ProductAccess::Full),
(&[User], ProductAccess::Full),
(&[Cxo], ProductAccess::ReadOnly),
(&[Legal], ProductAccess::ReadOnly),
(&[Finance], ProductAccess::None),
(&[Unknown], ProductAccess::None),
(&[], ProductAccess::None),
(&[Finance, Legal], ProductAccess::ReadOnly),
(&[Cxo, User], ProductAccess::Full),
(&[Finance, ItAdmin], ProductAccess::Full),
];
for (roles, want) in cases {
assert_eq!(ProductAccess::for_roles(roles), *want, "{roles:?}");
}
assert!(ProductAccess::Full.can_write());
assert!(!ProductAccess::ReadOnly.can_write());
assert!(ProductAccess::ReadOnly.can_read());
assert!(!ProductAccess::None.can_read());
assert_eq!(ProductAccess::default(), ProductAccess::None);
}
#[test]
fn support_is_not_judged_by_org_roles() {
let ctx = TenantContext {
tenant_id: "t1".into(),
tenant_slug: "acme".into(),
org_roles: vec![],
products: vec![],
plan: String::new(),
status: TenantStatus::Restricted,
user_id: "s".into(),
user_name: None,
staff: Some(StaffAccess {
user_id: "s".into(),
user_name: None,
}),
};
assert_eq!(ctx.product_access(), ProductAccess::Full);
let customer = TenantContext { staff: None, ..ctx };
assert_eq!(customer.product_access(), ProductAccess::None);
}
#[test]
fn has_any_role_matches() {
let ctx = TenantContext {
@@ -197,6 +345,7 @@ mod tests {
status: TenantStatus::Active,
user_id: "u".into(),
user_name: None,
staff: None,
};
assert!(ctx.has_any_role(&[OrgRole::ItAdmin]));
assert!(ctx.has_any_role(&[OrgRole::Cxo, OrgRole::ItAdmin]));
+107 -5
View File
@@ -20,24 +20,79 @@ use axum::{
response::{IntoResponse, Response},
};
use crate::TenantContext;
use crate::{StaffAccess, TenantContext};
/// What a support user without a chosen tenant is told by a tenant-scoped
/// route. Distinct from an expired sign-in, so the dashboard asks for a
/// tenant instead of sending the user back to the login.
pub const TENANT_NOT_SELECTED: &str = "tenant_not_selected";
#[derive(Debug, Clone)]
pub struct TenantCtx(pub TenantContext);
/// Why a tenant-scoped route refused the request.
#[derive(Debug)]
pub struct TenantCtxRejection;
pub enum TenantCtxRejection {
/// No authenticated tenant at all.
Unauthenticated,
/// BreakPilot support, signed in, with no tenant chosen yet.
TenantNotSelected,
}
impl IntoResponse for TenantCtxRejection {
fn into_response(self) -> Response {
match self {
Self::Unauthenticated => (
StatusCode::UNAUTHORIZED,
"Missing tenant context — request was not authenticated",
)
.into_response(),
Self::TenantNotSelected => (
StatusCode::PRECONDITION_REQUIRED,
axum::Json(serde_json::json!({ "error": TENANT_NOT_SELECTED })),
)
.into_response(),
}
}
}
/// A BreakPilot support user, with or without a chosen tenant. For the
/// support routes (the tenant list); 403 for everyone else.
#[derive(Debug, Clone)]
pub struct StaffCtx(pub StaffAccess);
/// A request that is not from BreakPilot support.
#[derive(Debug)]
pub struct StaffCtxRejection;
impl IntoResponse for StaffCtxRejection {
fn into_response(self) -> Response {
(
StatusCode::UNAUTHORIZED,
"Missing tenant context — request was not authenticated",
StatusCode::FORBIDDEN,
axum::Json(serde_json::json!({ "error": "support_only" })),
)
.into_response()
}
}
impl<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
where
S: Send + Sync,
@@ -50,7 +105,13 @@ where
.get::<TenantContext>()
.cloned()
.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,
user_id: "u-1".to_string(),
user_name: None,
staff: None,
}
}
@@ -92,4 +154,44 @@ mod tests {
let err = TenantCtx::from_request_parts(&mut parts, &()).await;
assert!(err.is_err());
}
fn staff() -> StaffAccess {
StaffAccess {
user_id: "s-1".to_string(),
user_name: Some("Support".to_string()),
}
}
#[tokio::test]
async fn support_without_a_tenant_is_asked_to_choose_one() {
let mut req = Request::new(());
req.extensions_mut().insert(staff());
let (mut parts, _) = req.into_parts();
let err = TenantCtx::from_request_parts(&mut parts, &()).await;
assert!(matches!(err, Err(TenantCtxRejection::TenantNotSelected)));
}
#[tokio::test]
async fn only_support_passes_the_staff_extractor() {
let mut customer = Request::new(());
customer.extensions_mut().insert(ctx());
let (mut parts, _) = customer.into_parts();
assert!(StaffCtx::from_request_parts(&mut parts, &()).await.is_err());
let mut chosen = Request::new(());
chosen.extensions_mut().insert(TenantContext {
staff: Some(staff()),
..ctx()
});
let (mut parts, _) = chosen.into_parts();
let StaffCtx(found) = StaffCtx::from_request_parts(&mut parts, &())
.await
.expect("support with a tenant");
assert_eq!(found.user_id, "s-1");
let mut unchosen = Request::new(());
unchosen.extensions_mut().insert(staff());
let (mut parts, _) = unchosen.into_parts();
assert!(StaffCtx::from_request_parts(&mut parts, &()).await.is_ok());
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-dashboard"
version = "0.1.0"
version = "0.4.4"
edition = "2021"
default-run = "compliance-dashboard"
@@ -0,0 +1,92 @@
Copyright (c) 2023 Vercel, in collaboration with basement.studio
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION AND CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+287 -1
View File
@@ -6,7 +6,25 @@
with the portal (platform/portal src/app/globals.css).
═══════════════════════════════════════════════════════════════ */
@import url('https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700;800&family=Geist+Mono:wght@400;500;600&display=swap');
/* ── Fonts ──
Geist and Geist Mono (SIL OFL 1.1, assets/fonts/OFL-Geist.txt), served by
the dashboard itself at /fonts/ (infrastructure/server.rs). No third-party
font CDN: a visitor's browser talks to this host only. */
@font-face {
font-family: 'Geist';
src: url('/fonts/geist.woff2') format('woff2');
font-weight: 100 900;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: 'Geist Mono';
src: url('/fonts/geist-mono.woff2') format('woff2');
font-weight: 100 900;
font-style: normal;
font-display: swap;
}
/* ── Design Tokens (light, the default) ── */
:root {
@@ -5204,3 +5222,271 @@ input[type="file"] {
color: var(--text-secondary);
font-size: 13px;
}
/* ═══════════════════════════════════════════════════════════════
SUPPORT ACCESS — tenant picker and banner for BreakPilot staff
═══════════════════════════════════════════════════════════════ */
.support-picker {
min-height: 100vh;
display: flex;
align-items: flex-start;
justify-content: center;
padding: 64px 16px;
background: var(--bg-primary);
}
.support-picker-card {
width: 100%;
max-width: 640px;
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 16px;
padding: 28px;
box-shadow: var(--shadow-pop);
}
.support-picker-head {
display: flex;
align-items: center;
gap: 10px;
}
.support-picker-head h1 {
margin: 0;
font-family: var(--font-display);
font-size: 22px;
}
.support-picker-mark {
display: inline-flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
border-radius: 10px;
background: var(--accent-muted);
color: var(--accent);
}
.support-picker-intro {
color: var(--text-secondary);
font-size: 14px;
margin: 10px 0 18px;
}
.support-picker-search {
display: flex;
align-items: center;
gap: 8px;
border: 1px solid var(--border);
border-radius: 10px;
padding: 0 12px;
background: var(--bg-elevated);
color: var(--text-tertiary);
}
.support-picker-search:focus-within {
border-color: var(--accent);
}
.support-picker-search input {
flex: 1;
border: none;
background: transparent;
padding: 10px 0;
font: inherit;
color: var(--text-primary);
outline: none;
}
.support-picker-list {
list-style: none;
margin: 14px 0 0;
padding: 0;
display: grid;
gap: 6px;
max-height: 60vh;
overflow-y: auto;
}
.support-picker-row {
width: 100%;
display: grid;
grid-template-columns: 1fr auto auto auto;
align-items: center;
gap: 12px;
text-align: left;
background: var(--bg-elevated);
border: 1px solid var(--border);
border-radius: 10px;
padding: 10px 14px;
font: inherit;
color: var(--text-primary);
cursor: pointer;
transition: border-color 0.15s, background 0.15s;
}
.support-picker-row:not(:disabled):hover {
border-color: var(--accent);
background: var(--accent-muted);
}
.support-picker-row:disabled {
cursor: wait;
opacity: 0.7;
}
.support-picker-name {
font-weight: 600;
}
.support-picker-slug,
.support-picker-status {
font-family: var(--font-mono);
font-size: 12px;
color: var(--text-tertiary);
}
.support-picker-open {
color: var(--accent);
font-size: 13px;
font-weight: 600;
}
.support-picker-note {
color: var(--text-secondary);
font-size: 14px;
}
.support-picker-error {
color: var(--danger);
font-size: 14px;
}
@media (max-width: 560px) {
.support-picker-row { grid-template-columns: 1fr auto; }
.support-picker-slug,
.support-picker-status { display: none; }
}
.support-banner {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px 12px;
margin: -8px 0 16px;
padding: 8px 14px;
border-radius: 10px;
background: var(--warning-bg, var(--accent-muted));
border: 1px solid color-mix(in oklch, var(--warning, var(--accent)) 45%, var(--border));
color: var(--text-primary);
font-size: 13px;
}
.support-banner-note {
color: var(--text-secondary);
}
.support-banner-switch {
margin-left: auto;
display: inline-flex;
align-items: center;
gap: 6px;
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 8px;
padding: 4px 10px;
font: inherit;
font-size: 12px;
color: var(--text-primary);
cursor: pointer;
}
.support-banner-switch:hover {
border-color: var(--accent);
}
.history-by-support {
color: var(--accent);
font-weight: 600;
}
/* ═══════════════════════════════════════════════════════════════
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; }
}
/* Org roles: the page for a role without access, and the read-only note. */
.no-access-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
margin-top: 16px;
}
.read-only-banner {
display: flex;
align-items: center;
gap: 8px;
margin: -8px 0 16px;
padding: 8px 14px;
border-radius: 10px;
background: var(--accent-muted);
border: 1px solid var(--border);
color: var(--text-secondary);
font-size: 13px;
}
+2 -2
View File
@@ -55,7 +55,6 @@ pub enum Route {
McpTokensPage {},
}
const FAVICON: Asset = asset!("/assets/favicon.svg");
const MAIN_CSS: Asset = asset!("/assets/main.css");
const TAILWIND_CSS: Asset = asset!("/assets/tailwind.css");
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
// in the page source and honoured by crawlers that read only HTML.
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: MAIN_CSS }
document::Script { src: VIS_NETWORK_JS }
@@ -2,8 +2,10 @@ use dioxus::prelude::*;
use crate::app::Route;
use crate::components::help_chat::HelpChat;
use crate::components::no_access::{NoAccess, ReadOnlyBanner};
use crate::components::notification_bell::NotificationBell;
use crate::components::sidebar::Sidebar;
use crate::components::support::{SupportBanner, SupportPicker};
use crate::components::toast::{ToastContainer, Toasts};
use crate::infrastructure::auth_check::check_auth;
use crate::infrastructure::platform::fetch_platform_info;
@@ -41,12 +43,34 @@ pub fn AppShell() -> Element {
});
match auth() {
// BreakPilot support chooses a tenant first: every page asks the agent
// for one, and without it would only be refused.
Some(Ok(info)) if info.authenticated && info.staff && info.support_tenant.is_none() => {
rsx! {
SupportPicker {}
ToastContainer {}
}
}
// A role without access to Prüfwerk (FINANCE, or none): no navigation
// and no page, so nothing is fetched or shown.
Some(Ok(info)) if info.authenticated && !info.access.can_read() => {
rsx! {
NoAccess { portal_url: info.portal_url.clone() }
}
}
Some(Ok(info)) if info.authenticated => {
use_context_provider(|| Signal::new(info.clone()));
let read_only = !info.access.can_write();
rsx! {
div { class: "app-shell",
Sidebar {}
main { class: "main-content",
if let Some(tenant) = info.support_tenant.clone() {
SupportBanner { tenant }
}
if read_only {
ReadOnlyBanner {}
}
Outlet::<Route> {}
}
NotificationBell {}
@@ -12,13 +12,16 @@ pub mod help_chat;
pub mod lang_toggle;
pub mod manual_findings;
pub mod markdown;
pub mod no_access;
pub mod notification_bell;
pub mod page_header;
pub mod pagination;
pub mod pentest_wizard;
pub mod projects;
pub mod scan_coverage;
pub mod scan_runs;
pub mod severity_badge;
pub mod sidebar;
pub mod support;
pub mod theme_toggle;
pub mod toast;
@@ -0,0 +1,54 @@
//! What a user sees whose org role has no access to Prüfwerk (`FINANCE`, or
//! no role at all), and the notice for roles that may only read.
use compliance_core::models::auth::AuthInfo;
use dioxus::prelude::*;
use dioxus_free_icons::icons::bs_icons::{BsEye, BsShieldLock};
use dioxus_free_icons::Icon;
use crate::components::lang_toggle::LangToggle;
use crate::i18n::texts::access as tx;
use crate::i18n::use_lang;
/// Whether the signed-in user's role may change anything. Write actions
/// (add, scan, delete, triage, tokens, settings) show only when it may; the
/// agent refuses them either way.
pub fn use_can_write() -> bool {
try_use_context::<Signal<AuthInfo>>().is_some_and(|info| info.read().access.can_write())
}
/// The whole page for a role without access: no navigation, no data.
#[component]
pub fn NoAccess(portal_url: String) -> Element {
let lang = use_lang()();
rsx! {
main { class: "support-picker",
div { class: "support-picker-card", role: "alert",
div { class: "support-picker-head",
span { class: "support-picker-mark", Icon { icon: BsShieldLock, width: 18, height: 18 } }
h1 { {tx::NO_ACCESS_TITLE.get(lang)} }
}
p { class: "support-picker-intro", {tx::NO_ACCESS_BODY.get(lang)} }
div { class: "no-access-actions",
if !portal_url.is_empty() {
a { class: "btn btn-primary", href: "{portal_url}", {tx::BACK_TO_PORTAL.get(lang)} }
}
a { class: "btn btn-ghost", href: "/logout", {tx::SIGN_OUT.get(lang)} }
LangToggle { collapsed: true }
}
}
}
}
}
/// A line at the top of the page for roles that may only read.
#[component]
pub fn ReadOnlyBanner() -> Element {
let lang = use_lang()();
rsx! {
div { class: "read-only-banner", role: "status",
Icon { icon: BsEye, width: 14, height: 14 }
span { {tx::READ_ONLY.get(lang)} }
}
}
}
@@ -9,6 +9,7 @@ use crate::infrastructure::notifications::{
#[component]
pub fn NotificationBell() -> Element {
let can_write = crate::components::no_access::use_can_write();
let mut is_open = use_signal(|| false);
let mut count = use_signal(|| 0u64);
let mut notifications = use_signal(Vec::new);
@@ -42,9 +43,12 @@ pub fn NotificationBell() -> Element {
if let Ok(resp) = fetch_notifications().await {
notifications.set(resp.data);
}
// Mark all as read when panel opens
let _ = mark_all_notifications_read().await;
count.set(0);
// Mark all as read when panel opens; a read-only role leaves the
// tenant's alerts as they are.
if can_write {
let _ = mark_all_notifications_read().await;
count.set(0);
}
is_loading.set(false);
});
};
@@ -124,11 +128,13 @@ pub fn NotificationBell() -> Element {
if let Some(score) = notif.cvss_score {
span { class: "notification-cvss", "CVSS {score:.1}" }
}
button {
class: "notification-dismiss-btn",
title: "Dismiss",
onclick: move |_| on_dismiss(dismiss_id.clone()),
Icon { icon: BsXCircle, width: 14, height: 14 }
if can_write {
button {
class: "notification-dismiss-btn",
title: "Dismiss",
onclick: move |_| on_dismiss(dismiss_id.clone()),
Icon { icon: BsXCircle, width: 14, height: 14 }
}
}
}
div { class: "notification-item-pkg",
@@ -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)} }
}
}
}
}
+13 -1
View File
@@ -5,6 +5,7 @@ use dioxus_free_icons::Icon;
use crate::app::Route;
use crate::components::lang_toggle::LangToggle;
use crate::components::no_access::use_can_write;
use crate::components::theme_toggle::ThemeToggle;
use crate::i18n::texts::{common, nav};
use crate::i18n::{use_lang, Text};
@@ -27,6 +28,8 @@ struct NavItem {
icon: Element,
/// Needs a runtime (browser / live target); disabled in source-only mode.
runtime_only: bool,
/// Only for roles that may change things (onboarding a target).
write_only: bool,
}
#[component]
@@ -37,24 +40,28 @@ pub fn Sidebar() -> Element {
let source_only = use_source_only();
let lang = use_lang()();
let can_write = use_can_write();
let nav_items = [
NavItem {
label: nav::OVERVIEW,
route: Route::OverviewPage {},
icon: rsx! { Icon { icon: BsSpeedometer2, width: 18, height: 18 } },
runtime_only: false,
write_only: false,
},
NavItem {
label: nav::TARGETS,
route: Route::TargetsPage {},
icon: rsx! { Icon { icon: BsFolder2Open, width: 18, height: 18 } },
runtime_only: false,
write_only: false,
},
NavItem {
label: nav::ONBOARD,
route: Route::OnboardingPage {},
icon: rsx! { Icon { icon: BsPlusCircle, width: 18, height: 18 } },
runtime_only: false,
write_only: true,
},
NavItem {
label: nav::FINDINGS,
@@ -63,30 +70,35 @@ pub fn Sidebar() -> Element {
},
icon: rsx! { Icon { icon: BsShieldExclamation, width: 18, height: 18 } },
runtime_only: false,
write_only: false,
},
NavItem {
label: nav::SBOM,
route: Route::SbomPage {},
icon: rsx! { Icon { icon: BsBoxSeam, width: 18, height: 18 } },
runtime_only: false,
write_only: false,
},
NavItem {
label: nav::ISSUES,
route: Route::IssuesPage {},
icon: rsx! { Icon { icon: BsListTask, width: 18, height: 18 } },
runtime_only: false,
write_only: false,
},
NavItem {
label: nav::DAST,
route: Route::DastOverviewPage {},
icon: rsx! { Icon { icon: BsBug, width: 18, height: 18 } },
runtime_only: true,
write_only: false,
},
NavItem {
label: nav::PENTEST,
route: Route::PentestDashboardPage {},
icon: rsx! { Icon { icon: BsLightningCharge, width: 18, height: 18 } },
runtime_only: true,
write_only: false,
},
];
@@ -144,7 +156,7 @@ pub fn Sidebar() -> Element {
}
}
div { class: "sidebar-nav",
for item in nav_items {
for item in nav_items.into_iter().filter(|i| can_write || !i.write_only) {
{
let is_active = match (&current_route, &item.route) {
(Route::FindingDetailPage { .. } | Route::FindingsPage { .. }, Route::FindingsPage { .. }) => true,
@@ -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)}
}
}
}
}
+134
View File
@@ -1653,6 +1653,11 @@ pub mod findings {
de: "Verlauf",
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 {
de: "Begründung",
en: "Reason",
@@ -2397,6 +2402,106 @@ pub mod demo {
}
/// 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.
pub mod help {
use super::Text;
@@ -2697,3 +2802,32 @@ mod run_error_tests {
);
}
}
/// What a user's org role allows (`IT_ADMIN` / `USER` everything, `CXO` /
/// `LEGAL` reading, `FINANCE` and no role nothing).
pub mod access {
use super::Text;
pub const NO_ACCESS_TITLE: Text = Text {
de: "Kein Zugriff auf Prüfwerk",
en: "No access to Prüfwerk",
};
pub const NO_ACCESS_BODY: Text = Text {
de: "Ihre Rolle hat keinen Zugriff auf Prüfwerk. Wenden Sie sich an Ihre \
IT-Administration.",
en: "Your role has no access to Prüfwerk. Please contact your IT administration.",
};
pub const BACK_TO_PORTAL: Text = Text {
de: "Zurück zum Portal",
en: "Back to the portal",
};
pub const SIGN_OUT: Text = Text {
de: "Abmelden",
en: "Sign out",
};
pub const READ_ONLY: Text = Text {
de: "Nur Lesezugriff: Ihre Rolle kann Ergebnisse ansehen und exportieren, aber \
nichts ändern.",
en: "Read-only: your role can view and export results, but not change anything.",
};
}
@@ -101,6 +101,15 @@ fn refusal_message(status: reqwest::StatusCode, body: &str) -> String {
let message = serde_json::from_str::<serde_json::Value>(body)
.ok()
.and_then(|v| v.get("error").and_then(|e| e.as_str()).map(String::from))
// The agent's role refusal, in words (the server does not know the
// page's language, so both).
.map(|m| {
if m == "forbidden_role" {
FORBIDDEN_ROLE_MESSAGE.to_string()
} else {
m
}
})
.filter(|m| !m.trim().is_empty())
.unwrap_or_else(|| {
status
@@ -111,6 +120,46 @@ fn refusal_message(status: reqwest::StatusCode, body: &str) -> String {
format!("{message} ({})", status.as_u16())
}
/// What the signed-in user may do in Prüfwerk; full access without Keycloak
/// (local development), none without a sign-in.
///
/// # Errors
///
/// The session could not be read.
pub(crate) async fn current_access() -> Result<compliance_core::ProductAccess, ServerFnError> {
let state: ServerState = FullstackContext::extract().await?;
if state.keycloak.is_none() {
return Ok(compliance_core::ProductAccess::Full);
}
let session: tower_sessions::Session = FullstackContext::extract().await?;
Ok(current_user(&state, &session)
.await?
.map(|u| u.product_access())
.unwrap_or_default())
}
/// Refuse a change for a role that may only read, as the agent does. For the
/// server functions that do not go through the agent.
///
/// # Errors
///
/// `forbidden_role` for read-only (or no) access; the session could not be
/// read.
pub(crate) async fn require_write_access() -> Result<(), ServerFnError> {
if current_access().await?.can_write() {
Ok(())
} else {
Err(ServerFnError::new(refusal_message(
reqwest::StatusCode::FORBIDDEN,
r#"{"error":"forbidden_role"}"#,
)))
}
}
/// What a user reads when their role may not do what they asked.
const FORBIDDEN_ROLE_MESSAGE: &str = "Ihre Rolle hat in Prüfwerk nur Lesezugriff. / \
Your role has read-only access to Prüfwerk.";
/// Same as [`agent_request`] but for `GET`. Convenience for the common case.
pub async fn agent_get(path: &str) -> Result<reqwest::RequestBuilder, ServerFnError> {
agent_request(Method::GET, path).await
@@ -213,11 +262,26 @@ async fn attach_token(
}
let session: tower_sessions::Session = FullstackContext::extract().await?;
match current_user(state, &session).await? {
Some(user) => Ok(req.bearer_auth(user.access_token)),
Some(user) => Ok(with_support_tenant(
req.bearer_auth(&user.access_token),
&user,
)),
None => Err(ServerFnError::new(super::auth_check::SESSION_EXPIRED)),
}
}
/// Name the tenant BreakPilot support has opened, when it has; the agent
/// honours the header only for a support role.
fn with_support_tenant(
req: reqwest::RequestBuilder,
user: &UserStateInner,
) -> reqwest::RequestBuilder {
match &user.support_tenant {
Some(tenant) => req.header(compliance_core::SUPPORT_TENANT_HEADER, &tenant.id),
None => req,
}
}
/// Decode the JWT's payload (no signature verification — the agent
/// does that) and check the `exp` claim. Treats malformed tokens as
/// expired so the refresh path runs.
@@ -331,6 +395,13 @@ mod tests {
refusal_message(reqwest::StatusCode::FORBIDDEN, r#"{"error":""}"#),
"Forbidden (403)"
);
assert_eq!(
refusal_message(
reqwest::StatusCode::FORBIDDEN,
r#"{"error":"forbidden_role","access":"read_only"}"#
),
format!("{FORBIDDEN_ROLE_MESSAGE} (403)")
);
}
use base64::Engine;
@@ -16,7 +16,7 @@ use url::Url;
use super::{
error::DashboardError,
server_state::ServerState,
user_state::{tenant_slug_from_token, User, UserStateInner},
user_state::{has_support_role, tenant_slug_from_token, User, UserStateInner},
};
pub const LOGGED_IN_USER_SESS_KEY: &str = "logged-in-user";
@@ -126,6 +126,30 @@ pub async fn auth_login(
Extension(pending): Extension<PendingOAuthStore>,
Query(params): Query<HashMap<String, String>>,
) -> 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
.keycloak
.ok_or(DashboardError::Other("Keycloak not configured".into()))?;
@@ -157,6 +181,9 @@ pub async fn auth_login(
.append_pair("state", &csrf_state)
.append_pair("code_challenge", &code_challenge)
.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()))
}
@@ -241,9 +268,12 @@ pub async fn auth_callback(
.unwrap_or_default();
let tenant_slug = tenant_slug_from_token(&tokens.access_token);
let staff = has_support_role(&tokens.access_token);
let user_state = UserStateInner {
sub: userinfo.sub,
tenant_slug,
staff,
support_tenant: None,
access_token: tokens.access_token,
refresh_token: tokens.refresh_token.unwrap_or_default(),
user: User {
@@ -39,6 +39,7 @@ pub async fn check_auth() -> Result<AuthInfo, ServerFnError> {
name: "Local User".into(),
portal_url: portal_link(state.portal_url.as_deref(), ""),
docs_url: state.docs_url.clone(),
access: compliance_core::ProductAccess::Full,
..Default::default()
});
}
@@ -52,7 +53,15 @@ pub async fn check_auth() -> Result<AuthInfo, ServerFnError> {
match user_state {
Some(u) => Ok(AuthInfo {
authenticated: true,
portal_url: portal_link(state.portal_url.as_deref(), &u.tenant_slug),
access: u.product_access(),
// Support is not a member of the tenant it opened: the portal's
// start page, not the workspace's.
portal_url: portal_link(
state.portal_url.as_deref(),
if u.staff { "" } else { &u.tenant_slug },
),
staff: u.staff,
support_tenant: u.support_tenant,
docs_url: state.docs_url.clone(),
sub: u.sub,
email: u.user.email,
@@ -29,15 +29,23 @@ pub async fn require_auth(
let path = request.uri().path();
if path.starts_with("/api/") && !PUBLIC_API_ENDPOINTS.contains(&path) {
let is_authed = session
let user = session
.get::<UserStateInner>(LOGGED_IN_USER_SESS_KEY)
.await
.ok()
.flatten()
.is_some();
.flatten();
if !is_authed {
let Some(user) = user else {
return (StatusCode::UNAUTHORIZED, "Authentication required").into_response();
};
// A role without access to Prüfwerk (FINANCE, or none) runs no server
// function at all; the agent refuses the same requests on its own.
if !user.product_access().can_read() {
return (
StatusCode::FORBIDDEN,
axum::Json(serde_json::json!({ "error": "forbidden_role", "access": "none" })),
)
.into_response();
}
}
@@ -6,6 +6,9 @@ pub struct KeycloakConfig {
pub client_id: String,
pub redirect_uri: 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 {
@@ -15,12 +18,17 @@ impl KeycloakConfig {
let client_id = std::env::var("KEYCLOAK_CLIENT_ID").ok()?;
let redirect_uri = std::env::var("REDIRECT_URI").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 {
url,
realm,
client_id,
redirect_uri,
app_url,
staff_idp_hint,
})
}
+12 -1
View File
@@ -23,15 +23,21 @@ pub async fn fetch_mcp_servers() -> Result<McpServersResponse, ServerFnError> {
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
// A server's access token is a key: only a role that may change things
// sees it.
let show_tokens = super::agent_client::current_access().await?.can_write();
let mut data = Vec::new();
while cursor
.advance()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?
{
let server = cursor
let mut server: McpServerConfig = cursor
.deserialize_current()
.map_err(|e| ServerFnError::new(e.to_string()))?;
if !show_tokens {
server.access_token = String::new();
}
data.push(server);
}
@@ -50,6 +56,7 @@ pub async fn add_mcp_server(
) -> Result<(), ServerFnError> {
use chrono::Utc;
use compliance_core::models::{McpServerStatus, McpTransport};
super::agent_client::require_write_access().await?;
let state: super::server_state::ServerState =
dioxus_fullstack::FullstackContext::extract().await?;
@@ -152,6 +159,8 @@ pub fn mcp_health_url_candidates(
/// Probe each MCP server's health endpoint and update status in MongoDB.
#[server]
pub async fn refresh_mcp_status() -> Result<(), ServerFnError> {
// Not a change a role is refused: it only records what the health probe
// saw, and every reader's overview runs it.
use chrono::Utc;
use compliance_core::models::McpServerStatus;
use mongodb::bson::doc;
@@ -234,6 +243,7 @@ pub async fn refresh_mcp_status() -> Result<(), ServerFnError> {
#[server]
pub async fn delete_mcp_server(server_id: String) -> Result<(), ServerFnError> {
super::agent_client::require_write_access().await?;
use mongodb::bson::doc;
let state: super::server_state::ServerState =
@@ -254,6 +264,7 @@ pub async fn delete_mcp_server(server_id: String) -> Result<(), ServerFnError> {
#[server]
pub async fn regenerate_mcp_token(server_id: String) -> Result<String, ServerFnError> {
super::agent_client::require_write_access().await?;
use chrono::Utc;
use mongodb::bson::doc;
@@ -15,10 +15,12 @@ pub mod notifications;
pub mod onboarding;
pub mod pentest;
pub mod platform;
pub mod projects;
#[allow(clippy::too_many_arguments)]
pub mod sbom;
pub mod scans;
pub mod stats;
pub mod support;
// Server-only modules
#[cfg(feature = "server")]
@@ -45,7 +47,7 @@ mod session_store;
mod user_state;
#[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")]
pub use auth_middleware::require_auth;
#[cfg(feature = "server")]
@@ -311,8 +311,17 @@ pub fn validate_artifact_ref(kind: &str, source_ref: &str) -> Option<String> {
/// List onboarded targets.
#[server]
pub async fn fetch_targets() -> Result<TargetsResponse, ServerFnError> {
let resp = super::agent_client::agent_get("/api/v1/targets")
.await?
fetch_targets_in(None).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()
.await
.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::server_state::{ServerState, ServerStateInner};
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.
/// Keep the trailing slash: the docs route matches `/docs/*`, and a plain
@@ -117,7 +117,16 @@ pub fn server_start(app: fn() -> Element) -> Result<(), DashboardError> {
"/robots.txt",
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))
// Geist and Geist Mono, self-hosted: main.css loads them from
// here, so no page makes a request to a third-party font CDN.
.route("/fonts/geist.woff2", get(font_geist))
.route("/fonts/geist-mono.woff2", get(font_geist_mono))
.route("/auth", get(auth_login))
.route("/auth/staff", get(auth_staff_login))
.route("/auth/callback", get(auth_callback))
.route("/logout", get(logout))
.serve_dioxus_application(ServeConfig::new(), app)
@@ -211,6 +220,44 @@ 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,
)
}
/// Geist (SIL OFL 1.1, `assets/fonts/OFL-Geist.txt`), weights 100–900.
const GEIST_WOFF2: &[u8] = include_bytes!("../../assets/fonts/Geist-Variable.woff2");
/// Geist Mono (SIL OFL 1.1), weights 100–900.
const GEIST_MONO_WOFF2: &[u8] = include_bytes!("../../assets/fonts/GeistMono-Variable.woff2");
/// A bundled font file, cacheable for a week.
fn woff2(bytes: &'static [u8]) -> impl axum::response::IntoResponse {
(
[
(axum::http::header::CONTENT_TYPE, "font/woff2"),
(axum::http::header::CACHE_CONTROL, "public, max-age=604800"),
],
bytes,
)
}
async fn font_geist() -> impl axum::response::IntoResponse {
woff2(GEIST_WOFF2)
}
async fn font_geist_mono() -> impl axum::response::IntoResponse {
woff2(GEIST_MONO_WOFF2)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -224,4 +271,23 @@ mod tests {
assert_eq!(non_blank(Some(" ".into())), 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"));
}
#[test]
fn the_fonts_are_self_hosted_woff2() {
assert!(GEIST_WOFF2.starts_with(b"wOF2"));
assert!(GEIST_MONO_WOFF2.starts_with(b"wOF2"));
let css = include_str!("../../assets/main.css");
assert!(css.contains("url('/fonts/geist.woff2')"));
assert!(css.contains("url('/fonts/geist-mono.woff2')"));
for host in ["googleapis", "gstatic"] {
assert!(!css.contains(host), "main.css references {host}");
}
}
}
@@ -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};
/// Per-session user data stored in the tower-sessions session store.
@@ -11,6 +12,14 @@ pub struct UserStateInner {
/// portal. Empty in sessions from before it was stored.
#[serde(default)]
pub tenant_slug: String,
/// Holds a BreakPilot support role (`realm_access.roles`): decides whether
/// the tenant picker shows. The agent checks the role itself.
#[serde(default)]
pub staff: bool,
/// The customer tenant support has opened, named to the agent with
/// every request.
#[serde(default)]
pub support_tenant: Option<SupportTenant>,
}
/// Basic user profile stored alongside the session.
@@ -26,21 +35,69 @@ pub struct User {
/// The signature is not checked: the token comes straight from Keycloak's
/// token endpoint, and the slug only builds a link.
pub fn tenant_slug_from_token(access_token: &str) -> String {
use base64::Engine;
access_token
.split('.')
.nth(1)
.and_then(|payload| {
base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(payload.trim_end_matches('='))
.ok()
})
.and_then(|json| serde_json::from_slice::<serde_json::Value>(&json).ok())
token_claims(access_token)
.and_then(|claims| claims.get("tenant_slug")?.as_str().map(str::to_owned))
.unwrap_or_default()
}
/// Whether a Keycloak access token carries a BreakPilot support role. Not
/// verified, as for the slug: it only decides what the dashboard shows; the
/// agent verifies the token before granting anything.
pub fn has_support_role(access_token: &str) -> bool {
token_claims(access_token)
.and_then(|claims| {
let roles = claims
.get("realm_access")?
.get("roles")?
.as_array()?
.clone();
Some(roles.iter().any(|role| {
role.as_str()
.is_some_and(|r| compliance_core::SUPPORT_ROLES.contains(&r))
}))
})
.unwrap_or(false)
}
/// The `org_roles` claim of a Keycloak access token; empty without one.
/// Not verified, as for the slug: it decides what the dashboard shows and
/// which server functions it runs; the agent checks the verified token.
pub fn org_roles_from_token(access_token: &str) -> Vec<compliance_core::OrgRole> {
token_claims(access_token)
.and_then(|claims| {
let roles = claims.get("org_roles")?.as_array()?.clone();
Some(
roles
.iter()
.filter_map(|r| r.as_str().map(compliance_core::OrgRole::parse))
.collect(),
)
})
.unwrap_or_default()
}
impl UserStateInner {
/// What this sign-in may do in Prüfwerk. BreakPilot support follows the
/// support rules on the agent, not org roles.
pub fn product_access(&self) -> compliance_core::ProductAccess {
if self.staff {
return compliance_core::ProductAccess::Full;
}
compliance_core::ProductAccess::for_roles(&org_roles_from_token(&self.access_token))
}
}
/// 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
/// portal's start page when the slug is unknown. Empty without a portal URL.
///
@@ -85,6 +142,78 @@ mod tests {
assert_eq!(tenant_slug_from_token("not-a-jwt"), "");
}
#[test]
fn support_roles_are_read_from_the_access_token() {
let staff = token(&serde_json::json!({
"sub": "s1",
"realm_access": { "roles": ["offline_access", "SUPPORT_ENGINEER"] }
}));
let admin = token(&serde_json::json!({
"sub": "s2",
"realm_access": { "roles": ["BREAKPILOT_ADMIN"] }
}));
let customer = token(&serde_json::json!({
"sub": "u1",
"realm_access": { "roles": ["offline_access"] },
"org_roles": ["IT_ADMIN"]
}));
assert!(has_support_role(&staff));
assert!(has_support_role(&admin));
assert!(!has_support_role(&customer));
assert!(!has_support_role("not-a-jwt"));
}
#[test]
fn access_follows_the_org_roles_in_the_token() {
use compliance_core::ProductAccess;
let user = |claims: serde_json::Value, staff: bool| UserStateInner {
access_token: token(&claims),
staff,
..Default::default()
};
let cases = [
(
serde_json::json!({ "org_roles": ["IT_ADMIN"] }),
ProductAccess::Full,
),
(
serde_json::json!({ "org_roles": ["USER"] }),
ProductAccess::Full,
),
(
serde_json::json!({ "org_roles": ["CXO"] }),
ProductAccess::ReadOnly,
),
(
serde_json::json!({ "org_roles": ["LEGAL"] }),
ProductAccess::ReadOnly,
),
(
serde_json::json!({ "org_roles": ["FINANCE"] }),
ProductAccess::None,
),
(serde_json::json!({ "org_roles": [] }), ProductAccess::None),
(serde_json::json!({ "sub": "u1" }), ProductAccess::None),
];
for (claims, want) in cases {
assert_eq!(
user(claims.clone(), false).product_access(),
want,
"{claims}"
);
}
// Support is judged by the agent's support rules instead.
assert_eq!(
user(serde_json::json!({ "sub": "s1" }), true).product_access(),
ProductAccess::Full
);
assert_eq!(
UserStateInner::default().product_access(),
ProductAccess::None
);
}
#[test]
fn the_link_goes_to_the_workspace_when_the_slug_is_plain() {
let portal = Some("https://app-stage.breakpilot.com/");
+8 -5
View File
@@ -18,6 +18,7 @@ struct UiChatMessage {
#[component]
pub fn ChatPage(repo_id: String) -> Element {
let can_write = crate::components::no_access::use_can_write();
let mut messages: Signal<Vec<UiChatMessage>> = use_signal(Vec::new);
let mut input_text = use_signal(String::new);
let mut loading = use_signal(|| false);
@@ -208,11 +209,13 @@ pub fn ChatPage(repo_id: String) -> Element {
}
}
}
button {
class: "btn btn-sm",
disabled: *building.read() || is_running,
onclick: on_build,
if *building.read() || is_running { "Building..." } else { "Build Embeddings" }
if can_write {
button {
class: "btn btn-sm",
disabled: *building.read() || is_running,
onclick: on_build,
if *building.read() || is_running { "Building..." } else { "Build Embeddings" }
}
}
}
+25 -20
View File
@@ -8,6 +8,7 @@ use crate::infrastructure::dast::{add_dast_target, fetch_dast_targets, trigger_d
#[component]
pub fn DastTargetsPage() -> Element {
let can_write = crate::components::no_access::use_can_write();
let mut targets = use_resource(|| async { fetch_dast_targets().await.ok() });
let mut toasts = use_context::<Toasts>();
@@ -31,14 +32,16 @@ pub fn DastTargetsPage() -> Element {
}
div { class: "mb-4",
button {
class: "btn btn-primary",
onclick: move |_| show_form.set(!show_form()),
if show_form() { "Cancel" } else { "Add Target" }
if can_write {
button {
class: "btn btn-primary",
onclick: move |_| show_form.set(!show_form()),
if show_form() { "Cancel" } else { "Add Target" }
}
}
}
if show_form() {
if can_write && show_form() {
div { class: "card mb-4",
h3 { "Add New Target" }
div { class: "form-group",
@@ -122,21 +125,23 @@ pub fn DastTargetsPage() -> Element {
}
}
td {
button {
class: "btn btn-sm",
onclick: {
let tid = target_id.clone();
move |_| {
let tid = tid.clone();
spawn(async move {
match trigger_dast_scan(tid).await {
Ok(_) => toasts.push(ToastType::Success, "DAST scan triggered"),
Err(e) => toasts.push(ToastType::Error, e.to_string()),
}
});
}
},
"Scan"
if can_write {
button {
class: "btn btn-sm",
onclick: {
let tid = target_id.clone();
move |_| {
let tid = tid.clone();
spawn(async move {
match trigger_dast_scan(tid).await {
Ok(_) => toasts.push(ToastType::Success, "DAST scan triggered"),
Err(e) => toasts.push(ToastType::Error, e.to_string()),
}
});
}
},
"Scan"
}
}
}
}
+153 -77
View File
@@ -23,7 +23,9 @@ enum SaveState {
#[component]
pub fn FindingDetailPage(id: String) -> Element {
let can_write = crate::components::no_access::use_can_write();
let lang = use_lang()();
let me = use_context::<Signal<compliance_core::models::AuthInfo>>()();
let finding_id = id.clone();
let mut status_save = use_signal(|| SaveState::Idle);
let mut feedback_save = use_signal(|| SaveState::Idle);
@@ -236,93 +238,95 @@ pub fn FindingDetailPage(id: String) -> Element {
}
}
div { class: "card",
div { class: "card-header", {tx::UPDATE_STATUS.get(lang)} }
div { class: "flex gap-2",
for status in tx::STATUSES {
{
let current = status == f.status;
let wire = wire_name(&status);
let id_clone = finding_id_for_status.clone();
let label = tx::status(&status).get(lang);
rsx! {
button {
class: if current { "btn btn-primary btn-current" } else { "btn btn-ghost" },
title: "{label}",
disabled: current,
onclick: move |_| {
if status.needs_reason() {
reasoning_for.set(Some(status.clone()));
return;
}
let s = wire.clone();
let id = id_clone.clone();
spawn(async move {
// Re-read only after the save: restarting
// at once raced it and showed the old status.
match crate::infrastructure::findings::update_finding_status(id, s, None).await {
Ok(()) => status_save.set(SaveState::Saved),
Err(e) => status_save.set(SaveState::Failed(e.to_string())),
if can_write {
div { class: "card",
div { class: "card-header", {tx::UPDATE_STATUS.get(lang)} }
div { class: "flex gap-2",
for status in tx::STATUSES {
{
let current = status == f.status;
let wire = wire_name(&status);
let id_clone = finding_id_for_status.clone();
let label = tx::status(&status).get(lang);
rsx! {
button {
class: if current { "btn btn-primary btn-current" } else { "btn btn-ghost" },
title: "{label}",
disabled: current,
onclick: move |_| {
if status.needs_reason() {
reasoning_for.set(Some(status.clone()));
return;
}
finding.restart();
});
},
{status_icon(&status)}
" {label}"
let s = wire.clone();
let id = id_clone.clone();
spawn(async move {
// Re-read only after the save: restarting
// at once raced it and showed the old status.
match crate::infrastructure::findings::update_finding_status(id, s, None).await {
Ok(()) => status_save.set(SaveState::Saved),
Err(e) => status_save.set(SaveState::Failed(e.to_string())),
}
finding.restart();
});
},
{status_icon(&status)}
" {label}"
}
}
}
}
}
}
if let Some(pending) = reasoning_for() {
div { style: "margin-top: 10px;",
p { style: "font-size: 13px; color: var(--text-secondary); margin-bottom: 6px;",
if pending == FindingStatus::WrongMapping {
{tx::WRONG_MAPPING_HINT.get(lang)}
} else {
{tx::ACCEPT_RISK_HINT.get(lang)}
if let Some(pending) = reasoning_for() {
div { style: "margin-top: 10px;",
p { style: "font-size: 13px; color: var(--text-secondary); margin-bottom: 6px;",
if pending == FindingStatus::WrongMapping {
{tx::WRONG_MAPPING_HINT.get(lang)}
} else {
{tx::ACCEPT_RISK_HINT.get(lang)}
}
}
}
textarea {
style: "width: 100%; min-height: 60px;",
value: "{risk_reason}",
oninput: move |e| risk_reason.set(e.value()),
}
button {
class: "btn btn-primary",
style: "margin-top: 6px;",
disabled: risk_reason().trim().is_empty(),
onclick: move |_| {
let id = finding_id_for_risk.clone();
let reason = risk_reason();
let status = wire_name(&pending);
spawn(async move {
match crate::infrastructure::findings::update_finding_status(
id,
status,
Some(reason),
)
.await
{
Ok(()) => {
status_save.set(SaveState::Saved);
reasoning_for.set(None);
risk_reason.set(String::new());
textarea {
style: "width: 100%; min-height: 60px;",
value: "{risk_reason}",
oninput: move |e| risk_reason.set(e.value()),
}
button {
class: "btn btn-primary",
style: "margin-top: 6px;",
disabled: risk_reason().trim().is_empty(),
onclick: move |_| {
let id = finding_id_for_risk.clone();
let reason = risk_reason();
let status = wire_name(&pending);
spawn(async move {
match crate::infrastructure::findings::update_finding_status(
id,
status,
Some(reason),
)
.await
{
Ok(()) => {
status_save.set(SaveState::Saved);
reasoning_for.set(None);
risk_reason.set(String::new());
}
Err(e) => status_save.set(SaveState::Failed(e.to_string())),
}
Err(e) => status_save.set(SaveState::Failed(e.to_string())),
}
finding.restart();
});
},
if pending == FindingStatus::WrongMapping {
{tx::CONFIRM_WRONG_MAPPING.get(lang)}
} else {
{tx::ACCEPT_RISK.get(lang)}
finding.restart();
});
},
if pending == FindingStatus::WrongMapping {
{tx::CONFIRM_WRONG_MAPPING.get(lang)}
} else {
{tx::ACCEPT_RISK.get(lang)}
}
}
}
}
SaveNote { state: status_save() }
}
SaveNote { state: status_save() }
}
if !f.status_history.is_empty() {
@@ -332,7 +336,11 @@ pub fn FindingDetailPage(id: String) -> Element {
for change in f.status_history.iter().rev() {
li { style: "margin-bottom: 4px;",
strong { {tx::status(&change.status).get(lang)} }
" · {change.by} · {format_time(&change.at, lang)}"
" · "
span { class: if change.support { "history-by history-by-support" } else { "history-by" },
{changed_by(change, &me, lang)}
}
" · {format_time(&change.at, lang)}"
if let Some(reason) = &change.reason {
div { style: "color: var(--text-secondary);", "{tx::REASON.get(lang)}: {reason}" }
}
@@ -351,6 +359,7 @@ pub fn FindingDetailPage(id: String) -> Element {
textarea {
style: "width: 100%; min-height: 80px; background: var(--bg-primary); border: 1px solid var(--border); border-radius: 8px; padding: 10px 14px; color: var(--text-primary); font-size: 14px; resize: vertical;",
value: "{existing_feedback}",
disabled: !can_write,
// `change` fires when the field loses focus: one save per
// edit, not one per keystroke racing each other.
onchange: move |e| {
@@ -433,3 +442,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");
}
}
+3 -1
View File
@@ -17,6 +17,7 @@ use crate::infrastructure::findings::{has_control_refs, location, wire_name};
#[component]
pub fn FindingsPage(target: String) -> Element {
let can_write = crate::components::no_access::use_can_write();
let lang = use_lang()();
let mut toasts = use_context::<Toasts>();
let mut page = use_signal(|| 1u64);
@@ -164,7 +165,8 @@ pub fn FindingsPage(target: String) -> Element {
}
// Bulk action bar
if !selected_ids().is_empty() {
// Triage is a change: read-only roles get no bulk actions.
if can_write && !selected_ids().is_empty() {
div {
class: "card",
style: "display: flex; align-items: center; gap: 12px; padding: 12px 16px; margin-bottom: 16px; background: rgba(56, 189, 248, 0.08); border-color: rgba(56, 189, 248, 0.2);",
@@ -40,6 +40,7 @@ pub fn GraphExplorerInline(repo_id: String) -> Element {
/// Shared graph explorer body used by both the full page and inline variants.
#[component]
fn GraphExplorerBody(repo_id: String) -> Element {
let can_write = crate::components::no_access::use_can_write();
let repo_id_clone = repo_id.clone();
let mut graph_data = use_resource(move || {
let rid = repo_id_clone.clone();
@@ -170,28 +171,30 @@ fn GraphExplorerBody(repo_id: String) -> Element {
} else {
// Toolbar
div { class: "graph-toolbar",
button {
class: "btn btn-primary",
disabled: building(),
onclick: {
let rid = repo_id.clone();
move |_| {
let rid = rid.clone();
building.set(true);
graph_ready.set(false);
nodes_json.set(String::new());
edges_json.set(String::new());
spawn(async move {
match trigger_graph_build(rid).await {
Ok(_) => toasts.push(ToastType::Success, "Graph build triggered"),
Err(e) => toasts.push(ToastType::Error, e.to_string()),
}
building.set(false);
graph_data.restart();
});
}
},
if building() { "Building..." } else { "Build Graph" }
if can_write {
button {
class: "btn btn-primary",
disabled: building(),
onclick: {
let rid = repo_id.clone();
move |_| {
let rid = rid.clone();
building.set(true);
graph_ready.set(false);
nodes_json.set(String::new());
edges_json.set(String::new());
spawn(async move {
match trigger_graph_build(rid).await {
Ok(_) => toasts.push(ToastType::Success, "Graph build triggered"),
Err(e) => toasts.push(ToastType::Error, e.to_string()),
}
building.set(false);
graph_data.restart();
});
}
},
if building() { "Building..." } else { "Build Graph" }
}
}
div { class: "graph-search-bar",
+68 -61
View File
@@ -10,6 +10,7 @@ use crate::infrastructure::mcp::{
#[component]
pub fn McpServersPage() -> Element {
let can_write = crate::components::no_access::use_can_write();
let mut servers = use_resource(|| async { fetch_mcp_servers().await.ok() });
let mut toasts = use_context::<Toasts>();
@@ -54,10 +55,12 @@ pub fn McpServersPage() -> Element {
}
div { class: "mb-4", style: "display: flex; gap: 8px; flex-wrap: wrap;",
button {
class: "btn btn-primary",
onclick: move |_| show_form.set(!show_form()),
if show_form() { "Cancel" } else { "Register Server" }
if can_write {
button {
class: "btn btn-primary",
onclick: move |_| show_form.set(!show_form()),
if show_form() { "Cancel" } else { "Register Server" }
}
}
Link {
to: crate::app::Route::McpTokensPage {},
@@ -68,7 +71,7 @@ pub fn McpServersPage() -> Element {
}
}
if show_form() {
if can_write && show_form() {
div { class: "card mb-4",
div { class: "card-header", "Register MCP Server" }
div { class: "mcp-form-grid",
@@ -243,17 +246,19 @@ pub fn McpServersPage() -> Element {
h3 { "{server.name}" }
span { class: "mcp-card-status {status_class}", "{status_label}" }
}
button {
class: "btn btn-sm btn-ghost btn-ghost-danger",
title: "Delete server",
onclick: {
let id = sid.clone();
let name = name.clone();
move |_| {
confirm_delete.set(Some((id.clone(), name.clone())));
}
},
Icon { icon: BsTrash, width: 14, height: 14 }
if can_write {
button {
class: "btn btn-sm btn-ghost btn-ghost-danger",
title: "Delete server",
onclick: {
let id = sid.clone();
let name = name.clone();
move |_| {
confirm_delete.set(Some((id.clone(), name.clone())));
}
},
Icon { icon: BsTrash, width: 14, height: 14 }
}
}
}
@@ -299,56 +304,58 @@ pub fn McpServersPage() -> Element {
}
// Token section
div { class: "mcp-card-token",
div { class: "mcp-token-display",
Icon { icon: BsKey, width: 13, height: 13 }
code { class: "mcp-token-code",
if is_token_visible {
"{server.access_token}"
} else {
"mcp_••••••••••••••••••••"
}
}
}
div { class: "mcp-token-actions",
button {
class: "btn btn-sm btn-ghost",
title: if is_token_visible { "Hide token" } else { "Reveal token" },
onclick: {
let id = sid.clone();
move |_| {
if visible_token().as_deref() == Some(id.as_str()) {
visible_token.set(None);
} else {
visible_token.set(Some(id.clone()));
}
if can_write {
div { class: "mcp-card-token",
div { class: "mcp-token-display",
Icon { icon: BsKey, width: 13, height: 13 }
code { class: "mcp-token-code",
if is_token_visible {
"{server.access_token}"
} else {
"mcp_••••••••••••••••••••"
}
},
if is_token_visible {
Icon { icon: BsEyeSlash, width: 14, height: 14 }
} else {
Icon { icon: BsEye, width: 14, height: 14 }
}
}
button {
class: "btn btn-sm btn-ghost",
title: "Regenerate token",
onclick: {
let id = sid.clone();
move |_| {
let id = id.clone();
spawn(async move {
match regenerate_mcp_token(id).await {
Ok(_) => {
toasts.push(ToastType::Success, "Token regenerated");
servers.restart();
}
Err(e) => toasts.push(ToastType::Error, e.to_string()),
div { class: "mcp-token-actions",
button {
class: "btn btn-sm btn-ghost",
title: if is_token_visible { "Hide token" } else { "Reveal token" },
onclick: {
let id = sid.clone();
move |_| {
if visible_token().as_deref() == Some(id.as_str()) {
visible_token.set(None);
} else {
visible_token.set(Some(id.clone()));
}
});
}
},
if is_token_visible {
Icon { icon: BsEyeSlash, width: 14, height: 14 }
} else {
Icon { icon: BsEye, width: 14, height: 14 }
}
},
Icon { icon: BsArrowRepeat, width: 14, height: 14 }
}
button {
class: "btn btn-sm btn-ghost",
title: "Regenerate token",
onclick: {
let id = sid.clone();
move |_| {
let id = id.clone();
spawn(async move {
match regenerate_mcp_token(id).await {
Ok(_) => {
toasts.push(ToastType::Success, "Token regenerated");
servers.restart();
}
Err(e) => toasts.push(ToastType::Error, e.to_string()),
}
});
}
},
Icon { icon: BsArrowRepeat, width: 14, height: 14 }
}
}
}
}
+15 -12
View File
@@ -10,6 +10,7 @@ use crate::infrastructure::mcp_tokens::{
#[component]
pub fn McpTokensPage() -> Element {
let can_write = crate::components::no_access::use_can_write();
let mut tokens = use_resource(|| async { fetch_mcp_tokens().await.ok() });
let mut toasts = use_context::<Toasts>();
@@ -58,21 +59,23 @@ pub fn McpTokensPage() -> Element {
}
// ── Create form ────────────────────────────────────────────
div { class: "mb-4",
button {
class: "btn btn-primary",
onclick: move |_| {
show_form.set(!show_form());
new_name.set(String::new());
},
if show_form() { "Cancel" } else {
Icon { icon: BsPlusLg, width: 14, height: 14 }
" Create Token"
if can_write {
div { class: "mb-4",
button {
class: "btn btn-primary",
onclick: move |_| {
show_form.set(!show_form());
new_name.set(String::new());
},
if show_form() { "Cancel" } else {
Icon { icon: BsPlusLg, width: 14, height: 14 }
" Create Token"
}
}
}
}
if show_form() {
if can_write && show_form() {
div { class: "card mb-4",
div { class: "card-header", "New MCP Token" }
div { style: "padding: 1rem;",
@@ -153,7 +156,7 @@ pub fn McpTokensPage() -> Element {
span { class: "mcp-card-status stopped", "revoked" }
}
}
if !revoked {
if can_write && !revoked {
button {
class: "btn btn-sm btn-ghost btn-ghost-danger",
title: "Revoke token",
@@ -9,6 +9,7 @@ use dioxus::prelude::*;
use crate::app::Route;
use crate::components::demo_targets::DemoTargetsButton;
use crate::components::no_access::use_can_write;
use crate::components::page_header::PageHeader;
use crate::components::scan_coverage::ScanCoverage;
use crate::components::scan_runs::ScanRunList;
@@ -79,6 +80,7 @@ enum FirstScan {
#[component]
pub fn OnboardingPage() -> Element {
let lang = use_lang()();
let can_write = use_can_write();
let mut step = use_signal(|| 0usize);
let mut name = use_signal(String::new);
let mut target_type = use_signal(String::new);
@@ -127,6 +129,17 @@ pub fn OnboardingPage() -> Element {
let type_label = move |value: &str| kinds::target_type(value, lang);
let kind_label = move |value: &str| kinds::artifact_kind(value, lang);
// Adding a target is a change: a read-only role only reads why not.
if !can_write {
return rsx! {
PageHeader {
title: tx::TITLE.get(lang),
description: tx::SUBTITLE.get(lang),
}
div { class: "card", p { {crate::i18n::texts::access::READ_ONLY.get(lang)} } }
};
}
rsx! {
PageHeader {
title: tx::TITLE.get(lang),
+5 -2
View File
@@ -76,6 +76,7 @@ fn target_lines(
#[component]
pub fn OverviewPage() -> Element {
let lang = use_lang()();
let can_write = crate::components::no_access::use_can_write();
// AI chat and MCP need the runtime a source-only deployment does not have,
// so they are not advertised there.
let source_only = use_source_only();
@@ -105,8 +106,10 @@ pub fn OverviewPage() -> Element {
div { class: "card ov-empty",
h3 { {overview::EMPTY_TITLE.get(lang)} }
p { {overview::EMPTY_BODY.get(lang)} }
Link { to: Route::OnboardingPage {}, class: "btn btn-primary",
{overview::EMPTY_ACTION.get(lang)}
if can_write {
Link { to: Route::OnboardingPage {}, class: "btn btn-primary",
{overview::EMPTY_ACTION.get(lang)}
}
}
}
},
@@ -12,6 +12,7 @@ use crate::infrastructure::pentest::{
#[component]
pub fn PentestDashboardPage() -> Element {
let can_write = crate::components::no_access::use_can_write();
let mut sessions = use_resource(|| async { fetch_pentest_sessions().await.ok() });
let stats = use_resource(|| async { fetch_pentest_stats().await.ok() });
@@ -150,11 +151,13 @@ pub fn PentestDashboardPage() -> Element {
// Actions row
div { style: "display: flex; gap: 12px; margin-bottom: 24px;",
button {
class: "btn btn-primary",
onclick: move |_| show_wizard.set(true),
Icon { icon: BsPlusCircle, width: 14, height: 14 }
" New Pentest"
if can_write {
button {
class: "btn btn-primary",
onclick: move |_| show_wizard.set(true),
Icon { icon: BsPlusCircle, width: 14, height: 14 }
" New Pentest"
}
}
}
@@ -234,7 +237,7 @@ pub fn PentestDashboardPage() -> Element {
}
}
}
if is_session_running || is_session_paused {
if can_write && (is_session_running || is_session_paused) {
div { style: "margin-top: 8px; display: flex; justify-content: flex-end; gap: 6px;",
if is_session_running {
button {
@@ -302,7 +305,7 @@ pub fn PentestDashboardPage() -> Element {
}
// Pentest Wizard
if *show_wizard.read() {
if can_write && *show_wizard.read() {
PentestWizard { show: show_wizard }
}
}
@@ -12,6 +12,7 @@ use crate::infrastructure::pentest::{
#[component]
pub fn PentestSessionPage(session_id: String) -> Element {
let can_write = crate::components::no_access::use_can_write();
let sid_for_session = session_id.clone();
let sid_for_findings = session_id.clone();
let sid_for_chain = session_id.clone();
@@ -238,7 +239,7 @@ pub fn PentestSessionPage(session_id: String) -> Element {
}
}
div { style: "display: flex; gap: 8px;",
if is_running {
if can_write && is_running {
{
let sid_pause = session_id.clone();
rsx! {
@@ -258,7 +259,7 @@ pub fn PentestSessionPage(session_id: String) -> Element {
}
}
}
if is_paused {
if can_write && is_paused {
{
let sid_resume = session_id.clone();
rsx! {
+68 -34
View File
@@ -11,6 +11,8 @@ use crate::components::artifact_upload::ArtifactUpload;
use crate::components::cra_bar::CraBar;
use crate::components::evidence_button::EvidencePackButton;
use crate::components::manual_findings::ManualFindingsPanel;
use crate::components::no_access::use_can_write;
use crate::components::projects::{ProjectChips, ProjectPicker};
use crate::components::scan_coverage::ScanCoverage;
use crate::components::scan_runs::ScanRunList;
use crate::components::severity_badge::SeverityBadge;
@@ -25,6 +27,7 @@ use crate::infrastructure::onboarding::{
ArchivePassword, ArtifactInputDto, PasswordOutcome,
};
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.
const OPEN_SHOWN: usize = 5;
@@ -72,6 +75,7 @@ fn editable_artifacts(target: &serde_json::Value) -> Vec<ArtifactInputDto> {
#[component]
pub fn TargetPage(id: String) -> Element {
let lang = use_lang()();
let can_write = use_can_write();
let mut toasts = use_context::<Toasts>();
let navigator = use_navigator();
let target_id = use_signal(|| id.clone());
@@ -94,6 +98,7 @@ pub fn TargetPage(id: String) -> Element {
let mut adding_manual = use_signal(|| false);
let mut starting = use_signal(|| false);
let mut scans_started = use_signal(|| 0u32);
let projects = use_resource(fetch_projects);
let snapshot = target.read().clone();
let Some(Some(resp)) = snapshot else {
@@ -134,6 +139,9 @@ pub fn TargetPage(id: String) -> Element {
header { class: "target-head",
div { class: "target-head-text",
h2 { "{name}" }
if let Some(Ok(projects)) = projects.read().clone() {
ProjectChips { ids: project_ids_of(&t), projects }
}
p { class: "target-head-meta",
span { "{type_label}" }
for a in artifacts.iter() {
@@ -145,38 +153,44 @@ pub fn TargetPage(id: String) -> Element {
}
}
div { class: "target-head-actions",
button {
class: "btn btn-primary",
disabled: starting(),
onclick: move |_| {
starting.set(true);
spawn(async move {
match trigger_target_scan(target_id()).await {
Ok(_) => {
toasts.push(ToastType::Success, tx::SCAN_STARTED.get(lang));
scans_started += 1;
if can_write {
button {
class: "btn btn-primary",
disabled: starting(),
onclick: move |_| {
starting.set(true);
spawn(async move {
match trigger_target_scan(target_id()).await {
Ok(_) => {
toasts.push(ToastType::Success, tx::SCAN_STARTED.get(lang));
scans_started += 1;
}
Err(e) => toasts.push(ToastType::Error, e.to_string()),
}
Err(e) => toasts.push(ToastType::Error, e.to_string()),
}
starting.set(false);
status.restart();
});
},
Icon { icon: BsPlayFill, width: 16, height: 16 }
{tx::RUN_SCAN.get(lang)}
starting.set(false);
status.restart();
});
},
Icon { icon: BsPlayFill, width: 16, height: 16 }
{tx::RUN_SCAN.get(lang)}
}
}
EvidencePackButton { target_id: id.clone() }
button {
class: "btn btn-ghost",
onclick: move |_| editing.set(true),
Icon { icon: BsPencil, width: 14, height: 14 }
{tx::EDIT.get(lang)}
if can_write {
button {
class: "btn btn-ghost",
onclick: move |_| editing.set(true),
Icon { icon: BsPencil, width: 14, height: 14 }
{tx::EDIT.get(lang)}
}
}
button {
class: "btn btn-ghost btn-ghost-danger",
onclick: move |_| confirm_delete.set(true),
Icon { icon: BsTrash, width: 14, height: 14 }
{tx::DELETE.get(lang)}
if can_write {
button {
class: "btn btn-ghost btn-ghost-danger",
onclick: move |_| confirm_delete.set(true),
Icon { icon: BsTrash, width: 14, height: 14 }
{tx::DELETE.get(lang)}
}
}
}
}
@@ -281,10 +295,12 @@ pub fn TargetPage(id: String) -> Element {
section { class: "card target-manual",
div { class: "target-card-head",
h3 { {crate::i18n::texts::manual::TITLE.get(lang)} }
button {
class: "btn btn-secondary btn-sm",
onclick: move |_| adding_manual.set(!adding_manual()),
if adding_manual() { {tx::MANUAL_CLOSE.get(lang)} } else { {tx::MANUAL_ADD.get(lang)} }
if can_write {
button {
class: "btn btn-secondary btn-sm",
onclick: move |_| adding_manual.set(!adding_manual()),
if adding_manual() { {tx::MANUAL_CLOSE.get(lang)} } else { {tx::MANUAL_ADD.get(lang)} }
}
}
}
div { class: "target-card-body",
@@ -411,6 +427,10 @@ fn TargetEditor(
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_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.
let mut e_kind = use_signal(|| "git_repo".to_string());
let mut e_source = use_signal(String::new);
@@ -576,6 +596,13 @@ fn TargetEditor(
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",
button {
class: "btn btn-secondary",
@@ -590,10 +617,17 @@ fn TargetEditor(
let nm = edit_name();
let tt = edit_type();
let arts = edit_arts();
let chosen = edit_projects();
let projects_changed = chosen != stored_projects;
edit_saving.set(true);
spawn(async move {
match update_target(id, Some(nm), Some(tt), Some(arts)).await {
Ok(_) => {
let saved = match update_target(id.clone(), Some(nm), Some(tt), Some(arts)).await {
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));
on_saved.call(());
}
+75 -33
View File
@@ -9,14 +9,17 @@ use dioxus_free_icons::Icon;
use crate::app::Route;
use crate::components::cra_bar::CraBar;
use crate::components::demo_targets::DemoTargetsButton;
use crate::components::no_access::use_can_write;
use crate::components::page_header::PageHeader;
use crate::components::projects::ProjectChips;
use crate::components::scan_runs::status_badge;
use crate::components::toast::{ToastType, Toasts};
use crate::i18n::texts::{common, kinds, scans as scan_texts, targets as tx};
use crate::i18n::{format_ago, use_lang, Lang};
use crate::infrastructure::auth_check::{go_to_login, is_session_expired};
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};
/// How often the list refreshes while a scan is running, in milliseconds.
@@ -63,13 +66,18 @@ fn target_id(t: &serde_json::Value) -> String {
#[component]
pub fn TargetsPage() -> Element {
let can_write = use_can_write();
let mut toasts = use_context::<Toasts>();
let navigator = use_navigator();
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
// login instead.
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) {
go_to_login();
}
@@ -102,8 +110,30 @@ pub fn TargetsPage() -> Element {
}
div { class: "page-actions",
Link { to: Route::OnboardingPage {}, class: "btn btn-primary",
{tx::ADD.get(lang)}
if can_write {
Link { to: Route::OnboardingPage {}, class: "btn btn-primary",
{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,16 +148,23 @@ pub fn TargetsPage() -> Element {
.and_then(|r| r.counts)
};
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! {
div { class: "card targets-empty",
p { {tx::EMPTY.get(lang)} }
div { class: "targets-empty-actions",
Link { to: Route::OnboardingPage {}, class: "btn btn-primary",
{tx::EMPTY_ACTION.get(lang)}
}
DemoTargetsButton {
secondary: true,
on_seeded: move |_| targets.restart(),
if can_write {
Link { to: Route::OnboardingPage {}, class: "btn btn-primary",
{tx::EMPTY_ACTION.get(lang)}
}
DemoTargetsButton {
secondary: true,
on_seeded: move |_| targets.restart(),
}
}
}
p { class: "targets-empty-hint", {tx::DEMO_HINT.get(lang)} }
@@ -169,6 +206,9 @@ pub fn TargetsPage() -> Element {
"{name}"
}
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",
match last_scan {
@@ -193,31 +233,33 @@ pub fn TargetsPage() -> Element {
}
}
td { class: "targets-actions",
button {
class: if is_scanning { "btn btn-ghost btn-sm btn-scanning" } else { "btn btn-ghost btn-sm" },
title: tx::RUN_SCAN.get(lang),
disabled: is_scanning,
onclick: move |e: MouseEvent| {
e.stop_propagation();
let id = id_scan.clone();
scanning_ids.write().push(id.clone());
spawn(async move {
match trigger_target_scan(id.clone()).await {
Ok(_) => {
toasts.push(ToastType::Success, tx::SCAN_STARTED.get(lang));
targets.restart();
if can_write {
button {
class: if is_scanning { "btn btn-ghost btn-sm btn-scanning" } else { "btn btn-ghost btn-sm" },
title: tx::RUN_SCAN.get(lang),
disabled: is_scanning,
onclick: move |e: MouseEvent| {
e.stop_propagation();
let id = id_scan.clone();
scanning_ids.write().push(id.clone());
spawn(async move {
match trigger_target_scan(id.clone()).await {
Ok(_) => {
toasts.push(ToastType::Success, tx::SCAN_STARTED.get(lang));
targets.restart();
}
Err(e) => toasts.push(ToastType::Error, e.to_string()),
}
Err(e) => toasts.push(ToastType::Error, e.to_string()),
}
scanning_ids.write().retain(|i| i != &id);
});
},
if is_scanning {
span { class: "spinner" }
} else {
Icon { icon: BsPlayFill, width: 14, height: 14 }
scanning_ids.write().retain(|i| i != &id);
});
},
if is_scanning {
span { class: "spinner" }
} else {
Icon { icon: BsPlayFill, width: 14, height: 14 }
}
{tx::RUN_SCAN.get(lang)}
}
{tx::RUN_SCAN.get(lang)}
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-dast"
version = "0.1.0"
version = "0.4.4"
edition = "2021"
[lints]
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-graph"
version = "0.1.0"
version = "0.4.4"
edition = "2021"
[lints]
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-mcp"
version = "0.1.0"
version = "0.4.4"
edition = "2021"
[dependencies]
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-smoke"
version = "0.1.0"
version = "0.4.4"
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."
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "control-map"
version = "0.1.0"
version = "0.4.4"
edition = "2021"
[lints]
+1 -9
View File
@@ -13,15 +13,7 @@ export default withMermaid(defineConfig({
description: 'CRA-Nachweise aus Ihrem Quellcode',
head: [
['link', { rel: 'icon', type: 'image/svg+xml', href: `${BASE}logo.svg` }],
['link', { rel: 'preconnect', href: 'https://fonts.googleapis.com' }],
['link', { rel: 'preconnect', href: 'https://fonts.gstatic.com', crossorigin: '' }],
[
'link',
{
rel: 'stylesheet',
href: 'https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700&family=Geist+Mono:wght@400;500&display=swap',
},
],
// Geist and Geist Mono are self-hosted (theme/custom.css), no font CDN.
],
ignoreDeadLinks: [
/localhost/,
+20 -1
View File
@@ -4,9 +4,28 @@
* Tokens first (light, then dark), then the default theme's variables mapped
* onto them, then typography for content pages, custom blocks, code, sidebar
* and the navbar wordmark. The home page styles live in HomePage.vue.
* Fonts (Geist, Geist Mono) are loaded from Google Fonts in config.mts.
* Fonts (Geist, Geist Mono; SIL OFL 1.1, fonts/OFL-Geist.txt) are bundled
* with the site below: no request goes to a third-party font CDN.
*/
/* ---------- Fonts ---------- */
@font-face {
font-family: 'Geist';
src: url('./fonts/Geist-Variable.woff2') format('woff2');
font-weight: 100 900;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: 'Geist Mono';
src: url('./fonts/GeistMono-Variable.woff2') format('woff2');
font-weight: 100 900;
font-style: normal;
font-display: swap;
}
/* ---------- Tokens ---------- */
:root {
Binary file not shown.
Binary file not shown.
+92
View File
@@ -0,0 +1,92 @@
Copyright (c) 2023 Vercel, in collaboration with basement.studio
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION AND CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+12
View File
@@ -28,6 +28,18 @@ vulnerabilities; **CRA-Stand je Prüfobjekt** (CRA status by target); and
**Als Nächstes** (Next up), the most severe open findings. See
[Dashboard Overview](/features/overview).
## Roles
What you can do in Prüfwerk depends on your role in the workspace:
| Role | Prüfwerk |
| --- | --- |
| `IT_ADMIN`, `USER` | everything: add targets, run scans, triage findings |
| `CXO`, `LEGAL` | read only: view and export findings, reports, SBOM, evidence |
| `FINANCE`, or none of these | no access |
Only `IT_ADMIN` can add or import findings by hand.
## Quick Walkthrough
### 0. Or start with the demo targets
+10
View File
@@ -34,6 +34,16 @@ Arbeitsbereich und wählen Sie **Prüfwerk**. Prüfwerk startet mit der
Die Oberfläche ist auf Deutsch; über den Sprachschalter wechseln Sie auf
Englisch.
Was Sie in Prüfwerk tun können, hängt von Ihrer Rolle im Arbeitsbereich ab:
| Rolle | Prüfwerk |
| --- | --- |
| IT-Administration (`IT_ADMIN`), Benutzer (`USER`) | alles: Prüfobjekte anlegen, prüfen, Befunde bewerten |
| Geschäftsführung (`CXO`), Recht (`LEGAL`) | nur lesen: Befunde, Berichte, Stückliste, Nachweise ansehen und exportieren |
| Finanzen (`FINANCE`) oder keine dieser Rollen | kein Zugriff |
Befunde von Hand anlegen oder importieren kann nur die IT-Administration.
## 2. Ein Prüfobjekt anlegen
Klicken Sie in der Seitenleiste auf **Neues Prüfobjekt**. Es öffnet sich
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "werkbank-exec"
version = "0.1.0"
version = "0.4.4"
edition = "2021"
description = "Shared dynamic-execution logic: soft-PLC provisioning + industrial-protocol probing, used by the compliance agent and the Werkbank runner."