Files
pruefwerk/compliance-core/src/tenant.rs
T
sharangandClaude Opus 5.5 ea1b48dd37
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m11s
CI / Deploy MCP (push) Successful in 4m54s
CI / Deploy Dashboard (push) Successful in 7m12s
CI / Deploy Agent (push) Successful in 9m1s
feat(auth): Prüfwerk access for the RBAC step 4 roles (#989) (#990)
Decided 2026-11-12: PSIRT and DEVELOPMENT get full access (they triage
findings and run scans); QUALITY, PURCHASING and AUDITOR read only;
PRIVACY and EXTERNAL none, as before. Each parses to its own OrgRole.
Admin-only actions (manual findings, git source, licence decisions) stay
with IT_ADMIN and OWNER; confirming a licence follows full access, so
PSIRT and DEVELOPMENT may confirm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:24:59 +00:00

487 lines
18 KiB
Rust

//! Tenant context propagated through every authenticated request.
//!
//! M7.1 single source of truth for "who is this request for". Claims come
//! from a Keycloak-issued JWT and land here via [`crate::auth::require_jwt_auth`]
//! (enabled with the `axum` feature). Handlers reach into the request
//! extensions with the [`crate::tenant_ctx::TenantCtx`] extractor.
//!
//! The shape mirrors the JWT claim names the breakpilot-platform realm
//! emits (see `platform/orca-platform/dev/keycloak/realm-export.json`).
//! Stable contract — adding fields is fine; renaming is a breaking
//! change for every downstream product.
use serde::{Deserialize, Serialize};
/// Tenant status ladder (`PLATFORM_ARCHITECTURE.md §5c`, ERP/02).
///
/// Drives the `tenant_status` middleware:
/// * `Demo` / `Trial` / `Active` / `Warning` — full access (Warning = payment
/// overdue within grace; UIs show a banner).
/// * `Restricted` (Eingeschränkt) and the legacy `Frozen` — read-only:
/// mutating endpoints return 402, exports still work.
/// * `Halted` (Angehalten) — every request returns 402 except the platform
/// export path; data retained for the export window.
/// * `Archived` — data-retention window closed. Every endpoint returns 410.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TenantStatus {
Demo,
Trial,
Active,
Warning,
Restricted,
Frozen,
Halted,
Archived,
}
impl TenantStatus {
/// Parse the registry / JWT string form. Unknown values → `None`.
pub fn parse(s: &str) -> Option<Self> {
Some(match s {
"demo" => Self::Demo,
"trial" => Self::Trial,
"active" => Self::Active,
"warning" => Self::Warning,
"restricted" => Self::Restricted,
"frozen" => Self::Frozen,
"halted" => Self::Halted,
"archived" => Self::Archived,
_ => return None,
})
}
/// True for the read-only rungs of the ladder (writes return 402).
pub fn blocks_writes(&self) -> bool {
matches!(self, TenantStatus::Frozen | TenantStatus::Restricted)
}
/// Legacy name for [`Self::blocks_writes`].
pub fn is_frozen(&self) -> bool {
self.blocks_writes()
}
/// True when every request except export is refused (402).
pub fn is_halted(&self) -> bool {
matches!(self, TenantStatus::Halted)
}
/// True for statuses that block every request.
pub fn is_archived(&self) -> bool {
matches!(self, TenantStatus::Archived)
}
/// True for the shared demo tenant — metering, billing, and audit
/// export are skipped.
pub fn is_demo(&self) -> bool {
matches!(self, TenantStatus::Demo)
}
}
impl std::fmt::Display for TenantStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Demo => write!(f, "demo"),
Self::Trial => write!(f, "trial"),
Self::Active => write!(f, "active"),
Self::Warning => write!(f, "warning"),
Self::Restricted => write!(f, "restricted"),
Self::Frozen => write!(f, "frozen"),
Self::Halted => write!(f, "halted"),
Self::Archived => write!(f, "archived"),
}
}
}
/// Org-level role baked into the JWT by the realm's protocol mapper.
/// `PLATFORM_ARCHITECTURE.md §6` is the canonical list.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum OrgRole {
/// The organisation's owner: in Prüfwerk the same rights as `IT_ADMIN`,
/// as on the rest of the platform.
Owner,
ItAdmin,
Cxo,
Finance,
Legal,
User,
/// Product security (RBAC step 4): full access, triages and scans.
Psirt,
/// Development (RBAC step 4): full access, triages and scans.
Development,
/// Quality (RBAC step 4): read only.
Quality,
/// Privacy (RBAC step 4): no access to Prüfwerk.
Privacy,
/// Purchasing (RBAC step 4): read only.
Purchasing,
/// Auditor (RBAC step 4): read only.
Auditor,
/// External (RBAC step 4): no access to Prüfwerk.
External,
/// Anything we haven't enumerated yet — forwards-compatible.
#[serde(other)]
Unknown,
}
impl OrgRole {
/// Parses a single role string (Keycloak emits these as `IT_ADMIN`,
/// `CXO`, etc.). Round-trips with the JSON layer.
pub fn parse(s: &str) -> Self {
match s {
"OWNER" => OrgRole::Owner,
"IT_ADMIN" => OrgRole::ItAdmin,
"CXO" => OrgRole::Cxo,
"FINANCE" => OrgRole::Finance,
"LEGAL" => OrgRole::Legal,
"USER" => OrgRole::User,
"PSIRT" => OrgRole::Psirt,
"DEVELOPMENT" => OrgRole::Development,
"QUALITY" => OrgRole::Quality,
"PRIVACY" => OrgRole::Privacy,
"PURCHASING" => OrgRole::Purchasing,
"AUDITOR" => OrgRole::Auditor,
"EXTERNAL" => OrgRole::External,
_ => OrgRole::Unknown,
}
}
/// Whether the role administers the organisation: `IT_ADMIN` or `OWNER`.
/// What only an administrator may do (manual findings, the git source)
/// asks this, not for `IT_ADMIN` alone.
pub fn is_admin(&self) -> bool {
matches!(self, OrgRole::Owner | OrgRole::ItAdmin)
}
}
/// What an organisation member may do in Prüfwerk, by their org roles
/// (decided 2026-09-30):
///
/// * `OWNER`, `IT_ADMIN`, `USER`, `PSIRT`, `DEVELOPMENT` —
/// [`ProductAccess::Full`]: read and write (`OWNER` added 2026-11-12: it has
/// `IT_ADMIN`'s rights platform-wide; `PSIRT` and `DEVELOPMENT` from RBAC
/// step 4, decided 2026-11-12).
/// * `CXO`, `LEGAL`, `QUALITY`, `PURCHASING`, `AUDITOR` —
/// [`ProductAccess::ReadOnly`]: findings, reports, SBOM, evidence and
/// exports, but no change of any kind.
/// * `FINANCE`, `PRIVACY`, `EXTERNAL`, 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| {
r.is_admin() || matches!(r, OrgRole::User | OrgRole::Psirt | OrgRole::Development)
}) {
Self::Full
} else if roles.iter().any(|r| {
matches!(
r,
OrgRole::Cxo
| OrgRole::Legal
| OrgRole::Quality
| OrgRole::Purchasing
| OrgRole::Auditor
)
}) {
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(),
}
}
}
/// A portal-issued API key acting in its tenant (tenant-registry ADR 0001).
/// Everything here comes from the registry's verify answer, never from the
/// request, except `on_behalf_of`, which is informational only.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ApiKeyAccess {
/// The registry's id of the key; the actor is `apikey:<key_id>`.
pub key_id: String,
/// `personal` or `service`, as the registry labels it.
pub kind: String,
/// Who the key was issued to, if the registry says.
pub holder: Option<String>,
/// What the key may do. A legacy key's read scopes are filled in by the
/// agent; nothing else widens this list.
pub scopes: Vec<String>,
/// Issued before scopes existed.
pub legacy: bool,
/// The `X-BP-Actor` header: who a caller says it acts for. Logged and
/// audited, never used to decide anything.
pub on_behalf_of: Option<String>,
}
impl ApiKeyAccess {
/// Whether the key carries `scope`. A `<x>.write` scope also grants
/// `<x>.read`; nothing else implies anything.
pub fn has_scope(&self, scope: &str) -> bool {
let write = scope
.strip_suffix(".read")
.map(|base| format!("{base}.write"));
self.scopes
.iter()
.any(|s| s == scope || write.as_deref() == Some(s.as_str()))
}
}
/// 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)]
pub struct TenantContext {
/// `tenants.id` from the platform's tenant-registry (UUID).
pub tenant_id: String,
/// Lowercase URL-safe slug. Useful for log lines + audit emit.
pub tenant_slug: String,
/// Org-level roles the authenticated user holds inside this tenant.
/// Drives the per-handler RBAC in `M7.1-followup` PRs.
pub org_roles: Vec<OrgRole>,
/// Products this tenant is currently entitled to. Used to short-circuit
/// MCP / API calls for unsubscribed products.
pub products: Vec<String>,
/// Customer plan (`starter` / `professional` / `enterprise`) — gates
/// per-plan feature flags (e.g., MCP server is enterprise-only).
pub plan: String,
/// Lifecycle status — read by `require_tenant_status` middleware.
pub status: TenantStatus,
/// Keycloak user id of the requester (`sub` claim). Required for audit
/// emit so we know WHO did the thing, not just WHICH tenant.
pub user_id: String,
/// 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>,
/// Set when an API key, not a person, made the request. `user_id` is
/// then `apikey:<key_id>` and `org_roles` is empty: a key is judged by
/// its scopes, never by a role.
/// Boxed: absent on almost every request, so it costs a pointer there.
#[serde(default)]
pub api_key: Option<Box<ApiKeyAccess>>,
}
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 {
// Scopes, not roles, decide for a key (`role_gate`); anything that
// asks for a role refuses it.
if self.api_key.is_some() {
return ProductAccess::None;
}
if self.staff.is_some() {
return ProductAccess::Full;
}
ProductAccess::for_roles(&self.org_roles)
}
/// True if the caller holds `IT_ADMIN` or `OWNER`.
pub fn is_admin(&self) -> bool {
self.org_roles.iter().any(OrgRole::is_admin)
}
/// 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))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn org_role_parses_known_values() {
assert_eq!(OrgRole::parse("IT_ADMIN"), OrgRole::ItAdmin);
assert_eq!(OrgRole::parse("OWNER"), OrgRole::Owner);
assert_eq!(OrgRole::parse("PSIRT"), OrgRole::Psirt);
assert_eq!(OrgRole::parse("DEVELOPMENT"), OrgRole::Development);
assert_eq!(OrgRole::parse("QUALITY"), OrgRole::Quality);
assert_eq!(OrgRole::parse("PRIVACY"), OrgRole::Privacy);
assert_eq!(OrgRole::parse("PURCHASING"), OrgRole::Purchasing);
assert_eq!(OrgRole::parse("AUDITOR"), OrgRole::Auditor);
assert_eq!(OrgRole::parse("EXTERNAL"), OrgRole::External);
assert_eq!(OrgRole::parse("CXO"), OrgRole::Cxo);
assert_eq!(OrgRole::parse("USER"), OrgRole::User);
}
#[test]
fn org_role_unknown_is_forward_compat() {
assert_eq!(OrgRole::parse("FUTURE_ROLE"), OrgRole::Unknown);
}
#[test]
fn tenant_status_predicates() {
assert!(TenantStatus::Frozen.is_frozen());
assert!(TenantStatus::Restricted.blocks_writes());
assert!(!TenantStatus::Warning.blocks_writes());
assert!(TenantStatus::Halted.is_halted());
assert!(!TenantStatus::Active.is_frozen());
assert_eq!(
TenantStatus::parse("restricted"),
Some(TenantStatus::Restricted)
);
assert_eq!(TenantStatus::parse("paid"), None);
assert_eq!(TenantStatus::Halted.to_string(), "halted");
assert!(TenantStatus::Archived.is_archived());
assert!(TenantStatus::Demo.is_demo());
assert!(!TenantStatus::Active.is_demo());
}
#[test]
fn product_access_follows_the_strongest_role() {
use OrgRole::*;
let cases: &[(&[OrgRole], ProductAccess)] = &[
(&[ItAdmin], ProductAccess::Full),
(&[Owner], ProductAccess::Full),
(&[Psirt], ProductAccess::Full),
(&[Development], ProductAccess::Full),
(&[Quality], ProductAccess::ReadOnly),
(&[Purchasing], ProductAccess::ReadOnly),
(&[Auditor], ProductAccess::ReadOnly),
(&[Privacy], ProductAccess::None),
(&[External], ProductAccess::None),
(&[External, Auditor], ProductAccess::ReadOnly),
(&[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 a_write_scope_implies_its_read_and_nothing_else() {
let key = ApiKeyAccess {
key_id: "k".into(),
kind: "service".into(),
holder: None,
scopes: vec![
"pruefwerk:findings.write".into(),
"pruefwerk:scans.run".into(),
],
legacy: false,
on_behalf_of: None,
};
assert!(key.has_scope("pruefwerk:findings.write"));
assert!(key.has_scope("pruefwerk:findings.read"));
assert!(key.has_scope("pruefwerk:scans.run"));
assert!(!key.has_scope("pruefwerk:scans.read"));
assert!(!key.has_scope("pruefwerk:sbom.read"));
assert!(!key.has_scope("pruefwerk:findings"));
}
#[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,
}),
api_key: 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 {
tenant_id: "t1".into(),
tenant_slug: "acme".into(),
org_roles: vec![OrgRole::ItAdmin],
products: vec![],
plan: "professional".into(),
status: TenantStatus::Active,
user_id: "u".into(),
user_name: None,
staff: None,
api_key: None,
};
assert!(ctx.has_any_role(&[OrgRole::ItAdmin]));
assert!(ctx.has_any_role(&[OrgRole::Cxo, OrgRole::ItAdmin]));
assert!(!ctx.has_any_role(&[OrgRole::User, OrgRole::Cxo]));
}
}