Compare commits

..
Author SHA1 Message Date
Sharang ParnerkarandClaude Opus 5.5 fa60318c19 fix(scan): removing a target's last controller clears its components and alerts
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 5m2s
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 22m48s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 14:57:05 +01:00
Sharang ParnerkarandClaude Opus 5.5 d75dd85e2e fix(scan): a target known only by its Siemens controllers is matched
A PLC target without a project file took the no-code path and never
persisted its device entries, so its controllers raised no CVE alerts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 14:57:05 +01:00
Sharang ParnerkarandClaude Opus 5.5 7dec38d74a fix(api): device route summaries fit the OpenAPI rule
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 14:57:05 +01:00
Sharang ParnerkarandClaude Opus 5.5 5d640e4457 fix(csaf): the test module goes last
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 14:57:05 +01:00
Sharang ParnerkarandClaude Opus 5.5 87a0f5b5c6 fix(csaf): read a Siemens fix only from 'Update to V<version>'
Sampled across the feed: a vendor fix can name hardware (LOGO! V9 BM) or a
version with letters (V3.X.18); neither is a firmware to update to.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 14:57:05 +01:00
Sharang ParnerkarandClaude Opus 5.5 5d4d6198df fix(dashboard): grey light on the dark module, form labels as in the mockup
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 14:57:05 +01:00
Sharang ParnerkarandClaude Opus 5.5 f5d9be1a93 docs(plc): Siemens controllers by order number; no scan-made VEX fixed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 14:57:05 +01:00
Sharang ParnerkarandClaude Opus 5.5 93f787160e feat(dashboard): a target's Siemens controllers on a DIN rail (SPS 4a)
Each controller is a module whose light says whether a Siemens advisory
affects its firmware. The chosen one shows its advisories with the fixed
firmware and the Quelle link. The form recognises an order number while it
is typed. The target page gets a card for PLC targets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 14:57:05 +01:00
Sharang ParnerkarandClaude Opus 5.5 5367e2ec71 feat(devices): a target's Siemens controllers against Siemens' advisories (SPS 4a)
DeviceCheck in core puts a device's state and advisory rows together with
the scan's matcher. Siemens writes a fix only as vendor_fix text, so its
firmware is read from there too. The agent serves the target's devices and
an order number lookup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-28 14:57:05 +01:00
41 changed files with 85 additions and 1915 deletions

No files matched your search

