From ae8761c15ca99582079b1dd522f40738fc8c2f23 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Tue, 13 Oct 2026 23:26:05 +0200 Subject: [PATCH] =?UTF-8?q?feat(api):=20the=20customer=20API=20accepts=20p?= =?UTF-8?q?ortal-issued=20API=20keys=20(bp=5F=E2=80=A6)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Step 5 of tenant-registry ADR 0001. A `Bearer bp_…` token is verified with the registry (pruefwerk-svc) and becomes a tenant context carrying the key; every other bearer goes through the JWT path unchanged. - Verdicts, valid and invalid, are cached for 60 s by the key's SHA-256; an unreachable registry with no fresh verdict means 503. The Werkbank runner shares the same cached verify. - Tenant, scopes and ladder status come only from the verify answer; the support header is never read for a key, and a key holds no org role. - role_gate gets a method + route -> scope table; every other route answers 403 scope_missing. x.write implies x.read. Legacy keys (no scopes) get the read scopes only. - The entitlement check is skipped for keys (verify already intersects scopes with entitlements). Key writes are audited like support writes, as apikey: with the holder and X-BP-Actor as on_behalf_of. - Guide page docs/guide/api-keys.md. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- compliance-agent/src/api/api_key_gate.rs | 243 +++++++++++++++++ .../src/api/handlers/manual_findings.rs | 1 + compliance-agent/src/api/handlers/projects.rs | 1 + compliance-agent/src/api/mod.rs | 1 + compliance-agent/src/api/role_gate.rs | 91 ++++++- .../src/api/role_gate/router_tests.rs | 158 ++++++++++- compliance-agent/src/api/server.rs | 50 ++-- compliance-agent/src/registry.rs | 165 +++++++++++- compliance-agent/tests/api_key_access.rs | 253 ++++++++++++++++++ compliance-agent/tests/mcp_servers.rs | 1 + compliance-agent/tests/member_blocked.rs | 1 + compliance-agent/tests/tenant_isolation.rs | 1 + .../tests/tenant_status_middleware.rs | 1 + compliance-core/src/auth.rs | 21 +- compliance-core/src/db.rs | 1 + compliance-core/src/lib.rs | 2 +- compliance-core/src/tenant.rs | 68 +++++ compliance-core/src/tenant_ctx.rs | 1 + docs/.vitepress/config.mts | 1 + docs/guide/api-keys.md | 49 ++++ 20 files changed, 1080 insertions(+), 30 deletions(-) create mode 100644 compliance-agent/src/api/api_key_gate.rs create mode 100644 compliance-agent/tests/api_key_access.rs create mode 100644 docs/guide/api-keys.md diff --git a/compliance-agent/src/api/api_key_gate.rs b/compliance-agent/src/api/api_key_gate.rs new file mode 100644 index 0000000..df618d3 --- /dev/null +++ b/compliance-agent/src/api/api_key_gate.rs @@ -0,0 +1,243 @@ +//! Portal-issued API keys on the customer API (tenant-registry ADR 0001, §4). +//! +//! A `Bearer bp_…` token is an API key; every other bearer goes on to the +//! JWT middleware unchanged. The key is verified with the registry (answers +//! cached for [`crate::registry::API_KEY_TTL`]) and becomes a +//! [`TenantContext`] carrying [`ApiKeyAccess`]: +//! +//! * the tenant, scopes and ladder status come only from the registry's +//! answer; no header, path or body can name another tenant, and the support +//! header is never read; +//! * the key holds no org role, so `role_gate` judges it by its scopes; +//! * `X-BP-Actor` is recorded as who the caller acts for, never trusted. +//! +//! `401 {"error": "invalid_api_key"}` for a key the registry rejects, `503` +//! when the registry cannot answer and no fresh verdict is cached. + +use std::sync::Arc; + +use axum::{ + extract::{Request, State}, + http::{header, StatusCode}, + middleware::Next, + response::{IntoResponse, Response}, + Json, +}; +use compliance_core::auth::bypasses_customer_auth; +use compliance_core::{ApiKeyAccess, TenantContext, TenantStatus}; + +use super::role_gate::LEGACY_SCOPES; +use crate::agent::ComplianceAgent; +use crate::registry::ApiKeyVerify; + +/// Every portal-issued API key starts with this. +pub const API_KEY_PREFIX: &str = "bp_"; + +/// The header a caller (e.g. a Werkmeister block) names the person it acts +/// for in. Informational: logged and audited, never used to authorise. +pub const ACTOR_HEADER: &str = "x-bp-actor"; + +/// The longest `X-BP-Actor` value kept; the rest is cut off. +const ACTOR_MAX_CHARS: usize = 120; + +/// The JSON `error` for a key the registry does not accept. +pub const INVALID_API_KEY: &str = "invalid_api_key"; + +/// The middleware. Mounted outside the JWT middleware, which lets through a +/// request this one has given a key context. +pub async fn require_api_key( + State(agent): State>, + mut request: Request, + next: Next, +) -> Response { + if bypasses_customer_auth(request.uri().path()) { + return next.run(request).await; + } + let Some(key) = presented_key(&request) else { + return next.run(request).await; + }; + let Some(registry) = agent.registry.as_ref() else { + return invalid_key(); + }; + let verdict = match registry.verify_api_key(&key).await { + Ok(v) => v, + Err(e) => { + tracing::error!("api-key verify unavailable: {e}"); + return ( + StatusCode::SERVICE_UNAVAILABLE, + Json(serde_json::json!({ "error": "api_key_verify_unavailable" })), + ) + .into_response(); + } + }; + let on_behalf_of = request + .headers() + .get(ACTOR_HEADER) + .and_then(|v| v.to_str().ok()) + .and_then(clean_actor); + let Some(ctx) = key_context(verdict, registry.product(), on_behalf_of) else { + return invalid_key(); + }; + request.extensions_mut().insert(ctx); + next.run(request).await +} + +/// The `bp_…` token of an `Authorization: Bearer` header, if it is one. +fn presented_key(request: &Request) -> Option { + request + .headers() + .get(header::AUTHORIZATION)? + .to_str() + .ok()? + .strip_prefix("Bearer ") + .map(str::trim) + .filter(|t| t.starts_with(API_KEY_PREFIX)) + .map(str::to_owned) +} + +fn invalid_key() -> Response { + ( + StatusCode::UNAUTHORIZED, + Json(serde_json::json!({ "error": INVALID_API_KEY })), + ) + .into_response() +} + +/// The context for a verified key, or `None` if the registry rejected it. +/// `product` is this product's registry key, which a legacy key must name +/// (or name none) to get [`LEGACY_SCOPES`]. +fn key_context( + v: ApiKeyVerify, + product: &str, + on_behalf_of: Option, +) -> Option { + if !v.valid || v.tenant_id.is_empty() { + return None; + } + let scopes = + if v.legacy && v.scopes.is_empty() && (v.product.is_empty() || v.product == product) { + LEGACY_SCOPES.iter().map(|s| (*s).to_string()).collect() + } else { + v.scopes + }; + let key_id = if v.key_id.is_empty() { + "unknown".to_string() + } else { + v.key_id + }; + Some(TenantContext { + tenant_id: v.tenant_id, + tenant_slug: String::new(), + org_roles: Vec::new(), + products: Vec::new(), + plan: String::new(), + // An older registry sends no status: read-only until it does. + status: TenantStatus::parse(&v.tenant_status).unwrap_or(TenantStatus::Restricted), + user_id: format!("apikey:{key_id}"), + user_name: v.holder.clone().filter(|h| !h.trim().is_empty()), + staff: None, + api_key: Some(Box::new(ApiKeyAccess { + key_id, + kind: v.kind, + holder: v.holder, + scopes, + legacy: v.legacy, + on_behalf_of, + })), + }) +} + +/// An `X-BP-Actor` value fit for a log line: no control characters, at most +/// [`ACTOR_MAX_CHARS`], `None` if nothing is left. +fn clean_actor(raw: &str) -> Option { + let cleaned: String = raw + .chars() + .filter(|c| !c.is_control()) + .take(ACTOR_MAX_CHARS) + .collect(); + let trimmed = cleaned.trim(); + (!trimmed.is_empty()).then(|| trimmed.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn verdict() -> ApiKeyVerify { + serde_json::from_value(serde_json::json!({ + "valid": true, + "tenant_id": "11111111-1111-1111-1111-111111111111", + "product": "pruefwerk", + "scopes": ["pruefwerk:findings.write"], + "key_id": "k1", + "kind": "service", + "holder": "CI", + "tenant_status": "active", + "legacy": false, + })) + .expect("verdict") + } + + #[test] + fn a_valid_key_becomes_a_roleless_context_of_its_tenant() { + let ctx = key_context(verdict(), "pruefwerk", Some("someone".into())).expect("ctx"); + assert_eq!(ctx.tenant_id, "11111111-1111-1111-1111-111111111111"); + assert_eq!(ctx.user_id, "apikey:k1"); + assert_eq!(ctx.actor_label(), "CI"); + assert!(ctx.org_roles.is_empty()); + assert_eq!(ctx.status, TenantStatus::Active); + let key = ctx.api_key.expect("key"); + assert_eq!(key.scopes, ["pruefwerk:findings.write"]); + assert_eq!(key.on_behalf_of.as_deref(), Some("someone")); + } + + #[test] + fn a_rejected_or_tenantless_key_gets_no_context() { + let mut v = verdict(); + v.valid = false; + assert!(key_context(v, "pruefwerk", None).is_none()); + let mut v = verdict(); + v.tenant_id.clear(); + assert!(key_context(v, "pruefwerk", None).is_none()); + } + + #[test] + fn a_legacy_key_reads_only_and_only_for_this_product() { + let mut v = verdict(); + v.legacy = true; + v.scopes.clear(); + let key = key_context(v.clone(), "pruefwerk", None) + .and_then(|c| c.api_key) + .expect("key"); + assert_eq!(key.scopes, LEGACY_SCOPES); + v.product = "werkbank".into(); + let key = key_context(v, "pruefwerk", None) + .and_then(|c| c.api_key) + .expect("key"); + assert!(key.scopes.is_empty()); + } + + #[test] + fn an_older_registry_answer_is_read_only_and_anonymous() { + let v: ApiKeyVerify = serde_json::from_value(serde_json::json!({ + "valid": true, + "tenant_id": "t", + "product": "pruefwerk", + "scopes": ["pruefwerk:findings.read"], + })) + .expect("old shape decodes"); + let ctx = key_context(v, "pruefwerk", None).expect("ctx"); + assert_eq!(ctx.status, TenantStatus::Restricted); + assert_eq!(ctx.user_id, "apikey:unknown"); + } + + #[test] + fn the_actor_header_is_cleaned_and_capped() { + assert_eq!(clean_actor(" a\nb\u{7}c "), Some("abc".into())); + assert_eq!(clean_actor(" \t "), None); + assert_eq!( + clean_actor(&"x".repeat(500)).map(|s| s.len()), + Some(ACTOR_MAX_CHARS) + ); + } +} diff --git a/compliance-agent/src/api/handlers/manual_findings.rs b/compliance-agent/src/api/handlers/manual_findings.rs index e0d4a17..72dc261 100644 --- a/compliance-agent/src/api/handlers/manual_findings.rs +++ b/compliance-agent/src/api/handlers/manual_findings.rs @@ -234,6 +234,7 @@ mod tests { user_id: "u".into(), user_name: None, staff: None, + api_key: None, }) } diff --git a/compliance-agent/src/api/handlers/projects.rs b/compliance-agent/src/api/handlers/projects.rs index 26019c2..e643e67 100644 --- a/compliance-agent/src/api/handlers/projects.rs +++ b/compliance-agent/src/api/handlers/projects.rs @@ -165,6 +165,7 @@ mod tests { user_id: "u-1".to_string(), user_name: Some("Sharang".to_string()), }), + api_key: None, } } diff --git a/compliance-agent/src/api/mod.rs b/compliance-agent/src/api/mod.rs index c0dc57e..be386da 100644 --- a/compliance-agent/src/api/mod.rs +++ b/compliance-agent/src/api/mod.rs @@ -1,3 +1,4 @@ +pub mod api_key_gate; pub mod handlers; pub mod role_gate; pub mod routes; diff --git a/compliance-agent/src/api/role_gate.rs b/compliance-agent/src/api/role_gate.rs index ac1b842..604ab05 100644 --- a/compliance-agent/src/api/role_gate.rs +++ b/compliance-agent/src/api/role_gate.rs @@ -17,6 +17,10 @@ //! check, and support staff who have not chosen a tenant yet. //! //! Handlers may still be stricter (manual findings stay `IT_ADMIN`-only). +//! +//! 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}, @@ -25,11 +29,78 @@ use axum::{ response::{IntoResponse, Response}, Json, }; -use compliance_core::{ProductAccess, TenantContext}; +use compliance_core::{ApiKeyAccess, 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/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. @@ -76,6 +147,24 @@ pub async fn require_org_role(request: Request, next: Next) -> Response { .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; }; diff --git a/compliance-agent/src/api/role_gate/router_tests.rs b/compliance-agent/src/api/role_gate/router_tests.rs index fd6626f..961d588 100644 --- a/compliance-agent/src/api/role_gate/router_tests.rs +++ b/compliance-agent/src/api/role_gate/router_tests.rs @@ -4,7 +4,7 @@ //! these tests, so a request the gate lets through fails later (500, missing //! extension); what is checked is only whether the gate refused it. -use super::{require_org_role, READ_ONLY_POSTS}; +use super::{require_org_role, KEY_SCOPES, LEGACY_SCOPES, READ_ONLY_POSTS}; use crate::api::routes::build_router; use axum::{ body::{to_bytes, Body}, @@ -13,7 +13,7 @@ use axum::{ middleware::{from_fn, Next}, Router, }; -use compliance_core::{OrgRole, StaffAccess, TenantContext, TenantStatus}; +use compliance_core::{ApiKeyAccess, OrgRole, StaffAccess, TenantContext, TenantStatus}; use tower::ServiceExt; /// Who is calling. @@ -29,6 +29,8 @@ enum Caller { Staff, /// A service / machine client: no tenant context reaches the gate. Service, + /// A portal-issued API key with these scopes (no org roles). + Key(&'static [&'static str]), } fn ctx(caller: Caller) -> Option { @@ -38,7 +40,7 @@ fn ctx(caller: Caller) -> Option { Caller::Cxo => vec![OrgRole::Cxo], Caller::Legal => vec![OrgRole::Legal], Caller::Finance => vec![OrgRole::Finance], - Caller::NoRoles | Caller::Staff => vec![], + Caller::NoRoles | Caller::Staff | Caller::Key(_) => vec![], Caller::Service => return None, }; Some(TenantContext { @@ -54,6 +56,17 @@ fn ctx(caller: Caller) -> Option { user_id: "u-1".to_string(), user_name: None, }), + api_key: match caller { + Caller::Key(scopes) => Some(Box::new(ApiKeyAccess { + key_id: "k-1".to_string(), + kind: "service".to_string(), + holder: None, + scopes: scopes.iter().map(|s| (*s).to_string()).collect(), + legacy: false, + on_behalf_of: None, + })), + _ => None, + }, }) } @@ -76,6 +89,11 @@ fn router(caller: Caller) -> Router { /// Whether the gate refused the request (403 `forbidden_role`). async fn refused(caller: Caller, method: Method, path: &str) -> bool { + refusal(caller, method, path).await.as_deref() == Some("forbidden_role") +} + +/// The gate's `error`, if it refused the request. +async fn refusal(caller: Caller, method: Method, path: &str) -> Option { let req = Request::builder() .method(method) .uri(path) @@ -84,11 +102,11 @@ async fn refused(caller: Caller, method: Method, path: &str) -> bool { .expect("request"); let resp = router(caller).oneshot(req).await.expect("oneshot"); if resp.status() != StatusCode::FORBIDDEN { - return false; + return None; } let body = to_bytes(resp.into_body(), 64 * 1024).await.expect("body"); let json: serde_json::Value = serde_json::from_slice(&body).unwrap_or_default(); - json["error"] == "forbidden_role" + json["error"].as_str().map(str::to_owned) } const ID: &str = "65f000000000000000000001"; @@ -211,3 +229,133 @@ async fn a_refusal_says_which_access_the_role_has() { serde_json::json!({ "error": "forbidden_role", "access": "none" }) ); } + +/// Every scope of the key table. +const ALL_SCOPES: &[&str] = &[ + "pruefwerk:findings.write", + "pruefwerk:sbom.read", + "pruefwerk:scans.read", + "pruefwerk:scans.run", + "pruefwerk:enisa.read", +]; + +fn concrete(template: &str) -> String { + template.replace("{id}", ID) +} + +#[tokio::test] +async fn every_key_route_is_real_and_needs_its_scope() { + for (method, template, scope) in KEY_SCOPES { + let path = concrete(template); + // A template that matches no route would refuse every key. + assert_eq!( + refusal(Caller::Key(ALL_SCOPES), method.clone(), &path).await, + None, + "{method} {template}" + ); + let lacking_sets: [&'static [&'static str]; 2] = [&[], &["werkbank:runner"]]; + for lacking in lacking_sets { + assert_eq!( + refusal(Caller::Key(lacking), method.clone(), &path) + .await + .as_deref(), + Some("scope_missing"), + "{method} {template} {lacking:?}" + ); + } + // Another row's scope does not open this one. + let other = KEY_SCOPES + .iter() + .map(|(_, _, s)| *s) + .find(|s| s.split('.').next() != scope.split('.').next()) + .expect("the table has several scope families"); + let other = ALL_SCOPES + .iter() + .find(|s| s.split('.').next() == other.split('.').next()) + .expect("every family is in ALL_SCOPES"); + assert_eq!( + refusal( + Caller::Key(std::slice::from_ref(other)), + method.clone(), + &path + ) + .await + .as_deref(), + Some("scope_missing"), + "{method} {template} {other}" + ); + } +} + +#[tokio::test] +async fn a_write_scope_grants_the_read_but_not_the_reverse() { + let path = format!("/api/v1/findings/{ID}"); + let write = Caller::Key(&["pruefwerk:findings.write"]); + let read = Caller::Key(&["pruefwerk:findings.read"]); + assert_eq!(refusal(write, Method::GET, &path).await, None); + assert_eq!(refusal(read, Method::GET, &path).await, None); + assert_eq!( + refusal(read, Method::PATCH, &format!("{path}/status")) + .await + .as_deref(), + Some("scope_missing") + ); + // `scans.run` is not a write of `scans.read`. + assert_eq!( + refusal( + Caller::Key(&["pruefwerk:scans.run"]), + Method::GET, + "/api/v1/scan-runs" + ) + .await + .as_deref(), + Some("scope_missing") + ); +} + +#[tokio::test] +async fn a_key_reaches_nothing_outside_the_table() { + let in_table = |m: &Method, p: &str| { + KEY_SCOPES + .iter() + .any(|(km, t, _)| km == m && concrete(t) == p) + }; + for (method, path, _) in routes() { + if in_table(&method, &path) { + continue; + } + assert_eq!( + refusal(Caller::Key(ALL_SCOPES), method.clone(), &path) + .await + .as_deref(), + Some("scope_missing"), + "{method} {path}" + ); + } + // A listed route with another method is not listed. + assert_eq!( + refusal( + Caller::Key(ALL_SCOPES), + Method::DELETE, + &format!("/api/v1/findings/{ID}") + ) + .await + .as_deref(), + Some("scope_missing") + ); +} + +#[tokio::test] +async fn a_legacy_key_reads_but_never_writes_or_runs() { + let legacy = Caller::Key(LEGACY_SCOPES); + for (method, template, scope) in KEY_SCOPES { + let read = scope.ends_with(".read"); + assert_eq!( + refusal(legacy, method.clone(), &concrete(template)) + .await + .is_none(), + read, + "{method} {template}" + ); + } +} diff --git a/compliance-agent/src/api/server.rs b/compliance-agent/src/api/server.rs index d851d3f..78f551a 100644 --- a/compliance-agent/src/api/server.rs +++ b/compliance-agent/src/api/server.rs @@ -53,6 +53,7 @@ pub async fn inject_dev_tenant(mut request: Request, next: Next) -> Response { user_id: "dev-user".to_string(), user_name: None, staff: None, + api_key: None, }; request.extensions_mut().insert(ctx); } @@ -114,6 +115,11 @@ pub async fn require_entitlement( let Some(ctx) = request.extensions().get::().cloned() else { return next.run(request).await; }; + // An API key: the registry's verify answer already intersected its + // scopes with the tenant's entitlements and carried the ladder status. + if ctx.api_key.is_some() { + return next.run(request).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. @@ -182,11 +188,11 @@ fn confirmed_support_context( ctx } -/// Record every change BreakPilot support makes in a tenant, refused ones -/// included, in the platform's audit log. Reads are not logged one by one; -/// opening a tenant is (`POST /api/v1/support/session`). Background and -/// best-effort: an unreachable registry never blocks support. -pub async fn audit_support_writes( +/// Record every change BreakPilot support or an API key makes in a tenant, +/// refused ones included, in the platform's audit log. Reads are not logged +/// one by one; opening a tenant is (`POST /api/v1/support/session`). +/// Background and best-effort: an unreachable registry never blocks either. +pub async fn audit_delegated_writes( State(agent): State>, request: Request, next: Next, @@ -194,7 +200,7 @@ pub async fn audit_support_writes( let staff_ctx = request .extensions() .get::() - .filter(|c| c.staff.is_some()) + .filter(|c| c.staff.is_some() || c.api_key.is_some()) .cloned(); let method = request.method().clone(); let path = request.uri().path().to_string(); @@ -205,26 +211,32 @@ pub async fn audit_support_writes( if matches!(method, Method::GET | Method::HEAD | Method::OPTIONS) { return response; } - let entry = support_audit_entry(&ctx, method.as_str(), &path, response.status().as_u16()); + let entry = delegated_audit_entry(&ctx, method.as_str(), &path, response.status().as_u16()); tokio::spawn(async move { if let Err(e) = registry.append_audit(&entry).await { - tracing::warn!(tenant_id = %entry.tenant_id, "support audit not recorded: {e}"); + tracing::warn!(tenant_id = %entry.tenant_id, "write audit not recorded: {e}"); } }); response } -/// The audit entry for a support request. The path names the resource; the -/// query and body are left out, as they may carry customer data. -fn support_audit_entry( +/// The audit entry for a support or API-key request. The path names the +/// resource; the query and body are left out, as they may carry customer +/// data. +fn delegated_audit_entry( ctx: &TenantContext, method: &str, path: &str, status: u16, ) -> crate::registry::AuditEntry { + let action = if ctx.api_key.is_some() { + "pruefwerk.api_key_write" + } else { + "pruefwerk.support_access" + }; crate::registry::AuditEntry::by( ctx, - "pruefwerk.support_access", + action, serde_json::json!({ "method": method, "path": path, "status": status }), ) } @@ -433,13 +445,14 @@ pub async fn start_api_server( registry = agent.registry.is_some(), "Keycloak JWT auth enabled" ); - // Layers execute outermost-first: Extension(jwks) → JWT → org roles - // → entitlement (registry) → support audit → status ladder → handlers. + // Layers execute outermost-first: Extension(jwks) → API key → JWT → + // org roles / key scopes → entitlement (registry) → support and key + // audit → status ladder → handlers. app = app .layer(middleware::from_fn(require_tenant_status)) .layer(middleware::from_fn_with_state( shared.clone(), - audit_support_writes, + audit_delegated_writes, )) .layer(middleware::from_fn_with_state( shared.clone(), @@ -447,6 +460,10 @@ pub async fn start_api_server( )) .layer(middleware::from_fn(role_gate::require_org_role)) .layer(middleware::from_fn(require_jwt_auth)) + .layer(middleware::from_fn_with_state( + shared.clone(), + super::api_key_gate::require_api_key, + )) .layer(Extension(jwks_state)); } else if agent.config.app_env.is_hardened() { // `validate_deployment` rejects this configuration at load time; this @@ -502,6 +519,7 @@ mod support_tests { user_id: "s-1".to_string(), user_name: Some("Sharang".to_string()), }), + api_key: None, } } @@ -530,7 +548,7 @@ mod support_tests { #[test] fn a_support_change_is_audited_without_its_content() { let entry = - support_audit_entry(&support_ctx(), "PATCH", "/api/v1/findings/abc/status", 200); + delegated_audit_entry(&support_ctx(), "PATCH", "/api/v1/findings/abc/status", 200); assert_eq!(entry.tenant_id, "00000000-0000-0000-0000-000000000002"); assert_eq!(entry.action, "pruefwerk.support_access"); assert_eq!(entry.actor_id, "s-1"); diff --git a/compliance-agent/src/registry.rs b/compliance-agent/src/registry.rs index b3b3324..abf573a 100644 --- a/compliance-agent/src/registry.rs +++ b/compliance-agent/src/registry.rs @@ -24,6 +24,10 @@ use compliance_core::AgentConfig; /// How long an entitlement answer is trusted before it is re-fetched. pub const ENTITLEMENT_TTL: Duration = Duration::from_secs(60); + +/// How long an API-key verdict is reused. A revoked key therefore keeps +/// working for up to this long; past it, an unreachable registry means `503`. +pub const API_KEY_TTL: Duration = Duration::from_secs(60); /// Refresh the service token this long before it expires. const TOKEN_MARGIN: Duration = Duration::from_secs(30); /// Upper bound for one registry or Keycloak token request. Without it a hung @@ -77,7 +81,7 @@ pub struct AuditEntry { pub product: String, /// What happened, e.g. `pruefwerk.support_access`. pub action: String, - /// `user`, or `staff` for BreakPilot support. + /// `user`, `staff` for BreakPilot support, or `apikey`. pub actor_type: String, pub actor_id: String, pub actor_name: String, @@ -91,18 +95,38 @@ pub struct AuditEntry { pub metadata: serde_json::Value, } +/// The cache key for an API key: its SHA-256, hex. The key itself is never +/// held longer than the request. +fn key_digest(key: &str) -> String { + use sha2::{Digest, Sha256}; + hex::encode(Sha256::digest(key.as_bytes())) +} + impl AuditEntry { /// An entry about `ctx`'s requester, with no object yet. pub fn by( ctx: &compliance_core::TenantContext, action: &str, - metadata: serde_json::Value, + mut metadata: serde_json::Value, ) -> Self { + let actor_type = match (&ctx.staff, &ctx.api_key) { + (Some(_), _) => "staff", + (None, Some(key)) => { + // Who the caller says it acts for: informational only. + if let (Some(on_behalf_of), Some(map)) = + (&key.on_behalf_of, metadata.as_object_mut()) + { + map.insert("on_behalf_of".to_string(), on_behalf_of.clone().into()); + } + "apikey" + } + (None, None) => "user", + }; Self { tenant_id: ctx.tenant_id.clone(), product: "pruefwerk".to_string(), action: action.to_string(), - actor_type: if ctx.staff.is_some() { "staff" } else { "user" }.to_string(), + actor_type: actor_type.to_string(), actor_id: ctx.user_id.clone(), actor_name: ctx.actor_label(), target_type: String::new(), @@ -122,6 +146,9 @@ impl AuditEntry { } } +/// The registry's answer for a portal-issued API key (tenant-registry ADR +/// 0001). Everything but `valid` defaults, so an older registry that sends +/// only `valid`, `tenant_id`, `product` and `scopes` still decodes. #[derive(Debug, Clone, Deserialize)] pub struct ApiKeyVerify { pub valid: bool, @@ -129,8 +156,26 @@ pub struct ApiKeyVerify { pub tenant_id: String, #[serde(default)] pub product: String, + /// Already intersected with the tenant's entitlements; empty for a + /// halted or archived tenant. #[serde(default)] pub scopes: Vec, + #[serde(default)] + pub key_id: String, + /// `personal` or `service`, as the registry labels it. + #[serde(default)] + pub kind: String, + /// Who the key was issued to, for the history and the audit log. + #[serde(default)] + pub holder: Option, + #[serde(default)] + pub expires_at: Option, + /// The tenant's ladder status (`active`, `restricted`, ...). + #[serde(default)] + pub tenant_status: String, + /// A key issued before scopes existed: it carries none. + #[serde(default)] + pub legacy: bool, } #[derive(Debug, Clone, Serialize)] @@ -161,6 +206,9 @@ pub struct RegistryClient { cache: DashMap, /// Each tenant's projects, for [`ENTITLEMENT_TTL`]. projects: DashMap)>, + /// API-key verdicts, valid and invalid, keyed by the key's SHA-256 (never + /// the key itself), for [`API_KEY_TTL`]. + api_keys: DashMap, } impl std::fmt::Debug for RegistryClient { @@ -203,6 +251,7 @@ impl RegistryClient { token: Mutex::new(None), cache: DashMap::new(), projects: DashMap::new(), + api_keys: DashMap::new(), })) } @@ -445,14 +494,34 @@ impl RegistryClient { Ok(page.items) } - /// Verify a portal-issued API key (`bp_…`). + /// Verify a portal-issued API key (`bp_…`), valid or not, reusing a + /// verdict younger than [`API_KEY_TTL`]. + /// + /// # Errors + /// + /// The registry could not answer and no fresh verdict is cached. The + /// message never contains the key. pub async fn verify_api_key(&self, key: &str) -> Result { + let digest = key_digest(key); + if let Some(entry) = self.api_keys.get(&digest) { + if entry.0.elapsed() < API_KEY_TTL { + return Ok(entry.1.clone()); + } + } + let verdict = self.fetch_api_key_verdict(key).await?; + self.api_keys + .insert(digest, (Instant::now(), verdict.clone())); + Ok(verdict) + } + + async fn fetch_api_key_verdict(&self, key: &str) -> Result { let resp = self .request(reqwest::Method::POST, "/v1/internal/api-keys/verify") .await? .json(&serde_json::json!({ "key": key })) .send() .await + // reqwest's error names the URL, never the body. .map_err(|e| format!("api-key verify failed: {e}"))?; if !resp.status().is_success() { return Err(format!("api-key verify returned {}", resp.status())); @@ -574,6 +643,7 @@ mod tests { token: Mutex::new(None), cache: DashMap::new(), projects: DashMap::new(), + api_keys: DashMap::new(), }; let started = Instant::now(); @@ -586,4 +656,91 @@ mod tests { started.elapsed() ); } + + /// A registry whose verify endpoint counts its calls and can be taken + /// down (500). Every key is valid for tenant `t`. + async fn verify_registry() -> ( + RegistryClient, + Arc, + Arc, + ) { + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + let calls = Arc::new(AtomicUsize::new(0)); + let down = Arc::new(AtomicBool::new(false)); + let (c, d) = (calls.clone(), down.clone()); + let app = axum::Router::new().route( + "/v1/internal/api-keys/verify", + axum::routing::post(move |axum::Json(body): axum::Json| { + let (c, d) = (c.clone(), d.clone()); + async move { + c.fetch_add(1, Ordering::SeqCst); + if d.load(Ordering::SeqCst) { + return Err(axum::http::StatusCode::INTERNAL_SERVER_ERROR); + } + let valid = body["key"] != "bp_revoked"; + Ok(axum::Json(serde_json::json!({ + "valid": valid, + "tenant_id": "t", + "scopes": ["pruefwerk:findings.read"], + }))) + } + }), + ); + 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() }); + let client = RegistryClient { + base_url: format!("http://{addr}"), + product: "pruefwerk".into(), + http: reqwest::Client::new(), + token_url: None, + client_id: None, + client_secret: None, + token: Mutex::new(None), + cache: DashMap::new(), + projects: DashMap::new(), + api_keys: DashMap::new(), + }; + (client, calls, down) + } + + #[tokio::test] + async fn api_key_verdicts_are_reused_valid_or_not() { + use std::sync::atomic::Ordering; + let (client, calls, _) = verify_registry().await; + for _ in 0..3 { + assert!(client.verify_api_key("bp_good").await.unwrap().valid); + assert!(!client.verify_api_key("bp_revoked").await.unwrap().valid); + } + assert_eq!(calls.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn an_unreachable_registry_is_bridged_only_by_a_fresh_verdict() { + use std::sync::atomic::Ordering; + let (client, _, down) = verify_registry().await; + client.verify_api_key("bp_good").await.unwrap(); + down.store(true, Ordering::SeqCst); + // Warm: served from the cache. + assert!(client.verify_api_key("bp_good").await.unwrap().valid); + // Cold: nothing to fall back on. + assert!(client.verify_api_key("bp_other").await.is_err()); + // Expired: as cold, so a revocation is never outlived by an outage. + for mut entry in client.api_keys.iter_mut() { + entry.0 = Instant::now() + .checked_sub(API_KEY_TTL + Duration::from_secs(1)) + .unwrap(); + } + let err = client.verify_api_key("bp_good").await.unwrap_err(); + assert!(!err.contains("bp_good"), "{err}"); + } + + #[tokio::test] + async fn the_cache_holds_a_digest_never_the_key() { + let (client, _, _) = verify_registry().await; + client.verify_api_key("bp_good").await.unwrap(); + assert!(!client.api_keys.contains_key("bp_good")); + assert!(client.api_keys.contains_key(&key_digest("bp_good"))); + assert!(client.api_keys.iter().all(|e| !e.key().contains("bp_"))); + } } diff --git a/compliance-agent/tests/api_key_access.rs b/compliance-agent/tests/api_key_access.rs new file mode 100644 index 0000000..29b5976 --- /dev/null +++ b/compliance-agent/tests/api_key_access.rs @@ -0,0 +1,253 @@ +//! Portal-issued API keys on the customer API (tenant-registry ADR 0001): +//! the key middleware, the JWT middleware, the entitlement gate, the write +//! audit and the status ladder, in the server's order, against a fake tenant +//! registry and a live Mongo (for the agent itself); skips cleanly without +//! one. The route → scope table is covered in `role_gate`'s router tests. + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +mod common; + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use axum::body::Body; +use axum::extract::{Request, State}; +use axum::http::StatusCode; +use axum::middleware::{from_fn, from_fn_with_state}; +use axum::routing::{get, post}; +use axum::{Extension, Json, Router}; +use tower::ServiceExt; + +use compliance_agent::agent::ComplianceAgent; +use compliance_agent::api::api_key_gate::require_api_key; +use compliance_agent::api::server::{audit_delegated_writes, require_entitlement}; +use compliance_agent::database::DatabasePool; +use compliance_core::auth::{require_jwt_auth, require_tenant_status, JwksState}; +use compliance_core::{TenantContext, SUPPORT_TENANT_HEADER}; + +use common::dev_config; + +/// What the fake registry was asked: the path of every call, and the bodies +/// of audit entries. +#[derive(Default)] +struct Seen { + paths: Vec, + audits: Vec, +} + +type Shared = Arc>; + +const TENANT: &str = "11111111-1111-1111-1111-111111111111"; + +/// The registry's verify answer for `key`, or `None` to fail with 500. +fn verdict(key: &str) -> Option { + let status = match key { + "bp_good" => "active", + "bp_restricted" => "restricted", + "bp_revoked" => return Some(serde_json::json!({ "valid": false })), + _ => return None, + }; + Some(serde_json::json!({ + "valid": true, + "tenant_id": TENANT, + "product": "pruefwerk", + "scopes": ["pruefwerk:findings.write"], + "key_id": "k-1", + "kind": "service", + "holder": "CI pipeline", + "tenant_status": status, + "legacy": false, + })) +} + +async fn fake_registry(seen: Shared) -> String { + let app = Router::new() + .route( + "/v1/internal/api-keys/verify", + post( + |State(seen): State, Json(body): Json| async move { + seen.lock().unwrap().paths.push("verify".into()); + verdict(body["key"].as_str().unwrap_or_default()) + .map(Json) + .ok_or(StatusCode::INTERNAL_SERVER_ERROR) + }, + ), + ) + .route( + "/v1/internal/entitlements/check", + post(|State(seen): State| async move { + seen.lock().unwrap().paths.push("entitlement".into()); + Json(serde_json::json!({ "allowed": true, "status": "active" })) + }), + ) + .route( + "/v1/audit", + post( + |State(seen): State, Json(body): Json| async move { + seen.lock().unwrap().audits.push(body); + StatusCode::CREATED + }, + ), + ) + .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}") +} + +/// An agent whose registry is `registry`, or `None` without Mongo. +async fn agent(registry: &str) -> Option> { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let db_name = format!("key_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]); + let Ok(pool) = DatabasePool::connect(&uri, &db_name).await else { + eprintln!("SKIP api_key_access: 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))) +} + +/// `/r` answers the tenant the request runs in, for reads and writes. +fn app(agent: Arc) -> Router { + let tenant = |Extension(ctx): Extension| async move { ctx.tenant_id }; + // Same order as the server, without the role gate. + Router::new() + .route("/r", get(tenant).patch(tenant)) + .layer(from_fn(require_tenant_status)) + .layer(from_fn_with_state(agent.clone(), audit_delegated_writes)) + .layer(from_fn_with_state(agent.clone(), require_entitlement)) + .layer(from_fn(require_jwt_auth)) + .layer(from_fn_with_state(agent, require_api_key)) + // Never reached: no test presents a well-formed JWT. + .layer(Extension(JwksState::new( + "http://127.0.0.1:9/jwks".into(), + None, + None, + ))) +} + +async fn call( + agent: &Arc, + method: &str, + bearer: &str, + headers: &[(&str, &str)], +) -> (StatusCode, String) { + let mut req = Request::builder() + .method(method) + .uri("/r") + .header("authorization", format!("Bearer {bearer}")); + for (name, value) in headers { + req = req.header(*name, *value); + } + let resp = app(agent.clone()) + .oneshot(req.body(Body::empty()).unwrap()) + .await + .unwrap(); + let status = resp.status(); + let bytes = axum::body::to_bytes(resp.into_body(), 1 << 16) + .await + .unwrap(); + (status, String::from_utf8_lossy(&bytes).into_owned()) +} + +#[tokio::test] +async fn a_key_works_in_its_own_tenant_only() { + let seen: Shared = Arc::default(); + let base = fake_registry(seen.clone()).await; + let Some(agent) = agent(&base).await else { + return; + }; + + // The tenant comes from the registry; the support header names another. + let other = "22222222-2222-2222-2222-222222222222"; + let (status, body) = call(&agent, "GET", "bp_good", &[(SUPPORT_TENANT_HEADER, other)]).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body, TENANT); + + // Within the TTL the registry is not asked again, and the entitlement + // check is never asked for a key. + let (status, _) = call(&agent, "GET", "bp_good", &[]).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(seen.lock().unwrap().paths, ["verify"]); +} + +#[tokio::test] +async fn a_rejected_key_or_a_jwt_never_gets_a_key_context() { + let seen: Shared = Arc::default(); + let base = fake_registry(seen.clone()).await; + let Some(agent) = agent(&base).await else { + return; + }; + + let (status, body) = call(&agent, "GET", "bp_revoked", &[]).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert!(body.contains("invalid_api_key"), "{body}"); + + // Not a key: the JWT middleware refuses it, and the registry's key + // verify is not asked. + let calls = seen.lock().unwrap().paths.len(); + let (status, _) = call(&agent, "GET", "not-a-jwt", &[]).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(seen.lock().unwrap().paths.len(), calls); +} + +#[tokio::test] +async fn a_cold_cache_and_an_unreachable_registry_mean_503() { + let seen: Shared = Arc::default(); + let base = fake_registry(seen).await; + let Some(agent) = agent(&base).await else { + return; + }; + let (status, body) = call(&agent, "GET", "bp_unreachable", &[]).await; + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); + assert!(!body.contains("bp_unreachable"), "{body}"); +} + +#[tokio::test] +async fn a_restricted_tenant_reads_but_does_not_write() { + let seen: Shared = Arc::default(); + let base = fake_registry(seen).await; + let Some(agent) = agent(&base).await else { + return; + }; + assert_eq!( + call(&agent, "GET", "bp_restricted", &[]).await.0, + StatusCode::OK + ); + assert_eq!( + call(&agent, "PATCH", "bp_restricted", &[]).await.0, + StatusCode::PAYMENT_REQUIRED + ); +} + +#[tokio::test] +async fn a_key_write_is_audited_as_the_key() { + let seen: Shared = Arc::default(); + let base = fake_registry(seen.clone()).await; + let Some(agent) = agent(&base).await else { + return; + }; + let (status, _) = call(&agent, "PATCH", "bp_good", &[("x-bp-actor", "jdoe")]).await; + assert_eq!(status, StatusCode::OK); + + // The audit is posted in the background. + let mut audit = None; + for _ in 0..50 { + audit = seen.lock().unwrap().audits.first().cloned(); + if audit.is_some() { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + let audit = audit.expect("audit entry posted"); + assert_eq!(audit["action"], "pruefwerk.api_key_write"); + assert_eq!(audit["actor_type"], "apikey"); + assert_eq!(audit["actor_id"], "apikey:k-1"); + assert_eq!(audit["actor_name"], "CI pipeline"); + assert_eq!(audit["metadata"]["on_behalf_of"], "jdoe"); + assert_eq!(audit["tenant_id"], TENANT); +} diff --git a/compliance-agent/tests/mcp_servers.rs b/compliance-agent/tests/mcp_servers.rs index e4865e4..9f3be81 100644 --- a/compliance-agent/tests/mcp_servers.rs +++ b/compliance-agent/tests/mcp_servers.rs @@ -35,6 +35,7 @@ fn tenant(id: &str, role: OrgRole) -> TenantCtx { user_id: "u-1".to_string(), user_name: None, staff: None, + api_key: None, }) } diff --git a/compliance-agent/tests/member_blocked.rs b/compliance-agent/tests/member_blocked.rs index 52541a6..bbfc12b 100644 --- a/compliance-agent/tests/member_blocked.rs +++ b/compliance-agent/tests/member_blocked.rs @@ -64,6 +64,7 @@ fn member(user: &str) -> TenantContext { user_id: user.into(), user_name: None, staff: None, + api_key: None, } } diff --git a/compliance-agent/tests/tenant_isolation.rs b/compliance-agent/tests/tenant_isolation.rs index 0186a16..8a46837 100644 --- a/compliance-agent/tests/tenant_isolation.rs +++ b/compliance-agent/tests/tenant_isolation.rs @@ -26,6 +26,7 @@ fn ctx(tenant_id: &str, slug: &str) -> TenantContext { user_id: "u-1".to_string(), user_name: None, staff: None, + api_key: None, } } diff --git a/compliance-agent/tests/tenant_status_middleware.rs b/compliance-agent/tests/tenant_status_middleware.rs index 248707e..621e634 100644 --- a/compliance-agent/tests/tenant_status_middleware.rs +++ b/compliance-agent/tests/tenant_status_middleware.rs @@ -29,6 +29,7 @@ fn ctx_with(status: TenantStatus) -> TenantContext { user_id: "u-1".to_string(), user_name: None, staff: None, + api_key: None, } } diff --git a/compliance-core/src/auth.rs b/compliance-core/src/auth.rs index b26de7d..cf3cfbc 100644 --- a/compliance-core/src/auth.rs +++ b/compliance-core/src/auth.rs @@ -129,6 +129,12 @@ const PUBLIC_ENDPOINTS: &[&str] = &["/api/v1/health"]; /// 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. /// @@ -137,9 +143,16 @@ const PUBLIC_PREFIXES: &[&str] = &["/api/v1/admin/", "/api/v1/werkbank/", "/api/ /// 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 { - let path = request.uri().path(); - - if PUBLIC_ENDPOINTS.contains(&path) || PUBLIC_PREFIXES.iter().any(|p| path.starts_with(p)) { + 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::() + .is_some_and(|c| c.api_key.is_some()) + { return next.run(request).await; } @@ -296,6 +309,7 @@ fn authenticate(c: Claims, requested_tenant: Option<&str>) -> Result Result { user_id: c.sub, user_name: c.name.or(c.preferred_username), staff: None, + api_key: None, }) } diff --git a/compliance-core/src/db.rs b/compliance-core/src/db.rs index 80e3bcd..c85f5bd 100644 --- a/compliance-core/src/db.rs +++ b/compliance-core/src/db.rs @@ -47,6 +47,7 @@ mod tests { user_id: "u-1".to_string(), user_name: None, staff: None, + api_key: None, } } diff --git a/compliance-core/src/lib.rs b/compliance-core/src/lib.rs index 53296cd..a224401 100644 --- a/compliance-core/src/lib.rs +++ b/compliance-core/src/lib.rs @@ -35,6 +35,6 @@ pub use error::CoreError; pub use exec_policy::ExecPolicy; pub use net_guard::{NetGuard, NetGuardError}; pub use tenant::{ - OrgRole, ProductAccess, StaffAccess, TenantContext, TenantStatus, SUPPORT_ROLES, + ApiKeyAccess, OrgRole, ProductAccess, StaffAccess, TenantContext, TenantStatus, SUPPORT_ROLES, SUPPORT_TENANT_HEADER, }; diff --git a/compliance-core/src/tenant.rs b/compliance-core/src/tenant.rs index 2ed88bd..d32c67c 100644 --- a/compliance-core/src/tenant.rs +++ b/compliance-core/src/tenant.rs @@ -196,6 +196,40 @@ impl StaffAccess { } } +/// 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:`. + 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, + /// 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, + /// 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, +} + +impl ApiKeyAccess { + /// Whether the key carries `scope`. A `.write` scope also grants + /// `.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)] @@ -225,6 +259,12 @@ pub struct TenantContext { /// its own users. `user_id` is then the staff member's id. #[serde(default)] pub staff: Option, + /// Set when an API key, not a person, made the request. `user_id` is + /// then `apikey:` 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>, } impl TenantContext { @@ -242,6 +282,11 @@ impl TenantContext { /// 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; } @@ -313,6 +358,27 @@ mod tests { 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 { @@ -328,6 +394,7 @@ mod tests { user_id: "s".into(), user_name: None, }), + api_key: None, }; assert_eq!(ctx.product_access(), ProductAccess::Full); let customer = TenantContext { staff: None, ..ctx }; @@ -346,6 +413,7 @@ mod tests { 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])); diff --git a/compliance-core/src/tenant_ctx.rs b/compliance-core/src/tenant_ctx.rs index f6f9201..8678f7b 100644 --- a/compliance-core/src/tenant_ctx.rs +++ b/compliance-core/src/tenant_ctx.rs @@ -133,6 +133,7 @@ mod tests { user_id: "u-1".to_string(), user_name: None, staff: None, + api_key: None, } } diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index 31eb237..b7084ac 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -62,6 +62,7 @@ export default withMermaid(defineConfig({ { text: 'Übersicht', link: '/features/overview' }, { text: 'Hilfe-Assistent', link: '/features/help-chat' }, { text: 'MCP-Schnittstelle', link: '/features/mcp-server' }, + { text: 'API-Schlüssel', link: '/guide/api-keys' }, { text: 'Tickets', link: '/guide/issues' }, { text: 'Webhooks und PR-Reviews', link: '/guide/webhooks' }, { text: 'Managed Git anbinden', link: '/guide/managed-git' }, diff --git a/docs/guide/api-keys.md b/docs/guide/api-keys.md new file mode 100644 index 0000000..35c2e92 --- /dev/null +++ b/docs/guide/api-keys.md @@ -0,0 +1,49 @@ +# API-Schlüssel + +Automatisierungen (eine CI-Pipeline, ein Werkmeister-Baustein, eigene Skripte) +melden sich bei der Prüfwerk-API mit einem API-Schlüssel an statt mit einem +Benutzerkonto. Schlüssel werden im Portal angelegt und widerrufen; jeder +Schlüssel gehört zu genau einer Organisation und trägt Berechtigungen +(_Scopes_). + +```sh +curl -H "Authorization: Bearer bp_…" https://pruefwerk.breakpilot.com/api/v1/findings +``` + +## Was ein Schlüssel darf + +| Scope | Erlaubt | +|---|---| +| `pruefwerk:findings.read` | Befunde lesen (`GET /api/v1/findings`, `/findings/variants`, `/findings/{id}`) | +| `pruefwerk:findings.write` | Status und Feedback von Befunden ändern (`PATCH /findings/{id}/status`, `/findings/bulk-status`, `/findings/{id}/feedback`); schließt das Lesen ein | +| `pruefwerk:sbom.read` | Stückliste lesen und exportieren (`GET /api/v1/sbom`, `/sbom/filters`, `/sbom/export`, `/sbom/licenses`, `/sbom/quality`, `/sbom/diff`) | +| `pruefwerk:scans.read` | Prüfläufe lesen (`GET /api/v1/scan-runs`) | +| `pruefwerk:scans.run` | Eine Prüfung starten (`POST /api/v1/targets/{id}/scan`, `/dast/targets/{id}/scan`) | +| `pruefwerk:enisa.read` | ENISA-Meldeentwürfe lesen (`GET /api/v1/targets/{id}/enisa`, `/cves/{id}/enisa`) | + +Alles andere ist mit einem Schlüssel nicht erreichbar, auch mit allen Scopes: +Prüfobjekte anlegen oder ändern, Zugangsdaten, Einstellungen, Befunde aus +manuellen Tests. Einen ENISA-Entwurf freigeben oder melden bleibt immer einer +Person vorbehalten. + +Ältere Schlüssel ohne Scopes dürfen nur lesen (die vier `read`-Scopes). + +## Antworten + +| Status | Bedeutung | +|---|---| +| `401 invalid_api_key` | Schlüssel unbekannt, abgelaufen oder widerrufen | +| `403 scope_missing` | Der Schlüssel hat den nötigen Scope nicht, oder die Route nimmt keine Schlüssel an; `required` nennt den Scope | +| `402` | Die Organisation ist eingeschränkt: lesen ja, ändern nein | +| `503` | Prüfwerk kann den Schlüssel gerade nicht prüfen; später erneut versuchen | + +## Gut zu wissen + +- **Widerruf wirkt nach höchstens 60 Sekunden.** Prüfwerk merkt sich das + Prüfergebnis eines Schlüssels eine Minute lang. +- **Nachvollziehbarkeit:** Änderungen mit einem Schlüssel stehen im Verlauf + und im Audit-Log unter dem Inhaber des Schlüssels bzw. `apikey:`. + Handelt ein Werkzeug für eine Person, kann es sie im Header `X-BP-Actor` + nennen; sie wird mitprotokolliert, berechtigt aber nichts. +- Ein Schlüssel wirkt nur in seiner eigenen Organisation. Angaben zur + Organisation in Headern, Pfaden oder Anfragedaten werden ignoriert.