Compare commits

..
Author SHA1 Message Date
Sharang ParnerkarandClaude Opus 5.5 fa60318c19 fix(scan): removing a target's last controller clears its components and alerts
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 5m2s
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 22m48s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 14:57:05 +01:00
Sharang ParnerkarandClaude Opus 5.5 d75dd85e2e fix(scan): a target known only by its Siemens controllers is matched
A PLC target without a project file took the no-code path and never
persisted its device entries, so its controllers raised no CVE alerts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 14:57:05 +01:00
Sharang ParnerkarandClaude Opus 5.5 7dec38d74a fix(api): device route summaries fit the OpenAPI rule
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 14:57:05 +01:00
Sharang ParnerkarandClaude Opus 5.5 5d640e4457 fix(csaf): the test module goes last
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 14:57:05 +01:00
Sharang ParnerkarandClaude Opus 5.5 87a0f5b5c6 fix(csaf): read a Siemens fix only from 'Update to V<version>'
Sampled across the feed: a vendor fix can name hardware (LOGO! V9 BM) or a
version with letters (V3.X.18); neither is a firmware to update to.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 14:57:05 +01:00
Sharang ParnerkarandClaude Opus 5.5 5d4d6198df fix(dashboard): grey light on the dark module, form labels as in the mockup
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 14:57:05 +01:00
Sharang ParnerkarandClaude Opus 5.5 f5d9be1a93 docs(plc): Siemens controllers by order number; no scan-made VEX fixed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 14:57:05 +01:00
Sharang ParnerkarandClaude Opus 5.5 93f787160e feat(dashboard): a target's Siemens controllers on a DIN rail (SPS 4a)
Each controller is a module whose light says whether a Siemens advisory
affects its firmware. The chosen one shows its advisories with the fixed
firmware and the Quelle link. The form recognises an order number while it
is typed. The target page gets a card for PLC targets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 14:57:05 +01:00
Sharang ParnerkarandClaude Opus 5.5 5367e2ec71 feat(devices): a target's Siemens controllers against Siemens' advisories (SPS 4a)
DeviceCheck in core puts a device's state and advisory rows together with
the scan's matcher. Siemens writes a fix only as vendor_fix text, so its
firmware is read from there too. The agent serves the target's devices and
an order number lookup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 14:57:05 +01:00
15 changed files with 54 additions and 745 deletions

No files matched your search

