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
sharangandClaude Opus 5.5 5407e1d7ed feat(dashboard): CRA requirements by name, no off-site advisory links (#1074)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 6m2s
CI / Deploy Dashboard (push) Successful in 14m42s
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 12m25s
The Prüfwerk views name each CRA requirement and what green, orange and red mean, in a map by area. Off-site advisory links become copy buttons; a "Quelle" link stays only where the provider requires a backlink (Siemens ProductCERT). Ticket texts and the readable evidence pack use the names; machine-readable exports keep their IDs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-27 22:49:10 +00:00
54 changed files with 2820 additions and 511 deletions

No files matched your search

Generated
+9 -9
View File
@@ -601,7 +601,7 @@ dependencies = [
[[package]]
name = "compliance-agent"
version = "0.4.17"
version = "0.4.18"
dependencies = [
"axum",
"base64 0.22.1",
@@ -657,7 +657,7 @@ dependencies = [
[[package]]
name = "compliance-core"
version = "0.4.17"
version = "0.4.18"
dependencies = [
"aes-gcm",
"axum",
@@ -689,7 +689,7 @@ dependencies = [
[[package]]
name = "compliance-dashboard"
version = "0.4.17"
version = "0.4.18"
dependencies = [
"async-trait",
"axum",
@@ -727,7 +727,7 @@ dependencies = [
[[package]]
name = "compliance-dast"
version = "0.4.17"
version = "0.4.18"
dependencies = [
"axum",
"base64 0.22.1",
@@ -749,7 +749,7 @@ dependencies = [
[[package]]
name = "compliance-graph"
version = "0.4.17"
version = "0.4.18"
dependencies = [
"bson",
"chrono",
@@ -774,7 +774,7 @@ dependencies = [
[[package]]
name = "compliance-mcp"
version = "0.4.17"
version = "0.4.18"
dependencies = [
"axum",
"bson",
@@ -797,7 +797,7 @@ dependencies = [
[[package]]
name = "compliance-smoke"
version = "0.4.17"
version = "0.4.18"
dependencies = [
"axum",
"compliance-core",
@@ -932,7 +932,7 @@ dependencies = [
[[package]]
name = "control-map"
version = "0.4.17"
version = "0.4.18"
dependencies = [
"serde",
"serde_json",
@@ -7127,7 +7127,7 @@ dependencies = [
[[package]]
name = "werkbank-exec"
version = "0.4.17"
version = "0.4.18"
dependencies = [
"compliance-core",
"compliance-dast",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-agent"
version = "0.4.17"
version = "0.4.18"
edition = "2021"
[lints]
+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,
}
}
+12 -1
View File
@@ -349,7 +349,7 @@ fn json<T: Serialize>(value: &T) -> Result<Vec<u8>, AgentError> {
/// The findings as CSV, one row each, for a spreadsheet.
fn findings_csv(findings: &[Finding]) -> String {
let mut out =
String::from("id,severity,status,type,scanner,rule_id,cwe,location,title,cra_controls\n");
String::from("id,severity,status,type,scanner,rule_id,cwe,location,title,cra_controls,cra_requirements\n");
for f in findings {
let location = match (&f.file_path, f.line_number) {
(Some(file), Some(line)) => format!("{file}:{line}"),
@@ -367,6 +367,13 @@ fn findings_csv(findings: &[Finding]) -> String {
location,
f.title.clone(),
f.control_refs.join(" "),
// The same requirements by name, for a person reading the sheet.
f.control_refs
.iter()
.filter_map(|id| compliance_core::cra_requirements::name(id))
.map(|name| name.de)
.collect::<Vec<_>>()
.join("; "),
];
let cells: Vec<String> = row.iter().map(|c| csv_cell(c)).collect();
out.push_str(&cells.join(","));
@@ -636,6 +643,10 @@ mod tests {
"{csv}"
);
assert!(csv.contains("Core/Src/comms.c:9"));
assert!(
csv.contains(",cra-ai-8,Keine Standardpasswörter\n"),
"{csv}"
);
assert_eq!(csv_cell("=HYPERLINK(1)"), "'=HYPERLINK(1)");
assert_eq!(csv_cell("plain"), "plain");
}
+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()
}
);
}
}
+4 -13
View File
@@ -466,10 +466,6 @@ fn issue_body(alert: &CveAlert, severity: &str, target_id: &str, dashboard: &str
.push_str("- Behoben in / Fixed in: keine Version bekannt / no fixed version known\n"),
fixed => body.push_str(&format!("- Behoben in / Fixed in: {}\n", fixed.join(", "))),
}
body.push_str(&format!(
"- Advisory: https://osv.dev/vulnerability/{}\n",
alert.cve_id
));
if alert
.exploitation
.as_ref()
@@ -481,14 +477,8 @@ fn issue_body(alert: &CveAlert, severity: &str, target_id: &str, dashboard: &str
));
}
body.push_str("\n### CRA\n\n");
let map = control_map::ControlMap::cra().ok();
for id in CVE_CONTROLS {
let title = map
.as_ref()
.and_then(|m| m.coverage(id))
.map(|c| c.title.clone())
.unwrap_or_default();
body.push_str(&format!("- {id} — {title} (Annex I)\n"));
for requirement in crate::pipeline::issue_creation::cra_requirements(&CVE_CONTROLS) {
body.push_str(&format!("- {requirement}\n"));
}
let dashboard = dashboard.trim_end_matches('/');
if dashboard.starts_with("https://") {
@@ -809,7 +799,8 @@ mod tests {
// pruefwerk (1), cra:annex-i (2), severity:high (4), cve (7).
assert!(calls[0].ends_with("labels=[1,2,4,7]"), "{}", calls[0]);
assert!(calls[1].contains("Fixed in: 4.9.2"));
assert!(calls[1].contains("cra-ai-22"));
assert!(calls[1].contains("Bekannte Schwachstellen in Komponenten"));
assert!(!calls[1].contains("cra-ai-22"));
assert!(calls[1].contains("https://pruefwerk.example/targets/target-1"));
}
@@ -47,7 +47,6 @@ pub async fn notify_new_cves(
);
notification.cvss_score = alert.cvss_score;
notification.summary = alert.summary.clone();
notification.url = Some(format!("https://osv.dev/vulnerability/{}", alert.cve_id));
let notification = match mongodb::bson::to_bson(&notification) {
Ok(n) => n,
Err(e) => {
+15 -18
View File
@@ -687,23 +687,18 @@ pub(super) fn format_issue_body(finding: &Finding) -> String {
body
}
/// The CRA requirements a finding is evidence for, as `cra-ai-8 — <title>`,
/// from its stamped `control_refs`. Titles come from the CRA control map.
fn cra_requirements(control_refs: &[String]) -> Vec<String> {
let map = control_map::ControlMap::cra().ok();
/// The CRA requirements a finding is evidence for, from its stamped
/// `control_refs`, by the name a customer reads in both languages
/// (`Keine Standardpasswörter / No default passwords (Annex I)`). An id
/// outside the 40 requirements stays as it is.
pub(crate) fn cra_requirements<S: AsRef<str>>(control_refs: &[S]) -> Vec<String> {
control_refs
.iter()
.map(AsRef::as_ref)
.filter(|id| id.starts_with("cra-"))
.map(|id| {
match map
.as_ref()
.and_then(|m| m.coverage(id))
.map(|c| c.title.as_str())
.filter(|t| !t.is_empty())
{
Some(title) => format!("{id} — {title} (Annex I)"),
None => format!("{id} (Annex I)"),
}
.map(|id| match compliance_core::cra_requirements::name(id) {
Some(name) => format!("{} / {} (Annex I)", name.de, name.en),
None => format!("{id} (Annex I)"),
})
.collect()
}
@@ -737,9 +732,10 @@ mod tests {
fn cra_requirements_name_the_control() {
let refs = vec!["cra-ai-1".to_string(), "iec-x".to_string()];
let lines = cra_requirements(&refs);
assert_eq!(lines.len(), 1);
assert!(lines[0].starts_with("cra-ai-1 — "), "{lines:?}");
assert!(lines[0].ends_with("(Annex I)"));
assert_eq!(
lines,
["Sichere Werkseinstellungen / Secure factory settings (Annex I)"]
);
assert_eq!(
cra_requirements(&["cra-unknown".to_string()]),
["cra-unknown (Annex I)"]
@@ -761,7 +757,8 @@ mod tests {
f.control_refs = vec!["cra-ai-1".into()];
let body = format_issue_body(&f);
assert!(body.contains("**CWE:** CWE-89"));
assert!(body.contains("**CRA:** cra-ai-1"));
assert!(body.contains("**CRA:** Sichere Werkseinstellungen / Secure factory settings"));
assert!(!body.contains("cra-ai-1"));
assert!(body.contains("`fp1`"));
}
+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");
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-core"
version = "0.4.17"
version = "0.4.18"
edition = "2021"
[lints]
+683
View File
@@ -0,0 +1,683 @@
//! The 40 CRA Annex I requirements in the words a customer reads: a name
//! that says what the requirement is about, and for each state what it means
//! for that requirement (#sps2026 item 10).
//!
//! The catalog (`cra-ai-1` … `cra-ai-40`) stays the source of the ids and of
//! the legal wording; people never see those ids. Machine-readable exports
//! (CSAF, VEX, OSCAL, JSON) keep them.
/// One text in both languages of the product.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Words {
/// German.
pub de: &'static str,
/// English.
pub en: &'static str,
}
/// The area a requirement belongs to, in the catalog's group order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum CraArea {
/// Secure by design (`cra-ai-1` … `6`).
SecureDesign,
/// Sign-in and access (`7` … `12`).
Access,
/// Encryption (`13` … `17`).
Encryption,
/// Development (`18` … `20`).
Development,
/// Supply chain (`21` … `23`).
SupplyChain,
/// Logs (`24` … `27`).
Logging,
/// Updates (`28` … `31`).
Updates,
/// Vulnerabilities and incidents (`32` … `40`).
Vulnerabilities,
}
impl CraArea {
/// Every area, in the order the views show them.
pub const ALL: [Self; 8] = [
Self::SecureDesign,
Self::Access,
Self::Encryption,
Self::Development,
Self::SupplyChain,
Self::Logging,
Self::Updates,
Self::Vulnerabilities,
];
/// The area's name.
pub const fn name(self) -> Words {
match self {
Self::SecureDesign => w("Sicher entworfen", "Secure by design"),
Self::Access => w("Anmeldung und Zugriff", "Sign-in and access"),
Self::Encryption => w("Verschlüsselung", "Encryption"),
Self::Development => w("Entwicklung", "Development"),
Self::SupplyChain => w("Lieferkette", "Supply chain"),
Self::Logging => w("Protokolle", "Logs"),
Self::Updates => w("Updates", "Updates"),
Self::Vulnerabilities => w(
"Schwachstellen und Vorfälle",
"Vulnerabilities and incidents",
),
}
}
}
/// One requirement as a customer reads it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CraRequirement {
/// The catalog id (`cra-ai-8`).
pub id: &'static str,
/// Its area.
pub area: CraArea,
/// Its name (`Keine Standardpasswörter`).
pub name: Words,
/// What red means here: what an open finding against it shows. `None`
/// for a requirement a code scan cannot decide.
pub against: Option<Words>,
/// What green means here: what the scan did not find.
pub clear: Option<Words>,
/// The document that proves a requirement no code scan decides, as the
/// end of "Sie weisen sie nach mit …" (`ein Rechtekonzept`).
pub proof: Option<Words>,
}
/// What orange means for every requirement: only part of what it covers was
/// checked.
pub const PARTLY_CHECKED: Words = w(
"Nur ein Teil wurde geprüft, zum Beispiel bei einem Yocto-Image die Rezeptliste statt des \
fertigen Images.",
"Only part was checked, for example a Yocto image's recipe list instead of the built image.",
);
/// The requirement with catalog id `id`, if it is one of the 40.
///
/// # Examples
///
/// ```
/// use compliance_core::cra_requirements::requirement;
/// assert_eq!(requirement("cra-ai-8").unwrap().name.de, "Keine Standardpasswörter");
/// assert!(requirement("cra-ai-20-csharp-xxe").is_none());
/// ```
pub fn requirement(id: &str) -> Option<&'static CraRequirement> {
let number: usize = id.strip_prefix("cra-ai-")?.parse().ok()?;
CRA_REQUIREMENTS
.get(number.checked_sub(1)?)
.filter(|r| r.id == id)
}
/// The name of requirement `id` in German and English, or `None` for an id
/// that is not one of the 40.
pub fn name(id: &str) -> Option<Words> {
requirement(id).map(|r| r.name)
}
const fn w(de: &'static str, en: &'static str) -> Words {
Words { de, en }
}
/// A requirement a code scan checks.
const fn checked(
id: &'static str,
area: CraArea,
name: Words,
against: Words,
clear: Words,
) -> CraRequirement {
CraRequirement {
id,
area,
name,
against: Some(against),
clear: Some(clear),
proof: None,
}
}
/// A requirement proven by a document.
const fn proven(id: &'static str, area: CraArea, name: Words, proof: Words) -> CraRequirement {
CraRequirement {
id,
area,
name,
against: None,
clear: None,
proof: Some(proof),
}
}
use CraArea::{
Access, Development, Encryption, Logging, SecureDesign, SupplyChain, Updates, Vulnerabilities,
};
/// The 40 requirements, `cra-ai-1` first.
pub const CRA_REQUIREMENTS: [CraRequirement; 40] = [
checked(
"cra-ai-1",
SecureDesign,
w("Sichere Werkseinstellungen", "Secure factory settings"),
w(
"Im Auslieferungszustand ist etwas offen, das es nicht sein muss, etwa eine \
Debug-Schnittstelle oder ein unnötiger Dienst.",
"Something is open as shipped that need not be, such as a debug interface or an \
unneeded service.",
),
w(
"Der Scan fand keine unsicheren Voreinstellungen.",
"The scan found no insecure defaults.",
),
),
// Decided in code only on a Yocto layer tree, so it has both.
CraRequirement {
id: "cra-ai-2",
area: SecureDesign,
name: w("Nur nötige Dienste aktiv", "Only needed services running"),
against: Some(w(
"Das Image startet Dienste oder öffnet Schnittstellen, die das Gerät nicht braucht.",
"The image starts services or opens interfaces the device does not need.",
)),
clear: Some(w(
"Im Image fand der Scan keine unnötig aktiven Dienste.",
"The scan found no needlessly running services in the image.",
)),
proof: Some(w(
"eine Liste der Dienste und Schnittstellen mit ihrem Zweck",
"a list of services and interfaces with their purpose",
)),
},
proven(
"cra-ai-3",
SecureDesign,
w("Getrennte Sicherheitsbereiche", "Separated security zones"),
w(
"eine Architekturbeschreibung",
"an architecture description",
),
),
proven(
"cra-ai-4",
SecureDesign,
w("Nur die nötigen Rechte", "Only the rights needed"),
w("ein Rechtekonzept", "a permissions concept"),
),
proven(
"cra-ai-5",
SecureDesign,
w("Schutz vor Manipulation", "Protection against tampering"),
w(
"eine Beschreibung von Secure Boot und Code-Signatur",
"a description of secure boot and code signing",
),
),
checked(
"cra-ai-6",
SecureDesign,
w("Prüfung auf Veränderung", "Checks for modification"),
w(
"Software oder Firmware wird geladen, ohne vorher zu prüfen, ob sie verändert wurde.",
"Software or firmware is loaded without first checking whether it was modified.",
),
w(
"An den Stellen, an denen Software geladen wird, fand der Scan eine Prüfung auf \
Veränderung.",
"Where software is loaded, the scan found a check for modification.",
),
),
checked(
"cra-ai-7",
Access,
w("Sichere Anmeldung", "Secure sign-in"),
w(
"Eine Anmeldung ist schwach umgesetzt, etwa ohne Passwortprüfung oder mit einem \
veralteten Verfahren.",
"A sign-in is weakly built, for example without a password check or with an \
outdated method.",
),
w(
"Der Scan fand keine schwach umgesetzte Anmeldung.",
"The scan found no weakly built sign-in.",
),
),
checked(
"cra-ai-8",
Access,
w("Keine Standardpasswörter", "No default passwords"),
w(
"Im Code oder im Image steckt ein fest eingebautes Passwort, das auf jedem Gerät \
gleich ist.",
"The code or image holds a built-in password that is the same on every device.",
),
w(
"Der Scan fand kein fest eingebautes Passwort.",
"The scan found no built-in password.",
),
),
checked(
"cra-ai-9",
Access,
w("Zugangsdaten sicher verwahrt", "Credentials kept safe"),
w(
"Zugangsdaten, Tokens oder Schlüssel liegen im Klartext im Code oder in Dateien.",
"Credentials, tokens or keys are in plain text in the code or in files.",
),
w(
"Der Scan fand keine Zugangsdaten im Klartext.",
"The scan found no credentials in plain text.",
),
),
checked(
"cra-ai-10",
Access,
w("Sitzungen enden sicher", "Sessions end safely"),
w(
"Sitzungen laufen nicht ab oder sind nicht gegen untergeschobene Anfragen geschützt.",
"Sessions do not expire or are not protected against forged requests.",
),
w(
"Der Scan fand keine unsicher verwalteten Sitzungen.",
"The scan found no unsafely managed sessions.",
),
),
checked(
"cra-ai-11",
Access,
w(
"Schutz vor Passwort-Raten",
"Protection against password guessing",
),
w(
"Eine Anmeldung erlaubt beliebig viele Versuche.",
"A sign-in allows any number of attempts.",
),
w(
"Wo man sich anmeldet, ist die Zahl der Versuche begrenzt.",
"Where people sign in, the number of attempts is limited.",
),
),
checked(
"cra-ai-12",
Access,
w("Rollen und Rechte", "Roles and permissions"),
w(
"Funktionen für Administratoren sind ohne Rechteprüfung erreichbar.",
"Administrator functions can be reached without a permission check.",
),
w(
"Vor den geschützten Funktionen fand der Scan eine Rechteprüfung.",
"The scan found a permission check before the protected functions.",
),
),
checked(
"cra-ai-13",
Encryption,
w(
"Vertrauliche Daten verschlüsselt",
"Sensitive data encrypted",
),
w(
"Vertrauliche Daten werden unverschlüsselt oder mit einem veralteten Verfahren \
verarbeitet.",
"Sensitive data is handled unencrypted or with an outdated method.",
),
w(
"Der Scan fand keine unverschlüsselten vertraulichen Daten.",
"The scan found no unencrypted sensitive data.",
),
),
checked(
"cra-ai-14",
Encryption,
w("Gespeicherte Daten verschlüsselt", "Stored data encrypted"),
w(
"Daten werden unverschlüsselt oder mit einem schwachen Verfahren gespeichert.",
"Data is stored unencrypted or with a weak method.",
),
w(
"Der Scan fand keine unverschlüsselt gespeicherten Daten.",
"The scan found no data stored unencrypted.",
),
),
checked(
"cra-ai-15",
Encryption,
w("Verbindungen verschlüsselt", "Connections encrypted"),
w(
"Eine Verbindung läuft unverschlüsselt oder mit altem SSL/TLS.",
"A connection runs unencrypted or over old SSL/TLS.",
),
w(
"Alle gefundenen Verbindungen nutzen aktuelle Verschlüsselung.",
"Every connection found uses current encryption.",
),
),
checked(
"cra-ai-16",
Encryption,
w("Schlüssel sicher verwahrt", "Keys kept safe"),
w(
"Ein kryptografischer Schlüssel steht im Code oder liegt ungeschützt bei den Dateien.",
"A cryptographic key is written in the code or lies unprotected among the files.",
),
w(
"Der Scan fand keinen ungeschützten Schlüssel.",
"The scan found no unprotected key.",
),
),
proven(
"cra-ai-17",
Encryption,
w("Nur nötige Daten erfassen", "Collect only the data needed"),
w("ein Datenschutzkonzept", "a data protection concept"),
),
proven(
"cra-ai-18",
Development,
w(
"Sicherheit im Entwicklungsablauf",
"Security in the development process",
),
w(
"eine Beschreibung Ihres Entwicklungsablaufs",
"a description of your development process",
),
),
proven(
"cra-ai-19",
Development,
w("Code-Prüfung durch Kollegen", "Code review by colleagues"),
w("Ihre Regeln für Code-Reviews", "your code review rules"),
),
checked(
"cra-ai-20",
Development,
w("Sicherer Programmcode", "Safe program code"),
w(
"Im Code stecken unsichere Muster, etwa ungeprüfte Eingaben oder unsichere \
C-Funktionen.",
"The code holds unsafe patterns, such as unchecked input or unsafe C functions.",
),
w(
"Die Sicherheitstests fanden keine unsicheren Muster.",
"The security tests found no unsafe patterns.",
),
),
proven(
"cra-ai-21",
SupplyChain,
w("Fremdkomponenten geprüft", "Third-party components vetted"),
w(
"Ihren Prüfablauf für zugekaufte Komponenten",
"your vetting process for bought-in components",
),
),
checked(
"cra-ai-22",
SupplyChain,
w(
"Bekannte Schwachstellen in Komponenten",
"Known vulnerabilities in components",
),
w(
"Eine eingesetzte Komponente hat eine bekannte Schwachstelle, die noch offen ist.",
"A component in use has a known vulnerability that is still open.",
),
w(
"Für keine eingesetzte Komponente ist eine offene Schwachstelle bekannt.",
"No component in use has a known open vulnerability.",
),
),
checked(
"cra-ai-23",
SupplyChain,
w(
"Vollständige Stückliste (SBOM)",
"Complete bill of materials (SBOM)",
),
w(
"Die Stückliste fehlt, oder ihr fehlen Angaben wie Version oder Lizenz.",
"The bill of materials is missing, or lacks details such as version or licence.",
),
w(
"Die Stückliste ist vollständig und maschinenlesbar.",
"The bill of materials is complete and machine-readable.",
),
),
checked(
"cra-ai-24",
Logging,
w(
"Sicherheitsereignisse protokolliert",
"Security events logged",
),
w(
"Anmeldungen, Rechteänderungen oder Aktionen von Administratoren werden nicht \
protokolliert.",
"Sign-ins, permission changes or administrator actions are not logged.",
),
w(
"Der Scan fand eine Protokollierung der sicherheitsrelevanten Ereignisse.",
"The scan found the security-relevant events being logged.",
),
),
proven(
"cra-ai-25",
Logging,
w("Zentrale Überwachung", "Central monitoring"),
w("Ihr Überwachungskonzept", "your monitoring concept"),
),
proven(
"cra-ai-26",
Logging,
w(
"Angriffe automatisch erkannt",
"Attacks detected automatically",
),
w(
"eine Beschreibung Ihrer Angriffserkennung",
"a description of your attack detection",
),
),
checked(
"cra-ai-27",
Logging,
w("Fälschungssichere Protokolle", "Tamper-proof logs"),
w(
"Protokolle lassen sich nachträglich ändern oder werden zu kurz aufbewahrt.",
"Logs can be changed afterwards or are kept too briefly.",
),
w(
"Der Scan fand keine änderbaren oder zu kurz aufbewahrten Protokolle.",
"The scan found no logs that can be changed or are kept too briefly.",
),
),
checked(
"cra-ai-28",
Updates,
w("Sicherer Update-Weg", "Secure update channel"),
w(
"Updates kommen über einen ungesicherten Weg, etwa per HTTP.",
"Updates arrive over an unsecured channel, such as plain HTTP.",
),
w(
"Updates kommen über einen gesicherten Weg.",
"Updates arrive over a secured channel.",
),
),
checked(
"cra-ai-29",
Updates,
w("Signierte Updates", "Signed updates"),
w(
"Ein Update wird installiert, ohne vorher seine Signatur zu prüfen.",
"An update is installed without first checking its signature.",
),
w(
"Vor der Installation wird die Signatur eines Updates geprüft.",
"An update's signature is checked before it is installed.",
),
),
checked(
"cra-ai-30",
Updates,
w("Unversehrte Update-Pakete", "Intact update packages"),
w(
"Update-Pakete werden ohne Prüfsumme oder Signatur übernommen.",
"Update packages are taken without a checksum or signature.",
),
w(
"Update-Pakete werden vor der Übernahme geprüft.",
"Update packages are checked before they are taken.",
),
),
proven(
"cra-ai-31",
Updates,
w(
"Updates über die Lebensdauer",
"Updates over the product's lifetime",
),
w(
"eine Support-Zusage mit Enddatum",
"a support commitment with an end date",
),
),
proven(
"cra-ai-32",
Vulnerabilities,
w(
"Schwachstellen werden gesucht",
"Vulnerabilities are looked for",
),
w(
"Ihren Meldeweg und Ihre Überwachung",
"your reporting channel and monitoring",
),
),
checked(
"cra-ai-33",
Vulnerabilities,
w(
"Stückliste laufend geprüft",
"Bill of materials checked continuously",
),
w(
"Die Stückliste nennt Komponenten mit neu bekannt gewordenen Schwachstellen.",
"The bill of materials lists components with newly known vulnerabilities.",
),
w(
"Bei jedem Scan wird die Stückliste gegen bekannte Schwachstellen geprüft; nichts \
ist offen.",
"Every scan checks the bill of materials against known vulnerabilities; nothing is \
open.",
),
),
proven(
"cra-ai-34",
Vulnerabilities,
w("Wichtiges zuerst beheben", "Fix what matters first"),
w("Ihre Fristen für die Behebung", "your deadlines for fixes"),
),
proven(
"cra-ai-35",
Vulnerabilities,
w(
"Meldestelle für Schwachstellen",
"Vulnerability reporting contact",
),
w(
"eine veröffentlichte Kontaktadresse für Meldungen",
"a published contact address for reports",
),
),
proven(
"cra-ai-36",
Vulnerabilities,
w("Plan für Sicherheitsvorfälle", "Incident response plan"),
w("Ihren Notfallplan", "your emergency plan"),
),
proven(
"cra-ai-37",
Vulnerabilities,
w(
"Frühwarnung binnen 24 Stunden",
"Early warning within 24 hours",
),
w(
"Ihren Meldeablauf an ENISA und CSIRT",
"your reporting procedure to ENISA and the CSIRT",
),
),
proven(
"cra-ai-38",
Vulnerabilities,
w(
"Vorfallsbericht binnen 72 Stunden",
"Incident report within 72 hours",
),
w("Ihre Berichtsvorlage", "your report template"),
),
proven(
"cra-ai-39",
Vulnerabilities,
w("Sicherheits-Updates bereitstellen", "Ship security updates"),
w(
"Ihren Ablauf für Sicherheits-Updates",
"your procedure for security updates",
),
),
proven(
"cra-ai-40",
Vulnerabilities,
w("Lückenlos dokumentiert", "Fully documented"),
w(
"Ihre Dokumentation, zehn Jahre aufbewahrt",
"your documentation, kept for ten years",
),
),
];
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_table_is_in_id_order_and_every_id_resolves() {
for (i, r) in CRA_REQUIREMENTS.iter().enumerate() {
assert_eq!(r.id, format!("cra-ai-{}", i + 1));
assert_eq!(requirement(r.id), Some(r));
}
assert!(requirement("cra-ai-0").is_none());
assert!(requirement("cra-ai-41").is_none());
assert!(requirement("cra-ai-8-csharp-hardcoded-credential").is_none());
assert!(requirement("mc-1").is_none());
}
#[test]
fn every_requirement_says_what_its_states_mean() {
for r in &CRA_REQUIREMENTS {
assert_eq!(r.against.is_some(), r.clear.is_some(), "{}", r.id);
assert!(r.against.is_some() || r.proof.is_some(), "{}", r.id);
for words in [Some(r.name), r.against, r.clear, r.proof]
.into_iter()
.flatten()
{
assert!(!words.de.is_empty() && !words.en.is_empty(), "{}", r.id);
}
}
}
#[test]
fn names_are_unique_and_every_area_has_requirements() {
let mut names: Vec<&str> = CRA_REQUIREMENTS.iter().map(|r| r.name.de).collect();
names.sort_unstable();
names.dedup();
assert_eq!(names.len(), CRA_REQUIREMENTS.len());
for area in CraArea::ALL {
assert!(CRA_REQUIREMENTS.iter().any(|r| r.area == area), "{area:?}");
}
}
}
+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));
+1
View File
@@ -2,6 +2,7 @@ pub mod build_info;
pub mod component_changes;
pub mod config;
pub mod control_check;
pub mod cra_requirements;
pub mod csaf_docs;
pub mod csaf_ingest;
pub mod cve_groups;
+39
View File
@@ -28,6 +28,20 @@ pub struct AdvisoryRef {
pub remediation: Option<String>,
}
/// The providers whose terms ask every use of an advisory to link it.
const BACKLINK_PROVIDERS: &[&str] = &["siemens"];
impl AdvisoryRef {
/// The advisory's page when its provider's terms require a link back to
/// it (Siemens ProductCERT); `None` otherwise. The views link nothing
/// else off-site: a customer copies the id instead.
pub fn required_backlink(&self) -> Option<&str> {
self.url
.as_deref()
.filter(|_| BACKLINK_PROVIDERS.contains(&self.provider.as_str()))
}
}
/// What is known about the exploitation of one CVE (#493), from public
/// sources: CISA's Known Exploited Vulnerabilities catalog, FIRST's EPSS and
/// CISA's Vulnrichment SSVC decision points.
@@ -284,6 +298,31 @@ mod tests {
a
}
#[test]
fn only_a_provider_that_asks_for_it_keeps_its_link() {
let advisory = |provider: &str| AdvisoryRef {
provider: provider.into(),
id: "X-1".into(),
title: "t".into(),
url: Some("https://vendor.example/x-1".into()),
remediation: None,
};
assert_eq!(
advisory("siemens").required_backlink(),
Some("https://vendor.example/x-1")
);
assert_eq!(advisory("codesys").required_backlink(), None);
assert_eq!(
advisory("supplier:https://s.example/pm.json").required_backlink(),
None
);
let unlinked = AdvisoryRef {
url: None,
..advisory("siemens")
};
assert_eq!(unlinked.required_backlink(), None);
}
#[test]
fn only_not_affected_and_fixed_resolve_an_alert() {
use crate::models::vex::{VexAssessment, VexStatus};
+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" }
}
]
}
]
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-dashboard"
version = "0.4.17"
version = "0.4.18"
edition = "2021"
default-run = "compliance-dashboard"
+272 -112
View File
@@ -884,6 +884,12 @@ tbody tr:last-child td {
}
/* Neutral: skipped because a feature is disabled in this environment — not an error. */
.badge-open {
background: var(--bg-elevated);
color: var(--text-secondary);
border: 1px dashed var(--text-faint);
}
.badge-neutral {
background: transparent;
color: var(--text-tertiary);
@@ -2955,18 +2961,6 @@ tbody tr:last-child td {
text-transform: uppercase;
}
.sbom-vuln-link {
font-size: 12px;
color: var(--accent);
text-decoration: none;
transition: color 0.15s;
}
.sbom-vuln-link:hover {
color: var(--accent-hover);
text-decoration: underline;
}
/* License compliance */
.sbom-license-badge {
font-size: 12px;
@@ -4243,9 +4237,7 @@ tbody tr:last-child td {
.notification-sev.sev-high { background: rgba(255,140,0,0.12); color: #ff8c00; }
.notification-sev.sev-medium { background: var(--warning-bg); color: var(--warning); }
.notification-sev.sev-low { background: rgba(0,200,255,0.08); color: var(--accent); }
.notification-cve-id { font-size: 12px; font-weight: 600; color: var(--text-primary); font-family: var(--font-mono); }
.notification-cve-id a { color: var(--accent); text-decoration: none; }
.notification-cve-id a:hover { text-decoration: underline; }
.notification-cve-id { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; font-weight: 600; color: var(--text-primary); font-family: var(--font-mono); }
.notification-cvss { font-size: 10px; color: var(--text-secondary); margin-left: auto; font-family: var(--font-mono); }
.notification-dismiss-btn { background: none; border: none; color: var(--text-tertiary); cursor: pointer; padding: 2px; margin-left: 4px; }
.notification-dismiss-btn:hover { color: var(--danger); }
@@ -4482,6 +4474,17 @@ tbody tr:last-child td {
align-items: center;
}
.finding-control {
display: inline-flex;
align-items: center;
padding: 2px 8px;
border-radius: 999px;
background: var(--accent-muted);
color: var(--text-primary);
font-size: 12px;
line-height: 1.35;
}
.finding-controls-more,
.finding-controls-none {
font-size: 11px;
@@ -4492,7 +4495,8 @@ tbody tr:last-child td {
.finding-refs {
list-style: none;
display: grid;
gap: 4px;
justify-items: start;
gap: 6px;
}
.finding-refs-catalog {
@@ -4582,8 +4586,8 @@ tbody tr:last-child td {
}
.cra-violated { background: var(--danger); }
.cra-open { background: var(--warning); }
.cra-partial { background: var(--info); }
.cra-open { background: var(--text-faint); }
.cra-partial { background: var(--warning); }
.cra-clear { background: var(--success); }
.cra-process { background: color-mix(in srgb, var(--accent) 28%, var(--bg-elevated)); }
@@ -5585,7 +5589,20 @@ tbody tr:last-child td {
}
.vex-advisory {
display: block;
font-family: var(--font-mono);
font-size: 11.5px;
color: var(--text-secondary);
}
.vex-cve-id,
.vex-advisory-line {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px 6px;
}
.vex-advisory-source {
font-size: 11.5px;
color: var(--accent);
}
@@ -5742,13 +5759,6 @@ tbody tr:last-child td {
gap: 6px 10px;
}
.cra-control-id {
font-family: var(--font-mono);
font-size: 11.5px;
color: var(--text-tertiary);
min-width: 72px;
}
.cra-control-title {
font-weight: 500;
}
@@ -5759,7 +5769,6 @@ tbody tr:last-child td {
}
.cra-control-reason {
padding-left: 82px;
font-size: 12.5px;
color: var(--text-secondary);
}
@@ -5768,7 +5777,6 @@ tbody tr:last-child td {
list-style: none;
display: grid;
gap: 3px;
padding-left: 82px;
font-size: 12.5px;
}
@@ -8062,14 +8070,18 @@ span.repo-crumb-name {
overflow-wrap: anywhere;
}
/* ── CRA Annex I tiles (#957) ── */
/* ── CRA Annex I map (#957): requirements by name, grouped by area ── */
.ct-card,
.sh-card {
display: grid;
gap: 12px;
}
.ct-head,
.ct-head {
display: grid;
gap: 10px;
}
.sh-head {
display: flex;
flex-wrap: wrap;
@@ -8084,7 +8096,6 @@ span.repo-crumb-name {
font-weight: 600;
}
.ct-legend,
.sh-legend {
display: flex;
flex-wrap: wrap;
@@ -8093,97 +8104,250 @@ span.repo-crumb-name {
font-size: 12px;
}
.ct-legend-item {
display: inline-flex;
align-items: center;
gap: 6px;
}
.ct-swatch {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 20px;
height: 16px;
padding: 0 3px;
border-radius: 3px;
font-size: 10px;
font-weight: 700;
}
/* Ten to a row, as the 40 requirements make four rows; five on a phone. */
.ct-grid {
display: grid;
grid-template-columns: repeat(10, minmax(0, 1fr));
gap: 6px;
}
@media (max-width: 720px) {
.ct-grid {
grid-template-columns: repeat(5, minmax(0, 1fr));
}
}
.ct-tile {
display: flex;
flex-direction: column;
justify-content: space-between;
min-height: 56px;
padding: 6px 8px;
border: 1px solid transparent;
border-radius: var(--radius);
font-family: var(--font-mono);
font-size: 12px;
text-decoration: none;
}
.ct-tile:hover,
.ct-tile:focus-visible {
outline: 2px solid var(--text-primary);
outline-offset: 1px;
}
.ct-tile-mark {
align-self: flex-end;
font-family: var(--font-body);
font-size: 13px;
font-weight: 700;
}
/* A state's colour, always with its sign beside it. */
.ct-ok { background: var(--success); color: #fff; }
.ct-bad { background: var(--danger); color: #fff; }
.ct-open { background: var(--warning-bg); border-color: var(--border-bright); color: var(--text-primary); }
.ct-partial { background: var(--info-bg); border-color: var(--border-bright); color: var(--text-primary); }
.ct-process { background: var(--bg-elevated); border-color: var(--border-bright); color: var(--text-secondary); }
.ct-hint,
.sh-hint {
color: var(--text-tertiary);
font-size: 12.5px;
}
.ct-crumbs {
/* The areas beside the open requirement; the panel goes below on a phone. */
.ct-layout {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px;
font-size: 13px;
align-items: flex-start;
gap: 16px;
}
.ct-crumbs a {
color: var(--accent);
}
.ct-back {
margin-left: auto;
}
.ct-detail {
.ct-areas {
flex: 999 1 560px;
min-width: 0;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(min(100%, 260px), 1fr));
gap: 12px;
}
.ct-area {
display: grid;
align-content: start;
gap: 8px;
padding: 12px;
border: 1px solid var(--border);
border-radius: var(--radius);
background: var(--bg-card);
}
.ct-area-name {
font-size: 14px;
font-weight: 600;
}
.ct-area-bar {
height: 6px;
}
.ct-chips {
list-style: none;
display: grid;
gap: 6px;
}
/* A requirement: its state's sign, its name, and its open findings. */
.ct-chip {
display: flex;
align-items: center;
gap: 10px;
min-height: 44px;
padding: 8px 10px;
border: 1px solid transparent;
border-radius: var(--radius);
color: var(--text-primary);
font-size: 13.5px;
font-weight: 500;
line-height: 1.3;
text-decoration: none;
}
.ct-chip:hover {
border-color: var(--accent);
}
.ct-chip:focus-visible,
.ct-chip.is-selected {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.ct-chip-name {
flex: 1 1 auto;
min-width: 0;
}
.ct-chip-n {
flex-shrink: 0;
min-width: 22px;
height: 22px;
padding: 0 6px;
border-radius: 11px;
display: inline-flex;
align-items: center;
justify-content: center;
background: var(--bg-card);
color: var(--danger);
font-size: 12px;
font-weight: 700;
font-variant-numeric: tabular-nums;
}
.ct-chip.ct-ok { background: var(--success-bg); }
.ct-chip.ct-unknown { border-color: var(--border-bright); }
.ct-chip.ct-bad { background: var(--danger); border-color: var(--danger); color: #fff; font-weight: 600; }
.ct-chip.ct-partial { background: var(--warning-bg); border-color: var(--warning); }
.ct-chip.ct-open { background: var(--bg-elevated); border: 1px dashed var(--text-faint); color: var(--text-secondary); }
.ct-chip.ct-process { background: transparent; border: 1px dotted var(--text-faint); color: var(--text-secondary); }
/* A state's sign in a round mark: never colour alone. */
.ct-mark {
flex-shrink: 0;
width: 20px;
height: 20px;
border-radius: 50%;
display: inline-flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
}
.ct-mark.ct-ok { background: var(--success); color: #fff; }
.ct-mark.ct-bad { background: var(--danger); color: #fff; }
.ct-mark.ct-partial { background: var(--warning); color: #fff; }
.ct-mark.ct-open { background: var(--bg-elevated); border: 1px dashed var(--text-faint); color: var(--text-secondary); }
.ct-mark.ct-process { background: var(--bg-card); border: 1px dotted var(--text-faint); color: var(--text-secondary); }
.ct-chip.ct-bad .ct-mark { background: #fff; color: var(--danger); }
/* The open requirement. */
.ct-panel {
flex: 1 1 320px;
min-width: 0;
max-width: 440px;
display: grid;
align-content: start;
gap: 14px;
padding: 16px;
border: 1px solid var(--border);
border-radius: var(--radius);
background: var(--bg-card);
}
/* Where the map and panel no longer fit side by side, the panel goes first,
so the requirement a tap opens is not below all forty. */
@media (max-width: 1200px) {
.ct-panel {
order: -1;
max-width: none;
}
}
.ct-panel-empty {
color: var(--text-tertiary);
font-size: 13.5px;
}
.ct-panel-head {
display: grid;
gap: 8px;
}
.ct-panel-area {
color: var(--text-tertiary);
font-size: 12.5px;
}
.ct-panel-name {
font-size: 20px;
font-weight: 600;
line-height: 1.25;
}
.ct-panel-state {
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
}
.ct-panel-what {
color: var(--text-secondary);
font-size: 14px;
line-height: 1.5;
}
.ct-meanings,
.ct-proof {
display: grid;
gap: 8px;
}
.ct-meanings h4,
.ct-proof h4 {
font-size: 13px;
font-weight: 600;
}
.ct-meanings ul {
list-style: none;
display: grid;
gap: 6px;
}
.ct-meaning {
display: flex;
align-items: flex-start;
gap: 10px;
padding: 8px 10px;
border: 1px solid var(--border);
border-radius: var(--radius);
font-size: 13.5px;
line-height: 1.45;
}
.ct-meaning div {
display: grid;
gap: 2px;
}
.ct-meaning span {
color: var(--text-secondary);
}
.ct-meaning.is-now {
border-color: var(--accent);
background: var(--bg-card-hover);
}
.ct-proof {
padding: 12px;
border: 1px dotted var(--text-faint);
border-radius: var(--radius);
font-size: 13.5px;
line-height: 1.45;
color: var(--text-secondary);
}
.ct-panel-detail:empty {
display: none;
}
.ct-panel-detail .cra-control {
padding-top: 0;
border-top: 0;
}
.ct-panel-links {
display: flex;
flex-wrap: wrap;
gap: 8px 16px;
}
/* ── Verlauf: per scan, new CVEs above the line, gone below (#957) ── */
.sh-swatch {
display: inline-block;
@@ -8402,10 +8566,6 @@ span.repo-crumb-name {
margin-top: 0;
}
.vex-advisory-line .vex-advisory {
display: inline;
}
.vex-advisory-note {
font-size: 11px;
color: var(--text-tertiary);
@@ -2,12 +2,22 @@ use dioxus::prelude::*;
use dioxus_free_icons::icons::bs_icons::*;
use dioxus_free_icons::Icon;
use crate::i18n::texts::common;
use crate::i18n::use_lang;
/// A small copy-to-clipboard button that shows a checkmark after copying.
///
/// Usage: `CopyButton { value: "text to copy" }`
#[component]
pub fn CopyButton(value: String, #[props(default = false)] small: bool) -> Element {
let lang = use_lang()();
let mut copied = use_signal(|| false);
let label = if copied() {
common::COPIED
} else {
common::COPY
};
let tip = format!("{}: {value}", label.get(lang));
let size = if small { 12 } else { 14 };
let class = if small {
@@ -19,7 +29,9 @@ pub fn CopyButton(value: String, #[props(default = false)] small: bool) -> Eleme
rsx! {
button {
class: class,
title: if copied() { "Copied!" } else { "Copy to clipboard" },
r#type: "button",
title: "{tip}",
"aria-label": "{tip}",
onclick: move |_| {
let val = value.clone();
// Escape for JS single-quoted string
+313 -110
View File
@@ -1,37 +1,90 @@
//! The CRA Annex I view of a target (#957): its 40 requirements as tiles,
//! coloured by state and marked with a sign, so the state is never told by
//! colour alone. A tile opens the requirement with what its state rests on.
//! The CRA Annex I view of a target (#957): its 40 requirements by name,
//! grouped by area, each marked with its state's colour and sign so the
//! state is never told by colour alone. A requirement opens beside the map
//! with what its colour means for it and what the state rests on.
use compliance_core::cra_requirements::{self as cra, CraArea, CraRequirement};
use dioxus::prelude::*;
use crate::app::Route;
use crate::components::cra_bar::CraBar;
use crate::i18n::texts::{common, compliance, cra_tiles as tx};
use crate::i18n::use_lang;
use crate::infrastructure::evidence::fetch_compliance;
use crate::pages::compliance::{ControlRow, STATES};
use crate::i18n::{use_lang, Lang, Text};
use crate::infrastructure::evidence::{fetch_compliance, CraCounts};
use crate::pages::compliance::{requirement_name, ControlRow, STATES};
use crate::pages::target_views::RepoView;
/// A tile's sign and CSS tone for a control `state` (as the API names it).
/// A state's sign (an SVG path) and CSS tone, for a control `state` as the
/// API names it.
fn mark(state: &str) -> (&'static str, &'static str) {
match state {
"not_satisfied" => ("!", "ct-bad"),
"not_assessed" => ("?", "ct-open"),
"partial" => ("~", "ct-partial"),
"no_violation_found" => ("OK", "ct-ok"),
_ => ("–", "ct-process"),
"not_satisfied" => ("M12 5v9M12 19v.5", "ct-bad"),
"partial" => ("M5 12h14", "ct-partial"),
"no_violation_found" => ("M5 12.5l4.5 4.5L19 7.5", "ct-ok"),
"not_assessed" => ("M9 9a3 3 0 1 1 4 2.8c-.7.3-1 .9-1 1.7M12 18v.5", "ct-open"),
_ => ("M7 4h7l4 4v12H7zM14 4v4h4M10 13h5M10 16h5", "ct-process"),
}
}
/// The short name a tile shows for control `id`: `cra-ai-7` is `AI-07`;
/// another id stays as it is.
fn short_id(id: &str) -> String {
id.strip_prefix("cra-ai-")
.and_then(|n| n.parse::<u32>().ok())
.map_or_else(|| id.to_string(), |n| format!("AI-{n:02}"))
/// The CSS tone of a requirement in `state`, or of one whose state is not
/// known (`None`).
pub(crate) fn cra_tone(state: Option<&str>) -> &'static str {
state.map_or("ct-unknown", |s| mark(s).1)
}
/// `controls` in tile order: by the number of their id, others last.
fn in_tile_order(mut controls: Vec<serde_json::Value>) -> Vec<serde_json::Value> {
/// The CraBar segment class of a control `state`, so an area's small bar
/// uses the target bar's colours.
fn bar_modifier(state: &str) -> &'static str {
match state {
"not_satisfied" => "violated",
"not_assessed" => "open",
"partial" => "partial",
"no_violation_found" => "clear",
_ => "process",
}
}
/// A state's label (`Offene Befunde`).
fn state_label(state: &str, lang: Lang) -> &'static str {
STATES
.iter()
.find(|(s, _, _)| *s == state)
.map_or("", |(_, label, _)| label.get(lang))
}
/// The sign of `state` in a round mark of its tone.
#[component]
pub(crate) fn StateMark(state: String) -> Element {
let (path, tone) = mark(&state);
rsx! {
span { class: "ct-mark {tone}", "aria-hidden": "true",
svg {
width: "12",
height: "12",
view_box: "0 0 24 24",
fill: "none",
stroke: "currentColor",
stroke_width: "3",
stroke_linecap: "round",
stroke_linejoin: "round",
path { d: path }
}
}
}
}
/// One area of the map: the API's controls of that area, in id order.
struct AreaControls {
name: Text,
controls: Vec<serde_json::Value>,
}
/// `controls` (the compliance API's) grouped by area in the catalog's order;
/// a control outside the 40 goes to a last group of its own.
fn by_area(controls: &[serde_json::Value]) -> Vec<AreaControls> {
let requirement = |c: &serde_json::Value| -> Option<&'static CraRequirement> {
c["control"].as_str().and_then(cra::requirement)
};
let number = |c: &serde_json::Value| {
c["control"]
.as_str()
@@ -39,12 +92,69 @@ fn in_tile_order(mut controls: Vec<serde_json::Value>) -> Vec<serde_json::Value>
.and_then(|n| n.parse::<u32>().ok())
.unwrap_or(u32::MAX)
};
controls.sort_by_key(number);
controls
let mut areas: Vec<AreaControls> = CraArea::ALL
.iter()
.map(|area| {
let mut list: Vec<serde_json::Value> = controls
.iter()
.filter(|c| requirement(c).is_some_and(|r| r.area == *area))
.cloned()
.collect();
list.sort_by_key(number);
AreaControls {
name: area.name().into(),
controls: list,
}
})
.filter(|a| !a.controls.is_empty())
.collect();
let others: Vec<serde_json::Value> = controls
.iter()
.filter(|c| requirement(c).is_none())
.cloned()
.collect();
if !others.is_empty() {
areas.push(AreaControls {
name: tx::OTHER_AREA,
controls: others,
});
}
areas
}
/// The tiles of target `target_id`, or, with `control` (from the URL) set,
/// that requirement with its state, findings and reasons.
/// The number of open findings `control` lists.
fn finding_count(control: &serde_json::Value) -> usize {
control["findings"].as_array().map_or(0, Vec::len)
}
/// What the state of `control` means right now, in one sentence.
fn state_sentence(control: &serde_json::Value, lang: Lang) -> String {
let req = control["control"].as_str().and_then(cra::requirement);
match control["state"].as_str().unwrap_or_default() {
"not_satisfied" => {
let against = req
.and_then(|r| r.against)
.map_or(tx::AGAINST_GENERIC, Text::from);
format!(
"{} {}",
tx::against_count(finding_count(control), lang),
against.get(lang)
)
}
"no_violation_found" => req
.and_then(|r| r.clear)
.map_or(tx::CLEAR_GENERIC, Text::from)
.get(lang)
.to_string(),
"partial" => Text::from(cra::PARTLY_CHECKED).get(lang).to_string(),
"not_assessed" => compliance::not_assessed_reason(&control["reason"], lang)
.unwrap_or_else(|| tx::OPEN_GENERIC.get(lang).to_string()),
_ => tx::PROCESS_GENERIC.get(lang).to_string(),
}
}
/// The map of target `target_id`'s requirements, with `control` (from the
/// URL) open beside it.
#[component]
pub fn CraTiles(target_id: String, control: Option<String>) -> Element {
let lang = use_lang()();
@@ -59,7 +169,9 @@ pub fn CraTiles(target_id: String, control: Option<String>) -> Element {
let Some(data) = loaded else {
return rsx! { div { class: "card", p { {tx::LOAD_FAILED.get(lang)} } } };
};
let controls = in_tile_order(data["controls"].as_array().cloned().unwrap_or_default());
let controls = data["controls"].as_array().cloned().unwrap_or_default();
let counts: CraCounts = serde_json::from_value(data["counts"].clone()).unwrap_or_default();
let areas = by_area(&controls);
let to_tile = |control: Option<String>| Route::TargetViewsPage {
id: target_id.clone(),
view: RepoView::Cra.slug().to_string(),
@@ -68,96 +180,152 @@ pub fn CraTiles(target_id: String, control: Option<String>) -> Element {
control,
scan: None,
};
if let Some(wanted) = control {
let back = to_tile(None);
let Some(chosen) = controls
let chosen = control.as_ref().map(|wanted| {
controls
.iter()
.find(|c| c["control"].as_str() == Some(wanted.as_str()))
.cloned()
else {
return rsx! {
div { class: "card",
p { {tx::UNKNOWN.get(lang)} }
Link { class: "repo-view-list", to: back, {tx::BACK.get(lang)} }
}
};
};
let state = chosen["state"].as_str().unwrap_or_default().to_string();
let (label, badge) = STATES
.iter()
.find(|(s, _, _)| *s == state)
.map_or(("", "badge"), |(_, label, badge)| (label.get(lang), *badge));
return rsx! {
nav { class: "ct-crumbs", "aria-label": tx::BREADCRUMB.get(lang),
Link { to: back.clone(), "CRA" }
span { "aria-hidden": "true", " › " }
strong { "{short_id(&wanted)} {chosen[\"title\"].as_str().unwrap_or_default()}" }
Link { class: "btn btn-sm btn-ghost ct-back", to: back, {tx::BACK.get(lang)} }
}
section { class: "card ct-detail",
p { span { class: "{badge}", "{label}" } }
ul { class: "cra-controls",
ControlRow { control: chosen, lang, show_reason: true }
}
Link {
class: "repo-view-list",
to: Route::CompliancePage { id: target_id.clone() },
{tx::ALL_REQUIREMENTS.get(lang)}
}
}
};
}
});
rsx! {
section { class: "card ct-card", "aria-label": tx::TITLE.get(lang),
div { class: "ct-head",
h3 { class: "ct-title", {tx::title(controls.len(), lang)} }
div { class: "ct-legend",
for (state, label, _) in STATES {
{
let (sign, tone) = mark(state);
let n = controls.iter().filter(|c| c["state"].as_str() == Some(state)).count();
rsx! {
span { key: "{state}", class: "ct-legend-item",
span { class: "ct-swatch {tone}", "aria-hidden": "true", "{sign}" }
"{label.get(lang)} ({n})"
CraBar { counts }
p { class: "ct-hint", {compliance::NOT_LEGAL_ADVICE.get(lang)} }
}
div { class: "ct-layout",
div { class: "ct-areas",
for area in areas {
section { class: "ct-area", "aria-label": area.name.get(lang),
h4 { class: "ct-area-name", {area.name.get(lang)} }
div { class: "cra-bar-track ct-area-bar", "aria-hidden": "true",
for (state, _, _) in STATES {
{
let n = area.controls.iter().filter(|c| c["state"].as_str() == Some(state)).count();
rsx! {
if n > 0 {
span { class: "cra-bar-seg cra-{bar_modifier(state)}", style: "flex: {n} 0 0;" }
}
}
}
}
}
ul { class: "ct-chips",
for c in area.controls.iter() {
{
let cid = c["control"].as_str().unwrap_or_default().to_string();
let state = c["state"].as_str().unwrap_or_default().to_string();
let (_, tone) = mark(&state);
let selected = control.as_deref() == Some(cid.as_str());
let n = finding_count(c);
let name = requirement_name(c, lang);
let label = state_label(&state, lang);
rsx! {
li { key: "{cid}",
Link {
class: if selected { "ct-chip {tone} is-selected" } else { "ct-chip {tone}" },
"aria-current": if selected { "true" } else { "false" },
to: to_tile(Some(cid.clone())),
StateMark { state: state.clone() }
span { class: "ct-chip-name", "{name}" }
if n > 0 {
span { class: "ct-chip-n", "{n}" }
}
span { class: "sr-only", ", {label}" }
}
}
}
}
}
}
}
}
}
aside { class: "ct-panel", "aria-label": tx::SELECTED.get(lang),
match chosen {
None => rsx! { p { class: "ct-panel-empty", {tx::PICK.get(lang)} } },
Some(None) => rsx! {
p { {tx::UNKNOWN.get(lang)} }
Link { class: "repo-view-list", to: to_tile(None), {tx::CLOSE.get(lang)} }
},
Some(Some(c)) => rsx! {
RequirementPanel { control: c, lang, close: to_tile(None), all: Route::CompliancePage { id: target_id.clone() } }
},
}
}
}
div { class: "ct-grid",
for c in controls.iter() {
{
let id = c["control"].as_str().unwrap_or_default().to_string();
let state = c["state"].as_str().unwrap_or_default();
let (sign, tone) = mark(state);
let state_label = STATES
.iter()
.find(|(s, _, _)| *s == state)
.map_or("", |(_, label, _)| label.get(lang));
let tip = format!(
"{}: {} ({state_label})",
short_id(&id),
c["title"].as_str().unwrap_or_default()
);
rsx! {
Link {
key: "{id}",
class: "ct-tile {tone}",
title: "{tip}",
"aria-label": "{tip}",
to: to_tile(Some(id.clone())),
span { class: "ct-tile-id", "{short_id(&id)}" }
span { class: "ct-tile-mark", "{sign}" }
}
}
}
/// The open requirement: its name and state, what each colour means for it
/// (or the document that proves it), and what its state rests on.
#[component]
fn RequirementPanel(control: serde_json::Value, lang: Lang, close: Route, all: Route) -> Element {
let req = control["control"].as_str().and_then(cra::requirement);
let state = control["state"].as_str().unwrap_or_default().to_string();
let area = req.map(|r| Text::from(r.area.name()).get(lang));
let name = requirement_name(&control, lang);
let sentence = state_sentence(&control, lang);
// Red, orange, green: what each would mean for this requirement.
let meanings: Vec<(&str, Text, Text)> = req
.and_then(|r| r.against.zip(r.clear))
.map(|(against, clear)| {
vec![
("not_satisfied", tx::RED, against.into()),
("partial", tx::ORANGE, cra::PARTLY_CHECKED.into()),
("no_violation_found", tx::GREEN, clear.into()),
]
})
.unwrap_or_default();
let proof = req.and_then(|r| r.proof).map(Text::from);
rsx! {
div { class: "ct-panel-head",
if let Some(area) = area {
span { class: "ct-panel-area", "{area}" }
}
h3 { class: "ct-panel-name", "{name}" }
p { class: "ct-panel-state",
StateMark { state: state.clone() }
strong { {state_label(&state, lang)} }
}
p { class: "ct-panel-what", "{sentence}" }
}
if !meanings.is_empty() {
div { class: "ct-meanings",
h4 { {tx::MEANINGS.get(lang)} }
ul {
for (meaning_state, colour, text) in meanings {
li { class: if meaning_state == state { "ct-meaning is-now" } else { "ct-meaning" },
StateMark { state: meaning_state.to_string() }
div {
strong {
{colour.get(lang)}
if meaning_state == state {
{tx::NOW.get(lang)}
}
}
span { {text.get(lang)} }
}
}
}
}
}
p { class: "ct-hint", {tx::HINT.get(lang)} " " {compliance::NOT_LEGAL_ADVICE.get(lang)} }
}
if let Some(proof) = proof {
div { class: "ct-proof",
h4 { {tx::PROOF_TITLE.get(lang)} }
p { {tx::proof(proof.get(lang), lang)} }
}
}
ul { class: "cra-controls ct-panel-detail",
ControlRow { control, lang, show_reason: false, headless: true }
}
div { class: "ct-panel-links",
Link { class: "repo-view-list", to: close, {tx::CLOSE.get(lang)} }
Link { class: "repo-view-list", to: all, {tx::ALL_REQUIREMENTS.get(lang)} }
}
}
}
@@ -167,25 +335,60 @@ mod tests {
use super::*;
#[test]
fn a_tile_names_its_requirement_short_and_in_number_order() {
assert_eq!(short_id("cra-ai-7"), "AI-07");
assert_eq!(short_id("cra-ai-40"), "AI-40");
assert_eq!(short_id("custom"), "custom");
let ordered = in_tile_order(vec![
serde_json::json!({ "control": "cra-ai-10" }),
serde_json::json!({ "control": "other" }),
serde_json::json!({ "control": "cra-ai-2" }),
]);
let ids: Vec<&str> = ordered
fn controls_are_grouped_by_area_in_id_order() {
let controls = vec![
serde_json::json!({ "control": "cra-ai-9" }),
serde_json::json!({ "control": "custom" }),
serde_json::json!({ "control": "cra-ai-7" }),
serde_json::json!({ "control": "cra-ai-1" }),
];
let areas = by_area(&controls);
let ids: Vec<Vec<&str>> = areas
.iter()
.filter_map(|c| c["control"].as_str())
.map(|a| {
a.controls
.iter()
.filter_map(|c| c["control"].as_str())
.collect()
})
.collect();
assert_eq!(ids, ["cra-ai-2", "cra-ai-10", "other"]);
assert_eq!(
ids,
[
vec!["cra-ai-1"],
vec!["cra-ai-7", "cra-ai-9"],
vec!["custom"]
]
);
assert_eq!(areas[0].name.de, "Sicher entworfen");
assert_eq!(areas[2].name, tx::OTHER_AREA);
}
#[test]
fn every_state_has_its_own_sign() {
let signs: Vec<&str> = STATES.iter().map(|(s, _, _)| mark(s).0).collect();
assert_eq!(signs, ["!", "?", "~", "OK", "–"]);
let mut signs: Vec<&str> = STATES.iter().map(|(s, _, _)| mark(s).0).collect();
signs.sort_unstable();
signs.dedup();
assert_eq!(signs.len(), STATES.len());
}
#[test]
fn the_sentence_says_what_the_state_means_for_the_requirement() {
let red = serde_json::json!({
"control": "cra-ai-8", "state": "not_satisfied",
"findings": [{ "id": "a" }, { "id": "b" }],
});
let text = state_sentence(&red, Lang::De);
assert!(text.starts_with("2 offene Befunde"), "{text}");
assert!(text.contains("fest eingebautes Passwort"), "{text}");
let green = serde_json::json!({ "control": "cra-ai-8", "state": "no_violation_found" });
assert_eq!(
state_sentence(&green, Lang::En),
"The scan found no built-in password."
);
let process = serde_json::json!({ "control": "cra-ai-36", "state": "not_code_checkable" });
assert_eq!(state_sentence(&process, Lang::De), tx::PROCESS_GENERIC.de);
}
}
+76 -43
View File
@@ -3,13 +3,15 @@
//! The help assistant answers in markdown, and semgrep rule messages are
//! markdown (the finding description). Neither is ours, so nothing in it may
//! reach the page as markup of its own: raw HTML is shown as text, and links
//! keep only web and mail targets.
//! keep only Breakpilot's own pages, relative paths and mail targets.
//! Prüfwerk sends nobody to another site: a link anywhere else (an advisory
//! database, a vendor page) is shown as its text, and an image from another
//! site as its description.
use pulldown_cmark::{CowStr, Event, Options, Parser, Tag};
use pulldown_cmark::{CowStr, Event, Options, Parser, Tag, TagEnd};
/// Link targets kept as they are; anything else (`javascript:`, `data:`, …)
/// becomes an inert `#`.
const SAFE_SCHEMES: &[&str] = &["https://", "http://", "mailto:"];
/// The domain whose pages (and subdomains) a link may open.
const OWN_DOMAIN: &str = "breakpilot.com";
/// Render `markdown` to HTML that is safe to insert into the page.
///
@@ -19,8 +21,9 @@ const SAFE_SCHEMES: &[&str] = &["https://", "http://", "mailto:"];
///
/// # Returns
///
/// HTML with every raw HTML tag escaped and every link pointing at a web
/// address, a mail address, a relative path, or `#`.
/// HTML with every raw HTML tag escaped and every link pointing at a
/// Breakpilot page, a mail address or a relative path; other links are left
/// as their text.
///
/// # Examples
///
@@ -29,47 +32,50 @@ const SAFE_SCHEMES: &[&str] = &["https://", "http://", "mailto:"];
/// ```
pub fn render_markdown(markdown: &str) -> String {
let options = Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH;
let events = Parser::new_ext(markdown, options).map(|event| match event {
// Links and images do not nest, so one flag per kind says whether the
// open one was dropped and its end tag must go too.
let (mut link_dropped, mut image_dropped) = (false, false);
let events = Parser::new_ext(markdown, options).filter_map(move |event| match event {
// Shown as the text it is; `push_html` escapes text.
Event::Html(html) | Event::InlineHtml(html) => Event::Text(html),
Event::Start(Tag::Link {
link_type,
dest_url,
title,
id,
}) => Event::Start(Tag::Link {
link_type,
dest_url: safe_url(dest_url),
title,
id,
}),
Event::Start(Tag::Image {
link_type,
dest_url,
title,
id,
}) => Event::Start(Tag::Image {
link_type,
dest_url: safe_url(dest_url),
title,
id,
}),
other => other,
Event::Html(html) | Event::InlineHtml(html) => Some(Event::Text(html)),
Event::Start(Tag::Link { ref dest_url, .. }) => {
link_dropped = !allowed(dest_url);
(!link_dropped).then_some(event)
}
Event::End(TagEnd::Link) => (!std::mem::take(&mut link_dropped)).then_some(event),
// An image's inner text is its description: a dropped image leaves it.
Event::Start(Tag::Image { ref dest_url, .. }) => {
image_dropped = !allowed(dest_url);
(!image_dropped).then_some(event)
}
Event::End(TagEnd::Image) => (!std::mem::take(&mut image_dropped)).then_some(event),
other => Some(other),
});
let mut html = String::with_capacity(markdown.len() * 3 / 2);
pulldown_cmark::html::push_html(&mut html, events);
html
}
/// `url` when it is a web or mail address or a relative path, else `#`.
fn safe_url(url: CowStr<'_>) -> CowStr<'_> {
/// Whether a link to `url` may stay a link: a relative path, a mail
/// address, or a web page on Breakpilot's own domain.
fn allowed(url: &CowStr<'_>) -> bool {
let lower = url.trim().to_ascii_lowercase();
let relative = !lower.contains(':');
if relative || SAFE_SCHEMES.iter().any(|scheme| lower.starts_with(scheme)) {
url
} else {
CowStr::Borrowed("#")
if lower.starts_with("mailto:") {
return true;
}
let Some(rest) = lower
.strip_prefix("https://")
.or_else(|| lower.strip_prefix("http://"))
else {
// `//host/…` is another site, `javascript:` and the like are not pages.
return !lower.contains(':') && !lower.starts_with("//");
};
// The host ends at the path, query or fragment; a `user@` before it and
// a port after it are not part of it.
let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
let host = authority.rsplit('@').next().unwrap_or_default();
let host = host.split(':').next().unwrap_or_default();
host == OWN_DOMAIN || host.ends_with(&format!(".{OWN_DOMAIN}"))
}
#[cfg(test)]
@@ -99,11 +105,38 @@ mod tests {
}
#[test]
fn script_links_are_made_inert() {
let html = render_markdown("[x](javascript:alert(1)) [y](https://example.com) [z](/guide)");
fn only_breakpilot_pages_and_relative_paths_stay_links() {
let html = render_markdown(
"[x](javascript:alert(1)) [osv](https://osv.dev/vulnerability/CVE-1) \
[docs](https://docs.breakpilot.com/pruefwerk/) [z](/guide) [m](mailto:a@b.example)",
);
assert!(!html.contains("javascript:"));
assert!(html.contains("href=\"#\""));
assert!(html.contains("href=\"https://example.com\""));
assert!(!html.contains("osv.dev"));
assert!(html.contains("osv"), "the text stays: {html}");
assert!(html.contains("href=\"https://docs.breakpilot.com/pruefwerk/\""));
assert!(html.contains("href=\"/guide\""));
assert!(html.contains("href=\"mailto:a@b.example\""));
}
#[test]
fn a_look_alike_host_is_another_site() {
for url in [
"https://breakpilot.com.evil.example/x",
"https://evilbreakpilot.com/x",
"https://breakpilot.com@evil.example/x",
"//evil.example/x",
] {
let html = render_markdown(&format!("[a]({url})"));
assert!(!html.contains("href"), "{url}: {html}");
}
let html = render_markdown("[a](https://user@cloud.breakpilot.com:443/x)");
assert!(html.contains("href"), "{html}");
}
#[test]
fn an_image_from_another_site_leaves_its_description() {
let html = render_markdown("![diagram](https://evil.example/p.png)");
assert!(!html.contains("<img"));
assert!(html.contains("diagram"));
}
}
@@ -2,6 +2,8 @@ use dioxus::prelude::*;
use dioxus_free_icons::icons::bs_icons::*;
use dioxus_free_icons::Icon;
use crate::components::copy_button::CopyButton;
use crate::infrastructure::notifications::{
dismiss_notification, fetch_notification_count, fetch_notifications,
mark_all_notifications_read,
@@ -118,12 +120,10 @@ pub fn NotificationBell() -> Element {
span { class: "notification-sev {sev_class}",
"{notif.severity.to_uppercase()}"
}
// The id to copy, never a link off-site.
span { class: "notification-cve-id",
if let Some(ref url) = notif.url {
a { href: "{url}", target: "_blank", "{notif.cve_id}" }
} else {
"{notif.cve_id}"
}
"{notif.cve_id}"
CopyButton { value: notif.cve_id.clone(), small: true }
}
if let Some(score) = notif.cvss_score {
span { class: "notification-cvss", "CVSS {score:.1}" }
@@ -15,6 +15,7 @@ use compliance_core::cve_matrix::CveFilter;
use compliance_core::models::{CveAlert, SupplierVex, VexAssessment, VexJustification, VexStatus};
use compliance_core::vex_docs::status_of;
use crate::components::copy_button::CopyButton;
use crate::components::no_access::use_can_write;
use crate::components::severity_badge::SeverityBadge;
use crate::components::toast::{ToastType, Toasts};
@@ -182,6 +183,36 @@ pub(crate) fn is_supplier_product(alert: &CveAlert) -> bool {
/// agent stores it (`csaf_feed::SUPPLIER_PREFIX`).
pub(crate) const SUPPLIER_PROVIDER_PREFIX: &str = "supplier:";
/// A vendor advisory that names a CVE alert: its id to copy, the vendor's
/// remediation on hover, and a link to its page only where the provider's
/// terms require one (Siemens ProductCERT). Nothing else leads off-site.
#[component]
pub(crate) fn AdvisoryLine(advisory: compliance_core::models::AdvisoryRef) -> Element {
let lang = use_lang()();
let hint = advisory
.remediation
.clone()
.unwrap_or_else(|| advisory.title.clone());
rsx! {
div { class: "vex-advisory-line",
span { class: "vex-advisory", title: "{hint}", "{advisory.id}" }
CopyButton { value: advisory.id.clone(), small: true }
if let Some(url) = advisory.required_backlink() {
a {
class: "vex-advisory-source",
href: "{url}",
target: "_blank",
rel: "noopener noreferrer",
{tx::SOURCE.get(lang)}
}
}
if advisory.provider.starts_with(SUPPLIER_PROVIDER_PREFIX) {
span { class: "vex-advisory-note", {tx::SUPPLIER_ADVISORY.get(lang)} }
}
}
}
}
/// Who made an alert's statement: the person's name, "Prüfung" for a scan.
fn stated_by(alert: &CveAlert, lang: Lang) -> String {
match &alert.vex {
@@ -442,24 +473,13 @@ fn CveTable(
rsx! {
tr { key: "{alert_id}", class: if open { "is-open" } else { "" },
td {
code { "{alert.cve_id}" }
// The vendor advisories that name it (#515), linked as
// their terms ask; the remediation on hover.
span { class: "vex-cve-id",
code { "{alert.cve_id}" }
CopyButton { value: alert.cve_id.clone(), small: true }
}
// The vendor advisories that name it (#515).
for adv in alert.advisories.iter() {
div { class: "vex-advisory-line",
a {
class: "vex-advisory",
href: adv.url.clone().unwrap_or_default(),
target: "_blank",
rel: "noopener noreferrer",
title: adv.remediation.clone().unwrap_or_else(|| adv.title.clone()),
"{adv.id}"
}
if adv.provider.starts_with(SUPPLIER_PROVIDER_PREFIX) {
" "
span { class: "vex-advisory-note", {tx::SUPPLIER_ADVISORY.get(lang)} }
}
}
AdvisoryLine { advisory: adv.clone() }
}
}
td {
+15
View File
@@ -70,6 +70,21 @@ impl Text {
}
}
impl From<compliance_core::cra_requirements::Words> for Text {
fn from(words: compliance_core::cra_requirements::Words) -> Self {
Self {
de: words.de,
en: words.en,
}
}
}
/// The name a customer reads for CRA requirement `id` (`cra-ai-8` is
/// `Keine Standardpasswörter`); an id outside the 40 stays as it is.
pub fn requirement_label(id: &str, lang: Lang) -> &str {
compliance_core::cra_requirements::name(id).map_or(id, |words| Text::from(words).get(lang))
}
/// The agent's refusal code in a server function's error message: the
/// first word of `error` that is one of `codes`, as in
/// `error running server function: label_taken (409) (details: None)`.
+119 -26
View File
@@ -17,6 +17,14 @@ pub mod common {
de: "Wird geladen …",
en: "Loading...",
};
pub const COPY: Text = Text {
de: "Kopieren",
en: "Copy",
};
pub const COPIED: Text = Text {
de: "Kopiert",
en: "Copied",
};
pub const PREVIOUS: Text = Text {
de: "Zurück",
en: "Previous",
@@ -3294,10 +3302,6 @@ pub mod sbom {
de: "Keine",
en: "None",
};
pub const VIEW_ADVISORY: Text = Text {
de: "Hinweis ansehen →",
en: "View advisory →",
};
pub const KEV_BADGE: Text = Text {
de: "Aktiv ausgenutzt (KEV)",
en: "Actively exploited (KEV)",
@@ -3650,6 +3654,10 @@ pub mod vex {
de: "Laut Lieferant",
en: "Per the supplier",
};
pub const SOURCE: Text = Text {
de: "Quelle",
en: "Source",
};
pub const SUPPLIER_ADVISORY: Text = Text {
de: "Hinweis des Zulieferers",
en: "Supplier advisory",
@@ -4145,26 +4153,26 @@ pub mod compliance {
en: "Show CRA status",
};
pub const NOT_SATISFIED: Text = Text {
de: "Befunde zugeordnet",
en: "Findings mapped",
de: "Offene Befunde",
en: "Open findings",
};
pub const NO_VIOLATION: Text = Text {
de: "Geprüft, keine Befunde",
en: "Checked, no findings",
de: "Nichts gefunden",
en: "Nothing found",
};
pub const VIOLATED_COUNT: Text = Text {
de: "mit Befunden",
en: "with findings",
};
pub const NOT_ASSESSED: Text = Text {
de: "Nicht geprüft",
en: "Not checked",
de: "Noch nicht geprüft",
en: "Not checked yet",
};
/// A control checked on part of what it covers (a Yocto recipe
/// inventory instead of the image's SBOM).
pub const PARTIAL: Text = Text {
de: "Teilweise geprüft",
en: "Partly checked",
de: "Nur teilweise geprüft",
en: "Only partly checked",
};
pub const RECIPE_INVENTORY_ONLY: Text = Text {
de: "Nur das Yocto-Rezeptinventar, nicht die SBOM des Images: geprüft sind die Rezepte im Layer-Baum, nicht was das Image enthält. Vollständig erst mit der SBOM aus dem Build.",
@@ -4212,8 +4220,8 @@ pub mod compliance {
en: "CVE lookup",
};
pub const NOT_CODE_CHECKABLE: Text = Text {
de: "Nicht im Code prüfbar",
en: "Not checkable in code",
de: "Nachweis per Dokument",
en: "Proven by a document",
};
pub const SHOW_REQUIREMENTS: Text = Text {
de: "Anforderungen anzeigen",
@@ -5775,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(),
@@ -7188,22 +7212,22 @@ pub mod cra_tiles {
de: "CRA Annex I",
en: "CRA Annex I",
};
pub const BREADCRUMB: Text = Text {
de: "Anforderung",
en: "Requirement",
pub const SELECTED: Text = Text {
de: "Ausgewählte Anforderung",
en: "Selected requirement",
};
pub const HINT: Text = Text {
de: "Klick auf eine Kachel: die Anforderung mit den Befunden und Gründen dahinter.",
en: "Click a tile: the requirement with the findings and reasons behind it.",
};
pub const BACK: Text = Text {
de: "← Zurück zum Raster",
en: "← Back to the grid",
pub const PICK: Text = Text {
de: "Klicken Sie auf eine Anforderung: Hier steht dann, was ihre Farbe bedeutet und worauf sie beruht.",
en: "Click a requirement: this shows what its colour means and what it rests on.",
};
pub const UNKNOWN: Text = Text {
de: "Diese Anforderung gibt es für dieses Prüfobjekt nicht.",
en: "This target has no such requirement.",
};
pub const CLOSE: Text = Text {
de: "Schließen",
en: "Close",
};
pub const ALL_REQUIREMENTS: Text = Text {
de: "Alle Anforderungen als Liste",
en: "All requirements as a list",
@@ -7212,14 +7236,81 @@ pub mod cra_tiles {
de: "Der CRA-Stand konnte nicht geladen werden.",
en: "The CRA status could not be loaded.",
};
pub const OTHER_AREA: Text = Text {
de: "Weitere Anforderungen",
en: "Other requirements",
};
pub const MEANINGS: Text = Text {
de: "Was die Farben hier bedeuten",
en: "What the colours mean here",
};
pub const NOW: Text = Text {
de: ": so ist es jetzt",
en: ": this is how it is now",
};
pub const RED: Text = Text {
de: "Rot",
en: "Red",
};
pub const ORANGE: Text = Text {
de: "Orange",
en: "Orange",
};
pub const GREEN: Text = Text {
de: "Grün",
en: "Green",
};
pub const PROOF_TITLE: Text = Text {
de: "Nachweis per Dokument",
en: "Proven by a document",
};
pub const AGAINST_GENERIC: Text = Text {
de: "Sie sprechen gegen diese Anforderung.",
en: "They count against this requirement.",
};
pub const CLEAR_GENERIC: Text = Text {
de: "Der Scan fand nichts, was dagegen spricht.",
en: "The scan found nothing against it.",
};
pub const OPEN_GENERIC: Text = Text {
de: "Noch nicht geprüft: Es ist noch kein Scan gelaufen, oder keine Regel deckt dieses Prüfobjekt ab.",
en: "Not checked yet: no scan has run, or no rule covers this target.",
};
pub const PROCESS_GENERIC: Text = Text {
de: "Diese Anforderung betrifft Ihre Abläufe und Ihren Entwurf, nicht einzelne Codezeilen.",
en: "This requirement is about your processes and design, not single lines of code.",
};
/// The grid's heading: `CRA Annex I: 40 Anforderungen`.
/// The map's heading: `CRA Annex I: 40 Anforderungen`.
pub fn title(count: usize, lang: Lang) -> String {
match lang {
Lang::De => format!("CRA Annex I: {count} Anforderungen"),
Lang::En => format!("CRA Annex I: {count} requirements"),
}
}
/// How many open findings count against a requirement, as a sentence.
pub fn against_count(count: usize, lang: Lang) -> String {
match (lang, count) {
(Lang::De, 1) => "Ein offener Befund spricht dagegen.".to_string(),
(Lang::De, n) => format!("{n} offene Befunde sprechen dagegen."),
(Lang::En, 1) => "One open finding counts against it.".to_string(),
(Lang::En, n) => format!("{n} open findings count against it."),
}
}
/// The proof a requirement no scan decides asks for: `doc` is the
/// document (`ein Rechtekonzept`).
pub fn proof(doc: &str, lang: Lang) -> String {
match lang {
Lang::De => format!(
"Ein Code-Scan kann diese Anforderung nicht entscheiden. Sie weisen sie mit einem Dokument nach: {doc}."
),
Lang::En => format!(
"A code scan cannot decide this requirement. You prove it with a document: {doc}."
),
}
}
}
/// The "Verlauf" of a target's views (#957): what each scan changed.
@@ -8764,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 {
@@ -8788,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()
+27 -8
View File
@@ -18,8 +18,8 @@ use crate::infrastructure::evidence::{fetch_compliance, CraCounts};
/// them: violated first, requirements evidenced outside the code last.
pub(crate) const STATES: [(&str, Text, &str); 5] = [
("not_satisfied", tx::NOT_SATISFIED, "badge badge-critical"),
("not_assessed", tx::NOT_ASSESSED, "badge badge-medium"),
("partial", tx::PARTIAL, "badge badge-info"),
("not_assessed", tx::NOT_ASSESSED, "badge badge-open"),
("partial", tx::PARTIAL, "badge badge-medium"),
(
"no_violation_found",
tx::NO_VIOLATION,
@@ -163,11 +163,29 @@ pub fn CompliancePage(id: String) -> Element {
}
}
/// One requirement: its id and title, the catalog's rating, and what the
/// state rests on (the findings against it, or why it was not assessed,
/// unless `show_reason` is off because the group states it once).
/// The name a customer reads for `control` (an entry of the compliance
/// API's `controls`): the requirement's name, else the catalog's title for
/// an id outside the 40, else the id.
pub(crate) fn requirement_name(control: &serde_json::Value, lang: Lang) -> String {
let id = control["control"].as_str().unwrap_or_default();
match compliance_core::cra_requirements::name(id) {
Some(words) => Text::from(words).get(lang).to_string(),
None => control["title"].as_str().unwrap_or(id).to_string(),
}
}
/// One requirement: its name, the catalog's rating, and what the state rests
/// on (the findings against it, or why it was not assessed, unless
/// `show_reason` is off because the group states it once). `headless` leaves
/// the name line out where the requirement is already named above.
#[component]
pub(crate) fn ControlRow(control: serde_json::Value, lang: Lang, show_reason: bool) -> Element {
pub(crate) fn ControlRow(
control: serde_json::Value,
lang: Lang,
show_reason: bool,
#[props(default)] headless: bool,
) -> Element {
let name = requirement_name(&control, lang);
let findings = control["findings"].as_array().cloned().unwrap_or_default();
// The control map's notes are engineering prose in English; in German
// the group's hint says the same.
@@ -186,8 +204,9 @@ pub(crate) fn ControlRow(control: serde_json::Value, lang: Lang, show_reason: bo
rsx! {
li { class: "cra-control",
div { class: "cra-control-head",
code { class: "cra-control-id", "{control[\"control\"].as_str().unwrap_or_default()}" }
span { class: "cra-control-title", "{control[\"title\"].as_str().unwrap_or_default()}" }
if !headless {
span { class: "cra-control-title", "{name}" }
}
if let Some(label) = severity_label {
span { class: "badge badge-{severity}", "{label}" }
}
@@ -4,11 +4,12 @@ use dioxus_free_icons::Icon;
use crate::app::Route;
use crate::components::code_snippet::CodeSnippet;
use crate::components::cra_tiles::{cra_tone, StateMark};
use crate::components::markdown::render_markdown;
use crate::components::page_header::PageHeader;
use crate::components::severity_badge::SeverityBadge;
use crate::i18n::texts::{common, finding_breakdown, findings as tx, graph as graph_tx};
use crate::i18n::{format_count, format_time, use_lang, Lang};
use crate::i18n::{format_count, format_time, requirement_label, use_lang, Lang};
use crate::infrastructure::evidence::{fetch_catalog_controls, CatalogControl};
use crate::infrastructure::findings::{location, mask_secrets, wire_name};
use crate::infrastructure::graph::fetch_impact;
@@ -127,11 +128,12 @@ pub fn FindingDetailPage(id: String) -> Element {
.as_ref()
.and_then(|d| d["target_name"].as_str())
.map(String::from);
let control_title = |id: &str| -> Option<String> {
// A requirement's state on the target, as the CRA map shows it.
let control_state = |id: &str| -> Option<String> {
status_data.as_ref()?["controls"]
.as_array()?
.iter()
.find(|c| c["control"].as_str() == Some(id))?["title"]
.find(|c| c["control"].as_str() == Some(id))?["state"]
.as_str()
.map(String::from)
};
@@ -143,8 +145,8 @@ pub fn FindingDetailPage(id: String) -> Element {
let cra_topics: Vec<(String, Option<String>)> = cra_refs
.into_iter()
.map(|c| {
let title = control_title(&c);
(c, title)
let state = control_state(&c);
(c, state)
})
.collect();
// Offer Breakpilot Git only once the agent said the target opens
@@ -309,11 +311,22 @@ pub fn FindingDetailPage(id: String) -> Element {
if !f.control_refs.is_empty() {
span { style: "opacity: 0.7;", {tx::CRA_REFS.get(lang)} }
ul { class: "finding-refs",
for (c, title) in cra_topics {
for (c, state) in cra_topics {
li {
span { class: "badge badge-info", "{c}" }
if let Some(title) = title {
span { " {title}" }
Link {
class: "ct-chip {cra_tone(state.as_deref())}",
to: Route::TargetViewsPage {
id: f.repo_id.clone(),
view: crate::pages::target_views::RepoView::Cra.slug().to_string(),
cve_severity: None,
cve_vex: None,
control: Some(c.clone()),
scan: None,
},
if let Some(state) = state.clone() {
StateMark { state }
}
span { class: "ct-chip-name", {requirement_label(&c, lang)} }
}
}
}
@@ -675,7 +688,7 @@ fn tracker_note(
/// # Arguments
///
/// * `finding` - the finding shown on the page
/// * `cra_topics` - its CRA control ids, each with its title when known
/// * `cra_topics` - its CRA requirement ids, each with its state when known
/// * `link` - the finding's page in Prüfwerk
/// * `lang` - the UI language, for the labels
///
@@ -720,11 +733,8 @@ fn ticket_markdown(
}
if !cra_topics.is_empty() {
md.push_str(&format!("\n### {}\n\n", tx::CRA_TOPICS.get(lang)));
for (id, title) in cra_topics {
match title {
Some(title) => md.push_str(&format!("- `{id}` {title}\n")),
None => md.push_str(&format!("- `{id}`\n")),
}
for (id, _) in cra_topics {
md.push_str(&format!("- {}\n", requirement_label(id, lang)));
}
}
md.push_str(&format!(
@@ -855,10 +865,7 @@ mod tests {
#[test]
fn the_ticket_text_holds_the_finding_and_a_link_back() {
let topics = vec![
(
"cra-ai-2c".to_string(),
Some("Schutz vor unbefugtem Zugriff".to_string()),
),
("cra-ai-8".to_string(), Some("not_satisfied".to_string())),
("cra-ai-2f".to_string(), None),
];
let md = ticket_markdown(
@@ -876,8 +883,8 @@ mod tests {
\n### Beschreibung\n\nDie Abfrage setzt Benutzereingaben direkt ein.\n\
\n### Einschätzung\n\nErreichbar über das Login-Formular.\n\
\n### CRA-Themen\n\n\
- `cra-ai-2c` Schutz vor unbefugtem Zugriff\n\
- `cra-ai-2f`\n\
- Keine Standardpasswörter\n\
- cra-ai-2f\n\
\n[Im Prüfwerk öffnen](https://pruefwerk.example/findings/abc)\n"
);
}
+7 -5
View File
@@ -16,7 +16,7 @@ use crate::components::toast::{ToastType, Toasts};
use crate::i18n::texts::{
common, finding_breakdown as breakdown_tx, finding_groups as gtx, findings as tx,
};
use crate::i18n::use_lang;
use crate::i18n::{requirement_label, use_lang};
use crate::infrastructure::findings::{has_control_refs, location, wire_name};
use compliance_core::finding_breakdown::OPEN_STATUS_FILTER;
@@ -436,9 +436,9 @@ pub fn FindingsPage(
if show_controls {
td {
{
// CRA Annex I refs by name; master controls
// (`mc-…`) only as a count, their detail is on
// the finding's page.
// CRA Annex I requirements by name; master
// controls (`mc-…`) only as a count, their
// detail is on the finding's page.
let (cra, other): (Vec<&String>, Vec<&String>) = finding
.control_refs
.iter()
@@ -446,7 +446,9 @@ pub fn FindingsPage(
rsx! {
div { class: "finding-controls",
for c in cra {
span { class: "badge badge-info", title: tx::CONTROLS_HINT.get(lang), "{c}" }
span { class: "finding-control", title: tx::CONTROLS_HINT.get(lang),
{requirement_label(c, lang)}
}
}
if !other.is_empty() {
span { class: "finding-controls-more",
+7 -15
View File
@@ -12,10 +12,11 @@ use compliance_core::scan_changes::ComponentRowKind;
use compliance_core::vex_docs::status_of;
use crate::app::Route;
use crate::components::copy_button::CopyButton;
use crate::components::severity_badge::SeverityBadge;
use crate::components::toast::{ToastType, Toasts};
use crate::components::vex_panel::{
is_supplier_product, status_class, status_text, supplier_gist, SUPPLIER_PROVIDER_PREFIX,
is_supplier_product, status_class, status_text, supplier_gist, AdvisoryLine,
};
use crate::i18n::texts::{common, cve_matrix, kinds, machine as tx, repo_views as rv};
use crate::i18n::{format_ago, format_count, format_time, use_lang, Lang};
@@ -477,21 +478,12 @@ fn MachineCveGroup(
rsx! {
tr { key: "{alert.repo_id}-{alert.cve_id}",
td {
code { "{alert.cve_id}" }
span { class: "vex-cve-id",
code { "{alert.cve_id}" }
CopyButton { value: alert.cve_id.clone(), small: true }
}
for adv in alert.advisories.iter() {
div { class: "vex-advisory-line",
a {
class: "vex-advisory",
href: adv.url.clone().unwrap_or_default(),
target: "_blank",
rel: "noopener noreferrer",
"{adv.id}"
}
if adv.provider.starts_with(SUPPLIER_PROVIDER_PREFIX) {
" "
span { class: "vex-advisory-note", {crate::i18n::texts::vex::SUPPLIER_ADVISORY.get(lang)} }
}
}
AdvisoryLine { advisory: adv.clone() }
}
}
td {
+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)";
+3 -8
View File
@@ -4,6 +4,7 @@ use dioxus::prelude::*;
use crate::app::Route;
use crate::components::component_overview::ComponentOverview;
use crate::components::copy_button::CopyButton;
use crate::components::license_editor::{category_class, confirmed_title, LicenseEditor};
use crate::components::license_review::{
action_class, reasons_text, review_title, LicenseCheckPanel,
@@ -545,7 +546,9 @@ pub fn SbomPage(target: String, #[props(default)] ecosystem: String) -> Element
for vuln in &entry.known_vulnerabilities {
div { class: "sbom-vuln-card",
div { class: "sbom-vuln-card-header",
// The id to copy, never a link off-site.
span { class: "sbom-vuln-id", "{vuln.id}" }
CopyButton { value: vuln.id.clone(), small: true }
span { class: "sbom-vuln-source", "{vuln.source}" }
if let Some(sev) = &vuln.severity {
span {
@@ -573,14 +576,6 @@ pub fn SbomPage(target: String, #[props(default)] ecosystem: String) -> Element
"{tx::SSVC_EXPLOITATION.get(lang)}: {ssvc}"
}
}
if let Some(url) = &vuln.url {
a {
href: "{url}",
target: "_blank",
class: "sbom-vuln-link",
{tx::VIEW_ADVISORY.get(lang)}
}
}
}
}
if entry.known_vulnerabilities.iter().any(|v| v.exploitation.as_ref().is_some_and(|e| e.epss.is_some())) {
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-dast"
version = "0.4.17"
version = "0.4.18"
edition = "2021"
[lints]
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-graph"
version = "0.4.17"
version = "0.4.18"
edition = "2021"
[lints]
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-mcp"
version = "0.4.17"
version = "0.4.18"
edition = "2021"
[dependencies]
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-smoke"
version = "0.4.17"
version = "0.4.18"
edition = "2021"
description = "Tiny Axum service exercising compliance-core M7.1 tenant gating. Run smoke.sh against it before merging anything that touches the auth/tenant path."
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "control-map"
version = "0.4.17"
version = "0.4.18"
edition = "2021"
[lints]
+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`
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "werkbank-exec"
version = "0.4.17"
version = "0.4.18"
edition = "2021"
description = "Shared dynamic-execution logic: soft-PLC provisioning + industrial-protocol probing, used by the compliance agent and the Werkbank runner."