Compare commits

...
Author SHA1 Message Date
Sharang ParnerkarandClaude Opus 5.5 53da41ae94 feat(metering): the entry plan bills no target as extra and leaves demo targets out
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (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 5m15s
CI / Check (pull_request) Successful in 23m9s
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 19:37:35 +01:00
Sharang ParnerkarandClaude Opus 5.5 7ef6387d39 feat(metering): a plan can allow no extra targets (entry plan)
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 5m29s
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Check (pull_request) Successful in 22m56s
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 15:07:53 +01:00
13 changed files with 475 additions and 48 deletions

No files matched your search

+7 -5
View File
@@ -173,8 +173,9 @@ impl ComplianceAgent {
} }
/// Store which of the tenant's targets are the plan's included ones and /// 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 /// which are extra (t72), from the plan's `included_targets`; a plan that
/// registry every target is included. Best-effort: when the plan cannot /// 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. /// be read or the targets not updated, the stored split stays.
/// ///
/// # Returns /// # Returns
@@ -187,7 +188,7 @@ impl ComplianceAgent {
) -> Vec<BillingChange> { ) -> Vec<BillingChange> {
match self.plan(tenant_id).await { match self.plan(tenant_id).await {
Some(plan) => { Some(plan) => {
self.assign_billing(tenant_id, db, plan.included_targets) self.assign_billing(tenant_id, db, plan.billed_included())
.await .await
} }
None => Vec::new(), None => Vec::new(),
@@ -205,6 +206,7 @@ impl ComplianceAgent {
match registry.check_entitlement(tenant_id, None, None).await { match registry.check_entitlement(tenant_id, None, None).await {
Ok(check) => Some(crate::metering::Plan { Ok(check) => Some(crate::metering::Plan {
included_targets: check.included_targets(), included_targets: check.included_targets(),
extra_targets: check.extra_targets(),
limits: check.plan_limits(), limits: check.plan_limits(),
}), }),
Err(e) => { Err(e) => {
@@ -216,7 +218,7 @@ impl ComplianceAgent {
/// Store the billing of the tenant's targets for a plan that includes /// Store the billing of the tenant's targets for a plan that includes
/// `included` targets; best-effort. /// `included` targets; best-effort.
async fn assign_billing( pub(crate) async fn assign_billing(
&self, &self,
tenant_id: &str, tenant_id: &str,
db: &crate::database::Database, db: &crate::database::Database,
@@ -359,7 +361,7 @@ impl ComplianceAgent {
// counts, and the plan's limits whether a counted one may run (t72). // counts, and the plan's limits whether a counted one may run (t72).
let plan = self.plan(tenant_id).await; let plan = self.plan(tenant_id).await;
if let Some(plan) = &plan { if let Some(plan) = &plan {
self.assign_billing(tenant_id, &db, plan.included_targets) self.assign_billing(tenant_id, &db, plan.billed_included())
.await; .await;
} }
let orchestrator = let orchestrator =
+3 -3
View File
@@ -490,7 +490,7 @@ pub async fn list_offers(
responses( responses(
(status = 200, description = "Accepted (`data`: the offer)"), (status = 200, description = "Accepted (`data`: the offer)"),
(status = 404, description = "No such offer, or no such component"), (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 = 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 = 503, description = "The registry cannot be asked"),
(status = 401, description = "No valid bearer token"), (status = 401, description = "No valid bearer token"),
@@ -601,9 +601,9 @@ pub async fn accept_offer(
.await .await
{ {
Ok(created) => created, Ok(created) => created,
Err(status) => { Err(e) => {
unclaim(&db, offer.id).await?; 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(); let created_id = created.id.map(|o| o.to_hex()).unwrap_or_default();
+43 -27
View File
@@ -20,6 +20,7 @@ use compliance_core::tenant_ctx::TenantCtx;
use crate::agent::ComplianceAgent; use crate::agent::ComplianceAgent;
use crate::classify::{classify_target, MockFirmwareDetector}; use crate::classify::{classify_target, MockFirmwareDetector};
use crate::error::AgentError;
use crate::secrets::SecretError; use crate::secrets::SecretError;
use crate::targets::{upload_dest, uploaded_artifact, MAX_UPLOAD_BYTES}; use crate::targets::{upload_dest, uploaded_artifact, MAX_UPLOAD_BYTES};
@@ -405,7 +406,8 @@ async fn findings_counts(
request_body = CreateTargetRequest, request_body = CreateTargetRequest,
responses( responses(
(status = 200, description = "The new target"), (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 = 503, description = "A credential cannot be sealed"),
(status = 401, description = "No valid bearer token"), (status = 401, description = "No valid bearer token"),
) )
@@ -415,20 +417,25 @@ pub async fn create_target(
Extension(agent): AgentExt, Extension(agent): AgentExt,
tenant: TenantCtx, tenant: TenantCtx,
Json(req): Json<CreateTargetRequest>, Json(req): Json<CreateTargetRequest>,
) -> Result<Json<ApiResponse<OnboardedTarget>>, StatusCode> { ) -> Result<Json<ApiResponse<OnboardedTarget>>, axum::response::Response> {
use axum::response::IntoResponse;
let mut target = OnboardedTarget::new(req.name, req.target_type); let mut target = OnboardedTarget::new(req.name, req.target_type);
target.description = req.description; target.description = req.description;
if let Some(supplier) = req.supplier { 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| { target.artifacts = merge_artifacts(&agent.secrets, &req.artifacts, &[]).map_err(|e| {
tracing::error!("storing a credential: {e}"); tracing::error!("storing a credential: {e}");
StatusCode::SERVICE_UNAVAILABLE StatusCode::SERVICE_UNAVAILABLE.into_response()
})?; })?;
let db = tenant_db(&agent, &tenant).await?; let db = tenant_db(&agent, &tenant)
let target = insert_target(&agent, &db, &tenant.0.tenant_id, target).await?; .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 { Ok(Json(ApiResponse {
data: target.redacted(), data: target.redacted(),
total: None, 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 /// Store a new `target` of tenant `tenant_id` and count it
/// of adding a target does (the API, and accepting a supplier's SBOM release, /// ([`crate::targets::create_target`]), then read its supplier's CSAF feed.
/// #1028), so each counts the same under the plan. /// What the API and accepting a supplier's SBOM release (#1028) do.
/// ///
/// # Errors /// # 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( pub(super) async fn insert_target(
agent: &Arc<ComplianceAgent>, agent: &Arc<ComplianceAgent>,
db: &crate::database::Database, db: &crate::database::Database,
tenant_id: &str, tenant_id: &str,
mut target: OnboardedTarget, target: OnboardedTarget,
) -> Result<OnboardedTarget, StatusCode> { ) -> Result<OnboardedTarget, AgentError> {
let res = db let target = crate::targets::create_target(agent, db, tenant_id, target).await?;
.onboarded_targets()
.insert_one(&target)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
target.id = res.inserted_id.as_object_id();
refresh_supplier_csaf(agent, tenant_id, target.supplier.as_ref()); 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) 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. /// One target, credentials redacted.
#[utoipa::path( #[utoipa::path(
get, get,
@@ -1743,7 +1759,7 @@ pub async fn swap_target_billing(
&db, &db,
incoming, incoming,
outgoing, outgoing,
plan.included_targets.is_some(), plan.billed_included().is_some(),
chrono::Utc::now(), chrono::Utc::now(),
) )
.await .await
+1
View File
@@ -166,6 +166,7 @@ async fn seed_one(
let mut target = let mut target =
compliance_core::models::OnboardedTarget::new(full_name.to_string(), demo.target_type); compliance_core::models::OnboardedTarget::new(full_name.to_string(), demo.target_type);
target.description = demo.description.clone(); target.description = demo.description.clone();
target.demo = true;
for a in demo.artifacts.iter().filter(|a| !a.is_upload()) { for a in demo.artifacts.iter().filter(|a| !a.is_upload()) {
match a.resolved_source_ref() { match a.resolved_source_ref() {
Some(source_ref) => target.artifacts.push(targets::reference_artifact( Some(source_ref) => target.artifacts.push(targets::reference_artifact(
+7
View File
@@ -47,6 +47,11 @@ pub enum AgentError {
#[error("not run: {0:?}")] #[error("not run: {0:?}")]
NotAdmitted(compliance_core::models::Refusal), 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}")] #[error("{0}")]
Other(String), Other(String),
} }
@@ -79,6 +84,7 @@ impl AgentError {
| Self::Secret(_) | Self::Secret(_)
| Self::Exec(_) | Self::Exec(_)
| Self::NotAdmitted(_) | Self::NotAdmitted(_)
| Self::TargetLimit(_)
| Self::Other(_) => ( | Self::Other(_) => (
RunErrorCode::Internal, RunErrorCode::Internal,
"the scan stopped because of an internal error", "the scan stopped because of an internal error",
@@ -91,6 +97,7 @@ impl From<AgentError> for axum::http::StatusCode {
fn from(err: AgentError) -> Self { fn from(err: AgentError) -> Self {
match err { match err {
AgentError::Core(CoreError::NotFound(_)) => axum::http::StatusCode::NOT_FOUND, AgentError::Core(CoreError::NotFound(_)) => axum::http::StatusCode::NOT_FOUND,
AgentError::TargetLimit(_) => axum::http::StatusCode::CONFLICT,
_ => axum::http::StatusCode::INTERNAL_SERVER_ERROR, _ => axum::http::StatusCode::INTERNAL_SERVER_ERROR,
} }
} }
+17 -2
View File
@@ -467,6 +467,10 @@ pub enum Outcome {
Ignored(&'static str), 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`. /// Carry out a routed delivery for `tenant_id`.
/// ///
/// # Errors /// # Errors
@@ -485,7 +489,10 @@ pub async fn apply_action(
archive_target(db, &source.base_url, repo.id).await?, archive_target(db, &source.base_url, repo.id).await?,
)), )),
SourceAction::Created(repo) => { 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. // An empty repository has nothing to scan; its first push will.
let scan = ensured.created && !repo.empty; let scan = ensured.created && !repo.empty;
if scan { if scan {
@@ -497,7 +504,10 @@ pub async fn apply_action(
}) })
} }
SourceAction::Push(repo) => { 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); spawn_scan(agent, tenant_id, &ensured.target_id, ScanTrigger::Webhook);
Ok(Outcome::Ensured { Ok(Outcome::Ensured {
target_id: ensured.target_id, target_id: ensured.target_id,
@@ -608,6 +618,11 @@ pub async fn sync_with<L: RepoLister>(
} }
} }
Ok(_) => report.refreshed += 1, 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) => { Err(err) => {
tracing::warn!(tenant_id, repo = %repo.full_name, "managed git sync: {err}"); tracing::warn!(tenant_id, repo = %repo.full_name, "managed git sync: {err}");
} }
+49
View File
@@ -2,6 +2,7 @@
//! //!
//! **Included and extra targets.** The oldest active targets are included, //! **Included and extra targets.** The oldest active targets are included,
//! up to the plan's `included_targets`; every other active target is extra. //! 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 //! The split is stored on each target ([`OnboardedTarget::billing`]) and
//! brought up to date before each scan and when a target is created, so //! brought up to date before each scan and when a target is created, so
//! archiving an included target moves the oldest extra one up. //! archiving an included target moves the oldest extra one up.
@@ -179,10 +180,31 @@ pub async fn swap(
pub struct Plan { pub struct Plan {
/// How many targets the plan includes; `None` is unlimited. /// How many targets the plan includes; `None` is unlimited.
pub included_targets: Option<u32>, pub included_targets: Option<u32>,
/// How many extra targets may be active besides; `None` is unlimited.
pub extra_targets: Option<u32>,
/// The quota and the customer's Prüftag cap. /// The quota and the customer's Prüftag cap.
pub limits: PlanLimits, 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<u32> {
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<u32> {
match self.extra_targets {
Some(0) => None,
_ => self.included_targets,
}
}
}
/// The tenant's counted Prüfungen and booked Prüftage per month. /// The tenant's counted Prüfungen and booked Prüftage per month.
const MONTHS: &str = "metering_months"; const MONTHS: &str = "metering_months";
/// Each target's Prüftag per day, once the quota was used up. /// Each target's Prüftag per day, once the quota was used up.
@@ -447,6 +469,33 @@ mod tests {
use super::*; use super::*;
use chrono::TimeZone; 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_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] #[test]
fn a_swap_holds_until_the_berlin_month_ends() { fn a_swap_holds_until_the_berlin_month_ends() {
let at = |y, m, d, h| { let at = |y, m, d, h| {
+28
View File
@@ -134,6 +134,13 @@ impl EntitlementCheck {
self.limit("included_targets") 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 /// The plan's monthly quota and the customer's Prüftag cap (t72), from
/// `limits.monthly_pruefungen` and `limits.prueftag_cap`; a missing or /// `limits.monthly_pruefungen` and `limits.prueftag_cap`; a missing or
/// null key is no limit. /// null key is no limit.
@@ -877,6 +884,27 @@ mod tests {
assert_eq!(check(serde_json::Value::Null).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] #[test]
fn the_plan_sets_the_quota_and_the_cap() { fn the_plan_sets_the_quota_and_the_cap() {
let check: EntitlementCheck = serde_json::from_value(serde_json::json!({ let check: EntitlementCheck = serde_json::from_value(serde_json::json!({
+31 -8
View File
@@ -17,23 +17,46 @@ use crate::database::Database;
use crate::error::AgentError; use crate::error::AgentError;
/// Insert a new target for `tenant_id` and emit the `target.added` usage /// 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`); demo targets are outside
/// that count. A database error.
pub async fn create_target( pub async fn create_target(
agent: &ComplianceAgent, agent: &ComplianceAgent,
db: &Database, db: &Database,
tenant_id: &str, tenant_id: &str,
mut target: OnboardedTarget, mut target: OnboardedTarget,
) -> Result<OnboardedTarget, AgentError> { ) -> Result<OnboardedTarget, AgentError> {
// 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;
// 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, "demo": { "$ne": true } })
.await?;
if active >= u64::from(cap) {
return Err(AgentError::TargetLimit(cap));
}
}
let res = db.onboarded_targets().insert_one(&target).await?; let res = db.onboarded_targets().insert_one(&target).await?;
target.id = res.inserted_id.as_object_id(); target.id = res.inserted_id.as_object_id();
// A target beyond the plan's included ones is extra from the start (t72). // A target beyond the plan's included ones is extra from the start (t72).
if let Some((_, billing)) = agent if let Some(plan) = plan {
.refresh_billing(tenant_id, db) if let Some((_, billing)) = agent
.await .assign_billing(tenant_id, db, plan.billed_included())
.into_iter() .await
.find(|(id, _)| Some(*id) == target.id) .into_iter()
{ .find(|(id, _)| Some(*id) == target.id)
target.billing = billing; {
target.billing = billing;
}
} }
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default(); let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
agent.emit_usage( agent.emit_usage(
+252
View File
@@ -0,0 +1,252 @@
//! 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, 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)]
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::models::{OnboardedTarget, TargetBilling, TargetType};
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<serde_json::Value>| 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<Arc<ComplianceAgent>> {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db_name = format!("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<ComplianceAgent>,
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(&registry).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(&registry).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");
}
#[tokio::test]
async fn targets_already_beyond_the_entry_plan_are_never_billed_extra() {
let registry = fake_registry().await;
let Some(agent) = agent(&registry).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(&registry).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");
}
+5
View File
@@ -708,6 +708,10 @@ pub struct OnboardedTarget {
/// order number and firmware against Siemens' CSAF advisories. /// order number and firmware against Siemens' CSAF advisories.
#[serde(default, skip_serializing_if = "Vec::is_empty")] #[serde(default, skip_serializing_if = "Vec::is_empty")]
pub devices: Vec<super::PlcDevice>, pub devices: Vec<super::PlcDevice>,
/// 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. /// Creation timestamp.
#[serde( #[serde(
default = "chrono::Utc::now", default = "chrono::Utc::now",
@@ -771,6 +775,7 @@ impl OnboardedTarget {
included_until: None, included_until: None,
supplier: None, supplier: None,
devices: Vec::new(), devices: Vec::new(),
demo: false,
created_at: now, created_at: now,
updated_at: now, updated_at: now,
} }
+19 -1
View File
@@ -5783,6 +5783,22 @@ pub mod metering {
} }
/// "1 zusätzliches Prüfobjekt", or that every target is included. /// "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 { pub fn extra_targets(extra: u32, lang: Lang) -> String {
match (lang, extra) { match (lang, extra) {
(Lang::De, 0) => "Alle Prüfobjekte im Tarif enthalten".to_string(), (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. /// The agent's refusal `error` in words; anything else as it came.
pub fn refusal(error: &str, lang: Lang) -> String { pub fn refusal(error: &str, lang: Lang) -> String {
const CODES: [&str; 4] = [ const CODES: [&str; 5] = [
"answered", "answered",
"ended", "ended",
"target_taken", "target_taken",
"not_supplier_component", "not_supplier_component",
"target_limit",
]; ];
let text = match crate::i18n::agent_code(error, &CODES) { let text = match crate::i18n::agent_code(error, &CODES) {
Some("answered") => Text { Some("answered") => Text {
@@ -8863,6 +8880,7 @@ pub mod offers {
de: "Nur eine zugekaufte Komponente kann eine SBOM eines Zulieferers erhalten.", de: "Nur eine zugekaufte Komponente kann eine SBOM eines Zulieferers erhalten.",
en: "Only a bought-in component can receive a supplier's SBOM.", en: "Only a bought-in component can receive a supplier's SBOM.",
}, },
Some("target_limit") => super::metering::TARGET_LIMIT,
_ => return error.to_string(), _ => return error.to_string(),
}; };
text.get(lang).to_string() text.get(lang).to_string()
+13 -2
View File
@@ -13,7 +13,7 @@ use crate::components::no_access::use_can_write;
use crate::components::page_header::PageHeader; use crate::components::page_header::PageHeader;
use crate::components::scan_coverage::ScanCoverage; use crate::components::scan_coverage::ScanCoverage;
use crate::components::scan_runs::ScanRunList; 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::i18n::{format_bytes, use_lang, Lang};
use crate::infrastructure::onboarding::{ use crate::infrastructure::onboarding::{
check_supplier_sbom, create_target, detect_target, enable_target_scans, fetch_applicable_scans, 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() { if let Some(err) = error() {
div { class: "card", style: "border-color: var(--danger, #d33); margin-bottom: 12px;", div { class: "card", style: "border-color: var(--danger, #d33); margin-bottom: 12px;",
div { class: "card-header", {tx::ERROR.get(lang)} } 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 { mod tests {
use super::*; 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] #[test]
fn a_refused_supplier_sbom_upload_reads_in_the_readers_language() { fn a_refused_supplier_sbom_upload_reads_in_the_readers_language() {
let error = "error running server function: supplier_sbom_refused:empty (details: None)"; let error = "error running server function: supplier_sbom_refused:empty (details: None)";