Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1f3beb5786 | ||
|
|
a9ea12651f | ||
|
|
12a02c3725 | ||
|
|
32c12b72e0 | ||
|
|
1ff5fcc1a4 | ||
|
|
b5cba8fb95 | ||
|
|
8fd78dd390 | ||
|
|
50b1a8b44b | ||
|
|
ecfee6db6e | ||
|
|
30079c6504 | ||
|
|
dd46af6f24 | ||
|
|
1df32d5e1a | ||
|
|
2d3311bd09 |
No files matched your search
Generated
+9
-9
@@ -601,7 +601,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "compliance-agent"
|
name = "compliance-agent"
|
||||||
version = "0.4.18"
|
version = "0.4.20"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"axum",
|
"axum",
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
@@ -657,7 +657,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "compliance-core"
|
name = "compliance-core"
|
||||||
version = "0.4.18"
|
version = "0.4.20"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aes-gcm",
|
"aes-gcm",
|
||||||
"axum",
|
"axum",
|
||||||
@@ -689,7 +689,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "compliance-dashboard"
|
name = "compliance-dashboard"
|
||||||
version = "0.4.18"
|
version = "0.4.20"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-trait",
|
"async-trait",
|
||||||
"axum",
|
"axum",
|
||||||
@@ -727,7 +727,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "compliance-dast"
|
name = "compliance-dast"
|
||||||
version = "0.4.18"
|
version = "0.4.20"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"axum",
|
"axum",
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
@@ -749,7 +749,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "compliance-graph"
|
name = "compliance-graph"
|
||||||
version = "0.4.18"
|
version = "0.4.20"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bson",
|
"bson",
|
||||||
"chrono",
|
"chrono",
|
||||||
@@ -774,7 +774,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "compliance-mcp"
|
name = "compliance-mcp"
|
||||||
version = "0.4.18"
|
version = "0.4.20"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"axum",
|
"axum",
|
||||||
"bson",
|
"bson",
|
||||||
@@ -797,7 +797,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "compliance-smoke"
|
name = "compliance-smoke"
|
||||||
version = "0.4.18"
|
version = "0.4.20"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"axum",
|
"axum",
|
||||||
"compliance-core",
|
"compliance-core",
|
||||||
@@ -932,7 +932,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "control-map"
|
name = "control-map"
|
||||||
version = "0.4.18"
|
version = "0.4.20"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
@@ -7127,7 +7127,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "werkbank-exec"
|
name = "werkbank-exec"
|
||||||
version = "0.4.18"
|
version = "0.4.20"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"compliance-core",
|
"compliance-core",
|
||||||
"compliance-dast",
|
"compliance-dast",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "compliance-agent"
|
name = "compliance-agent"
|
||||||
version = "0.4.18"
|
version = "0.4.20"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
|
|||||||
@@ -173,8 +173,9 @@ impl ComplianceAgent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Store which of the tenant's targets are the plan's included ones and
|
/// 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
|
/// which are extra (t72), from the plan's `included_targets`; a plan that
|
||||||
/// registry every target is included. Best-effort: when the plan cannot
|
/// 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.
|
/// be read or the targets not updated, the stored split stays.
|
||||||
///
|
///
|
||||||
/// # Returns
|
/// # Returns
|
||||||
@@ -187,7 +188,7 @@ impl ComplianceAgent {
|
|||||||
) -> Vec<BillingChange> {
|
) -> Vec<BillingChange> {
|
||||||
match self.plan(tenant_id).await {
|
match self.plan(tenant_id).await {
|
||||||
Some(plan) => {
|
Some(plan) => {
|
||||||
self.assign_billing(tenant_id, db, plan.included_targets)
|
self.assign_billing(tenant_id, db, plan.billed_included())
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
None => Vec::new(),
|
None => Vec::new(),
|
||||||
@@ -205,6 +206,7 @@ impl ComplianceAgent {
|
|||||||
match registry.check_entitlement(tenant_id, None, None).await {
|
match registry.check_entitlement(tenant_id, None, None).await {
|
||||||
Ok(check) => Some(crate::metering::Plan {
|
Ok(check) => Some(crate::metering::Plan {
|
||||||
included_targets: check.included_targets(),
|
included_targets: check.included_targets(),
|
||||||
|
extra_targets: check.extra_targets(),
|
||||||
limits: check.plan_limits(),
|
limits: check.plan_limits(),
|
||||||
}),
|
}),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@@ -216,7 +218,7 @@ impl ComplianceAgent {
|
|||||||
|
|
||||||
/// Store the billing of the tenant's targets for a plan that includes
|
/// Store the billing of the tenant's targets for a plan that includes
|
||||||
/// `included` targets; best-effort.
|
/// `included` targets; best-effort.
|
||||||
async fn assign_billing(
|
pub(crate) async fn assign_billing(
|
||||||
&self,
|
&self,
|
||||||
tenant_id: &str,
|
tenant_id: &str,
|
||||||
db: &crate::database::Database,
|
db: &crate::database::Database,
|
||||||
@@ -359,7 +361,7 @@ impl ComplianceAgent {
|
|||||||
// counts, and the plan's limits whether a counted one may run (t72).
|
// counts, and the plan's limits whether a counted one may run (t72).
|
||||||
let plan = self.plan(tenant_id).await;
|
let plan = self.plan(tenant_id).await;
|
||||||
if let Some(plan) = &plan {
|
if let Some(plan) = &plan {
|
||||||
self.assign_billing(tenant_id, &db, plan.included_targets)
|
self.assign_billing(tenant_id, &db, plan.billed_included())
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
let orchestrator =
|
let orchestrator =
|
||||||
|
|||||||
@@ -0,0 +1,268 @@
|
|||||||
|
//! The workspace's branding for the dashboard (tenant-registry#155): its CI
|
||||||
|
//! colour, which frames every page, its logo, and the one-time notice for its
|
||||||
|
//! admins that both were taken from its website.
|
||||||
|
//!
|
||||||
|
//! The registry derives and stores the branding; the agent only passes on
|
||||||
|
//! what the entitlement check (already cached per tenant) says, serves the
|
||||||
|
//! logo from its own origin, and forwards an admin's "Passt". Without a
|
||||||
|
//! registry, or when it cannot be asked, there is simply no branding.
|
||||||
|
|
||||||
|
use axum::extract::Extension;
|
||||||
|
use axum::http::{header, StatusCode};
|
||||||
|
use axum::response::{IntoResponse, Response};
|
||||||
|
use axum::Json;
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
use compliance_core::tenant::TenantContext;
|
||||||
|
use compliance_core::tenant_ctx::TenantCtx;
|
||||||
|
|
||||||
|
use super::dto::AgentExt;
|
||||||
|
use crate::registry::{AckRefusal, Branding};
|
||||||
|
|
||||||
|
/// What the dashboard draws.
|
||||||
|
#[derive(Debug, Default, PartialEq, Eq, Serialize, utoipa::ToSchema)]
|
||||||
|
pub struct BrandingView {
|
||||||
|
/// The frame colour, `#rrggbb`; none means no frame.
|
||||||
|
pub color: Option<String>,
|
||||||
|
/// Whether `GET /api/v1/branding/logo` has a logo.
|
||||||
|
pub logo: bool,
|
||||||
|
/// The workspace's name, beside the logo.
|
||||||
|
pub name: Option<String>,
|
||||||
|
/// Whether to show the caller the notice; only ever for its admins.
|
||||||
|
pub notice: bool,
|
||||||
|
/// The domain the branding was taken from, for the notice.
|
||||||
|
pub domain: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BrandingView {
|
||||||
|
/// The view of `branding` for `caller`: the notice only for a person who
|
||||||
|
/// is an admin of the workspace, never for support or an API key.
|
||||||
|
fn of(branding: &Branding, caller: &TenantContext) -> Self {
|
||||||
|
let admin = caller.is_admin() && caller.staff.is_none() && caller.api_key.is_none();
|
||||||
|
let notice = admin && branding.notice && branding.domain.is_some();
|
||||||
|
Self {
|
||||||
|
color: branding.frame_color(),
|
||||||
|
logo: branding.logo_etag().is_some(),
|
||||||
|
name: branding.name.clone().filter(|n| !n.trim().is_empty()),
|
||||||
|
notice,
|
||||||
|
domain: notice.then(|| branding.domain.clone()).flatten(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The workspace's branding as the registry answered, or none.
|
||||||
|
async fn branding(agent: &crate::agent::ComplianceAgent, tenant_id: &str) -> Option<Branding> {
|
||||||
|
let registry = agent.registry.as_ref()?;
|
||||||
|
match registry.check_entitlement(tenant_id, None, None).await {
|
||||||
|
Ok(check) => check.branding,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::debug!(tenant_id, "branding not read: {e}");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The workspace's branding.
|
||||||
|
///
|
||||||
|
/// Its CI colour, whether it has a logo, and whether the caller (an admin)
|
||||||
|
/// still has to acknowledge a branding taken from its website. Every field is
|
||||||
|
/// empty when the workspace has none or the registry cannot be asked.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/branding",
|
||||||
|
tag = "Workspace",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The branding", body = BrandingView),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
|
pub async fn get_branding(
|
||||||
|
Extension(agent): AgentExt,
|
||||||
|
tenant: TenantCtx,
|
||||||
|
) -> Json<serde_json::Value> {
|
||||||
|
let view = branding(&agent, &tenant.0.tenant_id)
|
||||||
|
.await
|
||||||
|
.map(|b| BrandingView::of(&b, &tenant.0))
|
||||||
|
.unwrap_or_default();
|
||||||
|
Json(serde_json::json!({ "data": view }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The workspace's logo.
|
||||||
|
///
|
||||||
|
/// A PNG of at most 256 px, from the registry, never an SVG.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// `404` when the workspace has no logo; `502` when the registry cannot
|
||||||
|
/// deliver it.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/branding/logo",
|
||||||
|
tag = "Workspace",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The logo", content_type = "image/png"),
|
||||||
|
(status = 404, description = "No logo"),
|
||||||
|
(status = 502, description = "The registry cannot deliver it"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
|
pub async fn get_logo(
|
||||||
|
Extension(agent): AgentExt,
|
||||||
|
tenant: TenantCtx,
|
||||||
|
) -> Result<Response, StatusCode> {
|
||||||
|
let tenant_id = &tenant.0.tenant_id;
|
||||||
|
let (Some(registry), Some(b)) = (agent.registry.as_ref(), branding(&agent, tenant_id).await)
|
||||||
|
else {
|
||||||
|
return Err(StatusCode::NOT_FOUND);
|
||||||
|
};
|
||||||
|
let etag = b.logo_etag().ok_or(StatusCode::NOT_FOUND)?;
|
||||||
|
match registry.branding_logo(tenant_id, etag).await {
|
||||||
|
Ok(Some(png)) => Ok((
|
||||||
|
[
|
||||||
|
(header::CONTENT_TYPE, "image/png".to_string()),
|
||||||
|
(header::ETAG, format!("\"{etag}\"")),
|
||||||
|
(header::CACHE_CONTROL, "private, max-age=300".to_string()),
|
||||||
|
(header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()),
|
||||||
|
],
|
||||||
|
png,
|
||||||
|
)
|
||||||
|
.into_response()),
|
||||||
|
Ok(None) => Err(StatusCode::NOT_FOUND),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(tenant_id, "logo not fetched: {e}");
|
||||||
|
Err(StatusCode::BAD_GATEWAY)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Acknowledge the workspace's branding ("Passt").
|
||||||
|
///
|
||||||
|
/// An admin confirms the logo and colour taken from the workspace's website;
|
||||||
|
/// the notice then no longer shows.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// `403` when the caller is no admin of the workspace; `503` without a
|
||||||
|
/// registry; `502` when the registry cannot record it.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/branding/ack",
|
||||||
|
tag = "Workspace",
|
||||||
|
responses(
|
||||||
|
(status = 204, description = "Recorded"),
|
||||||
|
(status = 403, description = "Only the workspace's admins acknowledge it"),
|
||||||
|
(status = 502, description = "The registry cannot record it"),
|
||||||
|
(status = 503, description = "No registry"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
|
pub async fn ack(Extension(agent): AgentExt, tenant: TenantCtx) -> StatusCode {
|
||||||
|
let caller = &tenant.0;
|
||||||
|
if !caller.is_admin() || caller.staff.is_some() || caller.api_key.is_some() {
|
||||||
|
return StatusCode::FORBIDDEN;
|
||||||
|
}
|
||||||
|
let Some(registry) = agent.registry.as_ref() else {
|
||||||
|
return StatusCode::SERVICE_UNAVAILABLE;
|
||||||
|
};
|
||||||
|
match registry
|
||||||
|
.ack_branding(&caller.tenant_id, &caller.user_id)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(()) => StatusCode::NO_CONTENT,
|
||||||
|
Err(AckRefusal::NotAdmin) => {
|
||||||
|
tracing::info!(
|
||||||
|
tenant_id = %caller.tenant_id,
|
||||||
|
"branding ack refused: the registry does not count the caller as an admin"
|
||||||
|
);
|
||||||
|
StatusCode::FORBIDDEN
|
||||||
|
}
|
||||||
|
Err(AckRefusal::Failed(e)) => {
|
||||||
|
tracing::warn!(tenant_id = %caller.tenant_id, "branding ack failed: {e}");
|
||||||
|
StatusCode::BAD_GATEWAY
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use compliance_core::{OrgRole, TenantStatus};
|
||||||
|
|
||||||
|
fn caller(roles: Vec<OrgRole>) -> TenantContext {
|
||||||
|
TenantContext {
|
||||||
|
tenant_id: "t-1".into(),
|
||||||
|
tenant_slug: "acme".into(),
|
||||||
|
org_roles: roles,
|
||||||
|
products: vec!["compliance-scanner".into()],
|
||||||
|
plan: "entry".into(),
|
||||||
|
status: TenantStatus::Active,
|
||||||
|
user_id: "u-1".into(),
|
||||||
|
user_name: None,
|
||||||
|
staff: None,
|
||||||
|
api_key: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn derived() -> Branding {
|
||||||
|
Branding {
|
||||||
|
color: Some("#14B8A6".into()),
|
||||||
|
logo_etag: Some("a".repeat(64)),
|
||||||
|
notice: true,
|
||||||
|
domain: Some("example.de".into()),
|
||||||
|
name: Some("Example GmbH".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_an_admin_sees_the_notice() {
|
||||||
|
// Arrange
|
||||||
|
let b = derived();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
let admin = BrandingView::of(&b, &caller(vec![OrgRole::ItAdmin]));
|
||||||
|
let member = BrandingView::of(&b, &caller(vec![OrgRole::User]));
|
||||||
|
|
||||||
|
// Assert: both see the frame and logo, only the admin the notice.
|
||||||
|
assert_eq!(admin.color.as_deref(), Some("#14b8a6"));
|
||||||
|
assert!(admin.logo && member.logo);
|
||||||
|
assert!(admin.notice);
|
||||||
|
assert_eq!(admin.domain.as_deref(), Some("example.de"));
|
||||||
|
assert!(!member.notice);
|
||||||
|
assert_eq!(member.domain, None);
|
||||||
|
assert_eq!(member.color, admin.color);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn support_and_api_keys_never_see_the_notice() {
|
||||||
|
let b = derived();
|
||||||
|
let mut staff = caller(vec![OrgRole::Owner]);
|
||||||
|
staff.staff = Some(compliance_core::tenant::StaffAccess {
|
||||||
|
user_id: "s-1".into(),
|
||||||
|
user_name: None,
|
||||||
|
});
|
||||||
|
assert!(!BrandingView::of(&b, &staff).notice);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_malformed_colour_or_etag_is_no_frame_and_no_logo() {
|
||||||
|
for color in ["red", "#12345", "#1234567", "#gggggg", "url(x)", ""] {
|
||||||
|
let b = Branding {
|
||||||
|
color: Some(color.into()),
|
||||||
|
logo_etag: Some("not-a-hash".into()),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let view = BrandingView::of(&b, &caller(vec![OrgRole::Owner]));
|
||||||
|
assert_eq!(view.color, None, "{color}");
|
||||||
|
assert!(!view.logo);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_notice_without_a_domain_is_not_shown() {
|
||||||
|
let b = Branding {
|
||||||
|
domain: None,
|
||||||
|
..derived()
|
||||||
|
};
|
||||||
|
assert!(!BrandingView::of(&b, &caller(vec![OrgRole::Owner])).notice);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
//! A target's Siemens controllers against Siemens' advisories (SPS item 4a):
|
||||||
|
//! `GET /api/v1/targets/{id}/devices` for its page, and
|
||||||
|
//! `GET /api/v1/devices/lookup` to recognise an order number while it is
|
||||||
|
//! typed.
|
||||||
|
//!
|
||||||
|
//! Both read the advisory index as it is now, so a device shows its state
|
||||||
|
//! as soon as it is entered; its CVE alerts follow at the target's next scan.
|
||||||
|
|
||||||
|
use axum::extract::{Extension, Path, Query};
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::Json;
|
||||||
|
use mongodb::bson::doc;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use super::dto::{tenant_db, AgentExt, ApiResponse, ApiResult};
|
||||||
|
use crate::pipeline::csaf_match::{AdvisoryIndex, Wanted};
|
||||||
|
use compliance_core::csaf_ingest::Advisory;
|
||||||
|
use compliance_core::device_check::{DeviceCheck, DeviceLookup};
|
||||||
|
use compliance_core::models::plc_device::normalised_order_number;
|
||||||
|
use compliance_core::models::PlcDevice;
|
||||||
|
use compliance_core::tenant_ctx::TenantCtx;
|
||||||
|
|
||||||
|
/// The provider whose advisories name devices by order number.
|
||||||
|
const PROVIDER: &str = "siemens";
|
||||||
|
|
||||||
|
/// Siemens' advisories naming any of `order_numbers` (normalised).
|
||||||
|
async fn advisories_naming(
|
||||||
|
index: &dyn AdvisoryIndex,
|
||||||
|
order_numbers: Vec<String>,
|
||||||
|
) -> Result<Vec<Advisory>, StatusCode> {
|
||||||
|
let wanted = Wanted {
|
||||||
|
order_numbers,
|
||||||
|
..Wanted::default()
|
||||||
|
};
|
||||||
|
let rows = index.relevant(&wanted).await.map_err(|e| {
|
||||||
|
tracing::warn!("Failed to read the advisory index: {e}");
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
})?;
|
||||||
|
Ok(rows
|
||||||
|
.into_iter()
|
||||||
|
.filter(|(provider, _)| provider == PROVIDER)
|
||||||
|
.map(|(_, advisory)| advisory)
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Each of `devices` against `advisories`.
|
||||||
|
fn checks(devices: Vec<PlcDevice>, advisories: &[Advisory]) -> Vec<DeviceCheck> {
|
||||||
|
devices
|
||||||
|
.into_iter()
|
||||||
|
.map(|device| DeviceCheck::new(device, advisories))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The Siemens controllers a target runs on.
|
||||||
|
///
|
||||||
|
/// Each with the Siemens advisories naming it.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/targets/{id}/devices",
|
||||||
|
tag = "Targets",
|
||||||
|
params(("id" = String, Path, description = "The target's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The target's devices in the order entered, each with the Siemens advisories naming it and whether one affects its firmware"),
|
||||||
|
(status = 400, description = "Not a target id"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
(status = 404, description = "No such target"),
|
||||||
|
(status = 500, description = "The target or the advisory index could not be read"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
|
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||||
|
pub async fn list_devices(
|
||||||
|
Extension(agent): AgentExt,
|
||||||
|
tenant: TenantCtx,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
) -> ApiResult<Vec<DeviceCheck>> {
|
||||||
|
let oid = mongodb::bson::oid::ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||||
|
let db = tenant_db(&agent, &tenant).await?;
|
||||||
|
let target = db
|
||||||
|
.onboarded_targets()
|
||||||
|
.find_one(doc! { "_id": oid })
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||||
|
.ok_or(StatusCode::NOT_FOUND)?;
|
||||||
|
// Entered and exported alike (#1090): a TIA export's devices are listed
|
||||||
|
// under their names in the project.
|
||||||
|
let target_devices: Vec<_> = target
|
||||||
|
.target_devices()
|
||||||
|
.into_iter()
|
||||||
|
.map(|d| d.device)
|
||||||
|
.collect();
|
||||||
|
let mut order_numbers: Vec<String> = target_devices
|
||||||
|
.iter()
|
||||||
|
.map(|d| d.order_number.clone())
|
||||||
|
.collect();
|
||||||
|
order_numbers.sort();
|
||||||
|
order_numbers.dedup();
|
||||||
|
let advisories = if order_numbers.is_empty() {
|
||||||
|
Vec::new()
|
||||||
|
} else {
|
||||||
|
advisories_naming(agent.advisory_index.as_ref(), order_numbers).await?
|
||||||
|
};
|
||||||
|
let devices = checks(target_devices, &advisories);
|
||||||
|
Ok(Json(ApiResponse {
|
||||||
|
total: Some(devices.len() as u64),
|
||||||
|
data: devices,
|
||||||
|
page: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `?order_number=` of [`lookup_device`].
|
||||||
|
#[derive(Debug, Deserialize, utoipa::IntoParams)]
|
||||||
|
pub struct LookupParams {
|
||||||
|
/// The order number as typed (`6es7511-1ak02-0ab0`).
|
||||||
|
pub order_number: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What Siemens' advisories know of an order number.
|
||||||
|
///
|
||||||
|
/// For recognising one while it is typed. Public data only: nothing of the
|
||||||
|
/// tenant is read.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/devices/lookup",
|
||||||
|
tag = "Targets",
|
||||||
|
params(LookupParams),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The order number normalised, whether it has a Siemens order number's shape, and, when advisories name it, the product's name and how many"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
(status = 500, description = "The advisory index could not be read"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
|
#[tracing::instrument(skip_all)]
|
||||||
|
pub async fn lookup_device(
|
||||||
|
Extension(agent): AgentExt,
|
||||||
|
_tenant: TenantCtx,
|
||||||
|
Query(params): Query<LookupParams>,
|
||||||
|
) -> ApiResult<DeviceLookup> {
|
||||||
|
let order_number = normalised_order_number(¶ms.order_number);
|
||||||
|
// Any firmware: only the shape of the order number is checked here.
|
||||||
|
let Ok(device) = PlcDevice::new(&order_number, "0", None) else {
|
||||||
|
return Ok(Json(ApiResponse {
|
||||||
|
data: DeviceLookup {
|
||||||
|
order_number,
|
||||||
|
valid: false,
|
||||||
|
product: None,
|
||||||
|
advisories: 0,
|
||||||
|
},
|
||||||
|
total: None,
|
||||||
|
page: None,
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
let advisories =
|
||||||
|
advisories_naming(agent.advisory_index.as_ref(), vec![order_number.clone()]).await?;
|
||||||
|
let check = DeviceCheck::new(device, &advisories);
|
||||||
|
Ok(Json(ApiResponse {
|
||||||
|
data: DeviceLookup {
|
||||||
|
order_number,
|
||||||
|
valid: true,
|
||||||
|
product: check.product,
|
||||||
|
advisories: check.advisories.len(),
|
||||||
|
},
|
||||||
|
total: None,
|
||||||
|
page: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[allow(clippy::unwrap_used)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use futures_util::future::BoxFuture;
|
||||||
|
|
||||||
|
/// An index answering with the synthetic Siemens advisory, and a CODESYS
|
||||||
|
/// one that must never reach a device.
|
||||||
|
struct Fixture;
|
||||||
|
|
||||||
|
impl AdvisoryIndex for Fixture {
|
||||||
|
fn relevant<'a>(
|
||||||
|
&'a self,
|
||||||
|
wanted: &'a Wanted,
|
||||||
|
) -> BoxFuture<'a, Result<Vec<(String, Advisory)>, String>> {
|
||||||
|
assert!(wanted.providers.is_empty() && wanted.purls.is_empty());
|
||||||
|
let doc: serde_json::Value = serde_json::from_str(include_str!(
|
||||||
|
"../../../../compliance-core/tests/fixtures/csaf/siemens-synthetic.json"
|
||||||
|
))
|
||||||
|
.unwrap();
|
||||||
|
let siemens = compliance_core::csaf_ingest::parse(&doc).unwrap();
|
||||||
|
let mut codesys = siemens.clone();
|
||||||
|
codesys.id = "VDE-2026-0001".into();
|
||||||
|
Box::pin(async move {
|
||||||
|
Ok(vec![
|
||||||
|
("siemens".to_string(), siemens),
|
||||||
|
("codesys".to_string(), codesys),
|
||||||
|
])
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn devices_are_checked_against_siemens_advisories_only() {
|
||||||
|
let advisories = advisories_naming(&Fixture, vec!["6ES7511-1AK02-0AB0".into()])
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(advisories.len(), 1);
|
||||||
|
let devices = checks(
|
||||||
|
vec![
|
||||||
|
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.4", None).unwrap(),
|
||||||
|
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.5", None).unwrap(),
|
||||||
|
PlcDevice::new("6ES7516-3AN02-0AB0", "3.0", None).unwrap(),
|
||||||
|
],
|
||||||
|
&advisories,
|
||||||
|
);
|
||||||
|
use compliance_core::device_check::DeviceState;
|
||||||
|
let states: Vec<DeviceState> = devices.iter().map(DeviceCheck::state).collect();
|
||||||
|
assert_eq!(
|
||||||
|
states,
|
||||||
|
[
|
||||||
|
DeviceState::Affected,
|
||||||
|
DeviceState::NotAffected,
|
||||||
|
DeviceState::NotNamed
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
devices[0].advisories[0].fixed_from.as_deref(),
|
||||||
|
Some("3.1.5")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
pub mod admin;
|
pub mod admin;
|
||||||
|
pub mod branding;
|
||||||
pub mod chat;
|
pub mod chat;
|
||||||
pub mod connections;
|
pub mod connections;
|
||||||
pub mod cve_history;
|
pub mod cve_history;
|
||||||
@@ -6,6 +7,7 @@ pub mod cve_matrix;
|
|||||||
pub mod dast;
|
pub mod dast;
|
||||||
mod delivery;
|
mod delivery;
|
||||||
pub mod demo_seed;
|
pub mod demo_seed;
|
||||||
|
pub mod devices;
|
||||||
pub mod dto;
|
pub mod dto;
|
||||||
pub mod evidence;
|
pub mod evidence;
|
||||||
pub mod finding_breakdown;
|
pub mod finding_breakdown;
|
||||||
|
|||||||
@@ -490,7 +490,7 @@ pub async fn list_offers(
|
|||||||
responses(
|
responses(
|
||||||
(status = 200, description = "Accepted (`data`: the offer)"),
|
(status = 200, description = "Accepted (`data`: the offer)"),
|
||||||
(status = 404, description = "No such offer, or no such component"),
|
(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 = 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 = 503, description = "The registry cannot be asked"),
|
||||||
(status = 401, description = "No valid bearer token"),
|
(status = 401, description = "No valid bearer token"),
|
||||||
@@ -601,9 +601,9 @@ pub async fn accept_offer(
|
|||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(created) => created,
|
Ok(created) => created,
|
||||||
Err(status) => {
|
Err(e) => {
|
||||||
unclaim(&db, offer.id).await?;
|
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();
|
let created_id = created.id.map(|o| o.to_hex()).unwrap_or_default();
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ use compliance_core::tenant_ctx::TenantCtx;
|
|||||||
|
|
||||||
use crate::agent::ComplianceAgent;
|
use crate::agent::ComplianceAgent;
|
||||||
use crate::classify::{classify_target, MockFirmwareDetector};
|
use crate::classify::{classify_target, MockFirmwareDetector};
|
||||||
|
use crate::error::AgentError;
|
||||||
use crate::secrets::SecretError;
|
use crate::secrets::SecretError;
|
||||||
use crate::targets::{upload_dest, uploaded_artifact, MAX_UPLOAD_BYTES};
|
use crate::targets::{upload_dest, uploaded_artifact, MAX_UPLOAD_BYTES};
|
||||||
|
|
||||||
@@ -405,7 +406,8 @@ async fn findings_counts(
|
|||||||
request_body = CreateTargetRequest,
|
request_body = CreateTargetRequest,
|
||||||
responses(
|
responses(
|
||||||
(status = 200, description = "The new target"),
|
(status = 200, description = "The new target"),
|
||||||
(status = 422, description = "A malformed body, or a device whose order number or firmware is not one"),
|
(status = 409, description = "The plan allows no further active target (`target_limit`)"),
|
||||||
|
(status = 422, description = "A malformed body"),
|
||||||
(status = 503, description = "A credential cannot be sealed"),
|
(status = 503, description = "A credential cannot be sealed"),
|
||||||
(status = 401, description = "No valid bearer token"),
|
(status = 401, description = "No valid bearer token"),
|
||||||
)
|
)
|
||||||
@@ -415,20 +417,25 @@ pub async fn create_target(
|
|||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
tenant: TenantCtx,
|
tenant: TenantCtx,
|
||||||
Json(req): Json<CreateTargetRequest>,
|
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);
|
let mut target = OnboardedTarget::new(req.name, req.target_type);
|
||||||
target.description = req.description;
|
target.description = req.description;
|
||||||
if let Some(supplier) = req.supplier {
|
if let Some(supplier) = req.supplier {
|
||||||
target.supplier = supplier.build()?;
|
target.supplier = supplier.build().map_err(IntoResponse::into_response)?;
|
||||||
}
|
}
|
||||||
target.devices = build_devices(&req.devices)?;
|
|
||||||
target.artifacts = merge_artifacts(&agent.secrets, &req.artifacts, &[]).map_err(|e| {
|
target.artifacts = merge_artifacts(&agent.secrets, &req.artifacts, &[]).map_err(|e| {
|
||||||
tracing::error!("storing a credential: {e}");
|
tracing::error!("storing a credential: {e}");
|
||||||
StatusCode::SERVICE_UNAVAILABLE
|
StatusCode::SERVICE_UNAVAILABLE.into_response()
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
let db = tenant_db(&agent, &tenant).await?;
|
let db = tenant_db(&agent, &tenant)
|
||||||
let target = insert_target(&agent, &db, &tenant.0.tenant_id, target).await?;
|
.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 {
|
Ok(Json(ApiResponse {
|
||||||
data: target.redacted(),
|
data: target.redacted(),
|
||||||
total: None,
|
total: None,
|
||||||
@@ -436,36 +443,45 @@ pub async fn create_target(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Store a new `target` of tenant `tenant_id` and count it: what every way
|
/// Store a new `target` of tenant `tenant_id` and count it
|
||||||
/// of adding a target does (the API, and accepting a supplier's SBOM release,
|
/// ([`crate::targets::create_target`]), then read its supplier's CSAF feed.
|
||||||
/// #1028), so each counts the same under the plan.
|
/// What the API and accepting a supplier's SBOM release (#1028) do.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # 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(
|
pub(super) async fn insert_target(
|
||||||
agent: &Arc<ComplianceAgent>,
|
agent: &Arc<ComplianceAgent>,
|
||||||
db: &crate::database::Database,
|
db: &crate::database::Database,
|
||||||
tenant_id: &str,
|
tenant_id: &str,
|
||||||
mut target: OnboardedTarget,
|
target: OnboardedTarget,
|
||||||
) -> Result<OnboardedTarget, StatusCode> {
|
) -> Result<OnboardedTarget, AgentError> {
|
||||||
let res = db
|
let target = crate::targets::create_target(agent, db, tenant_id, target).await?;
|
||||||
.onboarded_targets()
|
|
||||||
.insert_one(&target)
|
|
||||||
.await
|
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
||||||
target.id = res.inserted_id.as_object_id();
|
|
||||||
refresh_supplier_csaf(agent, tenant_id, target.supplier.as_ref());
|
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)
|
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.
|
/// One target, credentials redacted.
|
||||||
#[utoipa::path(
|
#[utoipa::path(
|
||||||
get,
|
get,
|
||||||
@@ -560,6 +576,7 @@ pub async fn list_webhook_deliveries(
|
|||||||
(status = 200, description = "The changed target"),
|
(status = 200, description = "The changed target"),
|
||||||
(status = 400, description = "Not an id"),
|
(status = 400, description = "Not an id"),
|
||||||
(status = 404, description = "No such target"),
|
(status = 404, description = "No such target"),
|
||||||
|
(status = 409, description = "`target_limit`: other artifacts would make a demo target the tenant's own, and the plan has no room for it"),
|
||||||
(status = 422, description = "A malformed body, a project that is not the tenant's, or a device whose order number or firmware is not one"),
|
(status = 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 = 503, description = "A credential cannot be sealed"),
|
||||||
(status = 401, description = "No valid bearer token"),
|
(status = 401, description = "No valid bearer token"),
|
||||||
@@ -571,7 +588,7 @@ pub async fn update_target(
|
|||||||
tenant: TenantCtx,
|
tenant: TenantCtx,
|
||||||
Path(id): Path<String>,
|
Path(id): Path<String>,
|
||||||
Json(req): Json<UpdateTargetRequest>,
|
Json(req): Json<UpdateTargetRequest>,
|
||||||
) -> Result<Json<ApiResponse<OnboardedTarget>>, StatusCode> {
|
) -> Result<Json<ApiResponse<OnboardedTarget>>, UploadRefusal> {
|
||||||
let oid = parse_oid(&id)?;
|
let oid = parse_oid(&id)?;
|
||||||
let db = tenant_db(&agent, &tenant).await?;
|
let db = tenant_db(&agent, &tenant).await?;
|
||||||
|
|
||||||
@@ -643,9 +660,14 @@ pub async fn update_target(
|
|||||||
);
|
);
|
||||||
set.insert("project_ids", ids);
|
set.insert("project_ids", ids);
|
||||||
}
|
}
|
||||||
|
// A demo target given other sources becomes the tenant's own (below).
|
||||||
|
let mut claimed_demo = None;
|
||||||
if let (Some(arts), Some(stored)) = (req.artifacts, stored.as_ref()) {
|
if let (Some(arts), Some(stored)) = (req.artifacts, stored.as_ref()) {
|
||||||
let built =
|
let built =
|
||||||
merge_artifacts(&agent.secrets, &arts, &stored.artifacts).map_err(credential_error)?;
|
merge_artifacts(&agent.secrets, &arts, &stored.artifacts).map_err(credential_error)?;
|
||||||
|
if !crate::targets::same_sources(&stored.artifacts, &built) {
|
||||||
|
claimed_demo = Some(stored);
|
||||||
|
}
|
||||||
set.insert(
|
set.insert(
|
||||||
"artifacts",
|
"artifacts",
|
||||||
to_bson(&built).map_err(|_| StatusCode::BAD_REQUEST)?,
|
to_bson(&built).map_err(|_| StatusCode::BAD_REQUEST)?,
|
||||||
@@ -677,6 +699,11 @@ pub async fn update_target(
|
|||||||
}
|
}
|
||||||
update.insert("$set", set);
|
update.insert("$set", set);
|
||||||
|
|
||||||
|
if let Some(stored) = claimed_demo {
|
||||||
|
crate::targets::claim_demo(&agent, &db, &tenant.0.tenant_id, stored)
|
||||||
|
.await
|
||||||
|
.map_err(demo_refused)?;
|
||||||
|
}
|
||||||
db.onboarded_targets()
|
db.onboarded_targets()
|
||||||
.update_one(doc! { "_id": oid }, update)
|
.update_one(doc! { "_id": oid }, update)
|
||||||
.await
|
.await
|
||||||
@@ -692,7 +719,22 @@ pub async fn update_target(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
get_target(Extension(agent), tenant, Path(id)).await
|
Ok(get_target(Extension(agent), tenant, Path(id)).await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A demo target not made the tenant's own, as the API answers: 409
|
||||||
|
/// `target_limit` when the plan has no room for it, else 500.
|
||||||
|
fn demo_refused(e: AgentError) -> UploadRefusal {
|
||||||
|
match e {
|
||||||
|
AgentError::TargetLimit(cap) => {
|
||||||
|
tracing::info!(cap, "demo target kept: the plan's targets are all active");
|
||||||
|
UploadRefusal::because(StatusCode::CONFLICT, "target_limit", "target_limit")
|
||||||
|
}
|
||||||
|
e => {
|
||||||
|
tracing::error!("claiming a demo target: {e}");
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR.into()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Remove a deleted target's clones, uploads, work trees and blobs from disk.
|
/// Remove a deleted target's clones, uploads, work trees and blobs from disk.
|
||||||
@@ -872,6 +914,8 @@ async fn delete_session_data(db: &crate::database::Database, session_id: &str) {
|
|||||||
responses(
|
responses(
|
||||||
(status = 200, description = "The target with the artifact"),
|
(status = 200, description = "The target with the artifact"),
|
||||||
(status = 400, description = "Not an id"),
|
(status = 400, description = "Not an id"),
|
||||||
|
(status = 404, description = "No such target"),
|
||||||
|
(status = 409, description = "`target_limit`: the artifact would make a demo target the tenant's own, and the plan has no room for it"),
|
||||||
(status = 422, description = "A malformed body"),
|
(status = 422, description = "A malformed body"),
|
||||||
(status = 503, description = "A credential cannot be sealed"),
|
(status = 503, description = "A credential cannot be sealed"),
|
||||||
(status = 401, description = "No valid bearer token"),
|
(status = 401, description = "No valid bearer token"),
|
||||||
@@ -883,9 +927,18 @@ pub async fn add_artifact(
|
|||||||
tenant: TenantCtx,
|
tenant: TenantCtx,
|
||||||
Path(id): Path<String>,
|
Path(id): Path<String>,
|
||||||
Json(input): Json<ArtifactInput>,
|
Json(input): Json<ArtifactInput>,
|
||||||
) -> Result<Json<ApiResponse<OnboardedTarget>>, StatusCode> {
|
) -> Result<Json<ApiResponse<OnboardedTarget>>, UploadRefusal> {
|
||||||
let oid = parse_oid(&id)?;
|
let oid = parse_oid(&id)?;
|
||||||
let db = tenant_db(&agent, &tenant).await?;
|
let db = tenant_db(&agent, &tenant).await?;
|
||||||
|
let stored = db
|
||||||
|
.onboarded_targets()
|
||||||
|
.find_one(doc! { "_id": oid })
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||||
|
.ok_or(StatusCode::NOT_FOUND)?;
|
||||||
|
crate::targets::claim_demo(&agent, &db, &tenant.0.tenant_id, &stored)
|
||||||
|
.await
|
||||||
|
.map_err(demo_refused)?;
|
||||||
let artifact = input.build(&agent.secrets, None).map_err(|e| {
|
let artifact = input.build(&agent.secrets, None).map_err(|e| {
|
||||||
tracing::error!("storing a credential: {e}");
|
tracing::error!("storing a credential: {e}");
|
||||||
StatusCode::SERVICE_UNAVAILABLE
|
StatusCode::SERVICE_UNAVAILABLE
|
||||||
@@ -898,7 +951,7 @@ pub async fn add_artifact(
|
|||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
get_target(Extension(agent), tenant, Path(id)).await
|
Ok(get_target(Extension(agent), tenant, Path(id)).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The multipart form of an artifact upload.
|
/// The multipart form of an artifact upload.
|
||||||
@@ -915,7 +968,10 @@ pub struct UploadArtifactForm {
|
|||||||
/// (a supplier's CycloneDX or SPDX 2 SBOM of a bought-in component).
|
/// (a supplier's CycloneDX or SPDX 2 SBOM of a bought-in component).
|
||||||
#[schema(example = "source_archive")]
|
#[schema(example = "source_archive")]
|
||||||
kind: String,
|
kind: String,
|
||||||
/// The PLC project's format, for a PLC project.
|
/// The PLC project's format, for a PLC project: `plcopen_xml`,
|
||||||
|
/// `structured_text`, `project_archive` or `tia_export` (a TIA
|
||||||
|
/// connector's export, whose manifest is read on upload).
|
||||||
|
#[schema(example = "tia_export")]
|
||||||
plc_format: Option<String>,
|
plc_format: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -941,10 +997,11 @@ pub struct UploadArtifactForm {
|
|||||||
responses(
|
responses(
|
||||||
(status = 200, description = "The target with the artifact"),
|
(status = 200, description = "The target with the artifact"),
|
||||||
(status = 404, description = "No such target"),
|
(status = 404, description = "No such target"),
|
||||||
|
(status = 409, description = "`target_limit`: the file would make a demo target the tenant's own, and the plan has no room for it"),
|
||||||
(status = 400, description = "Not an id, or a missing or unknown field"),
|
(status = 400, description = "Not an id, or a missing or unknown field"),
|
||||||
(status = 413, description = "The file is too large (a supplier SBOM: over 20 MiB)"),
|
(status = 413, description = "The file is too large (a supplier SBOM: over 20 MiB)"),
|
||||||
(status = 415, description = "An archive format that cannot be unpacked"),
|
(status = 415, description = "An archive format that cannot be unpacked"),
|
||||||
(status = 422, description = "A supplier SBOM that cannot be read; `error` says why"),
|
(status = 422, description = "A supplier SBOM or TIA export that cannot be read; `error` says why, `code` names it"),
|
||||||
(status = 401, description = "No valid bearer token"),
|
(status = 401, description = "No valid bearer token"),
|
||||||
)
|
)
|
||||||
)]
|
)]
|
||||||
@@ -965,6 +1022,11 @@ pub async fn upload_artifact(
|
|||||||
else {
|
else {
|
||||||
return Err(StatusCode::NOT_FOUND.into());
|
return Err(StatusCode::NOT_FOUND.into());
|
||||||
};
|
};
|
||||||
|
// Refused before the file streams in. A demo target becomes the
|
||||||
|
// tenant's own even when the file then turns out unreadable.
|
||||||
|
crate::targets::claim_demo(&agent, &db, &tenant.0.tenant_id, &stored_target)
|
||||||
|
.await
|
||||||
|
.map_err(demo_refused)?;
|
||||||
|
|
||||||
let mut kind: Option<ArtifactKind> = None;
|
let mut kind: Option<ArtifactKind> = None;
|
||||||
let mut plc_format: Option<PlcFormat> = None;
|
let mut plc_format: Option<PlcFormat> = None;
|
||||||
@@ -1025,13 +1087,15 @@ pub(super) struct AttachedUpload {
|
|||||||
/// refused when it cannot be, its summary is kept with it, and it replaces the
|
/// refused when it cannot be, its summary is kept with it, and it replaces the
|
||||||
/// target's previous one. Any other archive is checked for a format that can
|
/// target's previous one. Any other archive is checked for a format that can
|
||||||
/// be unpacked and for encryption. The file is deleted unless the artifact
|
/// be unpacked and for encryption. The file is deleted unless the artifact
|
||||||
/// references it.
|
/// references it. A TIA export's manifest is read (#1090), its devices are
|
||||||
|
/// kept with it, and it replaces the target's previous export.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
///
|
///
|
||||||
/// 400 for a kind that is not uploaded as a file, 415 for an archive that
|
/// 400 for a kind that is not uploaded as a file, 415 for an archive that
|
||||||
/// cannot be unpacked, the supplier SBOM's refusal ([`SupplierSbomSummary::of`]),
|
/// cannot be unpacked, the supplier SBOM's refusal ([`SupplierSbomSummary::of`]),
|
||||||
/// 500 when the file or the database fails.
|
/// 422 with its code for a TIA export that cannot be read, 500 when the
|
||||||
|
/// file or the database fails.
|
||||||
pub(super) async fn attach_upload(
|
pub(super) async fn attach_upload(
|
||||||
db: &crate::database::Database,
|
db: &crate::database::Database,
|
||||||
target: &OnboardedTarget,
|
target: &OnboardedTarget,
|
||||||
@@ -1064,6 +1128,22 @@ pub(super) async fn attach_upload(
|
|||||||
let read = SupplierSbomSummary::of(read)?;
|
let read = SupplierSbomSummary::of(read)?;
|
||||||
artifact.detected.extend(read.facts());
|
artifact.detected.extend(read.facts());
|
||||||
summary = Some(read);
|
summary = Some(read);
|
||||||
|
} else if is_tia_export(&artifact) {
|
||||||
|
// A connector's export (#1090): its manifest is read now, so a bad
|
||||||
|
// one is refused while the connector can still say so.
|
||||||
|
let path = upload.path.clone();
|
||||||
|
let manifest =
|
||||||
|
tokio::task::spawn_blocking(move || crate::pipeline::plc::tia::read_manifest(&path))
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||||
|
.map_err(|e| UploadRefusal {
|
||||||
|
status: StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
reason: Some((e.to_string(), e.code())),
|
||||||
|
})?;
|
||||||
|
artifact.detected.extend(tia_facts(&manifest));
|
||||||
|
if let Some(plc) = artifact.plc.as_mut() {
|
||||||
|
plc.devices = manifest.devices().matched;
|
||||||
|
}
|
||||||
} else if kind != ArtifactKind::FirmwareImage {
|
} else if kind != ArtifactKind::FirmwareImage {
|
||||||
match archive_check(upload.path.clone()).await? {
|
match archive_check(upload.path.clone()).await? {
|
||||||
// 7z and rar are never unpacked: say so now, not after a scan.
|
// 7z and rar are never unpacked: say so now, not after a scan.
|
||||||
@@ -1089,7 +1169,23 @@ pub(super) async fn attach_upload(
|
|||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
upload.keep();
|
upload.keep();
|
||||||
if kind == ArtifactKind::SupplierSbom {
|
if kind == ArtifactKind::SupplierSbom {
|
||||||
replace_supplier_sboms(db, oid, &artifact_id, &target.artifacts).await;
|
replace_earlier(
|
||||||
|
db,
|
||||||
|
oid,
|
||||||
|
&artifact_id,
|
||||||
|
&target.artifacts,
|
||||||
|
Replaced::SupplierSbom,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
} else if is_tia_export(&artifact) {
|
||||||
|
replace_earlier(
|
||||||
|
db,
|
||||||
|
oid,
|
||||||
|
&artifact_id,
|
||||||
|
&target.artifacts,
|
||||||
|
Replaced::TiaExport,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(AttachedUpload {
|
Ok(AttachedUpload {
|
||||||
@@ -1098,35 +1194,82 @@ pub(super) async fn attach_upload(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Remove the target's supplier SBOMs other than the one just uploaded
|
/// Whether `artifact` is a TIA connector's export (#1090).
|
||||||
/// (`kept`): a new version replaces the one before it (#1025), so a scan never
|
fn is_tia_export(artifact: &compliance_core::models::Artifact) -> bool {
|
||||||
/// reads two versions as one. Their files go too, once nothing references
|
artifact.kind == ArtifactKind::PlcProject
|
||||||
/// them. Best-effort, after the new one is stored: if this fails, the next
|
&& artifact.plc.as_ref().map(|p| p.format) == Some(PlcFormat::TiaExport)
|
||||||
/// scan reads both versions, and nothing is lost.
|
}
|
||||||
async fn replace_supplier_sboms(
|
|
||||||
|
/// What a TIA export's manifest says, as the artifact's facts.
|
||||||
|
fn tia_facts(manifest: &compliance_core::models::TiaManifest) -> [DetectedFact; 4] {
|
||||||
|
[
|
||||||
|
DetectedFact::new("tia_version", manifest.tia_version.as_str(), "upload"),
|
||||||
|
DetectedFact::new("tia_project", manifest.project.name.as_str(), "upload"),
|
||||||
|
DetectedFact::new("tia_devices", manifest.devices.len().to_string(), "upload"),
|
||||||
|
DetectedFact::new("tia_blocks", manifest.blocks.len().to_string(), "upload"),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The kinds of upload a new one replaces.
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
enum Replaced {
|
||||||
|
/// A supplier's SBOM: a new version replaces the one before it (#1025).
|
||||||
|
SupplierSbom,
|
||||||
|
/// A TIA export: a new export of the project replaces the last (#1090).
|
||||||
|
TiaExport,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Replaced {
|
||||||
|
/// The artifacts of this kind, as a Mongo filter.
|
||||||
|
fn filter(self) -> mongodb::bson::Document {
|
||||||
|
match self {
|
||||||
|
Self::SupplierSbom => doc! { "kind": "supplier_sbom" },
|
||||||
|
Self::TiaExport => doc! { "kind": "plc_project", "plc.format": "tia_export" },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `artifact` is of this kind.
|
||||||
|
fn matches(self, artifact: &compliance_core::models::Artifact) -> bool {
|
||||||
|
match self {
|
||||||
|
Self::SupplierSbom => artifact.kind == ArtifactKind::SupplierSbom,
|
||||||
|
Self::TiaExport => is_tia_export(artifact),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove the target's uploads of kind `what` other than the one just
|
||||||
|
/// uploaded (`kept`), so a scan never reads two versions as one: a new
|
||||||
|
/// supplier SBOM replaces the one before it (#1025), a new TIA export the
|
||||||
|
/// last (#1090). Their files go too, once nothing references them.
|
||||||
|
/// Best-effort, after the new one is stored: if this fails, the next scan
|
||||||
|
/// reads both, and nothing is lost.
|
||||||
|
async fn replace_earlier(
|
||||||
db: &crate::database::Database,
|
db: &crate::database::Database,
|
||||||
target: ObjectId,
|
target: ObjectId,
|
||||||
kept: &str,
|
kept: &str,
|
||||||
before: &[compliance_core::models::Artifact],
|
before: &[compliance_core::models::Artifact],
|
||||||
|
what: Replaced,
|
||||||
) {
|
) {
|
||||||
|
let mut earlier = what.filter();
|
||||||
|
earlier.insert("id", doc! { "$ne": kept });
|
||||||
let pulled = db
|
let pulled = db
|
||||||
.onboarded_targets()
|
.onboarded_targets()
|
||||||
.update_one(
|
.update_one(
|
||||||
doc! { "_id": target },
|
doc! { "_id": target },
|
||||||
doc! { "$pull": { "artifacts": { "kind": "supplier_sbom", "id": { "$ne": kept } } } },
|
doc! { "$pull": { "artifacts": earlier } },
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
if let Err(e) = pulled {
|
if let Err(e) = pulled {
|
||||||
tracing::warn!(target_id = %target, error = %e, "replaced supplier SBOM not removed");
|
tracing::warn!(target_id = %target, ?what, error = %e, "replaced upload not removed");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
for old in before
|
for old in before
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|a| a.kind == ArtifactKind::SupplierSbom && a.id != kept)
|
.filter(|a| what.matches(a) && a.id != kept)
|
||||||
.filter_map(|a| a.stored_path.as_deref())
|
.filter_map(|a| a.stored_path.as_deref())
|
||||||
{
|
{
|
||||||
if let Err(e) = std::fs::remove_file(old) {
|
if let Err(e) = std::fs::remove_file(old) {
|
||||||
tracing::warn!(target_id = %target, error = %e, "replaced supplier SBOM file left");
|
tracing::warn!(target_id = %target, ?what, error = %e, "replaced upload's file left");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1743,7 +1886,7 @@ pub async fn swap_target_billing(
|
|||||||
&db,
|
&db,
|
||||||
incoming,
|
incoming,
|
||||||
outgoing,
|
outgoing,
|
||||||
plan.included_targets.is_some(),
|
plan.billed_included().is_some(),
|
||||||
chrono::Utc::now(),
|
chrono::Utc::now(),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
|
|||||||
@@ -250,14 +250,16 @@ pub async fn export(
|
|||||||
|
|
||||||
/// `DELETE /api/v1/platform/tenants/{id}/data` — GDPR erasure: drops the
|
/// `DELETE /api/v1/platform/tenants/{id}/data` — GDPR erasure: drops the
|
||||||
/// tenant database and removes its code from disk (clones, uploads, work
|
/// tenant database and removes its code from disk (clones, uploads, work
|
||||||
/// trees, blobs, runner artifacts). Requires `{"confirm": "<slug or id>"}`.
|
/// trees, blobs, runner artifacts). Requires `{"confirm": "<tenant id>"}`:
|
||||||
|
/// the same id as in the path, so a call can only erase the tenant it names
|
||||||
|
/// twice; anything else is refused with 400 before anything is touched.
|
||||||
pub async fn delete_data(
|
pub async fn delete_data(
|
||||||
State(st): State<PlatformState>,
|
State(st): State<PlatformState>,
|
||||||
Path(tenant_id): Path<String>,
|
Path(tenant_id): Path<String>,
|
||||||
body: Option<Json<LifecycleBody>>,
|
body: Option<Json<LifecycleBody>>,
|
||||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||||
let confirm = body.and_then(|Json(b)| b.confirm).unwrap_or_default();
|
let confirm = body.and_then(|Json(b)| b.confirm);
|
||||||
if confirm.is_empty() {
|
if !confirms_erasure(&tenant_id, confirm.as_deref()) {
|
||||||
return Err(StatusCode::BAD_REQUEST);
|
return Err(StatusCode::BAD_REQUEST);
|
||||||
}
|
}
|
||||||
// Where the tenant's code lies on disk, read before its records go.
|
// Where the tenant's code lies on disk, read before its records go.
|
||||||
@@ -299,6 +301,12 @@ pub async fn delete_data(
|
|||||||
})))
|
})))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether `confirm` confirms erasing `tenant_id`: it must be that id,
|
||||||
|
/// exactly. A missing or empty value, or another tenant's id, does not.
|
||||||
|
fn confirms_erasure(tenant_id: &str, confirm: Option<&str>) -> bool {
|
||||||
|
!tenant_id.is_empty() && confirm == Some(tenant_id)
|
||||||
|
}
|
||||||
|
|
||||||
/// `POST /api/v1/platform/tenants/demo/reset` — drops and re-creates the
|
/// `POST /api/v1/platform/tenants/demo/reset` — drops and re-creates the
|
||||||
/// demo tenant database. With `{"seed": true}` it then re-seeds the bundled
|
/// demo tenant database. With `{"seed": true}` it then re-seeds the bundled
|
||||||
/// demo targets and starts their scans, which is what the nightly reset of the
|
/// demo targets and starts their scans, which is what the nightly reset of the
|
||||||
@@ -848,3 +856,20 @@ mod target_count_tests {
|
|||||||
assert!(stages[0].contains_key("$match") && stages[1].contains_key("$group"));
|
assert!(stages[0].contains_key("$match") && stages[1].contains_key("$group"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod erasure_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_the_tenants_own_id_confirms_its_erasure() {
|
||||||
|
assert!(confirms_erasure("t-1", Some("t-1")));
|
||||||
|
assert!(!confirms_erasure("t-1", None));
|
||||||
|
assert!(!confirms_erasure("t-1", Some("")));
|
||||||
|
assert!(!confirms_erasure("t-1", Some("t-2")));
|
||||||
|
assert!(!confirms_erasure("t-1", Some("T-1")));
|
||||||
|
assert!(!confirms_erasure("t-1", Some(" t-1")));
|
||||||
|
assert!(!confirms_erasure("t-1", Some("yes")));
|
||||||
|
assert!(!confirms_erasure("", Some("")));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -75,6 +75,12 @@ pub const KEY_SCOPES: &[(Method, &str, &str)] = &[
|
|||||||
(Method::GET, "/api/v1/licenses/policy", SBOM_READ),
|
(Method::GET, "/api/v1/licenses/policy", SBOM_READ),
|
||||||
(Method::GET, "/api/v1/scan-runs", SCANS_READ),
|
(Method::GET, "/api/v1/scan-runs", SCANS_READ),
|
||||||
(Method::POST, "/api/v1/targets/{id}/scan", SCANS_RUN),
|
(Method::POST, "/api/v1/targets/{id}/scan", SCANS_RUN),
|
||||||
|
// A TIA connector uploads its export (#1090) and starts a scan.
|
||||||
|
(
|
||||||
|
Method::POST,
|
||||||
|
"/api/v1/targets/{id}/artifacts/upload",
|
||||||
|
UPLOADS_WRITE,
|
||||||
|
),
|
||||||
(Method::POST, "/api/v1/dast/targets/{id}/scan", SCANS_RUN),
|
(Method::POST, "/api/v1/dast/targets/{id}/scan", SCANS_RUN),
|
||||||
(Method::GET, "/api/v1/targets/{id}/enisa", ENISA_READ),
|
(Method::GET, "/api/v1/targets/{id}/enisa", ENISA_READ),
|
||||||
(Method::GET, "/api/v1/cves/{id}/enisa", ENISA_READ),
|
(Method::GET, "/api/v1/cves/{id}/enisa", ENISA_READ),
|
||||||
@@ -85,6 +91,7 @@ const FINDINGS_WRITE: &str = "pruefwerk:findings.write";
|
|||||||
const SBOM_READ: &str = "pruefwerk:sbom.read";
|
const SBOM_READ: &str = "pruefwerk:sbom.read";
|
||||||
const SCANS_READ: &str = "pruefwerk:scans.read";
|
const SCANS_READ: &str = "pruefwerk:scans.read";
|
||||||
const SCANS_RUN: &str = "pruefwerk:scans.run";
|
const SCANS_RUN: &str = "pruefwerk:scans.run";
|
||||||
|
const UPLOADS_WRITE: &str = "pruefwerk:uploads.write";
|
||||||
const ENISA_READ: &str = "pruefwerk:enisa.read";
|
const ENISA_READ: &str = "pruefwerk:enisa.read";
|
||||||
|
|
||||||
/// What a legacy key (issued before scopes, no scopes of its own) may do:
|
/// What a legacy key (issued before scopes, no scopes of its own) may do:
|
||||||
|
|||||||
@@ -341,6 +341,7 @@ const ALL_SCOPES: &[&str] = &[
|
|||||||
"pruefwerk:sbom.read",
|
"pruefwerk:sbom.read",
|
||||||
"pruefwerk:scans.read",
|
"pruefwerk:scans.read",
|
||||||
"pruefwerk:scans.run",
|
"pruefwerk:scans.run",
|
||||||
|
"pruefwerk:uploads.write",
|
||||||
"pruefwerk:enisa.read",
|
"pruefwerk:enisa.read",
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -73,6 +73,10 @@ fn described_routes() -> OpenApiRouter {
|
|||||||
handlers::supply_chain_layout::reset_layout
|
handlers::supply_chain_layout::reset_layout
|
||||||
))
|
))
|
||||||
.routes(routes!(handlers::metering::get_usage))
|
.routes(routes!(handlers::metering::get_usage))
|
||||||
|
// The workspace's branding (tenant-registry#155).
|
||||||
|
.routes(routes!(handlers::branding::get_branding))
|
||||||
|
.routes(routes!(handlers::branding::get_logo))
|
||||||
|
.routes(routes!(handlers::branding::ack))
|
||||||
// Whether the caller may use Prüfwerk at all: answered by the
|
// Whether the caller may use Prüfwerk at all: answered by the
|
||||||
// authentication and entitlement layers in front of it (a blocked
|
// authentication and entitlement layers in front of it (a blocked
|
||||||
// member gets 403 MEMBER_BLOCKED), for the dashboard's sign-in check.
|
// member gets 403 MEMBER_BLOCKED), for the dashboard's sign-in check.
|
||||||
@@ -98,6 +102,9 @@ fn described_routes() -> OpenApiRouter {
|
|||||||
handlers::onboarding::delete_target
|
handlers::onboarding::delete_target
|
||||||
))
|
))
|
||||||
.routes(routes!(handlers::onboarding::add_artifact))
|
.routes(routes!(handlers::onboarding::add_artifact))
|
||||||
|
// A target's Siemens controllers against Siemens' advisories (SPS 4a).
|
||||||
|
.routes(routes!(handlers::devices::list_devices))
|
||||||
|
.routes(routes!(handlers::devices::lookup_device))
|
||||||
.routes(routes!(handlers::onboarding::list_webhook_deliveries))
|
.routes(routes!(handlers::onboarding::list_webhook_deliveries))
|
||||||
// The one route that takes large bodies — and it streams them to
|
// The one route that takes large bodies — and it streams them to
|
||||||
// disk. Every other route keeps axum's 2 MiB default, so a JSON
|
// disk. Every other route keeps axum's 2 MiB default, so a JSON
|
||||||
|
|||||||
@@ -166,6 +166,8 @@ async fn seed_one(
|
|||||||
let mut target =
|
let mut target =
|
||||||
compliance_core::models::OnboardedTarget::new(full_name.to_string(), demo.target_type);
|
compliance_core::models::OnboardedTarget::new(full_name.to_string(), demo.target_type);
|
||||||
target.description = demo.description.clone();
|
target.description = demo.description.clone();
|
||||||
|
target.demo = true;
|
||||||
|
target.devices = demo.devices.clone();
|
||||||
for a in demo.artifacts.iter().filter(|a| !a.is_upload()) {
|
for a in demo.artifacts.iter().filter(|a| !a.is_upload()) {
|
||||||
match a.resolved_source_ref() {
|
match a.resolved_source_ref() {
|
||||||
Some(source_ref) => target.artifacts.push(targets::reference_artifact(
|
Some(source_ref) => target.artifacts.push(targets::reference_artifact(
|
||||||
|
|||||||
@@ -47,6 +47,11 @@ pub enum AgentError {
|
|||||||
#[error("not run: {0:?}")]
|
#[error("not run: {0:?}")]
|
||||||
NotAdmitted(compliance_core::models::Refusal),
|
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}")]
|
#[error("{0}")]
|
||||||
Other(String),
|
Other(String),
|
||||||
}
|
}
|
||||||
@@ -79,6 +84,7 @@ impl AgentError {
|
|||||||
| Self::Secret(_)
|
| Self::Secret(_)
|
||||||
| Self::Exec(_)
|
| Self::Exec(_)
|
||||||
| Self::NotAdmitted(_)
|
| Self::NotAdmitted(_)
|
||||||
|
| Self::TargetLimit(_)
|
||||||
| Self::Other(_) => (
|
| Self::Other(_) => (
|
||||||
RunErrorCode::Internal,
|
RunErrorCode::Internal,
|
||||||
"the scan stopped because of an internal error",
|
"the scan stopped because of an internal error",
|
||||||
@@ -91,6 +97,7 @@ impl From<AgentError> for axum::http::StatusCode {
|
|||||||
fn from(err: AgentError) -> Self {
|
fn from(err: AgentError) -> Self {
|
||||||
match err {
|
match err {
|
||||||
AgentError::Core(CoreError::NotFound(_)) => axum::http::StatusCode::NOT_FOUND,
|
AgentError::Core(CoreError::NotFound(_)) => axum::http::StatusCode::NOT_FOUND,
|
||||||
|
AgentError::TargetLimit(_) => axum::http::StatusCode::CONFLICT,
|
||||||
_ => axum::http::StatusCode::INTERNAL_SERVER_ERROR,
|
_ => axum::http::StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -117,6 +117,10 @@ pub struct DemoTarget {
|
|||||||
/// Applied by the nightly harness to the fixtures it onboards itself.
|
/// Applied by the nightly harness to the fixtures it onboards itself.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub enabled_scans: Vec<String>,
|
pub enabled_scans: Vec<String>,
|
||||||
|
/// Siemens controllers the target runs on (SPS item 4a), stored with the
|
||||||
|
/// target so its SBOM lists them and Siemens' advisories match them.
|
||||||
|
#[serde(default)]
|
||||||
|
pub devices: Vec<compliance_core::models::PlcDevice>,
|
||||||
/// Golden baseline for the nightly regression.
|
/// Golden baseline for the nightly regression.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub expect: Expect,
|
pub expect: Expect,
|
||||||
@@ -491,6 +495,32 @@ mod tests {
|
|||||||
assert_eq!(on_disk.name_prefix, bundled.name_prefix);
|
assert_eq!(on_disk.name_prefix, bundled.name_prefix);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn demo_devices_are_stored_as_the_api_would_store_them() {
|
||||||
|
// Arrange
|
||||||
|
let m = manifest();
|
||||||
|
let pump = m
|
||||||
|
.targets
|
||||||
|
.iter()
|
||||||
|
.find(|t| t.key == "plc-pump-station")
|
||||||
|
.expect("pump station in the manifest");
|
||||||
|
|
||||||
|
// Assert: a controller on a firmware Siemens names as affected
|
||||||
|
// (SSA-876787: below V2.9.8), so the demo SBOM is not empty.
|
||||||
|
assert!(!pump.devices.is_empty());
|
||||||
|
for t in &m.targets {
|
||||||
|
for d in &t.devices {
|
||||||
|
let normalised = compliance_core::models::PlcDevice::new(
|
||||||
|
&d.order_number,
|
||||||
|
&d.firmware,
|
||||||
|
d.label.as_deref(),
|
||||||
|
)
|
||||||
|
.expect("a valid controller");
|
||||||
|
assert_eq!(&normalised, d, "{}: store it normalised", t.key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn manifest_is_well_formed() {
|
fn manifest_is_well_formed() {
|
||||||
let m = manifest();
|
let m = manifest();
|
||||||
@@ -589,6 +619,7 @@ mod tests {
|
|||||||
optional: true,
|
optional: true,
|
||||||
}],
|
}],
|
||||||
enabled_scans: Vec::new(),
|
enabled_scans: Vec::new(),
|
||||||
|
devices: Vec::new(),
|
||||||
expect: Expect::default(),
|
expect: Expect::default(),
|
||||||
};
|
};
|
||||||
assert!(t.source_only());
|
assert!(t.source_only());
|
||||||
|
|||||||
@@ -467,6 +467,10 @@ pub enum Outcome {
|
|||||||
Ignored(&'static str),
|
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`.
|
/// Carry out a routed delivery for `tenant_id`.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
@@ -485,7 +489,10 @@ pub async fn apply_action(
|
|||||||
archive_target(db, &source.base_url, repo.id).await?,
|
archive_target(db, &source.base_url, repo.id).await?,
|
||||||
)),
|
)),
|
||||||
SourceAction::Created(repo) => {
|
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.
|
// An empty repository has nothing to scan; its first push will.
|
||||||
let scan = ensured.created && !repo.empty;
|
let scan = ensured.created && !repo.empty;
|
||||||
if scan {
|
if scan {
|
||||||
@@ -497,7 +504,10 @@ pub async fn apply_action(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
SourceAction::Push(repo) => {
|
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);
|
spawn_scan(agent, tenant_id, &ensured.target_id, ScanTrigger::Webhook);
|
||||||
Ok(Outcome::Ensured {
|
Ok(Outcome::Ensured {
|
||||||
target_id: ensured.target_id,
|
target_id: ensured.target_id,
|
||||||
@@ -608,6 +618,11 @@ pub async fn sync_with<L: RepoLister>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(_) => report.refreshed += 1,
|
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) => {
|
Err(err) => {
|
||||||
tracing::warn!(tenant_id, repo = %repo.full_name, "managed git sync: {err}");
|
tracing::warn!(tenant_id, repo = %repo.full_name, "managed git sync: {err}");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
//!
|
//!
|
||||||
//! **Included and extra targets.** The oldest active targets are included,
|
//! **Included and extra targets.** The oldest active targets are included,
|
||||||
//! up to the plan's `included_targets`; every other active target is extra.
|
//! 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
|
//! The split is stored on each target ([`OnboardedTarget::billing`]) and
|
||||||
//! brought up to date before each scan and when a target is created, so
|
//! brought up to date before each scan and when a target is created, so
|
||||||
//! archiving an included target moves the oldest extra one up.
|
//! archiving an included target moves the oldest extra one up.
|
||||||
@@ -179,10 +180,31 @@ pub async fn swap(
|
|||||||
pub struct Plan {
|
pub struct Plan {
|
||||||
/// How many targets the plan includes; `None` is unlimited.
|
/// How many targets the plan includes; `None` is unlimited.
|
||||||
pub included_targets: Option<u32>,
|
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.
|
/// The quota and the customer's Prüftag cap.
|
||||||
pub limits: PlanLimits,
|
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.
|
/// The tenant's counted Prüfungen and booked Prüftage per month.
|
||||||
const MONTHS: &str = "metering_months";
|
const MONTHS: &str = "metering_months";
|
||||||
/// Each target's Prüftag per day, once the quota was used up.
|
/// Each target's Prüftag per day, once the quota was used up.
|
||||||
@@ -447,6 +469,33 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
use chrono::TimeZone;
|
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]
|
#[test]
|
||||||
fn a_swap_holds_until_the_berlin_month_ends() {
|
fn a_swap_holds_until_the_berlin_month_ends() {
|
||||||
let at = |y, m, d, h| {
|
let at = |y, m, d, h| {
|
||||||
|
|||||||
@@ -526,7 +526,7 @@ mod tests {
|
|||||||
|
|
||||||
fn device(order_number: &str, firmware: &str) -> SbomEntry {
|
fn device(order_number: &str, firmware: &str) -> SbomEntry {
|
||||||
let device = compliance_core::models::PlcDevice::new(order_number, firmware, None).unwrap();
|
let device = compliance_core::models::PlcDevice::new(order_number, firmware, None).unwrap();
|
||||||
crate::pipeline::sbom::devices::entries(&[device], "t").remove(0)
|
crate::pipeline::sbom::devices::entries(&[device.into()], "t").remove(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -1925,6 +1925,22 @@ impl PipelineOrchestrator {
|
|||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
|
// A control application known only by the Siemens controllers
|
||||||
|
// it runs on (SPS item 4a): they are its SBOM, matched against
|
||||||
|
// Siemens' advisories as with a project.
|
||||||
|
// Also when the last one was removed, so its components and
|
||||||
|
// alerts go with it.
|
||||||
|
let target_devices = target.target_devices();
|
||||||
|
if target.target_type == TargetType::PlcSps || !target_devices.is_empty() {
|
||||||
|
let devices =
|
||||||
|
crate::pipeline::sbom::devices::entries(&target_devices, &target_id);
|
||||||
|
if let Err(e) = self
|
||||||
|
.persist_control_app_sbom(target, &target_id, scan_run_id, devices)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
tracing::warn!(target_id = %target_id, error = %e, "device SBOM persist failed");
|
||||||
|
}
|
||||||
|
}
|
||||||
// No code to scan. DAST is attempted for a target the matrix
|
// No code to scan. DAST is attempted for a target the matrix
|
||||||
// plans it for, and for a migrated DAST target, which carries no
|
// plans it for, and for a migrated DAST target, which carries no
|
||||||
// artifacts at all and relies on its DastTarget row. Anywhere
|
// artifacts at all and relies on its DastTarget row. Anywhere
|
||||||
@@ -1992,6 +2008,12 @@ impl PipelineOrchestrator {
|
|||||||
// first, as in a code scan (#820, #825).
|
// first, as in a code scan (#820, #825).
|
||||||
let mut left_out = LeftOut::default();
|
let mut left_out = LeftOut::default();
|
||||||
for a in &sources {
|
for a in &sources {
|
||||||
|
// A TIA export's block code is not read yet (#1093): the run says
|
||||||
|
// what it holds instead of finding nothing in it.
|
||||||
|
if a.plc.as_ref().map(|p| p.format) == Some(PlcFormat::TiaExport) {
|
||||||
|
self.note_tia_export(scan_run_id, a).await;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
let Some(path) = ingest_set.get(&a.id).and_then(|ia| ia.working_path.clone()) else {
|
let Some(path) = ingest_set.get(&a.id).and_then(|ia| ia.working_path.clone()) else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
@@ -2137,7 +2159,7 @@ impl PipelineOrchestrator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
all_sbom.extend(crate::pipeline::sbom::devices::entries(
|
all_sbom.extend(crate::pipeline::sbom::devices::entries(
|
||||||
&target.devices,
|
&target.target_devices(),
|
||||||
target_id,
|
target_id,
|
||||||
));
|
));
|
||||||
if !all_sbom.is_empty() {
|
if !all_sbom.is_empty() {
|
||||||
@@ -2151,6 +2173,82 @@ impl PipelineOrchestrator {
|
|||||||
Ok(new_count)
|
Ok(new_count)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What a TIA export holds that this run does not analyse (#1090): its
|
||||||
|
/// blocks' code (until #1093), its know-how-protected blocks, and the
|
||||||
|
/// devices it names that cannot be matched against advisories. Its
|
||||||
|
/// matchable devices are in the SBOM through
|
||||||
|
/// [`compliance_core::models::OnboardedTarget::target_devices`].
|
||||||
|
async fn note_tia_export(&self, scan_run_id: &str, export: &Artifact) {
|
||||||
|
let name = export
|
||||||
|
.display_name
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| export.source_ref.clone());
|
||||||
|
let read = export
|
||||||
|
.stored_path
|
||||||
|
.as_deref()
|
||||||
|
.ok_or(compliance_core::models::TiaBundleError::NoManifest)
|
||||||
|
.and_then(|p| crate::pipeline::plc::tia::read_manifest(std::path::Path::new(p)));
|
||||||
|
let manifest = match read {
|
||||||
|
Ok(manifest) => manifest,
|
||||||
|
Err(e) => {
|
||||||
|
// Read at upload, so only a file lost since gets here.
|
||||||
|
tracing::warn!(scan_run_id, export = %name, error = %e, "TIA export not readable");
|
||||||
|
self.skip_stage(
|
||||||
|
scan_run_id,
|
||||||
|
SkippedStage::new(
|
||||||
|
"plc_tia_export",
|
||||||
|
SkipCode::ArtifactNotIngested,
|
||||||
|
format!("{name} could not be read: {e}"),
|
||||||
|
)
|
||||||
|
.about(name),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Some(blocks) = crate::pipeline::plc::tia::blocks_not_analysed(&manifest) {
|
||||||
|
self.skip_stage(
|
||||||
|
scan_run_id,
|
||||||
|
SkippedStage::new(
|
||||||
|
"plc_tia_blocks",
|
||||||
|
SkipCode::PlcBlocksNotAnalysed,
|
||||||
|
format!("the code of the blocks in {name} is not analysed yet: {blocks}"),
|
||||||
|
)
|
||||||
|
.about(blocks),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
let protected = component_list(&manifest.protected_blocks());
|
||||||
|
if !protected.is_empty() {
|
||||||
|
self.skip_stage(
|
||||||
|
scan_run_id,
|
||||||
|
SkippedStage::new(
|
||||||
|
"plc_protected_blocks",
|
||||||
|
SkipCode::ProtectedBlocks,
|
||||||
|
format!("know-how-protected blocks in {name} cannot be analysed: {protected}"),
|
||||||
|
)
|
||||||
|
.about(protected),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
let unmatched = component_list(&manifest.devices().unmatched);
|
||||||
|
if !unmatched.is_empty() {
|
||||||
|
self.skip_stage(
|
||||||
|
scan_run_id,
|
||||||
|
SkippedStage::new(
|
||||||
|
"plc_devices_unmatched",
|
||||||
|
SkipCode::DevicesUnmatched,
|
||||||
|
format!(
|
||||||
|
"devices in {name} without a Siemens order number or firmware are not \
|
||||||
|
matched against advisories: {unmatched}"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.about(unmatched),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Provision-and-test (#183): instantiate the target's control logic on an
|
/// Provision-and-test (#183): instantiate the target's control logic on an
|
||||||
/// ephemeral soft-PLC (OpenPLC), start it, probe the provisioned Modbus
|
/// ephemeral soft-PLC (OpenPLC), start it, probe the provisioned Modbus
|
||||||
/// endpoint, and tear the instance down. Used when a PLC/SPS target has the
|
/// endpoint, and tear the instance down. Used when a PLC/SPS target has the
|
||||||
@@ -2308,9 +2406,8 @@ impl PipelineOrchestrator {
|
|||||||
scan_run_id: &str,
|
scan_run_id: &str,
|
||||||
mut entries: Vec<SbomEntry>,
|
mut entries: Vec<SbomEntry>,
|
||||||
) -> Result<(), AgentError> {
|
) -> Result<(), AgentError> {
|
||||||
if entries.is_empty() {
|
// Empty entries are stored too: the components and alerts of the
|
||||||
return Ok(());
|
// last scan are then gone (callers skip it when nothing was read).
|
||||||
}
|
|
||||||
crate::pipeline::component_changes::record(
|
crate::pipeline::component_changes::record(
|
||||||
&self.db,
|
&self.db,
|
||||||
scan_run_id,
|
scan_run_id,
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ pub mod parser;
|
|||||||
pub mod plcopen;
|
pub mod plcopen;
|
||||||
pub mod rules;
|
pub mod rules;
|
||||||
pub mod sbom;
|
pub mod sbom;
|
||||||
|
pub(crate) mod tia;
|
||||||
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,152 @@
|
|||||||
|
//! Reading a TIA export (#1090): the zip a TIA Portal connector uploads, with
|
||||||
|
//! its [`TiaManifest`] at the root. Only the manifest is read here; the block
|
||||||
|
//! exports beside it are unpacked by ingest like any PLC project.
|
||||||
|
|
||||||
|
use std::io::Read;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use compliance_core::models::tia_export::{MANIFEST_NAME, MAX_MANIFEST_BYTES};
|
||||||
|
use compliance_core::models::{TiaBundleError, TiaManifest};
|
||||||
|
|
||||||
|
/// Read the manifest of the TIA export at `bundle`.
|
||||||
|
///
|
||||||
|
/// The manifest is read up to [`MAX_MANIFEST_BYTES`], whatever size the zip
|
||||||
|
/// declares for it, so a forged entry cannot make this read more.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// [`TiaBundleError::NotZip`] when `bundle` is not a readable zip,
|
||||||
|
/// [`TiaBundleError::NoManifest`] without a `manifest.json` at its root, and
|
||||||
|
/// [`TiaManifest::parse`]'s refusals.
|
||||||
|
pub(crate) fn read_manifest(bundle: &Path) -> Result<TiaManifest, TiaBundleError> {
|
||||||
|
let file = std::fs::File::open(bundle).map_err(|_| TiaBundleError::NotZip)?;
|
||||||
|
let mut zip = zip::ZipArchive::new(file).map_err(|_| TiaBundleError::NotZip)?;
|
||||||
|
let entry = match zip.by_name(MANIFEST_NAME) {
|
||||||
|
Ok(entry) => entry,
|
||||||
|
Err(zip::result::ZipError::FileNotFound) => return Err(TiaBundleError::NoManifest),
|
||||||
|
Err(e) => return Err(TiaBundleError::ManifestInvalid(e.to_string())),
|
||||||
|
};
|
||||||
|
let mut json = Vec::new();
|
||||||
|
// One byte more than allowed, so an oversized manifest is told apart from
|
||||||
|
// one exactly at the limit.
|
||||||
|
entry
|
||||||
|
.take(MAX_MANIFEST_BYTES + 1)
|
||||||
|
.read_to_end(&mut json)
|
||||||
|
.map_err(|e| TiaBundleError::ManifestInvalid(e.to_string()))?;
|
||||||
|
TiaManifest::parse(&json)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The blocks of `manifest` whose code is analysed by no stage yet (all
|
||||||
|
/// readable ones, until #1093): how many, and in which languages, as a run
|
||||||
|
/// note's subject (`12 (FBD, LAD, SCL)`). `None` when there are none.
|
||||||
|
pub(crate) fn blocks_not_analysed(manifest: &TiaManifest) -> Option<String> {
|
||||||
|
let readable: Vec<_> = manifest.blocks.iter().filter(|b| !b.protected).collect();
|
||||||
|
if readable.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let languages: std::collections::BTreeSet<String> = readable
|
||||||
|
.iter()
|
||||||
|
.filter_map(|b| b.language.as_deref())
|
||||||
|
.map(str::to_ascii_uppercase)
|
||||||
|
.collect();
|
||||||
|
let languages = languages.into_iter().collect::<Vec<_>>().join(", ");
|
||||||
|
Some(if languages.is_empty() {
|
||||||
|
readable.len().to_string()
|
||||||
|
} else {
|
||||||
|
format!("{} ({languages})", readable.len())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[allow(clippy::unwrap_used)]
|
||||||
|
pub(crate) mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::io::Write;
|
||||||
|
|
||||||
|
/// A fresh directory for one test's files.
|
||||||
|
pub(crate) fn scratch() -> std::path::PathBuf {
|
||||||
|
let dir = std::env::temp_dir().join(format!("tia-{}", uuid::Uuid::new_v4()));
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
dir
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A TIA export zip with `files` (name, content) in `dir`.
|
||||||
|
pub(crate) fn bundle(dir: &Path, files: &[(&str, &[u8])]) -> std::path::PathBuf {
|
||||||
|
let path = dir.join("linie1.tia-export.zip");
|
||||||
|
let mut zip = zip::ZipWriter::new(std::fs::File::create(&path).unwrap());
|
||||||
|
for (name, content) in files {
|
||||||
|
zip.start_file(*name, zip::write::SimpleFileOptions::default())
|
||||||
|
.unwrap();
|
||||||
|
zip.write_all(content).unwrap();
|
||||||
|
}
|
||||||
|
zip.finish().unwrap();
|
||||||
|
path
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A manifest with one CPU, one GSD device and three blocks, one of them
|
||||||
|
/// protected.
|
||||||
|
pub(crate) const MANIFEST: &str = r#"{
|
||||||
|
"bundle_version": 1,
|
||||||
|
"tia_version": "V20",
|
||||||
|
"project": {"name": "Linie 1"},
|
||||||
|
"devices": [
|
||||||
|
{"name": "PLC_1", "role": "cpu",
|
||||||
|
"type_identifier": "OrderNumber:6ES7 511-1AK02-0AB0/V2.9"},
|
||||||
|
{"name": "Drittgeraet", "role": "module", "type_identifier": "GSD:VENDOR.XML/DAP1"}
|
||||||
|
],
|
||||||
|
"blocks": [
|
||||||
|
{"device": "PLC_1", "name": "Main", "kind": "ob", "language": "LAD",
|
||||||
|
"file": "blocks/PLC_1/Main.xml"},
|
||||||
|
{"device": "PLC_1", "name": "Pumpe", "kind": "fb", "language": "scl",
|
||||||
|
"file": "blocks/PLC_1/Pumpe.scl"},
|
||||||
|
{"device": "PLC_1", "name": "FB_42", "kind": "fb", "protected": true}
|
||||||
|
]
|
||||||
|
}"#;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_manifest_is_read_from_the_root_of_the_zip() {
|
||||||
|
let dir = scratch();
|
||||||
|
let path = bundle(
|
||||||
|
&dir,
|
||||||
|
&[
|
||||||
|
("manifest.json", MANIFEST.as_bytes()),
|
||||||
|
("blocks/PLC_1/Main.xml", b"<Document/>"),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
let manifest = read_manifest(&path).unwrap();
|
||||||
|
assert_eq!(manifest.project.name, "Linie 1");
|
||||||
|
assert_eq!(
|
||||||
|
blocks_not_analysed(&manifest).as_deref(),
|
||||||
|
Some("2 (LAD, SCL)")
|
||||||
|
);
|
||||||
|
assert_eq!(manifest.protected_blocks(), ["PLC_1/FB_42"]);
|
||||||
|
std::fs::remove_dir_all(&dir).ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_bundle_that_is_not_one_is_refused_with_its_reason() {
|
||||||
|
let dir = scratch();
|
||||||
|
let not_zip = dir.join("x.zip");
|
||||||
|
std::fs::write(¬_zip, b"plain text").unwrap();
|
||||||
|
assert_eq!(read_manifest(¬_zip), Err(TiaBundleError::NotZip));
|
||||||
|
let nested = bundle(&dir, &[("export/manifest.json", MANIFEST.as_bytes())]);
|
||||||
|
assert_eq!(read_manifest(&nested), Err(TiaBundleError::NoManifest));
|
||||||
|
let huge = vec![b' '; MAX_MANIFEST_BYTES as usize + 10];
|
||||||
|
let oversized = bundle(&dir, &[("manifest.json", &huge)]);
|
||||||
|
assert_eq!(
|
||||||
|
read_manifest(&oversized),
|
||||||
|
Err(TiaBundleError::ManifestTooLarge)
|
||||||
|
);
|
||||||
|
std::fs::remove_dir_all(&dir).ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_protected_blocks_leave_nothing_unanalysed() {
|
||||||
|
let mut manifest = TiaManifest::parse(MANIFEST.as_bytes()).unwrap();
|
||||||
|
manifest.blocks.retain(|b| b.protected);
|
||||||
|
assert_eq!(blocks_not_analysed(&manifest), None);
|
||||||
|
manifest.blocks[0].protected = false;
|
||||||
|
manifest.blocks[0].language = None;
|
||||||
|
assert_eq!(blocks_not_analysed(&manifest).as_deref(), Some("1"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -65,8 +65,9 @@ pub struct RepoView {
|
|||||||
pub supplier_sboms: Vec<(std::path::PathBuf, String)>,
|
pub supplier_sboms: Vec<(std::path::PathBuf, String)>,
|
||||||
/// Who supplies the component, for one bought in (#1025).
|
/// Who supplies the component, for one bought in (#1025).
|
||||||
pub supplier: Option<compliance_core::models::SupplierComponent>,
|
pub supplier: Option<compliance_core::models::SupplierComponent>,
|
||||||
/// The Siemens controllers the target runs on (SPS item 4a).
|
/// The Siemens controllers the target runs on (SPS item 4a): entered,
|
||||||
pub devices: Vec<compliance_core::models::PlcDevice>,
|
/// and declared by its TIA exports (#1090).
|
||||||
|
pub devices: Vec<compliance_core::models::TargetDevice>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RepoView {
|
impl RepoView {
|
||||||
@@ -104,7 +105,7 @@ impl RepoView {
|
|||||||
build_outputs: Vec::new(),
|
build_outputs: Vec::new(),
|
||||||
supplier_sboms: Vec::new(),
|
supplier_sboms: Vec::new(),
|
||||||
supplier: target.supplier.clone(),
|
supplier: target.supplier.clone(),
|
||||||
devices: target.devices.clone(),
|
devices: target.target_devices(),
|
||||||
};
|
};
|
||||||
if let Some(git) = &code.git {
|
if let Some(git) = &code.git {
|
||||||
view.default_branch = git.default_branch.clone();
|
view.default_branch = git.default_branch.clone();
|
||||||
|
|||||||
@@ -1,23 +1,32 @@
|
|||||||
//! The Siemens controllers a target runs on ([`PlcDevice`], SPS item 4a) as
|
//! The Siemens controllers a target runs on ([`PlcDevice`], SPS item 4a) as
|
||||||
//! SBOM entries: one per device, named and versioned as the customer
|
//! 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
|
//! entered it or a TIA export declares it (#1090), with the order number the
|
||||||
//! (matched in [`crate::pipeline::csaf_match`]).
|
//! vendor's CSAF advisories name it by (matched in
|
||||||
|
//! [`crate::pipeline::csaf_match`]).
|
||||||
|
|
||||||
use compliance_core::models::{PlcDevice, SbomEntry};
|
use compliance_core::models::{SbomEntry, TargetDevice};
|
||||||
|
|
||||||
/// The package manager of a device entry.
|
/// The package manager of a device entry.
|
||||||
pub(crate) const DEVICE_MANAGER: &str = "siemens-device";
|
pub(crate) const DEVICE_MANAGER: &str = "siemens-device";
|
||||||
|
|
||||||
/// The SBOM entries of target `repo_id`'s `devices`. A device is named by its
|
/// The SBOM entries of target `repo_id`'s devices
|
||||||
/// order number, so two devices of one type at one firmware are one entry;
|
/// ([`compliance_core::models::OnboardedTarget::target_devices`]). A device
|
||||||
/// its label, if any, is kept as evidence.
|
/// is named by its order number, so two devices of one type at one firmware
|
||||||
pub(crate) fn entries(devices: &[PlcDevice], repo_id: &str) -> Vec<SbomEntry> {
|
/// are one entry; where it is known from, and its label, are kept as
|
||||||
|
/// evidence.
|
||||||
|
pub(crate) fn entries(devices: &[TargetDevice], repo_id: &str) -> Vec<SbomEntry> {
|
||||||
let mut entries: Vec<SbomEntry> = Vec::with_capacity(devices.len());
|
let mut entries: Vec<SbomEntry> = Vec::with_capacity(devices.len());
|
||||||
for device in devices {
|
for TargetDevice {
|
||||||
let evidence = device.label.as_deref().map_or_else(
|
device,
|
||||||
|| "entered with the target".to_string(),
|
exported_in,
|
||||||
|l| format!("entered as {l}"),
|
} in devices
|
||||||
);
|
{
|
||||||
|
let evidence = match (exported_in, device.label.as_deref()) {
|
||||||
|
(Some(file), Some(label)) => format!("configured as {label} in the TIA export {file}"),
|
||||||
|
(Some(file), None) => format!("configured in the TIA export {file}"),
|
||||||
|
(None, Some(label)) => format!("entered as {label}"),
|
||||||
|
(None, None) => "entered with the target".to_string(),
|
||||||
|
};
|
||||||
if let Some(known) = entries
|
if let Some(known) = entries
|
||||||
.iter_mut()
|
.iter_mut()
|
||||||
.find(|e| e.name == device.order_number && e.version == device.firmware)
|
.find(|e| e.name == device.order_number && e.version == device.firmware)
|
||||||
@@ -44,6 +53,7 @@ pub(crate) fn entries(devices: &[PlcDevice], repo_id: &str) -> Vec<SbomEntry> {
|
|||||||
#[allow(clippy::unwrap_used)]
|
#[allow(clippy::unwrap_used)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use compliance_core::models::PlcDevice;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn each_device_type_and_firmware_is_one_entry() {
|
fn each_device_type_and_firmware_is_one_entry() {
|
||||||
@@ -53,6 +63,7 @@ mod tests {
|
|||||||
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.5", None).unwrap(),
|
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.5", None).unwrap(),
|
||||||
];
|
];
|
||||||
|
|
||||||
|
let devices: Vec<TargetDevice> = devices.into_iter().map(TargetDevice::from).collect();
|
||||||
let entries = entries(&devices, "t");
|
let entries = entries(&devices, "t");
|
||||||
|
|
||||||
assert_eq!(entries.len(), 2);
|
assert_eq!(entries.len(), 2);
|
||||||
@@ -69,4 +80,16 @@ mod tests {
|
|||||||
assert_eq!(first.evidence, ["entered as Zelle 1", "entered as Zelle 2"]);
|
assert_eq!(first.evidence, ["entered as Zelle 1", "entered as Zelle 2"]);
|
||||||
assert_eq!(entries[1].evidence, ["entered with the target"]);
|
assert_eq!(entries[1].evidence, ["entered with the target"]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_exported_device_says_which_export_configures_it() {
|
||||||
|
let exported = TargetDevice {
|
||||||
|
device: PlcDevice::new("6ES7511-1AK02-0AB0", "2.9", Some("PLC_1")).unwrap(),
|
||||||
|
exported_in: Some("linie1.tia-export.zip".into()),
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
entries(&[exported], "t")[0].evidence,
|
||||||
|
["configured as PLC_1 in the TIA export linie1.tia-export.zip"]
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -118,6 +118,72 @@ pub struct EntitlementCheck {
|
|||||||
pub expires_at: Option<String>,
|
pub expires_at: Option<String>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub reason: Option<String>,
|
pub reason: Option<String>,
|
||||||
|
/// The workspace's branding (tenant-registry#155); absent when there is
|
||||||
|
/// nothing to show.
|
||||||
|
#[serde(default)]
|
||||||
|
pub branding: Option<Branding>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A workspace's branding as the registry derived or an admin set it
|
||||||
|
/// (tenant-registry#155): its CI colour, which frames every page, its logo,
|
||||||
|
/// and whether its admins have yet to acknowledge a derived one.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
|
||||||
|
pub struct Branding {
|
||||||
|
/// `#rrggbb`, or null.
|
||||||
|
#[serde(default)]
|
||||||
|
pub color: Option<String>,
|
||||||
|
/// The SHA-256 (hex) of the stored logo, or null when there is none.
|
||||||
|
#[serde(default)]
|
||||||
|
pub logo_etag: Option<String>,
|
||||||
|
/// Whether a derived branding waits for an admin's "Passt".
|
||||||
|
#[serde(default)]
|
||||||
|
pub notice: bool,
|
||||||
|
/// The domain it was derived from; present while `notice` is.
|
||||||
|
#[serde(default)]
|
||||||
|
pub domain: Option<String>,
|
||||||
|
/// The workspace's name, shown beside the logo.
|
||||||
|
#[serde(default)]
|
||||||
|
pub name: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Branding {
|
||||||
|
/// The frame colour as `#rrggbb` in lower case; anything else is no
|
||||||
|
/// frame, so a malformed value can never reach a style.
|
||||||
|
pub fn frame_color(&self) -> Option<String> {
|
||||||
|
let c = self.color.as_deref()?.trim();
|
||||||
|
let hex = c.strip_prefix('#')?;
|
||||||
|
(hex.len() == 6 && hex.bytes().all(|b| b.is_ascii_hexdigit()))
|
||||||
|
.then(|| c.to_ascii_lowercase())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The logo's ETag when it is a SHA-256 in hex; anything else is no logo.
|
||||||
|
pub fn logo_etag(&self) -> Option<&str> {
|
||||||
|
self.logo_etag
|
||||||
|
.as_deref()
|
||||||
|
.filter(|e| e.len() == 64 && e.bytes().all(|b| b.is_ascii_hexdigit()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why the registry did not record an admin's "Passt".
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum AckRefusal {
|
||||||
|
/// The user is no IT admin or owner of the workspace (403 `not_admin`).
|
||||||
|
NotAdmin,
|
||||||
|
/// The registry could not be asked, or answered something else.
|
||||||
|
Failed(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The largest logo the agent takes from the registry, which stores 256 px
|
||||||
|
/// PNGs: far below this.
|
||||||
|
const MAX_LOGO_BYTES: usize = 1 << 20;
|
||||||
|
|
||||||
|
/// Whether `tenant_id` may stand in a registry path: the registry's ids are
|
||||||
|
/// UUIDs, so anything else is refused before a request is made.
|
||||||
|
fn path_safe(tenant_id: &str) -> bool {
|
||||||
|
!tenant_id.is_empty()
|
||||||
|
&& tenant_id
|
||||||
|
.bytes()
|
||||||
|
.all(|b| b.is_ascii_alphanumeric() || b == b'-')
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EntitlementCheck {
|
impl EntitlementCheck {
|
||||||
@@ -134,6 +200,13 @@ impl EntitlementCheck {
|
|||||||
self.limit("included_targets")
|
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
|
/// The plan's monthly quota and the customer's Prüftag cap (t72), from
|
||||||
/// `limits.monthly_pruefungen` and `limits.prueftag_cap`; a missing or
|
/// `limits.monthly_pruefungen` and `limits.prueftag_cap`; a missing or
|
||||||
/// null key is no limit.
|
/// null key is no limit.
|
||||||
@@ -305,6 +378,9 @@ pub struct RegistryClient {
|
|||||||
/// API-key verdicts, valid and invalid, keyed by the key's SHA-256 (never
|
/// API-key verdicts, valid and invalid, keyed by the key's SHA-256 (never
|
||||||
/// the key itself), for [`API_KEY_TTL`].
|
/// the key itself), for [`API_KEY_TTL`].
|
||||||
api_keys: DashMap<String, (Instant, ApiKeyVerify)>,
|
api_keys: DashMap<String, (Instant, ApiKeyVerify)>,
|
||||||
|
/// Each tenant's logo with its ETag, kept until the registry names
|
||||||
|
/// another (tenant-registry#155).
|
||||||
|
logos: DashMap<String, (String, axum::body::Bytes)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::fmt::Debug for RegistryClient {
|
impl std::fmt::Debug for RegistryClient {
|
||||||
@@ -348,6 +424,7 @@ impl RegistryClient {
|
|||||||
cache: DashMap::new(),
|
cache: DashMap::new(),
|
||||||
projects: DashMap::new(),
|
projects: DashMap::new(),
|
||||||
api_keys: DashMap::new(),
|
api_keys: DashMap::new(),
|
||||||
|
logos: DashMap::new(),
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -469,6 +546,113 @@ impl RegistryClient {
|
|||||||
Ok(check)
|
Ok(check)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The workspace's logo with the ETag `etag`, as a PNG, or `None` when
|
||||||
|
/// the registry has none. Kept per tenant and asked for again only when
|
||||||
|
/// the registry names another ETag; then with `If-None-Match`, so an
|
||||||
|
/// unchanged logo is not sent twice.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// When the registry cannot be asked or answers with something other
|
||||||
|
/// than a PNG of at most 1 MiB.
|
||||||
|
pub async fn branding_logo(
|
||||||
|
&self,
|
||||||
|
tenant_id: &str,
|
||||||
|
etag: &str,
|
||||||
|
) -> Result<Option<axum::body::Bytes>, String> {
|
||||||
|
let cached = self
|
||||||
|
.logos
|
||||||
|
.get(tenant_id)
|
||||||
|
.map(|hit| (hit.0.clone(), hit.1.clone()));
|
||||||
|
if let Some((tag, png)) = &cached {
|
||||||
|
if tag == etag {
|
||||||
|
return Ok(Some(png.clone()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !path_safe(tenant_id) {
|
||||||
|
return Err("tenant id not usable in a path".into());
|
||||||
|
}
|
||||||
|
let mut rb = self
|
||||||
|
.request(
|
||||||
|
reqwest::Method::GET,
|
||||||
|
&format!("/v1/tenants/{tenant_id}/branding/logo"),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
if let Some((tag, _)) = &cached {
|
||||||
|
rb = rb.header(reqwest::header::IF_NONE_MATCH, format!("\"{tag}\""));
|
||||||
|
}
|
||||||
|
let resp = rb
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("logo request failed: {e}"))?;
|
||||||
|
match resp.status() {
|
||||||
|
reqwest::StatusCode::NOT_MODIFIED => Ok(cached.map(|(_, png)| png)),
|
||||||
|
reqwest::StatusCode::NOT_FOUND => {
|
||||||
|
self.logos.remove(tenant_id);
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
status if status.is_success() => {
|
||||||
|
let is_png = resp
|
||||||
|
.headers()
|
||||||
|
.get(reqwest::header::CONTENT_TYPE)
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.is_some_and(|v| v.starts_with("image/png"));
|
||||||
|
if !is_png {
|
||||||
|
return Err("logo is not a PNG".into());
|
||||||
|
}
|
||||||
|
let tag = resp
|
||||||
|
.headers()
|
||||||
|
.get(reqwest::header::ETAG)
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.map(|v| v.trim_start_matches("W/").trim_matches('"').to_string())
|
||||||
|
.unwrap_or_else(|| etag.to_string());
|
||||||
|
let png = resp
|
||||||
|
.bytes()
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("logo not read: {e}"))?;
|
||||||
|
if png.len() > MAX_LOGO_BYTES {
|
||||||
|
return Err("logo larger than 1 MiB".into());
|
||||||
|
}
|
||||||
|
self.logos.insert(tenant_id.to_string(), (tag, png.clone()));
|
||||||
|
Ok(Some(png))
|
||||||
|
}
|
||||||
|
status => Err(format!("logo request returned {status}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Record an admin's "Passt" on the workspace's derived branding
|
||||||
|
/// (`POST /v1/tenants/{id}/branding/ack`) and drop the cached entitlement
|
||||||
|
/// answers, so the notice goes with the next check.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// [`AckRefusal::NotAdmin`] when the registry does not count `user_id` as
|
||||||
|
/// an IT admin or owner of the tenant; [`AckRefusal::Failed`] otherwise.
|
||||||
|
pub async fn ack_branding(&self, tenant_id: &str, user_id: &str) -> Result<(), AckRefusal> {
|
||||||
|
if !path_safe(tenant_id) {
|
||||||
|
return Err(AckRefusal::Failed("tenant id not usable in a path".into()));
|
||||||
|
}
|
||||||
|
let resp = self
|
||||||
|
.request(
|
||||||
|
reqwest::Method::POST,
|
||||||
|
&format!("/v1/tenants/{tenant_id}/branding/ack"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(AckRefusal::Failed)?
|
||||||
|
.json(&serde_json::json!({ "user_id": user_id }))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| AckRefusal::Failed(format!("ack failed: {e}")))?;
|
||||||
|
match resp.status() {
|
||||||
|
status if status.is_success() => {
|
||||||
|
self.invalidate(tenant_id);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
reqwest::StatusCode::FORBIDDEN => Err(AckRefusal::NotAdmin),
|
||||||
|
status => Err(AckRefusal::Failed(format!("ack returned {status}"))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Drop the cached answer for a tenant (after a platform lifecycle call).
|
/// Drop the cached answer for a tenant (after a platform lifecycle call).
|
||||||
pub fn invalidate(&self, tenant_id: &str) {
|
pub fn invalidate(&self, tenant_id: &str) {
|
||||||
self.cache
|
self.cache
|
||||||
@@ -877,6 +1061,27 @@ mod tests {
|
|||||||
assert_eq!(check(serde_json::Value::Null).included_targets(), None);
|
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]
|
#[test]
|
||||||
fn the_plan_sets_the_quota_and_the_cap() {
|
fn the_plan_sets_the_quota_and_the_cap() {
|
||||||
let check: EntitlementCheck = serde_json::from_value(serde_json::json!({
|
let check: EntitlementCheck = serde_json::from_value(serde_json::json!({
|
||||||
@@ -935,6 +1140,7 @@ mod tests {
|
|||||||
cache: DashMap::new(),
|
cache: DashMap::new(),
|
||||||
projects: DashMap::new(),
|
projects: DashMap::new(),
|
||||||
api_keys: DashMap::new(),
|
api_keys: DashMap::new(),
|
||||||
|
logos: DashMap::new(),
|
||||||
};
|
};
|
||||||
|
|
||||||
let started = Instant::now();
|
let started = Instant::now();
|
||||||
@@ -991,6 +1197,7 @@ mod tests {
|
|||||||
cache: DashMap::new(),
|
cache: DashMap::new(),
|
||||||
projects: DashMap::new(),
|
projects: DashMap::new(),
|
||||||
api_keys: DashMap::new(),
|
api_keys: DashMap::new(),
|
||||||
|
logos: DashMap::new(),
|
||||||
};
|
};
|
||||||
(client, calls, down)
|
(client, calls, down)
|
||||||
}
|
}
|
||||||
@@ -1061,4 +1268,106 @@ mod tests {
|
|||||||
assert!(client.api_keys.contains_key(&key_digest("bp_good")));
|
assert!(client.api_keys.contains_key(&key_digest("bp_good")));
|
||||||
assert!(client.api_keys.iter().all(|e| !e.key().contains("bp_")));
|
assert!(client.api_keys.iter().all(|e| !e.key().contains("bp_")));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A registry with one tenant's logo (ETag `"aa…"`, honouring
|
||||||
|
/// If-None-Match) and an ack endpoint that takes only `u-admin`; the
|
||||||
|
/// number of logo bodies it sent is counted.
|
||||||
|
async fn branding_registry() -> (RegistryClient, Arc<std::sync::atomic::AtomicUsize>) {
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
let sent = Arc::new(AtomicUsize::new(0));
|
||||||
|
let s = sent.clone();
|
||||||
|
let tag = "a".repeat(64);
|
||||||
|
let quoted = format!("\"{tag}\"");
|
||||||
|
let app = axum::Router::new()
|
||||||
|
.route(
|
||||||
|
"/v1/tenants/{id}/branding/logo",
|
||||||
|
axum::routing::get(
|
||||||
|
move |axum::extract::Path(id): axum::extract::Path<String>,
|
||||||
|
headers: axum::http::HeaderMap| {
|
||||||
|
let (s, quoted) = (s.clone(), quoted.clone());
|
||||||
|
async move {
|
||||||
|
use axum::response::IntoResponse;
|
||||||
|
if id != "t-1" {
|
||||||
|
return axum::http::StatusCode::NOT_FOUND.into_response();
|
||||||
|
}
|
||||||
|
if headers.get("if-none-match").and_then(|v| v.to_str().ok())
|
||||||
|
== Some(quoted.as_str())
|
||||||
|
{
|
||||||
|
return axum::http::StatusCode::NOT_MODIFIED.into_response();
|
||||||
|
}
|
||||||
|
s.fetch_add(1, Ordering::SeqCst);
|
||||||
|
(
|
||||||
|
[("content-type", "image/png"), ("etag", quoted.as_str())],
|
||||||
|
b"\x89PNG fake".to_vec(),
|
||||||
|
)
|
||||||
|
.into_response()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/v1/tenants/{id}/branding/ack",
|
||||||
|
axum::routing::post(
|
||||||
|
|axum::Json(body): axum::Json<serde_json::Value>| async move {
|
||||||
|
if body["user_id"] == "u-admin" {
|
||||||
|
axum::http::StatusCode::NO_CONTENT
|
||||||
|
} else {
|
||||||
|
axum::http::StatusCode::FORBIDDEN
|
||||||
|
}
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
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.unwrap() });
|
||||||
|
let client = RegistryClient {
|
||||||
|
base_url: format!("http://{addr}"),
|
||||||
|
product: "pruefwerk".into(),
|
||||||
|
http: reqwest::Client::new(),
|
||||||
|
token_url: None,
|
||||||
|
client_id: None,
|
||||||
|
client_secret: None,
|
||||||
|
token: Mutex::new(None),
|
||||||
|
cache: DashMap::new(),
|
||||||
|
projects: DashMap::new(),
|
||||||
|
api_keys: DashMap::new(),
|
||||||
|
logos: DashMap::new(),
|
||||||
|
};
|
||||||
|
(client, sent)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_logo_is_fetched_once_per_etag_and_none_is_none() {
|
||||||
|
use std::sync::atomic::Ordering;
|
||||||
|
// Arrange
|
||||||
|
let (client, sent) = branding_registry().await;
|
||||||
|
let tag = "a".repeat(64);
|
||||||
|
|
||||||
|
// Act: twice with the same ETag, then with another one.
|
||||||
|
let first = client.branding_logo("t-1", &tag).await.unwrap();
|
||||||
|
let again = client.branding_logo("t-1", &tag).await.unwrap();
|
||||||
|
let other = client.branding_logo("t-1", &"b".repeat(64)).await.unwrap();
|
||||||
|
|
||||||
|
// Assert: one body sent; the other ETag was answered 304 from the
|
||||||
|
// cached PNG; a tenant without a logo has none.
|
||||||
|
assert_eq!(first.as_deref(), Some(&b"\x89PNG fake"[..]));
|
||||||
|
assert_eq!(again, first);
|
||||||
|
assert_eq!(other, first);
|
||||||
|
assert_eq!(sent.load(Ordering::SeqCst), 1);
|
||||||
|
assert_eq!(client.branding_logo("t-2", &tag).await.unwrap(), None);
|
||||||
|
assert!(
|
||||||
|
client.branding_logo("../x", &tag).await.is_err(),
|
||||||
|
"no path from an id"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn only_an_admin_the_registry_knows_acknowledges() {
|
||||||
|
let (client, _) = branding_registry().await;
|
||||||
|
assert_eq!(client.ack_branding("t-1", "u-admin").await, Ok(()));
|
||||||
|
assert_eq!(
|
||||||
|
client.ack_branding("t-1", "u-member").await,
|
||||||
|
Err(AckRefusal::NotAdmin)
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -16,24 +16,101 @@ use crate::classify::{classify_target, MockFirmwareDetector};
|
|||||||
use crate::database::Database;
|
use crate::database::Database;
|
||||||
use crate::error::AgentError;
|
use crate::error::AgentError;
|
||||||
|
|
||||||
|
/// Whether one more counted target fits under `cap`: the active targets
|
||||||
|
/// other than demo ones are fewer.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// [`AgentError::TargetLimit`] when they are not; a database error.
|
||||||
|
async fn room_for_one(db: &Database, cap: u32) -> Result<(), AgentError> {
|
||||||
|
let counted = db
|
||||||
|
.onboarded_targets()
|
||||||
|
.count_documents(doc! { "archived_at": null, "demo": { "$ne": true } })
|
||||||
|
.await?;
|
||||||
|
if counted >= u64::from(cap) {
|
||||||
|
return Err(AgentError::TargetLimit(cap));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Make a demo target the tenant's own before its artifacts change: from
|
||||||
|
/// then on it counts under the plan's cap like any other target. Without
|
||||||
|
/// that, a demo target pointed at the tenant's own code would sit outside
|
||||||
|
/// the cap. A target that is not a demo one is left as it is, and an
|
||||||
|
/// archived one is not checked against the cap (it does not count yet).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// [`AgentError::TargetLimit`] when the plan has no room for one more
|
||||||
|
/// counted target; the target then stays a demo one. A database error.
|
||||||
|
pub async fn claim_demo(
|
||||||
|
agent: &ComplianceAgent,
|
||||||
|
db: &Database,
|
||||||
|
tenant_id: &str,
|
||||||
|
target: &OnboardedTarget,
|
||||||
|
) -> Result<(), AgentError> {
|
||||||
|
let Some(id) = target.id.filter(|_| target.demo) else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
if target.archived_at.is_none() {
|
||||||
|
if let Some(cap) = agent.plan(tenant_id).await.and_then(|p| p.target_cap()) {
|
||||||
|
room_for_one(db, cap).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
db.onboarded_targets()
|
||||||
|
.update_one(doc! { "_id": id }, doc! { "$unset": { "demo": "" } })
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether two artifact lists point at the same sources: the same kinds and
|
||||||
|
/// references, in any order. Credentials, branches and scan state may
|
||||||
|
/// differ; the dashboard's editor sends every artifact on each save.
|
||||||
|
pub fn same_sources(a: &[Artifact], b: &[Artifact]) -> bool {
|
||||||
|
let mut taken = vec![false; b.len()];
|
||||||
|
a.len() == b.len()
|
||||||
|
&& a.iter().all(|x| {
|
||||||
|
let found = (0..b.len())
|
||||||
|
.find(|&i| !taken[i] && b[i].kind == x.kind && b[i].source_ref == x.source_ref);
|
||||||
|
found.map(|i| taken[i] = true).is_some()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// Insert a new target for `tenant_id` and emit the `target.added` usage
|
/// 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(
|
pub async fn create_target(
|
||||||
agent: &ComplianceAgent,
|
agent: &ComplianceAgent,
|
||||||
db: &Database,
|
db: &Database,
|
||||||
tenant_id: &str,
|
tenant_id: &str,
|
||||||
mut target: OnboardedTarget,
|
mut target: OnboardedTarget,
|
||||||
) -> Result<OnboardedTarget, AgentError> {
|
) -> Result<OnboardedTarget, AgentError> {
|
||||||
|
// The plan is read once for the cap and the billing. Without an answer
|
||||||
|
// from the registry the target is added, as a scan then runs unmetered.
|
||||||
|
let plan = agent.plan(tenant_id).await;
|
||||||
|
// Demo targets are outside the cap: neither refused nor counted.
|
||||||
|
if let Some(cap) = plan.and_then(|p| p.target_cap()).filter(|_| !target.demo) {
|
||||||
|
room_for_one(db, cap).await?;
|
||||||
|
}
|
||||||
let res = db.onboarded_targets().insert_one(&target).await?;
|
let res = db.onboarded_targets().insert_one(&target).await?;
|
||||||
target.id = res.inserted_id.as_object_id();
|
target.id = res.inserted_id.as_object_id();
|
||||||
// A target beyond the plan's included ones is extra from the start (t72).
|
// A target beyond the plan's included ones is extra from the start (t72).
|
||||||
if let Some((_, billing)) = agent
|
if let Some(plan) = plan {
|
||||||
.refresh_billing(tenant_id, db)
|
if let Some((_, billing)) = agent
|
||||||
.await
|
.assign_billing(tenant_id, db, plan.billed_included())
|
||||||
.into_iter()
|
.await
|
||||||
.find(|(id, _)| Some(*id) == target.id)
|
.into_iter()
|
||||||
{
|
.find(|(id, _)| Some(*id) == target.id)
|
||||||
target.billing = billing;
|
{
|
||||||
|
target.billing = billing;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
|
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
|
||||||
agent.emit_usage(
|
agent.emit_usage(
|
||||||
@@ -200,6 +277,27 @@ pub async fn detect_target(
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_another_source_changes_a_targets_sources() {
|
||||||
|
let repo = Artifact::git_repo("https://git.example/demo.git", "main");
|
||||||
|
let site = Artifact::live_url("https://demo.example");
|
||||||
|
let other_branch = Artifact::git_repo("https://git.example/demo.git", "dev");
|
||||||
|
let own = Artifact::git_repo("https://git.example/own.git", "main");
|
||||||
|
let both = [repo.clone(), site.clone()];
|
||||||
|
let reordered = [site, repo.clone()];
|
||||||
|
let just_repo = std::slice::from_ref(&repo);
|
||||||
|
let repo_twice = [repo.clone(), repo.clone()];
|
||||||
|
|
||||||
|
assert!(same_sources(&both, &reordered));
|
||||||
|
assert!(
|
||||||
|
same_sources(just_repo, &[other_branch]),
|
||||||
|
"a branch is no new source"
|
||||||
|
);
|
||||||
|
assert!(!same_sources(just_repo, &[own]));
|
||||||
|
assert!(!same_sources(just_repo, &both));
|
||||||
|
assert!(!same_sources(&repo_twice, just_repo));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn uploaded_artifact_records_stored_path_for_file_kinds() {
|
fn uploaded_artifact_records_stored_path_for_file_kinds() {
|
||||||
let a = uploaded_artifact(
|
let a = uploaded_artifact(
|
||||||
|
|||||||
@@ -606,3 +606,110 @@ async fn a_targets_supplier_is_set_checked_and_removed() {
|
|||||||
|
|
||||||
server.cleanup().await;
|
server.cleanup().await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A TIA connector's export (#1090), read with TIA
|
||||||
|
/// `tia`, its CPU at firmware `firmware`.
|
||||||
|
fn tia_export(tia: &str, firmware: &str) -> Vec<u8> {
|
||||||
|
use std::io::Write;
|
||||||
|
let manifest = json!({
|
||||||
|
"bundle_version": 1,
|
||||||
|
"tia_version": tia,
|
||||||
|
"project": {"name": "Linie 1"},
|
||||||
|
"devices": [
|
||||||
|
{"name": "PLC_1", "role": "cpu",
|
||||||
|
"type_identifier": format!("OrderNumber:6ES7 511-1AK02-0AB0/V{firmware}")},
|
||||||
|
{"name": "Drittgeraet", "role": "module", "type_identifier": "GSD:VENDOR.XML/DAP1"}
|
||||||
|
],
|
||||||
|
"blocks": [
|
||||||
|
{"device": "PLC_1", "name": "Main", "kind": "ob", "language": "LAD",
|
||||||
|
"file": "blocks/PLC_1/Main.xml"},
|
||||||
|
{"device": "PLC_1", "name": "FB_42", "kind": "fb", "protected": true}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||||
|
let options = zip::write::SimpleFileOptions::default();
|
||||||
|
zip.start_file("manifest.json", options).unwrap();
|
||||||
|
zip.write_all(manifest.to_string().as_bytes()).unwrap();
|
||||||
|
zip.start_file("blocks/PLC_1/Main.xml", options).unwrap();
|
||||||
|
zip.write_all(b"<Document/>").unwrap();
|
||||||
|
zip.finish().unwrap().into_inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Upload `bytes` as a TIA export to target `id`.
|
||||||
|
async fn upload_tia_export(server: &TestServer, id: &str, bytes: Vec<u8>) -> reqwest::Response {
|
||||||
|
let form = reqwest::multipart::Form::new()
|
||||||
|
.text("kind", "plc_project")
|
||||||
|
.text("plc_format", "tia_export")
|
||||||
|
.part(
|
||||||
|
"file",
|
||||||
|
reqwest::multipart::Part::bytes(bytes).file_name("linie1.tia-export.zip"),
|
||||||
|
);
|
||||||
|
server
|
||||||
|
.client
|
||||||
|
.post(format!(
|
||||||
|
"{}/api/v1/targets/{id}/artifacts/upload",
|
||||||
|
server.base_url
|
||||||
|
))
|
||||||
|
.multipart(form)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_tia_export_brings_its_devices_and_replaces_the_last_one() {
|
||||||
|
let server = TestServer::start().await;
|
||||||
|
let resp = server
|
||||||
|
.post(
|
||||||
|
"/api/v1/targets",
|
||||||
|
&json!({ "name": "linie-1", "target_type": "plc_sps", "artifacts": [] }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let body: serde_json::Value = resp.json().await.unwrap();
|
||||||
|
let id = body["data"]["_id"]["$oid"].as_str().unwrap().to_string();
|
||||||
|
|
||||||
|
// Not an export: refused with its code, and not kept.
|
||||||
|
let resp = upload_tia_export(&server, &id, b"plain text".to_vec()).await;
|
||||||
|
assert_eq!(resp.status(), 422);
|
||||||
|
let body: serde_json::Value = resp.json().await.unwrap();
|
||||||
|
assert_eq!(body["code"], "not_zip", "{body}");
|
||||||
|
assert!(stored_uploads(&id).is_empty());
|
||||||
|
|
||||||
|
let resp = upload_tia_export(&server, &id, tia_export("V20", "2.9")).await;
|
||||||
|
assert_eq!(resp.status(), 200);
|
||||||
|
let body: serde_json::Value = resp.json().await.unwrap();
|
||||||
|
let artifact = &body["data"]["artifacts"][0];
|
||||||
|
assert_eq!(artifact["plc"]["format"], "tia_export", "{body}");
|
||||||
|
// The CPU, by order number and configured firmware; not the GSD device.
|
||||||
|
assert_eq!(
|
||||||
|
artifact["plc"]["devices"],
|
||||||
|
json!([{"order_number": "6ES7511-1AK02-0AB0", "firmware": "2.9", "label": "PLC_1"}])
|
||||||
|
);
|
||||||
|
|
||||||
|
// The next export replaces it, file and all.
|
||||||
|
let resp = upload_tia_export(&server, &id, tia_export("V21", "3.1")).await;
|
||||||
|
assert_eq!(resp.status(), 200);
|
||||||
|
let body: serde_json::Value = resp.json().await.unwrap();
|
||||||
|
let artifacts = body["data"]["artifacts"].as_array().unwrap();
|
||||||
|
assert_eq!(artifacts.len(), 1, "{body}");
|
||||||
|
let facts = &artifacts[0]["detected"];
|
||||||
|
assert!(
|
||||||
|
facts
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.any(|f| f["key"] == "tia_version" && f["value"] == "V21"),
|
||||||
|
"{body}"
|
||||||
|
);
|
||||||
|
assert_eq!(stored_uploads(&id).len(), 1);
|
||||||
|
|
||||||
|
// The Steuerungen page lists the exported CPU under its project name.
|
||||||
|
let resp = server.get(&format!("/api/v1/targets/{id}/devices")).await;
|
||||||
|
assert_eq!(resp.status(), 200);
|
||||||
|
let body: serde_json::Value = resp.json().await.unwrap();
|
||||||
|
let devices = body["data"].as_array().unwrap();
|
||||||
|
assert_eq!(devices.len(), 1, "{body}");
|
||||||
|
assert_eq!(devices[0]["label"], "PLC_1", "{body}");
|
||||||
|
|
||||||
|
server.cleanup().await;
|
||||||
|
}
|
||||||
@@ -285,6 +285,7 @@ async fn seed_nightly(
|
|||||||
"target_type": t.target_type,
|
"target_type": t.target_type,
|
||||||
"description": t.description,
|
"description": t.description,
|
||||||
"artifacts": references,
|
"artifacts": references,
|
||||||
|
"devices": t.devices,
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
|||||||
@@ -0,0 +1,356 @@
|
|||||||
|
//! The entry plan's target cap against a fake tenant registry: with
|
||||||
|
//! `extra_targets: 0` a new target is refused (409 `target_limit`) once the
|
||||||
|
//! included ones are all active, archiving one frees its place, targets
|
||||||
|
//! already beyond it are never billed as extra, demo targets are outside the
|
||||||
|
//! cap until they are given the tenant's own sources, and a plan without
|
||||||
|
//! the key keeps adding extra targets as before.
|
||||||
|
//! Needs a live Mongo for the agent itself; skips cleanly without one.
|
||||||
|
|
||||||
|
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::body::Body;
|
||||||
|
use axum::extract::Request;
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::middleware::{from_fn, Next};
|
||||||
|
use axum::routing::{patch, post};
|
||||||
|
use axum::{Extension, Json, Router};
|
||||||
|
use mongodb::bson::doc;
|
||||||
|
use tower::ServiceExt;
|
||||||
|
|
||||||
|
use compliance_agent::agent::ComplianceAgent;
|
||||||
|
use compliance_agent::api::handlers::onboarding::{create_target, update_target};
|
||||||
|
use compliance_agent::database::DatabasePool;
|
||||||
|
use compliance_core::models::{OnboardedTarget, TargetBilling, TargetType};
|
||||||
|
use compliance_core::{OrgRole, TenantContext, TenantStatus};
|
||||||
|
|
||||||
|
use common::dev_config;
|
||||||
|
|
||||||
|
/// A registry where `t-entry` includes two targets and allows no extra one,
|
||||||
|
/// and `t-standard` includes one and bills the others.
|
||||||
|
async fn fake_registry() -> String {
|
||||||
|
let app = Router::new().route(
|
||||||
|
"/v1/internal/entitlements/check",
|
||||||
|
post(|Json(body): Json<serde_json::Value>| async move {
|
||||||
|
let limits = match body["tenant_id"].as_str() {
|
||||||
|
Some("t-entry") => serde_json::json!({ "included_targets": 2, "extra_targets": 0 }),
|
||||||
|
_ => serde_json::json!({ "included_targets": 1 }),
|
||||||
|
};
|
||||||
|
Json(serde_json::json!({ "allowed": true, "status": "active", "limits": limits }))
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let addr = listener.local_addr().unwrap();
|
||||||
|
tokio::spawn(async move { axum::serve(listener, app).await.ok() });
|
||||||
|
format!("http://{addr}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An agent whose registry is `registry`, or `None` without Mongo.
|
||||||
|
async fn agent(registry: &str) -> Option<Arc<ComplianceAgent>> {
|
||||||
|
let uri = std::env::var("TEST_MONGODB_URI")
|
||||||
|
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||||
|
let db_name = format!("cap_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
|
||||||
|
let Ok(pool) = DatabasePool::connect(&uri, &db_name).await else {
|
||||||
|
eprintln!("SKIP target_limit: no MongoDB reachable at {uri}");
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
let mut config = dev_config(uri, db_name);
|
||||||
|
config.tenant_registry_url = Some(registry.to_string());
|
||||||
|
Some(Arc::new(ComplianceAgent::new(config, pool)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn member(tenant: &str) -> TenantContext {
|
||||||
|
TenantContext {
|
||||||
|
tenant_id: tenant.into(),
|
||||||
|
tenant_slug: "acme".into(),
|
||||||
|
org_roles: vec![OrgRole::ItAdmin],
|
||||||
|
products: vec!["compliance-scanner".into()],
|
||||||
|
plan: "entry".into(),
|
||||||
|
status: TenantStatus::Active,
|
||||||
|
user_id: "u-1".into(),
|
||||||
|
user_name: None,
|
||||||
|
staff: None,
|
||||||
|
api_key: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `POST /api/v1/targets` named `name` as a member of `tenant`.
|
||||||
|
async fn add(
|
||||||
|
agent: &Arc<ComplianceAgent>,
|
||||||
|
tenant: &str,
|
||||||
|
name: &str,
|
||||||
|
) -> (StatusCode, serde_json::Value) {
|
||||||
|
let ctx = member(tenant);
|
||||||
|
let inject = move |mut req: Request, next: Next| {
|
||||||
|
let ctx = ctx.clone();
|
||||||
|
async move {
|
||||||
|
req.extensions_mut().insert(ctx);
|
||||||
|
next.run(req).await
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let app = Router::new()
|
||||||
|
.route("/api/v1/targets", post(create_target))
|
||||||
|
.layer(Extension(agent.clone()))
|
||||||
|
.layer(from_fn(inject));
|
||||||
|
let body = serde_json::json!({ "name": name, "target_type": "web_app" });
|
||||||
|
let resp = app
|
||||||
|
.oneshot(
|
||||||
|
Request::builder()
|
||||||
|
.method("POST")
|
||||||
|
.uri("/api/v1/targets")
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.body(Body::from(body.to_string()))
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let status = resp.status();
|
||||||
|
let bytes = axum::body::to_bytes(resp.into_body(), 1 << 16)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
(status, serde_json::from_slice(&bytes).unwrap_or_default())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_entry_plan_refuses_a_target_beyond_its_included_ones() {
|
||||||
|
let registry = fake_registry().await;
|
||||||
|
let Some(agent) = agent(®istry).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Arrange: both included places taken.
|
||||||
|
assert_eq!(
|
||||||
|
add(&agent, "t-entry", "Steuerung A").await.0,
|
||||||
|
StatusCode::OK
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
add(&agent, "t-entry", "Steuerung B").await.0,
|
||||||
|
StatusCode::OK
|
||||||
|
);
|
||||||
|
|
||||||
|
// Act + Assert: the third is refused and not stored.
|
||||||
|
let (status, body) = add(&agent, "t-entry", "Steuerung C").await;
|
||||||
|
assert_eq!(status, StatusCode::CONFLICT);
|
||||||
|
assert_eq!(body["error"], "target_limit");
|
||||||
|
let db = agent.db_pool.for_tenant_id("t-entry").await.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
db.onboarded_targets()
|
||||||
|
.count_documents(doc! { "name": "Steuerung C" })
|
||||||
|
.await
|
||||||
|
.unwrap(),
|
||||||
|
0
|
||||||
|
);
|
||||||
|
|
||||||
|
// Archiving one frees its place.
|
||||||
|
db.onboarded_targets()
|
||||||
|
.update_one(
|
||||||
|
doc! { "name": "Steuerung A" },
|
||||||
|
doc! { "$set": { "archived_at": mongodb::bson::DateTime::now() } },
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let (status, body) = add(&agent, "t-entry", "Steuerung C").await;
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
assert_eq!(body["data"]["billing"], "included");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_plan_without_the_key_adds_extra_targets_as_before() {
|
||||||
|
let registry = fake_registry().await;
|
||||||
|
let Some(agent) = agent(®istry).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
add(&agent, "t-standard", "Anlage 1").await.0,
|
||||||
|
StatusCode::OK
|
||||||
|
);
|
||||||
|
let (status, body) = add(&agent, "t-standard", "Anlage 2").await;
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
assert_eq!(body["data"]["billing"], "extra");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn targets_already_beyond_the_entry_plan_are_never_billed_extra() {
|
||||||
|
let registry = fake_registry().await;
|
||||||
|
let Some(agent) = agent(®istry).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
// Arrange: three active targets from before the plan, one billed extra.
|
||||||
|
let db = agent.db_pool.for_tenant_id("t-entry").await.unwrap();
|
||||||
|
for (name, billing) in [
|
||||||
|
("Anlage 1", TargetBilling::Included),
|
||||||
|
("Anlage 2", TargetBilling::Included),
|
||||||
|
("Anlage 3", TargetBilling::Extra),
|
||||||
|
] {
|
||||||
|
let mut target = OnboardedTarget::new(name.into(), TargetType::WebApp);
|
||||||
|
target.billing = billing;
|
||||||
|
db.onboarded_targets().insert_one(&target).await.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Act
|
||||||
|
agent.refresh_billing("t-entry", &db).await;
|
||||||
|
|
||||||
|
// Assert: all three stay, none is extra, and a fourth is refused.
|
||||||
|
let extra = mongodb::bson::to_bson(&TargetBilling::Extra).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
db.onboarded_targets()
|
||||||
|
.count_documents(doc! { "billing": extra })
|
||||||
|
.await
|
||||||
|
.unwrap(),
|
||||||
|
0
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
db.onboarded_targets()
|
||||||
|
.count_documents(doc! {})
|
||||||
|
.await
|
||||||
|
.unwrap(),
|
||||||
|
3
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
add(&agent, "t-entry", "Anlage 4").await.0,
|
||||||
|
StatusCode::CONFLICT
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn demo_targets_are_neither_counted_nor_refused() {
|
||||||
|
let registry = fake_registry().await;
|
||||||
|
let Some(agent) = agent(®istry).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let db = agent.db_pool.for_tenant_id("t-entry").await.unwrap();
|
||||||
|
let demo = |name: &str| {
|
||||||
|
let mut target = OnboardedTarget::new(name.into(), TargetType::WebApp);
|
||||||
|
target.demo = true;
|
||||||
|
target
|
||||||
|
};
|
||||||
|
|
||||||
|
// A demo target leaves both included places free.
|
||||||
|
compliance_agent::targets::create_target(&agent, &db, "t-entry", demo("Demo A"))
|
||||||
|
.await
|
||||||
|
.expect("demo target added");
|
||||||
|
assert_eq!(
|
||||||
|
add(&agent, "t-entry", "Steuerung A").await.0,
|
||||||
|
StatusCode::OK
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
add(&agent, "t-entry", "Steuerung B").await.0,
|
||||||
|
StatusCode::OK
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
add(&agent, "t-entry", "Steuerung C").await.0,
|
||||||
|
StatusCode::CONFLICT
|
||||||
|
);
|
||||||
|
|
||||||
|
// With the places taken, the seeder still adds its targets.
|
||||||
|
compliance_agent::targets::create_target(&agent, &db, "t-entry", demo("Demo B"))
|
||||||
|
.await
|
||||||
|
.expect("demo target added at the cap");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `PATCH /api/v1/targets/{id}` with `body` as a member of `tenant`.
|
||||||
|
async fn edit(
|
||||||
|
agent: &Arc<ComplianceAgent>,
|
||||||
|
tenant: &str,
|
||||||
|
id: &str,
|
||||||
|
body: serde_json::Value,
|
||||||
|
) -> (StatusCode, serde_json::Value) {
|
||||||
|
let ctx = member(tenant);
|
||||||
|
let inject = move |mut req: Request, next: Next| {
|
||||||
|
let ctx = ctx.clone();
|
||||||
|
async move {
|
||||||
|
req.extensions_mut().insert(ctx);
|
||||||
|
next.run(req).await
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let app = Router::new()
|
||||||
|
.route("/api/v1/targets/{id}", patch(update_target))
|
||||||
|
.layer(Extension(agent.clone()))
|
||||||
|
.layer(from_fn(inject));
|
||||||
|
let resp = app
|
||||||
|
.oneshot(
|
||||||
|
Request::builder()
|
||||||
|
.method("PATCH")
|
||||||
|
.uri(format!("/api/v1/targets/{id}"))
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.body(Body::from(body.to_string()))
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let status = resp.status();
|
||||||
|
let bytes = axum::body::to_bytes(resp.into_body(), 1 << 16)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
(status, serde_json::from_slice(&bytes).unwrap_or_default())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_demo_target_given_the_tenants_own_sources_counts() {
|
||||||
|
let registry = fake_registry().await;
|
||||||
|
let Some(agent) = agent(®istry).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let db = agent.db_pool.for_tenant_id("t-entry").await.unwrap();
|
||||||
|
let mut demo = OnboardedTarget::new("Demo · Pumpe".into(), TargetType::WebApp);
|
||||||
|
demo.demo = true;
|
||||||
|
demo.artifacts
|
||||||
|
.push(compliance_core::models::Artifact::live_url(
|
||||||
|
"https://demo.example",
|
||||||
|
));
|
||||||
|
let demo = compliance_agent::targets::create_target(&agent, &db, "t-entry", demo)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let id = demo.id.unwrap().to_hex();
|
||||||
|
assert_eq!(
|
||||||
|
add(&agent, "t-entry", "Steuerung A").await.0,
|
||||||
|
StatusCode::OK
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
add(&agent, "t-entry", "Steuerung B").await.0,
|
||||||
|
StatusCode::OK
|
||||||
|
);
|
||||||
|
let is_demo = || async {
|
||||||
|
db.onboarded_targets()
|
||||||
|
.find_one(doc! { "_id": demo.id.unwrap() })
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.unwrap()
|
||||||
|
.demo
|
||||||
|
};
|
||||||
|
let own = serde_json::json!({ "artifacts": [
|
||||||
|
{ "kind": "git_repo", "source_ref": "https://git.example/own.git", "branch": "main" }
|
||||||
|
] });
|
||||||
|
|
||||||
|
// A new name and the same sources keep it a demo target.
|
||||||
|
let same = serde_json::json!({ "name": "Pumpe", "artifacts": [
|
||||||
|
{ "kind": "live_url", "source_ref": "https://demo.example" }
|
||||||
|
] });
|
||||||
|
assert_eq!(edit(&agent, "t-entry", &id, same).await.0, StatusCode::OK);
|
||||||
|
assert!(is_demo().await);
|
||||||
|
|
||||||
|
// Act + Assert: the tenant's own sources need a place, and none is free.
|
||||||
|
let (status, body) = edit(&agent, "t-entry", &id, own.clone()).await;
|
||||||
|
assert_eq!(status, StatusCode::CONFLICT);
|
||||||
|
assert_eq!(body["error"], "target_limit");
|
||||||
|
assert!(is_demo().await, "refused: still a demo target");
|
||||||
|
|
||||||
|
// With a place free, it becomes the tenant's own and takes that place.
|
||||||
|
db.onboarded_targets()
|
||||||
|
.update_one(
|
||||||
|
doc! { "name": "Steuerung A" },
|
||||||
|
doc! { "$set": { "archived_at": mongodb::bson::DateTime::now() } },
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(edit(&agent, "t-entry", &id, own).await.0, StatusCode::OK);
|
||||||
|
assert!(!is_demo().await);
|
||||||
|
assert_eq!(
|
||||||
|
add(&agent, "t-entry", "Steuerung C").await.0,
|
||||||
|
StatusCode::CONFLICT
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "compliance-core"
|
name = "compliance-core"
|
||||||
version = "0.4.18"
|
version = "0.4.20"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
|
|||||||
@@ -175,14 +175,32 @@ impl Advisory {
|
|||||||
self.fixed_versions_where(vulnerability, |p| normalised_name(&p.name) == wanted)
|
self.fixed_versions_where(vulnerability, |p| normalised_name(&p.name) == wanted)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The fixed versions of `vulnerability` for the device with order number
|
/// The fixed firmware of `vulnerability` for the device with order
|
||||||
/// `order_number`, as [`Self::fixed_versions`] gives them by name.
|
/// number `order_number`, lowest first: the exact versions of its fixed
|
||||||
|
/// products, and the version a vendor fix for one of its products names
|
||||||
|
/// (Siemens marks its products only affected and writes the fix as
|
||||||
|
/// `Update to V3.1.5 or later version`).
|
||||||
pub fn fixed_device_versions(
|
pub fn fixed_device_versions(
|
||||||
&self,
|
&self,
|
||||||
vulnerability: &AdvisoryVulnerability,
|
vulnerability: &AdvisoryVulnerability,
|
||||||
order_number: &str,
|
order_number: &str,
|
||||||
) -> Vec<String> {
|
) -> Vec<String> {
|
||||||
self.fixed_versions_where(vulnerability, |p| p.has_order_number(order_number))
|
let is_it = |id: &String| {
|
||||||
|
self.product(id)
|
||||||
|
.is_some_and(|p| p.has_order_number(order_number))
|
||||||
|
};
|
||||||
|
let mut versions =
|
||||||
|
self.fixed_versions_where(vulnerability, |p| p.has_order_number(order_number));
|
||||||
|
versions.extend(
|
||||||
|
vulnerability
|
||||||
|
.remediations
|
||||||
|
.iter()
|
||||||
|
.filter(|r| r.category == "vendor_fix" && r.product_ids.iter().any(is_it))
|
||||||
|
.filter_map(|r| version_in_text(&r.details)),
|
||||||
|
);
|
||||||
|
versions.sort_by(|a, b| cmp_dotted(a, b));
|
||||||
|
versions.dedup();
|
||||||
|
versions
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The exact versions of the fixed products `is_it` picks, oldest first.
|
/// The exact versions of the fixed products `is_it` picks, oldest first.
|
||||||
@@ -204,6 +222,21 @@ impl Advisory {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The firmware a vendor fix's text updates to, when it says so the way
|
||||||
|
/// Siemens does: `Update to V3.1.5 or later version` is `3.1.5`. Anything
|
||||||
|
/// else gives none: a version with letters (`V3.X.18`), or a text about
|
||||||
|
/// something other than an update (`A hardware upgrade to LOGO! V9 BM`).
|
||||||
|
fn version_in_text(text: &str) -> Option<String> {
|
||||||
|
let rest = text.trim_start().strip_prefix("Update to V")?;
|
||||||
|
let end = rest
|
||||||
|
.find(|c: char| !(c.is_ascii_digit() || c == '.'))
|
||||||
|
.unwrap_or(rest.len());
|
||||||
|
let (version, after) = rest.split_at(end);
|
||||||
|
let version = version.trim_end_matches('.');
|
||||||
|
let ends_cleanly = after.is_empty() || after.starts_with([' ', ',', '.', ';']);
|
||||||
|
(version.starts_with(|c: char| c.is_ascii_digit()) && ends_cleanly).then(|| version.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
/// The text at `key` of `value`, trimmed, if not empty.
|
/// The text at `key` of `value`, trimmed, if not empty.
|
||||||
fn text(value: &serde_json::Value, key: &str) -> Option<String> {
|
fn text(value: &serde_json::Value, key: &str) -> Option<String> {
|
||||||
value
|
value
|
||||||
@@ -480,3 +513,32 @@ pub fn parse(doc: &serde_json::Value) -> Result<Advisory, CsafError> {
|
|||||||
.collect(),
|
.collect(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::version_in_text;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_an_update_to_a_numeric_version_names_a_fix() {
|
||||||
|
let read = |t: &str| version_in_text(t);
|
||||||
|
assert_eq!(
|
||||||
|
read("Update to V3.1.5 or later version").as_deref(),
|
||||||
|
Some("3.1.5")
|
||||||
|
);
|
||||||
|
assert_eq!(read("Update to V9 or later version").as_deref(), Some("9"));
|
||||||
|
assert_eq!(
|
||||||
|
read("Update to V4.2.1 or later version, migrate project").as_deref(),
|
||||||
|
Some("4.2.1")
|
||||||
|
);
|
||||||
|
assert_eq!(read("Update to V2.9.8.").as_deref(), Some("2.9.8"));
|
||||||
|
assert_eq!(read("Update to V3.X.18 or later version"), None);
|
||||||
|
assert_eq!(
|
||||||
|
read("Note: A hardware upgrade to LOGO! V9 BM or later is also required"),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
read("To obtain SIMATIC S7-410 V10.1 contact your local support."),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,435 @@
|
|||||||
|
//! A Siemens controller against the advisories that name it (SPS item 4a):
|
||||||
|
//! what its page shows before the next scan does.
|
||||||
|
//!
|
||||||
|
//! The matching is the scan's ([`AdvisoryProduct::covers_device`],
|
||||||
|
//! [`Advisory::fixed_device_versions`]), so a device's light and its CVE
|
||||||
|
//! alerts never disagree once the target is scanned.
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::csaf_ingest::{Advisory, AdvisoryProduct, AdvisoryVulnerability};
|
||||||
|
use crate::models::PlcDevice;
|
||||||
|
use crate::version::cmp_dotted;
|
||||||
|
|
||||||
|
/// What Siemens calls the device, from an advisory's product name.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct DeviceName {
|
||||||
|
/// The full name without the order number (`SIMATIC S7-1500 CPU 1511-1 PN`).
|
||||||
|
pub name: String,
|
||||||
|
/// The part from `CPU` on (`CPU 1511-1 PN`), or the full name.
|
||||||
|
pub short: String,
|
||||||
|
/// The series before `CPU` without the brand (`S7-1500`, `ET 200SP`).
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub family: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DeviceName {
|
||||||
|
/// The name in an advisory product's name `product` (`SIMATIC S7-1500
|
||||||
|
/// CPU 1511-1 PN (6ES7511-1AK02-0AB0)`): the order number in brackets
|
||||||
|
/// and a version after it are dropped. `None` for an empty name.
|
||||||
|
pub fn from_product(product: &str) -> Option<Self> {
|
||||||
|
let name = product
|
||||||
|
.split_once(" (")
|
||||||
|
.map_or(product, |(name, _)| name)
|
||||||
|
.trim();
|
||||||
|
if name.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let (short, family) = match name.find("CPU ") {
|
||||||
|
Some(at) if at > 0 => {
|
||||||
|
let series = name[..at].trim();
|
||||||
|
let series = series.strip_prefix("SIMATIC").unwrap_or(series).trim();
|
||||||
|
(
|
||||||
|
&name[at..],
|
||||||
|
(!series.is_empty()).then(|| series.to_string()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
_ => (name, None),
|
||||||
|
};
|
||||||
|
Some(Self {
|
||||||
|
name: name.to_string(),
|
||||||
|
short: short.to_string(),
|
||||||
|
family,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One advisory naming the device, as its page lists it.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct DeviceAdvisory {
|
||||||
|
/// Its id (`SSA-019113`).
|
||||||
|
pub id: String,
|
||||||
|
pub title: String,
|
||||||
|
/// Its page, which Siemens' terms ask every use to link.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub url: Option<String>,
|
||||||
|
/// The CVEs it lists for the device.
|
||||||
|
pub cves: Vec<String>,
|
||||||
|
/// The highest CVSS base severity of those (`HIGH`).
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub severity: Option<String>,
|
||||||
|
/// Whether one of them affects the device's firmware.
|
||||||
|
pub affected: bool,
|
||||||
|
/// The firmware that fixes all of them that apply: those affecting the
|
||||||
|
/// device when it is affected, otherwise all it lists. `None` when one
|
||||||
|
/// has no fix.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub fixed_from: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What Siemens' advisories know of an order number, to recognise it while
|
||||||
|
/// it is typed.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct DeviceLookup {
|
||||||
|
/// The order number, normalised (`6ES7511-1AK02-0AB0`).
|
||||||
|
pub order_number: String,
|
||||||
|
/// Whether it has a Siemens order number's shape.
|
||||||
|
pub valid: bool,
|
||||||
|
/// What Siemens calls it, from the newest advisory naming it.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub product: Option<DeviceName>,
|
||||||
|
/// How many advisories name it.
|
||||||
|
pub advisories: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A device's state in the advisories.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum DeviceState {
|
||||||
|
/// An advisory affects its firmware.
|
||||||
|
Affected,
|
||||||
|
/// Advisories name it, none affects its firmware.
|
||||||
|
NotAffected,
|
||||||
|
/// No advisory names its order number.
|
||||||
|
NotNamed,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A device and the advisories naming it.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct DeviceCheck {
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub device: PlcDevice,
|
||||||
|
/// What Siemens calls it, from the newest advisory naming it.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub product: Option<DeviceName>,
|
||||||
|
/// The advisories naming it: affecting it first, then by severity.
|
||||||
|
pub advisories: Vec<DeviceAdvisory>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DeviceCheck {
|
||||||
|
/// The device against `advisories`, Siemens' in any order.
|
||||||
|
pub fn new(device: PlcDevice, advisories: &[Advisory]) -> Self {
|
||||||
|
let mut naming: Vec<&Advisory> = advisories
|
||||||
|
.iter()
|
||||||
|
.filter(|a| {
|
||||||
|
a.products
|
||||||
|
.iter()
|
||||||
|
.any(|p| p.has_order_number(&device.order_number))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
// Newest first, so the name is the one Siemens uses now.
|
||||||
|
naming.sort_by(|a, b| b.updated.cmp(&a.updated).then_with(|| a.id.cmp(&b.id)));
|
||||||
|
let product = naming.iter().find_map(|a| {
|
||||||
|
a.products
|
||||||
|
.iter()
|
||||||
|
.filter(|p| p.has_order_number(&device.order_number))
|
||||||
|
.find_map(|p| DeviceName::from_product(&p.name))
|
||||||
|
});
|
||||||
|
let mut rows: Vec<DeviceAdvisory> =
|
||||||
|
naming.into_iter().filter_map(|a| row(a, &device)).collect();
|
||||||
|
rows.sort_by(|a, b| {
|
||||||
|
b.affected
|
||||||
|
.cmp(&a.affected)
|
||||||
|
.then_with(|| severity_rank(&b.severity).cmp(&severity_rank(&a.severity)))
|
||||||
|
.then_with(|| a.id.cmp(&b.id))
|
||||||
|
});
|
||||||
|
Self {
|
||||||
|
device,
|
||||||
|
product,
|
||||||
|
advisories: rows,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether an advisory affects it, names it only, or none names it.
|
||||||
|
pub fn state(&self) -> DeviceState {
|
||||||
|
if self.advisories.iter().any(|a| a.affected) {
|
||||||
|
DeviceState::Affected
|
||||||
|
} else if self.advisories.is_empty() {
|
||||||
|
DeviceState::NotNamed
|
||||||
|
} else {
|
||||||
|
DeviceState::NotAffected
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Advisory `advisory`'s row for `device`, when one of its vulnerabilities
|
||||||
|
/// lists one of the device's products.
|
||||||
|
fn row(advisory: &Advisory, device: &PlcDevice) -> Option<DeviceAdvisory> {
|
||||||
|
let order_number = device.order_number.as_str();
|
||||||
|
let products: Vec<&AdvisoryProduct> = advisory
|
||||||
|
.products
|
||||||
|
.iter()
|
||||||
|
.filter(|p| p.has_order_number(order_number))
|
||||||
|
.collect();
|
||||||
|
let lists = |ids: &[String]| {
|
||||||
|
ids.iter()
|
||||||
|
.any(|id| products.iter().any(|p| &p.product_id == id))
|
||||||
|
};
|
||||||
|
let named: Vec<&AdvisoryVulnerability> = advisory
|
||||||
|
.vulnerabilities
|
||||||
|
.iter()
|
||||||
|
.filter(|v| lists(&v.affected) || lists(&v.fixed) || lists(&v.not_affected))
|
||||||
|
.collect();
|
||||||
|
if named.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let affects = |v: &AdvisoryVulnerability| {
|
||||||
|
v.affected.iter().any(|id| {
|
||||||
|
advisory
|
||||||
|
.product(id)
|
||||||
|
.is_some_and(|p| p.covers_device(order_number, &device.firmware))
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let affecting: Vec<&AdvisoryVulnerability> =
|
||||||
|
named.iter().copied().filter(|v| affects(v)).collect();
|
||||||
|
let affected = !affecting.is_empty();
|
||||||
|
let fixing = if affected { &affecting } else { &named };
|
||||||
|
// The fix of each: the lowest fixed firmware above the device's when it
|
||||||
|
// is affected, the lowest at all otherwise. The row's is the highest.
|
||||||
|
let fixed_from = fixing
|
||||||
|
.iter()
|
||||||
|
.map(|v| {
|
||||||
|
advisory
|
||||||
|
.fixed_device_versions(v, order_number)
|
||||||
|
.into_iter()
|
||||||
|
.find(|f| !affected || cmp_dotted(f, &device.firmware).is_gt())
|
||||||
|
})
|
||||||
|
.try_fold(None::<String>, |highest, fix| {
|
||||||
|
let fix = fix?;
|
||||||
|
Some(Some(match highest {
|
||||||
|
Some(h) if cmp_dotted(&h, &fix).is_ge() => h,
|
||||||
|
_ => fix,
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
.flatten();
|
||||||
|
let severity = named
|
||||||
|
.iter()
|
||||||
|
.filter_map(|v| v.severity.clone())
|
||||||
|
.max_by_key(|s| severity_rank(&Some(s.clone())));
|
||||||
|
let mut cves: Vec<String> = named.iter().filter_map(|v| v.cve.clone()).collect();
|
||||||
|
cves.sort();
|
||||||
|
cves.dedup();
|
||||||
|
Some(DeviceAdvisory {
|
||||||
|
id: advisory.id.clone(),
|
||||||
|
title: advisory.title.clone(),
|
||||||
|
url: advisory.url.clone(),
|
||||||
|
cves,
|
||||||
|
severity,
|
||||||
|
affected,
|
||||||
|
fixed_from,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A CVSS base severity's order: `CRITICAL` highest, none lowest.
|
||||||
|
fn severity_rank(severity: &Option<String>) -> u8 {
|
||||||
|
match severity.as_deref().map(str::to_ascii_uppercase).as_deref() {
|
||||||
|
Some("CRITICAL") => 4,
|
||||||
|
Some("HIGH") => 3,
|
||||||
|
Some("MEDIUM") => 2,
|
||||||
|
Some("LOW") => 1,
|
||||||
|
_ => 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[allow(clippy::unwrap_used, clippy::expect_used)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::csaf_ingest::Remediation;
|
||||||
|
|
||||||
|
fn product(id: &str, name: &str, range: &str) -> AdvisoryProduct {
|
||||||
|
let order_number = name
|
||||||
|
.split_once('(')
|
||||||
|
.and_then(|(_, rest)| rest.split_once(')'))
|
||||||
|
.map(|(on, _)| on.to_string());
|
||||||
|
AdvisoryProduct {
|
||||||
|
product_id: id.into(),
|
||||||
|
vendor: Some("Siemens".into()),
|
||||||
|
family: None,
|
||||||
|
name: name.into(),
|
||||||
|
version: None,
|
||||||
|
version_range: Some(range.into()),
|
||||||
|
cpe: None,
|
||||||
|
purl: None,
|
||||||
|
model_numbers: order_number.into_iter().collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn vulnerability(
|
||||||
|
cve: &str,
|
||||||
|
severity: &str,
|
||||||
|
affected: &[&str],
|
||||||
|
fix: Option<(&str, &[&str])>,
|
||||||
|
) -> AdvisoryVulnerability {
|
||||||
|
AdvisoryVulnerability {
|
||||||
|
cve: Some(cve.into()),
|
||||||
|
severity: Some(severity.into()),
|
||||||
|
affected: affected.iter().map(|s| s.to_string()).collect(),
|
||||||
|
remediations: fix
|
||||||
|
.map(|(details, ids)| Remediation {
|
||||||
|
category: "vendor_fix".into(),
|
||||||
|
details: details.into(),
|
||||||
|
url: None,
|
||||||
|
product_ids: ids.iter().map(|s| s.to_string()).collect(),
|
||||||
|
})
|
||||||
|
.into_iter()
|
||||||
|
.collect(),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn advisory(
|
||||||
|
id: &str,
|
||||||
|
updated: &str,
|
||||||
|
products: Vec<AdvisoryProduct>,
|
||||||
|
vulnerabilities: Vec<AdvisoryVulnerability>,
|
||||||
|
) -> Advisory {
|
||||||
|
Advisory {
|
||||||
|
id: id.into(),
|
||||||
|
title: format!("{id} title"),
|
||||||
|
publisher: "Siemens ProductCERT".into(),
|
||||||
|
url: Some(format!(
|
||||||
|
"https://cert-portal.siemens.com/productcert/html/{id}.html"
|
||||||
|
)),
|
||||||
|
tlp: Some("WHITE".into()),
|
||||||
|
updated: updated.into(),
|
||||||
|
products,
|
||||||
|
vulnerabilities,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const CPU: &str = "SIMATIC S7-1500 CPU 1511-1 PN (6ES7511-1AK02-0AB0)";
|
||||||
|
|
||||||
|
fn device(firmware: &str) -> PlcDevice {
|
||||||
|
PlcDevice::new("6ES7511-1AK02-0AB0", firmware, Some("Hauptsteuerung")).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn siemens_names_split_into_series_and_cpu() {
|
||||||
|
assert_eq!(
|
||||||
|
DeviceName::from_product(CPU),
|
||||||
|
Some(DeviceName {
|
||||||
|
name: "SIMATIC S7-1500 CPU 1511-1 PN".into(),
|
||||||
|
short: "CPU 1511-1 PN".into(),
|
||||||
|
family: Some("S7-1500".into()),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
let et =
|
||||||
|
DeviceName::from_product("SIMATIC ET 200SP CPU 1512SP-1 PN (6ES7512-1DK01-0AB0) V3.0")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
(et.short.as_str(), et.family.as_deref()),
|
||||||
|
("CPU 1512SP-1 PN", Some("ET 200SP"))
|
||||||
|
);
|
||||||
|
let logo = DeviceName::from_product("LOGO! 8 BM (6ED1052-1MD08-0BA2)").unwrap();
|
||||||
|
assert_eq!((logo.short.as_str(), logo.family), ("LOGO! 8 BM", None));
|
||||||
|
assert_eq!(DeviceName::from_product(" (6ES7511-1AK02-0AB0)"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_device_is_affected_until_the_firmware_fixing_all_its_advisorys_cves() {
|
||||||
|
let advisories = [advisory(
|
||||||
|
"SSA-100001",
|
||||||
|
"2026-10-01",
|
||||||
|
vec![
|
||||||
|
product("1", CPU, "vers:intdot/<3.1.5"),
|
||||||
|
product("2", CPU, "vers:intdot/<3.1.7"),
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
vulnerability(
|
||||||
|
"CVE-2026-1",
|
||||||
|
"MEDIUM",
|
||||||
|
&["1"],
|
||||||
|
Some(("Update to V3.1.5 or later version", &["1"])),
|
||||||
|
),
|
||||||
|
vulnerability(
|
||||||
|
"CVE-2026-2",
|
||||||
|
"HIGH",
|
||||||
|
&["2"],
|
||||||
|
Some(("Update to V3.1.7 or later version", &["2"])),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)];
|
||||||
|
|
||||||
|
let old = DeviceCheck::new(device("3.1.4"), &advisories);
|
||||||
|
assert_eq!(old.state(), DeviceState::Affected);
|
||||||
|
let row = &old.advisories[0];
|
||||||
|
assert_eq!(row.cves, ["CVE-2026-1", "CVE-2026-2"]);
|
||||||
|
assert_eq!(row.severity.as_deref(), Some("HIGH"));
|
||||||
|
assert_eq!(row.fixed_from.as_deref(), Some("3.1.7"));
|
||||||
|
assert_eq!(old.product.as_ref().unwrap().short, "CPU 1511-1 PN");
|
||||||
|
|
||||||
|
let between = DeviceCheck::new(device("3.1.6"), &advisories);
|
||||||
|
assert_eq!(between.advisories[0].fixed_from.as_deref(), Some("3.1.7"));
|
||||||
|
|
||||||
|
let current = DeviceCheck::new(device("3.1.7"), &advisories);
|
||||||
|
assert_eq!(current.state(), DeviceState::NotAffected);
|
||||||
|
assert!(!current.advisories[0].affected);
|
||||||
|
assert_eq!(current.advisories[0].fixed_from.as_deref(), Some("3.1.7"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_affecting_cve_without_a_fix_leaves_no_fixed_firmware() {
|
||||||
|
let advisories = [advisory(
|
||||||
|
"SSA-100002",
|
||||||
|
"2026-10-01",
|
||||||
|
vec![product("1", CPU, "vers:all/*")],
|
||||||
|
vec![vulnerability("CVE-2026-3", "LOW", &["1"], None)],
|
||||||
|
)];
|
||||||
|
let check = DeviceCheck::new(device("3.1.4"), &advisories);
|
||||||
|
assert!(check.advisories[0].affected);
|
||||||
|
assert_eq!(check.advisories[0].fixed_from, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rows_put_affecting_and_severe_first_and_skip_other_devices() {
|
||||||
|
let other = "SIMATIC S7-1500 CPU 1513-1 PN (6ES7513-1AL02-0AB0)";
|
||||||
|
let advisories = [
|
||||||
|
advisory(
|
||||||
|
"SSA-1",
|
||||||
|
"2026-01-01",
|
||||||
|
vec![product("1", CPU, "vers:intdot/<2.0")],
|
||||||
|
vec![vulnerability("CVE-1", "CRITICAL", &["1"], None)],
|
||||||
|
),
|
||||||
|
advisory(
|
||||||
|
"SSA-2",
|
||||||
|
"2026-02-01",
|
||||||
|
vec![product("1", CPU, "vers:all/*")],
|
||||||
|
vec![vulnerability("CVE-2", "MEDIUM", &["1"], None)],
|
||||||
|
),
|
||||||
|
advisory(
|
||||||
|
"SSA-3",
|
||||||
|
"2026-03-01",
|
||||||
|
vec![product("1", CPU, "vers:all/*")],
|
||||||
|
vec![vulnerability("CVE-3", "HIGH", &["1"], None)],
|
||||||
|
),
|
||||||
|
advisory(
|
||||||
|
"SSA-4",
|
||||||
|
"2026-04-01",
|
||||||
|
vec![product("1", other, "vers:all/*")],
|
||||||
|
vec![vulnerability("CVE-4", "CRITICAL", &["1"], None)],
|
||||||
|
),
|
||||||
|
];
|
||||||
|
let check = DeviceCheck::new(device("3.1.4"), &advisories);
|
||||||
|
let ids: Vec<&str> = check.advisories.iter().map(|a| a.id.as_str()).collect();
|
||||||
|
assert_eq!(ids, ["SSA-3", "SSA-2", "SSA-1"]);
|
||||||
|
assert_eq!(
|
||||||
|
DeviceCheck::new(
|
||||||
|
PlcDevice::new("6ES7516-3AN02-0AB0", "3.0", None).unwrap(),
|
||||||
|
&advisories
|
||||||
|
)
|
||||||
|
.state(),
|
||||||
|
DeviceState::NotNamed
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@ pub mod cve_groups;
|
|||||||
pub mod cve_history;
|
pub mod cve_history;
|
||||||
pub mod cve_matrix;
|
pub mod cve_matrix;
|
||||||
pub mod db;
|
pub mod db;
|
||||||
|
pub mod device_check;
|
||||||
pub mod encoding;
|
pub mod encoding;
|
||||||
pub mod enisa_docs;
|
pub mod enisa_docs;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ pub mod repository;
|
|||||||
pub mod sbom;
|
pub mod sbom;
|
||||||
pub mod scan;
|
pub mod scan;
|
||||||
pub(crate) mod serde_helpers;
|
pub(crate) mod serde_helpers;
|
||||||
|
pub mod tia_export;
|
||||||
pub mod vex;
|
pub mod vex;
|
||||||
pub mod webhook_delivery;
|
pub mod webhook_delivery;
|
||||||
pub mod werkbank;
|
pub mod werkbank;
|
||||||
@@ -72,7 +73,8 @@ pub use onboarding::{
|
|||||||
default_compliance_profile, Artifact, ArtifactAuth, ArtifactKind, Classification,
|
default_compliance_profile, Artifact, ArtifactAuth, ArtifactKind, Classification,
|
||||||
ComplianceFramework, ComplianceProfile, DetectedFact, ExternalRef, ExternalSystem,
|
ComplianceFramework, ComplianceProfile, DetectedFact, ExternalRef, ExternalSystem,
|
||||||
GitArtifactConfig, IssueTrackerConfig, LastScan, OnboardedTarget, PlcArtifactConfig, PlcFormat,
|
GitArtifactConfig, IssueTrackerConfig, LastScan, OnboardedTarget, PlcArtifactConfig, PlcFormat,
|
||||||
SupplierComponent, TargetScanConfig, TargetType, TargetTypeCandidate, WebArtifactConfig,
|
SupplierComponent, TargetDevice, TargetScanConfig, TargetType, TargetTypeCandidate,
|
||||||
|
WebArtifactConfig,
|
||||||
};
|
};
|
||||||
pub use oscal::OscalDocument;
|
pub use oscal::OscalDocument;
|
||||||
pub use oscal_assessment::{assess, AssessmentResultsDoc, ControlLinker};
|
pub use oscal_assessment::{assess, AssessmentResultsDoc, ControlLinker};
|
||||||
@@ -93,6 +95,10 @@ pub use scan::{
|
|||||||
RunErrorCode, RunNote, ScanPhase, ScanRun, ScanRunStatus, ScanStep, ScanType, SkipCode,
|
RunErrorCode, RunNote, ScanPhase, ScanRun, ScanRunStatus, ScanStep, ScanType, SkipCode,
|
||||||
SkippedStage,
|
SkippedStage,
|
||||||
};
|
};
|
||||||
|
pub use tia_export::{
|
||||||
|
AccessLevel, CpuSecurity, ExportedDevices, Setting, TiaBlock, TiaBlockKind, TiaBundleError,
|
||||||
|
TiaConnector, TiaDevice, TiaDeviceRole, TiaManifest, TiaProject,
|
||||||
|
};
|
||||||
pub use vex::{SupplierVex, VexAssessment, VexError, VexJustification, VexStatus};
|
pub use vex::{SupplierVex, VexAssessment, VexError, VexJustification, VexStatus};
|
||||||
pub use webhook_delivery::{DeliveryResult, WebhookDelivery, DELIVERIES_SHOWN};
|
pub use webhook_delivery::{DeliveryResult, WebhookDelivery, DELIVERIES_SHOWN};
|
||||||
pub use werkbank::{
|
pub use werkbank::{
|
||||||
|
|||||||
@@ -218,6 +218,10 @@ pub enum PlcFormat {
|
|||||||
/// A CODESYS project archive (`.projectarchive` — a zip bundling the project
|
/// A CODESYS project archive (`.projectarchive` — a zip bundling the project
|
||||||
/// plus its referenced libraries and runtime; the source of the control-app SBOM).
|
/// plus its referenced libraries and runtime; the source of the control-app SBOM).
|
||||||
ProjectArchive,
|
ProjectArchive,
|
||||||
|
/// A Siemens TIA Portal project as a TIA connector exports it (#1090): a
|
||||||
|
/// zip with a manifest of devices, security settings and blocks
|
||||||
|
/// ([`super::TiaManifest`]) beside the block exports.
|
||||||
|
TiaExport,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// PLC-specific configuration for a [`ArtifactKind::PlcProject`] artifact.
|
/// PLC-specific configuration for a [`ArtifactKind::PlcProject`] artifact.
|
||||||
@@ -225,6 +229,30 @@ pub enum PlcFormat {
|
|||||||
pub struct PlcArtifactConfig {
|
pub struct PlcArtifactConfig {
|
||||||
/// The project source format.
|
/// The project source format.
|
||||||
pub format: PlcFormat,
|
pub format: PlcFormat,
|
||||||
|
/// The Siemens devices a [`PlcFormat::TiaExport`] declares, read when it
|
||||||
|
/// was uploaded; matched against Siemens' advisories beside the devices
|
||||||
|
/// entered with the target ([`OnboardedTarget::target_devices`]).
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub devices: Vec<super::PlcDevice>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A controller a target runs on and where it is known from.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct TargetDevice {
|
||||||
|
/// The device.
|
||||||
|
pub device: super::PlcDevice,
|
||||||
|
/// The TIA export that declares it (its file name); `None` for a device
|
||||||
|
/// entered with the target.
|
||||||
|
pub exported_in: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<super::PlcDevice> for TargetDevice {
|
||||||
|
fn from(device: super::PlcDevice) -> Self {
|
||||||
|
Self {
|
||||||
|
device,
|
||||||
|
exported_in: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A single fact discovered about a target by ingest or classification
|
/// A single fact discovered about a target by ingest or classification
|
||||||
@@ -354,7 +382,10 @@ impl Artifact {
|
|||||||
/// A PLC-project artifact in the given format.
|
/// A PLC-project artifact in the given format.
|
||||||
pub fn plc_project(source_ref: impl Into<String>, format: PlcFormat) -> Self {
|
pub fn plc_project(source_ref: impl Into<String>, format: PlcFormat) -> Self {
|
||||||
let mut a = Self::bare(ArtifactKind::PlcProject, source_ref);
|
let mut a = Self::bare(ArtifactKind::PlcProject, source_ref);
|
||||||
a.plc = Some(PlcArtifactConfig { format });
|
a.plc = Some(PlcArtifactConfig {
|
||||||
|
format,
|
||||||
|
devices: Vec::new(),
|
||||||
|
});
|
||||||
a
|
a
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -708,6 +739,10 @@ pub struct OnboardedTarget {
|
|||||||
/// order number and firmware against Siemens' CSAF advisories.
|
/// order number and firmware against Siemens' CSAF advisories.
|
||||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
pub devices: Vec<super::PlcDevice>,
|
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.
|
/// Creation timestamp.
|
||||||
#[serde(
|
#[serde(
|
||||||
default = "chrono::Utc::now",
|
default = "chrono::Utc::now",
|
||||||
@@ -771,11 +806,46 @@ impl OnboardedTarget {
|
|||||||
included_until: None,
|
included_until: None,
|
||||||
supplier: None,
|
supplier: None,
|
||||||
devices: Vec::new(),
|
devices: Vec::new(),
|
||||||
|
demo: false,
|
||||||
created_at: now,
|
created_at: now,
|
||||||
updated_at: now,
|
updated_at: now,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The controllers the target runs on: those entered with it, then those
|
||||||
|
/// its TIA exports declare (#1090). An exported device whose order number
|
||||||
|
/// an entered one already names is left out: the entered one says which
|
||||||
|
/// firmware is installed, the export only what was configured.
|
||||||
|
pub fn target_devices(&self) -> Vec<TargetDevice> {
|
||||||
|
let mut devices: Vec<TargetDevice> = self
|
||||||
|
.devices
|
||||||
|
.iter()
|
||||||
|
.cloned()
|
||||||
|
.map(TargetDevice::from)
|
||||||
|
.collect();
|
||||||
|
for artifact in &self.artifacts {
|
||||||
|
let Some(plc) = &artifact.plc else { continue };
|
||||||
|
let file = artifact
|
||||||
|
.display_name
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| artifact.source_ref.clone());
|
||||||
|
for device in &plc.devices {
|
||||||
|
if self
|
||||||
|
.devices
|
||||||
|
.iter()
|
||||||
|
.any(|entered| entered.order_number == device.order_number)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
devices.push(TargetDevice {
|
||||||
|
device: device.clone(),
|
||||||
|
exported_in: Some(file.clone()),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
devices
|
||||||
|
}
|
||||||
|
|
||||||
/// The first artifact of the given kind, if present.
|
/// The first artifact of the given kind, if present.
|
||||||
pub fn first_of(&self, kind: ArtifactKind) -> Option<&Artifact> {
|
pub fn first_of(&self, kind: ArtifactKind) -> Option<&Artifact> {
|
||||||
self.artifacts.iter().find(|a| a.kind == kind)
|
self.artifacts.iter().find(|a| a.kind == kind)
|
||||||
@@ -979,4 +1049,33 @@ mod tests {
|
|||||||
assert!(r.project_id.is_none());
|
assert!(r.project_id.is_none());
|
||||||
assert!(r.last_reconciled_at.is_none());
|
assert!(r.last_reconciled_at.is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn exported_devices_join_the_entered_ones_unless_one_names_their_type() {
|
||||||
|
let device = |order: &str, firmware: &str, label: &str| {
|
||||||
|
super::super::PlcDevice::new(order, firmware, Some(label)).unwrap()
|
||||||
|
};
|
||||||
|
let mut target = OnboardedTarget::new("Linie 1".into(), TargetType::PlcSps);
|
||||||
|
target.devices = vec![device("6ES7511-1AK02-0AB0", "3.1.4", "Zelle 1")];
|
||||||
|
let mut export = Artifact::plc_project("linie1.tia-export.zip", PlcFormat::TiaExport);
|
||||||
|
export.display_name = Some("Linie 1 (TIA V20)".into());
|
||||||
|
if let Some(plc) = export.plc.as_mut() {
|
||||||
|
plc.devices = vec![
|
||||||
|
// Entered with an exact firmware: the export does not add it again.
|
||||||
|
device("6ES7511-1AK02-0AB0", "3.1", "PLC_1"),
|
||||||
|
device("6AV2124-0GC01-0AX0", "17.0", "HMI_1"),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
target.artifacts.push(export);
|
||||||
|
assert_eq!(
|
||||||
|
target.target_devices(),
|
||||||
|
[
|
||||||
|
TargetDevice::from(device("6ES7511-1AK02-0AB0", "3.1.4", "Zelle 1")),
|
||||||
|
TargetDevice {
|
||||||
|
device: device("6AV2124-0GC01-0AX0", "17.0", "HMI_1"),
|
||||||
|
exported_in: Some("Linie 1 (TIA V20)".into()),
|
||||||
|
},
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -324,6 +324,17 @@ pub enum SkipCode {
|
|||||||
/// The month's quota is used up and the Prüftag limit the customer set
|
/// The month's quota is used up and the Prüftag limit the customer set
|
||||||
/// is reached, so this counted Prüfung did not run (t72).
|
/// is reached, so this counted Prüfung did not run (t72).
|
||||||
PrueftagCapReached,
|
PrueftagCapReached,
|
||||||
|
/// PLC blocks a project export holds whose code is not analysed yet
|
||||||
|
/// (TIA export blocks until #1093); `subject` says how many, in which
|
||||||
|
/// languages.
|
||||||
|
PlcBlocksNotAnalysed,
|
||||||
|
/// Know-how-protected PLC blocks, whose code cannot be read and so is
|
||||||
|
/// not analysed; `subject` lists them.
|
||||||
|
ProtectedBlocks,
|
||||||
|
/// Devices a project export names without a Siemens order number or a
|
||||||
|
/// firmware version, so they are not matched against advisories;
|
||||||
|
/// `subject` lists them.
|
||||||
|
DevicesUnmatched,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SkipCode {
|
impl SkipCode {
|
||||||
@@ -360,7 +371,10 @@ impl SkipCode {
|
|||||||
| Self::TooLargeToScan
|
| Self::TooLargeToScan
|
||||||
| Self::ReleaseUnknown
|
| Self::ReleaseUnknown
|
||||||
| Self::PrueftagLimitReached
|
| Self::PrueftagLimitReached
|
||||||
| Self::PrueftagCapReached => false,
|
| Self::PrueftagCapReached
|
||||||
|
| Self::PlcBlocksNotAnalysed
|
||||||
|
| Self::ProtectedBlocks
|
||||||
|
| Self::DevicesUnmatched => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,509 @@
|
|||||||
|
//! The export a TIA Portal connector uploads (#1090): one zip per export of
|
||||||
|
//! an engineering project, read only, with a `manifest.json` at its root.
|
||||||
|
//!
|
||||||
|
//! The manifest says what the project holds: its devices with their order
|
||||||
|
//! numbers and configured firmware (matched against Siemens' advisories like
|
||||||
|
//! a device entered by hand, [`PlcDevice`]), each CPU's security settings,
|
||||||
|
//! and its blocks, naming the know-how-protected ones that cannot be read.
|
||||||
|
//! Block code itself lies beside it under `blocks/` (SimaticML XML, SIMATIC SD
|
||||||
|
//! documents on V21, SCL sources).
|
||||||
|
//!
|
||||||
|
//! The contract is versioned by [`TiaManifest::bundle_version`]; fields this
|
||||||
|
//! version does not know are ignored, so a newer connector can add some
|
||||||
|
//! without breaking an older Prüfwerk. Nothing in it is a secret: a
|
||||||
|
//! connector never exports passwords or keys.
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use super::PlcDevice;
|
||||||
|
|
||||||
|
/// The manifest's file name, at the root of the zip.
|
||||||
|
pub const MANIFEST_NAME: &str = "manifest.json";
|
||||||
|
|
||||||
|
/// The largest manifest read, in bytes. A project with thousands of blocks
|
||||||
|
/// stays well below it.
|
||||||
|
pub const MAX_MANIFEST_BYTES: u64 = 4 << 20;
|
||||||
|
|
||||||
|
/// The bundle versions this Prüfwerk reads.
|
||||||
|
pub const BUNDLE_VERSIONS: std::ops::RangeInclusive<u32> = 1..=1;
|
||||||
|
|
||||||
|
/// The longest device name kept as a device's label; the rest is cut off.
|
||||||
|
const LABEL_MAX_CHARS: usize = 120;
|
||||||
|
|
||||||
|
/// The manifest of a TIA export.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct TiaManifest {
|
||||||
|
/// The contract version the connector wrote (see [`BUNDLE_VERSIONS`]).
|
||||||
|
pub bundle_version: u32,
|
||||||
|
/// The TIA Portal version the project was read with (`V20`, `V21`).
|
||||||
|
pub tia_version: String,
|
||||||
|
/// The engineering project.
|
||||||
|
pub project: TiaProject,
|
||||||
|
/// When the connector read the project (RFC 3339).
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub exported_at: Option<String>,
|
||||||
|
/// The connector that wrote the bundle.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub connector: Option<TiaConnector>,
|
||||||
|
/// The project's devices: CPUs, HMIs, modules.
|
||||||
|
#[serde(default)]
|
||||||
|
pub devices: Vec<TiaDevice>,
|
||||||
|
/// The project's PLC blocks.
|
||||||
|
#[serde(default)]
|
||||||
|
pub blocks: Vec<TiaBlock>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The engineering project a bundle was read from.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct TiaProject {
|
||||||
|
/// The project's name in TIA Portal.
|
||||||
|
pub name: String,
|
||||||
|
/// When the project was last changed (RFC 3339), if TIA says.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub modified: Option<String>,
|
||||||
|
/// Whether the project is protected by user management (UMAC).
|
||||||
|
#[serde(default, skip_serializing_if = "Setting::is_absent")]
|
||||||
|
pub protected: Setting<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The connector that wrote a bundle.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct TiaConnector {
|
||||||
|
/// Its name.
|
||||||
|
pub name: String,
|
||||||
|
/// Its version.
|
||||||
|
pub version: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a device is in the project.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum TiaDeviceRole {
|
||||||
|
/// A PLC CPU.
|
||||||
|
Cpu,
|
||||||
|
/// An HMI panel or PC runtime.
|
||||||
|
Hmi,
|
||||||
|
/// An I/O, communication or other module.
|
||||||
|
Module,
|
||||||
|
/// Anything else, including roles a newer connector names.
|
||||||
|
#[serde(other)]
|
||||||
|
Other,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A device of the project.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct TiaDevice {
|
||||||
|
/// Its name in the project (`PLC_1`).
|
||||||
|
pub name: String,
|
||||||
|
/// What it is.
|
||||||
|
pub role: TiaDeviceRole,
|
||||||
|
/// TIA's type identifier (`OrderNumber:6ES7 515-2UM01-0AB0/V2.9`), from
|
||||||
|
/// which order number and firmware are taken when not given on their own.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub type_identifier: Option<String>,
|
||||||
|
/// The order number (MLFB).
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub order_number: Option<String>,
|
||||||
|
/// The firmware version configured in the project (`V2.9`).
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub firmware: Option<String>,
|
||||||
|
/// A CPU's protection and security settings.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub security: Option<CpuSecurity>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A setting as the connector read it: its value, or why it could not be
|
||||||
|
/// read (Openness throws for some settings, e.g. the access level of a CPU
|
||||||
|
/// without a password). Absent when the connector did not look.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(bound(deserialize = "T: Deserialize<'de>"))]
|
||||||
|
pub struct Setting<T> {
|
||||||
|
/// The value read.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub value: Option<T>,
|
||||||
|
/// Why it could not be read.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub unreadable: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Default for Setting<T> {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
value: None,
|
||||||
|
unreadable: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Setting<T> {
|
||||||
|
/// Whether the connector said nothing about it.
|
||||||
|
pub fn is_absent(&self) -> bool {
|
||||||
|
self.value.is_none() && self.unreadable.is_none()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A CPU's access level ("Protection & Security"), as Openness names it
|
||||||
|
/// (`PlcProtectionAccessLevel`).
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum AccessLevel {
|
||||||
|
/// Full access including fail-safe: no protection.
|
||||||
|
FullAccessIncludingFailsafe,
|
||||||
|
/// Full access: no protection.
|
||||||
|
FullAccess,
|
||||||
|
/// Read access without a password.
|
||||||
|
ReadAccess,
|
||||||
|
/// HMI access only without a password.
|
||||||
|
HmiAccess,
|
||||||
|
/// No access without a password.
|
||||||
|
NoAccess,
|
||||||
|
/// No level set.
|
||||||
|
None,
|
||||||
|
/// A level a newer TIA names.
|
||||||
|
#[serde(other)]
|
||||||
|
Other,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A CPU's protection and security settings as configured in the project
|
||||||
|
/// (not necessarily as on the running machine). Read by #1091's rules.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct CpuSecurity {
|
||||||
|
/// The access level.
|
||||||
|
#[serde(default, skip_serializing_if = "Setting::is_absent")]
|
||||||
|
pub access_level: Setting<AccessLevel>,
|
||||||
|
/// "Permit access with PUT/GET communication from remote partner".
|
||||||
|
#[serde(default, skip_serializing_if = "Setting::is_absent")]
|
||||||
|
pub put_get: Setting<bool>,
|
||||||
|
/// Whether the web server is on.
|
||||||
|
#[serde(default, skip_serializing_if = "Setting::is_absent")]
|
||||||
|
pub web_server: Setting<bool>,
|
||||||
|
/// Whether the web server is reachable over HTTPS only.
|
||||||
|
#[serde(default, skip_serializing_if = "Setting::is_absent")]
|
||||||
|
pub web_server_https_only: Setting<bool>,
|
||||||
|
/// Whether the OPC UA server is on.
|
||||||
|
#[serde(default, skip_serializing_if = "Setting::is_absent")]
|
||||||
|
pub opc_ua_server: Setting<bool>,
|
||||||
|
/// The OPC UA server's security policies (`None`, `Basic256Sha256`, …).
|
||||||
|
#[serde(default, skip_serializing_if = "Setting::is_absent")]
|
||||||
|
pub opc_ua_security_policies: Setting<Vec<String>>,
|
||||||
|
/// "Only allow secure PG/PC and HMI communication".
|
||||||
|
#[serde(default, skip_serializing_if = "Setting::is_absent")]
|
||||||
|
pub secure_pg_hmi_only: Setting<bool>,
|
||||||
|
/// "Protect confidential PLC configuration data".
|
||||||
|
#[serde(default, skip_serializing_if = "Setting::is_absent")]
|
||||||
|
pub confidential_data_protected: Setting<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The kind of a PLC block.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum TiaBlockKind {
|
||||||
|
/// Organization block.
|
||||||
|
Ob,
|
||||||
|
/// Function block.
|
||||||
|
Fb,
|
||||||
|
/// Function.
|
||||||
|
Fc,
|
||||||
|
/// Data block.
|
||||||
|
Db,
|
||||||
|
/// PLC data type.
|
||||||
|
Udt,
|
||||||
|
/// Anything else.
|
||||||
|
#[serde(other)]
|
||||||
|
Other,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A PLC block of the project.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct TiaBlock {
|
||||||
|
/// The device whose program holds it (`PLC_1`).
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub device: Option<String>,
|
||||||
|
/// Its name.
|
||||||
|
pub name: String,
|
||||||
|
/// Its kind.
|
||||||
|
pub kind: TiaBlockKind,
|
||||||
|
/// Its programming language as TIA names it (`SCL`, `LAD`, `FBD`, `GRAPH`).
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub language: Option<String>,
|
||||||
|
/// Where its export lies in the bundle (`blocks/PLC_1/Main.xml`); none
|
||||||
|
/// for a protected block.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub file: Option<String>,
|
||||||
|
/// Whether it is know-how protected, so its code cannot be read.
|
||||||
|
#[serde(default)]
|
||||||
|
pub protected: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a bundle cannot be read.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum TiaBundleError {
|
||||||
|
/// Not a zip file.
|
||||||
|
#[error("not a zip file")]
|
||||||
|
NotZip,
|
||||||
|
/// No `manifest.json` at the root of the zip.
|
||||||
|
#[error("no manifest.json at the root of the zip")]
|
||||||
|
NoManifest,
|
||||||
|
/// The manifest is larger than [`MAX_MANIFEST_BYTES`].
|
||||||
|
#[error("manifest.json is larger than {} MiB", MAX_MANIFEST_BYTES >> 20)]
|
||||||
|
ManifestTooLarge,
|
||||||
|
/// The manifest is not the contract's JSON.
|
||||||
|
#[error("manifest.json is not a TIA export manifest: {0}")]
|
||||||
|
ManifestInvalid(String),
|
||||||
|
/// A bundle version this Prüfwerk does not read.
|
||||||
|
#[error("bundle version {0} is not supported (supported: {min}–{max})", min = BUNDLE_VERSIONS.start(), max = BUNDLE_VERSIONS.end())]
|
||||||
|
BundleVersion(u32),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TiaBundleError {
|
||||||
|
/// A stable name of the refusal, for a client to word in its own
|
||||||
|
/// language.
|
||||||
|
pub fn code(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::NotZip => "not_zip",
|
||||||
|
Self::NoManifest => "no_manifest",
|
||||||
|
Self::ManifestTooLarge => "manifest_too_large",
|
||||||
|
Self::ManifestInvalid(_) => "manifest_invalid",
|
||||||
|
Self::BundleVersion(_) => "bundle_version",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The devices of a manifest as advisories match them: those with a Siemens
|
||||||
|
/// order number and a firmware version, and the names of those without.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||||
|
pub struct ExportedDevices {
|
||||||
|
/// Devices matched against Siemens' advisories, labelled with their
|
||||||
|
/// names in the project.
|
||||||
|
pub matched: Vec<PlcDevice>,
|
||||||
|
/// Names of the devices that cannot be matched: no Siemens order number,
|
||||||
|
/// or no firmware version.
|
||||||
|
pub unmatched: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TiaManifest {
|
||||||
|
/// Read a manifest from its JSON.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// [`TiaBundleError::ManifestTooLarge`] above [`MAX_MANIFEST_BYTES`],
|
||||||
|
/// [`TiaBundleError::ManifestInvalid`] when it is not the contract's
|
||||||
|
/// JSON, [`TiaBundleError::BundleVersion`] for a version outside
|
||||||
|
/// [`BUNDLE_VERSIONS`].
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use compliance_core::models::TiaManifest;
|
||||||
|
///
|
||||||
|
/// let m = TiaManifest::parse(br#"{"bundle_version": 1, "tia_version": "V20",
|
||||||
|
/// "project": {"name": "Linie 1"}}"#).unwrap();
|
||||||
|
/// assert_eq!(m.project.name, "Linie 1");
|
||||||
|
/// ```
|
||||||
|
pub fn parse(json: &[u8]) -> Result<Self, TiaBundleError> {
|
||||||
|
if json.len() as u64 > MAX_MANIFEST_BYTES {
|
||||||
|
return Err(TiaBundleError::ManifestTooLarge);
|
||||||
|
}
|
||||||
|
// The version first, so a newer contract is refused as such rather
|
||||||
|
// than as a manifest that does not parse.
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Version {
|
||||||
|
bundle_version: u32,
|
||||||
|
}
|
||||||
|
let version: Version = serde_json::from_slice(json)
|
||||||
|
.map_err(|e| TiaBundleError::ManifestInvalid(e.to_string()))?;
|
||||||
|
if !BUNDLE_VERSIONS.contains(&version.bundle_version) {
|
||||||
|
return Err(TiaBundleError::BundleVersion(version.bundle_version));
|
||||||
|
}
|
||||||
|
serde_json::from_slice(json).map_err(|e| TiaBundleError::ManifestInvalid(e.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The devices to match against Siemens' advisories, and those that
|
||||||
|
/// cannot be. Order number and firmware come from the device's own
|
||||||
|
/// fields, else from its type identifier.
|
||||||
|
pub fn devices(&self) -> ExportedDevices {
|
||||||
|
let mut out = ExportedDevices::default();
|
||||||
|
for device in &self.devices {
|
||||||
|
let (type_order, type_firmware) = device
|
||||||
|
.type_identifier
|
||||||
|
.as_deref()
|
||||||
|
.map(split_type_identifier)
|
||||||
|
.unwrap_or_default();
|
||||||
|
let order = device.order_number.as_deref().or(type_order);
|
||||||
|
let firmware = device.firmware.as_deref().or(type_firmware);
|
||||||
|
let label: String = device.name.trim().chars().take(LABEL_MAX_CHARS).collect();
|
||||||
|
let matched = match (order, firmware) {
|
||||||
|
(Some(order), Some(firmware)) => {
|
||||||
|
PlcDevice::new(order, firmware, Some(label.as_str())).ok()
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
match matched {
|
||||||
|
Some(d) => out.matched.push(d),
|
||||||
|
None => out.unmatched.push(label),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The names of the know-how-protected blocks, as `device/block` when
|
||||||
|
/// the device is named.
|
||||||
|
pub fn protected_blocks(&self) -> Vec<String> {
|
||||||
|
self.blocks
|
||||||
|
.iter()
|
||||||
|
.filter(|b| b.protected)
|
||||||
|
.map(|b| match &b.device {
|
||||||
|
Some(d) => format!("{d}/{}", b.name),
|
||||||
|
None => b.name.clone(),
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Order number and firmware of a TIA type identifier
|
||||||
|
/// (`OrderNumber:6ES7 515-2UM01-0AB0/V2.9`). The firmware is the segment after
|
||||||
|
/// the order number when it is a version (`/V5.2.3/S120` has `V5.2.3`, a
|
||||||
|
/// catalog variant `//10002` none). A catalog order number with wildcards
|
||||||
|
/// (`6SL3040-1MA01-0Axx`) names no single article, so it is none. A GSD or
|
||||||
|
/// system identifier (`GSD:…`, `System:…`) has neither.
|
||||||
|
fn split_type_identifier(identifier: &str) -> (Option<&str>, Option<&str>) {
|
||||||
|
let Some(rest) = identifier.trim().strip_prefix("OrderNumber:") else {
|
||||||
|
return (None, None);
|
||||||
|
};
|
||||||
|
let mut segments = rest.split('/');
|
||||||
|
let order = segments
|
||||||
|
.next()
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|o| !o.is_empty() && !o.contains(['x', 'X']));
|
||||||
|
let firmware = segments
|
||||||
|
.next()
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|f| f.starts_with(['V', 'v']));
|
||||||
|
(order, firmware)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[allow(clippy::unwrap_used)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
const MANIFEST: &str = r#"{
|
||||||
|
"bundle_version": 1,
|
||||||
|
"tia_version": "V20",
|
||||||
|
"project": {"name": "Linie 1", "protected": {"value": false}},
|
||||||
|
"exported_at": "2026-12-01T10:00:00Z",
|
||||||
|
"connector": {"name": "Breakpilot TIA Connector", "version": "0.1.0"},
|
||||||
|
"devices": [
|
||||||
|
{"name": "PLC_1", "role": "cpu",
|
||||||
|
"type_identifier": "OrderNumber:6ES7 515-2UM01-0AB0/V2.9",
|
||||||
|
"security": {"access_level": {"unreadable": "no password set"},
|
||||||
|
"put_get": {"value": true}}},
|
||||||
|
{"name": "HMI_1", "role": "hmi", "order_number": "6AV2 124-0GC01-0AX0",
|
||||||
|
"firmware": "V17.0.0.0"},
|
||||||
|
{"name": "Drittgeraet", "role": "module", "type_identifier": "GSD:VENDOR.XML/DAP1"},
|
||||||
|
{"name": "Antrieb", "role": "drive", "order_number": "6SL3210-1KE11-8UF2"}
|
||||||
|
],
|
||||||
|
"blocks": [
|
||||||
|
{"device": "PLC_1", "name": "Main", "kind": "ob", "language": "LAD",
|
||||||
|
"file": "blocks/PLC_1/Main.xml"},
|
||||||
|
{"device": "PLC_1", "name": "FB_42", "kind": "fb", "protected": true},
|
||||||
|
{"name": "Rezept", "kind": "udt", "future_field": 1}
|
||||||
|
],
|
||||||
|
"future_section": {"anything": true}
|
||||||
|
}"#;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_manifest_is_read_and_unknown_fields_are_ignored() {
|
||||||
|
let m = TiaManifest::parse(MANIFEST.as_bytes()).unwrap();
|
||||||
|
assert_eq!(m.tia_version, "V20");
|
||||||
|
assert_eq!(m.project.protected.value, Some(false));
|
||||||
|
assert_eq!(m.devices[3].role, TiaDeviceRole::Other);
|
||||||
|
let security = m.devices[0].security.as_ref().unwrap();
|
||||||
|
assert_eq!(security.access_level.value, None);
|
||||||
|
assert_eq!(
|
||||||
|
security.access_level.unreadable.as_deref(),
|
||||||
|
Some("no password set")
|
||||||
|
);
|
||||||
|
assert_eq!(security.put_get.value, Some(true));
|
||||||
|
assert!(security.web_server.is_absent());
|
||||||
|
assert_eq!(m.blocks[2].kind, TiaBlockKind::Udt);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn devices_with_order_number_and_firmware_are_matched_the_rest_named() {
|
||||||
|
let devices = TiaManifest::parse(MANIFEST.as_bytes()).unwrap().devices();
|
||||||
|
assert_eq!(
|
||||||
|
devices.matched,
|
||||||
|
[
|
||||||
|
PlcDevice::new("6ES7515-2UM01-0AB0", "2.9", Some("PLC_1")).unwrap(),
|
||||||
|
PlcDevice::new("6AV2124-0GC01-0AX0", "17.0.0.0", Some("HMI_1")).unwrap(),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
// A GSD device has no order number; the drive no firmware.
|
||||||
|
assert_eq!(devices.unmatched, ["Drittgeraet", "Antrieb"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_type_identifier_yields_only_a_concrete_article_and_its_version() {
|
||||||
|
assert_eq!(
|
||||||
|
split_type_identifier("OrderNumber:6ES7 515-2UM01-0AB0/V2.9"),
|
||||||
|
(Some("6ES7 515-2UM01-0AB0"), Some("V2.9"))
|
||||||
|
);
|
||||||
|
// A family qualifier after the version.
|
||||||
|
assert_eq!(
|
||||||
|
split_type_identifier("OrderNumber:6SL3040-1MA01-0AA0/V5.2.3/S120"),
|
||||||
|
(Some("6SL3040-1MA01-0AA0"), Some("V5.2.3"))
|
||||||
|
);
|
||||||
|
// A catalog variant is no firmware; a wildcard is no article.
|
||||||
|
assert_eq!(
|
||||||
|
split_type_identifier("OrderNumber:6ES7 193-6BP00-0BA0//10002"),
|
||||||
|
(Some("6ES7 193-6BP00-0BA0"), None)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
split_type_identifier("OrderNumber:6SL3040-1MA01-0Axx/V5.2"),
|
||||||
|
(None, Some("V5.2"))
|
||||||
|
);
|
||||||
|
assert_eq!(split_type_identifier("System:Rack.S120"), (None, None));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn protected_blocks_are_named_with_their_device() {
|
||||||
|
let m = TiaManifest::parse(MANIFEST.as_bytes()).unwrap();
|
||||||
|
assert_eq!(m.protected_blocks(), ["PLC_1/FB_42"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_bad_manifest_is_refused_with_its_code() {
|
||||||
|
let code = |json: &str| TiaManifest::parse(json.as_bytes()).unwrap_err().code();
|
||||||
|
assert_eq!(code("not json"), "manifest_invalid");
|
||||||
|
assert_eq!(code(r#"{"tia_version": "V20"}"#), "manifest_invalid");
|
||||||
|
assert_eq!(
|
||||||
|
code(r#"{"bundle_version": 2, "tia_version": "V22", "project": {"name": "x"}}"#),
|
||||||
|
"bundle_version"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
code(r#"{"bundle_version": 1, "tia_version": "V20"}"#),
|
||||||
|
"manifest_invalid"
|
||||||
|
);
|
||||||
|
let huge = vec![b' '; MAX_MANIFEST_BYTES as usize + 1];
|
||||||
|
assert_eq!(
|
||||||
|
TiaManifest::parse(&huge).unwrap_err(),
|
||||||
|
TiaBundleError::ManifestTooLarge
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_long_device_name_is_cut_for_the_label() {
|
||||||
|
let json = format!(
|
||||||
|
r#"{{"bundle_version": 1, "tia_version": "V21", "project": {{"name": "p"}},
|
||||||
|
"devices": [{{"name": "{}", "role": "cpu",
|
||||||
|
"type_identifier": "OrderNumber:6ES7511-1AK02-0AB0/V3.1"}}]}}"#,
|
||||||
|
"x".repeat(500)
|
||||||
|
);
|
||||||
|
let devices = TiaManifest::parse(json.as_bytes()).unwrap().devices();
|
||||||
|
assert_eq!(
|
||||||
|
devices.matched[0].label.as_deref().map(str::len),
|
||||||
|
Some(LABEL_MAX_CHARS)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -148,3 +148,14 @@ fn live_advisories_of_the_default_providers_are_read() {
|
|||||||
assert!(!advisory.vulnerabilities.is_empty());
|
assert!(!advisory.vulnerabilities.is_empty());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_siemens_fix_is_read_from_its_vendor_fix_text_for_the_device_only() {
|
||||||
|
let a = fixture("siemens-synthetic.json");
|
||||||
|
let v = &a.vulnerabilities[0];
|
||||||
|
// Product 2 is fixed at 3.1.5, and the vendor fix for product 1 says
|
||||||
|
// "Update to V3.1.5 or later version": one version.
|
||||||
|
assert_eq!(a.fixed_device_versions(v, "6es7511-1ak02-0ab0"), ["3.1.5"]);
|
||||||
|
// The fix names product 1 only, not the other CPU.
|
||||||
|
assert!(a.fixed_device_versions(v, "6ES7513-1AL02-0AB0").is_empty());
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "compliance-dashboard"
|
name = "compliance-dashboard"
|
||||||
version = "0.4.18"
|
version = "0.4.20"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
default-run = "compliance-dashboard"
|
default-run = "compliance-dashboard"
|
||||||
|
|
||||||
|
|||||||
@@ -369,6 +369,100 @@ code {
|
|||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* The workspace's branding (tenant-registry#155): its CI colour frames every
|
||||||
|
page and its logo stands in for the wordmark. The frame never takes a
|
||||||
|
click, and our own colours (accent, severities) never change with it. */
|
||||||
|
.brand-frame {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
border: 6px solid var(--brand-frame);
|
||||||
|
pointer-events: none;
|
||||||
|
z-index: 80;
|
||||||
|
}
|
||||||
|
|
||||||
|
.customer-logo,
|
||||||
|
.customer-initials {
|
||||||
|
width: 28px;
|
||||||
|
height: 28px;
|
||||||
|
border-radius: var(--radius);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.customer-logo {
|
||||||
|
object-fit: contain;
|
||||||
|
}
|
||||||
|
|
||||||
|
.customer-initials {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
background: var(--brand-frame, var(--bg-elevated));
|
||||||
|
font-weight: 700;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand-name.customer-name {
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand-credit {
|
||||||
|
padding: 8px 14px 0;
|
||||||
|
font-size: 11px;
|
||||||
|
color: var(--text-tertiary);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.branding-notice {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px 16px;
|
||||||
|
padding: 12px 16px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
/* Clear of the notification bell, fixed at the top right. */
|
||||||
|
margin-right: 56px;
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
background: var(--bg-card);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
/* The bell sits in the top bar there. */
|
||||||
|
.branding-notice {
|
||||||
|
margin-right: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.branding-notice .customer-logo,
|
||||||
|
.branding-notice .customer-initials {
|
||||||
|
width: 32px;
|
||||||
|
height: 32px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.branding-notice-text {
|
||||||
|
flex: 1 1 280px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 2px;
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.branding-notice-text strong {
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.branding-notice-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
.sidebar-nav {
|
.sidebar-nav {
|
||||||
padding: 8px 8px 16px;
|
padding: 8px 8px 16px;
|
||||||
flex: 1;
|
flex: 1;
|
||||||
@@ -9684,3 +9778,258 @@ div.offer-option { flex-direction: column; align-items: flex-start; justify-cont
|
|||||||
}
|
}
|
||||||
.offer-waiting-dot { width: 8px; height: 8px; border-radius: 4px; background: var(--accent); }
|
.offer-waiting-dot { width: 8px; height: 8px; border-radius: 4px; background: var(--accent); }
|
||||||
.offer-waiting-go { margin-left: auto; font-weight: 600; color: var(--accent); }
|
.offer-waiting-go { margin-left: auto; font-weight: 600; color: var(--accent); }
|
||||||
|
|
||||||
|
/* A target's Siemens controllers (SPS item 4a): modules on a DIN rail. */
|
||||||
|
.dev-page {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 22px;
|
||||||
|
min-width: 0;
|
||||||
|
max-width: 1280px;
|
||||||
|
}
|
||||||
|
.dev-page > * { min-width: 0; }
|
||||||
|
.dev-rail-card {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 16px;
|
||||||
|
padding: 24px 24px 20px;
|
||||||
|
}
|
||||||
|
.dev-legend {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px 28px;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
list-style: none;
|
||||||
|
font-size: 14px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
.dev-legend li { display: flex; align-items: center; gap: 8px; }
|
||||||
|
.dev-led {
|
||||||
|
display: inline-block;
|
||||||
|
flex: none;
|
||||||
|
width: 10px;
|
||||||
|
height: 10px;
|
||||||
|
border-radius: 50%;
|
||||||
|
}
|
||||||
|
.dev-led-affected { background: var(--danger); box-shadow: 0 0 0 3px var(--danger-bg); }
|
||||||
|
.dev-led-clear { background: var(--success); box-shadow: 0 0 0 3px var(--success-bg); }
|
||||||
|
.dev-led-unnamed { background: #8C91AE; box-shadow: 0 0 0 3px rgb(140 145 174 / 0.25); }
|
||||||
|
.dev-rail-scroll { overflow-x: auto; padding-bottom: 4px; }
|
||||||
|
.dev-rail {
|
||||||
|
position: relative;
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-end;
|
||||||
|
gap: 6px;
|
||||||
|
min-width: max-content;
|
||||||
|
padding: 8px 12px 18px;
|
||||||
|
}
|
||||||
|
.dev-rail-bar {
|
||||||
|
position: absolute;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 4px;
|
||||||
|
height: 26px;
|
||||||
|
border-radius: 3px;
|
||||||
|
background: repeating-linear-gradient(90deg, var(--border-bright) 0 22px, var(--border-strong) 22px 24px);
|
||||||
|
border-top: 2px solid var(--border);
|
||||||
|
border-bottom: 2px solid var(--border-strong);
|
||||||
|
}
|
||||||
|
/* The module is a device's housing: dark in either theme. */
|
||||||
|
.dev-module {
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
width: 148px;
|
||||||
|
height: 236px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
padding: 12px;
|
||||||
|
border: none;
|
||||||
|
border-radius: 8px 8px 4px 4px;
|
||||||
|
background: linear-gradient(180deg, #2E3250 0%, #262A44 100%);
|
||||||
|
box-shadow: 0 4px 12px rgb(20 22 43 / 0.18);
|
||||||
|
color: #fff;
|
||||||
|
text-align: left;
|
||||||
|
font: inherit;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: transform 160ms ease, box-shadow 160ms ease;
|
||||||
|
}
|
||||||
|
.dev-module-on {
|
||||||
|
transform: translateY(-6px);
|
||||||
|
box-shadow: 0 0 0 3px var(--accent), 0 10px 24px rgb(20 22 43 / 0.25);
|
||||||
|
}
|
||||||
|
.dev-module:focus-visible { outline: 3px solid var(--accent); outline-offset: 3px; }
|
||||||
|
.dev-module-top { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||||
|
.dev-module-brand { font-size: 11px; letter-spacing: 0.02em; color: #C9CDE0; }
|
||||||
|
.dev-module-face {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
height: 40px;
|
||||||
|
border-radius: 4px;
|
||||||
|
background: #1D2033;
|
||||||
|
color: #8C91AE;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
.dev-module-names { display: flex; flex-direction: column; gap: 2px; }
|
||||||
|
.dev-module-short { font-size: 13px; font-weight: 600; line-height: 1.25; overflow-wrap: anywhere; }
|
||||||
|
.dev-module-label { font-size: 12px; color: #C9CDE0; overflow-wrap: anywhere; }
|
||||||
|
.dev-module-vents { display: flex; flex-direction: column; gap: 3px; }
|
||||||
|
.dev-module-vents span { height: 3px; border-radius: 2px; background: #3A3F5C; }
|
||||||
|
.dev-module-fw { font-size: 12px; color: #C9CDE0; font-variant-numeric: tabular-nums; }
|
||||||
|
.dev-add {
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 10px;
|
||||||
|
width: 148px;
|
||||||
|
height: 236px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
padding: 12px;
|
||||||
|
border: 2px dashed var(--border-strong);
|
||||||
|
border-radius: 8px 8px 4px 4px;
|
||||||
|
background: var(--bg-card);
|
||||||
|
color: var(--text-tertiary);
|
||||||
|
font: inherit;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.dev-add-on { border-color: var(--accent); background: var(--accent-muted); color: var(--accent); }
|
||||||
|
.dev-add:focus-visible { outline: 3px solid var(--accent); outline-offset: 3px; }
|
||||||
|
.dev-empty { margin: 0; color: var(--text-secondary); }
|
||||||
|
.dev-body { display: flex; flex-wrap: wrap; gap: 24px; align-items: flex-start; }
|
||||||
|
.dev-detail,
|
||||||
|
.dev-form {
|
||||||
|
flex: 999 1 560px;
|
||||||
|
min-width: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 20px;
|
||||||
|
padding: 24px;
|
||||||
|
}
|
||||||
|
.dev-detail h2,
|
||||||
|
.dev-form h2 { margin: 0; font-size: 22px; font-weight: 600; }
|
||||||
|
.dev-detail-head { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 12px; align-items: flex-start; }
|
||||||
|
.dev-detail-head > div:first-child { display: flex; flex-direction: column; gap: 4px; }
|
||||||
|
.dev-detail-label { font-size: 14px; color: var(--text-tertiary); }
|
||||||
|
.dev-detail-actions { display: flex; gap: 8px; }
|
||||||
|
.dev-detail-actions .btn { min-height: 44px; }
|
||||||
|
.btn-danger-ghost { color: var(--danger); border-color: var(--danger-bg); }
|
||||||
|
.dev-figures {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
.dev-figures > div {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
padding: 12px 14px;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: var(--bg-primary);
|
||||||
|
}
|
||||||
|
.dev-figures dt { font-size: 13px; color: var(--text-tertiary); }
|
||||||
|
.dev-figures dd {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
margin: 0;
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: 500;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
.dev-firmware-edit { flex-wrap: wrap; }
|
||||||
|
.dev-firmware-edit input { width: 9em; min-height: 40px; }
|
||||||
|
.dev-field-note { margin: 0; font-size: 13px; color: var(--warning); }
|
||||||
|
.dev-state {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 14px 16px;
|
||||||
|
border-radius: 10px;
|
||||||
|
font-size: 15px;
|
||||||
|
line-height: 1.45;
|
||||||
|
}
|
||||||
|
.dev-state .dev-led { width: 12px; height: 12px; }
|
||||||
|
.dev-state-affected { background: var(--danger-bg); }
|
||||||
|
.dev-state-clear { background: var(--success-bg); }
|
||||||
|
.dev-state-unnamed { background: var(--bg-elevated); }
|
||||||
|
.dev-advisories { display: flex; flex-direction: column; gap: 10px; }
|
||||||
|
.dev-advisories h3 { margin: 0; font-size: 15px; font-weight: 600; }
|
||||||
|
.dev-advisory {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px 16px;
|
||||||
|
padding: 12px 14px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 10px;
|
||||||
|
}
|
||||||
|
.dev-advisory-clear { opacity: 0.72; }
|
||||||
|
.dev-advisory .badge { flex: none; min-width: 72px; text-align: center; }
|
||||||
|
.dev-advisory-text { flex: 1 1 260px; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
|
||||||
|
.dev-advisory-title { font-size: 14px; font-weight: 500; }
|
||||||
|
.dev-advisory-meta { font-size: 13px; color: var(--text-tertiary); }
|
||||||
|
.dev-verdict { font-size: 13px; font-weight: 500; color: var(--success); white-space: nowrap; }
|
||||||
|
.dev-verdict-affected { color: var(--danger); }
|
||||||
|
.dev-source { font-size: 13px; }
|
||||||
|
.dev-to-cves { align-self: flex-start; font-size: 14px; font-weight: 500; }
|
||||||
|
.dev-form-fields {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
.dev-form-fields label {
|
||||||
|
font-family: var(--font-body);
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 500;
|
||||||
|
letter-spacing: normal;
|
||||||
|
text-transform: none;
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
.dev-form-fields input { min-height: 44px; font-size: 16px; font-variant-numeric: tabular-nums; }
|
||||||
|
.dev-recognised {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 12px 14px;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: var(--bg-elevated);
|
||||||
|
color: var(--text-secondary);
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 1.45;
|
||||||
|
}
|
||||||
|
.dev-recognised svg { flex: none; margin-top: 2px; }
|
||||||
|
.dev-recognised-bad { background: var(--warning-bg); color: var(--warning); }
|
||||||
|
.dev-recognised-known { background: var(--success-bg); color: var(--success); }
|
||||||
|
.dev-help { font-size: 14px; color: var(--text-secondary); }
|
||||||
|
.dev-help summary { min-height: 32px; color: var(--text-primary); font-weight: 500; cursor: pointer; }
|
||||||
|
.dev-help ul { display: flex; flex-direction: column; gap: 6px; margin: 8px 0 0; padding-left: 20px; line-height: 1.45; }
|
||||||
|
.dev-form-actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||||
|
.dev-form-actions .btn { min-height: 44px; }
|
||||||
|
.dev-how {
|
||||||
|
flex: 1 1 280px;
|
||||||
|
min-width: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 12px;
|
||||||
|
padding-top: 4px;
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 1.5;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
.dev-how h2 { margin: 0; font-size: 15px; font-weight: 600; color: var(--text-primary); }
|
||||||
|
.dev-how p { margin: 0; }
|
||||||
|
.dev-card-lights { display: flex; flex-wrap: wrap; gap: 10px; padding: 6px 3px; }
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.dev-module { transition: none; }
|
||||||
|
.dev-module-on { transform: none; }
|
||||||
|
}
|
||||||
@@ -48,6 +48,10 @@ pub enum Route {
|
|||||||
// and its published versions (#1028).
|
// and its published versions (#1028).
|
||||||
#[route("/targets/:id/releases")]
|
#[route("/targets/:id/releases")]
|
||||||
TargetReleasesPage { id: String },
|
TargetReleasesPage { id: String },
|
||||||
|
// The Siemens controllers it runs on, against Siemens' advisories
|
||||||
|
// (SPS item 4a).
|
||||||
|
#[route("/targets/:id/devices")]
|
||||||
|
TargetDevicesPage { id: String },
|
||||||
// A machine (#1026): a product project and its targets; `?tab=`
|
// A machine (#1026): a product project and its targets; `?tab=`
|
||||||
// `parts` (the default), `cves` or `history`.
|
// `parts` (the default), `cves` or `history`.
|
||||||
#[route("/projects/:id?:tab")]
|
#[route("/projects/:id?:tab")]
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
use dioxus::prelude::*;
|
use dioxus::prelude::*;
|
||||||
|
|
||||||
use crate::app::Route;
|
use crate::app::Route;
|
||||||
|
use crate::components::branding::BrandingNotice;
|
||||||
use crate::components::help_chat::HelpChat;
|
use crate::components::help_chat::HelpChat;
|
||||||
use crate::components::no_access::{NoAccess, ReadOnlyBanner};
|
use crate::components::no_access::{NoAccess, ReadOnlyBanner};
|
||||||
use crate::components::notification_bell::NotificationBell;
|
use crate::components::notification_bell::NotificationBell;
|
||||||
@@ -25,8 +26,13 @@ pub fn AppShell() -> Element {
|
|||||||
// then takes it away; an unreachable agent reads as the full set.
|
// then takes it away; an unreachable agent reads as the full set.
|
||||||
let platform = use_server_future(fetch_platform_info)?;
|
let platform = use_server_future(fetch_platform_info)?;
|
||||||
let auth = use_server_future(check_auth)?;
|
let auth = use_server_future(check_auth)?;
|
||||||
|
// The workspace's branding (tenant-registry#155), read with the page so
|
||||||
|
// the frame never appears a moment late; none when it cannot be read.
|
||||||
|
let branding = use_server_future(crate::infrastructure::branding::fetch_branding)?;
|
||||||
let platform_now = platform().and_then(Result::ok).unwrap_or_default();
|
let platform_now = platform().and_then(Result::ok).unwrap_or_default();
|
||||||
use_context_provider(|| Signal::new(platform_now));
|
use_context_provider(|| Signal::new(platform_now));
|
||||||
|
let branding_now = branding().and_then(Result::ok).unwrap_or_default();
|
||||||
|
use_context_provider(|| Signal::new(branding_now.clone()));
|
||||||
// A sign-in can run out while a page stays open: check now and then, and
|
// A sign-in can run out while a page stays open: check now and then, and
|
||||||
// send the browser to the login rather than letting every page fail.
|
// send the browser to the login rather than letting every page fail.
|
||||||
use_future(move || async move {
|
use_future(move || async move {
|
||||||
@@ -68,8 +74,19 @@ pub fn AppShell() -> Element {
|
|||||||
Some(Ok(info)) if info.authenticated => {
|
Some(Ok(info)) if info.authenticated => {
|
||||||
use_context_provider(|| Signal::new(info.clone()));
|
use_context_provider(|| Signal::new(info.clone()));
|
||||||
let read_only = !info.access.can_write();
|
let read_only = !info.access.can_write();
|
||||||
|
let shell_class = if branding_now.framed() {
|
||||||
|
"app-shell branded"
|
||||||
|
} else {
|
||||||
|
"app-shell"
|
||||||
|
};
|
||||||
|
let frame_style = branding_now.frame_style();
|
||||||
rsx! {
|
rsx! {
|
||||||
div { class: "app-shell",
|
div { class: "{shell_class}", style: "{frame_style}",
|
||||||
|
// The workspace's CI colour around every page; it never
|
||||||
|
// takes a click.
|
||||||
|
if branding_now.framed() {
|
||||||
|
div { class: "brand-frame", "aria-hidden": "true" }
|
||||||
|
}
|
||||||
Sidebar {}
|
Sidebar {}
|
||||||
main { class: "main-content",
|
main { class: "main-content",
|
||||||
if let Some(tenant) = info.support_tenant.clone() {
|
if let Some(tenant) = info.support_tenant.clone() {
|
||||||
@@ -78,6 +95,7 @@ pub fn AppShell() -> Element {
|
|||||||
if read_only {
|
if read_only {
|
||||||
ReadOnlyBanner {}
|
ReadOnlyBanner {}
|
||||||
}
|
}
|
||||||
|
BrandingNotice {}
|
||||||
Outlet::<Route> {}
|
Outlet::<Route> {}
|
||||||
}
|
}
|
||||||
NotificationBell {}
|
NotificationBell {}
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
//! The workspace's branding in the app (tenant-registry#155): its mark in the
|
||||||
|
//! sidebar and the one-time notice for its admins. The frame itself is the
|
||||||
|
//! app shell's.
|
||||||
|
|
||||||
|
use dioxus::prelude::*;
|
||||||
|
|
||||||
|
use crate::i18n::texts::branding as tx;
|
||||||
|
use crate::i18n::use_lang;
|
||||||
|
use crate::infrastructure::branding::{ack_branding, Branding, LOGO_URL};
|
||||||
|
use compliance_core::models::AuthInfo;
|
||||||
|
|
||||||
|
/// The workspace's branding, provided by the app shell; none outside it.
|
||||||
|
pub fn use_branding() -> Branding {
|
||||||
|
try_use_context::<Signal<Branding>>()
|
||||||
|
.map(|b| b.read().clone())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The workspace in the sidebar: its logo, or its initials on its CI colour,
|
||||||
|
/// and unless `with_name` is off its name with "Prüfwerk" beneath.
|
||||||
|
#[component]
|
||||||
|
pub fn CustomerMark(branding: Branding, with_name: bool) -> Element {
|
||||||
|
let lang = use_lang()();
|
||||||
|
let initials = branding.initials();
|
||||||
|
let ink = branding.ink();
|
||||||
|
let name = branding.name.clone().unwrap_or_default();
|
||||||
|
rsx! {
|
||||||
|
if branding.logo {
|
||||||
|
img { class: "customer-logo", src: LOGO_URL, alt: "" }
|
||||||
|
} else {
|
||||||
|
span {
|
||||||
|
class: "customer-initials",
|
||||||
|
style: "color: {ink};",
|
||||||
|
"aria-hidden": "true",
|
||||||
|
"{initials}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if with_name {
|
||||||
|
div { class: "brand-text",
|
||||||
|
if name.is_empty() {
|
||||||
|
span { class: "brand-name", {tx::PRODUCT.get(lang)} }
|
||||||
|
} else {
|
||||||
|
span { class: "brand-name customer-name", "{name}" }
|
||||||
|
span { class: "brand-sub", {tx::PRODUCT.get(lang)} }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "Logo und Farbe von <domain> übernommen", for the workspace's admins only
|
||||||
|
/// (the agent sends `notice` to no one else), until one of them says "Passt".
|
||||||
|
/// "Passt" hides it at once; the registry records it in the background.
|
||||||
|
#[component]
|
||||||
|
pub fn BrandingNotice() -> Element {
|
||||||
|
let lang = use_lang()();
|
||||||
|
let branding = use_branding();
|
||||||
|
let mut hidden = use_signal(|| false);
|
||||||
|
let portal_url = try_use_context::<Signal<AuthInfo>>()
|
||||||
|
.map(|a| a.read().portal_url.clone())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let Some(domain) = branding.domain.clone().filter(|_| branding.notice) else {
|
||||||
|
return rsx! {};
|
||||||
|
};
|
||||||
|
if hidden() {
|
||||||
|
return rsx! {};
|
||||||
|
}
|
||||||
|
rsx! {
|
||||||
|
div { class: "branding-notice", role: "status",
|
||||||
|
CustomerMark { branding: branding.clone(), with_name: false }
|
||||||
|
div { class: "branding-notice-text",
|
||||||
|
strong { {tx::notice_title(&domain, lang)} }
|
||||||
|
span { {tx::NOTICE_BODY.get(lang)} }
|
||||||
|
}
|
||||||
|
div { class: "branding-notice-actions",
|
||||||
|
button {
|
||||||
|
r#type: "button",
|
||||||
|
class: "btn btn-primary",
|
||||||
|
onclick: move |_| {
|
||||||
|
hidden.set(true);
|
||||||
|
spawn(async move {
|
||||||
|
if let Err(e) = ack_branding().await {
|
||||||
|
tracing::warn!("branding ack failed: {e}");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
{tx::OK.get(lang)}
|
||||||
|
}
|
||||||
|
if !portal_url.is_empty() {
|
||||||
|
a { class: "btn btn-secondary", href: "{portal_url}", {tx::CHANGE.get(lang)} }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ pub mod app_shell;
|
|||||||
pub mod artifact_upload;
|
pub mod artifact_upload;
|
||||||
pub mod attack_chain;
|
pub mod attack_chain;
|
||||||
pub mod billing_swap;
|
pub mod billing_swap;
|
||||||
|
pub mod branding;
|
||||||
pub mod code_inspector;
|
pub mod code_inspector;
|
||||||
pub mod code_snippet;
|
pub mod code_snippet;
|
||||||
pub mod component_overview;
|
pub mod component_overview;
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ use dioxus_free_icons::icons::bs_icons::*;
|
|||||||
use dioxus_free_icons::Icon;
|
use dioxus_free_icons::Icon;
|
||||||
|
|
||||||
use crate::app::Route;
|
use crate::app::Route;
|
||||||
|
use crate::components::branding::{use_branding, CustomerMark};
|
||||||
use crate::components::lang_toggle::LangToggle;
|
use crate::components::lang_toggle::LangToggle;
|
||||||
use crate::components::no_access::use_can_write;
|
use crate::components::no_access::use_can_write;
|
||||||
use crate::components::theme_toggle::ThemeToggle;
|
use crate::components::theme_toggle::ThemeToggle;
|
||||||
@@ -39,6 +40,7 @@ pub fn Sidebar() -> Element {
|
|||||||
let mut collapsed = use_signal(|| false);
|
let mut collapsed = use_signal(|| false);
|
||||||
let source_only = use_source_only();
|
let source_only = use_source_only();
|
||||||
let lang = use_lang()();
|
let lang = use_lang()();
|
||||||
|
let branding = use_branding();
|
||||||
|
|
||||||
let can_write = use_can_write();
|
let can_write = use_can_write();
|
||||||
// Open supplier offers, counted on "Prüfobjekte" (#1028).
|
// Open supplier offers, counted on "Prüfobjekte" (#1028).
|
||||||
@@ -152,7 +154,13 @@ pub fn Sidebar() -> Element {
|
|||||||
Icon { icon: BsList, width: 20, height: 20 }
|
Icon { icon: BsList, width: 20, height: 20 }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
div { class: "mobile-bar-brand", Wordmark { with_name: true } }
|
div { class: "mobile-bar-brand",
|
||||||
|
if branding.branded() {
|
||||||
|
CustomerMark { branding: branding.clone(), with_name: true }
|
||||||
|
} else {
|
||||||
|
Wordmark { with_name: true }
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if mobile_open() {
|
if mobile_open() {
|
||||||
div { class: "mobile-backdrop", onclick: move |_| mobile_open.set(false) }
|
div { class: "mobile-backdrop", onclick: move |_| mobile_open.set(false) }
|
||||||
@@ -161,7 +169,11 @@ pub fn Sidebar() -> Element {
|
|||||||
// The breakpilot brand, as the portal shows it; Prüfwerk is the
|
// The breakpilot brand, as the portal shows it; Prüfwerk is the
|
||||||
// product within it.
|
// product within it.
|
||||||
div { class: "sidebar-header",
|
div { class: "sidebar-header",
|
||||||
Wordmark { with_name: !collapsed() }
|
if branding.branded() {
|
||||||
|
CustomerMark { branding: branding.clone(), with_name: !collapsed() }
|
||||||
|
} else {
|
||||||
|
Wordmark { with_name: !collapsed() }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if !portal_url.is_empty() {
|
if !portal_url.is_empty() {
|
||||||
a {
|
a {
|
||||||
@@ -296,6 +308,9 @@ pub fn Sidebar() -> Element {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if !collapsed() && branding.branded() {
|
||||||
|
div { class: "brand-credit", {crate::i18n::texts::branding::CREDIT.get(lang)} }
|
||||||
|
}
|
||||||
if !collapsed() {
|
if !collapsed() {
|
||||||
div { class: "sidebar-legal",
|
div { class: "sidebar-legal",
|
||||||
a { href: PRIVACY_URL, target: "_blank", rel: "noopener", {nav::PRIVACY.get(lang)} }
|
a { href: PRIVACY_URL, target: "_blank", rel: "noopener", {nav::PRIVACY.get(lang)} }
|
||||||
|
|||||||
@@ -819,6 +819,24 @@ pub mod scans {
|
|||||||
(SkipCode::NativePlcProject, Lang::En) => format!(
|
(SkipCode::NativePlcProject, Lang::En) => format!(
|
||||||
"CODESYS project in its native format, control logic not analysed: {subject}. Export the POUs as PLCopen XML (Project → Export PLCopenXML) and add the export to the target."
|
"CODESYS project in its native format, control logic not analysed: {subject}. Export the POUs as PLCopen XML (Project → Export PLCopenXML) and add the export to the target."
|
||||||
),
|
),
|
||||||
|
(SkipCode::PlcBlocksNotAnalysed, Lang::De) => format!(
|
||||||
|
"Bausteine aus dem TIA-Export, Code noch nicht analysiert: {subject}"
|
||||||
|
),
|
||||||
|
(SkipCode::PlcBlocksNotAnalysed, Lang::En) => format!(
|
||||||
|
"Blocks from the TIA export, code not analysed yet: {subject}"
|
||||||
|
),
|
||||||
|
(SkipCode::ProtectedBlocks, Lang::De) => format!(
|
||||||
|
"Know-how-geschützte Bausteine, nicht analysierbar: {subject}"
|
||||||
|
),
|
||||||
|
(SkipCode::ProtectedBlocks, Lang::En) => format!(
|
||||||
|
"Know-how-protected blocks, which cannot be analysed: {subject}"
|
||||||
|
),
|
||||||
|
(SkipCode::DevicesUnmatched, Lang::De) => format!(
|
||||||
|
"Geräte ohne Siemens-Bestellnummer oder Firmware, nicht mit Advisories abgeglichen: {subject}"
|
||||||
|
),
|
||||||
|
(SkipCode::DevicesUnmatched, Lang::En) => format!(
|
||||||
|
"Devices without a Siemens order number or firmware, not matched against advisories: {subject}"
|
||||||
|
),
|
||||||
(SkipCode::ToolFailed, Lang::De) => format!(
|
(SkipCode::ToolFailed, Lang::De) => format!(
|
||||||
"{subject} wurde nicht fertig; was es prüft, gilt als nicht bewertet."
|
"{subject} wurde nicht fertig; was es prüft, gilt als nicht bewertet."
|
||||||
),
|
),
|
||||||
@@ -3169,6 +3187,26 @@ pub mod sbom {
|
|||||||
requirements.txt; for JavaScript, npm install writes package-lock.json; for Rust, \
|
requirements.txt; for JavaScript, npm install writes package-lock.json; for Rust, \
|
||||||
commit Cargo.lock. After the next scan the components are listed here.",
|
commit Cargo.lock. After the next scan the components are listed here.",
|
||||||
};
|
};
|
||||||
|
/// Why a PLC target's component table is empty.
|
||||||
|
pub const EMPTY_WHY_PLC: Text = Text {
|
||||||
|
de: "Bei einer SPS-Anwendung entsteht die Stückliste aus den Bibliotheken und der \
|
||||||
|
Laufzeit eines CODESYS-Projektarchivs (.projectarchive) und aus den \
|
||||||
|
Siemens-Steuerungen, die auf der Seite „Steuerungen“ des Prüfobjekts eingetragen \
|
||||||
|
sind. Structured Text und PLCopen XML allein nennen keine Komponenten.",
|
||||||
|
en: "For a PLC application the SBOM is built from the libraries and runtime in a \
|
||||||
|
CODESYS project archive (.projectarchive) and from the Siemens controllers \
|
||||||
|
entered on the target's Controllers page. Structured Text and PLCopen XML alone \
|
||||||
|
name no components.",
|
||||||
|
};
|
||||||
|
/// How to fill a PLC target's component table, by example.
|
||||||
|
pub const EMPTY_EXAMPLE_PLC: Text = Text {
|
||||||
|
de: "Zum Beispiel: Tragen Sie auf der Seite „Steuerungen“ die CPU mit Artikelnummer \
|
||||||
|
und Firmware ein (etwa 6ES7511-1AK02-0AB0, V2.9.4), oder laden Sie das \
|
||||||
|
CODESYS-Projektarchiv hoch. Nach der nächsten Prüfung stehen die Komponenten hier.",
|
||||||
|
en: "For example: enter the CPU with its order number and firmware on the Controllers \
|
||||||
|
page (such as 6ES7511-1AK02-0AB0, V2.9.4), or upload the CODESYS project archive. \
|
||||||
|
After the next scan the components are listed here.",
|
||||||
|
};
|
||||||
/// Above the open findings that say what is missing.
|
/// Above the open findings that say what is missing.
|
||||||
pub const EMPTY_FINDINGS: Text = Text {
|
pub const EMPTY_FINDINGS: Text = Text {
|
||||||
de: "Was in diesem Prüfobjekt fehlt und wie Sie es ergänzen:",
|
de: "Was in diesem Prüfobjekt fehlt und wie Sie es ergänzen:",
|
||||||
@@ -5783,6 +5821,42 @@ pub mod metering {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// "1 zusätzliches Prüfobjekt", or that every target is included.
|
/// "1 zusätzliches Prüfobjekt", or that every target is included.
|
||||||
|
/// The plan's refusal of a new target (`target_limit`): its places are
|
||||||
|
/// all taken.
|
||||||
|
pub const TARGET_LIMIT: Text = Text {
|
||||||
|
de: "Ihr Tarif enthält keine weiteren Prüfobjekte. Löschen Sie ein Prüfobjekt, \
|
||||||
|
um ein neues anzulegen (seine Ergebnisse werden mit gelöscht), oder wechseln \
|
||||||
|
Sie den Tarif.",
|
||||||
|
en: "Your plan includes no further targets. Delete a target to add a new one \
|
||||||
|
(its results are deleted with it), or change your plan.",
|
||||||
|
};
|
||||||
|
/// The plan's refusal to make a demo target the tenant's own
|
||||||
|
/// (`target_limit`): other sources would make it count, and its places
|
||||||
|
/// are all taken.
|
||||||
|
pub const DEMO_LIMIT: Text = Text {
|
||||||
|
de: "Mit eigenen Dateien oder Quellen zählt ein Demo-Prüfobjekt wie Ihre anderen, \
|
||||||
|
und Ihr Tarif enthält keine weiteren Prüfobjekte. Löschen Sie ein anderes \
|
||||||
|
Prüfobjekt (seine Ergebnisse werden mit gelöscht) oder wechseln Sie den Tarif.",
|
||||||
|
en: "With your own files or sources a demo target counts like your other targets, \
|
||||||
|
and your plan includes no further targets. Delete another target (its results \
|
||||||
|
are deleted with it) or change your plan.",
|
||||||
|
};
|
||||||
|
/// A failed creation of a target in words: the plan's refusal as
|
||||||
|
/// [`TARGET_LIMIT`], anything else as it came.
|
||||||
|
pub fn target_refusal(error: &str, lang: Lang) -> String {
|
||||||
|
plan_refusal(error, &TARGET_LIMIT, lang)
|
||||||
|
}
|
||||||
|
/// A failed change of a target's artifacts in words: the plan's refusal
|
||||||
|
/// as [`DEMO_LIMIT`], anything else as it came.
|
||||||
|
pub fn demo_refusal(error: &str, lang: Lang) -> String {
|
||||||
|
plan_refusal(error, &DEMO_LIMIT, lang)
|
||||||
|
}
|
||||||
|
fn plan_refusal(error: &str, text: &Text, lang: Lang) -> String {
|
||||||
|
match crate::i18n::agent_code(error, &["target_limit"]) {
|
||||||
|
Some(_) => text.get(lang).to_string(),
|
||||||
|
None => error.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
pub fn extra_targets(extra: u32, lang: Lang) -> String {
|
pub fn extra_targets(extra: u32, lang: Lang) -> String {
|
||||||
match (lang, extra) {
|
match (lang, extra) {
|
||||||
(Lang::De, 0) => "Alle Prüfobjekte im Tarif enthalten".to_string(),
|
(Lang::De, 0) => "Alle Prüfobjekte im Tarif enthalten".to_string(),
|
||||||
@@ -8839,11 +8913,12 @@ pub mod offers {
|
|||||||
|
|
||||||
/// The agent's refusal `error` in words; anything else as it came.
|
/// The agent's refusal `error` in words; anything else as it came.
|
||||||
pub fn refusal(error: &str, lang: Lang) -> String {
|
pub fn refusal(error: &str, lang: Lang) -> String {
|
||||||
const CODES: [&str; 4] = [
|
const CODES: [&str; 5] = [
|
||||||
"answered",
|
"answered",
|
||||||
"ended",
|
"ended",
|
||||||
"target_taken",
|
"target_taken",
|
||||||
"not_supplier_component",
|
"not_supplier_component",
|
||||||
|
"target_limit",
|
||||||
];
|
];
|
||||||
let text = match crate::i18n::agent_code(error, &CODES) {
|
let text = match crate::i18n::agent_code(error, &CODES) {
|
||||||
Some("answered") => Text {
|
Some("answered") => Text {
|
||||||
@@ -8863,8 +8938,330 @@ pub mod offers {
|
|||||||
de: "Nur eine zugekaufte Komponente kann eine SBOM eines Zulieferers erhalten.",
|
de: "Nur eine zugekaufte Komponente kann eine SBOM eines Zulieferers erhalten.",
|
||||||
en: "Only a bought-in component can receive a supplier's SBOM.",
|
en: "Only a bought-in component can receive a supplier's SBOM.",
|
||||||
},
|
},
|
||||||
|
Some("target_limit") => super::metering::TARGET_LIMIT,
|
||||||
_ => return error.to_string(),
|
_ => return error.to_string(),
|
||||||
};
|
};
|
||||||
text.get(lang).to_string()
|
text.get(lang).to_string()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A target's Siemens controllers (SPS item 4a).
|
||||||
|
pub mod devices {
|
||||||
|
use super::Text;
|
||||||
|
use crate::i18n::Lang;
|
||||||
|
|
||||||
|
pub const CRUMB: Text = Text {
|
||||||
|
de: "Steuerungen",
|
||||||
|
en: "Controllers",
|
||||||
|
};
|
||||||
|
pub fn title(name: &str, lang: Lang) -> String {
|
||||||
|
match lang {
|
||||||
|
Lang::De => format!("Auf welchen Siemens-Steuerungen läuft {name}?"),
|
||||||
|
Lang::En => format!("Which Siemens controllers does {name} run on?"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub const INTRO: Text = Text {
|
||||||
|
de: "Mit Artikelnummer und Firmware gleicht Prüfwerk jeden Sicherheitshinweis von \
|
||||||
|
Siemens mit Ihren Steuerungen ab, auch ohne Projektdatei.",
|
||||||
|
en: "With the order number and firmware, Prüfwerk checks every Siemens security \
|
||||||
|
advisory against your controllers, even without a project file.",
|
||||||
|
};
|
||||||
|
pub const LOADING: Text = Text {
|
||||||
|
de: "Steuerungen werden geladen …",
|
||||||
|
en: "Loading the controllers …",
|
||||||
|
};
|
||||||
|
pub const LOAD_FAILED: Text = Text {
|
||||||
|
de: "Die Steuerungen lassen sich gerade nicht laden.",
|
||||||
|
en: "The controllers cannot be loaded right now.",
|
||||||
|
};
|
||||||
|
pub const SAVE_FAILED: Text = Text {
|
||||||
|
de: "Die Steuerungen ließen sich nicht speichern.",
|
||||||
|
en: "The controllers could not be saved.",
|
||||||
|
};
|
||||||
|
pub const ADDED: Text = Text {
|
||||||
|
de: "Steuerung hinzugefügt",
|
||||||
|
en: "Controller added",
|
||||||
|
};
|
||||||
|
pub const REMOVED: Text = Text {
|
||||||
|
de: "Steuerung entfernt",
|
||||||
|
en: "Controller removed",
|
||||||
|
};
|
||||||
|
pub const FIRMWARE_SAVED: Text = Text {
|
||||||
|
de: "Firmware gespeichert",
|
||||||
|
en: "Firmware saved",
|
||||||
|
};
|
||||||
|
|
||||||
|
// The rail.
|
||||||
|
pub const RAIL: Text = Text {
|
||||||
|
de: "Steuerungen auf der Schiene",
|
||||||
|
en: "Controllers on the rail",
|
||||||
|
};
|
||||||
|
pub const LEGEND_AFFECTED: Text = Text {
|
||||||
|
de: "Ein Hinweis betrifft die Firmware",
|
||||||
|
en: "An advisory affects the firmware",
|
||||||
|
};
|
||||||
|
pub const LEGEND_NOT_AFFECTED: Text = Text {
|
||||||
|
de: "Genannt, aber nicht betroffen",
|
||||||
|
en: "Named, not affected",
|
||||||
|
};
|
||||||
|
pub const LEGEND_NOT_NAMED: Text = Text {
|
||||||
|
de: "In keinem Hinweis genannt",
|
||||||
|
en: "Named in no advisory",
|
||||||
|
};
|
||||||
|
pub const ADD: Text = Text {
|
||||||
|
de: "Steuerung hinzufügen",
|
||||||
|
en: "Add a controller",
|
||||||
|
};
|
||||||
|
pub const NO_LABEL: Text = Text {
|
||||||
|
de: "Ohne Bezeichnung",
|
||||||
|
en: "No name",
|
||||||
|
};
|
||||||
|
pub const EMPTY: Text = Text {
|
||||||
|
de: "Noch keine Steuerung. Fügen Sie die erste mit Artikelnummer und Firmware hinzu.",
|
||||||
|
en: "No controller yet. Add the first with its order number and firmware.",
|
||||||
|
};
|
||||||
|
pub const EMPTY_READ_ONLY: Text = Text {
|
||||||
|
de: "Für dieses Prüfobjekt ist keine Steuerung eingetragen.",
|
||||||
|
en: "No controller is entered for this target.",
|
||||||
|
};
|
||||||
|
/// What a screen reader says for a module on the rail.
|
||||||
|
pub fn module(
|
||||||
|
short: &str,
|
||||||
|
firmware: &str,
|
||||||
|
affecting: usize,
|
||||||
|
named: bool,
|
||||||
|
lang: Lang,
|
||||||
|
) -> String {
|
||||||
|
match (lang, affecting, named) {
|
||||||
|
(Lang::De, 0, true) => {
|
||||||
|
format!("{short}, Firmware {firmware}, kein Hinweis betrifft sie")
|
||||||
|
}
|
||||||
|
(Lang::De, 0, false) => {
|
||||||
|
format!("{short}, Firmware {firmware}, in keinem Hinweis genannt")
|
||||||
|
}
|
||||||
|
(Lang::De, 1, _) => format!("{short}, Firmware {firmware}, ein Hinweis betrifft sie"),
|
||||||
|
(Lang::De, n, _) => format!("{short}, Firmware {firmware}, {n} Hinweise betreffen sie"),
|
||||||
|
(Lang::En, 0, true) => format!("{short}, firmware {firmware}, no advisory affects it"),
|
||||||
|
(Lang::En, 0, false) => format!("{short}, firmware {firmware}, named in no advisory"),
|
||||||
|
(Lang::En, 1, _) => format!("{short}, firmware {firmware}, one advisory affects it"),
|
||||||
|
(Lang::En, n, _) => format!("{short}, firmware {firmware}, {n} advisories affect it"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The detail.
|
||||||
|
pub const ORDER_NUMBER: Text = Text {
|
||||||
|
de: "Artikelnummer",
|
||||||
|
en: "Order number",
|
||||||
|
};
|
||||||
|
pub const FIRMWARE: Text = Text {
|
||||||
|
de: "Firmware",
|
||||||
|
en: "Firmware",
|
||||||
|
};
|
||||||
|
pub const CHANGE_FIRMWARE: Text = Text {
|
||||||
|
de: "Firmware ändern",
|
||||||
|
en: "Change firmware",
|
||||||
|
};
|
||||||
|
pub const SAVE_FIRMWARE: Text = Text {
|
||||||
|
de: "Firmware speichern",
|
||||||
|
en: "Save firmware",
|
||||||
|
};
|
||||||
|
pub const REMOVE: Text = Text {
|
||||||
|
de: "Entfernen",
|
||||||
|
en: "Remove",
|
||||||
|
};
|
||||||
|
pub const CANCEL: Text = Text {
|
||||||
|
de: "Abbrechen",
|
||||||
|
en: "Cancel",
|
||||||
|
};
|
||||||
|
/// The sentence under a device's figures.
|
||||||
|
pub fn state(affecting: usize, named: usize, firmware: &str, lang: Lang) -> String {
|
||||||
|
match (lang, affecting, named) {
|
||||||
|
(Lang::De, 0, 0) => "Siemens nennt diese Artikelnummer bisher in keinem Hinweis. \
|
||||||
|
Prüfwerk prüft sie bei jedem neuen."
|
||||||
|
.to_string(),
|
||||||
|
(Lang::De, 0, 1) => {
|
||||||
|
format!("Siemens nennt diese Steuerung in einem Hinweis; er betrifft Firmware V{firmware} nicht.")
|
||||||
|
}
|
||||||
|
(Lang::De, 0, n) => {
|
||||||
|
format!("Siemens nennt diese Steuerung in {n} Hinweisen; keiner betrifft Firmware V{firmware}.")
|
||||||
|
}
|
||||||
|
(Lang::De, 1, _) => format!("Ein Siemens-Hinweis betrifft Firmware V{firmware}."),
|
||||||
|
(Lang::De, n, _) => format!("{n} Siemens-Hinweise betreffen Firmware V{firmware}."),
|
||||||
|
(Lang::En, 0, 0) => "No Siemens advisory names this order number so far. Prüfwerk \
|
||||||
|
checks it against every new one."
|
||||||
|
.to_string(),
|
||||||
|
(Lang::En, 0, 1) => {
|
||||||
|
format!("Siemens names this controller in one advisory; it does not affect firmware V{firmware}.")
|
||||||
|
}
|
||||||
|
(Lang::En, 0, n) => {
|
||||||
|
format!("Siemens names this controller in {n} advisories; none affects firmware V{firmware}.")
|
||||||
|
}
|
||||||
|
(Lang::En, 1, _) => format!("One Siemens advisory affects firmware V{firmware}."),
|
||||||
|
(Lang::En, n, _) => format!("{n} Siemens advisories affect firmware V{firmware}."),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub const ADVISORIES: Text = Text {
|
||||||
|
de: "Siemens-Hinweise zu dieser Steuerung",
|
||||||
|
en: "Siemens advisories for this controller",
|
||||||
|
};
|
||||||
|
pub fn fixed_from(version: &str, lang: Lang) -> String {
|
||||||
|
match lang {
|
||||||
|
Lang::De => format!("Behoben ab V{version}"),
|
||||||
|
Lang::En => format!("Fixed from V{version}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub const NO_FIX: Text = Text {
|
||||||
|
de: "Noch keine behobene Firmware, Siemens nennt Gegenmaßnahmen",
|
||||||
|
en: "No fixed firmware yet, Siemens names mitigations",
|
||||||
|
};
|
||||||
|
pub fn affects(firmware: &str, lang: Lang) -> String {
|
||||||
|
match lang {
|
||||||
|
Lang::De => format!("betrifft V{firmware}"),
|
||||||
|
Lang::En => format!("affects V{firmware}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub const NOT_AFFECTED: Text = Text {
|
||||||
|
de: "nicht betroffen",
|
||||||
|
en: "not affected",
|
||||||
|
};
|
||||||
|
pub const SOURCE: Text = Text {
|
||||||
|
de: "Quelle",
|
||||||
|
en: "Source",
|
||||||
|
};
|
||||||
|
pub const TO_CVES: Text = Text {
|
||||||
|
de: "Zu den Schwachstellen dieses Prüfobjekts",
|
||||||
|
en: "To this target's vulnerabilities",
|
||||||
|
};
|
||||||
|
pub const NEXT_SCAN: Text = Text {
|
||||||
|
de: "Die Schwachstellen des Prüfobjekts zeigen eine neue oder geänderte Steuerung nach \
|
||||||
|
der nächsten Prüfung.",
|
||||||
|
en: "The target's vulnerabilities show a new or changed controller after the next scan.",
|
||||||
|
};
|
||||||
|
|
||||||
|
// Adding one.
|
||||||
|
pub const LABEL: Text = Text {
|
||||||
|
de: "Bezeichnung (optional)",
|
||||||
|
en: "Name (optional)",
|
||||||
|
};
|
||||||
|
pub const LABEL_EXAMPLE: Text = Text {
|
||||||
|
de: "Hauptsteuerung Zelle 2",
|
||||||
|
en: "Main controller cell 2",
|
||||||
|
};
|
||||||
|
pub const BAD_ORDER_NUMBER: Text = Text {
|
||||||
|
de: "Eine Artikelnummer hat drei Teile, etwa 6ES7511-1AK02-0AB0.",
|
||||||
|
en: "An order number has three parts, such as 6ES7511-1AK02-0AB0.",
|
||||||
|
};
|
||||||
|
pub const BAD_FIRMWARE: Text = Text {
|
||||||
|
de: "Die Firmware besteht aus Zahlen mit Punkten, etwa V3.1.4.",
|
||||||
|
en: "Firmware is numbers with dots, such as V3.1.4.",
|
||||||
|
};
|
||||||
|
pub fn known(name: &str, lang: Lang) -> String {
|
||||||
|
match lang {
|
||||||
|
Lang::De => format!("Siemens führt diese Nummer als {name}."),
|
||||||
|
Lang::En => format!("Siemens lists this number as {name}."),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub const UNKNOWN: Text = Text {
|
||||||
|
de: "Gültige Artikelnummer. Siemens nennt sie bisher in keinem Hinweis; Prüfwerk prüft \
|
||||||
|
sie bei jedem neuen.",
|
||||||
|
en: "A valid order number. No Siemens advisory names it so far; Prüfwerk checks it \
|
||||||
|
against every new one.",
|
||||||
|
};
|
||||||
|
pub const HELP: Text = Text {
|
||||||
|
de: "Wo finde ich Artikelnummer und Firmware?",
|
||||||
|
en: "Where do I find the order number and firmware?",
|
||||||
|
};
|
||||||
|
pub const HELP_PLATE: Text = Text {
|
||||||
|
de: "Auf dem Typenschild vorn an der CPU, beginnend mit 6ES7, 6AG1 oder 6ED1.",
|
||||||
|
en: "On the rating plate on the front of the CPU, starting with 6ES7, 6AG1 or 6ED1.",
|
||||||
|
};
|
||||||
|
pub const HELP_TIA: Text = Text {
|
||||||
|
de: "In TIA Portal: die CPU in der Gerätekonfiguration markieren, dann Eigenschaften, \
|
||||||
|
Allgemein, Katalog-Informationen.",
|
||||||
|
en: "In TIA Portal: select the CPU in the device configuration, then Properties, \
|
||||||
|
General, Catalog information.",
|
||||||
|
};
|
||||||
|
pub const HELP_WEB: Text = Text {
|
||||||
|
de: "Die Firmware zeigt auch der Webserver der CPU auf der Startseite.",
|
||||||
|
en: "The CPU's web server also shows the firmware on its start page.",
|
||||||
|
};
|
||||||
|
|
||||||
|
// How it works.
|
||||||
|
pub const HOW_TITLE: Text = Text {
|
||||||
|
de: "So gleicht Prüfwerk ab",
|
||||||
|
en: "How Prüfwerk checks",
|
||||||
|
};
|
||||||
|
pub const HOW_MATCH: Text = Text {
|
||||||
|
de: "Siemens nennt in seinen Hinweisen jede betroffene CPU mit Artikelnummer und \
|
||||||
|
Firmware-Stand. Prüfwerk liest die Hinweise täglich und vergleicht sie mit den \
|
||||||
|
Steuerungen hier.",
|
||||||
|
en: "Siemens names every affected CPU in its advisories by order number and firmware. \
|
||||||
|
Prüfwerk reads the advisories daily and compares them with the controllers here.",
|
||||||
|
};
|
||||||
|
pub const HOW_FAMILIES: Text = Text {
|
||||||
|
de: "Hinweise, die nur eine ganze Baureihe nennen (etwa „S7-1200 CPU family“), gleicht \
|
||||||
|
Prüfwerk noch nicht ab.",
|
||||||
|
en: "Advisories that name only a whole series (such as “S7-1200 CPU family”) are not \
|
||||||
|
checked yet.",
|
||||||
|
};
|
||||||
|
|
||||||
|
// The target page's card.
|
||||||
|
pub const CARD_HINT: Text = Text {
|
||||||
|
de: "Siemens-Steuerungen mit Artikelnummer und Firmware eintragen",
|
||||||
|
en: "Enter Siemens controllers by order number and firmware",
|
||||||
|
};
|
||||||
|
pub fn card_figure(devices: usize, affected: usize, lang: Lang) -> String {
|
||||||
|
match (lang, devices, affected) {
|
||||||
|
(Lang::De, 1, 0) => "1 Steuerung, kein Hinweis betrifft sie".to_string(),
|
||||||
|
(Lang::De, n, 0) => format!("{n} Steuerungen, kein Hinweis betrifft sie"),
|
||||||
|
(Lang::De, 1, _) => "1 Steuerung, betroffen".to_string(),
|
||||||
|
(Lang::De, n, a) => format!("{n} Steuerungen, {a} betroffen"),
|
||||||
|
(Lang::En, 1, 0) => "1 controller, no advisory affects it".to_string(),
|
||||||
|
(Lang::En, n, 0) => format!("{n} controllers, no advisory affects them"),
|
||||||
|
(Lang::En, 1, _) => "1 controller, affected".to_string(),
|
||||||
|
(Lang::En, n, a) => format!("{n} controllers, {a} affected"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The workspace's branding (tenant-registry#155): the sidebar's credit line
|
||||||
|
/// and the one-time notice for its admins.
|
||||||
|
pub mod branding {
|
||||||
|
use super::Text;
|
||||||
|
use crate::i18n::Lang;
|
||||||
|
|
||||||
|
/// Under the workspace's name in the sidebar.
|
||||||
|
pub const PRODUCT: Text = Text {
|
||||||
|
de: "Prüfwerk",
|
||||||
|
en: "Prüfwerk",
|
||||||
|
};
|
||||||
|
/// At the foot of a branded sidebar: whose product it is.
|
||||||
|
pub const CREDIT: Text = Text {
|
||||||
|
de: "Prüfwerk von Breakpilot",
|
||||||
|
en: "Prüfwerk by Breakpilot",
|
||||||
|
};
|
||||||
|
/// Who sees the notice, and where to change the branding.
|
||||||
|
pub const NOTICE_BODY: Text = Text {
|
||||||
|
de: "Nur Administrator:innen sehen diesen Hinweis. Ändern können Sie beides im Portal \
|
||||||
|
unter Erscheinungsbild.",
|
||||||
|
en: "Only admins see this notice. You can change both in the portal under Appearance.",
|
||||||
|
};
|
||||||
|
/// Acknowledges the branding.
|
||||||
|
pub const OK: Text = Text {
|
||||||
|
de: "Passt",
|
||||||
|
en: "Looks right",
|
||||||
|
};
|
||||||
|
/// Opens the portal to change it.
|
||||||
|
pub const CHANGE: Text = Text {
|
||||||
|
de: "Ändern",
|
||||||
|
en: "Change",
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The notice's title: where logo and colour were taken from.
|
||||||
|
pub fn notice_title(domain: &str, lang: Lang) -> String {
|
||||||
|
match lang {
|
||||||
|
Lang::De => format!("Logo und Farbe von {domain} übernommen"),
|
||||||
|
Lang::En => format!("Logo and colour taken from {domain}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
//! The workspace's branding (tenant-registry#155): its CI colour framing
|
||||||
|
//! every page, its logo in the sidebar, and the one-time notice for its
|
||||||
|
//! admins. Proxies the agent's `/api/v1/branding*`.
|
||||||
|
|
||||||
|
use dioxus::prelude::*;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// The branding as the agent reports it; all empty means none.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Branding {
|
||||||
|
/// The frame colour, `#rrggbb`; none means no frame.
|
||||||
|
#[serde(default)]
|
||||||
|
pub color: Option<String>,
|
||||||
|
/// Whether [`LOGO_URL`] has a logo.
|
||||||
|
#[serde(default)]
|
||||||
|
pub logo: bool,
|
||||||
|
/// The workspace's name, beside the logo.
|
||||||
|
#[serde(default)]
|
||||||
|
pub name: Option<String>,
|
||||||
|
/// Whether to show this admin the notice.
|
||||||
|
#[serde(default)]
|
||||||
|
pub notice: bool,
|
||||||
|
/// The domain the branding was taken from.
|
||||||
|
#[serde(default)]
|
||||||
|
pub domain: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Branding {
|
||||||
|
/// The inline style that sets the frame colour, or empty without one.
|
||||||
|
/// Only a `#rrggbb` value ever reaches it, whatever the agent sent.
|
||||||
|
pub fn frame_style(&self) -> String {
|
||||||
|
match self.color.as_deref() {
|
||||||
|
Some(c) if is_hex_colour(c) => format!("--brand-frame: {c};"),
|
||||||
|
_ => String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the sidebar shows the workspace instead of the Breakpilot
|
||||||
|
/// wordmark: it has a colour or a logo.
|
||||||
|
pub fn branded(&self) -> bool {
|
||||||
|
self.framed() || self.logo
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The text colour on the CI colour: white or Breakpilot ink, whichever
|
||||||
|
/// reads better.
|
||||||
|
pub fn ink(&self) -> &'static str {
|
||||||
|
let Some(hex) = self.color.as_deref().filter(|c| is_hex_colour(c)) else {
|
||||||
|
return "#FFFFFF";
|
||||||
|
};
|
||||||
|
let channel = |i: usize| {
|
||||||
|
let v = f64::from(u8::from_str_radix(&hex[i..i + 2], 16).unwrap_or(0)) / 255.0;
|
||||||
|
if v <= 0.039_28 {
|
||||||
|
v / 12.92
|
||||||
|
} else {
|
||||||
|
((v + 0.055) / 1.055).powf(2.4)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let lum = 0.2126 * channel(1) + 0.7152 * channel(3) + 0.0722 * channel(5);
|
||||||
|
// Contrast with white is 1.05 / (L + 0.05); with ink (#14162B,
|
||||||
|
// L about 0.0085) it is (L + 0.05) / 0.0585.
|
||||||
|
if 1.05 / (lum + 0.05) >= (lum + 0.05) / 0.0585 {
|
||||||
|
"#FFFFFF"
|
||||||
|
} else {
|
||||||
|
"#14162B"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the frame is drawn.
|
||||||
|
pub fn framed(&self) -> bool {
|
||||||
|
self.color.as_deref().is_some_and(is_hex_colour)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The initials shown instead of a logo: the first letters of the first
|
||||||
|
/// two words of the name, or none without a name.
|
||||||
|
pub fn initials(&self) -> String {
|
||||||
|
self.name
|
||||||
|
.as_deref()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.split_whitespace()
|
||||||
|
.filter_map(|w| w.chars().find(|c| c.is_alphanumeric()))
|
||||||
|
.take(2)
|
||||||
|
.flat_map(char::to_uppercase)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `#rrggbb`.
|
||||||
|
fn is_hex_colour(c: &str) -> bool {
|
||||||
|
c.strip_prefix('#')
|
||||||
|
.is_some_and(|h| h.len() == 6 && h.bytes().all(|b| b.is_ascii_hexdigit()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the browser loads the workspace's logo.
|
||||||
|
pub const LOGO_URL: &str = "/api/branding/logo";
|
||||||
|
|
||||||
|
/// The agent's answer, read on the server only.
|
||||||
|
#[cfg(feature = "server")]
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
struct BrandingResponse {
|
||||||
|
data: Branding,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The workspace's branding; none when the agent cannot say.
|
||||||
|
#[server]
|
||||||
|
pub async fn fetch_branding() -> Result<Branding, ServerFnError> {
|
||||||
|
let resp = super::agent_client::agent_get("/api/v1/branding")
|
||||||
|
.await?
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||||
|
let answer: BrandingResponse = super::agent_client::json_or_error(resp).await?;
|
||||||
|
Ok(answer.data)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `GET /api/branding/logo`: the workspace's logo, a PNG.
|
||||||
|
#[get("/api/branding/logo")]
|
||||||
|
pub async fn branding_logo() -> Result<dioxus::fullstack::FileStream, ServerFnError> {
|
||||||
|
let resp = super::agent_client::agent_get("/api/v1/branding/logo")
|
||||||
|
.await?
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||||
|
let resp = super::agent_client::ok_response(resp).await?;
|
||||||
|
let size = resp.content_length();
|
||||||
|
let body = axum::body::Body::from_stream(resp.bytes_stream()).into_data_stream();
|
||||||
|
Ok(dioxus::fullstack::FileStream::from_raw(
|
||||||
|
"logo.png".to_string(),
|
||||||
|
size,
|
||||||
|
"image/png".to_string(),
|
||||||
|
body,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Record an admin's "Passt" on the branding taken from the website.
|
||||||
|
#[server]
|
||||||
|
pub async fn ack_branding() -> Result<(), ServerFnError> {
|
||||||
|
let resp = super::agent_client::agent_request(reqwest::Method::POST, "/api/v1/branding/ack")
|
||||||
|
.await?
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||||
|
super::agent_client::ok_response(resp).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_a_hex_colour_draws_a_frame() {
|
||||||
|
for (color, framed) in [
|
||||||
|
("#14b8a6", true),
|
||||||
|
("#C8102E", true),
|
||||||
|
("red", false),
|
||||||
|
("#12345", false),
|
||||||
|
("#14b8a6; background: url(x)", false),
|
||||||
|
] {
|
||||||
|
let b = Branding {
|
||||||
|
color: Some(color.into()),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
assert_eq!(b.framed(), framed, "{color}");
|
||||||
|
assert_eq!(b.frame_style().is_empty(), !framed, "{color}");
|
||||||
|
}
|
||||||
|
assert!(!Branding::default().framed());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_initials_read_on_the_ci_colour() {
|
||||||
|
let on = |c: &str| {
|
||||||
|
Branding {
|
||||||
|
color: Some(c.into()),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
.ink()
|
||||||
|
};
|
||||||
|
assert_eq!(on("#C8102E"), "#FFFFFF");
|
||||||
|
assert_eq!(on("#1F3A5F"), "#FFFFFF");
|
||||||
|
assert_eq!(on("#F5B700"), "#14162B");
|
||||||
|
assert_eq!(on("#14B8A6"), "#14162B");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn initials_come_from_the_first_two_words() {
|
||||||
|
let named = |n: &str| Branding {
|
||||||
|
name: Some(n.into()),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
assert_eq!(named("Musterwerk GmbH").initials(), "MG");
|
||||||
|
assert_eq!(named("nordachse").initials(), "N");
|
||||||
|
assert_eq!(named(" (Lindtal) Werke AG").initials(), "LW");
|
||||||
|
assert_eq!(Branding::default().initials(), "");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
//! A target's Siemens controllers (SPS item 4a), read from the agent's
|
||||||
|
//! `/api/v1/targets/{id}/devices` and changed with the target.
|
||||||
|
|
||||||
|
use compliance_core::device_check::{DeviceCheck, DeviceLookup};
|
||||||
|
use compliance_core::models::PlcDevice;
|
||||||
|
use dioxus::prelude::*;
|
||||||
|
|
||||||
|
/// Target `id`'s devices, each with the Siemens advisories naming it.
|
||||||
|
#[server]
|
||||||
|
pub async fn fetch_devices(id: String) -> Result<Vec<DeviceCheck>, ServerFnError> {
|
||||||
|
super::agent_client::data(
|
||||||
|
super::agent_client::agent_get(&format!("/api/v1/targets/{id}/devices")).await?,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What Siemens' advisories know of `order_number`, as typed.
|
||||||
|
#[server]
|
||||||
|
pub async fn lookup_device(order_number: String) -> Result<DeviceLookup, ServerFnError> {
|
||||||
|
super::agent_client::data(
|
||||||
|
super::agent_client::agent_get("/api/v1/devices/lookup")
|
||||||
|
.await?
|
||||||
|
.query(&[("order_number", order_number)]),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Store `devices` as target `id`'s devices, replacing the ones it had.
|
||||||
|
#[server]
|
||||||
|
pub async fn save_devices(id: String, devices: Vec<PlcDevice>) -> Result<(), ServerFnError> {
|
||||||
|
let resp = super::agent_client::agent_request(
|
||||||
|
reqwest::Method::PATCH,
|
||||||
|
&format!("/api/v1/targets/{id}"),
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
.json(&serde_json::json!({ "devices": devices }))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||||
|
super::agent_client::ok_or_error(resp).await
|
||||||
|
}
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
// Server function modules (compiled for both web and server;
|
// Server function modules (compiled for both web and server;
|
||||||
// the #[server] macro generates client stubs for the web target)
|
// the #[server] macro generates client stubs for the web target)
|
||||||
pub mod auth_check;
|
pub mod auth_check;
|
||||||
|
pub mod branding;
|
||||||
pub mod chat;
|
pub mod chat;
|
||||||
pub mod cve_history;
|
pub mod cve_history;
|
||||||
pub mod cve_matrix;
|
pub mod cve_matrix;
|
||||||
pub mod dast;
|
pub mod dast;
|
||||||
|
pub mod devices;
|
||||||
pub mod download;
|
pub mod download;
|
||||||
pub mod evidence;
|
pub mod evidence;
|
||||||
pub mod finding_breakdown;
|
pub mod finding_breakdown;
|
||||||
|
|||||||
@@ -68,7 +68,7 @@ pub fn upload_problem(error: String, lang: Lang) -> String {
|
|||||||
} else if error.contains(UNSUPPORTED_ARCHIVE) {
|
} else if error.contains(UNSUPPORTED_ARCHIVE) {
|
||||||
common::UNSUPPORTED_ARCHIVE.get(lang).to_string()
|
common::UNSUPPORTED_ARCHIVE.get(lang).to_string()
|
||||||
} else {
|
} else {
|
||||||
error
|
crate::i18n::texts::metering::demo_refusal(&error, lang)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -694,6 +694,8 @@ pub async fn upload_target_artifact(
|
|||||||
413 if sbom => format!("{SBOM_REFUSED}too_large"),
|
413 if sbom => format!("{SBOM_REFUSED}too_large"),
|
||||||
413 => "file is larger than the 512 MiB upload limit".to_string(),
|
413 => "file is larger than the 512 MiB upload limit".to_string(),
|
||||||
415 => UNSUPPORTED_ARCHIVE.to_string(),
|
415 => UNSUPPORTED_ARCHIVE.to_string(),
|
||||||
|
// A demo target the plan has no room for as the tenant's own.
|
||||||
|
409 => refusal_code(resp).await,
|
||||||
422 => format!("{SBOM_REFUSED}{}", refusal_code(resp).await),
|
422 => format!("{SBOM_REFUSED}{}", refusal_code(resp).await),
|
||||||
code => format!("upload rejected by the agent ({code})"),
|
code => format!("upload rejected by the agent ({code})"),
|
||||||
}));
|
}));
|
||||||
|
|||||||
@@ -0,0 +1,667 @@
|
|||||||
|
//! A target's Siemens controllers (SPS item 4a): each one a module on a DIN
|
||||||
|
//! rail whose light says whether a Siemens advisory affects its firmware,
|
||||||
|
//! the chosen one's advisories beside it, and a form that recognises an
|
||||||
|
//! order number while it is typed.
|
||||||
|
|
||||||
|
use dioxus::prelude::*;
|
||||||
|
use dioxus_free_icons::icons::bs_icons::{BsArrowRight, BsCheckLg, BsExclamationCircle, BsPlusLg};
|
||||||
|
use dioxus_free_icons::Icon;
|
||||||
|
|
||||||
|
use compliance_core::device_check::{DeviceAdvisory, DeviceCheck, DeviceState};
|
||||||
|
use compliance_core::models::{PlcDevice, PlcDeviceError};
|
||||||
|
|
||||||
|
use crate::app::Route;
|
||||||
|
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};
|
||||||
|
use crate::i18n::texts::{devices as tx, repo_views as rv};
|
||||||
|
use crate::i18n::{use_lang, Text};
|
||||||
|
use crate::infrastructure::devices::{fetch_devices, lookup_device, save_devices};
|
||||||
|
use crate::infrastructure::onboarding::fetch_target;
|
||||||
|
use crate::pages::target_views::RepoView;
|
||||||
|
|
||||||
|
/// The CSS class of a state's light.
|
||||||
|
fn light(state: DeviceState) -> &'static str {
|
||||||
|
match state {
|
||||||
|
DeviceState::Affected => "dev-led dev-led-affected",
|
||||||
|
DeviceState::NotAffected => "dev-led dev-led-clear",
|
||||||
|
DeviceState::NotNamed => "dev-led dev-led-unnamed",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many of a device's advisories affect it.
|
||||||
|
fn affecting(check: &DeviceCheck) -> usize {
|
||||||
|
check.advisories.iter().filter(|a| a.affected).count()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the rail shows of a device: Siemens' short name for it (or its order
|
||||||
|
/// number) and its series (or the vendor).
|
||||||
|
fn module_names(check: &DeviceCheck) -> (String, String) {
|
||||||
|
match &check.product {
|
||||||
|
Some(p) => (
|
||||||
|
p.short.clone(),
|
||||||
|
p.family.clone().unwrap_or_else(|| "Siemens".to_string()),
|
||||||
|
),
|
||||||
|
None => (check.device.order_number.clone(), "Siemens".to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A change to a target's devices, for the toast it ends with.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||||
|
enum Change {
|
||||||
|
Added,
|
||||||
|
Removed,
|
||||||
|
Firmware,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Change {
|
||||||
|
fn done(self) -> Text {
|
||||||
|
match self {
|
||||||
|
Self::Added => tx::ADDED,
|
||||||
|
Self::Removed => tx::REMOVED,
|
||||||
|
Self::Firmware => tx::FIRMWARE_SAVED,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Target `id`'s Siemens controllers.
|
||||||
|
#[component]
|
||||||
|
pub fn TargetDevicesPage(id: String) -> Element {
|
||||||
|
let lang = use_lang()();
|
||||||
|
let can_write = use_can_write();
|
||||||
|
let mut toasts = use_context::<Toasts>();
|
||||||
|
let target_id = use_signal(|| id.clone());
|
||||||
|
let target = use_resource(move || async move { fetch_target(target_id()).await.ok() });
|
||||||
|
let mut checks = use_resource(move || async move { fetch_devices(target_id()).await });
|
||||||
|
let mut selected = use_signal(|| 0_usize);
|
||||||
|
let mut adding = use_signal(|| false);
|
||||||
|
let mut saving = use_signal(|| false);
|
||||||
|
|
||||||
|
let name = match &*target.read() {
|
||||||
|
Some(Some(t)) => t
|
||||||
|
.data
|
||||||
|
.get("name")
|
||||||
|
.and_then(|n| n.as_str())
|
||||||
|
.unwrap_or_default()
|
||||||
|
.to_string(),
|
||||||
|
Some(None) => {
|
||||||
|
return rsx! {
|
||||||
|
div { class: "card target-missing",
|
||||||
|
p { {crate::i18n::texts::targets::NOT_FOUND.get(lang)} }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => return rsx! { div { class: "loading", {tx::LOADING.get(lang)} } },
|
||||||
|
};
|
||||||
|
let listed: Vec<DeviceCheck> = match &*checks.read() {
|
||||||
|
Some(Ok(listed)) => listed.clone(),
|
||||||
|
Some(Err(_)) => {
|
||||||
|
return rsx! {
|
||||||
|
DeviceCrumbs { id: id.clone(), name }
|
||||||
|
div { class: "card", p { {tx::LOAD_FAILED.get(lang)} } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => return rsx! { div { class: "loading", {tx::LOADING.get(lang)} } },
|
||||||
|
};
|
||||||
|
let devices: Vec<PlcDevice> = listed.iter().map(|c| c.device.clone()).collect();
|
||||||
|
// A first device is added from the empty rail's form.
|
||||||
|
let show_form = can_write && (adding() || listed.is_empty());
|
||||||
|
let chosen = (!show_form)
|
||||||
|
.then(|| listed.get(selected()))
|
||||||
|
.flatten()
|
||||||
|
.cloned();
|
||||||
|
|
||||||
|
let save = move |next: Vec<PlcDevice>, change: Change, then_select: usize| {
|
||||||
|
spawn(async move {
|
||||||
|
saving.set(true);
|
||||||
|
match save_devices(target_id(), next).await {
|
||||||
|
Ok(()) => {
|
||||||
|
toasts.push(ToastType::Success, change.done().get(lang).to_string());
|
||||||
|
selected.set(then_select);
|
||||||
|
adding.set(false);
|
||||||
|
checks.restart();
|
||||||
|
}
|
||||||
|
Err(e) => toasts.push(
|
||||||
|
ToastType::Error,
|
||||||
|
format!("{} {e}", tx::SAVE_FAILED.get(lang)),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
saving.set(false);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
rsx! {
|
||||||
|
div { class: "dev-page",
|
||||||
|
DeviceCrumbs { id: id.clone(), name: name.clone() }
|
||||||
|
header { class: "chain-head",
|
||||||
|
h1 { {tx::title(&name, lang)} }
|
||||||
|
p { {tx::INTRO.get(lang)} }
|
||||||
|
}
|
||||||
|
section { class: "card dev-rail-card", "aria-label": tx::RAIL.get(lang),
|
||||||
|
ul { class: "dev-legend",
|
||||||
|
li { span { class: light(DeviceState::Affected), "aria-hidden": "true" } {tx::LEGEND_AFFECTED.get(lang)} }
|
||||||
|
li { span { class: light(DeviceState::NotAffected), "aria-hidden": "true" } {tx::LEGEND_NOT_AFFECTED.get(lang)} }
|
||||||
|
li { span { class: light(DeviceState::NotNamed), "aria-hidden": "true" } {tx::LEGEND_NOT_NAMED.get(lang)} }
|
||||||
|
}
|
||||||
|
div { class: "dev-rail-scroll",
|
||||||
|
div { class: "dev-rail",
|
||||||
|
div { class: "dev-rail-bar", "aria-hidden": "true" }
|
||||||
|
for (i , check) in listed.iter().enumerate() {
|
||||||
|
DeviceModule {
|
||||||
|
key: "{i}-{check.device.order_number}",
|
||||||
|
check: check.clone(),
|
||||||
|
pressed: chosen.is_some() && selected() == i,
|
||||||
|
on_pick: move |_| {
|
||||||
|
selected.set(i);
|
||||||
|
adding.set(false);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if can_write {
|
||||||
|
button {
|
||||||
|
r#type: "button",
|
||||||
|
class: if show_form { "dev-add dev-add-on" } else { "dev-add" },
|
||||||
|
"aria-pressed": "{show_form}",
|
||||||
|
onclick: move |_| adding.set(true),
|
||||||
|
Icon { icon: BsPlusLg, width: 28, height: 28 }
|
||||||
|
span { {tx::ADD.get(lang)} }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if listed.is_empty() && !can_write {
|
||||||
|
p { class: "dev-empty", {tx::EMPTY_READ_ONLY.get(lang)} }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
div { class: "dev-body",
|
||||||
|
if show_form {
|
||||||
|
AddDevice {
|
||||||
|
first: listed.is_empty(),
|
||||||
|
saving: saving(),
|
||||||
|
on_cancel: move |_| adding.set(false),
|
||||||
|
on_add: {
|
||||||
|
let devices = devices.clone();
|
||||||
|
move |device: PlcDevice| {
|
||||||
|
let mut next = devices.clone();
|
||||||
|
next.push(device);
|
||||||
|
let last = next.len() - 1;
|
||||||
|
save(next, Change::Added, last);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
} else if let Some(check) = chosen {
|
||||||
|
DeviceDetail {
|
||||||
|
key: "{selected()}-{check.device.order_number}-{check.device.firmware}",
|
||||||
|
target_id: id.clone(),
|
||||||
|
check,
|
||||||
|
can_write,
|
||||||
|
saving: saving(),
|
||||||
|
on_firmware: {
|
||||||
|
let devices = devices.clone();
|
||||||
|
move |firmware: String| {
|
||||||
|
let at = selected();
|
||||||
|
let mut next = devices.clone();
|
||||||
|
if let Some(d) = next.get_mut(at) {
|
||||||
|
d.firmware = firmware;
|
||||||
|
}
|
||||||
|
save(next, Change::Firmware, at);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
on_remove: {
|
||||||
|
let devices = devices.clone();
|
||||||
|
move |_| {
|
||||||
|
let at = selected();
|
||||||
|
let mut next = devices.clone();
|
||||||
|
if at < next.len() {
|
||||||
|
next.remove(at);
|
||||||
|
}
|
||||||
|
save(next, Change::Removed, at.saturating_sub(1));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
aside { class: "dev-how", "aria-label": tx::HOW_TITLE.get(lang),
|
||||||
|
h2 { {tx::HOW_TITLE.get(lang)} }
|
||||||
|
p { {tx::HOW_MATCH.get(lang)} }
|
||||||
|
p { {tx::HOW_FAMILIES.get(lang)} }
|
||||||
|
p { {tx::NEXT_SCAN.get(lang)} }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The target page's card: a light per device and the way to the page.
|
||||||
|
#[component]
|
||||||
|
pub fn DevicesCard(target_id: String) -> Element {
|
||||||
|
let lang = use_lang()();
|
||||||
|
let id = use_signal(|| target_id.clone());
|
||||||
|
let checks = use_resource(move || async move { fetch_devices(id()).await.ok() });
|
||||||
|
let listed = checks.read().clone().flatten().unwrap_or_default();
|
||||||
|
let affected = listed
|
||||||
|
.iter()
|
||||||
|
.filter(|c| c.state() == DeviceState::Affected)
|
||||||
|
.count();
|
||||||
|
rsx! {
|
||||||
|
section { class: "card target-devices",
|
||||||
|
div { class: "target-card-head",
|
||||||
|
h3 { {tx::CRUMB.get(lang)} }
|
||||||
|
Link { to: Route::TargetDevicesPage { id: target_id.clone() }, class: "target-card-link",
|
||||||
|
Icon { icon: BsArrowRight, width: 14, height: 14 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if listed.is_empty() {
|
||||||
|
p { class: "target-graph-note", {tx::CARD_HINT.get(lang)} }
|
||||||
|
} else {
|
||||||
|
div { class: "dev-card-lights", "aria-hidden": "true",
|
||||||
|
for check in listed.iter() {
|
||||||
|
span { class: light(check.state()) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p { class: "target-graph-note", {tx::card_figure(listed.len(), affected, lang)} }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Overview › target › Controllers.
|
||||||
|
#[component]
|
||||||
|
fn DeviceCrumbs(id: String, name: String) -> Element {
|
||||||
|
let lang = use_lang()();
|
||||||
|
rsx! {
|
||||||
|
nav { class: "repo-crumbs", "aria-label": rv::BREADCRUMB.get(lang),
|
||||||
|
Link { to: Route::OverviewPage {}, {rv::OVERVIEW.get(lang)} }
|
||||||
|
span { class: "repo-crumb-sep", "aria-hidden": "true", "›" }
|
||||||
|
Link { class: "repo-crumb-name", to: Route::target(id.clone()), "{name}" }
|
||||||
|
span { class: "repo-crumb-sep", "aria-hidden": "true", "›" }
|
||||||
|
span { "aria-current": "page", {tx::CRUMB.get(lang)} }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One device on the rail.
|
||||||
|
#[component]
|
||||||
|
fn DeviceModule(check: DeviceCheck, pressed: bool, on_pick: EventHandler<()>) -> Element {
|
||||||
|
let lang = use_lang()();
|
||||||
|
let (short, family) = module_names(&check);
|
||||||
|
let label = check
|
||||||
|
.device
|
||||||
|
.label
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| tx::NO_LABEL.get(lang).to_string());
|
||||||
|
let aria = tx::module(
|
||||||
|
&short,
|
||||||
|
&check.device.firmware,
|
||||||
|
affecting(&check),
|
||||||
|
!check.advisories.is_empty(),
|
||||||
|
lang,
|
||||||
|
);
|
||||||
|
rsx! {
|
||||||
|
button {
|
||||||
|
r#type: "button",
|
||||||
|
class: if pressed { "dev-module dev-module-on" } else { "dev-module" },
|
||||||
|
"aria-pressed": "{pressed}",
|
||||||
|
"aria-label": "{aria}",
|
||||||
|
onclick: move |_| on_pick.call(()),
|
||||||
|
span { class: "dev-module-top",
|
||||||
|
span { class: "dev-module-brand", "SIEMENS" }
|
||||||
|
span { class: light(check.state()), "aria-hidden": "true" }
|
||||||
|
}
|
||||||
|
span { class: "dev-module-face", "aria-hidden": "true", "{family}" }
|
||||||
|
span { class: "dev-module-names",
|
||||||
|
span { class: "dev-module-short", "{short}" }
|
||||||
|
span { class: "dev-module-label", "{label}" }
|
||||||
|
}
|
||||||
|
span { class: "dev-module-vents", "aria-hidden": "true", span {} span {} span {} }
|
||||||
|
span { class: "dev-module-fw", "V{check.device.firmware}" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The chosen device: its figures, its state and its advisories.
|
||||||
|
#[component]
|
||||||
|
fn DeviceDetail(
|
||||||
|
target_id: String,
|
||||||
|
check: DeviceCheck,
|
||||||
|
can_write: bool,
|
||||||
|
saving: bool,
|
||||||
|
on_firmware: EventHandler<String>,
|
||||||
|
on_remove: EventHandler<()>,
|
||||||
|
) -> Element {
|
||||||
|
let lang = use_lang()();
|
||||||
|
let mut editing = use_signal(|| false);
|
||||||
|
let mut draft = use_signal(|| check.device.firmware.clone());
|
||||||
|
let state = check.state();
|
||||||
|
let device = &check.device;
|
||||||
|
let order_number = device.order_number.clone();
|
||||||
|
let name = check.product.as_ref().map_or_else(
|
||||||
|
|| format!("Siemens {}", device.order_number),
|
||||||
|
|p| p.name.clone(),
|
||||||
|
);
|
||||||
|
let label = device
|
||||||
|
.label
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| tx::NO_LABEL.get(lang).to_string());
|
||||||
|
let sentence = tx::state(
|
||||||
|
affecting(&check),
|
||||||
|
check.advisories.len(),
|
||||||
|
&device.firmware,
|
||||||
|
lang,
|
||||||
|
);
|
||||||
|
let firmware_error = PlcDevice::new(&device.order_number, &draft(), None).is_err();
|
||||||
|
let tint = match state {
|
||||||
|
DeviceState::Affected => "dev-state dev-state-affected",
|
||||||
|
DeviceState::NotAffected => "dev-state dev-state-clear",
|
||||||
|
DeviceState::NotNamed => "dev-state dev-state-unnamed",
|
||||||
|
};
|
||||||
|
|
||||||
|
rsx! {
|
||||||
|
section { class: "card dev-detail", "aria-label": "{name}",
|
||||||
|
div { class: "dev-detail-head",
|
||||||
|
div {
|
||||||
|
h2 { "{name}" }
|
||||||
|
span { class: "dev-detail-label", "{label}" }
|
||||||
|
}
|
||||||
|
if can_write {
|
||||||
|
div { class: "dev-detail-actions",
|
||||||
|
if !editing() {
|
||||||
|
button {
|
||||||
|
r#type: "button",
|
||||||
|
class: "btn btn-ghost",
|
||||||
|
disabled: saving,
|
||||||
|
onclick: move |_| editing.set(true),
|
||||||
|
{tx::CHANGE_FIRMWARE.get(lang)}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
button {
|
||||||
|
r#type: "button",
|
||||||
|
class: "btn btn-ghost btn-danger-ghost",
|
||||||
|
disabled: saving,
|
||||||
|
onclick: move |_| on_remove.call(()),
|
||||||
|
{tx::REMOVE.get(lang)}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dl { class: "dev-figures",
|
||||||
|
div {
|
||||||
|
dt { {tx::ORDER_NUMBER.get(lang)} }
|
||||||
|
dd { "{device.order_number}" CopyButton { value: device.order_number.clone(), small: true } }
|
||||||
|
}
|
||||||
|
div {
|
||||||
|
dt { {tx::FIRMWARE.get(lang)} }
|
||||||
|
if editing() {
|
||||||
|
dd { class: "dev-firmware-edit",
|
||||||
|
input {
|
||||||
|
r#type: "text",
|
||||||
|
"aria-label": tx::FIRMWARE.get(lang),
|
||||||
|
"aria-invalid": "{firmware_error}",
|
||||||
|
value: "{draft}",
|
||||||
|
autocomplete: "off",
|
||||||
|
spellcheck: "false",
|
||||||
|
oninput: move |e| draft.set(e.value()),
|
||||||
|
}
|
||||||
|
button {
|
||||||
|
r#type: "button",
|
||||||
|
class: "btn btn-primary",
|
||||||
|
disabled: firmware_error || saving,
|
||||||
|
onclick: move |_| {
|
||||||
|
if let Ok(d) = PlcDevice::new(&order_number, &draft(), None) {
|
||||||
|
on_firmware.call(d.firmware);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{tx::SAVE_FIRMWARE.get(lang)}
|
||||||
|
}
|
||||||
|
button {
|
||||||
|
r#type: "button",
|
||||||
|
class: "btn btn-ghost",
|
||||||
|
onclick: move |_| editing.set(false),
|
||||||
|
{tx::CANCEL.get(lang)}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if firmware_error && !draft().trim().is_empty() {
|
||||||
|
p { class: "dev-field-note", role: "status", {tx::BAD_FIRMWARE.get(lang)} }
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
dd { "V{device.firmware}" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
div { class: tint,
|
||||||
|
span { class: light(state), "aria-hidden": "true" }
|
||||||
|
span { "{sentence}" }
|
||||||
|
}
|
||||||
|
if !check.advisories.is_empty() {
|
||||||
|
div { class: "dev-advisories",
|
||||||
|
h3 { {tx::ADVISORIES.get(lang)} }
|
||||||
|
for advisory in check.advisories.iter() {
|
||||||
|
AdvisoryRow { key: "{advisory.id}", advisory: advisory.clone(), firmware: device.firmware.clone() }
|
||||||
|
}
|
||||||
|
Link {
|
||||||
|
class: "dev-to-cves",
|
||||||
|
to: Route::target_view(target_id.clone(), RepoView::Cves),
|
||||||
|
{tx::TO_CVES.get(lang)}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One advisory naming the device.
|
||||||
|
#[component]
|
||||||
|
fn AdvisoryRow(advisory: DeviceAdvisory, firmware: String) -> Element {
|
||||||
|
let lang = use_lang()();
|
||||||
|
let fix = match &advisory.fixed_from {
|
||||||
|
Some(version) => tx::fixed_from(version, lang),
|
||||||
|
None => tx::NO_FIX.get(lang).to_string(),
|
||||||
|
};
|
||||||
|
let verdict = if advisory.affected {
|
||||||
|
tx::affects(&firmware, lang)
|
||||||
|
} else {
|
||||||
|
tx::NOT_AFFECTED.get(lang).to_string()
|
||||||
|
};
|
||||||
|
rsx! {
|
||||||
|
div { class: if advisory.affected { "dev-advisory" } else { "dev-advisory dev-advisory-clear" },
|
||||||
|
SeverityBadge { severity: advisory.severity.clone().unwrap_or_default() }
|
||||||
|
div { class: "dev-advisory-text",
|
||||||
|
span { class: "dev-advisory-title", "{advisory.title}" }
|
||||||
|
span { class: "dev-advisory-meta", "{advisory.id}. {fix}" }
|
||||||
|
}
|
||||||
|
span { class: if advisory.affected { "dev-verdict dev-verdict-affected" } else { "dev-verdict" }, "{verdict}" }
|
||||||
|
// Every row is Siemens' (the agent reads no other provider for a
|
||||||
|
// device), whose terms ask each use to link the advisory.
|
||||||
|
if let Some(url) = &advisory.url {
|
||||||
|
a { class: "dev-source", href: "{url}", target: "_blank", rel: "noopener noreferrer", {tx::SOURCE.get(lang)} }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the form says of the order number typed so far.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
enum Recognised {
|
||||||
|
/// Too short to say anything yet.
|
||||||
|
Nothing,
|
||||||
|
/// Long enough, but not an order number's shape.
|
||||||
|
BadShape,
|
||||||
|
/// The shape is right; what Siemens' advisories know is being asked.
|
||||||
|
Asking,
|
||||||
|
/// Siemens' advisories name it, by this name.
|
||||||
|
Known(String),
|
||||||
|
/// The shape is right, but no advisory names it.
|
||||||
|
Unknown,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The shape of what has been typed: an order number, or not (yet).
|
||||||
|
fn shape(order_number: &str) -> Option<bool> {
|
||||||
|
match PlcDevice::new(order_number, "0", None) {
|
||||||
|
Ok(_) => Some(true),
|
||||||
|
Err(PlcDeviceError::OrderNumber(n)) if n.len() >= 6 => Some(false),
|
||||||
|
Err(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The form for a new device.
|
||||||
|
#[component]
|
||||||
|
fn AddDevice(
|
||||||
|
/// The target has no device yet: nothing to go back to.
|
||||||
|
first: bool,
|
||||||
|
saving: bool,
|
||||||
|
on_cancel: EventHandler<()>,
|
||||||
|
on_add: EventHandler<PlcDevice>,
|
||||||
|
) -> Element {
|
||||||
|
let lang = use_lang()();
|
||||||
|
let mut order_number = use_signal(String::new);
|
||||||
|
let mut firmware = use_signal(String::new);
|
||||||
|
let mut label = use_signal(String::new);
|
||||||
|
// Asked only once the typed number has an order number's shape.
|
||||||
|
let known = use_resource(move || async move {
|
||||||
|
let typed = order_number();
|
||||||
|
if shape(&typed) != Some(true) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
lookup_device(typed).await.ok()
|
||||||
|
});
|
||||||
|
let recognised = match shape(&order_number()) {
|
||||||
|
None => Recognised::Nothing,
|
||||||
|
Some(false) => Recognised::BadShape,
|
||||||
|
Some(true) => match &*known.read() {
|
||||||
|
Some(Some(found)) => match &found.product {
|
||||||
|
Some(p) => Recognised::Known(p.name.clone()),
|
||||||
|
None => Recognised::Unknown,
|
||||||
|
},
|
||||||
|
// Not answered, or the index cannot be read: the number is valid
|
||||||
|
// either way and can be added.
|
||||||
|
_ => Recognised::Asking,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
let device = PlcDevice::new(&order_number(), &firmware(), Some(&label()));
|
||||||
|
let firmware_bad =
|
||||||
|
!firmware().trim().is_empty() && matches!(device, Err(PlcDeviceError::Firmware(_)));
|
||||||
|
|
||||||
|
rsx! {
|
||||||
|
section { class: "card dev-form", "aria-label": tx::ADD.get(lang),
|
||||||
|
h2 { {tx::ADD.get(lang)} }
|
||||||
|
div { class: "dev-form-fields",
|
||||||
|
div { class: "form-group",
|
||||||
|
label { r#for: "dev-on", {tx::ORDER_NUMBER.get(lang)} }
|
||||||
|
input {
|
||||||
|
id: "dev-on",
|
||||||
|
r#type: "text",
|
||||||
|
value: "{order_number}",
|
||||||
|
placeholder: "6ES7511-1AK02-0AB0",
|
||||||
|
autocomplete: "off",
|
||||||
|
spellcheck: "false",
|
||||||
|
oninput: move |e| order_number.set(e.value()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
div { class: "form-group",
|
||||||
|
label { r#for: "dev-fw", {tx::FIRMWARE.get(lang)} }
|
||||||
|
input {
|
||||||
|
id: "dev-fw",
|
||||||
|
r#type: "text",
|
||||||
|
value: "{firmware}",
|
||||||
|
placeholder: "V3.1.4",
|
||||||
|
autocomplete: "off",
|
||||||
|
spellcheck: "false",
|
||||||
|
"aria-invalid": "{firmware_bad}",
|
||||||
|
oninput: move |e| firmware.set(e.value()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
div { class: "form-group",
|
||||||
|
label { r#for: "dev-label", {tx::LABEL.get(lang)} }
|
||||||
|
input {
|
||||||
|
id: "dev-label",
|
||||||
|
r#type: "text",
|
||||||
|
value: "{label}",
|
||||||
|
placeholder: tx::LABEL_EXAMPLE.get(lang),
|
||||||
|
autocomplete: "off",
|
||||||
|
oninput: move |e| label.set(e.value()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match recognised {
|
||||||
|
Recognised::Nothing | Recognised::Asking => rsx! {},
|
||||||
|
Recognised::BadShape => rsx! {
|
||||||
|
div { class: "dev-recognised dev-recognised-bad", role: "status",
|
||||||
|
Icon { icon: BsExclamationCircle, width: 16, height: 16 }
|
||||||
|
span { {tx::BAD_ORDER_NUMBER.get(lang)} }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Recognised::Known(name) => rsx! {
|
||||||
|
div { class: "dev-recognised dev-recognised-known", role: "status",
|
||||||
|
Icon { icon: BsCheckLg, width: 16, height: 16 }
|
||||||
|
span { {tx::known(&name, lang)} }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Recognised::Unknown => rsx! {
|
||||||
|
div { class: "dev-recognised", role: "status",
|
||||||
|
Icon { icon: BsExclamationCircle, width: 16, height: 16 }
|
||||||
|
span { {tx::UNKNOWN.get(lang)} }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if firmware_bad {
|
||||||
|
div { class: "dev-recognised dev-recognised-bad", role: "status",
|
||||||
|
Icon { icon: BsExclamationCircle, width: 16, height: 16 }
|
||||||
|
span { {tx::BAD_FIRMWARE.get(lang)} }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
details { class: "dev-help",
|
||||||
|
summary { {tx::HELP.get(lang)} }
|
||||||
|
ul {
|
||||||
|
li { {tx::HELP_PLATE.get(lang)} }
|
||||||
|
li { {tx::HELP_TIA.get(lang)} }
|
||||||
|
li { {tx::HELP_WEB.get(lang)} }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
div { class: "dev-form-actions",
|
||||||
|
button {
|
||||||
|
r#type: "button",
|
||||||
|
class: "btn btn-primary",
|
||||||
|
disabled: device.is_err() || saving,
|
||||||
|
onclick: move |_| {
|
||||||
|
if let Ok(d) = PlcDevice::new(&order_number(), &firmware(), Some(&label())) {
|
||||||
|
on_add.call(d);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{tx::ADD.get(lang)}
|
||||||
|
}
|
||||||
|
if !first {
|
||||||
|
button {
|
||||||
|
r#type: "button",
|
||||||
|
class: "btn btn-ghost",
|
||||||
|
onclick: move |_| on_cancel.call(()),
|
||||||
|
{tx::CANCEL.get(lang)}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[allow(clippy::unwrap_used)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_form_speaks_once_six_characters_are_typed() {
|
||||||
|
assert_eq!(shape("6ES7"), None);
|
||||||
|
assert_eq!(shape("6ES751"), Some(false));
|
||||||
|
assert_eq!(shape("6es7511-1ak02-0ab0"), Some(true));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_module_shows_the_name_siemens_uses_or_the_order_number() {
|
||||||
|
let device = PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.4", None).unwrap();
|
||||||
|
let unnamed = DeviceCheck::new(device, &[]);
|
||||||
|
assert_eq!(
|
||||||
|
module_names(&unnamed),
|
||||||
|
("6ES7511-1AK02-0AB0".to_string(), "Siemens".to_string())
|
||||||
|
);
|
||||||
|
assert_eq!(light(unnamed.state()), "dev-led dev-led-unnamed");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ pub mod dast_finding_detail;
|
|||||||
pub mod dast_findings;
|
pub mod dast_findings;
|
||||||
pub mod dast_overview;
|
pub mod dast_overview;
|
||||||
pub mod dast_targets;
|
pub mod dast_targets;
|
||||||
|
pub mod devices;
|
||||||
pub mod finding_detail;
|
pub mod finding_detail;
|
||||||
pub mod findings;
|
pub mod findings;
|
||||||
pub mod graph_explorer;
|
pub mod graph_explorer;
|
||||||
@@ -34,6 +35,7 @@ pub use dast_finding_detail::DastFindingDetailPage;
|
|||||||
pub use dast_findings::DastFindingsPage;
|
pub use dast_findings::DastFindingsPage;
|
||||||
pub use dast_overview::DastOverviewPage;
|
pub use dast_overview::DastOverviewPage;
|
||||||
pub use dast_targets::DastTargetsPage;
|
pub use dast_targets::DastTargetsPage;
|
||||||
|
pub use devices::TargetDevicesPage;
|
||||||
pub use finding_detail::FindingDetailPage;
|
pub use finding_detail::FindingDetailPage;
|
||||||
pub use findings::FindingsPage;
|
pub use findings::FindingsPage;
|
||||||
pub use graph_explorer::GraphExplorerPage;
|
pub use graph_explorer::GraphExplorerPage;
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ use crate::components::no_access::use_can_write;
|
|||||||
use crate::components::page_header::PageHeader;
|
use crate::components::page_header::PageHeader;
|
||||||
use crate::components::scan_coverage::ScanCoverage;
|
use crate::components::scan_coverage::ScanCoverage;
|
||||||
use crate::components::scan_runs::ScanRunList;
|
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::i18n::{format_bytes, use_lang, Lang};
|
||||||
use crate::infrastructure::onboarding::{
|
use crate::infrastructure::onboarding::{
|
||||||
check_supplier_sbom, create_target, detect_target, enable_target_scans, fetch_applicable_scans,
|
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() {
|
if let Some(err) = error() {
|
||||||
div { class: "card", style: "border-color: var(--danger, #d33); margin-bottom: 12px;",
|
div { class: "card", style: "border-color: var(--danger, #d33); margin-bottom: 12px;",
|
||||||
div { class: "card-header", {tx::ERROR.get(lang)} }
|
div { class: "card-header", {tx::ERROR.get(lang)} }
|
||||||
div { style: "padding: 12px;", "{err}" }
|
div { style: "padding: 12px;", {metering::target_refusal(&err, lang)} }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -993,6 +993,34 @@ fn type_label_of(value: &str, lang: Lang) -> String {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_target_the_plan_has_no_room_for_reads_in_words() {
|
||||||
|
let error = "error running server function: target_limit (409) (details: None)";
|
||||||
|
assert_eq!(
|
||||||
|
metering::target_refusal(error, Lang::En),
|
||||||
|
"Your plan includes no further targets. Delete a target to add a new one \
|
||||||
|
(its results are deleted with it), or change your plan."
|
||||||
|
);
|
||||||
|
assert_eq!(metering::target_refusal("x (500)", Lang::De), "x (500)");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_demo_target_the_plan_has_no_room_for_reads_in_words() {
|
||||||
|
let error = "error running server function: target_limit (409) (details: None)";
|
||||||
|
assert_eq!(
|
||||||
|
metering::demo_refusal(error, Lang::En),
|
||||||
|
metering::DEMO_LIMIT.get(Lang::En)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
upload_problem(
|
||||||
|
"error running server function: target_limit".into(),
|
||||||
|
Lang::De
|
||||||
|
),
|
||||||
|
metering::DEMO_LIMIT.get(Lang::De)
|
||||||
|
);
|
||||||
|
assert_eq!(metering::demo_refusal("x (500)", Lang::De), "x (500)");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_refused_supplier_sbom_upload_reads_in_the_readers_language() {
|
fn a_refused_supplier_sbom_upload_reads_in_the_readers_language() {
|
||||||
let error = "error running server function: supplier_sbom_refused:empty (details: None)";
|
let error = "error running server function: supplier_sbom_refused:empty (details: None)";
|
||||||
|
|||||||
@@ -350,7 +350,10 @@ pub fn SbomPage(target: String, #[props(default)] ecosystem: String) -> Element
|
|||||||
// ── SBOM table ──
|
// ── SBOM table ──
|
||||||
match &*sbom.read() {
|
match &*sbom.read() {
|
||||||
Some(Some(resp)) if resp.data.is_empty() && unfiltered() => rsx! {
|
Some(Some(resp)) if resp.data.is_empty() && unfiltered() => rsx! {
|
||||||
SbomEmpty { target_id: repo_filter() }
|
SbomEmpty {
|
||||||
|
target_id: repo_filter(),
|
||||||
|
plc: is_plc_target(repos.read().as_ref().and_then(|r| r.as_ref()).map(|r| r.data.as_slice()), &repo_filter()),
|
||||||
|
}
|
||||||
},
|
},
|
||||||
Some(Some(resp)) => {
|
Some(Some(resp)) => {
|
||||||
let total_pages = resp.total.unwrap_or(0).div_ceil(50).max(1);
|
let total_pages = resp.total.unwrap_or(0).div_ceil(50).max(1);
|
||||||
@@ -1039,6 +1042,19 @@ fn kev_title(kev: &KevData, lang: Lang) -> String {
|
|||||||
title
|
title
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether the target `id` among `targets` (the targets list's documents)
|
||||||
|
/// is a PLC application (`target_type` `plc_sps`).
|
||||||
|
fn is_plc_target(targets: Option<&[serde_json::Value]>, id: &str) -> bool {
|
||||||
|
!id.is_empty()
|
||||||
|
&& targets.unwrap_or_default().iter().any(|t| {
|
||||||
|
t.get("_id")
|
||||||
|
.and_then(|o| o.get("$oid"))
|
||||||
|
.and_then(|s| s.as_str())
|
||||||
|
== Some(id)
|
||||||
|
&& t.get("target_type").and_then(|v| v.as_str()) == Some("plc_sps")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// An EPSS badge's text: the probability and the percentile, in percent
|
/// An EPSS badge's text: the probability and the percentile, in percent
|
||||||
/// (`EPSS 94.4 % · P99`).
|
/// (`EPSS 94.4 % · P99`).
|
||||||
fn epss_label(epss: &EpssData) -> String {
|
fn epss_label(epss: &EpssData) -> String {
|
||||||
@@ -1052,9 +1068,10 @@ fn epss_label(epss: &EpssData) -> String {
|
|||||||
/// The component table's empty state (#979): why the SBOM is empty, and the
|
/// The component table's empty state (#979): why the SBOM is empty, and the
|
||||||
/// target's open findings that say what it is missing and how to add it, or
|
/// target's open findings that say what it is missing and how to add it, or
|
||||||
/// an example where there are none (all targets, or code such as C that has
|
/// an example where there are none (all targets, or code such as C that has
|
||||||
/// no standard manifest).
|
/// no standard manifest). A PLC target (`plc`) gets its own reason and
|
||||||
|
/// example: its components come from a CODESYS archive or its controllers.
|
||||||
#[component]
|
#[component]
|
||||||
fn SbomEmpty(target_id: ReadSignal<String>) -> Element {
|
fn SbomEmpty(target_id: ReadSignal<String>, plc: bool) -> Element {
|
||||||
let lang = use_lang()();
|
let lang = use_lang()();
|
||||||
let findings = use_resource(move || async move {
|
let findings = use_resource(move || async move {
|
||||||
let repo_id = target_id();
|
let repo_id = target_id();
|
||||||
@@ -1076,9 +1093,9 @@ fn SbomEmpty(target_id: ReadSignal<String>) -> Element {
|
|||||||
rsx! {
|
rsx! {
|
||||||
section { class: "card sbom-empty",
|
section { class: "card sbom-empty",
|
||||||
h3 { class: "sbom-quality-head", {tx::EMPTY_TITLE.get(lang)} }
|
h3 { class: "sbom-quality-head", {tx::EMPTY_TITLE.get(lang)} }
|
||||||
p { {tx::EMPTY_WHY.get(lang)} }
|
p { if plc { {tx::EMPTY_WHY_PLC.get(lang)} } else { {tx::EMPTY_WHY.get(lang)} } }
|
||||||
if findings.is_empty() {
|
if findings.is_empty() {
|
||||||
p { {tx::EMPTY_EXAMPLE.get(lang)} }
|
p { if plc { {tx::EMPTY_EXAMPLE_PLC.get(lang)} } else { {tx::EMPTY_EXAMPLE.get(lang)} } }
|
||||||
} else {
|
} else {
|
||||||
p { {tx::EMPTY_FINDINGS.get(lang)} }
|
p { {tx::EMPTY_FINDINGS.get(lang)} }
|
||||||
ul { class: "sbom-empty-findings",
|
ul { class: "sbom-empty-findings",
|
||||||
@@ -1158,3 +1175,24 @@ fn grade_class(grade: &str) -> &'static str {
|
|||||||
_ => "badge-critical",
|
_ => "badge-critical",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_a_plc_target_gets_the_plc_explanation() {
|
||||||
|
// Arrange
|
||||||
|
let targets = vec![
|
||||||
|
serde_json::json!({ "_id": { "$oid": "a1" }, "target_type": "plc_sps" }),
|
||||||
|
serde_json::json!({ "_id": { "$oid": "b2" }, "target_type": "web_app" }),
|
||||||
|
];
|
||||||
|
|
||||||
|
// Act + Assert
|
||||||
|
assert!(is_plc_target(Some(&targets), "a1"));
|
||||||
|
assert!(!is_plc_target(Some(&targets), "b2"));
|
||||||
|
assert!(!is_plc_target(Some(&targets), "c3"));
|
||||||
|
assert!(!is_plc_target(Some(&targets), ""), "all targets");
|
||||||
|
assert!(!is_plc_target(None, "a1"), "targets not loaded yet");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -39,6 +39,7 @@ use crate::infrastructure::platform::{use_source_only, SourceOnlyNote};
|
|||||||
use crate::infrastructure::projects::{
|
use crate::infrastructure::projects::{
|
||||||
fetch_projects, project_ids_of, projects_named, set_target_projects,
|
fetch_projects, project_ids_of, projects_named, set_target_projects,
|
||||||
};
|
};
|
||||||
|
use crate::pages::devices::DevicesCard;
|
||||||
use crate::pages::target_views::{RepoCrumbs, RepoView, TodayLink};
|
use crate::pages::target_views::{RepoCrumbs, RepoView, TodayLink};
|
||||||
|
|
||||||
/// Open findings listed on the page; the rest are one click away.
|
/// Open findings listed on the page; the rest are one click away.
|
||||||
@@ -317,6 +318,12 @@ pub fn TargetPage(id: String) -> Element {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// A control application's Siemens controllers (SPS item 4a).
|
||||||
|
if str_at(&t, "target_type") == "plc_sps"
|
||||||
|
|| t.get("devices").and_then(|d| d.as_array()).is_some_and(|d| !d.is_empty())
|
||||||
|
{
|
||||||
|
DevicesCard { target_id: id.clone() }
|
||||||
|
}
|
||||||
if let Some(graph) = graph {
|
if let Some(graph) = graph {
|
||||||
section { class: "card target-graph",
|
section { class: "card target-graph",
|
||||||
div { class: "target-card-head",
|
div { class: "target-card-head",
|
||||||
@@ -904,7 +911,10 @@ fn TargetEditor(
|
|||||||
toasts.push(ToastType::Success, tx::UPDATED.get(lang));
|
toasts.push(ToastType::Success, tx::UPDATED.get(lang));
|
||||||
on_saved.call(());
|
on_saved.call(());
|
||||||
}
|
}
|
||||||
Err(e) => toasts.push(ToastType::Error, e.to_string()),
|
Err(e) => toasts.push(
|
||||||
|
ToastType::Error,
|
||||||
|
crate::i18n::texts::metering::demo_refusal(&e.to_string(), lang),
|
||||||
|
),
|
||||||
}
|
}
|
||||||
edit_saving.set(false);
|
edit_saving.set(false);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "compliance-dast"
|
name = "compliance-dast"
|
||||||
version = "0.4.18"
|
version = "0.4.20"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "compliance-graph"
|
name = "compliance-graph"
|
||||||
version = "0.4.18"
|
version = "0.4.20"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "compliance-mcp"
|
name = "compliance-mcp"
|
||||||
version = "0.4.18"
|
version = "0.4.20"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "compliance-smoke"
|
name = "compliance-smoke"
|
||||||
version = "0.4.18"
|
version = "0.4.20"
|
||||||
edition = "2021"
|
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."
|
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,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "control-map"
|
name = "control-map"
|
||||||
version = "0.4.18"
|
version = "0.4.20"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ curl -H "Authorization: Bearer bp_…" https://pruefwerk.breakpilot.com/api/v1/f
|
|||||||
| `pruefwerk:sbom.read` | Stückliste lesen und exportieren (`GET /api/v1/sbom`, `/sbom/filters`, `/sbom/export`, `/sbom/licenses`, `/sbom/quality`, `/sbom/diff`) |
|
| `pruefwerk:sbom.read` | Stückliste lesen und exportieren (`GET /api/v1/sbom`, `/sbom/filters`, `/sbom/export`, `/sbom/licenses`, `/sbom/quality`, `/sbom/diff`) |
|
||||||
| `pruefwerk:scans.read` | Prüfläufe lesen (`GET /api/v1/scan-runs`) |
|
| `pruefwerk:scans.read` | Prüfläufe lesen (`GET /api/v1/scan-runs`) |
|
||||||
| `pruefwerk:scans.run` | Eine Prüfung starten (`POST /api/v1/targets/{id}/scan`, `/dast/targets/{id}/scan`) |
|
| `pruefwerk:scans.run` | Eine Prüfung starten (`POST /api/v1/targets/{id}/scan`, `/dast/targets/{id}/scan`) |
|
||||||
|
| `pruefwerk:uploads.write` | Dateien zu Prüfobjekten hochladen (`POST /api/v1/targets/{id}/artifacts/upload`), etwa den Export des TIA-Connectors |
|
||||||
| `pruefwerk:enisa.read` | ENISA-Meldeentwürfe lesen (`GET /api/v1/targets/{id}/enisa`, `/cves/{id}/enisa`) |
|
| `pruefwerk:enisa.read` | ENISA-Meldeentwürfe lesen (`GET /api/v1/targets/{id}/enisa`, `/cves/{id}/enisa`) |
|
||||||
|
|
||||||
Alles andere ist mit einem Schlüssel nicht erreichbar, auch mit allen Scopes:
|
Alles andere ist mit einem Schlüssel nicht erreichbar, auch mit allen Scopes:
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ What Prüfwerk keeps about a target, where, and when it is removed.
|
|||||||
|
|
||||||
Deleting a target (`DELETE /api/v1/targets/{id}`, or **Delete** on the
|
Deleting a target (`DELETE /api/v1/targets/{id}`, or **Delete** on the
|
||||||
targets page) removes its records and its files. Erasing a tenant
|
targets page) removes its records and its files. Erasing a tenant
|
||||||
(`DELETE /api/v1/platform/tenants/{id}/data`, confirmed) drops its database
|
(`DELETE /api/v1/platform/tenants/{id}/data` with `{"confirm": "<tenant id>"}`,
|
||||||
|
the same id as in the path) drops its database
|
||||||
and removes every file listed above; the response says how many paths were
|
and removes every file listed above; the response says how many paths were
|
||||||
removed and how many could not be. Only paths inside the two configured base
|
removed and how many could not be. Only paths inside the two configured base
|
||||||
directories are ever removed.
|
directories are ever removed.
|
||||||
|
|||||||
+130
-4
@@ -196,10 +196,136 @@ CERT@VDE): the alert links the advisory (e.g. `VDE-2026-094`) and carries the
|
|||||||
vendor's remediation and the fixed version.
|
vendor's remediation and the fixed version.
|
||||||
|
|
||||||
A CVE alert a later scan no longer finds (the project now references a fixed
|
A CVE alert a later scan no longer finds (the project now references a fixed
|
||||||
runtime or library version) is marked resolved, and its VEX status becomes
|
runtime or library version) is marked resolved, as for code targets; this needs
|
||||||
`fixed`, as for code targets; this needs both lookups (OSV and NVD) to have
|
both lookups (OSV and NVD) to have covered every component. The scan does not
|
||||||
covered every component. For a PLC project in a managed Git repository, the CVE
|
state VEX `fixed` for it: that is a person's statement. For a PLC project in a
|
||||||
issues in the repository follow, as for code.
|
managed Git repository, its CVE issue stays open with a note that the CVE is no
|
||||||
|
longer found, and a person closes it.
|
||||||
|
|
||||||
|
## Siemens controllers by order number
|
||||||
|
|
||||||
|
A Siemens CPU is matched by what is printed on it, without a project file. On the
|
||||||
|
target's page, the **Steuerungen** card opens the target's controllers. Each
|
||||||
|
controller is entered with:
|
||||||
|
|
||||||
|
- its **order number** (Artikelnummer, MLFB), such as `6ES7511-1AK02-0AB0`, from
|
||||||
|
the rating plate or from TIA Portal (device configuration, Properties,
|
||||||
|
General, Catalog information);
|
||||||
|
- its **firmware**, such as `V3.1.4`, also shown on the CPU web server's start
|
||||||
|
page;
|
||||||
|
- optionally a name (`Hauptsteuerung Zelle 2`).
|
||||||
|
|
||||||
|
The form recognises the order number while it is typed, by the name Siemens
|
||||||
|
uses for it. A valid number that no advisory names yet is accepted: Prüfwerk
|
||||||
|
checks it against every new advisory.
|
||||||
|
|
||||||
|
Siemens ProductCERT names every affected CPU in its CSAF advisories by order
|
||||||
|
number and firmware range. Prüfwerk reads them daily and shows each controller
|
||||||
|
as a module on a DIN rail, with a light:
|
||||||
|
|
||||||
|
| Light | Meaning |
|
||||||
|
| --- | --- |
|
||||||
|
| red | an advisory affects the installed firmware |
|
||||||
|
| green | advisories name the controller, none affects this firmware |
|
||||||
|
| grey | no advisory names the order number |
|
||||||
|
|
||||||
|
The controller's panel lists the advisories with their severity, the firmware
|
||||||
|
that fixes them (`Behoben ab V3.1.5`, read from Siemens' remediation) and a
|
||||||
|
**Quelle** link to the advisory, which Siemens' terms require. The page shows
|
||||||
|
the current advisories at once. The target's CVE alerts and issues follow at
|
||||||
|
its next scan.
|
||||||
|
|
||||||
|
Not matched yet: advisories that name only a whole series ("S7-1200 CPU
|
||||||
|
family") instead of order numbers.
|
||||||
|
|
||||||
|
The API takes `devices` on `POST /api/v1/targets` and `PATCH
|
||||||
|
/api/v1/targets/{id}` (`order_number`, `firmware`, `label`).
|
||||||
|
`GET /api/v1/targets/{id}/devices` returns each device with the advisories
|
||||||
|
naming it, and `GET /api/v1/devices/lookup?order_number=` what the advisories
|
||||||
|
know of an order number.
|
||||||
|
|
||||||
|
## Siemens TIA Portal projects (TIA export)
|
||||||
|
|
||||||
|
A TIA Portal project reaches Prüfwerk as a **TIA export**: a zip that a TIA
|
||||||
|
connector writes on the engineering PC, reading the project through TIA Portal
|
||||||
|
Openness and never changing it. It is uploaded to a PLC/SPS target as a PLC
|
||||||
|
project with the format `tia_export`, with an API key holding
|
||||||
|
`pruefwerk:uploads.write` ([API keys](./api-keys)):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -H "Authorization: Bearer bp_…" \
|
||||||
|
-F kind=plc_project -F plc_format=tia_export \
|
||||||
|
-F file=@linie1.tia-export.zip \
|
||||||
|
https://pruefwerk.breakpilot.com/api/v1/targets/<id>/artifacts/upload
|
||||||
|
```
|
||||||
|
|
||||||
|
Its manifest is read on upload: a file that is not an export is refused with
|
||||||
|
`422` and a `code` (`not_zip`, `no_manifest`, `manifest_too_large`,
|
||||||
|
`manifest_invalid`, `bundle_version`). A new export of a target replaces the
|
||||||
|
last one.
|
||||||
|
|
||||||
|
What the export brings today:
|
||||||
|
|
||||||
|
- **Devices**: each device with a Siemens order number and a firmware version
|
||||||
|
joins the target's controllers (above), named as in the project, and is
|
||||||
|
matched against Siemens' advisories like one entered by hand. A controller
|
||||||
|
entered by hand with the same order number wins: it says which firmware is
|
||||||
|
installed, the export only what was configured. Devices without either are
|
||||||
|
listed on the run as not matched.
|
||||||
|
- **Blocks**: their code is not analysed yet; the run says how many and in
|
||||||
|
which languages. Know-how-protected blocks are listed as not analysable,
|
||||||
|
never counted as clean.
|
||||||
|
- **Security settings** of each CPU: carried in the export, not checked yet.
|
||||||
|
|
||||||
|
### The export's contract
|
||||||
|
|
||||||
|
`manifest.json` at the root of the zip, at most 4 MiB; fields Prüfwerk does not
|
||||||
|
know are ignored. Nothing in it is a secret: a connector never exports
|
||||||
|
passwords or keys.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"bundle_version": 1,
|
||||||
|
"tia_version": "V20",
|
||||||
|
"project": { "name": "Linie 1", "modified": "2026-11-30T10:00:00Z",
|
||||||
|
"protected": { "value": true } },
|
||||||
|
"exported_at": "2026-12-01T09:00:00Z",
|
||||||
|
"connector": { "name": "Breakpilot TIA Connector", "version": "0.1.0" },
|
||||||
|
"devices": [
|
||||||
|
{ "name": "PLC_1", "role": "cpu",
|
||||||
|
"type_identifier": "OrderNumber:6ES7 515-2UM01-0AB0/V2.9",
|
||||||
|
"security": {
|
||||||
|
"access_level": { "unreadable": "no password set" },
|
||||||
|
"put_get": { "value": false },
|
||||||
|
"web_server": { "value": true },
|
||||||
|
"web_server_https_only": { "value": true },
|
||||||
|
"opc_ua_server": { "value": true },
|
||||||
|
"opc_ua_security_policies": { "value": ["Basic256Sha256"] },
|
||||||
|
"secure_pg_hmi_only": { "value": true },
|
||||||
|
"confidential_data_protected": { "value": true }
|
||||||
|
} },
|
||||||
|
{ "name": "HMI_1", "role": "hmi", "order_number": "6AV2 124-0GC01-0AX0",
|
||||||
|
"firmware": "V17.0.0.0" }
|
||||||
|
],
|
||||||
|
"blocks": [
|
||||||
|
{ "device": "PLC_1", "name": "Main", "kind": "ob", "language": "LAD",
|
||||||
|
"file": "blocks/PLC_1/Main.xml" },
|
||||||
|
{ "device": "PLC_1", "name": "FB_42", "kind": "fb", "protected": true }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Field | |
|
||||||
|
| --- | --- |
|
||||||
|
| `bundle_version` | `1` |
|
||||||
|
| `tia_version` | the TIA Portal version read with: `V20`, `V21` |
|
||||||
|
| `devices[].role` | `cpu`, `hmi`, `module`, anything else counts as other |
|
||||||
|
| `devices[].type_identifier` | TIA's type identifier; order number and firmware are taken from it unless given as `order_number` and `firmware`. A catalog order number with wildcards (`…-0Axx`) or a variant without a version (`//10002`) leaves the device not matched |
|
||||||
|
| `devices[].security` | a CPU's settings as configured in the project; each is `{"value": …}` when read, `{"unreadable": "<why>"}` when Openness could not read it, absent when not looked at |
|
||||||
|
| `security.access_level` | `full_access_including_failsafe`, `full_access`, `read_access`, `hmi_access`, `no_access`, `none` |
|
||||||
|
| `blocks[].kind` | `ob`, `fb`, `fc`, `db`, `udt` |
|
||||||
|
| `blocks[].file` | where the block's export lies in the zip: SimaticML (`.xml`), SIMATIC SD (`.s7dcl` with its `.s7res`, V21) or SCL (`.scl`) |
|
||||||
|
| `blocks[].protected` | know-how protected: no `file`, listed as not analysable |
|
||||||
|
|
||||||
## Dynamic testing — ICS protocol probe
|
## Dynamic testing — ICS protocol probe
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
"key": "plc-pump-station",
|
"key": "plc-pump-station",
|
||||||
"name": "PLC pump station (ST + FBD, composite)",
|
"name": "PLC pump station (ST + FBD, composite)",
|
||||||
"target_type": "plc_sps",
|
"target_type": "plc_sps",
|
||||||
"description": "Composite PlcSps demo: Structured Text + FBD-as-PLCopen-XML control logic, plus an optional live Modbus endpoint (in-cluster plc-sim) and an optional device firmware image. Exercises PLC SAST, ICS probe, semantic control mapping.",
|
"description": "Composite PlcSps demo: Structured Text + FBD-as-PLCopen-XML control logic, plus an optional live Modbus endpoint (in-cluster plc-sim) and an optional device firmware image. Runs on a Siemens S7-1500 CPU with an old firmware, so its SBOM lists the controller and Siemens' advisories match it. Exercises PLC SAST, ICS probe, semantic control mapping, Siemens advisory matching.",
|
||||||
"artifacts": [
|
"artifacts": [
|
||||||
{
|
{
|
||||||
"kind": "plc_project",
|
"kind": "plc_project",
|
||||||
@@ -30,6 +30,13 @@
|
|||||||
"optional": true
|
"optional": true
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
|
"devices": [
|
||||||
|
{
|
||||||
|
"order_number": "6ES7511-1AK02-0AB0",
|
||||||
|
"firmware": "2.9.4",
|
||||||
|
"label": "Pump station CPU"
|
||||||
|
}
|
||||||
|
],
|
||||||
"expect": {
|
"expect": {
|
||||||
"min_findings": 16,
|
"min_findings": 16,
|
||||||
"sast_rule_ids": [
|
"sast_rule_ids": [
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
{
|
{
|
||||||
"scan_status": "completed",
|
"scan_status": "completed",
|
||||||
"skipped_stages": [],
|
"skipped_stages": [],
|
||||||
"sbom": [],
|
"sbom": [
|
||||||
|
"siemens-device:6ES7511-1AK02-0AB0@2.9.4"
|
||||||
|
],
|
||||||
"findings": [
|
"findings": [
|
||||||
"plc-control-logic:plc-array-unchecked-index pump_station.st:29",
|
"plc-control-logic:plc-array-unchecked-index pump_station.st:29",
|
||||||
"plc-control-logic:plc-default-password pump_fbd.xml:8",
|
"plc-control-logic:plc-default-password pump_fbd.xml:8",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "werkbank-exec"
|
name = "werkbank-exec"
|
||||||
version = "0.4.18"
|
version = "0.4.20"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
description = "Shared dynamic-execution logic: soft-PLC provisioning + industrial-protocol probing, used by the compliance agent and the Werkbank runner."
|
description = "Shared dynamic-execution logic: soft-PLC provisioning + industrial-protocol probing, used by the compliance agent and the Werkbank runner."
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user