CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 4m37s
CI / Deploy Agent (pull_request) Skipped
CI / Check (pull_request) Successful in 20m55s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
1374 lines
50 KiB
Rust
1374 lines
50 KiB
Rust
//! 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<String>,
|
|
}
|
|
|
|
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<String>,
|
|
#[serde(default)]
|
|
pub size_bytes: Option<u64>,
|
|
/// `legal_web`, `product_public` or `internal`; none for BreakPilot's
|
|
/// deliveries.
|
|
#[serde(default)]
|
|
pub area: Option<String>,
|
|
/// The product projects it belongs to.
|
|
#[serde(default)]
|
|
pub project_ids: Vec<String>,
|
|
#[serde(default)]
|
|
pub created_at: Option<chrono::DateTime<chrono::Utc>>,
|
|
}
|
|
|
|
/// 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<String>,
|
|
#[serde(default)]
|
|
pub limits: Option<serde_json::Value>,
|
|
#[serde(default)]
|
|
pub expires_at: Option<String>,
|
|
#[serde(default)]
|
|
pub reason: Option<String>,
|
|
/// The workspace's branding (tenant-registry#155); absent when there is
|
|
/// nothing to show.
|
|
#[serde(default)]
|
|
pub branding: Option<Branding>,
|
|
}
|
|
|
|
/// A workspace's branding as the registry derived or an admin set it
|
|
/// (tenant-registry#155): its CI colour, which frames every page, its logo,
|
|
/// and whether its admins have yet to acknowledge a derived one.
|
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
|
|
pub struct Branding {
|
|
/// `#rrggbb`, or null.
|
|
#[serde(default)]
|
|
pub color: Option<String>,
|
|
/// The SHA-256 (hex) of the stored logo, or null when there is none.
|
|
#[serde(default)]
|
|
pub logo_etag: Option<String>,
|
|
/// Whether a derived branding waits for an admin's "Passt".
|
|
#[serde(default)]
|
|
pub notice: bool,
|
|
/// The domain it was derived from; present while `notice` is.
|
|
#[serde(default)]
|
|
pub domain: Option<String>,
|
|
/// The workspace's name, shown beside the logo.
|
|
#[serde(default)]
|
|
pub name: Option<String>,
|
|
}
|
|
|
|
impl Branding {
|
|
/// The frame colour as `#rrggbb` in lower case; anything else is no
|
|
/// frame, so a malformed value can never reach a style.
|
|
pub fn frame_color(&self) -> Option<String> {
|
|
let c = self.color.as_deref()?.trim();
|
|
let hex = c.strip_prefix('#')?;
|
|
(hex.len() == 6 && hex.bytes().all(|b| b.is_ascii_hexdigit()))
|
|
.then(|| c.to_ascii_lowercase())
|
|
}
|
|
|
|
/// The logo's ETag when it is a SHA-256 in hex; anything else is no logo.
|
|
pub fn logo_etag(&self) -> Option<&str> {
|
|
self.logo_etag
|
|
.as_deref()
|
|
.filter(|e| e.len() == 64 && e.bytes().all(|b| b.is_ascii_hexdigit()))
|
|
}
|
|
}
|
|
|
|
/// Why the registry did not record an admin's "Passt".
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub enum AckRefusal {
|
|
/// The user is no IT admin or owner of the workspace (403 `not_admin`).
|
|
NotAdmin,
|
|
/// The registry could not be asked, or answered something else.
|
|
Failed(String),
|
|
}
|
|
|
|
/// The largest logo the agent takes from the registry, which stores 256 px
|
|
/// PNGs: far below this.
|
|
const MAX_LOGO_BYTES: usize = 1 << 20;
|
|
|
|
/// Whether `tenant_id` may stand in a registry path: the registry's ids are
|
|
/// UUIDs, so anything else is refused before a request is made.
|
|
fn path_safe(tenant_id: &str) -> bool {
|
|
!tenant_id.is_empty()
|
|
&& tenant_id
|
|
.bytes()
|
|
.all(|b| b.is_ascii_alphanumeric() || b == b'-')
|
|
}
|
|
|
|
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<u32> {
|
|
self.limit("included_targets")
|
|
}
|
|
|
|
/// How many targets beyond the included ones the plan lets be active:
|
|
/// `limits.extra_targets` (`0` on the entry plan). `None` when the key is
|
|
/// missing or null: extra targets are allowed and billed.
|
|
pub fn extra_targets(&self) -> Option<u32> {
|
|
self.limit("extra_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<u32> {
|
|
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<String>,
|
|
#[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<String>,
|
|
#[serde(default)]
|
|
pub expires_at: Option<String>,
|
|
/// 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<serde_json::Value>,
|
|
}
|
|
|
|
struct CachedToken {
|
|
value: String,
|
|
expires_at: Instant,
|
|
}
|
|
|
|
pub struct RegistryClient {
|
|
base_url: String,
|
|
product: String,
|
|
http: reqwest::Client,
|
|
token_url: Option<String>,
|
|
client_id: Option<String>,
|
|
client_secret: Option<String>,
|
|
token: Mutex<Option<CachedToken>>,
|
|
cache: DashMap<String, (Instant, EntitlementCheck)>,
|
|
/// Each tenant's projects, for [`ENTITLEMENT_TTL`].
|
|
projects: DashMap<String, (Instant, Vec<compliance_core::models::Project>)>,
|
|
/// API-key verdicts, valid and invalid, keyed by the key's SHA-256 (never
|
|
/// the key itself), for [`API_KEY_TTL`].
|
|
api_keys: DashMap<String, (Instant, ApiKeyVerify)>,
|
|
/// Each tenant's logo with its ETag, kept until the registry names
|
|
/// another (tenant-registry#155).
|
|
logos: DashMap<String, (String, axum::body::Bytes)>,
|
|
}
|
|
|
|
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<Arc<Self>> {
|
|
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(),
|
|
logos: DashMap::new(),
|
|
}))
|
|
}
|
|
|
|
pub fn product(&self) -> &str {
|
|
&self.product
|
|
}
|
|
|
|
async fn bearer(&self) -> Result<Option<String>, 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<reqwest::RequestBuilder, String> {
|
|
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<EntitlementCheck, String> {
|
|
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)
|
|
}
|
|
|
|
/// The workspace's logo with the ETag `etag`, as a PNG, or `None` when
|
|
/// the registry has none. Kept per tenant and asked for again only when
|
|
/// the registry names another ETag; then with `If-None-Match`, so an
|
|
/// unchanged logo is not sent twice.
|
|
///
|
|
/// # Errors
|
|
///
|
|
/// When the registry cannot be asked or answers with something other
|
|
/// than a PNG of at most 1 MiB.
|
|
pub async fn branding_logo(
|
|
&self,
|
|
tenant_id: &str,
|
|
etag: &str,
|
|
) -> Result<Option<axum::body::Bytes>, String> {
|
|
let cached = self
|
|
.logos
|
|
.get(tenant_id)
|
|
.map(|hit| (hit.0.clone(), hit.1.clone()));
|
|
if let Some((tag, png)) = &cached {
|
|
if tag == etag {
|
|
return Ok(Some(png.clone()));
|
|
}
|
|
}
|
|
if !path_safe(tenant_id) {
|
|
return Err("tenant id not usable in a path".into());
|
|
}
|
|
let mut rb = self
|
|
.request(
|
|
reqwest::Method::GET,
|
|
&format!("/v1/tenants/{tenant_id}/branding/logo"),
|
|
)
|
|
.await?;
|
|
if let Some((tag, _)) = &cached {
|
|
rb = rb.header(reqwest::header::IF_NONE_MATCH, format!("\"{tag}\""));
|
|
}
|
|
let resp = rb
|
|
.send()
|
|
.await
|
|
.map_err(|e| format!("logo request failed: {e}"))?;
|
|
match resp.status() {
|
|
reqwest::StatusCode::NOT_MODIFIED => Ok(cached.map(|(_, png)| png)),
|
|
reqwest::StatusCode::NOT_FOUND => {
|
|
self.logos.remove(tenant_id);
|
|
Ok(None)
|
|
}
|
|
status if status.is_success() => {
|
|
let is_png = resp
|
|
.headers()
|
|
.get(reqwest::header::CONTENT_TYPE)
|
|
.and_then(|v| v.to_str().ok())
|
|
.is_some_and(|v| v.starts_with("image/png"));
|
|
if !is_png {
|
|
return Err("logo is not a PNG".into());
|
|
}
|
|
let tag = resp
|
|
.headers()
|
|
.get(reqwest::header::ETAG)
|
|
.and_then(|v| v.to_str().ok())
|
|
.map(|v| v.trim_start_matches("W/").trim_matches('"').to_string())
|
|
.unwrap_or_else(|| etag.to_string());
|
|
let png = resp
|
|
.bytes()
|
|
.await
|
|
.map_err(|e| format!("logo not read: {e}"))?;
|
|
if png.len() > MAX_LOGO_BYTES {
|
|
return Err("logo larger than 1 MiB".into());
|
|
}
|
|
self.logos.insert(tenant_id.to_string(), (tag, png.clone()));
|
|
Ok(Some(png))
|
|
}
|
|
status => Err(format!("logo request returned {status}")),
|
|
}
|
|
}
|
|
|
|
/// Record an admin's "Passt" on the workspace's derived branding
|
|
/// (`POST /v1/tenants/{id}/branding/ack`) and drop the cached entitlement
|
|
/// answers, so the notice goes with the next check.
|
|
///
|
|
/// # Errors
|
|
///
|
|
/// [`AckRefusal::NotAdmin`] when the registry does not count `user_id` as
|
|
/// an IT admin or owner of the tenant; [`AckRefusal::Failed`] otherwise.
|
|
pub async fn ack_branding(&self, tenant_id: &str, user_id: &str) -> Result<(), AckRefusal> {
|
|
if !path_safe(tenant_id) {
|
|
return Err(AckRefusal::Failed("tenant id not usable in a path".into()));
|
|
}
|
|
let resp = self
|
|
.request(
|
|
reqwest::Method::POST,
|
|
&format!("/v1/tenants/{tenant_id}/branding/ack"),
|
|
)
|
|
.await
|
|
.map_err(AckRefusal::Failed)?
|
|
.json(&serde_json::json!({ "user_id": user_id }))
|
|
.send()
|
|
.await
|
|
.map_err(|e| AckRefusal::Failed(format!("ack failed: {e}")))?;
|
|
match resp.status() {
|
|
status if status.is_success() => {
|
|
self.invalidate(tenant_id);
|
|
Ok(())
|
|
}
|
|
reqwest::StatusCode::FORBIDDEN => Err(AckRefusal::NotAdmin),
|
|
status => Err(AckRefusal::Failed(format!("ack returned {status}"))),
|
|
}
|
|
}
|
|
|
|
/// 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<Vec<RegistryTenant>, String> {
|
|
#[derive(Deserialize)]
|
|
struct Page {
|
|
items: Vec<RegistryTenant>,
|
|
#[serde(default)]
|
|
next_cursor: Option<String>,
|
|
}
|
|
let mut out = Vec::new();
|
|
let mut cursor: Option<String> = 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<Option<RegistryTenant>, 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<Vec<compliance_core::models::Project>, 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<compliance_core::models::Project>,
|
|
}
|
|
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<Vec<StoreDocument>, String> {
|
|
#[derive(Deserialize)]
|
|
struct Page {
|
|
#[serde(default)]
|
|
items: Vec<StoreDocument>,
|
|
}
|
|
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<Vec<Connection>, String> {
|
|
#[derive(Deserialize)]
|
|
struct Page {
|
|
#[serde(default)]
|
|
items: Vec<Connection>,
|
|
}
|
|
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<Option<ConnectionState>, 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<ApiKeyVerify, String> {
|
|
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<ApiKeyVerify, String> {
|
|
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_may_allow_no_extra_targets() {
|
|
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": 1, "extra_targets": 0 })).extra_targets(),
|
|
Some(0)
|
|
);
|
|
assert_eq!(
|
|
check(serde_json::json!({ "extra_targets": null })).extra_targets(),
|
|
None
|
|
);
|
|
assert_eq!(
|
|
check(serde_json::json!({ "included_targets": 5 })).extra_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(),
|
|
logos: 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<std::sync::atomic::AtomicUsize>,
|
|
Arc<std::sync::atomic::AtomicBool>,
|
|
) {
|
|
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<serde_json::Value>| {
|
|
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(),
|
|
logos: 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_")));
|
|
}
|
|
|
|
/// A registry with one tenant's logo (ETag `"aa…"`, honouring
|
|
/// If-None-Match) and an ack endpoint that takes only `u-admin`; the
|
|
/// number of logo bodies it sent is counted.
|
|
async fn branding_registry() -> (RegistryClient, Arc<std::sync::atomic::AtomicUsize>) {
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
let sent = Arc::new(AtomicUsize::new(0));
|
|
let s = sent.clone();
|
|
let tag = "a".repeat(64);
|
|
let quoted = format!("\"{tag}\"");
|
|
let app = axum::Router::new()
|
|
.route(
|
|
"/v1/tenants/{id}/branding/logo",
|
|
axum::routing::get(
|
|
move |axum::extract::Path(id): axum::extract::Path<String>,
|
|
headers: axum::http::HeaderMap| {
|
|
let (s, quoted) = (s.clone(), quoted.clone());
|
|
async move {
|
|
use axum::response::IntoResponse;
|
|
if id != "t-1" {
|
|
return axum::http::StatusCode::NOT_FOUND.into_response();
|
|
}
|
|
if headers.get("if-none-match").and_then(|v| v.to_str().ok())
|
|
== Some(quoted.as_str())
|
|
{
|
|
return axum::http::StatusCode::NOT_MODIFIED.into_response();
|
|
}
|
|
s.fetch_add(1, Ordering::SeqCst);
|
|
(
|
|
[("content-type", "image/png"), ("etag", quoted.as_str())],
|
|
b"\x89PNG fake".to_vec(),
|
|
)
|
|
.into_response()
|
|
}
|
|
},
|
|
),
|
|
)
|
|
.route(
|
|
"/v1/tenants/{id}/branding/ack",
|
|
axum::routing::post(
|
|
|axum::Json(body): axum::Json<serde_json::Value>| async move {
|
|
if body["user_id"] == "u-admin" {
|
|
axum::http::StatusCode::NO_CONTENT
|
|
} else {
|
|
axum::http::StatusCode::FORBIDDEN
|
|
}
|
|
},
|
|
),
|
|
);
|
|
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(),
|
|
logos: DashMap::new(),
|
|
};
|
|
(client, sent)
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_logo_is_fetched_once_per_etag_and_none_is_none() {
|
|
use std::sync::atomic::Ordering;
|
|
// Arrange
|
|
let (client, sent) = branding_registry().await;
|
|
let tag = "a".repeat(64);
|
|
|
|
// Act: twice with the same ETag, then with another one.
|
|
let first = client.branding_logo("t-1", &tag).await.unwrap();
|
|
let again = client.branding_logo("t-1", &tag).await.unwrap();
|
|
let other = client.branding_logo("t-1", &"b".repeat(64)).await.unwrap();
|
|
|
|
// Assert: one body sent; the other ETag was answered 304 from the
|
|
// cached PNG; a tenant without a logo has none.
|
|
assert_eq!(first.as_deref(), Some(&b"\x89PNG fake"[..]));
|
|
assert_eq!(again, first);
|
|
assert_eq!(other, first);
|
|
assert_eq!(sent.load(Ordering::SeqCst), 1);
|
|
assert_eq!(client.branding_logo("t-2", &tag).await.unwrap(), None);
|
|
assert!(
|
|
client.branding_logo("../x", &tag).await.is_err(),
|
|
"no path from an id"
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn only_an_admin_the_registry_knows_acknowledges() {
|
|
let (client, _) = branding_registry().await;
|
|
assert_eq!(client.ack_branding("t-1", "u-admin").await, Ok(()));
|
|
assert_eq!(
|
|
client.ack_branding("t-1", "u-member").await,
|
|
Err(AckRefusal::NotAdmin)
|
|
);
|
|
}
|
|
}
|