+5 -7
View File
@@ -173,9 +173,8 @@ 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`; a plan that
/// allows no extra target includes them all. Without a registry every
/// target is included. Best-effort: when the plan cannot
/// which are extra (t72), from the plan's `included_targets`. 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
@@ -188,7 +187,7 @@ impl ComplianceAgent {
) -> Vec<BillingChange> {
match self.plan(tenant_id).await {
Some(plan) => {
self.assign_billing(tenant_id, db, plan.billed_included())
self.assign_billing(tenant_id, db, plan.included_targets)
.await
}
None => Vec::new(),
@@ -206,7 +205,6 @@ 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) => {
@@ -218,7 +216,7 @@ impl ComplianceAgent {
/// Store the billing of the tenant's targets for a plan that includes
/// `included` targets; best-effort.
pub(crate) async fn assign_billing(
async fn assign_billing(
&self,
tenant_id: &str,
db: &crate::database::Database,
@@ -361,7 +359,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.billed_included())
self.assign_billing(tenant_id, &db, plan.included_targets)
.await;
}
let orchestrator =
+3 -3
View File
@@ -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`), or the plan allows no further active target (`target_limit`)"),
(status = 409, description = "Already answered (`answered`), the release or connection ended (`ended`), or the component already receives another release (`target_taken`)"),
(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(e) => {
Err(status) => {
unclaim(&db, offer.id).await?;
return Ok(super::onboarding::target_refused(e));
return Err(status);
}
};
let created_id = created.id.map(|o| o.to_hex()).unwrap_or_default();
+31 -90
View File
@@ -20,7 +20,6 @@ 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};
@@ -406,8 +405,7 @@ async fn findings_counts(
request_body = CreateTargetRequest,
responses(
(status = 200, description = "The new target"),
(status = 409, description = "The plan allows no further active target (`target_limit`)"),
(status = 422, description = "A malformed body"),
(status = 422, description = "A malformed body, 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"),
)
@@ -417,25 +415,20 @@ pub async fn create_target(
Extension(agent): AgentExt,
tenant: TenantCtx,
Json(req): Json<CreateTargetRequest>,
) -> Result<Json<ApiResponse<OnboardedTarget>>, axum::response::Response> {
use axum::response::IntoResponse;
) -> Result<Json<ApiResponse<OnboardedTarget>>, StatusCode> {
let mut target = OnboardedTarget::new(req.name, req.target_type);
target.description = req.description;
if let Some(supplier) = req.supplier {
target.supplier = supplier.build().map_err(IntoResponse::into_response)?;
target.supplier = supplier.build()?;
}
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.into_response()
StatusCode::SERVICE_UNAVAILABLE
})?;
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)?;
let db = tenant_db(&agent, &tenant).await?;
let target = insert_target(&agent, &db, &tenant.0.tenant_id, target).await?;
Ok(Json(ApiResponse {
data: target.redacted(),
total: None,
@@ -443,45 +436,36 @@ pub async fn create_target(
}))
}
/// 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.
/// 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.
///
/// # Errors
///
/// [`AgentError::TargetLimit`] when the plan has no room for it; a database
/// error.
/// 500 when it cannot be stored.
pub(super) async fn insert_target(
agent: &Arc<ComplianceAgent>,
db: &crate::database::Database,
tenant_id: &str,
target: OnboardedTarget,
) -> Result<OnboardedTarget, AgentError> {
let target = crate::targets::create_target(agent, db, tenant_id, target).await?;
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();
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,
@@ -576,7 +560,6 @@ 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"),
@@ -588,7 +571,7 @@ pub async fn update_target(
tenant: TenantCtx,
Path(id): Path<String>,
Json(req): Json<UpdateTargetRequest>,
) -> Result<Json<ApiResponse<OnboardedTarget>>, UploadRefusal> {
) -> Result<Json<ApiResponse<OnboardedTarget>>, StatusCode> {
let oid = parse_oid(&id)?;
let db = tenant_db(&agent, &tenant).await?;
@@ -660,14 +643,9 @@ 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)?,
@@ -699,11 +677,6 @@ 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
@@ -719,22 +692,7 @@ pub async fn update_target(
});
}
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()
}
}
get_target(Extension(agent), tenant, Path(id)).await
}
/// Remove a deleted target's clones, uploads, work trees and blobs from disk.
@@ -914,8 +872,6 @@ 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"),
@@ -927,18 +883,9 @@ pub async fn add_artifact(
tenant: TenantCtx,
Path(id): Path<String>,
Json(input): Json<ArtifactInput>,
) -> Result<Json<ApiResponse<OnboardedTarget>>, UploadRefusal> {
) -> Result<Json<ApiResponse<OnboardedTarget>>, StatusCode> {
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
@@ -951,7 +898,7 @@ pub async fn add_artifact(
)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(get_target(Extension(agent), tenant, Path(id)).await?)
get_target(Extension(agent), tenant, Path(id)).await
}
/// The multipart form of an artifact upload.
@@ -994,7 +941,6 @@ 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"),
@@ -1019,11 +965,6 @@ 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;
@@ -1802,7 +1743,7 @@ pub async fn swap_target_billing(
&db,
incoming,
outgoing,
plan.billed_included().is_some(),
plan.included_targets.is_some(),
chrono::Utc::now(),
)
.await
-1
View File
@@ -166,7 +166,6 @@ 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(
-7
View File
@@ -47,11 +47,6 @@ 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),
}
@@ -84,7 +79,6 @@ impl AgentError {
| Self::Secret(_)
| Self::Exec(_)
| Self::NotAdmitted(_)
| Self::TargetLimit(_)
| Self::Other(_) => (
RunErrorCode::Internal,
"the scan stopped because of an internal error",
@@ -97,7 +91,6 @@ 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,
}
}
+2 -17
View File
@@ -467,10 +467,6 @@ 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
@@ -489,10 +485,7 @@ pub async fn apply_action(
archive_target(db, &source.base_url, repo.id).await?,
)),
SourceAction::Created(repo) => {
let ensured = match ensure_target(agent, db, tenant_id, source, &repo).await {
Err(AgentError::TargetLimit(_)) => return Ok(Outcome::Ignored(NO_ROOM)),
ensured => ensured?,
};
let ensured = ensure_target(agent, db, tenant_id, source, &repo).await?;
// An empty repository has nothing to scan; its first push will.
let scan = ensured.created && !repo.empty;
if scan {
@@ -504,10 +497,7 @@ pub async fn apply_action(
})
}
SourceAction::Push(repo) => {
let ensured = match ensure_target(agent, db, tenant_id, source, &repo).await {
Err(AgentError::TargetLimit(_)) => return Ok(Outcome::Ignored(NO_ROOM)),
ensured => ensured?,
};
let ensured = ensure_target(agent, db, tenant_id, source, &repo).await?;
spawn_scan(agent, tenant_id, &ensured.target_id, ScanTrigger::Webhook);
Ok(Outcome::Ensured {
target_id: ensured.target_id,
@@ -618,11 +608,6 @@ 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}");
}
-49
View File
@@ -2,7 +2,6 @@
//!
//! **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.
@@ -180,31 +179,10 @@ 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.
@@ -469,33 +447,6 @@ 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| {
-28
View File
@@ -134,13 +134,6 @@ 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.
@@ -884,27 +877,6 @@ 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!({
+8 -106
View File
@@ -16,101 +16,24 @@ 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
/// 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.
/// event. Returns the stored record with its id set.
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(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;
}
if let Some((_, billing)) = agent
.refresh_billing(tenant_id, db)
.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(
@@ -277,27 +200,6 @@ 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(
-356
View File
@@ -1,356 +0,0 @@
//! 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(&registry).await else {
return;
};
// Arrange: both included places taken.
assert_eq!(
add(&agent, "t-entry", "Steuerung A").await.0,
StatusCode::OK
);
assert_eq!(
add(&agent, "t-entry", "Steuerung B").await.0,
StatusCode::OK
);
// Act + Assert: the third is refused and not stored.
let (status, body) = add(&agent, "t-entry", "Steuerung C").await;
assert_eq!(status, StatusCode::CONFLICT);
assert_eq!(body["error"], "target_limit");
let db = agent.db_pool.for_tenant_id("t-entry").await.unwrap();
assert_eq!(
db.onboarded_targets()
.count_documents(doc! { "name": "Steuerung C" })
.await
.unwrap(),
0
);
// Archiving one frees its place.
db.onboarded_targets()
.update_one(
doc! { "name": "Steuerung A" },
doc! { "$set": { "archived_at": mongodb::bson::DateTime::now() } },
)
.await
.unwrap();
let (status, body) = add(&agent, "t-entry", "Steuerung C").await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body["data"]["billing"], "included");
}
#[tokio::test]
async fn a_plan_without_the_key_adds_extra_targets_as_before() {
let registry = fake_registry().await;
let Some(agent) = agent(&registry).await else {
return;
};
assert_eq!(
add(&agent, "t-standard", "Anlage 1").await.0,
StatusCode::OK
);
let (status, body) = add(&agent, "t-standard", "Anlage 2").await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body["data"]["billing"], "extra");
}
#[tokio::test]
async fn targets_already_beyond_the_entry_plan_are_never_billed_extra() {
let registry = fake_registry().await;
let Some(agent) = agent(&registry).await else {
return;
};
// Arrange: three active targets from before the plan, one billed extra.
let db = agent.db_pool.for_tenant_id("t-entry").await.unwrap();
for (name, billing) in [
("Anlage 1", TargetBilling::Included),
("Anlage 2", TargetBilling::Included),
("Anlage 3", TargetBilling::Extra),
] {
let mut target = OnboardedTarget::new(name.into(), TargetType::WebApp);
target.billing = billing;
db.onboarded_targets().insert_one(&target).await.unwrap();
}
// Act
agent.refresh_billing("t-entry", &db).await;
// Assert: all three stay, none is extra, and a fourth is refused.
let extra = mongodb::bson::to_bson(&TargetBilling::Extra).unwrap();
assert_eq!(
db.onboarded_targets()
.count_documents(doc! { "billing": extra })
.await
.unwrap(),
0
);
assert_eq!(
db.onboarded_targets()
.count_documents(doc! {})
.await
.unwrap(),
3
);
assert_eq!(
add(&agent, "t-entry", "Anlage 4").await.0,
StatusCode::CONFLICT
);
}
#[tokio::test]
async fn demo_targets_are_neither_counted_nor_refused() {
let registry = fake_registry().await;
let Some(agent) = agent(&registry).await else {
return;
};
let db = agent.db_pool.for_tenant_id("t-entry").await.unwrap();
let demo = |name: &str| {
let mut target = OnboardedTarget::new(name.into(), TargetType::WebApp);
target.demo = true;
target
};
// A demo target leaves both included places free.
compliance_agent::targets::create_target(&agent, &db, "t-entry", demo("Demo A"))
.await
.expect("demo target added");
assert_eq!(
add(&agent, "t-entry", "Steuerung A").await.0,
StatusCode::OK
);
assert_eq!(
add(&agent, "t-entry", "Steuerung B").await.0,
StatusCode::OK
);
assert_eq!(
add(&agent, "t-entry", "Steuerung C").await.0,
StatusCode::CONFLICT
);
// With the places taken, the seeder still adds its targets.
compliance_agent::targets::create_target(&agent, &db, "t-entry", demo("Demo B"))
.await
.expect("demo target added at the cap");
}
/// `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(&registry).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
);
}
-5
View File
@@ -708,10 +708,6 @@ 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",
@@ -775,7 +771,6 @@ impl OnboardedTarget {
included_until: None,
supplier: None,
devices: Vec::new(),
demo: false,
created_at: now,
updated_at: now,
}
+1 -39
View File
@@ -5783,42 +5783,6 @@ 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. Löschen Sie ein Prüfobjekt, \
um ein neues anzulegen (seine Ergebnisse werden mit gelöscht), oder wechseln \
Sie den Tarif.",
en: "Your plan includes no further targets. Delete a target to add a new one \
(its results are deleted with it), 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. Löschen Sie ein anderes \
Prüfobjekt (seine Ergebnisse werden mit gelöscht) 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. Delete another target (its results \
are deleted with it) 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(),
@@ -8875,12 +8839,11 @@ 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; 5] = [
const CODES: [&str; 4] = [
"answered",
"ended",
"target_taken",
"not_supplier_component",
"target_limit",
];
let text = match crate::i18n::agent_code(error, &CODES) {
Some("answered") => Text {
@@ -8900,7 +8863,6 @@ 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 {
crate::i18n::texts::metering::demo_refusal(&error, lang)
error
}
}
@@ -694,8 +694,6 @@ 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})"),
}));
+2 -30
View File
@@ -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, metering, onboarding as tx};
use crate::i18n::texts::{common, kinds, 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;", {metering::target_refusal(&err, lang)} }
div { style: "padding: 12px;", "{err}" }
}
}
@@ -993,34 +993,6 @@ 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. Delete a target to add a new one \
(its results are deleted with it), 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)";
+1 -4
View File
@@ -911,10 +911,7 @@ fn TargetEditor(
toasts.push(ToastType::Success, tx::UPDATED.get(lang));
on_saved.call(());
}
Err(e) => toasts.push(
ToastType::Error,
crate::i18n::texts::metering::demo_refusal(&e.to_string(), lang),
),
Err(e) => toasts.push(ToastType::Error, e.to_string()),
}
edit_saving.set(false);
});