Compare commits

..
Author SHA1 Message Date
Sharang ParnerkarandClaude Opus 5.5 53da41ae94 feat(metering): the entry plan bills no target as extra and leaves demo targets out
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 5m15s
CI / Check (pull_request) Successful in 23m9s
Sharang's answers to the entry plan's open questions:

- A plan with `extra_targets: 0` bills every active target as included,
  also those already beyond its included ones when a workspace moves to
  it: no extra-target line, no counted change scans on them. Only new
  targets are refused. A swap on such a plan is refused as unlimited.
- The demo seeder marks its targets (`demo: true`); the cap neither
  counts nor refuses them. Demo targets seeded before this count as
  before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 19:37:35 +01:00
Sharang ParnerkarandClaude Opus 5.5 7ef6387d39 feat(metering): a plan can allow no extra targets (entry plan)
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 5m29s
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Check (pull_request) Successful in 22m56s
The registry's `limits.extra_targets` caps how many targets beyond the
included ones may be active; the entry plan sends 0. A new target past
included_targets + extra_targets is refused with 409 `target_limit`,
whichever way it is added: the API, accepting a supplier's SBOM release
(the offer stays open), Managed Git (skipped, retried at the next sync)
and the demo seed. A missing or null key keeps today's behaviour: extra
targets are allowed and billed.

All active targets count, as for the included/extra split; archiving
one frees its place. Without an answer from the registry the target is
added, as scans then run unmetered.

