Files
pruefwerk/compliance-core/src/tenant_ctx.rs
T
sharang 96d97ae6eb
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 4m24s
CI / Deploy Dashboard (push) Successful in 6m0s
CI / Deploy Agent (push) Successful in 7m22s
feat(support): BreakPilot support can open any tenant, attributed and audited (#425)
2026-09-29 07:37:12 +00:00

198 lines
6.1 KiB
Rust

//! Axum extractor for the per-request `TenantContext`.
//!
//! Handlers consume it as a normal extractor argument:
//!
//! ```ignore
//! async fn list_findings(TenantCtx(ctx): TenantCtx) -> Json<...> {
//! let filter = compliance_core::db::tenant_filter(&ctx);
//! ...
//! }
//! ```
//!
//! The middleware ([`crate::auth::require_jwt_auth`]) is responsible for
//! inserting the context into the request extensions. If it's missing on
//! a route that uses this extractor, that's a bug in the wiring — we
//! return 401 so the caller sees an auth failure rather than a 500.
use axum::{
extract::FromRequestParts,
http::{request::Parts, StatusCode},
response::{IntoResponse, Response},
};
use crate::{StaffAccess, TenantContext};
/// What a support user without a chosen tenant is told by a tenant-scoped
/// route. Distinct from an expired sign-in, so the dashboard asks for a
/// tenant instead of sending the user back to the login.
pub const TENANT_NOT_SELECTED: &str = "tenant_not_selected";
#[derive(Debug, Clone)]
pub struct TenantCtx(pub TenantContext);
/// Why a tenant-scoped route refused the request.
#[derive(Debug)]
pub enum TenantCtxRejection {
/// No authenticated tenant at all.
Unauthenticated,
/// BreakPilot support, signed in, with no tenant chosen yet.
TenantNotSelected,
}
impl IntoResponse for TenantCtxRejection {
fn into_response(self) -> Response {
match self {
Self::Unauthenticated => (
StatusCode::UNAUTHORIZED,
"Missing tenant context — request was not authenticated",
)
.into_response(),
Self::TenantNotSelected => (
StatusCode::PRECONDITION_REQUIRED,
axum::Json(serde_json::json!({ "error": TENANT_NOT_SELECTED })),
)
.into_response(),
}
}
}
/// A BreakPilot support user, with or without a chosen tenant. For the
/// support routes (the tenant list); 403 for everyone else.
#[derive(Debug, Clone)]
pub struct StaffCtx(pub StaffAccess);
/// A request that is not from BreakPilot support.
#[derive(Debug)]
pub struct StaffCtxRejection;
impl IntoResponse for StaffCtxRejection {
fn into_response(self) -> Response {
(
StatusCode::FORBIDDEN,
axum::Json(serde_json::json!({ "error": "support_only" })),
)
.into_response()
}
}
impl<S> FromRequestParts<S> for StaffCtx
where
S: Send + Sync,
{
type Rejection = StaffCtxRejection;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let chosen = parts
.extensions
.get::<TenantContext>()
.and_then(|ctx| ctx.staff.clone());
chosen
.or_else(|| parts.extensions.get::<StaffAccess>().cloned())
.map(StaffCtx)
.ok_or(StaffCtxRejection)
}
}
impl<S> FromRequestParts<S> for TenantCtx
where
S: Send + Sync,
{
type Rejection = TenantCtxRejection;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
parts
.extensions
.get::<TenantContext>()
.cloned()
.map(TenantCtx)
.ok_or_else(|| {
if parts.extensions.get::<StaffAccess>().is_some() {
TenantCtxRejection::TenantNotSelected
} else {
TenantCtxRejection::Unauthenticated
}
})
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use crate::TenantStatus;
use axum::http::Request;
fn ctx() -> TenantContext {
TenantContext {
tenant_id: "t-1".to_string(),
tenant_slug: "acme".to_string(),
org_roles: vec![],
products: vec![],
plan: "starter".to_string(),
status: TenantStatus::Active,
user_id: "u-1".to_string(),
user_name: None,
staff: None,
}
}
#[tokio::test]
async fn extracts_context_when_present() {
let mut req = Request::new(());
req.extensions_mut().insert(ctx());
let (mut parts, _) = req.into_parts();
let TenantCtx(found) = TenantCtx::from_request_parts(&mut parts, &())
.await
.expect("extractor should succeed");
assert_eq!(found.tenant_id, "t-1");
}
#[tokio::test]
async fn rejects_when_missing() {
let req: Request<()> = Request::new(());
let (mut parts, _) = req.into_parts();
let err = TenantCtx::from_request_parts(&mut parts, &()).await;
assert!(err.is_err());
}
fn staff() -> StaffAccess {
StaffAccess {
user_id: "s-1".to_string(),
user_name: Some("Support".to_string()),
}
}
#[tokio::test]
async fn support_without_a_tenant_is_asked_to_choose_one() {
let mut req = Request::new(());
req.extensions_mut().insert(staff());
let (mut parts, _) = req.into_parts();
let err = TenantCtx::from_request_parts(&mut parts, &()).await;
assert!(matches!(err, Err(TenantCtxRejection::TenantNotSelected)));
}
#[tokio::test]
async fn only_support_passes_the_staff_extractor() {
let mut customer = Request::new(());
customer.extensions_mut().insert(ctx());
let (mut parts, _) = customer.into_parts();
assert!(StaffCtx::from_request_parts(&mut parts, &()).await.is_err());
let mut chosen = Request::new(());
chosen.extensions_mut().insert(TenantContext {
staff: Some(staff()),
..ctx()
});
let (mut parts, _) = chosen.into_parts();
let StaffCtx(found) = StaffCtx::from_request_parts(&mut parts, &())
.await
.expect("support with a tenant");
assert_eq!(found.user_id, "s-1");
let mut unchosen = Request::new(());
unchosen.extensions_mut().insert(staff());
let (mut parts, _) = unchosen.into_parts();
assert!(StaffCtx::from_request_parts(&mut parts, &()).await.is_ok());
}
}