Files
pruefwerk/compliance-agent/tests/api_key_access.rs
T
Sharang ParnerkarandClaude Opus 5.5 ae8761c15c feat(api): the customer API accepts portal-issued API keys (bp_…)
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:<key_id> 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) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
2026-10-14 00:07:09 +02:00

254 lines
8.9 KiB
Rust

//! 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<String>,
audits: Vec<serde_json::Value>,
}
type Shared = Arc<Mutex<Seen>>;
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<serde_json::Value> {
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<Shared>, Json(body): Json<serde_json::Value>| 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<Shared>| async move {
seen.lock().unwrap().paths.push("entitlement".into());
Json(serde_json::json!({ "allowed": true, "status": "active" }))
}),
)
.route(
"/v1/audit",
post(
|State(seen): State<Shared>, Json(body): Json<serde_json::Value>| 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<Arc<ComplianceAgent>> {
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<ComplianceAgent>) -> Router {
let tenant = |Extension(ctx): Extension<TenantContext>| 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<ComplianceAgent>,
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);
}