From dd46af6f248f20fe503960d49e9a73608d5a7c97 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Sun, 29 Nov 2026 09:56:18 +0000 Subject: [PATCH] fix(metering): a demo target given the tenant's own sources counts under the cap (#1080) --- .../src/api/handlers/onboarding.rs | 51 +++++++- compliance-agent/src/targets.rs | 89 ++++++++++++-- compliance-agent/tests/target_limit.rs | 110 +++++++++++++++++- compliance-dashboard/src/i18n/texts.rs | 20 +++- .../src/infrastructure/onboarding.rs | 4 +- compliance-dashboard/src/pages/onboarding.rs | 17 +++ compliance-dashboard/src/pages/target.rs | 5 +- 7 files changed, 279 insertions(+), 17 deletions(-) diff --git a/compliance-agent/src/api/handlers/onboarding.rs b/compliance-agent/src/api/handlers/onboarding.rs index 1dedb42..60107e6 100644 --- a/compliance-agent/src/api/handlers/onboarding.rs +++ b/compliance-agent/src/api/handlers/onboarding.rs @@ -576,6 +576,7 @@ pub async fn list_webhook_deliveries( (status = 200, description = "The changed target"), (status = 400, description = "Not an id"), (status = 404, description = "No such target"), + (status = 409, description = "`target_limit`: other artifacts would make a demo target the tenant's own, and the plan has no room for it"), (status = 422, description = "A malformed body, a project that is not the tenant's, or a device whose order number or firmware is not one"), (status = 503, description = "A credential cannot be sealed"), (status = 401, description = "No valid bearer token"), @@ -587,7 +588,7 @@ pub async fn update_target( tenant: TenantCtx, Path(id): Path, Json(req): Json, -) -> Result>, StatusCode> { +) -> Result>, UploadRefusal> { let oid = parse_oid(&id)?; let db = tenant_db(&agent, &tenant).await?; @@ -659,9 +660,14 @@ pub async fn update_target( ); set.insert("project_ids", ids); } + // A demo target given other sources becomes the tenant's own (below). + let mut claimed_demo = None; if let (Some(arts), Some(stored)) = (req.artifacts, stored.as_ref()) { let built = merge_artifacts(&agent.secrets, &arts, &stored.artifacts).map_err(credential_error)?; + if !crate::targets::same_sources(&stored.artifacts, &built) { + claimed_demo = Some(stored); + } set.insert( "artifacts", to_bson(&built).map_err(|_| StatusCode::BAD_REQUEST)?, @@ -693,6 +699,11 @@ pub async fn update_target( } update.insert("$set", set); + if let Some(stored) = claimed_demo { + crate::targets::claim_demo(&agent, &db, &tenant.0.tenant_id, stored) + .await + .map_err(demo_refused)?; + } db.onboarded_targets() .update_one(doc! { "_id": oid }, update) .await @@ -708,7 +719,22 @@ pub async fn update_target( }); } - get_target(Extension(agent), tenant, Path(id)).await + Ok(get_target(Extension(agent), tenant, Path(id)).await?) +} + +/// A demo target not made the tenant's own, as the API answers: 409 +/// `target_limit` when the plan has no room for it, else 500. +fn demo_refused(e: AgentError) -> UploadRefusal { + match e { + AgentError::TargetLimit(cap) => { + tracing::info!(cap, "demo target kept: the plan's targets are all active"); + UploadRefusal::because(StatusCode::CONFLICT, "target_limit", "target_limit") + } + e => { + tracing::error!("claiming a demo target: {e}"); + StatusCode::INTERNAL_SERVER_ERROR.into() + } + } } /// Remove a deleted target's clones, uploads, work trees and blobs from disk. @@ -888,6 +914,8 @@ async fn delete_session_data(db: &crate::database::Database, session_id: &str) { responses( (status = 200, description = "The target with the artifact"), (status = 400, description = "Not an id"), + (status = 404, description = "No such target"), + (status = 409, description = "`target_limit`: the artifact would make a demo target the tenant's own, and the plan has no room for it"), (status = 422, description = "A malformed body"), (status = 503, description = "A credential cannot be sealed"), (status = 401, description = "No valid bearer token"), @@ -899,9 +927,18 @@ pub async fn add_artifact( tenant: TenantCtx, Path(id): Path, Json(input): Json, -) -> Result>, StatusCode> { +) -> Result>, UploadRefusal> { let oid = parse_oid(&id)?; let db = tenant_db(&agent, &tenant).await?; + let stored = db + .onboarded_targets() + .find_one(doc! { "_id": oid }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + crate::targets::claim_demo(&agent, &db, &tenant.0.tenant_id, &stored) + .await + .map_err(demo_refused)?; let artifact = input.build(&agent.secrets, None).map_err(|e| { tracing::error!("storing a credential: {e}"); StatusCode::SERVICE_UNAVAILABLE @@ -914,7 +951,7 @@ pub async fn add_artifact( ) .await .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - get_target(Extension(agent), tenant, Path(id)).await + Ok(get_target(Extension(agent), tenant, Path(id)).await?) } /// The multipart form of an artifact upload. @@ -957,6 +994,7 @@ pub struct UploadArtifactForm { responses( (status = 200, description = "The target with the artifact"), (status = 404, description = "No such target"), + (status = 409, description = "`target_limit`: the file would make a demo target the tenant's own, and the plan has no room for it"), (status = 400, description = "Not an id, or a missing or unknown field"), (status = 413, description = "The file is too large (a supplier SBOM: over 20 MiB)"), (status = 415, description = "An archive format that cannot be unpacked"), @@ -981,6 +1019,11 @@ pub async fn upload_artifact( else { return Err(StatusCode::NOT_FOUND.into()); }; + // Refused before the file streams in. A demo target becomes the + // tenant's own even when the file then turns out unreadable. + crate::targets::claim_demo(&agent, &db, &tenant.0.tenant_id, &stored_target) + .await + .map_err(demo_refused)?; let mut kind: Option = None; let mut plc_format: Option = None; diff --git a/compliance-agent/src/targets.rs b/compliance-agent/src/targets.rs index 7a7d0bf..3eee7a6 100644 --- a/compliance-agent/src/targets.rs +++ b/compliance-agent/src/targets.rs @@ -16,6 +16,66 @@ use crate::classify::{classify_target, MockFirmwareDetector}; use crate::database::Database; use crate::error::AgentError; +/// Whether one more counted target fits under `cap`: the active targets +/// other than demo ones are fewer. +/// +/// # Errors +/// +/// [`AgentError::TargetLimit`] when they are not; a database error. +async fn room_for_one(db: &Database, cap: u32) -> Result<(), AgentError> { + let counted = db + .onboarded_targets() + .count_documents(doc! { "archived_at": null, "demo": { "$ne": true } }) + .await?; + if counted >= u64::from(cap) { + return Err(AgentError::TargetLimit(cap)); + } + Ok(()) +} + +/// Make a demo target the tenant's own before its artifacts change: from +/// then on it counts under the plan's cap like any other target. Without +/// that, a demo target pointed at the tenant's own code would sit outside +/// the cap. A target that is not a demo one is left as it is, and an +/// archived one is not checked against the cap (it does not count yet). +/// +/// # Errors +/// +/// [`AgentError::TargetLimit`] when the plan has no room for one more +/// counted target; the target then stays a demo one. A database error. +pub async fn claim_demo( + agent: &ComplianceAgent, + db: &Database, + tenant_id: &str, + target: &OnboardedTarget, +) -> Result<(), AgentError> { + let Some(id) = target.id.filter(|_| target.demo) else { + return Ok(()); + }; + if target.archived_at.is_none() { + if let Some(cap) = agent.plan(tenant_id).await.and_then(|p| p.target_cap()) { + room_for_one(db, cap).await?; + } + } + db.onboarded_targets() + .update_one(doc! { "_id": id }, doc! { "$unset": { "demo": "" } }) + .await?; + Ok(()) +} + +/// Whether two artifact lists point at the same sources: the same kinds and +/// references, in any order. Credentials, branches and scan state may +/// differ; the dashboard's editor sends every artifact on each save. +pub fn same_sources(a: &[Artifact], b: &[Artifact]) -> bool { + let mut taken = vec![false; b.len()]; + a.len() == b.len() + && a.iter().all(|x| { + let found = (0..b.len()) + .find(|&i| !taken[i] && b[i].kind == x.kind && b[i].source_ref == x.source_ref); + found.map(|i| taken[i] = true).is_some() + }) +} + /// Insert a new target for `tenant_id` and emit the `target.added` usage /// 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 @@ -37,13 +97,7 @@ pub async fn create_target( 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)); - } + room_for_one(db, cap).await?; } let res = db.onboarded_targets().insert_one(&target).await?; target.id = res.inserted_id.as_object_id(); @@ -223,6 +277,27 @@ pub async fn detect_target( mod tests { use super::*; + #[test] + fn only_another_source_changes_a_targets_sources() { + let repo = Artifact::git_repo("https://git.example/demo.git", "main"); + let site = Artifact::live_url("https://demo.example"); + let other_branch = Artifact::git_repo("https://git.example/demo.git", "dev"); + let own = Artifact::git_repo("https://git.example/own.git", "main"); + let both = [repo.clone(), site.clone()]; + let reordered = [site, repo.clone()]; + let just_repo = std::slice::from_ref(&repo); + let repo_twice = [repo.clone(), repo.clone()]; + + assert!(same_sources(&both, &reordered)); + assert!( + same_sources(just_repo, &[other_branch]), + "a branch is no new source" + ); + assert!(!same_sources(just_repo, &[own])); + assert!(!same_sources(just_repo, &both)); + assert!(!same_sources(&repo_twice, just_repo)); + } + #[test] fn uploaded_artifact_records_stored_path_for_file_kinds() { let a = uploaded_artifact( diff --git a/compliance-agent/tests/target_limit.rs b/compliance-agent/tests/target_limit.rs index 725ceed..a3bcb5e 100644 --- a/compliance-agent/tests/target_limit.rs +++ b/compliance-agent/tests/target_limit.rs @@ -2,7 +2,8 @@ //! `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. +//! cap until they are given the tenant's own sources, 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)] @@ -15,13 +16,13 @@ use axum::body::Body; use axum::extract::Request; use axum::http::StatusCode; use axum::middleware::{from_fn, Next}; -use axum::routing::post; +use axum::routing::{patch, 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::api::handlers::onboarding::{create_target, update_target}; use compliance_agent::database::DatabasePool; use compliance_core::models::{OnboardedTarget, TargetBilling, TargetType}; use compliance_core::{OrgRole, TenantContext, TenantStatus}; @@ -250,3 +251,106 @@ async fn demo_targets_are_neither_counted_nor_refused() { .await .expect("demo target added at the cap"); } + +/// `PATCH /api/v1/targets/{id}` with `body` as a member of `tenant`. +async fn edit( + agent: &Arc, + tenant: &str, + id: &str, + body: serde_json::Value, +) -> (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/{id}", patch(update_target)) + .layer(Extension(agent.clone())) + .layer(from_fn(inject)); + let resp = app + .oneshot( + Request::builder() + .method("PATCH") + .uri(format!("/api/v1/targets/{id}")) + .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 a_demo_target_given_the_tenants_own_sources_counts() { + 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 mut demo = OnboardedTarget::new("Demo · Pumpe".into(), TargetType::WebApp); + demo.demo = true; + demo.artifacts + .push(compliance_core::models::Artifact::live_url( + "https://demo.example", + )); + let demo = compliance_agent::targets::create_target(&agent, &db, "t-entry", demo) + .await + .unwrap(); + let id = demo.id.unwrap().to_hex(); + assert_eq!( + add(&agent, "t-entry", "Steuerung A").await.0, + StatusCode::OK + ); + assert_eq!( + add(&agent, "t-entry", "Steuerung B").await.0, + StatusCode::OK + ); + let is_demo = || async { + db.onboarded_targets() + .find_one(doc! { "_id": demo.id.unwrap() }) + .await + .unwrap() + .unwrap() + .demo + }; + let own = serde_json::json!({ "artifacts": [ + { "kind": "git_repo", "source_ref": "https://git.example/own.git", "branch": "main" } + ] }); + + // A new name and the same sources keep it a demo target. + let same = serde_json::json!({ "name": "Pumpe", "artifacts": [ + { "kind": "live_url", "source_ref": "https://demo.example" } + ] }); + assert_eq!(edit(&agent, "t-entry", &id, same).await.0, StatusCode::OK); + assert!(is_demo().await); + + // Act + Assert: the tenant's own sources need a place, and none is free. + let (status, body) = edit(&agent, "t-entry", &id, own.clone()).await; + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!(body["error"], "target_limit"); + assert!(is_demo().await, "refused: still a demo target"); + + // With a place free, it becomes the tenant's own and takes that place. + db.onboarded_targets() + .update_one( + doc! { "name": "Steuerung A" }, + doc! { "$set": { "archived_at": mongodb::bson::DateTime::now() } }, + ) + .await + .unwrap(); + assert_eq!(edit(&agent, "t-entry", &id, own).await.0, StatusCode::OK); + assert!(!is_demo().await); + assert_eq!( + add(&agent, "t-entry", "Steuerung C").await.0, + StatusCode::CONFLICT + ); +} diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 88eafce..7685217 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -5791,11 +5791,29 @@ pub mod metering { en: "Your plan includes no further targets. Archive a target to add a new one, \ or change your plan.", }; + /// The plan's refusal to make a demo target the tenant's own + /// (`target_limit`): other sources would make it count, and its places + /// are all taken. + pub const DEMO_LIMIT: Text = Text { + de: "Mit eigenen Dateien oder Quellen zählt ein Demo-Prüfobjekt wie Ihre anderen, \ + und Ihr Tarif enthält keine weiteren Prüfobjekte. Archivieren Sie ein \ + Prüfobjekt oder wechseln Sie den Tarif.", + en: "With your own files or sources a demo target counts like your other targets, \ + and your plan includes no further targets. Archive a target 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 { + plan_refusal(error, &TARGET_LIMIT, lang) + } + /// A failed change of a target's artifacts in words: the plan's refusal + /// as [`DEMO_LIMIT`], anything else as it came. + pub fn demo_refusal(error: &str, lang: Lang) -> String { + plan_refusal(error, &DEMO_LIMIT, lang) + } + fn plan_refusal(error: &str, text: &Text, lang: Lang) -> String { match crate::i18n::agent_code(error, &["target_limit"]) { - Some(_) => TARGET_LIMIT.get(lang).to_string(), + Some(_) => text.get(lang).to_string(), None => error.to_string(), } } diff --git a/compliance-dashboard/src/infrastructure/onboarding.rs b/compliance-dashboard/src/infrastructure/onboarding.rs index 8697a2d..b1d27d1 100644 --- a/compliance-dashboard/src/infrastructure/onboarding.rs +++ b/compliance-dashboard/src/infrastructure/onboarding.rs @@ -68,7 +68,7 @@ pub fn upload_problem(error: String, lang: Lang) -> String { } else if error.contains(UNSUPPORTED_ARCHIVE) { common::UNSUPPORTED_ARCHIVE.get(lang).to_string() } else { - error + crate::i18n::texts::metering::demo_refusal(&error, lang) } } @@ -694,6 +694,8 @@ pub async fn upload_target_artifact( 413 if sbom => format!("{SBOM_REFUSED}too_large"), 413 => "file is larger than the 512 MiB upload limit".to_string(), 415 => UNSUPPORTED_ARCHIVE.to_string(), + // A demo target the plan has no room for as the tenant's own. + 409 => refusal_code(resp).await, 422 => format!("{SBOM_REFUSED}{}", refusal_code(resp).await), code => format!("upload rejected by the agent ({code})"), })); diff --git a/compliance-dashboard/src/pages/onboarding.rs b/compliance-dashboard/src/pages/onboarding.rs index 90a26b2..496f9f3 100644 --- a/compliance-dashboard/src/pages/onboarding.rs +++ b/compliance-dashboard/src/pages/onboarding.rs @@ -1004,6 +1004,23 @@ mod tests { assert_eq!(metering::target_refusal("x (500)", Lang::De), "x (500)"); } + #[test] + fn a_demo_target_the_plan_has_no_room_for_reads_in_words() { + let error = "error running server function: target_limit (409) (details: None)"; + assert_eq!( + metering::demo_refusal(error, Lang::En), + metering::DEMO_LIMIT.get(Lang::En) + ); + assert_eq!( + upload_problem( + "error running server function: target_limit".into(), + Lang::De + ), + metering::DEMO_LIMIT.get(Lang::De) + ); + assert_eq!(metering::demo_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)"; diff --git a/compliance-dashboard/src/pages/target.rs b/compliance-dashboard/src/pages/target.rs index c501de7..b4d09cd 100644 --- a/compliance-dashboard/src/pages/target.rs +++ b/compliance-dashboard/src/pages/target.rs @@ -911,7 +911,10 @@ fn TargetEditor( toasts.push(ToastType::Success, tx::UPDATED.get(lang)); on_saved.call(()); } - Err(e) => toasts.push(ToastType::Error, e.to_string()), + Err(e) => toasts.push( + ToastType::Error, + crate::i18n::texts::metering::demo_refusal(&e.to_string(), lang), + ), } edit_saving.set(false); });