Generated
+9 -9
View File
@@ -601,7 +601,7 @@ dependencies = [
[[package]]
name = "compliance-agent"
version = "0.4.19"
version = "0.4.18"
dependencies = [
"axum",
"base64 0.22.1",
@@ -657,7 +657,7 @@ dependencies = [
[[package]]
name = "compliance-core"
version = "0.4.19"
version = "0.4.18"
dependencies = [
"aes-gcm",
"axum",
@@ -689,7 +689,7 @@ dependencies = [
[[package]]
name = "compliance-dashboard"
version = "0.4.19"
version = "0.4.18"
dependencies = [
"async-trait",
"axum",
@@ -727,7 +727,7 @@ dependencies = [
[[package]]
name = "compliance-dast"
version = "0.4.19"
version = "0.4.18"
dependencies = [
"axum",
"base64 0.22.1",
@@ -749,7 +749,7 @@ dependencies = [
[[package]]
name = "compliance-graph"
version = "0.4.19"
version = "0.4.18"
dependencies = [
"bson",
"chrono",
@@ -774,7 +774,7 @@ dependencies = [
[[package]]
name = "compliance-mcp"
version = "0.4.19"
version = "0.4.18"
dependencies = [
"axum",
"bson",
@@ -797,7 +797,7 @@ dependencies = [
[[package]]
name = "compliance-smoke"
version = "0.4.19"
version = "0.4.18"
dependencies = [
"axum",
"compliance-core",
@@ -932,7 +932,7 @@ dependencies = [
[[package]]
name = "control-map"
version = "0.4.19"
version = "0.4.18"
dependencies = [
"serde",
"serde_json",
@@ -7127,7 +7127,7 @@ dependencies = [
[[package]]
name = "werkbank-exec"
version = "0.4.19"
version = "0.4.18"
dependencies = [
"compliance-core",
"compliance-dast",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-agent"
version = "0.4.19"
version = "0.4.18"
edition = "2021"
[lints]
+5 -7
View File
@@ -173,9 +173,8 @@ impl ComplianceAgent {
}
/// Store which of the tenant's targets are the plan's included ones and
/// which are extra (t72), from the plan's `included_targets`; a plan that
/// allows no extra target includes them all. Without a registry every
/// target is included. Best-effort: when the plan cannot
/// which are extra (t72), from the plan's `included_targets`. Without a
/// registry every target is included. Best-effort: when the plan cannot
/// be read or the targets not updated, the stored split stays.
///
/// # Returns
@@ -188,7 +187,7 @@ impl ComplianceAgent {
) -> Vec<BillingChange> {
match self.plan(tenant_id).await {
Some(plan) => {
self.assign_billing(tenant_id, db, plan.billed_included())
self.assign_billing(tenant_id, db, plan.included_targets)
.await
}
None => Vec::new(),
@@ -206,7 +205,6 @@ impl ComplianceAgent {
match registry.check_entitlement(tenant_id, None, None).await {
Ok(check) => Some(crate::metering::Plan {
included_targets: check.included_targets(),
extra_targets: check.extra_targets(),
limits: check.plan_limits(),
}),
Err(e) => {
@@ -218,7 +216,7 @@ impl ComplianceAgent {
/// Store the billing of the tenant's targets for a plan that includes
/// `included` targets; best-effort.
pub(crate) async fn assign_billing(
async fn assign_billing(
&self,
tenant_id: &str,
db: &crate::database::Database,
@@ -361,7 +359,7 @@ impl ComplianceAgent {
// counts, and the plan's limits whether a counted one may run (t72).
let plan = self.plan(tenant_id).await;
if let Some(plan) = &plan {
self.assign_billing(tenant_id, &db, plan.billed_included())
self.assign_billing(tenant_id, &db, plan.included_targets)
.await;
}
let orchestrator =
@@ -1,268 +0,0 @@
//! The workspace's branding for the dashboard (tenant-registry#155): its CI
//! colour, which frames every page, its logo, and the one-time notice for its
//! admins that both were taken from its website.
//!
//! The registry derives and stores the branding; the agent only passes on
//! what the entitlement check (already cached per tenant) says, serves the
//! logo from its own origin, and forwards an admin's "Passt". Without a
//! registry, or when it cannot be asked, there is simply no branding.
use axum::extract::Extension;
use axum::http::{header, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::Json;
use serde::Serialize;
use compliance_core::tenant::TenantContext;
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::AgentExt;
use crate::registry::{AckRefusal, Branding};
/// What the dashboard draws.
#[derive(Debug, Default, PartialEq, Eq, Serialize, utoipa::ToSchema)]
pub struct BrandingView {
/// The frame colour, `#rrggbb`; none means no frame.
pub color: Option<String>,
/// Whether `GET /api/v1/branding/logo` has a logo.
pub logo: bool,
/// The workspace's name, beside the logo.
pub name: Option<String>,
/// Whether to show the caller the notice; only ever for its admins.
pub notice: bool,
/// The domain the branding was taken from, for the notice.
pub domain: Option<String>,
}
impl BrandingView {
/// The view of `branding` for `caller`: the notice only for a person who
/// is an admin of the workspace, never for support or an API key.
fn of(branding: &Branding, caller: &TenantContext) -> Self {
let admin = caller.is_admin() && caller.staff.is_none() && caller.api_key.is_none();
let notice = admin && branding.notice && branding.domain.is_some();
Self {
color: branding.frame_color(),
logo: branding.logo_etag().is_some(),
name: branding.name.clone().filter(|n| !n.trim().is_empty()),
notice,
domain: notice.then(|| branding.domain.clone()).flatten(),
}
}
}
/// The workspace's branding as the registry answered, or none.
async fn branding(agent: &crate::agent::ComplianceAgent, tenant_id: &str) -> Option<Branding> {
let registry = agent.registry.as_ref()?;
match registry.check_entitlement(tenant_id, None, None).await {
Ok(check) => check.branding,
Err(e) => {
tracing::debug!(tenant_id, "branding not read: {e}");
None
}
}
}
/// The workspace's branding.
///
/// Its CI colour, whether it has a logo, and whether the caller (an admin)
/// still has to acknowledge a branding taken from its website. Every field is
/// empty when the workspace has none or the registry cannot be asked.
#[utoipa::path(
get,
path = "/api/v1/branding",
tag = "Workspace",
responses(
(status = 200, description = "The branding", body = BrandingView),
(status = 401, description = "No valid bearer token"),
)
)]
pub async fn get_branding(
Extension(agent): AgentExt,
tenant: TenantCtx,
) -> Json<serde_json::Value> {
let view = branding(&agent, &tenant.0.tenant_id)
.await
.map(|b| BrandingView::of(&b, &tenant.0))
.unwrap_or_default();
Json(serde_json::json!({ "data": view }))
}
/// The workspace's logo.
///
/// A PNG of at most 256 px, from the registry, never an SVG.
///
/// # Errors
///
/// `404` when the workspace has no logo; `502` when the registry cannot
/// deliver it.
#[utoipa::path(
get,
path = "/api/v1/branding/logo",
tag = "Workspace",
responses(
(status = 200, description = "The logo", content_type = "image/png"),
(status = 404, description = "No logo"),
(status = 502, description = "The registry cannot deliver it"),
(status = 401, description = "No valid bearer token"),
)
)]
pub async fn get_logo(
Extension(agent): AgentExt,
tenant: TenantCtx,
) -> Result<Response, StatusCode> {
let tenant_id = &tenant.0.tenant_id;
let (Some(registry), Some(b)) = (agent.registry.as_ref(), branding(&agent, tenant_id).await)
else {
return Err(StatusCode::NOT_FOUND);
};
let etag = b.logo_etag().ok_or(StatusCode::NOT_FOUND)?;
match registry.branding_logo(tenant_id, etag).await {
Ok(Some(png)) => Ok((
[
(header::CONTENT_TYPE, "image/png".to_string()),
(header::ETAG, format!("\"{etag}\"")),
(header::CACHE_CONTROL, "private, max-age=300".to_string()),
(header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()),
],
png,
)
.into_response()),
Ok(None) => Err(StatusCode::NOT_FOUND),
Err(e) => {
tracing::warn!(tenant_id, "logo not fetched: {e}");
Err(StatusCode::BAD_GATEWAY)
}
}
}
/// Acknowledge the workspace's branding ("Passt").
///
/// An admin confirms the logo and colour taken from the workspace's website;
/// the notice then no longer shows.
///
/// # Errors
///
/// `403` when the caller is no admin of the workspace; `503` without a
/// registry; `502` when the registry cannot record it.
#[utoipa::path(
post,
path = "/api/v1/branding/ack",
tag = "Workspace",
responses(
(status = 204, description = "Recorded"),
(status = 403, description = "Only the workspace's admins acknowledge it"),
(status = 502, description = "The registry cannot record it"),
(status = 503, description = "No registry"),
(status = 401, description = "No valid bearer token"),
)
)]
pub async fn ack(Extension(agent): AgentExt, tenant: TenantCtx) -> StatusCode {
let caller = &tenant.0;
if !caller.is_admin() || caller.staff.is_some() || caller.api_key.is_some() {
return StatusCode::FORBIDDEN;
}
let Some(registry) = agent.registry.as_ref() else {
return StatusCode::SERVICE_UNAVAILABLE;
};
match registry
.ack_branding(&caller.tenant_id, &caller.user_id)
.await
{
Ok(()) => StatusCode::NO_CONTENT,
Err(AckRefusal::NotAdmin) => {
tracing::info!(
tenant_id = %caller.tenant_id,
"branding ack refused: the registry does not count the caller as an admin"
);
StatusCode::FORBIDDEN
}
Err(AckRefusal::Failed(e)) => {
tracing::warn!(tenant_id = %caller.tenant_id, "branding ack failed: {e}");
StatusCode::BAD_GATEWAY
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use compliance_core::{OrgRole, TenantStatus};
fn caller(roles: Vec<OrgRole>) -> TenantContext {
TenantContext {
tenant_id: "t-1".into(),
tenant_slug: "acme".into(),
org_roles: roles,
products: vec!["compliance-scanner".into()],
plan: "entry".into(),
status: TenantStatus::Active,
user_id: "u-1".into(),
user_name: None,
staff: None,
api_key: None,
}
}
fn derived() -> Branding {
Branding {
color: Some("#14B8A6".into()),
logo_etag: Some("a".repeat(64)),
notice: true,
domain: Some("example.de".into()),
name: Some("Example GmbH".into()),
}
}
#[test]
fn only_an_admin_sees_the_notice() {
// Arrange
let b = derived();
// Act
let admin = BrandingView::of(&b, &caller(vec![OrgRole::ItAdmin]));
let member = BrandingView::of(&b, &caller(vec![OrgRole::User]));
// Assert: both see the frame and logo, only the admin the notice.
assert_eq!(admin.color.as_deref(), Some("#14b8a6"));
assert!(admin.logo && member.logo);
assert!(admin.notice);
assert_eq!(admin.domain.as_deref(), Some("example.de"));
assert!(!member.notice);
assert_eq!(member.domain, None);
assert_eq!(member.color, admin.color);
}
#[test]
fn support_and_api_keys_never_see_the_notice() {
let b = derived();
let mut staff = caller(vec![OrgRole::Owner]);
staff.staff = Some(compliance_core::tenant::StaffAccess {
user_id: "s-1".into(),
user_name: None,
});
assert!(!BrandingView::of(&b, &staff).notice);
}
#[test]
fn a_malformed_colour_or_etag_is_no_frame_and_no_logo() {
for color in ["red", "#12345", "#1234567", "#gggggg", "url(x)", ""] {
let b = Branding {
color: Some(color.into()),
logo_etag: Some("not-a-hash".into()),
..Default::default()
};
let view = BrandingView::of(&b, &caller(vec![OrgRole::Owner]));
assert_eq!(view.color, None, "{color}");
assert!(!view.logo);
}
}
#[test]
fn a_notice_without_a_domain_is_not_shown() {
let b = Branding {
domain: None,
..derived()
};
assert!(!BrandingView::of(&b, &caller(vec![OrgRole::Owner])).notice);
}
}
-1
View File
@@ -1,5 +1,4 @@
pub mod admin;
pub mod branding;
pub mod chat;
pub mod connections;
pub mod cve_history;
+3 -3
View File
@@ -490,7 +490,7 @@ pub async fn list_offers(
responses(
(status = 200, description = "Accepted (`data`: the offer)"),
(status = 404, description = "No such offer, or no such component"),
(status = 409, description = "Already answered (`answered`), the release or connection ended (`ended`), or the component already receives another release (`target_taken`), or the plan allows no further active target (`target_limit`)"),
(status = 409, description = "Already answered (`answered`), the release or connection ended (`ended`), or the component already receives another release (`target_taken`)"),
(status = 422, description = "The component is not a supplier component (`not_supplier_component`), or an unknown project"),
(status = 503, description = "The registry cannot be asked"),
(status = 401, description = "No valid bearer token"),
@@ -601,9 +601,9 @@ pub async fn accept_offer(
.await
{
Ok(created) => created,
Err(e) => {
Err(status) => {
unclaim(&db, offer.id).await?;
return Ok(super::onboarding::target_refused(e));
return Err(status);
}
};
let created_id = created.id.map(|o| o.to_hex()).unwrap_or_default();
+31 -90
View File
@@ -20,7 +20,6 @@ use compliance_core::tenant_ctx::TenantCtx;
use crate::agent::ComplianceAgent;
use crate::classify::{classify_target, MockFirmwareDetector};
use crate::error::AgentError;
use crate::secrets::SecretError;
use crate::targets::{upload_dest, uploaded_artifact, MAX_UPLOAD_BYTES};
@@ -406,8 +405,7 @@ async fn findings_counts(
request_body = CreateTargetRequest,
responses(
(status = 200, description = "The new target"),
(status = 409, description = "The plan allows no further active target (`target_limit`)"),
(status = 422, description = "A malformed body"),
(status = 422, description = "A malformed body, or a device whose order number or firmware is not one"),
(status = 503, description = "A credential cannot be sealed"),
(status = 401, description = "No valid bearer token"),
)
@@ -417,25 +415,20 @@ pub async fn create_target(
Extension(agent): AgentExt,
tenant: TenantCtx,
Json(req): Json<CreateTargetRequest>,
) -> Result<Json<ApiResponse<OnboardedTarget>>, axum::response::Response> {
use axum::response::IntoResponse;
) -> Result<Json<ApiResponse<OnboardedTarget>>, StatusCode> {
let mut target = OnboardedTarget::new(req.name, req.target_type);
target.description = req.description;
if let Some(supplier) = req.supplier {
target.supplier = supplier.build().map_err(IntoResponse::into_response)?;
target.supplier = supplier.build()?;
}
target.devices = build_devices(&req.devices)?;
target.artifacts = merge_artifacts(&agent.secrets, &req.artifacts, &[]).map_err(|e| {
tracing::error!("storing a credential: {e}");
StatusCode::SERVICE_UNAVAILABLE.into_response()
StatusCode::SERVICE_UNAVAILABLE
})?;
let db = tenant_db(&agent, &tenant)
.await
.map_err(IntoResponse::into_response)?;
let target = insert_target(&agent, &db, &tenant.0.tenant_id, target)
.await
.map_err(target_refused)?;
let db = tenant_db(&agent, &tenant).await?;
let target = insert_target(&agent, &db, &tenant.0.tenant_id, target).await?;
Ok(Json(ApiResponse {
data: target.redacted(),
total: None,
@@ -443,45 +436,36 @@ pub async fn create_target(
}))
}
/// Store a new `target` of tenant `tenant_id` and count it
/// ([`crate::targets::create_target`]), then read its supplier's CSAF feed.
/// What the API and accepting a supplier's SBOM release (#1028) do.
/// Store a new `target` of tenant `tenant_id` and count it: what every way
/// of adding a target does (the API, and accepting a supplier's SBOM release,
/// #1028), so each counts the same under the plan.
///
/// # Errors
///
/// [`AgentError::TargetLimit`] when the plan has no room for it; a database
/// error.
/// 500 when it cannot be stored.
pub(super) async fn insert_target(
agent: &Arc<ComplianceAgent>,
db: &crate::database::Database,
tenant_id: &str,
target: OnboardedTarget,
) -> Result<OnboardedTarget, AgentError> {
let target = crate::targets::create_target(agent, db, tenant_id, target).await?;
mut target: OnboardedTarget,
) -> Result<OnboardedTarget, StatusCode> {
let res = db
.onboarded_targets()
.insert_one(&target)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
target.id = res.inserted_id.as_object_id();
refresh_supplier_csaf(agent, tenant_id, target.supplier.as_ref());
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
agent.emit_usage(
tenant_id,
"target.added",
format!("target:{tenant_id}:{target_id}"),
serde_json::json!({ "target_id": target_id, "target_type": format!("{:?}", target.target_type) }),
);
Ok(target)
}
/// A new target refused, as the API answers: 409 `{"error": "target_limit"}`
/// when the plan has no room for it, else 500.
pub(super) fn target_refused(e: AgentError) -> axum::response::Response {
use axum::response::IntoResponse;
match e {
AgentError::TargetLimit(cap) => {
tracing::info!(cap, "new target refused: the plan's targets are all active");
(
StatusCode::CONFLICT,
Json(serde_json::json!({ "error": "target_limit" })),
)
.into_response()
}
e => {
tracing::error!("storing a target: {e}");
StatusCode::INTERNAL_SERVER_ERROR.into_response()
}
}
}
/// One target, credentials redacted.
#[utoipa::path(
get,
@@ -576,7 +560,6 @@ pub async fn list_webhook_deliveries(
(status = 200, description = "The changed target"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such target"),
(status = 409, description = "`target_limit`: other artifacts would make a demo target the tenant's own, and the plan has no room for it"),
(status = 422, description = "A malformed body, a project that is not the tenant's, or a device whose order number or firmware is not one"),
(status = 503, description = "A credential cannot be sealed"),
(status = 401, description = "No valid bearer token"),
@@ -588,7 +571,7 @@ pub async fn update_target(
tenant: TenantCtx,
Path(id): Path<String>,
Json(req): Json<UpdateTargetRequest>,
) -> Result<Json<ApiResponse<OnboardedTarget>>, UploadRefusal> {
) -> Result<Json<ApiResponse<OnboardedTarget>>, StatusCode> {
let oid = parse_oid(&id)?;
let db = tenant_db(&agent, &tenant).await?;
@@ -660,14 +643,9 @@ pub async fn update_target(
);
set.insert("project_ids", ids);
}
// A demo target given other sources becomes the tenant's own (below).
let mut claimed_demo = None;
if let (Some(arts), Some(stored)) = (req.artifacts, stored.as_ref()) {
let built =
merge_artifacts(&agent.secrets, &arts, &stored.artifacts).map_err(credential_error)?;
if !crate::targets::same_sources(&stored.artifacts, &built) {
claimed_demo = Some(stored);
}
set.insert(
"artifacts",
to_bson(&built).map_err(|_| StatusCode::BAD_REQUEST)?,
@@ -699,11 +677,6 @@ pub async fn update_target(
}
update.insert("$set", set);
if let Some(stored) = claimed_demo {
crate::targets::claim_demo(&agent, &db, &tenant.0.tenant_id, stored)
.await
.map_err(demo_refused)?;
}
db.onboarded_targets()
.update_one(doc! { "_id": oid }, update)
.await
@@ -719,22 +692,7 @@ pub async fn update_target(
});
}
Ok(get_target(Extension(agent), tenant, Path(id)).await?)
}
/// A demo target not made the tenant's own, as the API answers: 409
/// `target_limit` when the plan has no room for it, else 500.
fn demo_refused(e: AgentError) -> UploadRefusal {
match e {
AgentError::TargetLimit(cap) => {
tracing::info!(cap, "demo target kept: the plan's targets are all active");
UploadRefusal::because(StatusCode::CONFLICT, "target_limit", "target_limit")
}
e => {
tracing::error!("claiming a demo target: {e}");
StatusCode::INTERNAL_SERVER_ERROR.into()
}
}
get_target(Extension(agent), tenant, Path(id)).await
}
/// Remove a deleted target's clones, uploads, work trees and blobs from disk.
@@ -914,8 +872,6 @@ async fn delete_session_data(db: &crate::database::Database, session_id: &str) {
responses(
(status = 200, description = "The target with the artifact"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such target"),
(status = 409, description = "`target_limit`: the artifact would make a demo target the tenant's own, and the plan has no room for it"),
(status = 422, description = "A malformed body"),
(status = 503, description = "A credential cannot be sealed"),
(status = 401, description = "No valid bearer token"),
@@ -927,18 +883,9 @@ pub async fn add_artifact(
tenant: TenantCtx,
Path(id): Path<String>,
Json(input): Json<ArtifactInput>,
) -> Result<Json<ApiResponse<OnboardedTarget>>, UploadRefusal> {
) -> Result<Json<ApiResponse<OnboardedTarget>>, StatusCode> {
let oid = parse_oid(&id)?;
let db = tenant_db(&agent, &tenant).await?;
let stored = db
.onboarded_targets()
.find_one(doc! { "_id": oid })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::NOT_FOUND)?;
crate::targets::claim_demo(&agent, &db, &tenant.0.tenant_id, &stored)
.await
.map_err(demo_refused)?;
let artifact = input.build(&agent.secrets, None).map_err(|e| {
tracing::error!("storing a credential: {e}");
StatusCode::SERVICE_UNAVAILABLE
@@ -951,7 +898,7 @@ pub async fn add_artifact(
)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(get_target(Extension(agent), tenant, Path(id)).await?)
get_target(Extension(agent), tenant, Path(id)).await
}
/// The multipart form of an artifact upload.
@@ -994,7 +941,6 @@ pub struct UploadArtifactForm {
responses(
(status = 200, description = "The target with the artifact"),
(status = 404, description = "No such target"),
(status = 409, description = "`target_limit`: the file would make a demo target the tenant's own, and the plan has no room for it"),
(status = 400, description = "Not an id, or a missing or unknown field"),
(status = 413, description = "The file is too large (a supplier SBOM: over 20 MiB)"),
(status = 415, description = "An archive format that cannot be unpacked"),
@@ -1019,11 +965,6 @@ pub async fn upload_artifact(
else {
return Err(StatusCode::NOT_FOUND.into());
};
// Refused before the file streams in. A demo target becomes the
// tenant's own even when the file then turns out unreadable.
crate::targets::claim_demo(&agent, &db, &tenant.0.tenant_id, &stored_target)
.await
.map_err(demo_refused)?;
let mut kind: Option<ArtifactKind> = None;
let mut plc_format: Option<PlcFormat> = None;
@@ -1802,7 +1743,7 @@ pub async fn swap_target_billing(
&db,
incoming,
outgoing,
plan.billed_included().is_some(),
plan.included_targets.is_some(),
chrono::Utc::now(),
)
.await
+3 -28
View File
@@ -250,16 +250,14 @@ pub async fn export(
/// `DELETE /api/v1/platform/tenants/{id}/data` — GDPR erasure: drops the
/// tenant database and removes its code from disk (clones, uploads, work
/// trees, blobs, runner artifacts). Requires `{"confirm": "<tenant id>"}`:
/// the same id as in the path, so a call can only erase the tenant it names
/// twice; anything else is refused with 400 before anything is touched.
/// trees, blobs, runner artifacts). Requires `{"confirm": "<slug or id>"}`.
pub async fn delete_data(
State(st): State<PlatformState>,
Path(tenant_id): Path<String>,
body: Option<Json<LifecycleBody>>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let confirm = body.and_then(|Json(b)| b.confirm);
if !confirms_erasure(&tenant_id, confirm.as_deref()) {
let confirm = body.and_then(|Json(b)| b.confirm).unwrap_or_default();
if confirm.is_empty() {
return Err(StatusCode::BAD_REQUEST);
}
// Where the tenant's code lies on disk, read before its records go.
@@ -301,12 +299,6 @@ pub async fn delete_data(
})))
}
/// Whether `confirm` confirms erasing `tenant_id`: it must be that id,
/// exactly. A missing or empty value, or another tenant's id, does not.
fn confirms_erasure(tenant_id: &str, confirm: Option<&str>) -> bool {
!tenant_id.is_empty() && confirm == Some(tenant_id)
}
/// `POST /api/v1/platform/tenants/demo/reset` — drops and re-creates the
/// demo tenant database. With `{"seed": true}` it then re-seeds the bundled
/// demo targets and starts their scans, which is what the nightly reset of the
@@ -856,20 +848,3 @@ mod target_count_tests {
assert!(stages[0].contains_key("$match") && stages[1].contains_key("$group"));
}
}
#[cfg(test)]
mod erasure_tests {
use super::*;
#[test]
fn only_the_tenants_own_id_confirms_its_erasure() {
assert!(confirms_erasure("t-1", Some("t-1")));
assert!(!confirms_erasure("t-1", None));
assert!(!confirms_erasure("t-1", Some("")));
assert!(!confirms_erasure("t-1", Some("t-2")));
assert!(!confirms_erasure("t-1", Some("T-1")));
assert!(!confirms_erasure("t-1", Some(" t-1")));
assert!(!confirms_erasure("t-1", Some("yes")));
assert!(!confirms_erasure("", Some("")));
}
}
-4
View File
@@ -73,10 +73,6 @@ fn described_routes() -> OpenApiRouter {
handlers::supply_chain_layout::reset_layout
))
.routes(routes!(handlers::metering::get_usage))
// The workspace's branding (tenant-registry#155).
.routes(routes!(handlers::branding::get_branding))
.routes(routes!(handlers::branding::get_logo))
.routes(routes!(handlers::branding::ack))
// Whether the caller may use Prüfwerk at all: answered by the
// authentication and entitlement layers in front of it (a blocked
// member gets 403 MEMBER_BLOCKED), for the dashboard's sign-in check.
-2
View File
@@ -166,8 +166,6 @@ async fn seed_one(
let mut target =
compliance_core::models::OnboardedTarget::new(full_name.to_string(), demo.target_type);
target.description = demo.description.clone();
target.demo = true;
target.devices = demo.devices.clone();
for a in demo.artifacts.iter().filter(|a| !a.is_upload()) {
match a.resolved_source_ref() {
Some(source_ref) => target.artifacts.push(targets::reference_artifact(
-7
View File
@@ -47,11 +47,6 @@ pub enum AgentError {
#[error("not run: {0:?}")]
NotAdmitted(compliance_core::models::Refusal),
/// A new target the plan has no room for: as many targets are active
/// as it allows (the entry plan's `extra_targets: 0`).
#[error("the plan allows {0} active targets")]
TargetLimit(u32),
#[error("{0}")]
Other(String),
}
@@ -84,7 +79,6 @@ impl AgentError {
| Self::Secret(_)
| Self::Exec(_)
| Self::NotAdmitted(_)
| Self::TargetLimit(_)
| Self::Other(_) => (
RunErrorCode::Internal,
"the scan stopped because of an internal error",
@@ -97,7 +91,6 @@ impl From<AgentError> for axum::http::StatusCode {
fn from(err: AgentError) -> Self {
match err {
AgentError::Core(CoreError::NotFound(_)) => axum::http::StatusCode::NOT_FOUND,
AgentError::TargetLimit(_) => axum::http::StatusCode::CONFLICT,
_ => axum::http::StatusCode::INTERNAL_SERVER_ERROR,
}
}
-31
View File
@@ -117,10 +117,6 @@ pub struct DemoTarget {
/// Applied by the nightly harness to the fixtures it onboards itself.
#[serde(default)]
pub enabled_scans: Vec<String>,
/// Siemens controllers the target runs on (SPS item 4a), stored with the
/// target so its SBOM lists them and Siemens' advisories match them.
#[serde(default)]
pub devices: Vec<compliance_core::models::PlcDevice>,
/// Golden baseline for the nightly regression.
#[serde(default)]
pub expect: Expect,
@@ -495,32 +491,6 @@ mod tests {
assert_eq!(on_disk.name_prefix, bundled.name_prefix);
}
#[test]
fn demo_devices_are_stored_as_the_api_would_store_them() {
// Arrange
let m = manifest();
let pump = m
.targets
.iter()
.find(|t| t.key == "plc-pump-station")
.expect("pump station in the manifest");
// Assert: a controller on a firmware Siemens names as affected
// (SSA-876787: below V2.9.8), so the demo SBOM is not empty.
assert!(!pump.devices.is_empty());
for t in &m.targets {
for d in &t.devices {
let normalised = compliance_core::models::PlcDevice::new(
&d.order_number,
&d.firmware,
d.label.as_deref(),
)
.expect("a valid controller");
assert_eq!(&normalised, d, "{}: store it normalised", t.key);
}
}
}
#[test]
fn manifest_is_well_formed() {
let m = manifest();
@@ -619,7 +589,6 @@ mod tests {
optional: true,
}],
enabled_scans: Vec::new(),
devices: Vec::new(),
expect: Expect::default(),
};
assert!(t.source_only());
+2 -17
View File
@@ -467,10 +467,6 @@ pub enum Outcome {
Ignored(&'static str),
}
/// Why a delivery for a repository without a target makes none: the plan's
/// targets are all active (`extra_targets: 0`).
const NO_ROOM: &str = "the plan allows no further active target";
/// Carry out a routed delivery for `tenant_id`.
///
/// # Errors
@@ -489,10 +485,7 @@ pub async fn apply_action(
archive_target(db, &source.base_url, repo.id).await?,
)),
SourceAction::Created(repo) => {
let ensured = match ensure_target(agent, db, tenant_id, source, &repo).await {
Err(AgentError::TargetLimit(_)) => return Ok(Outcome::Ignored(NO_ROOM)),
ensured => ensured?,
};
let ensured = ensure_target(agent, db, tenant_id, source, &repo).await?;
// An empty repository has nothing to scan; its first push will.
let scan = ensured.created && !repo.empty;
if scan {
@@ -504,10 +497,7 @@ pub async fn apply_action(
})
}
SourceAction::Push(repo) => {
let ensured = match ensure_target(agent, db, tenant_id, source, &repo).await {
Err(AgentError::TargetLimit(_)) => return Ok(Outcome::Ignored(NO_ROOM)),
ensured => ensured?,
};
let ensured = ensure_target(agent, db, tenant_id, source, &repo).await?;
spawn_scan(agent, tenant_id, &ensured.target_id, ScanTrigger::Webhook);
Ok(Outcome::Ensured {
target_id: ensured.target_id,
@@ -618,11 +608,6 @@ pub async fn sync_with<L: RepoLister>(
}
}
Ok(_) => report.refreshed += 1,
// Not an error: the next sync tries again, once a target is
// archived or the plan changed.
Err(AgentError::TargetLimit(cap)) => {
tracing::info!(tenant_id, repo = %repo.full_name, cap, "managed git sync: no target, the plan's targets are all active");
}
Err(err) => {
tracing::warn!(tenant_id, repo = %repo.full_name, "managed git sync: {err}");
}
-49
View File
@@ -2,7 +2,6 @@
//!
//! **Included and extra targets.** The oldest active targets are included,
//! up to the plan's `included_targets`; every other active target is extra.
//! A plan that allows no extra target (the entry plan) includes them all.
//! The split is stored on each target ([`OnboardedTarget::billing`]) and
//! brought up to date before each scan and when a target is created, so
//! archiving an included target moves the oldest extra one up.
@@ -180,31 +179,10 @@ pub async fn swap(
pub struct Plan {
/// How many targets the plan includes; `None` is unlimited.
pub included_targets: Option<u32>,
/// How many extra targets may be active besides; `None` is unlimited.
pub extra_targets: Option<u32>,
/// The quota and the customer's Prüftag cap.
pub limits: PlanLimits,
}
impl Plan {
/// How many targets may be active at once: the included ones and the
/// extra ones the plan allows. `None` when either is unlimited, as on
/// every plan that bills extra targets.
pub fn target_cap(&self) -> Option<u32> {
Some(self.included_targets?.saturating_add(self.extra_targets?))
}
/// How many targets the billing split includes; `None` includes every
/// active target. A plan that allows no extra target bills none as
/// extra, not even those already active beyond its included ones.
pub fn billed_included(&self) -> Option<u32> {
match self.extra_targets {
Some(0) => None,
_ => self.included_targets,
}
}
}
/// The tenant's counted Prüfungen and booked Prüftage per month.
const MONTHS: &str = "metering_months";
/// Each target's Prüftag per day, once the quota was used up.
@@ -469,33 +447,6 @@ mod tests {
use super::*;
use chrono::TimeZone;
#[test]
fn only_a_plan_capping_both_counts_caps_the_active_targets() {
let plan = |included_targets, extra_targets| Plan {
included_targets,
extra_targets,
..Plan::default()
};
assert_eq!(plan(Some(3), Some(0)).target_cap(), Some(3), "entry");
assert_eq!(plan(Some(3), Some(2)).target_cap(), Some(5));
assert_eq!(plan(Some(5), None).target_cap(), None, "extras billed");
assert_eq!(plan(None, Some(0)).target_cap(), None, "all included");
assert_eq!(plan(Some(u32::MAX), Some(1)).target_cap(), Some(u32::MAX));
}
#[test]
fn a_plan_allowing_no_extra_target_bills_none_as_extra() {
let plan = |included_targets, extra_targets| Plan {
included_targets,
extra_targets,
limits: PlanLimits::default(),
};
assert_eq!(plan(Some(2), Some(0)).billed_included(), None, "entry");
assert_eq!(plan(Some(5), None).billed_included(), Some(5));
assert_eq!(plan(Some(5), Some(2)).billed_included(), Some(5));
assert_eq!(plan(None, None).billed_included(), None);
}
#[test]
fn a_swap_holds_until_the_berlin_month_ends() {
let at = |y, m, d, h| {
-309
View File
@@ -118,72 +118,6 @@ pub struct EntitlementCheck {
pub expires_at: Option<String>,
#[serde(default)]
pub reason: Option<String>,
/// The workspace's branding (tenant-registry#155); absent when there is
/// nothing to show.
#[serde(default)]
pub branding: Option<Branding>,
}
/// A workspace's branding as the registry derived or an admin set it
/// (tenant-registry#155): its CI colour, which frames every page, its logo,
/// and whether its admins have yet to acknowledge a derived one.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
pub struct Branding {
/// `#rrggbb`, or null.
#[serde(default)]
pub color: Option<String>,
/// The SHA-256 (hex) of the stored logo, or null when there is none.
#[serde(default)]
pub logo_etag: Option<String>,
/// Whether a derived branding waits for an admin's "Passt".
#[serde(default)]
pub notice: bool,
/// The domain it was derived from; present while `notice` is.
#[serde(default)]
pub domain: Option<String>,
/// The workspace's name, shown beside the logo.
#[serde(default)]
pub name: Option<String>,
}
impl Branding {
/// The frame colour as `#rrggbb` in lower case; anything else is no
/// frame, so a malformed value can never reach a style.
pub fn frame_color(&self) -> Option<String> {
let c = self.color.as_deref()?.trim();
let hex = c.strip_prefix('#')?;
(hex.len() == 6 && hex.bytes().all(|b| b.is_ascii_hexdigit()))
.then(|| c.to_ascii_lowercase())
}
/// The logo's ETag when it is a SHA-256 in hex; anything else is no logo.
pub fn logo_etag(&self) -> Option<&str> {
self.logo_etag
.as_deref()
.filter(|e| e.len() == 64 && e.bytes().all(|b| b.is_ascii_hexdigit()))
}
}
/// Why the registry did not record an admin's "Passt".
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AckRefusal {
/// The user is no IT admin or owner of the workspace (403 `not_admin`).
NotAdmin,
/// The registry could not be asked, or answered something else.
Failed(String),
}
/// The largest logo the agent takes from the registry, which stores 256 px
/// PNGs: far below this.
const MAX_LOGO_BYTES: usize = 1 << 20;
/// Whether `tenant_id` may stand in a registry path: the registry's ids are
/// UUIDs, so anything else is refused before a request is made.
fn path_safe(tenant_id: &str) -> bool {
!tenant_id.is_empty()
&& tenant_id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-')
}
impl EntitlementCheck {
@@ -200,13 +134,6 @@ impl EntitlementCheck {
self.limit("included_targets")
}
/// How many targets beyond the included ones the plan lets be active:
/// `limits.extra_targets` (`0` on the entry plan). `None` when the key is
/// missing or null: extra targets are allowed and billed.
pub fn extra_targets(&self) -> Option<u32> {
self.limit("extra_targets")
}
/// The plan's monthly quota and the customer's Prüftag cap (t72), from
/// `limits.monthly_pruefungen` and `limits.prueftag_cap`; a missing or
/// null key is no limit.
@@ -378,9 +305,6 @@ pub struct RegistryClient {
/// API-key verdicts, valid and invalid, keyed by the key's SHA-256 (never
/// the key itself), for [`API_KEY_TTL`].
api_keys: DashMap<String, (Instant, ApiKeyVerify)>,
/// Each tenant's logo with its ETag, kept until the registry names
/// another (tenant-registry#155).
logos: DashMap<String, (String, axum::body::Bytes)>,
}
impl std::fmt::Debug for RegistryClient {
@@ -424,7 +348,6 @@ impl RegistryClient {
cache: DashMap::new(),
projects: DashMap::new(),
api_keys: DashMap::new(),
logos: DashMap::new(),
}))
}
@@ -546,113 +469,6 @@ impl RegistryClient {
Ok(check)
}
/// The workspace's logo with the ETag `etag`, as a PNG, or `None` when
/// the registry has none. Kept per tenant and asked for again only when
/// the registry names another ETag; then with `If-None-Match`, so an
/// unchanged logo is not sent twice.
///
/// # Errors
///
/// When the registry cannot be asked or answers with something other
/// than a PNG of at most 1 MiB.
pub async fn branding_logo(
&self,
tenant_id: &str,
etag: &str,
) -> Result<Option<axum::body::Bytes>, String> {
let cached = self
.logos
.get(tenant_id)
.map(|hit| (hit.0.clone(), hit.1.clone()));
if let Some((tag, png)) = &cached {
if tag == etag {
return Ok(Some(png.clone()));
}
}
if !path_safe(tenant_id) {
return Err("tenant id not usable in a path".into());
}
let mut rb = self
.request(
reqwest::Method::GET,
&format!("/v1/tenants/{tenant_id}/branding/logo"),
)
.await?;
if let Some((tag, _)) = &cached {
rb = rb.header(reqwest::header::IF_NONE_MATCH, format!("\"{tag}\""));
}
let resp = rb
.send()
.await
.map_err(|e| format!("logo request failed: {e}"))?;
match resp.status() {
reqwest::StatusCode::NOT_MODIFIED => Ok(cached.map(|(_, png)| png)),
reqwest::StatusCode::NOT_FOUND => {
self.logos.remove(tenant_id);
Ok(None)
}
status if status.is_success() => {
let is_png = resp
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.starts_with("image/png"));
if !is_png {
return Err("logo is not a PNG".into());
}
let tag = resp
.headers()
.get(reqwest::header::ETAG)
.and_then(|v| v.to_str().ok())
.map(|v| v.trim_start_matches("W/").trim_matches('"').to_string())
.unwrap_or_else(|| etag.to_string());
let png = resp
.bytes()
.await
.map_err(|e| format!("logo not read: {e}"))?;
if png.len() > MAX_LOGO_BYTES {
return Err("logo larger than 1 MiB".into());
}
self.logos.insert(tenant_id.to_string(), (tag, png.clone()));
Ok(Some(png))
}
status => Err(format!("logo request returned {status}")),
}
}
/// Record an admin's "Passt" on the workspace's derived branding
/// (`POST /v1/tenants/{id}/branding/ack`) and drop the cached entitlement
/// answers, so the notice goes with the next check.
///
/// # Errors
///
/// [`AckRefusal::NotAdmin`] when the registry does not count `user_id` as
/// an IT admin or owner of the tenant; [`AckRefusal::Failed`] otherwise.
pub async fn ack_branding(&self, tenant_id: &str, user_id: &str) -> Result<(), AckRefusal> {
if !path_safe(tenant_id) {
return Err(AckRefusal::Failed("tenant id not usable in a path".into()));
}
let resp = self
.request(
reqwest::Method::POST,
&format!("/v1/tenants/{tenant_id}/branding/ack"),
)
.await
.map_err(AckRefusal::Failed)?
.json(&serde_json::json!({ "user_id": user_id }))
.send()
.await
.map_err(|e| AckRefusal::Failed(format!("ack failed: {e}")))?;
match resp.status() {
status if status.is_success() => {
self.invalidate(tenant_id);
Ok(())
}
reqwest::StatusCode::FORBIDDEN => Err(AckRefusal::NotAdmin),
status => Err(AckRefusal::Failed(format!("ack returned {status}"))),
}
}
/// Drop the cached answer for a tenant (after a platform lifecycle call).
pub fn invalidate(&self, tenant_id: &str) {
self.cache
@@ -1061,27 +877,6 @@ mod tests {
assert_eq!(check(serde_json::Value::Null).included_targets(), None);
}
#[test]
fn the_plan_may_allow_no_extra_targets() {
let check = |limits: serde_json::Value| -> EntitlementCheck {
serde_json::from_value(serde_json::json!({ "allowed": true, "limits": limits }))
.expect("an entitlement answer")
};
assert_eq!(
check(serde_json::json!({ "included_targets": 1, "extra_targets": 0 })).extra_targets(),
Some(0)
);
assert_eq!(
check(serde_json::json!({ "extra_targets": null })).extra_targets(),
None
);
assert_eq!(
check(serde_json::json!({ "included_targets": 5 })).extra_targets(),
None
);
}
#[test]
fn the_plan_sets_the_quota_and_the_cap() {
let check: EntitlementCheck = serde_json::from_value(serde_json::json!({
@@ -1140,7 +935,6 @@ mod tests {
cache: DashMap::new(),
projects: DashMap::new(),
api_keys: DashMap::new(),
logos: DashMap::new(),
};
let started = Instant::now();
@@ -1197,7 +991,6 @@ mod tests {
cache: DashMap::new(),
projects: DashMap::new(),
api_keys: DashMap::new(),
logos: DashMap::new(),
};
(client, calls, down)
}
@@ -1268,106 +1061,4 @@ mod tests {
assert!(client.api_keys.contains_key(&key_digest("bp_good")));
assert!(client.api_keys.iter().all(|e| !e.key().contains("bp_")));
}
/// A registry with one tenant's logo (ETag `"aa…"`, honouring
/// If-None-Match) and an ack endpoint that takes only `u-admin`; the
/// number of logo bodies it sent is counted.
async fn branding_registry() -> (RegistryClient, Arc<std::sync::atomic::AtomicUsize>) {
use std::sync::atomic::{AtomicUsize, Ordering};
let sent = Arc::new(AtomicUsize::new(0));
let s = sent.clone();
let tag = "a".repeat(64);
let quoted = format!("\"{tag}\"");
let app = axum::Router::new()
.route(
"/v1/tenants/{id}/branding/logo",
axum::routing::get(
move |axum::extract::Path(id): axum::extract::Path<String>,
headers: axum::http::HeaderMap| {
let (s, quoted) = (s.clone(), quoted.clone());
async move {
use axum::response::IntoResponse;
if id != "t-1" {
return axum::http::StatusCode::NOT_FOUND.into_response();
}
if headers.get("if-none-match").and_then(|v| v.to_str().ok())
== Some(quoted.as_str())
{
return axum::http::StatusCode::NOT_MODIFIED.into_response();
}
s.fetch_add(1, Ordering::SeqCst);
(
[("content-type", "image/png"), ("etag", quoted.as_str())],
b"\x89PNG fake".to_vec(),
)
.into_response()
}
},
),
)
.route(
"/v1/tenants/{id}/branding/ack",
axum::routing::post(
|axum::Json(body): axum::Json<serde_json::Value>| async move {
if body["user_id"] == "u-admin" {
axum::http::StatusCode::NO_CONTENT
} else {
axum::http::StatusCode::FORBIDDEN
}
},
),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let client = RegistryClient {
base_url: format!("http://{addr}"),
product: "pruefwerk".into(),
http: reqwest::Client::new(),
token_url: None,
client_id: None,
client_secret: None,
token: Mutex::new(None),
cache: DashMap::new(),
projects: DashMap::new(),
api_keys: DashMap::new(),
logos: DashMap::new(),
};
(client, sent)
}
#[tokio::test]
async fn a_logo_is_fetched_once_per_etag_and_none_is_none() {
use std::sync::atomic::Ordering;
// Arrange
let (client, sent) = branding_registry().await;
let tag = "a".repeat(64);
// Act: twice with the same ETag, then with another one.
let first = client.branding_logo("t-1", &tag).await.unwrap();
let again = client.branding_logo("t-1", &tag).await.unwrap();
let other = client.branding_logo("t-1", &"b".repeat(64)).await.unwrap();
// Assert: one body sent; the other ETag was answered 304 from the
// cached PNG; a tenant without a logo has none.
assert_eq!(first.as_deref(), Some(&b"\x89PNG fake"[..]));
assert_eq!(again, first);
assert_eq!(other, first);
assert_eq!(sent.load(Ordering::SeqCst), 1);
assert_eq!(client.branding_logo("t-2", &tag).await.unwrap(), None);
assert!(
client.branding_logo("../x", &tag).await.is_err(),
"no path from an id"
);
}
#[tokio::test]
async fn only_an_admin_the_registry_knows_acknowledges() {
let (client, _) = branding_registry().await;
assert_eq!(client.ack_branding("t-1", "u-admin").await, Ok(()));
assert_eq!(
client.ack_branding("t-1", "u-member").await,
Err(AckRefusal::NotAdmin)
);
}
}
+8 -106
View File
@@ -16,101 +16,24 @@ use crate::classify::{classify_target, MockFirmwareDetector};
use crate::database::Database;
use crate::error::AgentError;
/// Whether one more counted target fits under `cap`: the active targets
/// other than demo ones are fewer.
///
/// # Errors
///
/// [`AgentError::TargetLimit`] when they are not; a database error.
async fn room_for_one(db: &Database, cap: u32) -> Result<(), AgentError> {
let counted = db
.onboarded_targets()
.count_documents(doc! { "archived_at": null, "demo": { "$ne": true } })
.await?;
if counted >= u64::from(cap) {
return Err(AgentError::TargetLimit(cap));
}
Ok(())
}
/// Make a demo target the tenant's own before its artifacts change: from
/// then on it counts under the plan's cap like any other target. Without
/// that, a demo target pointed at the tenant's own code would sit outside
/// the cap. A target that is not a demo one is left as it is, and an
/// archived one is not checked against the cap (it does not count yet).
///
/// # Errors
///
/// [`AgentError::TargetLimit`] when the plan has no room for one more
/// counted target; the target then stays a demo one. A database error.
pub async fn claim_demo(
agent: &ComplianceAgent,
db: &Database,
tenant_id: &str,
target: &OnboardedTarget,
) -> Result<(), AgentError> {
let Some(id) = target.id.filter(|_| target.demo) else {
return Ok(());
};
if target.archived_at.is_none() {
if let Some(cap) = agent.plan(tenant_id).await.and_then(|p| p.target_cap()) {
room_for_one(db, cap).await?;
}
}
db.onboarded_targets()
.update_one(doc! { "_id": id }, doc! { "$unset": { "demo": "" } })
.await?;
Ok(())
}
/// Whether two artifact lists point at the same sources: the same kinds and
/// references, in any order. Credentials, branches and scan state may
/// differ; the dashboard's editor sends every artifact on each save.
pub fn same_sources(a: &[Artifact], b: &[Artifact]) -> bool {
let mut taken = vec![false; b.len()];
a.len() == b.len()
&& a.iter().all(|x| {
let found = (0..b.len())
.find(|&i| !taken[i] && b[i].kind == x.kind && b[i].source_ref == x.source_ref);
found.map(|i| taken[i] = true).is_some()
})
}
/// Insert a new target for `tenant_id` and emit the `target.added` usage
/// event: what every way of adding a target does (the API, accepting a
/// supplier's SBOM release, Managed Git, the demo seeder), so each counts
/// the same under the plan. Returns the stored record with its id set.
///
/// # Errors
///
/// [`AgentError::TargetLimit`] when the plan has no room for another active
/// target (the entry plan's `extra_targets: 0`); demo targets are outside
/// that count. A database error.
/// event. Returns the stored record with its id set.
pub async fn create_target(
agent: &ComplianceAgent,
db: &Database,
tenant_id: &str,
mut target: OnboardedTarget,
) -> Result<OnboardedTarget, AgentError> {
// The plan is read once for the cap and the billing. Without an answer
// from the registry the target is added, as a scan then runs unmetered.
let plan = agent.plan(tenant_id).await;
// Demo targets are outside the cap: neither refused nor counted.
if let Some(cap) = plan.and_then(|p| p.target_cap()).filter(|_| !target.demo) {
room_for_one(db, cap).await?;
}
let res = db.onboarded_targets().insert_one(&target).await?;
target.id = res.inserted_id.as_object_id();
// A target beyond the plan's included ones is extra from the start (t72).
if let Some(plan) = plan {
if let Some((_, billing)) = agent
.assign_billing(tenant_id, db, plan.billed_included())
.await
.into_iter()
.find(|(id, _)| Some(*id) == target.id)
{
target.billing = billing;
}
if let Some((_, billing)) = agent
.refresh_billing(tenant_id, db)
.await
.into_iter()
.find(|(id, _)| Some(*id) == target.id)
{
target.billing = billing;
}
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
agent.emit_usage(
@@ -277,27 +200,6 @@ pub async fn detect_target(
mod tests {
use super::*;
#[test]
fn only_another_source_changes_a_targets_sources() {
let repo = Artifact::git_repo("https://git.example/demo.git", "main");
let site = Artifact::live_url("https://demo.example");
let other_branch = Artifact::git_repo("https://git.example/demo.git", "dev");
let own = Artifact::git_repo("https://git.example/own.git", "main");
let both = [repo.clone(), site.clone()];
let reordered = [site, repo.clone()];
let just_repo = std::slice::from_ref(&repo);
let repo_twice = [repo.clone(), repo.clone()];
assert!(same_sources(&both, &reordered));
assert!(
same_sources(just_repo, &[other_branch]),
"a branch is no new source"
);
assert!(!same_sources(just_repo, &[own]));
assert!(!same_sources(just_repo, &both));
assert!(!same_sources(&repo_twice, just_repo));
}
#[test]
fn uploaded_artifact_records_stored_path_for_file_kinds() {
let a = uploaded_artifact(
-1
View File
@@ -285,7 +285,6 @@ async fn seed_nightly(
"target_type": t.target_type,
"description": t.description,
"artifacts": references,
"devices": t.devices,
}),
)
.await;
-356
View File
@@ -1,356 +0,0 @@
//! The entry plan's target cap against a fake tenant registry: with
//! `extra_targets: 0` a new target is refused (409 `target_limit`) once the
//! included ones are all active, archiving one frees its place, targets
//! already beyond it are never billed as extra, demo targets are outside the
//! cap until they are given the tenant's own sources, and a plan without
//! the key keeps adding extra targets as before.
//! Needs a live Mongo for the agent itself; skips cleanly without one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
mod common;
use std::sync::Arc;
use axum::body::Body;
use axum::extract::Request;
use axum::http::StatusCode;
use axum::middleware::{from_fn, Next};
use axum::routing::{patch, post};
use axum::{Extension, Json, Router};
use mongodb::bson::doc;
use tower::ServiceExt;
use compliance_agent::agent::ComplianceAgent;
use compliance_agent::api::handlers::onboarding::{create_target, update_target};
use compliance_agent::database::DatabasePool;
use compliance_core::models::{OnboardedTarget, TargetBilling, TargetType};
use compliance_core::{OrgRole, TenantContext, TenantStatus};
use common::dev_config;
/// A registry where `t-entry` includes two targets and allows no extra one,
/// and `t-standard` includes one and bills the others.
async fn fake_registry() -> String {
let app = Router::new().route(
"/v1/internal/entitlements/check",
post(|Json(body): Json<serde_json::Value>| async move {
let limits = match body["tenant_id"].as_str() {
Some("t-entry") => serde_json::json!({ "included_targets": 2, "extra_targets": 0 }),
_ => serde_json::json!({ "included_targets": 1 }),
};
Json(serde_json::json!({ "allowed": true, "status": "active", "limits": limits }))
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.ok() });
format!("http://{addr}")
}
/// An agent whose registry is `registry`, or `None` without Mongo.
async fn agent(registry: &str) -> Option<Arc<ComplianceAgent>> {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db_name = format!("cap_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
let Ok(pool) = DatabasePool::connect(&uri, &db_name).await else {
eprintln!("SKIP target_limit: no MongoDB reachable at {uri}");
return None;
};
let mut config = dev_config(uri, db_name);
config.tenant_registry_url = Some(registry.to_string());
Some(Arc::new(ComplianceAgent::new(config, pool)))
}
fn member(tenant: &str) -> TenantContext {
TenantContext {
tenant_id: tenant.into(),
tenant_slug: "acme".into(),
org_roles: vec![OrgRole::ItAdmin],
products: vec!["compliance-scanner".into()],
plan: "entry".into(),
status: TenantStatus::Active,
user_id: "u-1".into(),
user_name: None,
staff: None,
api_key: None,
}
}
/// `POST /api/v1/targets` named `name` as a member of `tenant`.
async fn add(
agent: &Arc<ComplianceAgent>,
tenant: &str,
name: &str,
) -> (StatusCode, serde_json::Value) {
let ctx = member(tenant);
let inject = move |mut req: Request, next: Next| {
let ctx = ctx.clone();
async move {
req.extensions_mut().insert(ctx);
next.run(req).await
}
};
let app = Router::new()
.route("/api/v1/targets", post(create_target))
.layer(Extension(agent.clone()))
.layer(from_fn(inject));
let body = serde_json::json!({ "name": name, "target_type": "web_app" });
let resp = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/v1/targets")
.header("content-type", "application/json")
.body(Body::from(body.to_string()))
.unwrap(),
)
.await
.unwrap();
let status = resp.status();
let bytes = axum::body::to_bytes(resp.into_body(), 1 << 16)
.await
.unwrap();
(status, serde_json::from_slice(&bytes).unwrap_or_default())
}
#[tokio::test]
async fn the_entry_plan_refuses_a_target_beyond_its_included_ones() {
let registry = fake_registry().await;
let Some(agent) = agent(&registry).await else {
return;
};
// Arrange: both included places taken.
assert_eq!(
add(&agent, "t-entry", "Steuerung A").await.0,
StatusCode::OK
);
assert_eq!(
add(&agent, "t-entry", "Steuerung B").await.0,
StatusCode::OK
);
// Act + Assert: the third is refused and not stored.
let (status, body) = add(&agent, "t-entry", "Steuerung C").await;
assert_eq!(status, StatusCode::CONFLICT);
assert_eq!(body["error"], "target_limit");
let db = agent.db_pool.for_tenant_id("t-entry").await.unwrap();
assert_eq!(
db.onboarded_targets()
.count_documents(doc! { "name": "Steuerung C" })
.await
.unwrap(),
0
);
// Archiving one frees its place.
db.onboarded_targets()
.update_one(
doc! { "name": "Steuerung A" },
doc! { "$set": { "archived_at": mongodb::bson::DateTime::now() } },
)
.await
.unwrap();
let (status, body) = add(&agent, "t-entry", "Steuerung C").await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body["data"]["billing"], "included");
}
#[tokio::test]
async fn a_plan_without_the_key_adds_extra_targets_as_before() {
let registry = fake_registry().await;
let Some(agent) = agent(&registry).await else {
return;
};
assert_eq!(
add(&agent, "t-standard", "Anlage 1").await.0,
StatusCode::OK
);
let (status, body) = add(&agent, "t-standard", "Anlage 2").await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body["data"]["billing"], "extra");
}
#[tokio::test]
async fn targets_already_beyond_the_entry_plan_are_never_billed_extra() {
let registry = fake_registry().await;
let Some(agent) = agent(&registry).await else {
return;
};
// Arrange: three active targets from before the plan, one billed extra.
let db = agent.db_pool.for_tenant_id("t-entry").await.unwrap();
for (name, billing) in [
("Anlage 1", TargetBilling::Included),
("Anlage 2", TargetBilling::Included),
("Anlage 3", TargetBilling::Extra),
] {
let mut target = OnboardedTarget::new(name.into(), TargetType::WebApp);
target.billing = billing;
db.onboarded_targets().insert_one(&target).await.unwrap();
}
// Act
agent.refresh_billing("t-entry", &db).await;
// Assert: all three stay, none is extra, and a fourth is refused.
let extra = mongodb::bson::to_bson(&TargetBilling::Extra).unwrap();
assert_eq!(
db.onboarded_targets()
.count_documents(doc! { "billing": extra })
.await
.unwrap(),
0
);
assert_eq!(
db.onboarded_targets()
.count_documents(doc! {})
.await
.unwrap(),
3
);
assert_eq!(
add(&agent, "t-entry", "Anlage 4").await.0,
StatusCode::CONFLICT
);
}
#[tokio::test]
async fn demo_targets_are_neither_counted_nor_refused() {
let registry = fake_registry().await;
let Some(agent) = agent(&registry).await else {
return;
};
let db = agent.db_pool.for_tenant_id("t-entry").await.unwrap();
let demo = |name: &str| {
let mut target = OnboardedTarget::new(name.into(), TargetType::WebApp);
target.demo = true;
target
};
// A demo target leaves both included places free.
compliance_agent::targets::create_target(&agent, &db, "t-entry", demo("Demo A"))
.await
.expect("demo target added");
assert_eq!(
add(&agent, "t-entry", "Steuerung A").await.0,
StatusCode::OK
);
assert_eq!(
add(&agent, "t-entry", "Steuerung B").await.0,
StatusCode::OK
);
assert_eq!(
add(&agent, "t-entry", "Steuerung C").await.0,
StatusCode::CONFLICT
);
// With the places taken, the seeder still adds its targets.
compliance_agent::targets::create_target(&agent, &db, "t-entry", demo("Demo B"))
.await
.expect("demo target added at the cap");
}
/// `PATCH /api/v1/targets/{id}` with `body` as a member of `tenant`.
async fn edit(
agent: &Arc<ComplianceAgent>,
tenant: &str,
id: &str,
body: serde_json::Value,
) -> (StatusCode, serde_json::Value) {
let ctx = member(tenant);
let inject = move |mut req: Request, next: Next| {
let ctx = ctx.clone();
async move {
req.extensions_mut().insert(ctx);
next.run(req).await
}
};
let app = Router::new()
.route("/api/v1/targets/{id}", patch(update_target))
.layer(Extension(agent.clone()))
.layer(from_fn(inject));
let resp = app
.oneshot(
Request::builder()
.method("PATCH")
.uri(format!("/api/v1/targets/{id}"))
.header("content-type", "application/json")
.body(Body::from(body.to_string()))
.unwrap(),
)
.await
.unwrap();
let status = resp.status();
let bytes = axum::body::to_bytes(resp.into_body(), 1 << 16)
.await
.unwrap();
(status, serde_json::from_slice(&bytes).unwrap_or_default())
}
#[tokio::test]
async fn a_demo_target_given_the_tenants_own_sources_counts() {
let registry = fake_registry().await;
let Some(agent) = agent(&registry).await else {
return;
};
let db = agent.db_pool.for_tenant_id("t-entry").await.unwrap();
let mut demo = OnboardedTarget::new("Demo · Pumpe".into(), TargetType::WebApp);
demo.demo = true;
demo.artifacts
.push(compliance_core::models::Artifact::live_url(
"https://demo.example",
));
let demo = compliance_agent::targets::create_target(&agent, &db, "t-entry", demo)
.await
.unwrap();
let id = demo.id.unwrap().to_hex();
assert_eq!(
add(&agent, "t-entry", "Steuerung A").await.0,
StatusCode::OK
);
assert_eq!(
add(&agent, "t-entry", "Steuerung B").await.0,
StatusCode::OK
);
let is_demo = || async {
db.onboarded_targets()
.find_one(doc! { "_id": demo.id.unwrap() })
.await
.unwrap()
.unwrap()
.demo
};
let own = serde_json::json!({ "artifacts": [
{ "kind": "git_repo", "source_ref": "https://git.example/own.git", "branch": "main" }
] });
// A new name and the same sources keep it a demo target.
let same = serde_json::json!({ "name": "Pumpe", "artifacts": [
{ "kind": "live_url", "source_ref": "https://demo.example" }
] });
assert_eq!(edit(&agent, "t-entry", &id, same).await.0, StatusCode::OK);
assert!(is_demo().await);
// Act + Assert: the tenant's own sources need a place, and none is free.
let (status, body) = edit(&agent, "t-entry", &id, own.clone()).await;
assert_eq!(status, StatusCode::CONFLICT);
assert_eq!(body["error"], "target_limit");
assert!(is_demo().await, "refused: still a demo target");
// With a place free, it becomes the tenant's own and takes that place.
db.onboarded_targets()
.update_one(
doc! { "name": "Steuerung A" },
doc! { "$set": { "archived_at": mongodb::bson::DateTime::now() } },
)
.await
.unwrap();
assert_eq!(edit(&agent, "t-entry", &id, own).await.0, StatusCode::OK);
assert!(!is_demo().await);
assert_eq!(
add(&agent, "t-entry", "Steuerung C").await.0,
StatusCode::CONFLICT
);
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-core"
version = "0.4.19"
version = "0.4.18"
edition = "2021"
[lints]
-5
View File
@@ -708,10 +708,6 @@ pub struct OnboardedTarget {
/// order number and firmware against Siemens' CSAF advisories.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub devices: Vec<super::PlcDevice>,
/// Whether the demo seeder added the target: a plan's cap on active
/// targets neither counts nor refuses it. Not settable through the API.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub demo: bool,
/// Creation timestamp.
#[serde(
default = "chrono::Utc::now",
@@ -775,7 +771,6 @@ impl OnboardedTarget {
included_until: None,
supplier: None,
devices: Vec::new(),
demo: false,
created_at: now,
updated_at: now,
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-dashboard"
version = "0.4.19"
version = "0.4.18"
edition = "2021"
default-run = "compliance-dashboard"
-94
View File
@@ -369,100 +369,6 @@ code {
text-transform: uppercase;
}
/* The workspace's branding (tenant-registry#155): its CI colour frames every
page and its logo stands in for the wordmark. The frame never takes a
click, and our own colours (accent, severities) never change with it. */
.brand-frame {
position: fixed;
inset: 0;
border: 6px solid var(--brand-frame);
pointer-events: none;
z-index: 80;
}
.customer-logo,
.customer-initials {
width: 28px;
height: 28px;
border-radius: var(--radius);
flex-shrink: 0;
}
.customer-logo {
object-fit: contain;
}
.customer-initials {
display: flex;
align-items: center;
justify-content: center;
background: var(--brand-frame, var(--bg-elevated));
font-weight: 700;
font-size: 12px;
}
.brand-name.customer-name {
font-weight: 600;
letter-spacing: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.brand-credit {
padding: 8px 14px 0;
font-size: 11px;
color: var(--text-tertiary);
text-align: center;
}
.branding-notice {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px 16px;
padding: 12px 16px;
margin-bottom: 16px;
/* Clear of the notification bell, fixed at the top right. */
margin-right: 56px;
border-radius: var(--radius-lg);
background: var(--bg-card);
border: 1px solid var(--border);
}
@media (max-width: 768px) {
/* The bell sits in the top bar there. */
.branding-notice {
margin-right: 0;
}
}
.branding-notice .customer-logo,
.branding-notice .customer-initials {
width: 32px;
height: 32px;
}
.branding-notice-text {
flex: 1 1 280px;
display: flex;
flex-direction: column;
gap: 2px;
font-size: 13px;
color: var(--text-secondary);
}
.branding-notice-text strong {
font-size: 14px;
font-weight: 600;
color: var(--text-primary);
}
.branding-notice-actions {
display: flex;
gap: 8px;
}
.sidebar-nav {
padding: 8px 8px 16px;
flex: 1;
@@ -1,7 +1,6 @@
use dioxus::prelude::*;
use crate::app::Route;
use crate::components::branding::BrandingNotice;
use crate::components::help_chat::HelpChat;
use crate::components::no_access::{NoAccess, ReadOnlyBanner};
use crate::components::notification_bell::NotificationBell;
@@ -26,13 +25,8 @@ pub fn AppShell() -> Element {
// then takes it away; an unreachable agent reads as the full set.
let platform = use_server_future(fetch_platform_info)?;
let auth = use_server_future(check_auth)?;
// The workspace's branding (tenant-registry#155), read with the page so
// the frame never appears a moment late; none when it cannot be read.
let branding = use_server_future(crate::infrastructure::branding::fetch_branding)?;
let platform_now = platform().and_then(Result::ok).unwrap_or_default();
use_context_provider(|| Signal::new(platform_now));
let branding_now = branding().and_then(Result::ok).unwrap_or_default();
use_context_provider(|| Signal::new(branding_now.clone()));
// A sign-in can run out while a page stays open: check now and then, and
// send the browser to the login rather than letting every page fail.
use_future(move || async move {
@@ -74,19 +68,8 @@ pub fn AppShell() -> Element {
Some(Ok(info)) if info.authenticated => {
use_context_provider(|| Signal::new(info.clone()));
let read_only = !info.access.can_write();
let shell_class = if branding_now.framed() {
"app-shell branded"
} else {
"app-shell"
};
let frame_style = branding_now.frame_style();
rsx! {
div { class: "{shell_class}", style: "{frame_style}",
// The workspace's CI colour around every page; it never
// takes a click.
if branding_now.framed() {
div { class: "brand-frame", "aria-hidden": "true" }
}
div { class: "app-shell",
Sidebar {}
main { class: "main-content",
if let Some(tenant) = info.support_tenant.clone() {
@@ -95,7 +78,6 @@ pub fn AppShell() -> Element {
if read_only {
ReadOnlyBanner {}
}
BrandingNotice {}
Outlet::<Route> {}
}
NotificationBell {}
@@ -1,95 +0,0 @@
//! The workspace's branding in the app (tenant-registry#155): its mark in the
//! sidebar and the one-time notice for its admins. The frame itself is the
//! app shell's.
use dioxus::prelude::*;
use crate::i18n::texts::branding as tx;
use crate::i18n::use_lang;
use crate::infrastructure::branding::{ack_branding, Branding, LOGO_URL};
use compliance_core::models::AuthInfo;
/// The workspace's branding, provided by the app shell; none outside it.
pub fn use_branding() -> Branding {
try_use_context::<Signal<Branding>>()
.map(|b| b.read().clone())
.unwrap_or_default()
}
/// The workspace in the sidebar: its logo, or its initials on its CI colour,
/// and unless `with_name` is off its name with "Prüfwerk" beneath.
#[component]
pub fn CustomerMark(branding: Branding, with_name: bool) -> Element {
let lang = use_lang()();
let initials = branding.initials();
let ink = branding.ink();
let name = branding.name.clone().unwrap_or_default();
rsx! {
if branding.logo {
img { class: "customer-logo", src: LOGO_URL, alt: "" }
} else {
span {
class: "customer-initials",
style: "color: {ink};",
"aria-hidden": "true",
"{initials}"
}
}
if with_name {
div { class: "brand-text",
if name.is_empty() {
span { class: "brand-name", {tx::PRODUCT.get(lang)} }
} else {
span { class: "brand-name customer-name", "{name}" }
span { class: "brand-sub", {tx::PRODUCT.get(lang)} }
}
}
}
}
}
/// "Logo und Farbe von <domain> übernommen", for the workspace's admins only
/// (the agent sends `notice` to no one else), until one of them says "Passt".
/// "Passt" hides it at once; the registry records it in the background.
#[component]
pub fn BrandingNotice() -> Element {
let lang = use_lang()();
let branding = use_branding();
let mut hidden = use_signal(|| false);
let portal_url = try_use_context::<Signal<AuthInfo>>()
.map(|a| a.read().portal_url.clone())
.unwrap_or_default();
let Some(domain) = branding.domain.clone().filter(|_| branding.notice) else {
return rsx! {};
};
if hidden() {
return rsx! {};
}
rsx! {
div { class: "branding-notice", role: "status",
CustomerMark { branding: branding.clone(), with_name: false }
div { class: "branding-notice-text",
strong { {tx::notice_title(&domain, lang)} }
span { {tx::NOTICE_BODY.get(lang)} }
}
div { class: "branding-notice-actions",
button {
r#type: "button",
class: "btn btn-primary",
onclick: move |_| {
hidden.set(true);
spawn(async move {
if let Err(e) = ack_branding().await {
tracing::warn!("branding ack failed: {e}");
}
});
},
{tx::OK.get(lang)}
}
if !portal_url.is_empty() {
a { class: "btn btn-secondary", href: "{portal_url}", {tx::CHANGE.get(lang)} }
}
}
}
}
}
@@ -2,7 +2,6 @@ pub mod app_shell;
pub mod artifact_upload;
pub mod attack_chain;
pub mod billing_swap;
pub mod branding;
pub mod code_inspector;
pub mod code_snippet;
pub mod component_overview;
+2 -17
View File
@@ -4,7 +4,6 @@ use dioxus_free_icons::icons::bs_icons::*;
use dioxus_free_icons::Icon;
use crate::app::Route;
use crate::components::branding::{use_branding, CustomerMark};
use crate::components::lang_toggle::LangToggle;
use crate::components::no_access::use_can_write;
use crate::components::theme_toggle::ThemeToggle;
@@ -40,7 +39,6 @@ pub fn Sidebar() -> Element {
let mut collapsed = use_signal(|| false);
let source_only = use_source_only();
let lang = use_lang()();
let branding = use_branding();
let can_write = use_can_write();
// Open supplier offers, counted on "Prüfobjekte" (#1028).
@@ -154,13 +152,7 @@ pub fn Sidebar() -> Element {
Icon { icon: BsList, width: 20, height: 20 }
}
}
div { class: "mobile-bar-brand",
if branding.branded() {
CustomerMark { branding: branding.clone(), with_name: true }
} else {
Wordmark { with_name: true }
}
}
div { class: "mobile-bar-brand", Wordmark { with_name: true } }
}
if mobile_open() {
div { class: "mobile-backdrop", onclick: move |_| mobile_open.set(false) }
@@ -169,11 +161,7 @@ pub fn Sidebar() -> Element {
// The breakpilot brand, as the portal shows it; Prüfwerk is the
// product within it.
div { class: "sidebar-header",
if branding.branded() {
CustomerMark { branding: branding.clone(), with_name: !collapsed() }
} else {
Wordmark { with_name: !collapsed() }
}
Wordmark { with_name: !collapsed() }
}
if !portal_url.is_empty() {
a {
@@ -308,9 +296,6 @@ pub fn Sidebar() -> Element {
}
}
}
if !collapsed() && branding.branded() {
div { class: "brand-credit", {crate::i18n::texts::branding::CREDIT.get(lang)} }
}
if !collapsed() {
div { class: "sidebar-legal",
a { href: PRIVACY_URL, target: "_blank", rel: "noopener", {nav::PRIVACY.get(lang)} }
+1 -101
View File
@@ -3169,26 +3169,6 @@ pub mod sbom {
requirements.txt; for JavaScript, npm install writes package-lock.json; for Rust, \
commit Cargo.lock. After the next scan the components are listed here.",
};
/// Why a PLC target's component table is empty.
pub const EMPTY_WHY_PLC: Text = Text {
de: "Bei einer SPS-Anwendung entsteht die Stückliste aus den Bibliotheken und der \
Laufzeit eines CODESYS-Projektarchivs (.projectarchive) und aus den \
Siemens-Steuerungen, die auf der Seite „Steuerungen“ des Prüfobjekts eingetragen \
sind. Structured Text und PLCopen XML allein nennen keine Komponenten.",
en: "For a PLC application the SBOM is built from the libraries and runtime in a \
CODESYS project archive (.projectarchive) and from the Siemens controllers \
entered on the target's Controllers page. Structured Text and PLCopen XML alone \
name no components.",
};
/// How to fill a PLC target's component table, by example.
pub const EMPTY_EXAMPLE_PLC: Text = Text {
de: "Zum Beispiel: Tragen Sie auf der Seite „Steuerungen“ die CPU mit Artikelnummer \
und Firmware ein (etwa 6ES7511-1AK02-0AB0, V2.9.4), oder laden Sie das \
CODESYS-Projektarchiv hoch. Nach der nächsten Prüfung stehen die Komponenten hier.",
en: "For example: enter the CPU with its order number and firmware on the Controllers \
page (such as 6ES7511-1AK02-0AB0, V2.9.4), or upload the CODESYS project archive. \
After the next scan the components are listed here.",
};
/// Above the open findings that say what is missing.
pub const EMPTY_FINDINGS: Text = Text {
de: "Was in diesem Prüfobjekt fehlt und wie Sie es ergänzen:",
@@ -5803,42 +5783,6 @@ pub mod metering {
}
/// "1 zusätzliches Prüfobjekt", or that every target is included.
/// The plan's refusal of a new target (`target_limit`): its places are
/// all taken.
pub const TARGET_LIMIT: Text = Text {
de: "Ihr Tarif enthält keine weiteren Prüfobjekte. Löschen Sie ein Prüfobjekt, \
um ein neues anzulegen (seine Ergebnisse werden mit gelöscht), oder wechseln \
Sie den Tarif.",
en: "Your plan includes no further targets. Delete a target to add a new one \
(its results are deleted with it), or change your plan.",
};
/// The plan's refusal to make a demo target the tenant's own
/// (`target_limit`): other sources would make it count, and its places
/// are all taken.
pub const DEMO_LIMIT: Text = Text {
de: "Mit eigenen Dateien oder Quellen zählt ein Demo-Prüfobjekt wie Ihre anderen, \
und Ihr Tarif enthält keine weiteren Prüfobjekte. Löschen Sie ein anderes \
Prüfobjekt (seine Ergebnisse werden mit gelöscht) oder wechseln Sie den Tarif.",
en: "With your own files or sources a demo target counts like your other targets, \
and your plan includes no further targets. Delete another target (its results \
are deleted with it) or change your plan.",
};
/// A failed creation of a target in words: the plan's refusal as
/// [`TARGET_LIMIT`], anything else as it came.
pub fn target_refusal(error: &str, lang: Lang) -> String {
plan_refusal(error, &TARGET_LIMIT, lang)
}
/// A failed change of a target's artifacts in words: the plan's refusal
/// as [`DEMO_LIMIT`], anything else as it came.
pub fn demo_refusal(error: &str, lang: Lang) -> String {
plan_refusal(error, &DEMO_LIMIT, lang)
}
fn plan_refusal(error: &str, text: &Text, lang: Lang) -> String {
match crate::i18n::agent_code(error, &["target_limit"]) {
Some(_) => text.get(lang).to_string(),
None => error.to_string(),
}
}
pub fn extra_targets(extra: u32, lang: Lang) -> String {
match (lang, extra) {
(Lang::De, 0) => "Alle Prüfobjekte im Tarif enthalten".to_string(),
@@ -8895,12 +8839,11 @@ pub mod offers {
/// The agent's refusal `error` in words; anything else as it came.
pub fn refusal(error: &str, lang: Lang) -> String {
const CODES: [&str; 5] = [
const CODES: [&str; 4] = [
"answered",
"ended",
"target_taken",
"not_supplier_component",
"target_limit",
];
let text = match crate::i18n::agent_code(error, &CODES) {
Some("answered") => Text {
@@ -8920,7 +8863,6 @@ pub mod offers {
de: "Nur eine zugekaufte Komponente kann eine SBOM eines Zulieferers erhalten.",
en: "Only a bought-in component can receive a supplier's SBOM.",
},
Some("target_limit") => super::metering::TARGET_LIMIT,
_ => return error.to_string(),
};
text.get(lang).to_string()
@@ -9205,45 +9147,3 @@ pub mod devices {
}
}
}
/// The workspace's branding (tenant-registry#155): the sidebar's credit line
/// and the one-time notice for its admins.
pub mod branding {
use super::Text;
use crate::i18n::Lang;
/// Under the workspace's name in the sidebar.
pub const PRODUCT: Text = Text {
de: "Prüfwerk",
en: "Prüfwerk",
};
/// At the foot of a branded sidebar: whose product it is.
pub const CREDIT: Text = Text {
de: "Prüfwerk von Breakpilot",
en: "Prüfwerk by Breakpilot",
};
/// Who sees the notice, and where to change the branding.
pub const NOTICE_BODY: Text = Text {
de: "Nur Administrator:innen sehen diesen Hinweis. Ändern können Sie beides im Portal \
unter Erscheinungsbild.",
en: "Only admins see this notice. You can change both in the portal under Appearance.",
};
/// Acknowledges the branding.
pub const OK: Text = Text {
de: "Passt",
en: "Looks right",
};
/// Opens the portal to change it.
pub const CHANGE: Text = Text {
de: "Ändern",
en: "Change",
};
/// The notice's title: where logo and colour were taken from.
pub fn notice_title(domain: &str, lang: Lang) -> String {
match lang {
Lang::De => format!("Logo und Farbe von {domain} übernommen"),
Lang::En => format!("Logo and colour taken from {domain}"),
}
}
}
@@ -1,195 +0,0 @@
//! The workspace's branding (tenant-registry#155): its CI colour framing
//! every page, its logo in the sidebar, and the one-time notice for its
//! admins. Proxies the agent's `/api/v1/branding*`.
use dioxus::prelude::*;
use serde::{Deserialize, Serialize};
/// The branding as the agent reports it; all empty means none.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Branding {
/// The frame colour, `#rrggbb`; none means no frame.
#[serde(default)]
pub color: Option<String>,
/// Whether [`LOGO_URL`] has a logo.
#[serde(default)]
pub logo: bool,
/// The workspace's name, beside the logo.
#[serde(default)]
pub name: Option<String>,
/// Whether to show this admin the notice.
#[serde(default)]
pub notice: bool,
/// The domain the branding was taken from.
#[serde(default)]
pub domain: Option<String>,
}
impl Branding {
/// The inline style that sets the frame colour, or empty without one.
/// Only a `#rrggbb` value ever reaches it, whatever the agent sent.
pub fn frame_style(&self) -> String {
match self.color.as_deref() {
Some(c) if is_hex_colour(c) => format!("--brand-frame: {c};"),
_ => String::new(),
}
}
/// Whether the sidebar shows the workspace instead of the Breakpilot
/// wordmark: it has a colour or a logo.
pub fn branded(&self) -> bool {
self.framed() || self.logo
}
/// The text colour on the CI colour: white or Breakpilot ink, whichever
/// reads better.
pub fn ink(&self) -> &'static str {
let Some(hex) = self.color.as_deref().filter(|c| is_hex_colour(c)) else {
return "#FFFFFF";
};
let channel = |i: usize| {
let v = f64::from(u8::from_str_radix(&hex[i..i + 2], 16).unwrap_or(0)) / 255.0;
if v <= 0.039_28 {
v / 12.92
} else {
((v + 0.055) / 1.055).powf(2.4)
}
};
let lum = 0.2126 * channel(1) + 0.7152 * channel(3) + 0.0722 * channel(5);
// Contrast with white is 1.05 / (L + 0.05); with ink (#14162B,
// L about 0.0085) it is (L + 0.05) / 0.0585.
if 1.05 / (lum + 0.05) >= (lum + 0.05) / 0.0585 {
"#FFFFFF"
} else {
"#14162B"
}
}
/// Whether the frame is drawn.
pub fn framed(&self) -> bool {
self.color.as_deref().is_some_and(is_hex_colour)
}
/// The initials shown instead of a logo: the first letters of the first
/// two words of the name, or none without a name.
pub fn initials(&self) -> String {
self.name
.as_deref()
.unwrap_or_default()
.split_whitespace()
.filter_map(|w| w.chars().find(|c| c.is_alphanumeric()))
.take(2)
.flat_map(char::to_uppercase)
.collect()
}
}
/// `#rrggbb`.
fn is_hex_colour(c: &str) -> bool {
c.strip_prefix('#')
.is_some_and(|h| h.len() == 6 && h.bytes().all(|b| b.is_ascii_hexdigit()))
}
/// Where the browser loads the workspace's logo.
pub const LOGO_URL: &str = "/api/branding/logo";
/// The agent's answer, read on the server only.
#[cfg(feature = "server")]
#[derive(Debug, Clone, Deserialize)]
struct BrandingResponse {
data: Branding,
}
/// The workspace's branding; none when the agent cannot say.
#[server]
pub async fn fetch_branding() -> Result<Branding, ServerFnError> {
let resp = super::agent_client::agent_get("/api/v1/branding")
.await?
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
let answer: BrandingResponse = super::agent_client::json_or_error(resp).await?;
Ok(answer.data)
}
/// `GET /api/branding/logo`: the workspace's logo, a PNG.
#[get("/api/branding/logo")]
pub async fn branding_logo() -> Result<dioxus::fullstack::FileStream, ServerFnError> {
let resp = super::agent_client::agent_get("/api/v1/branding/logo")
.await?
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
let resp = super::agent_client::ok_response(resp).await?;
let size = resp.content_length();
let body = axum::body::Body::from_stream(resp.bytes_stream()).into_data_stream();
Ok(dioxus::fullstack::FileStream::from_raw(
"logo.png".to_string(),
size,
"image/png".to_string(),
body,
))
}
/// Record an admin's "Passt" on the branding taken from the website.
#[server]
pub async fn ack_branding() -> Result<(), ServerFnError> {
let resp = super::agent_client::agent_request(reqwest::Method::POST, "/api/v1/branding/ack")
.await?
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
super::agent_client::ok_response(resp).await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_hex_colour_draws_a_frame() {
for (color, framed) in [
("#14b8a6", true),
("#C8102E", true),
("red", false),
("#12345", false),
("#14b8a6; background: url(x)", false),
] {
let b = Branding {
color: Some(color.into()),
..Default::default()
};
assert_eq!(b.framed(), framed, "{color}");
assert_eq!(b.frame_style().is_empty(), !framed, "{color}");
}
assert!(!Branding::default().framed());
}
#[test]
fn the_initials_read_on_the_ci_colour() {
let on = |c: &str| {
Branding {
color: Some(c.into()),
..Default::default()
}
.ink()
};
assert_eq!(on("#C8102E"), "#FFFFFF");
assert_eq!(on("#1F3A5F"), "#FFFFFF");
assert_eq!(on("#F5B700"), "#14162B");
assert_eq!(on("#14B8A6"), "#14162B");
}
#[test]
fn initials_come_from_the_first_two_words() {
let named = |n: &str| Branding {
name: Some(n.into()),
..Default::default()
};
assert_eq!(named("Musterwerk GmbH").initials(), "MG");
assert_eq!(named("nordachse").initials(), "N");
assert_eq!(named(" (Lindtal) Werke AG").initials(), "LW");
assert_eq!(Branding::default().initials(), "");
}
}
@@ -1,7 +1,6 @@
// Server function modules (compiled for both web and server;
// the #[server] macro generates client stubs for the web target)
pub mod auth_check;
pub mod branding;
pub mod chat;
pub mod cve_history;
pub mod cve_matrix;
@@ -68,7 +68,7 @@ pub fn upload_problem(error: String, lang: Lang) -> String {
} else if error.contains(UNSUPPORTED_ARCHIVE) {
common::UNSUPPORTED_ARCHIVE.get(lang).to_string()
} else {
crate::i18n::texts::metering::demo_refusal(&error, lang)
error
}
}
@@ -694,8 +694,6 @@ pub async fn upload_target_artifact(
413 if sbom => format!("{SBOM_REFUSED}too_large"),
413 => "file is larger than the 512 MiB upload limit".to_string(),
415 => UNSUPPORTED_ARCHIVE.to_string(),
// A demo target the plan has no room for as the tenant's own.
409 => refusal_code(resp).await,
422 => format!("{SBOM_REFUSED}{}", refusal_code(resp).await),
code => format!("upload rejected by the agent ({code})"),
}));
+2 -30
View File
@@ -13,7 +13,7 @@ use crate::components::no_access::use_can_write;
use crate::components::page_header::PageHeader;
use crate::components::scan_coverage::ScanCoverage;
use crate::components::scan_runs::ScanRunList;
use crate::i18n::texts::{common, kinds, metering, onboarding as tx};
use crate::i18n::texts::{common, kinds, onboarding as tx};
use crate::i18n::{format_bytes, use_lang, Lang};
use crate::infrastructure::onboarding::{
check_supplier_sbom, create_target, detect_target, enable_target_scans, fetch_applicable_scans,
@@ -232,7 +232,7 @@ pub fn OnboardingPage(origin: String) -> Element {
if let Some(err) = error() {
div { class: "card", style: "border-color: var(--danger, #d33); margin-bottom: 12px;",
div { class: "card-header", {tx::ERROR.get(lang)} }
div { style: "padding: 12px;", {metering::target_refusal(&err, lang)} }
div { style: "padding: 12px;", "{err}" }
}
}
@@ -993,34 +993,6 @@ fn type_label_of(value: &str, lang: Lang) -> String {
mod tests {
use super::*;
#[test]
fn a_target_the_plan_has_no_room_for_reads_in_words() {
let error = "error running server function: target_limit (409) (details: None)";
assert_eq!(
metering::target_refusal(error, Lang::En),
"Your plan includes no further targets. Delete a target to add a new one \
(its results are deleted with it), or change your plan."
);
assert_eq!(metering::target_refusal("x (500)", Lang::De), "x (500)");
}
#[test]
fn a_demo_target_the_plan_has_no_room_for_reads_in_words() {
let error = "error running server function: target_limit (409) (details: None)";
assert_eq!(
metering::demo_refusal(error, Lang::En),
metering::DEMO_LIMIT.get(Lang::En)
);
assert_eq!(
upload_problem(
"error running server function: target_limit".into(),
Lang::De
),
metering::DEMO_LIMIT.get(Lang::De)
);
assert_eq!(metering::demo_refusal("x (500)", Lang::De), "x (500)");
}
#[test]
fn a_refused_supplier_sbom_upload_reads_in_the_readers_language() {
let error = "error running server function: supplier_sbom_refused:empty (details: None)";
+5 -43
View File
@@ -350,10 +350,7 @@ pub fn SbomPage(target: String, #[props(default)] ecosystem: String) -> Element
// ── SBOM table ──
match &*sbom.read() {
Some(Some(resp)) if resp.data.is_empty() && unfiltered() => rsx! {
SbomEmpty {
target_id: repo_filter(),
plc: is_plc_target(repos.read().as_ref().and_then(|r| r.as_ref()).map(|r| r.data.as_slice()), &repo_filter()),
}
SbomEmpty { target_id: repo_filter() }
},
Some(Some(resp)) => {
let total_pages = resp.total.unwrap_or(0).div_ceil(50).max(1);
@@ -1042,19 +1039,6 @@ fn kev_title(kev: &KevData, lang: Lang) -> String {
title
}
/// Whether the target `id` among `targets` (the targets list's documents)
/// is a PLC application (`target_type` `plc_sps`).
fn is_plc_target(targets: Option<&[serde_json::Value]>, id: &str) -> bool {
!id.is_empty()
&& targets.unwrap_or_default().iter().any(|t| {
t.get("_id")
.and_then(|o| o.get("$oid"))
.and_then(|s| s.as_str())
== Some(id)
&& t.get("target_type").and_then(|v| v.as_str()) == Some("plc_sps")
})
}
/// An EPSS badge's text: the probability and the percentile, in percent
/// (`EPSS 94.4 % · P99`).
fn epss_label(epss: &EpssData) -> String {
@@ -1068,10 +1052,9 @@ fn epss_label(epss: &EpssData) -> String {
/// The component table's empty state (#979): why the SBOM is empty, and the
/// target's open findings that say what it is missing and how to add it, or
/// an example where there are none (all targets, or code such as C that has
/// no standard manifest). A PLC target (`plc`) gets its own reason and
/// example: its components come from a CODESYS archive or its controllers.
/// no standard manifest).
#[component]
fn SbomEmpty(target_id: ReadSignal<String>, plc: bool) -> Element {
fn SbomEmpty(target_id: ReadSignal<String>) -> Element {
let lang = use_lang()();
let findings = use_resource(move || async move {
let repo_id = target_id();
@@ -1093,9 +1076,9 @@ fn SbomEmpty(target_id: ReadSignal<String>, plc: bool) -> Element {
rsx! {
section { class: "card sbom-empty",
h3 { class: "sbom-quality-head", {tx::EMPTY_TITLE.get(lang)} }
p { if plc { {tx::EMPTY_WHY_PLC.get(lang)} } else { {tx::EMPTY_WHY.get(lang)} } }
p { {tx::EMPTY_WHY.get(lang)} }
if findings.is_empty() {
p { if plc { {tx::EMPTY_EXAMPLE_PLC.get(lang)} } else { {tx::EMPTY_EXAMPLE.get(lang)} } }
p { {tx::EMPTY_EXAMPLE.get(lang)} }
} else {
p { {tx::EMPTY_FINDINGS.get(lang)} }
ul { class: "sbom-empty-findings",
@@ -1175,24 +1158,3 @@ fn grade_class(grade: &str) -> &'static str {
_ => "badge-critical",
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_plc_target_gets_the_plc_explanation() {
// Arrange
let targets = vec![
serde_json::json!({ "_id": { "$oid": "a1" }, "target_type": "plc_sps" }),
serde_json::json!({ "_id": { "$oid": "b2" }, "target_type": "web_app" }),
];
// Act + Assert
assert!(is_plc_target(Some(&targets), "a1"));
assert!(!is_plc_target(Some(&targets), "b2"));
assert!(!is_plc_target(Some(&targets), "c3"));
assert!(!is_plc_target(Some(&targets), ""), "all targets");
assert!(!is_plc_target(None, "a1"), "targets not loaded yet");
}
}
+1 -4
View File
@@ -911,10 +911,7 @@ fn TargetEditor(
toasts.push(ToastType::Success, tx::UPDATED.get(lang));
on_saved.call(());
}
Err(e) => toasts.push(
ToastType::Error,
crate::i18n::texts::metering::demo_refusal(&e.to_string(), lang),
),
Err(e) => toasts.push(ToastType::Error, e.to_string()),
}
edit_saving.set(false);
});
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-dast"
version = "0.4.19"
version = "0.4.18"
edition = "2021"
[lints]
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-graph"
version = "0.4.19"
version = "0.4.18"
edition = "2021"
[lints]
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-mcp"
version = "0.4.19"
version = "0.4.18"
edition = "2021"
[dependencies]
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-smoke"
version = "0.4.19"
version = "0.4.18"
edition = "2021"
description = "Tiny Axum service exercising compliance-core M7.1 tenant gating. Run smoke.sh against it before merging anything that touches the auth/tenant path."
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "control-map"
version = "0.4.19"
version = "0.4.18"
edition = "2021"
[lints]
+1 -2
View File
@@ -13,8 +13,7 @@ What Prüfwerk keeps about a target, where, and when it is removed.
Deleting a target (`DELETE /api/v1/targets/{id}`, or **Delete** on the
targets page) removes its records and its files. Erasing a tenant
(`DELETE /api/v1/platform/tenants/{id}/data` with `{"confirm": "<tenant id>"}`,
the same id as in the path) drops its database
(`DELETE /api/v1/platform/tenants/{id}/data`, confirmed) drops its database
and removes every file listed above; the response says how many paths were
removed and how many could not be. Only paths inside the two configured base
directories are ever removed.
+1 -8
View File
@@ -6,7 +6,7 @@
"key": "plc-pump-station",
"name": "PLC pump station (ST + FBD, composite)",
"target_type": "plc_sps",
"description": "Composite PlcSps demo: Structured Text + FBD-as-PLCopen-XML control logic, plus an optional live Modbus endpoint (in-cluster plc-sim) and an optional device firmware image. Runs on a Siemens S7-1500 CPU with an old firmware, so its SBOM lists the controller and Siemens' advisories match it. Exercises PLC SAST, ICS probe, semantic control mapping, Siemens advisory matching.",
"description": "Composite PlcSps demo: Structured Text + FBD-as-PLCopen-XML control logic, plus an optional live Modbus endpoint (in-cluster plc-sim) and an optional device firmware image. Exercises PLC SAST, ICS probe, semantic control mapping.",
"artifacts": [
{
"kind": "plc_project",
@@ -30,13 +30,6 @@
"optional": true
}
],
"devices": [
{
"order_number": "6ES7511-1AK02-0AB0",
"firmware": "2.9.4",
"label": "Pump station CPU"
}
],
"expect": {
"min_findings": 16,
"sast_rule_ids": [
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "werkbank-exec"
version = "0.4.19"
version = "0.4.18"
edition = "2021"
description = "Shared dynamic-execution logic: soft-PLC provisioning + industrial-protocol probing, used by the compliance agent and the Werkbank runner."