//! Tenant-registry client (PRODUCT_INTEGRATION_SPEC 2.0 §4.4, §9.2). //! //! The registry is the entitlement authority: the product asks it whether a //! tenant may use `pruefwerk` (and which limits apply), enumerates tenants //! for the scheduler, verifies portal-issued API keys for the Werkbank //! runners, and pushes usage events. Answers are cached for ≤ 60 s and the //! gate fails CLOSED when the registry is unreachable and no fresh answer is //! cached. //! //! Authentication: a client_credentials token from the platform realm //! (`TENANT_REGISTRY_CLIENT_ID/SECRET`, audience `tenant-registry`). Without //! credentials the calls are sent unauthenticated (dev registry with //! `AUTH_ENABLED=false`). use std::sync::Arc; use std::time::{Duration, Instant}; use dashmap::DashMap; use secrecy::ExposeSecret; use serde::{Deserialize, Serialize}; use tokio::sync::Mutex; 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); /// The most API-key verdicts held at once. Callers choose the keys, so an /// unbounded cache of invalid ones would grow without end. const API_KEY_CACHE_MAX: usize = 10_000; /// 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 /// Keycloak holds the token lock, and every caller behind it, for the shared /// client's 30 s. const REQUEST_TIMEOUT: Duration = Duration::from_secs(5); /// One of the tenant's active connections to another workspace (#1028, /// tenant-registry#138), as a product reads it. The peer's tenant id is for /// delivering to it inside the product; it is never shown to anyone. #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] pub struct Connection { /// The connection's id. pub id: String, /// The other workspace's tenant id. pub peer_tenant_id: String, /// The other workspace's display name: all either side sees of the other. pub peer_name: String, } /// One connection as the registry checks it /// (`GET /v1/internal/connections/{id}`). #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] pub struct ConnectionState { /// Whether it is active: accepted and not ended. pub active: bool, /// The two tenants it joins. pub tenant_ids: Vec, } impl ConnectionState { /// The tenant on the other side from `tenant`, while the connection is /// active and `tenant` is one of its two sides; `None` otherwise. What a /// delivery asks right before it writes to another tenant's database. pub fn peer_of(&self, tenant: &str) -> Option<&str> { let [a, b] = self.tenant_ids.as_slice() else { return None; }; match (self.active, a == b) { (false, _) | (_, true) => None, _ if a == tenant => Some(b), _ if b == tenant => Some(a), _ => None, } } } /// A document of the tenant's store (Dokumentenablage), as the registry /// lists it (`GET /v1/tenants/{id}/store`). #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] pub struct StoreDocument { pub id: String, pub title: String, #[serde(default)] pub filename: String, #[serde(default)] pub content_type: Option, #[serde(default)] pub size_bytes: Option, /// `legal_web`, `product_public` or `internal`; none for BreakPilot's /// deliveries. #[serde(default)] pub area: Option, /// The product projects it belongs to. #[serde(default)] pub project_ids: Vec, #[serde(default)] pub created_at: Option>, } /// The registry's `reason` for a member blocked in the tenant. pub const MEMBER_BLOCKED: &str = "member_blocked"; #[derive(Debug, Clone, Deserialize, Serialize, Default)] pub struct EntitlementCheck { pub allowed: bool, #[serde(default)] pub read_only: bool, #[serde(default)] pub status: Option, #[serde(default)] pub limits: Option, #[serde(default)] pub expires_at: Option, #[serde(default)] pub reason: Option, } impl EntitlementCheck { /// Whether the registry refused because the member is blocked in the /// tenant, not because the tenant lacks the product. pub fn member_blocked(&self) -> bool { !self.allowed && self.reason.as_deref() == Some(MEMBER_BLOCKED) } /// How many targets the tenant's plan includes (t72): /// `limits.included_targets`. `None` when the plan sets no limit (no /// limits, the key missing or null), so every target is included. pub fn included_targets(&self) -> Option { self.limit("included_targets") } /// The plan's monthly quota and the customer's Prüftag cap (t72), from /// `limits.monthly_pruefungen` and `limits.prueftag_cap`; a missing or /// null key is no limit. pub fn plan_limits(&self) -> compliance_core::models::PlanLimits { compliance_core::models::PlanLimits { monthly_pruefungen: self.limit("monthly_pruefungen"), prueftag_cap: self.limit("prueftag_cap"), } } /// The whole-number limit `key`; `None` when absent or null. fn limit(&self, key: &str) -> Option { let n = self.limits.as_ref()?.get(key)?.as_u64()?; // A count beyond u32 is no limit in practice. Some(u32::try_from(n).unwrap_or(u32::MAX)) } } #[derive(Debug, Clone, Deserialize)] pub struct RegistryTenant { pub id: String, #[serde(default)] pub slug: String, /// The organisation's name, for the support tenant picker. #[serde(default)] pub name: String, #[serde(default)] pub status: String, } /// One entry of the platform's audit log (`POST /v1/audit`). #[derive(Debug, Clone, PartialEq, serde::Serialize)] pub struct AuditEntry { pub tenant_id: String, /// The product that wrote it (`pruefwerk`). pub product: String, /// What happened, e.g. `pruefwerk.support_access`. pub action: String, /// `user`, `staff` for BreakPilot support, or `apikey`. pub actor_type: String, pub actor_id: String, pub actor_name: String, /// What it happened to (e.g. `target`), when it concerns one object. #[serde(skip_serializing_if = "String::is_empty")] pub target_type: String, #[serde(skip_serializing_if = "String::is_empty")] pub target_id: String, #[serde(skip_serializing_if = "String::is_empty")] pub target_name: String, pub metadata: serde_json::Value, /// The caller's address, when the agent knows it; the registry otherwise /// records the address of the agent itself. #[serde(skip_serializing_if = "String::is_empty")] pub source_ip: String, } /// 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, 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: actor_type.to_string(), actor_id: ctx.user_id.clone(), actor_name: ctx.actor_label(), target_type: String::new(), target_id: String::new(), target_name: String::new(), metadata, source_ip: String::new(), } } /// The same entry, about the target `id` named `name`. #[must_use] pub fn about_target(mut self, id: &str, name: &str) -> Self { self.target_type = "target".to_string(); self.target_id = id.to_string(); self.target_name = name.to_string(); self } } /// 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, #[serde(default)] 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)] pub struct UsageEvent { pub idempotency_key: String, pub tenant_id: String, pub product: String, pub metric: String, pub quantity: f64, pub occurred_at: String, #[serde(skip_serializing_if = "Option::is_none")] pub properties: Option, } struct CachedToken { value: String, expires_at: Instant, } pub struct RegistryClient { base_url: String, product: String, http: reqwest::Client, token_url: Option, client_id: Option, client_secret: Option, token: Mutex>, 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 { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("RegistryClient") .field("base_url", &self.base_url) .field("product", &self.product) .field("authenticated", &self.client_id.is_some()) .finish() } } impl RegistryClient { /// `None` when `TENANT_REGISTRY_URL` is unset — the agent then runs in /// claims-only mode (dev) and logs it. pub fn from_config(cfg: &AgentConfig, http: reqwest::Client) -> Option> { let base_url = cfg.tenant_registry_url.clone()?; let token_url = match (&cfg.keycloak_url, &cfg.keycloak_realm) { (Some(u), Some(r)) => Some(format!( "{}/realms/{r}/protocol/openid-connect/token", u.trim_end_matches('/') )), _ => None, }; if cfg.tenant_registry_client_id.is_none() { tracing::warn!( "TENANT_REGISTRY_CLIENT_ID not set — registry calls are unauthenticated (dev only)" ); } Some(Arc::new(Self { base_url: base_url.trim_end_matches('/').to_string(), product: cfg.product_key.clone(), http, token_url, client_id: cfg.tenant_registry_client_id.clone(), client_secret: cfg .tenant_registry_client_secret .as_ref() .map(|s| s.expose_secret().to_string()), token: Mutex::new(None), cache: DashMap::new(), projects: DashMap::new(), api_keys: DashMap::new(), })) } pub fn product(&self) -> &str { &self.product } async fn bearer(&self) -> Result, String> { let (Some(url), Some(id), Some(secret)) = (&self.token_url, &self.client_id, &self.client_secret) else { return Ok(None); }; let mut guard = self.token.lock().await; if let Some(t) = guard.as_ref() { if Instant::now() + TOKEN_MARGIN < t.expires_at { return Ok(Some(t.value.clone())); } } #[derive(Deserialize)] struct TokenResp { access_token: String, #[serde(default = "default_expiry")] expires_in: u64, } fn default_expiry() -> u64 { 300 } let resp = self .http .post(url) .timeout(REQUEST_TIMEOUT) .form(&[ ("grant_type", "client_credentials"), ("client_id", id.as_str()), ("client_secret", secret.as_str()), ]) .send() .await .map_err(|e| format!("registry token request failed: {e}"))?; if !resp.status().is_success() { return Err(format!("registry token request returned {}", resp.status())); } let t: TokenResp = resp .json() .await .map_err(|e| format!("registry token response invalid: {e}"))?; let value = t.access_token; *guard = Some(CachedToken { value: value.clone(), expires_at: Instant::now() + Duration::from_secs(t.expires_in), }); Ok(Some(value)) } async fn request( &self, method: reqwest::Method, path: &str, ) -> Result { let mut rb = self .http .request(method, format!("{}{path}", self.base_url)) .timeout(REQUEST_TIMEOUT); if let Some(tok) = self.bearer().await? { rb = rb.bearer_auth(tok); } // traceparent: the registry's spans join this request's trace. for (name, value) in compliance_core::telemetry::trace_context_headers() { rb = rb.header(name, value); } Ok(rb) } /// Authoritative entitlement answer for this product, cached ≤ 60 s per /// (tenant, addon, user). Errors mean "unknown" — callers fail closed. /// /// With `user_id` (the Keycloak `sub` of a person), the registry also /// answers `allowed: false, reason: "member_blocked"` when that member is /// blocked in the tenant (portal#74). The registry itself allows when it /// cannot tell, so a failing block lookup never locks anyone out. pub async fn check_entitlement( &self, tenant_id: &str, addon: Option<&str>, user_id: Option<&str>, ) -> Result { let key = format!( "{tenant_id}|{}|{}", addon.unwrap_or(""), user_id.unwrap_or("") ); if let Some(entry) = self.cache.get(&key) { if entry.0.elapsed() < ENTITLEMENT_TTL { return Ok(entry.1.clone()); } } let body = serde_json::json!({ "tenant_id": tenant_id, "product": self.product, "addon": addon, "user_id": user_id, }); let resp = self .request(reqwest::Method::POST, "/v1/internal/entitlements/check") .await? .json(&body) .send() .await .map_err(|e| format!("entitlement check failed: {e}"))?; if !resp.status().is_success() { return Err(format!("entitlement check returned {}", resp.status())); } let check: EntitlementCheck = resp .json() .await .map_err(|e| format!("entitlement response invalid: {e}"))?; self.cache.insert(key, (Instant::now(), check.clone())); Ok(check) } /// Drop the cached answer for a tenant (after a platform lifecycle call). pub fn invalidate(&self, tenant_id: &str) { self.cache .retain(|k, _| !k.starts_with(&format!("{tenant_id}|"))); } /// Every tenant known to the registry (all statuses; the scheduler /// applies the ladder filter). Follows `next_cursor` pagination. pub async fn list_tenants(&self) -> Result, String> { #[derive(Deserialize)] struct Page { items: Vec, #[serde(default)] next_cursor: Option, } let mut out = Vec::new(); let mut cursor: Option = None; for _ in 0..50 { let mut path = "/v1/tenants?limit=200".to_string(); if let Some(c) = &cursor { path.push_str("&cursor="); path.push_str(&urlencoding::encode(c)); } let resp = self .request(reqwest::Method::GET, &path) .await? .send() .await .map_err(|e| format!("tenant list failed: {e}"))?; if !resp.status().is_success() { return Err(format!("tenant list returned {}", resp.status())); } let page: Page = resp .json() .await .map_err(|e| format!("tenant list invalid: {e}"))?; out.extend(page.items); match page.next_cursor { Some(c) if !c.is_empty() => cursor = Some(c), _ => break, } } Ok(out) } /// One tenant (`GET /v1/tenants/{id}`); `Ok(None)` when the registry /// does not know it. Errors mean "unknown": callers fail closed. pub async fn get_tenant(&self, tenant_id: &str) -> Result, String> { let resp = self .request( reqwest::Method::GET, &format!("/v1/tenants/{}", urlencoding::encode(tenant_id)), ) .await? .send() .await .map_err(|e| format!("tenant lookup failed: {e}"))?; if resp.status() == reqwest::StatusCode::NOT_FOUND { return Ok(None); } if !resp.status().is_success() { return Err(format!("tenant lookup returned {}", resp.status())); } resp.json() .await .map(Some) .map_err(|e| format!("tenant lookup invalid: {e}")) } /// Append to the platform's audit log. pub async fn append_audit(&self, entry: &AuditEntry) -> Result<(), String> { let resp = self .request(reqwest::Method::POST, "/v1/audit") .await? .json(entry) .send() .await .map_err(|e| format!("audit append failed: {e}"))?; if !resp.status().is_success() { return Err(format!("audit append returned {}", resp.status())); } Ok(()) } /// The tenant's active projects (`GET /v1/tenants/{id}/projects`), /// cached ≤ 60 s. A deleted project is simply no longer listed. /// /// # Errors /// /// The registry could not be asked, or answered with an error. pub async fn list_projects( &self, tenant_id: &str, ) -> Result, String> { if let Some(entry) = self.projects.get(tenant_id) { if entry.0.elapsed() < ENTITLEMENT_TTL { return Ok(entry.1.clone()); } } #[derive(Deserialize)] struct Page { #[serde(default)] items: Vec, } let resp = self .request( reqwest::Method::GET, &format!("/v1/tenants/{}/projects", urlencoding::encode(tenant_id)), ) .await? .send() .await .map_err(|e| format!("project list failed: {e}"))?; if !resp.status().is_success() { return Err(format!("project list returned {}", resp.status())); } let page: Page = resp .json() .await .map_err(|e| format!("project list invalid: {e}"))?; self.projects .insert(tenant_id.to_string(), (Instant::now(), page.items.clone())); Ok(page.items) } /// The tenant's document store (Dokumentenablage): its published /// documents, by area. Not cached: it is read when a product's box is /// opened on the Lieferkette (#1054). /// /// # Errors /// /// The registry could not be asked, or answered with an error. pub async fn list_store(&self, tenant_id: &str) -> Result, String> { #[derive(Deserialize)] struct Page { #[serde(default)] items: Vec, } let resp = self .request( reqwest::Method::GET, &format!("/v1/tenants/{}/store", urlencoding::encode(tenant_id)), ) .await? .send() .await .map_err(|e| format!("store list failed: {e}"))?; if !resp.status().is_success() { return Err(format!("store list returned {}", resp.status())); } let page: Page = resp .json() .await .map_err(|e| format!("store list invalid: {e}"))?; Ok(page.items) } /// The tenant's active connections to other workspaces (#1028). Not /// cached: a connection ended a second ago must not be offered. /// /// # Errors /// /// The registry could not be asked, or answered with an error other than /// 404. pub async fn active_connections(&self, tenant_id: &str) -> Result, String> { #[derive(Deserialize)] struct Page { #[serde(default)] items: Vec, } let resp = self .request( reqwest::Method::GET, &format!( "/v1/internal/tenants/{}/connections?state=active", urlencoding::encode(tenant_id) ), ) .await? .send() .await .map_err(|e| format!("connection list failed: {e}"))?; // A registry without connections for the tenant (or, before // tenant-registry#138, without the route) has none to list. if resp.status() == reqwest::StatusCode::NOT_FOUND { return Ok(Vec::new()); } if !resp.status().is_success() { return Err(format!("connection list returned {}", resp.status())); } let page: Page = resp .json() .await .map_err(|e| format!("connection list invalid: {e}"))?; Ok(page.items) } /// Connection `id` as the registry knows it now; `None` when it knows no /// such connection. Asked right before every delivery over it. /// /// # Errors /// /// The registry could not be asked, or answered with an error other than /// 404. pub async fn connection(&self, id: &str) -> Result, String> { let resp = self .request( reqwest::Method::GET, &format!("/v1/internal/connections/{}", urlencoding::encode(id)), ) .await? .send() .await .map_err(|e| format!("connection check failed: {e}"))?; if resp.status() == reqwest::StatusCode::NOT_FOUND { return Ok(None); } if !resp.status().is_success() { return Err(format!("connection check returned {}", resp.status())); } resp.json() .await .map(Some) .map_err(|e| format!("connection check invalid: {e}")) } /// 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.cache_api_key_verdict(digest, &verdict); Ok(verdict) } /// Keep `verdict` under `digest`. At [`API_KEY_CACHE_MAX`] the expired /// verdicts go first; if none have, this one is not kept (the request /// still gets it). fn cache_api_key_verdict(&self, digest: String, verdict: &ApiKeyVerify) { if self.api_keys.len() >= API_KEY_CACHE_MAX { self.api_keys .retain(|_, (at, _)| at.elapsed() < API_KEY_TTL); if self.api_keys.len() >= API_KEY_CACHE_MAX { return; } } self.api_keys .insert(digest, (Instant::now(), verdict.clone())); } 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())); } resp.json() .await .map_err(|e| format!("api-key verify response invalid: {e}")) } /// Push usage events (§9.2). Best-effort: the caller logs failures. pub async fn push_usage_events(&self, events: &[UsageEvent]) -> Result<(), String> { if events.is_empty() { return Ok(()); } let resp = self .request(reqwest::Method::POST, "/v1/usage/events") .await? .json(events) .send() .await .map_err(|e| format!("usage push failed: {e}"))?; if !resp.status().is_success() { return Err(format!("usage push returned {}", resp.status())); } Ok(()) } /// Ask the platform to tell the workspace about new findings /// (`POST /v1/notifications`, kind `findings.new`). The registry mails the /// people who run the workspace; `key` makes a retry harmless. pub async fn notify_new_findings(&self, n: &FindingsNotification) -> Result<(), String> { let resp = self .request(reqwest::Method::POST, "/v1/notifications") .await? .json(&serde_json::json!({ "tenant_id": n.tenant_id, "kind": "findings.new", "idempotency_key": n.key, "data": { "target_name": n.target_name, "new_count": n.new_count, "critical": n.critical, "high": n.high, "medium": n.medium, "low": n.low, "url": n.url, }, })) .send() .await .map_err(|e| format!("notification failed: {e}"))?; if !resp.status().is_success() { return Err(format!("notification returned {}", resp.status())); } Ok(()) } } /// New findings of one scan, for [`RegistryClient::notify_new_findings`]. #[derive(Debug, Clone, Default, PartialEq)] pub struct FindingsNotification { pub tenant_id: String, pub key: String, pub target_name: String, pub new_count: u64, pub critical: u64, pub high: u64, pub medium: u64, /// Low and info together. pub low: u64, /// Deep link into the dashboard; empty lets the platform link its own page. pub url: String, } /// Ladder rungs on which scheduled work still makes sense. Restricted / /// frozen / halted / archived tenants are skipped — the status gate would /// refuse the writes anyway. pub fn scheduler_runs_for(status: &str) -> bool { matches!(status, "" | "active" | "trial" | "demo" | "warning") } #[cfg(test)] mod tests { use super::*; #[test] fn a_connection_names_the_other_side_only_while_active_and_ours() { let joined = |active: bool, ids: &[&str]| ConnectionState { active, tenant_ids: ids.iter().map(|t| t.to_string()).collect(), }; let c = joined(true, &["supplier", "customer"]); assert_eq!(c.peer_of("supplier"), Some("customer")); assert_eq!(c.peer_of("customer"), Some("supplier")); assert_eq!( c.peer_of("someone else"), None, "a third tenant gets nothing" ); assert_eq!( joined(false, &["supplier", "customer"]).peer_of("supplier"), None, "ended" ); assert_eq!( joined(true, &["supplier", "supplier"]).peer_of("supplier"), None, "itself" ); assert_eq!( joined(true, &["supplier"]).peer_of("supplier"), None, "one side" ); assert_eq!( joined(true, &["a", "b", "c"]).peer_of("a"), None, "three sides" ); } #[test] fn the_plan_sets_how_many_targets_are_included() { let check = |limits: serde_json::Value| -> EntitlementCheck { serde_json::from_value(serde_json::json!({ "allowed": true, "limits": limits })) .expect("an entitlement answer") }; assert_eq!( check(serde_json::json!({ "included_targets": 5 })).included_targets(), Some(5) ); assert_eq!( check(serde_json::json!({ "included_targets": null })).included_targets(), None ); assert_eq!(check(serde_json::json!({})).included_targets(), None); assert_eq!(check(serde_json::Value::Null).included_targets(), None); } #[test] fn the_plan_sets_the_quota_and_the_cap() { let check: EntitlementCheck = serde_json::from_value(serde_json::json!({ "allowed": true, "limits": { "included_targets": 5, "monthly_pruefungen": 100, "prueftag_cap": 0 }, })) .expect("an entitlement answer"); assert_eq!( check.plan_limits(), compliance_core::models::PlanLimits { monthly_pruefungen: Some(100), prueftag_cap: Some(0), } ); assert_eq!( EntitlementCheck::default().plan_limits(), compliance_core::models::PlanLimits::default(), "Enterprise: no limits" ); } #[test] fn ladder_filter() { for s in ["active", "trial", "demo", "warning", ""] { assert!(scheduler_runs_for(s), "{s} should run"); } for s in ["restricted", "frozen", "halted", "archived"] { assert!(!scheduler_runs_for(s), "{s} should be skipped"); } } /// A Keycloak that accepts the connection and never answers costs one /// [`REQUEST_TIMEOUT`], not the shared client's 30 s. #[tokio::test] async fn a_hung_token_endpoint_gives_up_after_the_request_timeout() { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); tokio::spawn(async move { let mut held = Vec::new(); while let Ok((socket, _)) = listener.accept().await { held.push(socket); } }); let http = reqwest::Client::builder() .timeout(Duration::from_secs(30)) .build() .unwrap(); let client = RegistryClient { base_url: format!("http://{addr}"), product: "pruefwerk".into(), http, token_url: Some(format!("http://{addr}/token")), client_id: Some("svc".into()), client_secret: Some("secret".into()), token: Mutex::new(None), cache: DashMap::new(), projects: DashMap::new(), api_keys: DashMap::new(), }; let started = Instant::now(); let result = client.bearer().await; assert!(result.is_err(), "{result:?}"); assert!( started.elapsed() < REQUEST_TIMEOUT * 2, "{:?}", 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 a_full_cache_drops_expired_verdicts_and_never_grows_past_its_cap() { let (client, _, _) = verify_registry().await; let verdict = client.verify_api_key("bp_good").await.unwrap(); let aged = Instant::now() .checked_sub(API_KEY_TTL + Duration::from_secs(1)) .unwrap(); for i in 0..API_KEY_CACHE_MAX { client .api_keys .insert(format!("old-{i}"), (aged, verdict.clone())); } client.verify_api_key("bp_new").await.unwrap(); assert!(client.api_keys.len() < 10, "{}", client.api_keys.len()); assert!(client.api_keys.contains_key(&key_digest("bp_new"))); // Full of fresh verdicts: the new one is answered but not kept. for i in 0..API_KEY_CACHE_MAX { client .api_keys .insert(format!("new-{i}"), (Instant::now(), verdict.clone())); } let before = client.api_keys.len(); assert!(client.verify_api_key("bp_newer").await.unwrap().valid); assert_eq!(client.api_keys.len(), before); } #[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_"))); } }