Files
pruefwerk/compliance-core/src/auth.rs
T
sharang 07ba0d6665
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m23s
CI / Deploy Agent (push) Successful in 5m32s
CI / Deploy MCP (push) Successful in 3m1s
CI / Deploy Dashboard (push) Successful in 3m53s
feat(api): the customer API accepts portal-issued API keys (#564)
2026-10-13 22:22:21 +00:00

671 lines
23 KiB
Rust

//! M7.1 — JWT validation + tenant context propagation.
//!
//! `require_jwt_auth` validates a Bearer JWT against Keycloak's JWKS and
//! attaches a [`TenantContext`] to the request extensions. Downstream
//! middleware ([`require_tenant_status`]) and Axum extractors
//! ([`crate::tenant_ctx::TenantCtx`]) read it from there.
//!
//! Skipped paths:
//! * `/api/v1/health` — Kubernetes liveness; never authenticated.
//!
//! Failure modes:
//! * No `JwksState` extension → pass-through (single-tenant dev mode).
//! * Missing / malformed Bearer header → 401.
//! * Signature / expiry invalid → 401.
//! * Claims present but tenant_id missing → 401 (treated as a malformed
//! token; the realm must always issue tenant_id).
//!
//! Support access: a token carrying one of [`SUPPORT_ROLES`] (BreakPilot
//! staff) may name the tenant to act in with the [`SUPPORT_TENANT_HEADER`].
//! The context is then marked as staff access and left read-only until the
//! agent has confirmed the tenant with the registry. Staff without a chosen
//! tenant get only a [`StaffAccess`] extension, which no tenant-scoped handler
//! accepts. For every other token the header is ignored.
use std::sync::Arc;
use axum::{
extract::Request,
http::Method,
middleware::Next,
response::{IntoResponse, Response},
};
use jsonwebtoken::{decode, decode_header, jwk::JwkSet, DecodingKey, Validation};
use reqwest::StatusCode;
use serde::Deserialize;
use tokio::sync::RwLock;
use crate::tenant::SUPPORT_TENANT_HEADER;
use crate::{OrgRole, StaffAccess, TenantContext, TenantStatus, SUPPORT_ROLES};
/// Cached JWKS from Keycloak for token validation.
///
/// `issuer` and `audience` are pinned when set (PRODUCT_INTEGRATION_SPEC 2.0
/// §9.1: never skip iss/aud validation). `None` keeps the legacy dev
/// behaviour and is logged as a warning at startup.
#[derive(Clone)]
pub struct JwksState {
pub jwks: Arc<RwLock<Option<JwkSet>>>,
pub jwks_url: String,
pub issuer: Option<String>,
pub audience: Option<String>,
}
impl JwksState {
pub fn new(jwks_url: String, issuer: Option<String>, audience: Option<String>) -> Self {
Self {
jwks: Arc::new(RwLock::new(None)),
jwks_url,
issuer,
audience,
}
}
}
/// Claims of a platform service token (client_credentials). `azp` is the
/// Keycloak client that obtained it — the platform endpoints allow-list it.
#[derive(Debug, Clone)]
pub struct ServiceClaims {
pub sub: String,
pub azp: String,
}
/// Raw shape of the JWT payload — matches the breakpilot-dev realm's
/// protocol-mapper output. Missing fields default to "" / empty so a
/// realm that hasn't been fully wired yet still validates.
#[derive(Debug, Deserialize)]
struct Claims {
sub: String,
#[serde(default)]
name: Option<String>,
#[serde(default)]
preferred_username: Option<String>,
#[serde(default)]
tenant_id: String,
#[serde(default)]
tenant_slug: String,
#[serde(default)]
org_roles: Vec<String>,
#[serde(default)]
products: Vec<String>,
#[serde(default)]
plan: String,
#[serde(default)]
tenant_status: Option<TenantStatus>,
#[serde(default)]
azp: Option<String>,
/// Keycloak realm roles; staff roles live here, not in `org_roles`.
#[serde(default)]
realm_access: Option<RealmAccess>,
}
/// The `realm_access` claim.
#[derive(Debug, Default, Deserialize)]
struct RealmAccess {
#[serde(default)]
roles: Vec<String>,
}
/// What a validated token grants.
#[derive(Debug)]
enum Authenticated {
/// Access to one tenant: the user's own, or the one support chose.
Tenant(TenantContext),
/// A staff member who has not chosen a tenant yet.
StaffWithoutTenant(StaffAccess),
}
/// Upper bound on a JWKS fetch. The cache write lock is held for its
/// duration, so an unbounded call would queue every authenticated request
/// behind an unreachable Keycloak.
const JWKS_FETCH_TIMEOUT_SECS: u64 = 5;
const PUBLIC_ENDPOINTS: &[&str] = &["/api/v1/health"];
/// Path prefixes that bypass JWT validation. The admin sub-router
/// (`/api/v1/admin/*`) and the Werkbank runner API (`/api/v1/werkbank/*`)
/// have their own static-bearer middleware and must not be routed through the
/// customer-JWT path — a Keycloak token always carries a single tenant_id and
/// would semantically conflict with these cross-tenant / machine operations.
const PUBLIC_PREFIXES: &[&str] = &["/api/v1/admin/", "/api/v1/werkbank/", "/api/v1/platform/"];
/// Whether `path` is outside the customer API: the health check, or a
/// sub-API with its own authentication ([`PUBLIC_PREFIXES`]).
pub fn bypasses_customer_auth(path: &str) -> bool {
PUBLIC_ENDPOINTS.contains(&path) || PUBLIC_PREFIXES.iter().any(|p| path.starts_with(p))
}
/// Middleware that validates Bearer JWT tokens against Keycloak's JWKS
/// and attaches a `TenantContext` extension on success.
///
/// Skips validation for the health endpoint and any path under one of
/// the [`PUBLIC_PREFIXES`]. If `JwksState` is not present (Keycloak
/// not configured), requests pass through and downstream code must
/// handle the missing context.
pub async fn require_jwt_auth(mut request: Request, next: Next) -> Response {
if bypasses_customer_auth(request.uri().path()) {
return next.run(request).await;
}
// An API key the agent's key middleware (mounted outside this one, the
// only place that inserts a context this early) has already verified.
if request
.extensions()
.get::<TenantContext>()
.is_some_and(|c| c.api_key.is_some())
{
return next.run(request).await;
}
let jwks_state = match request.extensions().get::<JwksState>() {
Some(s) => s.clone(),
None => return next.run(request).await,
};
let auth_header = match request.headers().get("authorization") {
Some(h) => h,
None => return (StatusCode::UNAUTHORIZED, "Missing authorization header").into_response(),
};
let token = match auth_header.to_str() {
Ok(s) if s.starts_with("Bearer ") => &s[7..],
_ => return (StatusCode::UNAUTHORIZED, "Invalid authorization header").into_response(),
};
let requested_tenant = request
.headers()
.get(SUPPORT_TENANT_HEADER)
.and_then(|v| v.to_str().ok())
.map(str::to_owned);
match validate_token(token, &jwks_state, requested_tenant.as_deref()).await {
Ok(Authenticated::Tenant(ctx)) => {
request.extensions_mut().insert(ctx);
next.run(request).await
}
Ok(Authenticated::StaffWithoutTenant(staff)) => {
request.extensions_mut().insert(staff);
next.run(request).await
}
Err(e) => {
tracing::warn!("JWT validation failed: {e}");
(StatusCode::UNAUTHORIZED, "Invalid token").into_response()
}
}
}
/// Middleware that enforces the tenant status ladder (contract 2.0 §9.3).
///
/// * `Active` / `Trial` / `Demo` / `Warning` — pass through.
/// * `Restricted` / `Frozen` — read-only. Writes return 402.
/// * `Halted` — every request returns 402 (exports go through the platform
/// endpoints, which bypass this middleware).
/// * `Archived` — data-retention window closed. Every request returns 410.
///
/// Pass-through when no `TenantContext` is present (single-tenant dev or
/// the upstream JWT middleware ran without `JwksState`).
pub async fn require_tenant_status(request: Request, next: Next) -> Response {
let ctx = match request.extensions().get::<TenantContext>() {
Some(c) => c.clone(),
None => return next.run(request).await,
};
if ctx.status.is_archived() {
return (
StatusCode::GONE,
"Tenant archived — data retention window closed",
)
.into_response();
}
if ctx.status.is_halted() {
return (
StatusCode::PAYMENT_REQUIRED,
"Tenant halted — access suspended; data export remains available via the portal.",
)
.into_response();
}
if ctx.status.blocks_writes() && is_write(request.method()) {
return (
StatusCode::PAYMENT_REQUIRED,
"Tenant restricted — read-only. Settle the open invoice to resume writes.",
)
.into_response();
}
next.run(request).await
}
/// Validate a platform service token (client_credentials JWT from the same
/// realm) for the `/api/v1/platform/*` endpoints. Signature, expiry, issuer
/// and audience are enforced like user tokens; `tenant_id` is NOT required.
pub async fn validate_service_token(
token: &str,
state: &JwksState,
) -> Result<ServiceClaims, String> {
let claims = decode_claims(token, state).await?;
let azp = claims.azp.clone().unwrap_or_default();
if azp.is_empty() {
return Err("service token is missing the azp claim".to_string());
}
Ok(ServiceClaims {
sub: claims.sub,
azp,
})
}
/// Treat anything other than GET/HEAD/OPTIONS as a write. Good enough for
/// REST. The few exceptions (e.g. read-side POSTs) can opt out at the
/// handler level once we have them.
fn is_write(m: &Method) -> bool {
!matches!(m, &Method::GET | &Method::HEAD | &Method::OPTIONS)
}
async fn validate_token(
token: &str,
state: &JwksState,
requested_tenant: Option<&str>,
) -> Result<Authenticated, String> {
authenticate(decode_claims(token, state).await?, requested_tenant)
}
/// Decide what validated `claims` grant, given the tenant a support user
/// asked for (`requested_tenant`, from [`SUPPORT_TENANT_HEADER`]).
///
/// # Errors
///
/// A customer token without a tenant, or a support request naming something
/// that is not a registry tenant id.
fn authenticate(c: Claims, requested_tenant: Option<&str>) -> Result<Authenticated, String> {
let is_staff = c.realm_access.as_ref().is_some_and(|r| {
r.roles
.iter()
.any(|role| SUPPORT_ROLES.contains(&role.as_str()))
});
if !is_staff {
if requested_tenant.is_some_and(|t| t != c.tenant_id) {
tracing::warn!(sub = %c.sub, "tenant header from a non-support token ignored");
}
return claims_to_context(c).map(Authenticated::Tenant);
}
let staff = StaffAccess {
user_id: c.sub.clone(),
user_name: c.name.clone().or_else(|| c.preferred_username.clone()),
};
match requested_tenant {
Some(tenant_id) => {
// It becomes part of a database name: only a registry id passes.
if !is_registry_id(tenant_id) {
return Err("support tenant header is not a tenant id".to_string());
}
Ok(Authenticated::Tenant(TenantContext {
tenant_id: tenant_id.to_string(),
// Filled in, with the real status, once the agent has asked
// the registry; until then nothing may be written.
tenant_slug: String::new(),
org_roles: vec![OrgRole::ItAdmin],
products: Vec::new(),
plan: String::new(),
status: TenantStatus::Restricted,
user_id: staff.user_id.clone(),
user_name: staff.user_name.clone(),
staff: Some(staff),
api_key: None,
}))
}
// Staff who also belong to a tenant work in it like anyone else.
None if !c.tenant_id.is_empty() => claims_to_context(c).map(Authenticated::Tenant),
None => Ok(Authenticated::StaffWithoutTenant(staff)),
}
}
/// Whether `s` has the shape of a registry tenant id (a UUID).
fn is_registry_id(s: &str) -> bool {
s.len() == 36
&& s.char_indices().all(|(i, c)| match i {
8 | 13 | 18 | 23 => c == '-',
_ => c.is_ascii_hexdigit(),
})
}
/// Decode + verify a token against the cached JWKS (refreshing once on a
/// stale kid / signature) and return the raw claims.
async fn decode_claims(token: &str, state: &JwksState) -> Result<Claims, String> {
let header = decode_header(token).map_err(|e| format!("failed to decode JWT header: {e}"))?;
let kid = header
.kid
.clone()
.ok_or_else(|| "JWT missing kid header".to_string())?;
// First try against whatever's currently cached. If the kid isn't
// there or the signature doesn't verify, the cached JWKS is most
// likely stale (KC rotated keys) — refresh once and retry before
// giving up. Without this every key rotation produces a silent 401
// storm that only goes away when the agent restarts.
let jwks = fetch_or_get_jwks(state, false).await?;
match try_validate(token, &header, &kid, &jwks, state) {
Ok(c) => Ok(c),
Err(ValidationError::Permanent(e)) => Err(e),
Err(ValidationError::Stale(reason)) => {
tracing::info!(
kid = %kid,
reason = %reason,
"JWKS appears stale — forcing refresh and retrying"
);
let jwks = fetch_or_get_jwks(state, true).await?;
try_validate(token, &header, &kid, &jwks, state).map_err(|e| match e {
ValidationError::Stale(s) | ValidationError::Permanent(s) => s,
})
}
}
}
#[derive(Debug)]
enum ValidationError {
/// Refresh-eligible: cached JWKS may be stale.
Stale(String),
/// Refusing the token regardless of JWKS freshness.
Permanent(String),
}
fn try_validate(
token: &str,
header: &jsonwebtoken::Header,
kid: &str,
jwks: &JwkSet,
state: &JwksState,
) -> Result<Claims, ValidationError> {
let jwk = match jwks
.keys
.iter()
.find(|k| k.common.key_id.as_deref() == Some(kid))
{
Some(j) => j,
None => {
return Err(ValidationError::Stale(
"no matching key found in JWKS".to_string(),
))
}
};
let decoding_key = DecodingKey::from_jwk(jwk)
.map_err(|e| ValidationError::Permanent(format!("failed to create decoding key: {e}")))?;
let mut validation = Validation::new(header.alg);
validation.validate_exp = true;
match state.audience.as_deref() {
Some(aud) => validation.set_audience(&[aud]),
None => validation.validate_aud = false,
}
if let Some(iss) = state.issuer.as_deref() {
validation.set_issuer(&[iss]);
}
let data = match decode::<Claims>(token, &decoding_key, &validation) {
Ok(d) => d,
Err(e) => {
// Signature mismatch is the other refresh-eligible failure:
// the matching kid is present but the key bytes don't match.
// Everything else (expired, malformed, etc.) is permanent.
return Err(
if matches!(e.kind(), jsonwebtoken::errors::ErrorKind::InvalidSignature) {
ValidationError::Stale(format!("token validation failed: {e}"))
} else {
ValidationError::Permanent(format!("token validation failed: {e}"))
},
);
}
};
Ok(data.claims)
}
/// Map the decoded JWT payload into the platform-wide `TenantContext`.
/// Pulled out for unit testing — no I/O.
fn claims_to_context(c: Claims) -> Result<TenantContext, String> {
if c.tenant_id.is_empty() {
return Err("JWT is missing tenant_id claim".to_string());
}
let status = c.tenant_status.unwrap_or_else(|| {
tracing::warn!(
"JWT missing tenant_status claim for tenant {} — defaulting to Trial",
c.tenant_id
);
TenantStatus::Trial
});
Ok(TenantContext {
tenant_id: c.tenant_id,
tenant_slug: c.tenant_slug,
org_roles: c.org_roles.iter().map(|r| OrgRole::parse(r)).collect(),
products: c.products,
plan: c.plan,
status,
user_id: c.sub,
user_name: c.name.or(c.preferred_username),
staff: None,
api_key: None,
})
}
async fn fetch_or_get_jwks(state: &JwksState, force: bool) -> Result<JwkSet, String> {
if !force {
let cached = state.jwks.read().await;
if let Some(ref jwks) = *cached {
return Ok(jwks.clone());
}
}
// Hold the write lock across the fetch so concurrent refreshers
// don't all hammer Keycloak when keys rotate. If another writer
// already populated a fresh JWKS while we were waiting (and we
// weren't asked to force), use theirs.
let mut cached = state.jwks.write().await;
if !force {
if let Some(ref jwks) = *cached {
return Ok(jwks.clone());
}
}
// Bounded: the write lock is held across this call, so an unreachable
// Keycloak would otherwise stall every request waiting on the JWKS.
let resp = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(JWKS_FETCH_TIMEOUT_SECS))
.build()
.map_err(|e| format!("failed to build JWKS client: {e}"))?
.get(&state.jwks_url)
.send()
.await
.map_err(|e| format!("failed to fetch JWKS: {e}"))?;
let jwks: JwkSet = resp
.json()
.await
.map_err(|e| format!("failed to parse JWKS: {e}"))?;
*cached = Some(jwks.clone());
Ok(jwks)
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
fn base_claims() -> Claims {
Claims {
sub: "user-123".to_string(),
name: Some("Alice Acme".to_string()),
preferred_username: None,
tenant_id: "00000000-0000-0000-0000-000000000001".to_string(),
tenant_slug: "acme".to_string(),
org_roles: vec!["IT_ADMIN".to_string()],
products: vec!["compliance".to_string()],
plan: "professional".to_string(),
tenant_status: Some(TenantStatus::Active),
azp: Some("pruefwerk-dashboard-stage".to_string()),
realm_access: None,
}
}
const OTHER_TENANT: &str = "00000000-0000-0000-0000-000000000002";
fn staff_claims() -> Claims {
let mut c = base_claims();
c.tenant_id = String::new();
c.tenant_slug = String::new();
c.org_roles = Vec::new();
c.name = Some("Sharang Parnerkar".to_string());
c.realm_access = Some(RealmAccess {
roles: vec!["offline_access".to_string(), "SUPPORT_ENGINEER".to_string()],
});
c
}
#[test]
fn a_customer_cannot_switch_tenants_with_the_header() {
let outcome = authenticate(base_claims(), Some(OTHER_TENANT)).expect("should map");
let Authenticated::Tenant(ctx) = outcome else {
panic!("expected the customer's own tenant");
};
assert_eq!(ctx.tenant_id, "00000000-0000-0000-0000-000000000001");
assert_eq!(ctx.staff, None);
}
#[test]
fn support_opens_the_tenant_it_names_read_only_until_confirmed() {
let outcome = authenticate(staff_claims(), Some(OTHER_TENANT)).expect("should map");
let Authenticated::Tenant(ctx) = outcome else {
panic!("expected a tenant context");
};
assert_eq!(ctx.tenant_id, OTHER_TENANT);
assert_eq!(ctx.status, TenantStatus::Restricted);
assert_eq!(ctx.user_id, "user-123");
let staff = ctx.staff.expect("marked as support");
assert_eq!(staff.label(), "BreakPilot-Support (Sharang Parnerkar)");
}
#[test]
fn both_staff_roles_grant_support_access() {
for role in SUPPORT_ROLES {
let mut c = staff_claims();
c.realm_access = Some(RealmAccess {
roles: vec![role.to_string()],
});
assert!(matches!(
authenticate(c, Some(OTHER_TENANT)),
Ok(Authenticated::Tenant(TenantContext { staff: Some(_), .. }))
));
}
}
#[test]
fn support_without_a_chosen_tenant_gets_no_tenant() {
let outcome = authenticate(staff_claims(), None).expect("should map");
assert!(matches!(outcome, Authenticated::StaffWithoutTenant(_)));
}
#[test]
fn a_malformed_tenant_header_is_refused() {
for bad in [
"../admin",
"acme",
"00000000-0000-0000-0000-00000000000g",
"",
] {
assert!(authenticate(staff_claims(), Some(bad)).is_err(), "{bad}");
}
}
#[test]
fn claims_to_context_happy_path() {
let ctx = claims_to_context(base_claims()).expect("should map");
assert_eq!(ctx.tenant_id, "00000000-0000-0000-0000-000000000001");
assert_eq!(ctx.tenant_slug, "acme");
assert_eq!(ctx.org_roles, vec![OrgRole::ItAdmin]);
assert_eq!(ctx.products, vec!["compliance"]);
assert_eq!(ctx.plan, "professional");
assert_eq!(ctx.status, TenantStatus::Active);
assert_eq!(ctx.user_id, "user-123");
assert_eq!(ctx.user_name.as_deref(), Some("Alice Acme"));
}
#[test]
fn claims_to_context_rejects_missing_tenant_id() {
let mut c = base_claims();
c.tenant_id = "".to_string();
let err = claims_to_context(c).expect_err("should reject");
assert!(err.contains("tenant_id"));
}
#[test]
fn claims_to_context_defaults_status_when_missing() {
let mut c = base_claims();
c.tenant_status = None;
let ctx = claims_to_context(c).expect("should map");
assert_eq!(ctx.status, TenantStatus::Trial);
}
#[test]
fn claims_to_context_falls_back_to_preferred_username() {
let mut c = base_claims();
c.name = None;
c.preferred_username = Some("alice@acme.dev".to_string());
let ctx = claims_to_context(c).expect("should map");
assert_eq!(ctx.user_name.as_deref(), Some("alice@acme.dev"));
}
#[test]
fn claims_to_context_parses_multiple_roles() {
let mut c = base_claims();
c.org_roles = vec![
"IT_ADMIN".to_string(),
"CXO".to_string(),
"GARBAGE".to_string(),
];
let ctx = claims_to_context(c).expect("should map");
assert_eq!(
ctx.org_roles,
vec![OrgRole::ItAdmin, OrgRole::Cxo, OrgRole::Unknown]
);
}
#[test]
fn try_validate_returns_stale_when_kid_missing_from_jwks() {
// Empty JWKS — the kid we ask for can't possibly match. The error
// must classify as Stale so the caller refreshes JWKS and retries.
let jwks = JwkSet { keys: vec![] };
let header = jsonwebtoken::Header {
alg: jsonwebtoken::Algorithm::RS256,
kid: Some("kid-rotated-out".to_string()),
..Default::default()
};
let state = JwksState::new("http://unused/certs".to_string(), None, None);
let err = try_validate(
"ignored.token.value",
&header,
"kid-rotated-out",
&jwks,
&state,
)
.expect_err("should fail");
match err {
ValidationError::Stale(s) => assert!(s.contains("no matching key")),
ValidationError::Permanent(s) => panic!("must be Stale, got Permanent: {s}"),
}
}
#[test]
fn is_write_detects_methods() {
assert!(!is_write(&Method::GET));
assert!(!is_write(&Method::HEAD));
assert!(!is_write(&Method::OPTIONS));
assert!(is_write(&Method::POST));
assert!(is_write(&Method::PUT));
assert!(is_write(&Method::PATCH));
assert!(is_write(&Method::DELETE));
}
}