feat(supply-chain): keep the customer's arrangement (#1052) (#1056)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Dashboard (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Agent (push) Successful in 5m41s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Dashboard (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Agent (push) Successful in 5m41s
This commit was merged in pull request #1056.
This commit is contained in:
1 parent
240c4d734a
commit
bc73a61f96
5 files changed
+341
No files matched your search
@@ -35,6 +35,7 @@ pub mod scans;
|
||||
pub mod supplier;
|
||||
pub mod supplier_invites;
|
||||
pub mod supply_chain;
|
||||
pub mod supply_chain_layout;
|
||||
pub mod support;
|
||||
pub mod target_input;
|
||||
pub mod vex;
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
//! The customer's arrangement of the supply chain (#1050, #1052): where each
|
||||
//! box of the Lieferkette sits, kept per workspace.
|
||||
//!
|
||||
//! One document in the tenant's own database, so the workspace export and
|
||||
//! erasure cover it. The positions are a list, not a map keyed by node: a
|
||||
//! supplier's name may hold a dot, which a document key may not. Saving
|
||||
//! replaces the whole arrangement (the last save wins); a node the graph no
|
||||
//! longer has is ignored by the page, and a new one takes its computed place.
|
||||
|
||||
use axum::extract::Extension;
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use chrono::{DateTime, Utc};
|
||||
use mongodb::bson::{doc, DateTime as BsonDateTime};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use super::dto::{tenant_db, AgentExt};
|
||||
use super::ApiResponse;
|
||||
use crate::database::Database;
|
||||
|
||||
/// The collection, in the tenant's own database.
|
||||
pub const COLLECTION: &str = "supply_chain_layout";
|
||||
|
||||
/// The one document's id.
|
||||
const LAYOUT_ID: &str = "layout";
|
||||
|
||||
/// The most boxes an arrangement holds.
|
||||
const MAX_POSITIONS: usize = 5_000;
|
||||
|
||||
/// The longest node key accepted.
|
||||
const MAX_KEY_LEN: usize = 400;
|
||||
|
||||
/// How far a box may sit from the origin, in pixels, either way.
|
||||
const MAX_COORDINATE: i32 = 100_000;
|
||||
|
||||
/// Where one box sits.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)]
|
||||
pub struct NodePosition {
|
||||
/// The node's key, as `GET /api/v1/supply-chain` gives it.
|
||||
pub key: String,
|
||||
/// Its left edge, in pixels.
|
||||
pub x: i32,
|
||||
/// Its top edge, in pixels.
|
||||
pub y: i32,
|
||||
}
|
||||
|
||||
/// The arrangement as the page reads it.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct Layout {
|
||||
/// The boxes the customer placed; any other takes its computed place.
|
||||
pub positions: Vec<NodePosition>,
|
||||
/// When it was last saved; `None` before the first save.
|
||||
pub updated_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
/// The body of a save.
|
||||
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||
pub struct SaveLayout {
|
||||
/// Every placed box. One that is left out takes its computed place.
|
||||
pub positions: Vec<NodePosition>,
|
||||
}
|
||||
|
||||
/// The arrangement as stored.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct StoredLayout {
|
||||
#[serde(rename = "_id")]
|
||||
id: String,
|
||||
positions: Vec<NodePosition>,
|
||||
updated_at: BsonDateTime,
|
||||
updated_by: String,
|
||||
}
|
||||
|
||||
fn layouts(db: &Database) -> mongodb::Collection<StoredLayout> {
|
||||
db.inner().collection(COLLECTION)
|
||||
}
|
||||
|
||||
/// `positions` as kept: each key trimmed and once (the last position given
|
||||
/// wins), in the order first given.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 422 for too many boxes, an empty or overlong key, or a box too far out.
|
||||
fn checked(positions: Vec<NodePosition>) -> Result<Vec<NodePosition>, StatusCode> {
|
||||
if positions.len() > MAX_POSITIONS {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
let mut kept: Vec<NodePosition> = Vec::with_capacity(positions.len());
|
||||
// Where each key sits in `kept`: one lookup per box, not a scan.
|
||||
let mut index: std::collections::HashMap<String, usize> =
|
||||
std::collections::HashMap::with_capacity(positions.len());
|
||||
for p in positions {
|
||||
let key = p.key.trim();
|
||||
let usable = !key.is_empty()
|
||||
&& key.len() <= MAX_KEY_LEN
|
||||
&& p.x.abs() <= MAX_COORDINATE
|
||||
&& p.y.abs() <= MAX_COORDINATE;
|
||||
if !usable {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
match index.get(key) {
|
||||
Some(&i) => (kept[i].x, kept[i].y) = (p.x, p.y),
|
||||
None => {
|
||||
index.insert(key.to_string(), kept.len());
|
||||
kept.push(NodePosition {
|
||||
key: key.to_string(),
|
||||
x: p.x,
|
||||
y: p.y,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(kept)
|
||||
}
|
||||
|
||||
/// The workspace's arrangement of its supply chain.
|
||||
///
|
||||
/// The boxes the customer placed, by node key; an empty list before the
|
||||
/// first save, when every box takes its computed place.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/supply-chain/layout",
|
||||
tag = "Targets",
|
||||
responses(
|
||||
(status = 200, description = "The arrangement (`data`: `positions`, `updated_at`)"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn get_layout(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
) -> Result<Json<ApiResponse<Layout>>, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let stored = layouts(&db)
|
||||
.find_one(doc! { "_id": LAYOUT_ID })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let data = stored.map_or(
|
||||
Layout {
|
||||
positions: Vec::new(),
|
||||
updated_at: None,
|
||||
},
|
||||
|s| Layout {
|
||||
positions: s.positions,
|
||||
updated_at: Some(s.updated_at.to_chrono()),
|
||||
},
|
||||
);
|
||||
Ok(Json(ApiResponse {
|
||||
data,
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Save the workspace's arrangement of its supply chain.
|
||||
///
|
||||
/// Replaces the whole arrangement: the last save wins. Each key is kept once,
|
||||
/// with the last position given for it.
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/api/v1/supply-chain/layout",
|
||||
tag = "Targets",
|
||||
request_body = SaveLayout,
|
||||
responses(
|
||||
(status = 200, description = "The arrangement as kept (`data`)"),
|
||||
(status = 422, description = "Too many boxes, an empty or overlong key, or a box too far out"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
(status = 403, description = "A read-only role"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn save_layout(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Json(body): Json<SaveLayout>,
|
||||
) -> Result<Json<ApiResponse<Layout>>, StatusCode> {
|
||||
let positions = checked(body.positions)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let now = Utc::now();
|
||||
let stored = StoredLayout {
|
||||
id: LAYOUT_ID.to_string(),
|
||||
positions,
|
||||
updated_at: now.into(),
|
||||
updated_by: tenant.0.user_id.clone(),
|
||||
};
|
||||
layouts(&db)
|
||||
.replace_one(doc! { "_id": LAYOUT_ID }, &stored)
|
||||
.upsert(true)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
Ok(Json(ApiResponse {
|
||||
data: Layout {
|
||||
positions: stored.positions,
|
||||
updated_at: Some(stored.updated_at.to_chrono()),
|
||||
},
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Reset the workspace's arrangement: every box takes its computed place.
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
path = "/api/v1/supply-chain/layout",
|
||||
tag = "Targets",
|
||||
responses(
|
||||
(status = 200, description = "The arrangement was reset"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
(status = 403, description = "A read-only role"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn reset_layout(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
layouts(&db)
|
||||
.delete_one(doc! { "_id": LAYOUT_ID })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
Ok(Json(serde_json::json!({ "status": "reset" })))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn at(key: &str, x: i32, y: i32) -> NodePosition {
|
||||
NodePosition {
|
||||
key: key.into(),
|
||||
x,
|
||||
y,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_is_kept_once_with_its_last_position() {
|
||||
let kept = checked(vec![
|
||||
at(" target:a ", 10, 20),
|
||||
at("supplier:Beispiel GmbH & Co. KG", 0, 0),
|
||||
at("target:a", 30, 40),
|
||||
])
|
||||
.expect("usable");
|
||||
assert_eq!(
|
||||
kept,
|
||||
[
|
||||
at("target:a", 30, 40),
|
||||
at("supplier:Beispiel GmbH & Co. KG", 0, 0)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonsense_is_refused() {
|
||||
for bad in [
|
||||
vec![at(" ", 0, 0)],
|
||||
vec![at(&"k".repeat(401), 0, 0)],
|
||||
vec![at("target:a", 100_001, 0)],
|
||||
vec![at("target:a", 0, -100_001)],
|
||||
] {
|
||||
assert_eq!(checked(bad), Err(StatusCode::UNPROCESSABLE_ENTITY));
|
||||
}
|
||||
let many = (0..=MAX_POSITIONS)
|
||||
.map(|i| at(&format!("target:{i}"), 0, 0))
|
||||
.collect();
|
||||
assert_eq!(checked(many), Err(StatusCode::UNPROCESSABLE_ENTITY));
|
||||
assert_eq!(checked(Vec::new()), Ok(Vec::new()));
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,12 @@ fn described_routes() -> OpenApiRouter {
|
||||
.routes(routes!(handlers::machine::machine_cves))
|
||||
.routes(routes!(handlers::machine::machine_scan_changes))
|
||||
.routes(routes!(handlers::supply_chain::get_supply_chain))
|
||||
// The customer's arrangement of the supply chain (#1052).
|
||||
.routes(routes!(
|
||||
handlers::supply_chain_layout::get_layout,
|
||||
handlers::supply_chain_layout::save_layout,
|
||||
handlers::supply_chain_layout::reset_layout
|
||||
))
|
||||
.routes(routes!(handlers::metering::get_usage))
|
||||
// Whether the caller may use Prüfwerk at all: answered by the
|
||||
// authentication and entitlement layers in front of it (a blocked
|
||||
|
||||
@@ -147,6 +147,16 @@ impl TestServer {
|
||||
.expect("PATCH request failed")
|
||||
}
|
||||
|
||||
/// PUT helper with JSON body
|
||||
pub async fn put(&self, path: &str, body: &serde_json::Value) -> reqwest::Response {
|
||||
self.client
|
||||
.put(format!("{}{path}", self.base_url))
|
||||
.json(body)
|
||||
.send()
|
||||
.await
|
||||
.expect("PUT request failed")
|
||||
}
|
||||
|
||||
/// DELETE helper
|
||||
pub async fn delete(&self, path: &str) -> reqwest::Response {
|
||||
self.client
|
||||
|
||||
@@ -103,3 +103,55 @@ async fn the_supply_chain_links_suppliers_components_and_products() {
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_arrangement_is_kept_until_it_is_reset() {
|
||||
let server = TestServer::start().await;
|
||||
let layout = "/api/v1/supply-chain/layout";
|
||||
|
||||
let resp = server.get(layout).await;
|
||||
assert_eq!(resp.status(), 200);
|
||||
let body: serde_json::Value = resp.json().await.unwrap();
|
||||
assert_eq!(body["data"]["positions"], json!([]));
|
||||
assert!(body["data"]["updated_at"].is_null());
|
||||
|
||||
let saved = json!({ "positions": [
|
||||
{ "key": "supplier:Beispiel GmbH & Co. KG", "x": 40, "y": 60 },
|
||||
{ "key": "target:a", "x": 400, "y": 60 },
|
||||
{ "key": "target:a", "x": 420, "y": 80 },
|
||||
] });
|
||||
let resp = server.put(layout, &saved).await;
|
||||
assert_eq!(resp.status(), 200);
|
||||
|
||||
let body: serde_json::Value = server.get(layout).await.json().await.unwrap();
|
||||
assert_eq!(
|
||||
body["data"]["positions"],
|
||||
json!([
|
||||
{ "key": "supplier:Beispiel GmbH & Co. KG", "x": 40, "y": 60 },
|
||||
{ "key": "target:a", "x": 420, "y": 80 },
|
||||
]),
|
||||
"a name with a dot is kept, a key once with its last position"
|
||||
);
|
||||
assert!(body["data"]["updated_at"].is_string());
|
||||
|
||||
let resp = server
|
||||
.put(
|
||||
layout,
|
||||
&json!({ "positions": [{ "key": " ", "x": 0, "y": 0 }] }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(resp.status(), 422);
|
||||
let body: serde_json::Value = server.get(layout).await.json().await.unwrap();
|
||||
assert_eq!(
|
||||
body["data"]["positions"].as_array().unwrap().len(),
|
||||
2,
|
||||
"a refused save changes nothing"
|
||||
);
|
||||
|
||||
let resp = server.delete(layout).await;
|
||||
assert_eq!(resp.status(), 200);
|
||||
let body: serde_json::Value = server.get(layout).await.json().await.unwrap();
|
||||
assert_eq!(body["data"]["positions"], json!([]));
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
Reference in new issue
Block a user