Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9cf0e493ad | ||
|
|
b08e398b66 |
No files matched your search
@@ -17,7 +17,7 @@ use crate::pipeline::csaf_match::{AdvisoryIndex, Wanted};
|
|||||||
use compliance_core::csaf_ingest::Advisory;
|
use compliance_core::csaf_ingest::Advisory;
|
||||||
use compliance_core::device_check::{DeviceCheck, DeviceLookup};
|
use compliance_core::device_check::{DeviceCheck, DeviceLookup};
|
||||||
use compliance_core::models::plc_device::normalised_order_number;
|
use compliance_core::models::plc_device::normalised_order_number;
|
||||||
use compliance_core::models::PlcDevice;
|
use compliance_core::models::{PlcDevice, TargetDevice};
|
||||||
use compliance_core::tenant_ctx::TenantCtx;
|
use compliance_core::tenant_ctx::TenantCtx;
|
||||||
|
|
||||||
/// The provider whose advisories name devices by order number.
|
/// The provider whose advisories name devices by order number.
|
||||||
@@ -44,10 +44,14 @@ async fn advisories_naming(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Each of `devices` against `advisories`.
|
/// Each of `devices` against `advisories`.
|
||||||
fn checks(devices: Vec<PlcDevice>, advisories: &[Advisory]) -> Vec<DeviceCheck> {
|
/// An exported device keeps the export it comes from (#1090, #1097).
|
||||||
|
fn checks(devices: Vec<TargetDevice>, advisories: &[Advisory]) -> Vec<DeviceCheck> {
|
||||||
devices
|
devices
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|device| DeviceCheck::new(device, advisories))
|
.map(|d| DeviceCheck {
|
||||||
|
exported_in: d.exported_in,
|
||||||
|
..DeviceCheck::new(d.device, advisories)
|
||||||
|
})
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,16 +85,13 @@ pub async fn list_devices(
|
|||||||
.await
|
.await
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||||
.ok_or(StatusCode::NOT_FOUND)?;
|
.ok_or(StatusCode::NOT_FOUND)?;
|
||||||
// Entered and exported alike (#1090): a TIA export's devices are listed
|
// Entered and exported alike (#1090, #1097): a TIA export's devices are
|
||||||
// under their names in the project.
|
// listed under their names in the project, saying which export they are
|
||||||
let target_devices: Vec<_> = target
|
// from, so a client edits only the entered ones.
|
||||||
.target_devices()
|
let target_devices = target.target_devices();
|
||||||
.into_iter()
|
|
||||||
.map(|d| d.device)
|
|
||||||
.collect();
|
|
||||||
let mut order_numbers: Vec<String> = target_devices
|
let mut order_numbers: Vec<String> = target_devices
|
||||||
.iter()
|
.iter()
|
||||||
.map(|d| d.order_number.clone())
|
.map(|d| d.device.order_number.clone())
|
||||||
.collect();
|
.collect();
|
||||||
order_numbers.sort();
|
order_numbers.sort();
|
||||||
order_numbers.dedup();
|
order_numbers.dedup();
|
||||||
@@ -204,9 +205,15 @@ mod tests {
|
|||||||
assert_eq!(advisories.len(), 1);
|
assert_eq!(advisories.len(), 1);
|
||||||
let devices = checks(
|
let devices = checks(
|
||||||
vec![
|
vec![
|
||||||
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.4", None).unwrap(),
|
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.4", None)
|
||||||
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.5", None).unwrap(),
|
.unwrap()
|
||||||
PlcDevice::new("6ES7516-3AN02-0AB0", "3.0", None).unwrap(),
|
.into(),
|
||||||
|
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.5", None)
|
||||||
|
.unwrap()
|
||||||
|
.into(),
|
||||||
|
PlcDevice::new("6ES7516-3AN02-0AB0", "3.0", None)
|
||||||
|
.unwrap()
|
||||||
|
.into(),
|
||||||
],
|
],
|
||||||
&advisories,
|
&advisories,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -969,8 +969,9 @@ pub struct UploadArtifactForm {
|
|||||||
#[schema(example = "source_archive")]
|
#[schema(example = "source_archive")]
|
||||||
kind: String,
|
kind: String,
|
||||||
/// The PLC project's format, for a PLC project: `plcopen_xml`,
|
/// The PLC project's format, for a PLC project: `plcopen_xml`,
|
||||||
/// `structured_text`, `project_archive` or `tia_export` (a TIA
|
/// `structured_text`, `project_archive`, `tia_export` (a TIA
|
||||||
/// connector's export, whose manifest is read on upload).
|
/// 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")]
|
#[schema(example = "tia_export")]
|
||||||
plc_format: Option<String>,
|
plc_format: Option<String>,
|
||||||
}
|
}
|
||||||
@@ -1001,7 +1002,7 @@ pub struct UploadArtifactForm {
|
|||||||
(status = 400, description = "Not an id, or a missing or unknown field"),
|
(status = 400, description = "Not an id, or a missing or unknown field"),
|
||||||
(status = 413, description = "The file is too large (a supplier SBOM: over 20 MiB)"),
|
(status = 413, description = "The file is too large (a supplier SBOM: over 20 MiB)"),
|
||||||
(status = 415, description = "An archive format that cannot be unpacked"),
|
(status = 415, description = "An archive format that cannot be unpacked"),
|
||||||
(status = 422, description = "A supplier SBOM or TIA export that cannot be read; `error` says why, `code` names it"),
|
(status = 422, description = "A supplier SBOM, TIA export or TIA hardware export (`.aml`) that cannot be read; `error` says why, `code` names it"),
|
||||||
(status = 401, description = "No valid bearer token"),
|
(status = 401, description = "No valid bearer token"),
|
||||||
)
|
)
|
||||||
)]
|
)]
|
||||||
@@ -1104,6 +1105,13 @@ pub(super) async fn attach_upload(
|
|||||||
upload: StoredUpload,
|
upload: StoredUpload,
|
||||||
) -> Result<AttachedUpload, UploadRefusal> {
|
) -> Result<AttachedUpload, UploadRefusal> {
|
||||||
let oid = target.id.ok_or(StatusCode::INTERNAL_SERVER_ERROR)?;
|
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
|
// Non-file kinds (git repo, live URL, container ref, text) use the JSON
|
||||||
// add-artifact endpoint, not upload.
|
// add-artifact endpoint, not upload.
|
||||||
let mut artifact = uploaded_artifact(kind, plc_format, &upload.name, &upload.path, upload.size)
|
let mut artifact = uploaded_artifact(kind, plc_format, &upload.name, &upload.path, upload.size)
|
||||||
@@ -1144,6 +1152,35 @@ pub(super) async fn attach_upload(
|
|||||||
if let Some(plc) = artifact.plc.as_mut() {
|
if let Some(plc) = artifact.plc.as_mut() {
|
||||||
plc.devices = manifest.devices().matched;
|
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 {
|
} else if kind != ArtifactKind::FirmwareImage {
|
||||||
match archive_check(upload.path.clone()).await? {
|
match archive_check(upload.path.clone()).await? {
|
||||||
// 7z and rar are never unpacked: say so now, not after a scan.
|
// 7z and rar are never unpacked: say so now, not after a scan.
|
||||||
@@ -1186,6 +1223,15 @@ pub(super) async fn attach_upload(
|
|||||||
Replaced::TiaExport,
|
Replaced::TiaExport,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
} else if is_tia_aml(&artifact) {
|
||||||
|
replace_earlier(
|
||||||
|
db,
|
||||||
|
oid,
|
||||||
|
&artifact_id,
|
||||||
|
&target.artifacts,
|
||||||
|
Replaced::TiaAml(&artifact.source_ref),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(AttachedUpload {
|
Ok(AttachedUpload {
|
||||||
@@ -1200,6 +1246,19 @@ fn is_tia_export(artifact: &compliance_core::models::Artifact) -> bool {
|
|||||||
&& artifact.plc.as_ref().map(|p| p.format) == Some(PlcFormat::TiaExport)
|
&& 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.
|
/// What a TIA export's manifest says, as the artifact's facts.
|
||||||
fn tia_facts(manifest: &compliance_core::models::TiaManifest) -> [DetectedFact; 4] {
|
fn tia_facts(manifest: &compliance_core::models::TiaManifest) -> [DetectedFact; 4] {
|
||||||
[
|
[
|
||||||
@@ -1212,19 +1271,25 @@ fn tia_facts(manifest: &compliance_core::models::TiaManifest) -> [DetectedFact;
|
|||||||
|
|
||||||
/// The kinds of upload a new one replaces.
|
/// The kinds of upload a new one replaces.
|
||||||
#[derive(Debug, Clone, Copy)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
enum Replaced {
|
enum Replaced<'a> {
|
||||||
/// A supplier's SBOM: a new version replaces the one before it (#1025).
|
/// A supplier's SBOM: a new version replaces the one before it (#1025).
|
||||||
SupplierSbom,
|
SupplierSbom,
|
||||||
/// A TIA export: a new export of the project replaces the last (#1090).
|
/// A TIA export: a new export of the project replaces the last (#1090).
|
||||||
TiaExport,
|
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 {
|
impl Replaced<'_> {
|
||||||
/// The artifacts of this kind, as a Mongo filter.
|
/// The artifacts of this kind, as a Mongo filter.
|
||||||
fn filter(self) -> mongodb::bson::Document {
|
fn filter(self) -> mongodb::bson::Document {
|
||||||
match self {
|
match self {
|
||||||
Self::SupplierSbom => doc! { "kind": "supplier_sbom" },
|
Self::SupplierSbom => doc! { "kind": "supplier_sbom" },
|
||||||
Self::TiaExport => doc! { "kind": "plc_project", "plc.format": "tia_export" },
|
Self::TiaExport => doc! { "kind": "plc_project", "plc.format": "tia_export" },
|
||||||
|
Self::TiaAml(name) => {
|
||||||
|
doc! { "kind": "plc_project", "plc.format": "tia_aml", "source_ref": name }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1233,6 +1298,7 @@ impl Replaced {
|
|||||||
match self {
|
match self {
|
||||||
Self::SupplierSbom => artifact.kind == ArtifactKind::SupplierSbom,
|
Self::SupplierSbom => artifact.kind == ArtifactKind::SupplierSbom,
|
||||||
Self::TiaExport => is_tia_export(artifact),
|
Self::TiaExport => is_tia_export(artifact),
|
||||||
|
Self::TiaAml(name) => is_tia_aml(artifact) && artifact.source_ref == name,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1248,7 +1314,7 @@ async fn replace_earlier(
|
|||||||
target: ObjectId,
|
target: ObjectId,
|
||||||
kept: &str,
|
kept: &str,
|
||||||
before: &[compliance_core::models::Artifact],
|
before: &[compliance_core::models::Artifact],
|
||||||
what: Replaced,
|
what: Replaced<'_>,
|
||||||
) {
|
) {
|
||||||
let mut earlier = what.filter();
|
let mut earlier = what.filter();
|
||||||
earlier.insert("id", doc! { "$ne": kept });
|
earlier.insert("id", doc! { "$ne": kept });
|
||||||
|
|||||||
@@ -2008,11 +2008,19 @@ impl PipelineOrchestrator {
|
|||||||
// first, as in a code scan (#820, #825).
|
// first, as in a code scan (#820, #825).
|
||||||
let mut left_out = LeftOut::default();
|
let mut left_out = LeftOut::default();
|
||||||
for a in &sources {
|
for a in &sources {
|
||||||
// A TIA export's block code is not read yet (#1093): the run says
|
// A TIA export's block code is not read yet (#1093), and a
|
||||||
// what it holds instead of finding nothing in it.
|
// hardware export holds none: the run says what they hold
|
||||||
if a.plc.as_ref().map(|p| p.format) == Some(PlcFormat::TiaExport) {
|
// instead of finding nothing in them.
|
||||||
self.note_tia_export(scan_run_id, a).await;
|
match a.plc.as_ref().map(|p| p.format) {
|
||||||
continue;
|
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 {
|
let Some(path) = ingest_set.get(&a.id).and_then(|ia| ia.working_path.clone()) else {
|
||||||
continue;
|
continue;
|
||||||
@@ -2249,6 +2257,58 @@ impl PipelineOrchestrator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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
|
/// Provision-and-test (#183): instantiate the target's control logic on an
|
||||||
/// ephemeral soft-PLC (OpenPLC), start it, probe the provisioned Modbus
|
/// ephemeral soft-PLC (OpenPLC), start it, probe the provisioned Modbus
|
||||||
/// endpoint, and tear the instance down. Used when a PLC/SPS target has the
|
/// endpoint, and tear the instance down. Used when a PLC/SPS target has the
|
||||||
|
|||||||
@@ -0,0 +1,280 @@
|
|||||||
|
//! 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"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@
|
|||||||
//! a `.projectarchive`) cannot be read; [`native_projects`] lists them so the
|
//! a `.projectarchive`) cannot be read; [`native_projects`] lists them so the
|
||||||
//! scan says so instead of finding nothing in silence (#165).
|
//! scan says so instead of finding nothing in silence (#165).
|
||||||
|
|
||||||
|
pub(crate) mod aml;
|
||||||
pub mod ast;
|
pub mod ast;
|
||||||
pub(crate) mod graph;
|
pub(crate) mod graph;
|
||||||
pub mod lexer;
|
pub mod lexer;
|
||||||
|
|||||||
@@ -713,3 +713,131 @@ async fn a_tia_export_brings_its_devices_and_replaces_the_last_one() {
|
|||||||
|
|
||||||
server.cleanup().await;
|
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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
//! 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;
|
||||||
|
}
|
||||||
@@ -114,6 +114,10 @@ pub struct DeviceCheck {
|
|||||||
pub product: Option<DeviceName>,
|
pub product: Option<DeviceName>,
|
||||||
/// The advisories naming it: affecting it first, then by severity.
|
/// The advisories naming it: affecting it first, then by severity.
|
||||||
pub advisories: Vec<DeviceAdvisory>,
|
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 {
|
impl DeviceCheck {
|
||||||
@@ -147,6 +151,7 @@ impl DeviceCheck {
|
|||||||
device,
|
device,
|
||||||
product,
|
product,
|
||||||
advisories: rows,
|
advisories: rows,
|
||||||
|
exported_in: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -96,8 +96,8 @@ pub use scan::{
|
|||||||
SkippedStage,
|
SkippedStage,
|
||||||
};
|
};
|
||||||
pub use tia_export::{
|
pub use tia_export::{
|
||||||
AccessLevel, CpuSecurity, ExportedDevices, Setting, TiaBlock, TiaBlockKind, TiaBundleError,
|
exported_devices, AccessLevel, CpuSecurity, ExportedDevices, Setting, TiaBlock, TiaBlockKind,
|
||||||
TiaConnector, TiaDevice, TiaDeviceRole, TiaManifest, TiaProject,
|
TiaBundleError, TiaConnector, TiaDevice, TiaDeviceRole, TiaManifest, TiaProject,
|
||||||
};
|
};
|
||||||
pub use vex::{SupplierVex, VexAssessment, VexError, VexJustification, VexStatus};
|
pub use vex::{SupplierVex, VexAssessment, VexError, VexJustification, VexStatus};
|
||||||
pub use webhook_delivery::{DeliveryResult, WebhookDelivery, DELIVERIES_SHOWN};
|
pub use webhook_delivery::{DeliveryResult, WebhookDelivery, DELIVERIES_SHOWN};
|
||||||
|
|||||||
@@ -222,6 +222,10 @@ pub enum PlcFormat {
|
|||||||
/// zip with a manifest of devices, security settings and blocks
|
/// zip with a manifest of devices, security settings and blocks
|
||||||
/// ([`super::TiaManifest`]) beside the block exports.
|
/// ([`super::TiaManifest`]) beside the block exports.
|
||||||
TiaExport,
|
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.
|
/// PLC-specific configuration for a [`ArtifactKind::PlcProject`] artifact.
|
||||||
@@ -229,8 +233,8 @@ pub enum PlcFormat {
|
|||||||
pub struct PlcArtifactConfig {
|
pub struct PlcArtifactConfig {
|
||||||
/// The project source format.
|
/// The project source format.
|
||||||
pub format: PlcFormat,
|
pub format: PlcFormat,
|
||||||
/// The Siemens devices a [`PlcFormat::TiaExport`] declares, read when it
|
/// The Siemens devices a [`PlcFormat::TiaExport`] or [`PlcFormat::TiaAml`]
|
||||||
/// was uploaded; matched against Siemens' advisories beside the devices
|
/// declares, read when it was uploaded; matched against Siemens' advisories beside the devices
|
||||||
/// entered with the target ([`OnboardedTarget::target_devices`]).
|
/// entered with the target ([`OnboardedTarget::target_devices`]).
|
||||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
pub devices: Vec<super::PlcDevice>,
|
pub devices: Vec<super::PlcDevice>,
|
||||||
|
|||||||
@@ -322,28 +322,7 @@ impl TiaManifest {
|
|||||||
/// cannot be. Order number and firmware come from the device's own
|
/// cannot be. Order number and firmware come from the device's own
|
||||||
/// fields, else from its type identifier.
|
/// fields, else from its type identifier.
|
||||||
pub fn devices(&self) -> ExportedDevices {
|
pub fn devices(&self) -> ExportedDevices {
|
||||||
let mut out = ExportedDevices::default();
|
exported_devices(&self.devices)
|
||||||
for device in &self.devices {
|
|
||||||
let (type_order, type_firmware) = device
|
|
||||||
.type_identifier
|
|
||||||
.as_deref()
|
|
||||||
.map(split_type_identifier)
|
|
||||||
.unwrap_or_default();
|
|
||||||
let order = device.order_number.as_deref().or(type_order);
|
|
||||||
let firmware = device.firmware.as_deref().or(type_firmware);
|
|
||||||
let label: String = device.name.trim().chars().take(LABEL_MAX_CHARS).collect();
|
|
||||||
let matched = match (order, firmware) {
|
|
||||||
(Some(order), Some(firmware)) => {
|
|
||||||
PlcDevice::new(order, firmware, Some(label.as_str())).ok()
|
|
||||||
}
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
match matched {
|
|
||||||
Some(d) => out.matched.push(d),
|
|
||||||
None => out.unmatched.push(label),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
out
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The names of the know-how-protected blocks, as `device/block` when
|
/// The names of the know-how-protected blocks, as `device/block` when
|
||||||
@@ -360,11 +339,41 @@ impl TiaManifest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `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
|
/// Order number and firmware of a TIA type identifier
|
||||||
/// (`OrderNumber:6ES7 515-2UM01-0AB0/V2.9`). The firmware is the segment after
|
/// (`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
|
/// 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
|
/// catalog variant `//10002` none). A catalog order number with wildcards
|
||||||
/// (`6SL3040-1MA01-0Axx`) names no single article, so it is none. A GSD or
|
/// (`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.
|
/// system identifier (`GSD:…`, `System:…`) has neither.
|
||||||
fn split_type_identifier(identifier: &str) -> (Option<&str>, Option<&str>) {
|
fn split_type_identifier(identifier: &str) -> (Option<&str>, Option<&str>) {
|
||||||
let Some(rest) = identifier.trim().strip_prefix("OrderNumber:") else {
|
let Some(rest) = identifier.trim().strip_prefix("OrderNumber:") else {
|
||||||
@@ -374,7 +383,7 @@ fn split_type_identifier(identifier: &str) -> (Option<&str>, Option<&str>) {
|
|||||||
let order = segments
|
let order = segments
|
||||||
.next()
|
.next()
|
||||||
.map(str::trim)
|
.map(str::trim)
|
||||||
.filter(|o| !o.is_empty() && !o.contains(['x', 'X']));
|
.filter(|o| !o.is_empty() && !o.contains('x'));
|
||||||
let firmware = segments
|
let firmware = segments
|
||||||
.next()
|
.next()
|
||||||
.map(str::trim)
|
.map(str::trim)
|
||||||
@@ -464,6 +473,11 @@ mod tests {
|
|||||||
(None, Some("V5.2"))
|
(None, Some("V5.2"))
|
||||||
);
|
);
|
||||||
assert_eq!(split_type_identifier("System:Rack.S120"), (None, None));
|
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]
|
#[test]
|
||||||
|
|||||||
@@ -9919,6 +9919,7 @@ 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 { 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-head > div:first-child { display: flex; flex-direction: column; gap: 4px; }
|
||||||
.dev-detail-label { font-size: 14px; color: var(--text-tertiary); }
|
.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 { display: flex; gap: 8px; }
|
||||||
.dev-detail-actions .btn { min-height: 44px; }
|
.dev-detail-actions .btn { min-height: 44px; }
|
||||||
.btn-danger-ghost { color: var(--danger); border-color: var(--danger-bg); }
|
.btn-danger-ghost { color: var(--danger); border-color: var(--danger-bg); }
|
||||||
|
|||||||
@@ -1971,6 +1971,44 @@ pub mod onboarding {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Why a supplier SBOM is refused, by the agent's code.
|
/// 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 {
|
pub fn sbom_refusal(code: &str, lang: Lang) -> &'static str {
|
||||||
let text = match code {
|
let text = match code {
|
||||||
"unknown_format" => Text {
|
"unknown_format" => Text {
|
||||||
@@ -9057,6 +9095,15 @@ pub mod devices {
|
|||||||
de: "Firmware",
|
de: "Firmware",
|
||||||
en: "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 {
|
pub const CHANGE_FIRMWARE: Text = Text {
|
||||||
de: "Firmware ändern",
|
de: "Firmware ändern",
|
||||||
en: "Change firmware",
|
en: "Change firmware",
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ pub fn agent_time(value: &serde_json::Value) -> Option<chrono::DateTime<chrono::
|
|||||||
chrono::DateTime::from_timestamp_millis(millis)
|
chrono::DateTime::from_timestamp_millis(millis)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An upload error in words: a refused supplier SBOM by its code, a 7z or
|
/// An upload error in words: a refused supplier SBOM or TIA export by its code, a 7z or
|
||||||
/// rar archive as such, anything else as the agent said it.
|
/// rar archive as such, anything else as the agent said it.
|
||||||
pub fn upload_problem(error: String, lang: Lang) -> String {
|
pub fn upload_problem(error: String, lang: Lang) -> String {
|
||||||
use crate::i18n::texts::{common, onboarding};
|
use crate::i18n::texts::{common, onboarding};
|
||||||
@@ -65,6 +65,12 @@ pub fn upload_problem(error: String, lang: Lang) -> String {
|
|||||||
onboarding::REFUSED.get(lang),
|
onboarding::REFUSED.get(lang),
|
||||||
onboarding::sbom_refusal(code, 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) {
|
} else if error.contains(UNSUPPORTED_ARCHIVE) {
|
||||||
common::UNSUPPORTED_ARCHIVE.get(lang).to_string()
|
common::UNSUPPORTED_ARCHIVE.get(lang).to_string()
|
||||||
} else {
|
} else {
|
||||||
@@ -160,10 +166,25 @@ pub enum SbomCheck {
|
|||||||
/// by the agent's code.
|
/// by the agent's code.
|
||||||
pub const SBOM_REFUSED: &str = "supplier_sbom_refused:";
|
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
|
/// 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.
|
/// lowercase word after [`SBOM_REFUSED`], whatever the error wraps it in.
|
||||||
pub fn sbom_refusal_code(error: &str) -> Option<&str> {
|
pub fn sbom_refusal_code(error: &str) -> Option<&str> {
|
||||||
let rest = &error[error.find(SBOM_REFUSED)? + SBOM_REFUSED.len()..];
|
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 end = rest
|
let end = rest
|
||||||
.find(|c: char| !(c.is_ascii_lowercase() || c == '_'))
|
.find(|c: char| !(c.is_ascii_lowercase() || c == '_'))
|
||||||
.unwrap_or(rest.len());
|
.unwrap_or(rest.len());
|
||||||
@@ -671,6 +692,10 @@ pub async fn upload_target_artifact(
|
|||||||
) -> Result<TargetResponse, ServerFnError> {
|
) -> Result<TargetResponse, ServerFnError> {
|
||||||
let filename = file.file_name().to_string();
|
let filename = file.file_name().to_string();
|
||||||
let sbom = kind == "supplier_sbom";
|
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 =
|
let part =
|
||||||
reqwest::multipart::Part::stream(reqwest::Body::wrap_stream(file)).file_name(filename);
|
reqwest::multipart::Part::stream(reqwest::Body::wrap_stream(file)).file_name(filename);
|
||||||
let mut form = reqwest::multipart::Form::new()
|
let mut form = reqwest::multipart::Form::new()
|
||||||
@@ -692,10 +717,12 @@ pub async fn upload_target_artifact(
|
|||||||
return Err(ServerFnError::new(match resp.status().as_u16() {
|
return Err(ServerFnError::new(match resp.status().as_u16() {
|
||||||
// A supplier SBOM has its own, smaller limit.
|
// A supplier SBOM has its own, smaller limit.
|
||||||
413 if sbom => format!("{SBOM_REFUSED}too_large"),
|
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(),
|
413 => "file is larger than the 512 MiB upload limit".to_string(),
|
||||||
415 => UNSUPPORTED_ARCHIVE.to_string(),
|
415 => UNSUPPORTED_ARCHIVE.to_string(),
|
||||||
// A demo target the plan has no room for as the tenant's own.
|
// A demo target the plan has no room for as the tenant's own.
|
||||||
409 => refusal_code(resp).await,
|
409 => refusal_code(resp).await,
|
||||||
|
422 if tia => format!("{TIA_REFUSED}{}", refusal_code(resp).await),
|
||||||
422 => format!("{SBOM_REFUSED}{}", refusal_code(resp).await),
|
422 => format!("{SBOM_REFUSED}{}", refusal_code(resp).await),
|
||||||
code => format!("upload rejected by the agent ({code})"),
|
code => format!("upload rejected by the agent ({code})"),
|
||||||
}));
|
}));
|
||||||
@@ -963,6 +990,11 @@ mod tests {
|
|||||||
Some("unknown_format")
|
Some("unknown_format")
|
||||||
);
|
);
|
||||||
assert_eq!(sbom_refusal_code("supplier_sbom_refused:"), None);
|
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!(
|
assert_eq!(
|
||||||
sbom_refusal_code("upload rejected by the agent (500)"),
|
sbom_refusal_code("upload rejected by the agent (500)"),
|
||||||
None
|
None
|
||||||
|
|||||||
@@ -104,7 +104,14 @@ pub fn TargetDevicesPage(id: String) -> Element {
|
|||||||
}
|
}
|
||||||
None => return rsx! { div { class: "loading", {tx::LOADING.get(lang)} } },
|
None => return rsx! { div { class: "loading", {tx::LOADING.get(lang)} } },
|
||||||
};
|
};
|
||||||
let devices: Vec<PlcDevice> = listed.iter().map(|c| c.device.clone()).collect();
|
// 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();
|
||||||
// A first device is added from the empty rail's form.
|
// A first device is added from the empty rail's form.
|
||||||
let show_form = can_write && (adding() || listed.is_empty());
|
let show_form = can_write && (adding() || listed.is_empty());
|
||||||
let chosen = (!show_form)
|
let chosen = (!show_form)
|
||||||
@@ -362,8 +369,11 @@ fn DeviceDetail(
|
|||||||
div {
|
div {
|
||||||
h2 { "{name}" }
|
h2 { "{name}" }
|
||||||
span { class: "dev-detail-label", "{label}" }
|
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 {
|
if can_write && check.exported_in.is_none() {
|
||||||
div { class: "dev-detail-actions",
|
div { class: "dev-detail-actions",
|
||||||
if !editing() {
|
if !editing() {
|
||||||
button {
|
button {
|
||||||
|
|||||||
+31
-1
@@ -244,6 +244,36 @@ The API takes `devices` on `POST /api/v1/targets` and `PATCH
|
|||||||
naming it, and `GET /api/v1/devices/lookup?order_number=` what the advisories
|
naming it, and `GET /api/v1/devices/lookup?order_number=` what the advisories
|
||||||
know of an order number.
|
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)
|
## Siemens TIA Portal projects (TIA export)
|
||||||
|
|
||||||
A TIA Portal project reaches Prüfwerk as a **TIA export**: a zip that a TIA
|
A TIA Portal project reaches Prüfwerk as a **TIA export**: a zip that a TIA
|
||||||
@@ -320,7 +350,7 @@ passwords or keys.
|
|||||||
| `bundle_version` | `1` |
|
| `bundle_version` | `1` |
|
||||||
| `tia_version` | the TIA Portal version read with: `V20`, `V21` |
|
| `tia_version` | the TIA Portal version read with: `V20`, `V21` |
|
||||||
| `devices[].role` | `cpu`, `hmi`, `module`, anything else counts as other |
|
| `devices[].role` | `cpu`, `hmi`, `module`, anything else counts as other |
|
||||||
| `devices[].type_identifier` | TIA's type identifier; order number and firmware are taken from it unless given as `order_number` and `firmware`. A catalog order number with wildcards (`…-0Axx`) or a variant without a version (`//10002`) leaves the device not matched |
|
| `devices[].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 |
|
| `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` |
|
| `security.access_level` | `full_access_including_failsafe`, `full_access`, `read_access`, `hmi_access`, `no_access`, `none` |
|
||||||
| `blocks[].kind` | `ob`, `fb`, `fc`, `db`, `udt` |
|
| `blocks[].kind` | `ob`, `fb`, `fc`, `db`, `udt` |
|
||||||
|
|||||||
Reference in new issue
Block a user