feat(access): blocked workspace members are refused (portal#74)
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 8m42s

Since portal#82 / tenant-registry#64 an IT admin or staff can block a
member per workspace; the registry records it, never disables the
Keycloak user, and Prüfwerk let a blocked member back in after a new
login.

- The entitlement check now sends the person's Keycloak `sub` as
  `user_id`; the registry answers `allowed: false, reason:
  member_blocked` for a blocked member, and the agent refuses with
  403 {"error":"MEMBER_BLOCKED"}. Cached per tenant and user for up to
  60 s, like the entitlement answer. Only person tokens are checked:
  support takes its own path, and service tokens (platform API, runner)
  carry no tenant context there. The registry allows when its own block
  lookup fails; an unreachable registry is still refused as before
  (entitlement fails closed).
- GET /api/v1/access: answered only past authentication, entitlement
  and role checks, for the dashboard's sign-in check.
- Dashboard: check_auth asks it once per page load (not for support)
  and a blocked member sees only "Zugang gesperrt" ("Ihr Zugang zu
  diesem Arbeitsbereich ist gesperrt oder wurde entfernt…"), with the
  way back to the portal and sign-out. AuthInfo gains member_blocked.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
This commit is contained in:
Sharang ParnerkarandClaude Opus 5.5 committed 2026-10-06 00:11:42 +02:00
1 parent 34688fa322
commit 3abb32b65c
11 files changed
+273 -8

No files matched your search

@@ -5,6 +5,14 @@ use super::dto::*;
use compliance_core::models::ScanRun;
use compliance_core::tenant_ctx::TenantCtx;
/// `GET /api/v1/access`: reached only when the authentication, entitlement
/// and role layers let the caller through; they answer the refusals (a
/// blocked member gets 403 `MEMBER_BLOCKED`).
#[tracing::instrument(skip_all)]
pub async fn access() -> Json<serde_json::Value> {
Json(serde_json::json!({ "access": true }))
}
#[tracing::instrument(skip_all)]
pub async fn health() -> Json<serde_json::Value> {
Json(serde_json::json!({ "status": "ok" }))
+4
View File
@@ -15,6 +15,10 @@ pub fn build_router() -> Router {
.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))
// Whether the caller may use Prüfwerk at all: answered by the
// authentication and entitlement layers in front of it (a blocked
// member gets 403 MEMBER_BLOCKED), for the dashboard's sign-in check.
.route("/api/v1/access", get(handlers::health::access))
// The managed git source, read-only (IT admin and support).
.route(
"/api/v1/git-source",
+13 -1
View File
@@ -114,7 +114,11 @@ pub async fn require_entitlement(
let Some(ctx) = request.extensions().get::<TenantContext>().cloned() else {
return next.run(request).await;
};
match registry.check_entitlement(&ctx.tenant_id, None).await {
// A person's token (support took its own branch above; service tokens
// carry no tenant context here): the registry also says whether this
// member is blocked in the tenant.
let user = Some(ctx.user_id.as_str()).filter(|u| !u.is_empty());
match registry.check_entitlement(&ctx.tenant_id, None, user).await {
Ok(check) if check.allowed => {
let mut ctx = ctx;
if let Some(st) = check.status.as_deref().and_then(TenantStatus::parse) {
@@ -126,6 +130,14 @@ pub async fn require_entitlement(
request.extensions_mut().insert(ctx);
next.run(request).await
}
Ok(check) if check.member_blocked() => (
StatusCode::FORBIDDEN,
Json(serde_json::json!({
"error": "MEMBER_BLOCKED",
"status": check.status,
})),
)
.into_response(),
Ok(check) => (
StatusCode::FORBIDDEN,
Json(serde_json::json!({
+1 -1
View File
@@ -191,7 +191,7 @@ pub async fn automation_allowed(agent: &ComplianceAgent, tenant_id: &str) -> Res
}
return Ok(());
};
let check = registry.check_entitlement(tenant_id, None).await?;
let check = registry.check_entitlement(tenant_id, None, None).await?;
if !check.allowed {
return Err(format!(
"not entitled: {}",
+24 -2
View File
@@ -27,6 +27,9 @@ pub const ENTITLEMENT_TTL: Duration = Duration::from_secs(60);
/// Refresh the service token this long before it expires.
const TOKEN_MARGIN: Duration = Duration::from_secs(30);
/// The registry's `reason` for a member blocked in the tenant.
pub const MEMBER_BLOCKED: &str = "member_blocked";
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
pub struct EntitlementCheck {
pub allowed: bool,
@@ -42,6 +45,14 @@ pub struct EntitlementCheck {
pub reason: Option<String>,
}
impl EntitlementCheck {
/// Whether the registry refused because the member is blocked in the
/// tenant, not because the tenant lacks the product.
pub fn member_blocked(&self) -> bool {
!self.allowed && self.reason.as_deref() == Some(MEMBER_BLOCKED)
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct RegistryTenant {
pub id: String,
@@ -258,13 +269,23 @@ impl RegistryClient {
}
/// Authoritative entitlement answer for this product, cached ≤ 60 s per
/// (tenant, addon). Errors mean "unknown" — callers fail closed.
/// (tenant, addon, user). Errors mean "unknown" — callers fail closed.
///
/// With `user_id` (the Keycloak `sub` of a person), the registry also
/// answers `allowed: false, reason: "member_blocked"` when that member is
/// blocked in the tenant (portal#74). The registry itself allows when it
/// cannot tell, so a failing block lookup never locks anyone out.
pub async fn check_entitlement(
&self,
tenant_id: &str,
addon: Option<&str>,
user_id: Option<&str>,
) -> Result<EntitlementCheck, String> {
let key = format!("{tenant_id}|{}", addon.unwrap_or(""));
let key = format!(
"{tenant_id}|{}|{}",
addon.unwrap_or(""),
user_id.unwrap_or("")
);
if let Some(entry) = self.cache.get(&key) {
if entry.0.elapsed() < ENTITLEMENT_TTL {
return Ok(entry.1.clone());
@@ -274,6 +295,7 @@ impl RegistryClient {
"tenant_id": tenant_id,
"product": self.product,
"addon": addon,
"user_id": user_id,
});
let resp = self
.request(reqwest::Method::POST, "/v1/internal/entitlements/check")
+150
View File
@@ -0,0 +1,150 @@
//! A member the workspace blocked (portal#74) is refused, everyone else is
//! let in, and support is never asked about. Runs the real entitlement
//! middleware against a fake tenant registry and a live Mongo (for the agent
//! itself); skips cleanly without one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
mod common;
use std::sync::{Arc, Mutex};
use axum::body::Body;
use axum::extract::{Request, State};
use axum::http::StatusCode;
use axum::middleware::{from_fn, from_fn_with_state, Next};
use axum::routing::{get, post};
use axum::{Json, Router};
use tower::ServiceExt;
use compliance_agent::agent::ComplianceAgent;
use compliance_agent::api::server::require_entitlement;
use compliance_agent::database::DatabasePool;
use compliance_core::{OrgRole, StaffAccess, TenantContext, TenantStatus};
use common::dev_config;
/// The bodies the fake registry's entitlement check received.
type Seen = Arc<Mutex<Vec<serde_json::Value>>>;
/// A registry that blocks the member `u-blocked`.
async fn fake_registry(seen: Seen) -> String {
let app = Router::new()
.route(
"/v1/internal/entitlements/check",
post(|State(seen): State<Seen>, Json(body): Json<serde_json::Value>| async move {
let blocked = body["user_id"].as_str() == Some("u-blocked");
seen.lock().unwrap().push(body);
Json(if blocked {
serde_json::json!({ "allowed": false, "status": "active", "reason": "member_blocked" })
} else {
serde_json::json!({ "allowed": true, "status": "active" })
})
}),
)
.route(
"/v1/tenants/{id}",
get(|| async { Json(serde_json::json!({ "id": "t-1", "slug": "acme", "name": "Acme", "status": "active" })) }),
)
.with_state(seen);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
format!("http://{addr}")
}
fn member(user: &str) -> TenantContext {
TenantContext {
tenant_id: "t-1".into(),
tenant_slug: "acme".into(),
org_roles: vec![OrgRole::ItAdmin],
products: vec!["compliance-scanner".into()],
plan: "starter".into(),
status: TenantStatus::Active,
user_id: user.into(),
user_name: None,
staff: None,
}
}
/// An agent whose registry is `registry`, or `None` without Mongo.
async fn agent(registry: &str) -> Option<Arc<ComplianceAgent>> {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db_name = format!("blk_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
let Ok(pool) = DatabasePool::connect(&uri, &db_name).await else {
eprintln!("SKIP member_blocked: no MongoDB reachable at {uri}");
return None;
};
let mut config = dev_config(uri, db_name);
config.tenant_registry_url = Some(registry.to_string());
Some(Arc::new(ComplianceAgent::new(config, pool)))
}
/// GET /r as `ctx` through the entitlement middleware.
async fn call(agent: Arc<ComplianceAgent>, ctx: TenantContext) -> (StatusCode, serde_json::Value) {
let inject = move |mut req: Request, next: Next| {
let ctx = ctx.clone();
async move {
req.extensions_mut().insert(ctx);
next.run(req).await
}
};
let app = Router::new()
.route("/r", get(|| async { "ok" }))
.layer(from_fn_with_state(agent, require_entitlement))
.layer(from_fn(inject));
let resp = app
.oneshot(Request::builder().uri("/r").body(Body::empty()).unwrap())
.await
.unwrap();
let status = resp.status();
let bytes = axum::body::to_bytes(resp.into_body(), 1 << 16)
.await
.unwrap();
(status, serde_json::from_slice(&bytes).unwrap_or_default())
}
#[tokio::test]
async fn a_blocked_member_is_refused_and_others_are_not() {
let seen: Seen = Arc::default();
let base = fake_registry(seen.clone()).await;
let Some(agent) = agent(&base).await else {
return;
};
// A blocked member: 403 MEMBER_BLOCKED.
let (status, body) = call(agent.clone(), member("u-blocked")).await;
assert_eq!(status, StatusCode::FORBIDDEN);
assert_eq!(body["error"], "MEMBER_BLOCKED");
// Anyone else in the same tenant: let in, and the registry was asked
// about that person (by their Keycloak sub).
let (status, _) = call(agent.clone(), member("u-ok")).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(seen.lock().unwrap().last().unwrap()["user_id"], "u-ok");
// Support takes its own path: the entitlement check (and with it the
// block check) is not asked at all.
let calls = seen.lock().unwrap().len();
let mut support = member("staff-1");
support.staff = Some(StaffAccess {
user_id: "staff-1".into(),
user_name: Some("Support".into()),
});
let (status, _) = call(agent.clone(), support).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(seen.lock().unwrap().len(), calls);
}
#[tokio::test]
async fn an_unreachable_registry_still_refuses_as_before() {
// Not a block decision: the entitlement check itself fails closed when
// the registry cannot be asked (MVP-1.2); the block check adds nothing.
let Some(agent) = agent("http://127.0.0.1:9").await else {
return;
};
let (status, body) = call(agent, member("u-ok")).await;
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(body["error"], "entitlement_unavailable");
}
+4
View File
@@ -30,6 +30,10 @@ pub struct AuthInfo {
/// the same rule on every request.
#[serde(default)]
pub access: crate::ProductAccess,
/// The workspace blocked or removed this member (portal#74): the app
/// shows only that, whatever the role allows.
#[serde(default)]
pub member_blocked: bool,
}
/// A customer tenant opened by BreakPilot support.
@@ -51,6 +51,13 @@ pub fn AppShell() -> Element {
ToastContainer {}
}
}
// A member the workspace blocked (portal#74): the agent refuses
// everything, so the app shows only that.
Some(Ok(info)) if info.authenticated && info.member_blocked => {
rsx! {
NoAccess { portal_url: info.portal_url.clone(), blocked: true }
}
}
// 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() => {
@@ -17,18 +17,24 @@ 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.
/// The whole page for a role without access, or a member the workspace
/// blocked (`blocked`): no navigation, no data.
#[component]
pub fn NoAccess(portal_url: String) -> Element {
pub fn NoAccess(portal_url: String, #[props(default)] blocked: bool) -> Element {
let lang = use_lang()();
let (title, body) = if blocked {
(tx::BLOCKED_TITLE, tx::BLOCKED_BODY)
} else {
(tx::NO_ACCESS_TITLE, tx::NO_ACCESS_BODY)
};
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)} }
h1 { {title.get(lang)} }
}
p { class: "support-picker-intro", {tx::NO_ACCESS_BODY.get(lang)} }
p { class: "support-picker-intro", {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)} }
+11
View File
@@ -2969,6 +2969,17 @@ mod run_error_tests {
pub mod access {
use super::Text;
pub const BLOCKED_TITLE: Text = Text {
de: "Zugang gesperrt",
en: "Access blocked",
};
pub const BLOCKED_BODY: Text = Text {
de: "Ihr Zugang zu diesem Arbeitsbereich ist gesperrt oder wurde entfernt. Wenden \
Sie sich an die IT-Administration Ihres Unternehmens, wenn Sie wieder Zugriff \
benötigen.",
en: "Your access to this workspace has been blocked or removed. Please contact your \
company's IT administration if you need access again.",
};
pub const NO_ACCESS_TITLE: Text = Text {
de: "Kein Zugriff auf Prüfwerk",
en: "No access to Prüfwerk",
@@ -52,6 +52,9 @@ pub async fn check_auth() -> Result<AuthInfo, ServerFnError> {
match user_state {
Some(u) => Ok(AuthInfo {
// Support is never a member; everyone else is asked about once
// per page load (the agent caches the registry's answer).
member_blocked: !u.staff && member_blocked().await,
authenticated: true,
access: u.product_access(),
// Support is not a member of the tenant it opened: the portal's
@@ -75,10 +78,48 @@ pub async fn check_auth() -> Result<AuthInfo, ServerFnError> {
}
}
/// Whether the agent refuses the signed-in member as blocked in their
/// workspace. Anything else, an unreachable agent included, is not a block:
/// the agent refuses every request itself anyway.
#[cfg(feature = "server")]
async fn member_blocked() -> bool {
let Ok(request) = super::agent_client::agent_get("/api/v1/access").await else {
return false;
};
let Ok(response) = request.send().await else {
return false;
};
if response.status() != reqwest::StatusCode::FORBIDDEN {
return false;
}
response
.json::<serde_json::Value>()
.await
.is_ok_and(|body| is_member_blocked(&body))
}
/// Whether an agent refusal says the member is blocked.
pub fn is_member_blocked(body: &serde_json::Value) -> bool {
body["error"].as_str() == Some("MEMBER_BLOCKED")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_blocked_refusal_counts_as_a_block() {
assert!(is_member_blocked(
&serde_json::json!({ "error": "MEMBER_BLOCKED" })
));
assert!(!is_member_blocked(
&serde_json::json!({ "error": "forbidden_role" })
));
assert!(!is_member_blocked(
&serde_json::json!({ "error": "not_entitled" })
));
}
#[test]
fn an_expired_sign_in_is_recognised_in_a_server_error() {
assert!(is_session_expired(&ServerFnError::new(SESSION_EXPIRED)));