//! Org-role enforcement for the customer API (decided 2026-09-30). //! //! One middleware for every tenant-scoped route, so no handler can forget it: //! //! * `OWNER`, `IT_ADMIN`, `USER`, `PSIRT`, `DEVELOPMENT` — read and write. //! * `CXO`, `LEGAL`, `QUALITY`, `PURCHASING`, `AUDITOR` — read only: `GET` / `HEAD` / `OPTIONS`, plus the few //! `POST` routes that only read ([`READ_ONLY_POSTS`]). `LEGAL` also //! decides about licences: the licence policy and the legal review //! ([`ROLE_WRITES`], decided 2026-10-15). //! * `FINANCE`, `PRIVACY`, `EXTERNAL`, 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 for administrators: //! `IT_ADMIN` and `OWNER`). //! //! API keys (tenant-registry ADR 0001) hold no role. They reach only the //! routes in [`KEY_SCOPES`], each with the scope it names; every other route //! answers `403 {"error": "scope_missing"}`. use axum::{ extract::{MatchedPath, Request}, http::{Method, StatusCode}, middleware::Next, response::{IntoResponse, Response}, Json, }; use compliance_core::{ApiKeyAccess, OrgRole, ProductAccess, TenantContext}; /// The JSON `error` of a refusal. pub const FORBIDDEN_ROLE: &str = "forbidden_role"; /// The JSON `error` when an API key lacks the route's scope, or the route /// takes no key at all. pub const SCOPE_MISSING: &str = "scope_missing"; /// Every route an API key may call: method, route template, required scope. /// Anything not listed (manual findings, credentials, target admin, /// settings, releasing an ENISA draft) is unreachable with a key. pub const KEY_SCOPES: &[(Method, &str, &str)] = &[ (Method::GET, "/api/v1/findings", FINDINGS_READ), (Method::GET, "/api/v1/findings/variants", FINDINGS_READ), (Method::GET, "/api/v1/findings/{id}", FINDINGS_READ), ( Method::PATCH, "/api/v1/findings/{id}/status", FINDINGS_WRITE, ), ( Method::PATCH, "/api/v1/findings/bulk-status", FINDINGS_WRITE, ), ( Method::PATCH, "/api/v1/findings/{id}/feedback", FINDINGS_WRITE, ), (Method::GET, "/api/v1/sbom", SBOM_READ), (Method::GET, "/api/v1/sbom/filters", SBOM_READ), (Method::GET, "/api/v1/sbom/export", SBOM_READ), (Method::GET, "/api/v1/sbom/licenses", SBOM_READ), (Method::GET, "/api/v1/sbom/quality", SBOM_READ), (Method::GET, "/api/v1/sbom/diff", SBOM_READ), (Method::GET, "/api/v1/sbom/notices", SBOM_READ), (Method::GET, "/api/v1/licenses/check", SBOM_READ), (Method::GET, "/api/v1/licenses/policy", SBOM_READ), (Method::GET, "/api/v1/scan-runs", SCANS_READ), (Method::POST, "/api/v1/targets/{id}/scan", SCANS_RUN), (Method::POST, "/api/v1/dast/targets/{id}/scan", SCANS_RUN), (Method::GET, "/api/v1/targets/{id}/enisa", ENISA_READ), (Method::GET, "/api/v1/cves/{id}/enisa", ENISA_READ), ]; const FINDINGS_READ: &str = "pruefwerk:findings.read"; const FINDINGS_WRITE: &str = "pruefwerk:findings.write"; const SBOM_READ: &str = "pruefwerk:sbom.read"; const SCANS_READ: &str = "pruefwerk:scans.read"; const SCANS_RUN: &str = "pruefwerk:scans.run"; const ENISA_READ: &str = "pruefwerk:enisa.read"; /// What a legacy key (issued before scopes, no scopes of its own) may do: /// read, never write or run. Such keys never reached this API before. pub const LEGACY_SCOPES: &[&str] = &[FINDINGS_READ, SBOM_READ, SCANS_READ, ENISA_READ]; /// The scope `key` lacks for `method` on `template`, if any. A route that is /// not in [`KEY_SCOPES`] (or matched no route) lacks `None`: no scope opens it. pub fn key_refusal( key: &ApiKeyAccess, method: &Method, template: Option<&str>, ) -> Option> { let required = KEY_SCOPES .iter() .find(|(m, t, _)| m == method && Some(*t) == template) .map(|(_, _, scope)| *scope); match required { Some(scope) if key.has_scope(scope) => None, missing => Some(missing), } } /// `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", ]; /// Writes a read-only role may still make: method, route template, the /// roles that may. The handler decides who else may (IT_ADMIN, support). pub const ROLE_WRITES: &[(Method, &str, &[OrgRole])] = &[ (Method::PUT, "/api/v1/licenses/policy", &[OrgRole::Legal]), (Method::POST, "/api/v1/licenses/review", &[OrgRole::Legal]), (Method::DELETE, "/api/v1/licenses/review", &[OrgRole::Legal]), ]; /// Whether `ctx` holds a role [`ROLE_WRITES`] lets write `method` on `template`. pub fn role_may_write(ctx: &TenantContext, method: &Method, template: Option<&str>) -> bool { ROLE_WRITES .iter() .any(|(m, t, roles)| m == method && Some(*t) == template && ctx.has_any_role(roles)) } /// 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 { match ctx.product_access() { ProductAccess::Full => None, ProductAccess::ReadOnly if !is_write(method, template) => None, ProductAccess::ReadOnly if role_may_write(ctx, 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::() else { return next.run(request).await; }; let template = request .extensions() .get::() .map(MatchedPath::as_str); if let Some(key) = ctx.api_key.as_ref() { let Some(required) = key_refusal(key, request.method(), template) else { return next.run(request).await; }; tracing::info!( tenant_id = %ctx.tenant_id, key_id = %key.key_id, method = %request.method(), route = template.unwrap_or("-"), required = required.unwrap_or("-"), "request refused: API key scope" ); return ( StatusCode::FORBIDDEN, Json(serde_json::json!({ "error": SCOPE_MISSING, "required": required })), ) .into_response(); } 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}"))); } }