Every way of adding a target now goes through targets::create_target,
which reads the plan once for the cap and the billing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 15:07:53 +01:00
sharang 5b4d8bbe5f feat(csaf): Siemens devices by order number and firmware against Siemens advisories (SPS 4a) (#1077)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Successful in 1m16s
CI / Deploy MCP (push) Successful in 3m18s
CI / Deploy Dashboard (push) Successful in 7m6s
CI / Deploy Agent (push) Successful in 9m28s
2026-11-28 13:56:53 +00:00
sharangandClaude Opus 5.5 9274387e85 chore(release): workspace crates at 0.4.18 (#1076)
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 2m44s
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Successful in 6m19s
CI / Deploy Agent (push) Successful in 8m0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-27 23:26:33 +00:00
25 changed files with 1145 additions and 90 deletions

No files matched your search

+7 -5
View File
@@ -173,8 +173,9 @@ impl ComplianceAgent {
}
/// Store which of the tenant's targets are the plan's included ones and
/// 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 =
+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`)"),
(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();
+91 -27
View File
@@ -13,13 +13,14 @@ use serde::{Deserialize, Serialize};
use compliance_core::models::{
ArtifactKind, ComplianceProfile, Credentials, DetectedFact, Finding, OnboardedTarget,
PlcFormat, ScanRun, TargetType, WebhookDelivery, DELIVERIES_SHOWN,
PlcDevice, PlcFormat, ScanRun, TargetType, WebhookDelivery, DELIVERIES_SHOWN,
};
use compliance_core::scan_matrix::{applicable_scans, supports_pentest};
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};
@@ -46,6 +47,42 @@ pub struct CreateTargetRequest {
/// Who supplies the component, for one bought in (#1025).
#[serde(default)]
pub supplier: Option<SupplierInput>,
/// The Siemens controllers the target runs on, matched against Siemens'
/// CSAF advisories by order number and firmware.
#[serde(default)]
pub devices: Vec<DeviceInput>,
}
/// A Siemens controller as a client sends it.
#[derive(Deserialize, utoipa::ToSchema)]
pub struct DeviceInput {
/// The order number (MLFB).
#[schema(example = "6ES7511-1AK02-0AB0")]
pub order_number: String,
/// The firmware version installed, with or without a leading `V`.
#[schema(example = "V3.1.4")]
pub firmware: String,
/// What the customer calls it.
#[serde(default)]
pub label: Option<String>,
}
/// The devices to store.
///
/// # Errors
///
/// 422 for a device whose order number or firmware is not one
/// ([`PlcDevice::new`]).
fn build_devices(inputs: &[DeviceInput]) -> Result<Vec<PlcDevice>, StatusCode> {
inputs
.iter()
.map(|d| {
PlcDevice::new(&d.order_number, &d.firmware, d.label.as_deref()).map_err(|e| {
tracing::debug!(code = e.code(), "device refused: {e}");
StatusCode::UNPROCESSABLE_ENTITY
})
})
.collect()
}
/// A supplier as a client sends it (#1025). An empty `name` removes it.
@@ -141,6 +178,10 @@ pub struct UpdateTargetRequest {
/// Who supplies the component (#1025); an empty `name` removes it.
#[serde(default)]
pub supplier: Option<SupplierInput>,
/// The Siemens controllers the target runs on; replaces the stored list
/// (an empty list removes them all).
#[serde(default)]
pub devices: Option<Vec<DeviceInput>>,
}
/// One applicable-scan option, serialized for the wizard.
@@ -365,6 +406,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 = 503, description = "A credential cannot be sealed"),
(status = 401, description = "No valid bearer token"),
@@ -375,19 +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.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,
@@ -395,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,
@@ -519,7 +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 = 422, description = "A malformed body, or a project that is not the tenant's"),
(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"),
)
@@ -611,6 +668,13 @@ pub async fn update_target(
);
}
if let Some(devices) = req.devices {
set.insert(
"devices",
to_bson(&build_devices(&devices)?).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
);
}
let mut update = doc! {};
let mut supplier = None;
if let Some(input) = req.supplier {
@@ -1695,7 +1759,7 @@ pub async fn swap_target_billing(
&db,
incoming,
outgoing,
plan.included_targets.is_some(),
plan.billed_included().is_some(),
chrono::Utc::now(),
)
.await
+1
View File
@@ -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(
+7
View File
@@ -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,
}
}
+17 -2
View File
@@ -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}");
}
+49
View File
@@ -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| {
+159 -25
View File
@@ -1,7 +1,8 @@
//! A target's components against the vendor CSAF advisories in the index
//! (#515, see [`super::csaf_feed`]): a CODESYS runtime or library by its
//! name and version against CODESYS's advisories, any component with a purl
//! against an advisory product with the same purl. A match raises a CVE
//! name and version against CODESYS's advisories, a Siemens device by its
//! order number and firmware against Siemens' (SPS item 4a), and any
//! component with a purl against an advisory product with the same purl. A match raises a CVE
//! alert with source `csaf`, or, where OSV or NVD already reported the CVE,
//! adds the advisory to that alert; either way the alert links the advisory
//! and carries the vendor's remediation and fixed versions.
@@ -17,6 +18,10 @@ use compliance_core::version::Vers;
use super::csaf_feed::{MongoAdvisoryStore, StoredAdvisory};
/// The provider whose advisories name devices by order number
/// ([`compliance_core::models::PlcDevice`]).
const ORDER_NUMBER_PROVIDER: &str = "siemens";
/// The provider whose advisories name the components of a package manager
/// by product name.
fn provider_for(package_manager: &str) -> Option<&'static str> {
@@ -26,29 +31,46 @@ fn provider_for(package_manager: &str) -> Option<&'static str> {
}
}
/// What the advisory index is asked for, for some components ([`wanted`]).
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct Wanted {
/// Providers whose advisories all count ([`provider_for`]).
pub providers: Vec<String>,
/// Purls without version.
pub purls: Vec<String>,
/// Device order numbers, normalised.
pub order_numbers: Vec<String>,
}
impl Wanted {
fn is_empty(&self) -> bool {
self.providers.is_empty() && self.purls.is_empty() && self.order_numbers.is_empty()
}
}
/// Reads the advisory index, behind a trait so tests keep it in memory.
pub(crate) trait AdvisoryIndex: Send + Sync {
/// The advisories of `providers`, and those naming any of `purls`
/// (without version), as `(provider, advisory)`.
/// The advisories of `wanted`'s providers, and those naming any of its
/// purls (without version) or, of [`ORDER_NUMBER_PROVIDER`], any of its
/// order numbers, as `(provider, advisory)`.
fn relevant<'a>(
&'a self,
providers: &'a [String],
purls: &'a [String],
wanted: &'a Wanted,
) -> BoxFuture<'a, Result<Vec<(String, Advisory)>, String>>;
}
impl AdvisoryIndex for MongoAdvisoryStore {
fn relevant<'a>(
&'a self,
providers: &'a [String],
purls: &'a [String],
wanted: &'a Wanted,
) -> BoxFuture<'a, Result<Vec<(String, Advisory)>, String>> {
Box::pin(async move {
if providers.is_empty() && purls.is_empty() {
if wanted.is_empty() {
return Ok(Vec::new());
}
// A product's purl may carry a version; compare from the start.
let purl_patterns: Vec<mongodb::bson::Regex> = purls
let purl_patterns: Vec<mongodb::bson::Regex> = wanted
.purls
.iter()
.map(|p| mongodb::bson::Regex {
pattern: format!("^{}(@|$)", regex::escape(p)),
@@ -58,8 +80,12 @@ impl AdvisoryIndex for MongoAdvisoryStore {
let rows: Vec<StoredAdvisory> = self
.collection()
.find(doc! { "$or": [
{ "provider": { "$in": providers } },
{ "provider": { "$in": &wanted.providers } },
{ "advisory.products.purl": { "$in": purl_patterns } },
{
"provider": ORDER_NUMBER_PROVIDER,
"advisory.products.model_numbers": { "$in": &wanted.order_numbers },
},
] })
.await
.map_err(|e| e.to_string())?
@@ -83,6 +109,11 @@ fn purl_base(purl: &str) -> Option<String> {
/// Whether advisory product `p` (of `provider`) is `entry`'s component at
/// its version.
fn names(p: &AdvisoryProduct, provider: &str, entry: &SbomEntry) -> bool {
// A device, by its order number and firmware, only in the advisories of
// the vendor whose order numbers they are.
if let Some(order_number) = entry.order_number.as_deref() {
return provider == ORDER_NUMBER_PROVIDER && p.covers_device(order_number, &entry.version);
}
if provider_for(&entry.package_manager) == Some(provider)
&& p.covers(&entry.name, &entry.version)
{
@@ -203,7 +234,12 @@ pub(crate) fn apply(
aliases: Vec::new(),
});
}
let fixed = hit.advisory.fixed_versions(hit.vulnerability, &entry.name);
let fixed = match entry.order_number.as_deref() {
Some(order_number) => hit
.advisory
.fixed_device_versions(hit.vulnerability, order_number),
None => hit.advisory.fixed_versions(hit.vulnerability, &entry.name),
};
let alert = match alerts.iter_mut().position(|a| a.cve_id == hit.cve) {
Some(i) => &mut alerts[i],
None => {
@@ -255,23 +291,27 @@ pub(crate) fn apply(
count
}
/// The providers and purls the index is asked for, for `entries`.
pub(crate) fn wanted(entries: &[SbomEntry]) -> (Vec<String>, Vec<String>) {
let mut providers: Vec<String> = Vec::new();
let mut purls: Vec<String> = Vec::new();
/// What the index is asked for, for `entries`.
pub(crate) fn wanted(entries: &[SbomEntry]) -> Wanted {
let mut wanted = Wanted::default();
for entry in entries {
if let Some(p) = provider_for(&entry.package_manager) {
if !providers.iter().any(|q| q == p) {
providers.push(p.to_string());
if !wanted.providers.iter().any(|q| q == p) {
wanted.providers.push(p.to_string());
}
}
if let Some(base) = entry.purl.as_deref().and_then(purl_base) {
if !purls.contains(&base) {
purls.push(base);
if !wanted.purls.contains(&base) {
wanted.purls.push(base);
}
}
if let Some(order_number) = entry.order_number.as_deref() {
if !wanted.order_numbers.iter().any(|o| o == order_number) {
wanted.order_numbers.push(order_number.to_string());
}
}
}
(providers, purls)
wanted
}
#[cfg(test)]
@@ -464,10 +504,104 @@ mod tests {
assert_eq!(alerts[0].affected_version, "3.1.0");
assert_eq!(
wanted(&entries),
(
Vec::new(),
vec!["pkg:generic/example/fieldbus-stack".to_string()]
)
Wanted {
purls: vec!["pkg:generic/example/fieldbus-stack".to_string()],
..Wanted::default()
}
);
}
/// The synthetic Siemens-shaped advisory of the core fixtures, as
/// `provider`'s.
fn siemens_advisory(provider: &str) -> (String, Advisory) {
let doc: serde_json::Value = serde_json::from_str(include_str!(
"../../../compliance-core/tests/fixtures/csaf/siemens-synthetic.json"
))
.unwrap();
(
provider.to_string(),
compliance_core::csaf_ingest::parse(&doc).unwrap(),
)
}
fn device(order_number: &str, firmware: &str) -> SbomEntry {
let device = compliance_core::models::PlcDevice::new(order_number, firmware, None).unwrap();
crate::pipeline::sbom::devices::entries(&[device], "t").remove(0)
}
#[test]
fn a_device_matches_the_advisories_naming_its_order_number_and_firmware() {
let advisories = vec![siemens_advisory(ORDER_NUMBER_PROVIDER)];
let mut entries = vec![
device("6es7511-1ak02-0ab0", "V3.1.4"),
device("6ES7511-1AK02-0AB0", "3.1.5"),
device("6ES7513-1AL02-0AB0", "2.9.7"),
device("6ES7512-1DK01-0AB0", "1.0"),
];
let mut alerts = Vec::new();
let matched = apply("t", &mut entries, &advisories, &mut alerts);
// Below the fixed firmware, and in an advisory for every version; not
// at the fixed firmware, and not a CPU the advisory does not name.
assert_eq!(matched, 2);
let affected: Vec<(&str, &str)> = alerts
.iter()
.map(|a| (a.affected_package.as_str(), a.affected_version.as_str()))
.collect();
assert_eq!(
affected,
[("6ES7511-1AK02-0AB0", "3.1.4")],
"one alert per CVE"
);
let alert = &alerts[0];
assert_eq!(alert.cve_id, "CVE-2026-90101");
assert_eq!(alert.fixed_versions, ["3.1.5"]);
assert_eq!(alert.severity.as_deref(), Some("HIGH"));
let advisory = &alert.advisories[0];
assert_eq!(advisory.id, "SSA-900001");
assert!(advisory
.remediation
.as_deref()
.is_some_and(|r| r.contains("Update to V3.1.5")));
assert!(entries[2]
.known_vulnerabilities
.iter()
.any(|v| v.id == "CVE-2026-90101"));
assert!(entries[1].known_vulnerabilities.is_empty());
assert!(entries[3].known_vulnerabilities.is_empty());
}
#[test]
fn a_device_is_matched_only_against_the_vendor_of_its_order_number() {
let advisories = vec![siemens_advisory("codesys"), siemens_advisory("supplier:x")];
let mut entries = vec![device("6ES7511-1AK02-0AB0", "3.1.4")];
let mut alerts = Vec::new();
assert_eq!(apply("t", &mut entries, &advisories, &mut alerts), 0);
// And a component with that name is not a device.
let named = SbomEntry::new(
"t".into(),
"Example S7-1500 CPU 1511-1 PN (6ES7511-1AK02-0AB0)".into(),
"3.1.4".into(),
"supplier-product".into(),
);
let advisories = vec![siemens_advisory(ORDER_NUMBER_PROVIDER)];
assert_eq!(apply("t", &mut [named], &advisories, &mut alerts), 0);
}
#[test]
fn the_index_is_asked_for_each_order_number_once() {
let entries = vec![
device("6ES7511-1AK02-0AB0", "3.1.4"),
device("6es7511-1ak02-0ab0", "3.1.5"),
];
assert_eq!(
wanted(&entries),
Wanted {
order_numbers: vec!["6ES7511-1AK02-0AB0".to_string()],
..Wanted::default()
}
);
}
}
+32 -10
View File
@@ -88,6 +88,11 @@ pub struct PipelineOrchestrator {
pub(super) charged_as: Option<ScanTrigger>,
}
/// The package managers of the control-application SBOM the PLC scan stores
/// (`PipelineOrchestrator::persist_control_app_sbom`): CODESYS libraries and
/// runtime, and the Siemens devices the target runs on.
const CONTROL_APP_MANAGERS: [&str; 2] = ["codesys", crate::pipeline::sbom::devices::DEVICE_MANAGER];
/// Why a target with only a build output skips its code stages: what the
/// dashboard words from it (`coverage::reason`).
const NO_CODE_BUILD_OUTPUT: &str = "the target has no source code (a git repository or a \
@@ -172,10 +177,15 @@ impl PipelineOrchestrator {
else {
return;
};
let providers = [crate::pipeline::csaf_feed::supplier_key(url)];
let (_, purls) = crate::pipeline::csaf_match::wanted(entries);
// The supplier's advisories name its product and components by name
// and purl; devices are matched against the vendor index instead.
let wanted = crate::pipeline::csaf_match::Wanted {
providers: vec![crate::pipeline::csaf_feed::supplier_key(url)],
purls: crate::pipeline::csaf_match::wanted(entries).purls,
order_numbers: Vec::new(),
};
let store = crate::pipeline::csaf_feed::MongoAdvisoryStore::supplier(self.db.inner());
match store.relevant(&providers, &purls).await {
match store.relevant(&wanted).await {
Ok(advisories) if advisories.is_empty() => {}
Ok(advisories) => {
let matched =
@@ -200,8 +210,8 @@ impl PipelineOrchestrator {
let Some(index) = &self.advisory_index else {
return;
};
let (providers, purls) = crate::pipeline::csaf_match::wanted(entries);
match index.relevant(&providers, &purls).await {
let wanted = crate::pipeline::csaf_match::wanted(entries);
match index.relevant(&wanted).await {
Ok(advisories) if advisories.is_empty() => {}
Ok(advisories) => {
let matched =
@@ -687,6 +697,10 @@ impl PipelineOrchestrator {
.as_ref()
.and_then(|s| crate::pipeline::sbom::supplied::product_entry(s, &repo_id)),
);
supplied.extend(crate::pipeline::sbom::devices::entries(
&repo.devices,
&repo_id,
));
for entry in embedded
.into_iter()
.chain(codesys)
@@ -2122,6 +2136,10 @@ impl PipelineOrchestrator {
.spawn(left_out_run.status_changed().to_vec());
}
all_sbom.extend(crate::pipeline::sbom::devices::entries(
&target.devices,
target_id,
));
if !all_sbom.is_empty() {
if let Err(e) = self
.persist_control_app_sbom(target, target_id, scan_run_id, all_sbom)
@@ -2277,9 +2295,10 @@ impl PipelineOrchestrator {
Ok(new_count)
}
/// Store a control-application SBOM (CODESYS libraries + runtime) for a target
/// and match it against known CVEs. Scoped to `package_manager = "codesys"` so
/// it refreshes on re-scan and coexists with any firmware/source SBOM. The
/// Store a control-application SBOM (CODESYS libraries + runtime, and the
/// Siemens devices the target runs on) for a target and match it against
/// known CVEs. Scoped to those package managers so it refreshes on re-scan
/// and coexists with any firmware/source SBOM. The
/// runtime `Cmp*` / `3SLicense` components carry real CODESYS advisories, so
/// this is where PLC-device CVE coverage comes from.
async fn persist_control_app_sbom(
@@ -2296,13 +2315,16 @@ impl PipelineOrchestrator {
&self.db,
scan_run_id,
target_id,
doc! { "package_manager": "codesys" },
doc! { "package_manager": { "$in": CONTROL_APP_MANAGERS.to_vec() } },
&entries,
)
.await;
self.db
.sbom_entries()
.delete_many(doc! { "repo_id": target_id, "package_manager": "codesys" })
.delete_many(doc! {
"repo_id": target_id,
"package_manager": { "$in": CONTROL_APP_MANAGERS.to_vec() },
})
.await?;
let cve_scanner = CveScanner::new(
@@ -65,6 +65,8 @@ pub struct RepoView {
pub supplier_sboms: Vec<(std::path::PathBuf, String)>,
/// Who supplies the component, for one bought in (#1025).
pub supplier: Option<compliance_core::models::SupplierComponent>,
/// The Siemens controllers the target runs on (SPS item 4a).
pub devices: Vec<compliance_core::models::PlcDevice>,
}
impl RepoView {
@@ -102,6 +104,7 @@ impl RepoView {
build_outputs: Vec::new(),
supplier_sboms: Vec::new(),
supplier: target.supplier.clone(),
devices: target.devices.clone(),
};
if let Some(git) = &code.git {
view.default_branch = git.default_branch.clone();
@@ -0,0 +1,72 @@
//! The Siemens controllers a target runs on ([`PlcDevice`], SPS item 4a) as
//! SBOM entries: one per device, named and versioned as the customer
//! entered it, with the order number the vendor's CSAF advisories name it by
//! (matched in [`crate::pipeline::csaf_match`]).
use compliance_core::models::{PlcDevice, SbomEntry};
/// The package manager of a device entry.
pub(crate) const DEVICE_MANAGER: &str = "siemens-device";
/// The SBOM entries of target `repo_id`'s `devices`. A device is named by its
/// order number, so two devices of one type at one firmware are one entry;
/// its label, if any, is kept as evidence.
pub(crate) fn entries(devices: &[PlcDevice], repo_id: &str) -> Vec<SbomEntry> {
let mut entries: Vec<SbomEntry> = Vec::with_capacity(devices.len());
for device in devices {
let evidence = device.label.as_deref().map_or_else(
|| "entered with the target".to_string(),
|l| format!("entered as {l}"),
);
if let Some(known) = entries
.iter_mut()
.find(|e| e.name == device.order_number && e.version == device.firmware)
{
if !known.evidence.contains(&evidence) {
known.evidence.push(evidence);
}
continue;
}
let mut entry = SbomEntry::new(
repo_id.to_string(),
device.order_number.clone(),
device.firmware.clone(),
DEVICE_MANAGER.to_string(),
);
entry.order_number = Some(device.order_number.clone());
entry.evidence = vec![evidence];
entries.push(entry);
}
entries
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
#[test]
fn each_device_type_and_firmware_is_one_entry() {
let devices = [
PlcDevice::new("6ES7511-1AK02-0AB0", "V3.1.4", Some("Zelle 1")).unwrap(),
PlcDevice::new("6es7511-1ak02-0ab0", "3.1.4", Some("Zelle 2")).unwrap(),
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.5", None).unwrap(),
];
let entries = entries(&devices, "t");
assert_eq!(entries.len(), 2);
let first = &entries[0];
assert_eq!(
(
first.name.as_str(),
first.version.as_str(),
first.package_manager.as_str()
),
("6ES7511-1AK02-0AB0", "3.1.4", DEVICE_MANAGER)
);
assert_eq!(first.order_number.as_deref(), Some("6ES7511-1AK02-0AB0"));
assert_eq!(first.evidence, ["entered as Zelle 1", "entered as Zelle 2"]);
assert_eq!(entries[1].evidence, ["entered with the target"]);
}
}
@@ -1,6 +1,7 @@
mod cargo_audit;
pub(crate) mod carthage;
pub(crate) mod coverage;
pub(crate) mod devices;
mod distribution;
mod gradle;
mod mobile;
+28
View File
@@ -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!({
+31 -8
View File
@@ -17,23 +17,46 @@ use crate::database::Database;
use crate::error::AgentError;
/// Insert a new target for `tenant_id` and emit the `target.added` usage
/// event. Returns the stored record with its id set.
/// event: what every way of adding a target does (the API, accepting a
/// supplier's SBOM release, Managed Git, the demo seeder), so each counts
/// the same under the plan. Returns the stored record with its id set.
///
/// # Errors
///
/// [`AgentError::TargetLimit`] when the plan has no room for another active
/// target (the entry plan's `extra_targets: 0`); 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) {
let active = db
.onboarded_targets()
.count_documents(doc! { "archived_at": null, "demo": { "$ne": true } })
.await?;
if active >= u64::from(cap) {
return Err(AgentError::TargetLimit(cap));
}
}
let res = db.onboarded_targets().insert_one(&target).await?;
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(
+252
View File
@@ -0,0 +1,252 @@
//! The entry plan's target cap against a fake tenant registry: with
//! `extra_targets: 0` a new target is refused (409 `target_limit`) once the
//! included ones are all active, archiving one frees its place, targets
//! already beyond it are never billed as extra, demo targets are outside the
//! cap, and a plan without the key keeps adding extra targets as before.
//! Needs a live Mongo for the agent itself; skips cleanly without one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
mod common;
use std::sync::Arc;
use axum::body::Body;
use axum::extract::Request;
use axum::http::StatusCode;
use axum::middleware::{from_fn, Next};
use axum::routing::post;
use axum::{Extension, Json, Router};
use mongodb::bson::doc;
use tower::ServiceExt;
use compliance_agent::agent::ComplianceAgent;
use compliance_agent::api::handlers::onboarding::create_target;
use compliance_agent::database::DatabasePool;
use compliance_core::models::{OnboardedTarget, TargetBilling, TargetType};
use compliance_core::{OrgRole, TenantContext, TenantStatus};
use common::dev_config;
/// A registry where `t-entry` includes two targets and allows no extra one,
/// and `t-standard` includes one and bills the others.
async fn fake_registry() -> String {
let app = Router::new().route(
"/v1/internal/entitlements/check",
post(|Json(body): Json<serde_json::Value>| async move {
let limits = match body["tenant_id"].as_str() {
Some("t-entry") => serde_json::json!({ "included_targets": 2, "extra_targets": 0 }),
_ => serde_json::json!({ "included_targets": 1 }),
};
Json(serde_json::json!({ "allowed": true, "status": "active", "limits": limits }))
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.ok() });
format!("http://{addr}")
}
/// An agent whose registry is `registry`, or `None` without Mongo.
async fn agent(registry: &str) -> Option<Arc<ComplianceAgent>> {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db_name = format!("cap_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
let Ok(pool) = DatabasePool::connect(&uri, &db_name).await else {
eprintln!("SKIP target_limit: no MongoDB reachable at {uri}");
return None;
};
let mut config = dev_config(uri, db_name);
config.tenant_registry_url = Some(registry.to_string());
Some(Arc::new(ComplianceAgent::new(config, pool)))
}
fn member(tenant: &str) -> TenantContext {
TenantContext {
tenant_id: tenant.into(),
tenant_slug: "acme".into(),
org_roles: vec![OrgRole::ItAdmin],
products: vec!["compliance-scanner".into()],
plan: "entry".into(),
status: TenantStatus::Active,
user_id: "u-1".into(),
user_name: None,
staff: None,
api_key: None,
}
}
/// `POST /api/v1/targets` named `name` as a member of `tenant`.
async fn add(
agent: &Arc<ComplianceAgent>,
tenant: &str,
name: &str,
) -> (StatusCode, serde_json::Value) {
let ctx = member(tenant);
let inject = move |mut req: Request, next: Next| {
let ctx = ctx.clone();
async move {
req.extensions_mut().insert(ctx);
next.run(req).await
}
};
let app = Router::new()
.route("/api/v1/targets", post(create_target))
.layer(Extension(agent.clone()))
.layer(from_fn(inject));
let body = serde_json::json!({ "name": name, "target_type": "web_app" });
let resp = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/v1/targets")
.header("content-type", "application/json")
.body(Body::from(body.to_string()))
.unwrap(),
)
.await
.unwrap();
let status = resp.status();
let bytes = axum::body::to_bytes(resp.into_body(), 1 << 16)
.await
.unwrap();
(status, serde_json::from_slice(&bytes).unwrap_or_default())
}
#[tokio::test]
async fn the_entry_plan_refuses_a_target_beyond_its_included_ones() {
let registry = fake_registry().await;
let Some(agent) = agent(&registry).await else {
return;
};
// Arrange: both included places taken.
assert_eq!(
add(&agent, "t-entry", "Steuerung A").await.0,
StatusCode::OK
);
assert_eq!(
add(&agent, "t-entry", "Steuerung B").await.0,
StatusCode::OK
);
// Act + Assert: the third is refused and not stored.
let (status, body) = add(&agent, "t-entry", "Steuerung C").await;
assert_eq!(status, StatusCode::CONFLICT);
assert_eq!(body["error"], "target_limit");
let db = agent.db_pool.for_tenant_id("t-entry").await.unwrap();
assert_eq!(
db.onboarded_targets()
.count_documents(doc! { "name": "Steuerung C" })
.await
.unwrap(),
0
);
// Archiving one frees its place.
db.onboarded_targets()
.update_one(
doc! { "name": "Steuerung A" },
doc! { "$set": { "archived_at": mongodb::bson::DateTime::now() } },
)
.await
.unwrap();
let (status, body) = add(&agent, "t-entry", "Steuerung C").await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body["data"]["billing"], "included");
}
#[tokio::test]
async fn a_plan_without_the_key_adds_extra_targets_as_before() {
let registry = fake_registry().await;
let Some(agent) = agent(&registry).await else {
return;
};
assert_eq!(
add(&agent, "t-standard", "Anlage 1").await.0,
StatusCode::OK
);
let (status, body) = add(&agent, "t-standard", "Anlage 2").await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body["data"]["billing"], "extra");
}
#[tokio::test]
async fn targets_already_beyond_the_entry_plan_are_never_billed_extra() {
let registry = fake_registry().await;
let Some(agent) = agent(&registry).await else {
return;
};
// Arrange: three active targets from before the plan, one billed extra.
let db = agent.db_pool.for_tenant_id("t-entry").await.unwrap();
for (name, billing) in [
("Anlage 1", TargetBilling::Included),
("Anlage 2", TargetBilling::Included),
("Anlage 3", TargetBilling::Extra),
] {
let mut target = OnboardedTarget::new(name.into(), TargetType::WebApp);
target.billing = billing;
db.onboarded_targets().insert_one(&target).await.unwrap();
}
// Act
agent.refresh_billing("t-entry", &db).await;
// Assert: all three stay, none is extra, and a fourth is refused.
let extra = mongodb::bson::to_bson(&TargetBilling::Extra).unwrap();
assert_eq!(
db.onboarded_targets()
.count_documents(doc! { "billing": extra })
.await
.unwrap(),
0
);
assert_eq!(
db.onboarded_targets()
.count_documents(doc! {})
.await
.unwrap(),
3
);
assert_eq!(
add(&agent, "t-entry", "Anlage 4").await.0,
StatusCode::CONFLICT
);
}
#[tokio::test]
async fn demo_targets_are_neither_counted_nor_refused() {
let registry = fake_registry().await;
let Some(agent) = agent(&registry).await else {
return;
};
let db = agent.db_pool.for_tenant_id("t-entry").await.unwrap();
let demo = |name: &str| {
let mut target = OnboardedTarget::new(name.into(), TargetType::WebApp);
target.demo = true;
target
};
// A demo target leaves both included places free.
compliance_agent::targets::create_target(&agent, &db, "t-entry", demo("Demo A"))
.await
.expect("demo target added");
assert_eq!(
add(&agent, "t-entry", "Steuerung A").await.0,
StatusCode::OK
);
assert_eq!(
add(&agent, "t-entry", "Steuerung B").await.0,
StatusCode::OK
);
assert_eq!(
add(&agent, "t-entry", "Steuerung C").await.0,
StatusCode::CONFLICT
);
// With the places taken, the seeder still adds its targets.
compliance_agent::targets::create_target(&agent, &db, "t-entry", demo("Demo B"))
.await
.expect("demo target added at the cap");
}
+41 -4
View File
@@ -53,9 +53,27 @@ impl AdvisoryProduct {
/// `version`: its exact version, or one its range contains. A product
/// without either covers every version of it.
pub fn covers(&self, name: &str, version: &str) -> bool {
if normalised_name(&self.name) != normalised_name(name) {
return false;
}
normalised_name(&self.name) == normalised_name(name) && self.covers_version(version)
}
/// Whether the product is the device with order number `order_number`
/// (compared as [`crate::models::plc_device::normalised_order_number`])
/// at firmware `version`, as [`Self::covers`] compares versions.
pub fn covers_device(&self, order_number: &str, version: &str) -> bool {
self.has_order_number(order_number) && self.covers_version(version)
}
/// Whether `order_number` is one of the product's order numbers.
pub fn has_order_number(&self, order_number: &str) -> bool {
let wanted = crate::models::plc_device::normalised_order_number(order_number);
self.model_numbers
.iter()
.any(|m| crate::models::plc_device::normalised_order_number(m) == wanted)
}
/// Whether `version` is the product's exact version or in its range; a
/// product without either covers every version.
fn covers_version(&self, version: &str) -> bool {
match (&self.version, &self.version_range) {
(Some(exact), _) => cmp_dotted(exact, version).is_eq(),
(None, Some(range)) => Vers::parse(range).is_some_and(|r| r.contains(version)),
@@ -154,11 +172,30 @@ impl Advisory {
/// (`3.5.22.40`), lowest first.
pub fn fixed_versions(&self, vulnerability: &AdvisoryVulnerability, name: &str) -> Vec<String> {
let wanted = normalised_name(name);
self.fixed_versions_where(vulnerability, |p| normalised_name(&p.name) == wanted)
}
/// The fixed versions of `vulnerability` for the device with order number
/// `order_number`, as [`Self::fixed_versions`] gives them by name.
pub fn fixed_device_versions(
&self,
vulnerability: &AdvisoryVulnerability,
order_number: &str,
) -> Vec<String> {
self.fixed_versions_where(vulnerability, |p| p.has_order_number(order_number))
}
/// The exact versions of the fixed products `is_it` picks, oldest first.
fn fixed_versions_where(
&self,
vulnerability: &AdvisoryVulnerability,
is_it: impl Fn(&AdvisoryProduct) -> bool,
) -> Vec<String> {
let mut versions: Vec<String> = vulnerability
.fixed
.iter()
.filter_map(|id| self.product(id))
.filter(|p| normalised_name(&p.name) == wanted)
.filter(|p| is_it(p))
.filter_map(|p| p.version.clone())
.collect();
versions.sort_by(|a, b| cmp_dotted(a, b));
+2
View File
@@ -21,6 +21,7 @@ pub mod onboarding;
pub mod oscal;
pub mod oscal_assessment;
pub mod pentest;
pub mod plc_device;
pub mod project;
pub mod repository;
pub mod sbom;
@@ -81,6 +82,7 @@ pub use pentest::{
PentestStatus, PentestStrategy, SeverityDistribution, TestUserRecord, TesterInfo,
ToolCallRecord,
};
pub use plc_device::{PlcDevice, PlcDeviceError};
pub use project::{Project, ProjectKind, ProjectLevel};
pub use repository::ScanTrigger;
pub use sbom::{
+10
View File
@@ -704,6 +704,14 @@ pub struct OnboardedTarget {
/// advisories. `None` for what the tenant makes itself.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub supplier: Option<SupplierComponent>,
/// The Siemens controllers the target runs on (SPS item 4a), matched by
/// 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",
@@ -766,6 +774,8 @@ impl OnboardedTarget {
included_choice: None,
included_until: None,
supplier: None,
devices: Vec::new(),
demo: false,
created_at: now,
updated_at: now,
}
+168
View File
@@ -0,0 +1,168 @@
//! A Siemens controller a target runs on, by its order number (SPS item 4a).
//!
//! Siemens ProductCERT names each affected CPU in its CSAF advisories by its
//! order number (MLFB, `6ES7511-1AK02-0AB0`) and a firmware range. A device
//! entered with both is matched against them, so an advisory about the CPU
//! a machine uses reaches its target even when no project file names it.
use serde::{Deserialize, Serialize};
/// A controller the target runs on: a Siemens order number and the firmware
/// version installed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlcDevice {
/// The order number, upper case without spaces (`6ES7511-1AK02-0AB0`).
pub order_number: String,
/// The firmware version installed, without a leading `V` (`3.1.4`).
pub firmware: String,
/// What the customer calls it (`Hauptsteuerung Zelle 2`), if anything.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
}
/// Why a device cannot be stored.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum PlcDeviceError {
/// Not a Siemens order number (`6ES7511-1AK02-0AB0`).
#[error("not a Siemens order number (such as 6ES7511-1AK02-0AB0): {0}")]
OrderNumber(String),
/// No firmware version, or not one of dot-separated numbers (`3.1.4`).
/// Advisories name affected firmware by range, so a device without one
/// could not be matched.
#[error("not a firmware version (such as V3.1.4): {0}")]
Firmware(String),
}
impl PlcDeviceError {
/// A stable name of the refusal, for a client to word it in its own
/// language: `order_number` or `firmware`.
pub fn code(&self) -> &'static str {
match self {
Self::OrderNumber(_) => "order_number",
Self::Firmware(_) => "firmware",
}
}
}
impl PlcDevice {
/// A device from what a person entered: the order number is upper-cased
/// with spaces removed, a leading `V` of the firmware dropped, and a
/// blank label left out.
///
/// # Errors
///
/// [`PlcDeviceError::OrderNumber`] when the order number does not have a
/// Siemens order number's shape (`7 characters - 5 - 4`, starting with a
/// digit); [`PlcDeviceError::Firmware`] when the firmware is not
/// dot-separated numbers.
///
/// # Examples
///
/// ```
/// use compliance_core::models::PlcDevice;
///
/// let device = PlcDevice::new("6es7511-1ak02-0ab0 ", "V3.1.4", None).unwrap();
/// assert_eq!(device.order_number, "6ES7511-1AK02-0AB0");
/// assert_eq!(device.firmware, "3.1.4");
/// ```
pub fn new(
order_number: &str,
firmware: &str,
label: Option<&str>,
) -> Result<Self, PlcDeviceError> {
let order_number = normalised_order_number(order_number);
if !is_order_number(&order_number) {
return Err(PlcDeviceError::OrderNumber(order_number));
}
let trimmed = firmware.trim();
let firmware = trimmed
.strip_prefix(['V', 'v'])
.unwrap_or(trimmed)
.trim()
.to_string();
let numeric = !firmware.is_empty()
&& firmware
.split('.')
.all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()));
if !numeric {
return Err(PlcDeviceError::Firmware(trimmed.to_string()));
}
Ok(Self {
order_number,
firmware,
label: label
.map(str::trim)
.filter(|l| !l.is_empty())
.map(str::to_string),
})
}
}
/// An order number as advisories and devices compare: upper case, without
/// spaces (` 6es7511-1ak02-0ab0` is `6ES7511-1AK02-0AB0`).
pub fn normalised_order_number(text: &str) -> String {
text.chars()
.filter(|c| !c.is_whitespace())
.collect::<String>()
.to_uppercase()
}
/// Whether `text` (normalised) has a Siemens order number's shape: three
/// dash-separated groups of 7, 5 and 4 letters or digits, the first a digit
/// (`6ES7511-1AK02-0AB0`, `6AG1518-4AX00-4AC0`, `6ED1052-1MD08-0BA2`).
fn is_order_number(text: &str) -> bool {
let groups: Vec<&str> = text.split('-').collect();
groups.len() == 3
&& [7, 5, 4]
.iter()
.zip(&groups)
.all(|(len, g)| g.len() == *len && g.bytes().all(|b| b.is_ascii_alphanumeric()))
&& text.as_bytes().first().is_some_and(u8::is_ascii_digit)
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
#[test]
fn an_entered_device_is_stored_as_advisories_name_it() {
let device = PlcDevice::new(" 6es7511-1ak02-0ab0", " v3.1.4 ", Some(" ")).unwrap();
assert_eq!(
device,
PlcDevice {
order_number: "6ES7511-1AK02-0AB0".into(),
firmware: "3.1.4".into(),
label: None,
}
);
let logo = PlcDevice::new("6ED1052-1MD08-0BA2", "8.4", Some("Pumpe")).unwrap();
assert_eq!(logo.label.as_deref(), Some("Pumpe"));
}
#[test]
fn a_device_that_could_not_be_matched_is_refused() {
for bad in [
"",
"CPU 1511-1 PN",
"6ES7511-1AK02",
"6ES7511-1AK02-0AB0X",
"XES7511-1AK02-0AB0",
] {
assert_eq!(
PlcDevice::new(bad, "3.1.4", None).unwrap_err().code(),
"order_number",
"{bad}"
);
}
for bad in ["", "V", "latest", "3..1", "V3.1.4a"] {
assert_eq!(
PlcDevice::new("6ES7511-1AK02-0AB0", bad, None)
.unwrap_err()
.code(),
"firmware",
"{bad}"
);
}
}
}
+6
View File
@@ -124,6 +124,11 @@ pub struct SbomEntry {
/// advisory database could look up (a Yocto recipe's CVE_PRODUCT).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cpe: Option<String>,
/// The vendor's order number of a device (Siemens MLFB
/// `6ES7511-1AK02-0AB0`; [`super::PlcDevice`]), which the vendor's CSAF
/// advisories name it by.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub order_number: Option<String>,
/// The images the component is in, where that is known (a Yocto recipe
/// an image recipe installs); `None` when it is not, and on components
/// stored before it was recorded.
@@ -180,6 +185,7 @@ impl SbomEntry {
download_url: None,
manufacturer_url: None,
cpe: None,
order_number: None,
in_image: None,
concluded: None,
policy: None,
+26
View File
@@ -241,6 +241,12 @@ pub fn cdx_components(entries: &[SbomEntry]) -> Vec<serde_json::Value> {
"name": e.name,
"version": e.version,
});
// A Siemens device (`PlcDevice`) is hardware named by its order
// number, at the firmware version installed.
if e.order_number.is_some() {
comp["type"] = serde_json::Value::String("device".into());
comp["manufacturer"] = serde_json::json!({ "name": "Siemens" });
}
if let Some(purl) = &e.purl {
comp["purl"] = serde_json::Value::String(purl.clone());
if let Some(parsed) = Purl::parse(purl) {
@@ -1173,4 +1179,24 @@ mod tests {
assert_eq!(spdx["packages"][1]["licenseDeclared"], "MIT");
assert!(spdx.get("hasExtractedLicensingInfos").is_none());
}
#[test]
fn a_siemens_device_is_a_device_by_its_manufacturer() {
let mut device = SbomEntry::new(
"t".into(),
"6ES7511-1AK02-0AB0".into(),
"3.1.4".into(),
"siemens-device".into(),
);
device.order_number = Some("6ES7511-1AK02-0AB0".into());
let library = SbomEntry::new("t".into(), "zlib".into(), "1.3".into(), "conan".into());
let components = cdx_components(&[device, library]);
assert_eq!(components[0]["type"], "device");
assert_eq!(components[0]["manufacturer"]["name"], "Siemens");
assert_eq!(components[0]["version"], "3.1.4");
assert_eq!(components[1]["type"], "library");
assert!(components[1].get("manufacturer").is_none());
}
}
@@ -0,0 +1,99 @@
{
"document": {
"category": "csaf_security_advisory",
"csaf_version": "2.0",
"title": "Example CPUs: a synthetic advisory shaped like Siemens ProductCERT's",
"publisher": { "category": "vendor", "name": "Example ProductCERT", "namespace": "https://example.invalid" },
"distribution": { "tlp": { "label": "WHITE", "url": "https://www.first.org/tlp/" } },
"references": [
{ "category": "self", "summary": "CSAF", "url": "https://example.invalid/productcert/csaf/ssa-900001.json" },
{ "category": "self", "summary": "Advisory", "url": "https://example.invalid/productcert/html/ssa-900001.html" }
],
"tracking": {
"id": "SSA-900001",
"status": "final",
"version": "1",
"current_release_date": "2026-11-10T00:00:00.000Z",
"initial_release_date": "2026-11-10T00:00:00.000Z",
"revision_history": [{ "date": "2026-11-10T00:00:00.000Z", "number": "1", "summary": "Initial" }]
}
},
"product_tree": {
"branches": [
{
"category": "vendor",
"name": "Example",
"branches": [
{
"category": "product_name",
"name": "Example S7-1500 CPU 1511-1 PN (6ES7511-1AK02-0AB0)",
"branches": [
{
"category": "product_version_range",
"name": "vers:intdot/<3.1.5",
"product": {
"name": "Example S7-1500 CPU 1511-1 PN (6ES7511-1AK02-0AB0)",
"product_id": "1",
"product_identification_helper": { "model_numbers": ["6ES7511-1AK02-0AB0"] }
}
},
{
"category": "product_version",
"name": "3.1.5",
"product": {
"name": "Example S7-1500 CPU 1511-1 PN (6ES7511-1AK02-0AB0) V3.1.5",
"product_id": "2",
"product_identification_helper": { "model_numbers": ["6ES7511-1AK02-0AB0"] }
}
}
]
},
{
"category": "product_name",
"name": "Example S7-1500 CPU 1513-1 PN (6ES7513-1AL02-0AB0)",
"branches": [
{
"category": "product_version_range",
"name": "vers:all/*",
"product": {
"name": "Example S7-1500 CPU 1513-1 PN (6ES7513-1AL02-0AB0)",
"product_id": "3",
"product_identification_helper": { "model_numbers": ["6ES7513-1AL02-0AB0"] }
}
}
]
},
{
"category": "product_name",
"name": "Example S7-1200 CPU family (incl. SIPLUS variants)",
"branches": [
{
"category": "product_version_range",
"name": "vers:all/*",
"product": { "name": "Example S7-1200 CPU family (incl. SIPLUS variants)", "product_id": "4" }
}
]
}
]
}
]
},
"vulnerabilities": [
{
"cve": "CVE-2026-90101",
"title": "Improper input validation in the web server",
"notes": [{ "category": "description", "text": "A crafted request can restart the CPU." }],
"product_status": { "known_affected": ["1", "3", "4"], "fixed": ["2"] },
"remediations": [
{ "category": "vendor_fix", "details": "Update to V3.1.5 or later version", "product_ids": ["1"] },
{ "category": "mitigation", "details": "Restrict access to port 443/tcp", "product_ids": ["1", "3", "4"] }
],
"scores": [
{
"products": ["1", "3", "4"],
"cvss_v3": { "version": "3.1", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "baseScore": 7.5, "baseSeverity": "HIGH" }
}
]
}
]
}
+19 -1
View File
@@ -5783,6 +5783,22 @@ pub mod metering {
}
/// "1 zusätzliches Prüfobjekt", or that every target is included.
/// The plan's refusal of a new target (`target_limit`): its places are
/// all taken.
pub const TARGET_LIMIT: Text = Text {
de: "Ihr Tarif enthält keine weiteren Prüfobjekte. Archivieren Sie ein Prüfobjekt, \
um ein neues anzulegen, oder wechseln Sie den Tarif.",
en: "Your plan includes no further targets. Archive a target to add a new one, \
or change your plan.",
};
/// A failed creation of a target in words: the plan's refusal as
/// [`TARGET_LIMIT`], anything else as it came.
pub fn target_refusal(error: &str, lang: Lang) -> String {
match crate::i18n::agent_code(error, &["target_limit"]) {
Some(_) => TARGET_LIMIT.get(lang).to_string(),
None => error.to_string(),
}
}
pub fn extra_targets(extra: u32, lang: Lang) -> String {
match (lang, extra) {
(Lang::De, 0) => "Alle Prüfobjekte im Tarif enthalten".to_string(),
@@ -8839,11 +8855,12 @@ pub mod offers {
/// The agent's refusal `error` in words; anything else as it came.
pub fn refusal(error: &str, lang: Lang) -> String {
const CODES: [&str; 4] = [
const CODES: [&str; 5] = [
"answered",
"ended",
"target_taken",
"not_supplier_component",
"target_limit",
];
let text = match crate::i18n::agent_code(error, &CODES) {
Some("answered") => Text {
@@ -8863,6 +8880,7 @@ pub mod offers {
de: "Nur eine zugekaufte Komponente kann eine SBOM eines Zulieferers erhalten.",
en: "Only a bought-in component can receive a supplier's SBOM.",
},
Some("target_limit") => super::metering::TARGET_LIMIT,
_ => return error.to_string(),
};
text.get(lang).to_string()
+13 -2
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, onboarding as tx};
use crate::i18n::texts::{common, kinds, metering, onboarding as tx};
use crate::i18n::{format_bytes, use_lang, Lang};
use crate::infrastructure::onboarding::{
check_supplier_sbom, create_target, detect_target, enable_target_scans, fetch_applicable_scans,
@@ -232,7 +232,7 @@ pub fn OnboardingPage(origin: String) -> Element {
if let Some(err) = error() {
div { class: "card", style: "border-color: var(--danger, #d33); margin-bottom: 12px;",
div { class: "card-header", {tx::ERROR.get(lang)} }
div { style: "padding: 12px;", "{err}" }
div { style: "padding: 12px;", {metering::target_refusal(&err, lang)} }
}
}
@@ -993,6 +993,17 @@ fn type_label_of(value: &str, lang: Lang) -> String {
mod tests {
use super::*;
#[test]
fn a_target_the_plan_has_no_room_for_reads_in_words() {
let error = "error running server function: target_limit (409) (details: None)";
assert_eq!(
metering::target_refusal(error, Lang::En),
"Your plan includes no further targets. Archive a target to add a new one, \
or change your plan."
);
assert_eq!(metering::target_refusal("x (500)", Lang::De), "x (500)");
}
#[test]
fn a_refused_supplier_sbom_upload_reads_in_the_readers_language() {
let error = "error running server function: supplier_sbom_refused:empty (details: None)";
+8 -3
View File
@@ -247,14 +247,19 @@ runs. Scans never fetch; they match the target's components against the index:
- a CODESYS runtime or library (from a `.projectarchive`) by its name and
version against CODESYS's advisories, including the range forms CERT@VDE's
vendors write besides proper `vers` (`4.15.0.0<4.21.0.0`, `<4.17.0.0`);
- a Siemens device the target runs on (its `devices`: order number and
firmware, entered with the target) against Siemens' advisories, by the
product's order number (MLFB, `6ES7511-1AK02-0AB0`) and firmware range
(`vers:intdot/<3.1.5`, `vers:all/*`); a device is matched only against
Siemens', and is a `device` component in the CycloneDX export;
- any component with a purl against an advisory product with the same purl.
A match raises a CVE alert with source `csaf`, or, where OSV or NVD reported
the same CVE, is added to that alert. Either way the alert names the advisory
(id, title, link) with the vendor's remediation and the fixed versions, and
the component lists the CVE with the advisory's link. Siemens order numbers
(MLFB) are indexed but not matched yet: no component carries one until TIA
exports are read.
the component lists the CVE with the advisory's link. A Siemens advisory that
names a whole family (`S7-1200 CPU family`) and no order number is not matched
to a device yet.
`PW_CSAF_PROVIDERS` chooses the providers: unset or `default` (CERT@VDE's
vendors and Siemens), `off`, or a comma list of `default`, `siemens`, `cisa`