From 7ef6387d3910be33643bf116e0971c8221e06523 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:07:53 +0100 Subject: [PATCH 1/2] feat(metering): a plan can allow no extra targets (entry plan) The registry's `limits.extra_targets` caps how many targets beyond the included ones may be active; the entry plan sends 0. A new target past included_targets + extra_targets is refused with 409 `target_limit`, whichever way it is added: the API, accepting a supplier's SBOM release (the offer stays open), Managed Git (skipped, retried at the next sync) and the demo seed. A missing or null key keeps today's behaviour: extra targets are allowed and billed. All active targets count, as for the included/extra split; archiving one frees its place. Without an answer from the registry the target is added, as scans then run unmetered. Every way of adding a target now goes through targets::create_target, which reads the plan once for the cap and the billing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9 --- compliance-agent/src/agent.rs | 3 +- compliance-agent/src/api/handlers/offers.rs | 6 +- .../src/api/handlers/onboarding.rs | 68 ++++--- compliance-agent/src/error.rs | 7 + compliance-agent/src/git_source/mod.rs | 19 +- compliance-agent/src/metering.rs | 25 +++ compliance-agent/src/registry.rs | 28 +++ compliance-agent/src/targets.rs | 37 +++- compliance-agent/tests/target_limit.rs | 171 ++++++++++++++++++ compliance-dashboard/src/i18n/texts.rs | 20 +- compliance-dashboard/src/pages/onboarding.rs | 15 +- 11 files changed, 356 insertions(+), 43 deletions(-) create mode 100644 compliance-agent/tests/target_limit.rs diff --git a/compliance-agent/src/agent.rs b/compliance-agent/src/agent.rs index 5fc8764..dc6677b 100644 --- a/compliance-agent/src/agent.rs +++ b/compliance-agent/src/agent.rs @@ -205,6 +205,7 @@ impl ComplianceAgent { match registry.check_entitlement(tenant_id, None, None).await { Ok(check) => Some(crate::metering::Plan { included_targets: check.included_targets(), + extra_targets: check.extra_targets(), limits: check.plan_limits(), }), Err(e) => { @@ -216,7 +217,7 @@ impl ComplianceAgent { /// Store the billing of the tenant's targets for a plan that includes /// `included` targets; best-effort. - async fn assign_billing( + pub(crate) async fn assign_billing( &self, tenant_id: &str, db: &crate::database::Database, diff --git a/compliance-agent/src/api/handlers/offers.rs b/compliance-agent/src/api/handlers/offers.rs index d44c04b..b1dd82e 100644 --- a/compliance-agent/src/api/handlers/offers.rs +++ b/compliance-agent/src/api/handlers/offers.rs @@ -490,7 +490,7 @@ pub async fn list_offers( responses( (status = 200, description = "Accepted (`data`: the offer)"), (status = 404, description = "No such offer, or no such component"), - (status = 409, description = "Already answered (`answered`), the release or connection ended (`ended`), or the component already receives another release (`target_taken`)"), + (status = 409, description = "Already answered (`answered`), the release or connection ended (`ended`), or the component already receives another release (`target_taken`), or the plan allows no further active target (`target_limit`)"), (status = 422, description = "The component is not a supplier component (`not_supplier_component`), or an unknown project"), (status = 503, description = "The registry cannot be asked"), (status = 401, description = "No valid bearer token"), @@ -601,9 +601,9 @@ pub async fn accept_offer( .await { Ok(created) => created, - Err(status) => { + Err(e) => { unclaim(&db, offer.id).await?; - return Err(status); + return Ok(super::onboarding::target_refused(e)); } }; let created_id = created.id.map(|o| o.to_hex()).unwrap_or_default(); diff --git a/compliance-agent/src/api/handlers/onboarding.rs b/compliance-agent/src/api/handlers/onboarding.rs index 5dd183c..9ecf45f 100644 --- a/compliance-agent/src/api/handlers/onboarding.rs +++ b/compliance-agent/src/api/handlers/onboarding.rs @@ -20,6 +20,7 @@ use compliance_core::tenant_ctx::TenantCtx; use crate::agent::ComplianceAgent; use crate::classify::{classify_target, MockFirmwareDetector}; +use crate::error::AgentError; use crate::secrets::SecretError; use crate::targets::{upload_dest, uploaded_artifact, MAX_UPLOAD_BYTES}; @@ -405,7 +406,8 @@ async fn findings_counts( request_body = CreateTargetRequest, responses( (status = 200, description = "The new target"), - (status = 422, description = "A malformed body, or a device whose order number or firmware is not one"), + (status = 409, description = "The plan allows no further active target (`target_limit`)"), + (status = 422, description = "A malformed body"), (status = 503, description = "A credential cannot be sealed"), (status = 401, description = "No valid bearer token"), ) @@ -415,20 +417,25 @@ pub async fn create_target( Extension(agent): AgentExt, tenant: TenantCtx, Json(req): Json, -) -> Result>, StatusCode> { +) -> Result>, axum::response::Response> { + use axum::response::IntoResponse; + let mut target = OnboardedTarget::new(req.name, req.target_type); target.description = req.description; if let Some(supplier) = req.supplier { - target.supplier = supplier.build()?; + target.supplier = supplier.build().map_err(IntoResponse::into_response)?; } - target.devices = build_devices(&req.devices)?; target.artifacts = merge_artifacts(&agent.secrets, &req.artifacts, &[]).map_err(|e| { tracing::error!("storing a credential: {e}"); - StatusCode::SERVICE_UNAVAILABLE + StatusCode::SERVICE_UNAVAILABLE.into_response() })?; - let db = tenant_db(&agent, &tenant).await?; - let target = insert_target(&agent, &db, &tenant.0.tenant_id, target).await?; + let db = tenant_db(&agent, &tenant) + .await + .map_err(IntoResponse::into_response)?; + let target = insert_target(&agent, &db, &tenant.0.tenant_id, target) + .await + .map_err(target_refused)?; Ok(Json(ApiResponse { data: target.redacted(), total: None, @@ -436,36 +443,45 @@ pub async fn create_target( })) } -/// Store a new `target` of tenant `tenant_id` and count it: what every way -/// of adding a target does (the API, and accepting a supplier's SBOM release, -/// #1028), so each counts the same under the plan. +/// Store a new `target` of tenant `tenant_id` and count it +/// ([`crate::targets::create_target`]), then read its supplier's CSAF feed. +/// What the API and accepting a supplier's SBOM release (#1028) do. /// /// # Errors /// -/// 500 when it cannot be stored. +/// [`AgentError::TargetLimit`] when the plan has no room for it; a database +/// error. pub(super) async fn insert_target( agent: &Arc, db: &crate::database::Database, tenant_id: &str, - mut target: OnboardedTarget, -) -> Result { - let res = db - .onboarded_targets() - .insert_one(&target) - .await - .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - target.id = res.inserted_id.as_object_id(); + target: OnboardedTarget, +) -> Result { + let target = crate::targets::create_target(agent, db, tenant_id, target).await?; refresh_supplier_csaf(agent, tenant_id, target.supplier.as_ref()); - let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default(); - agent.emit_usage( - tenant_id, - "target.added", - format!("target:{tenant_id}:{target_id}"), - serde_json::json!({ "target_id": target_id, "target_type": format!("{:?}", target.target_type) }), - ); Ok(target) } +/// A new target refused, as the API answers: 409 `{"error": "target_limit"}` +/// when the plan has no room for it, else 500. +pub(super) fn target_refused(e: AgentError) -> axum::response::Response { + use axum::response::IntoResponse; + match e { + AgentError::TargetLimit(cap) => { + tracing::info!(cap, "new target refused: the plan's targets are all active"); + ( + StatusCode::CONFLICT, + Json(serde_json::json!({ "error": "target_limit" })), + ) + .into_response() + } + e => { + tracing::error!("storing a target: {e}"); + StatusCode::INTERNAL_SERVER_ERROR.into_response() + } + } +} + /// One target, credentials redacted. #[utoipa::path( get, diff --git a/compliance-agent/src/error.rs b/compliance-agent/src/error.rs index 2a670a8..ac5d142 100644 --- a/compliance-agent/src/error.rs +++ b/compliance-agent/src/error.rs @@ -47,6 +47,11 @@ pub enum AgentError { #[error("not run: {0:?}")] NotAdmitted(compliance_core::models::Refusal), + /// A new target the plan has no room for: as many targets are active + /// as it allows (the entry plan's `extra_targets: 0`). + #[error("the plan allows {0} active targets")] + TargetLimit(u32), + #[error("{0}")] Other(String), } @@ -79,6 +84,7 @@ impl AgentError { | Self::Secret(_) | Self::Exec(_) | Self::NotAdmitted(_) + | Self::TargetLimit(_) | Self::Other(_) => ( RunErrorCode::Internal, "the scan stopped because of an internal error", @@ -91,6 +97,7 @@ impl From for axum::http::StatusCode { fn from(err: AgentError) -> Self { match err { AgentError::Core(CoreError::NotFound(_)) => axum::http::StatusCode::NOT_FOUND, + AgentError::TargetLimit(_) => axum::http::StatusCode::CONFLICT, _ => axum::http::StatusCode::INTERNAL_SERVER_ERROR, } } diff --git a/compliance-agent/src/git_source/mod.rs b/compliance-agent/src/git_source/mod.rs index 4f91120..1cd3428 100644 --- a/compliance-agent/src/git_source/mod.rs +++ b/compliance-agent/src/git_source/mod.rs @@ -467,6 +467,10 @@ pub enum Outcome { Ignored(&'static str), } +/// Why a delivery for a repository without a target makes none: the plan's +/// targets are all active (`extra_targets: 0`). +const NO_ROOM: &str = "the plan allows no further active target"; + /// Carry out a routed delivery for `tenant_id`. /// /// # Errors @@ -485,7 +489,10 @@ pub async fn apply_action( archive_target(db, &source.base_url, repo.id).await?, )), SourceAction::Created(repo) => { - let ensured = ensure_target(agent, db, tenant_id, source, &repo).await?; + let ensured = match ensure_target(agent, db, tenant_id, source, &repo).await { + Err(AgentError::TargetLimit(_)) => return Ok(Outcome::Ignored(NO_ROOM)), + ensured => ensured?, + }; // An empty repository has nothing to scan; its first push will. let scan = ensured.created && !repo.empty; if scan { @@ -497,7 +504,10 @@ pub async fn apply_action( }) } SourceAction::Push(repo) => { - let ensured = ensure_target(agent, db, tenant_id, source, &repo).await?; + let ensured = match ensure_target(agent, db, tenant_id, source, &repo).await { + Err(AgentError::TargetLimit(_)) => return Ok(Outcome::Ignored(NO_ROOM)), + ensured => ensured?, + }; spawn_scan(agent, tenant_id, &ensured.target_id, ScanTrigger::Webhook); Ok(Outcome::Ensured { target_id: ensured.target_id, @@ -608,6 +618,11 @@ pub async fn sync_with( } } Ok(_) => report.refreshed += 1, + // Not an error: the next sync tries again, once a target is + // archived or the plan changed. + Err(AgentError::TargetLimit(cap)) => { + tracing::info!(tenant_id, repo = %repo.full_name, cap, "managed git sync: no target, the plan's targets are all active"); + } Err(err) => { tracing::warn!(tenant_id, repo = %repo.full_name, "managed git sync: {err}"); } diff --git a/compliance-agent/src/metering.rs b/compliance-agent/src/metering.rs index 2d1c0c2..0067485 100644 --- a/compliance-agent/src/metering.rs +++ b/compliance-agent/src/metering.rs @@ -179,10 +179,21 @@ pub async fn swap( pub struct Plan { /// How many targets the plan includes; `None` is unlimited. pub included_targets: Option, + /// How many extra targets may be active besides; `None` is unlimited. + pub extra_targets: Option, /// The quota and the customer's Prüftag cap. pub limits: PlanLimits, } +impl Plan { + /// How many targets may be active at once: the included ones and the + /// extra ones the plan allows. `None` when either is unlimited, as on + /// every plan that bills extra targets. + pub fn target_cap(&self) -> Option { + Some(self.included_targets?.saturating_add(self.extra_targets?)) + } +} + /// The tenant's counted Prüfungen and booked Prüftage per month. const MONTHS: &str = "metering_months"; /// Each target's Prüftag per day, once the quota was used up. @@ -447,6 +458,20 @@ mod tests { use super::*; use chrono::TimeZone; + #[test] + fn only_a_plan_capping_both_counts_caps_the_active_targets() { + let plan = |included_targets, extra_targets| Plan { + included_targets, + extra_targets, + ..Plan::default() + }; + assert_eq!(plan(Some(3), Some(0)).target_cap(), Some(3), "entry"); + assert_eq!(plan(Some(3), Some(2)).target_cap(), Some(5)); + assert_eq!(plan(Some(5), None).target_cap(), None, "extras billed"); + assert_eq!(plan(None, Some(0)).target_cap(), None, "all included"); + assert_eq!(plan(Some(u32::MAX), Some(1)).target_cap(), Some(u32::MAX)); + } + #[test] fn a_swap_holds_until_the_berlin_month_ends() { let at = |y, m, d, h| { diff --git a/compliance-agent/src/registry.rs b/compliance-agent/src/registry.rs index e9e9267..81ea2a3 100644 --- a/compliance-agent/src/registry.rs +++ b/compliance-agent/src/registry.rs @@ -134,6 +134,13 @@ impl EntitlementCheck { 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 { + 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. @@ -877,6 +884,27 @@ mod tests { 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!({ diff --git a/compliance-agent/src/targets.rs b/compliance-agent/src/targets.rs index 6dab1e6..0dab290 100644 --- a/compliance-agent/src/targets.rs +++ b/compliance-agent/src/targets.rs @@ -17,23 +17,44 @@ use crate::database::Database; use crate::error::AgentError; /// Insert a new target for `tenant_id` and emit the `target.added` usage -/// event. Returns the stored record with its id set. +/// event: what every way of adding a target does (the API, accepting a +/// supplier's SBOM release, Managed Git, the demo seeder), so each counts +/// the same under the plan. Returns the stored record with its id set. +/// +/// # Errors +/// +/// [`AgentError::TargetLimit`] when the plan has no room for another active +/// target (the entry plan's `extra_targets: 0`); a database error. pub async fn create_target( agent: &ComplianceAgent, db: &Database, tenant_id: &str, mut target: OnboardedTarget, ) -> Result { + // The plan is read once for the cap and the billing. Without an answer + // from the registry the target is added, as a scan then runs unmetered. + let plan = agent.plan(tenant_id).await; + if let Some(cap) = plan.and_then(|p| p.target_cap()) { + let active = db + .onboarded_targets() + .count_documents(doc! { "archived_at": null }) + .await?; + if active >= u64::from(cap) { + return Err(AgentError::TargetLimit(cap)); + } + } let res = db.onboarded_targets().insert_one(&target).await?; target.id = res.inserted_id.as_object_id(); // A target beyond the plan's included ones is extra from the start (t72). - if let Some((_, billing)) = agent - .refresh_billing(tenant_id, db) - .await - .into_iter() - .find(|(id, _)| Some(*id) == target.id) - { - target.billing = billing; + if let Some(plan) = plan { + if let Some((_, billing)) = agent + .assign_billing(tenant_id, db, plan.included_targets) + .await + .into_iter() + .find(|(id, _)| Some(*id) == target.id) + { + target.billing = billing; + } } let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default(); agent.emit_usage( diff --git a/compliance-agent/tests/target_limit.rs b/compliance-agent/tests/target_limit.rs new file mode 100644 index 0000000..82693af --- /dev/null +++ b/compliance-agent/tests/target_limit.rs @@ -0,0 +1,171 @@ +//! The entry plan's target cap against a fake tenant registry: with +//! `extra_targets: 0` a new target is refused (409 `target_limit`) once the +//! included ones are all active, archiving one frees its place, and a plan +//! without the key keeps adding extra targets as before. Needs a live Mongo +//! for the agent itself; skips cleanly without one. + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +mod common; + +use std::sync::Arc; + +use axum::body::Body; +use axum::extract::Request; +use axum::http::StatusCode; +use axum::middleware::{from_fn, Next}; +use axum::routing::post; +use axum::{Extension, Json, Router}; +use mongodb::bson::doc; +use tower::ServiceExt; + +use compliance_agent::agent::ComplianceAgent; +use compliance_agent::api::handlers::onboarding::create_target; +use compliance_agent::database::DatabasePool; +use compliance_core::{OrgRole, TenantContext, TenantStatus}; + +use common::dev_config; + +/// A registry where `t-entry` includes two targets and allows no extra one, +/// and `t-standard` includes one and bills the others. +async fn fake_registry() -> String { + let app = Router::new().route( + "/v1/internal/entitlements/check", + post(|Json(body): Json| async move { + let limits = match body["tenant_id"].as_str() { + Some("t-entry") => serde_json::json!({ "included_targets": 2, "extra_targets": 0 }), + _ => serde_json::json!({ "included_targets": 1 }), + }; + Json(serde_json::json!({ "allowed": true, "status": "active", "limits": limits })) + }), + ); + 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.ok() }); + 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!("cap_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]); + let Ok(pool) = DatabasePool::connect(&uri, &db_name).await else { + eprintln!("SKIP target_limit: 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))) +} + +fn member(tenant: &str) -> TenantContext { + TenantContext { + tenant_id: tenant.into(), + tenant_slug: "acme".into(), + org_roles: vec![OrgRole::ItAdmin], + products: vec!["compliance-scanner".into()], + plan: "entry".into(), + status: TenantStatus::Active, + user_id: "u-1".into(), + user_name: None, + staff: None, + api_key: None, + } +} + +/// `POST /api/v1/targets` named `name` as a member of `tenant`. +async fn add( + agent: &Arc, + tenant: &str, + name: &str, +) -> (StatusCode, serde_json::Value) { + let ctx = member(tenant); + let inject = move |mut req: Request, next: Next| { + let ctx = ctx.clone(); + async move { + req.extensions_mut().insert(ctx); + next.run(req).await + } + }; + let app = Router::new() + .route("/api/v1/targets", post(create_target)) + .layer(Extension(agent.clone())) + .layer(from_fn(inject)); + let body = serde_json::json!({ "name": name, "target_type": "web_app" }); + let resp = app + .oneshot( + Request::builder() + .method("POST") + .uri("/api/v1/targets") + .header("content-type", "application/json") + .body(Body::from(body.to_string())) + .unwrap(), + ) + .await + .unwrap(); + let status = resp.status(); + let bytes = axum::body::to_bytes(resp.into_body(), 1 << 16) + .await + .unwrap(); + (status, serde_json::from_slice(&bytes).unwrap_or_default()) +} + +#[tokio::test] +async fn the_entry_plan_refuses_a_target_beyond_its_included_ones() { + let registry = fake_registry().await; + let Some(agent) = agent(®istry).await else { + return; + }; + + // Arrange: both included places taken. + assert_eq!( + add(&agent, "t-entry", "Steuerung A").await.0, + StatusCode::OK + ); + assert_eq!( + add(&agent, "t-entry", "Steuerung B").await.0, + StatusCode::OK + ); + + // Act + Assert: the third is refused and not stored. + let (status, body) = add(&agent, "t-entry", "Steuerung C").await; + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!(body["error"], "target_limit"); + let db = agent.db_pool.for_tenant_id("t-entry").await.unwrap(); + assert_eq!( + db.onboarded_targets() + .count_documents(doc! { "name": "Steuerung C" }) + .await + .unwrap(), + 0 + ); + + // Archiving one frees its place. + db.onboarded_targets() + .update_one( + doc! { "name": "Steuerung A" }, + doc! { "$set": { "archived_at": mongodb::bson::DateTime::now() } }, + ) + .await + .unwrap(); + let (status, body) = add(&agent, "t-entry", "Steuerung C").await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["data"]["billing"], "included"); +} + +#[tokio::test] +async fn a_plan_without_the_key_adds_extra_targets_as_before() { + let registry = fake_registry().await; + let Some(agent) = agent(®istry).await else { + return; + }; + + assert_eq!( + add(&agent, "t-standard", "Anlage 1").await.0, + StatusCode::OK + ); + let (status, body) = add(&agent, "t-standard", "Anlage 2").await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["data"]["billing"], "extra"); +} diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 13c3825..e0ab403 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -5783,6 +5783,22 @@ pub mod metering { } /// "1 zusätzliches Prüfobjekt", or that every target is included. + /// The plan's refusal of a new target (`target_limit`): its places are + /// all taken. + pub const TARGET_LIMIT: Text = Text { + de: "Ihr Tarif enthält keine weiteren Prüfobjekte. Archivieren Sie ein Prüfobjekt, \ + um ein neues anzulegen, oder wechseln Sie den Tarif.", + en: "Your plan includes no further targets. Archive a target to add a new one, \ + or change your plan.", + }; + /// A failed creation of a target in words: the plan's refusal as + /// [`TARGET_LIMIT`], anything else as it came. + pub fn target_refusal(error: &str, lang: Lang) -> String { + match crate::i18n::agent_code(error, &["target_limit"]) { + Some(_) => TARGET_LIMIT.get(lang).to_string(), + None => error.to_string(), + } + } pub fn extra_targets(extra: u32, lang: Lang) -> String { match (lang, extra) { (Lang::De, 0) => "Alle Prüfobjekte im Tarif enthalten".to_string(), @@ -8839,11 +8855,12 @@ pub mod offers { /// The agent's refusal `error` in words; anything else as it came. pub fn refusal(error: &str, lang: Lang) -> String { - const CODES: [&str; 4] = [ + const CODES: [&str; 5] = [ "answered", "ended", "target_taken", "not_supplier_component", + "target_limit", ]; let text = match crate::i18n::agent_code(error, &CODES) { Some("answered") => Text { @@ -8863,6 +8880,7 @@ pub mod offers { de: "Nur eine zugekaufte Komponente kann eine SBOM eines Zulieferers erhalten.", en: "Only a bought-in component can receive a supplier's SBOM.", }, + Some("target_limit") => super::metering::TARGET_LIMIT, _ => return error.to_string(), }; text.get(lang).to_string() diff --git a/compliance-dashboard/src/pages/onboarding.rs b/compliance-dashboard/src/pages/onboarding.rs index 1dc686d..90a26b2 100644 --- a/compliance-dashboard/src/pages/onboarding.rs +++ b/compliance-dashboard/src/pages/onboarding.rs @@ -13,7 +13,7 @@ use crate::components::no_access::use_can_write; use crate::components::page_header::PageHeader; use crate::components::scan_coverage::ScanCoverage; use crate::components::scan_runs::ScanRunList; -use crate::i18n::texts::{common, kinds, onboarding as tx}; +use crate::i18n::texts::{common, kinds, metering, onboarding as tx}; use crate::i18n::{format_bytes, use_lang, Lang}; use crate::infrastructure::onboarding::{ check_supplier_sbom, create_target, detect_target, enable_target_scans, fetch_applicable_scans, @@ -232,7 +232,7 @@ pub fn OnboardingPage(origin: String) -> Element { if let Some(err) = error() { div { class: "card", style: "border-color: var(--danger, #d33); margin-bottom: 12px;", div { class: "card-header", {tx::ERROR.get(lang)} } - div { style: "padding: 12px;", "{err}" } + div { style: "padding: 12px;", {metering::target_refusal(&err, lang)} } } } @@ -993,6 +993,17 @@ fn type_label_of(value: &str, lang: Lang) -> String { mod tests { use super::*; + #[test] + fn a_target_the_plan_has_no_room_for_reads_in_words() { + let error = "error running server function: target_limit (409) (details: None)"; + assert_eq!( + metering::target_refusal(error, Lang::En), + "Your plan includes no further targets. Archive a target to add a new one, \ + or change your plan." + ); + assert_eq!(metering::target_refusal("x (500)", Lang::De), "x (500)"); + } + #[test] fn a_refused_supplier_sbom_upload_reads_in_the_readers_language() { let error = "error running server function: supplier_sbom_refused:empty (details: None)"; -- 2.54.1 From 53da41ae946e4f79b1c62fec78af69431f1181c8 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:37:35 +0100 Subject: [PATCH 2/2] feat(metering): the entry plan bills no target as extra and leaves demo targets out Sharang's answers to the entry plan's open questions: - A plan with `extra_targets: 0` bills every active target as included, also those already beyond its included ones when a workspace moves to it: no extra-target line, no counted change scans on them. Only new targets are refused. A swap on such a plan is refused as unlimited. - The demo seeder marks its targets (`demo: true`); the cap neither counts nor refuses them. Demo targets seeded before this count as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9 --- compliance-agent/src/agent.rs | 9 +- .../src/api/handlers/onboarding.rs | 2 +- compliance-agent/src/demo_seed.rs | 1 + compliance-agent/src/metering.rs | 24 +++++ compliance-agent/src/targets.rs | 10 ++- compliance-agent/tests/target_limit.rs | 87 ++++++++++++++++++- compliance-core/src/models/onboarding.rs | 5 ++ 7 files changed, 126 insertions(+), 12 deletions(-) diff --git a/compliance-agent/src/agent.rs b/compliance-agent/src/agent.rs index dc6677b..50de408 100644 --- a/compliance-agent/src/agent.rs +++ b/compliance-agent/src/agent.rs @@ -173,8 +173,9 @@ impl ComplianceAgent { } /// Store which of the tenant's targets are the plan's included ones and - /// which are extra (t72), from the plan's `included_targets`. Without a - /// registry every target is included. Best-effort: when the plan cannot + /// which are extra (t72), from the plan's `included_targets`; a plan that + /// allows no extra target includes them all. Without a registry every + /// target is included. Best-effort: when the plan cannot /// be read or the targets not updated, the stored split stays. /// /// # Returns @@ -187,7 +188,7 @@ impl ComplianceAgent { ) -> Vec { match self.plan(tenant_id).await { Some(plan) => { - self.assign_billing(tenant_id, db, plan.included_targets) + self.assign_billing(tenant_id, db, plan.billed_included()) .await } None => Vec::new(), @@ -360,7 +361,7 @@ impl ComplianceAgent { // counts, and the plan's limits whether a counted one may run (t72). let plan = self.plan(tenant_id).await; if let Some(plan) = &plan { - self.assign_billing(tenant_id, &db, plan.included_targets) + self.assign_billing(tenant_id, &db, plan.billed_included()) .await; } let orchestrator = diff --git a/compliance-agent/src/api/handlers/onboarding.rs b/compliance-agent/src/api/handlers/onboarding.rs index 9ecf45f..1dedb42 100644 --- a/compliance-agent/src/api/handlers/onboarding.rs +++ b/compliance-agent/src/api/handlers/onboarding.rs @@ -1759,7 +1759,7 @@ pub async fn swap_target_billing( &db, incoming, outgoing, - plan.included_targets.is_some(), + plan.billed_included().is_some(), chrono::Utc::now(), ) .await diff --git a/compliance-agent/src/demo_seed.rs b/compliance-agent/src/demo_seed.rs index 345f9b0..fdb45d9 100644 --- a/compliance-agent/src/demo_seed.rs +++ b/compliance-agent/src/demo_seed.rs @@ -166,6 +166,7 @@ async fn seed_one( let mut target = compliance_core::models::OnboardedTarget::new(full_name.to_string(), demo.target_type); target.description = demo.description.clone(); + target.demo = true; for a in demo.artifacts.iter().filter(|a| !a.is_upload()) { match a.resolved_source_ref() { Some(source_ref) => target.artifacts.push(targets::reference_artifact( diff --git a/compliance-agent/src/metering.rs b/compliance-agent/src/metering.rs index 0067485..880003e 100644 --- a/compliance-agent/src/metering.rs +++ b/compliance-agent/src/metering.rs @@ -2,6 +2,7 @@ //! //! **Included and extra targets.** The oldest active targets are included, //! up to the plan's `included_targets`; every other active target is extra. +//! A plan that allows no extra target (the entry plan) includes them all. //! The split is stored on each target ([`OnboardedTarget::billing`]) and //! brought up to date before each scan and when a target is created, so //! archiving an included target moves the oldest extra one up. @@ -192,6 +193,16 @@ impl Plan { pub fn target_cap(&self) -> Option { Some(self.included_targets?.saturating_add(self.extra_targets?)) } + + /// How many targets the billing split includes; `None` includes every + /// active target. A plan that allows no extra target bills none as + /// extra, not even those already active beyond its included ones. + pub fn billed_included(&self) -> Option { + match self.extra_targets { + Some(0) => None, + _ => self.included_targets, + } + } } /// The tenant's counted Prüfungen and booked Prüftage per month. @@ -472,6 +483,19 @@ mod tests { assert_eq!(plan(Some(u32::MAX), Some(1)).target_cap(), Some(u32::MAX)); } + #[test] + fn a_plan_allowing_no_extra_target_bills_none_as_extra() { + let plan = |included_targets, extra_targets| Plan { + included_targets, + extra_targets, + limits: PlanLimits::default(), + }; + assert_eq!(plan(Some(2), Some(0)).billed_included(), None, "entry"); + assert_eq!(plan(Some(5), None).billed_included(), Some(5)); + assert_eq!(plan(Some(5), Some(2)).billed_included(), Some(5)); + assert_eq!(plan(None, None).billed_included(), None); + } + #[test] fn a_swap_holds_until_the_berlin_month_ends() { let at = |y, m, d, h| { diff --git a/compliance-agent/src/targets.rs b/compliance-agent/src/targets.rs index 0dab290..7a7d0bf 100644 --- a/compliance-agent/src/targets.rs +++ b/compliance-agent/src/targets.rs @@ -24,7 +24,8 @@ use crate::error::AgentError; /// # Errors /// /// [`AgentError::TargetLimit`] when the plan has no room for another active -/// target (the entry plan's `extra_targets: 0`); a database error. +/// target (the entry plan's `extra_targets: 0`); demo targets are outside +/// that count. A database error. pub async fn create_target( agent: &ComplianceAgent, db: &Database, @@ -34,10 +35,11 @@ pub async fn create_target( // The plan is read once for the cap and the billing. Without an answer // from the registry the target is added, as a scan then runs unmetered. let plan = agent.plan(tenant_id).await; - if let Some(cap) = plan.and_then(|p| p.target_cap()) { + // Demo targets are outside the cap: neither refused nor counted. + if let Some(cap) = plan.and_then(|p| p.target_cap()).filter(|_| !target.demo) { let active = db .onboarded_targets() - .count_documents(doc! { "archived_at": null }) + .count_documents(doc! { "archived_at": null, "demo": { "$ne": true } }) .await?; if active >= u64::from(cap) { return Err(AgentError::TargetLimit(cap)); @@ -48,7 +50,7 @@ pub async fn create_target( // A target beyond the plan's included ones is extra from the start (t72). if let Some(plan) = plan { if let Some((_, billing)) = agent - .assign_billing(tenant_id, db, plan.included_targets) + .assign_billing(tenant_id, db, plan.billed_included()) .await .into_iter() .find(|(id, _)| Some(*id) == target.id) diff --git a/compliance-agent/tests/target_limit.rs b/compliance-agent/tests/target_limit.rs index 82693af..725ceed 100644 --- a/compliance-agent/tests/target_limit.rs +++ b/compliance-agent/tests/target_limit.rs @@ -1,8 +1,9 @@ //! The entry plan's target cap against a fake tenant registry: with //! `extra_targets: 0` a new target is refused (409 `target_limit`) once the -//! included ones are all active, archiving one frees its place, and a plan -//! without the key keeps adding extra targets as before. Needs a live Mongo -//! for the agent itself; skips cleanly without one. +//! included ones are all active, archiving one frees its place, targets +//! already beyond it are never billed as extra, demo targets are outside the +//! cap, and a plan without the key keeps adding extra targets as before. +//! Needs a live Mongo for the agent itself; skips cleanly without one. #![allow(clippy::expect_used, clippy::unwrap_used)] @@ -22,6 +23,7 @@ use tower::ServiceExt; use compliance_agent::agent::ComplianceAgent; use compliance_agent::api::handlers::onboarding::create_target; use compliance_agent::database::DatabasePool; +use compliance_core::models::{OnboardedTarget, TargetBilling, TargetType}; use compliance_core::{OrgRole, TenantContext, TenantStatus}; use common::dev_config; @@ -169,3 +171,82 @@ async fn a_plan_without_the_key_adds_extra_targets_as_before() { assert_eq!(status, StatusCode::OK); assert_eq!(body["data"]["billing"], "extra"); } + +#[tokio::test] +async fn targets_already_beyond_the_entry_plan_are_never_billed_extra() { + let registry = fake_registry().await; + let Some(agent) = agent(®istry).await else { + return; + }; + // Arrange: three active targets from before the plan, one billed extra. + let db = agent.db_pool.for_tenant_id("t-entry").await.unwrap(); + for (name, billing) in [ + ("Anlage 1", TargetBilling::Included), + ("Anlage 2", TargetBilling::Included), + ("Anlage 3", TargetBilling::Extra), + ] { + let mut target = OnboardedTarget::new(name.into(), TargetType::WebApp); + target.billing = billing; + db.onboarded_targets().insert_one(&target).await.unwrap(); + } + + // Act + agent.refresh_billing("t-entry", &db).await; + + // Assert: all three stay, none is extra, and a fourth is refused. + let extra = mongodb::bson::to_bson(&TargetBilling::Extra).unwrap(); + assert_eq!( + db.onboarded_targets() + .count_documents(doc! { "billing": extra }) + .await + .unwrap(), + 0 + ); + assert_eq!( + db.onboarded_targets() + .count_documents(doc! {}) + .await + .unwrap(), + 3 + ); + assert_eq!( + add(&agent, "t-entry", "Anlage 4").await.0, + StatusCode::CONFLICT + ); +} + +#[tokio::test] +async fn demo_targets_are_neither_counted_nor_refused() { + let registry = fake_registry().await; + let Some(agent) = agent(®istry).await else { + return; + }; + let db = agent.db_pool.for_tenant_id("t-entry").await.unwrap(); + let demo = |name: &str| { + let mut target = OnboardedTarget::new(name.into(), TargetType::WebApp); + target.demo = true; + target + }; + + // A demo target leaves both included places free. + compliance_agent::targets::create_target(&agent, &db, "t-entry", demo("Demo A")) + .await + .expect("demo target added"); + assert_eq!( + add(&agent, "t-entry", "Steuerung A").await.0, + StatusCode::OK + ); + assert_eq!( + add(&agent, "t-entry", "Steuerung B").await.0, + StatusCode::OK + ); + assert_eq!( + add(&agent, "t-entry", "Steuerung C").await.0, + StatusCode::CONFLICT + ); + + // With the places taken, the seeder still adds its targets. + compliance_agent::targets::create_target(&agent, &db, "t-entry", demo("Demo B")) + .await + .expect("demo target added at the cap"); +} diff --git a/compliance-core/src/models/onboarding.rs b/compliance-core/src/models/onboarding.rs index 41d110a..923a901 100644 --- a/compliance-core/src/models/onboarding.rs +++ b/compliance-core/src/models/onboarding.rs @@ -708,6 +708,10 @@ pub struct OnboardedTarget { /// order number and firmware against Siemens' CSAF advisories. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub devices: Vec, + /// Whether the demo seeder added the target: a plan's cap on active + /// targets neither counts nor refuses it. Not settable through the API. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub demo: bool, /// Creation timestamp. #[serde( default = "chrono::Utc::now", @@ -771,6 +775,7 @@ impl OnboardedTarget { included_until: None, supplier: None, devices: Vec::new(), + demo: false, created_at: now, updated_at: now, } -- 2.54.1