Compare commits

..
Author SHA1 Message Date
Sharang ParnerkarandClaude Opus 5.5 aad3831e82 fix(metering): a demo target given the tenant's own sources counts under the cap
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 5m1s
CI / Check (pull_request) Successful in 21m44s
A demo target sat outside the entry plan's cap for good, even once it
was pointed at the tenant's own code. Now, when its artifacts change to
other sources (editor, attach, upload), it becomes the tenant's own
target: the demo mark goes and it counts. If the plan has no room, the
change is refused with 409 `target_limit` and it stays a demo target.
A new name or branch on the same sources changes nothing.

The dashboard says so in words in the target editor and the upload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 23:20:57 +01:00
53 changed files with 92 additions and 3310 deletions

No files matched your search

Generated
+9 -9
View File
@@ -601,7 +601,7 @@ dependencies = [
[[package]]
name = "compliance-agent"
version = "0.4.20"
version = "0.4.18"
dependencies = [
"axum",
"base64 0.22.1",
@@ -657,7 +657,7 @@ dependencies = [
[[package]]
name = "compliance-core"
version = "0.4.20"
version = "0.4.18"
dependencies = [
"aes-gcm",
"axum",
@@ -689,7 +689,7 @@ dependencies = [
[[package]]
name = "compliance-dashboard"
version = "0.4.20"
version = "0.4.18"
dependencies = [
"async-trait",
"axum",
@@ -727,7 +727,7 @@ dependencies = [
[[package]]
name = "compliance-dast"
version = "0.4.20"
version = "0.4.18"
dependencies = [
"axum",
"base64 0.22.1",
@@ -749,7 +749,7 @@ dependencies = [
[[package]]
name = "compliance-graph"
version = "0.4.20"
version = "0.4.18"
dependencies = [
"bson",
"chrono",
@@ -774,7 +774,7 @@ dependencies = [
[[package]]
name = "compliance-mcp"
version = "0.4.20"
version = "0.4.18"
dependencies = [
"axum",
"bson",
@@ -797,7 +797,7 @@ dependencies = [
[[package]]
name = "compliance-smoke"
version = "0.4.20"
version = "0.4.18"
dependencies = [
"axum",
"compliance-core",
@@ -932,7 +932,7 @@ dependencies = [
[[package]]
name = "control-map"
version = "0.4.20"
version = "0.4.18"
dependencies = [
"serde",
"serde_json",
@@ -7127,7 +7127,7 @@ dependencies = [
[[package]]
name = "werkbank-exec"
version = "0.4.20"
version = "0.4.18"
dependencies = [
"compliance-core",
"compliance-dast",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-agent"
version = "0.4.20"
version = "0.4.18"
edition = "2021"
[lints]
@@ -1,268 +0,0 @@
//! 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);
}
}
+10 -23
View File
@@ -17,7 +17,7 @@ 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, TargetDevice};
use compliance_core::models::PlcDevice;
use compliance_core::tenant_ctx::TenantCtx;
/// The provider whose advisories name devices by order number.
@@ -44,14 +44,10 @@ async fn advisories_naming(
}
/// Each of `devices` against `advisories`.
/// An exported device keeps the export it comes from (#1090, #1097).
fn checks(devices: Vec<TargetDevice>, advisories: &[Advisory]) -> Vec<DeviceCheck> {
fn checks(devices: Vec<PlcDevice>, advisories: &[Advisory]) -> Vec<DeviceCheck> {
devices
.into_iter()
.map(|d| DeviceCheck {
exported_in: d.exported_in,
..DeviceCheck::new(d.device, advisories)
})
.map(|device| DeviceCheck::new(device, advisories))
.collect()
}
@@ -85,13 +81,10 @@ pub async fn list_devices(
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::NOT_FOUND)?;
// Entered and exported alike (#1090, #1097): a TIA export's devices are
// listed under their names in the project, saying which export they are
// from, so a client edits only the entered ones.
let target_devices = target.target_devices();
let mut order_numbers: Vec<String> = target_devices
let mut order_numbers: Vec<String> = target
.devices
.iter()
.map(|d| d.device.order_number.clone())
.map(|d| d.order_number.clone())
.collect();
order_numbers.sort();
order_numbers.dedup();
@@ -100,7 +93,7 @@ pub async fn list_devices(
} else {
advisories_naming(agent.advisory_index.as_ref(), order_numbers).await?
};
let devices = checks(target_devices, &advisories);
let devices = checks(target.devices, &advisories);
Ok(Json(ApiResponse {
total: Some(devices.len() as u64),
data: devices,
@@ -205,15 +198,9 @@ mod tests {
assert_eq!(advisories.len(), 1);
let devices = checks(
vec![
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.4", None)
.unwrap()
.into(),
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.5", None)
.unwrap()
.into(),
PlcDevice::new("6ES7516-3AN02-0AB0", "3.0", None)
.unwrap()
.into(),
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,
);
-1
View File
@@ -1,5 +1,4 @@
pub mod admin;
pub mod branding;
pub mod chat;
pub mod connections;
pub mod cve_history;
+15 -165
View File
@@ -968,11 +968,7 @@ pub struct UploadArtifactForm {
/// (a supplier's CycloneDX or SPDX 2 SBOM of a bought-in component).
#[schema(example = "source_archive")]
kind: String,
/// The PLC project's format, for a PLC project: `plcopen_xml`,
/// `structured_text`, `project_archive`, `tia_export` (a TIA
/// connector's export, whose manifest is read on upload) or `tia_aml` (a
/// TIA hardware export; a file named `*.aml` is one whatever is given).
#[schema(example = "tia_export")]
/// The PLC project's format, for a PLC project.
plc_format: Option<String>,
}
@@ -1002,7 +998,7 @@ pub struct UploadArtifactForm {
(status = 400, description = "Not an id, or a missing or unknown field"),
(status = 413, description = "The file is too large (a supplier SBOM: over 20 MiB)"),
(status = 415, description = "An archive format that cannot be unpacked"),
(status = 422, description = "A supplier SBOM, TIA export or TIA hardware export (`.aml`) that cannot be read; `error` says why, `code` names it"),
(status = 422, description = "A supplier SBOM that cannot be read; `error` says why"),
(status = 401, description = "No valid bearer token"),
)
)]
@@ -1088,15 +1084,13 @@ pub(super) struct AttachedUpload {
/// 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
/// be unpacked and for encryption. The file is deleted unless the artifact
/// references it. A TIA export's manifest is read (#1090), its devices are
/// kept with it, and it replaces the target's previous export.
/// references it.
///
/// # Errors
///
/// 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`]),
/// 422 with its code for a TIA export that cannot be read, 500 when the
/// file or the database fails.
/// 500 when the file or the database fails.
pub(super) async fn attach_upload(
db: &crate::database::Database,
target: &OnboardedTarget,
@@ -1105,13 +1099,6 @@ pub(super) async fn attach_upload(
upload: StoredUpload,
) -> Result<AttachedUpload, UploadRefusal> {
let oid = target.id.ok_or(StatusCode::INTERNAL_SERVER_ERROR)?;
// A TIA hardware export is told by its name, whatever format was picked
// (#1097): the dashboard offers no format for it.
let plc_format = if kind == ArtifactKind::PlcProject && is_aml_name(&upload.name) {
Some(PlcFormat::TiaAml)
} else {
plc_format
};
// Non-file kinds (git repo, live URL, container ref, text) use the JSON
// add-artifact endpoint, not upload.
let mut artifact = uploaded_artifact(kind, plc_format, &upload.name, &upload.path, upload.size)
@@ -1136,51 +1123,6 @@ pub(super) async fn attach_upload(
let read = SupplierSbomSummary::of(read)?;
artifact.detected.extend(read.facts());
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 is_tia_aml(&artifact) {
// A hardware export (#1097): read now, so a wrong file is refused
// while the person who chose it is still there.
let path = upload.path.clone();
let export =
tokio::task::spawn_blocking(move || crate::pipeline::plc::aml::read_aml(&path))
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.map_err(|e| UploadRefusal {
status: if e == crate::pipeline::plc::aml::AmlError::TooLarge {
StatusCode::PAYLOAD_TOO_LARGE
} else {
StatusCode::UNPROCESSABLE_ENTITY
},
reason: Some((e.to_string(), e.code())),
})?;
artifact.detected.push(DetectedFact::new(
"tia_devices",
export.devices.len().to_string(),
"upload",
));
if let Some(writer) = &export.writer {
artifact
.detected
.push(DetectedFact::new("tia_writer", writer.as_str(), "upload"));
}
if let Some(plc) = artifact.plc.as_mut() {
plc.devices = compliance_core::models::exported_devices(&export.devices).matched;
}
} else if kind != ArtifactKind::FirmwareImage {
match archive_check(upload.path.clone()).await? {
// 7z and rar are never unpacked: say so now, not after a scan.
@@ -1206,32 +1148,7 @@ pub(super) async fn attach_upload(
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
upload.keep();
if kind == ArtifactKind::SupplierSbom {
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;
} else if is_tia_aml(&artifact) {
replace_earlier(
db,
oid,
&artifact_id,
&target.artifacts,
Replaced::TiaAml(&artifact.source_ref),
)
.await;
replace_supplier_sboms(db, oid, &artifact_id, &target.artifacts).await;
}
Ok(AttachedUpload {
@@ -1240,102 +1157,35 @@ pub(super) async fn attach_upload(
})
}
/// Whether `artifact` is a TIA connector's export (#1090).
fn is_tia_export(artifact: &compliance_core::models::Artifact) -> bool {
artifact.kind == ArtifactKind::PlcProject
&& artifact.plc.as_ref().map(|p| p.format) == Some(PlcFormat::TiaExport)
}
/// Whether `artifact` is a TIA hardware export (#1097).
fn is_tia_aml(artifact: &compliance_core::models::Artifact) -> bool {
artifact.kind == ArtifactKind::PlcProject
&& artifact.plc.as_ref().map(|p| p.format) == Some(PlcFormat::TiaAml)
}
/// Whether a file name is an AutomationML file's (`.aml`, any case).
fn is_aml_name(name: &str) -> bool {
std::path::Path::new(name)
.extension()
.is_some_and(|e| e.eq_ignore_ascii_case("aml"))
}
/// 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> {
/// 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,
/// A hardware export of this file name (#1097): a station is exported on
/// its own, so another file of the same machine stays.
TiaAml(&'a str),
}
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" },
Self::TiaAml(name) => {
doc! { "kind": "plc_project", "plc.format": "tia_aml", "source_ref": name }
}
}
}
/// 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),
Self::TiaAml(name) => is_tia_aml(artifact) && artifact.source_ref == name,
}
}
}
/// 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(
/// Remove the target's supplier SBOMs other than the one just uploaded
/// (`kept`): a new version replaces the one before it (#1025), so a scan never
/// reads two versions as one. Their files go too, once nothing references
/// them. Best-effort, after the new one is stored: if this fails, the next
/// scan reads both versions, and nothing is lost.
async fn replace_supplier_sboms(
db: &crate::database::Database,
target: ObjectId,
kept: &str,
before: &[compliance_core::models::Artifact],
what: Replaced<'_>,
) {
let mut earlier = what.filter();
earlier.insert("id", doc! { "$ne": kept });
let pulled = db
.onboarded_targets()
.update_one(
doc! { "_id": target },
doc! { "$pull": { "artifacts": earlier } },
doc! { "$pull": { "artifacts": { "kind": "supplier_sbom", "id": { "$ne": kept } } } },
)
.await;
if let Err(e) = pulled {
tracing::warn!(target_id = %target, ?what, error = %e, "replaced upload not removed");
tracing::warn!(target_id = %target, error = %e, "replaced supplier SBOM not removed");
return;
}
for old in before
.iter()
.filter(|a| what.matches(a) && a.id != kept)
.filter(|a| a.kind == ArtifactKind::SupplierSbom && a.id != kept)
.filter_map(|a| a.stored_path.as_deref())
{
if let Err(e) = std::fs::remove_file(old) {
tracing::warn!(target_id = %target, ?what, error = %e, "replaced upload's file left");
tracing::warn!(target_id = %target, error = %e, "replaced supplier SBOM file left");
}
}
}
+3 -28
View File
@@ -250,16 +250,14 @@ pub async fn export(
/// `DELETE /api/v1/platform/tenants/{id}/data` — GDPR erasure: drops the
/// tenant database and removes its code from disk (clones, uploads, work
/// 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.
/// trees, blobs, runner artifacts). Requires `{"confirm": "<slug or id>"}`.
pub async fn delete_data(
State(st): State<PlatformState>,
Path(tenant_id): Path<String>,
body: Option<Json<LifecycleBody>>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let confirm = body.and_then(|Json(b)| b.confirm);
if !confirms_erasure(&tenant_id, confirm.as_deref()) {
let confirm = body.and_then(|Json(b)| b.confirm).unwrap_or_default();
if confirm.is_empty() {
return Err(StatusCode::BAD_REQUEST);
}
// Where the tenant's code lies on disk, read before its records go.
@@ -301,12 +299,6 @@ 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
/// 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
@@ -856,20 +848,3 @@ mod target_count_tests {
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("")));
}
}
-7
View File
@@ -75,12 +75,6 @@ pub const KEY_SCOPES: &[(Method, &str, &str)] = &[
(Method::GET, "/api/v1/licenses/policy", SBOM_READ),
(Method::GET, "/api/v1/scan-runs", SCANS_READ),
(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::GET, "/api/v1/targets/{id}/enisa", ENISA_READ),
(Method::GET, "/api/v1/cves/{id}/enisa", ENISA_READ),
@@ -91,7 +85,6 @@ const FINDINGS_WRITE: &str = "pruefwerk:findings.write";
const SBOM_READ: &str = "pruefwerk:sbom.read";
const SCANS_READ: &str = "pruefwerk:scans.read";
const SCANS_RUN: &str = "pruefwerk:scans.run";
const UPLOADS_WRITE: &str = "pruefwerk:uploads.write";
const ENISA_READ: &str = "pruefwerk:enisa.read";
/// What a legacy key (issued before scopes, no scopes of its own) may do:
@@ -341,7 +341,6 @@ const ALL_SCOPES: &[&str] = &[
"pruefwerk:sbom.read",
"pruefwerk:scans.read",
"pruefwerk:scans.run",
"pruefwerk:uploads.write",
"pruefwerk:enisa.read",
];
-4
View File
@@ -73,10 +73,6 @@ fn described_routes() -> OpenApiRouter {
handlers::supply_chain_layout::reset_layout
))
.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
// authentication and entitlement layers in front of it (a blocked
// member gets 403 MEMBER_BLOCKED), for the dashboard's sign-in check.
-1
View File
@@ -167,7 +167,6 @@ async fn seed_one(
compliance_core::models::OnboardedTarget::new(full_name.to_string(), demo.target_type);
target.description = demo.description.clone();
target.demo = true;
target.devices = demo.devices.clone();
for a in demo.artifacts.iter().filter(|a| !a.is_upload()) {
match a.resolved_source_ref() {
Some(source_ref) => target.artifacts.push(targets::reference_artifact(
-31
View File
@@ -117,10 +117,6 @@ pub struct DemoTarget {
/// Applied by the nightly harness to the fixtures it onboards itself.
#[serde(default)]
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.
#[serde(default)]
pub expect: Expect,
@@ -495,32 +491,6 @@ mod tests {
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]
fn manifest_is_well_formed() {
let m = manifest();
@@ -619,7 +589,6 @@ mod tests {
optional: true,
}],
enabled_scans: Vec::new(),
devices: Vec::new(),
expect: Expect::default(),
};
assert!(t.source_only());
+1 -1
View File
@@ -526,7 +526,7 @@ mod tests {
fn device(order_number: &str, firmware: &str) -> SbomEntry {
let device = compliance_core::models::PlcDevice::new(order_number, firmware, None).unwrap();
crate::pipeline::sbom::devices::entries(&[device.into()], "t").remove(0)
crate::pipeline::sbom::devices::entries(&[device], "t").remove(0)
}
#[test]
+3 -146
View File
@@ -1930,10 +1930,9 @@ impl PipelineOrchestrator {
// 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() {
if target.target_type == TargetType::PlcSps || !target.devices.is_empty() {
let devices =
crate::pipeline::sbom::devices::entries(&target_devices, &target_id);
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
@@ -2008,20 +2007,6 @@ impl PipelineOrchestrator {
// first, as in a code scan (#820, #825).
let mut left_out = LeftOut::default();
for a in &sources {
// A TIA export's block code is not read yet (#1093), and a
// hardware export holds none: the run says what they hold
// instead of finding nothing in them.
match a.plc.as_ref().map(|p| p.format) {
Some(PlcFormat::TiaExport) => {
self.note_tia_export(scan_run_id, a).await;
continue;
}
Some(PlcFormat::TiaAml) => {
self.note_tia_aml(scan_run_id, a).await;
continue;
}
_ => {}
}
let Some(path) = ingest_set.get(&a.id).and_then(|ia| ia.working_path.clone()) else {
continue;
};
@@ -2167,7 +2152,7 @@ impl PipelineOrchestrator {
}
all_sbom.extend(crate::pipeline::sbom::devices::entries(
&target.target_devices(),
&target.devices,
target_id,
));
if !all_sbom.is_empty() {
@@ -2181,134 +2166,6 @@ impl PipelineOrchestrator {
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;
}
}
/// What a TIA hardware export holds that this run cannot match (#1097):
/// devices without a Siemens order number or firmware. Its matchable
/// devices are in the SBOM through
/// [`compliance_core::models::OnboardedTarget::target_devices`].
async fn note_tia_aml(&self, scan_run_id: &str, export: &Artifact) {
let name = export
.display_name
.clone()
.unwrap_or_else(|| export.source_ref.clone());
let read = match export.stored_path.as_deref() {
Some(p) => crate::pipeline::plc::aml::read_aml(std::path::Path::new(p)),
None => Err(crate::pipeline::plc::aml::AmlError::NotAml(
"not stored".to_string(),
)),
};
let devices = match read {
Ok(export) => export.devices,
Err(e) => {
// Read at upload, so only a file lost since gets here.
tracing::warn!(scan_run_id, export = %name, error = %e, "TIA hardware export not readable");
self.skip_stage(
scan_run_id,
SkippedStage::new(
"plc_tia_aml",
SkipCode::ArtifactNotIngested,
format!("{name} could not be read: {e}"),
)
.about(name),
)
.await;
return;
}
};
let unmatched =
component_list(&compliance_core::models::exported_devices(&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
/// ephemeral soft-PLC (OpenPLC), start it, probe the provisioned Modbus
/// endpoint, and tear the instance down. Used when a PLC/SPS target has the
-280
View File
@@ -1,280 +0,0 @@
//! Reading a TIA Portal hardware export (#1097): the AutomationML file
//! ("CAx-Daten exportieren", `.aml`) a customer uploads without any connector.
//!
//! The file is CAEX XML, written to AutomationML's application
//! recommendation "Automation Project Configuration": each device item is an
//! `InternalElement` whose `Attribute`s include `TypeIdentifier`
//! (`OrderNumber:6ES7 515-2UM01-0AB0/V2.9`) and `FirmwareVersion`. Only those
//! two are read, and the item's name and the station it sits in for its
//! label. Elements are matched by local name, so CAEX 2.15 and 3.0 files both
//! read. The format was taken from the recommendation, not yet from a real
//! TIA export: check it against one before relying on more of it.
use std::path::Path;
use compliance_core::models::{TiaDevice, TiaDeviceRole};
/// The largest hardware export read, in bytes. A whole project with
/// hundreds of stations stays well below it.
pub(crate) const MAX_AML_BYTES: u64 = 64 << 20;
/// What a hardware export holds.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct AmlExport {
/// The tool and version that wrote it (`TIA Portal V20`), if it says.
pub writer: Option<String>,
/// Its device items with a concrete order number or a GSD identifier:
/// the ones advisories could name, and the third-party ones they cannot.
pub devices: Vec<TiaDevice>,
}
/// Why a hardware export cannot be read.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub(crate) enum AmlError {
/// Larger than [`MAX_AML_BYTES`].
#[error("the hardware export is larger than {} MiB", MAX_AML_BYTES >> 20)]
TooLarge,
/// Not an AutomationML (CAEX) file.
#[error("not an AutomationML hardware export: {0}")]
NotAml(String),
/// An AutomationML file without any device item.
#[error("the hardware export names no device")]
NoDevices,
}
impl AmlError {
/// A stable name of the refusal, for a client to word in its own language.
pub(crate) fn code(&self) -> &'static str {
match self {
Self::TooLarge => "too_large",
Self::NotAml(_) => "not_aml",
Self::NoDevices => "no_devices",
}
}
}
/// Read the hardware export at `path`.
///
/// # Errors
///
/// [`AmlError::TooLarge`] above [`MAX_AML_BYTES`], [`AmlError::NotAml`] for a
/// file that is not CAEX XML (a DTD is refused too), [`AmlError::NoDevices`]
/// when no device item carries a type identifier.
pub(crate) fn read_aml(path: &Path) -> Result<AmlExport, AmlError> {
let size = std::fs::metadata(path)
.map_err(|e| AmlError::NotAml(e.to_string()))?
.len();
if size > MAX_AML_BYTES {
return Err(AmlError::TooLarge);
}
// TIA writes UTF-8 with a BOM or UTF-16; the shared reader decodes both.
let text = compliance_core::encoding::read_source(path)
.map_err(|e| AmlError::NotAml(e.to_string()))?;
parse_aml(&text)
}
/// Read a hardware export from its text; see [`read_aml`].
pub(crate) fn parse_aml(text: &str) -> Result<AmlExport, AmlError> {
let doc = roxmltree::Document::parse(text).map_err(|e| AmlError::NotAml(e.to_string()))?;
let root = doc.root_element();
if root.tag_name().name() != "CAEXFile" {
return Err(AmlError::NotAml(format!(
"the root element is {}, not CAEXFile",
root.tag_name().name()
)));
}
let mut devices = Vec::new();
let mut items = 0_usize;
for element in root.descendants().filter(|n| is(n, "InternalElement")) {
let Some(identifier) = attribute(element, "TypeIdentifier") else {
continue;
};
items += 1;
let identifier = identifier.trim();
if !(identifier.starts_with("OrderNumber:") || identifier.starts_with("GSD:")) {
// Racks, stations and other system items name no article.
continue;
}
devices.push(TiaDevice {
name: label(element),
role: TiaDeviceRole::Module,
type_identifier: Some(identifier.to_string()),
order_number: None,
firmware: attribute(element, "FirmwareVersion").filter(|f| !f.trim().is_empty()),
security: None,
});
}
if items == 0 {
return Err(AmlError::NoDevices);
}
Ok(AmlExport {
writer: writer(root),
devices,
})
}
/// Whether `node` is an element with local name `name`, whatever its
/// namespace.
fn is(node: &roxmltree::Node<'_, '_>, name: &str) -> bool {
node.is_element() && node.tag_name().name() == name
}
/// The value of `element`'s own `Attribute` named `name`, if any.
fn attribute(element: roxmltree::Node<'_, '_>, name: &str) -> Option<String> {
element
.children()
.filter(|c| is(c, "Attribute") && c.attribute("Name") == Some(name))
.find_map(|a| a.children().find(|v| is(v, "Value")))
.and_then(|v| v.text())
.map(str::to_string)
}
/// A device item's label: its name, after the name of the outermost item
/// above it that also has a type (its station), so identical modules of two
/// stations stay apart (`Station_1 / DI 8x24VDC ST_1`).
fn label(element: roxmltree::Node<'_, '_>) -> String {
let name = element.attribute("Name").unwrap_or("").trim().to_string();
let station = element
.ancestors()
.skip(1)
.filter(|a| is(a, "InternalElement") && attribute(*a, "TypeIdentifier").is_some())
.last()
.and_then(|a| a.attribute("Name"))
.map(str::trim)
.filter(|s| !s.is_empty() && *s != name);
match station {
Some(station) => format!("{station} / {name}"),
None => name,
}
}
/// The tool that wrote the file: CAEX 3.0's `SourceDocumentInformation`
/// (`OriginName`, `OriginVersion`), else CAEX 2.15's `WriterHeader`.
fn writer(root: roxmltree::Node<'_, '_>) -> Option<String> {
let joined = |name: Option<&str>, version: Option<&str>| match (name, version) {
(Some(n), Some(v)) => Some(format!("{} {}", n.trim(), v.trim())),
(Some(n), None) => Some(n.trim().to_string()),
_ => None,
};
if let Some(info) = root
.descendants()
.find(|n| is(n, "SourceDocumentInformation"))
{
return joined(
info.attribute("OriginName"),
info.attribute("OriginVersion"),
);
}
let header = root.descendants().find(|n| is(n, "WriterHeader"))?;
let text_of = |name: &str| {
header
.children()
.find(|c| is(c, name))
.and_then(|c| c.text())
};
joined(text_of("WriterName"), text_of("WriterVersion"))
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
pub(crate) mod tests {
use super::*;
use compliance_core::models::exported_devices;
/// A synthetic hardware export after the "Automation Project
/// Configuration" recommendation (CAEX 3.0): one S7-1500 station with
/// two identical I/O modules, a drive, a GSD device and a rack.
pub(crate) const AML: &str = r#"<?xml version="1.0" encoding="utf-8"?>
<CAEXFile SchemaVersion="3.0" FileName="linie1.aml" xmlns="http://www.dke.de/CAEX">
<SourceDocumentInformation OriginName="TIA Portal" OriginVersion="V20" OriginID="x" LastWritingDateTime="2026-12-01T10:00:00"/>
<InstanceHierarchy Name="Linie 1">
<InternalElement Name="Linie 1" ID="p">
<InternalElement Name="Station_1" ID="d1">
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string"><Value>System:Device.S71500</Value></Attribute>
<InternalElement Name="Rack_0" ID="r1">
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string"><Value>System:Rack.S71500</Value></Attribute>
<InternalElement Name="PLC_1" ID="c1">
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string"><Value>OrderNumber:6ES7 515-2UM01-0AB0/V2.9</Value></Attribute>
<Attribute Name="FirmwareVersion" AttributeDataType="xs:string"><Value>V2.9</Value></Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int"><Value>1</Value></Attribute>
</InternalElement>
<InternalElement Name="DI 16x24VDC_1" ID="m1">
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string"><Value>OrderNumber:6ES7 521-1BH00-0AB0/V2.2</Value></Attribute>
</InternalElement>
<InternalElement Name="DI 16x24VDC_2" ID="m2">
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string"><Value>OrderNumber:6ES7 521-1BH00-0AB0/V2.1</Value></Attribute>
<Attribute Name="FirmwareVersion" AttributeDataType="xs:string"><Value>V2.2</Value></Attribute>
</InternalElement>
</InternalElement>
</InternalElement>
<InternalElement Name="Antrieb_1" ID="g1">
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string"><Value>OrderNumber:6SL3210-1KE11-8UF2</Value></Attribute>
</InternalElement>
<InternalElement Name="Drittgeraet" ID="x1">
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string"><Value>GSD:VENDOR.XML/DAP1</Value></Attribute>
</InternalElement>
</InternalElement>
</InstanceHierarchy>
</CAEXFile>"#;
#[test]
fn device_items_are_read_with_their_station_and_firmware() {
let export = parse_aml(AML).unwrap();
assert_eq!(export.writer.as_deref(), Some("TIA Portal V20"));
let names: Vec<_> = export.devices.iter().map(|d| d.name.as_str()).collect();
assert_eq!(
names,
[
"Station_1 / PLC_1",
"Station_1 / DI 16x24VDC_1",
"Station_1 / DI 16x24VDC_2",
"Antrieb_1",
"Drittgeraet"
]
);
let devices = exported_devices(&export.devices);
let matched: Vec<_> = devices
.matched
.iter()
.map(|d| (d.order_number.as_str(), d.firmware.as_str()))
.collect();
// The explicit FirmwareVersion wins over the identifier's version.
assert_eq!(
matched,
[
("6ES7515-2UM01-0AB0", "2.9"),
("6ES7521-1BH00-0AB0", "2.2"),
("6ES7521-1BH00-0AB0", "2.2"),
]
);
// The drive names no firmware, the GSD device no article.
assert_eq!(devices.unmatched, ["Antrieb_1", "Drittgeraet"]);
}
#[test]
fn a_caex_2_15_file_with_a_writer_header_reads_too() {
let aml = r#"<CAEXFile FileName="x.aml" SchemaVersion="2.15">
<AdditionalInformation><WriterHeader><WriterName>TIA Portal</WriterName><WriterVersion>V21</WriterVersion></WriterHeader></AdditionalInformation>
<InstanceHierarchy Name="p"><InternalElement Name="PLC_1" ID="c">
<Attribute Name="TypeIdentifier"><Value>OrderNumber:6ES7 511-1AK02-0AB0/V3.1</Value></Attribute>
</InternalElement></InstanceHierarchy></CAEXFile>"#;
let export = parse_aml(aml).unwrap();
assert_eq!(export.writer.as_deref(), Some("TIA Portal V21"));
assert_eq!(export.devices[0].name, "PLC_1");
}
#[test]
fn a_file_that_is_not_a_hardware_export_is_refused_with_its_code() {
let code = |text: &str| parse_aml(text).unwrap_err().code();
assert_eq!(code("not xml"), "not_aml");
assert_eq!(code("<project/>"), "not_aml");
assert_eq!(
code(r#"<!DOCTYPE x [<!ENTITY a "b">]><CAEXFile/>"#),
"not_aml"
);
assert_eq!(
code(r#"<CAEXFile><InstanceHierarchy Name="p"/></CAEXFile>"#),
"no_devices"
);
}
}
-2
View File
@@ -8,7 +8,6 @@
//! a `.projectarchive`) cannot be read; [`native_projects`] lists them so the
//! scan says so instead of finding nothing in silence (#165).
pub(crate) mod aml;
pub mod ast;
pub(crate) mod graph;
pub mod lexer;
@@ -16,7 +15,6 @@ pub mod parser;
pub mod plcopen;
pub mod rules;
pub mod sbom;
pub(crate) mod tia;
use std::path::Path;
-152
View File
@@ -1,152 +0,0 @@
//! 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(&not_zip, b"plain text").unwrap();
assert_eq!(read_manifest(&not_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"));
}
}
+3 -4
View File
@@ -65,9 +65,8 @@ pub struct RepoView {
pub supplier_sboms: Vec<(std::path::PathBuf, String)>,
/// Who supplies the component, for one bought in (#1025).
pub supplier: Option<compliance_core::models::SupplierComponent>,
/// The Siemens controllers the target runs on (SPS item 4a): entered,
/// and declared by its TIA exports (#1090).
pub devices: Vec<compliance_core::models::TargetDevice>,
/// The Siemens controllers the target runs on (SPS item 4a).
pub devices: Vec<compliance_core::models::PlcDevice>,
}
impl RepoView {
@@ -105,7 +104,7 @@ impl RepoView {
build_outputs: Vec::new(),
supplier_sboms: Vec::new(),
supplier: target.supplier.clone(),
devices: target.target_devices(),
devices: target.devices.clone(),
};
if let Some(git) = &code.git {
view.default_branch = git.default_branch.clone();
+12 -35
View File
@@ -1,32 +1,23 @@
//! The Siemens controllers a target runs on ([`PlcDevice`], SPS item 4a) as
//! SBOM entries: one per device, named and versioned as the customer
//! entered it or a TIA export declares it (#1090), with the order number the
//! vendor's CSAF advisories name it by (matched in
//! [`crate::pipeline::csaf_match`]).
//! entered it, with the order number the vendor's CSAF advisories name it by
//! (matched in [`crate::pipeline::csaf_match`]).
use compliance_core::models::{SbomEntry, TargetDevice};
use compliance_core::models::{PlcDevice, SbomEntry};
/// The package manager of a device entry.
pub(crate) const DEVICE_MANAGER: &str = "siemens-device";
/// The SBOM entries of target `repo_id`'s devices
/// ([`compliance_core::models::OnboardedTarget::target_devices`]). A device
/// is named by its order number, so two devices of one type at one firmware
/// 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> {
/// The SBOM entries of target `repo_id`'s `devices`. A device is named by its
/// order number, so two devices of one type at one firmware are one entry;
/// its label, if any, is kept as evidence.
pub(crate) fn entries(devices: &[PlcDevice], repo_id: &str) -> Vec<SbomEntry> {
let mut entries: Vec<SbomEntry> = Vec::with_capacity(devices.len());
for TargetDevice {
device,
exported_in,
} 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(),
};
for device in devices {
let evidence = device.label.as_deref().map_or_else(
|| "entered with the target".to_string(),
|l| format!("entered as {l}"),
);
if let Some(known) = entries
.iter_mut()
.find(|e| e.name == device.order_number && e.version == device.firmware)
@@ -53,7 +44,6 @@ pub(crate) fn entries(devices: &[TargetDevice], repo_id: &str) -> Vec<SbomEntry>
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
use compliance_core::models::PlcDevice;
#[test]
fn each_device_type_and_firmware_is_one_entry() {
@@ -63,7 +53,6 @@ mod tests {
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");
assert_eq!(entries.len(), 2);
@@ -80,16 +69,4 @@ mod tests {
assert_eq!(first.evidence, ["entered as Zelle 1", "entered as Zelle 2"]);
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"]
);
}
}
-281
View File
@@ -118,72 +118,6 @@ pub struct EntitlementCheck {
pub expires_at: Option<String>,
#[serde(default)]
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 {
@@ -378,9 +312,6 @@ pub struct RegistryClient {
/// API-key verdicts, valid and invalid, keyed by the key's SHA-256 (never
/// the key itself), for [`API_KEY_TTL`].
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 {
@@ -424,7 +355,6 @@ impl RegistryClient {
cache: DashMap::new(),
projects: DashMap::new(),
api_keys: DashMap::new(),
logos: DashMap::new(),
}))
}
@@ -546,113 +476,6 @@ impl RegistryClient {
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).
pub fn invalidate(&self, tenant_id: &str) {
self.cache
@@ -1140,7 +963,6 @@ mod tests {
cache: DashMap::new(),
projects: DashMap::new(),
api_keys: DashMap::new(),
logos: DashMap::new(),
};
let started = Instant::now();
@@ -1197,7 +1019,6 @@ mod tests {
cache: DashMap::new(),
projects: DashMap::new(),
api_keys: DashMap::new(),
logos: DashMap::new(),
};
(client, calls, down)
}
@@ -1268,106 +1089,4 @@ mod tests {
assert!(client.api_keys.contains_key(&key_digest("bp_good")));
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)
);
}
}
@@ -606,241 +606,3 @@ async fn a_targets_supplier_is_set_checked_and_removed() {
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}");
// It says which export it comes from, so the page saves and edits only
// the devices entered with the target, never this one.
assert_eq!(devices[0]["exported_in"], "linie1.tia-export.zip", "{body}");
server.cleanup().await;
}
/// A synthetic TIA hardware export (#1097) of station `station`, its CPU at
/// firmware `firmware`, with a GSD device beside it.
fn tia_aml(station: &str, firmware: &str) -> Vec<u8> {
format!(
r#"<?xml version="1.0" encoding="utf-8"?>
<CAEXFile SchemaVersion="3.0" FileName="x.aml" xmlns="http://www.dke.de/CAEX">
<SourceDocumentInformation OriginName="TIA Portal" OriginVersion="V20" OriginID="x" LastWritingDateTime="2026-12-01T10:00:00"/>
<InstanceHierarchy Name="Linie 1"><InternalElement Name="Linie 1" ID="p">
<InternalElement Name="{station}" ID="d1">
<Attribute Name="TypeIdentifier"><Value>System:Device.S71500</Value></Attribute>
<InternalElement Name="PLC_1" ID="c1">
<Attribute Name="TypeIdentifier"><Value>OrderNumber:6ES7 511-1AK02-0AB0/V{firmware}</Value></Attribute>
<Attribute Name="FirmwareVersion"><Value>V{firmware}</Value></Attribute>
</InternalElement>
</InternalElement>
<InternalElement Name="Drittgeraet" ID="x1">
<Attribute Name="TypeIdentifier"><Value>GSD:VENDOR.XML/DAP1</Value></Attribute>
</InternalElement>
</InternalElement></InstanceHierarchy>
</CAEXFile>"#
)
.into_bytes()
}
/// Upload `bytes` named `name` to target `id` as a PLC project in the
/// format the dashboard sends by default.
async fn upload_plc_file(
server: &TestServer,
id: &str,
name: &str,
bytes: Vec<u8>,
) -> reqwest::Response {
let form = reqwest::multipart::Form::new()
.text("kind", "plc_project")
.text("plc_format", "plcopen_xml")
.part(
"file",
reqwest::multipart::Part::bytes(bytes).file_name(name.to_string()),
);
server
.client
.post(format!(
"{}/api/v1/targets/{id}/artifacts/upload",
server.base_url
))
.multipart(form)
.send()
.await
.unwrap()
}
#[tokio::test]
async fn a_tia_hardware_export_is_told_by_its_name_and_brings_its_devices() {
let server = TestServer::start().await;
let resp = server
.post(
"/api/v1/targets",
&json!({ "name": "linie-1-aml", "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();
// Named .aml but not one: refused with its code, not kept.
let resp = upload_plc_file(&server, &id, "station1.aml", b"<project/>".to_vec()).await;
assert_eq!(resp.status(), 422);
let body: serde_json::Value = resp.json().await.unwrap();
assert_eq!(body["code"], "not_aml", "{body}");
assert!(stored_uploads(&id).is_empty());
// Sent as PLCopen XML, read as the hardware export its name says.
let resp = upload_plc_file(&server, &id, "station1.aml", tia_aml("Station_1", "3.1")).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_aml", "{body}");
assert_eq!(
artifact["plc"]["devices"],
json!([{"order_number": "6ES7511-1AK02-0AB0", "firmware": "3.1", "label": "Station_1 / PLC_1"}])
);
// Another station of the machine stays beside it; the same file again
// replaces it.
let resp = upload_plc_file(&server, &id, "station2.aml", tia_aml("Station_2", "3.0")).await;
assert_eq!(resp.status(), 200);
let resp = upload_plc_file(&server, &id, "station1.aml", tia_aml("Station_1", "3.2")).await;
assert_eq!(resp.status(), 200);
let body: serde_json::Value = resp.json().await.unwrap();
let mut files: Vec<_> = body["data"]["artifacts"]
.as_array()
.unwrap()
.iter()
.map(|a| a["source_ref"].as_str().unwrap().to_string())
.collect();
files.sort();
assert_eq!(files, ["station1.aml", "station2.aml"], "{body}");
assert_eq!(stored_uploads(&id).len(), 2);
// Both stations' CPUs are on the Steuerungen page.
let resp = server.get(&format!("/api/v1/targets/{id}/devices")).await;
let body: serde_json::Value = resp.json().await.unwrap();
let mut seen: Vec<_> = body["data"]
.as_array()
.unwrap()
.iter()
.map(|d| {
format!(
"{} {} ({})",
d["label"].as_str().unwrap(),
d["firmware"].as_str().unwrap(),
d["exported_in"].as_str().unwrap_or("entered")
)
})
.collect();
seen.sort();
// Each says which export it comes from, so the page edits none of them.
assert_eq!(
seen,
[
"Station_1 / PLC_1 3.2 (station1.aml)",
"Station_2 / PLC_1 3.0 (station2.aml)"
],
"{body}"
);
server.cleanup().await;
}
-1
View File
@@ -285,7 +285,6 @@ async fn seed_nightly(
"target_type": t.target_type,
"description": t.description,
"artifacts": references,
"devices": t.devices,
}),
)
.await;
-197
View File
@@ -1,197 +0,0 @@
//! A scan of a PLC target fed from TIA Portal (#1090, #1097): the devices of
//! a hardware export and of a connector's export land in the SBOM as Siemens
//! devices, and the run names what it did not analyse.
#![allow(clippy::expect_used, clippy::unwrap_used)]
mod common;
use std::io::Write;
use common::TestServer;
use mongodb::bson::{doc, Document};
use serde_json::json;
/// A hardware export with one CPU and a GSD device.
const AML: &str = r#"<?xml version="1.0" encoding="utf-8"?>
<CAEXFile SchemaVersion="3.0" FileName="station1.aml" xmlns="http://www.dke.de/CAEX">
<SourceDocumentInformation OriginName="TIA Portal" OriginVersion="V20" OriginID="x" LastWritingDateTime="2026-12-01T10:00:00"/>
<InstanceHierarchy Name="Linie 1"><InternalElement Name="Linie 1" ID="p">
<InternalElement Name="Station_1" ID="d1">
<Attribute Name="TypeIdentifier"><Value>System:Device.S71500</Value></Attribute>
<InternalElement Name="PLC_1" ID="c1">
<Attribute Name="TypeIdentifier"><Value>OrderNumber:6ES7 511-1AK02-0AB0/V2.9</Value></Attribute>
</InternalElement>
</InternalElement>
<InternalElement Name="Drittgeraet" ID="x1">
<Attribute Name="TypeIdentifier"><Value>GSD:VENDOR.XML/DAP1</Value></Attribute>
</InternalElement>
</InternalElement></InstanceHierarchy>
</CAEXFile>"#;
/// A connector's export with an HMI, one readable and one protected block.
fn bundle() -> Vec<u8> {
let manifest = json!({
"bundle_version": 1,
"tia_version": "V20",
"project": {"name": "Linie 1"},
"devices": [{"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}
]
});
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()
}
async fn upload(server: &TestServer, id: &str, name: &str, format: &str, bytes: Vec<u8>) {
let form = reqwest::multipart::Form::new()
.text("kind", "plc_project")
.text("plc_format", format.to_string())
.part(
"file",
reqwest::multipart::Part::bytes(bytes).file_name(name.to_string()),
);
let resp = server
.client
.post(format!(
"{}/api/v1/targets/{id}/artifacts/upload",
server.base_url
))
.multipart(form)
.send()
.await
.unwrap();
assert_eq!(resp.status(), 200, "{name}: {}", resp.text().await.unwrap());
}
/// Start a scan of `id` and wait for its run to end.
async fn scan(server: &TestServer, runs: &mongodb::Collection<Document>, id: &str) -> Document {
let resp = server
.post(&format!("/api/v1/targets/{id}/scan"), &json!({}))
.await;
assert!(resp.status().is_success(), "{}", resp.status());
for _ in 0..240 {
if let Some(run) = runs
.find_one(doc! { "repo_id": id, "status": { "$in": ["completed", "failed"] } })
.await
.unwrap()
{
return run;
}
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
}
panic!("the scan of {id} did not finish");
}
#[tokio::test]
async fn tia_devices_reach_the_sbom_and_the_run_says_what_it_left_out() {
let server = TestServer::start().await;
let created: serde_json::Value = server
.post(
"/api/v1/targets",
&json!({ "name": "linie-1-tia", "target_type": "plc_sps", "artifacts": [] }),
)
.await
.json()
.await
.unwrap();
let id = created["data"]["_id"]["$oid"].as_str().unwrap().to_string();
upload(
&server,
&id,
"station1.aml",
"plcopen_xml",
AML.as_bytes().to_vec(),
)
.await;
upload(
&server,
&id,
"linie1.tia-export.zip",
"tia_export",
bundle(),
)
.await;
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db = mongodb::Client::with_uri_str(&uri)
.await
.unwrap()
.database(&server.tenant_db_name());
let run = scan(&server, &db.collection("scan_runs"), &id).await;
assert_eq!(run.get_str("status").unwrap(), "completed", "{run:?}");
// What the run did not analyse, each named.
let skipped: Vec<(String, String)> = run
.get_array("skipped_stages")
.map(|a| {
a.iter()
.filter_map(|s| s.as_document())
.map(|s| {
(
s.get_str("stage").unwrap_or("").to_string(),
s.get_str("subject").unwrap_or("").to_string(),
)
})
.collect()
})
.unwrap_or_default();
let subject = |stage: &str| {
skipped
.iter()
.find(|(s, _)| s == stage)
.map(|(_, subject)| subject.clone())
};
assert_eq!(
subject("plc_devices_unmatched").as_deref(),
Some("Drittgeraet"),
"{skipped:?}"
);
assert_eq!(
subject("plc_tia_blocks").as_deref(),
Some("1 (LAD)"),
"{skipped:?}"
);
assert_eq!(
subject("plc_protected_blocks").as_deref(),
Some("PLC_1/FB_42"),
"{skipped:?}"
);
// Both exports' devices are in the SBOM as Siemens devices.
let sbom: serde_json::Value = server
.get(&format!("/api/v1/sbom?repo_id={id}"))
.await
.json()
.await
.unwrap();
let mut devices: Vec<String> = sbom["data"]
.as_array()
.unwrap()
.iter()
.filter(|e| e["package_manager"] == "siemens-device")
.map(|e| {
format!(
"{}@{}",
e["name"].as_str().unwrap(),
e["version"].as_str().unwrap()
)
})
.collect();
devices.sort();
assert_eq!(
devices,
["6AV2124-0GC01-0AX0@17.0.0.0", "6ES7511-1AK02-0AB0@2.9"],
"{sbom}"
);
server.cleanup().await;
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-core"
version = "0.4.20"
version = "0.4.18"
edition = "2021"
[lints]
-5
View File
@@ -114,10 +114,6 @@ pub struct DeviceCheck {
pub product: Option<DeviceName>,
/// The advisories naming it: affecting it first, then by severity.
pub advisories: Vec<DeviceAdvisory>,
/// The TIA export that declares it (its file name, #1090/#1097); none for
/// a device entered with the target. Only an entered one is edited.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exported_in: Option<String>,
}
impl DeviceCheck {
@@ -151,7 +147,6 @@ impl DeviceCheck {
device,
product,
advisories: rows,
exported_in: None,
}
}
+1 -7
View File
@@ -27,7 +27,6 @@ pub mod repository;
pub mod sbom;
pub mod scan;
pub(crate) mod serde_helpers;
pub mod tia_export;
pub mod vex;
pub mod webhook_delivery;
pub mod werkbank;
@@ -73,8 +72,7 @@ pub use onboarding::{
default_compliance_profile, Artifact, ArtifactAuth, ArtifactKind, Classification,
ComplianceFramework, ComplianceProfile, DetectedFact, ExternalRef, ExternalSystem,
GitArtifactConfig, IssueTrackerConfig, LastScan, OnboardedTarget, PlcArtifactConfig, PlcFormat,
SupplierComponent, TargetDevice, TargetScanConfig, TargetType, TargetTypeCandidate,
WebArtifactConfig,
SupplierComponent, TargetScanConfig, TargetType, TargetTypeCandidate, WebArtifactConfig,
};
pub use oscal::OscalDocument;
pub use oscal_assessment::{assess, AssessmentResultsDoc, ControlLinker};
@@ -95,10 +93,6 @@ pub use scan::{
RunErrorCode, RunNote, ScanPhase, ScanRun, ScanRunStatus, ScanStep, ScanType, SkipCode,
SkippedStage,
};
pub use tia_export::{
exported_devices, AccessLevel, CpuSecurity, ExportedDevices, Setting, TiaBlock, TiaBlockKind,
TiaBundleError, TiaConnector, TiaDevice, TiaDeviceRole, TiaManifest, TiaProject,
};
pub use vex::{SupplierVex, VexAssessment, VexError, VexJustification, VexStatus};
pub use webhook_delivery::{DeliveryResult, WebhookDelivery, DELIVERIES_SHOWN};
pub use werkbank::{
+1 -99
View File
@@ -218,14 +218,6 @@ pub enum PlcFormat {
/// A CODESYS project archive (`.projectarchive` — a zip bundling the project
/// plus its referenced libraries and runtime; the source of the control-app SBOM).
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,
/// A Siemens TIA Portal hardware export ("CAx-Daten exportieren"): an
/// AutomationML (`.aml`, CAEX XML) file of a station or project, whose
/// device items name their type and firmware (#1097).
TiaAml,
}
/// PLC-specific configuration for a [`ArtifactKind::PlcProject`] artifact.
@@ -233,30 +225,6 @@ pub enum PlcFormat {
pub struct PlcArtifactConfig {
/// The project source format.
pub format: PlcFormat,
/// The Siemens devices a [`PlcFormat::TiaExport`] or [`PlcFormat::TiaAml`]
/// 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
@@ -386,10 +354,7 @@ impl Artifact {
/// A PLC-project artifact in the given format.
pub fn plc_project(source_ref: impl Into<String>, format: PlcFormat) -> Self {
let mut a = Self::bare(ArtifactKind::PlcProject, source_ref);
a.plc = Some(PlcArtifactConfig {
format,
devices: Vec::new(),
});
a.plc = Some(PlcArtifactConfig { format });
a
}
@@ -816,40 +781,6 @@ impl OnboardedTarget {
}
}
/// 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.
pub fn first_of(&self, kind: ArtifactKind) -> Option<&Artifact> {
self.artifacts.iter().find(|a| a.kind == kind)
@@ -1053,33 +984,4 @@ mod tests {
assert!(r.project_id.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()),
},
]
);
}
}
+1 -15
View File
@@ -324,17 +324,6 @@ pub enum SkipCode {
/// 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).
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 {
@@ -371,10 +360,7 @@ impl SkipCode {
| Self::TooLargeToScan
| Self::ReleaseUnknown
| Self::PrueftagLimitReached
| Self::PrueftagCapReached
| Self::PlcBlocksNotAnalysed
| Self::ProtectedBlocks
| Self::DevicesUnmatched => false,
| Self::PrueftagCapReached => false,
}
}
}
-523
View File
@@ -1,523 +0,0 @@
//! 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 {
exported_devices(&self.devices)
}
/// 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()
}
}
/// `devices` as advisories match them: those with a Siemens order number and
/// a firmware version, and the names of those without. Order number and
/// firmware come from a device's own fields, else from its type identifier;
/// a TIA export (#1090) and a hardware export (AML, #1097) both read so.
pub fn exported_devices(devices: &[TiaDevice]) -> ExportedDevices {
let mut out = ExportedDevices::default();
for device in 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
}
/// 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`, lower-case `x`) names no single article, so it is
/// none; an upper-case `X` is part of real order numbers (`6AV2124-0GC01-0AX0`). 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'));
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));
// An upper-case X is part of the article, not a wildcard.
assert_eq!(
split_type_identifier("OrderNumber:6AV2 124-0GC01-0AX0/V17.0.0.0"),
(Some("6AV2 124-0GC01-0AX0"), Some("V17.0.0.0"))
);
}
#[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)
);
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-dashboard"
version = "0.4.20"
version = "0.4.18"
edition = "2021"
default-run = "compliance-dashboard"
-95
View File
@@ -369,100 +369,6 @@ code {
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 {
padding: 8px 8px 16px;
flex: 1;
@@ -9919,7 +9825,6 @@ div.offer-option { flex-direction: column; align-items: flex-start; justify-cont
.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-source { display: block; margin-top: 2px; }
.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); }
@@ -1,7 +1,6 @@
use dioxus::prelude::*;
use crate::app::Route;
use crate::components::branding::BrandingNotice;
use crate::components::help_chat::HelpChat;
use crate::components::no_access::{NoAccess, ReadOnlyBanner};
use crate::components::notification_bell::NotificationBell;
@@ -26,13 +25,8 @@ pub fn AppShell() -> Element {
// then takes it away; an unreachable agent reads as the full set.
let platform = use_server_future(fetch_platform_info)?;
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();
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
// send the browser to the login rather than letting every page fail.
use_future(move || async move {
@@ -74,19 +68,8 @@ pub fn AppShell() -> Element {
Some(Ok(info)) if info.authenticated => {
use_context_provider(|| Signal::new(info.clone()));
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! {
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" }
}
div { class: "app-shell",
Sidebar {}
main { class: "main-content",
if let Some(tenant) = info.support_tenant.clone() {
@@ -95,7 +78,6 @@ pub fn AppShell() -> Element {
if read_only {
ReadOnlyBanner {}
}
BrandingNotice {}
Outlet::<Route> {}
}
NotificationBell {}
@@ -1,95 +0,0 @@
//! 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,7 +2,6 @@ pub mod app_shell;
pub mod artifact_upload;
pub mod attack_chain;
pub mod billing_swap;
pub mod branding;
pub mod code_inspector;
pub mod code_snippet;
pub mod component_overview;
+2 -17
View File
@@ -4,7 +4,6 @@ use dioxus_free_icons::icons::bs_icons::*;
use dioxus_free_icons::Icon;
use crate::app::Route;
use crate::components::branding::{use_branding, CustomerMark};
use crate::components::lang_toggle::LangToggle;
use crate::components::no_access::use_can_write;
use crate::components::theme_toggle::ThemeToggle;
@@ -40,7 +39,6 @@ pub fn Sidebar() -> Element {
let mut collapsed = use_signal(|| false);
let source_only = use_source_only();
let lang = use_lang()();
let branding = use_branding();
let can_write = use_can_write();
// Open supplier offers, counted on "Prüfobjekte" (#1028).
@@ -154,13 +152,7 @@ pub fn Sidebar() -> Element {
Icon { icon: BsList, width: 20, height: 20 }
}
}
div { class: "mobile-bar-brand",
if branding.branded() {
CustomerMark { branding: branding.clone(), with_name: true }
} else {
Wordmark { with_name: true }
}
}
div { class: "mobile-bar-brand", Wordmark { with_name: true } }
}
if mobile_open() {
div { class: "mobile-backdrop", onclick: move |_| mobile_open.set(false) }
@@ -169,11 +161,7 @@ pub fn Sidebar() -> Element {
// The breakpilot brand, as the portal shows it; Prüfwerk is the
// product within it.
div { class: "sidebar-header",
if branding.branded() {
CustomerMark { branding: branding.clone(), with_name: !collapsed() }
} else {
Wordmark { with_name: !collapsed() }
}
Wordmark { with_name: !collapsed() }
}
if !portal_url.is_empty() {
a {
@@ -308,9 +296,6 @@ pub fn Sidebar() -> Element {
}
}
}
if !collapsed() && branding.branded() {
div { class: "brand-credit", {crate::i18n::texts::branding::CREDIT.get(lang)} }
}
if !collapsed() {
div { class: "sidebar-legal",
a { href: PRIVACY_URL, target: "_blank", rel: "noopener", {nav::PRIVACY.get(lang)} }
+7 -136
View File
@@ -819,24 +819,6 @@ pub mod scans {
(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."
),
(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!(
"{subject} wurde nicht fertig; was es prüft, gilt als nicht bewertet."
),
@@ -1971,44 +1953,6 @@ pub mod onboarding {
}
/// Why a supplier SBOM is refused, by the agent's code.
/// Why a TIA upload was refused, by the agent's code: a hardware export
/// (`.aml`, #1097) or a TIA connector's export (#1090).
pub fn tia_refusal(code: &str, lang: Lang) -> &'static str {
let text = match code {
"not_aml" => Text {
de: "keine AutomationML-Datei aus dem TIA Portal. Bitte im TIA Portal die \
Station markieren und „CAx-Daten exportieren“ wählen.",
en: "not an AutomationML file from TIA Portal. Please select the station in \
TIA Portal and choose \"Export CAx data\".",
},
"no_devices" => Text {
de: "der Hardware-Export nennt kein Gerät. Bitte die Station mit ihren \
Geräten exportieren, nicht nur die Projektstruktur.",
en: "the hardware export names no device. Please export the station with \
its devices, not only the project structure.",
},
"too_large" => Text {
de: "die Datei ist zu groß (Hardware-Export höchstens 64 MiB).",
en: "the file is too large (a hardware export at most 64 MiB).",
},
"not_zip" | "no_manifest" | "manifest_invalid" => Text {
de: "kein Export des Breakpilot TIA Connectors.",
en: "not an export of the Breakpilot TIA Connector.",
},
"bundle_version" => Text {
de: "der Export stammt von einer neueren Version des Connectors; bitte \
Breakpilot aktualisieren lassen.",
en: "the export comes from a newer connector version; please have Breakpilot \
updated.",
},
_ => Text {
de: "die Datei lässt sich nicht lesen.",
en: "the file cannot be read.",
},
};
text.get(lang)
}
pub fn sbom_refusal(code: &str, lang: Lang) -> &'static str {
let text = match code {
"unknown_format" => Text {
@@ -3225,26 +3169,6 @@ pub mod sbom {
requirements.txt; for JavaScript, npm install writes package-lock.json; for Rust, \
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.
pub const EMPTY_FINDINGS: Text = Text {
de: "Was in diesem Prüfobjekt fehlt und wie Sie es ergänzen:",
@@ -5862,22 +5786,20 @@ pub mod metering {
/// 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.",
de: "Ihr Tarif enthält keine weiteren Prüfobjekte. Archivieren Sie ein Prüfobjekt, \
um ein neues anzulegen, oder wechseln Sie den Tarif.",
en: "Your plan includes no further targets. Archive a target to add a new one, \
or change your plan.",
};
/// The plan's refusal to make a demo target the tenant's own
/// (`target_limit`): other sources would make it count, and its places
/// are all taken.
pub const DEMO_LIMIT: Text = Text {
de: "Mit eigenen Dateien oder Quellen zählt ein Demo-Prüfobjekt wie Ihre anderen, \
und Ihr Tarif enthält keine weiteren Prüfobjekte. Löschen Sie ein anderes \
Prüfobjekt (seine Ergebnisse werden mit gelöscht) oder wechseln Sie den Tarif.",
und Ihr Tarif enthält keine weiteren Prüfobjekte. Archivieren Sie ein \
Prüfobjekt oder wechseln Sie den Tarif.",
en: "With your own files or sources a demo target counts like your other targets, \
and your plan includes no further targets. Delete another target (its results \
are deleted with it) or change your plan.",
and your plan includes no further targets. Archive a target or change your plan.",
};
/// A failed creation of a target in words: the plan's refusal as
/// [`TARGET_LIMIT`], anything else as it came.
@@ -9095,15 +9017,6 @@ pub mod devices {
de: "Firmware",
en: "Firmware",
};
/// Where an exported device comes from, instead of its edit buttons: it
/// changes with the next export, not here.
pub fn exported_from(file: &str, lang: Lang) -> String {
match lang {
Lang::De => format!("Aus dem TIA-Export {file}; ändert sich mit dem nächsten Export."),
Lang::En => format!("From the TIA export {file}; changes with the next export."),
}
}
pub const CHANGE_FIRMWARE: Text = Text {
de: "Firmware ändern",
en: "Change firmware",
@@ -9270,45 +9183,3 @@ pub mod devices {
}
}
}
/// 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}"),
}
}
}
@@ -1,195 +0,0 @@
//! 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(), "");
}
}
@@ -1,7 +1,6 @@
// Server function modules (compiled for both web and server;
// the #[server] macro generates client stubs for the web target)
pub mod auth_check;
pub mod branding;
pub mod chat;
pub mod cve_history;
pub mod cve_matrix;
@@ -55,7 +55,7 @@ pub fn agent_time(value: &serde_json::Value) -> Option<chrono::DateTime<chrono::
chrono::DateTime::from_timestamp_millis(millis)
}
/// An upload error in words: a refused supplier SBOM or TIA export by its code, a 7z or
/// An upload error in words: a refused supplier SBOM by its code, a 7z or
/// rar archive as such, anything else as the agent said it.
pub fn upload_problem(error: String, lang: Lang) -> String {
use crate::i18n::texts::{common, onboarding};
@@ -65,12 +65,6 @@ pub fn upload_problem(error: String, lang: Lang) -> String {
onboarding::REFUSED.get(lang),
onboarding::sbom_refusal(code, lang)
)
} else if let Some(code) = tia_refusal_code(&error) {
format!(
"{}: {}",
onboarding::REFUSED.get(lang),
onboarding::tia_refusal(code, lang)
)
} else if error.contains(UNSUPPORTED_ARCHIVE) {
common::UNSUPPORTED_ARCHIVE.get(lang).to_string()
} else {
@@ -166,25 +160,10 @@ pub enum SbomCheck {
/// by the agent's code.
pub const SBOM_REFUSED: &str = "supplier_sbom_refused:";
/// The marker an upload error carries for a refused TIA export or TIA
/// hardware export (#1090, #1097), followed by the agent's code.
pub const TIA_REFUSED: &str = "tia_refused:";
/// The agent's code of a refused supplier SBOM upload, from its error: the
/// lowercase word after [`SBOM_REFUSED`], whatever the error wraps it in.
pub fn sbom_refusal_code(error: &str) -> Option<&str> {
code_after(error, SBOM_REFUSED)
}
/// The agent's code of a refused TIA upload, as [`sbom_refusal_code`] for
/// [`TIA_REFUSED`].
pub fn tia_refusal_code(error: &str) -> Option<&str> {
code_after(error, TIA_REFUSED)
}
/// The lowercase word after `marker` in `error`.
fn code_after<'a>(error: &'a str, marker: &str) -> Option<&'a str> {
let rest = &error[error.find(marker)? + marker.len()..];
let rest = &error[error.find(SBOM_REFUSED)? + SBOM_REFUSED.len()..];
let end = rest
.find(|c: char| !(c.is_ascii_lowercase() || c == '_'))
.unwrap_or(rest.len());
@@ -692,10 +671,6 @@ pub async fn upload_target_artifact(
) -> Result<TargetResponse, ServerFnError> {
let filename = file.file_name().to_string();
let sbom = kind == "supplier_sbom";
// A TIA export or hardware export, refused with its own codes.
let tia = kind == "plc_project"
&& (plc_format.as_deref() == Some("tia_export")
|| filename.to_ascii_lowercase().ends_with(".aml"));
let part =
reqwest::multipart::Part::stream(reqwest::Body::wrap_stream(file)).file_name(filename);
let mut form = reqwest::multipart::Form::new()
@@ -717,12 +692,10 @@ pub async fn upload_target_artifact(
return Err(ServerFnError::new(match resp.status().as_u16() {
// A supplier SBOM has its own, smaller limit.
413 if sbom => format!("{SBOM_REFUSED}too_large"),
413 if tia => format!("{TIA_REFUSED}too_large"),
413 => "file is larger than the 512 MiB upload limit".to_string(),
415 => UNSUPPORTED_ARCHIVE.to_string(),
// A demo target the plan has no room for as the tenant's own.
409 => refusal_code(resp).await,
422 if tia => format!("{TIA_REFUSED}{}", refusal_code(resp).await),
422 => format!("{SBOM_REFUSED}{}", refusal_code(resp).await),
code => format!("upload rejected by the agent ({code})"),
}));
@@ -990,11 +963,6 @@ mod tests {
Some("unknown_format")
);
assert_eq!(sbom_refusal_code("supplier_sbom_refused:"), None);
assert_eq!(
super::tia_refusal_code("error running server function: tia_refused:not_aml"),
Some("not_aml")
);
assert_eq!(super::tia_refusal_code("supplier_sbom_refused:empty"), None);
assert_eq!(
sbom_refusal_code("upload rejected by the agent (500)"),
None
+2 -12
View File
@@ -104,14 +104,7 @@ pub fn TargetDevicesPage(id: String) -> Element {
}
None => return rsx! { div { class: "loading", {tx::LOADING.get(lang)} } },
};
// The devices entered with the target: the only ones saved. Exported ones
// (#1090, #1097) are listed after them and change with their export, so
// a selected entered device has the same index in both lists.
let devices: Vec<PlcDevice> = listed
.iter()
.filter(|c| c.exported_in.is_none())
.map(|c| c.device.clone())
.collect();
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)
@@ -369,11 +362,8 @@ fn DeviceDetail(
div {
h2 { "{name}" }
span { class: "dev-detail-label", "{label}" }
if let Some(file) = &check.exported_in {
span { class: "dev-detail-label dev-detail-source", {tx::exported_from(file, lang)} }
}
}
if can_write && check.exported_in.is_none() {
if can_write {
div { class: "dev-detail-actions",
if !editing() {
button {
+2 -2
View File
@@ -998,8 +998,8 @@ mod tests {
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."
"Your plan includes no further targets. Archive a target to add a new one, \
or change your plan."
);
assert_eq!(metering::target_refusal("x (500)", Lang::De), "x (500)");
}
+5 -43
View File
@@ -350,10 +350,7 @@ pub fn SbomPage(target: String, #[props(default)] ecosystem: String) -> Element
// ── SBOM table ──
match &*sbom.read() {
Some(Some(resp)) if resp.data.is_empty() && unfiltered() => rsx! {
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()),
}
SbomEmpty { target_id: repo_filter() }
},
Some(Some(resp)) => {
let total_pages = resp.total.unwrap_or(0).div_ceil(50).max(1);
@@ -1042,19 +1039,6 @@ fn kev_title(kev: &KevData, lang: Lang) -> String {
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
/// (`EPSS 94.4 % · P99`).
fn epss_label(epss: &EpssData) -> String {
@@ -1068,10 +1052,9 @@ fn epss_label(epss: &EpssData) -> String {
/// 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
/// an example where there are none (all targets, or code such as C that has
/// no standard manifest). A PLC target (`plc`) gets its own reason and
/// example: its components come from a CODESYS archive or its controllers.
/// no standard manifest).
#[component]
fn SbomEmpty(target_id: ReadSignal<String>, plc: bool) -> Element {
fn SbomEmpty(target_id: ReadSignal<String>) -> Element {
let lang = use_lang()();
let findings = use_resource(move || async move {
let repo_id = target_id();
@@ -1093,9 +1076,9 @@ fn SbomEmpty(target_id: ReadSignal<String>, plc: bool) -> Element {
rsx! {
section { class: "card sbom-empty",
h3 { class: "sbom-quality-head", {tx::EMPTY_TITLE.get(lang)} }
p { if plc { {tx::EMPTY_WHY_PLC.get(lang)} } else { {tx::EMPTY_WHY.get(lang)} } }
p { {tx::EMPTY_WHY.get(lang)} }
if findings.is_empty() {
p { if plc { {tx::EMPTY_EXAMPLE_PLC.get(lang)} } else { {tx::EMPTY_EXAMPLE.get(lang)} } }
p { {tx::EMPTY_EXAMPLE.get(lang)} }
} else {
p { {tx::EMPTY_FINDINGS.get(lang)} }
ul { class: "sbom-empty-findings",
@@ -1175,24 +1158,3 @@ fn grade_class(grade: &str) -> &'static str {
_ => "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");
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-dast"
version = "0.4.20"
version = "0.4.18"
edition = "2021"
[lints]
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-graph"
version = "0.4.20"
version = "0.4.18"
edition = "2021"
[lints]
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-mcp"
version = "0.4.20"
version = "0.4.18"
edition = "2021"
[dependencies]
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-smoke"
version = "0.4.20"
version = "0.4.18"
edition = "2021"
description = "Tiny Axum service exercising compliance-core M7.1 tenant gating. Run smoke.sh against it before merging anything that touches the auth/tenant path."
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "control-map"
version = "0.4.20"
version = "0.4.18"
edition = "2021"
[lints]
-1
View File
@@ -19,7 +19,6 @@ 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: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: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`) |
Alles andere ist mit einem Schlüssel nicht erreichbar, auch mit allen Scopes:
+1 -2
View File
@@ -13,8 +13,7 @@ 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
targets page) removes its records and its files. Erasing a tenant
(`DELETE /api/v1/platform/tenants/{id}/data` with `{"confirm": "<tenant id>"}`,
the same id as in the path) drops its database
(`DELETE /api/v1/platform/tenants/{id}/data`, confirmed) drops its database
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
directories are ever removed.
-113
View File
@@ -244,119 +244,6 @@ The API takes `devices` on `POST /api/v1/targets` and `PATCH
naming it, and `GET /api/v1/devices/lookup?order_number=` what the advisories
know of an order number.
## Siemens TIA Portal hardware export (AML)
Without installing anything, a TIA Portal project's hardware reaches Prüfwerk as
TIA Portal's own hardware export:
1. In TIA Portal, select the station (or the project) in the project tree.
2. Right-click, **CAx-Daten exportieren** (*Export CAx data*). TIA Portal writes
an AutomationML file, `*.aml`.
3. On the PLC/SPS target, upload the file as a **PLC project**. A file named
`*.aml` is read as a hardware export whatever format is picked.
Each device item with a Siemens order number and firmware (CPUs, I/O modules,
drives, HMIs, switches) joins the target's controllers, named
`station / device`, and is matched against Siemens' advisories. Devices
without either (GSD devices of other vendors) are listed on the run as not
matched. A file that is not a hardware export is refused with `422` and a
`code` (`not_aml`, `no_devices`; `413 too_large` above 64 MiB). Exporting the
same station again under the same file name replaces it; stations exported
one by one stay side by side.
Exported devices show on the **Steuerungen** page with the export they come
from; they change with the next export, not there.
::: warning Checked against the format, not yet a real export
The reader follows AutomationML's "Automation Project Configuration"
recommendation (`TypeIdentifier`, `FirmwareVersion` on each device item).
Whether every TIA version writes both for every device is being checked
against real exports.
:::
## 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 (lower-case `x`, `…-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
Beyond the static analysis, Prüfwerk can **probe the running device** over
+1 -8
View File
@@ -6,7 +6,7 @@
"key": "plc-pump-station",
"name": "PLC pump station (ST + FBD, composite)",
"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. 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.",
"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.",
"artifacts": [
{
"kind": "plc_project",
@@ -30,13 +30,6 @@
"optional": true
}
],
"devices": [
{
"order_number": "6ES7511-1AK02-0AB0",
"firmware": "2.9.4",
"label": "Pump station CPU"
}
],
"expect": {
"min_findings": 16,
"sast_rule_ids": [
@@ -1,9 +1,7 @@
{
"scan_status": "completed",
"skipped_stages": [],
"sbom": [
"siemens-device:6ES7511-1AK02-0AB0@2.9.4"
],
"sbom": [],
"findings": [
"plc-control-logic:plc-array-unchecked-index pump_station.st:29",
"plc-control-logic:plc-default-password pump_fbd.xml:8",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "werkbank-exec"
version = "0.4.20"
version = "0.4.18"
edition = "2021"
description = "Shared dynamic-execution logic: soft-PLC provisioning + industrial-protocol probing, used by the compliance agent and the Werkbank runner."