CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 3m1s
CI / Deploy Dashboard (push) Successful in 7m6s
CI / Deploy Agent (push) Successful in 8m57s
719 lines
25 KiB
Rust
719 lines
25 KiB
Rust
use crate::common::TestServer;
|
|
use serde_json::json;
|
|
|
|
#[tokio::test]
|
|
async fn create_list_and_applicable_scans() {
|
|
let server = TestServer::start().await;
|
|
|
|
// Initially empty.
|
|
let resp = server.get("/api/v1/targets").await;
|
|
assert_eq!(resp.status(), 200);
|
|
let body: serde_json::Value = resp.json().await.unwrap();
|
|
assert_eq!(body["data"].as_array().unwrap().len(), 0);
|
|
|
|
// Create a web-app target with a git repo + a live URL.
|
|
let resp = server
|
|
.post(
|
|
"/api/v1/targets",
|
|
&json!({
|
|
"name": "acme-web",
|
|
"target_type": "web_app",
|
|
"artifacts": [
|
|
{ "kind": "git_repo", "source_ref": "https://git/acme.git", "branch": "main" },
|
|
{ "kind": "live_url", "source_ref": "https://acme.example.com" }
|
|
]
|
|
}),
|
|
)
|
|
.await;
|
|
assert_eq!(resp.status(), 200);
|
|
let body: serde_json::Value = resp.json().await.unwrap();
|
|
let id = body["data"]["_id"]["$oid"].as_str().unwrap().to_string();
|
|
assert!(!id.is_empty());
|
|
assert_eq!(body["data"]["artifacts"].as_array().unwrap().len(), 2);
|
|
|
|
// List returns it.
|
|
let resp = server.get("/api/v1/targets").await;
|
|
let body: serde_json::Value = resp.json().await.unwrap();
|
|
assert_eq!(body["data"].as_array().unwrap().len(), 1);
|
|
|
|
// Applicable scans: SAST present + DAST offered (live URL present), pentest supported.
|
|
let resp = server
|
|
.get(&format!("/api/v1/targets/{id}/applicable-scans"))
|
|
.await;
|
|
assert_eq!(resp.status(), 200);
|
|
let body: serde_json::Value = resp.json().await.unwrap();
|
|
let scans = body["data"]["scans"].as_array().unwrap();
|
|
let names: Vec<&str> = scans.iter().filter_map(|s| s["scan"].as_str()).collect();
|
|
assert!(names.contains(&"sast"));
|
|
assert!(names.contains(&"dast"));
|
|
assert_eq!(body["data"]["pentest_supported"], true);
|
|
|
|
server.cleanup().await;
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn detect_classifies_a_plc_target() {
|
|
let server = TestServer::start().await;
|
|
|
|
// A PLC project artifact is a strong kind-based signal.
|
|
let resp = server
|
|
.post(
|
|
"/api/v1/targets",
|
|
&json!({
|
|
"name": "line-controller",
|
|
"target_type": "backend_service", // deliberately wrong; detect should suggest PLC
|
|
"artifacts": [
|
|
{ "kind": "plc_project", "source_ref": "line.xml", "plc_format": "plcopen_xml" }
|
|
]
|
|
}),
|
|
)
|
|
.await;
|
|
let body: serde_json::Value = resp.json().await.unwrap();
|
|
let id = body["data"]["_id"]["$oid"].as_str().unwrap().to_string();
|
|
|
|
let resp = server
|
|
.post(&format!("/api/v1/targets/{id}/detect"), &json!({}))
|
|
.await;
|
|
assert_eq!(resp.status(), 200);
|
|
let body: serde_json::Value = resp.json().await.unwrap();
|
|
assert_eq!(body["data"]["classification"]["suggested"], "plc_sps");
|
|
|
|
server.cleanup().await;
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn add_artifact_and_delete_target() {
|
|
let server = TestServer::start().await;
|
|
|
|
let resp = server
|
|
.post(
|
|
"/api/v1/targets",
|
|
&json!({ "name": "svc", "target_type": "backend_service" }),
|
|
)
|
|
.await;
|
|
let body: serde_json::Value = resp.json().await.unwrap();
|
|
let id = body["data"]["_id"]["$oid"].as_str().unwrap().to_string();
|
|
|
|
// Attach a git repo.
|
|
let resp = server
|
|
.post(
|
|
&format!("/api/v1/targets/{id}/artifacts"),
|
|
&json!({ "kind": "git_repo", "source_ref": "https://git/svc.git" }),
|
|
)
|
|
.await;
|
|
assert_eq!(resp.status(), 200);
|
|
let body: serde_json::Value = resp.json().await.unwrap();
|
|
assert_eq!(body["data"]["artifacts"].as_array().unwrap().len(), 1);
|
|
|
|
// Delete it.
|
|
let resp = server.delete(&format!("/api/v1/targets/{id}")).await;
|
|
assert_eq!(resp.status(), 200);
|
|
let resp = server.get(&format!("/api/v1/targets/{id}")).await;
|
|
assert_eq!(resp.status(), 404);
|
|
|
|
server.cleanup().await;
|
|
}
|
|
|
|
/// Create an empty firmware target and return its id.
|
|
async fn firmware_target(server: &TestServer, name: &str) -> String {
|
|
let resp = server
|
|
.post(
|
|
"/api/v1/targets",
|
|
&json!({ "name": name, "target_type": "firmware_bare_metal", "artifacts": [] }),
|
|
)
|
|
.await;
|
|
assert_eq!(resp.status(), 200);
|
|
let body: serde_json::Value = resp.json().await.unwrap();
|
|
body["data"]["_id"]["$oid"].as_str().unwrap().to_string()
|
|
}
|
|
|
|
/// Files under the upload directory of `target_id`.
|
|
fn stored_uploads(target_id: &str) -> Vec<std::path::PathBuf> {
|
|
let dir = std::path::Path::new("/tmp/compliance-scanner-tests/artifacts")
|
|
.join("uploads")
|
|
.join(target_id);
|
|
std::fs::read_dir(dir)
|
|
.map(|entries| entries.filter_map(|e| e.ok().map(|e| e.path())).collect())
|
|
.unwrap_or_default()
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn an_upload_larger_than_the_json_limit_is_streamed_to_disk() {
|
|
let server = TestServer::start().await;
|
|
let id = firmware_target(&server, "fw-upload").await;
|
|
|
|
// 3 MiB: over axum's 2 MiB default, so it only works on the upload
|
|
// route's own limit, and it is written as it arrives.
|
|
let payload = vec![0xA5_u8; 3 * 1024 * 1024];
|
|
let form = reqwest::multipart::Form::new()
|
|
.text("kind", "firmware_image")
|
|
.part(
|
|
"file",
|
|
reqwest::multipart::Part::bytes(payload.clone()).file_name("fw.bin"),
|
|
);
|
|
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);
|
|
let body: serde_json::Value = resp.json().await.unwrap();
|
|
let artifacts = body["data"]["artifacts"].as_array().unwrap();
|
|
assert_eq!(artifacts.len(), 1);
|
|
assert_eq!(artifacts[0]["size_bytes"], payload.len() as u64);
|
|
|
|
let files = stored_uploads(&id);
|
|
assert_eq!(files.len(), 1);
|
|
assert_eq!(std::fs::read(&files[0]).unwrap(), payload);
|
|
|
|
server.cleanup().await;
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn an_ordinary_json_route_no_longer_accepts_a_huge_body() {
|
|
let server = TestServer::start().await;
|
|
// A 3 MiB description on a JSON route: it used to be buffered under a
|
|
// 512 MiB limit that applied to every route.
|
|
let resp = server
|
|
.post(
|
|
"/api/v1/targets",
|
|
&json!({
|
|
"name": "too-big",
|
|
"target_type": "web_app",
|
|
"description": "x".repeat(3 * 1024 * 1024),
|
|
"artifacts": []
|
|
}),
|
|
)
|
|
.await;
|
|
assert_eq!(resp.status(), 413);
|
|
server.cleanup().await;
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_rejected_upload_leaves_no_file_behind() {
|
|
let server = TestServer::start().await;
|
|
let id = firmware_target(&server, "fw-reject").await;
|
|
|
|
// No `kind` field: refused only after the file was already streamed.
|
|
let form = reqwest::multipart::Form::new().part(
|
|
"file",
|
|
reqwest::multipart::Part::bytes(vec![1_u8; 1024]).file_name("fw.bin"),
|
|
);
|
|
let resp = server
|
|
.client
|
|
.post(format!(
|
|
"{}/api/v1/targets/{id}/artifacts/upload",
|
|
server.base_url
|
|
))
|
|
.multipart(form)
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(resp.status(), 400);
|
|
assert!(
|
|
stored_uploads(&id).is_empty(),
|
|
"the partial upload must be deleted"
|
|
);
|
|
|
|
server.cleanup().await;
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn the_list_pages_with_a_total_after_the_project_filter() {
|
|
let server = TestServer::start().await;
|
|
let mut ids = Vec::new();
|
|
for name in ["page-a", "page-b", "page-c"] {
|
|
ids.push(firmware_target(&server, name).await);
|
|
}
|
|
// Projects are registry-owned, so put two targets in one directly.
|
|
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
|
|
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
|
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
|
|
let targets = client
|
|
.database(&server.tenant_db_name())
|
|
.collection::<mongodb::bson::Document>("onboarded_targets");
|
|
for id in &ids[1..] {
|
|
let oid = mongodb::bson::oid::ObjectId::parse_str(id).unwrap();
|
|
let updated = targets
|
|
.update_one(
|
|
mongodb::bson::doc! { "_id": oid },
|
|
mongodb::bson::doc! { "$set": { "project_ids": ["p1"] } },
|
|
)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(updated.matched_count, 1);
|
|
}
|
|
|
|
let names = |body: &serde_json::Value| -> Vec<String> {
|
|
body["data"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.map(|t| t["name"].as_str().unwrap().to_string())
|
|
.collect()
|
|
};
|
|
let page = |query: &'static str| {
|
|
let server = &server;
|
|
async move {
|
|
let resp = server.get(&format!("/api/v1/targets?{query}")).await;
|
|
assert_eq!(resp.status(), 200);
|
|
resp.json::<serde_json::Value>().await.unwrap()
|
|
}
|
|
};
|
|
|
|
// Creation order, two to a page, the total over every page.
|
|
let first = page("limit=2&page=1").await;
|
|
assert_eq!(names(&first), ["page-a", "page-b"]);
|
|
assert_eq!(first["total"], 3);
|
|
assert_eq!(first["page"], 1);
|
|
let second = page("limit=2&page=2").await;
|
|
assert_eq!(names(&second), ["page-c"]);
|
|
assert_eq!(second["total"], 3);
|
|
|
|
// The filter applies before paging: the total counts the project only.
|
|
let in_project = page("project=p1&limit=1&page=2").await;
|
|
assert_eq!(names(&in_project), ["page-c"]);
|
|
assert_eq!(in_project["total"], 2);
|
|
|
|
// A page past the end is empty but still knows the total.
|
|
let past = page("limit=2&page=9").await;
|
|
assert!(names(&past).is_empty());
|
|
assert_eq!(past["total"], 3);
|
|
|
|
server.cleanup().await;
|
|
}
|
|
|
|
/// Upload `bytes` as a supplier SBOM (#1025) named `name` to target `id`.
|
|
async fn upload_supplier_sbom(
|
|
server: &TestServer,
|
|
id: &str,
|
|
name: &str,
|
|
bytes: &[u8],
|
|
) -> reqwest::Response {
|
|
let form = reqwest::multipart::Form::new()
|
|
.text("kind", "supplier_sbom")
|
|
.part(
|
|
"file",
|
|
reqwest::multipart::Part::bytes(bytes.to_vec()).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_supplier_sbom_is_kept_and_brings_its_scans() {
|
|
let server = TestServer::start().await;
|
|
let id = firmware_target(&server, "bought-in-pump").await;
|
|
let sbom = br#"{"bomFormat": "CycloneDX", "specVersion": "1.5", "components": [
|
|
{"type": "library", "name": "lodash", "version": "4.17.20", "purl": "pkg:npm/lodash@4.17.20"}
|
|
]}"#;
|
|
|
|
let resp = upload_supplier_sbom(&server, &id, "pump.cdx.json", sbom).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);
|
|
assert_eq!(artifacts[0]["kind"], "supplier_sbom");
|
|
assert!(!artifacts[0]["ingested_at"].is_null(), "{body}");
|
|
// What the editor shows of it is kept with it.
|
|
let fact = |key: &str| {
|
|
artifacts[0]["detected"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.find(|f| f["key"] == key)
|
|
.map(|f| f["value"].clone())
|
|
};
|
|
assert_eq!(fact("sbom_format"), Some(json!("CycloneDX 1.5")));
|
|
assert_eq!(fact("sbom_components"), Some(json!("1")));
|
|
assert_eq!(fact("sbom_statements"), Some(json!("0")));
|
|
assert_eq!(stored_uploads(&id).len(), 1);
|
|
// Its SBOM and CVE scans run, though the target has no code.
|
|
let resp = server
|
|
.get(&format!("/api/v1/targets/{id}/applicable-scans"))
|
|
.await;
|
|
let body: serde_json::Value = resp.json().await.unwrap();
|
|
let runs =
|
|
|scan: &str| {
|
|
body["data"]["scans"].as_array().unwrap().iter().any(|s| {
|
|
s["scan"] == scan && s["default_on"] == true && s["blocked_reason"].is_null()
|
|
})
|
|
};
|
|
assert!(runs("sbom") && runs("cve"), "{body}");
|
|
// Each once: not also as blocked by the rules that need code (#1043).
|
|
let listed = |scan: &str| {
|
|
body["data"]["scans"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.filter(|s| s["scan"] == scan)
|
|
.count()
|
|
};
|
|
assert_eq!((listed("sbom"), listed("cve")), (1, 1), "{body}");
|
|
|
|
server.cleanup().await;
|
|
}
|
|
|
|
/// Files that are no supplier SBOM a scan can read: (name, bytes, part of
|
|
/// the reason, its code).
|
|
fn unreadable_sboms() -> [(&'static str, &'static [u8], &'static str, &'static str); 2] {
|
|
[
|
|
(
|
|
"valve.csv",
|
|
b"name,version\nzlib,1.2.11",
|
|
"not a CycloneDX",
|
|
"unknown_format",
|
|
),
|
|
(
|
|
"valve.cdx.json",
|
|
br#"{"bomFormat": "CycloneDX", "specVersion": "1.5"}"#,
|
|
"lists no components",
|
|
"empty",
|
|
),
|
|
]
|
|
}
|
|
|
|
/// Check `bytes` as a supplier SBOM, before any target holds it.
|
|
async fn check_supplier_sbom(server: &TestServer, bytes: &[u8]) -> reqwest::Response {
|
|
let form = reqwest::multipart::Form::new().part(
|
|
"file",
|
|
reqwest::multipart::Part::bytes(bytes.to_vec()).file_name("x.json"),
|
|
);
|
|
server
|
|
.client
|
|
.post(format!("{}/api/v1/supplier-sboms/check", server.base_url))
|
|
.multipart(form)
|
|
.send()
|
|
.await
|
|
.unwrap()
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_supplier_sbom_is_checked_before_a_target_holds_it() {
|
|
let server = TestServer::start().await;
|
|
let sbom = br#"{"bomFormat": "CycloneDX", "specVersion": "1.6",
|
|
"components": [
|
|
{"type": "library", "name": "lodash", "version": "4.17.20", "bom-ref": "l",
|
|
"purl": "pkg:npm/lodash@4.17.20"},
|
|
{"type": "library", "name": "zlib", "version": "1.2.11"}
|
|
],
|
|
"vulnerabilities": [{"id": "CVE-2021-23337", "affects": [{"ref": "l"}],
|
|
"analysis": {"state": "not_affected", "justification": "code_not_reachable"}}]
|
|
}"#;
|
|
|
|
let resp = check_supplier_sbom(&server, sbom).await;
|
|
|
|
assert_eq!(resp.status(), 200);
|
|
let body: serde_json::Value = resp.json().await.unwrap();
|
|
assert_eq!(
|
|
body["data"],
|
|
json!({ "format": "CycloneDX 1.6", "components": 2, "statements": 1 })
|
|
);
|
|
for (name, bytes, _, code) in unreadable_sboms() {
|
|
let resp = check_supplier_sbom(&server, bytes).await;
|
|
assert_eq!(resp.status(), 422, "{name}");
|
|
let body: serde_json::Value = resp.json().await.unwrap();
|
|
assert_eq!(body["code"], code, "{name}");
|
|
}
|
|
// Larger than the 2 MiB of a JSON route, within the SBOM's 20 MiB.
|
|
let padded = [
|
|
&br#"{"bomFormat": "CycloneDX", "specVersion": "1.5", "x": ""#[..],
|
|
&vec![b'a'; 3 * 1024 * 1024],
|
|
br#"", "components": [{"type": "library", "name": "zlib", "version": "1.2.11"}]}"#,
|
|
]
|
|
.concat();
|
|
let resp = check_supplier_sbom(&server, &padded).await;
|
|
assert_eq!(resp.status(), 200);
|
|
|
|
server.cleanup().await;
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_supplier_sbom_that_cannot_be_read_is_refused_with_the_reason() {
|
|
let server = TestServer::start().await;
|
|
let id = firmware_target(&server, "bought-in-valve").await;
|
|
|
|
for (name, bytes, reason, code) in unreadable_sboms() {
|
|
let resp = upload_supplier_sbom(&server, &id, name, bytes).await;
|
|
assert_eq!(resp.status(), 422, "{name}");
|
|
let body: serde_json::Value = resp.json().await.unwrap();
|
|
assert!(
|
|
body["error"].as_str().is_some_and(|e| e.contains(reason)),
|
|
"{name}: {body}"
|
|
);
|
|
assert_eq!(body["code"], code, "{name}");
|
|
}
|
|
assert!(
|
|
stored_uploads(&id).is_empty(),
|
|
"a refused SBOM must be deleted"
|
|
);
|
|
let resp = server.get(&format!("/api/v1/targets/{id}")).await;
|
|
let body: serde_json::Value = resp.json().await.unwrap();
|
|
assert!(body["data"]["artifacts"].as_array().unwrap().is_empty());
|
|
|
|
server.cleanup().await;
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_new_supplier_sbom_replaces_the_one_before_it() {
|
|
let server = TestServer::start().await;
|
|
let id = firmware_target(&server, "bought-in-drive").await;
|
|
let version = |v: &str| {
|
|
format!(
|
|
r#"{{"bomFormat": "CycloneDX", "specVersion": "1.5", "components": [
|
|
{{"type": "library", "name": "zlib", "version": "{v}", "purl": "pkg:generic/zlib@{v}"}}
|
|
]}}"#
|
|
)
|
|
};
|
|
for (name, v) in [
|
|
("drive-1.cdx.json", "1.2.11"),
|
|
("drive-2.cdx.json", "1.3.1"),
|
|
] {
|
|
let resp = upload_supplier_sbom(&server, &id, name, version(v).as_bytes()).await;
|
|
assert_eq!(resp.status(), 200, "{name}");
|
|
}
|
|
|
|
let resp = server.get(&format!("/api/v1/targets/{id}")).await;
|
|
let body: serde_json::Value = resp.json().await.unwrap();
|
|
let artifacts = body["data"]["artifacts"].as_array().unwrap();
|
|
assert_eq!(artifacts.len(), 1, "{body}");
|
|
assert_eq!(artifacts[0]["source_ref"], "drive-2.cdx.json");
|
|
let files = stored_uploads(&id);
|
|
assert_eq!(files.len(), 1, "the replaced file must be gone: {files:?}");
|
|
assert!(std::fs::read_to_string(&files[0])
|
|
.unwrap()
|
|
.contains("1.3.1"));
|
|
|
|
server.cleanup().await;
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_targets_supplier_advisories_are_counted_with_their_last_read() {
|
|
let server = TestServer::start().await;
|
|
let id = firmware_target(&server, "bought-in-motor").await;
|
|
let path = format!("/api/v1/targets/{id}/supplier-advisories");
|
|
let advisories = || async {
|
|
let resp = server.get(&path).await;
|
|
assert_eq!(resp.status(), 200);
|
|
resp.json::<serde_json::Value>().await.unwrap()["data"].clone()
|
|
};
|
|
// Without a provider there is nothing to count.
|
|
assert!(advisories().await.is_null());
|
|
|
|
// `.invalid` never resolves: the background refresh reaches no network.
|
|
let url = "https://motor.invalid/.well-known/csaf/provider-metadata.json";
|
|
let resp = server
|
|
.patch(
|
|
&format!("/api/v1/targets/{id}"),
|
|
&json!({ "supplier": { "name": "Example GmbH", "csaf_provider": url } }),
|
|
)
|
|
.await;
|
|
assert_eq!(resp.status(), 200);
|
|
assert_eq!(advisories().await["advisories"], 0);
|
|
|
|
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 key = format!("supplier:{url}");
|
|
db.collection::<mongodb::bson::Document>("supplier_csaf_advisories")
|
|
.insert_one(mongodb::bson::doc! { "_id": format!("{key}:SA-1"), "provider": &key })
|
|
.await
|
|
.unwrap();
|
|
// As the refresh keeps it: a provider that could not be read.
|
|
db.collection::<mongodb::bson::Document>("supplier_csaf_providers")
|
|
.replace_one(
|
|
mongodb::bson::doc! { "_id": &key },
|
|
mongodb::bson::doc! {
|
|
"_id": &key,
|
|
"checked_at": mongodb::bson::DateTime::now(),
|
|
"reachable": false,
|
|
},
|
|
)
|
|
.upsert(true)
|
|
.await
|
|
.unwrap();
|
|
|
|
let data = advisories().await;
|
|
assert_eq!(data["advisories"], 1, "{data}");
|
|
assert_eq!(data["reachable"], false, "{data}");
|
|
assert!(data["checked_at"].is_string(), "{data}");
|
|
|
|
server.cleanup().await;
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_targets_supplier_is_set_checked_and_removed() {
|
|
let server = TestServer::start().await;
|
|
let id = firmware_target(&server, "bought-in-gearbox").await;
|
|
let path = format!("/api/v1/targets/{id}");
|
|
// `.invalid` never resolves: the refresh started in the background
|
|
// reaches no network.
|
|
let url = "https://supplier.invalid/.well-known/csaf/provider-metadata.json";
|
|
|
|
let resp = server
|
|
.patch(
|
|
&path,
|
|
&json!({ "supplier": {
|
|
"name": " Example GmbH ", "product": "Gearbox Control", "version": "2.1",
|
|
"csaf_provider": url
|
|
} }),
|
|
)
|
|
.await;
|
|
assert_eq!(resp.status(), 200);
|
|
let body: serde_json::Value = resp.json().await.unwrap();
|
|
assert_eq!(
|
|
body["data"]["supplier"],
|
|
json!({ "name": "Example GmbH", "product": "Gearbox Control", "version": "2.1",
|
|
"csaf_provider": url })
|
|
);
|
|
|
|
// A provider that is not an https URL is refused, and nothing changes.
|
|
let resp = server
|
|
.patch(
|
|
&path,
|
|
&json!({ "supplier": { "name": "Example GmbH",
|
|
"csaf_provider": "http://supplier.invalid/x.json" } }),
|
|
)
|
|
.await;
|
|
assert_eq!(resp.status(), 422);
|
|
let body: serde_json::Value = server.get(&path).await.json().await.unwrap();
|
|
assert_eq!(body["data"]["supplier"]["csaf_provider"], url);
|
|
|
|
// An empty name removes the supplier.
|
|
let resp = server
|
|
.patch(&path, &json!({ "supplier": { "name": "" } }))
|
|
.await;
|
|
assert_eq!(resp.status(), 200);
|
|
let body: serde_json::Value = resp.json().await.unwrap();
|
|
assert!(body["data"].get("supplier").is_none(), "{body}");
|
|
|
|
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;
|
|
}
|