Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aad3831e82 | ||
|
|
1df32d5e1a | ||
|
|
2d3311bd09 |
No files matched your search
@@ -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<BillingChange> {
|
||||
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(),
|
||||
@@ -205,6 +206,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 +218,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,
|
||||
@@ -359,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 =
|
||||
|
||||
@@ -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,
|
||||
@@ -560,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"),
|
||||
@@ -571,7 +588,7 @@ pub async fn update_target(
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
Json(req): Json<UpdateTargetRequest>,
|
||||
) -> Result<Json<ApiResponse<OnboardedTarget>>, StatusCode> {
|
||||
) -> Result<Json<ApiResponse<OnboardedTarget>>, UploadRefusal> {
|
||||
let oid = parse_oid(&id)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
|
||||
@@ -643,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)?,
|
||||
@@ -677,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
|
||||
@@ -692,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.
|
||||
@@ -872,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"),
|
||||
@@ -883,9 +927,18 @@ pub async fn add_artifact(
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
Json(input): Json<ArtifactInput>,
|
||||
) -> Result<Json<ApiResponse<OnboardedTarget>>, StatusCode> {
|
||||
) -> Result<Json<ApiResponse<OnboardedTarget>>, 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
|
||||
@@ -898,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.
|
||||
@@ -941,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"),
|
||||
@@ -965,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<ArtifactKind> = None;
|
||||
let mut plc_format: Option<PlcFormat> = None;
|
||||
@@ -1743,7 +1802,7 @@ pub async fn swap_target_billing(
|
||||
&db,
|
||||
incoming,
|
||||
outgoing,
|
||||
plan.included_targets.is_some(),
|
||||
plan.billed_included().is_some(),
|
||||
chrono::Utc::now(),
|
||||
)
|
||||
.await
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
@@ -179,10 +180,31 @@ 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?))
|
||||
}
|
||||
|
||||
/// 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.
|
||||
const MONTHS: &str = "metering_months";
|
||||
/// Each target's Prüftag per day, once the quota was used up.
|
||||
@@ -447,6 +469,33 @@ 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_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| {
|
||||
|
||||
@@ -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!({
|
||||
|
||||
@@ -16,24 +16,101 @@ 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. 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(
|
||||
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;
|
||||
// Demo targets are outside the cap: neither refused nor counted.
|
||||
if let Some(cap) = plan.and_then(|p| p.target_cap()).filter(|_| !target.demo) {
|
||||
room_for_one(db, cap).await?;
|
||||
}
|
||||
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.billed_included())
|
||||
.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(
|
||||
@@ -200,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(
|
||||
|
||||
@@ -0,0 +1,356 @@
|
||||
//! 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 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)]
|
||||
|
||||
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::{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, update_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(®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");
|
||||
}
|
||||
|
||||
#[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");
|
||||
}
|
||||
|
||||
/// `PATCH /api/v1/targets/{id}` with `body` as a member of `tenant`.
|
||||
async fn edit(
|
||||
agent: &Arc<ComplianceAgent>,
|
||||
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
|
||||
);
|
||||
}
|
||||
@@ -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<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.
|
||||
#[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,
|
||||
}
|
||||
|
||||
@@ -5783,6 +5783,40 @@ 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.",
|
||||
};
|
||||
/// 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(_) => text.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 +8873,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 +8898,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()
|
||||
|
||||
@@ -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})"),
|
||||
}));
|
||||
|
||||
@@ -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,34 @@ 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_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)";
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user