Compare commits

..
1 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
44 changed files with 1139 additions and 308 deletions

No files matched your search

Generated
+9 -9
View File
@@ -663,7 +663,7 @@ dependencies = [
[[package]]
name = "compliance-agent"
version = "0.4.3"
version = "0.4.4"
dependencies = [
"axum",
"base64",
@@ -714,7 +714,7 @@ dependencies = [
[[package]]
name = "compliance-core"
version = "0.4.3"
version = "0.4.4"
dependencies = [
"aes-gcm",
"axum",
@@ -744,7 +744,7 @@ dependencies = [
[[package]]
name = "compliance-dashboard"
version = "0.4.3"
version = "0.4.4"
dependencies = [
"async-trait",
"axum",
@@ -784,7 +784,7 @@ dependencies = [
[[package]]
name = "compliance-dast"
version = "0.4.3"
version = "0.4.4"
dependencies = [
"base64",
"bollard",
@@ -810,7 +810,7 @@ dependencies = [
[[package]]
name = "compliance-graph"
version = "0.4.3"
version = "0.4.4"
dependencies = [
"bson",
"chrono",
@@ -834,7 +834,7 @@ dependencies = [
[[package]]
name = "compliance-mcp"
version = "0.4.3"
version = "0.4.4"
dependencies = [
"axum",
"bson",
@@ -858,7 +858,7 @@ dependencies = [
[[package]]
name = "compliance-smoke"
version = "0.4.3"
version = "0.4.4"
dependencies = [
"axum",
"compliance-core",
@@ -985,7 +985,7 @@ dependencies = [
[[package]]
name = "control-map"
version = "0.4.3"
version = "0.4.4"
dependencies = [
"serde",
"serde_json",
@@ -6793,7 +6793,7 @@ dependencies = [
[[package]]
name = "werkbank-exec"
version = "0.4.3"
version = "0.4.4"
dependencies = [
"compliance-core",
"compliance-dast",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-agent"
version = "0.4.3"
version = "0.4.4"
edition = "2021"
[lints]
+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" })
);
}
+7 -4
View File
@@ -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,
@@ -414,8 +414,8 @@ pub async fn start_api_server(
registry = agent.registry.is_some(),
"Keycloak JWT auth enabled"
);
// Layers execute outermost-first: Extension(jwks) → JWT → entitlement
// (registry) → support audit → 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(
@@ -426,6 +426,7 @@ pub async fn start_api_server(
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() {
@@ -445,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}");
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-core"
version = "0.4.3"
version = "0.4.4"
edition = "2021"
[lints]
+2 -1
View File
@@ -28,5 +28,6 @@ pub use error::CoreError;
pub use exec_policy::ExecPolicy;
pub use net_guard::{NetGuard, NetGuardError};
pub use tenant::{
OrgRole, StaffAccess, TenantContext, TenantStatus, SUPPORT_ROLES, SUPPORT_TENANT_HEADER,
OrgRole, ProductAccess, StaffAccess, TenantContext, TenantStatus, SUPPORT_ROLES,
SUPPORT_TENANT_HEADER,
};
+5
View File
@@ -25,6 +25,11 @@ pub struct AuthInfo {
/// 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.
+107
View File
@@ -118,6 +118,57 @@ 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"];
@@ -187,6 +238,16 @@ impl TenantContext {
}
}
/// 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))
@@ -227,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 {
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-dashboard"
version = "0.4.3"
version = "0.4.4"
edition = "2021"
default-run = "compliance-dashboard"
+21
View File
@@ -5469,3 +5469,24 @@ input[type="file"] {
.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,6 +2,7 @@ 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};
@@ -50,8 +51,16 @@ pub fn AppShell() -> Element {
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 {}
@@ -59,6 +68,9 @@ pub fn AppShell() -> Element {
if let Some(tenant) = info.support_tenant.clone() {
SupportBanner { tenant }
}
if read_only {
ReadOnlyBanner {}
}
Outlet::<Route> {}
}
NotificationBell {}
@@ -12,6 +12,7 @@ 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;
@@ -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",
+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,
+29
View File
@@ -2802,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
@@ -346,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;
@@ -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,6 +53,7 @@ pub async fn check_auth() -> Result<AuthInfo, ServerFnError> {
match user_state {
Some(u) => Ok(AuthInfo {
authenticated: true,
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(
@@ -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();
}
}
+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;
@@ -59,6 +59,34 @@ pub fn has_support_role(access_token: &str) -> bool {
.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;
@@ -136,6 +164,56 @@ mod tests {
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"
}
}
}
}
@@ -23,6 +23,7 @@ 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();
@@ -237,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() {
@@ -356,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| {
+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! {
+42 -32
View File
@@ -11,6 +11,7 @@ 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;
@@ -74,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());
@@ -151,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)}
}
}
}
}
@@ -287,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",
+39 -31
View File
@@ -9,6 +9,7 @@ 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;
@@ -65,6 +66,7 @@ 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);
@@ -108,8 +110,10 @@ 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",
@@ -153,12 +157,14 @@ pub fn TargetsPage() -> Element {
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)} }
@@ -227,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.4.3"
version = "0.4.4"
edition = "2021"
[lints]
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-graph"
version = "0.4.3"
version = "0.4.4"
edition = "2021"
[lints]
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-mcp"
version = "0.4.3"
version = "0.4.4"
edition = "2021"
[dependencies]
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-smoke"
version = "0.4.3"
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.4.3"
version = "0.4.4"
edition = "2021"
[lints]
+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.4.3"
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."