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
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
This commit is contained in:
1 parent
5b4d8bbe5f
commit
7ef6387d39
11 files changed
+356
-43
No files matched your search
@@ -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,
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<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);
|
||||
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<ComplianceAgent>,
|
||||
db: &crate::database::Database,
|
||||
tenant_id: &str,
|
||||
mut target: OnboardedTarget,
|
||||
) -> Result<OnboardedTarget, StatusCode> {
|
||||
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<OnboardedTarget, AgentError> {
|
||||
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,
|
||||
|
||||
@@ -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<AgentError> 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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<L: RepoLister>(
|
||||
}
|
||||
}
|
||||
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}");
|
||||
}
|
||||
|
||||
@@ -179,10 +179,21 @@ pub async fn swap(
|
||||
pub struct Plan {
|
||||
/// How many targets the plan includes; `None` is unlimited.
|
||||
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.
|
||||
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?))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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| {
|
||||
|
||||
@@ -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<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.
|
||||
@@ -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!({
|
||||
|
||||
@@ -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<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;
|
||||
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(
|
||||
|
||||
@@ -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<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(®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");
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -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)";
|
||||
|
||||
Reference in new issue
Block a user