Compare commits
83
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1f3beb5786 | ||
|
|
a9ea12651f | ||
|
|
12a02c3725 | ||
|
|
32c12b72e0 | ||
|
|
1ff5fcc1a4 | ||
|
|
b5cba8fb95 | ||
|
|
8fd78dd390 | ||
|
|
50b1a8b44b | ||
|
|
ecfee6db6e | ||
|
|
30079c6504 | ||
|
|
dd46af6f24 | ||
|
|
1df32d5e1a | ||
|
|
2d3311bd09 | ||
|
|
5b4d8bbe5f | ||
|
|
9274387e85 | ||
|
|
5407e1d7ed | ||
|
|
87b1e281ed | ||
|
|
ddb0068b3e | ||
|
|
f5848f7bad | ||
|
|
d9280939e2 | ||
|
|
600a8f0dd7 | ||
|
|
f59dae4a66 | ||
|
|
ae5d8f1ca8 | ||
|
|
7478ff57df | ||
|
|
a252096810 | ||
|
|
d3500d4be4 | ||
|
|
9da4d83ed0 | ||
|
|
20d56d2301 | ||
|
|
c8a13fecad | ||
|
|
fb8223bc11 | ||
|
|
835bc3fc98 | ||
|
|
f06a347dd7 | ||
|
|
1376efa249 | ||
|
|
40fb69072e | ||
|
|
d979fc1644 | ||
|
|
bc73a61f96 | ||
|
|
240c4d734a | ||
|
|
019ea73e86 | ||
|
|
497318e50d | ||
|
|
dc14c77e84 | ||
|
|
31b8cb9d37 | ||
|
|
c222210a87 | ||
|
|
832f9b13e1 | ||
|
|
eff6f92a33 | ||
|
|
6f42fbd583 | ||
|
|
90d5c8f8d1 | ||
|
|
b5a2dd93fd | ||
|
|
72ef09b981 | ||
|
|
684d3514ab | ||
|
|
0790810afb | ||
|
|
af76e516a1 | ||
|
|
7d0ccd7171 | ||
|
|
d679f9cbf1 | ||
|
|
55091fe02e | ||
|
|
97b8e35a87 | ||
|
|
e521c8fdd9 | ||
|
|
126345aa9d | ||
|
|
8ae561a01a | ||
|
|
668b6814c8 | ||
|
|
48b1a4a47d | ||
|
|
bde53a96dd | ||
|
|
dcfac283e6 | ||
|
|
141176df20 | ||
|
|
32332f65bb | ||
|
|
246e2c4ac5 | ||
|
|
98be82c0d0 | ||
|
|
0ad8bbc3c9 | ||
|
|
cdb84f0967 | ||
|
|
4f5d713bbc | ||
|
|
df16a49c93 | ||
|
|
12206bfac5 | ||
|
|
f5ac5321bd | ||
|
|
fad023e734 | ||
|
|
396cb3cd39 | ||
|
|
064bada213 | ||
|
|
deda6d4867 | ||
|
|
783e075891 | ||
|
|
ea1b48dd37 | ||
|
|
867453b63e | ||
|
|
ca8a662b60 | ||
|
|
fc72b6a1f4 | ||
|
|
aa022b0d0f | ||
|
|
5ea49661d0 |
No files matched your search
@@ -140,6 +140,10 @@ jobs:
|
|||||||
run: cargo clippy -p control-map --all-targets -- -D warnings
|
run: cargo clippy -p control-map --all-targets -- -D warnings
|
||||||
- name: Clippy (graph)
|
- name: Clippy (graph)
|
||||||
run: cargo clippy -p compliance-graph --all-targets -- -D warnings
|
run: cargo clippy -p compliance-graph --all-targets -- -D warnings
|
||||||
|
# The library only: its test modules still predate the lint
|
||||||
|
# (items_after_test_module); --all-targets once they are moved.
|
||||||
|
- name: Clippy (dast)
|
||||||
|
run: cargo clippy -p compliance-dast -- -D warnings
|
||||||
|
|
||||||
# Security audit
|
# Security audit
|
||||||
- name: Security Audit
|
- name: Security Audit
|
||||||
@@ -153,6 +157,10 @@ jobs:
|
|||||||
# compliance-core's integration tests need no services.
|
# compliance-core's integration tests need no services.
|
||||||
- name: Tests (core integration)
|
- name: Tests (core integration)
|
||||||
run: cargo test -p compliance-core --tests
|
run: cargo test -p compliance-core --tests
|
||||||
|
# compliance-dast: unit tests, doc tests and the scan tests against
|
||||||
|
# local fake sites (no services).
|
||||||
|
- name: Tests (dast)
|
||||||
|
run: cargo test -p compliance-dast
|
||||||
# The dashboard crate compiles as the library and as its test harness at
|
# The dashboard crate compiles as the library and as its test harness at
|
||||||
# once, each rustc at about 1.65 GB: two of them exceed the job's 3 GiB
|
# once, each rustc at about 1.65 GB: two of them exceed the job's 3 GiB
|
||||||
# and get OOM-killed (signal 9). One at a time for these two steps.
|
# and get OOM-killed (signal 9). One at a time for these two steps.
|
||||||
|
|||||||
Generated
+60
-20
@@ -601,7 +601,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "compliance-agent"
|
name = "compliance-agent"
|
||||||
version = "0.4.6"
|
version = "0.4.20"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"axum",
|
"axum",
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
@@ -645,6 +645,8 @@ dependencies = [
|
|||||||
"tracing",
|
"tracing",
|
||||||
"tracing-subscriber",
|
"tracing-subscriber",
|
||||||
"urlencoding",
|
"urlencoding",
|
||||||
|
"utoipa",
|
||||||
|
"utoipa-axum",
|
||||||
"uuid",
|
"uuid",
|
||||||
"walkdir",
|
"walkdir",
|
||||||
"werkbank-exec",
|
"werkbank-exec",
|
||||||
@@ -655,7 +657,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "compliance-core"
|
name = "compliance-core"
|
||||||
version = "0.4.6"
|
version = "0.4.20"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aes-gcm",
|
"aes-gcm",
|
||||||
"axum",
|
"axum",
|
||||||
@@ -687,7 +689,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "compliance-dashboard"
|
name = "compliance-dashboard"
|
||||||
version = "0.4.6"
|
version = "0.4.20"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-trait",
|
"async-trait",
|
||||||
"axum",
|
"axum",
|
||||||
@@ -725,8 +727,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "compliance-dast"
|
name = "compliance-dast"
|
||||||
version = "0.4.6"
|
version = "0.4.20"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"axum",
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
"chrono",
|
"chrono",
|
||||||
"compliance-core",
|
"compliance-core",
|
||||||
@@ -735,6 +738,7 @@ dependencies = [
|
|||||||
"reqwest",
|
"reqwest",
|
||||||
"scraper",
|
"scraper",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
"thiserror 2.0.18",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-native-tls",
|
"tokio-native-tls",
|
||||||
"tokio-tungstenite 0.26.2",
|
"tokio-tungstenite 0.26.2",
|
||||||
@@ -745,7 +749,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "compliance-graph"
|
name = "compliance-graph"
|
||||||
version = "0.4.6"
|
version = "0.4.20"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bson",
|
"bson",
|
||||||
"chrono",
|
"chrono",
|
||||||
@@ -770,7 +774,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "compliance-mcp"
|
name = "compliance-mcp"
|
||||||
version = "0.4.6"
|
version = "0.4.20"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"axum",
|
"axum",
|
||||||
"bson",
|
"bson",
|
||||||
@@ -793,7 +797,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "compliance-smoke"
|
name = "compliance-smoke"
|
||||||
version = "0.4.6"
|
version = "0.4.20"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"axum",
|
"axum",
|
||||||
"compliance-core",
|
"compliance-core",
|
||||||
@@ -928,7 +932,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "control-map"
|
name = "control-map"
|
||||||
version = "0.4.6"
|
version = "0.4.20"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
@@ -955,9 +959,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cookie"
|
name = "cookie"
|
||||||
version = "0.18.1"
|
version = "0.18.3"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747"
|
checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
"hmac 0.12.1",
|
"hmac 0.12.1",
|
||||||
@@ -2288,9 +2292,9 @@ checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "form_urlencoded"
|
name = "form_urlencoded"
|
||||||
version = "1.2.2"
|
version = "1.2.3"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
|
checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
]
|
]
|
||||||
@@ -3379,9 +3383,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "libz-sys"
|
name = "libz-sys"
|
||||||
version = "1.1.31"
|
version = "1.1.33"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ff20308ecabd635a2dc1dd5834a86c462cca20efba1d5d3ddab1f8aea3455cb2"
|
checksum = "fee3f59f4321dab0c78d828942e7aa09d0bd8ad6e78a501977e6bf3d02938045"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cc",
|
"cc",
|
||||||
"libc",
|
"libc",
|
||||||
@@ -4615,16 +4619,16 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "quinn-udp"
|
name = "quinn-udp"
|
||||||
version = "0.5.14"
|
version = "0.5.16"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd"
|
checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg_aliases",
|
"cfg_aliases",
|
||||||
"libc",
|
"libc",
|
||||||
"once_cell",
|
"once_cell",
|
||||||
"socket2 0.6.2",
|
"socket2 0.6.2",
|
||||||
"tracing",
|
"tracing",
|
||||||
"windows-sys 0.60.2",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -6780,9 +6784,9 @@ checksum = "e497bb1f828cc9fb236722c2eaa100dcf201563f38f4da6252357a59037adf31"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "url"
|
name = "url"
|
||||||
version = "2.5.8"
|
version = "2.5.9"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
|
checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"form_urlencoded",
|
"form_urlencoded",
|
||||||
"idna",
|
"idna",
|
||||||
@@ -6815,6 +6819,42 @@ version = "1.0.4"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "utoipa"
|
||||||
|
version = "6.0.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8765fe27aeff71012a3f90fa474cf1df863a7d0dd81ed25de4e63fff2544994f"
|
||||||
|
dependencies = [
|
||||||
|
"indexmap",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"utoipa-gen",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "utoipa-axum"
|
||||||
|
version = "0.3.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "865319162dc3d0032e1e40ed11bd49d5b78e8ef576740589fd6823e2e9977423"
|
||||||
|
dependencies = [
|
||||||
|
"axum",
|
||||||
|
"pastey",
|
||||||
|
"tower-layer",
|
||||||
|
"tower-service",
|
||||||
|
"utoipa",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "utoipa-gen"
|
||||||
|
version = "6.0.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d935f1c83fdf8b88f09bbe050d0cea78ea4afee6d7b0317403228c1200b2c8ab"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 3.0.9",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "uuid"
|
name = "uuid"
|
||||||
version = "1.21.0"
|
version = "1.21.0"
|
||||||
@@ -7087,7 +7127,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "werkbank-exec"
|
name = "werkbank-exec"
|
||||||
version = "0.4.6"
|
version = "0.4.20"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"compliance-core",
|
"compliance-core",
|
||||||
"compliance-dast",
|
"compliance-dast",
|
||||||
|
|||||||
@@ -1,12 +1,15 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "compliance-agent"
|
name = "compliance-agent"
|
||||||
version = "0.4.6"
|
version = "0.4.20"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
workspace = true
|
workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
# The OpenAPI description of the API, generated from the handlers (#1006).
|
||||||
|
utoipa = "6"
|
||||||
|
utoipa-axum = "0.3"
|
||||||
compliance-core = { workspace = true, features = ["mongodb", "telemetry", "axum", "secrets"] }
|
compliance-core = { workspace = true, features = ["mongodb", "telemetry", "axum", "secrets"] }
|
||||||
control-map = { workspace = true }
|
control-map = { workspace = true }
|
||||||
compliance-graph = { path = "../compliance-graph" }
|
compliance-graph = { path = "../compliance-graph" }
|
||||||
|
|||||||
@@ -173,8 +173,9 @@ impl ComplianceAgent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Store which of the tenant's targets are the plan's included ones and
|
/// Store which of the tenant's targets are the plan's included ones and
|
||||||
/// which are extra (t72), from the plan's `included_targets`. Without a
|
/// which are extra (t72), from the plan's `included_targets`; a plan that
|
||||||
/// registry every target is included. Best-effort: when the plan cannot
|
/// allows no extra target includes them all. Without a registry every
|
||||||
|
/// target is included. Best-effort: when the plan cannot
|
||||||
/// be read or the targets not updated, the stored split stays.
|
/// be read or the targets not updated, the stored split stays.
|
||||||
///
|
///
|
||||||
/// # Returns
|
/// # Returns
|
||||||
@@ -187,7 +188,7 @@ impl ComplianceAgent {
|
|||||||
) -> Vec<BillingChange> {
|
) -> Vec<BillingChange> {
|
||||||
match self.plan(tenant_id).await {
|
match self.plan(tenant_id).await {
|
||||||
Some(plan) => {
|
Some(plan) => {
|
||||||
self.assign_billing(tenant_id, db, plan.included_targets)
|
self.assign_billing(tenant_id, db, plan.billed_included())
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
None => Vec::new(),
|
None => Vec::new(),
|
||||||
@@ -205,6 +206,7 @@ impl ComplianceAgent {
|
|||||||
match registry.check_entitlement(tenant_id, None, None).await {
|
match registry.check_entitlement(tenant_id, None, None).await {
|
||||||
Ok(check) => Some(crate::metering::Plan {
|
Ok(check) => Some(crate::metering::Plan {
|
||||||
included_targets: check.included_targets(),
|
included_targets: check.included_targets(),
|
||||||
|
extra_targets: check.extra_targets(),
|
||||||
limits: check.plan_limits(),
|
limits: check.plan_limits(),
|
||||||
}),
|
}),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@@ -216,7 +218,7 @@ impl ComplianceAgent {
|
|||||||
|
|
||||||
/// Store the billing of the tenant's targets for a plan that includes
|
/// Store the billing of the tenant's targets for a plan that includes
|
||||||
/// `included` targets; best-effort.
|
/// `included` targets; best-effort.
|
||||||
async fn assign_billing(
|
pub(crate) async fn assign_billing(
|
||||||
&self,
|
&self,
|
||||||
tenant_id: &str,
|
tenant_id: &str,
|
||||||
db: &crate::database::Database,
|
db: &crate::database::Database,
|
||||||
@@ -359,7 +361,7 @@ impl ComplianceAgent {
|
|||||||
// counts, and the plan's limits whether a counted one may run (t72).
|
// counts, and the plan's limits whether a counted one may run (t72).
|
||||||
let plan = self.plan(tenant_id).await;
|
let plan = self.plan(tenant_id).await;
|
||||||
if let Some(plan) = &plan {
|
if let Some(plan) = &plan {
|
||||||
self.assign_billing(tenant_id, &db, plan.included_targets)
|
self.assign_billing(tenant_id, &db, plan.billed_included())
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
let orchestrator =
|
let orchestrator =
|
||||||
|
|||||||
@@ -0,0 +1,268 @@
|
|||||||
|
//! 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,7 +18,18 @@ use super::ApiResponse;
|
|||||||
|
|
||||||
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
||||||
|
|
||||||
/// POST /api/v1/chat/:repo_id — Send a chat message with RAG context
|
/// Ask about a target's code, answered from its code graph.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/chat/{repo_id}",
|
||||||
|
tag = "Chat",
|
||||||
|
params(("repo_id" = String, Path, description = "The target's id")),
|
||||||
|
request_body(content = Object, description = "`message`, and the earlier `history` as `role` and `content`"),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The answer with its sources"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||||
pub async fn chat(
|
pub async fn chat(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -133,7 +144,17 @@ pub async fn chat(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /api/v1/chat/:repo_id/build-embeddings — Trigger embedding build
|
/// Build the embeddings the chat answers from, in the background.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/chat/{repo_id}/build-embeddings",
|
||||||
|
tag = "Chat",
|
||||||
|
params(("repo_id" = String, Path, description = "The target's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The build was started"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||||
pub async fn build_embeddings(
|
pub async fn build_embeddings(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -244,7 +265,17 @@ pub async fn build_embeddings(
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/chat/:repo_id/status — Get latest embedding build status
|
/// The status of a target's latest embedding build.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/chat/{repo_id}/status",
|
||||||
|
tag = "Chat",
|
||||||
|
params(("repo_id" = String, Path, description = "The target's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The build, or null"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||||
pub async fn embedding_status(
|
pub async fn embedding_status(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
//! The workspace's connections to other workspaces (#1028), held by the
|
||||||
|
//! tenant registry (tenant-registry#138): whom a supplier can release an SBOM
|
||||||
|
//! to. A connection shows only its id and the other workspace's display
|
||||||
|
//! name, never the other tenant's id.
|
||||||
|
|
||||||
|
use axum::extract::Extension;
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::Json;
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
use compliance_core::tenant_ctx::TenantCtx;
|
||||||
|
|
||||||
|
use super::dto::AgentExt;
|
||||||
|
use super::ApiResponse;
|
||||||
|
|
||||||
|
/// A connection as the workspace sees it.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||||
|
pub struct ConnectionView {
|
||||||
|
/// The connection's id.
|
||||||
|
pub id: String,
|
||||||
|
/// The other workspace's display name.
|
||||||
|
pub peer_name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The workspace's active connections to other workspaces.
|
||||||
|
///
|
||||||
|
/// Each by its id and the other workspace's display name, by name; nothing
|
||||||
|
/// else of the other workspace. Connections are made and ended in the
|
||||||
|
/// portal. Without a registry (development) there are none.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/connections",
|
||||||
|
tag = "Targets",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The active connections (`data`)"),
|
||||||
|
(status = 503, description = "The registry cannot be asked"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
|
#[tracing::instrument(skip_all)]
|
||||||
|
pub async fn list_connections(
|
||||||
|
Extension(agent): AgentExt,
|
||||||
|
tenant: TenantCtx,
|
||||||
|
) -> Result<Json<ApiResponse<Vec<ConnectionView>>>, StatusCode> {
|
||||||
|
let connections = match agent.registry.as_ref() {
|
||||||
|
None => Vec::new(),
|
||||||
|
Some(registry) => registry
|
||||||
|
.active_connections(&tenant.0.tenant_id)
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
tracing::error!(tenant_id = %tenant.0.tenant_id, "connections unavailable: {e}");
|
||||||
|
StatusCode::SERVICE_UNAVAILABLE
|
||||||
|
})?,
|
||||||
|
};
|
||||||
|
let mut views: Vec<ConnectionView> = connections
|
||||||
|
.into_iter()
|
||||||
|
.map(|c| ConnectionView {
|
||||||
|
id: c.id,
|
||||||
|
peer_name: c.peer_name,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
// One lowercase name per connection, not one per comparison.
|
||||||
|
views.sort_by_cached_key(|v| v.peer_name.to_lowercase());
|
||||||
|
Ok(Json(ApiResponse {
|
||||||
|
data: views,
|
||||||
|
total: None,
|
||||||
|
page: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
@@ -6,7 +6,9 @@ use axum::Json;
|
|||||||
use mongodb::bson::doc;
|
use mongodb::bson::doc;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
use compliance_core::models::dast::{DastFinding, DastScanRun, DastTarget, DastTargetType};
|
use compliance_core::models::dast::{
|
||||||
|
DastAuthConfig, DastFinding, DastScanRun, DastTarget, DastTargetType,
|
||||||
|
};
|
||||||
use compliance_core::models::Credentials;
|
use compliance_core::models::Credentials;
|
||||||
use compliance_core::tenant_ctx::TenantCtx;
|
use compliance_core::tenant_ctx::TenantCtx;
|
||||||
|
|
||||||
@@ -17,21 +19,41 @@ use super::{collect_cursor_async, ApiResponse, PaginationParams};
|
|||||||
|
|
||||||
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
/// A DAST target to add.
|
||||||
|
#[derive(Deserialize, utoipa::ToSchema)]
|
||||||
pub struct AddTargetRequest {
|
pub struct AddTargetRequest {
|
||||||
|
/// A name for the target.
|
||||||
pub name: String,
|
pub name: String,
|
||||||
|
/// Where the scan starts; must be publicly routable.
|
||||||
pub base_url: String,
|
pub base_url: String,
|
||||||
|
/// `web_app` (default), `rest_api` or `graph_ql`.
|
||||||
#[serde(default = "default_target_type")]
|
#[serde(default = "default_target_type")]
|
||||||
|
#[schema(value_type = Option<String>, example = "web_app")]
|
||||||
pub target_type: DastTargetType,
|
pub target_type: DastTargetType,
|
||||||
|
/// The target (Prüfobjekt) this DAST target belongs to.
|
||||||
pub repo_id: Option<String>,
|
pub repo_id: Option<String>,
|
||||||
|
/// URL paths the scan leaves out.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub excluded_paths: Vec<String>,
|
pub excluded_paths: Vec<String>,
|
||||||
|
/// How many link levels the crawl follows (default 5).
|
||||||
#[serde(default = "default_crawl_depth")]
|
#[serde(default = "default_crawl_depth")]
|
||||||
|
#[schema(value_type = Option<u32>)]
|
||||||
pub max_crawl_depth: u32,
|
pub max_crawl_depth: u32,
|
||||||
|
/// Requests per second (default 10).
|
||||||
#[serde(default = "default_rate_limit")]
|
#[serde(default = "default_rate_limit")]
|
||||||
|
#[schema(value_type = Option<u32>)]
|
||||||
pub rate_limit: u32,
|
pub rate_limit: u32,
|
||||||
|
/// Whether the scan may send `PUT`, `PATCH` and `DELETE` (default false).
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
#[schema(value_type = Option<bool>)]
|
||||||
pub allow_destructive: bool,
|
pub allow_destructive: bool,
|
||||||
|
/// The login every scan request carries (#1000): `method` `basic`
|
||||||
|
/// (`username`, `password`), `bearer` (`token`) or `cookie` (`token` =
|
||||||
|
/// `name=value`), plus optional extra `headers`. Stored encrypted, never
|
||||||
|
/// returned.
|
||||||
|
#[serde(default)]
|
||||||
|
#[schema(value_type = Option<Object>)]
|
||||||
|
pub auth: Option<DastAuthConfig>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_target_type() -> DastTargetType {
|
fn default_target_type() -> DastTargetType {
|
||||||
@@ -44,7 +66,19 @@ fn default_rate_limit() -> u32 {
|
|||||||
10
|
10
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/dast/targets — List DAST targets
|
/// List the tenant's DAST targets.
|
||||||
|
///
|
||||||
|
/// Logins are never returned.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/dast/targets",
|
||||||
|
tag = "DAST",
|
||||||
|
params(PaginationParams),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "A page of DAST targets"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn list_targets(
|
pub async fn list_targets(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -81,7 +115,22 @@ pub async fn list_targets(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /api/v1/dast/targets — Add a new DAST target
|
/// Add a DAST target.
|
||||||
|
///
|
||||||
|
/// Its login is stored encrypted and never returned; the answer is the new
|
||||||
|
/// target with its id.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/dast/targets",
|
||||||
|
tag = "DAST",
|
||||||
|
request_body = AddTargetRequest,
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The new DAST target"),
|
||||||
|
(status = 400, description = "The base URL is refused (not publicly routable) or the login cannot be sent"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
(status = 503, description = "The login cannot be stored encrypted"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn add_target(
|
pub async fn add_target(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -94,12 +143,22 @@ pub async fn add_target(
|
|||||||
tracing::warn!(tenant_id = %tenant.0.tenant_id, "DAST target refused: {e}");
|
tracing::warn!(tenant_id = %tenant.0.tenant_id, "DAST target refused: {e}");
|
||||||
return Err(StatusCode::BAD_REQUEST);
|
return Err(StatusCode::BAD_REQUEST);
|
||||||
}
|
}
|
||||||
|
// A login the scan could not send is refused now, not at the first scan.
|
||||||
|
if let Err(e) = compliance_dast::auth::login_headers(req.auth.as_ref()) {
|
||||||
|
tracing::warn!(tenant_id = %tenant.0.tenant_id, "DAST target login refused: {e}");
|
||||||
|
return Err(StatusCode::BAD_REQUEST);
|
||||||
|
}
|
||||||
let mut target = DastTarget::new(req.name, req.base_url, req.target_type);
|
let mut target = DastTarget::new(req.name, req.base_url, req.target_type);
|
||||||
target.repo_id = req.repo_id;
|
target.repo_id = req.repo_id;
|
||||||
target.excluded_paths = req.excluded_paths;
|
target.excluded_paths = req.excluded_paths;
|
||||||
target.max_crawl_depth = req.max_crawl_depth;
|
target.max_crawl_depth = req.max_crawl_depth;
|
||||||
target.rate_limit = req.rate_limit;
|
target.rate_limit = req.rate_limit;
|
||||||
target.allow_destructive = req.allow_destructive;
|
target.allow_destructive = req.allow_destructive;
|
||||||
|
target.auth_config = req.auth;
|
||||||
|
agent
|
||||||
|
.secrets
|
||||||
|
.seal_unsealed(&mut target)
|
||||||
|
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||||
|
|
||||||
let db = tenant_db(&agent, &tenant).await?;
|
let db = tenant_db(&agent, &tenant).await?;
|
||||||
let res = db
|
let res = db
|
||||||
@@ -107,11 +166,8 @@ pub async fn add_target(
|
|||||||
.insert_one(&target)
|
.insert_one(&target)
|
||||||
.await
|
.await
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
let target_id = res
|
target.id = res.inserted_id.as_object_id();
|
||||||
.inserted_id
|
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
|
||||||
.as_object_id()
|
|
||||||
.map(|id| id.to_hex())
|
|
||||||
.unwrap_or_default();
|
|
||||||
agent.emit_usage(
|
agent.emit_usage(
|
||||||
&tenant.0.tenant_id,
|
&tenant.0.tenant_id,
|
||||||
"target.added",
|
"target.added",
|
||||||
@@ -126,7 +182,23 @@ pub async fn add_target(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /api/v1/dast/targets/:id/scan — Trigger DAST scan
|
/// Start a DAST scan of a target.
|
||||||
|
///
|
||||||
|
/// The scan runs in the background; its run and findings appear under the
|
||||||
|
/// scan-run and finding lists.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/dast/targets/{id}/scan",
|
||||||
|
tag = "DAST",
|
||||||
|
params(("id" = String, Path, description = "The DAST target's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The scan was started"),
|
||||||
|
(status = 400, description = "Not an id, or the target's address is refused"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
(status = 404, description = "No such DAST target"),
|
||||||
|
(status = 409, description = "This deployment does not run DAST"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||||
pub async fn trigger_scan(
|
pub async fn trigger_scan(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -141,12 +213,14 @@ pub async fn trigger_scan(
|
|||||||
let oid = mongodb::bson::oid::ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
let oid = mongodb::bson::oid::ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||||
let db = tenant_db(&agent, &tenant).await?;
|
let db = tenant_db(&agent, &tenant).await?;
|
||||||
|
|
||||||
let target = db
|
let mut target = db
|
||||||
.dast_targets()
|
.dast_targets()
|
||||||
.find_one(doc! { "_id": oid })
|
.find_one(doc! { "_id": oid })
|
||||||
.await
|
.await
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||||
.ok_or(StatusCode::NOT_FOUND)?;
|
.ok_or(StatusCode::NOT_FOUND)?;
|
||||||
|
// The login is used here, in memory only.
|
||||||
|
agent.secrets.open_in_place(&mut target);
|
||||||
|
|
||||||
// Re-check at use: the target may have been stored before this policy
|
// Re-check at use: the target may have been stored before this policy
|
||||||
// existed, and a hostname can be repointed after registration.
|
// existed, and a hostname can be repointed after registration.
|
||||||
@@ -197,7 +271,17 @@ pub async fn trigger_scan(
|
|||||||
Ok(Json(serde_json::json!({ "status": "dast_scan_triggered" })))
|
Ok(Json(serde_json::json!({ "status": "dast_scan_triggered" })))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/dast/scan-runs — List DAST scan runs
|
/// List the tenant's DAST scan runs.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/dast/scan-runs",
|
||||||
|
tag = "DAST",
|
||||||
|
params(PaginationParams),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "A page of DAST scan runs"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn list_scan_runs(
|
pub async fn list_scan_runs(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -235,7 +319,17 @@ pub async fn list_scan_runs(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/dast/findings — List DAST findings
|
/// List the tenant's DAST findings, with their evidence.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/dast/findings",
|
||||||
|
tag = "DAST",
|
||||||
|
params(PaginationParams),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "A page of DAST findings"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn list_findings(
|
pub async fn list_findings(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -273,7 +367,19 @@ pub async fn list_findings(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/dast/findings/:id — Finding detail with evidence
|
/// One DAST finding, with its request and response evidence.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/dast/findings/{id}",
|
||||||
|
tag = "DAST",
|
||||||
|
params(("id" = String, Path, description = "The DAST finding's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The DAST finding"),
|
||||||
|
(status = 400, description = "Not an id"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
(status = 404, description = "No such DAST finding"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(finding_id = %id))]
|
#[tracing::instrument(skip_all, fields(finding_id = %id))]
|
||||||
pub async fn get_finding(
|
pub async fn get_finding(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
|
|||||||
@@ -0,0 +1,280 @@
|
|||||||
|
//! Delivering published SBOM versions to the customers who accepted a
|
||||||
|
//! release (#1028), the second half of phase 4's customer side.
|
||||||
|
//!
|
||||||
|
//! A version reaches a customer's supplier component the way a supplier's
|
||||||
|
//! upload does (`onboarding::attach_upload`): it replaces the component's
|
||||||
|
//! supplier SBOM and a scan starts. Publishing delivers to every accepted
|
||||||
|
//! release of the target, accepting delivers the latest version at once. The
|
||||||
|
//! connection is asked again right before each write into the customer's
|
||||||
|
//! workspace, and the version last delivered is not delivered again. (Each
|
||||||
|
//! publication is its own document, with its own serial number and time,
|
||||||
|
//! so a new version is delivered even when its components are unchanged.)
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use futures_util::TryStreamExt;
|
||||||
|
use mongodb::bson::{doc, oid::ObjectId, DateTime as BsonDateTime};
|
||||||
|
|
||||||
|
use compliance_core::models::{ArtifactKind, ScanTrigger};
|
||||||
|
|
||||||
|
use super::offers::{OfferState, SbomOffer};
|
||||||
|
use super::onboarding::{attach_upload, StoredUpload};
|
||||||
|
use super::releases::{SbomRelease, SbomVersion};
|
||||||
|
use crate::agent::ComplianceAgent;
|
||||||
|
use crate::database::Database;
|
||||||
|
|
||||||
|
/// What became of one delivery.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub(super) enum Outcome {
|
||||||
|
/// Attached to the customer's component; a scan started.
|
||||||
|
Delivered,
|
||||||
|
/// The customer already has this content.
|
||||||
|
Unchanged,
|
||||||
|
/// Not delivered: the offer is not accepted, its component has gone, or
|
||||||
|
/// the connection no longer joins the two workspaces.
|
||||||
|
Skipped,
|
||||||
|
/// It could not be written; the next publication tries again.
|
||||||
|
Failed,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `release`'s connection still joins `supplier` and the customer it
|
||||||
|
/// was released to. Without a registry (development) it does not.
|
||||||
|
async fn joined(agent: &ComplianceAgent, supplier: &str, release: &SbomRelease) -> bool {
|
||||||
|
let Some(registry) = agent.registry.as_ref() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
match registry.connection(&release.connection_id).await {
|
||||||
|
Ok(state) => {
|
||||||
|
state.is_some_and(|s| s.peer_of(supplier) == Some(release.peer_tenant_id.as_str()))
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(release = %release.id, "connection not checked, nothing delivered: {e}");
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deliver `version` of `release` to the customer the release went to, into
|
||||||
|
/// the component its accepted offer names. The caller has checked the
|
||||||
|
/// connection.
|
||||||
|
async fn deliver(
|
||||||
|
agent: &Arc<ComplianceAgent>,
|
||||||
|
release: &SbomRelease,
|
||||||
|
version: &SbomVersion,
|
||||||
|
) -> Outcome {
|
||||||
|
let customer = &release.peer_tenant_id;
|
||||||
|
let db = agent.db_pool.for_existing_tenant_id(customer);
|
||||||
|
let offers = db.inner().collection::<SbomOffer>(SbomOffer::COLLECTION);
|
||||||
|
let offer = match offers
|
||||||
|
.find_one(doc! { "release_id": release.id.to_hex(), "state": "accepted" })
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(Some(offer)) => offer,
|
||||||
|
Ok(None) => return Outcome::Skipped,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(release = %release.id, "offer not read: {e}");
|
||||||
|
return Outcome::Failed;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if offer.delivered_hash.as_deref() == Some(version.content_hash.as_str()) {
|
||||||
|
return Outcome::Unchanged;
|
||||||
|
}
|
||||||
|
let Some(target_id) = offer.target_id.clone() else {
|
||||||
|
return Outcome::Skipped;
|
||||||
|
};
|
||||||
|
let Ok(oid) = ObjectId::parse_str(&target_id) else {
|
||||||
|
return Outcome::Skipped;
|
||||||
|
};
|
||||||
|
let target = match db.onboarded_targets().find_one(doc! { "_id": oid }).await {
|
||||||
|
Ok(Some(target)) => target,
|
||||||
|
Ok(None) => return Outcome::Skipped,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(target_id, "component not read: {e}");
|
||||||
|
return Outcome::Failed;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match attach(agent, &db, &target, version).await {
|
||||||
|
Ok(()) => {}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(target_id, label = %version.label, "version not delivered: {e}");
|
||||||
|
return Outcome::Failed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let now = BsonDateTime::now();
|
||||||
|
let marked = offers
|
||||||
|
.update_one(
|
||||||
|
doc! { "_id": offer.id, "state": "accepted" },
|
||||||
|
doc! { "$set": {
|
||||||
|
"delivered_hash": &version.content_hash,
|
||||||
|
"delivered_label": &version.label,
|
||||||
|
"delivered_at": now,
|
||||||
|
} },
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
if let Err(e) = marked {
|
||||||
|
tracing::warn!(target_id, "delivery not recorded on the offer: {e}");
|
||||||
|
}
|
||||||
|
let supplier = agent
|
||||||
|
.db_pool
|
||||||
|
.for_existing_tenant_id(&offer.supplier_tenant_id);
|
||||||
|
let shown = supplier
|
||||||
|
.inner()
|
||||||
|
.collection::<SbomRelease>(SbomRelease::COLLECTION)
|
||||||
|
.update_one(
|
||||||
|
doc! { "_id": release.id },
|
||||||
|
doc! { "$set": { "delivered_label": &version.label, "delivered_at": now } },
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
if let Err(e) = shown {
|
||||||
|
tracing::warn!(release = %release.id, "delivery not recorded on the release: {e}");
|
||||||
|
}
|
||||||
|
// A set: a release delivered the same version again counts once.
|
||||||
|
let counted = supplier
|
||||||
|
.inner()
|
||||||
|
.collection::<SbomVersion>(SbomVersion::COLLECTION)
|
||||||
|
.update_one(
|
||||||
|
doc! { "_id": version.id },
|
||||||
|
doc! { "$addToSet": { "delivered_to": release.id.to_hex() } },
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
if let Err(e) = counted {
|
||||||
|
tracing::warn!(label = %version.label, "delivery not counted on the version: {e}");
|
||||||
|
}
|
||||||
|
let (agent, customer) = (Arc::clone(agent), customer.clone());
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Err(e) = agent
|
||||||
|
.run_target_scan(&customer, &target_id, ScanTrigger::NewContent)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
tracing::error!(target_id, "scan after a delivered SBOM failed: {e}");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Outcome::Delivered
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Copy `version`'s document into `target`'s upload folder in the
|
||||||
|
/// customer's workspace and attach it as the component's supplier SBOM,
|
||||||
|
/// labelled with the version.
|
||||||
|
async fn attach(
|
||||||
|
agent: &ComplianceAgent,
|
||||||
|
db: &Database,
|
||||||
|
target: &compliance_core::models::OnboardedTarget,
|
||||||
|
version: &SbomVersion,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let target_id = target.id.map(|o| o.to_hex()).unwrap_or_default();
|
||||||
|
let bytes = tokio::fs::read(&version.stored_path)
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("the published document is not readable: {e}"))?;
|
||||||
|
let name = format!("release-{}.cdx.json", version.label);
|
||||||
|
let path = crate::targets::store_upload(agent, &target_id, &name, &bytes)
|
||||||
|
.map_err(|e| format!("not stored: {e}"))?;
|
||||||
|
let mut upload = StoredUpload::new(path, name);
|
||||||
|
upload.size = u64::try_from(bytes.len()).unwrap_or(u64::MAX);
|
||||||
|
attach_upload(db, target, ArtifactKind::SupplierSbom, None, upload)
|
||||||
|
.await
|
||||||
|
.map_err(|refusal| format!("refused ({})", refusal.code().unwrap_or("unreadable")))?;
|
||||||
|
if let Some(mut supplier) = target.supplier.clone() {
|
||||||
|
supplier.version = Some(version.label.clone());
|
||||||
|
let set = mongodb::bson::to_bson(&supplier).map_err(|e| e.to_string())?;
|
||||||
|
db.onboarded_targets()
|
||||||
|
.update_one(
|
||||||
|
doc! { "_id": target.id },
|
||||||
|
doc! { "$set": { "supplier": set } },
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deliver `version` of target `target_id`, just published by `supplier`
|
||||||
|
/// (its database `db`), to every customer that accepted a release of it,
|
||||||
|
/// and tell every customer whose offer is still open that it is now what
|
||||||
|
/// accepting delivers.
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// How many customers it was delivered to.
|
||||||
|
pub(super) async fn deliver_published(
|
||||||
|
agent: &Arc<ComplianceAgent>,
|
||||||
|
supplier: &str,
|
||||||
|
db: &Database,
|
||||||
|
target_id: &str,
|
||||||
|
version: &SbomVersion,
|
||||||
|
) -> usize {
|
||||||
|
let live: Vec<SbomRelease> = match db
|
||||||
|
.inner()
|
||||||
|
.collection::<SbomRelease>(SbomRelease::COLLECTION)
|
||||||
|
.find(doc! { "target_id": target_id, "ended_at": null })
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(cursor) => cursor.try_collect().await.unwrap_or_default(),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(target_id, "releases not read, nothing delivered: {e}");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut delivered = 0;
|
||||||
|
for release in &live {
|
||||||
|
let open = matches!(release.answer, None | Some(OfferState::Offered));
|
||||||
|
if !(open || release.answer == Some(OfferState::Accepted))
|
||||||
|
|| !joined(agent, supplier, release).await
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if open {
|
||||||
|
let id = release.id.to_hex();
|
||||||
|
super::offers::announce(
|
||||||
|
agent,
|
||||||
|
&release.peer_tenant_id,
|
||||||
|
&id,
|
||||||
|
&version.label,
|
||||||
|
version.components,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
} else if deliver(agent, release, version).await == Outcome::Delivered {
|
||||||
|
delivered += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
delivered
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deliver the latest published version of the release `offer` answers, if
|
||||||
|
/// there is one, right after the customer accepted it. The caller has
|
||||||
|
/// checked the connection and that the release is live.
|
||||||
|
pub(super) async fn deliver_latest(agent: &Arc<ComplianceAgent>, offer: &SbomOffer) -> Outcome {
|
||||||
|
debug_assert_eq!(offer.state, OfferState::Accepted);
|
||||||
|
let Ok(id) = ObjectId::parse_str(&offer.release_id) else {
|
||||||
|
return Outcome::Skipped;
|
||||||
|
};
|
||||||
|
let supplier = agent
|
||||||
|
.db_pool
|
||||||
|
.for_existing_tenant_id(&offer.supplier_tenant_id);
|
||||||
|
let release = match supplier
|
||||||
|
.inner()
|
||||||
|
.collection::<SbomRelease>(SbomRelease::COLLECTION)
|
||||||
|
.find_one(doc! { "_id": id, "ended_at": null })
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(Some(release)) => release,
|
||||||
|
Ok(None) => return Outcome::Skipped,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(release = %offer.release_id, "release not read: {e}");
|
||||||
|
return Outcome::Failed;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let latest = supplier
|
||||||
|
.inner()
|
||||||
|
.collection::<SbomVersion>(SbomVersion::COLLECTION)
|
||||||
|
.find_one(doc! { "target_id": &release.target_id })
|
||||||
|
.sort(doc! { "created_at": -1, "_id": -1 })
|
||||||
|
.await;
|
||||||
|
match latest {
|
||||||
|
Ok(Some(version)) => deliver(agent, &release, &version).await,
|
||||||
|
Ok(None) => Outcome::Skipped,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(release = %offer.release_id, "versions not read: {e}");
|
||||||
|
Outcome::Failed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -27,7 +27,16 @@ pub struct SeedResponse {
|
|||||||
pub seeded: Vec<SeededTarget>,
|
pub seeded: Vec<SeededTarget>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/targets/demo-seed — what "Add demo targets" would create.
|
/// The demo targets the agent ships, which seeding would create.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/targets/demo-seed",
|
||||||
|
tag = "Targets",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The demo targets"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn list_demo_targets(
|
pub async fn list_demo_targets(
|
||||||
_tenant: TenantCtx,
|
_tenant: TenantCtx,
|
||||||
@@ -39,8 +48,20 @@ pub async fn list_demo_targets(
|
|||||||
Ok(Json(DemoTargetsResponse { targets }))
|
Ok(Json(DemoTargetsResponse { targets }))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /api/v1/targets/demo-seed — seed the caller's tenant. 202: the targets
|
/// Create the demo targets for the tenant and start their scans.
|
||||||
/// exist and their scans are running in the background.
|
///
|
||||||
|
/// 202: the targets exist and their scans are running in the background.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/targets/demo-seed",
|
||||||
|
tag = "Targets",
|
||||||
|
request_body(content = Option<SeedRequest>, description = "Which demo targets; none seeds all"),
|
||||||
|
responses(
|
||||||
|
(status = 202, description = "The targets exist; their scans are running"),
|
||||||
|
(status = 400, description = "An unknown demo target"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn seed_demo_targets(
|
pub async fn seed_demo_targets(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
|
|||||||
@@ -0,0 +1,228 @@
|
|||||||
|
//! A target's Siemens controllers against Siemens' advisories (SPS item 4a):
|
||||||
|
//! `GET /api/v1/targets/{id}/devices` for its page, and
|
||||||
|
//! `GET /api/v1/devices/lookup` to recognise an order number while it is
|
||||||
|
//! typed.
|
||||||
|
//!
|
||||||
|
//! Both read the advisory index as it is now, so a device shows its state
|
||||||
|
//! as soon as it is entered; its CVE alerts follow at the target's next scan.
|
||||||
|
|
||||||
|
use axum::extract::{Extension, Path, Query};
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::Json;
|
||||||
|
use mongodb::bson::doc;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use super::dto::{tenant_db, AgentExt, ApiResponse, ApiResult};
|
||||||
|
use crate::pipeline::csaf_match::{AdvisoryIndex, Wanted};
|
||||||
|
use compliance_core::csaf_ingest::Advisory;
|
||||||
|
use compliance_core::device_check::{DeviceCheck, DeviceLookup};
|
||||||
|
use compliance_core::models::plc_device::normalised_order_number;
|
||||||
|
use compliance_core::models::PlcDevice;
|
||||||
|
use compliance_core::tenant_ctx::TenantCtx;
|
||||||
|
|
||||||
|
/// The provider whose advisories name devices by order number.
|
||||||
|
const PROVIDER: &str = "siemens";
|
||||||
|
|
||||||
|
/// Siemens' advisories naming any of `order_numbers` (normalised).
|
||||||
|
async fn advisories_naming(
|
||||||
|
index: &dyn AdvisoryIndex,
|
||||||
|
order_numbers: Vec<String>,
|
||||||
|
) -> Result<Vec<Advisory>, StatusCode> {
|
||||||
|
let wanted = Wanted {
|
||||||
|
order_numbers,
|
||||||
|
..Wanted::default()
|
||||||
|
};
|
||||||
|
let rows = index.relevant(&wanted).await.map_err(|e| {
|
||||||
|
tracing::warn!("Failed to read the advisory index: {e}");
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
})?;
|
||||||
|
Ok(rows
|
||||||
|
.into_iter()
|
||||||
|
.filter(|(provider, _)| provider == PROVIDER)
|
||||||
|
.map(|(_, advisory)| advisory)
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Each of `devices` against `advisories`.
|
||||||
|
fn checks(devices: Vec<PlcDevice>, advisories: &[Advisory]) -> Vec<DeviceCheck> {
|
||||||
|
devices
|
||||||
|
.into_iter()
|
||||||
|
.map(|device| DeviceCheck::new(device, advisories))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The Siemens controllers a target runs on.
|
||||||
|
///
|
||||||
|
/// Each with the Siemens advisories naming it.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/targets/{id}/devices",
|
||||||
|
tag = "Targets",
|
||||||
|
params(("id" = String, Path, description = "The target's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The target's devices in the order entered, each with the Siemens advisories naming it and whether one affects its firmware"),
|
||||||
|
(status = 400, description = "Not a target id"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
(status = 404, description = "No such target"),
|
||||||
|
(status = 500, description = "The target or the advisory index could not be read"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
|
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||||
|
pub async fn list_devices(
|
||||||
|
Extension(agent): AgentExt,
|
||||||
|
tenant: TenantCtx,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
) -> ApiResult<Vec<DeviceCheck>> {
|
||||||
|
let oid = mongodb::bson::oid::ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||||
|
let db = tenant_db(&agent, &tenant).await?;
|
||||||
|
let target = db
|
||||||
|
.onboarded_targets()
|
||||||
|
.find_one(doc! { "_id": oid })
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||||
|
.ok_or(StatusCode::NOT_FOUND)?;
|
||||||
|
// Entered and exported alike (#1090): a TIA export's devices are listed
|
||||||
|
// under their names in the project.
|
||||||
|
let target_devices: Vec<_> = target
|
||||||
|
.target_devices()
|
||||||
|
.into_iter()
|
||||||
|
.map(|d| d.device)
|
||||||
|
.collect();
|
||||||
|
let mut order_numbers: Vec<String> = target_devices
|
||||||
|
.iter()
|
||||||
|
.map(|d| d.order_number.clone())
|
||||||
|
.collect();
|
||||||
|
order_numbers.sort();
|
||||||
|
order_numbers.dedup();
|
||||||
|
let advisories = if order_numbers.is_empty() {
|
||||||
|
Vec::new()
|
||||||
|
} else {
|
||||||
|
advisories_naming(agent.advisory_index.as_ref(), order_numbers).await?
|
||||||
|
};
|
||||||
|
let devices = checks(target_devices, &advisories);
|
||||||
|
Ok(Json(ApiResponse {
|
||||||
|
total: Some(devices.len() as u64),
|
||||||
|
data: devices,
|
||||||
|
page: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `?order_number=` of [`lookup_device`].
|
||||||
|
#[derive(Debug, Deserialize, utoipa::IntoParams)]
|
||||||
|
pub struct LookupParams {
|
||||||
|
/// The order number as typed (`6es7511-1ak02-0ab0`).
|
||||||
|
pub order_number: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What Siemens' advisories know of an order number.
|
||||||
|
///
|
||||||
|
/// For recognising one while it is typed. Public data only: nothing of the
|
||||||
|
/// tenant is read.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/devices/lookup",
|
||||||
|
tag = "Targets",
|
||||||
|
params(LookupParams),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The order number normalised, whether it has a Siemens order number's shape, and, when advisories name it, the product's name and how many"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
(status = 500, description = "The advisory index could not be read"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
|
#[tracing::instrument(skip_all)]
|
||||||
|
pub async fn lookup_device(
|
||||||
|
Extension(agent): AgentExt,
|
||||||
|
_tenant: TenantCtx,
|
||||||
|
Query(params): Query<LookupParams>,
|
||||||
|
) -> ApiResult<DeviceLookup> {
|
||||||
|
let order_number = normalised_order_number(¶ms.order_number);
|
||||||
|
// Any firmware: only the shape of the order number is checked here.
|
||||||
|
let Ok(device) = PlcDevice::new(&order_number, "0", None) else {
|
||||||
|
return Ok(Json(ApiResponse {
|
||||||
|
data: DeviceLookup {
|
||||||
|
order_number,
|
||||||
|
valid: false,
|
||||||
|
product: None,
|
||||||
|
advisories: 0,
|
||||||
|
},
|
||||||
|
total: None,
|
||||||
|
page: None,
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
let advisories =
|
||||||
|
advisories_naming(agent.advisory_index.as_ref(), vec![order_number.clone()]).await?;
|
||||||
|
let check = DeviceCheck::new(device, &advisories);
|
||||||
|
Ok(Json(ApiResponse {
|
||||||
|
data: DeviceLookup {
|
||||||
|
order_number,
|
||||||
|
valid: true,
|
||||||
|
product: check.product,
|
||||||
|
advisories: check.advisories.len(),
|
||||||
|
},
|
||||||
|
total: None,
|
||||||
|
page: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[allow(clippy::unwrap_used)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use futures_util::future::BoxFuture;
|
||||||
|
|
||||||
|
/// An index answering with the synthetic Siemens advisory, and a CODESYS
|
||||||
|
/// one that must never reach a device.
|
||||||
|
struct Fixture;
|
||||||
|
|
||||||
|
impl AdvisoryIndex for Fixture {
|
||||||
|
fn relevant<'a>(
|
||||||
|
&'a self,
|
||||||
|
wanted: &'a Wanted,
|
||||||
|
) -> BoxFuture<'a, Result<Vec<(String, Advisory)>, String>> {
|
||||||
|
assert!(wanted.providers.is_empty() && wanted.purls.is_empty());
|
||||||
|
let doc: serde_json::Value = serde_json::from_str(include_str!(
|
||||||
|
"../../../../compliance-core/tests/fixtures/csaf/siemens-synthetic.json"
|
||||||
|
))
|
||||||
|
.unwrap();
|
||||||
|
let siemens = compliance_core::csaf_ingest::parse(&doc).unwrap();
|
||||||
|
let mut codesys = siemens.clone();
|
||||||
|
codesys.id = "VDE-2026-0001".into();
|
||||||
|
Box::pin(async move {
|
||||||
|
Ok(vec![
|
||||||
|
("siemens".to_string(), siemens),
|
||||||
|
("codesys".to_string(), codesys),
|
||||||
|
])
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn devices_are_checked_against_siemens_advisories_only() {
|
||||||
|
let advisories = advisories_naming(&Fixture, vec!["6ES7511-1AK02-0AB0".into()])
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(advisories.len(), 1);
|
||||||
|
let devices = checks(
|
||||||
|
vec![
|
||||||
|
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.4", None).unwrap(),
|
||||||
|
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.5", None).unwrap(),
|
||||||
|
PlcDevice::new("6ES7516-3AN02-0AB0", "3.0", None).unwrap(),
|
||||||
|
],
|
||||||
|
&advisories,
|
||||||
|
);
|
||||||
|
use compliance_core::device_check::DeviceState;
|
||||||
|
let states: Vec<DeviceState> = devices.iter().map(DeviceCheck::state).collect();
|
||||||
|
assert_eq!(
|
||||||
|
states,
|
||||||
|
[
|
||||||
|
DeviceState::Affected,
|
||||||
|
DeviceState::NotAffected,
|
||||||
|
DeviceState::NotNamed
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
devices[0].advisories[0].fixed_from.as_deref(),
|
||||||
|
Some("3.1.5")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,11 +15,17 @@ pub const MAX_PAGE_SIZE: i64 = 200;
|
|||||||
/// absurd offset. At [`MAX_PAGE_SIZE`] this is still 20M documents deep.
|
/// absurd offset. At [`MAX_PAGE_SIZE`] this is still 20M documents deep.
|
||||||
pub const MAX_PAGE: u64 = 100_000;
|
pub const MAX_PAGE: u64 = 100_000;
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
/// The page of a list a request asks for.
|
||||||
|
#[derive(Deserialize, utoipa::IntoParams)]
|
||||||
|
#[into_params(parameter_in = Query)]
|
||||||
pub struct PaginationParams {
|
pub struct PaginationParams {
|
||||||
|
/// The page, from 1 (default 1, at most 100 000).
|
||||||
#[serde(default = "default_page", deserialize_with = "de_page")]
|
#[serde(default = "default_page", deserialize_with = "de_page")]
|
||||||
|
#[param(minimum = 1, maximum = 100_000)]
|
||||||
pub page: u64,
|
pub page: u64,
|
||||||
|
/// Entries per page (default 50, at most 200).
|
||||||
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
||||||
|
#[param(minimum = 1, maximum = 200)]
|
||||||
pub limit: i64,
|
pub limit: i64,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,22 +55,35 @@ pub(crate) fn de_limit<'de, D: serde::Deserializer<'de>>(d: D) -> Result<i64, D:
|
|||||||
Ok(i64::deserialize(d)?.clamp(1, MAX_PAGE_SIZE))
|
Ok(i64::deserialize(d)?.clamp(1, MAX_PAGE_SIZE))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
/// Which findings a list returns, and in what order.
|
||||||
|
#[derive(Deserialize, utoipa::IntoParams)]
|
||||||
|
#[into_params(parameter_in = Query)]
|
||||||
pub struct FindingsFilter {
|
pub struct FindingsFilter {
|
||||||
|
/// Only one target's findings (its id).
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub repo_id: Option<String>,
|
pub repo_id: Option<String>,
|
||||||
/// Only the findings a given scan run found first (the dashboard reveals
|
/// Only the findings a given scan run found first (the dashboard reveals
|
||||||
/// them when the run ends).
|
/// them when the run ends).
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub scan_run_id: Option<String>,
|
pub scan_run_id: Option<String>,
|
||||||
|
/// `info`, `low`, `medium`, `high` or `critical`.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub severity: Option<String>,
|
pub severity: Option<String>,
|
||||||
|
/// Only one kind of scan (`sast`, `cve`, `dast`, …).
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub scan_type: Option<String>,
|
pub scan_type: Option<String>,
|
||||||
|
/// `open`, `triaged`, `false_positive`, `resolved`, `ignored`,
|
||||||
|
/// `accepted_risk`, `needs_review` or `wrong_mapping`.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub status: Option<String>,
|
pub status: Option<String>,
|
||||||
|
/// Text the title, description or file path contains (at most 128
|
||||||
|
/// characters, matched literally).
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub q: Option<String>,
|
pub q: Option<String>,
|
||||||
|
/// Only the findings of one scanner (`Finding::scanner`, e.g.
|
||||||
|
/// `sbom-coverage`).
|
||||||
|
#[serde(default)]
|
||||||
|
pub scanner: Option<String>,
|
||||||
/// Only the findings in one app variant (`Tablet App`): its own, and the
|
/// Only the findings in one app variant (`Tablet App`): its own, and the
|
||||||
/// groups listing a place in it.
|
/// groups listing a place in it.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
@@ -73,13 +92,20 @@ pub struct FindingsFilter {
|
|||||||
/// ([`path_regex`]).
|
/// ([`path_regex`]).
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub path: Option<String>,
|
pub path: Option<String>,
|
||||||
|
/// `created_at` (default), `updated_at`, `severity`, `scan_type`,
|
||||||
|
/// `status`, `file_path`, `rule_id`, `repo_id`, `title` or `confidence`.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub sort_by: Option<String>,
|
pub sort_by: Option<String>,
|
||||||
|
/// `asc`, or newest/highest first (default).
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub sort_order: Option<String>,
|
pub sort_order: Option<String>,
|
||||||
|
/// The page, from 1 (default 1, at most 100 000).
|
||||||
#[serde(default = "default_page", deserialize_with = "de_page")]
|
#[serde(default = "default_page", deserialize_with = "de_page")]
|
||||||
|
#[param(minimum = 1, maximum = 100_000)]
|
||||||
pub page: u64,
|
pub page: u64,
|
||||||
|
/// Entries per page (default 50, at most 200).
|
||||||
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
||||||
|
#[param(minimum = 1, maximum = 200)]
|
||||||
pub limit: i64,
|
pub limit: i64,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -115,20 +141,26 @@ impl TicketState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The query of the tickets list (`GET /api/v1/issues`).
|
/// The query of the tickets list (`GET /api/v1/issues`).
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize, utoipa::IntoParams)]
|
||||||
|
#[into_params(parameter_in = Query)]
|
||||||
pub struct IssuesFilter {
|
pub struct IssuesFilter {
|
||||||
/// A word of the title or the ticket number (`913`, `#913`, `PROJ-913`).
|
/// A word of the title or the ticket number (`913`, `#913`, `PROJ-913`).
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub q: Option<String>,
|
pub q: Option<String>,
|
||||||
/// Only open or only closed tickets; an unknown value is refused (400).
|
/// `open` or `closed`; an unknown value is refused (400).
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
#[param(value_type = Option<String>, example = "open")]
|
||||||
pub status: Option<TicketState>,
|
pub status: Option<TicketState>,
|
||||||
/// Only the tickets of one target: of its findings and its CVEs.
|
/// Only the tickets of one target: of its findings and its CVEs.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub repo_id: Option<String>,
|
pub repo_id: Option<String>,
|
||||||
|
/// The page, from 1 (default 1, at most 100 000).
|
||||||
#[serde(default = "default_page", deserialize_with = "de_page")]
|
#[serde(default = "default_page", deserialize_with = "de_page")]
|
||||||
|
#[param(minimum = 1, maximum = 100_000)]
|
||||||
pub page: u64,
|
pub page: u64,
|
||||||
|
/// Entries per page (default 50, at most 200).
|
||||||
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
||||||
|
#[param(minimum = 1, maximum = 200)]
|
||||||
pub limit: i64,
|
pub limit: i64,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -283,39 +315,58 @@ fn default_branch() -> String {
|
|||||||
"main".to_string()
|
"main".to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
/// A finding's new status.
|
||||||
|
#[derive(Deserialize, utoipa::ToSchema)]
|
||||||
pub struct UpdateStatusRequest {
|
pub struct UpdateStatusRequest {
|
||||||
/// Typed, so an unknown status is refused (422) instead of being stored
|
/// `open`, `triaged`, `false_positive`, `resolved`, `ignored`,
|
||||||
/// and breaking every later read of the finding.
|
/// `accepted_risk`, `needs_review` or `wrong_mapping`. Typed, so an
|
||||||
|
/// unknown status is refused (422) instead of being stored and breaking
|
||||||
|
/// every later read of the finding.
|
||||||
|
#[schema(value_type = String, example = "false_positive")]
|
||||||
pub status: compliance_core::models::FindingStatus,
|
pub status: compliance_core::models::FindingStatus,
|
||||||
/// Why; required for `accepted_risk`.
|
/// Why; required for `accepted_risk`.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub reason: Option<String>,
|
pub reason: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
/// The same new status for many findings.
|
||||||
|
#[derive(Deserialize, utoipa::ToSchema)]
|
||||||
pub struct BulkUpdateStatusRequest {
|
pub struct BulkUpdateStatusRequest {
|
||||||
|
/// The findings' ids.
|
||||||
pub ids: Vec<String>,
|
pub ids: Vec<String>,
|
||||||
|
/// The status, as for one finding.
|
||||||
|
#[schema(value_type = String, example = "resolved")]
|
||||||
pub status: compliance_core::models::FindingStatus,
|
pub status: compliance_core::models::FindingStatus,
|
||||||
|
/// Why; required for `accepted_risk` and `wrong_mapping`.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub reason: Option<String>,
|
pub reason: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
/// A developer's feedback on a finding.
|
||||||
|
#[derive(Deserialize, utoipa::ToSchema)]
|
||||||
pub struct UpdateFeedbackRequest {
|
pub struct UpdateFeedbackRequest {
|
||||||
|
/// The feedback, as text.
|
||||||
pub feedback: String,
|
pub feedback: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
/// Which SBOM components a list or summary shows.
|
||||||
|
#[derive(Deserialize, utoipa::IntoParams)]
|
||||||
|
#[into_params(parameter_in = Query)]
|
||||||
pub struct SbomFilter {
|
pub struct SbomFilter {
|
||||||
|
/// Only one target's components (its id).
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub repo_id: Option<String>,
|
pub repo_id: Option<String>,
|
||||||
|
/// Only one package manager's components, such as `npm` or `cargo`.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub package_manager: Option<String>,
|
pub package_manager: Option<String>,
|
||||||
|
/// Only components whose name contains this text.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub q: Option<String>,
|
pub q: Option<String>,
|
||||||
|
/// Only components with known vulnerabilities (`true`), or only those
|
||||||
|
/// without (`false`).
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub has_vulns: Option<bool>,
|
pub has_vulns: Option<bool>,
|
||||||
|
/// Only components with this licence.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub license: Option<String>,
|
pub license: Option<String>,
|
||||||
/// Only components an image is known to contain (`true`), or only the
|
/// Only components an image is known to contain (`true`), or only the
|
||||||
@@ -326,9 +377,13 @@ pub struct SbomFilter {
|
|||||||
/// none and nobody has confirmed one.
|
/// none and nobody has confirmed one.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub unresolved: Option<bool>,
|
pub unresolved: Option<bool>,
|
||||||
|
/// The page, from 1 (default 1, at most 100 000).
|
||||||
#[serde(default = "default_page", deserialize_with = "de_page")]
|
#[serde(default = "default_page", deserialize_with = "de_page")]
|
||||||
|
#[param(minimum = 1, maximum = 100_000)]
|
||||||
pub page: u64,
|
pub page: u64,
|
||||||
|
/// Entries per page (default 50, at most 200).
|
||||||
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
||||||
|
#[param(minimum = 1, maximum = 200)]
|
||||||
pub limit: i64,
|
pub limit: i64,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -341,10 +396,15 @@ impl SbomFilter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
/// The target and format of an SBOM export.
|
||||||
|
#[derive(Deserialize, utoipa::IntoParams)]
|
||||||
|
#[into_params(parameter_in = Query)]
|
||||||
pub struct SbomExportParams {
|
pub struct SbomExportParams {
|
||||||
|
/// The target (its id).
|
||||||
pub repo_id: String,
|
pub repo_id: String,
|
||||||
|
/// `cyclonedx` (default) or `spdx`.
|
||||||
#[serde(default = "default_export_format")]
|
#[serde(default = "default_export_format")]
|
||||||
|
#[param(example = "cyclonedx")]
|
||||||
pub format: String,
|
pub format: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -352,9 +412,13 @@ fn default_export_format() -> String {
|
|||||||
"cyclonedx".to_string()
|
"cyclonedx".to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
/// The two targets an SBOM diff compares.
|
||||||
|
#[derive(Deserialize, utoipa::IntoParams)]
|
||||||
|
#[into_params(parameter_in = Query)]
|
||||||
pub struct SbomDiffParams {
|
pub struct SbomDiffParams {
|
||||||
|
/// The first target (its id).
|
||||||
pub repo_a: String,
|
pub repo_a: String,
|
||||||
|
/// The second target (its id).
|
||||||
pub repo_b: String,
|
pub repo_b: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -112,9 +112,19 @@ fn state_counts(controls: &[crate::evidence::compliance::ControlStatus]) -> serd
|
|||||||
/// Targets whose CRA status is computed at the same time for the summary.
|
/// Targets whose CRA status is computed at the same time for the summary.
|
||||||
const SUMMARY_CONCURRENCY: usize = 4;
|
const SUMMARY_CONCURRENCY: usize = 4;
|
||||||
|
|
||||||
/// GET /api/v1/compliance/summary — every target's CRA state counts, for the
|
/// Every target's CRA control counts per state, for the overview.
|
||||||
/// overview. A target too large to evaluate in memory is listed with
|
///
|
||||||
/// `counts: null` rather than failing the whole summary.
|
/// A target too large to evaluate in memory is listed with `counts: null`
|
||||||
|
/// rather than failing the whole summary.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/compliance/summary",
|
||||||
|
tag = "Compliance",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The counts per target"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn compliance_summary(
|
pub async fn compliance_summary(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -158,8 +168,22 @@ pub async fn compliance_summary(
|
|||||||
Ok(Json(serde_json::json!({ "data": rows })))
|
Ok(Json(serde_json::json!({ "data": rows })))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/targets/{id}/compliance — the target's state against every CRA
|
/// A target's state against every CRA Annex I control.
|
||||||
/// Annex I control, with the findings against each and the last scan.
|
///
|
||||||
|
/// With the findings against each and the last scan.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/targets/{id}/compliance",
|
||||||
|
tag = "Compliance",
|
||||||
|
params(("id" = String, Path, description = "The target's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The state per control"),
|
||||||
|
(status = 400, description = "Not an id"),
|
||||||
|
(status = 404, description = "No such target"),
|
||||||
|
(status = 413, description = "Too large to evaluate in memory"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||||
pub async fn compliance_view(
|
pub async fn compliance_view(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -173,6 +197,9 @@ pub async fn compliance_view(
|
|||||||
"data": {
|
"data": {
|
||||||
"target_id": id,
|
"target_id": id,
|
||||||
"target_name": inputs.target.name,
|
"target_name": inputs.target.name,
|
||||||
|
// Whether Prüfwerk opens tickets for the target's findings; the
|
||||||
|
// finding page offers Breakpilot Git when it does not.
|
||||||
|
"issue_tracker_connected": inputs.target.issue_tracker_connected(),
|
||||||
"counts": state_counts(&controls),
|
"counts": state_counts(&controls),
|
||||||
"last_scan": inputs.last_run,
|
"last_scan": inputs.last_run,
|
||||||
"sbom_components": inputs.sbom.len(),
|
"sbom_components": inputs.sbom.len(),
|
||||||
@@ -182,8 +209,22 @@ pub async fn compliance_view(
|
|||||||
})))
|
})))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/targets/{id}/evidence-pack — 404 for an unknown target, 413
|
/// A target's evidence pack to download.
|
||||||
/// when it is too large to build in memory.
|
///
|
||||||
|
/// 404 for an unknown target, 413 when it is too large to build in memory.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/targets/{id}/evidence-pack",
|
||||||
|
tag = "Compliance",
|
||||||
|
params(("id" = String, Path, description = "The target's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The evidence pack"),
|
||||||
|
(status = 400, description = "Not an id"),
|
||||||
|
(status = 404, description = "No such target"),
|
||||||
|
(status = 413, description = "Too large to build in memory"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||||
pub async fn evidence_pack(
|
pub async fn evidence_pack(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -228,14 +269,28 @@ pub async fn evidence_pack(
|
|||||||
const MAX_CONTROL_LOOKUP: usize = 50;
|
const MAX_CONTROL_LOOKUP: usize = 50;
|
||||||
|
|
||||||
/// The query of [`describe_controls`]: comma-separated control ids.
|
/// The query of [`describe_controls`]: comma-separated control ids.
|
||||||
#[derive(Debug, serde::Deserialize)]
|
#[derive(Debug, serde::Deserialize, utoipa::IntoParams)]
|
||||||
|
#[into_params(parameter_in = Query)]
|
||||||
pub struct ControlIdsQuery {
|
pub struct ControlIdsQuery {
|
||||||
|
/// The master control ids, comma-separated, at most 50.
|
||||||
|
#[param(example = "mc-1,mc-2")]
|
||||||
ids: String,
|
ids: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/controls?ids=mc-1,mc-2 — what the master controls stamped on
|
/// What the master controls stamped on a finding require.
|
||||||
/// a finding require, for the finding page. Unknown ids are left out; at
|
///
|
||||||
/// most [`MAX_CONTROL_LOOKUP`] are described.
|
/// For the finding page. Unknown ids are left out; at most
|
||||||
|
/// [`MAX_CONTROL_LOOKUP`] are described.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/controls",
|
||||||
|
tag = "Compliance",
|
||||||
|
params(ControlIdsQuery),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The controls"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn describe_controls(
|
pub async fn describe_controls(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
|
|||||||
@@ -18,11 +18,22 @@ fn open_findings_of(target_id: &str) -> mongodb::bson::Document {
|
|||||||
doc! { "repo_id": target_id, "status": { "$in": open } }
|
doc! { "repo_id": target_id, "status": { "$in": open } }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The open findings of target `id`, counted by type and severity and by
|
/// A target's open findings, counted by type and severity and by folder.
|
||||||
/// folder. Tenant-scoped like the findings list, and read-only, so every
|
///
|
||||||
|
/// Tenant-scoped like the findings list, and read-only, so every
|
||||||
/// role that may read findings may read it. A target without open findings
|
/// role that may read findings may read it. A target without open findings
|
||||||
/// (or of another tenant, whose findings are not in this tenant's database)
|
/// (or of another tenant, whose findings are not in this tenant's database)
|
||||||
/// gets an empty breakdown.
|
/// gets an empty breakdown.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/targets/{id}/finding-breakdown",
|
||||||
|
tag = "Findings",
|
||||||
|
params(("id" = String, Path, description = "The target's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The breakdown"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||||
pub async fn finding_breakdown(
|
pub async fn finding_breakdown(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
|
|||||||
@@ -22,7 +22,8 @@ use compliance_core::models::{Finding, FindingStatus};
|
|||||||
use compliance_core::tenant_ctx::TenantCtx;
|
use compliance_core::tenant_ctx::TenantCtx;
|
||||||
|
|
||||||
/// The query of [`list_finding_groups`].
|
/// The query of [`list_finding_groups`].
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize, utoipa::IntoParams)]
|
||||||
|
#[into_params(parameter_in = Query)]
|
||||||
pub struct GroupsQuery {
|
pub struct GroupsQuery {
|
||||||
/// Only one target's findings (`Finding::repo_id`).
|
/// Only one target's findings (`Finding::repo_id`).
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
@@ -30,11 +31,13 @@ pub struct GroupsQuery {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The body of [`decide_finding_group`].
|
/// The body of [`decide_finding_group`].
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||||
pub struct DecideGroupRequest {
|
pub struct DecideGroupRequest {
|
||||||
/// The group, as [`list_finding_groups`] named it.
|
/// The group, as [`list_finding_groups`] named it.
|
||||||
|
#[schema(value_type = Object)]
|
||||||
pub key: GroupKey,
|
pub key: GroupKey,
|
||||||
/// The decision for every member.
|
/// The decision for every member, a finding status.
|
||||||
|
#[schema(value_type = String, example = "false_positive")]
|
||||||
pub status: FindingStatus,
|
pub status: FindingStatus,
|
||||||
/// Why; required for an accepted risk or a wrong mapping.
|
/// Why; required for an accepted risk or a wrong mapping.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
@@ -71,9 +74,19 @@ async fn undecided_findings(
|
|||||||
Ok(collect_cursor_async(cursor).await)
|
Ok(collect_cursor_async(cursor).await)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/finding-groups[?target=] — the undecided findings, grouped
|
/// List the undecided findings, grouped by rule and file.
|
||||||
/// by rule and file (see [`compliance_core::models::finding_group`]), most
|
///
|
||||||
/// severe first.
|
/// Most severe first (see [`compliance_core::models::finding_group`]).
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/finding-groups",
|
||||||
|
tag = "Findings",
|
||||||
|
params(GroupsQuery),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The groups, most severe first"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(target = ?query.target))]
|
#[tracing::instrument(skip_all, fields(target = ?query.target))]
|
||||||
pub async fn list_finding_groups(
|
pub async fn list_finding_groups(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -134,12 +147,25 @@ fn candidates_filter(key: &GroupKey) -> Document {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /api/v1/finding-groups/decide — give every undecided member of a
|
/// Decide every undecided finding of a group at once.
|
||||||
/// group the same status, as if each were changed on its own.
|
///
|
||||||
|
/// Each member gets the same status, as if each were changed on its own.
|
||||||
///
|
///
|
||||||
/// The members are found again from the key, so a member someone decided
|
/// The members are found again from the key, so a member someone decided
|
||||||
/// in the meantime keeps that decision. 404 when the group has no undecided
|
/// in the meantime keeps that decision. 404 when the group has no undecided
|
||||||
/// member (any more), 422 as [`decision_update`].
|
/// member (any more), 422 as [`decision_update`].
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/finding-groups/decide",
|
||||||
|
tag = "Findings",
|
||||||
|
request_body = DecideGroupRequest,
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The members were decided"),
|
||||||
|
(status = 404, description = "The group has no undecided member"),
|
||||||
|
(status = 422, description = "An unknown status, or no reason for one that needs it"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(rule = %req.key.rule, scope = ?req.key.scope))]
|
#[tracing::instrument(skip_all, fields(rule = %req.key.rule, scope = ?req.key.scope))]
|
||||||
pub async fn decide_finding_group(
|
pub async fn decide_finding_group(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
|
|||||||
@@ -7,6 +7,17 @@ use super::dto::*;
|
|||||||
use compliance_core::models::{Finding, FindingStatus, StatusChange};
|
use compliance_core::models::{Finding, FindingStatus, StatusChange};
|
||||||
use compliance_core::tenant_ctx::TenantCtx;
|
use compliance_core::tenant_ctx::TenantCtx;
|
||||||
|
|
||||||
|
/// List the tenant's findings, filtered, sorted and a page at a time.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/findings",
|
||||||
|
tag = "Findings",
|
||||||
|
params(FindingsFilter),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "A page of findings"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(repo_id = ?filter.repo_id, severity = ?filter.severity, scan_type = ?filter.scan_type))]
|
#[tracing::instrument(skip_all, fields(repo_id = ?filter.repo_id, severity = ?filter.severity, scan_type = ?filter.scan_type))]
|
||||||
pub async fn list_findings(
|
pub async fn list_findings(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -28,6 +39,9 @@ pub async fn list_findings(
|
|||||||
if let Some(scan_type) = &filter.scan_type {
|
if let Some(scan_type) = &filter.scan_type {
|
||||||
query.insert("scan_type", scan_type);
|
query.insert("scan_type", scan_type);
|
||||||
}
|
}
|
||||||
|
if let Some(scanner) = &filter.scanner {
|
||||||
|
query.insert("scanner", scanner);
|
||||||
|
}
|
||||||
if let Some(status) = &filter.status {
|
if let Some(status) = &filter.status {
|
||||||
query.insert("status", status_filter(status));
|
query.insert("status", status_filter(status));
|
||||||
}
|
}
|
||||||
@@ -141,15 +155,27 @@ fn severity_rank() -> mongodb::bson::Document {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The query of [`list_finding_variants`].
|
/// The query of [`list_finding_variants`].
|
||||||
#[derive(Debug, serde::Deserialize)]
|
#[derive(Debug, serde::Deserialize, utoipa::IntoParams)]
|
||||||
|
#[into_params(parameter_in = Query)]
|
||||||
pub struct VariantsQuery {
|
pub struct VariantsQuery {
|
||||||
/// Only one target's variants.
|
/// Only one target's variants.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub repo_id: Option<String>,
|
pub repo_id: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The app variants the tenant's findings are labelled with (theirs and their
|
/// List the app variants the tenant's findings are in.
|
||||||
/// groups' places), sorted, for the findings filter.
|
///
|
||||||
|
/// Their own and their groups' places, sorted, for the findings filter.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/findings/variants",
|
||||||
|
tag = "Findings",
|
||||||
|
params(VariantsQuery),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The app variant names, sorted"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(repo_id = ?query.repo_id))]
|
#[tracing::instrument(skip_all, fields(repo_id = ?query.repo_id))]
|
||||||
pub async fn list_finding_variants(
|
pub async fn list_finding_variants(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -180,6 +206,19 @@ pub async fn list_finding_variants(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One finding.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/findings/{id}",
|
||||||
|
tag = "Findings",
|
||||||
|
params(("id" = String, Path, description = "The finding's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The finding"),
|
||||||
|
(status = 400, description = "Not an id"),
|
||||||
|
(status = 404, description = "No such finding"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(finding_id = %id))]
|
#[tracing::instrument(skip_all, fields(finding_id = %id))]
|
||||||
pub async fn get_finding(
|
pub async fn get_finding(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -270,8 +309,23 @@ fn issue_sync(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// PATCH /api/v1/findings/{id}/status — change the status, recording who,
|
/// Change a finding's status.
|
||||||
/// when and why. 404 when there is no such finding.
|
///
|
||||||
|
/// Records who, when and why. 404 when there is no such finding.
|
||||||
|
#[utoipa::path(
|
||||||
|
patch,
|
||||||
|
path = "/api/v1/findings/{id}/status",
|
||||||
|
tag = "Findings",
|
||||||
|
params(("id" = String, Path, description = "The finding's id")),
|
||||||
|
request_body = UpdateStatusRequest,
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The status was changed"),
|
||||||
|
(status = 400, description = "Not an id"),
|
||||||
|
(status = 404, description = "No such finding"),
|
||||||
|
(status = 422, description = "An unknown status, or no reason for one that needs it"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(finding_id = %id))]
|
#[tracing::instrument(skip_all, fields(finding_id = %id))]
|
||||||
pub async fn update_finding_status(
|
pub async fn update_finding_status(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -296,7 +350,19 @@ pub async fn update_finding_status(
|
|||||||
Ok(Json(serde_json::json!({ "status": "updated" })))
|
Ok(Json(serde_json::json!({ "status": "updated" })))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// PATCH /api/v1/findings/bulk-status — the same change on many findings.
|
/// Change the status of many findings at once.
|
||||||
|
#[utoipa::path(
|
||||||
|
patch,
|
||||||
|
path = "/api/v1/findings/bulk-status",
|
||||||
|
tag = "Findings",
|
||||||
|
request_body = BulkUpdateStatusRequest,
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "How many findings changed"),
|
||||||
|
(status = 400, description = "An id that is not one"),
|
||||||
|
(status = 422, description = "An unknown status, or no reason for one that needs it"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn bulk_update_finding_status(
|
pub async fn bulk_update_finding_status(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -351,8 +417,22 @@ pub(crate) async fn apply_status(
|
|||||||
Ok(result.modified_count)
|
Ok(result.modified_count)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// PATCH /api/v1/findings/{id}/feedback — store the developer's feedback on a
|
/// Store a developer's feedback on a finding.
|
||||||
/// finding. 404 when there is no such finding.
|
///
|
||||||
|
/// 404 when there is no such finding.
|
||||||
|
#[utoipa::path(
|
||||||
|
patch,
|
||||||
|
path = "/api/v1/findings/{id}/feedback",
|
||||||
|
tag = "Findings",
|
||||||
|
params(("id" = String, Path, description = "The finding's id")),
|
||||||
|
request_body = UpdateFeedbackRequest,
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The feedback was stored"),
|
||||||
|
(status = 400, description = "Not an id"),
|
||||||
|
(status = 404, description = "No such finding"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(finding_id = %id))]
|
#[tracing::instrument(skip_all, fields(finding_id = %id))]
|
||||||
pub async fn update_finding_feedback(
|
pub async fn update_finding_feedback(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
|
|||||||
@@ -6,19 +6,31 @@ use axum::http::StatusCode;
|
|||||||
use axum::Json;
|
use axum::Json;
|
||||||
|
|
||||||
use compliance_core::models::GitSourceView;
|
use compliance_core::models::GitSourceView;
|
||||||
use compliance_core::tenant::OrgRole;
|
|
||||||
use compliance_core::tenant_ctx::TenantCtx;
|
use compliance_core::tenant_ctx::TenantCtx;
|
||||||
|
|
||||||
use super::dto::{tenant_db, AgentExt};
|
use super::dto::{tenant_db, AgentExt};
|
||||||
use super::ApiResponse;
|
use super::ApiResponse;
|
||||||
|
|
||||||
/// Whether the caller may see the git source: IT administrators and support.
|
/// Whether the caller may see the git source: administrators (IT_ADMIN,
|
||||||
|
/// OWNER) and support.
|
||||||
fn may_view(tenant: &TenantCtx) -> bool {
|
fn may_view(tenant: &TenantCtx) -> bool {
|
||||||
tenant.0.staff.is_some() || tenant.0.org_roles.contains(&OrgRole::ItAdmin)
|
tenant.0.staff.is_some() || tenant.0.is_admin()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The source without secrets, plus the webhook URL; `data: null` when the
|
/// The workspace's managed git source, without secrets.
|
||||||
/// workspace has none.
|
///
|
||||||
|
/// Plus the webhook URL; `data: null` when the workspace has none. For
|
||||||
|
/// administrators (IT_ADMIN, OWNER) and support.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/git-source",
|
||||||
|
tag = "Workspace",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The source, or null"),
|
||||||
|
(status = 403, description = "Not an administrator or support"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
pub async fn get_git_source(
|
pub async fn get_git_source(
|
||||||
axum::extract::Extension(agent): AgentExt,
|
axum::extract::Extension(agent): AgentExt,
|
||||||
tenant: TenantCtx,
|
tenant: TenantCtx,
|
||||||
|
|||||||
@@ -42,14 +42,18 @@ pub struct GraphData {
|
|||||||
pub total_nodes: u64,
|
pub total_nodes: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
/// A symbol search.
|
||||||
|
#[derive(Deserialize, utoipa::IntoParams)]
|
||||||
|
#[into_params(parameter_in = Query)]
|
||||||
pub struct SearchParams {
|
pub struct SearchParams {
|
||||||
|
/// The search text.
|
||||||
pub q: String,
|
pub q: String,
|
||||||
/// Clamped to `1..=MAX_PAGE_SIZE` while deserializing, like every list.
|
/// Clamped to `1..=MAX_PAGE_SIZE` while deserializing, like every list.
|
||||||
#[serde(
|
#[serde(
|
||||||
default = "default_search_limit",
|
default = "default_search_limit",
|
||||||
deserialize_with = "super::dto::de_limit"
|
deserialize_with = "super::dto::de_limit"
|
||||||
)]
|
)]
|
||||||
|
#[param(minimum = 1, maximum = 200)]
|
||||||
pub limit: i64,
|
pub limit: i64,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,7 +61,19 @@ fn default_search_limit() -> i64 {
|
|||||||
50
|
50
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/graph/:repo_id — Full graph data
|
/// A target's code graph: its latest build, nodes and edges.
|
||||||
|
///
|
||||||
|
/// Truncated past a size a browser can lay out, and says so.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/graph/{repo_id}",
|
||||||
|
tag = "Code graph",
|
||||||
|
params(("repo_id" = String, Path, description = "The target's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The graph"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||||
pub async fn get_graph(
|
pub async fn get_graph(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -150,7 +166,17 @@ pub async fn get_graph(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/graph/:repo_id/nodes — List nodes (paginated)
|
/// A target's code graph nodes, a page at a time.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/graph/{repo_id}/nodes",
|
||||||
|
tag = "Code graph",
|
||||||
|
params(("repo_id" = String, Path, description = "The target's id"), PaginationParams),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "A page of nodes"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||||
pub async fn get_nodes(
|
pub async fn get_nodes(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -222,8 +248,19 @@ impl GraphSummary {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/graph/:repo_id/summary — The latest build's counts, without
|
/// The counts of a target's latest graph build, without loading any node.
|
||||||
/// loading any node: `data` is `null` when there is none to show.
|
///
|
||||||
|
/// `data` is `null` when there is none to show.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/graph/{repo_id}/summary",
|
||||||
|
tag = "Code graph",
|
||||||
|
params(("repo_id" = String, Path, description = "The target's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The counts, or null"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||||
pub async fn get_summary(
|
pub async fn get_summary(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -244,7 +281,17 @@ pub async fn get_summary(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/graph/:repo_id/communities — List detected communities
|
/// The communities detected in a target's code graph.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/graph/{repo_id}/communities",
|
||||||
|
tag = "Code graph",
|
||||||
|
params(("repo_id" = String, Path, description = "The target's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The communities"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||||
pub async fn get_communities(
|
pub async fn get_communities(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -312,7 +359,17 @@ pub struct CommunityInfo {
|
|||||||
pub members: Vec<String>,
|
pub members: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/graph/:repo_id/impact/:finding_id — Impact analysis
|
/// What a finding reaches in a target's code graph.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/graph/{repo_id}/impact/{finding_id}",
|
||||||
|
tag = "Code graph",
|
||||||
|
params(("repo_id" = String, Path, description = "The target's id"), ("finding_id" = String, Path, description = "The finding's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The impact analysis, or null"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id, finding_id = %finding_id))]
|
#[tracing::instrument(skip_all, fields(repo_id = %repo_id, finding_id = %finding_id))]
|
||||||
pub async fn get_impact(
|
pub async fn get_impact(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -336,7 +393,17 @@ pub async fn get_impact(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/graph/:repo_id/search — BM25 symbol search
|
/// Search a target's code graph for symbols (BM25).
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/graph/{repo_id}/search",
|
||||||
|
tag = "Code graph",
|
||||||
|
params(("repo_id" = String, Path, description = "The target's id"), SearchParams),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The matching nodes"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id, query = %params.q))]
|
#[tracing::instrument(skip_all, fields(repo_id = %repo_id, query = %params.q))]
|
||||||
pub async fn search_symbols(
|
pub async fn search_symbols(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -370,7 +437,19 @@ pub async fn search_symbols(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/graph/:repo_id/file-content — Read source file from cloned repo
|
/// A source file of a target's checkout.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/graph/{repo_id}/file-content",
|
||||||
|
tag = "Code graph",
|
||||||
|
params(("repo_id" = String, Path, description = "The target's id"), FileContentParams),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The file"),
|
||||||
|
(status = 403, description = "The path leaves the checkout"),
|
||||||
|
(status = 404, description = "No such target, checkout or file"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||||
pub async fn get_file_content(
|
pub async fn get_file_content(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -431,8 +510,11 @@ pub async fn get_file_content(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
/// The file of [`get_file_content`].
|
||||||
|
#[derive(Deserialize, utoipa::IntoParams)]
|
||||||
|
#[into_params(parameter_in = Query)]
|
||||||
pub struct FileContentParams {
|
pub struct FileContentParams {
|
||||||
|
/// The file's path in the checkout.
|
||||||
pub path: String,
|
pub path: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -443,7 +525,17 @@ pub struct FileContent {
|
|||||||
pub language: String,
|
pub language: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /api/v1/graph/:repo_id/build — Trigger graph rebuild
|
/// Rebuild a target's code graph in the background.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/graph/{repo_id}/build",
|
||||||
|
tag = "Code graph",
|
||||||
|
params(("repo_id" = String, Path, description = "The target's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The build was started"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||||
pub async fn trigger_build(
|
pub async fn trigger_build(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
|
|||||||
@@ -5,9 +5,21 @@ use super::dto::*;
|
|||||||
use compliance_core::models::ScanRun;
|
use compliance_core::models::ScanRun;
|
||||||
use compliance_core::tenant_ctx::TenantCtx;
|
use compliance_core::tenant_ctx::TenantCtx;
|
||||||
|
|
||||||
/// `GET /api/v1/access`: reached only when the authentication, entitlement
|
/// Whether the caller may use Prüfwerk at all.
|
||||||
/// and role layers let the caller through; they answer the refusals (a
|
///
|
||||||
/// blocked member gets 403 `MEMBER_BLOCKED`).
|
/// Reached only when the authentication, entitlement and role layers let the
|
||||||
|
/// caller through; they answer the refusals (a blocked member gets 403
|
||||||
|
/// `MEMBER_BLOCKED`).
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/access",
|
||||||
|
tag = "Workspace",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The caller may use Prüfwerk"),
|
||||||
|
(status = 403, description = "Not entitled, or a blocked member"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn access() -> Json<serde_json::Value> {
|
pub async fn access() -> Json<serde_json::Value> {
|
||||||
Json(serde_json::json!({ "access": true }))
|
Json(serde_json::json!({ "access": true }))
|
||||||
@@ -16,10 +28,21 @@ pub async fn access() -> Json<serde_json::Value> {
|
|||||||
/// How long the health check waits for MongoDB before it reports it down.
|
/// How long the health check waits for MongoDB before it reports it down.
|
||||||
const DB_PING_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
|
const DB_PING_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
|
||||||
|
|
||||||
/// `GET /api/v1/health`: 200 `{"status":"ok"}` when MongoDB answers a ping,
|
/// Whether the agent can serve: MongoDB answers a ping.
|
||||||
/// 503 `{"status":"degraded","mongo":"unreachable"}` when it does not, so a
|
///
|
||||||
/// load balancer and the container health check stop sending traffic to an
|
/// 200 `{"status":"ok"}` when MongoDB answers, 503
|
||||||
|
/// `{"status":"degraded","mongo":"unreachable"}` when it does not, so a load
|
||||||
|
/// balancer and the container health check stop sending traffic to an
|
||||||
/// instance that cannot serve it (#60). Public, untraced, no tenant.
|
/// instance that cannot serve it (#60). Public, untraced, no tenant.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/health",
|
||||||
|
tag = "Health",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "MongoDB answers"),
|
||||||
|
(status = 503, description = "MongoDB is unreachable"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn health(
|
pub async fn health(
|
||||||
axum::extract::Extension(agent): AgentExt,
|
axum::extract::Extension(agent): AgentExt,
|
||||||
@@ -93,6 +116,16 @@ pub(crate) async fn open_findings_by_severity(
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The counts the overview page shows for the tenant.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/stats/overview",
|
||||||
|
tag = "Workspace",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The counts"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn stats_overview(
|
pub async fn stats_overview(
|
||||||
axum::extract::Extension(agent): AgentExt,
|
axum::extract::Extension(agent): AgentExt,
|
||||||
|
|||||||
@@ -11,15 +11,21 @@ use super::dto::{AgentExt, ApiResponse};
|
|||||||
|
|
||||||
// ── DTOs ─────────────────────────────────────────────────────────────────────
|
// ── DTOs ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
/// An earlier turn of a help chat.
|
||||||
|
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||||
pub struct HelpChatMessage {
|
pub struct HelpChatMessage {
|
||||||
|
/// `user` or `assistant`.
|
||||||
pub role: String,
|
pub role: String,
|
||||||
|
/// What was said.
|
||||||
pub content: String,
|
pub content: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
/// The body of [`help_chat`].
|
||||||
|
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||||
pub struct HelpChatRequest {
|
pub struct HelpChatRequest {
|
||||||
|
/// The question.
|
||||||
pub message: String,
|
pub message: String,
|
||||||
|
/// The earlier turns, oldest first.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub history: Vec<HelpChatMessage>,
|
pub history: Vec<HelpChatMessage>,
|
||||||
}
|
}
|
||||||
@@ -170,8 +176,17 @@ fn doc_context() -> &'static str {
|
|||||||
|
|
||||||
// ── Handler ──────────────────────────────────────────────────────────────────
|
// ── Handler ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
/// POST /api/v1/help/chat — Answer questions about the compliance-scanner
|
/// Ask about Prüfwerk, answered from its published documentation.
|
||||||
/// using the project documentation as grounding context.
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/help/chat",
|
||||||
|
tag = "Help",
|
||||||
|
request_body = HelpChatRequest,
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The answer"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn help_chat(
|
pub async fn help_chat(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
|
|||||||
@@ -55,16 +55,20 @@ fn store_error(e: mongodb::error::Error) -> Refusal {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The query of [`get_inbox`].
|
/// The query of [`get_inbox`].
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize, utoipa::IntoParams)]
|
||||||
|
#[into_params(parameter_in = Query)]
|
||||||
pub struct InboxQuery {
|
pub struct InboxQuery {
|
||||||
/// Only this target's cards, counts and Erstbewertung.
|
/// Only this target's cards, counts and Erstbewertung.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub target: Option<String>,
|
pub target: Option<String>,
|
||||||
/// The bucket whose cards to list (default `today`).
|
/// The bucket whose cards to list: `today` (default), `this_week`,
|
||||||
|
/// `later` or `likely_false_positive`.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
#[param(value_type = Option<String>, example = "this_week")]
|
||||||
pub bucket: Option<Bucket>,
|
pub bucket: Option<Bucket>,
|
||||||
/// The most cards to list (default 100, at most 500).
|
/// The most cards to list (default 100, at most 500).
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
#[param(minimum = 1, maximum = 500)]
|
||||||
pub limit: Option<usize>,
|
pub limit: Option<usize>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -174,13 +178,24 @@ async fn progress(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/inbox[?target=<id>&bucket=<bucket>&limit=<n>] — the bucket
|
/// The open decisions in urgency buckets, most urgent first.
|
||||||
/// counts, the Erstbewertung, the targets with cards, and the cards of one
|
///
|
||||||
/// bucket (default `today`), most urgent first.
|
/// The bucket counts, the Erstbewertung, the targets with cards, and the
|
||||||
|
/// cards of one bucket (default `today`).
|
||||||
///
|
///
|
||||||
/// Cards: one per finding, one per target, package and version for CVE
|
/// Cards: one per finding, one per target, package and version for CVE
|
||||||
/// alerts. Cards put off until a date are left out until then and come back
|
/// alerts. Cards put off until a date are left out until then and come back
|
||||||
/// under `later`.
|
/// under `later`.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/inbox",
|
||||||
|
tag = "Inbox",
|
||||||
|
params(InboxQuery),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The buckets and cards"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(target = ?query.target, bucket = ?query.bucket))]
|
#[tracing::instrument(skip_all, fields(target = ?query.target, bucket = ?query.bucket))]
|
||||||
pub async fn get_inbox(
|
pub async fn get_inbox(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -324,13 +339,27 @@ async fn set_vex(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /api/v1/inbox/decide `{key, action, reason?, justification?,
|
/// Decide on every item of a card.
|
||||||
/// statement?}` — apply `action` to every item of card `key`, through the
|
///
|
||||||
/// findings' and the VEX endpoints' code, and answer what each item was
|
/// `{key, action, reason?, justification?, statement?}`: apply `action`
|
||||||
/// before (for `POST /api/v1/inbox/undo`). The card's resubmission, if any,
|
/// through the findings' and the VEX endpoints' code, and answer what each
|
||||||
/// is dropped. 409 when nothing on the card waits any more, 422 for an action
|
/// item was before (for `POST /api/v1/inbox/undo`). The card's resubmission,
|
||||||
/// the card does not offer or without the reason, justification or statement
|
/// if any, is dropped. 409 when nothing on the card waits any more, 422 for an
|
||||||
/// it needs.
|
/// action the card does not offer or without the reason, justification or
|
||||||
|
/// statement it needs.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/inbox/decide",
|
||||||
|
tag = "Inbox",
|
||||||
|
request_body(content = Object, description = "`key`, `action`, and the `reason`, `justification` or `statement` the action needs"),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "Decided, with what each item was before"),
|
||||||
|
(status = 400, description = "A malformed key"),
|
||||||
|
(status = 409, description = "Nothing on the card waits for a decision"),
|
||||||
|
(status = 422, description = "An action the card does not offer, or what it needs is missing"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(key = %req.key, action = ?req.action))]
|
#[tracing::instrument(skip_all, fields(key = %req.key, action = ?req.action))]
|
||||||
pub async fn decide(
|
pub async fn decide(
|
||||||
agent: AgentExt,
|
agent: AgentExt,
|
||||||
@@ -431,12 +460,26 @@ async fn belongs_to(db: &Database, key: &str, previous: &[PreviousState]) -> Res
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /api/v1/inbox/undo `{key, previous}` — put the items of a decision
|
/// Undo a decision on a card.
|
||||||
/// on card `key` back, through the same code the decision went through: a
|
///
|
||||||
/// finding gets its previous status (a new entry in its history, which keeps
|
/// `{key, previous}`: put the items back through the same code the decision
|
||||||
/// the decision on record), an alert `under_investigation` (also when it had
|
/// went through. A finding gets its previous status (a new entry in its
|
||||||
/// no statement before; both leave it open). 422 when an item does not
|
/// history, which keeps the decision on record), an alert
|
||||||
/// belong to the card or its previous state was not an open one.
|
/// `under_investigation` (also when it had no statement before; both leave
|
||||||
|
/// it open). 422 when an item does not belong to the card or its previous
|
||||||
|
/// state was not an open one.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/inbox/undo",
|
||||||
|
tag = "Inbox",
|
||||||
|
request_body(content = Object, description = "`key`, and `previous` as the decision answered it"),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "Put back"),
|
||||||
|
(status = 400, description = "A malformed key or id"),
|
||||||
|
(status = 422, description = "An item not of the card, or not open before"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(key = %req.key))]
|
#[tracing::instrument(skip_all, fields(key = %req.key))]
|
||||||
pub async fn undo(
|
pub async fn undo(
|
||||||
agent: AgentExt,
|
agent: AgentExt,
|
||||||
@@ -486,13 +529,27 @@ pub async fn undo(
|
|||||||
Ok(Json(serde_json::json!({ "status": "restored" })))
|
Ok(Json(serde_json::json!({ "status": "restored" })))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /api/v1/inbox/snooze `{key, for}` — put card `key` off: one week, one
|
/// Put a card off: one week, one month, or until a date.
|
||||||
/// month, or until a date (`{"kind": "date", "date": "2026-12-01"}`). It is
|
///
|
||||||
/// hidden until then and comes back in its own bucket, or earlier when a new
|
/// `{key, for}`, `for` as `{"kind": "week"}`, `{"kind": "month"}` or
|
||||||
|
/// `{"kind": "date", "date": "2026-12-01"}`. It is hidden until then and comes back in its own bucket, or earlier when a new
|
||||||
/// CVE or a KEV entry joins it: the snooze records the card's items and
|
/// CVE or a KEV entry joins it: the snooze records the card's items and
|
||||||
/// whether it was KEV. A second snooze replaces the first. 400 for a
|
/// whether it was KEV. A second snooze replaces the first. 400 for a
|
||||||
/// malformed key, 409 when nothing on the card waits for a decision, 422 for
|
/// malformed key, 409 when nothing on the card waits for a decision, 422 for
|
||||||
/// a date that is not in the future.
|
/// a date that is not in the future.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/inbox/snooze",
|
||||||
|
tag = "Inbox",
|
||||||
|
request_body(content = Object, description = "`key`, and `for`: a week, a month or a date"),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "When the card comes back"),
|
||||||
|
(status = 400, description = "A malformed key"),
|
||||||
|
(status = 409, description = "Nothing on the card waits for a decision"),
|
||||||
|
(status = 422, description = "A date that is not in the future"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(key = %req.key))]
|
#[tracing::instrument(skip_all, fields(key = %req.key))]
|
||||||
pub async fn snooze(
|
pub async fn snooze(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -532,8 +589,20 @@ pub async fn snooze(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// DELETE /api/v1/inbox/snooze/{key} — take card `key`'s resubmission back
|
/// Take a card's resubmission back (the undo of a snooze).
|
||||||
/// (the undo of a snooze); nothing to take back is no error.
|
///
|
||||||
|
/// Nothing to take back is no error.
|
||||||
|
#[utoipa::path(
|
||||||
|
delete,
|
||||||
|
path = "/api/v1/inbox/snooze/{key}",
|
||||||
|
tag = "Inbox",
|
||||||
|
params(("key" = String, Path, description = "The card's key")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The resubmission is gone"),
|
||||||
|
(status = 400, description = "A malformed key"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(key = %key))]
|
#[tracing::instrument(skip_all, fields(key = %key))]
|
||||||
pub async fn unsnooze(
|
pub async fn unsnooze(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
|
|||||||
@@ -7,10 +7,21 @@ use compliance_core::models::issue::cve_issue_prefix;
|
|||||||
use compliance_core::models::TrackerIssue;
|
use compliance_core::models::TrackerIssue;
|
||||||
use compliance_core::tenant_ctx::TenantCtx;
|
use compliance_core::tenant_ctx::TenantCtx;
|
||||||
|
|
||||||
/// The tenant's tickets, newest first, searched and filtered by `filter`.
|
/// The tenant's tickets, newest first, searched and filtered.
|
||||||
///
|
///
|
||||||
/// A ticket stores no target, only the finding it is about: the target filter
|
/// A ticket stores no target, only the finding it is about: the target filter
|
||||||
/// first looks up the ids of the target's findings that have a ticket.
|
/// first looks up the ids of the target's findings that have a ticket.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/issues",
|
||||||
|
tag = "Tickets",
|
||||||
|
params(IssuesFilter),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "A page of tickets"),
|
||||||
|
(status = 400, description = "An unknown status"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(repo_id = ?filter.repo_id, status = ?filter.status))]
|
#[tracing::instrument(skip_all, fields(repo_id = ?filter.repo_id, status = ?filter.status))]
|
||||||
pub async fn list_issues(
|
pub async fn list_issues(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
|
|||||||
@@ -35,12 +35,16 @@ use crate::license_conclusions::MAX_CONCLUSIONS;
|
|||||||
pub const MAX_COMPONENTS: usize = 500;
|
pub const MAX_COMPONENTS: usize = 500;
|
||||||
|
|
||||||
/// A component a licence is confirmed for, as the SBOM list shows it.
|
/// A component a licence is confirmed for, as the SBOM list shows it.
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Deserialize, utoipa::ToSchema)]
|
||||||
pub struct ComponentRef {
|
pub struct ComponentRef {
|
||||||
|
/// The package's name.
|
||||||
pub name: String,
|
pub name: String,
|
||||||
|
/// Its package manager, such as `npm` or `cargo`.
|
||||||
pub package_manager: String,
|
pub package_manager: String,
|
||||||
|
/// Its version; empty with `all_versions`.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub version: String,
|
pub version: String,
|
||||||
|
/// Its purl, when known.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub purl: Option<String>,
|
pub purl: Option<String>,
|
||||||
/// The licence the scan found, as the list shows it. Read only by a
|
/// The licence the scan found, as the list shows it. Read only by a
|
||||||
@@ -50,8 +54,9 @@ pub struct ComponentRef {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The body of [`conclude`].
|
/// The body of [`conclude`].
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||||
pub struct ConcludeRequest {
|
pub struct ConcludeRequest {
|
||||||
|
/// The components, at most 500.
|
||||||
pub components: Vec<ComponentRef>,
|
pub components: Vec<ComponentRef>,
|
||||||
/// For every version of the packages, not just the listed ones.
|
/// For every version of the packages, not just the listed ones.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
@@ -60,25 +65,38 @@ pub struct ConcludeRequest {
|
|||||||
/// licence of its own, named in `license_name`.
|
/// licence of its own, named in `license_name`.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub license: Option<String>,
|
pub license: Option<String>,
|
||||||
|
/// The name of a licence of its own.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub license_name: Option<String>,
|
pub license_name: Option<String>,
|
||||||
/// Used for a licence of its own and where SPDX gives no category.
|
/// Used for a licence of its own and where SPDX gives no category, such
|
||||||
|
/// as `permissive`, `weak_copyleft` or `proprietary`.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
#[schema(value_type = Option<String>, example = "proprietary")]
|
||||||
pub category: Option<LicenseCategory>,
|
pub category: Option<LicenseCategory>,
|
||||||
|
/// The copyright lines.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub copyright: Vec<String>,
|
pub copyright: Vec<String>,
|
||||||
|
/// The licence's text.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub license_text: Option<String>,
|
pub license_text: Option<String>,
|
||||||
|
/// Where the licence is published.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub license_url: Option<String>,
|
pub license_url: Option<String>,
|
||||||
|
/// Where the licence was confirmed, such as a file or a contract.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub evidence: Option<String>,
|
pub evidence: Option<String>,
|
||||||
|
/// The contract a licence of its own comes from.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub contract_ref: Option<String>,
|
pub contract_ref: Option<String>,
|
||||||
|
/// When the licence ends.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
#[schema(value_type = Option<String>, format = Date)]
|
||||||
pub valid_until: Option<NaiveDate>,
|
pub valid_until: Option<NaiveDate>,
|
||||||
|
/// `shipped` or `build_only`.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
#[schema(value_type = Option<String>, example = "shipped")]
|
||||||
pub usage: Option<LicenseUsage>,
|
pub usage: Option<LicenseUsage>,
|
||||||
|
/// A note.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub note: Option<String>,
|
pub note: Option<String>,
|
||||||
}
|
}
|
||||||
@@ -196,8 +214,16 @@ fn conclusions_of(
|
|||||||
Ok(out)
|
Ok(out)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/licenses/conclusions — every licence the workspace
|
/// Every licence the workspace confirmed, by package name.
|
||||||
/// confirmed, by package name.
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/licenses/conclusions",
|
||||||
|
tag = "Licences",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The confirmed licences"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn list_conclusions(
|
pub async fn list_conclusions(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -212,10 +238,22 @@ pub async fn list_conclusions(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// PUT /api/v1/licenses/conclusions — confirm a licence for one or more
|
/// Confirm a licence for one or more components.
|
||||||
/// components (one version, or every version of their packages). A second
|
///
|
||||||
/// confirmation of the same package and version replaces the first. 422
|
/// One version, or every version of their packages. A second confirmation
|
||||||
/// with the reason when the licence or a field is not acceptable.
|
/// of the same package and version replaces the first. 422 with the reason
|
||||||
|
/// when the licence or a field is not acceptable.
|
||||||
|
#[utoipa::path(
|
||||||
|
put,
|
||||||
|
path = "/api/v1/licenses/conclusions",
|
||||||
|
tag = "Licences",
|
||||||
|
request_body = ConcludeRequest,
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The licence was confirmed"),
|
||||||
|
(status = 422, description = "The licence or a field is not acceptable; `error` says why"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn conclude(
|
pub async fn conclude(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -261,15 +299,26 @@ pub async fn conclude(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The query of [`withdraw`].
|
/// The query of [`withdraw`].
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize, utoipa::IntoParams)]
|
||||||
|
#[into_params(parameter_in = Query)]
|
||||||
pub struct WithdrawQuery {
|
pub struct WithdrawQuery {
|
||||||
/// The conclusion's id (package and version, see
|
/// The conclusion's id (package and version, see
|
||||||
/// [`license::conclusion_id`]); a query value, as it holds `/` and `@`.
|
/// [`license::conclusion_id`]); a query value, as it holds `/` and `@`.
|
||||||
pub id: String,
|
pub id: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// DELETE /api/v1/licenses/conclusions?id= — withdraw a confirmed licence;
|
/// Withdraw a confirmed licence; the component shows the detected one again.
|
||||||
/// the component shows the detected one again. 404 when there is none.
|
#[utoipa::path(
|
||||||
|
delete,
|
||||||
|
path = "/api/v1/licenses/conclusions",
|
||||||
|
tag = "Licences",
|
||||||
|
params(WithdrawQuery),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The licence was withdrawn"),
|
||||||
|
(status = 404, description = "No such confirmed licence"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn withdraw(
|
pub async fn withdraw(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -292,12 +341,12 @@ pub async fn withdraw(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Whether the requester may change the policy and decide reviews: LEGAL,
|
/// Whether the requester may change the policy and decide reviews: LEGAL,
|
||||||
/// IT_ADMIN, or BreakPilot support. USER confirms licences but does not
|
/// an administrator (IT_ADMIN, OWNER), or BreakPilot support. USER confirms licences but does not
|
||||||
/// decide whether they may be used.
|
/// decide whether they may be used.
|
||||||
fn may_decide(tenant: &TenantCtx) -> bool {
|
fn may_decide(tenant: &TenantCtx) -> bool {
|
||||||
let ctx = &tenant.0;
|
let ctx = &tenant.0;
|
||||||
ctx.api_key.is_none()
|
ctx.api_key.is_none()
|
||||||
&& (ctx.staff.is_some() || ctx.has_any_role(&[OrgRole::Legal, OrgRole::ItAdmin]))
|
&& (ctx.staff.is_some() || ctx.is_admin() || ctx.has_any_role(&[OrgRole::Legal]))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn refuse_role() -> Refusal {
|
fn refuse_role() -> Refusal {
|
||||||
@@ -306,11 +355,21 @@ fn refuse_role() -> Refusal {
|
|||||||
Json(serde_json::json!({
|
Json(serde_json::json!({
|
||||||
"error": crate::api::role_gate::FORBIDDEN_ROLE,
|
"error": crate::api::role_gate::FORBIDDEN_ROLE,
|
||||||
"access": "read_only",
|
"access": "read_only",
|
||||||
"needs": ["LEGAL", "IT_ADMIN"],
|
"needs": ["LEGAL", "IT_ADMIN", "OWNER"],
|
||||||
})),
|
})),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The workspace's licence policy, and whether the requester may change it.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/licenses/policy",
|
||||||
|
tag = "Licences",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The policy"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn get_policy(
|
pub async fn get_policy(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -324,6 +383,19 @@ pub async fn get_policy(
|
|||||||
})))
|
})))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Replace the workspace's licence policy.
|
||||||
|
#[utoipa::path(
|
||||||
|
put,
|
||||||
|
path = "/api/v1/licenses/policy",
|
||||||
|
tag = "Licences",
|
||||||
|
request_body(content = Object, description = "The policy: which licences are allowed, need a review or are forbidden"),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The policy was saved"),
|
||||||
|
(status = 403, description = "The role may not decide on licences (LEGAL, IT_ADMIN or OWNER)"),
|
||||||
|
(status = 422, description = "The policy is not acceptable; `error` says why"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn put_policy(
|
pub async fn put_policy(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -437,9 +509,11 @@ fn decidable(entry: &SbomEntry) -> bool {
|
|||||||
.is_some_and(|l| spdx_license::is_spdx_expression(&spdx_license::normalise(l)))
|
.is_some_and(|l| spdx_license::is_spdx_expression(&spdx_license::normalise(l)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The query of [`check`] and [`notices`].
|
/// The query of [`check`].
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize, utoipa::IntoParams)]
|
||||||
|
#[into_params(parameter_in = Query)]
|
||||||
pub struct CheckQuery {
|
pub struct CheckQuery {
|
||||||
|
/// Only one target's components; every target's without.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub repo_id: Option<String>,
|
pub repo_id: Option<String>,
|
||||||
}
|
}
|
||||||
@@ -447,6 +521,20 @@ pub struct CheckQuery {
|
|||||||
/// The most open components one check lists.
|
/// The most open components one check lists.
|
||||||
pub const MAX_CHECK_ITEMS: usize = 2_000;
|
pub const MAX_CHECK_ITEMS: usize = 2_000;
|
||||||
|
|
||||||
|
/// Judge the components against the licence policy.
|
||||||
|
///
|
||||||
|
/// The counts per verdict, and the components that are forbidden, need a
|
||||||
|
/// review or expire soon, at most 2 000.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/licenses/check",
|
||||||
|
tag = "Licences",
|
||||||
|
params(CheckQuery),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The verdicts"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn check(
|
pub async fn check(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -522,13 +610,17 @@ pub async fn check(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The body of [`review`].
|
/// The body of [`review`].
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||||
pub struct ReviewRequest {
|
pub struct ReviewRequest {
|
||||||
|
/// The components.
|
||||||
pub components: Vec<ComponentRef>,
|
pub components: Vec<ComponentRef>,
|
||||||
/// For every version of the packages, not just the listed ones.
|
/// For every version of the packages, not just the listed ones.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub all_versions: bool,
|
pub all_versions: bool,
|
||||||
|
/// `approved` or `rejected`.
|
||||||
|
#[schema(value_type = String, example = "approved")]
|
||||||
pub decision: ReviewDecision,
|
pub decision: ReviewDecision,
|
||||||
|
/// Why.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub note: Option<String>,
|
pub note: Option<String>,
|
||||||
}
|
}
|
||||||
@@ -639,6 +731,19 @@ fn reviewed(
|
|||||||
Ok(out)
|
Ok(out)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Decide in a legal review whether the components' licences may be used.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/licenses/review",
|
||||||
|
tag = "Licences",
|
||||||
|
request_body = ReviewRequest,
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The review was saved"),
|
||||||
|
(status = 403, description = "The role may not decide on licences (LEGAL, IT_ADMIN or OWNER)"),
|
||||||
|
(status = 422, description = "A component without a licence to review; `error` says why"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn review(
|
pub async fn review(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -687,6 +792,19 @@ pub async fn review(
|
|||||||
})))
|
})))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Withdraw a legal review.
|
||||||
|
#[utoipa::path(
|
||||||
|
delete,
|
||||||
|
path = "/api/v1/licenses/review",
|
||||||
|
tag = "Licences",
|
||||||
|
params(WithdrawQuery),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The review was withdrawn"),
|
||||||
|
(status = 403, description = "The role may not decide on licences (LEGAL, IT_ADMIN or OWNER)"),
|
||||||
|
(status = 404, description = "No such review"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn withdraw_review(
|
pub async fn withdraw_review(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -715,16 +833,31 @@ pub async fn withdraw_review(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The query of [`notices`].
|
/// The query of [`notices`].
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize, utoipa::IntoParams)]
|
||||||
|
#[into_params(parameter_in = Query)]
|
||||||
pub struct NoticesQuery {
|
pub struct NoticesQuery {
|
||||||
|
/// The target (its id).
|
||||||
pub repo_id: String,
|
pub repo_id: String,
|
||||||
|
/// `text` (default) or `markdown`.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
#[param(value_type = Option<String>, example = "markdown")]
|
||||||
pub format: NoticeFormat,
|
pub format: NoticeFormat,
|
||||||
/// Also list components only used to build.
|
/// Also list components only used to build.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub build_only: bool,
|
pub build_only: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A target's third-party notices to ship with the product.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/sbom/notices",
|
||||||
|
tag = "Licences",
|
||||||
|
params(NoticesQuery),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The notices file"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn notices(
|
pub async fn notices(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -912,6 +1045,7 @@ mod tests {
|
|||||||
fn legal_and_it_admin_decide_users_do_not() {
|
fn legal_and_it_admin_decide_users_do_not() {
|
||||||
assert!(may_decide(&with_roles(vec![OrgRole::Legal])));
|
assert!(may_decide(&with_roles(vec![OrgRole::Legal])));
|
||||||
assert!(may_decide(&with_roles(vec![OrgRole::ItAdmin])));
|
assert!(may_decide(&with_roles(vec![OrgRole::ItAdmin])));
|
||||||
|
assert!(may_decide(&with_roles(vec![OrgRole::Owner])));
|
||||||
assert!(!may_decide(&with_roles(vec![OrgRole::User])));
|
assert!(!may_decide(&with_roles(vec![OrgRole::User])));
|
||||||
assert!(!may_decide(&with_roles(vec![OrgRole::Cxo])));
|
assert!(!may_decide(&with_roles(vec![OrgRole::Cxo])));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,527 @@
|
|||||||
|
//! A machine (#1026): a project of kind `product` in the registry, made of
|
||||||
|
//! the targets assigned to it, in-house ones and components bought in from
|
||||||
|
//! suppliers (#1025). Its documents cover all of them.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use axum::extract::{Extension, Path, Query};
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::response::IntoResponse;
|
||||||
|
use axum::Json;
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use futures_util::StreamExt;
|
||||||
|
use mongodb::bson::{doc, oid::ObjectId};
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
use compliance_core::cve_groups::{self, CveGroup, SeverityCounts};
|
||||||
|
use compliance_core::models::{
|
||||||
|
CveAlert, OnboardedTarget, ProjectKind, SbomEntry, SupplierComponent, TargetType,
|
||||||
|
};
|
||||||
|
use compliance_core::sbom_docs::{self, MachinePart};
|
||||||
|
use compliance_core::scan_changes::ScanChange;
|
||||||
|
use compliance_core::tenant_ctx::TenantCtx;
|
||||||
|
|
||||||
|
use super::dto::{tenant_db, AgentExt};
|
||||||
|
use super::{
|
||||||
|
collect_cursor_async, projects::tenant_projects, sbom::MAX_EXPORT_COMPONENTS, ApiResponse,
|
||||||
|
};
|
||||||
|
use crate::agent::ComplianceAgent;
|
||||||
|
use crate::database::Database;
|
||||||
|
use crate::pipeline::csaf_feed::{supplier_key, MongoAdvisoryStore, SupplierProviderStatus};
|
||||||
|
use crate::pipeline::sbom::supplied::SUPPLIER_PRODUCT_MANAGER;
|
||||||
|
|
||||||
|
/// A machine as its endpoints read it: its name, its parts (its targets that
|
||||||
|
/// are not archived, by name) and their ids, in the same order.
|
||||||
|
struct Machine {
|
||||||
|
name: String,
|
||||||
|
targets: Vec<OnboardedTarget>,
|
||||||
|
ids: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Machine `id` of the tenant, and the tenant's database.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// As [`machine_name`]; 500 when the targets cannot be read.
|
||||||
|
async fn machine(
|
||||||
|
agent: &ComplianceAgent,
|
||||||
|
tenant: &TenantCtx,
|
||||||
|
id: &str,
|
||||||
|
) -> Result<(Machine, Database), StatusCode> {
|
||||||
|
let name = machine_name(agent, tenant, id).await?;
|
||||||
|
let db = tenant_db(agent, tenant).await?;
|
||||||
|
let targets: Vec<OnboardedTarget> = collect_cursor_async(
|
||||||
|
db.onboarded_targets()
|
||||||
|
.find(doc! { "project_ids": id, "archived_at": null })
|
||||||
|
.sort(doc! { "name": 1 })
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let ids = targets
|
||||||
|
.iter()
|
||||||
|
.filter_map(|t| t.id.map(|o: ObjectId| o.to_hex()))
|
||||||
|
.collect();
|
||||||
|
Ok((Machine { name, targets, ids }, db))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The open CVE alerts of the targets `ids`.
|
||||||
|
pub(super) async fn open_alerts(
|
||||||
|
db: &Database,
|
||||||
|
ids: &[String],
|
||||||
|
) -> Result<Vec<CveAlert>, StatusCode> {
|
||||||
|
let alerts: Vec<CveAlert> = collect_cursor_async(
|
||||||
|
db.cve_alerts()
|
||||||
|
.find(doc! { "repo_id": { "$in": ids }, "resolved_at": null })
|
||||||
|
.projection(doc! { "llm_impact_summary": 0 })
|
||||||
|
.sort(doc! { "cve_id": 1 })
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
Ok(alerts.into_iter().filter(cve_groups::is_open).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The name of machine `id`: a product project of the tenant's.
|
||||||
|
///
|
||||||
|
/// Without a registry (development) no project can be looked up, and the
|
||||||
|
/// machine is named by its id.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// 404 when the tenant has no such project, 422 when it is a topic rather
|
||||||
|
/// than a product, 503 when the registry cannot be asked.
|
||||||
|
async fn machine_name(
|
||||||
|
agent: &ComplianceAgent,
|
||||||
|
tenant: &TenantCtx,
|
||||||
|
id: &str,
|
||||||
|
) -> Result<String, StatusCode> {
|
||||||
|
let projects = tenant_projects(agent, &tenant.0.tenant_id).await?;
|
||||||
|
match projects.into_iter().find(|p| p.id == id) {
|
||||||
|
Some(p) if p.kind == ProjectKind::Product => Ok(p.name),
|
||||||
|
Some(_) => Err(StatusCode::UNPROCESSABLE_ENTITY),
|
||||||
|
None if agent.registry.is_none() => Ok(id.to_string()),
|
||||||
|
None => Err(StatusCode::NOT_FOUND),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The CycloneDX type of a part of target type `kind`: device software is
|
||||||
|
/// firmware, a PLC program and other software an application.
|
||||||
|
fn part_kind(kind: TargetType) -> &'static str {
|
||||||
|
match kind {
|
||||||
|
TargetType::FirmwareBareMetal
|
||||||
|
| TargetType::FirmwareRtos
|
||||||
|
| TargetType::EmbeddedLinuxYocto => "firmware",
|
||||||
|
TargetType::PlcSps
|
||||||
|
| TargetType::WebApp
|
||||||
|
| TargetType::BackendService
|
||||||
|
| TargetType::DesktopApp
|
||||||
|
| TargetType::AndroidApp
|
||||||
|
| TargetType::IosApp => "application",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A machine's SBOM as a CycloneDX 1.6 document to download.
|
||||||
|
///
|
||||||
|
/// The machine is a product project; its parts are its targets that are not
|
||||||
|
/// archived, each with its supplier (the workspace for one made in-house)
|
||||||
|
/// and its components beneath it. A component bought in is named by its
|
||||||
|
/// supplier's product and version. Never truncated: a machine with more than
|
||||||
|
/// 100 000 components is refused.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/projects/{id}/sbom",
|
||||||
|
tag = "SBOM",
|
||||||
|
params(("id" = String, Path, description = "The project's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The machine's CycloneDX SBOM"),
|
||||||
|
(status = 404, description = "No such project"),
|
||||||
|
(status = 413, description = "Too many components to export"),
|
||||||
|
(status = 422, description = "The project is a topic, not a product, or has no targets"),
|
||||||
|
(status = 503, description = "The registry cannot be asked"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
|
#[tracing::instrument(skip_all, fields(project_id = %id))]
|
||||||
|
pub async fn export_machine_sbom(
|
||||||
|
Extension(agent): AgentExt,
|
||||||
|
tenant: TenantCtx,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
) -> Result<impl IntoResponse, StatusCode> {
|
||||||
|
let (Machine { name, targets, ids }, db) = machine(&agent, &tenant, &id).await?;
|
||||||
|
// A machine without parts would read as one without components.
|
||||||
|
if targets.is_empty() {
|
||||||
|
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
}
|
||||||
|
// The supplier's product is the part itself, not one of its components.
|
||||||
|
let of_parts = doc! {
|
||||||
|
"repo_id": { "$in": &ids },
|
||||||
|
"package_manager": { "$ne": SUPPLIER_PRODUCT_MANAGER },
|
||||||
|
};
|
||||||
|
let components = db
|
||||||
|
.sbom_entries()
|
||||||
|
.count_documents(of_parts.clone())
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
if components > MAX_EXPORT_COMPONENTS {
|
||||||
|
tracing::warn!(
|
||||||
|
components,
|
||||||
|
"machine SBOM refused: too large to build in memory"
|
||||||
|
);
|
||||||
|
return Err(StatusCode::PAYLOAD_TOO_LARGE);
|
||||||
|
}
|
||||||
|
let mut entries: Vec<SbomEntry> = collect_cursor_async(
|
||||||
|
db.sbom_entries()
|
||||||
|
.find(of_parts)
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
crate::license_conclusions::attach(&db, &mut entries).await;
|
||||||
|
|
||||||
|
let workspace = super::vex::author(&tenant);
|
||||||
|
let parts: Vec<MachinePart<'_>> = targets
|
||||||
|
.iter()
|
||||||
|
.zip(&ids)
|
||||||
|
.map(|(t, id)| {
|
||||||
|
let supplier = t.supplier.as_ref();
|
||||||
|
MachinePart {
|
||||||
|
id,
|
||||||
|
name: &t.name,
|
||||||
|
kind: part_kind(t.target_type),
|
||||||
|
supplier: supplier.map_or(workspace.as_str(), |s| s.name.as_str()),
|
||||||
|
version: supplier.and_then(|s| s.version.as_deref()),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let body = sbom_docs::machine_cyclonedx(&name, &id, &parts, &entries);
|
||||||
|
super::vex::download(&body, &format!("sbom-machine-{id}-cyclonedx.json"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One part of a machine in its overview.
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct PartOverview {
|
||||||
|
/// The target's id.
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub target_type: TargetType,
|
||||||
|
/// Its supplier, for a component bought in; none for one made in-house.
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub supplier: Option<SupplierComponent>,
|
||||||
|
/// Its open CVEs per severity, a CVE counted once per component.
|
||||||
|
pub open: SeverityCounts,
|
||||||
|
/// When its last scan ended (or started, while it runs); none before
|
||||||
|
/// the first.
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub last_scan_at: Option<DateTime<Utc>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The advisories of a machine's suppliers, as read for the workspace.
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct MachineAdvisories {
|
||||||
|
/// The advisories kept, over all its suppliers' providers.
|
||||||
|
pub advisories: u64,
|
||||||
|
/// The suppliers' providers, each once.
|
||||||
|
pub providers: usize,
|
||||||
|
/// When one of them was last read; none before the first refresh.
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub checked_at: Option<DateTime<Utc>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A machine at a glance: its parts and what is open across them.
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct MachineOverview {
|
||||||
|
pub name: String,
|
||||||
|
/// Its parts, by name.
|
||||||
|
pub parts: Vec<PartOverview>,
|
||||||
|
/// Its open CVEs per severity: its parts' together, as each part
|
||||||
|
/// decides on its own.
|
||||||
|
pub open: SeverityCounts,
|
||||||
|
/// The open alerts nobody has stated anything on yet.
|
||||||
|
pub undecided: usize,
|
||||||
|
/// Of those, the ones the supplier states something on.
|
||||||
|
pub undecided_with_supplier: usize,
|
||||||
|
/// Its components, each once, however many parts contain it.
|
||||||
|
pub components: u64,
|
||||||
|
/// Of those, the ones more than one part contains.
|
||||||
|
pub shared_components: u64,
|
||||||
|
/// Its suppliers' advisories; none when no part names a CSAF provider.
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub advisories: Option<MachineAdvisories>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many components the parts `ids` contain, each once, and how many of
|
||||||
|
/// them more than one part contains, counted by the database. A component
|
||||||
|
/// is known by its purl, else by its package manager, name and version, as
|
||||||
|
/// the SBOM documents name it; the supplier's product is the part itself.
|
||||||
|
async fn component_counts(db: &Database, ids: &[String]) -> Result<(u64, u64), StatusCode> {
|
||||||
|
let pipeline = vec![
|
||||||
|
doc! { "$match": {
|
||||||
|
"repo_id": { "$in": ids },
|
||||||
|
"package_manager": { "$ne": SUPPLIER_PRODUCT_MANAGER },
|
||||||
|
} },
|
||||||
|
doc! { "$group": {
|
||||||
|
"_id": { "$ifNull": [
|
||||||
|
"$purl",
|
||||||
|
{ "$concat": ["$package_manager", ":", "$name", "@", "$version"] },
|
||||||
|
] },
|
||||||
|
"parts": { "$addToSet": "$repo_id" },
|
||||||
|
} },
|
||||||
|
doc! { "$group": {
|
||||||
|
"_id": null,
|
||||||
|
"components": { "$sum": 1 },
|
||||||
|
"shared": { "$sum": { "$cond": [{ "$gt": [{ "$size": "$parts" }, 1] }, 1, 0] } },
|
||||||
|
} },
|
||||||
|
];
|
||||||
|
let mut cursor = db
|
||||||
|
.sbom_entries()
|
||||||
|
.aggregate(pipeline)
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
let Some(row) = cursor.next().await else {
|
||||||
|
return Ok((0, 0));
|
||||||
|
};
|
||||||
|
let row = row.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
let count = |key: &str| {
|
||||||
|
row.get_i32(key)
|
||||||
|
.map(i64::from)
|
||||||
|
.or_else(|_| row.get_i64(key))
|
||||||
|
.map_or(0, |n| u64::try_from(n).unwrap_or(0))
|
||||||
|
};
|
||||||
|
Ok((count("components"), count("shared")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The advisories of the suppliers `targets` name, read for the workspace.
|
||||||
|
async fn machine_advisories(
|
||||||
|
db: &Database,
|
||||||
|
targets: &[OnboardedTarget],
|
||||||
|
) -> Result<Option<MachineAdvisories>, StatusCode> {
|
||||||
|
let mut keys: Vec<String> = targets
|
||||||
|
.iter()
|
||||||
|
.filter_map(|t| t.supplier.as_ref()?.csaf_provider.as_deref())
|
||||||
|
.map(supplier_key)
|
||||||
|
.collect();
|
||||||
|
keys.sort_unstable();
|
||||||
|
keys.dedup();
|
||||||
|
if keys.is_empty() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let advisories = MongoAdvisoryStore::supplier(db.inner())
|
||||||
|
.collection()
|
||||||
|
.count_documents(doc! { "provider": { "$in": &keys } })
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
let checked_at = db
|
||||||
|
.inner()
|
||||||
|
.collection::<SupplierProviderStatus>(SupplierProviderStatus::COLLECTION)
|
||||||
|
.find_one(doc! { "_id": { "$in": &keys } })
|
||||||
|
.sort(doc! { "checked_at": -1 })
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||||
|
.map(|s| s.checked_at.to_chrono());
|
||||||
|
Ok(Some(MachineAdvisories {
|
||||||
|
advisories,
|
||||||
|
providers: keys.len(),
|
||||||
|
checked_at,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The open CVEs per severity of `alerts`, a CVE counted once per component.
|
||||||
|
pub(super) fn open_counts<'a>(alerts: impl IntoIterator<Item = &'a CveAlert>) -> SeverityCounts {
|
||||||
|
let alerts: Vec<CveAlert> = alerts.into_iter().cloned().collect();
|
||||||
|
cve_groups::group_open_alerts(&alerts)
|
||||||
|
.iter()
|
||||||
|
.fold(SeverityCounts::default(), |sum, g| sum.plus(g.counts))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether nobody has stated anything on `alert` yet: no statement of a
|
||||||
|
/// person's.
|
||||||
|
fn undecided(alert: &CveAlert) -> bool {
|
||||||
|
alert.vex.as_ref().is_none_or(|v| v.by_scan)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A machine at a glance: its parts and what is open across them.
|
||||||
|
///
|
||||||
|
/// Each part with its supplier, open CVEs and last scan; across them the
|
||||||
|
/// open and undecided CVEs, the components and the suppliers' advisories.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/projects/{id}/overview",
|
||||||
|
tag = "Targets",
|
||||||
|
params(("id" = String, Path, description = "The project's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The machine at a glance (`data`)"),
|
||||||
|
(status = 404, description = "No such project"),
|
||||||
|
(status = 422, description = "The project is a topic, not a product"),
|
||||||
|
(status = 503, description = "The registry cannot be asked"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
|
#[tracing::instrument(skip_all, fields(project_id = %id))]
|
||||||
|
pub async fn machine_overview(
|
||||||
|
Extension(agent): AgentExt,
|
||||||
|
tenant: TenantCtx,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
) -> Result<Json<ApiResponse<MachineOverview>>, StatusCode> {
|
||||||
|
let (machine, db) = machine(&agent, &tenant, &id).await?;
|
||||||
|
let alerts = open_alerts(&db, &machine.ids).await?;
|
||||||
|
let (components, shared_components) = component_counts(&db, &machine.ids).await?;
|
||||||
|
let advisories = machine_advisories(&db, &machine.targets).await?;
|
||||||
|
let mut last_scans =
|
||||||
|
super::onboarding::latest_scan_runs(&db.scan_runs(), machine.ids.clone(), false).await;
|
||||||
|
let mut by_part: HashMap<&str, Vec<&CveAlert>> = HashMap::new();
|
||||||
|
for alert in &alerts {
|
||||||
|
by_part
|
||||||
|
.entry(alert.repo_id.as_str())
|
||||||
|
.or_default()
|
||||||
|
.push(alert);
|
||||||
|
}
|
||||||
|
let parts: Vec<PartOverview> = machine
|
||||||
|
.targets
|
||||||
|
.into_iter()
|
||||||
|
.zip(&machine.ids)
|
||||||
|
.map(|(t, id)| PartOverview {
|
||||||
|
open: open_counts(by_part.remove(id.as_str()).unwrap_or_default()),
|
||||||
|
last_scan_at: last_scans
|
||||||
|
.remove(id)
|
||||||
|
.map(|run| run.completed_at.unwrap_or(run.started_at)),
|
||||||
|
id: id.clone(),
|
||||||
|
name: t.name,
|
||||||
|
target_type: t.target_type,
|
||||||
|
supplier: t.supplier,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let undecided_alerts: Vec<&CveAlert> = alerts.iter().filter(|a| undecided(a)).collect();
|
||||||
|
Ok(Json(ApiResponse {
|
||||||
|
data: MachineOverview {
|
||||||
|
open: parts
|
||||||
|
.iter()
|
||||||
|
.fold(SeverityCounts::default(), |sum, p| sum.plus(p.open)),
|
||||||
|
parts,
|
||||||
|
name: machine.name,
|
||||||
|
undecided: undecided_alerts.len(),
|
||||||
|
undecided_with_supplier: undecided_alerts
|
||||||
|
.iter()
|
||||||
|
.filter(|a| a.supplier_vex.is_some())
|
||||||
|
.count(),
|
||||||
|
components,
|
||||||
|
shared_components,
|
||||||
|
advisories,
|
||||||
|
},
|
||||||
|
total: None,
|
||||||
|
page: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A machine's open CVEs: grouped by component across its parts, and the
|
||||||
|
/// alerts themselves, each with its part (`repo_id`).
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct MachineCves {
|
||||||
|
/// The groups, the most severe first; a group's `alert_ids` may belong
|
||||||
|
/// to several parts.
|
||||||
|
pub groups: Vec<CveGroup>,
|
||||||
|
/// The open alerts, by CVE.
|
||||||
|
pub alerts: Vec<CveAlert>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A machine's open CVEs, grouped by component across its parts.
|
||||||
|
///
|
||||||
|
/// A component in several parts is one group, with the alerts of every part
|
||||||
|
/// it is in: whether it affects the machine is stated per part, as the code
|
||||||
|
/// may be reached in one and not in another.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/projects/{id}/cves",
|
||||||
|
tag = "CVEs",
|
||||||
|
params(("id" = String, Path, description = "The project's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The groups and the open alerts (`data`)"),
|
||||||
|
(status = 404, description = "No such project"),
|
||||||
|
(status = 422, description = "The project is a topic, not a product"),
|
||||||
|
(status = 503, description = "The registry cannot be asked"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
|
#[tracing::instrument(skip_all, fields(project_id = %id))]
|
||||||
|
pub async fn machine_cves(
|
||||||
|
Extension(agent): AgentExt,
|
||||||
|
tenant: TenantCtx,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
) -> Result<Json<ApiResponse<MachineCves>>, StatusCode> {
|
||||||
|
let (machine, db) = machine(&agent, &tenant, &id).await?;
|
||||||
|
let alerts = open_alerts(&db, &machine.ids).await?;
|
||||||
|
Ok(Json(ApiResponse {
|
||||||
|
data: MachineCves {
|
||||||
|
groups: cve_groups::group_open_alerts(&alerts),
|
||||||
|
alerts,
|
||||||
|
},
|
||||||
|
total: None,
|
||||||
|
page: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One scan of one of a machine's parts, with what it changed.
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct MachineChange {
|
||||||
|
/// The part (its target's id).
|
||||||
|
pub part: String,
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub change: ScanChange,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What changed in a machine: the last scans of its parts, the newest first.
|
||||||
|
///
|
||||||
|
/// Each scan comes with the CVEs it found new and gone and the components
|
||||||
|
/// it added, updated and removed, as a target's own history (`limit`, 20
|
||||||
|
/// when not given, at most 50, over all parts). A supplier's new version
|
||||||
|
/// shows as its product updated (`from` → `to`) in a part bought in.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/projects/{id}/scan-changes",
|
||||||
|
tag = "CVEs",
|
||||||
|
params(
|
||||||
|
("id" = String, Path, description = "The project's id"),
|
||||||
|
("limit" = Option<usize>, Query, description = "The scans to show, 1 to 50"),
|
||||||
|
),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The parts' scans, each with its part (`data`)"),
|
||||||
|
(status = 404, description = "No such project"),
|
||||||
|
(status = 422, description = "The project is a topic, not a product"),
|
||||||
|
(status = 503, description = "The registry cannot be asked"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
|
#[tracing::instrument(skip_all, fields(project_id = %id))]
|
||||||
|
pub async fn machine_scan_changes(
|
||||||
|
Extension(agent): AgentExt,
|
||||||
|
tenant: TenantCtx,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
Query(query): Query<super::scan_changes::ChangesQuery>,
|
||||||
|
) -> Result<Json<ApiResponse<Vec<MachineChange>>>, StatusCode> {
|
||||||
|
let (machine, db) = machine(&agent, &tenant, &id).await?;
|
||||||
|
let per_part = futures_util::future::try_join_all(
|
||||||
|
machine
|
||||||
|
.ids
|
||||||
|
.iter()
|
||||||
|
.map(|part| super::scan_changes::target_changes(&db, part, query.limit)),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let mut data: Vec<MachineChange> = machine
|
||||||
|
.ids
|
||||||
|
.iter()
|
||||||
|
.zip(per_part)
|
||||||
|
.flat_map(|(part, changes)| {
|
||||||
|
changes.into_iter().map(|change| MachineChange {
|
||||||
|
part: part.clone(),
|
||||||
|
change,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
data.sort_by_key(|c| std::cmp::Reverse(c.change.started_at));
|
||||||
|
data.truncate(query.limit);
|
||||||
|
Ok(Json(ApiResponse {
|
||||||
|
total: Some(data.len() as u64),
|
||||||
|
data,
|
||||||
|
page: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
//!
|
//!
|
||||||
//! Writing findings into a tenant's record is an administrator's action: the
|
//! Writing findings into a tenant's record is an administrator's action: the
|
||||||
//! tester is given an account in the customer's organisation with the
|
//! tester is given an account in the customer's organisation with the
|
||||||
//! `IT_ADMIN` role.
|
//! `IT_ADMIN` (or `OWNER`) role.
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
@@ -16,7 +16,6 @@ use mongodb::bson::{doc, oid::ObjectId};
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use compliance_core::models::{Finding, ScanType};
|
use compliance_core::models::{Finding, ScanType};
|
||||||
use compliance_core::tenant::OrgRole;
|
|
||||||
use compliance_core::tenant_ctx::TenantCtx;
|
use compliance_core::tenant_ctx::TenantCtx;
|
||||||
|
|
||||||
use super::dto::tenant_db;
|
use super::dto::tenant_db;
|
||||||
@@ -47,9 +46,11 @@ impl From<ManualKind> for ScanType {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `POST /api/v1/targets/{id}/findings`.
|
/// The body of [`create_finding`]: a finding from a manual test.
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||||
pub struct CreateFindingRequest {
|
pub struct CreateFindingRequest {
|
||||||
|
/// `dast` or `pentest`: the manual test the finding comes from.
|
||||||
|
#[schema(value_type = String, example = "pentest")]
|
||||||
pub kind: ManualKind,
|
pub kind: ManualKind,
|
||||||
/// The tool used, if any; `manual` otherwise.
|
/// The tool used, if any; `manual` otherwise.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
@@ -67,9 +68,14 @@ pub enum ImportFormat {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// `?format=&kind=` of an import.
|
/// `?format=&kind=` of an import.
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize, utoipa::IntoParams)]
|
||||||
|
#[into_params(parameter_in = Query)]
|
||||||
pub struct ImportParams {
|
pub struct ImportParams {
|
||||||
|
/// `sarif` or `zap`.
|
||||||
|
#[param(value_type = String, example = "sarif")]
|
||||||
pub format: ImportFormat,
|
pub format: ImportFormat,
|
||||||
|
/// `dast` or `pentest`.
|
||||||
|
#[param(value_type = String, example = "dast")]
|
||||||
pub kind: ManualKind,
|
pub kind: ManualKind,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,9 +90,10 @@ pub struct ImportSummary {
|
|||||||
pub duplicates: usize,
|
pub duplicates: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Only an organisation's IT administrator writes findings by hand.
|
/// Only an organisation's administrator (IT_ADMIN, OWNER) writes findings by
|
||||||
|
/// hand.
|
||||||
fn require_admin(tenant: &TenantCtx) -> Result<(), StatusCode> {
|
fn require_admin(tenant: &TenantCtx) -> Result<(), StatusCode> {
|
||||||
if tenant.0.org_roles.contains(&OrgRole::ItAdmin) {
|
if tenant.0.is_admin() {
|
||||||
Ok(())
|
Ok(())
|
||||||
} else {
|
} else {
|
||||||
Err(StatusCode::FORBIDDEN)
|
Err(StatusCode::FORBIDDEN)
|
||||||
@@ -124,8 +131,26 @@ async fn insert_new(db: &Database, finding: &mut Finding) -> Result<bool, Status
|
|||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /api/v1/targets/{id}/findings — add one finding by hand. 409 when the
|
/// Add a finding from a manual DAST run or penetration test.
|
||||||
/// same finding (tool, title, location) is already on the target.
|
///
|
||||||
|
/// 409 when the same finding (tool, title, location) is already on the
|
||||||
|
/// target. Only an organisation's administrator (IT_ADMIN, OWNER).
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/targets/{id}/findings",
|
||||||
|
tag = "Findings",
|
||||||
|
params(("id" = String, Path, description = "The target's id")),
|
||||||
|
request_body = CreateFindingRequest,
|
||||||
|
responses(
|
||||||
|
(status = 201, description = "The finding"),
|
||||||
|
(status = 400, description = "Not an id"),
|
||||||
|
(status = 403, description = "Only an administrator adds findings by hand"),
|
||||||
|
(status = 404, description = "No such target"),
|
||||||
|
(status = 409, description = "The same finding is already on the target"),
|
||||||
|
(status = 422, description = "A malformed finding"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||||
pub async fn create_finding(
|
pub async fn create_finding(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -164,9 +189,26 @@ pub async fn create_finding(
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /api/v1/targets/{id}/findings/import?format=sarif|zap&kind=dast|pentest
|
/// Import the findings of a SARIF or ZAP report; the body is the report.
|
||||||
/// — the body is the report itself. Findings already on the target are
|
///
|
||||||
/// skipped, so importing a report again adds nothing.
|
/// Findings already on the target are skipped, so importing a report again
|
||||||
|
/// adds nothing. Only an organisation's administrator (IT_ADMIN, OWNER).
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/targets/{id}/findings/import",
|
||||||
|
tag = "Findings",
|
||||||
|
params(("id" = String, Path, description = "The target's id"), ImportParams),
|
||||||
|
request_body(content = Object, description = "The SARIF or ZAP JSON report"),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "What the import did"),
|
||||||
|
(status = 400, description = "Not an id"),
|
||||||
|
(status = 403, description = "Only an administrator imports findings"),
|
||||||
|
(status = 404, description = "No such target"),
|
||||||
|
(status = 413, description = "The report is larger than 20 MiB"),
|
||||||
|
(status = 422, description = "The report cannot be read"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||||
pub async fn import_findings(
|
pub async fn import_findings(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -221,7 +263,7 @@ pub async fn import_findings(
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use compliance_core::tenant::{TenantContext, TenantStatus};
|
use compliance_core::tenant::{OrgRole, TenantContext, TenantStatus};
|
||||||
|
|
||||||
fn tenant(roles: Vec<OrgRole>) -> TenantCtx {
|
fn tenant(roles: Vec<OrgRole>) -> TenantCtx {
|
||||||
TenantCtx(TenantContext {
|
TenantCtx(TenantContext {
|
||||||
@@ -241,6 +283,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn only_an_it_admin_writes_findings() {
|
fn only_an_it_admin_writes_findings() {
|
||||||
assert_eq!(require_admin(&tenant(vec![OrgRole::ItAdmin])), Ok(()));
|
assert_eq!(require_admin(&tenant(vec![OrgRole::ItAdmin])), Ok(()));
|
||||||
|
assert_eq!(require_admin(&tenant(vec![OrgRole::Owner])), Ok(()));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
require_admin(&tenant(vec![OrgRole::User, OrgRole::Cxo])),
|
require_admin(&tenant(vec![OrgRole::User, OrgRole::Cxo])),
|
||||||
Err(StatusCode::FORBIDDEN)
|
Err(StatusCode::FORBIDDEN)
|
||||||
|
|||||||
@@ -49,7 +49,9 @@ const ALL_TOOLS: [&str; 7] = [
|
|||||||
"dast_scan_summary",
|
"dast_scan_summary",
|
||||||
];
|
];
|
||||||
|
|
||||||
#[derive(Debug, serde::Deserialize)]
|
/// The query of [`list_mcp_servers`].
|
||||||
|
#[derive(Debug, serde::Deserialize, utoipa::IntoParams)]
|
||||||
|
#[into_params(parameter_in = Query)]
|
||||||
pub struct ListQuery {
|
pub struct ListQuery {
|
||||||
/// Where the deployment's MCP server answers (the dashboard's
|
/// Where the deployment's MCP server answers (the dashboard's
|
||||||
/// `MCP_ENDPOINT_URL`), for the default cards of a tenant that has none.
|
/// `MCP_ENDPOINT_URL`), for the default cards of a tenant that has none.
|
||||||
@@ -57,18 +59,26 @@ pub struct ListQuery {
|
|||||||
pub default_endpoint: Option<String>,
|
pub default_endpoint: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, serde::Deserialize)]
|
/// The body of [`create_mcp_server`].
|
||||||
|
#[derive(Debug, serde::Deserialize, utoipa::ToSchema)]
|
||||||
pub struct CreateRequest {
|
pub struct CreateRequest {
|
||||||
|
/// The card's name.
|
||||||
pub name: String,
|
pub name: String,
|
||||||
|
/// Where the MCP server answers.
|
||||||
pub endpoint_url: String,
|
pub endpoint_url: String,
|
||||||
|
/// The transport, such as `streamable-http`.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub transport: String,
|
pub transport: String,
|
||||||
|
/// The port, when not in the URL.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub port: Option<u16>,
|
pub port: Option<u16>,
|
||||||
|
/// A description.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub description: Option<String>,
|
pub description: Option<String>,
|
||||||
|
/// The MongoDB URI the server reads, for a server of its own.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub mongodb_uri: Option<String>,
|
pub mongodb_uri: Option<String>,
|
||||||
|
/// The MongoDB database the server reads.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub mongodb_database: Option<String>,
|
pub mongodb_database: Option<String>,
|
||||||
}
|
}
|
||||||
@@ -126,8 +136,19 @@ async fn seed_defaults(db: &Database, endpoint: &str) -> Result<(), mongodb::err
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `GET /api/v1/mcp-servers` — the tenant's cards, newest first; the access
|
/// The tenant's MCP server cards, newest first.
|
||||||
/// tokens only for roles that may change things.
|
///
|
||||||
|
/// The access tokens only for roles that may change things.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/mcp-servers",
|
||||||
|
tag = "MCP",
|
||||||
|
params(ListQuery),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The cards"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn list_mcp_servers(
|
pub async fn list_mcp_servers(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -155,7 +176,18 @@ pub async fn list_mcp_servers(
|
|||||||
Ok(Json(serde_json::json!({ "data": servers })))
|
Ok(Json(serde_json::json!({ "data": servers })))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `POST /api/v1/mcp-servers` — add a card to the tenant.
|
/// Add an MCP server card.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/mcp-servers",
|
||||||
|
tag = "MCP",
|
||||||
|
request_body = CreateRequest,
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The new card"),
|
||||||
|
(status = 400, description = "No name or no endpoint URL"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn create_mcp_server(
|
pub async fn create_mcp_server(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -194,8 +226,19 @@ pub async fn create_mcp_server(
|
|||||||
Ok(Json(serde_json::json!({ "id": inserted.inserted_id })))
|
Ok(Json(serde_json::json!({ "id": inserted.inserted_id })))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `DELETE /api/v1/mcp-servers/{id}` — remove one of the tenant's cards; 404
|
/// Remove an MCP server card.
|
||||||
/// for an id the tenant has not.
|
#[utoipa::path(
|
||||||
|
delete,
|
||||||
|
path = "/api/v1/mcp-servers/{id}",
|
||||||
|
tag = "MCP",
|
||||||
|
params(("id" = String, Path, description = "The card's id")),
|
||||||
|
responses(
|
||||||
|
(status = 204, description = "Removed"),
|
||||||
|
(status = 400, description = "Not an id"),
|
||||||
|
(status = 404, description = "No such card"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(server_id = %id))]
|
#[tracing::instrument(skip_all, fields(server_id = %id))]
|
||||||
pub async fn delete_mcp_server(
|
pub async fn delete_mcp_server(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -215,8 +258,19 @@ pub async fn delete_mcp_server(
|
|||||||
Ok(StatusCode::NO_CONTENT)
|
Ok(StatusCode::NO_CONTENT)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `POST /api/v1/mcp-servers/{id}/token` — give one of the tenant's cards a
|
/// Give an MCP server card a new access token.
|
||||||
/// new access token; 404 for an id the tenant has not.
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/mcp-servers/{id}/token",
|
||||||
|
tag = "MCP",
|
||||||
|
params(("id" = String, Path, description = "The card's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The new token"),
|
||||||
|
(status = 400, description = "Not an id"),
|
||||||
|
(status = 404, description = "No such card"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(server_id = %id))]
|
#[tracing::instrument(skip_all, fields(server_id = %id))]
|
||||||
pub async fn regenerate_mcp_server_token(
|
pub async fn regenerate_mcp_server_token(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
|
|||||||
@@ -33,8 +33,10 @@ const TOKEN_PREFIX: &str = "mcpt_";
|
|||||||
/// Combined with `mcpt_` → 48-char tokens.
|
/// Combined with `mcpt_` → 48-char tokens.
|
||||||
const TOKEN_RAND_BYTES: usize = 32;
|
const TOKEN_RAND_BYTES: usize = 32;
|
||||||
|
|
||||||
#[derive(serde::Deserialize)]
|
/// The body of [`create_mcp_token`].
|
||||||
|
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
||||||
pub struct CreateMcpTokenRequest {
|
pub struct CreateMcpTokenRequest {
|
||||||
|
/// What the token is for.
|
||||||
pub name: String,
|
pub name: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,7 +48,18 @@ pub struct CreateMcpTokenResponse {
|
|||||||
pub view: McpTokenView,
|
pub view: McpTokenView,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `POST /api/v1/mcp-tokens` — mint a new token for the caller's tenant.
|
/// Mint an MCP token for the tenant; it is shown only in this answer.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/mcp-tokens",
|
||||||
|
tag = "MCP",
|
||||||
|
request_body = CreateMcpTokenRequest,
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The token, once"),
|
||||||
|
(status = 400, description = "No name"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn create_mcp_token(
|
pub async fn create_mcp_token(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -85,9 +98,19 @@ pub async fn create_mcp_token(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `GET /api/v1/mcp-tokens` — list tokens for the caller's tenant.
|
/// The tenant's MCP tokens, without the tokens.
|
||||||
/// Hash is never returned; only metadata + the 12-char prefix so the
|
///
|
||||||
/// user can identify which row is which.
|
/// The hash is never returned; only metadata and the 12-character prefix,
|
||||||
|
/// so the user can tell which row is which.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/mcp-tokens",
|
||||||
|
tag = "MCP",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The tokens"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn list_mcp_tokens(
|
pub async fn list_mcp_tokens(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -119,9 +142,22 @@ pub async fn list_mcp_tokens(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `DELETE /api/v1/mcp-tokens/{id}` — revoke (soft delete).
|
/// Revoke an MCP token.
|
||||||
|
///
|
||||||
/// Scoped to the caller's tenant: a user can't revoke another tenant's
|
/// Scoped to the caller's tenant: a user can't revoke another tenant's
|
||||||
/// token even if they guess its id.
|
/// token even if they guess its id.
|
||||||
|
#[utoipa::path(
|
||||||
|
delete,
|
||||||
|
path = "/api/v1/mcp-tokens/{id}",
|
||||||
|
tag = "MCP",
|
||||||
|
params(("id" = String, Path, description = "The token's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "Revoked"),
|
||||||
|
(status = 400, description = "Not an id"),
|
||||||
|
(status = 404, description = "No such token"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(id = %id))]
|
#[tracing::instrument(skip_all, fields(id = %id))]
|
||||||
pub async fn revoke_mcp_token(
|
pub async fn revoke_mcp_token(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
|
|||||||
@@ -27,12 +27,23 @@ struct UsageView {
|
|||||||
prueftag_cap: Option<u32>,
|
prueftag_cap: Option<u32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/metering/usage — the tenant's Prüfungen, Prüftage and extra
|
/// The tenant's usage this month, with the plan's limits.
|
||||||
/// targets this month (Europe/Berlin), with the plan's limits.
|
///
|
||||||
|
/// Prüfungen, Prüftage and extra targets this month (Europe/Berlin).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
///
|
///
|
||||||
/// `500` when the counters cannot be read.
|
/// `500` when the counters cannot be read.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/metering/usage",
|
||||||
|
tag = "Workspace",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The usage"),
|
||||||
|
(status = 500, description = "The counters cannot be read"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
pub async fn get_usage(
|
pub async fn get_usage(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
tenant: TenantCtx,
|
tenant: TenantCtx,
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
pub mod admin;
|
pub mod admin;
|
||||||
|
pub mod branding;
|
||||||
pub mod chat;
|
pub mod chat;
|
||||||
|
pub mod connections;
|
||||||
pub mod cve_history;
|
pub mod cve_history;
|
||||||
pub mod cve_matrix;
|
pub mod cve_matrix;
|
||||||
pub mod dast;
|
pub mod dast;
|
||||||
|
mod delivery;
|
||||||
pub mod demo_seed;
|
pub mod demo_seed;
|
||||||
|
pub mod devices;
|
||||||
pub mod dto;
|
pub mod dto;
|
||||||
pub mod evidence;
|
pub mod evidence;
|
||||||
pub mod finding_breakdown;
|
pub mod finding_breakdown;
|
||||||
@@ -16,21 +20,28 @@ pub mod help_chat;
|
|||||||
pub mod inbox;
|
pub mod inbox;
|
||||||
pub mod issues;
|
pub mod issues;
|
||||||
pub mod licenses;
|
pub mod licenses;
|
||||||
|
pub mod machine;
|
||||||
pub mod manual_findings;
|
pub mod manual_findings;
|
||||||
pub mod mcp_servers;
|
pub mod mcp_servers;
|
||||||
pub mod mcp_tokens;
|
pub mod mcp_tokens;
|
||||||
pub mod metering;
|
pub mod metering;
|
||||||
pub mod notifications;
|
pub mod notifications;
|
||||||
|
pub mod offers;
|
||||||
pub mod onboarding;
|
pub mod onboarding;
|
||||||
pub mod oscal;
|
pub mod oscal;
|
||||||
pub mod pentest_handlers;
|
pub mod pentest_handlers;
|
||||||
pub mod platform;
|
pub mod platform;
|
||||||
pub mod projects;
|
pub mod projects;
|
||||||
|
pub mod releases;
|
||||||
pub use pentest_handlers as pentest;
|
pub use pentest_handlers as pentest;
|
||||||
pub mod sbom;
|
pub mod sbom;
|
||||||
pub mod sbom_ecosystems;
|
pub mod sbom_ecosystems;
|
||||||
pub mod scan_changes;
|
pub mod scan_changes;
|
||||||
pub mod scans;
|
pub mod scans;
|
||||||
|
pub mod supplier;
|
||||||
|
pub mod supplier_invites;
|
||||||
|
pub mod supply_chain;
|
||||||
|
pub mod supply_chain_layout;
|
||||||
pub mod support;
|
pub mod support;
|
||||||
pub mod target_input;
|
pub mod target_input;
|
||||||
pub mod vex;
|
pub mod vex;
|
||||||
|
|||||||
@@ -9,7 +9,17 @@ use compliance_core::tenant_ctx::TenantCtx;
|
|||||||
|
|
||||||
use super::dto::{tenant_db, AgentExt, ApiResponse};
|
use super::dto::{tenant_db, AgentExt, ApiResponse};
|
||||||
|
|
||||||
/// GET /api/v1/notifications — List CVE notifications (newest first)
|
/// The tenant's CVE notifications, newest first, a page at a time.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/notifications",
|
||||||
|
tag = "Notifications",
|
||||||
|
params(NotificationFilter),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "A page of notifications"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn list_notifications(
|
pub async fn list_notifications(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -85,7 +95,16 @@ pub async fn list_notifications(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/notifications/count — Count of unread notifications
|
/// The number of unread notifications.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/notifications/count",
|
||||||
|
tag = "Notifications",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The count"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn notification_count(
|
pub async fn notification_count(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -101,7 +120,19 @@ pub async fn notification_count(
|
|||||||
Ok(Json(serde_json::json!({ "count": count })))
|
Ok(Json(serde_json::json!({ "count": count })))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// PATCH /api/v1/notifications/:id/read — Mark a notification as read
|
/// Mark a notification as read.
|
||||||
|
#[utoipa::path(
|
||||||
|
patch,
|
||||||
|
path = "/api/v1/notifications/{id}/read",
|
||||||
|
tag = "Notifications",
|
||||||
|
params(("id" = String, Path, description = "The notification's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "Marked as read"),
|
||||||
|
(status = 400, description = "Not an id"),
|
||||||
|
(status = 404, description = "No such notification"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(id = %id))]
|
#[tracing::instrument(skip_all, fields(id = %id))]
|
||||||
pub async fn mark_read(
|
pub async fn mark_read(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -129,7 +160,19 @@ pub async fn mark_read(
|
|||||||
Ok(Json(serde_json::json!({ "status": "read" })))
|
Ok(Json(serde_json::json!({ "status": "read" })))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// PATCH /api/v1/notifications/:id/dismiss — Dismiss a notification
|
/// Dismiss a notification.
|
||||||
|
#[utoipa::path(
|
||||||
|
patch,
|
||||||
|
path = "/api/v1/notifications/{id}/dismiss",
|
||||||
|
tag = "Notifications",
|
||||||
|
params(("id" = String, Path, description = "The notification's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "Dismissed"),
|
||||||
|
(status = 400, description = "Not an id"),
|
||||||
|
(status = 404, description = "No such notification"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(id = %id))]
|
#[tracing::instrument(skip_all, fields(id = %id))]
|
||||||
pub async fn dismiss_notification(
|
pub async fn dismiss_notification(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -154,7 +197,16 @@ pub async fn dismiss_notification(
|
|||||||
Ok(Json(serde_json::json!({ "status": "dismissed" })))
|
Ok(Json(serde_json::json!({ "status": "dismissed" })))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /api/v1/notifications/read-all — Mark all new notifications as read
|
/// Mark every new notification as read.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/notifications/read-all",
|
||||||
|
tag = "Notifications",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "Marked as read"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn mark_all_read(
|
pub async fn mark_all_read(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -178,11 +230,20 @@ pub async fn mark_all_read(
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
/// Which notifications a list shows.
|
||||||
|
#[derive(Debug, Deserialize, utoipa::IntoParams)]
|
||||||
|
#[into_params(parameter_in = Query)]
|
||||||
pub struct NotificationFilter {
|
pub struct NotificationFilter {
|
||||||
|
/// `new`, `read`, `dismissed` or `all`; new and read without it.
|
||||||
pub status: Option<String>,
|
pub status: Option<String>,
|
||||||
|
/// Only one severity.
|
||||||
pub severity: Option<String>,
|
pub severity: Option<String>,
|
||||||
|
/// Only one target's notifications (its id).
|
||||||
pub repo_id: Option<String>,
|
pub repo_id: Option<String>,
|
||||||
|
/// The page, from 1 (default 1, at most 100 000).
|
||||||
|
#[param(minimum = 1, maximum = 100_000)]
|
||||||
pub page: Option<u64>,
|
pub page: Option<u64>,
|
||||||
|
/// Entries per page (default 50, at most 200).
|
||||||
|
#[param(minimum = 1, maximum = 200)]
|
||||||
pub limit: Option<i64>,
|
pub limit: Option<i64>,
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,702 @@
|
|||||||
|
//! SBOM releases, the customer's side (#1028): what a connected supplier
|
||||||
|
//! workspace offers, and the customer's answer.
|
||||||
|
//!
|
||||||
|
//! A supplier's release (`super::releases`) writes an offer into the
|
||||||
|
//! customer's database, after the registry confirmed the connection joins the
|
||||||
|
//! two. The customer accepts it into a supplier component (a new one, or one
|
||||||
|
//! it has) or declines it; the answer is written back to the supplier's
|
||||||
|
//! release. Accepting creates a target, which counts like any other, so it
|
||||||
|
//! is the customer's decision and never automatic.
|
||||||
|
|
||||||
|
use axum::extract::{Extension, Path};
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::response::IntoResponse;
|
||||||
|
use axum::Json;
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use futures_util::TryStreamExt;
|
||||||
|
use mongodb::bson::{doc, oid::ObjectId, DateTime as BsonDateTime};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use compliance_core::models::{OnboardedTarget, SupplierComponent, TargetType};
|
||||||
|
use compliance_core::tenant_ctx::TenantCtx;
|
||||||
|
|
||||||
|
use super::dto::{tenant_db, AgentExt};
|
||||||
|
use super::releases::SbomRelease;
|
||||||
|
use super::ApiResponse;
|
||||||
|
use crate::agent::ComplianceAgent;
|
||||||
|
use crate::database::Database;
|
||||||
|
|
||||||
|
/// Where an offer stands.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum OfferState {
|
||||||
|
/// Waiting for the customer's answer.
|
||||||
|
Offered,
|
||||||
|
/// Accepted into a supplier component.
|
||||||
|
Accepted,
|
||||||
|
/// Declined by the customer.
|
||||||
|
Declined,
|
||||||
|
/// Ended by the supplier, or the connection ended.
|
||||||
|
Ended,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A supplier's offer, as stored in the customer's database.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct SbomOffer {
|
||||||
|
#[serde(rename = "_id")]
|
||||||
|
pub id: ObjectId,
|
||||||
|
/// The supplier's release it answers.
|
||||||
|
pub release_id: String,
|
||||||
|
/// The connection it came over.
|
||||||
|
pub connection_id: String,
|
||||||
|
/// The supplier's tenant: for answering and delivering inside Prüfwerk,
|
||||||
|
/// never shown.
|
||||||
|
pub supplier_tenant_id: String,
|
||||||
|
/// The supplier workspace's display name.
|
||||||
|
pub supplier_name: String,
|
||||||
|
/// The supplier's name for the product (its target's name).
|
||||||
|
pub product_name: String,
|
||||||
|
/// The product's type, for the component it becomes.
|
||||||
|
pub product_type: TargetType,
|
||||||
|
pub state: OfferState,
|
||||||
|
/// The component it delivers into, once accepted.
|
||||||
|
#[serde(default)]
|
||||||
|
pub target_id: Option<String>,
|
||||||
|
pub offered_at: BsonDateTime,
|
||||||
|
#[serde(default)]
|
||||||
|
pub decided_at: Option<BsonDateTime>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub decided_by: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub ended_at: Option<BsonDateTime>,
|
||||||
|
/// The content hash of the version last delivered, so the same version
|
||||||
|
/// is never delivered twice.
|
||||||
|
#[serde(default)]
|
||||||
|
pub delivered_hash: Option<String>,
|
||||||
|
/// The label of the version last delivered.
|
||||||
|
#[serde(default)]
|
||||||
|
pub delivered_label: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub delivered_at: Option<BsonDateTime>,
|
||||||
|
/// While the offer is open: the supplier's latest published version,
|
||||||
|
/// what accepting delivers at once, and how many components it lists.
|
||||||
|
#[serde(default)]
|
||||||
|
pub offered_label: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub offered_components: Option<i64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SbomOffer {
|
||||||
|
/// The collection, in the customer's own database.
|
||||||
|
pub const COLLECTION: &'static str = "sbom_offers";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An offer as the customer reads it: nothing of the supplier's but its
|
||||||
|
/// name, the product's, and the version it offers.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||||
|
pub struct OfferView {
|
||||||
|
pub id: String,
|
||||||
|
pub supplier_name: String,
|
||||||
|
pub product_name: String,
|
||||||
|
pub product_type: TargetType,
|
||||||
|
pub state: OfferState,
|
||||||
|
pub target_id: Option<String>,
|
||||||
|
pub offered_at: DateTime<Utc>,
|
||||||
|
pub decided_at: Option<DateTime<Utc>>,
|
||||||
|
pub ended_at: Option<DateTime<Utc>>,
|
||||||
|
/// The version last delivered into the component, and when.
|
||||||
|
pub delivered_label: Option<String>,
|
||||||
|
pub delivered_at: Option<DateTime<Utc>>,
|
||||||
|
/// While it is open: the version accepting delivers at once, and how
|
||||||
|
/// many components it lists; `None` before the supplier published one.
|
||||||
|
pub offered_label: Option<String>,
|
||||||
|
pub offered_components: Option<i64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<SbomOffer> for OfferView {
|
||||||
|
fn from(o: SbomOffer) -> Self {
|
||||||
|
Self {
|
||||||
|
id: o.id.to_hex(),
|
||||||
|
supplier_name: o.supplier_name,
|
||||||
|
product_name: o.product_name,
|
||||||
|
product_type: o.product_type,
|
||||||
|
state: o.state,
|
||||||
|
target_id: o.target_id,
|
||||||
|
offered_at: o.offered_at.to_chrono(),
|
||||||
|
decided_at: o.decided_at.map(BsonDateTime::to_chrono),
|
||||||
|
ended_at: o.ended_at.map(BsonDateTime::to_chrono),
|
||||||
|
delivered_label: o.delivered_label,
|
||||||
|
delivered_at: o.delivered_at.map(BsonDateTime::to_chrono),
|
||||||
|
offered_label: o.offered_label,
|
||||||
|
offered_components: o.offered_components,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The body of an acceptance: into an existing supplier component, or a new
|
||||||
|
/// one with its name and projects.
|
||||||
|
#[derive(Debug, Default, Deserialize, utoipa::ToSchema)]
|
||||||
|
pub struct AcceptOffer {
|
||||||
|
/// An existing supplier component to deliver into.
|
||||||
|
#[serde(default)]
|
||||||
|
pub target_id: Option<String>,
|
||||||
|
/// The new component's name; the product's name when left out.
|
||||||
|
#[serde(default)]
|
||||||
|
pub name: Option<String>,
|
||||||
|
/// The new component's projects.
|
||||||
|
#[serde(default)]
|
||||||
|
pub project_ids: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn offers(db: &Database) -> mongodb::Collection<SbomOffer> {
|
||||||
|
db.inner().collection(SbomOffer::COLLECTION)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn internal<E: std::fmt::Display>(e: E) -> StatusCode {
|
||||||
|
tracing::error!("offer endpoint failed: {e}");
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A refusal with its code, as `{"error": …}`.
|
||||||
|
fn refused(status: StatusCode, code: &str) -> axum::response::Response {
|
||||||
|
(status, Json(serde_json::json!({ "error": code }))).into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write `offer` into `customer`'s database. The supplier's release calls it
|
||||||
|
/// once the registry has confirmed the connection joins the two.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// 500 when it cannot be written.
|
||||||
|
pub(super) async fn offer(
|
||||||
|
agent: &ComplianceAgent,
|
||||||
|
customer: &str,
|
||||||
|
offer: &SbomOffer,
|
||||||
|
) -> Result<(), StatusCode> {
|
||||||
|
let db = agent
|
||||||
|
.db_pool
|
||||||
|
.for_tenant_id(customer)
|
||||||
|
.await
|
||||||
|
.map_err(internal)?;
|
||||||
|
offers(&db).insert_one(offer).await.map_err(internal)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tell `customer`'s open offer of release `release` that `label` (with
|
||||||
|
/// `components` components) is now what accepting delivers. Best-effort:
|
||||||
|
/// the next publication tells it again.
|
||||||
|
pub(super) async fn announce(
|
||||||
|
agent: &ComplianceAgent,
|
||||||
|
customer: &str,
|
||||||
|
release: &str,
|
||||||
|
label: &str,
|
||||||
|
components: i64,
|
||||||
|
) {
|
||||||
|
let db = agent.db_pool.for_existing_tenant_id(customer);
|
||||||
|
let told = offers(&db)
|
||||||
|
.update_one(
|
||||||
|
doc! { "release_id": release, "state": "offered" },
|
||||||
|
doc! { "$set": { "offered_label": label, "offered_components": components } },
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
if let Err(e) = told {
|
||||||
|
tracing::warn!(release, "new version not announced to the customer: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mark the offer of release `release` in `customer`'s database ended: the
|
||||||
|
/// supplier ended the release. Best-effort; a customer that has gone keeps
|
||||||
|
/// nothing to mark.
|
||||||
|
pub(super) async fn end(agent: &ComplianceAgent, customer: &str, release: &str) {
|
||||||
|
let db = agent.db_pool.for_existing_tenant_id(customer);
|
||||||
|
let ended = offers(&db)
|
||||||
|
.update_one(
|
||||||
|
doc! { "release_id": release, "state": { "$in": ["offered", "accepted"] } },
|
||||||
|
doc! { "$set": { "state": "ended", "ended_at": BsonDateTime::now() } },
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
if let Err(e) = ended {
|
||||||
|
tracing::warn!(release, "ended release not marked at the customer: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write the customer's answer `state` back to release `release` in the
|
||||||
|
/// supplier's database, for the supplier to see. Best-effort.
|
||||||
|
async fn answer_release(agent: &ComplianceAgent, offer: &SbomOffer, state: OfferState) {
|
||||||
|
let Ok(id) = ObjectId::parse_str(&offer.release_id) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let db = agent
|
||||||
|
.db_pool
|
||||||
|
.for_existing_tenant_id(&offer.supplier_tenant_id);
|
||||||
|
let answered = db
|
||||||
|
.inner()
|
||||||
|
.collection::<SbomRelease>(SbomRelease::COLLECTION)
|
||||||
|
.update_one(
|
||||||
|
doc! { "_id": id, "connection_id": &offer.connection_id },
|
||||||
|
doc! { "$set": { "answer": mongodb::bson::to_bson(&state).unwrap_or_default() } },
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
if let Err(e) = answered {
|
||||||
|
tracing::warn!(release = %offer.release_id, "answer not written to the supplier: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `offer` can still be accepted: the connection it came over still
|
||||||
|
/// joins this workspace (`tenant`) and its supplier, and the supplier's
|
||||||
|
/// release still exists and has not ended (a supplier that deleted the
|
||||||
|
/// target, or left Prüfwerk, takes its releases with it).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// 503 without a registry or when it cannot be asked.
|
||||||
|
async fn still_open(
|
||||||
|
agent: &ComplianceAgent,
|
||||||
|
tenant: &str,
|
||||||
|
offer: &SbomOffer,
|
||||||
|
) -> Result<bool, StatusCode> {
|
||||||
|
let registry = agent
|
||||||
|
.registry
|
||||||
|
.as_ref()
|
||||||
|
.ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
|
||||||
|
let state = registry
|
||||||
|
.connection(&offer.connection_id)
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
tracing::error!("connection check unavailable: {e}");
|
||||||
|
StatusCode::SERVICE_UNAVAILABLE
|
||||||
|
})?;
|
||||||
|
if state.is_none_or(|s| s.peer_of(tenant) != Some(offer.supplier_tenant_id.as_str())) {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
let Ok(release) = ObjectId::parse_str(&offer.release_id) else {
|
||||||
|
return Ok(false);
|
||||||
|
};
|
||||||
|
let live = agent
|
||||||
|
.db_pool
|
||||||
|
.for_existing_tenant_id(&offer.supplier_tenant_id)
|
||||||
|
.inner()
|
||||||
|
.collection::<SbomRelease>(SbomRelease::COLLECTION)
|
||||||
|
.count_documents(doc! {
|
||||||
|
"_id": release,
|
||||||
|
"connection_id": &offer.connection_id,
|
||||||
|
"ended_at": null,
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(internal)?;
|
||||||
|
Ok(live > 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether workspace `peer` may be offered a release: it holds Prüfwerk and
|
||||||
|
/// is neither halted nor archived. An offer is written into its database,
|
||||||
|
/// so a workspace without the product never gets one created. Without a
|
||||||
|
/// registry (development) every workspace may.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// 503 when the registry cannot be asked.
|
||||||
|
pub(super) async fn takes_offers(agent: &ComplianceAgent, peer: &str) -> Result<bool, StatusCode> {
|
||||||
|
let Some(registry) = agent.registry.as_ref() else {
|
||||||
|
return Ok(true);
|
||||||
|
};
|
||||||
|
let check = registry
|
||||||
|
.check_entitlement(peer, None, None)
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
tracing::error!("entitlement check unavailable: {e}");
|
||||||
|
StatusCode::SERVICE_UNAVAILABLE
|
||||||
|
})?;
|
||||||
|
let status = check
|
||||||
|
.status
|
||||||
|
.as_deref()
|
||||||
|
.and_then(compliance_core::TenantStatus::parse);
|
||||||
|
Ok(check.allowed && status.is_none_or(|s| !s.is_halted() && !s.is_archived()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mark `offer` ended in `db`, from whichever state it is in.
|
||||||
|
async fn mark_ended(db: &Database, offer: ObjectId) -> Result<(), StatusCode> {
|
||||||
|
offers(db)
|
||||||
|
.update_one(
|
||||||
|
doc! { "_id": offer, "state": { "$in": ["offered", "accepted"] } },
|
||||||
|
doc! { "$set": { "state": "ended", "ended_at": BsonDateTime::now() } },
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(internal)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Give back a claim on `offer` that could not be completed: it is open
|
||||||
|
/// again.
|
||||||
|
async fn unclaim(db: &Database, offer: ObjectId) -> Result<(), StatusCode> {
|
||||||
|
offers(db)
|
||||||
|
.update_one(
|
||||||
|
doc! { "_id": offer, "state": "accepted" },
|
||||||
|
doc! {
|
||||||
|
"$set": { "state": "offered" },
|
||||||
|
"$unset": { "target_id": "", "decided_at": "", "decided_by": "" },
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(internal)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What an accepted offer delivers into.
|
||||||
|
enum Destination {
|
||||||
|
/// A supplier component the workspace has.
|
||||||
|
Existing(OnboardedTarget),
|
||||||
|
/// A new supplier component, not yet stored.
|
||||||
|
New(OnboardedTarget),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The refusal for an offer that is no longer open: `ended` or `answered`.
|
||||||
|
fn not_open(state: OfferState) -> axum::response::Response {
|
||||||
|
let code = if state == OfferState::Ended {
|
||||||
|
"ended"
|
||||||
|
} else {
|
||||||
|
"answered"
|
||||||
|
};
|
||||||
|
refused(StatusCode::CONFLICT, code)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What deleting target `target_id` of tenant `tenant_id` (in `db`) means
|
||||||
|
/// for releases: its active releases end at their customers, and offers
|
||||||
|
/// accepted into it end, with `ended` as the answer the supplier sees, so
|
||||||
|
/// nothing is delivered into a component that has gone. Called before the
|
||||||
|
/// target's releases are deleted. Best-effort.
|
||||||
|
pub(super) async fn on_target_deleted(agent: &ComplianceAgent, db: &Database, target_id: &str) {
|
||||||
|
let active: Vec<SbomRelease> = match db
|
||||||
|
.inner()
|
||||||
|
.collection::<SbomRelease>(SbomRelease::COLLECTION)
|
||||||
|
.find(doc! { "target_id": target_id, "ended_at": null })
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(cursor) => cursor.try_collect().await.unwrap_or_default(),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(target_id, "releases of a deleted target not read: {e}");
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for release in active {
|
||||||
|
end(agent, &release.peer_tenant_id, &release.id.to_hex()).await;
|
||||||
|
}
|
||||||
|
let accepted: Vec<SbomOffer> = match offers(db)
|
||||||
|
.find(doc! { "target_id": target_id, "state": "accepted" })
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(cursor) => cursor.try_collect().await.unwrap_or_default(),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(target_id, "offers into a deleted target not read: {e}");
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for offer in accepted {
|
||||||
|
if mark_ended(db, offer.id).await.is_ok() {
|
||||||
|
answer_release(agent, &offer, OfferState::Ended).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Record `action` about `target` in the platform's audit log, in the
|
||||||
|
/// background.
|
||||||
|
fn audit(
|
||||||
|
agent: &ComplianceAgent,
|
||||||
|
tenant: &TenantCtx,
|
||||||
|
action: &str,
|
||||||
|
target: Option<&OnboardedTarget>,
|
||||||
|
offer: &SbomOffer,
|
||||||
|
) {
|
||||||
|
let Some(registry) = agent.registry.clone() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let mut entry = crate::registry::AuditEntry::by(
|
||||||
|
&tenant.0,
|
||||||
|
action,
|
||||||
|
serde_json::json!({ "supplier_name": offer.supplier_name, "product_name": offer.product_name }),
|
||||||
|
);
|
||||||
|
if let Some(t) = target {
|
||||||
|
entry = entry.about_target(&t.id.map(|o| o.to_hex()).unwrap_or_default(), &t.name);
|
||||||
|
}
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Err(e) = registry.append_audit(&entry).await {
|
||||||
|
tracing::warn!("offer answer not audited: {e}");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Offer `id` of the tenant behind `db`.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// 404 when it is not an id or there is no such offer.
|
||||||
|
async fn find(db: &Database, id: &str) -> Result<SbomOffer, StatusCode> {
|
||||||
|
let oid = ObjectId::parse_str(id).map_err(|_| StatusCode::NOT_FOUND)?;
|
||||||
|
offers(db)
|
||||||
|
.find_one(doc! { "_id": oid })
|
||||||
|
.await
|
||||||
|
.map_err(internal)?
|
||||||
|
.ok_or(StatusCode::NOT_FOUND)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The SBOM releases connected suppliers offer the workspace.
|
||||||
|
///
|
||||||
|
/// Open offers first, then the answered and ended ones, each newest first.
|
||||||
|
/// Each names the supplier workspace and its product; nothing else of the
|
||||||
|
/// supplier's is shown.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/sbom-offers",
|
||||||
|
tag = "Targets",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The offers (`data`)"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
|
#[tracing::instrument(skip_all)]
|
||||||
|
pub async fn list_offers(
|
||||||
|
Extension(agent): AgentExt,
|
||||||
|
tenant: TenantCtx,
|
||||||
|
) -> Result<Json<ApiResponse<Vec<OfferView>>>, StatusCode> {
|
||||||
|
let db = tenant_db(&agent, &tenant).await?;
|
||||||
|
let mut listed: Vec<SbomOffer> = offers(&db)
|
||||||
|
.find(doc! {})
|
||||||
|
.sort(doc! { "offered_at": -1, "_id": -1 })
|
||||||
|
.await
|
||||||
|
.map_err(internal)?
|
||||||
|
.try_collect()
|
||||||
|
.await
|
||||||
|
.map_err(internal)?;
|
||||||
|
// Open ones first; the sort keeps each group newest first.
|
||||||
|
listed.sort_by_key(|o| o.state != OfferState::Offered);
|
||||||
|
Ok(Json(ApiResponse {
|
||||||
|
data: listed.into_iter().map(OfferView::from).collect(),
|
||||||
|
total: None,
|
||||||
|
page: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Accept a supplier's SBOM release.
|
||||||
|
///
|
||||||
|
/// Into an existing supplier component (`target_id`), or into a new one
|
||||||
|
/// named `name` (the product's name when left out) in `project_ids`. A new
|
||||||
|
/// component counts like any other target. The supplier sees the answer.
|
||||||
|
/// The connection must still join the two workspaces.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/sbom-offers/{id}/accept",
|
||||||
|
tag = "Targets",
|
||||||
|
params(("id" = String, Path, description = "The offer's id")),
|
||||||
|
request_body = AcceptOffer,
|
||||||
|
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 = 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"),
|
||||||
|
(status = 403, description = "A read-only role"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
|
#[tracing::instrument(skip_all, fields(offer_id = %id))]
|
||||||
|
pub async fn accept_offer(
|
||||||
|
Extension(agent): AgentExt,
|
||||||
|
tenant: TenantCtx,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
Json(body): Json<AcceptOffer>,
|
||||||
|
) -> Result<axum::response::Response, StatusCode> {
|
||||||
|
let db = tenant_db(&agent, &tenant).await?;
|
||||||
|
let offer = find(&db, &id).await?;
|
||||||
|
if offer.state != OfferState::Offered {
|
||||||
|
return Ok(not_open(offer.state));
|
||||||
|
}
|
||||||
|
if !still_open(&agent, &tenant.0.tenant_id, &offer).await? {
|
||||||
|
mark_ended(&db, offer.id).await?;
|
||||||
|
return Ok(refused(StatusCode::CONFLICT, "ended"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// What it goes into, checked before anything is claimed or created.
|
||||||
|
let into = match body
|
||||||
|
.target_id
|
||||||
|
.as_deref()
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|t| !t.is_empty())
|
||||||
|
{
|
||||||
|
Some(chosen) => {
|
||||||
|
let oid = ObjectId::parse_str(chosen).map_err(|_| StatusCode::NOT_FOUND)?;
|
||||||
|
let target = db
|
||||||
|
.onboarded_targets()
|
||||||
|
.find_one(doc! { "_id": oid })
|
||||||
|
.await
|
||||||
|
.map_err(internal)?
|
||||||
|
.ok_or(StatusCode::NOT_FOUND)?;
|
||||||
|
if target.supplier.is_none() {
|
||||||
|
return Ok(refused(
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
"not_supplier_component",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Destination::Existing(target)
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
let known = super::projects::tenant_projects(&agent, &tenant.0.tenant_id).await?;
|
||||||
|
let project_ids = super::projects::validated_project_ids(&body.project_ids, &known)?;
|
||||||
|
let name = body
|
||||||
|
.name
|
||||||
|
.as_deref()
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|n| !n.is_empty())
|
||||||
|
.unwrap_or(&offer.product_name)
|
||||||
|
.to_string();
|
||||||
|
let mut target = OnboardedTarget::new(name, offer.product_type);
|
||||||
|
target.supplier = Some(SupplierComponent {
|
||||||
|
name: offer.supplier_name.clone(),
|
||||||
|
product: Some(offer.product_name.clone()),
|
||||||
|
version: None,
|
||||||
|
csaf_provider: None,
|
||||||
|
});
|
||||||
|
target.project_ids = project_ids;
|
||||||
|
Destination::New(target)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Claim the offer first: of two acceptances, or an acceptance and the
|
||||||
|
// supplier's end, one wins, and nothing is created for the other.
|
||||||
|
let chosen_id = match &into {
|
||||||
|
Destination::Existing(target) => target.id.map(|o| o.to_hex()),
|
||||||
|
Destination::New(_) => None,
|
||||||
|
};
|
||||||
|
let claimed = offers(&db)
|
||||||
|
.update_one(
|
||||||
|
doc! { "_id": offer.id, "state": "offered" },
|
||||||
|
doc! { "$set": {
|
||||||
|
"state": "accepted",
|
||||||
|
"target_id": chosen_id.as_deref(),
|
||||||
|
"decided_at": BsonDateTime::now(),
|
||||||
|
"decided_by": &tenant.0.user_id,
|
||||||
|
} },
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(internal)?;
|
||||||
|
if claimed.modified_count == 0 {
|
||||||
|
return Ok(not_open(find(&db, &id).await?.state));
|
||||||
|
}
|
||||||
|
|
||||||
|
let target = match into {
|
||||||
|
Destination::Existing(target) => {
|
||||||
|
// One release per component: of two claims on it, neither keeps
|
||||||
|
// it when they raced, and the next acceptance finds it free.
|
||||||
|
let receiving = offers(&db)
|
||||||
|
.count_documents(doc! { "target_id": chosen_id.as_deref(), "state": "accepted" })
|
||||||
|
.await
|
||||||
|
.map_err(internal)?;
|
||||||
|
if receiving > 1 {
|
||||||
|
unclaim(&db, offer.id).await?;
|
||||||
|
return Ok(refused(StatusCode::CONFLICT, "target_taken"));
|
||||||
|
}
|
||||||
|
target
|
||||||
|
}
|
||||||
|
Destination::New(target) => {
|
||||||
|
let created =
|
||||||
|
match super::onboarding::insert_target(&agent, &db, &tenant.0.tenant_id, target)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(created) => created,
|
||||||
|
Err(e) => {
|
||||||
|
unclaim(&db, offer.id).await?;
|
||||||
|
return Ok(super::onboarding::target_refused(e));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let created_id = created.id.map(|o| o.to_hex()).unwrap_or_default();
|
||||||
|
let linked = offers(&db)
|
||||||
|
.update_one(
|
||||||
|
doc! { "_id": offer.id, "state": "accepted" },
|
||||||
|
doc! { "$set": { "target_id": &created_id } },
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(internal)?;
|
||||||
|
if linked.matched_count == 0 {
|
||||||
|
// The supplier ended it meanwhile: the new component, still
|
||||||
|
// empty, goes again.
|
||||||
|
if let Some(oid) = created.id {
|
||||||
|
db.onboarded_targets()
|
||||||
|
.delete_one(doc! { "_id": oid })
|
||||||
|
.await
|
||||||
|
.map_err(internal)?;
|
||||||
|
}
|
||||||
|
return Ok(refused(StatusCode::CONFLICT, "ended"));
|
||||||
|
}
|
||||||
|
created
|
||||||
|
}
|
||||||
|
};
|
||||||
|
answer_release(&agent, &offer, OfferState::Accepted).await;
|
||||||
|
// What the supplier already published arrives at once.
|
||||||
|
let accepted = find(&db, &id).await?;
|
||||||
|
super::delivery::deliver_latest(&agent, &accepted).await;
|
||||||
|
audit(
|
||||||
|
&agent,
|
||||||
|
&tenant,
|
||||||
|
"pruefwerk.sbom_offer_accepted",
|
||||||
|
Some(&target),
|
||||||
|
&offer,
|
||||||
|
);
|
||||||
|
let offer = find(&db, &id).await?;
|
||||||
|
Ok(Json(ApiResponse {
|
||||||
|
data: OfferView::from(offer),
|
||||||
|
total: None,
|
||||||
|
page: None,
|
||||||
|
})
|
||||||
|
.into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decline a supplier's SBOM release. The supplier sees the answer.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/sbom-offers/{id}/decline",
|
||||||
|
tag = "Targets",
|
||||||
|
params(("id" = String, Path, description = "The offer's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "Declined (`data`: the offer)"),
|
||||||
|
(status = 404, description = "No such offer"),
|
||||||
|
(status = 409, description = "Already answered or ended (`answered`)"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
(status = 403, description = "A read-only role"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
|
#[tracing::instrument(skip_all, fields(offer_id = %id))]
|
||||||
|
pub async fn decline_offer(
|
||||||
|
Extension(agent): AgentExt,
|
||||||
|
tenant: TenantCtx,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
) -> Result<axum::response::Response, StatusCode> {
|
||||||
|
let db = tenant_db(&agent, &tenant).await?;
|
||||||
|
let offer = find(&db, &id).await?;
|
||||||
|
let declined = offers(&db)
|
||||||
|
.update_one(
|
||||||
|
doc! { "_id": offer.id, "state": "offered" },
|
||||||
|
doc! { "$set": {
|
||||||
|
"state": "declined",
|
||||||
|
"decided_at": BsonDateTime::now(),
|
||||||
|
"decided_by": &tenant.0.user_id,
|
||||||
|
} },
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(internal)?;
|
||||||
|
if declined.modified_count == 0 {
|
||||||
|
return Ok(refused(StatusCode::CONFLICT, "answered"));
|
||||||
|
}
|
||||||
|
answer_release(&agent, &offer, OfferState::Declined).await;
|
||||||
|
audit(
|
||||||
|
&agent,
|
||||||
|
&tenant,
|
||||||
|
"pruefwerk.sbom_offer_declined",
|
||||||
|
None,
|
||||||
|
&offer,
|
||||||
|
);
|
||||||
|
let offer = find(&db, &id).await?;
|
||||||
|
Ok(Json(ApiResponse {
|
||||||
|
data: OfferView::from(offer),
|
||||||
|
total: None,
|
||||||
|
page: None,
|
||||||
|
})
|
||||||
|
.into_response())
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -18,13 +18,24 @@ use compliance_core::tenant_ctx::TenantCtx;
|
|||||||
|
|
||||||
use super::dto::{collect_cursor_async, tenant_db, AgentExt};
|
use super::dto::{collect_cursor_async, tenant_db, AgentExt};
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
/// The body of [`assess_target`].
|
||||||
|
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||||
pub struct AssessRequest {
|
pub struct AssessRequest {
|
||||||
/// The target / repo id whose findings are assessed.
|
/// The target / repo id whose findings are assessed.
|
||||||
pub target_id: String,
|
pub target_id: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `POST /api/v1/oscal/assess` — OSCAL assessment-results for a target's findings.
|
/// A target's findings as OSCAL assessment results.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/oscal/assess",
|
||||||
|
tag = "Compliance",
|
||||||
|
request_body = AssessRequest,
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The OSCAL assessment results"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
pub async fn assess_target(
|
pub async fn assess_target(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
tenant: TenantCtx,
|
tenant: TenantCtx,
|
||||||
|
|||||||
@@ -21,8 +21,10 @@ use super::super::dto::{collect_cursor_async, tenant_db};
|
|||||||
|
|
||||||
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
/// The body of [`export_session_report`].
|
||||||
|
#[derive(Deserialize, utoipa::ToSchema)]
|
||||||
pub struct ExportBody {
|
pub struct ExportBody {
|
||||||
|
/// The password the archive is encrypted with.
|
||||||
pub password: String,
|
pub password: String,
|
||||||
/// Requester display name (from auth)
|
/// Requester display name (from auth)
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
@@ -32,7 +34,20 @@ pub struct ExportBody {
|
|||||||
pub requester_email: String,
|
pub requester_email: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /api/v1/pentest/sessions/:id/export — Export an encrypted pentest report archive
|
/// A session's report as an encrypted archive to download.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/pentest/sessions/{id}/export",
|
||||||
|
tag = "Pentest",
|
||||||
|
params(("id" = String, Path, description = "The session's id")),
|
||||||
|
request_body = ExportBody,
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The archive"),
|
||||||
|
(status = 400, description = "Not an id, or no password"),
|
||||||
|
(status = 404, description = "No such session"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
||||||
pub async fn export_session_report(
|
pub async fn export_session_report(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
|
|||||||
@@ -17,13 +17,18 @@ use super::super::dto::{collect_cursor_async, tenant_db, ApiResponse, Pagination
|
|||||||
|
|
||||||
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
/// The body of [`create_session`].
|
||||||
|
#[derive(Deserialize, utoipa::ToSchema)]
|
||||||
pub struct CreateSessionRequest {
|
pub struct CreateSessionRequest {
|
||||||
|
/// The target to test, for a session without `config`.
|
||||||
pub target_id: Option<String>,
|
pub target_id: Option<String>,
|
||||||
|
/// `quick`, `comprehensive` (default), `targeted` or `aggressive`.
|
||||||
#[serde(default = "default_strategy")]
|
#[serde(default = "default_strategy")]
|
||||||
pub strategy: String,
|
pub strategy: String,
|
||||||
|
/// The first instruction.
|
||||||
pub message: Option<String>,
|
pub message: Option<String>,
|
||||||
/// Wizard configuration — if present, takes precedence over legacy fields
|
/// Wizard configuration — if present, takes precedence over legacy fields
|
||||||
|
#[schema(value_type = Option<Object>)]
|
||||||
pub config: Option<PentestConfig>,
|
pub config: Option<PentestConfig>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -31,17 +36,37 @@ fn default_strategy() -> String {
|
|||||||
"comprehensive".to_string()
|
"comprehensive".to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
/// The body of [`send_message`].
|
||||||
|
#[derive(Deserialize, utoipa::ToSchema)]
|
||||||
pub struct SendMessageRequest {
|
pub struct SendMessageRequest {
|
||||||
|
/// The message.
|
||||||
pub message: String,
|
pub message: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
/// The query of [`lookup_repo`].
|
||||||
|
#[derive(Deserialize, utoipa::IntoParams)]
|
||||||
|
#[into_params(parameter_in = Query)]
|
||||||
pub struct LookupRepoQuery {
|
pub struct LookupRepoQuery {
|
||||||
|
/// The repository's git URL.
|
||||||
pub url: String,
|
pub url: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /api/v1/pentest/sessions — Create a new pentest session and start the orchestrator
|
/// Create a pentest session and start it.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/pentest/sessions",
|
||||||
|
tag = "Pentest",
|
||||||
|
request_body = CreateSessionRequest,
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The session"),
|
||||||
|
(status = 400, description = "A missing disclaimer, target or id, or a URL the agent may not reach"),
|
||||||
|
(status = 404, description = "No such target"),
|
||||||
|
(status = 409, description = "Pentests are not available on this deployment (static analysis only)"),
|
||||||
|
(status = 429, description = "Too many sessions are running"),
|
||||||
|
(status = 503, description = "A credential cannot be sealed"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn create_session(
|
pub async fn create_session(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -86,6 +111,13 @@ pub async fn create_session(
|
|||||||
if let Err(e) = agent.net_guard.check_url(&config.app_url) {
|
if let Err(e) = agent.net_guard.check_url(&config.app_url) {
|
||||||
return Err((StatusCode::BAD_REQUEST, e.to_string()));
|
return Err((StatusCode::BAD_REQUEST, e.to_string()));
|
||||||
}
|
}
|
||||||
|
// The test-user cleanup talks to the target's identity provider, also
|
||||||
|
// a tenant-chosen URL.
|
||||||
|
if let Some(access) = &config.auth.cleanup {
|
||||||
|
if let Err(e) = agent.net_guard.check_url(&access.base_url()) {
|
||||||
|
return Err((StatusCode::BAD_REQUEST, e.to_string()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Look up or auto-create DastTarget by app_url
|
// Look up or auto-create DastTarget by app_url
|
||||||
let target = match db
|
let target = match db
|
||||||
@@ -187,35 +219,21 @@ pub async fn create_session(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pre-populate test user record for auto-register sessions
|
// The test user an auto-register session registers, kept on the
|
||||||
if let Some(ref cfg) = session.config {
|
// stored session so cleanup and the report find it.
|
||||||
if cfg.auth.mode == AuthMode::AutoRegister {
|
if let Some(cfg) = &session.config {
|
||||||
let verification_email = cfg.auth.verification_email.clone();
|
session.test_user = crate::pentest::cleanup::planned_test_user(cfg, &session_id_str);
|
||||||
// Build plus-addressed email for this session
|
}
|
||||||
let test_email = verification_email.as_deref().map(|email| {
|
if let (Some(sid), Some(test_user)) = (session.id, &session.test_user) {
|
||||||
let parts: Vec<&str> = email.splitn(2, '@').collect();
|
let record = mongodb::bson::to_bson(test_user)
|
||||||
if parts.len() == 2 {
|
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||||
format!("{}+{}@{}", parts[0], session_id_str, parts[1])
|
db.pentest_sessions()
|
||||||
} else {
|
.update_one(
|
||||||
email.to_string()
|
doc! { "_id": sid },
|
||||||
}
|
doc! { "$set": { "test_user": record } },
|
||||||
});
|
)
|
||||||
|
.await
|
||||||
// Detect identity provider from keycloak config
|
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("DB error: {e}")))?;
|
||||||
let provider = if agent.config.keycloak_url.is_some() {
|
|
||||||
Some(compliance_core::models::pentest::IdentityProvider::Keycloak)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
session.test_user = Some(compliance_core::models::pentest::TestUserRecord {
|
|
||||||
username: None, // LLM will choose; updated after registration
|
|
||||||
email: test_email,
|
|
||||||
provider_user_id: None,
|
|
||||||
provider,
|
|
||||||
cleaned_up: false,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let initial_message = config
|
let initial_message = config
|
||||||
@@ -356,7 +374,17 @@ fn parse_strategy(s: &str) -> PentestStrategy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/pentest/lookup-repo — Look up a tracked repository by git URL
|
/// Look up a tracked repository by its git URL.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/pentest/lookup-repo",
|
||||||
|
tag = "Pentest",
|
||||||
|
params(LookupRepoQuery),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The repository, or null"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn lookup_repo(
|
pub async fn lookup_repo(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -389,7 +417,17 @@ pub async fn lookup_repo(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/pentest/sessions — List pentest sessions
|
/// The tenant's pentest sessions, a page at a time.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/pentest/sessions",
|
||||||
|
tag = "Pentest",
|
||||||
|
params(PaginationParams),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "A page of sessions"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn list_sessions(
|
pub async fn list_sessions(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -427,7 +465,19 @@ pub async fn list_sessions(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/pentest/sessions/:id — Get a single pentest session
|
/// One pentest session.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/pentest/sessions/{id}",
|
||||||
|
tag = "Pentest",
|
||||||
|
params(("id" = String, Path, description = "The session's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The session"),
|
||||||
|
(status = 400, description = "Not an id"),
|
||||||
|
(status = 404, description = "No such session"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
||||||
pub async fn get_session(
|
pub async fn get_session(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -461,7 +511,20 @@ pub async fn get_session(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /api/v1/pentest/sessions/:id/chat — Send a user message and trigger next orchestrator iteration
|
/// Send a message to a session, which starts its next iteration.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/pentest/sessions/{id}/chat",
|
||||||
|
tag = "Pentest",
|
||||||
|
params(("id" = String, Path, description = "The session's id")),
|
||||||
|
request_body = SendMessageRequest,
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The stored message"),
|
||||||
|
(status = 400, description = "Not an id"),
|
||||||
|
(status = 404, description = "No such session"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
||||||
pub async fn send_message(
|
pub async fn send_message(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -561,7 +624,19 @@ pub async fn send_message(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /api/v1/pentest/sessions/:id/stop — Stop a running pentest session
|
/// Stop a running session.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/pentest/sessions/{id}/stop",
|
||||||
|
tag = "Pentest",
|
||||||
|
params(("id" = String, Path, description = "The session's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The stopped session"),
|
||||||
|
(status = 400, description = "Not an id, or the session is not running"),
|
||||||
|
(status = 404, description = "No such session"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
||||||
pub async fn stop_session(
|
pub async fn stop_session(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -637,7 +712,19 @@ pub async fn stop_session(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /api/v1/pentest/sessions/:id/pause — Pause a running pentest session
|
/// Pause a running session.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/pentest/sessions/{id}/pause",
|
||||||
|
tag = "Pentest",
|
||||||
|
params(("id" = String, Path, description = "The session's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "Paused"),
|
||||||
|
(status = 400, description = "Not an id, or the session is not running"),
|
||||||
|
(status = 404, description = "No such session"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
||||||
pub async fn pause_session(
|
pub async fn pause_session(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -683,7 +770,19 @@ pub async fn pause_session(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /api/v1/pentest/sessions/:id/resume — Resume a paused pentest session
|
/// Resume a paused session.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/pentest/sessions/{id}/resume",
|
||||||
|
tag = "Pentest",
|
||||||
|
params(("id" = String, Path, description = "The session's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "Resumed"),
|
||||||
|
(status = 400, description = "Not an id, or the session is not paused"),
|
||||||
|
(status = 404, description = "No such session"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
||||||
pub async fn resume_session(
|
pub async fn resume_session(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -734,7 +833,18 @@ pub async fn resume_session(
|
|||||||
/// being loaded whole into agent memory.
|
/// being loaded whole into agent memory.
|
||||||
const MAX_ATTACK_CHAIN_NODES: i64 = 2_000;
|
const MAX_ATTACK_CHAIN_NODES: i64 = 2_000;
|
||||||
|
|
||||||
/// GET /api/v1/pentest/sessions/:id/attack-chain — Get attack chain nodes for a session
|
/// A session's attack chain.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/pentest/sessions/{id}/attack-chain",
|
||||||
|
tag = "Pentest",
|
||||||
|
params(("id" = String, Path, description = "The session's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The nodes"),
|
||||||
|
(status = 400, description = "Not an id"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
||||||
pub async fn get_attack_chain(
|
pub async fn get_attack_chain(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -774,7 +884,18 @@ pub async fn get_attack_chain(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/pentest/sessions/:id/messages — Get messages for a session
|
/// A session's messages, a page at a time.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/pentest/sessions/{id}/messages",
|
||||||
|
tag = "Pentest",
|
||||||
|
params(("id" = String, Path, description = "The session's id"), PaginationParams),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "A page of messages"),
|
||||||
|
(status = 400, description = "Not an id"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
||||||
pub async fn get_messages(
|
pub async fn get_messages(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -814,7 +935,18 @@ pub async fn get_messages(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/pentest/sessions/:id/findings — Get DAST findings for a pentest session
|
/// A session's findings, a page at a time.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/pentest/sessions/{id}/findings",
|
||||||
|
tag = "Pentest",
|
||||||
|
params(("id" = String, Path, description = "The session's id"), PaginationParams),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "A page of findings"),
|
||||||
|
(status = 400, description = "Not an id"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
||||||
pub async fn get_session_findings(
|
pub async fn get_session_findings(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
|
|||||||
@@ -14,7 +14,16 @@ use super::super::dto::{collect_cursor_async, tenant_db, ApiResponse};
|
|||||||
|
|
||||||
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
||||||
|
|
||||||
/// GET /api/v1/pentest/stats — Aggregated pentest statistics
|
/// The tenant's pentest statistics.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/pentest/stats",
|
||||||
|
tag = "Pentest",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The statistics"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn pentest_stats(
|
pub async fn pentest_stats(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
|
|||||||
@@ -19,10 +19,22 @@ use super::super::dto::{collect_cursor_async, tenant_db};
|
|||||||
|
|
||||||
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
||||||
|
|
||||||
/// GET /api/v1/pentest/sessions/:id/stream — SSE endpoint for real-time events
|
/// A session's events as they happen (server-sent events).
|
||||||
///
|
///
|
||||||
/// Replays stored messages/nodes as initial burst, then subscribes to the
|
/// Replays stored messages/nodes as initial burst, then subscribes to the
|
||||||
/// broadcast channel for live updates. Sends keepalive comments every 15s.
|
/// broadcast channel for live updates. Sends keepalive comments every 15s.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/pentest/sessions/{id}/stream",
|
||||||
|
tag = "Pentest",
|
||||||
|
params(("id" = String, Path, description = "The session's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The event stream (text/event-stream)"),
|
||||||
|
(status = 400, description = "Not an id"),
|
||||||
|
(status = 404, description = "No such session"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
||||||
pub async fn session_stream(
|
pub async fn session_stream(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
|
|||||||
@@ -250,14 +250,16 @@ pub async fn export(
|
|||||||
|
|
||||||
/// `DELETE /api/v1/platform/tenants/{id}/data` — GDPR erasure: drops the
|
/// `DELETE /api/v1/platform/tenants/{id}/data` — GDPR erasure: drops the
|
||||||
/// tenant database and removes its code from disk (clones, uploads, work
|
/// tenant database and removes its code from disk (clones, uploads, work
|
||||||
/// trees, blobs, runner artifacts). Requires `{"confirm": "<slug or id>"}`.
|
/// 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.
|
||||||
pub async fn delete_data(
|
pub async fn delete_data(
|
||||||
State(st): State<PlatformState>,
|
State(st): State<PlatformState>,
|
||||||
Path(tenant_id): Path<String>,
|
Path(tenant_id): Path<String>,
|
||||||
body: Option<Json<LifecycleBody>>,
|
body: Option<Json<LifecycleBody>>,
|
||||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||||
let confirm = body.and_then(|Json(b)| b.confirm).unwrap_or_default();
|
let confirm = body.and_then(|Json(b)| b.confirm);
|
||||||
if confirm.is_empty() {
|
if !confirms_erasure(&tenant_id, confirm.as_deref()) {
|
||||||
return Err(StatusCode::BAD_REQUEST);
|
return Err(StatusCode::BAD_REQUEST);
|
||||||
}
|
}
|
||||||
// Where the tenant's code lies on disk, read before its records go.
|
// Where the tenant's code lies on disk, read before its records go.
|
||||||
@@ -299,6 +301,12 @@ 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
|
/// `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 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
|
/// demo targets and starts their scans, which is what the nightly reset of the
|
||||||
@@ -462,6 +470,10 @@ pub struct PlatformTarget {
|
|||||||
pub open_vulnerabilities: u64,
|
pub open_vulnerabilities: u64,
|
||||||
/// Its projects that the registry still lists.
|
/// Its projects that the registry still lists.
|
||||||
pub project_ids: Vec<String>,
|
pub project_ids: Vec<String>,
|
||||||
|
/// Who supplies it, for a component bought in (#1025): the targets a
|
||||||
|
/// supplier can be invited for (#1027). Left out for the tenant's own.
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub supplier: Option<compliance_core::models::SupplierComponent>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Open findings of each target in `target_ids`, in one query.
|
/// Open findings of each target in `target_ids`, in one query.
|
||||||
@@ -582,6 +594,7 @@ pub async fn list_targets(
|
|||||||
},
|
},
|
||||||
name: t.name,
|
name: t.name,
|
||||||
target_type: t.target_type,
|
target_type: t.target_type,
|
||||||
|
supplier: t.supplier,
|
||||||
id,
|
id,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -843,3 +856,20 @@ mod target_count_tests {
|
|||||||
assert!(stages[0].contains_key("$match") && stages[1].contains_key("$group"));
|
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("")));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -106,8 +106,17 @@ pub fn projects_changed_entry(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/projects — the tenant's projects, for choosing and showing
|
/// The tenant's projects, for choosing and showing them in the dashboard.
|
||||||
/// them in the dashboard.
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/projects",
|
||||||
|
tag = "Workspace",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The projects"),
|
||||||
|
(status = 503, description = "The registry cannot be asked"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn list_projects(
|
pub async fn list_projects(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -128,6 +137,8 @@ mod tests {
|
|||||||
name: format!("Projekt {id}"),
|
name: format!("Projekt {id}"),
|
||||||
kind: ProjectKind::Product,
|
kind: ProjectKind::Product,
|
||||||
description: String::new(),
|
description: String::new(),
|
||||||
|
level: None,
|
||||||
|
parent_id: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -16,6 +16,16 @@ pub(crate) const MAX_EXPORT_COMPONENTS: u64 = 100_000;
|
|||||||
/// Package names listed per license in the summary; `count` stays exact.
|
/// Package names listed per license in the summary; `count` stays exact.
|
||||||
const MAX_LICENSE_PACKAGES: i64 = 100;
|
const MAX_LICENSE_PACKAGES: i64 = 100;
|
||||||
|
|
||||||
|
/// The package managers and licences the SBOM list can be filtered by.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/sbom/filters",
|
||||||
|
tag = "SBOM",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The package managers and licences"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn sbom_filters(
|
pub async fn sbom_filters(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -50,6 +60,17 @@ pub async fn sbom_filters(
|
|||||||
})))
|
})))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// List the tenant's SBOM components, filtered and a page at a time.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/sbom",
|
||||||
|
tag = "SBOM",
|
||||||
|
params(SbomFilter),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "A page of components"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(repo_id = ?filter.repo_id, package_manager = ?filter.package_manager))]
|
#[tracing::instrument(skip_all, fields(repo_id = ?filter.repo_id, package_manager = ?filter.package_manager))]
|
||||||
pub async fn list_sbom(
|
pub async fn list_sbom(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -198,6 +219,20 @@ async fn unresolved_ids(
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A target's SBOM as a CycloneDX or SPDX document to download.
|
||||||
|
///
|
||||||
|
/// Never truncated: a target with more than 100 000 components is refused.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/sbom/export",
|
||||||
|
tag = "SBOM",
|
||||||
|
params(SbomExportParams),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The SBOM document"),
|
||||||
|
(status = 413, description = "Too many components to export"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn export_sbom(
|
pub async fn export_sbom(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -274,14 +309,27 @@ pub async fn export_sbom(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The target whose SBOM quality is asked for.
|
/// The target whose SBOM quality is asked for.
|
||||||
#[derive(serde::Deserialize)]
|
#[derive(serde::Deserialize, utoipa::IntoParams)]
|
||||||
|
#[into_params(parameter_in = Query)]
|
||||||
pub struct SbomQualityParams {
|
pub struct SbomQualityParams {
|
||||||
|
/// The target (its id).
|
||||||
pub repo_id: String,
|
pub repo_id: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/sbom/quality?repo_id= — the target's SBOM quality score
|
/// A target's SBOM quality score from its newest scan that scored one.
|
||||||
/// (sbomqs against BSI TR-03183-2 and NTIA, #496) from its newest scan that
|
///
|
||||||
/// scored one, with that scan's id and end; `data: null` when none did.
|
/// sbomqs against BSI TR-03183-2 and NTIA (#496), with that scan's id and
|
||||||
|
/// end; `data: null` when none did.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/sbom/quality",
|
||||||
|
tag = "SBOM",
|
||||||
|
params(SbomQualityParams),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The score, or null"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all, fields(repo_id = %params.repo_id))]
|
#[tracing::instrument(skip_all, fields(repo_id = %params.repo_id))]
|
||||||
pub async fn sbom_quality(
|
pub async fn sbom_quality(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -308,6 +356,19 @@ pub async fn sbom_quality(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The licences of the SBOM components, most components first.
|
||||||
|
///
|
||||||
|
/// The confirmed licence where there is one, else the detected one.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/sbom/licenses",
|
||||||
|
tag = "SBOM",
|
||||||
|
params(SbomFilter),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "One row per licence"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn license_summary(
|
pub async fn license_summary(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -411,6 +472,19 @@ fn summarize_licenses(
|
|||||||
summaries
|
summaries
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Compare the SBOMs of two targets.
|
||||||
|
///
|
||||||
|
/// The components only in one of them and those whose version differs.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/sbom/diff",
|
||||||
|
tag = "SBOM",
|
||||||
|
params(SbomDiffParams),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The differences"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn sbom_diff(
|
pub async fn sbom_diff(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
|
|||||||
@@ -64,11 +64,30 @@ pub async fn target_scan_changes(
|
|||||||
.map_err(db_error("reading the target"))?
|
.map_err(db_error("reading the target"))?
|
||||||
.ok_or(StatusCode::NOT_FOUND)?;
|
.ok_or(StatusCode::NOT_FOUND)?;
|
||||||
|
|
||||||
|
let data = target_changes(&db, &id, query.limit).await?;
|
||||||
|
Ok(Json(ApiResponse {
|
||||||
|
total: Some(data.len() as u64),
|
||||||
|
data,
|
||||||
|
page: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The last `limit` scans of target `id`, oldest first, each with what it
|
||||||
|
/// changed (see [`target_scan_changes`]).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// 500 when the database cannot be read.
|
||||||
|
pub(crate) async fn target_changes(
|
||||||
|
db: &crate::database::Database,
|
||||||
|
id: &str,
|
||||||
|
limit: usize,
|
||||||
|
) -> Result<Vec<ScanChange>, StatusCode> {
|
||||||
let runs: Vec<ScanRun> = collect_cursor_async(
|
let runs: Vec<ScanRun> = collect_cursor_async(
|
||||||
db.scan_runs()
|
db.scan_runs()
|
||||||
.find(doc! { "repo_id": &id })
|
.find(doc! { "repo_id": id })
|
||||||
.sort(doc! { "started_at": -1 })
|
.sort(doc! { "started_at": -1 })
|
||||||
.limit(i64::try_from(query.limit).unwrap_or(i64::MAX))
|
.limit(i64::try_from(limit).unwrap_or(i64::MAX))
|
||||||
.await
|
.await
|
||||||
.map_err(db_error("listing the runs"))?,
|
.map_err(db_error("listing the runs"))?,
|
||||||
)
|
)
|
||||||
@@ -79,7 +98,7 @@ pub async fn target_scan_changes(
|
|||||||
Some(oldest) => db
|
Some(oldest) => db
|
||||||
.scan_runs()
|
.scan_runs()
|
||||||
.find_one(doc! {
|
.find_one(doc! {
|
||||||
"repo_id": &id,
|
"repo_id": id,
|
||||||
"status": "completed",
|
"status": "completed",
|
||||||
"started_at": { "$lt": BsonDateTime::from_chrono(oldest) },
|
"started_at": { "$lt": BsonDateTime::from_chrono(oldest) },
|
||||||
})
|
})
|
||||||
@@ -90,7 +109,7 @@ pub async fn target_scan_changes(
|
|||||||
None => None,
|
None => None,
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut filter = doc! { "repo_id": &id };
|
let mut filter = doc! { "repo_id": id };
|
||||||
if let Some(since) = since {
|
if let Some(since) = since {
|
||||||
let since = BsonDateTime::from_chrono(since);
|
let since = BsonDateTime::from_chrono(since);
|
||||||
filter.insert(
|
filter.insert(
|
||||||
@@ -112,12 +131,7 @@ pub async fn target_scan_changes(
|
|||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
let data = changes(&runs, since, &alerts);
|
Ok(changes(&runs, since, &alerts))
|
||||||
Ok(Json(ApiResponse {
|
|
||||||
total: Some(data.len() as u64),
|
|
||||||
data,
|
|
||||||
page: None,
|
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -8,7 +8,8 @@ use compliance_core::models::ScanRun;
|
|||||||
use compliance_core::tenant_ctx::TenantCtx;
|
use compliance_core::tenant_ctx::TenantCtx;
|
||||||
|
|
||||||
/// Which scan runs to list.
|
/// Which scan runs to list.
|
||||||
#[derive(Debug, Default, Deserialize)]
|
#[derive(Debug, Default, Deserialize, utoipa::IntoParams)]
|
||||||
|
#[into_params(parameter_in = Query)]
|
||||||
pub struct ScanRunFilter {
|
pub struct ScanRunFilter {
|
||||||
/// Only the runs of this target (its id), for the target's scan history.
|
/// Only the runs of this target (its id), for the target's scan history.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
@@ -25,7 +26,17 @@ impl ScanRunFilter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/scan-runs?target_id=&page=&limit= — newest first.
|
/// The tenant's scan runs, newest first, a page at a time.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/scan-runs",
|
||||||
|
tag = "Scans",
|
||||||
|
params(PaginationParams, ScanRunFilter),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "A page of scan runs"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn list_scan_runs(
|
pub async fn list_scan_runs(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
//! What Prüfwerk knows of a bought-in component's supplier (#1025): how many
|
||||||
|
//! of its CSAF advisories are kept for the workspace, and when its provider
|
||||||
|
//! was last read.
|
||||||
|
|
||||||
|
use axum::extract::{Extension, Path};
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::Json;
|
||||||
|
use mongodb::bson::{doc, oid::ObjectId};
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
use compliance_core::tenant_ctx::TenantCtx;
|
||||||
|
|
||||||
|
use super::dto::{tenant_db, AgentExt};
|
||||||
|
use super::ApiResponse;
|
||||||
|
use crate::pipeline::csaf_feed::{supplier_key, MongoAdvisoryStore, SupplierProviderStatus};
|
||||||
|
|
||||||
|
/// The advisories of a target's supplier, as the target editor shows them.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||||
|
pub struct SupplierAdvisories {
|
||||||
|
/// The supplier's advisories kept for the workspace.
|
||||||
|
pub advisories: u64,
|
||||||
|
/// When its provider was last read; none before the first refresh.
|
||||||
|
pub checked_at: Option<chrono::DateTime<chrono::Utc>>,
|
||||||
|
/// Whether its metadata and feeds could be read then; none before the
|
||||||
|
/// first refresh.
|
||||||
|
pub reachable: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Count the target's supplier advisories, with their provider's last read.
|
||||||
|
///
|
||||||
|
/// `data` holds `advisories`, `checked_at` and `reachable` (both null before
|
||||||
|
/// the first refresh), or is null when the target names no supplier CSAF
|
||||||
|
/// provider. The
|
||||||
|
/// advisories are the workspace's own: a provider is read for the workspaces
|
||||||
|
/// that name it, daily and right after it is set.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/targets/{id}/supplier-advisories",
|
||||||
|
tag = "Targets",
|
||||||
|
params(("id" = String, Path, description = "The target's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The supplier's advisories, or null without a provider"),
|
||||||
|
(status = 400, description = "Not an id"),
|
||||||
|
(status = 404, description = "No such target"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
|
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||||
|
pub async fn get_supplier_advisories(
|
||||||
|
Extension(agent): AgentExt,
|
||||||
|
tenant: TenantCtx,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
) -> Result<Json<ApiResponse<Option<SupplierAdvisories>>>, StatusCode> {
|
||||||
|
let oid = ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||||
|
let db = tenant_db(&agent, &tenant).await?;
|
||||||
|
let target = db
|
||||||
|
.onboarded_targets()
|
||||||
|
.find_one(doc! { "_id": oid })
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||||
|
.ok_or(StatusCode::NOT_FOUND)?;
|
||||||
|
let Some(url) = target.supplier.and_then(|s| s.csaf_provider) else {
|
||||||
|
return Ok(Json(ApiResponse {
|
||||||
|
data: None,
|
||||||
|
total: None,
|
||||||
|
page: None,
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
let key = supplier_key(&url);
|
||||||
|
let advisories = MongoAdvisoryStore::supplier(db.inner())
|
||||||
|
.collection()
|
||||||
|
.count_documents(doc! { "provider": &key })
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
let status = db
|
||||||
|
.inner()
|
||||||
|
.collection::<SupplierProviderStatus>(SupplierProviderStatus::COLLECTION)
|
||||||
|
.find_one(doc! { "_id": &key })
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
Ok(Json(ApiResponse {
|
||||||
|
data: Some(SupplierAdvisories {
|
||||||
|
advisories,
|
||||||
|
checked_at: status.as_ref().map(|s| s.checked_at.to_chrono()),
|
||||||
|
reachable: status.map(|s| s.reachable),
|
||||||
|
}),
|
||||||
|
total: None,
|
||||||
|
page: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
@@ -0,0 +1,904 @@
|
|||||||
|
//! Supplier invites (#1027): the customer invites a supplier, through the
|
||||||
|
//! portal, to upload the SBOM of one bought-in component.
|
||||||
|
//!
|
||||||
|
//! The portal owns the secret link and the mail; Prüfwerk keeps the invite in
|
||||||
|
//! the tenant's own database (so the tenant export and erasure cover it, the
|
||||||
|
//! supplier's address included) and refuses what an expired or withdrawn
|
||||||
|
//! invite would allow. The portal calls these endpoints with its platform
|
||||||
|
//! service token ([`super::platform::require_platform_token`]).
|
||||||
|
//!
|
||||||
|
//! An invite is valid for [`INVITE_LIFETIME_DAYS`] from when it is made, and
|
||||||
|
//! serves the component's later SBOM versions until it expires or is
|
||||||
|
//! withdrawn (decided 2026-11-18).
|
||||||
|
//!
|
||||||
|
//! An upload through an invite takes the customer's own upload path
|
||||||
|
//! ([`super::onboarding::attach_upload`]): it becomes the component's SBOM and
|
||||||
|
//! starts a scan. Every upload, refused ones included, is recorded with the
|
||||||
|
//! invite it came through ([`SupplierUpload`]), for the customer and the
|
||||||
|
//! supplier to see.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use axum::extract::{Multipart, Path, Query, State};
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::Json;
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use futures_util::TryStreamExt;
|
||||||
|
use mongodb::bson::{doc, oid::ObjectId, DateTime as BsonDateTime};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use compliance_core::models::{ArtifactKind, OnboardedTarget, ScanTrigger};
|
||||||
|
|
||||||
|
use super::onboarding::{
|
||||||
|
attach_upload, is_https_url, refresh_supplier_csaf, stream_to_disk, StoredUpload,
|
||||||
|
SupplierSbomSummary, UploadRefusal,
|
||||||
|
};
|
||||||
|
use super::platform::PlatformState;
|
||||||
|
use crate::agent::ComplianceAgent;
|
||||||
|
use crate::database::Database;
|
||||||
|
use crate::pipeline::sbom::supplied::MAX_BYTES as MAX_SBOM_BYTES;
|
||||||
|
|
||||||
|
/// How long an invite is valid, in days from when it is made.
|
||||||
|
pub const INVITE_LIFETIME_DAYS: i64 = 90;
|
||||||
|
|
||||||
|
/// The longest e-mail address accepted (RFC 5321's path limit).
|
||||||
|
const MAX_EMAIL_LEN: usize = 254;
|
||||||
|
|
||||||
|
/// The longest `invited_by` / `withdrawn_by` accepted: a portal user's id.
|
||||||
|
const MAX_ACTOR_LEN: usize = 200;
|
||||||
|
|
||||||
|
/// The most uploads one invite takes in a day, refused ones included: each
|
||||||
|
/// accepted one starts a scan the customer pays for.
|
||||||
|
pub const MAX_UPLOADS_PER_DAY: u64 = 20;
|
||||||
|
|
||||||
|
/// The longest file name kept with an upload, in characters.
|
||||||
|
const MAX_FILENAME_CHARS: usize = 200;
|
||||||
|
|
||||||
|
/// An invite as stored, in the tenant's [`SupplierInvite::COLLECTION`].
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct SupplierInvite {
|
||||||
|
/// Its id, which the portal keys its secret link by.
|
||||||
|
#[serde(rename = "_id")]
|
||||||
|
pub id: ObjectId,
|
||||||
|
/// The target (a supplier component) the invite is for.
|
||||||
|
pub target_id: String,
|
||||||
|
/// Who was invited: the supplier's e-mail address, lower case.
|
||||||
|
pub email: String,
|
||||||
|
/// The portal user who sent it.
|
||||||
|
pub invited_by: String,
|
||||||
|
/// When it was made.
|
||||||
|
pub created_at: BsonDateTime,
|
||||||
|
/// When it stops being valid.
|
||||||
|
pub expires_at: BsonDateTime,
|
||||||
|
/// When it was withdrawn; `None` while it is not.
|
||||||
|
#[serde(default)]
|
||||||
|
pub withdrawn_at: Option<BsonDateTime>,
|
||||||
|
/// The portal user who withdrew it.
|
||||||
|
#[serde(default)]
|
||||||
|
pub withdrawn_by: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether an invite still allows an upload.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum InviteState {
|
||||||
|
/// Uploads are accepted.
|
||||||
|
Active,
|
||||||
|
/// Past `expires_at`.
|
||||||
|
Expired,
|
||||||
|
/// Withdrawn by the customer (this wins over expiry).
|
||||||
|
Withdrawn,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SupplierInvite {
|
||||||
|
/// The collection, in the tenant's own database.
|
||||||
|
pub const COLLECTION: &'static str = "supplier_invites";
|
||||||
|
|
||||||
|
/// A new invite for `target_id`, made at `now`.
|
||||||
|
pub fn new(target_id: String, email: String, invited_by: String, now: DateTime<Utc>) -> Self {
|
||||||
|
Self {
|
||||||
|
id: ObjectId::new(),
|
||||||
|
target_id,
|
||||||
|
email,
|
||||||
|
invited_by,
|
||||||
|
created_at: now.into(),
|
||||||
|
expires_at: (now + chrono::Duration::days(INVITE_LIFETIME_DAYS)).into(),
|
||||||
|
withdrawn_at: None,
|
||||||
|
withdrawn_by: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Its state at `now`.
|
||||||
|
pub fn state(&self, now: DateTime<Utc>) -> InviteState {
|
||||||
|
if self.withdrawn_at.is_some() {
|
||||||
|
InviteState::Withdrawn
|
||||||
|
} else if now >= self.expires_at.to_chrono() {
|
||||||
|
InviteState::Expired
|
||||||
|
} else {
|
||||||
|
InviteState::Active
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An invite as the portal reads it.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||||
|
pub struct InviteView {
|
||||||
|
/// The invite's id.
|
||||||
|
pub id: String,
|
||||||
|
/// The target it is for.
|
||||||
|
pub target_id: String,
|
||||||
|
/// The supplier's e-mail address.
|
||||||
|
pub email: String,
|
||||||
|
/// The portal user who sent it.
|
||||||
|
pub invited_by: String,
|
||||||
|
/// When it was made.
|
||||||
|
pub created_at: DateTime<Utc>,
|
||||||
|
/// When it stops being valid.
|
||||||
|
pub expires_at: DateTime<Utc>,
|
||||||
|
/// When it was withdrawn, if it was.
|
||||||
|
pub withdrawn_at: Option<DateTime<Utc>>,
|
||||||
|
/// Who withdrew it, if anyone did.
|
||||||
|
pub withdrawn_by: Option<String>,
|
||||||
|
/// Whether it still allows an upload.
|
||||||
|
pub state: InviteState,
|
||||||
|
/// What came through it, newest first.
|
||||||
|
pub uploads: Vec<UploadView>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InviteView {
|
||||||
|
/// The view of `invite` at `now`, with its `uploads`.
|
||||||
|
fn of(invite: SupplierInvite, now: DateTime<Utc>, uploads: Vec<UploadView>) -> Self {
|
||||||
|
Self {
|
||||||
|
uploads,
|
||||||
|
state: invite.state(now),
|
||||||
|
id: invite.id.to_hex(),
|
||||||
|
target_id: invite.target_id,
|
||||||
|
email: invite.email,
|
||||||
|
invited_by: invite.invited_by,
|
||||||
|
created_at: invite.created_at.to_chrono(),
|
||||||
|
expires_at: invite.expires_at.to_chrono(),
|
||||||
|
withdrawn_at: invite.withdrawn_at.map(BsonDateTime::to_chrono),
|
||||||
|
withdrawn_by: invite.withdrawn_by,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An upload through an invite, as stored in [`SupplierUpload::COLLECTION`]:
|
||||||
|
/// accepted or refused, with what the file held.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct SupplierUpload {
|
||||||
|
/// Its id.
|
||||||
|
#[serde(rename = "_id")]
|
||||||
|
pub id: ObjectId,
|
||||||
|
/// The invite it came through.
|
||||||
|
pub invite_id: String,
|
||||||
|
/// The target it was for.
|
||||||
|
pub target_id: String,
|
||||||
|
/// When it arrived.
|
||||||
|
pub uploaded_at: BsonDateTime,
|
||||||
|
/// The file's name, as the supplier sent it.
|
||||||
|
pub filename: String,
|
||||||
|
/// Whether it became the component's SBOM.
|
||||||
|
pub accepted: bool,
|
||||||
|
/// Why it was refused: the code of the refusal.
|
||||||
|
#[serde(default)]
|
||||||
|
pub code: Option<String>,
|
||||||
|
/// What an accepted SBOM holds.
|
||||||
|
#[serde(default)]
|
||||||
|
pub summary: Option<SupplierSbomSummary>,
|
||||||
|
/// The artifact an accepted SBOM became.
|
||||||
|
#[serde(default)]
|
||||||
|
pub artifact_id: Option<String>,
|
||||||
|
/// The CSAF provider the supplier gave with it.
|
||||||
|
#[serde(default)]
|
||||||
|
pub csaf_provider: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SupplierUpload {
|
||||||
|
/// The collection, in the tenant's own database.
|
||||||
|
pub const COLLECTION: &'static str = "supplier_uploads";
|
||||||
|
|
||||||
|
/// A refused upload of `filename` through `invite`, with the refusal's code.
|
||||||
|
fn refused(invite: &SupplierInvite, filename: &str, code: &str) -> Self {
|
||||||
|
Self {
|
||||||
|
id: ObjectId::new(),
|
||||||
|
invite_id: invite.id.to_hex(),
|
||||||
|
target_id: invite.target_id.clone(),
|
||||||
|
uploaded_at: BsonDateTime::now(),
|
||||||
|
filename: filename.to_string(),
|
||||||
|
accepted: false,
|
||||||
|
code: Some(code.to_string()),
|
||||||
|
summary: None,
|
||||||
|
artifact_id: None,
|
||||||
|
csaf_provider: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An upload as the portal shows it, to the customer and to the supplier.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||||
|
pub struct UploadView {
|
||||||
|
/// Its id.
|
||||||
|
pub id: String,
|
||||||
|
/// When it arrived.
|
||||||
|
pub uploaded_at: DateTime<Utc>,
|
||||||
|
/// The file's name.
|
||||||
|
pub filename: String,
|
||||||
|
/// Whether it became the component's SBOM.
|
||||||
|
pub accepted: bool,
|
||||||
|
/// Why it was refused: `too_large`, `too_many_components`, `empty`,
|
||||||
|
/// `unknown_format`, `malformed` or `csaf_provider`.
|
||||||
|
pub code: Option<String>,
|
||||||
|
/// What an accepted SBOM holds.
|
||||||
|
pub summary: Option<SupplierSbomSummary>,
|
||||||
|
/// The CSAF provider given with it.
|
||||||
|
pub csaf_provider: Option<String>,
|
||||||
|
/// Whether it is the component's SBOM now (a later one replaces it).
|
||||||
|
pub current: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UploadView {
|
||||||
|
/// The view of `upload`; `current` is the target's SBOM artifact now.
|
||||||
|
fn of(upload: SupplierUpload, current: Option<&str>) -> Self {
|
||||||
|
Self {
|
||||||
|
current: upload.artifact_id.is_some() && upload.artifact_id.as_deref() == current,
|
||||||
|
id: upload.id.to_hex(),
|
||||||
|
uploaded_at: upload.uploaded_at.to_chrono(),
|
||||||
|
filename: upload.filename,
|
||||||
|
accepted: upload.accepted,
|
||||||
|
code: upload.code,
|
||||||
|
summary: upload.summary,
|
||||||
|
csaf_provider: upload.csaf_provider,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the supplier sees of its invite: the component, until when the link
|
||||||
|
/// is valid, and its uploads. Nothing else of the customer's.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||||
|
pub struct SupplierPage {
|
||||||
|
/// The component, by the customer's name for it.
|
||||||
|
pub component: String,
|
||||||
|
/// The supplier's name for the product, if the customer gave it.
|
||||||
|
pub product: Option<String>,
|
||||||
|
/// The version in use, if the customer gave it.
|
||||||
|
pub version: Option<String>,
|
||||||
|
/// Until when the link is valid.
|
||||||
|
pub expires_at: DateTime<Utc>,
|
||||||
|
/// The CSAF provider kept for the component.
|
||||||
|
pub csaf_provider: Option<String>,
|
||||||
|
/// Its uploads through this invite, newest first.
|
||||||
|
pub uploads: Vec<UploadView>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The body of an invite: which component, whom, and who invites.
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct CreateInvite {
|
||||||
|
/// The supplier component's target id.
|
||||||
|
pub target_id: String,
|
||||||
|
/// The supplier's e-mail address.
|
||||||
|
pub email: String,
|
||||||
|
/// The portal user who invites.
|
||||||
|
pub invited_by: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The body of a withdrawal.
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct WithdrawInvite {
|
||||||
|
/// The portal user who withdraws it.
|
||||||
|
pub withdrawn_by: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The query of the invite list: one target's, or all of them.
|
||||||
|
#[derive(Debug, Default, Deserialize)]
|
||||||
|
pub struct InviteFilter {
|
||||||
|
/// Only this target's invites.
|
||||||
|
#[serde(default)]
|
||||||
|
pub target: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `email` trimmed and in lower case, or `None` when it is not an address
|
||||||
|
/// with one `@` between a non-empty local part and a domain holding a dot.
|
||||||
|
fn normalized_email(email: &str) -> Option<String> {
|
||||||
|
let email = email.trim().to_lowercase();
|
||||||
|
let (local, domain) = email.split_once('@')?;
|
||||||
|
let plausible = !local.is_empty()
|
||||||
|
&& domain.contains('.')
|
||||||
|
&& !domain.starts_with('.')
|
||||||
|
&& !domain.ends_with('.')
|
||||||
|
&& !domain.contains('@')
|
||||||
|
&& email.len() <= MAX_EMAIL_LEN
|
||||||
|
&& !email.chars().any(|c| c.is_whitespace() || c.is_control());
|
||||||
|
plausible.then_some(email)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `actor` trimmed, or `None` when it is empty or too long.
|
||||||
|
fn normalized_actor(actor: &str) -> Option<String> {
|
||||||
|
let actor = actor.trim();
|
||||||
|
(!actor.is_empty() && actor.len() <= MAX_ACTOR_LEN).then(|| actor.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn invites(db: &Database) -> mongodb::Collection<SupplierInvite> {
|
||||||
|
db.inner().collection(SupplierInvite::COLLECTION)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn uploads(db: &Database) -> mongodb::Collection<SupplierUpload> {
|
||||||
|
db.inner().collection(SupplierUpload::COLLECTION)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The id of `target`'s supplier SBOM now, if it has one.
|
||||||
|
fn current_sbom(target: &OnboardedTarget) -> Option<&str> {
|
||||||
|
target
|
||||||
|
.artifacts
|
||||||
|
.iter()
|
||||||
|
.find(|a| a.kind == ArtifactKind::SupplierSbom)
|
||||||
|
.map(|a| a.id.as_str())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `listed` as the portal reads them at `now`, each with its uploads.
|
||||||
|
async fn views(
|
||||||
|
db: &Database,
|
||||||
|
listed: Vec<SupplierInvite>,
|
||||||
|
now: DateTime<Utc>,
|
||||||
|
) -> Result<Vec<InviteView>, StatusCode> {
|
||||||
|
let ids: Vec<String> = listed.iter().map(|i| i.id.to_hex()).collect();
|
||||||
|
let mut by_invite: HashMap<String, Vec<SupplierUpload>> = HashMap::new();
|
||||||
|
let mut cursor = uploads(db)
|
||||||
|
.find(doc! { "invite_id": { "$in": &ids } })
|
||||||
|
.sort(doc! { "uploaded_at": -1, "_id": -1 })
|
||||||
|
.await
|
||||||
|
.map_err(internal)?;
|
||||||
|
while let Some(upload) = cursor.try_next().await.map_err(internal)? {
|
||||||
|
by_invite
|
||||||
|
.entry(upload.invite_id.clone())
|
||||||
|
.or_default()
|
||||||
|
.push(upload);
|
||||||
|
}
|
||||||
|
let target_ids: Vec<ObjectId> = listed
|
||||||
|
.iter()
|
||||||
|
.filter_map(|i| ObjectId::parse_str(&i.target_id).ok())
|
||||||
|
.collect();
|
||||||
|
let targets: Vec<OnboardedTarget> = db
|
||||||
|
.onboarded_targets()
|
||||||
|
.find(doc! { "_id": { "$in": target_ids } })
|
||||||
|
.await
|
||||||
|
.map_err(internal)?
|
||||||
|
.try_collect()
|
||||||
|
.await
|
||||||
|
.map_err(internal)?;
|
||||||
|
let current: HashMap<String, String> = targets
|
||||||
|
.iter()
|
||||||
|
.filter_map(|t| Some((t.id?.to_hex(), current_sbom(t)?.to_string())))
|
||||||
|
.collect();
|
||||||
|
Ok(listed
|
||||||
|
.into_iter()
|
||||||
|
.map(|invite| {
|
||||||
|
let sbom = current.get(&invite.target_id).map(String::as_str);
|
||||||
|
let uploads = by_invite
|
||||||
|
.remove(&invite.id.to_hex())
|
||||||
|
.unwrap_or_default()
|
||||||
|
.into_iter()
|
||||||
|
.map(|u| UploadView::of(u, sbom))
|
||||||
|
.collect();
|
||||||
|
InviteView::of(invite, now, uploads)
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The invite `invite_id` of the tenant behind `db` while it allows uploads.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// 404 when there is no such invite; 410 with the code `expired` or
|
||||||
|
/// `withdrawn` when it no longer allows anything.
|
||||||
|
async fn open_invite(db: &Database, invite_id: &str) -> Result<SupplierInvite, UploadRefusal> {
|
||||||
|
let id = ObjectId::parse_str(invite_id.trim()).map_err(|_| StatusCode::NOT_FOUND)?;
|
||||||
|
let invite = invites(db)
|
||||||
|
.find_one(doc! { "_id": id })
|
||||||
|
.await
|
||||||
|
.map_err(internal)?
|
||||||
|
.ok_or(StatusCode::NOT_FOUND)?;
|
||||||
|
match invite.state(Utc::now()) {
|
||||||
|
InviteState::Active => Ok(invite),
|
||||||
|
InviteState::Expired => Err(closed("expired")),
|
||||||
|
InviteState::Withdrawn => Err(closed("withdrawn")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 410: the invite allows nothing more.
|
||||||
|
fn closed(code: &'static str) -> UploadRefusal {
|
||||||
|
UploadRefusal::because(StatusCode::GONE, "the invite is no longer valid", code)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the tenant may change its data now: not when the registry has it
|
||||||
|
/// read-only, halted or archived. Without a registry (dev) it may.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// 403 with the code `read_only` when it may not; 503 when the registry
|
||||||
|
/// cannot answer (access is never widened on doubt).
|
||||||
|
async fn accepts_writes(agent: &ComplianceAgent, tenant_id: &str) -> Result<(), UploadRefusal> {
|
||||||
|
let Some(registry) = agent.registry.as_ref() else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
let check = registry
|
||||||
|
.check_entitlement(tenant_id, None, None)
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
tracing::error!(tenant_id, "entitlement check unavailable: {e}");
|
||||||
|
StatusCode::SERVICE_UNAVAILABLE
|
||||||
|
})?;
|
||||||
|
// A status it does not name or Prüfwerk does not know limits nothing, as
|
||||||
|
// for a person's request (`require_entitlement`).
|
||||||
|
let status = check
|
||||||
|
.status
|
||||||
|
.as_deref()
|
||||||
|
.and_then(compliance_core::TenantStatus::parse);
|
||||||
|
let writable = check.allowed
|
||||||
|
&& !check.read_only
|
||||||
|
&& status.is_none_or(|s| !s.blocks_writes() && !s.is_halted() && !s.is_archived());
|
||||||
|
if writable {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(UploadRefusal::because(
|
||||||
|
StatusCode::FORBIDDEN,
|
||||||
|
"the workspace takes no uploads now",
|
||||||
|
"read_only",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The name an upload is shown by: the last part of `name`, at most
|
||||||
|
/// [`MAX_FILENAME_CHARS`] long.
|
||||||
|
fn shown_filename(name: &str) -> String {
|
||||||
|
let base = name.rsplit(['/', '\\']).next().unwrap_or(name).trim();
|
||||||
|
let base = if base.is_empty() { "sbom" } else { base };
|
||||||
|
base.chars().take(MAX_FILENAME_CHARS).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn internal<E: std::fmt::Display>(e: E) -> StatusCode {
|
||||||
|
tracing::error!("supplier invite endpoint failed: {e}");
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `POST /api/v1/platform/tenants/{id}/supplier-invites`: invite a supplier
|
||||||
|
/// to upload the SBOM of one supplier component. Answers 201 with the
|
||||||
|
/// invite, whose `id` the portal keys its secret link by.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// 404 when the tenant has no such target; 422 when the target is not a
|
||||||
|
/// supplier component, or the address or the inviting user is not usable.
|
||||||
|
pub async fn create_invite(
|
||||||
|
State(st): State<PlatformState>,
|
||||||
|
Path(tenant_id): Path<String>,
|
||||||
|
Json(body): Json<CreateInvite>,
|
||||||
|
) -> Result<(StatusCode, Json<InviteView>), StatusCode> {
|
||||||
|
let target = ObjectId::parse_str(body.target_id.trim()).map_err(|_| StatusCode::NOT_FOUND)?;
|
||||||
|
// Looked up without creating anything: an unknown tenant just has no target.
|
||||||
|
let lookup = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
|
||||||
|
let stored = lookup
|
||||||
|
.onboarded_targets()
|
||||||
|
.find_one(doc! { "_id": target })
|
||||||
|
.await
|
||||||
|
.map_err(internal)?
|
||||||
|
.ok_or(StatusCode::NOT_FOUND)?;
|
||||||
|
if stored.supplier.is_none() {
|
||||||
|
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
}
|
||||||
|
let (Some(email), Some(invited_by)) = (
|
||||||
|
normalized_email(&body.email),
|
||||||
|
normalized_actor(&body.invited_by),
|
||||||
|
) else {
|
||||||
|
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
};
|
||||||
|
let now = Utc::now();
|
||||||
|
let invite = SupplierInvite::new(target.to_hex(), email, invited_by, now);
|
||||||
|
let db = st
|
||||||
|
.agent
|
||||||
|
.db_pool
|
||||||
|
.for_tenant_id(&tenant_id)
|
||||||
|
.await
|
||||||
|
.map_err(internal)?;
|
||||||
|
invites(&db).insert_one(&invite).await.map_err(internal)?;
|
||||||
|
Ok((
|
||||||
|
StatusCode::CREATED,
|
||||||
|
Json(InviteView::of(invite, now, Vec::new())),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `GET /api/v1/platform/tenants/{id}/supplier-invites[?target=<id>]`: the
|
||||||
|
/// tenant's invites, newest first, each with its state.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// 500 when the database cannot be read.
|
||||||
|
pub async fn list_invites(
|
||||||
|
State(st): State<PlatformState>,
|
||||||
|
Path(tenant_id): Path<String>,
|
||||||
|
Query(filter): Query<InviteFilter>,
|
||||||
|
) -> Result<Json<Vec<InviteView>>, StatusCode> {
|
||||||
|
let db = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
|
||||||
|
let query = match filter.target.as_deref().map(str::trim) {
|
||||||
|
Some(target) if !target.is_empty() => doc! { "target_id": target },
|
||||||
|
_ => doc! {},
|
||||||
|
};
|
||||||
|
let now = Utc::now();
|
||||||
|
let listed: Vec<SupplierInvite> = invites(&db)
|
||||||
|
.find(query)
|
||||||
|
.sort(doc! { "created_at": -1, "_id": -1 })
|
||||||
|
.await
|
||||||
|
.map_err(internal)?
|
||||||
|
.try_collect()
|
||||||
|
.await
|
||||||
|
.map_err(internal)?;
|
||||||
|
Ok(Json(views(&db, listed, now).await?))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `POST /api/v1/platform/tenants/{id}/supplier-invites/{invite}/withdraw`:
|
||||||
|
/// withdraw an invite, so its link allows nothing more. Withdrawing one
|
||||||
|
/// already withdrawn keeps the first withdrawal.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// 404 when the tenant has no such invite; 422 without a usable
|
||||||
|
/// `withdrawn_by`.
|
||||||
|
pub async fn withdraw_invite(
|
||||||
|
State(st): State<PlatformState>,
|
||||||
|
Path((tenant_id, invite_id)): Path<(String, String)>,
|
||||||
|
Json(body): Json<WithdrawInvite>,
|
||||||
|
) -> Result<Json<InviteView>, StatusCode> {
|
||||||
|
let id = ObjectId::parse_str(invite_id.trim()).map_err(|_| StatusCode::NOT_FOUND)?;
|
||||||
|
let by = normalized_actor(&body.withdrawn_by).ok_or(StatusCode::UNPROCESSABLE_ENTITY)?;
|
||||||
|
let db = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
|
||||||
|
let now = Utc::now();
|
||||||
|
// Only an invite not yet withdrawn is changed; either way it is read back.
|
||||||
|
invites(&db)
|
||||||
|
.update_one(
|
||||||
|
doc! { "_id": id, "withdrawn_at": null },
|
||||||
|
doc! { "$set": {
|
||||||
|
"withdrawn_at": BsonDateTime::from(now),
|
||||||
|
"withdrawn_by": by,
|
||||||
|
} },
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(internal)?;
|
||||||
|
let invite = invites(&db)
|
||||||
|
.find_one(doc! { "_id": id })
|
||||||
|
.await
|
||||||
|
.map_err(internal)?
|
||||||
|
.ok_or(StatusCode::NOT_FOUND)?;
|
||||||
|
let mut viewed = views(&db, vec![invite], now).await?;
|
||||||
|
viewed
|
||||||
|
.pop()
|
||||||
|
.map(Json)
|
||||||
|
.ok_or(StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `GET /api/v1/platform/tenants/{id}/supplier-invites/{invite}/supplier-view`:
|
||||||
|
/// what the supplier's upload page shows, while the invite is valid.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// 404 when there is no such invite, or its component is gone or no longer a
|
||||||
|
/// supplier component; 410 with the code `expired` or `withdrawn`.
|
||||||
|
pub async fn supplier_view(
|
||||||
|
State(st): State<PlatformState>,
|
||||||
|
Path((tenant_id, invite_id)): Path<(String, String)>,
|
||||||
|
) -> Result<Json<SupplierPage>, UploadRefusal> {
|
||||||
|
let db = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
|
||||||
|
let invite = open_invite(&db, &invite_id).await?;
|
||||||
|
let target = invite_target(&db, &invite).await?;
|
||||||
|
let sbom = current_sbom(&target).map(str::to_string);
|
||||||
|
let listed: Vec<UploadView> = uploads(&db)
|
||||||
|
.find(doc! { "invite_id": invite.id.to_hex() })
|
||||||
|
.sort(doc! { "uploaded_at": -1, "_id": -1 })
|
||||||
|
.await
|
||||||
|
.map_err(internal)?
|
||||||
|
.try_collect::<Vec<SupplierUpload>>()
|
||||||
|
.await
|
||||||
|
.map_err(internal)?
|
||||||
|
.into_iter()
|
||||||
|
.map(|u| UploadView::of(u, sbom.as_deref()))
|
||||||
|
.collect();
|
||||||
|
let (product, version, csaf_provider) = target
|
||||||
|
.supplier
|
||||||
|
.map(|s| (s.product, s.version, s.csaf_provider))
|
||||||
|
.unwrap_or_default();
|
||||||
|
Ok(Json(SupplierPage {
|
||||||
|
component: target.name,
|
||||||
|
product,
|
||||||
|
version,
|
||||||
|
expires_at: invite.expires_at.to_chrono(),
|
||||||
|
csaf_provider,
|
||||||
|
uploads: listed,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The component `invite` is for, while it is a supplier component.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// 404 when it is gone, or names no supplier any more (the customer removed
|
||||||
|
/// it in the target editor).
|
||||||
|
async fn invite_target(
|
||||||
|
db: &Database,
|
||||||
|
invite: &SupplierInvite,
|
||||||
|
) -> Result<OnboardedTarget, UploadRefusal> {
|
||||||
|
let id = ObjectId::parse_str(&invite.target_id).map_err(|_| StatusCode::NOT_FOUND)?;
|
||||||
|
Ok(db
|
||||||
|
.onboarded_targets()
|
||||||
|
.find_one(doc! { "_id": id, "supplier": { "$ne": null } })
|
||||||
|
.await
|
||||||
|
.map_err(internal)?
|
||||||
|
.ok_or(StatusCode::NOT_FOUND)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `POST /api/v1/platform/tenants/{id}/supplier-invites/{invite}/sboms`: the
|
||||||
|
/// supplier uploads an SBOM through its invite.
|
||||||
|
///
|
||||||
|
/// Multipart fields: `file` (exactly one) and, optionally, `csaf_provider`
|
||||||
|
/// (the supplier's `provider-metadata.json`, an https URL). An accepted SBOM
|
||||||
|
/// becomes the component's SBOM, replacing the one before, exactly as a
|
||||||
|
/// customer's upload does, and a scan starts. A CSAF provider given with it
|
||||||
|
/// becomes the component's when it has none yet. Every upload is recorded,
|
||||||
|
/// refused ones with their code; the answer is the record (201).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// - 404: no such invite, or its component is gone or no longer a supplier
|
||||||
|
/// component.
|
||||||
|
/// - 410 (`expired`, `withdrawn`): the invite allows nothing more.
|
||||||
|
/// - 403 (`read_only`): the workspace takes no uploads now; 503 when the
|
||||||
|
/// registry cannot say.
|
||||||
|
/// - 429 (`too_many_uploads`): [`MAX_UPLOADS_PER_DAY`] reached.
|
||||||
|
/// - 400: no file, or more than one.
|
||||||
|
/// - 413 (`too_large`) and 422 (`too_many_components`, `empty`,
|
||||||
|
/// `unknown_format`, `malformed`, `csaf_provider`): refused, and recorded.
|
||||||
|
pub async fn upload_through_invite(
|
||||||
|
State(st): State<PlatformState>,
|
||||||
|
Path((tenant_id, invite_id)): Path<(String, String)>,
|
||||||
|
mut multipart: Multipart,
|
||||||
|
) -> Result<(StatusCode, Json<UploadView>), UploadRefusal> {
|
||||||
|
// Nothing is created before the invite is known to be valid.
|
||||||
|
let lookup = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
|
||||||
|
let invite = open_invite(&lookup, &invite_id).await?;
|
||||||
|
accepts_writes(&st.agent, &tenant_id).await?;
|
||||||
|
let day_ago = BsonDateTime::from(Utc::now() - chrono::Duration::days(1));
|
||||||
|
let recent = uploads(&lookup)
|
||||||
|
.count_documents(
|
||||||
|
doc! { "invite_id": invite.id.to_hex(), "uploaded_at": { "$gte": day_ago } },
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(internal)?;
|
||||||
|
if recent >= MAX_UPLOADS_PER_DAY {
|
||||||
|
return Err(UploadRefusal::because(
|
||||||
|
StatusCode::TOO_MANY_REQUESTS,
|
||||||
|
"too many uploads through this invite today",
|
||||||
|
"too_many_uploads",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let target = invite_target(&lookup, &invite).await?;
|
||||||
|
let db = st
|
||||||
|
.agent
|
||||||
|
.db_pool
|
||||||
|
.for_tenant_id(&tenant_id)
|
||||||
|
.await
|
||||||
|
.map_err(internal)?;
|
||||||
|
|
||||||
|
let mut csaf_provider = None;
|
||||||
|
let mut filename = String::from("sbom");
|
||||||
|
let mut stored: Option<StoredUpload> = None;
|
||||||
|
while let Some(mut field) = multipart.next_field().await.map_err(|e| e.status())? {
|
||||||
|
match field.name().unwrap_or("") {
|
||||||
|
"csaf_provider" => {
|
||||||
|
let url = field.text().await.map_err(|e| e.status())?;
|
||||||
|
csaf_provider = Some(url.trim().to_string()).filter(|u| !u.is_empty());
|
||||||
|
}
|
||||||
|
"file" => {
|
||||||
|
if stored.is_some() {
|
||||||
|
return Err(StatusCode::BAD_REQUEST.into());
|
||||||
|
}
|
||||||
|
filename = shown_filename(field.file_name().unwrap_or_default());
|
||||||
|
let dest = crate::targets::upload_dest(&st.agent, &invite.target_id, &filename)
|
||||||
|
.map_err(internal)?;
|
||||||
|
let mut upload = StoredUpload::new(dest, filename.clone());
|
||||||
|
match stream_to_disk(&mut field, &upload.path, MAX_SBOM_BYTES).await {
|
||||||
|
Ok(size) => upload.size = size,
|
||||||
|
Err(StatusCode::PAYLOAD_TOO_LARGE) => {
|
||||||
|
let refusal = UploadRefusal::because(
|
||||||
|
StatusCode::PAYLOAD_TOO_LARGE,
|
||||||
|
"the SBOM is larger than 20 MiB",
|
||||||
|
"too_large",
|
||||||
|
);
|
||||||
|
return Err(refused(&db, &invite, &filename, refusal).await);
|
||||||
|
}
|
||||||
|
Err(status) => return Err(status.into()),
|
||||||
|
}
|
||||||
|
stored = Some(upload);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let upload = stored.ok_or(StatusCode::BAD_REQUEST)?;
|
||||||
|
if csaf_provider
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(|url| !is_https_url(url))
|
||||||
|
{
|
||||||
|
let refusal = UploadRefusal::because(
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
"the CSAF provider must be an https URL",
|
||||||
|
"csaf_provider",
|
||||||
|
);
|
||||||
|
return Err(refused(&db, &invite, &filename, refusal).await);
|
||||||
|
}
|
||||||
|
let attached = match attach_upload(&db, &target, ArtifactKind::SupplierSbom, None, upload).await
|
||||||
|
{
|
||||||
|
Ok(attached) => attached,
|
||||||
|
Err(refusal) => return Err(refused(&db, &invite, &filename, refusal).await),
|
||||||
|
};
|
||||||
|
// Only a component without one takes the supplier's provider: one the
|
||||||
|
// customer set stays. The upload keeps what the supplier gave either way.
|
||||||
|
let unset = target
|
||||||
|
.supplier
|
||||||
|
.clone()
|
||||||
|
.filter(|supplier| supplier.csaf_provider.is_none());
|
||||||
|
if let (Some(url), Some(mut supplier)) = (&csaf_provider, unset) {
|
||||||
|
supplier.csaf_provider = Some(url.clone());
|
||||||
|
let set = mongodb::bson::to_bson(&supplier).map_err(internal)?;
|
||||||
|
db.onboarded_targets()
|
||||||
|
.update_one(
|
||||||
|
doc! { "_id": target.id },
|
||||||
|
doc! { "$set": { "supplier": set } },
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(internal)?;
|
||||||
|
refresh_supplier_csaf(&st.agent, &tenant_id, Some(&supplier));
|
||||||
|
}
|
||||||
|
let record = SupplierUpload {
|
||||||
|
id: ObjectId::new(),
|
||||||
|
invite_id: invite.id.to_hex(),
|
||||||
|
target_id: invite.target_id.clone(),
|
||||||
|
uploaded_at: BsonDateTime::now(),
|
||||||
|
filename,
|
||||||
|
accepted: true,
|
||||||
|
code: None,
|
||||||
|
summary: attached.summary,
|
||||||
|
artifact_id: Some(attached.artifact_id.clone()),
|
||||||
|
csaf_provider,
|
||||||
|
};
|
||||||
|
uploads(&db).insert_one(&record).await.map_err(internal)?;
|
||||||
|
let (agent, target_id) = (st.agent.clone(), invite.target_id.clone());
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Err(e) = agent
|
||||||
|
.run_target_scan(&tenant_id, &target_id, ScanTrigger::NewContent)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
tracing::error!(target_id, "scan after a supplier upload failed: {e}");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let current = Some(attached.artifact_id.as_str());
|
||||||
|
Ok((StatusCode::CREATED, Json(UploadView::of(record, current))))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `POST /api/v1/platform/tenants/{id}/supplier-invites/{invite}/sboms/check`:
|
||||||
|
/// what the supplier's page shows of a file before it is uploaded, through a
|
||||||
|
/// valid invite: the same check as `POST /api/v1/supplier-sboms/check`.
|
||||||
|
/// Nothing is stored or recorded.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// 404 and 410 as for [`upload_through_invite`]; the check's own refusals.
|
||||||
|
pub async fn check_through_invite(
|
||||||
|
State(st): State<PlatformState>,
|
||||||
|
Path((tenant_id, invite_id)): Path<(String, String)>,
|
||||||
|
multipart: Multipart,
|
||||||
|
) -> Result<Json<super::ApiResponse<SupplierSbomSummary>>, UploadRefusal> {
|
||||||
|
let db = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
|
||||||
|
let invite = open_invite(&db, &invite_id).await?;
|
||||||
|
invite_target(&db, &invite).await?;
|
||||||
|
super::onboarding::check_supplier_sbom(multipart).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Record `refusal` of an upload of `filename` through `invite`, when it has a
|
||||||
|
/// code the supplier can act on, and hand it back. A failed record is logged:
|
||||||
|
/// the refusal stands either way.
|
||||||
|
async fn refused(
|
||||||
|
db: &Database,
|
||||||
|
invite: &SupplierInvite,
|
||||||
|
filename: &str,
|
||||||
|
refusal: UploadRefusal,
|
||||||
|
) -> UploadRefusal {
|
||||||
|
if let Some(code) = refusal.code() {
|
||||||
|
let record = SupplierUpload::refused(invite, filename, code);
|
||||||
|
if let Err(e) = uploads(db).insert_one(&record).await {
|
||||||
|
tracing::warn!(invite_id = %invite.id, "refused supplier upload not recorded: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
refusal
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn invite_at(now: DateTime<Utc>) -> SupplierInvite {
|
||||||
|
SupplierInvite::new("t1".into(), "a@b.example".into(), "u1".into(), now)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_invite_is_active_for_ninety_days() {
|
||||||
|
let now = Utc::now();
|
||||||
|
let invite = invite_at(now);
|
||||||
|
assert_eq!(
|
||||||
|
invite.expires_at.to_chrono() - invite.created_at.to_chrono(),
|
||||||
|
chrono::Duration::days(90)
|
||||||
|
);
|
||||||
|
assert_eq!(invite.state(now), InviteState::Active);
|
||||||
|
let last = now + chrono::Duration::days(90) - chrono::Duration::seconds(1);
|
||||||
|
assert_eq!(invite.state(last), InviteState::Active);
|
||||||
|
assert_eq!(
|
||||||
|
invite.state(now + chrono::Duration::days(90)),
|
||||||
|
InviteState::Expired
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_withdrawn_invite_stays_withdrawn_after_it_expires() {
|
||||||
|
let now = Utc::now();
|
||||||
|
let mut invite = invite_at(now);
|
||||||
|
invite.withdrawn_at = Some(now.into());
|
||||||
|
assert_eq!(invite.state(now), InviteState::Withdrawn);
|
||||||
|
assert_eq!(
|
||||||
|
invite.state(now + chrono::Duration::days(200)),
|
||||||
|
InviteState::Withdrawn
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_address_is_kept_in_lower_case_and_nonsense_is_refused() {
|
||||||
|
assert_eq!(
|
||||||
|
normalized_email(" SBOM@Antrieb.Example "),
|
||||||
|
Some("sbom@antrieb.example".into())
|
||||||
|
);
|
||||||
|
for bad in [
|
||||||
|
"",
|
||||||
|
"no-at.example",
|
||||||
|
"@antrieb.example",
|
||||||
|
"a@localhost",
|
||||||
|
"a@.example",
|
||||||
|
"a@example.",
|
||||||
|
"a@b@c.example",
|
||||||
|
"a b@c.example",
|
||||||
|
] {
|
||||||
|
assert_eq!(normalized_email(bad), None, "{bad}");
|
||||||
|
}
|
||||||
|
let long = format!("{}@b.example", "a".repeat(250));
|
||||||
|
assert_eq!(normalized_email(&long), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_upload_is_shown_by_its_file_name_only() {
|
||||||
|
assert_eq!(shown_filename("../../dr4.cdx.json"), "dr4.cdx.json");
|
||||||
|
assert_eq!(shown_filename("C:\\sbom\\dr4.json"), "dr4.json");
|
||||||
|
assert_eq!(shown_filename(" "), "sbom");
|
||||||
|
assert_eq!(shown_filename("dir/"), "sbom");
|
||||||
|
assert_eq!(shown_filename(&"ä".repeat(300)).chars().count(), 200);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_actor_is_required_and_bounded() {
|
||||||
|
assert_eq!(normalized_actor(" u-1 "), Some("u-1".into()));
|
||||||
|
assert_eq!(normalized_actor(" "), None);
|
||||||
|
assert_eq!(normalized_actor(&"u".repeat(201)), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_invite_round_trips_through_bson() {
|
||||||
|
let invite = invite_at(Utc::now());
|
||||||
|
let stored = mongodb::bson::to_document(&invite).expect("bson");
|
||||||
|
assert!(stored.get_datetime("expires_at").is_ok(), "a BSON date");
|
||||||
|
let back: SupplierInvite = mongodb::bson::from_document(stored).expect("back");
|
||||||
|
assert_eq!(back, invite);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,823 @@
|
|||||||
|
//! The supply chain (#1050, #1051): what a workspace's products are made of,
|
||||||
|
//! as a graph for the dashboard to draw.
|
||||||
|
//!
|
||||||
|
//! Suppliers deliver components (targets); components are part of assemblies
|
||||||
|
//! and products (the registry's product projects); assemblies are part of
|
||||||
|
//! products. A component can be part of several products, so the graph is a
|
||||||
|
//! DAG, not a tree. Every component and project carries its open CVEs.
|
||||||
|
|
||||||
|
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||||
|
|
||||||
|
use axum::extract::Extension;
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::Json;
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use mongodb::bson::{doc, oid::ObjectId};
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
use compliance_core::cve_groups::SeverityCounts;
|
||||||
|
use compliance_core::models::{
|
||||||
|
ArtifactKind, CveAlert, OnboardedTarget, Project, ProjectKind, ProjectLevel, TargetType,
|
||||||
|
};
|
||||||
|
use compliance_core::tenant_ctx::TenantCtx;
|
||||||
|
|
||||||
|
use super::dto::{collect_cursor_async, tenant_db, AgentExt};
|
||||||
|
use super::machine::{open_alerts, open_counts};
|
||||||
|
use super::offers::SbomOffer;
|
||||||
|
use super::projects::tenant_projects;
|
||||||
|
use super::supplier_invites::SupplierInvite;
|
||||||
|
use super::ApiResponse;
|
||||||
|
use crate::database::Database;
|
||||||
|
|
||||||
|
/// The supply chain: its nodes and the edges between them.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||||
|
pub struct SupplyChain {
|
||||||
|
/// Suppliers, then components, then projects.
|
||||||
|
pub nodes: Vec<ChainNode>,
|
||||||
|
/// From supplier to component, component to project, project to the
|
||||||
|
/// project above it.
|
||||||
|
pub edges: Vec<ChainEdge>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a node stands for.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum NodeKind {
|
||||||
|
/// A supplier, by the name a target gives it.
|
||||||
|
Supplier,
|
||||||
|
/// A component: one of the workspace's targets.
|
||||||
|
Target,
|
||||||
|
/// A product project: a family, product or assembly.
|
||||||
|
Project,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One node of the supply chain.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||||
|
pub struct ChainNode {
|
||||||
|
/// Stable across calls, for the arrangement to be kept by:
|
||||||
|
/// `supplier:<name>`, `target:<id>` or `project:<id>`.
|
||||||
|
pub key: String,
|
||||||
|
pub kind: NodeKind,
|
||||||
|
pub name: String,
|
||||||
|
/// A component's type.
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub target_type: Option<TargetType>,
|
||||||
|
/// A component bought in from a supplier, rather than the workspace's own.
|
||||||
|
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||||
|
pub bought: bool,
|
||||||
|
/// A project's place in the hierarchy.
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub level: Option<ProjectLevel>,
|
||||||
|
/// Open CVEs: a component's own; a project's, the sum over the distinct
|
||||||
|
/// components beneath it. None for a supplier.
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub open: Option<SeverityCounts>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What an edge means.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum EdgeKind {
|
||||||
|
/// A supplier delivers the component.
|
||||||
|
Supplies,
|
||||||
|
/// The component or project is part of the project.
|
||||||
|
PartOf,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How a supplier's SBOM reaches its component.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum DeliveryKind {
|
||||||
|
/// A connected supplier's release, accepted into the component (#1028):
|
||||||
|
/// each version it publishes arrives by itself.
|
||||||
|
Release,
|
||||||
|
/// The supplier uploads it through an active invite link (#1027).
|
||||||
|
Invite,
|
||||||
|
/// The release it came by has ended (the supplier ended it, or the
|
||||||
|
/// connection ended); the version last delivered stays.
|
||||||
|
ReleaseEnded,
|
||||||
|
/// Someone in the workspace uploaded it.
|
||||||
|
Upload,
|
||||||
|
/// No SBOM yet.
|
||||||
|
Missing,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A supplier's delivery to its component.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||||
|
pub struct Delivery {
|
||||||
|
pub how: DeliveryKind,
|
||||||
|
/// The version in use, as the workspace names it.
|
||||||
|
pub version: Option<String>,
|
||||||
|
/// When the current SBOM arrived.
|
||||||
|
pub at: Option<DateTime<Utc>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One edge of the supply chain, `from` and `to` by node key.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||||
|
pub struct ChainEdge {
|
||||||
|
pub from: String,
|
||||||
|
pub to: String,
|
||||||
|
pub kind: EdgeKind,
|
||||||
|
/// How the SBOM arrives, on a supplier's edge.
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub delivery: Option<Delivery>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn target_key(id: &str) -> String {
|
||||||
|
format!("target:{id}")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn project_key(id: &str) -> String {
|
||||||
|
format!("project:{id}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The supplier `target` names, trimmed; `None` for one of its own.
|
||||||
|
fn supplier_name(target: &OnboardedTarget) -> Option<&str> {
|
||||||
|
target
|
||||||
|
.supplier
|
||||||
|
.as_ref()
|
||||||
|
.map(|s| s.name.trim())
|
||||||
|
.filter(|name| !name.is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What brings a component's new versions by themselves, if anything does.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum Feed {
|
||||||
|
/// An accepted release of a connected supplier.
|
||||||
|
Release,
|
||||||
|
/// An active invite link.
|
||||||
|
Invite,
|
||||||
|
/// A release that delivered, then ended.
|
||||||
|
ReleaseEnded,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How `target`'s SBOM arrives from its supplier: by its `feed`, else as an
|
||||||
|
/// upload once there is one. An ended release names the SBOM it left.
|
||||||
|
fn delivery(target: &OnboardedTarget, feed: Option<Feed>) -> Delivery {
|
||||||
|
let sbom = target
|
||||||
|
.artifacts
|
||||||
|
.iter()
|
||||||
|
.filter(|a| a.kind == ArtifactKind::SupplierSbom)
|
||||||
|
.max_by_key(|a| a.ingested_at);
|
||||||
|
let how = match (feed, sbom) {
|
||||||
|
(Some(Feed::Release), _) => DeliveryKind::Release,
|
||||||
|
(Some(Feed::Invite), _) => DeliveryKind::Invite,
|
||||||
|
(Some(Feed::ReleaseEnded), Some(_)) => DeliveryKind::ReleaseEnded,
|
||||||
|
(_, Some(_)) => DeliveryKind::Upload,
|
||||||
|
(_, None) => DeliveryKind::Missing,
|
||||||
|
};
|
||||||
|
Delivery {
|
||||||
|
how,
|
||||||
|
version: target.supplier.as_ref().and_then(|s| s.version.clone()),
|
||||||
|
at: sbom.and_then(|a| a.ingested_at),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The supply chain of `targets` in `projects`.
|
||||||
|
///
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// * `targets` - the workspace's targets, not archived, in display order
|
||||||
|
/// * `projects` - its projects; topics are left out
|
||||||
|
/// * `open` - each target's open CVEs, by id
|
||||||
|
/// * `feeds` - what brings each target's new versions, by id, if anything
|
||||||
|
pub fn supply_chain(
|
||||||
|
targets: &[OnboardedTarget],
|
||||||
|
projects: &[Project],
|
||||||
|
open: &HashMap<String, SeverityCounts>,
|
||||||
|
feeds: &HashMap<String, Feed>,
|
||||||
|
) -> SupplyChain {
|
||||||
|
let products: Vec<&Project> = projects
|
||||||
|
.iter()
|
||||||
|
.filter(|p| p.kind == ProjectKind::Product)
|
||||||
|
.collect();
|
||||||
|
let known: HashSet<&str> = products.iter().map(|p| p.id.as_str()).collect();
|
||||||
|
let mut nodes = Vec::new();
|
||||||
|
let mut edges = Vec::new();
|
||||||
|
|
||||||
|
let mut suppliers = BTreeSet::new();
|
||||||
|
for t in targets {
|
||||||
|
if let Some(name) = supplier_name(t) {
|
||||||
|
suppliers.insert(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
nodes.extend(suppliers.into_iter().map(|name| ChainNode {
|
||||||
|
key: format!("supplier:{name}"),
|
||||||
|
kind: NodeKind::Supplier,
|
||||||
|
name: name.to_string(),
|
||||||
|
target_type: None,
|
||||||
|
bought: false,
|
||||||
|
level: None,
|
||||||
|
open: None,
|
||||||
|
}));
|
||||||
|
|
||||||
|
// The targets directly in each project, by id.
|
||||||
|
let mut direct: HashMap<&str, Vec<String>> = HashMap::new();
|
||||||
|
for t in targets {
|
||||||
|
let Some(id) = t.id.map(|o: ObjectId| o.to_hex()) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let key = target_key(&id);
|
||||||
|
if let Some(name) = supplier_name(t) {
|
||||||
|
edges.push(ChainEdge {
|
||||||
|
from: format!("supplier:{name}"),
|
||||||
|
to: key.clone(),
|
||||||
|
kind: EdgeKind::Supplies,
|
||||||
|
delivery: Some(delivery(t, feeds.get(&id).copied())),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for project in t.project_ids.iter().filter(|p| known.contains(p.as_str())) {
|
||||||
|
edges.push(ChainEdge {
|
||||||
|
from: key.clone(),
|
||||||
|
to: project_key(project),
|
||||||
|
kind: EdgeKind::PartOf,
|
||||||
|
delivery: None,
|
||||||
|
});
|
||||||
|
direct.entry(project.as_str()).or_default().push(id.clone());
|
||||||
|
}
|
||||||
|
nodes.push(ChainNode {
|
||||||
|
key,
|
||||||
|
kind: NodeKind::Target,
|
||||||
|
name: t.name.clone(),
|
||||||
|
target_type: Some(t.target_type),
|
||||||
|
bought: t.supplier.is_some(),
|
||||||
|
level: None,
|
||||||
|
open: Some(open.get(&id).copied().unwrap_or_default()),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Each project's children: the projects whose parent it is.
|
||||||
|
let mut children: HashMap<&str, Vec<&str>> = HashMap::new();
|
||||||
|
for p in &products {
|
||||||
|
if let Some(parent) = p
|
||||||
|
.parent_id
|
||||||
|
.as_deref()
|
||||||
|
.filter(|id| known.contains(id) && *id != p.id)
|
||||||
|
{
|
||||||
|
children.entry(parent).or_default().push(&p.id);
|
||||||
|
edges.push(ChainEdge {
|
||||||
|
from: project_key(&p.id),
|
||||||
|
to: project_key(parent),
|
||||||
|
kind: EdgeKind::PartOf,
|
||||||
|
delivery: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for p in &products {
|
||||||
|
// Every target beneath the project, once, however it is reached.
|
||||||
|
let mut seen: HashSet<&str> = HashSet::new();
|
||||||
|
let mut beneath: HashSet<&String> = HashSet::new();
|
||||||
|
let mut queue = vec![p.id.as_str()];
|
||||||
|
while let Some(cur) = queue.pop() {
|
||||||
|
if !seen.insert(cur) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
beneath.extend(direct.get(cur).into_iter().flatten());
|
||||||
|
queue.extend(children.get(cur).into_iter().flatten().copied());
|
||||||
|
}
|
||||||
|
let sum = beneath
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|id| open.get(id))
|
||||||
|
.fold(SeverityCounts::default(), |sum, c| sum.plus(*c));
|
||||||
|
nodes.push(ChainNode {
|
||||||
|
key: project_key(&p.id),
|
||||||
|
kind: NodeKind::Project,
|
||||||
|
name: p.name.clone(),
|
||||||
|
target_type: None,
|
||||||
|
bought: false,
|
||||||
|
level: Some(p.level.unwrap_or(ProjectLevel::Product)),
|
||||||
|
open: Some(sum),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
SupplyChain { nodes, edges }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A document of a product's box: one of the store's documents of the
|
||||||
|
/// product, opened in the portal.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||||
|
pub struct BoxDocument {
|
||||||
|
/// The store's id of the document.
|
||||||
|
pub id: String,
|
||||||
|
pub title: String,
|
||||||
|
pub filename: String,
|
||||||
|
pub content_type: Option<String>,
|
||||||
|
pub size_bytes: Option<u64>,
|
||||||
|
/// Internal to the workspace rather than published with the product.
|
||||||
|
pub internal: bool,
|
||||||
|
pub created_at: Option<DateTime<Utc>>,
|
||||||
|
/// Where the portal shows it, below the portal's address.
|
||||||
|
pub path: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a product's box shows besides its graph (#1054): the project's
|
||||||
|
/// description and its documents in the portal's Dokumentenablage.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||||
|
pub struct ProjectDocuments {
|
||||||
|
/// The project's description, as the portal keeps it.
|
||||||
|
pub description: String,
|
||||||
|
/// Its documents, newest first.
|
||||||
|
pub documents: Vec<BoxDocument>,
|
||||||
|
/// Where the portal's store is, below the portal's address, for adding
|
||||||
|
/// one; empty without a registry.
|
||||||
|
pub store_path: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The documents of `store` that belong to product project `project`, newest
|
||||||
|
/// first, with where the portal of workspace `slug` shows each. Legal web
|
||||||
|
/// documents and BreakPilot's deliveries belong to no product.
|
||||||
|
fn box_documents(
|
||||||
|
store: Vec<crate::registry::StoreDocument>,
|
||||||
|
project: &str,
|
||||||
|
slug: &str,
|
||||||
|
) -> Vec<BoxDocument> {
|
||||||
|
let slug = urlencoding::encode(slug);
|
||||||
|
let mut documents: Vec<BoxDocument> = store
|
||||||
|
.into_iter()
|
||||||
|
.filter(|d| d.project_ids.iter().any(|p| p == project))
|
||||||
|
.filter_map(|d| {
|
||||||
|
let internal = match d.area.as_deref() {
|
||||||
|
Some("product_public") => false,
|
||||||
|
Some("internal") => true,
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
Some(BoxDocument {
|
||||||
|
path: format!("/{slug}/dokumente/{}/original", urlencoding::encode(&d.id)),
|
||||||
|
id: d.id,
|
||||||
|
title: d.title,
|
||||||
|
filename: d.filename,
|
||||||
|
content_type: d.content_type,
|
||||||
|
size_bytes: d.size_bytes,
|
||||||
|
internal,
|
||||||
|
created_at: d.created_at,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
documents.sort_by_key(|d| std::cmp::Reverse(d.created_at));
|
||||||
|
documents
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A product's description and documents, for its box on the Lieferkette.
|
||||||
|
///
|
||||||
|
/// The description is the project's, and the documents are those of the
|
||||||
|
/// portal's Dokumentenablage that belong to the project (published with the
|
||||||
|
/// product or internal), newest first. Each names where the portal shows it.
|
||||||
|
/// Prüfwerk keeps no copy. Without a registry (development) there is
|
||||||
|
/// nothing to show.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/supply-chain/projects/{id}/documents",
|
||||||
|
tag = "Targets",
|
||||||
|
params(("id" = String, Path, description = "The product project's id")),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "Its description and documents (`data`)"),
|
||||||
|
(status = 404, description = "No product project of the workspace"),
|
||||||
|
(status = 503, description = "The registry cannot be asked"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
|
#[tracing::instrument(skip_all, fields(project_id = %id))]
|
||||||
|
pub async fn project_documents(
|
||||||
|
Extension(agent): AgentExt,
|
||||||
|
tenant: TenantCtx,
|
||||||
|
axum::extract::Path(id): axum::extract::Path<String>,
|
||||||
|
) -> Result<Json<ApiResponse<ProjectDocuments>>, StatusCode> {
|
||||||
|
let Some(registry) = agent.registry.as_ref() else {
|
||||||
|
return Ok(Json(ApiResponse {
|
||||||
|
data: ProjectDocuments {
|
||||||
|
description: String::new(),
|
||||||
|
documents: Vec::new(),
|
||||||
|
store_path: String::new(),
|
||||||
|
},
|
||||||
|
total: None,
|
||||||
|
page: None,
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
let ctx = &tenant.0;
|
||||||
|
let project = tenant_projects(&agent, &ctx.tenant_id)
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.find(|p| p.id == id && p.kind == ProjectKind::Product)
|
||||||
|
.ok_or(StatusCode::NOT_FOUND)?;
|
||||||
|
let store = registry.list_store(&ctx.tenant_id).await.map_err(|e| {
|
||||||
|
tracing::error!(tenant_id = %ctx.tenant_id, "store list unavailable: {e}");
|
||||||
|
StatusCode::SERVICE_UNAVAILABLE
|
||||||
|
})?;
|
||||||
|
Ok(Json(ApiResponse {
|
||||||
|
data: ProjectDocuments {
|
||||||
|
description: project.description,
|
||||||
|
documents: box_documents(store, &id, &ctx.tenant_slug),
|
||||||
|
store_path: format!("/{}/dokumente", urlencoding::encode(&ctx.tenant_slug)),
|
||||||
|
},
|
||||||
|
total: None,
|
||||||
|
page: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Without a registry (development), every project a target names, as a
|
||||||
|
/// product named by its id, as the machine page names it.
|
||||||
|
fn unregistered_projects(targets: &[OnboardedTarget]) -> Vec<Project> {
|
||||||
|
targets
|
||||||
|
.iter()
|
||||||
|
.flat_map(|t| t.project_ids.iter())
|
||||||
|
.collect::<BTreeSet<_>>()
|
||||||
|
.into_iter()
|
||||||
|
.map(|id| Project {
|
||||||
|
id: id.clone(),
|
||||||
|
name: id.clone(),
|
||||||
|
kind: ProjectKind::Product,
|
||||||
|
description: String::new(),
|
||||||
|
level: None,
|
||||||
|
parent_id: None,
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The targets among `ids` with a supplier invite that is neither withdrawn
|
||||||
|
/// nor expired.
|
||||||
|
async fn invited_targets(db: &Database, ids: &[String]) -> Result<HashSet<String>, StatusCode> {
|
||||||
|
let found = db
|
||||||
|
.inner()
|
||||||
|
.collection::<SupplierInvite>(SupplierInvite::COLLECTION)
|
||||||
|
.distinct(
|
||||||
|
"target_id",
|
||||||
|
doc! {
|
||||||
|
"target_id": { "$in": ids },
|
||||||
|
"withdrawn_at": null,
|
||||||
|
"expires_at": { "$gt": mongodb::bson::DateTime::now() },
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
Ok(found
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|id| id.as_str().map(str::to_string))
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The targets among `ids` that offers of connected suppliers deliver into,
|
||||||
|
/// in state `state`; for an ended one, only if it delivered a version.
|
||||||
|
async fn offered_targets(
|
||||||
|
db: &Database,
|
||||||
|
ids: &[String],
|
||||||
|
state: &str,
|
||||||
|
) -> Result<HashSet<String>, StatusCode> {
|
||||||
|
let mut filter = doc! { "target_id": { "$in": ids }, "state": state };
|
||||||
|
if state == "ended" {
|
||||||
|
filter.insert("delivered_label", doc! { "$ne": null });
|
||||||
|
}
|
||||||
|
let found = db
|
||||||
|
.inner()
|
||||||
|
.collection::<SbomOffer>(SbomOffer::COLLECTION)
|
||||||
|
.distinct("target_id", filter)
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
Ok(found
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|id| id.as_str().map(str::to_string))
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What brings each of the targets `ids` its new versions: an accepted
|
||||||
|
/// release before an invite link, and either before a release that ended.
|
||||||
|
async fn feeds(db: &Database, ids: &[String]) -> Result<HashMap<String, Feed>, StatusCode> {
|
||||||
|
let mut feeds = HashMap::new();
|
||||||
|
for (found, feed) in [
|
||||||
|
(offered_targets(db, ids, "ended").await?, Feed::ReleaseEnded),
|
||||||
|
(invited_targets(db, ids).await?, Feed::Invite),
|
||||||
|
(offered_targets(db, ids, "accepted").await?, Feed::Release),
|
||||||
|
] {
|
||||||
|
feeds.extend(found.into_iter().map(|id| (id, feed)));
|
||||||
|
}
|
||||||
|
Ok(feeds)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The workspace's supply chain.
|
||||||
|
///
|
||||||
|
/// Its suppliers, components (targets) and product projects (families,
|
||||||
|
/// products and assemblies) as nodes, and as edges: supplier to component,
|
||||||
|
/// with how its SBOM arrives; component to the projects it is part of;
|
||||||
|
/// project to the project above it. A component can be part of several
|
||||||
|
/// projects. Each component carries its open CVEs, each project the sum over
|
||||||
|
/// the distinct components beneath it. Archived targets and topic projects
|
||||||
|
/// are left out.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/supply-chain",
|
||||||
|
tag = "Targets",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The supply chain (`data`: `nodes` and `edges`)"),
|
||||||
|
(status = 503, description = "The registry cannot be asked"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
|
#[tracing::instrument(skip_all)]
|
||||||
|
pub async fn get_supply_chain(
|
||||||
|
Extension(agent): AgentExt,
|
||||||
|
tenant: TenantCtx,
|
||||||
|
) -> Result<Json<ApiResponse<SupplyChain>>, StatusCode> {
|
||||||
|
let db = tenant_db(&agent, &tenant).await?;
|
||||||
|
let targets: Vec<OnboardedTarget> = collect_cursor_async(
|
||||||
|
db.onboarded_targets()
|
||||||
|
.find(doc! { "archived_at": null })
|
||||||
|
.sort(doc! { "name": 1 })
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let projects = match agent.registry {
|
||||||
|
Some(_) => tenant_projects(&agent, &tenant.0.tenant_id).await?,
|
||||||
|
None => unregistered_projects(&targets),
|
||||||
|
};
|
||||||
|
let ids: Vec<String> = targets
|
||||||
|
.iter()
|
||||||
|
.filter_map(|t| t.id.map(|o: ObjectId| o.to_hex()))
|
||||||
|
.collect();
|
||||||
|
let alerts = open_alerts(&db, &ids).await?;
|
||||||
|
let mut by_target: HashMap<&str, Vec<&CveAlert>> = HashMap::new();
|
||||||
|
for alert in &alerts {
|
||||||
|
by_target
|
||||||
|
.entry(alert.repo_id.as_str())
|
||||||
|
.or_default()
|
||||||
|
.push(alert);
|
||||||
|
}
|
||||||
|
let open: HashMap<String, SeverityCounts> = by_target
|
||||||
|
.into_iter()
|
||||||
|
.map(|(id, alerts)| (id.to_string(), open_counts(alerts)))
|
||||||
|
.collect();
|
||||||
|
let feeds = feeds(&db, &ids).await?;
|
||||||
|
Ok(Json(ApiResponse {
|
||||||
|
data: supply_chain(&targets, &projects, &open, &feeds),
|
||||||
|
total: None,
|
||||||
|
page: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use compliance_core::models::{Artifact, SupplierComponent};
|
||||||
|
|
||||||
|
fn target(name: &str, supplier: Option<&str>, projects: &[&str]) -> OnboardedTarget {
|
||||||
|
let mut t = OnboardedTarget::new(name.into(), TargetType::FirmwareRtos);
|
||||||
|
t.id = Some(ObjectId::new());
|
||||||
|
t.supplier = supplier.map(|s| SupplierComponent {
|
||||||
|
name: format!(" {s} "),
|
||||||
|
product: None,
|
||||||
|
version: Some("1.4.0".into()),
|
||||||
|
csaf_provider: None,
|
||||||
|
});
|
||||||
|
t.project_ids = projects.iter().map(|p| p.to_string()).collect();
|
||||||
|
t
|
||||||
|
}
|
||||||
|
|
||||||
|
fn project(id: &str, level: ProjectLevel, parent: Option<&str>) -> Project {
|
||||||
|
Project {
|
||||||
|
id: id.into(),
|
||||||
|
name: format!("Projekt {id}"),
|
||||||
|
kind: ProjectKind::Product,
|
||||||
|
description: String::new(),
|
||||||
|
level: Some(level),
|
||||||
|
parent_id: parent.map(String::from),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn id(t: &OnboardedTarget) -> String {
|
||||||
|
t.id.unwrap().to_hex()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn counts(critical: usize, high: usize, medium: usize) -> SeverityCounts {
|
||||||
|
SeverityCounts {
|
||||||
|
critical,
|
||||||
|
high,
|
||||||
|
medium,
|
||||||
|
..SeverityCounts::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A drive and a sensor in an assembly of product p1; a panel and the
|
||||||
|
/// workspace's own PLC program shared by products p1 and p2.
|
||||||
|
fn machine() -> (Vec<OnboardedTarget>, Vec<Project>) {
|
||||||
|
let mut drive = target("Antrieb", Some("Antriebe GmbH"), &["c1"]);
|
||||||
|
let mut sbom = Artifact::supplier_sbom("drive.cdx.json");
|
||||||
|
sbom.ingested_at = Some(Utc::now());
|
||||||
|
drive.artifacts.push(sbom);
|
||||||
|
let sensor = target("Sensor", Some("Sensorik AG"), &["c1"]);
|
||||||
|
let panel = target("Panel", Some("Display KG"), &["p1", "p2", "t1", "gone"]);
|
||||||
|
let plc = target("Steuerung", None, &["p1", "p2"]);
|
||||||
|
let mut topic = project("t1", ProjectLevel::Product, None);
|
||||||
|
topic.kind = ProjectKind::Topic;
|
||||||
|
topic.level = None;
|
||||||
|
let projects = vec![
|
||||||
|
project("p1", ProjectLevel::Product, None),
|
||||||
|
project("p2", ProjectLevel::Product, None),
|
||||||
|
project("c1", ProjectLevel::Component, Some("p1")),
|
||||||
|
topic,
|
||||||
|
];
|
||||||
|
(vec![drive, sensor, panel, plc], projects)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn suppliers_deliver_their_components_and_say_how() {
|
||||||
|
let (targets, projects) = machine();
|
||||||
|
let feeds = HashMap::from([(id(&targets[1]), Feed::Invite)]);
|
||||||
|
|
||||||
|
let chain = supply_chain(&targets, &projects, &HashMap::new(), &feeds);
|
||||||
|
|
||||||
|
let suppliers: Vec<&str> = chain
|
||||||
|
.nodes
|
||||||
|
.iter()
|
||||||
|
.filter(|n| n.kind == NodeKind::Supplier)
|
||||||
|
.map(|n| n.key.as_str())
|
||||||
|
.collect();
|
||||||
|
assert_eq!(
|
||||||
|
suppliers,
|
||||||
|
[
|
||||||
|
"supplier:Antriebe GmbH",
|
||||||
|
"supplier:Display KG",
|
||||||
|
"supplier:Sensorik AG"
|
||||||
|
],
|
||||||
|
"named once each, trimmed"
|
||||||
|
);
|
||||||
|
let how = |target: &OnboardedTarget| {
|
||||||
|
chain
|
||||||
|
.edges
|
||||||
|
.iter()
|
||||||
|
.find(|e| e.kind == EdgeKind::Supplies && e.to == target_key(&id(target)))
|
||||||
|
.and_then(|e| e.delivery.clone())
|
||||||
|
.unwrap()
|
||||||
|
};
|
||||||
|
let drive = how(&targets[0]);
|
||||||
|
assert_eq!(drive.how, DeliveryKind::Upload);
|
||||||
|
assert_eq!(drive.version.as_deref(), Some("1.4.0"));
|
||||||
|
assert!(drive.at.is_some());
|
||||||
|
assert_eq!(how(&targets[1]).how, DeliveryKind::Invite);
|
||||||
|
assert_eq!(how(&targets[2]).how, DeliveryKind::Missing);
|
||||||
|
let plc = chain.nodes.iter().find(|n| n.name == "Steuerung").unwrap();
|
||||||
|
assert!(!plc.bought, "the workspace's own");
|
||||||
|
assert!(!chain
|
||||||
|
.edges
|
||||||
|
.iter()
|
||||||
|
.any(|e| e.to == plc.key && e.kind == EdgeKind::Supplies));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_release_delivers_by_itself_and_leaves_its_version_when_it_ends() {
|
||||||
|
let (targets, _) = machine();
|
||||||
|
let (drive, sensor) = (&targets[0], &targets[1]);
|
||||||
|
|
||||||
|
let live = delivery(drive, Some(Feed::Release));
|
||||||
|
assert_eq!(live.how, DeliveryKind::Release);
|
||||||
|
assert_eq!(live.version.as_deref(), Some("1.4.0"));
|
||||||
|
assert!(live.at.is_some(), "when the version arrived");
|
||||||
|
assert_eq!(
|
||||||
|
delivery(sensor, Some(Feed::Release)).how,
|
||||||
|
DeliveryKind::Release
|
||||||
|
);
|
||||||
|
|
||||||
|
let ended = delivery(drive, Some(Feed::ReleaseEnded));
|
||||||
|
assert_eq!(ended.how, DeliveryKind::ReleaseEnded);
|
||||||
|
assert_eq!(
|
||||||
|
ended.version.as_deref(),
|
||||||
|
Some("1.4.0"),
|
||||||
|
"the version that stays"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
delivery(sensor, Some(Feed::ReleaseEnded)).how,
|
||||||
|
DeliveryKind::Missing,
|
||||||
|
"an ended release that left no SBOM"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(DeliveryKind::ReleaseEnded).unwrap(),
|
||||||
|
"release_ended"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn components_are_part_of_products_and_assemblies_of_their_product() {
|
||||||
|
let (targets, projects) = machine();
|
||||||
|
let chain = supply_chain(&targets, &projects, &HashMap::new(), &HashMap::new());
|
||||||
|
|
||||||
|
let part_of: BTreeSet<(String, &str)> = chain
|
||||||
|
.edges
|
||||||
|
.iter()
|
||||||
|
.filter(|e| e.kind == EdgeKind::PartOf)
|
||||||
|
.map(|e| {
|
||||||
|
let from = chain
|
||||||
|
.nodes
|
||||||
|
.iter()
|
||||||
|
.find(|n| n.key == e.from)
|
||||||
|
.map(|n| n.name.clone())
|
||||||
|
.unwrap();
|
||||||
|
(from, e.to.as_str())
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let expected: BTreeSet<(String, &str)> = [
|
||||||
|
("Antrieb", "project:c1"),
|
||||||
|
("Sensor", "project:c1"),
|
||||||
|
("Projekt c1", "project:p1"),
|
||||||
|
("Panel", "project:p1"),
|
||||||
|
("Panel", "project:p2"),
|
||||||
|
("Steuerung", "project:p1"),
|
||||||
|
("Steuerung", "project:p2"),
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.map(|(a, b)| (a.to_string(), b))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(part_of, expected, "no topic, no unknown project");
|
||||||
|
assert!(!chain.nodes.iter().any(|n| n.key == "project:t1"));
|
||||||
|
let c1 = chain.nodes.iter().find(|n| n.key == "project:c1").unwrap();
|
||||||
|
assert_eq!(c1.level, Some(ProjectLevel::Component));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_project_counts_each_component_beneath_it_once() {
|
||||||
|
let (targets, projects) = machine();
|
||||||
|
let open = HashMap::from([
|
||||||
|
(id(&targets[0]), counts(1, 0, 0)),
|
||||||
|
(id(&targets[1]), counts(0, 2, 0)),
|
||||||
|
(id(&targets[2]), counts(0, 0, 1)),
|
||||||
|
]);
|
||||||
|
|
||||||
|
let chain = supply_chain(&targets, &projects, &open, &HashMap::new());
|
||||||
|
|
||||||
|
let open_of = |key: &str| {
|
||||||
|
chain
|
||||||
|
.nodes
|
||||||
|
.iter()
|
||||||
|
.find(|n| n.key == key)
|
||||||
|
.and_then(|n| n.open)
|
||||||
|
.unwrap()
|
||||||
|
};
|
||||||
|
assert_eq!(open_of("project:c1"), counts(1, 2, 0));
|
||||||
|
// The assembly's parts and the shared panel; the PLC has none.
|
||||||
|
assert_eq!(open_of("project:p1"), counts(1, 2, 1));
|
||||||
|
assert_eq!(open_of("project:p2"), counts(0, 0, 1));
|
||||||
|
assert_eq!(
|
||||||
|
open_of(&target_key(&id(&targets[3]))),
|
||||||
|
SeverityCounts::default()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_cycle_of_parents_ends() {
|
||||||
|
let targets = vec![target("Teil", None, &["a"])];
|
||||||
|
let projects = vec![
|
||||||
|
project("a", ProjectLevel::Component, Some("b")),
|
||||||
|
project("b", ProjectLevel::Component, Some("a")),
|
||||||
|
];
|
||||||
|
let open = HashMap::from([(id(&targets[0]), counts(0, 1, 0))]);
|
||||||
|
let chain = supply_chain(&targets, &projects, &open, &HashMap::new());
|
||||||
|
let b = chain.nodes.iter().find(|n| n.key == "project:b").unwrap();
|
||||||
|
assert_eq!(b.open, Some(counts(0, 1, 0)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_box_shows_the_documents_of_its_product_newest_first() {
|
||||||
|
use crate::registry::StoreDocument;
|
||||||
|
let doc = |id: &str, area: Option<&str>, projects: &[&str], day: u32| StoreDocument {
|
||||||
|
id: id.into(),
|
||||||
|
title: format!("Doc {id}"),
|
||||||
|
filename: format!("{id}.pdf"),
|
||||||
|
content_type: Some("application/pdf".into()),
|
||||||
|
size_bytes: Some(1024),
|
||||||
|
area: area.map(String::from),
|
||||||
|
project_ids: projects.iter().map(|p| p.to_string()).collect(),
|
||||||
|
created_at: chrono::NaiveDate::from_ymd_opt(2026, 11, day)
|
||||||
|
.and_then(|d| d.and_hms_opt(9, 0, 0))
|
||||||
|
.map(|d| d.and_utc()),
|
||||||
|
};
|
||||||
|
let store = vec![
|
||||||
|
doc("manual", Some("product_public"), &["p1"], 10),
|
||||||
|
doc("notes", Some("internal"), &["p1", "p2"], 12),
|
||||||
|
doc("other", Some("product_public"), &["p2"], 11),
|
||||||
|
doc("imprint", Some("legal_web"), &["p1"], 13),
|
||||||
|
doc("delivery", None, &["p1"], 14),
|
||||||
|
];
|
||||||
|
|
||||||
|
let shown = box_documents(store, "p1", "beispiel maschinenbau");
|
||||||
|
|
||||||
|
let ids: Vec<(&str, bool)> = shown.iter().map(|d| (d.id.as_str(), d.internal)).collect();
|
||||||
|
assert_eq!(
|
||||||
|
ids,
|
||||||
|
[("notes", true), ("manual", false)],
|
||||||
|
"newest first, its own only"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
shown[1].path,
|
||||||
|
"/beispiel%20maschinenbau/dokumente/manual/original"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn without_a_registry_projects_are_named_by_their_id() {
|
||||||
|
let targets = vec![
|
||||||
|
target("Teil", None, &["m1", "m2"]),
|
||||||
|
target("Ander", None, &["m1"]),
|
||||||
|
];
|
||||||
|
let projects = unregistered_projects(&targets);
|
||||||
|
let ids: Vec<&str> = projects.iter().map(|p| p.name.as_str()).collect();
|
||||||
|
assert_eq!(ids, ["m1", "m2"]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -41,8 +41,20 @@ fn picker_order(mut tenants: Vec<SupportTenant>) -> Vec<SupportTenant> {
|
|||||||
tenants
|
tenants
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /api/v1/support/tenants — every tenant, for support to choose from.
|
/// Every tenant, for Breakpilot support to choose from.
|
||||||
|
///
|
||||||
/// 403 for anyone but support; 503 without a registry.
|
/// 403 for anyone but support; 503 without a registry.
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/api/v1/support/tenants",
|
||||||
|
tag = "Support",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The tenants"),
|
||||||
|
(status = 403, description = "Not support"),
|
||||||
|
(status = 503, description = "No registry"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn list_tenants(
|
pub async fn list_tenants(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -60,9 +72,20 @@ pub async fn list_tenants(
|
|||||||
Ok(Json(serde_json::json!({ "data": tenants })))
|
Ok(Json(serde_json::json!({ "data": tenants })))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /api/v1/support/session — open the tenant named in the header. The
|
/// Open the tenant named in the `X-Pruefwerk-Tenant` header for support.
|
||||||
/// middleware has confirmed it with the registry and records the opening in
|
///
|
||||||
/// the audit log; this answers what was opened. 403 for anyone but support.
|
/// The middleware has confirmed it with the registry and records the opening
|
||||||
|
/// in the audit log; this answers what was opened. 403 for anyone but support.
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
path = "/api/v1/support/session",
|
||||||
|
tag = "Support",
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "The opened tenant"),
|
||||||
|
(status = 403, description = "Not support"),
|
||||||
|
(status = 401, description = "No valid bearer token"),
|
||||||
|
)
|
||||||
|
)]
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn open_session(tenant: TenantCtx) -> Result<Json<serde_json::Value>, StatusCode> {
|
pub async fn open_session(tenant: TenantCtx) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||||
if tenant.0.staff.is_none() {
|
if tenant.0.staff.is_none() {
|
||||||
|
|||||||
@@ -21,13 +21,19 @@ const TOKEN_METHOD: &str = "token";
|
|||||||
|
|
||||||
/// A client-supplied artifact spec. The server builds the [`Artifact`] (and its
|
/// A client-supplied artifact spec. The server builds the [`Artifact`] (and its
|
||||||
/// id) from it, so clients never set internal fields.
|
/// id) from it, so clients never set internal fields.
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||||
pub struct ArtifactInput {
|
pub struct ArtifactInput {
|
||||||
|
/// What the artifact is, such as `git_repo`, `source_archive` or `plc_project`.
|
||||||
|
#[schema(value_type = String, example = "git_repo")]
|
||||||
pub kind: ArtifactKind,
|
pub kind: ArtifactKind,
|
||||||
|
/// Where it is: a clone URL, or a reference to an uploaded file.
|
||||||
pub source_ref: String,
|
pub source_ref: String,
|
||||||
|
/// The branch of a git repository.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub branch: Option<String>,
|
pub branch: Option<String>,
|
||||||
|
/// The PLC project's format, for a PLC project.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
#[schema(value_type = Option<String>, example = "plcopen_xml")]
|
||||||
pub plc_format: Option<PlcFormat>,
|
pub plc_format: Option<PlcFormat>,
|
||||||
/// A git access token for a private repository (#303). Sent: stored
|
/// A git access token for a private repository (#303). Sent: stored
|
||||||
/// sealed. Sent empty: removed. Left out: the stored one is kept.
|
/// sealed. Sent empty: removed. Left out: the stored one is kept.
|
||||||
@@ -129,14 +135,27 @@ pub fn merge_artifacts(
|
|||||||
|
|
||||||
/// A change to a target's scan config. A field left out keeps its stored
|
/// A change to a target's scan config. A field left out keeps its stored
|
||||||
/// value: enabling a scan must not remove the issue tracker (#304).
|
/// value: enabling a scan must not remove the issue tracker (#304).
|
||||||
#[derive(Debug, Default, Deserialize)]
|
#[derive(Debug, Default, Deserialize, utoipa::ToSchema)]
|
||||||
pub struct ScanConfigUpdate {
|
pub struct ScanConfigUpdate {
|
||||||
|
/// The scans to run, such as `sast`, `sbom` or `cve`.
|
||||||
|
#[schema(value_type = Option<Vec<String>>)]
|
||||||
pub enabled_scans: Option<Vec<ScanType>>,
|
pub enabled_scans: Option<Vec<ScanType>>,
|
||||||
|
/// The scans not to run.
|
||||||
|
#[schema(value_type = Option<Vec<String>>)]
|
||||||
pub disabled_scans: Option<Vec<ScanType>>,
|
pub disabled_scans: Option<Vec<ScanType>>,
|
||||||
|
/// `development`, `staging` or `production`.
|
||||||
|
#[schema(value_type = Option<String>, example = "staging")]
|
||||||
pub environment: Option<Environment>,
|
pub environment: Option<Environment>,
|
||||||
|
/// Whether dynamic tests may change data.
|
||||||
pub allow_destructive: Option<bool>,
|
pub allow_destructive: Option<bool>,
|
||||||
|
/// The pentest strategy: `quick`, `comprehensive`, `targeted` or `aggressive`.
|
||||||
|
#[schema(value_type = Option<String>)]
|
||||||
pub strategy: Option<PentestStrategy>,
|
pub strategy: Option<PentestStrategy>,
|
||||||
|
/// The pentest's scope and login.
|
||||||
|
#[schema(value_type = Option<Object>)]
|
||||||
pub pentest: Option<PentestConfig>,
|
pub pentest: Option<PentestConfig>,
|
||||||
|
/// Where findings are filed as issues.
|
||||||
|
#[schema(value_type = Option<Object>)]
|
||||||
pub issue_tracker: Option<IssueTrackerConfig>,
|
pub issue_tracker: Option<IssueTrackerConfig>,
|
||||||
/// Paths left out of every scan; replaces the stored list. Normalised
|
/// Paths left out of every scan; replaces the stored list. Normalised
|
||||||
/// while the request is read, so an invalid path is refused with its
|
/// while the request is read, so an invalid path is refused with its
|
||||||
|
|||||||
@@ -20,7 +20,8 @@ use super::dto::{collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResu
|
|||||||
use super::findings::Actor;
|
use super::findings::Actor;
|
||||||
|
|
||||||
/// GET /api/v1/targets/{id}/cves — the target's CVE alerts with their VEX
|
/// GET /api/v1/targets/{id}/cves — the target's CVE alerts with their VEX
|
||||||
/// statements, newest first.
|
/// statements, newest first. A `fixed` a scan inferred from a CVE no longer
|
||||||
|
/// being found is left out (#994).
|
||||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||||
pub async fn list_target_cves(
|
pub async fn list_target_cves(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -29,7 +30,8 @@ pub async fn list_target_cves(
|
|||||||
) -> ApiResult<Vec<CveAlert>> {
|
) -> ApiResult<Vec<CveAlert>> {
|
||||||
let db = tenant_db(&agent, &tenant).await?;
|
let db = tenant_db(&agent, &tenant).await?;
|
||||||
// An unreadable list reads as empty here, as it always has.
|
// An unreadable list reads as empty here, as it always has.
|
||||||
let alerts = target_alerts(&db, &id).await.unwrap_or_default();
|
let mut alerts = target_alerts(&db, &id).await.unwrap_or_default();
|
||||||
|
alerts.iter_mut().for_each(CveAlert::drop_inferred_fix);
|
||||||
Ok(Json(ApiResponse {
|
Ok(Json(ApiResponse {
|
||||||
total: Some(alerts.len() as u64),
|
total: Some(alerts.len() as u64),
|
||||||
data: alerts,
|
data: alerts,
|
||||||
@@ -253,7 +255,7 @@ async fn load_source(db: &crate::database::Database, id: &str) -> Result<VexSour
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The workspace's name, the author of its VEX statements.
|
/// The workspace's name, the author of its VEX statements.
|
||||||
fn author(tenant: &TenantCtx) -> String {
|
pub(super) fn author(tenant: &TenantCtx) -> String {
|
||||||
if tenant.0.tenant_slug.is_empty() {
|
if tenant.0.tenant_slug.is_empty() {
|
||||||
tenant.0.tenant_id.clone()
|
tenant.0.tenant_id.clone()
|
||||||
} else {
|
} else {
|
||||||
@@ -262,7 +264,10 @@ fn author(tenant: &TenantCtx) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// `body` as a JSON file named `filename` to download.
|
/// `body` as a JSON file named `filename` to download.
|
||||||
fn download(body: &serde_json::Value, filename: &str) -> Result<impl IntoResponse, StatusCode> {
|
pub(super) fn download(
|
||||||
|
body: &serde_json::Value,
|
||||||
|
filename: &str,
|
||||||
|
) -> Result<impl IntoResponse, StatusCode> {
|
||||||
let json = serde_json::to_string_pretty(body).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
let json = serde_json::to_string_pretty(body).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
let disposition = HeaderValue::from_str(&format!("attachment; filename=\"{filename}\""))
|
let disposition = HeaderValue::from_str(&format!("attachment; filename=\"{filename}\""))
|
||||||
.unwrap_or_else(|_| HeaderValue::from_static("attachment"));
|
.unwrap_or_else(|_| HeaderValue::from_static("attachment"));
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
pub mod api_key_gate;
|
pub mod api_key_gate;
|
||||||
pub mod handlers;
|
pub mod handlers;
|
||||||
|
pub mod openapi;
|
||||||
pub mod role_gate;
|
pub mod role_gate;
|
||||||
pub mod routes;
|
pub mod routes;
|
||||||
pub mod server;
|
pub mod server;
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
//! The OpenAPI description of the customer API (#1006).
|
||||||
|
//!
|
||||||
|
//! Generated from the handlers: a route registered through
|
||||||
|
//! [`utoipa_axum::routes!`] takes its path, method, parameters and body from
|
||||||
|
//! the handler's `#[utoipa::path]`, so the description cannot drift from the
|
||||||
|
//! route. The document is served at [`SPEC_PATH`], behind the same
|
||||||
|
//! authentication as the API, for integrators and for DAST, which seeds its
|
||||||
|
//! endpoints from it (#997).
|
||||||
|
|
||||||
|
use utoipa::openapi::security::{HttpAuthScheme, HttpBuilder, SecurityRequirement, SecurityScheme};
|
||||||
|
use utoipa::OpenApi;
|
||||||
|
|
||||||
|
/// Where the agent serves its OpenAPI document. Under the API prefix, so the
|
||||||
|
/// customer authentication covers it, and one of the paths DAST tries.
|
||||||
|
pub const SPEC_PATH: &str = "/api/v1/openapi.json";
|
||||||
|
|
||||||
|
/// The name of the bearer scheme in the document.
|
||||||
|
const BEARER: &str = "bearer";
|
||||||
|
|
||||||
|
/// The document's frame; the routes add their paths to it.
|
||||||
|
#[derive(OpenApi)]
|
||||||
|
#[openapi(info(
|
||||||
|
title = "Prüfwerk API",
|
||||||
|
description = "The customer API of the Prüfwerk agent. Every operation but the health \
|
||||||
|
check needs a Keycloak access token or an API key as a bearer token."
|
||||||
|
))]
|
||||||
|
pub struct ApiDoc;
|
||||||
|
|
||||||
|
/// `api` with the bearer scheme, required by every operation except the
|
||||||
|
/// public ones ([`compliance_core::auth::bypasses_customer_auth`]).
|
||||||
|
///
|
||||||
|
/// The scheme goes on each operation rather than once for the document: a
|
||||||
|
/// reader that only looks at operations (the DAST spec parser) still sees it.
|
||||||
|
///
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// * `api` - the document with every described route's path
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// The finished document.
|
||||||
|
pub fn with_bearer_auth(mut api: utoipa::openapi::OpenApi) -> utoipa::openapi::OpenApi {
|
||||||
|
api.components
|
||||||
|
.get_or_insert_with(Default::default)
|
||||||
|
.add_security_scheme(
|
||||||
|
BEARER,
|
||||||
|
SecurityScheme::Http(
|
||||||
|
HttpBuilder::new()
|
||||||
|
.scheme(HttpAuthScheme::Bearer)
|
||||||
|
.description(Some("A Keycloak access token or an API key"))
|
||||||
|
.build(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
for (path, item) in api.paths.paths.iter_mut() {
|
||||||
|
if compliance_core::auth::bypasses_customer_auth(path) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let operations = [
|
||||||
|
&mut item.get,
|
||||||
|
&mut item.put,
|
||||||
|
&mut item.post,
|
||||||
|
&mut item.delete,
|
||||||
|
&mut item.options,
|
||||||
|
&mut item.head,
|
||||||
|
&mut item.patch,
|
||||||
|
&mut item.trace,
|
||||||
|
];
|
||||||
|
for operation in operations.into_iter().flatten() {
|
||||||
|
operation.security = Some(vec![SecurityRequirement::new(BEARER, Vec::<String>::new())]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
api
|
||||||
|
}
|
||||||
@@ -2,12 +2,13 @@
|
|||||||
//!
|
//!
|
||||||
//! One middleware for every tenant-scoped route, so no handler can forget it:
|
//! One middleware for every tenant-scoped route, so no handler can forget it:
|
||||||
//!
|
//!
|
||||||
//! * `IT_ADMIN`, `USER` — read and write.
|
//! * `OWNER`, `IT_ADMIN`, `USER`, `PSIRT`, `DEVELOPMENT` — read and write.
|
||||||
//! * `CXO`, `LEGAL` — read only: `GET` / `HEAD` / `OPTIONS`, plus the few
|
//! * `CXO`, `LEGAL`, `QUALITY`, `PURCHASING`, `AUDITOR` — read only: `GET` / `HEAD` / `OPTIONS`, plus the few
|
||||||
//! `POST` routes that only read ([`READ_ONLY_POSTS`]). `LEGAL` also
|
//! `POST` routes that only read ([`READ_ONLY_POSTS`]). `LEGAL` also
|
||||||
//! decides about licences: the licence policy and the legal review
|
//! decides about licences: the licence policy and the legal review
|
||||||
//! ([`ROLE_WRITES`], decided 2026-10-15).
|
//! ([`ROLE_WRITES`], decided 2026-10-15).
|
||||||
//! * `FINANCE`, or none of these roles — nothing; every request is refused.
|
//! * `FINANCE`, `PRIVACY`, `EXTERNAL`, or none of these roles — nothing;
|
||||||
|
//! every request is refused.
|
||||||
//!
|
//!
|
||||||
//! Refusals are `403 {"error": "forbidden_role", "access": "none" | "read_only"}`.
|
//! Refusals are `403 {"error": "forbidden_role", "access": "none" | "read_only"}`.
|
||||||
//!
|
//!
|
||||||
@@ -18,7 +19,8 @@
|
|||||||
//! Werkbank runner and admin APIs (their own token middleware), the health
|
//! Werkbank runner and admin APIs (their own token middleware), the health
|
||||||
//! check, and support staff who have not chosen a tenant yet.
|
//! check, and support staff who have not chosen a tenant yet.
|
||||||
//!
|
//!
|
||||||
//! Handlers may still be stricter (manual findings stay `IT_ADMIN`-only).
|
//! Handlers may still be stricter (manual findings stay for administrators:
|
||||||
|
//! `IT_ADMIN` and `OWNER`).
|
||||||
//!
|
//!
|
||||||
//! API keys (tenant-registry ADR 0001) hold no role. They reach only the
|
//! API keys (tenant-registry ADR 0001) hold no role. They reach only the
|
||||||
//! routes in [`KEY_SCOPES`], each with the scope it names; every other route
|
//! routes in [`KEY_SCOPES`], each with the scope it names; every other route
|
||||||
@@ -73,6 +75,12 @@ pub const KEY_SCOPES: &[(Method, &str, &str)] = &[
|
|||||||
(Method::GET, "/api/v1/licenses/policy", SBOM_READ),
|
(Method::GET, "/api/v1/licenses/policy", SBOM_READ),
|
||||||
(Method::GET, "/api/v1/scan-runs", SCANS_READ),
|
(Method::GET, "/api/v1/scan-runs", SCANS_READ),
|
||||||
(Method::POST, "/api/v1/targets/{id}/scan", SCANS_RUN),
|
(Method::POST, "/api/v1/targets/{id}/scan", SCANS_RUN),
|
||||||
|
// A TIA connector uploads its export (#1090) and starts a scan.
|
||||||
|
(
|
||||||
|
Method::POST,
|
||||||
|
"/api/v1/targets/{id}/artifacts/upload",
|
||||||
|
UPLOADS_WRITE,
|
||||||
|
),
|
||||||
(Method::POST, "/api/v1/dast/targets/{id}/scan", SCANS_RUN),
|
(Method::POST, "/api/v1/dast/targets/{id}/scan", SCANS_RUN),
|
||||||
(Method::GET, "/api/v1/targets/{id}/enisa", ENISA_READ),
|
(Method::GET, "/api/v1/targets/{id}/enisa", ENISA_READ),
|
||||||
(Method::GET, "/api/v1/cves/{id}/enisa", ENISA_READ),
|
(Method::GET, "/api/v1/cves/{id}/enisa", ENISA_READ),
|
||||||
@@ -83,6 +91,7 @@ const FINDINGS_WRITE: &str = "pruefwerk:findings.write";
|
|||||||
const SBOM_READ: &str = "pruefwerk:sbom.read";
|
const SBOM_READ: &str = "pruefwerk:sbom.read";
|
||||||
const SCANS_READ: &str = "pruefwerk:scans.read";
|
const SCANS_READ: &str = "pruefwerk:scans.read";
|
||||||
const SCANS_RUN: &str = "pruefwerk:scans.run";
|
const SCANS_RUN: &str = "pruefwerk:scans.run";
|
||||||
|
const UPLOADS_WRITE: &str = "pruefwerk:uploads.write";
|
||||||
const ENISA_READ: &str = "pruefwerk:enisa.read";
|
const ENISA_READ: &str = "pruefwerk:enisa.read";
|
||||||
|
|
||||||
/// What a legacy key (issued before scopes, no scopes of its own) may do:
|
/// What a legacy key (issued before scopes, no scopes of its own) may do:
|
||||||
|
|||||||
@@ -19,11 +19,19 @@ use tower::ServiceExt;
|
|||||||
/// Who is calling.
|
/// Who is calling.
|
||||||
#[derive(Debug, Clone, Copy)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
enum Caller {
|
enum Caller {
|
||||||
|
Owner,
|
||||||
ItAdmin,
|
ItAdmin,
|
||||||
User,
|
User,
|
||||||
Cxo,
|
Cxo,
|
||||||
Legal,
|
Legal,
|
||||||
Finance,
|
Finance,
|
||||||
|
Psirt,
|
||||||
|
Development,
|
||||||
|
Quality,
|
||||||
|
Purchasing,
|
||||||
|
Auditor,
|
||||||
|
Privacy,
|
||||||
|
External,
|
||||||
NoRoles,
|
NoRoles,
|
||||||
/// BreakPilot support in a customer's tenant (no org roles of its own).
|
/// BreakPilot support in a customer's tenant (no org roles of its own).
|
||||||
Staff,
|
Staff,
|
||||||
@@ -35,11 +43,19 @@ enum Caller {
|
|||||||
|
|
||||||
fn ctx(caller: Caller) -> Option<TenantContext> {
|
fn ctx(caller: Caller) -> Option<TenantContext> {
|
||||||
let roles = match caller {
|
let roles = match caller {
|
||||||
|
Caller::Owner => vec![OrgRole::Owner],
|
||||||
Caller::ItAdmin => vec![OrgRole::ItAdmin],
|
Caller::ItAdmin => vec![OrgRole::ItAdmin],
|
||||||
Caller::User => vec![OrgRole::User],
|
Caller::User => vec![OrgRole::User],
|
||||||
Caller::Cxo => vec![OrgRole::Cxo],
|
Caller::Cxo => vec![OrgRole::Cxo],
|
||||||
Caller::Legal => vec![OrgRole::Legal],
|
Caller::Legal => vec![OrgRole::Legal],
|
||||||
Caller::Finance => vec![OrgRole::Finance],
|
Caller::Finance => vec![OrgRole::Finance],
|
||||||
|
Caller::Psirt => vec![OrgRole::Psirt],
|
||||||
|
Caller::Development => vec![OrgRole::Development],
|
||||||
|
Caller::Quality => vec![OrgRole::Quality],
|
||||||
|
Caller::Purchasing => vec![OrgRole::Purchasing],
|
||||||
|
Caller::Auditor => vec![OrgRole::Auditor],
|
||||||
|
Caller::Privacy => vec![OrgRole::Privacy],
|
||||||
|
Caller::External => vec![OrgRole::External],
|
||||||
Caller::NoRoles | Caller::Staff | Caller::Key(_) => vec![],
|
Caller::NoRoles | Caller::Staff | Caller::Key(_) => vec![],
|
||||||
Caller::Service => return None,
|
Caller::Service => return None,
|
||||||
};
|
};
|
||||||
@@ -196,11 +212,19 @@ fn routes() -> Vec<(Method, String, bool)> {
|
|||||||
async fn roles_decide_reads_and_writes() {
|
async fn roles_decide_reads_and_writes() {
|
||||||
// (caller, may read, may write)
|
// (caller, may read, may write)
|
||||||
let matrix = [
|
let matrix = [
|
||||||
|
(Caller::Owner, true, true),
|
||||||
(Caller::ItAdmin, true, true),
|
(Caller::ItAdmin, true, true),
|
||||||
(Caller::User, true, true),
|
(Caller::User, true, true),
|
||||||
(Caller::Cxo, true, false),
|
(Caller::Cxo, true, false),
|
||||||
(Caller::Legal, true, false),
|
(Caller::Legal, true, false),
|
||||||
(Caller::Finance, false, false),
|
(Caller::Finance, false, false),
|
||||||
|
(Caller::Psirt, true, true),
|
||||||
|
(Caller::Development, true, true),
|
||||||
|
(Caller::Quality, true, false),
|
||||||
|
(Caller::Purchasing, true, false),
|
||||||
|
(Caller::Auditor, true, false),
|
||||||
|
(Caller::Privacy, false, false),
|
||||||
|
(Caller::External, false, false),
|
||||||
(Caller::NoRoles, false, false),
|
(Caller::NoRoles, false, false),
|
||||||
(Caller::Staff, true, true),
|
(Caller::Staff, true, true),
|
||||||
(Caller::Service, true, true),
|
(Caller::Service, true, true),
|
||||||
@@ -317,6 +341,7 @@ const ALL_SCOPES: &[&str] = &[
|
|||||||
"pruefwerk:sbom.read",
|
"pruefwerk:sbom.read",
|
||||||
"pruefwerk:scans.read",
|
"pruefwerk:scans.read",
|
||||||
"pruefwerk:scans.run",
|
"pruefwerk:scans.run",
|
||||||
|
"pruefwerk:uploads.write",
|
||||||
"pruefwerk:enisa.read",
|
"pruefwerk:enisa.read",
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
+343
-304
@@ -1,130 +1,147 @@
|
|||||||
use axum::extract::DefaultBodyLimit;
|
use axum::extract::DefaultBodyLimit;
|
||||||
use axum::routing::{delete, get, patch, post, put};
|
use axum::http::header::CONTENT_TYPE;
|
||||||
|
use axum::routing::{get, patch};
|
||||||
use axum::Router;
|
use axum::Router;
|
||||||
|
use utoipa::OpenApi;
|
||||||
|
use utoipa_axum::router::{OpenApiRouter, UtoipaMethodRouterExt};
|
||||||
|
use utoipa_axum::routes;
|
||||||
|
|
||||||
use crate::api::handlers;
|
use crate::api::{handlers, openapi};
|
||||||
|
|
||||||
/// Allowance on top of the file itself for the multipart framing: boundaries,
|
/// Allowance on top of the file itself for the multipart framing: boundaries,
|
||||||
/// part headers and the small `kind` / `plc_format` text fields.
|
/// part headers and the small `kind` / `plc_format` text fields.
|
||||||
const MULTIPART_OVERHEAD: usize = 1024 * 1024;
|
pub(crate) const MULTIPART_OVERHEAD: usize = 1024 * 1024;
|
||||||
|
|
||||||
|
/// The customer API, with its OpenAPI description at [`openapi::SPEC_PATH`]
|
||||||
|
/// (#1006).
|
||||||
|
///
|
||||||
|
/// A route registered with `.routes(routes!(…))` is described by its
|
||||||
|
/// handler's `#[utoipa::path]`. The plain route calls are the routes not
|
||||||
|
/// described yet; a test keeps them listed in `UNDESCRIBED`, so a new route
|
||||||
|
/// cannot be added without its description.
|
||||||
pub fn build_router() -> Router {
|
pub fn build_router() -> Router {
|
||||||
Router::new()
|
let (router, api) = described_routes().split_for_parts();
|
||||||
.route("/api/v1/health", get(handlers::health))
|
let spec = std::sync::Arc::<str>::from(
|
||||||
.route("/api/v1/oscal/assess", post(handlers::oscal::assess_target))
|
openapi::with_bearer_auth(api)
|
||||||
.route("/api/v1/stats/overview", get(handlers::stats_overview))
|
.to_json()
|
||||||
|
.unwrap_or_else(|e| {
|
||||||
|
tracing::error!("OpenAPI description not built: {e}");
|
||||||
|
"{}".to_string()
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
router.route(
|
||||||
|
openapi::SPEC_PATH,
|
||||||
|
get(move || {
|
||||||
|
let spec = spec.clone();
|
||||||
|
async move { ([(CONTENT_TYPE, "application/json")], spec.to_string()) }
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn described_routes() -> OpenApiRouter {
|
||||||
|
OpenApiRouter::with_openapi(openapi::ApiDoc::openapi())
|
||||||
|
.routes(routes!(handlers::health))
|
||||||
|
.routes(routes!(handlers::oscal::assess_target))
|
||||||
|
.routes(routes!(handlers::stats_overview))
|
||||||
// The tenant's projects (owned by the registry), for assigning targets.
|
// The tenant's projects (owned by the registry), for assigning targets.
|
||||||
.route("/api/v1/projects", get(handlers::projects::list_projects))
|
.routes(routes!(handlers::projects::list_projects))
|
||||||
.route("/api/v1/metering/usage", get(handlers::metering::get_usage))
|
// A machine: a product project and the targets it is made of (#1026).
|
||||||
|
.routes(routes!(handlers::machine::export_machine_sbom))
|
||||||
|
.routes(routes!(handlers::machine::machine_overview))
|
||||||
|
.routes(routes!(handlers::machine::machine_cves))
|
||||||
|
.routes(routes!(handlers::machine::machine_scan_changes))
|
||||||
|
.routes(routes!(handlers::supply_chain::get_supply_chain))
|
||||||
|
.routes(routes!(handlers::connections::list_connections))
|
||||||
|
// SBOM releases to connected workspaces, the supplier's side (#1028).
|
||||||
|
.routes(routes!(
|
||||||
|
handlers::releases::list_releases,
|
||||||
|
handlers::releases::create_release
|
||||||
|
))
|
||||||
|
.routes(routes!(handlers::releases::end_release))
|
||||||
|
.routes(routes!(handlers::releases::publish_version))
|
||||||
|
.routes(routes!(handlers::releases::preview_version))
|
||||||
|
.routes(routes!(handlers::releases::version_draft))
|
||||||
|
// What connected suppliers offer, the customer's side (#1028).
|
||||||
|
.routes(routes!(handlers::offers::list_offers))
|
||||||
|
.routes(routes!(handlers::offers::accept_offer))
|
||||||
|
.routes(routes!(handlers::offers::decline_offer))
|
||||||
|
.routes(routes!(handlers::supply_chain::project_documents))
|
||||||
|
// 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))
|
||||||
|
// 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
|
// Whether the caller may use Prüfwerk at all: answered by the
|
||||||
// authentication and entitlement layers in front of it (a blocked
|
// authentication and entitlement layers in front of it (a blocked
|
||||||
// member gets 403 MEMBER_BLOCKED), for the dashboard's sign-in check.
|
// member gets 403 MEMBER_BLOCKED), for the dashboard's sign-in check.
|
||||||
.route("/api/v1/access", get(handlers::health::access))
|
.routes(routes!(handlers::health::access))
|
||||||
// The managed git source, read-only (IT admin and support).
|
// The managed git source, read-only (IT admin and support).
|
||||||
.route(
|
.routes(routes!(handlers::git_source::get_git_source))
|
||||||
"/api/v1/git-source",
|
|
||||||
get(handlers::git_source::get_git_source),
|
|
||||||
)
|
|
||||||
// BreakPilot support access: choose and open a customer's tenant.
|
// BreakPilot support access: choose and open a customer's tenant.
|
||||||
.route(
|
.routes(routes!(handlers::support::list_tenants))
|
||||||
"/api/v1/support/tenants",
|
.routes(routes!(handlers::support::open_session))
|
||||||
get(handlers::support::list_tenants),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/support/session",
|
|
||||||
post(handlers::support::open_session),
|
|
||||||
)
|
|
||||||
// Unified onboarding targets (#131).
|
// Unified onboarding targets (#131).
|
||||||
.route(
|
.routes(routes!(
|
||||||
"/api/v1/targets",
|
handlers::onboarding::list_targets,
|
||||||
get(handlers::onboarding::list_targets).post(handlers::onboarding::create_target),
|
handlers::onboarding::create_target
|
||||||
)
|
))
|
||||||
// Curated demo targets (D3). Registered before "/targets/{id}" for
|
// Curated demo targets (D3).
|
||||||
// readability; the router matches the literal segment first either way.
|
.routes(routes!(
|
||||||
.route(
|
handlers::demo_seed::list_demo_targets,
|
||||||
"/api/v1/targets/demo-seed",
|
handlers::demo_seed::seed_demo_targets
|
||||||
get(handlers::demo_seed::list_demo_targets)
|
))
|
||||||
.post(handlers::demo_seed::seed_demo_targets),
|
.routes(routes!(
|
||||||
)
|
handlers::onboarding::get_target,
|
||||||
.route(
|
handlers::onboarding::update_target,
|
||||||
"/api/v1/targets/{id}",
|
handlers::onboarding::delete_target
|
||||||
get(handlers::onboarding::get_target)
|
))
|
||||||
.patch(handlers::onboarding::update_target)
|
.routes(routes!(handlers::onboarding::add_artifact))
|
||||||
.delete(handlers::onboarding::delete_target),
|
// A target's Siemens controllers against Siemens' advisories (SPS 4a).
|
||||||
)
|
.routes(routes!(handlers::devices::list_devices))
|
||||||
.route(
|
.routes(routes!(handlers::devices::lookup_device))
|
||||||
"/api/v1/targets/{id}/artifacts",
|
.routes(routes!(handlers::onboarding::list_webhook_deliveries))
|
||||||
post(handlers::onboarding::add_artifact),
|
// The one route that takes large bodies — and it streams them to
|
||||||
)
|
// disk. Every other route keeps axum's 2 MiB default, so a JSON
|
||||||
.route(
|
// endpoint can no longer be sent a 512 MiB body to buffer.
|
||||||
"/api/v1/targets/{id}/webhook-deliveries",
|
.routes(
|
||||||
get(handlers::onboarding::list_webhook_deliveries),
|
routes!(handlers::onboarding::upload_artifact).layer(DefaultBodyLimit::max(
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/targets/{id}/artifacts/upload",
|
|
||||||
// The one route that takes large bodies — and it streams them to
|
|
||||||
// disk. Every other route keeps axum's 2 MiB default, so a JSON
|
|
||||||
// endpoint can no longer be sent a 512 MiB body to buffer.
|
|
||||||
post(handlers::onboarding::upload_artifact).layer(DefaultBodyLimit::max(
|
|
||||||
crate::targets::MAX_UPLOAD_BYTES as usize + MULTIPART_OVERHEAD,
|
crate::targets::MAX_UPLOAD_BYTES as usize + MULTIPART_OVERHEAD,
|
||||||
)),
|
)),
|
||||||
)
|
)
|
||||||
.route(
|
// A supplier SBOM is checked when the wizard adds it, before any
|
||||||
"/api/v1/targets/{id}/artifacts/{artifact_id}/archive-password",
|
// target holds it: up to its own size limit, never kept.
|
||||||
put(handlers::onboarding::set_archive_password),
|
.routes(
|
||||||
)
|
routes!(handlers::onboarding::check_supplier_sbom).layer(DefaultBodyLimit::max(
|
||||||
.route(
|
crate::pipeline::sbom::supplied::MAX_BYTES as usize + MULTIPART_OVERHEAD,
|
||||||
"/api/v1/targets/{id}/applicable-scans",
|
)),
|
||||||
get(handlers::onboarding::applicable_scans_for_target),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/targets/{id}/detect",
|
|
||||||
post(handlers::onboarding::detect_target),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/targets/{id}/scan",
|
|
||||||
post(handlers::onboarding::trigger_target_scan),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/targets/{id}/billing/swap",
|
|
||||||
post(handlers::onboarding::swap_target_billing),
|
|
||||||
)
|
|
||||||
.route("/api/v1/findings", get(handlers::list_findings))
|
|
||||||
.route(
|
|
||||||
"/api/v1/findings/variants",
|
|
||||||
get(handlers::list_finding_variants),
|
|
||||||
)
|
|
||||||
.route("/api/v1/findings/{id}", get(handlers::get_finding))
|
|
||||||
.route(
|
|
||||||
"/api/v1/findings/{id}/status",
|
|
||||||
patch(handlers::update_finding_status),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/findings/bulk-status",
|
|
||||||
patch(handlers::bulk_update_finding_status),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/findings/{id}/feedback",
|
|
||||||
patch(handlers::update_finding_feedback),
|
|
||||||
)
|
)
|
||||||
|
.routes(routes!(handlers::supplier::get_supplier_advisories))
|
||||||
|
.routes(routes!(handlers::onboarding::set_archive_password))
|
||||||
|
.routes(routes!(handlers::onboarding::applicable_scans_for_target))
|
||||||
|
.routes(routes!(handlers::onboarding::detect_target))
|
||||||
|
.routes(routes!(handlers::onboarding::trigger_target_scan))
|
||||||
|
.routes(routes!(handlers::onboarding::swap_target_billing))
|
||||||
|
.routes(routes!(handlers::list_findings))
|
||||||
|
.routes(routes!(handlers::list_finding_variants))
|
||||||
|
.routes(routes!(handlers::get_finding))
|
||||||
|
.routes(routes!(handlers::update_finding_status))
|
||||||
|
.routes(routes!(handlers::bulk_update_finding_status))
|
||||||
|
.routes(routes!(handlers::update_finding_feedback))
|
||||||
// Undecided findings grouped by rule and file; one decision per group (#951).
|
// Undecided findings grouped by rule and file; one decision per group (#951).
|
||||||
.route(
|
.routes(routes!(handlers::finding_groups::list_finding_groups))
|
||||||
"/api/v1/finding-groups",
|
.routes(routes!(handlers::finding_groups::decide_finding_group))
|
||||||
get(handlers::finding_groups::list_finding_groups),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/finding-groups/decide",
|
|
||||||
post(handlers::finding_groups::decide_finding_group),
|
|
||||||
)
|
|
||||||
// The "Heute" inbox (#950): open decisions in urgency buckets.
|
// The "Heute" inbox (#950): open decisions in urgency buckets.
|
||||||
.route("/api/v1/inbox", get(handlers::inbox::get_inbox))
|
.routes(routes!(handlers::inbox::get_inbox))
|
||||||
.route("/api/v1/inbox/decide", post(handlers::inbox::decide))
|
.routes(routes!(handlers::inbox::decide))
|
||||||
.route("/api/v1/inbox/undo", post(handlers::inbox::undo))
|
.routes(routes!(handlers::inbox::undo))
|
||||||
.route("/api/v1/inbox/snooze", post(handlers::inbox::snooze))
|
.routes(routes!(handlers::inbox::snooze))
|
||||||
.route(
|
.routes(routes!(handlers::inbox::unsnooze))
|
||||||
"/api/v1/inbox/snooze/{key}",
|
|
||||||
delete(handlers::inbox::unsnooze),
|
|
||||||
)
|
|
||||||
// VEX on a target's CVE alerts (#498).
|
// VEX on a target's CVE alerts (#498).
|
||||||
.route(
|
.route(
|
||||||
"/api/v1/targets/{id}/cves",
|
"/api/v1/targets/{id}/cves",
|
||||||
@@ -167,218 +184,103 @@ pub fn build_router() -> Router {
|
|||||||
"/api/v1/targets/{id}/sbom-ecosystems",
|
"/api/v1/targets/{id}/sbom-ecosystems",
|
||||||
get(handlers::sbom_ecosystems::list_sbom_ecosystems),
|
get(handlers::sbom_ecosystems::list_sbom_ecosystems),
|
||||||
)
|
)
|
||||||
.route(
|
.routes(routes!(handlers::evidence::evidence_pack))
|
||||||
"/api/v1/targets/{id}/evidence-pack",
|
.routes(routes!(handlers::evidence::compliance_view))
|
||||||
get(handlers::evidence::evidence_pack),
|
.routes(routes!(handlers::finding_breakdown::finding_breakdown))
|
||||||
)
|
.routes(routes!(handlers::evidence::compliance_summary))
|
||||||
.route(
|
.routes(routes!(handlers::evidence::describe_controls))
|
||||||
"/api/v1/targets/{id}/compliance",
|
|
||||||
get(handlers::evidence::compliance_view),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/targets/{id}/finding-breakdown",
|
|
||||||
get(handlers::finding_breakdown::finding_breakdown),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/compliance/summary",
|
|
||||||
get(handlers::evidence::compliance_summary),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/controls",
|
|
||||||
get(handlers::evidence::describe_controls),
|
|
||||||
)
|
|
||||||
// Findings from a manual DAST run or penetration test.
|
// Findings from a manual DAST run or penetration test.
|
||||||
.route(
|
.routes(routes!(handlers::manual_findings::create_finding))
|
||||||
"/api/v1/targets/{id}/findings",
|
.routes(
|
||||||
post(handlers::manual_findings::create_finding),
|
routes!(handlers::manual_findings::import_findings).layer(DefaultBodyLimit::max(
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/targets/{id}/findings/import",
|
|
||||||
post(handlers::manual_findings::import_findings).layer(DefaultBodyLimit::max(
|
|
||||||
handlers::manual_findings::MAX_IMPORT_BYTES,
|
handlers::manual_findings::MAX_IMPORT_BYTES,
|
||||||
)),
|
)),
|
||||||
)
|
)
|
||||||
.route("/api/v1/sbom", get(handlers::list_sbom))
|
.routes(routes!(handlers::list_sbom))
|
||||||
.route("/api/v1/sbom/filters", get(handlers::sbom_filters))
|
.routes(routes!(handlers::sbom_filters))
|
||||||
.route("/api/v1/sbom/export", get(handlers::export_sbom))
|
.routes(routes!(handlers::export_sbom))
|
||||||
.route("/api/v1/sbom/licenses", get(handlers::license_summary))
|
.routes(routes!(handlers::license_summary))
|
||||||
.route("/api/v1/sbom/quality", get(handlers::sbom_quality))
|
.routes(routes!(handlers::sbom_quality))
|
||||||
.route("/api/v1/sbom/diff", get(handlers::sbom_diff))
|
.routes(routes!(handlers::sbom_diff))
|
||||||
// Licences the workspace confirms for its components.
|
// Licences the workspace confirms for its components.
|
||||||
.route(
|
.routes(routes!(
|
||||||
"/api/v1/licenses/conclusions",
|
handlers::licenses::list_conclusions,
|
||||||
get(handlers::licenses::list_conclusions)
|
handlers::licenses::conclude,
|
||||||
.put(handlers::licenses::conclude)
|
handlers::licenses::withdraw
|
||||||
.delete(handlers::licenses::withdraw),
|
))
|
||||||
)
|
|
||||||
// The licence policy, what it says about each component, and the
|
// The licence policy, what it says about each component, and the
|
||||||
// legal review that resolves what it asks a review for.
|
// legal review that resolves what it asks a review for.
|
||||||
.route(
|
.routes(routes!(
|
||||||
"/api/v1/licenses/policy",
|
handlers::licenses::get_policy,
|
||||||
get(handlers::licenses::get_policy).put(handlers::licenses::put_policy),
|
handlers::licenses::put_policy
|
||||||
)
|
))
|
||||||
.route("/api/v1/licenses/check", get(handlers::licenses::check))
|
.routes(routes!(handlers::licenses::check))
|
||||||
.route(
|
.routes(routes!(
|
||||||
"/api/v1/licenses/review",
|
handlers::licenses::review,
|
||||||
post(handlers::licenses::review).delete(handlers::licenses::withdraw_review),
|
handlers::licenses::withdraw_review
|
||||||
)
|
))
|
||||||
.route("/api/v1/sbom/notices", get(handlers::licenses::notices))
|
.routes(routes!(handlers::licenses::notices))
|
||||||
.route("/api/v1/issues", get(handlers::list_issues))
|
.routes(routes!(handlers::list_issues))
|
||||||
.route("/api/v1/scan-runs", get(handlers::list_scan_runs))
|
.routes(routes!(handlers::list_scan_runs))
|
||||||
// MCP token management (per-tenant API tokens for the MCP server)
|
// MCP token management (per-tenant API tokens for the MCP server)
|
||||||
.route(
|
.routes(routes!(
|
||||||
"/api/v1/mcp-servers",
|
handlers::mcp_servers::list_mcp_servers,
|
||||||
get(handlers::mcp_servers::list_mcp_servers)
|
handlers::mcp_servers::create_mcp_server
|
||||||
.post(handlers::mcp_servers::create_mcp_server),
|
))
|
||||||
)
|
.routes(routes!(handlers::mcp_servers::delete_mcp_server))
|
||||||
.route(
|
.routes(routes!(handlers::mcp_servers::regenerate_mcp_server_token))
|
||||||
"/api/v1/mcp-servers/{id}",
|
.routes(routes!(
|
||||||
delete(handlers::mcp_servers::delete_mcp_server),
|
handlers::mcp_tokens::list_mcp_tokens,
|
||||||
)
|
handlers::mcp_tokens::create_mcp_token
|
||||||
.route(
|
))
|
||||||
"/api/v1/mcp-servers/{id}/token",
|
.routes(routes!(handlers::mcp_tokens::revoke_mcp_token))
|
||||||
post(handlers::mcp_servers::regenerate_mcp_server_token),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/mcp-tokens",
|
|
||||||
get(handlers::mcp_tokens::list_mcp_tokens).post(handlers::mcp_tokens::create_mcp_token),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/mcp-tokens/{id}",
|
|
||||||
delete(handlers::mcp_tokens::revoke_mcp_token),
|
|
||||||
)
|
|
||||||
// Graph API endpoints
|
// Graph API endpoints
|
||||||
.route("/api/v1/graph/{repo_id}", get(handlers::graph::get_graph))
|
.routes(routes!(handlers::graph::get_graph))
|
||||||
.route(
|
.routes(routes!(handlers::graph::get_nodes))
|
||||||
"/api/v1/graph/{repo_id}/nodes",
|
.routes(routes!(handlers::graph::get_summary))
|
||||||
get(handlers::graph::get_nodes),
|
.routes(routes!(handlers::graph::get_communities))
|
||||||
)
|
.routes(routes!(handlers::graph::get_impact))
|
||||||
.route(
|
.routes(routes!(handlers::graph::search_symbols))
|
||||||
"/api/v1/graph/{repo_id}/summary",
|
.routes(routes!(handlers::graph::get_file_content))
|
||||||
get(handlers::graph::get_summary),
|
.routes(routes!(handlers::graph::trigger_build))
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/graph/{repo_id}/communities",
|
|
||||||
get(handlers::graph::get_communities),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/graph/{repo_id}/impact/{finding_id}",
|
|
||||||
get(handlers::graph::get_impact),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/graph/{repo_id}/search",
|
|
||||||
get(handlers::graph::search_symbols),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/graph/{repo_id}/file-content",
|
|
||||||
get(handlers::graph::get_file_content),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/graph/{repo_id}/build",
|
|
||||||
post(handlers::graph::trigger_build),
|
|
||||||
)
|
|
||||||
// DAST API endpoints
|
// DAST API endpoints
|
||||||
.route("/api/v1/dast/targets", get(handlers::dast::list_targets))
|
.routes(routes!(
|
||||||
.route("/api/v1/dast/targets", post(handlers::dast::add_target))
|
handlers::dast::list_targets,
|
||||||
.route(
|
handlers::dast::add_target
|
||||||
"/api/v1/dast/targets/{id}/scan",
|
))
|
||||||
post(handlers::dast::trigger_scan),
|
.routes(routes!(handlers::dast::trigger_scan))
|
||||||
)
|
.routes(routes!(handlers::dast::list_scan_runs))
|
||||||
.route(
|
.routes(routes!(handlers::dast::list_findings))
|
||||||
"/api/v1/dast/scan-runs",
|
.routes(routes!(handlers::dast::get_finding))
|
||||||
get(handlers::dast::list_scan_runs),
|
|
||||||
)
|
|
||||||
.route("/api/v1/dast/findings", get(handlers::dast::list_findings))
|
|
||||||
.route(
|
|
||||||
"/api/v1/dast/findings/{id}",
|
|
||||||
get(handlers::dast::get_finding),
|
|
||||||
)
|
|
||||||
// Chat / RAG API endpoints
|
// Chat / RAG API endpoints
|
||||||
.route("/api/v1/chat/{repo_id}", post(handlers::chat::chat))
|
.routes(routes!(handlers::chat::chat))
|
||||||
.route(
|
.routes(routes!(handlers::chat::build_embeddings))
|
||||||
"/api/v1/chat/{repo_id}/build-embeddings",
|
.routes(routes!(handlers::chat::embedding_status))
|
||||||
post(handlers::chat::build_embeddings),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/chat/{repo_id}/status",
|
|
||||||
get(handlers::chat::embedding_status),
|
|
||||||
)
|
|
||||||
// Help chat (documentation-grounded Q&A)
|
// Help chat (documentation-grounded Q&A)
|
||||||
.route("/api/v1/help/chat", post(handlers::help_chat::help_chat))
|
.routes(routes!(handlers::help_chat::help_chat))
|
||||||
// CVE notification endpoints
|
// CVE notification endpoints
|
||||||
.route(
|
.routes(routes!(handlers::notifications::list_notifications))
|
||||||
"/api/v1/notifications",
|
.routes(routes!(handlers::notifications::notification_count))
|
||||||
get(handlers::notifications::list_notifications),
|
.routes(routes!(handlers::notifications::mark_all_read))
|
||||||
)
|
.routes(routes!(handlers::notifications::mark_read))
|
||||||
.route(
|
.routes(routes!(handlers::notifications::dismiss_notification))
|
||||||
"/api/v1/notifications/count",
|
|
||||||
get(handlers::notifications::notification_count),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/notifications/read-all",
|
|
||||||
post(handlers::notifications::mark_all_read),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/notifications/{id}/read",
|
|
||||||
patch(handlers::notifications::mark_read),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/notifications/{id}/dismiss",
|
|
||||||
patch(handlers::notifications::dismiss_notification),
|
|
||||||
)
|
|
||||||
// Pentest API endpoints
|
// Pentest API endpoints
|
||||||
.route(
|
.routes(routes!(handlers::pentest::lookup_repo))
|
||||||
"/api/v1/pentest/lookup-repo",
|
.routes(routes!(
|
||||||
get(handlers::pentest::lookup_repo),
|
handlers::pentest::list_sessions,
|
||||||
)
|
handlers::pentest::create_session
|
||||||
.route(
|
))
|
||||||
"/api/v1/pentest/sessions",
|
.routes(routes!(handlers::pentest::get_session))
|
||||||
get(handlers::pentest::list_sessions).post(handlers::pentest::create_session),
|
.routes(routes!(handlers::pentest::send_message))
|
||||||
)
|
.routes(routes!(handlers::pentest::stop_session))
|
||||||
.route(
|
.routes(routes!(handlers::pentest::pause_session))
|
||||||
"/api/v1/pentest/sessions/{id}",
|
.routes(routes!(handlers::pentest::resume_session))
|
||||||
get(handlers::pentest::get_session),
|
.routes(routes!(handlers::pentest::session_stream))
|
||||||
)
|
.routes(routes!(handlers::pentest::get_attack_chain))
|
||||||
.route(
|
.routes(routes!(handlers::pentest::get_messages))
|
||||||
"/api/v1/pentest/sessions/{id}/chat",
|
.routes(routes!(handlers::pentest::get_session_findings))
|
||||||
post(handlers::pentest::send_message),
|
.routes(routes!(handlers::pentest::export_session_report))
|
||||||
)
|
.routes(routes!(handlers::pentest::pentest_stats))
|
||||||
.route(
|
|
||||||
"/api/v1/pentest/sessions/{id}/stop",
|
|
||||||
post(handlers::pentest::stop_session),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/pentest/sessions/{id}/pause",
|
|
||||||
post(handlers::pentest::pause_session),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/pentest/sessions/{id}/resume",
|
|
||||||
post(handlers::pentest::resume_session),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/pentest/sessions/{id}/stream",
|
|
||||||
get(handlers::pentest::session_stream),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/pentest/sessions/{id}/attack-chain",
|
|
||||||
get(handlers::pentest::get_attack_chain),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/pentest/sessions/{id}/messages",
|
|
||||||
get(handlers::pentest::get_messages),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/pentest/sessions/{id}/findings",
|
|
||||||
get(handlers::pentest::get_session_findings),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/pentest/sessions/{id}/export",
|
|
||||||
post(handlers::pentest::export_session_report),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/v1/pentest/stats",
|
|
||||||
get(handlers::pentest::pentest_stats),
|
|
||||||
)
|
|
||||||
// Webhook routes live on the separate webhook server (port 3002,
|
// Webhook routes live on the separate webhook server (port 3002,
|
||||||
// see crate::webhooks::server). The M7.2-C tenant-in-URL form is
|
// see crate::webhooks::server). The M7.2-C tenant-in-URL form is
|
||||||
// `/webhook/{tenant_id}/{platform}/{repo_id}` and the handlers
|
// `/webhook/{tenant_id}/{platform}/{repo_id}` and the handlers
|
||||||
@@ -386,3 +288,140 @@ pub fn build_router() -> Router {
|
|||||||
// them here on the API server would mismatch the handler
|
// them here on the API server would mismatch the handler
|
||||||
// signature, so the routes are not exported.
|
// signature, so the routes are not exported.
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||||
|
mod tests {
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
/// The routes the description does not cover yet, as listed.
|
||||||
|
fn undescribed() -> BTreeSet<&'static str> {
|
||||||
|
include_str!("undescribed_routes.txt")
|
||||||
|
.lines()
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|l| !l.is_empty() && !l.starts_with('#'))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The paths of the plain route calls in this file (the ones without
|
||||||
|
/// `routes!`).
|
||||||
|
fn plain_routes() -> BTreeSet<String> {
|
||||||
|
let pattern = regex::Regex::new(r#"\.route\(\s*"([^"]+)""#).unwrap();
|
||||||
|
pattern
|
||||||
|
.captures_iter(include_str!("routes.rs"))
|
||||||
|
.map(|c| c[1].to_string())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_route_is_described_or_listed_as_not_yet() {
|
||||||
|
let plain = plain_routes();
|
||||||
|
let listed = undescribed();
|
||||||
|
|
||||||
|
let unlisted: Vec<_> = plain
|
||||||
|
.iter()
|
||||||
|
.filter(|p| !listed.contains(p.as_str()))
|
||||||
|
.collect();
|
||||||
|
assert!(
|
||||||
|
unlisted.is_empty(),
|
||||||
|
"describe these routes with #[utoipa::path] and routes!(…): {unlisted:?}"
|
||||||
|
);
|
||||||
|
let stale: Vec<_> = listed.iter().filter(|p| !plain.contains(**p)).collect();
|
||||||
|
assert!(
|
||||||
|
stale.is_empty(),
|
||||||
|
"described or gone, delete from undescribed_routes.txt: {stale:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_description_has_the_dast_routes_with_parameters_and_auth() {
|
||||||
|
let (_, api) = described_routes().split_for_parts();
|
||||||
|
let api = openapi::with_bearer_auth(api);
|
||||||
|
let doc: serde_json::Value = serde_json::from_str(&api.to_json().unwrap()).unwrap();
|
||||||
|
|
||||||
|
assert!(doc["openapi"].as_str().unwrap().starts_with("3.1"));
|
||||||
|
let paths = &doc["paths"];
|
||||||
|
for (path, method) in [
|
||||||
|
("/api/v1/dast/targets", "get"),
|
||||||
|
("/api/v1/dast/targets", "post"),
|
||||||
|
("/api/v1/dast/targets/{id}/scan", "post"),
|
||||||
|
("/api/v1/dast/scan-runs", "get"),
|
||||||
|
("/api/v1/dast/findings", "get"),
|
||||||
|
("/api/v1/dast/findings/{id}", "get"),
|
||||||
|
] {
|
||||||
|
let operation = &paths[path][method];
|
||||||
|
assert!(operation.is_object(), "{method} {path}");
|
||||||
|
assert_eq!(
|
||||||
|
operation["security"],
|
||||||
|
serde_json::json!([{ "bearer": [] }]),
|
||||||
|
"{method} {path}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let id = &paths["/api/v1/dast/findings/{id}"]["get"]["parameters"][0];
|
||||||
|
assert_eq!(id["name"], "id");
|
||||||
|
assert_eq!(id["in"], "path");
|
||||||
|
let page: Vec<&str> = paths["/api/v1/dast/findings"]["get"]["parameters"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.map(|p| p["name"].as_str().unwrap())
|
||||||
|
.collect();
|
||||||
|
assert_eq!(page, ["page", "limit"]);
|
||||||
|
let body = &paths["/api/v1/dast/targets"]["post"]["requestBody"]["content"];
|
||||||
|
assert!(body["application/json"].is_object(), "{body}");
|
||||||
|
assert_eq!(
|
||||||
|
doc["components"]["securitySchemes"]["bearer"]["scheme"],
|
||||||
|
"bearer"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every described operation has a one-line summary (the first paragraph
|
||||||
|
/// of the handler's doc comment, without the route), and every `{name}`
|
||||||
|
/// in its path a path parameter of that name: a reader can call it from
|
||||||
|
/// the description alone.
|
||||||
|
#[test]
|
||||||
|
fn every_described_operation_is_complete() {
|
||||||
|
let (_, api) = described_routes().split_for_parts();
|
||||||
|
let doc: serde_json::Value = serde_json::from_str(&api.to_json().unwrap()).unwrap();
|
||||||
|
let placeholder = regex::Regex::new(r"\{([^}]+)\}").unwrap();
|
||||||
|
|
||||||
|
for (path, item) in doc["paths"].as_object().unwrap() {
|
||||||
|
for (method, operation) in item.as_object().unwrap() {
|
||||||
|
let summary = operation["summary"].as_str().unwrap_or_default();
|
||||||
|
assert!(
|
||||||
|
!summary.is_empty()
|
||||||
|
&& !summary.contains('\n')
|
||||||
|
&& !["GET ", "POST ", "PUT ", "PATCH ", "DELETE "]
|
||||||
|
.iter()
|
||||||
|
.any(|m| summary.starts_with(m))
|
||||||
|
&& !summary.contains("/api/"),
|
||||||
|
"{method} {path}: the summary is the doc comment's first line, \
|
||||||
|
a short sentence without the route: {summary:?}"
|
||||||
|
);
|
||||||
|
let in_path: Vec<&str> = operation["parameters"]
|
||||||
|
.as_array()
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.filter(|p| p["in"] == "path")
|
||||||
|
.filter_map(|p| p["name"].as_str())
|
||||||
|
.collect();
|
||||||
|
for name in placeholder.captures_iter(path) {
|
||||||
|
assert!(
|
||||||
|
in_path.contains(&&name[1]),
|
||||||
|
"{method} {path} has no path parameter {}",
|
||||||
|
&name[1]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_description_is_behind_the_customer_authentication() {
|
||||||
|
assert!(!compliance_core::auth::bypasses_customer_auth(
|
||||||
|
openapi::SPEC_PATH
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,6 +18,7 @@ use compliance_core::{OrgRole, TenantContext, TenantStatus};
|
|||||||
use crate::agent::ComplianceAgent;
|
use crate::agent::ComplianceAgent;
|
||||||
use crate::api::handlers;
|
use crate::api::handlers;
|
||||||
use crate::api::handlers::platform::{self, PlatformState};
|
use crate::api::handlers::platform::{self, PlatformState};
|
||||||
|
use crate::api::handlers::supplier_invites;
|
||||||
use crate::api::{role_gate, routes};
|
use crate::api::{role_gate, routes};
|
||||||
use crate::error::AgentError;
|
use crate::error::AgentError;
|
||||||
|
|
||||||
@@ -365,6 +366,32 @@ pub async fn start_api_server(
|
|||||||
.put(platform::put_git_source)
|
.put(platform::put_git_source)
|
||||||
.delete(platform::delete_git_source),
|
.delete(platform::delete_git_source),
|
||||||
)
|
)
|
||||||
|
// Supplier invites (#1027): the portal invites a supplier to upload
|
||||||
|
// one component's SBOM.
|
||||||
|
.route(
|
||||||
|
"/api/v1/platform/tenants/{id}/supplier-invites",
|
||||||
|
get(supplier_invites::list_invites).post(supplier_invites::create_invite),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/withdraw",
|
||||||
|
post(supplier_invites::withdraw_invite),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/supplier-view",
|
||||||
|
get(supplier_invites::supplier_view),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/sboms",
|
||||||
|
post(supplier_invites::upload_through_invite).layer(DefaultBodyLimit::max(
|
||||||
|
crate::pipeline::sbom::supplied::MAX_BYTES as usize + routes::MULTIPART_OVERHEAD,
|
||||||
|
)),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/sboms/check",
|
||||||
|
post(supplier_invites::check_through_invite).layer(DefaultBodyLimit::max(
|
||||||
|
crate::pipeline::sbom::supplied::MAX_BYTES as usize + routes::MULTIPART_OVERHEAD,
|
||||||
|
)),
|
||||||
|
)
|
||||||
.layer(middleware::from_fn_with_state(
|
.layer(middleware::from_fn_with_state(
|
||||||
platform_state.clone(),
|
platform_state.clone(),
|
||||||
platform::require_platform_token,
|
platform::require_platform_token,
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# Routes of the customer API (routes.rs) that the OpenAPI description does
|
||||||
|
# not cover yet (#1006), one path per line. A test fails when a plain
|
||||||
|
# `.route("...")` in routes.rs is missing here, or when a line here names no
|
||||||
|
# such route, so the list only ever shrinks. Describe a route with
|
||||||
|
# `#[utoipa::path]` and `.routes(routes!(...))`, then delete its line.
|
||||||
|
/api/v1/targets/{id}/cves
|
||||||
|
/api/v1/targets/{id}/cve-matrix
|
||||||
|
/api/v1/cve-history
|
||||||
|
/api/v1/targets/{id}/top-updates
|
||||||
|
/api/v1/targets/{id}/scan-changes
|
||||||
|
/api/v1/targets/{id}/vex
|
||||||
|
/api/v1/targets/{id}/csaf
|
||||||
|
/api/v1/targets/{id}/enisa
|
||||||
|
/api/v1/cves/{id}/enisa
|
||||||
|
/api/v1/cves/{id}/vex
|
||||||
|
/api/v1/targets/{id}/cve-groups
|
||||||
|
/api/v1/targets/{id}/cve-groups/vex
|
||||||
|
/api/v1/targets/{id}/sbom-ecosystems
|
||||||
@@ -87,8 +87,6 @@ fn build_config(app_env: AppEnv) -> Result<AgentConfig, AgentError> {
|
|||||||
.unwrap_or_else(|| "/data/compliance-scanner/artifacts".to_string()),
|
.unwrap_or_else(|| "/data/compliance-scanner/artifacts".to_string()),
|
||||||
keycloak_url: env_var_opt("KEYCLOAK_URL"),
|
keycloak_url: env_var_opt("KEYCLOAK_URL"),
|
||||||
keycloak_realm: env_var_opt("KEYCLOAK_REALM"),
|
keycloak_realm: env_var_opt("KEYCLOAK_REALM"),
|
||||||
keycloak_admin_username: env_var_opt("KEYCLOAK_ADMIN_USERNAME"),
|
|
||||||
keycloak_admin_password: env_secret_opt("KEYCLOAK_ADMIN_PASSWORD"),
|
|
||||||
pentest_verification_email: env_var_opt("PENTEST_VERIFICATION_EMAIL"),
|
pentest_verification_email: env_var_opt("PENTEST_VERIFICATION_EMAIL"),
|
||||||
pentest_imap_host: env_var_opt("PENTEST_IMAP_HOST"),
|
pentest_imap_host: env_var_opt("PENTEST_IMAP_HOST"),
|
||||||
pentest_imap_port: env_var_opt("PENTEST_IMAP_PORT").and_then(|p| p.parse().ok()),
|
pentest_imap_port: env_var_opt("PENTEST_IMAP_PORT").and_then(|p| p.parse().ok()),
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ use crate::fixtures::{DemoTarget, DemoTargets, FixtureError};
|
|||||||
use crate::targets;
|
use crate::targets;
|
||||||
|
|
||||||
/// What the caller asked to seed.
|
/// What the caller asked to seed.
|
||||||
#[derive(Debug, Clone, Default, Deserialize)]
|
#[derive(Debug, Clone, Default, Deserialize, utoipa::ToSchema)]
|
||||||
pub struct SeedRequest {
|
pub struct SeedRequest {
|
||||||
/// Manifest keys to seed; empty seeds every target.
|
/// Manifest keys to seed; empty seeds every target.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
@@ -166,6 +166,8 @@ async fn seed_one(
|
|||||||
let mut target =
|
let mut target =
|
||||||
compliance_core::models::OnboardedTarget::new(full_name.to_string(), demo.target_type);
|
compliance_core::models::OnboardedTarget::new(full_name.to_string(), demo.target_type);
|
||||||
target.description = demo.description.clone();
|
target.description = demo.description.clone();
|
||||||
|
target.demo = true;
|
||||||
|
target.devices = demo.devices.clone();
|
||||||
for a in demo.artifacts.iter().filter(|a| !a.is_upload()) {
|
for a in demo.artifacts.iter().filter(|a| !a.is_upload()) {
|
||||||
match a.resolved_source_ref() {
|
match a.resolved_source_ref() {
|
||||||
Some(source_ref) => target.artifacts.push(targets::reference_artifact(
|
Some(source_ref) => target.artifacts.push(targets::reference_artifact(
|
||||||
|
|||||||
@@ -47,6 +47,11 @@ pub enum AgentError {
|
|||||||
#[error("not run: {0:?}")]
|
#[error("not run: {0:?}")]
|
||||||
NotAdmitted(compliance_core::models::Refusal),
|
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}")]
|
#[error("{0}")]
|
||||||
Other(String),
|
Other(String),
|
||||||
}
|
}
|
||||||
@@ -79,6 +84,7 @@ impl AgentError {
|
|||||||
| Self::Secret(_)
|
| Self::Secret(_)
|
||||||
| Self::Exec(_)
|
| Self::Exec(_)
|
||||||
| Self::NotAdmitted(_)
|
| Self::NotAdmitted(_)
|
||||||
|
| Self::TargetLimit(_)
|
||||||
| Self::Other(_) => (
|
| Self::Other(_) => (
|
||||||
RunErrorCode::Internal,
|
RunErrorCode::Internal,
|
||||||
"the scan stopped because of an internal error",
|
"the scan stopped because of an internal error",
|
||||||
@@ -91,6 +97,7 @@ impl From<AgentError> for axum::http::StatusCode {
|
|||||||
fn from(err: AgentError) -> Self {
|
fn from(err: AgentError) -> Self {
|
||||||
match err {
|
match err {
|
||||||
AgentError::Core(CoreError::NotFound(_)) => axum::http::StatusCode::NOT_FOUND,
|
AgentError::Core(CoreError::NotFound(_)) => axum::http::StatusCode::NOT_FOUND,
|
||||||
|
AgentError::TargetLimit(_) => axum::http::StatusCode::CONFLICT,
|
||||||
_ => axum::http::StatusCode::INTERNAL_SERVER_ERROR,
|
_ => axum::http::StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -72,11 +72,12 @@ pub enum SbomCoverage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The tools that check a target's components rather than its code.
|
/// The tools that check a target's components rather than its code.
|
||||||
const COMPONENT_TOOLS: [&str; 5] = [
|
const COMPONENT_TOOLS: [&str; 6] = [
|
||||||
"syft",
|
"syft",
|
||||||
"osv",
|
"osv",
|
||||||
"dotnet-lifecycle",
|
"dotnet-lifecycle",
|
||||||
"build-lifecycle",
|
"build-lifecycle",
|
||||||
|
compliance_core::models::SBOM_COVERAGE_SCANNER,
|
||||||
"yocto-release",
|
"yocto-release",
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -513,6 +514,31 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_sbom_coverage_finding_is_evidence_against_the_sbom_requirement() {
|
||||||
|
let map = ControlMap::cra().expect("map");
|
||||||
|
let mut f = finding(SBOM_CONTROL, FindingStatus::Open);
|
||||||
|
f.scanner = compliance_core::models::SBOM_COVERAGE_SCANNER.into();
|
||||||
|
f.rule_id = Some("sbom-dependencies-unresolved".into());
|
||||||
|
let unresolved = SbomCoverage::Unresolved(vec!["Cargo.toml".into()]);
|
||||||
|
|
||||||
|
let statuses = control_statuses(&map, &[f], Some(&python()), &[], &unresolved);
|
||||||
|
|
||||||
|
let sbom = status_of(&statuses, SBOM_CONTROL);
|
||||||
|
assert_eq!(sbom.state, ControlState::NotSatisfied);
|
||||||
|
assert_eq!(sbom.findings.len(), 1);
|
||||||
|
// The CVE controls still say why their components were not checked.
|
||||||
|
for control in ["cra-ai-22", "cra-ai-33"] {
|
||||||
|
assert_eq!(
|
||||||
|
status_of(&statuses, control).reason,
|
||||||
|
Some(NotAssessedReason::DependenciesUnresolved {
|
||||||
|
manifests: vec!["Cargo.toml".into()]
|
||||||
|
}),
|
||||||
|
"{control}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_failed_cve_lookup_claims_nothing_about_component_cves() {
|
fn a_failed_cve_lookup_claims_nothing_about_component_cves() {
|
||||||
let map = ControlMap::cra().expect("map");
|
let map = ControlMap::cra().expect("map");
|
||||||
|
|||||||
@@ -349,7 +349,7 @@ fn json<T: Serialize>(value: &T) -> Result<Vec<u8>, AgentError> {
|
|||||||
/// The findings as CSV, one row each, for a spreadsheet.
|
/// The findings as CSV, one row each, for a spreadsheet.
|
||||||
fn findings_csv(findings: &[Finding]) -> String {
|
fn findings_csv(findings: &[Finding]) -> String {
|
||||||
let mut out =
|
let mut out =
|
||||||
String::from("id,severity,status,type,scanner,rule_id,cwe,location,title,cra_controls\n");
|
String::from("id,severity,status,type,scanner,rule_id,cwe,location,title,cra_controls,cra_requirements\n");
|
||||||
for f in findings {
|
for f in findings {
|
||||||
let location = match (&f.file_path, f.line_number) {
|
let location = match (&f.file_path, f.line_number) {
|
||||||
(Some(file), Some(line)) => format!("{file}:{line}"),
|
(Some(file), Some(line)) => format!("{file}:{line}"),
|
||||||
@@ -367,6 +367,13 @@ fn findings_csv(findings: &[Finding]) -> String {
|
|||||||
location,
|
location,
|
||||||
f.title.clone(),
|
f.title.clone(),
|
||||||
f.control_refs.join(" "),
|
f.control_refs.join(" "),
|
||||||
|
// The same requirements by name, for a person reading the sheet.
|
||||||
|
f.control_refs
|
||||||
|
.iter()
|
||||||
|
.filter_map(|id| compliance_core::cra_requirements::name(id))
|
||||||
|
.map(|name| name.de)
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("; "),
|
||||||
];
|
];
|
||||||
let cells: Vec<String> = row.iter().map(|c| csv_cell(c)).collect();
|
let cells: Vec<String> = row.iter().map(|c| csv_cell(c)).collect();
|
||||||
out.push_str(&cells.join(","));
|
out.push_str(&cells.join(","));
|
||||||
@@ -636,6 +643,10 @@ mod tests {
|
|||||||
"{csv}"
|
"{csv}"
|
||||||
);
|
);
|
||||||
assert!(csv.contains("Core/Src/comms.c:9"));
|
assert!(csv.contains("Core/Src/comms.c:9"));
|
||||||
|
assert!(
|
||||||
|
csv.contains(",cra-ai-8,Keine Standardpasswörter\n"),
|
||||||
|
"{csv}"
|
||||||
|
);
|
||||||
assert_eq!(csv_cell("=HYPERLINK(1)"), "'=HYPERLINK(1)");
|
assert_eq!(csv_cell("=HYPERLINK(1)"), "'=HYPERLINK(1)");
|
||||||
assert_eq!(csv_cell("plain"), "plain");
|
assert_eq!(csv_cell("plain"), "plain");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -117,6 +117,10 @@ pub struct DemoTarget {
|
|||||||
/// Applied by the nightly harness to the fixtures it onboards itself.
|
/// Applied by the nightly harness to the fixtures it onboards itself.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub enabled_scans: Vec<String>,
|
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.
|
/// Golden baseline for the nightly regression.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub expect: Expect,
|
pub expect: Expect,
|
||||||
@@ -491,6 +495,32 @@ mod tests {
|
|||||||
assert_eq!(on_disk.name_prefix, bundled.name_prefix);
|
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]
|
#[test]
|
||||||
fn manifest_is_well_formed() {
|
fn manifest_is_well_formed() {
|
||||||
let m = manifest();
|
let m = manifest();
|
||||||
@@ -589,6 +619,7 @@ mod tests {
|
|||||||
optional: true,
|
optional: true,
|
||||||
}],
|
}],
|
||||||
enabled_scans: Vec::new(),
|
enabled_scans: Vec::new(),
|
||||||
|
devices: Vec::new(),
|
||||||
expect: Expect::default(),
|
expect: Expect::default(),
|
||||||
};
|
};
|
||||||
assert!(t.source_only());
|
assert!(t.source_only());
|
||||||
|
|||||||
@@ -467,6 +467,10 @@ pub enum Outcome {
|
|||||||
Ignored(&'static str),
|
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`.
|
/// Carry out a routed delivery for `tenant_id`.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
@@ -485,7 +489,10 @@ pub async fn apply_action(
|
|||||||
archive_target(db, &source.base_url, repo.id).await?,
|
archive_target(db, &source.base_url, repo.id).await?,
|
||||||
)),
|
)),
|
||||||
SourceAction::Created(repo) => {
|
SourceAction::Created(repo) => {
|
||||||
let ensured = ensure_target(agent, db, tenant_id, source, &repo).await?;
|
let ensured = match ensure_target(agent, db, tenant_id, source, &repo).await {
|
||||||
|
Err(AgentError::TargetLimit(_)) => return Ok(Outcome::Ignored(NO_ROOM)),
|
||||||
|
ensured => ensured?,
|
||||||
|
};
|
||||||
// An empty repository has nothing to scan; its first push will.
|
// An empty repository has nothing to scan; its first push will.
|
||||||
let scan = ensured.created && !repo.empty;
|
let scan = ensured.created && !repo.empty;
|
||||||
if scan {
|
if scan {
|
||||||
@@ -497,7 +504,10 @@ pub async fn apply_action(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
SourceAction::Push(repo) => {
|
SourceAction::Push(repo) => {
|
||||||
let ensured = ensure_target(agent, db, tenant_id, source, &repo).await?;
|
let ensured = match ensure_target(agent, db, tenant_id, source, &repo).await {
|
||||||
|
Err(AgentError::TargetLimit(_)) => return Ok(Outcome::Ignored(NO_ROOM)),
|
||||||
|
ensured => ensured?,
|
||||||
|
};
|
||||||
spawn_scan(agent, tenant_id, &ensured.target_id, ScanTrigger::Webhook);
|
spawn_scan(agent, tenant_id, &ensured.target_id, ScanTrigger::Webhook);
|
||||||
Ok(Outcome::Ensured {
|
Ok(Outcome::Ensured {
|
||||||
target_id: ensured.target_id,
|
target_id: ensured.target_id,
|
||||||
@@ -608,6 +618,11 @@ pub async fn sync_with<L: RepoLister>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(_) => report.refreshed += 1,
|
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) => {
|
Err(err) => {
|
||||||
tracing::warn!(tenant_id, repo = %repo.full_name, "managed git sync: {err}");
|
tracing::warn!(tenant_id, repo = %repo.full_name, "managed git sync: {err}");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,15 +18,20 @@ const MAX_EVIDENCE_CHARS: usize = 4_000;
|
|||||||
|
|
||||||
/// What a finding from a manual test says, whether typed into the form or
|
/// What a finding from a manual test says, whether typed into the form or
|
||||||
/// read from a report.
|
/// read from a report.
|
||||||
#[derive(Debug, Clone, Deserialize, PartialEq)]
|
#[derive(Debug, Clone, Deserialize, PartialEq, utoipa::ToSchema)]
|
||||||
pub struct ManualFinding {
|
pub struct ManualFinding {
|
||||||
|
/// What was found.
|
||||||
pub title: String,
|
pub title: String,
|
||||||
|
/// The finding in detail.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub description: String,
|
pub description: String,
|
||||||
|
/// `info`, `low`, `medium`, `high` or `critical`.
|
||||||
|
#[schema(value_type = String, example = "high")]
|
||||||
pub severity: Severity,
|
pub severity: Severity,
|
||||||
/// `CWE-79`, or just `79`.
|
/// `CWE-79`, or just `79`.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub cwe: Option<String>,
|
pub cwe: Option<String>,
|
||||||
|
/// The CVSS base score.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub cvss_score: Option<f64>,
|
pub cvss_score: Option<f64>,
|
||||||
/// Where it was found: a URL, an endpoint, a file.
|
/// Where it was found: a URL, an endpoint, a file.
|
||||||
@@ -35,8 +40,10 @@ pub struct ManualFinding {
|
|||||||
/// A request or response excerpt that shows it.
|
/// A request or response excerpt that shows it.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub evidence: Option<String>,
|
pub evidence: Option<String>,
|
||||||
|
/// How to reproduce it.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub reproduction: Option<String>,
|
pub reproduction: Option<String>,
|
||||||
|
/// How to fix it.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub remediation: Option<String>,
|
pub remediation: Option<String>,
|
||||||
/// The tool's rule or plugin id, for an imported finding.
|
/// The tool's rule or plugin id, for an imported finding.
|
||||||
@@ -102,7 +109,7 @@ pub fn normalise_cwe(raw: &str) -> Option<String> {
|
|||||||
|
|
||||||
/// The CRA controls a verified weakness is evidence for (see
|
/// The CRA controls a verified weakness is evidence for (see
|
||||||
/// [`control_map::ControlMap::controls_for_cwe`]).
|
/// [`control_map::ControlMap::controls_for_cwe`]).
|
||||||
fn control_refs(cwe: &str) -> Vec<String> {
|
pub(crate) fn control_refs(cwe: &str) -> Vec<String> {
|
||||||
control_map::ControlMap::cra()
|
control_map::ControlMap::cra()
|
||||||
.map(|map| {
|
.map(|map| {
|
||||||
map.controls_for_cwe(cwe)
|
map.controls_for_cwe(cwe)
|
||||||
|
|||||||
@@ -189,8 +189,9 @@ pub fn ingest_artifact(
|
|||||||
ArtifactKind::SourceArchive | ArtifactKind::MobilePackage | ArtifactKind::PlcProject => {
|
ArtifactKind::SourceArchive | ArtifactKind::MobilePackage | ArtifactKind::PlcProject => {
|
||||||
ingest_blob(artifact, ctx, true)
|
ingest_blob(artifact, ctx, true)
|
||||||
}
|
}
|
||||||
// Stored as uploaded: the SPDX reader opens the archive itself.
|
// Stored as uploaded: the SPDX reader opens the archive itself, and a
|
||||||
ArtifactKind::FirmwareImage | ArtifactKind::BuildOutput => {
|
// supplier's SBOM is read as the document it is.
|
||||||
|
ArtifactKind::FirmwareImage | ArtifactKind::BuildOutput | ArtifactKind::SupplierSbom => {
|
||||||
ingest_blob(artifact, ctx, false)
|
ingest_blob(artifact, ctx, false)
|
||||||
}
|
}
|
||||||
ArtifactKind::ContainerImage => Ok(metadata_only(
|
ArtifactKind::ContainerImage => Ok(metadata_only(
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
//!
|
//!
|
||||||
//! **Included and extra targets.** The oldest active targets are included,
|
//! **Included and extra targets.** The oldest active targets are included,
|
||||||
//! up to the plan's `included_targets`; every other active target is extra.
|
//! 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
|
//! The split is stored on each target ([`OnboardedTarget::billing`]) and
|
||||||
//! brought up to date before each scan and when a target is created, so
|
//! brought up to date before each scan and when a target is created, so
|
||||||
//! archiving an included target moves the oldest extra one up.
|
//! archiving an included target moves the oldest extra one up.
|
||||||
@@ -179,10 +180,31 @@ pub async fn swap(
|
|||||||
pub struct Plan {
|
pub struct Plan {
|
||||||
/// How many targets the plan includes; `None` is unlimited.
|
/// How many targets the plan includes; `None` is unlimited.
|
||||||
pub included_targets: Option<u32>,
|
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.
|
/// The quota and the customer's Prüftag cap.
|
||||||
pub limits: PlanLimits,
|
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.
|
/// The tenant's counted Prüfungen and booked Prüftage per month.
|
||||||
const MONTHS: &str = "metering_months";
|
const MONTHS: &str = "metering_months";
|
||||||
/// Each target's Prüftag per day, once the quota was used up.
|
/// Each target's Prüftag per day, once the quota was used up.
|
||||||
@@ -447,6 +469,33 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
use chrono::TimeZone;
|
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]
|
#[test]
|
||||||
fn a_swap_holds_until_the_berlin_month_ends() {
|
fn a_swap_holds_until_the_berlin_month_ends() {
|
||||||
let at = |y, m, d, h| {
|
let at = |y, m, d, h| {
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -14,6 +14,7 @@ use crate::database::Database;
|
|||||||
use crate::llm::{
|
use crate::llm::{
|
||||||
ChatMessage, LlmClient, LlmResponse, ToolCallRequest, ToolCallRequestFunction, ToolDefinition,
|
ChatMessage, LlmClient, LlmResponse, ToolCallRequest, ToolCallRequestFunction, ToolDefinition,
|
||||||
};
|
};
|
||||||
|
use crate::pentest::cleanup::CleanupOutcome;
|
||||||
|
|
||||||
/// Maximum duration for a single pentest session before timeout
|
/// Maximum duration for a single pentest session before timeout
|
||||||
const SESSION_TIMEOUT: Duration = Duration::from_secs(30 * 60); // 30 minutes
|
const SESSION_TIMEOUT: Duration = Duration::from_secs(30 * 60); // 30 minutes
|
||||||
@@ -24,6 +25,8 @@ pub struct PentestOrchestrator {
|
|||||||
pub(crate) db: Database,
|
pub(crate) db: Database,
|
||||||
pub(crate) event_tx: broadcast::Sender<PentestEvent>,
|
pub(crate) event_tx: broadcast::Sender<PentestEvent>,
|
||||||
pub(crate) pause_rx: Option<watch::Receiver<bool>>,
|
pub(crate) pause_rx: Option<watch::Receiver<bool>>,
|
||||||
|
/// Outbound policy for tenant-chosen URLs, the test-user cleanup's too.
|
||||||
|
pub(crate) net_guard: NetGuard,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PentestOrchestrator {
|
impl PentestOrchestrator {
|
||||||
@@ -42,6 +45,55 @@ impl PentestOrchestrator {
|
|||||||
db,
|
db,
|
||||||
event_tx,
|
event_tx,
|
||||||
pause_rx,
|
pause_rx,
|
||||||
|
net_guard,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delete the session's test user with the access given for the target's
|
||||||
|
/// identity provider, and record on the session what became of it.
|
||||||
|
async fn clean_up_test_user(
|
||||||
|
&self,
|
||||||
|
session_id: Option<mongodb::bson::oid::ObjectId>,
|
||||||
|
test_user: &TestUserRecord,
|
||||||
|
access: Option<&TestUserCleanup>,
|
||||||
|
) {
|
||||||
|
let outcome = match compliance_core::guarded_net::guarded_client_builder(self.net_guard)
|
||||||
|
.timeout(std::time::Duration::from_secs(30))
|
||||||
|
.build()
|
||||||
|
{
|
||||||
|
Ok(http) => crate::pentest::cleanup::cleanup_test_user(test_user, access, &http).await,
|
||||||
|
Err(e) => Err(format!("no HTTP client: {e}")),
|
||||||
|
};
|
||||||
|
let left_behind = match outcome {
|
||||||
|
Ok(CleanupOutcome::Deleted) | Ok(CleanupOutcome::NotRegistered) => None,
|
||||||
|
Ok(CleanupOutcome::LeftBehind(reason)) => Some(reason),
|
||||||
|
Err(e) => Some(format!("cleanup failed: {e}")),
|
||||||
|
};
|
||||||
|
match &left_behind {
|
||||||
|
None => tracing::info!("Pentest test user deleted"),
|
||||||
|
Some(reason) => {
|
||||||
|
tracing::warn!(reason = %reason, "Pentest test user left behind");
|
||||||
|
let _ = self.event_tx.send(PentestEvent::Message {
|
||||||
|
content: format!(
|
||||||
|
"The test user {} is still registered with the application ({reason}); \
|
||||||
|
delete it by hand.",
|
||||||
|
test_user.email.as_deref().unwrap_or("(unknown)")
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(sid) = session_id {
|
||||||
|
let _ = self
|
||||||
|
.db
|
||||||
|
.pentest_sessions()
|
||||||
|
.update_one(
|
||||||
|
doc! { "_id": sid },
|
||||||
|
doc! { "$set": {
|
||||||
|
"test_user.cleaned_up": left_behind.is_none(),
|
||||||
|
"test_user.left_behind": left_behind,
|
||||||
|
} },
|
||||||
|
)
|
||||||
|
.await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -499,55 +551,12 @@ impl PentestOrchestrator {
|
|||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clean up test user via identity provider API if requested
|
// Delete the test user in the target's identity provider if asked.
|
||||||
if session
|
if let (Some(cfg), Some(test_user)) = (session.config.as_ref(), session.test_user.as_ref())
|
||||||
.config
|
|
||||||
.as_ref()
|
|
||||||
.is_some_and(|c| c.auth.cleanup_test_user)
|
|
||||||
{
|
{
|
||||||
if let Some(ref test_user) = session.test_user {
|
if cfg.auth.cleanup_test_user {
|
||||||
let http = reqwest::Client::new();
|
self.clean_up_test_user(session.id, test_user, cfg.auth.cleanup.as_ref())
|
||||||
// We need the AgentConfig — read from env since orchestrator doesn't hold it
|
.await;
|
||||||
let config = crate::config::load_config();
|
|
||||||
match config {
|
|
||||||
Ok(cfg) => {
|
|
||||||
match crate::pentest::cleanup::cleanup_test_user(test_user, &cfg, &http)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(true) => {
|
|
||||||
tracing::info!(
|
|
||||||
username = test_user.username.as_deref(),
|
|
||||||
"Test user cleaned up via provider API"
|
|
||||||
);
|
|
||||||
// Mark as cleaned up in DB
|
|
||||||
if let Some(sid) = session.id {
|
|
||||||
let _ = self
|
|
||||||
.db
|
|
||||||
.pentest_sessions()
|
|
||||||
.update_one(
|
|
||||||
doc! { "_id": sid },
|
|
||||||
doc! { "$set": { "test_user.cleaned_up": true } },
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(false) => {
|
|
||||||
tracing::info!(
|
|
||||||
"Test user cleanup skipped (no provider configured)"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
tracing::warn!(error = %e, "Test user cleanup failed");
|
|
||||||
let _ = self.event_tx.send(PentestEvent::Error {
|
|
||||||
message: format!("Test user cleanup failed: {e}"),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
tracing::warn!(error = %e, "Could not load config for cleanup");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,8 @@ use compliance_core::models::sbom::SbomEntry;
|
|||||||
use super::orchestrator::PentestOrchestrator;
|
use super::orchestrator::PentestOrchestrator;
|
||||||
|
|
||||||
/// Build additional prompt sections from PentestConfig when present.
|
/// Build additional prompt sections from PentestConfig when present.
|
||||||
fn build_config_sections(config: &PentestConfig) -> String {
|
/// `test_email` is the address an auto-register session registers with.
|
||||||
|
fn build_config_sections(config: &PentestConfig, test_email: Option<&str>) -> String {
|
||||||
let mut sections = String::new();
|
let mut sections = String::new();
|
||||||
|
|
||||||
// Authentication section
|
// Authentication section
|
||||||
@@ -35,13 +36,11 @@ fn build_config_sections(config: &PentestConfig) -> String {
|
|||||||
"- **Registration URL**: Not provided — use Playwright to discover the registration page.\n",
|
"- **Registration URL**: Not provided — use Playwright to discover the registration page.\n",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if let Some(ref email) = config.auth.verification_email {
|
if let Some(email) = test_email {
|
||||||
sections.push_str(&format!(
|
sections.push_str(&format!(
|
||||||
"- **Verification Email**: Use plus-addressing from `{email}` \
|
"- **E-mail address**: Register with exactly `{email}` (no other \
|
||||||
(e.g. `{base}+{{session_id}}@{domain}`) for email verification. \
|
address): the system polls its mailbox for verification links and \
|
||||||
The system will poll the IMAP mailbox for verification links.\n",
|
finds the test account by it afterwards.\n",
|
||||||
base = email.split('@').next().unwrap_or(email),
|
|
||||||
domain = email.split('@').nth(1).unwrap_or("example.com"),
|
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
sections.push_str(
|
sections.push_str(
|
||||||
@@ -245,7 +244,10 @@ impl PentestOrchestrator {
|
|||||||
let config_sections = session
|
let config_sections = session
|
||||||
.config
|
.config
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(build_config_sections)
|
.map(|c| {
|
||||||
|
let test_email = session.test_user.as_ref().and_then(|u| u.email.as_deref());
|
||||||
|
build_config_sections(c, test_email)
|
||||||
|
})
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
|
|
||||||
format!(
|
format!(
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use super::{html_escape, tool_category};
|
use super::{html_escape, tool_category};
|
||||||
use compliance_core::models::pentest::{AuthMode, PentestConfig, PentestSession};
|
use compliance_core::models::pentest::{AuthMode, PentestConfig, PentestSession, TestUserRecord};
|
||||||
|
|
||||||
pub(super) fn scope(
|
pub(super) fn scope(
|
||||||
session: &PentestSession,
|
session: &PentestSession,
|
||||||
@@ -43,6 +43,9 @@ pub(super) fn scope(
|
|||||||
AuthMode::AutoRegister => "Auto-register",
|
AuthMode::AutoRegister => "Auto-register",
|
||||||
};
|
};
|
||||||
rows.push_str(&format!("<tr><td>Auth Mode</td><td>{auth_mode}</td></tr>"));
|
rows.push_str(&format!("<tr><td>Auth Mode</td><td>{auth_mode}</td></tr>"));
|
||||||
|
if let Some(user) = &session.test_user {
|
||||||
|
rows.push_str(&test_user_row(user));
|
||||||
|
}
|
||||||
if !cfg.scope_exclusions.is_empty() {
|
if !cfg.scope_exclusions.is_empty() {
|
||||||
let excl = cfg
|
let excl = cfg
|
||||||
.scope_exclusions
|
.scope_exclusions
|
||||||
@@ -125,3 +128,47 @@ pub(super) fn scope(
|
|||||||
success_rate = session.success_rate(),
|
success_rate = session.success_rate(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The report row for the session's test user: deleted, or still registered
|
||||||
|
/// with the application and to be deleted by hand.
|
||||||
|
fn test_user_row(user: &TestUserRecord) -> String {
|
||||||
|
let email = html_escape(user.email.as_deref().unwrap_or("(unknown)"));
|
||||||
|
let state = match (&user.left_behind, user.cleaned_up) {
|
||||||
|
(Some(reason), _) => format!(
|
||||||
|
"<strong>Left behind</strong>: still registered with the application, \
|
||||||
|
delete it by hand ({})",
|
||||||
|
html_escape(reason)
|
||||||
|
),
|
||||||
|
(None, true) => "Deleted after the test".to_string(),
|
||||||
|
(None, false) => "Not deleted (cleanup was not requested)".to_string(),
|
||||||
|
};
|
||||||
|
format!("<tr><td>Test User</td><td><code>{email}</code> — {state}</td></tr>")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test_user_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_left_behind_test_user_is_named_with_its_reason() {
|
||||||
|
let user = TestUserRecord {
|
||||||
|
email: Some("pentest+1@mail.example.com".into()),
|
||||||
|
left_behind: Some("no admin access <given>".into()),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let row = test_user_row(&user);
|
||||||
|
assert!(row.contains("pentest+1@mail.example.com"));
|
||||||
|
assert!(row.contains("Left behind"));
|
||||||
|
assert!(row.contains("no admin access <given>"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_deleted_test_user_says_so() {
|
||||||
|
let user = TestUserRecord {
|
||||||
|
email: Some("pentest+1@mail.example.com".into()),
|
||||||
|
cleaned_up: true,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
assert!(test_user_row(&user).contains("Deleted after the test"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -93,6 +93,46 @@ impl Provider {
|
|||||||
max_age: Some(CISA_MAX_AGE),
|
max_age: Some(CISA_MAX_AGE),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A supplier's provider a tenant named for a bought-in component (#1025),
|
||||||
|
/// keyed by its metadata URL ([`supplier_key`]).
|
||||||
|
pub(crate) fn supplier(metadata_url: &str) -> Self {
|
||||||
|
Self {
|
||||||
|
name: supplier_key(metadata_url),
|
||||||
|
metadata_url: metadata_url.to_string(),
|
||||||
|
feed_filter: None,
|
||||||
|
max_age: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// When a supplier's provider was last read, and whether it could be
|
||||||
|
/// (#1025): kept per tenant in [`SupplierProviderStatus::COLLECTION`], so the
|
||||||
|
/// target editor can tell a provider without advisories from one never or no
|
||||||
|
/// longer read.
|
||||||
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
|
pub(crate) struct SupplierProviderStatus {
|
||||||
|
/// The provider's key ([`supplier_key`]).
|
||||||
|
#[serde(rename = "_id")]
|
||||||
|
pub provider: String,
|
||||||
|
/// When the last refresh read it.
|
||||||
|
pub checked_at: mongodb::bson::DateTime,
|
||||||
|
/// Whether its metadata and feeds could be read then.
|
||||||
|
pub reachable: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SupplierProviderStatus {
|
||||||
|
/// The collection, in the tenant's own database.
|
||||||
|
pub(crate) const COLLECTION: &'static str = "supplier_csaf_providers";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The prefix of a supplier provider's key, which tells its advisories from
|
||||||
|
/// the shared providers' ([`Provider::supplier`]).
|
||||||
|
pub(crate) const SUPPLIER_PREFIX: &str = "supplier:";
|
||||||
|
|
||||||
|
/// The key a supplier's advisories are stored and matched under.
|
||||||
|
pub(crate) fn supplier_key(metadata_url: &str) -> String {
|
||||||
|
format!("{SUPPLIER_PREFIX}{}", metadata_url.trim())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The providers `PW_CSAF_PROVIDERS` names: `off` (none), unset or `default`
|
/// The providers `PW_CSAF_PROVIDERS` names: `off` (none), unset or `default`
|
||||||
@@ -224,6 +264,19 @@ impl MongoAdvisoryStore {
|
|||||||
pub(crate) fn collection(&self) -> &mongodb::Collection<StoredAdvisory> {
|
pub(crate) fn collection(&self) -> &mongodb::Collection<StoredAdvisory> {
|
||||||
&self.collection
|
&self.collection
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The collection of a tenant's supplier advisories (#1025), in the
|
||||||
|
/// tenant's own database.
|
||||||
|
pub(crate) const SUPPLIER_COLLECTION: &'static str = "supplier_csaf_advisories";
|
||||||
|
|
||||||
|
/// The advisories of the suppliers a tenant named (#1025), in its own
|
||||||
|
/// database: a provider one tenant chooses is never matched against
|
||||||
|
/// another tenant's components.
|
||||||
|
pub(crate) fn supplier(tenant_db: &mongodb::Database) -> Self {
|
||||||
|
Self {
|
||||||
|
collection: tenant_db.collection(Self::SUPPLIER_COLLECTION),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AdvisoryStore for MongoAdvisoryStore {
|
impl AdvisoryStore for MongoAdvisoryStore {
|
||||||
@@ -316,6 +369,8 @@ pub(crate) struct Counts {
|
|||||||
pub failed: usize,
|
pub failed: usize,
|
||||||
/// Left for a later run (over the limits).
|
/// Left for a later run (over the limits).
|
||||||
pub deferred: usize,
|
pub deferred: usize,
|
||||||
|
/// The provider's metadata or feeds could not be read at all.
|
||||||
|
pub unreachable: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One advisory a feed lists.
|
/// One advisory a feed lists.
|
||||||
@@ -456,6 +511,7 @@ pub(crate) async fn refresh(
|
|||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::warn!(provider = %provider.name, "CSAF provider not read: {e}");
|
tracing::warn!(provider = %provider.name, "CSAF provider not read: {e}");
|
||||||
counts.failed = 1;
|
counts.failed = 1;
|
||||||
|
counts.unreachable = true;
|
||||||
out.insert(provider.name.clone(), counts);
|
out.insert(provider.name.clone(), counts);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -566,6 +622,99 @@ pub(crate) async fn refresh_index(admin_db: &mongodb::Database, guard: NetGuard)
|
|||||||
refresh(&fetch, &store, &providers, Limits::default()).await;
|
refresh(&fetch, &store, &providers, Limits::default()).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The supplier providers a tenant's active targets name (#1025), once each.
|
||||||
|
pub(crate) fn supplier_providers(
|
||||||
|
targets: &[compliance_core::models::OnboardedTarget],
|
||||||
|
) -> Vec<Provider> {
|
||||||
|
let mut urls: Vec<&str> = targets
|
||||||
|
.iter()
|
||||||
|
.filter(|t| t.archived_at.is_none())
|
||||||
|
.filter_map(|t| t.supplier.as_ref()?.csaf_provider.as_deref())
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|u| !u.is_empty())
|
||||||
|
.collect();
|
||||||
|
urls.sort_unstable();
|
||||||
|
urls.dedup();
|
||||||
|
urls.into_iter().map(Provider::supplier).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bounds of one refresh of a tenant's supplier advisories: fewer than the
|
||||||
|
/// shared index, as one tenant's suppliers publish fewer.
|
||||||
|
fn supplier_limits() -> Limits {
|
||||||
|
Limits {
|
||||||
|
max_advisories: 200,
|
||||||
|
concurrency: 2,
|
||||||
|
budget: Duration::from_secs(5 * 60),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Refresh the advisories of the supplier providers tenant `tenant_id`'s
|
||||||
|
/// targets name (#1025), into its own database, through the guarded client.
|
||||||
|
/// Logs and returns on any failure.
|
||||||
|
pub(crate) async fn refresh_supplier_advisories(
|
||||||
|
agent: &crate::agent::ComplianceAgent,
|
||||||
|
tenant_id: &str,
|
||||||
|
) {
|
||||||
|
let db = match agent.db_pool.for_tenant_id(tenant_id).await {
|
||||||
|
Ok(db) => db,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(tenant_id, "supplier CSAF advisories not refreshed: {e}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let targets: Vec<compliance_core::models::OnboardedTarget> = match db
|
||||||
|
.onboarded_targets()
|
||||||
|
.find(doc! { "supplier.csaf_provider": { "$exists": true }, "archived_at": null })
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(cursor) => cursor.try_collect().await.unwrap_or_default(),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(tenant_id, "supplier CSAF providers not read: {e}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let providers = supplier_providers(&targets);
|
||||||
|
if providers.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let fetch = match HttpFetch::new(agent.net_guard) {
|
||||||
|
Ok(fetch) => fetch,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(tenant_id, "supplier CSAF advisories not refreshed: {e}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let store = MongoAdvisoryStore::supplier(db.inner());
|
||||||
|
let counts = refresh(&fetch, &store, &providers, supplier_limits()).await;
|
||||||
|
let statuses = db
|
||||||
|
.inner()
|
||||||
|
.collection::<SupplierProviderStatus>(SupplierProviderStatus::COLLECTION);
|
||||||
|
let checked_at = mongodb::bson::DateTime::now();
|
||||||
|
for (provider, c) in &counts {
|
||||||
|
let status = SupplierProviderStatus {
|
||||||
|
provider: provider.clone(),
|
||||||
|
checked_at,
|
||||||
|
reachable: !c.unreachable,
|
||||||
|
};
|
||||||
|
if let Err(e) = statuses
|
||||||
|
.replace_one(doc! { "_id": provider }, &status)
|
||||||
|
.upsert(true)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
tracing::warn!(tenant_id, provider, "supplier CSAF status not kept: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let stored: usize = counts.values().map(|c| c.stored).sum();
|
||||||
|
let failed: usize = counts.values().map(|c| c.failed).sum();
|
||||||
|
tracing::info!(
|
||||||
|
tenant_id,
|
||||||
|
providers = providers.len(),
|
||||||
|
stored,
|
||||||
|
failed,
|
||||||
|
"supplier CSAF advisories refreshed"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/// A store for tests: advisories in memory.
|
/// A store for tests: advisories in memory.
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
@@ -632,6 +781,33 @@ impl AdvisoryStore for MemoryStore {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_tenants_supplier_providers_are_its_active_targets_once_each() {
|
||||||
|
use compliance_core::models::{OnboardedTarget, SupplierComponent, TargetType};
|
||||||
|
let url = "https://supplier.example/.well-known/csaf/provider-metadata.json";
|
||||||
|
let target = |provider: Option<&str>, archived: bool| {
|
||||||
|
let mut t = OnboardedTarget::new("c".into(), TargetType::FirmwareBareMetal);
|
||||||
|
t.supplier = Some(SupplierComponent {
|
||||||
|
name: "Example GmbH".into(),
|
||||||
|
product: None,
|
||||||
|
version: None,
|
||||||
|
csaf_provider: provider.map(String::from),
|
||||||
|
});
|
||||||
|
t.archived_at = archived.then(chrono::Utc::now);
|
||||||
|
t
|
||||||
|
};
|
||||||
|
let providers = supplier_providers(&[
|
||||||
|
target(Some(url), false),
|
||||||
|
target(Some(&format!(" {url} ")), false),
|
||||||
|
target(Some("https://gone.example/provider-metadata.json"), true),
|
||||||
|
target(None, false),
|
||||||
|
]);
|
||||||
|
assert_eq!(providers.len(), 1);
|
||||||
|
assert_eq!(providers[0].metadata_url, url);
|
||||||
|
assert_eq!(providers[0].name, format!("{SUPPLIER_PREFIX}{url}"));
|
||||||
|
assert!(providers[0].feed_filter.is_none() && providers[0].max_age.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
/// A provider answering from a table; counts requests.
|
/// A provider answering from a table; counts requests.
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
struct Fake(HashMap<String, Vec<u8>>, std::sync::Mutex<Vec<String>>);
|
struct Fake(HashMap<String, Vec<u8>>, std::sync::Mutex<Vec<String>>);
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
//! A target's components against the vendor CSAF advisories in the index
|
//! A target's components against the vendor CSAF advisories in the index
|
||||||
//! (#515, see [`super::csaf_feed`]): a CODESYS runtime or library by its
|
//! (#515, see [`super::csaf_feed`]): a CODESYS runtime or library by its
|
||||||
//! name and version against CODESYS's advisories, any component with a purl
|
//! name and version against CODESYS's advisories, a Siemens device by its
|
||||||
//! against an advisory product with the same purl. A match raises a CVE
|
//! order number and firmware against Siemens' (SPS item 4a), and any
|
||||||
|
//! component with a purl against an advisory product with the same purl. A match raises a CVE
|
||||||
//! alert with source `csaf`, or, where OSV or NVD already reported the CVE,
|
//! alert with source `csaf`, or, where OSV or NVD already reported the CVE,
|
||||||
//! adds the advisory to that alert; either way the alert links the advisory
|
//! adds the advisory to that alert; either way the alert links the advisory
|
||||||
//! and carries the vendor's remediation and fixed versions.
|
//! and carries the vendor's remediation and fixed versions.
|
||||||
@@ -17,6 +18,10 @@ use compliance_core::version::Vers;
|
|||||||
|
|
||||||
use super::csaf_feed::{MongoAdvisoryStore, StoredAdvisory};
|
use super::csaf_feed::{MongoAdvisoryStore, StoredAdvisory};
|
||||||
|
|
||||||
|
/// The provider whose advisories name devices by order number
|
||||||
|
/// ([`compliance_core::models::PlcDevice`]).
|
||||||
|
const ORDER_NUMBER_PROVIDER: &str = "siemens";
|
||||||
|
|
||||||
/// The provider whose advisories name the components of a package manager
|
/// The provider whose advisories name the components of a package manager
|
||||||
/// by product name.
|
/// by product name.
|
||||||
fn provider_for(package_manager: &str) -> Option<&'static str> {
|
fn provider_for(package_manager: &str) -> Option<&'static str> {
|
||||||
@@ -26,29 +31,46 @@ fn provider_for(package_manager: &str) -> Option<&'static str> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What the advisory index is asked for, for some components ([`wanted`]).
|
||||||
|
#[derive(Debug, Default, PartialEq, Eq)]
|
||||||
|
pub(crate) struct Wanted {
|
||||||
|
/// Providers whose advisories all count ([`provider_for`]).
|
||||||
|
pub providers: Vec<String>,
|
||||||
|
/// Purls without version.
|
||||||
|
pub purls: Vec<String>,
|
||||||
|
/// Device order numbers, normalised.
|
||||||
|
pub order_numbers: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Wanted {
|
||||||
|
fn is_empty(&self) -> bool {
|
||||||
|
self.providers.is_empty() && self.purls.is_empty() && self.order_numbers.is_empty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Reads the advisory index, behind a trait so tests keep it in memory.
|
/// Reads the advisory index, behind a trait so tests keep it in memory.
|
||||||
pub(crate) trait AdvisoryIndex: Send + Sync {
|
pub(crate) trait AdvisoryIndex: Send + Sync {
|
||||||
/// The advisories of `providers`, and those naming any of `purls`
|
/// The advisories of `wanted`'s providers, and those naming any of its
|
||||||
/// (without version), as `(provider, advisory)`.
|
/// purls (without version) or, of [`ORDER_NUMBER_PROVIDER`], any of its
|
||||||
|
/// order numbers, as `(provider, advisory)`.
|
||||||
fn relevant<'a>(
|
fn relevant<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
providers: &'a [String],
|
wanted: &'a Wanted,
|
||||||
purls: &'a [String],
|
|
||||||
) -> BoxFuture<'a, Result<Vec<(String, Advisory)>, String>>;
|
) -> BoxFuture<'a, Result<Vec<(String, Advisory)>, String>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AdvisoryIndex for MongoAdvisoryStore {
|
impl AdvisoryIndex for MongoAdvisoryStore {
|
||||||
fn relevant<'a>(
|
fn relevant<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
providers: &'a [String],
|
wanted: &'a Wanted,
|
||||||
purls: &'a [String],
|
|
||||||
) -> BoxFuture<'a, Result<Vec<(String, Advisory)>, String>> {
|
) -> BoxFuture<'a, Result<Vec<(String, Advisory)>, String>> {
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
if providers.is_empty() && purls.is_empty() {
|
if wanted.is_empty() {
|
||||||
return Ok(Vec::new());
|
return Ok(Vec::new());
|
||||||
}
|
}
|
||||||
// A product's purl may carry a version; compare from the start.
|
// A product's purl may carry a version; compare from the start.
|
||||||
let purl_patterns: Vec<mongodb::bson::Regex> = purls
|
let purl_patterns: Vec<mongodb::bson::Regex> = wanted
|
||||||
|
.purls
|
||||||
.iter()
|
.iter()
|
||||||
.map(|p| mongodb::bson::Regex {
|
.map(|p| mongodb::bson::Regex {
|
||||||
pattern: format!("^{}(@|$)", regex::escape(p)),
|
pattern: format!("^{}(@|$)", regex::escape(p)),
|
||||||
@@ -58,8 +80,12 @@ impl AdvisoryIndex for MongoAdvisoryStore {
|
|||||||
let rows: Vec<StoredAdvisory> = self
|
let rows: Vec<StoredAdvisory> = self
|
||||||
.collection()
|
.collection()
|
||||||
.find(doc! { "$or": [
|
.find(doc! { "$or": [
|
||||||
{ "provider": { "$in": providers } },
|
{ "provider": { "$in": &wanted.providers } },
|
||||||
{ "advisory.products.purl": { "$in": purl_patterns } },
|
{ "advisory.products.purl": { "$in": purl_patterns } },
|
||||||
|
{
|
||||||
|
"provider": ORDER_NUMBER_PROVIDER,
|
||||||
|
"advisory.products.model_numbers": { "$in": &wanted.order_numbers },
|
||||||
|
},
|
||||||
] })
|
] })
|
||||||
.await
|
.await
|
||||||
.map_err(|e| e.to_string())?
|
.map_err(|e| e.to_string())?
|
||||||
@@ -83,11 +109,24 @@ fn purl_base(purl: &str) -> Option<String> {
|
|||||||
/// Whether advisory product `p` (of `provider`) is `entry`'s component at
|
/// Whether advisory product `p` (of `provider`) is `entry`'s component at
|
||||||
/// its version.
|
/// its version.
|
||||||
fn names(p: &AdvisoryProduct, provider: &str, entry: &SbomEntry) -> bool {
|
fn names(p: &AdvisoryProduct, provider: &str, entry: &SbomEntry) -> bool {
|
||||||
|
// A device, by its order number and firmware, only in the advisories of
|
||||||
|
// the vendor whose order numbers they are.
|
||||||
|
if let Some(order_number) = entry.order_number.as_deref() {
|
||||||
|
return provider == ORDER_NUMBER_PROVIDER && p.covers_device(order_number, &entry.version);
|
||||||
|
}
|
||||||
if provider_for(&entry.package_manager) == Some(provider)
|
if provider_for(&entry.package_manager) == Some(provider)
|
||||||
&& p.covers(&entry.name, &entry.version)
|
&& p.covers(&entry.name, &entry.version)
|
||||||
{
|
{
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
// A bought-in product (#1025), by its supplier's name for it, only in
|
||||||
|
// that supplier's own advisories.
|
||||||
|
if entry.package_manager == crate::pipeline::sbom::supplied::SUPPLIER_PRODUCT_MANAGER
|
||||||
|
&& provider.starts_with(crate::pipeline::csaf_feed::SUPPLIER_PREFIX)
|
||||||
|
&& p.covers(&entry.name, &entry.version)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
let (Some(theirs), Some(ours)) = (p.purl.as_deref(), entry.purl.as_deref()) else {
|
let (Some(theirs), Some(ours)) = (p.purl.as_deref(), entry.purl.as_deref()) else {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
@@ -195,7 +234,12 @@ pub(crate) fn apply(
|
|||||||
aliases: Vec::new(),
|
aliases: Vec::new(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
let fixed = hit.advisory.fixed_versions(hit.vulnerability, &entry.name);
|
let fixed = match entry.order_number.as_deref() {
|
||||||
|
Some(order_number) => hit
|
||||||
|
.advisory
|
||||||
|
.fixed_device_versions(hit.vulnerability, order_number),
|
||||||
|
None => hit.advisory.fixed_versions(hit.vulnerability, &entry.name),
|
||||||
|
};
|
||||||
let alert = match alerts.iter_mut().position(|a| a.cve_id == hit.cve) {
|
let alert = match alerts.iter_mut().position(|a| a.cve_id == hit.cve) {
|
||||||
Some(i) => &mut alerts[i],
|
Some(i) => &mut alerts[i],
|
||||||
None => {
|
None => {
|
||||||
@@ -247,23 +291,27 @@ pub(crate) fn apply(
|
|||||||
count
|
count
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The providers and purls the index is asked for, for `entries`.
|
/// What the index is asked for, for `entries`.
|
||||||
pub(crate) fn wanted(entries: &[SbomEntry]) -> (Vec<String>, Vec<String>) {
|
pub(crate) fn wanted(entries: &[SbomEntry]) -> Wanted {
|
||||||
let mut providers: Vec<String> = Vec::new();
|
let mut wanted = Wanted::default();
|
||||||
let mut purls: Vec<String> = Vec::new();
|
|
||||||
for entry in entries {
|
for entry in entries {
|
||||||
if let Some(p) = provider_for(&entry.package_manager) {
|
if let Some(p) = provider_for(&entry.package_manager) {
|
||||||
if !providers.iter().any(|q| q == p) {
|
if !wanted.providers.iter().any(|q| q == p) {
|
||||||
providers.push(p.to_string());
|
wanted.providers.push(p.to_string());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if let Some(base) = entry.purl.as_deref().and_then(purl_base) {
|
if let Some(base) = entry.purl.as_deref().and_then(purl_base) {
|
||||||
if !purls.contains(&base) {
|
if !wanted.purls.contains(&base) {
|
||||||
purls.push(base);
|
wanted.purls.push(base);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(order_number) = entry.order_number.as_deref() {
|
||||||
|
if !wanted.order_numbers.iter().any(|o| o == order_number) {
|
||||||
|
wanted.order_numbers.push(order_number.to_string());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
(providers, purls)
|
wanted
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -292,6 +340,52 @@ mod tests {
|
|||||||
e
|
e
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_bought_in_product_is_matched_only_by_its_own_suppliers_advisory() {
|
||||||
|
// #1025: the product itself, named as its supplier names it, against
|
||||||
|
// that supplier's advisories; the same advisory under a shared
|
||||||
|
// provider's key does not name it.
|
||||||
|
let advisory = codesys_advisory();
|
||||||
|
let product = |version: &str| {
|
||||||
|
let mut e = SbomEntry::new(
|
||||||
|
"t".into(),
|
||||||
|
"CODESYS Control for Linux SL".into(),
|
||||||
|
version.into(),
|
||||||
|
crate::pipeline::sbom::supplied::SUPPLIER_PRODUCT_MANAGER.into(),
|
||||||
|
);
|
||||||
|
e.evidence = vec!["supplied by Example GmbH".into()];
|
||||||
|
e
|
||||||
|
};
|
||||||
|
let supplier = crate::pipeline::csaf_feed::supplier_key(
|
||||||
|
"https://supplier.example/.well-known/csaf/provider-metadata.json",
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut entries = vec![product("3.5.16.0"), product("3.5.22.40")];
|
||||||
|
let mut alerts = Vec::new();
|
||||||
|
let n = apply(
|
||||||
|
"t",
|
||||||
|
&mut entries,
|
||||||
|
&[(supplier, advisory.clone())],
|
||||||
|
&mut alerts,
|
||||||
|
);
|
||||||
|
assert_eq!(n, 1, "only the version below the fix");
|
||||||
|
assert_eq!(alerts[0].cve_id, "CVE-2026-90001");
|
||||||
|
assert_eq!(alerts[0].affected_version, "3.5.16.0");
|
||||||
|
|
||||||
|
let mut entries = vec![product("3.5.16.0")];
|
||||||
|
let mut alerts = Vec::new();
|
||||||
|
let n = apply(
|
||||||
|
"t",
|
||||||
|
&mut entries,
|
||||||
|
&[("siemens".to_string(), advisory)],
|
||||||
|
&mut alerts,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
n, 0,
|
||||||
|
"a shared provider's advisory does not name a supplier product"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_codesys_runtime_below_the_fix_gets_the_advisory() {
|
fn a_codesys_runtime_below_the_fix_gets_the_advisory() {
|
||||||
let advisories = vec![("codesys".to_string(), codesys_advisory())];
|
let advisories = vec![("codesys".to_string(), codesys_advisory())];
|
||||||
@@ -410,10 +504,104 @@ mod tests {
|
|||||||
assert_eq!(alerts[0].affected_version, "3.1.0");
|
assert_eq!(alerts[0].affected_version, "3.1.0");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
wanted(&entries),
|
wanted(&entries),
|
||||||
(
|
Wanted {
|
||||||
Vec::new(),
|
purls: vec!["pkg:generic/example/fieldbus-stack".to_string()],
|
||||||
vec!["pkg:generic/example/fieldbus-stack".to_string()]
|
..Wanted::default()
|
||||||
)
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The synthetic Siemens-shaped advisory of the core fixtures, as
|
||||||
|
/// `provider`'s.
|
||||||
|
fn siemens_advisory(provider: &str) -> (String, Advisory) {
|
||||||
|
let doc: serde_json::Value = serde_json::from_str(include_str!(
|
||||||
|
"../../../compliance-core/tests/fixtures/csaf/siemens-synthetic.json"
|
||||||
|
))
|
||||||
|
.unwrap();
|
||||||
|
(
|
||||||
|
provider.to_string(),
|
||||||
|
compliance_core::csaf_ingest::parse(&doc).unwrap(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn device(order_number: &str, firmware: &str) -> SbomEntry {
|
||||||
|
let device = compliance_core::models::PlcDevice::new(order_number, firmware, None).unwrap();
|
||||||
|
crate::pipeline::sbom::devices::entries(&[device.into()], "t").remove(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_device_matches_the_advisories_naming_its_order_number_and_firmware() {
|
||||||
|
let advisories = vec![siemens_advisory(ORDER_NUMBER_PROVIDER)];
|
||||||
|
let mut entries = vec![
|
||||||
|
device("6es7511-1ak02-0ab0", "V3.1.4"),
|
||||||
|
device("6ES7511-1AK02-0AB0", "3.1.5"),
|
||||||
|
device("6ES7513-1AL02-0AB0", "2.9.7"),
|
||||||
|
device("6ES7512-1DK01-0AB0", "1.0"),
|
||||||
|
];
|
||||||
|
let mut alerts = Vec::new();
|
||||||
|
|
||||||
|
let matched = apply("t", &mut entries, &advisories, &mut alerts);
|
||||||
|
|
||||||
|
// Below the fixed firmware, and in an advisory for every version; not
|
||||||
|
// at the fixed firmware, and not a CPU the advisory does not name.
|
||||||
|
assert_eq!(matched, 2);
|
||||||
|
let affected: Vec<(&str, &str)> = alerts
|
||||||
|
.iter()
|
||||||
|
.map(|a| (a.affected_package.as_str(), a.affected_version.as_str()))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(
|
||||||
|
affected,
|
||||||
|
[("6ES7511-1AK02-0AB0", "3.1.4")],
|
||||||
|
"one alert per CVE"
|
||||||
|
);
|
||||||
|
let alert = &alerts[0];
|
||||||
|
assert_eq!(alert.cve_id, "CVE-2026-90101");
|
||||||
|
assert_eq!(alert.fixed_versions, ["3.1.5"]);
|
||||||
|
assert_eq!(alert.severity.as_deref(), Some("HIGH"));
|
||||||
|
let advisory = &alert.advisories[0];
|
||||||
|
assert_eq!(advisory.id, "SSA-900001");
|
||||||
|
assert!(advisory
|
||||||
|
.remediation
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(|r| r.contains("Update to V3.1.5")));
|
||||||
|
assert!(entries[2]
|
||||||
|
.known_vulnerabilities
|
||||||
|
.iter()
|
||||||
|
.any(|v| v.id == "CVE-2026-90101"));
|
||||||
|
assert!(entries[1].known_vulnerabilities.is_empty());
|
||||||
|
assert!(entries[3].known_vulnerabilities.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_device_is_matched_only_against_the_vendor_of_its_order_number() {
|
||||||
|
let advisories = vec![siemens_advisory("codesys"), siemens_advisory("supplier:x")];
|
||||||
|
let mut entries = vec![device("6ES7511-1AK02-0AB0", "3.1.4")];
|
||||||
|
let mut alerts = Vec::new();
|
||||||
|
assert_eq!(apply("t", &mut entries, &advisories, &mut alerts), 0);
|
||||||
|
|
||||||
|
// And a component with that name is not a device.
|
||||||
|
let named = SbomEntry::new(
|
||||||
|
"t".into(),
|
||||||
|
"Example S7-1500 CPU 1511-1 PN (6ES7511-1AK02-0AB0)".into(),
|
||||||
|
"3.1.4".into(),
|
||||||
|
"supplier-product".into(),
|
||||||
|
);
|
||||||
|
let advisories = vec![siemens_advisory(ORDER_NUMBER_PROVIDER)];
|
||||||
|
assert_eq!(apply("t", &mut [named], &advisories, &mut alerts), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_index_is_asked_for_each_order_number_once() {
|
||||||
|
let entries = vec![
|
||||||
|
device("6ES7511-1AK02-0AB0", "3.1.4"),
|
||||||
|
device("6es7511-1ak02-0ab0", "3.1.5"),
|
||||||
|
];
|
||||||
|
assert_eq!(
|
||||||
|
wanted(&entries),
|
||||||
|
Wanted {
|
||||||
|
order_numbers: vec!["6ES7511-1AK02-0AB0".to_string()],
|
||||||
|
..Wanted::default()
|
||||||
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -565,6 +565,10 @@ const PURL_TYPES_WITHOUT_OSV: &[&str] = &["pkg:cocoapods/"];
|
|||||||
/// Whether `entry` belongs to a package manager OSV has no advisories for.
|
/// Whether `entry` belongs to a package manager OSV has no advisories for.
|
||||||
fn without_osv_advisories(entry: &SbomEntry) -> bool {
|
fn without_osv_advisories(entry: &SbomEntry) -> bool {
|
||||||
entry.package_manager == crate::pipeline::sbom::unity::UNITY_MANAGER
|
entry.package_manager == crate::pipeline::sbom::unity::UNITY_MANAGER
|
||||||
|
// A supplier SBOM's component without a purl (#1025): nothing else
|
||||||
|
// looks it up, so it is not checked rather than free of CVEs.
|
||||||
|
|| (entry.package_manager == crate::pipeline::sbom::supplied::SUPPLIER_MANAGER
|
||||||
|
&& entry.purl.is_none())
|
||||||
|| entry
|
|| entry
|
||||||
.purl
|
.purl
|
||||||
.as_deref()
|
.as_deref()
|
||||||
@@ -687,6 +691,40 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_supplier_sboms_components_are_matched_like_any_others() {
|
||||||
|
// #1025: the parts of a bought-in component, read from its
|
||||||
|
// supplier's CycloneDX SBOM, go through the same OSV lookup; one
|
||||||
|
// without a purl is reported as not checked, not as free of CVEs.
|
||||||
|
let (url, hits) = fake_osv().await;
|
||||||
|
let scanner = CveScanner::new(NetGuard::allow_private(), None)
|
||||||
|
.unwrap()
|
||||||
|
.with_osv_api(url);
|
||||||
|
let sbom = r#"{"bomFormat": "CycloneDX", "specVersion": "1.5", "components": [
|
||||||
|
{"type": "library", "name": "lodash", "version": "4.17.20",
|
||||||
|
"purl": "pkg:npm/lodash@4.17.20"},
|
||||||
|
{"type": "library", "name": "vendor-blob", "version": "2.0"}
|
||||||
|
]}"#;
|
||||||
|
let mut entries = crate::pipeline::sbom::supplied::parse_with_statements(
|
||||||
|
sbom.as_bytes(),
|
||||||
|
"t",
|
||||||
|
"pump.cdx.json",
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
.entries;
|
||||||
|
|
||||||
|
let lookup = scanner.scan_dependencies("t", &mut entries).await.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(hits.load(Ordering::SeqCst), 1);
|
||||||
|
assert_eq!(lookup.alerts.len(), 1);
|
||||||
|
assert_eq!(lookup.alerts[0].affected_package, "lodash");
|
||||||
|
assert_eq!(
|
||||||
|
lookup.alerts[0].purl.as_deref(),
|
||||||
|
Some("pkg:npm/lodash@4.17.20")
|
||||||
|
);
|
||||||
|
assert_eq!(lookup.unchecked, ["vendor-blob 2.0"]);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn yocto_recipes_are_left_to_nvd_not_asked_of_osv() {
|
async fn yocto_recipes_are_left_to_nvd_not_asked_of_osv() {
|
||||||
let (url, hits) = fake_osv().await;
|
let (url, hits) = fake_osv().await;
|
||||||
|
|||||||
@@ -3,9 +3,10 @@
|
|||||||
//! For a target from a managed git source (#439), every critical or high CVE
|
//! For a target from a managed git source (#439), every critical or high CVE
|
||||||
//! in its components becomes one issue per package and CVE, labelled like the
|
//! in its components becomes one issue per package and CVE, labelled like the
|
||||||
//! finding issues plus `cve`, with the fixed version where the advisory names
|
//! finding issues plus `cve`, with the fixed version where the advisory names
|
||||||
//! one. When a later complete scan no longer finds the CVE (the dependency was
|
//! one. When a later complete scan no longer finds the CVE, the issue stays
|
||||||
//! updated or removed), the issue is closed with a comment; when it comes back,
|
//! open and is told so once (#994): a CVE can disappear without a fix (other
|
||||||
//! it is reopened.
|
//! scan data, a changed identification), so a person checks and closes it.
|
||||||
|
//! When the CVE comes back, the next disappearance is told again.
|
||||||
//!
|
//!
|
||||||
//! An issue a person closed in Gitea (#953) stays closed while the scan still
|
//! An issue a person closed in Gitea (#953) stays closed while the scan still
|
||||||
//! finds its CVE: closing it was that person's call, and no VEX statement is
|
//! finds its CVE: closing it was that person's call, and no VEX statement is
|
||||||
@@ -96,6 +97,8 @@ pub(crate) struct CveIssueCounts {
|
|||||||
pub created: u32,
|
pub created: u32,
|
||||||
pub reopened: u32,
|
pub reopened: u32,
|
||||||
pub closed: u32,
|
pub closed: u32,
|
||||||
|
/// Open issues told that the scan no longer finds their CVE.
|
||||||
|
pub noted_gone: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The key a CVE issue is stored under (`TrackerIssue::finding_id`): one per
|
/// The key a CVE issue is stored under (`TrackerIssue::finding_id`): one per
|
||||||
@@ -165,7 +168,8 @@ fn issue_worthy(alert: &CveAlert, epss_percentile: Option<f64>) -> bool {
|
|||||||
/// its stored VEX statement
|
/// its stored VEX statement
|
||||||
/// ([`crate::pipeline::vex_lifecycle::attach_stored_vex`])
|
/// ([`crate::pipeline::vex_lifecycle::attach_stored_vex`])
|
||||||
/// * `complete` - whether every component was matched; only then is a CVE
|
/// * `complete` - whether every component was matched; only then is a CVE
|
||||||
/// that is missing from `alerts` known to be gone, and its issue closed
|
/// that is missing from `alerts` known to be gone, and its open issue told
|
||||||
|
/// so (once; it stays open)
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
///
|
///
|
||||||
@@ -203,6 +207,11 @@ pub(crate) async fn sync_cve_issues(
|
|||||||
match existing.get(key) {
|
match existing.get(key) {
|
||||||
// A person closed it in Gitea while the CVE is unchanged.
|
// A person closed it in Gitea while the CVE is unchanged.
|
||||||
Some(issue) if issue.closed_in_tracker.is_some() => {}
|
Some(issue) if issue.closed_in_tracker.is_some() => {}
|
||||||
|
// Found again after it was gone: a later disappearance is told
|
||||||
|
// again.
|
||||||
|
Some(issue) if issue.gone_noted_at.is_some() && !issue.status.is_closed() => {
|
||||||
|
note_gone(target.db, issue, false).await?;
|
||||||
|
}
|
||||||
Some(issue) if issue.status.is_closed() => {
|
Some(issue) if issue.status.is_closed() => {
|
||||||
let comment = "**Prüfwerk:** Bei der Prüfung erneut gefunden, daher wieder geöffnet.\n\nFound again by the scan, so reopened.";
|
let comment = "**Prüfwerk:** Bei der Prüfung erneut gefunden, daher wieder geöffnet.\n\nFound again by the scan, so reopened.";
|
||||||
if set_state(target, issue, comment, "open").await {
|
if set_state(target, issue, comment, "open").await {
|
||||||
@@ -242,10 +251,22 @@ pub(crate) async fn sync_cve_issues(
|
|||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let comment = "**Prüfwerk:** Die Prüfung findet diese Schwachstelle nicht mehr: Die Abhängigkeit wurde aktualisiert oder entfernt.\n\nThe scan no longer finds this vulnerability: the dependency was updated or removed.";
|
if issue.gone_noted_at.is_some() {
|
||||||
if set_state(target, issue, comment, "closed").await {
|
continue;
|
||||||
record(target.db, issue, IssueStatus::Closed).await?;
|
}
|
||||||
counts.closed += 1;
|
let number = issue.external_id.as_str();
|
||||||
|
match target
|
||||||
|
.tracker
|
||||||
|
.add_comment(target.owner, target.repo, number, GONE_COMMENT)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(()) => {
|
||||||
|
note_gone(target.db, issue, true).await?;
|
||||||
|
counts.noted_gone += 1;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(issue = number, error = %e, "could not comment on the CVE issue");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -445,10 +466,6 @@ fn issue_body(alert: &CveAlert, severity: &str, target_id: &str, dashboard: &str
|
|||||||
.push_str("- Behoben in / Fixed in: keine Version bekannt / no fixed version known\n"),
|
.push_str("- Behoben in / Fixed in: keine Version bekannt / no fixed version known\n"),
|
||||||
fixed => body.push_str(&format!("- Behoben in / Fixed in: {}\n", fixed.join(", "))),
|
fixed => body.push_str(&format!("- Behoben in / Fixed in: {}\n", fixed.join(", "))),
|
||||||
}
|
}
|
||||||
body.push_str(&format!(
|
|
||||||
"- Advisory: https://osv.dev/vulnerability/{}\n",
|
|
||||||
alert.cve_id
|
|
||||||
));
|
|
||||||
if alert
|
if alert
|
||||||
.exploitation
|
.exploitation
|
||||||
.as_ref()
|
.as_ref()
|
||||||
@@ -460,14 +477,8 @@ fn issue_body(alert: &CveAlert, severity: &str, target_id: &str, dashboard: &str
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
body.push_str("\n### CRA\n\n");
|
body.push_str("\n### CRA\n\n");
|
||||||
let map = control_map::ControlMap::cra().ok();
|
for requirement in crate::pipeline::issue_creation::cra_requirements(&CVE_CONTROLS) {
|
||||||
for id in CVE_CONTROLS {
|
body.push_str(&format!("- {requirement}\n"));
|
||||||
let title = map
|
|
||||||
.as_ref()
|
|
||||||
.and_then(|m| m.coverage(id))
|
|
||||||
.map(|c| c.title.clone())
|
|
||||||
.unwrap_or_default();
|
|
||||||
body.push_str(&format!("- {id} — {title} (Annex I)\n"));
|
|
||||||
}
|
}
|
||||||
let dashboard = dashboard.trim_end_matches('/');
|
let dashboard = dashboard.trim_end_matches('/');
|
||||||
if dashboard.starts_with("https://") {
|
if dashboard.starts_with("https://") {
|
||||||
@@ -505,6 +516,27 @@ async fn set_state(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The comment an open issue gets once when a complete scan no longer finds
|
||||||
|
/// its CVE. It stays open: that the CVE is gone is no proof of a fix (#994).
|
||||||
|
const GONE_COMMENT: &str = "**Prüfwerk:** Die Prüfung findet diese Schwachstelle nicht mehr. Das allein belegt keine Behebung: Bitte prüfen Sie, ob sie behoben ist, und schließen Sie das Issue dann selbst. In Prüfwerk können Sie dazu den VEX-Status \"Behoben\" mit Begründung setzen.\n\nThe scan no longer finds this vulnerability. That alone does not prove a fix: please check whether it is fixed and close the issue yourself. In Prüfwerk you can set the VEX status \"fixed\" with a reason.";
|
||||||
|
|
||||||
|
/// Store that `issue` was told its CVE is gone (`gone`), or that the CVE was
|
||||||
|
/// found again.
|
||||||
|
async fn note_gone(db: &Database, issue: &TrackerIssue, gone: bool) -> Result<(), AgentError> {
|
||||||
|
let Some(id) = issue.id else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
let update = if gone {
|
||||||
|
doc! { "$set": { "gone_noted_at": mongodb::bson::DateTime::now() } }
|
||||||
|
} else {
|
||||||
|
doc! { "$unset": { "gone_noted_at": "" } }
|
||||||
|
};
|
||||||
|
db.tracker_issues()
|
||||||
|
.update_one(doc! { "_id": id }, update)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Store an issue's new state.
|
/// Store an issue's new state.
|
||||||
async fn record(
|
async fn record(
|
||||||
db: &Database,
|
db: &Database,
|
||||||
@@ -719,7 +751,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn severe_cves_open_issues_that_close_when_the_dependency_is_fixed() {
|
async fn severe_cves_open_issues_a_person_closes_once_the_cve_is_gone() {
|
||||||
let uri = std::env::var("TEST_MONGODB_URI")
|
let uri = std::env::var("TEST_MONGODB_URI")
|
||||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||||
let prefix = format!(
|
let prefix = format!(
|
||||||
@@ -767,7 +799,8 @@ mod tests {
|
|||||||
// pruefwerk (1), cra:annex-i (2), severity:high (4), cve (7).
|
// pruefwerk (1), cra:annex-i (2), severity:high (4), cve (7).
|
||||||
assert!(calls[0].ends_with("labels=[1,2,4,7]"), "{}", calls[0]);
|
assert!(calls[0].ends_with("labels=[1,2,4,7]"), "{}", calls[0]);
|
||||||
assert!(calls[1].contains("Fixed in: 4.9.2"));
|
assert!(calls[1].contains("Fixed in: 4.9.2"));
|
||||||
assert!(calls[1].contains("cra-ai-22"));
|
assert!(calls[1].contains("Bekannte Schwachstellen in Komponenten"));
|
||||||
|
assert!(!calls[1].contains("cra-ai-22"));
|
||||||
assert!(calls[1].contains("https://pruefwerk.example/targets/target-1"));
|
assert!(calls[1].contains("https://pruefwerk.example/targets/target-1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -783,30 +816,50 @@ mod tests {
|
|||||||
CveIssueCounts::default()
|
CveIssueCounts::default()
|
||||||
);
|
);
|
||||||
|
|
||||||
// The dependency is updated: the complete scan finds it no more.
|
// The complete scan finds it no more: the issue is told so once and
|
||||||
|
// stays open, since a CVE that is gone is no proof of a fix (#994).
|
||||||
|
let noted = CveIssueCounts {
|
||||||
|
noted_gone: 1,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
sync_cve_issues(&target, &[minor], true).await.unwrap(),
|
sync_cve_issues(&target, std::slice::from_ref(&minor), true)
|
||||||
CveIssueCounts {
|
.await
|
||||||
closed: 1,
|
.unwrap(),
|
||||||
..Default::default()
|
noted
|
||||||
}
|
|
||||||
);
|
);
|
||||||
|
{
|
||||||
|
let calls = calls.lock().unwrap();
|
||||||
|
let last = calls.last().unwrap();
|
||||||
|
assert!(
|
||||||
|
last.starts_with("comment 100: ") && last.contains("no longer finds"),
|
||||||
|
"{last}"
|
||||||
|
);
|
||||||
|
assert!(calls.iter().all(|c| !c.starts_with("state ")), "{calls:?}");
|
||||||
|
}
|
||||||
|
let sent = calls.lock().unwrap().len();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
calls.lock().unwrap().last().unwrap(),
|
sync_cve_issues(&target, std::slice::from_ref(&minor), true)
|
||||||
"state 100: \"closed\""
|
.await
|
||||||
|
.unwrap(),
|
||||||
|
CveIssueCounts::default(),
|
||||||
|
"told once"
|
||||||
);
|
);
|
||||||
|
assert_eq!(calls.lock().unwrap().len(), sent);
|
||||||
|
|
||||||
// It comes back: reopened, not opened twice.
|
// It comes back: the issue is still open, so nothing is sent; gone
|
||||||
|
// again, it is told again.
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
sync_cve_issues(&target, std::slice::from_ref(&okhttp), true)
|
sync_cve_issues(&target, std::slice::from_ref(&okhttp), true)
|
||||||
.await
|
.await
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
CveIssueCounts {
|
CveIssueCounts::default()
|
||||||
reopened: 1,
|
|
||||||
..Default::default()
|
|
||||||
}
|
|
||||||
);
|
);
|
||||||
assert_eq!(calls.lock().unwrap().last().unwrap(), "state 100: \"open\"");
|
assert_eq!(calls.lock().unwrap().len(), sent);
|
||||||
|
assert_eq!(sync_cve_issues(&target, &[], true).await.unwrap(), noted);
|
||||||
|
sync_cve_issues(&target, std::slice::from_ref(&okhttp), true)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
// A person closes it in Gitea (#953): the scan that still finds the
|
// A person closes it in Gitea (#953): the scan that still finds the
|
||||||
// CVE leaves it closed and sends nothing.
|
// CVE leaves it closed and sends nothing.
|
||||||
@@ -997,6 +1050,55 @@ mod tests {
|
|||||||
pool.drop_tenant("cve-issues-vex").await.ok();
|
pool.drop_tenant("cve-issues-vex").await.ok();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_cve_gone_from_the_scan_is_never_closed_as_vex_fixed() {
|
||||||
|
let Some((pool, db)) = test_db("cve-issues-gone").await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let calls: Calls = Arc::default();
|
||||||
|
let tracker = tracker_at(fake_gitea(calls.clone()).await);
|
||||||
|
let target = vex_target(&db, &tracker, IssueAutoclose::On);
|
||||||
|
// The `fixed` scans inferred from a CVE no longer found (#994).
|
||||||
|
let mut log4j = alert("log4j-core", "2.14.1", "CVE-2021-44228", "CRITICAL");
|
||||||
|
log4j.vex = Some(VexAssessment {
|
||||||
|
by: "pruefwerk-scan".into(),
|
||||||
|
by_scan: true,
|
||||||
|
..vex(VexStatus::Fixed)
|
||||||
|
});
|
||||||
|
|
||||||
|
// Reported with it: no statement, so the issue opens.
|
||||||
|
let counts = sync_cve_issues(&target, std::slice::from_ref(&log4j), true)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
counts,
|
||||||
|
CveIssueCounts {
|
||||||
|
created: 1,
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// Gone: never closed, neither for being gone nor with a VEX status;
|
||||||
|
// the issue is told once that the scan no longer finds the CVE.
|
||||||
|
assert_eq!(
|
||||||
|
sync_cve_issues(&target, &[], true).await.unwrap(),
|
||||||
|
CveIssueCounts {
|
||||||
|
noted_gone: 1,
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
);
|
||||||
|
{
|
||||||
|
let calls = calls.lock().unwrap();
|
||||||
|
assert!(calls.iter().all(|c| !c.starts_with("state ")), "{calls:?}");
|
||||||
|
assert!(
|
||||||
|
calls.iter().any(|c| c.contains("no longer finds")),
|
||||||
|
"{calls:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
pool.drop_tenant("cve-issues-gone").await.ok();
|
||||||
|
}
|
||||||
|
|
||||||
/// Log lines written while the returned guard lives (on this thread; a
|
/// Log lines written while the returned guard lives (on this thread; a
|
||||||
/// `#[tokio::test]` runs on one).
|
/// `#[tokio::test]` runs on one).
|
||||||
fn capture_logs() -> (Arc<Mutex<Vec<u8>>>, tracing::subscriber::DefaultGuard) {
|
fn capture_logs() -> (Arc<Mutex<Vec<u8>>>, tracing::subscriber::DefaultGuard) {
|
||||||
|
|||||||
@@ -47,7 +47,6 @@ pub async fn notify_new_cves(
|
|||||||
);
|
);
|
||||||
notification.cvss_score = alert.cvss_score;
|
notification.cvss_score = alert.cvss_score;
|
||||||
notification.summary = alert.summary.clone();
|
notification.summary = alert.summary.clone();
|
||||||
notification.url = Some(format!("https://osv.dev/vulnerability/{}", alert.cve_id));
|
|
||||||
let notification = match mongodb::bson::to_bson(¬ification) {
|
let notification = match mongodb::bson::to_bson(¬ification) {
|
||||||
Ok(n) => n,
|
Ok(n) => n,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
|
|||||||
@@ -0,0 +1,197 @@
|
|||||||
|
//! DAST findings as findings of the target they were found on (#998), so they
|
||||||
|
//! carry control refs and reach the findings list, the issue tracker and the
|
||||||
|
//! evidence pack like every other finding. The request and response evidence
|
||||||
|
//! stays with the DAST finding.
|
||||||
|
|
||||||
|
use compliance_core::models::dast::DastFinding;
|
||||||
|
use compliance_core::models::{Finding, ScanType};
|
||||||
|
|
||||||
|
use super::dedup;
|
||||||
|
use crate::import::{control_refs, normalise_cwe};
|
||||||
|
|
||||||
|
/// The scanner name DAST findings are stored under.
|
||||||
|
pub const SCANNER: &str = "dast";
|
||||||
|
|
||||||
|
/// The finding of target `repo_id` that `dast` stands for.
|
||||||
|
///
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// * `repo_id` - the target the DAST target belongs to
|
||||||
|
/// * `dast` - the finding as the DAST scan reported it
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// A finding with a fingerprint that is the same for the same weakness at the
|
||||||
|
/// same endpoint, method and parameter in every scan (so a later scan finds it
|
||||||
|
/// again instead of adding it twice), the CWE normalised, and the control refs
|
||||||
|
/// that CWE is evidence for. The endpoint goes into the description, since a
|
||||||
|
/// DAST finding has no file.
|
||||||
|
pub fn as_finding(repo_id: &str, dast: &DastFinding) -> Finding {
|
||||||
|
let fingerprint =
|
||||||
|
dedup::compute_fingerprint(&[repo_id, SCANNER, &dedup::compute_dast_fingerprint(dast)]);
|
||||||
|
let parameter = dast
|
||||||
|
.parameter
|
||||||
|
.as_deref()
|
||||||
|
.map(|p| format!(", parameter `{p}`"))
|
||||||
|
.unwrap_or_default();
|
||||||
|
let description = format!(
|
||||||
|
"{}\n\nFound by DAST at {} {}{parameter}.",
|
||||||
|
dast.description, dast.method, dast.endpoint
|
||||||
|
);
|
||||||
|
let mut finding = Finding::new(
|
||||||
|
repo_id.to_string(),
|
||||||
|
fingerprint,
|
||||||
|
SCANNER.to_string(),
|
||||||
|
ScanType::Dast,
|
||||||
|
dast.title.clone(),
|
||||||
|
description,
|
||||||
|
dast.severity.clone(),
|
||||||
|
);
|
||||||
|
finding.rule_id = Some(format!("dast-{}", dast.vuln_type));
|
||||||
|
finding.cwe = dast.cwe.as_deref().and_then(normalise_cwe);
|
||||||
|
finding.control_refs = finding.cwe.as_deref().map(control_refs).unwrap_or_default();
|
||||||
|
finding.remediation = dast.remediation.clone();
|
||||||
|
finding
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The code finding `dast` is linked to (#998): the one finding in `code`
|
||||||
|
/// with the same CWE, so the DAST finding shows the file and line its
|
||||||
|
/// weakness is likely in.
|
||||||
|
///
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// * `dast` - the finding the DAST scan reported
|
||||||
|
/// * `code` - the target's open findings that have a place in the code
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// That finding's id, or `None` when `dast` has no CWE, or no finding or
|
||||||
|
/// several share it: a CWE alone does not say which of several it is.
|
||||||
|
pub fn linked_code_finding(dast: &DastFinding, code: &[Finding]) -> Option<String> {
|
||||||
|
let cwe = dast.cwe.as_deref().and_then(normalise_cwe)?;
|
||||||
|
let mut same = code
|
||||||
|
.iter()
|
||||||
|
.filter(|f| f.cwe.as_deref().and_then(normalise_cwe).as_deref() == Some(cwe.as_str()));
|
||||||
|
let only = same.next()?;
|
||||||
|
if same.next().is_some() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
only.id.map(|id| id.to_hex())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use compliance_core::models::dast::DastVulnType;
|
||||||
|
use compliance_core::models::Severity;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn dast(endpoint: &str, parameter: Option<&str>) -> DastFinding {
|
||||||
|
let mut f = DastFinding::new(
|
||||||
|
"run-1".into(),
|
||||||
|
"dast-target-1".into(),
|
||||||
|
DastVulnType::CorsMisconfiguration,
|
||||||
|
"CORS misconfiguration allows arbitrary origins".into(),
|
||||||
|
"The server allows any origin.".into(),
|
||||||
|
Severity::Medium,
|
||||||
|
endpoint.into(),
|
||||||
|
"GET".into(),
|
||||||
|
);
|
||||||
|
f.cwe = Some("cwe-942".into());
|
||||||
|
f.parameter = parameter.map(str::to_string);
|
||||||
|
f.remediation = Some("Allow only trusted origins.".into());
|
||||||
|
f
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_dast_finding_becomes_a_finding_of_the_target() {
|
||||||
|
let finding = as_finding("target-1", &dast("https://app.example.com/", None));
|
||||||
|
|
||||||
|
assert_eq!(finding.repo_id, "target-1");
|
||||||
|
assert_eq!(finding.scanner, "dast");
|
||||||
|
assert_eq!(finding.scan_type, ScanType::Dast);
|
||||||
|
assert_eq!(
|
||||||
|
finding.rule_id.as_deref(),
|
||||||
|
Some("dast-cors_misconfiguration")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
finding.title,
|
||||||
|
"CORS misconfiguration allows arbitrary origins"
|
||||||
|
);
|
||||||
|
assert_eq!(finding.severity, Severity::Medium);
|
||||||
|
assert_eq!(finding.cwe.as_deref(), Some("CWE-942"));
|
||||||
|
assert_eq!(finding.control_refs, ["cra-ai-1"]);
|
||||||
|
assert!(finding
|
||||||
|
.description
|
||||||
|
.ends_with("Found by DAST at GET https://app.example.com/."));
|
||||||
|
assert_eq!(
|
||||||
|
finding.remediation.as_deref(),
|
||||||
|
Some("Allow only trusted origins.")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_same_weakness_keeps_its_fingerprint_and_others_get_their_own() {
|
||||||
|
let first = as_finding("target-1", &dast("https://app.example.com/", None));
|
||||||
|
let again = as_finding("target-1", &dast("https://app.example.com", None));
|
||||||
|
let elsewhere = as_finding("target-1", &dast("https://app.example.com/login", None));
|
||||||
|
let other_target = as_finding("target-2", &dast("https://app.example.com/", None));
|
||||||
|
let with_parameter = as_finding("target-1", &dast("https://app.example.com/", Some("q")));
|
||||||
|
|
||||||
|
assert_eq!(first.fingerprint, again.fingerprint);
|
||||||
|
for other in [&elsewhere, &other_target, &with_parameter] {
|
||||||
|
assert_ne!(first.fingerprint, other.fingerprint);
|
||||||
|
}
|
||||||
|
assert!(with_parameter.description.contains("parameter `q`"));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn code_finding(cwe: &str) -> Finding {
|
||||||
|
let mut f = Finding::new(
|
||||||
|
"target-1".into(),
|
||||||
|
format!("fp-{cwe}"),
|
||||||
|
"semgrep".into(),
|
||||||
|
ScanType::Sast,
|
||||||
|
"Permissive CORS".into(),
|
||||||
|
"Any origin is allowed.".into(),
|
||||||
|
Severity::Medium,
|
||||||
|
);
|
||||||
|
f.id = Some(mongodb::bson::oid::ObjectId::new());
|
||||||
|
f.cwe = Some(cwe.into());
|
||||||
|
f.file_path = Some("src/server.rs".into());
|
||||||
|
f
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_dast_finding_links_the_one_code_finding_with_its_cwe() {
|
||||||
|
let cors = code_finding("CWE-942");
|
||||||
|
let code = [code_finding("CWE-79"), cors.clone()];
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
linked_code_finding(&dast("https://app.example.com/", None), &code),
|
||||||
|
cors.id.map(|id| id.to_hex())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn no_link_without_a_cwe_or_with_several_candidates() {
|
||||||
|
let finding = dast("https://app.example.com/", None);
|
||||||
|
let mut no_cwe = finding.clone();
|
||||||
|
no_cwe.cwe = None;
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
linked_code_finding(&finding, &[code_finding("CWE-79")]),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
linked_code_finding(&no_cwe, &[code_finding("CWE-942")]),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
linked_code_finding(
|
||||||
|
&finding,
|
||||||
|
&[code_finding("cwe-942"), code_finding("CWE-942")]
|
||||||
|
),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,9 @@ use super::orchestrator::{GraphContext, PipelineOrchestrator};
|
|||||||
use super::plc::PlcFile;
|
use super::plc::PlcFile;
|
||||||
use crate::error::AgentError;
|
use crate::error::AgentError;
|
||||||
|
|
||||||
|
/// How long the DAST stage waits for one target's scan.
|
||||||
|
const DAST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20 * 60);
|
||||||
|
|
||||||
/// The most nodes a graph build parses.
|
/// The most nodes a graph build parses.
|
||||||
const GRAPH_MAX_NODES: u32 = 50_000;
|
const GRAPH_MAX_NODES: u32 = 50_000;
|
||||||
|
|
||||||
@@ -105,8 +108,15 @@ impl PipelineOrchestrator {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Trigger DAST scan if a target is configured for this repo
|
/// The DAST stage: scan every DAST target of `repo_id` and wait for the
|
||||||
pub(super) async fn maybe_trigger_dast(&self, repo_id: &str, scan_run_id: &str) {
|
/// scans (#998). A scan that does not complete is recorded as the `dast`
|
||||||
|
/// stage with [`SkipCode::ToolFailed`](compliance_core::models::SkipCode);
|
||||||
|
/// it fails the stage, not the run.
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// How many findings the DAST scans added to the target's findings.
|
||||||
|
pub(super) async fn maybe_trigger_dast(&self, repo_id: &str, scan_run_id: &str) -> u32 {
|
||||||
use futures_util::TryStreamExt;
|
use futures_util::TryStreamExt;
|
||||||
|
|
||||||
if self.source_only() {
|
if self.source_only() {
|
||||||
@@ -115,45 +125,151 @@ impl PipelineOrchestrator {
|
|||||||
compliance_core::models::SkippedStage::feature_disabled("dast"),
|
compliance_core::models::SkippedStage::feature_disabled("dast"),
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
return;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
let filter = mongodb::bson::doc! { "repo_id": repo_id };
|
let filter = mongodb::bson::doc! { "repo_id": repo_id };
|
||||||
let targets: Vec<compliance_core::models::DastTarget> =
|
let targets: Vec<compliance_core::models::DastTarget> =
|
||||||
match self.db.dast_targets().find(filter).await {
|
match self.db.dast_targets().find(filter).await {
|
||||||
Ok(cursor) => cursor.try_collect().await.unwrap_or_default(),
|
Ok(cursor) => cursor.try_collect().await.unwrap_or_default(),
|
||||||
Err(_) => return,
|
Err(_) => return 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
if targets.is_empty() {
|
if targets.is_empty() {
|
||||||
tracing::info!("[{repo_id}] No DAST targets configured, skipping");
|
tracing::info!("[{repo_id}] No DAST targets configured, skipping");
|
||||||
return;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
for target in targets {
|
let mut new_count = 0;
|
||||||
let db = self.db.clone();
|
for mut target in targets {
|
||||||
let scan_run_id = scan_run_id.to_string();
|
self.secrets.open_in_place(&mut target);
|
||||||
let net_guard = self.net_guard;
|
match self.run_dast_target(&target, repo_id, scan_run_id).await {
|
||||||
tokio::spawn(async move {
|
Ok(added) => new_count += added,
|
||||||
let orchestrator = compliance_dast::DastOrchestrator::new(100, net_guard);
|
Err(failed) => self.skip_stage(scan_run_id, failed).await,
|
||||||
match orchestrator.run_scan(&target, Vec::new()).await {
|
}
|
||||||
Ok((mut scan_run, findings)) => {
|
}
|
||||||
scan_run.sast_scan_run_id = Some(scan_run_id);
|
new_count
|
||||||
if let Err(e) = db.dast_scan_runs().insert_one(&scan_run).await {
|
}
|
||||||
tracing::error!("Failed to store DAST scan run: {e}");
|
|
||||||
}
|
/// Scan one DAST target, waiting for the result (#998), and store the
|
||||||
for finding in &findings {
|
/// scan run and its findings: as DAST findings, with their evidence, and
|
||||||
if let Err(e) = db.dast_findings().insert_one(finding).await {
|
/// as findings of the target `repo_id`.
|
||||||
tracing::error!("Failed to store DAST finding: {e}");
|
///
|
||||||
}
|
/// # Returns
|
||||||
}
|
///
|
||||||
tracing::info!("DAST scan complete: {} findings", findings.len());
|
/// How many findings the target did not have yet.
|
||||||
}
|
///
|
||||||
Err(e) => {
|
/// # Errors
|
||||||
tracing::error!("DAST scan failed: {e}");
|
///
|
||||||
}
|
/// The `dast` stage entry to record when the scan did not complete: it
|
||||||
}
|
/// failed, timed out, or its run could not be stored. The error itself
|
||||||
});
|
/// goes to the log only.
|
||||||
|
async fn run_dast_target(
|
||||||
|
&self,
|
||||||
|
target: &compliance_core::models::DastTarget,
|
||||||
|
repo_id: &str,
|
||||||
|
scan_run_id: &str,
|
||||||
|
) -> Result<u32, compliance_core::models::SkippedStage> {
|
||||||
|
use compliance_core::models::{DastScanStatus, SkipCode, SkippedStage};
|
||||||
|
|
||||||
|
// The subject names the tool, as for the other stages: the dashboard
|
||||||
|
// reads it as "DAST did not complete". The log names the target.
|
||||||
|
let failed = |reason: &str| {
|
||||||
|
Err(SkippedStage::new("dast", SkipCode::ToolFailed, reason).about("DAST"))
|
||||||
|
};
|
||||||
|
let orchestrator = compliance_dast::DastOrchestrator::new(100, self.net_guard);
|
||||||
|
let scan = tokio::time::timeout(DAST_TIMEOUT, orchestrator.run_scan(target, Vec::new()));
|
||||||
|
let (mut run, mut findings) = match scan.await {
|
||||||
|
Ok(Ok(result)) => result,
|
||||||
|
Ok(Err(e)) => {
|
||||||
|
tracing::error!(target = %target.name, "DAST scan failed: {e}");
|
||||||
|
return failed("DAST did not complete");
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
tracing::error!(target = %target.name, "DAST scan timed out");
|
||||||
|
return failed("DAST did not complete in time");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
run.sast_scan_run_id = Some(scan_run_id.to_string());
|
||||||
|
if let Err(e) = self.db.dast_scan_runs().insert_one(&run).await {
|
||||||
|
tracing::error!("Failed to store DAST scan run: {e}");
|
||||||
|
return failed("DAST results could not be stored");
|
||||||
|
}
|
||||||
|
let code = self.open_code_findings(repo_id).await;
|
||||||
|
let mut new_count = 0;
|
||||||
|
for finding in &mut findings {
|
||||||
|
finding.linked_sast_finding_id =
|
||||||
|
super::dast_findings::linked_code_finding(finding, &code);
|
||||||
|
if let Err(e) = self.db.dast_findings().insert_one(&*finding).await {
|
||||||
|
tracing::error!("Failed to store DAST finding: {e}");
|
||||||
|
}
|
||||||
|
match self.add_dast_finding(repo_id, scan_run_id, finding).await {
|
||||||
|
Ok(added) => new_count += u32::from(added),
|
||||||
|
Err(e) => tracing::error!("Failed to store DAST finding as a finding: {e}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tracing::info!(target = %target.name, findings = findings.len(), new = new_count, "DAST scan done");
|
||||||
|
if run.status == DastScanStatus::Failed {
|
||||||
|
// `error_message` is the scanner's English reason ("Login: ...",
|
||||||
|
// "Reconnaissance failed: ..."); the run keeps it in full.
|
||||||
|
tracing::warn!(target = %target.name, error = ?run.error_message, "DAST scan failed");
|
||||||
|
return failed("DAST did not complete");
|
||||||
|
}
|
||||||
|
Ok(new_count)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The open findings of target `repo_id` that have a place in the code and
|
||||||
|
/// a CWE: what a DAST finding can be linked to (#998). Empty when they
|
||||||
|
/// cannot be read (logged); the DAST findings are then stored unlinked.
|
||||||
|
async fn open_code_findings(&self, repo_id: &str) -> Vec<compliance_core::models::Finding> {
|
||||||
|
use futures_util::TryStreamExt;
|
||||||
|
|
||||||
|
let filter = mongodb::bson::doc! {
|
||||||
|
"repo_id": repo_id,
|
||||||
|
"scanner": { "$ne": super::dast_findings::SCANNER },
|
||||||
|
"file_path": { "$ne": null },
|
||||||
|
"cwe": { "$ne": null },
|
||||||
|
"status": { "$in": ["open", "triaged", "needs_review"] },
|
||||||
|
};
|
||||||
|
match self.db.findings().find(filter).await {
|
||||||
|
Ok(cursor) => cursor.try_collect().await.unwrap_or_else(|e| {
|
||||||
|
tracing::warn!("Code findings for DAST links not read: {e}");
|
||||||
|
Vec::new()
|
||||||
|
}),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!("Code findings for DAST links not read: {e}");
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Store `dast` as a finding of target `repo_id`, unless the target has
|
||||||
|
/// it already (the same fingerprint).
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// Whether it was new.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// The database's error.
|
||||||
|
async fn add_dast_finding(
|
||||||
|
&self,
|
||||||
|
repo_id: &str,
|
||||||
|
scan_run_id: &str,
|
||||||
|
dast: &compliance_core::models::DastFinding,
|
||||||
|
) -> Result<bool, mongodb::error::Error> {
|
||||||
|
let mut finding = super::dast_findings::as_finding(repo_id, dast);
|
||||||
|
finding.scan_run_id = Some(scan_run_id.to_string());
|
||||||
|
let known = self
|
||||||
|
.db
|
||||||
|
.findings()
|
||||||
|
.find_one(mongodb::bson::doc! { "fingerprint": &finding.fingerprint })
|
||||||
|
.await?
|
||||||
|
.is_some();
|
||||||
|
if !known {
|
||||||
|
self.db.findings().insert_one(&finding).await?;
|
||||||
|
}
|
||||||
|
Ok(!known)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -243,10 +243,11 @@ impl CveIssueSync<'_> {
|
|||||||
let counts =
|
let counts =
|
||||||
crate::pipeline::cve_issues::sync_cve_issues(&target, alerts, complete).await?;
|
crate::pipeline::cve_issues::sync_cve_issues(&target, alerts, complete).await?;
|
||||||
tracing::info!(
|
tracing::info!(
|
||||||
"[{repo_id}] CVE issues: {} opened, {} reopened, {} closed",
|
"[{repo_id}] CVE issues: {} opened, {} reopened, {} closed, {} told the CVE is gone",
|
||||||
counts.created,
|
counts.created,
|
||||||
counts.reopened,
|
counts.reopened,
|
||||||
counts.closed
|
counts.closed,
|
||||||
|
counts.noted_gone
|
||||||
);
|
);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -686,23 +687,18 @@ pub(super) fn format_issue_body(finding: &Finding) -> String {
|
|||||||
body
|
body
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The CRA requirements a finding is evidence for, as `cra-ai-8 — <title>`,
|
/// The CRA requirements a finding is evidence for, from its stamped
|
||||||
/// from its stamped `control_refs`. Titles come from the CRA control map.
|
/// `control_refs`, by the name a customer reads in both languages
|
||||||
fn cra_requirements(control_refs: &[String]) -> Vec<String> {
|
/// (`Keine Standardpasswörter / No default passwords (Annex I)`). An id
|
||||||
let map = control_map::ControlMap::cra().ok();
|
/// outside the 40 requirements stays as it is.
|
||||||
|
pub(crate) fn cra_requirements<S: AsRef<str>>(control_refs: &[S]) -> Vec<String> {
|
||||||
control_refs
|
control_refs
|
||||||
.iter()
|
.iter()
|
||||||
|
.map(AsRef::as_ref)
|
||||||
.filter(|id| id.starts_with("cra-"))
|
.filter(|id| id.starts_with("cra-"))
|
||||||
.map(|id| {
|
.map(|id| match compliance_core::cra_requirements::name(id) {
|
||||||
match map
|
Some(name) => format!("{} / {} (Annex I)", name.de, name.en),
|
||||||
.as_ref()
|
None => format!("{id} (Annex I)"),
|
||||||
.and_then(|m| m.coverage(id))
|
|
||||||
.map(|c| c.title.as_str())
|
|
||||||
.filter(|t| !t.is_empty())
|
|
||||||
{
|
|
||||||
Some(title) => format!("{id} — {title} (Annex I)"),
|
|
||||||
None => format!("{id} (Annex I)"),
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
@@ -736,9 +732,10 @@ mod tests {
|
|||||||
fn cra_requirements_name_the_control() {
|
fn cra_requirements_name_the_control() {
|
||||||
let refs = vec!["cra-ai-1".to_string(), "iec-x".to_string()];
|
let refs = vec!["cra-ai-1".to_string(), "iec-x".to_string()];
|
||||||
let lines = cra_requirements(&refs);
|
let lines = cra_requirements(&refs);
|
||||||
assert_eq!(lines.len(), 1);
|
assert_eq!(
|
||||||
assert!(lines[0].starts_with("cra-ai-1 — "), "{lines:?}");
|
lines,
|
||||||
assert!(lines[0].ends_with("(Annex I)"));
|
["Sichere Werkseinstellungen / Secure factory settings (Annex I)"]
|
||||||
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
cra_requirements(&["cra-unknown".to_string()]),
|
cra_requirements(&["cra-unknown".to_string()]),
|
||||||
["cra-unknown (Annex I)"]
|
["cra-unknown (Annex I)"]
|
||||||
@@ -760,7 +757,8 @@ mod tests {
|
|||||||
f.control_refs = vec!["cra-ai-1".into()];
|
f.control_refs = vec!["cra-ai-1".into()];
|
||||||
let body = format_issue_body(&f);
|
let body = format_issue_body(&f);
|
||||||
assert!(body.contains("**CWE:** CWE-89"));
|
assert!(body.contains("**CWE:** CWE-89"));
|
||||||
assert!(body.contains("**CRA:** cra-ai-1"));
|
assert!(body.contains("**CRA:** Sichere Werkseinstellungen / Secure factory settings"));
|
||||||
|
assert!(!body.contains("cra-ai-1"));
|
||||||
assert!(body.contains("`fp1`"));
|
assert!(body.contains("`fp1`"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ fn language_of(extension: &str) -> Option<&'static str> {
|
|||||||
"cs" => "csharp",
|
"cs" => "csharp",
|
||||||
"vb" => "vb",
|
"vb" => "vb",
|
||||||
"swift" => "swift",
|
"swift" => "swift",
|
||||||
|
"dart" => "dart",
|
||||||
// Objective-C; `.m` is also MATLAB's extension, which only means
|
// Objective-C; `.m` is also MATLAB's extension, which only means
|
||||||
// mobsfscan looks at a tree it finds nothing in.
|
// mobsfscan looks at a tree it finds nothing in.
|
||||||
"m" | "mm" => "objc",
|
"m" | "mm" => "objc",
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ pub mod cve;
|
|||||||
pub(crate) mod cve_enrichment;
|
pub(crate) mod cve_enrichment;
|
||||||
pub(crate) mod cve_issues;
|
pub(crate) mod cve_issues;
|
||||||
pub mod cve_notify;
|
pub mod cve_notify;
|
||||||
|
pub mod dast_findings;
|
||||||
pub mod dedup;
|
pub mod dedup;
|
||||||
pub mod devskim;
|
pub mod devskim;
|
||||||
pub mod dotnet;
|
pub mod dotnet;
|
||||||
|
|||||||
@@ -88,6 +88,21 @@ pub struct PipelineOrchestrator {
|
|||||||
pub(super) charged_as: Option<ScanTrigger>,
|
pub(super) charged_as: Option<ScanTrigger>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The package managers of the control-application SBOM the PLC scan stores
|
||||||
|
/// (`PipelineOrchestrator::persist_control_app_sbom`): CODESYS libraries and
|
||||||
|
/// runtime, and the Siemens devices the target runs on.
|
||||||
|
const CONTROL_APP_MANAGERS: [&str; 2] = ["codesys", crate::pipeline::sbom::devices::DEVICE_MANAGER];
|
||||||
|
|
||||||
|
/// Why a target with only a build output skips its code stages: what the
|
||||||
|
/// dashboard words from it (`coverage::reason`).
|
||||||
|
const NO_CODE_BUILD_OUTPUT: &str = "the target has no source code (a git repository or a \
|
||||||
|
source archive): only its build output is read; code analysis, the recipe inventory and \
|
||||||
|
the recipe lint need the code";
|
||||||
|
|
||||||
|
/// Why a target with only a supplier SBOM (#1025) skips its code stages.
|
||||||
|
const NO_CODE_SUPPLIER_SBOM: &str = "the target has no source code (a git repository or a \
|
||||||
|
source archive): only its supplier SBOM is read; code analysis needs the code";
|
||||||
|
|
||||||
impl PipelineOrchestrator {
|
impl PipelineOrchestrator {
|
||||||
pub fn new(config: AgentConfig, tenant_id: &str, db: Database, llm: Arc<LlmClient>) -> Self {
|
pub fn new(config: AgentConfig, tenant_id: &str, db: Database, llm: Arc<LlmClient>) -> Self {
|
||||||
let secrets = SecretBox::from_config(&config);
|
let secrets = SecretBox::from_config(&config);
|
||||||
@@ -144,6 +159,48 @@ impl PipelineOrchestrator {
|
|||||||
/// Add what the vendor advisories say about `entries` to `alerts`
|
/// Add what the vendor advisories say about `entries` to `alerts`
|
||||||
/// (#515). Best-effort: an index that cannot be read leaves them as
|
/// (#515). Best-effort: an index that cannot be read leaves them as
|
||||||
/// they are.
|
/// they are.
|
||||||
|
/// Match `entries` against the advisories of the supplier this target is
|
||||||
|
/// bought from (#1025), stored for this tenant only: the product itself
|
||||||
|
/// by name and version, and its components by purl.
|
||||||
|
async fn match_supplier_advisories(
|
||||||
|
&self,
|
||||||
|
repo: &RepoView,
|
||||||
|
target_id: &str,
|
||||||
|
entries: &mut [SbomEntry],
|
||||||
|
alerts: &mut Vec<CveAlert>,
|
||||||
|
) {
|
||||||
|
use crate::pipeline::csaf_match::AdvisoryIndex;
|
||||||
|
let Some(url) = repo
|
||||||
|
.supplier
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|s| s.csaf_provider.as_deref())
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
// The supplier's advisories name its product and components by name
|
||||||
|
// and purl; devices are matched against the vendor index instead.
|
||||||
|
let wanted = crate::pipeline::csaf_match::Wanted {
|
||||||
|
providers: vec![crate::pipeline::csaf_feed::supplier_key(url)],
|
||||||
|
purls: crate::pipeline::csaf_match::wanted(entries).purls,
|
||||||
|
order_numbers: Vec::new(),
|
||||||
|
};
|
||||||
|
let store = crate::pipeline::csaf_feed::MongoAdvisoryStore::supplier(self.db.inner());
|
||||||
|
match store.relevant(&wanted).await {
|
||||||
|
Ok(advisories) if advisories.is_empty() => {}
|
||||||
|
Ok(advisories) => {
|
||||||
|
let matched =
|
||||||
|
crate::pipeline::csaf_match::apply(target_id, entries, &advisories, alerts);
|
||||||
|
tracing::info!(
|
||||||
|
target_id,
|
||||||
|
advisories = advisories.len(),
|
||||||
|
matched,
|
||||||
|
"supplier CSAF advisories matched"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(e) => tracing::warn!(target_id, "supplier CSAF advisories not read: {e}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async fn match_advisories(
|
async fn match_advisories(
|
||||||
&self,
|
&self,
|
||||||
target_id: &str,
|
target_id: &str,
|
||||||
@@ -153,8 +210,8 @@ impl PipelineOrchestrator {
|
|||||||
let Some(index) = &self.advisory_index else {
|
let Some(index) = &self.advisory_index else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let (providers, purls) = crate::pipeline::csaf_match::wanted(entries);
|
let wanted = crate::pipeline::csaf_match::wanted(entries);
|
||||||
match index.relevant(&providers, &purls).await {
|
match index.relevant(&wanted).await {
|
||||||
Ok(advisories) if advisories.is_empty() => {}
|
Ok(advisories) if advisories.is_empty() => {}
|
||||||
Ok(advisories) => {
|
Ok(advisories) => {
|
||||||
let matched =
|
let matched =
|
||||||
@@ -538,7 +595,8 @@ impl PipelineOrchestrator {
|
|||||||
// the project's own code, which this deployment may not. Syft reports
|
// the project's own code, which this deployment may not. Syft reports
|
||||||
// nothing for it, so say so rather than leaving the gap in an SBOM that
|
// nothing for it, so say so rather than leaving the gap in an SBOM that
|
||||||
// looks complete.
|
// looks complete.
|
||||||
for eco in crate::pipeline::sbom::unlocked_ecosystems(&repo_path, &resolved_nuget) {
|
let unlocked = crate::pipeline::sbom::unlocked_ecosystems(&repo_path, &resolved_nuget);
|
||||||
|
for eco in &unlocked {
|
||||||
self.skip_stage(
|
self.skip_stage(
|
||||||
scan_run_id,
|
scan_run_id,
|
||||||
SkippedStage::new(
|
SkippedStage::new(
|
||||||
@@ -549,7 +607,7 @@ impl PipelineOrchestrator {
|
|||||||
eco.manifest, eco.problem, eco.remedy
|
eco.manifest, eco.problem, eco.remedy
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.about(eco.manifest),
|
.about(eco.manifest.clone()),
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
@@ -633,7 +691,22 @@ impl PipelineOrchestrator {
|
|||||||
&repo_id,
|
&repo_id,
|
||||||
));
|
));
|
||||||
let yocto_recipes = yocto.recipes;
|
let yocto_recipes = yocto.recipes;
|
||||||
for entry in embedded.into_iter().chain(codesys).chain(yocto_entries) {
|
let (mut supplied, supplier_statements) = self.read_supplier_sboms(repo, &repo_id).await?;
|
||||||
|
supplied.extend(
|
||||||
|
repo.supplier
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|s| crate::pipeline::sbom::supplied::product_entry(s, &repo_id)),
|
||||||
|
);
|
||||||
|
supplied.extend(crate::pipeline::sbom::devices::entries(
|
||||||
|
&repo.devices,
|
||||||
|
&repo_id,
|
||||||
|
));
|
||||||
|
for entry in embedded
|
||||||
|
.into_iter()
|
||||||
|
.chain(codesys)
|
||||||
|
.chain(yocto_entries)
|
||||||
|
.chain(supplied)
|
||||||
|
{
|
||||||
let known = sbom_entries
|
let known = sbom_entries
|
||||||
.iter()
|
.iter()
|
||||||
.any(|e| e.name.eq_ignore_ascii_case(&entry.name) && e.version == entry.version);
|
.any(|e| e.name.eq_ignore_ascii_case(&entry.name) && e.version == entry.version);
|
||||||
@@ -642,6 +715,49 @@ impl PipelineOrchestrator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Why the SBOM is empty or incomplete (#979): code with no manifest
|
||||||
|
// at all, and manifests whose dependencies were not resolved. Every
|
||||||
|
// code scan completes this check, so a finding closes at the next
|
||||||
|
// scan that finds the manifest or lockfile. A firmware SBOM, which
|
||||||
|
// the firmware step stored before this, counts as an SBOM.
|
||||||
|
let firmware_sbom = self
|
||||||
|
.db
|
||||||
|
.sbom_entries()
|
||||||
|
.count_documents(doc! {
|
||||||
|
"repo_id": &repo_id,
|
||||||
|
"package_manager": {
|
||||||
|
"$in": crate::pipeline::firmware_sbom::FIRMWARE_MANAGERS.to_vec()
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.limit(1)
|
||||||
|
.await?
|
||||||
|
> 0;
|
||||||
|
let (coverage, entries) = {
|
||||||
|
let (root, vendor, languages) = (repo_path.clone(), vendor.clone(), languages.clone());
|
||||||
|
let (target, yocto_layers) = (repo_id.clone(), repo.yocto_layers);
|
||||||
|
tokio::task::spawn_blocking(move || {
|
||||||
|
use crate::pipeline::sbom::coverage::{coverage_findings, ScannedTree};
|
||||||
|
let tree = ScannedTree {
|
||||||
|
repo_id: &target,
|
||||||
|
root: &root,
|
||||||
|
vendor: &vendor,
|
||||||
|
languages: &languages,
|
||||||
|
yocto_layers,
|
||||||
|
firmware_sbom,
|
||||||
|
};
|
||||||
|
(
|
||||||
|
coverage_findings(&tree, &sbom_entries, &unlocked),
|
||||||
|
sbom_entries,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|e| AgentError::Other(format!("SBOM coverage check: {e}")))?
|
||||||
|
};
|
||||||
|
sbom_entries = entries;
|
||||||
|
run_findings.completed(crate::pipeline::sbom::coverage::SCANNER);
|
||||||
|
all_findings.extend(coverage);
|
||||||
|
run_findings.save_new(&self.db, &mut all_findings).await?;
|
||||||
|
|
||||||
// Stage 3: CVE Scanning
|
// Stage 3: CVE Scanning
|
||||||
tracing::info!("[{repo_id}] Stage 3: CVE Scanning");
|
tracing::info!("[{repo_id}] Stage 3: CVE Scanning");
|
||||||
self.update_phase(scan_run_id, ScanPhase::CveScanning).await;
|
self.update_phase(scan_run_id, ScanPhase::CveScanning).await;
|
||||||
@@ -806,6 +922,10 @@ impl PipelineOrchestrator {
|
|||||||
|
|
||||||
self.match_advisories(&repo_id, &mut sbom_entries, &mut cve_alerts)
|
self.match_advisories(&repo_id, &mut sbom_entries, &mut cve_alerts)
|
||||||
.await;
|
.await;
|
||||||
|
self.match_supplier_advisories(repo, &repo_id, &mut sbom_entries, &mut cve_alerts)
|
||||||
|
.await;
|
||||||
|
// What the supplier states about each, beside the alert (#1025).
|
||||||
|
crate::pipeline::sbom::supplied::attach(&supplier_statements, &mut cve_alerts);
|
||||||
|
|
||||||
self.enrich_cves(&repo_id, &mut cve_alerts, &mut sbom_entries)
|
self.enrich_cves(&repo_id, &mut cve_alerts, &mut sbom_entries)
|
||||||
.await;
|
.await;
|
||||||
@@ -1719,7 +1839,7 @@ impl PipelineOrchestrator {
|
|||||||
if plan.has(ScanType::Dast) {
|
if plan.has(ScanType::Dast) {
|
||||||
self.update_phase(scan_run_id, ScanPhase::DastScanning)
|
self.update_phase(scan_run_id, ScanPhase::DastScanning)
|
||||||
.await;
|
.await;
|
||||||
self.maybe_trigger_dast(&target_id, scan_run_id).await;
|
new_count += self.maybe_trigger_dast(&target_id, scan_run_id).await;
|
||||||
}
|
}
|
||||||
return Ok(new_count);
|
return Ok(new_count);
|
||||||
}
|
}
|
||||||
@@ -1754,10 +1874,12 @@ impl PipelineOrchestrator {
|
|||||||
let mut repo = RepoView::from_target(target, code, &self.secrets);
|
let mut repo = RepoView::from_target(target, code, &self.secrets);
|
||||||
repo.yocto_layers = yocto_layers;
|
repo.yocto_layers = yocto_layers;
|
||||||
repo.build_outputs = build_output_paths(target, &working_paths);
|
repo.build_outputs = build_output_paths(target, &working_paths);
|
||||||
|
repo.supplier_sboms = supplier_sbom_paths(target, &working_paths);
|
||||||
let n = self.run_pipeline(&repo, scan_run_id, trigger).await?;
|
let n = self.run_pipeline(&repo, scan_run_id, trigger).await?;
|
||||||
self.finalize_target(target, &repo, n).await?;
|
self.finalize_target(target, &repo, n).await?;
|
||||||
new_count += n;
|
new_count += n;
|
||||||
self.dast_after_code_scan(&target_id, &plan, scan_run_id)
|
new_count += self
|
||||||
|
.dast_after_code_scan(&target_id, &plan, scan_run_id)
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
Some(code) => {
|
Some(code) => {
|
||||||
@@ -1770,11 +1892,13 @@ impl PipelineOrchestrator {
|
|||||||
let mut repo = RepoView::from_target(target, code, &self.secrets);
|
let mut repo = RepoView::from_target(target, code, &self.secrets);
|
||||||
repo.yocto_layers = yocto_layers;
|
repo.yocto_layers = yocto_layers;
|
||||||
repo.build_outputs = build_output_paths(target, &working_paths);
|
repo.build_outputs = build_output_paths(target, &working_paths);
|
||||||
|
repo.supplier_sboms = supplier_sbom_paths(target, &working_paths);
|
||||||
let upload = crate::pipeline::plc::sbom::uploaded_archive(code);
|
let upload = crate::pipeline::plc::sbom::uploaded_archive(code);
|
||||||
let n = self.scan_tree(tree, upload, &repo, scan_run_id).await?;
|
let n = self.scan_tree(tree, upload, &repo, scan_run_id).await?;
|
||||||
self.finalize_target(target, &repo, n).await?;
|
self.finalize_target(target, &repo, n).await?;
|
||||||
new_count += n;
|
new_count += n;
|
||||||
self.dast_after_code_scan(&target_id, &plan, scan_run_id)
|
new_count += self
|
||||||
|
.dast_after_code_scan(&target_id, &plan, scan_run_id)
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
// The ingest stage recorded why. A run over nothing must not
|
// The ingest stage recorded why. A run over nothing must not
|
||||||
@@ -1791,12 +1915,32 @@ impl PipelineOrchestrator {
|
|||||||
// Only what a build wrote about its image (an image SPDX archive,
|
// Only what a build wrote about its image (an image SPDX archive,
|
||||||
// a cve-check report): the same stages run over an empty tree, so
|
// a cve-check report): the same stages run over an empty tree, so
|
||||||
// the SBOM, CVEs and VEX come from the build output alone.
|
// the SBOM, CVEs and VEX come from the build output alone.
|
||||||
None if target.has(ArtifactKind::BuildOutput) => {
|
// Or only a supplier's SBOM of a bought-in component (#1025): the
|
||||||
|
// same, with the components read from it.
|
||||||
|
None if target.has(ArtifactKind::BuildOutput)
|
||||||
|
|| target.has(ArtifactKind::SupplierSbom) =>
|
||||||
|
{
|
||||||
new_count += self
|
new_count += self
|
||||||
.scan_build_output_only(target, &target_id, &working_paths, scan_run_id)
|
.scan_build_output_only(target, &target_id, &working_paths, scan_run_id)
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
|
// A control application known only by the Siemens controllers
|
||||||
|
// it runs on (SPS item 4a): they are its SBOM, matched against
|
||||||
|
// Siemens' advisories as with a project.
|
||||||
|
// Also when the last one was removed, so its components and
|
||||||
|
// alerts go with it.
|
||||||
|
let target_devices = target.target_devices();
|
||||||
|
if target.target_type == TargetType::PlcSps || !target_devices.is_empty() {
|
||||||
|
let devices =
|
||||||
|
crate::pipeline::sbom::devices::entries(&target_devices, &target_id);
|
||||||
|
if let Err(e) = self
|
||||||
|
.persist_control_app_sbom(target, &target_id, scan_run_id, devices)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
tracing::warn!(target_id = %target_id, error = %e, "device SBOM persist failed");
|
||||||
|
}
|
||||||
|
}
|
||||||
// No code to scan. DAST is attempted for a target the matrix
|
// No code to scan. DAST is attempted for a target the matrix
|
||||||
// plans it for, and for a migrated DAST target, which carries no
|
// plans it for, and for a migrated DAST target, which carries no
|
||||||
// artifacts at all and relies on its DastTarget row. Anywhere
|
// artifacts at all and relies on its DastTarget row. Anywhere
|
||||||
@@ -1810,7 +1954,7 @@ impl PipelineOrchestrator {
|
|||||||
);
|
);
|
||||||
self.update_phase(scan_run_id, ScanPhase::DastScanning)
|
self.update_phase(scan_run_id, ScanPhase::DastScanning)
|
||||||
.await;
|
.await;
|
||||||
self.maybe_trigger_dast(&target_id, scan_run_id).await;
|
new_count += self.maybe_trigger_dast(&target_id, scan_run_id).await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1864,6 +2008,12 @@ impl PipelineOrchestrator {
|
|||||||
// first, as in a code scan (#820, #825).
|
// first, as in a code scan (#820, #825).
|
||||||
let mut left_out = LeftOut::default();
|
let mut left_out = LeftOut::default();
|
||||||
for a in &sources {
|
for a in &sources {
|
||||||
|
// A TIA export's block code is not read yet (#1093): the run says
|
||||||
|
// what it holds instead of finding nothing in it.
|
||||||
|
if a.plc.as_ref().map(|p| p.format) == Some(PlcFormat::TiaExport) {
|
||||||
|
self.note_tia_export(scan_run_id, a).await;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
let Some(path) = ingest_set.get(&a.id).and_then(|ia| ia.working_path.clone()) else {
|
let Some(path) = ingest_set.get(&a.id).and_then(|ia| ia.working_path.clone()) else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
@@ -2008,6 +2158,10 @@ impl PipelineOrchestrator {
|
|||||||
.spawn(left_out_run.status_changed().to_vec());
|
.spawn(left_out_run.status_changed().to_vec());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
all_sbom.extend(crate::pipeline::sbom::devices::entries(
|
||||||
|
&target.target_devices(),
|
||||||
|
target_id,
|
||||||
|
));
|
||||||
if !all_sbom.is_empty() {
|
if !all_sbom.is_empty() {
|
||||||
if let Err(e) = self
|
if let Err(e) = self
|
||||||
.persist_control_app_sbom(target, target_id, scan_run_id, all_sbom)
|
.persist_control_app_sbom(target, target_id, scan_run_id, all_sbom)
|
||||||
@@ -2019,6 +2173,82 @@ impl PipelineOrchestrator {
|
|||||||
Ok(new_count)
|
Ok(new_count)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What a TIA export holds that this run does not analyse (#1090): its
|
||||||
|
/// blocks' code (until #1093), its know-how-protected blocks, and the
|
||||||
|
/// devices it names that cannot be matched against advisories. Its
|
||||||
|
/// matchable devices are in the SBOM through
|
||||||
|
/// [`compliance_core::models::OnboardedTarget::target_devices`].
|
||||||
|
async fn note_tia_export(&self, scan_run_id: &str, export: &Artifact) {
|
||||||
|
let name = export
|
||||||
|
.display_name
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| export.source_ref.clone());
|
||||||
|
let read = export
|
||||||
|
.stored_path
|
||||||
|
.as_deref()
|
||||||
|
.ok_or(compliance_core::models::TiaBundleError::NoManifest)
|
||||||
|
.and_then(|p| crate::pipeline::plc::tia::read_manifest(std::path::Path::new(p)));
|
||||||
|
let manifest = match read {
|
||||||
|
Ok(manifest) => manifest,
|
||||||
|
Err(e) => {
|
||||||
|
// Read at upload, so only a file lost since gets here.
|
||||||
|
tracing::warn!(scan_run_id, export = %name, error = %e, "TIA export not readable");
|
||||||
|
self.skip_stage(
|
||||||
|
scan_run_id,
|
||||||
|
SkippedStage::new(
|
||||||
|
"plc_tia_export",
|
||||||
|
SkipCode::ArtifactNotIngested,
|
||||||
|
format!("{name} could not be read: {e}"),
|
||||||
|
)
|
||||||
|
.about(name),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Some(blocks) = crate::pipeline::plc::tia::blocks_not_analysed(&manifest) {
|
||||||
|
self.skip_stage(
|
||||||
|
scan_run_id,
|
||||||
|
SkippedStage::new(
|
||||||
|
"plc_tia_blocks",
|
||||||
|
SkipCode::PlcBlocksNotAnalysed,
|
||||||
|
format!("the code of the blocks in {name} is not analysed yet: {blocks}"),
|
||||||
|
)
|
||||||
|
.about(blocks),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
let protected = component_list(&manifest.protected_blocks());
|
||||||
|
if !protected.is_empty() {
|
||||||
|
self.skip_stage(
|
||||||
|
scan_run_id,
|
||||||
|
SkippedStage::new(
|
||||||
|
"plc_protected_blocks",
|
||||||
|
SkipCode::ProtectedBlocks,
|
||||||
|
format!("know-how-protected blocks in {name} cannot be analysed: {protected}"),
|
||||||
|
)
|
||||||
|
.about(protected),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
let unmatched = component_list(&manifest.devices().unmatched);
|
||||||
|
if !unmatched.is_empty() {
|
||||||
|
self.skip_stage(
|
||||||
|
scan_run_id,
|
||||||
|
SkippedStage::new(
|
||||||
|
"plc_devices_unmatched",
|
||||||
|
SkipCode::DevicesUnmatched,
|
||||||
|
format!(
|
||||||
|
"devices in {name} without a Siemens order number or firmware are not \
|
||||||
|
matched against advisories: {unmatched}"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.about(unmatched),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Provision-and-test (#183): instantiate the target's control logic on an
|
/// Provision-and-test (#183): instantiate the target's control logic on an
|
||||||
/// ephemeral soft-PLC (OpenPLC), start it, probe the provisioned Modbus
|
/// ephemeral soft-PLC (OpenPLC), start it, probe the provisioned Modbus
|
||||||
/// endpoint, and tear the instance down. Used when a PLC/SPS target has the
|
/// endpoint, and tear the instance down. Used when a PLC/SPS target has the
|
||||||
@@ -2163,9 +2393,10 @@ impl PipelineOrchestrator {
|
|||||||
Ok(new_count)
|
Ok(new_count)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Store a control-application SBOM (CODESYS libraries + runtime) for a target
|
/// Store a control-application SBOM (CODESYS libraries + runtime, and the
|
||||||
/// and match it against known CVEs. Scoped to `package_manager = "codesys"` so
|
/// Siemens devices the target runs on) for a target and match it against
|
||||||
/// it refreshes on re-scan and coexists with any firmware/source SBOM. The
|
/// known CVEs. Scoped to those package managers so it refreshes on re-scan
|
||||||
|
/// and coexists with any firmware/source SBOM. The
|
||||||
/// runtime `Cmp*` / `3SLicense` components carry real CODESYS advisories, so
|
/// runtime `Cmp*` / `3SLicense` components carry real CODESYS advisories, so
|
||||||
/// this is where PLC-device CVE coverage comes from.
|
/// this is where PLC-device CVE coverage comes from.
|
||||||
async fn persist_control_app_sbom(
|
async fn persist_control_app_sbom(
|
||||||
@@ -2175,20 +2406,22 @@ impl PipelineOrchestrator {
|
|||||||
scan_run_id: &str,
|
scan_run_id: &str,
|
||||||
mut entries: Vec<SbomEntry>,
|
mut entries: Vec<SbomEntry>,
|
||||||
) -> Result<(), AgentError> {
|
) -> Result<(), AgentError> {
|
||||||
if entries.is_empty() {
|
// Empty entries are stored too: the components and alerts of the
|
||||||
return Ok(());
|
// last scan are then gone (callers skip it when nothing was read).
|
||||||
}
|
|
||||||
crate::pipeline::component_changes::record(
|
crate::pipeline::component_changes::record(
|
||||||
&self.db,
|
&self.db,
|
||||||
scan_run_id,
|
scan_run_id,
|
||||||
target_id,
|
target_id,
|
||||||
doc! { "package_manager": "codesys" },
|
doc! { "package_manager": { "$in": CONTROL_APP_MANAGERS.to_vec() } },
|
||||||
&entries,
|
&entries,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
self.db
|
self.db
|
||||||
.sbom_entries()
|
.sbom_entries()
|
||||||
.delete_many(doc! { "repo_id": target_id, "package_manager": "codesys" })
|
.delete_many(doc! {
|
||||||
|
"repo_id": target_id,
|
||||||
|
"package_manager": { "$in": CONTROL_APP_MANAGERS.to_vec() },
|
||||||
|
})
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let cve_scanner = CveScanner::new(
|
let cve_scanner = CveScanner::new(
|
||||||
@@ -2564,13 +2797,13 @@ impl PipelineOrchestrator {
|
|||||||
target_id: &str,
|
target_id: &str,
|
||||||
plan: &crate::pipeline::plan::ScanPlan,
|
plan: &crate::pipeline::plan::ScanPlan,
|
||||||
scan_run_id: &str,
|
scan_run_id: &str,
|
||||||
) {
|
) -> u32 {
|
||||||
if !plan.has(ScanType::Dast) {
|
if !plan.has(ScanType::Dast) {
|
||||||
return;
|
return 0;
|
||||||
}
|
}
|
||||||
self.update_phase(scan_run_id, ScanPhase::DastScanning)
|
self.update_phase(scan_run_id, ScanPhase::DastScanning)
|
||||||
.await;
|
.await;
|
||||||
self.maybe_trigger_dast(target_id, scan_run_id).await;
|
self.maybe_trigger_dast(target_id, scan_run_id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// If the target has a `LiveUrl` artifact and DAST is planned, provision a
|
/// If the target has a `LiveUrl` artifact and DAST is planned, provision a
|
||||||
@@ -2618,15 +2851,23 @@ impl PipelineOrchestrator {
|
|||||||
dast.allow_destructive = web.allow_destructive;
|
dast.allow_destructive = web.allow_destructive;
|
||||||
}
|
}
|
||||||
if let Some(auth) = &url.auth {
|
if let Some(auth) = &url.auth {
|
||||||
|
// The artifact keeps one secret (sealed): a password for a basic
|
||||||
|
// login, otherwise the token or cookie.
|
||||||
|
let basic = auth.method.eq_ignore_ascii_case("basic");
|
||||||
dast.auth_config = Some(DastAuthConfig {
|
dast.auth_config = Some(DastAuthConfig {
|
||||||
method: auth.method.clone(),
|
method: auth.method.clone(),
|
||||||
login_url: auth.login_url.clone(),
|
login_url: auth.login_url.clone(),
|
||||||
username: auth.username.clone(),
|
username: auth.username.clone(),
|
||||||
password: None,
|
password: auth.secret.clone().filter(|_| basic),
|
||||||
token: auth.secret.clone(),
|
token: auth.secret.clone().filter(|_| !basic),
|
||||||
headers: auth.headers.clone(),
|
headers: auth.headers.clone(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
// The copied secret is sealed already; the login headers are not.
|
||||||
|
if let Err(e) = self.secrets.seal_unsealed(&mut dast) {
|
||||||
|
tracing::warn!(error = %e, "Unified pipeline: DAST login not stored");
|
||||||
|
return;
|
||||||
|
}
|
||||||
if let Err(e) = self.db.dast_targets().insert_one(&dast).await {
|
if let Err(e) = self.db.dast_targets().insert_one(&dast).await {
|
||||||
tracing::warn!(error = %e, "Unified pipeline: failed to provision DAST target");
|
tracing::warn!(error = %e, "Unified pipeline: failed to provision DAST target");
|
||||||
}
|
}
|
||||||
@@ -3072,10 +3313,11 @@ impl PipelineOrchestrator {
|
|||||||
/// The recipes, images and package groups of a Yocto layer tree. A parser
|
/// The recipes, images and package groups of a Yocto layer tree. A parser
|
||||||
/// that failed, a tree with no layer, or recipes the parser could not read
|
/// that failed, a tree with no layer, or recipes the parser could not read
|
||||||
/// are recorded on the run.
|
/// are recorded on the run.
|
||||||
/// Scan a target whose only code-like input is its build output: the
|
/// Scan a target whose only code-like input is its build output or a
|
||||||
/// stages run over an empty working directory (nothing to find there),
|
/// supplier's SBOM: the stages run over an empty working directory
|
||||||
/// with the build outputs read as for a layer tree. The run says that
|
/// (nothing to find there), with the build outputs read as for a layer
|
||||||
/// there was no source code.
|
/// tree and the supplier SBOMs as SBOMs. The run says that there was no
|
||||||
|
/// source code.
|
||||||
///
|
///
|
||||||
/// # Returns
|
/// # Returns
|
||||||
///
|
///
|
||||||
@@ -3092,22 +3334,24 @@ impl PipelineOrchestrator {
|
|||||||
working_paths: &std::collections::HashMap<String, std::path::PathBuf>,
|
working_paths: &std::collections::HashMap<String, std::path::PathBuf>,
|
||||||
scan_run_id: &str,
|
scan_run_id: &str,
|
||||||
) -> Result<u32, AgentError> {
|
) -> Result<u32, AgentError> {
|
||||||
let Some(first) = target
|
let Some(first) = target.artifacts.iter().find(|a| {
|
||||||
.artifacts
|
matches!(
|
||||||
.iter()
|
a.kind,
|
||||||
.find(|a| a.kind == ArtifactKind::BuildOutput)
|
ArtifactKind::BuildOutput | ArtifactKind::SupplierSbom
|
||||||
else {
|
)
|
||||||
|
}) else {
|
||||||
return Ok(0);
|
return Ok(0);
|
||||||
};
|
};
|
||||||
|
// What is read instead of code: a build output brings the recipe
|
||||||
|
// stages a supplier SBOM does not (#1042).
|
||||||
|
let reason = if target.has(ArtifactKind::BuildOutput) {
|
||||||
|
NO_CODE_BUILD_OUTPUT
|
||||||
|
} else {
|
||||||
|
NO_CODE_SUPPLIER_SBOM
|
||||||
|
};
|
||||||
self.skip_stage(
|
self.skip_stage(
|
||||||
scan_run_id,
|
scan_run_id,
|
||||||
SkippedStage::new(
|
SkippedStage::new("source_code", SkipCode::NotAnalysedYet, reason),
|
||||||
"source_code",
|
|
||||||
SkipCode::NotAnalysedYet,
|
|
||||||
"the target has no source code (a git repository or a source archive): only \
|
|
||||||
its build output is read; code analysis, the recipe inventory and the recipe \
|
|
||||||
lint need the layer tree",
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
// Under the agent's own work directory, so it is never a tree the
|
// Under the agent's own work directory, so it is never a tree the
|
||||||
@@ -3122,6 +3366,7 @@ impl PipelineOrchestrator {
|
|||||||
.map_err(|e| AgentError::Other(format!("build-output work directory: {e}")))?;
|
.map_err(|e| AgentError::Other(format!("build-output work directory: {e}")))?;
|
||||||
let mut repo = RepoView::from_target(target, first, &self.secrets);
|
let mut repo = RepoView::from_target(target, first, &self.secrets);
|
||||||
repo.build_outputs = build_output_paths(target, working_paths);
|
repo.build_outputs = build_output_paths(target, working_paths);
|
||||||
|
repo.supplier_sboms = supplier_sbom_paths(target, working_paths);
|
||||||
let scanned = self.scan_tree(&tree, None, &repo, scan_run_id).await;
|
let scanned = self.scan_tree(&tree, None, &repo, scan_run_id).await;
|
||||||
let _ = std::fs::remove_dir_all(&tree);
|
let _ = std::fs::remove_dir_all(&tree);
|
||||||
let n = scanned?;
|
let n = scanned?;
|
||||||
@@ -3129,6 +3374,42 @@ impl PipelineOrchestrator {
|
|||||||
Ok(n)
|
Ok(n)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The components of the target's supplier SBOMs (#1025), read on a
|
||||||
|
/// blocking thread.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// One that cannot be read fails the scan, with the reason: read as
|
||||||
|
/// empty, it would let a complete CVE check take every known CVE of the
|
||||||
|
/// component for gone.
|
||||||
|
async fn read_supplier_sboms(
|
||||||
|
&self,
|
||||||
|
repo: &RepoView,
|
||||||
|
repo_id: &str,
|
||||||
|
) -> Result<
|
||||||
|
(
|
||||||
|
Vec<compliance_core::models::SbomEntry>,
|
||||||
|
Vec<crate::pipeline::sbom::supplied::SuppliedStatement>,
|
||||||
|
),
|
||||||
|
AgentError,
|
||||||
|
> {
|
||||||
|
let (mut entries, mut statements) = (Vec::new(), Vec::new());
|
||||||
|
for (path, label) in &repo.supplier_sboms {
|
||||||
|
let (file, id, name) = (path.clone(), repo_id.to_string(), label.clone());
|
||||||
|
let read = tokio::task::spawn_blocking(move || {
|
||||||
|
crate::pipeline::sbom::supplied::read_with_statements(&file, &id, &name)
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|e| AgentError::Other(format!("reading the supplier SBOM {label}: {e}")))?
|
||||||
|
.map_err(|e| {
|
||||||
|
AgentError::Other(format!("the supplier SBOM {label} cannot be read: {e}"))
|
||||||
|
})?;
|
||||||
|
entries.extend(read.entries);
|
||||||
|
statements.extend(read.statements);
|
||||||
|
}
|
||||||
|
Ok((entries, statements))
|
||||||
|
}
|
||||||
|
|
||||||
/// What the target's build outputs say: the images their SPDX archives
|
/// What the target's build outputs say: the images their SPDX archives
|
||||||
/// describe ([`crate::pipeline::yocto_spdx`]) and their cve-check reports
|
/// describe ([`crate::pipeline::yocto_spdx`]) and their cve-check reports
|
||||||
/// ([`crate::pipeline::yocto_cve_check`]), told apart by content. One
|
/// ([`crate::pipeline::yocto_cve_check`]), told apart by content. One
|
||||||
@@ -3519,17 +3800,40 @@ fn build_output_paths(
|
|||||||
target: &OnboardedTarget,
|
target: &OnboardedTarget,
|
||||||
working_paths: &std::collections::HashMap<String, std::path::PathBuf>,
|
working_paths: &std::collections::HashMap<String, std::path::PathBuf>,
|
||||||
) -> Vec<std::path::PathBuf> {
|
) -> Vec<std::path::PathBuf> {
|
||||||
|
artifacts_of(target, ArtifactKind::BuildOutput, working_paths)
|
||||||
|
.map(|(_, path)| path)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The target's supplier SBOMs (#1025) as ingested, each with the name it
|
||||||
|
/// was uploaded under.
|
||||||
|
fn supplier_sbom_paths(
|
||||||
|
target: &OnboardedTarget,
|
||||||
|
working_paths: &std::collections::HashMap<String, std::path::PathBuf>,
|
||||||
|
) -> Vec<(std::path::PathBuf, String)> {
|
||||||
|
artifacts_of(target, ArtifactKind::SupplierSbom, working_paths)
|
||||||
|
.map(|(artifact, path)| (path, artifact.source_ref.clone()))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The target's artifacts of `kind` with the path each was ingested to (or
|
||||||
|
/// stored at, when this run did not ingest it).
|
||||||
|
fn artifacts_of<'a>(
|
||||||
|
target: &'a OnboardedTarget,
|
||||||
|
kind: ArtifactKind,
|
||||||
|
working_paths: &'a std::collections::HashMap<String, std::path::PathBuf>,
|
||||||
|
) -> impl Iterator<Item = (&'a compliance_core::models::Artifact, std::path::PathBuf)> + 'a {
|
||||||
target
|
target
|
||||||
.artifacts
|
.artifacts
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|a| a.kind == ArtifactKind::BuildOutput)
|
.filter(move |a| a.kind == kind)
|
||||||
.filter_map(|a| {
|
.filter_map(|a| {
|
||||||
working_paths
|
working_paths
|
||||||
.get(&a.id)
|
.get(&a.id)
|
||||||
.cloned()
|
.cloned()
|
||||||
.or_else(|| a.stored_path.as_deref().map(std::path::PathBuf::from))
|
.or_else(|| a.stored_path.as_deref().map(std::path::PathBuf::from))
|
||||||
|
.map(|path| (a, path))
|
||||||
})
|
})
|
||||||
.collect()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ pub mod parser;
|
|||||||
pub mod plcopen;
|
pub mod plcopen;
|
||||||
pub mod rules;
|
pub mod rules;
|
||||||
pub mod sbom;
|
pub mod sbom;
|
||||||
|
pub(crate) mod tia;
|
||||||
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,152 @@
|
|||||||
|
//! Reading a TIA export (#1090): the zip a TIA Portal connector uploads, with
|
||||||
|
//! its [`TiaManifest`] at the root. Only the manifest is read here; the block
|
||||||
|
//! exports beside it are unpacked by ingest like any PLC project.
|
||||||
|
|
||||||
|
use std::io::Read;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use compliance_core::models::tia_export::{MANIFEST_NAME, MAX_MANIFEST_BYTES};
|
||||||
|
use compliance_core::models::{TiaBundleError, TiaManifest};
|
||||||
|
|
||||||
|
/// Read the manifest of the TIA export at `bundle`.
|
||||||
|
///
|
||||||
|
/// The manifest is read up to [`MAX_MANIFEST_BYTES`], whatever size the zip
|
||||||
|
/// declares for it, so a forged entry cannot make this read more.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// [`TiaBundleError::NotZip`] when `bundle` is not a readable zip,
|
||||||
|
/// [`TiaBundleError::NoManifest`] without a `manifest.json` at its root, and
|
||||||
|
/// [`TiaManifest::parse`]'s refusals.
|
||||||
|
pub(crate) fn read_manifest(bundle: &Path) -> Result<TiaManifest, TiaBundleError> {
|
||||||
|
let file = std::fs::File::open(bundle).map_err(|_| TiaBundleError::NotZip)?;
|
||||||
|
let mut zip = zip::ZipArchive::new(file).map_err(|_| TiaBundleError::NotZip)?;
|
||||||
|
let entry = match zip.by_name(MANIFEST_NAME) {
|
||||||
|
Ok(entry) => entry,
|
||||||
|
Err(zip::result::ZipError::FileNotFound) => return Err(TiaBundleError::NoManifest),
|
||||||
|
Err(e) => return Err(TiaBundleError::ManifestInvalid(e.to_string())),
|
||||||
|
};
|
||||||
|
let mut json = Vec::new();
|
||||||
|
// One byte more than allowed, so an oversized manifest is told apart from
|
||||||
|
// one exactly at the limit.
|
||||||
|
entry
|
||||||
|
.take(MAX_MANIFEST_BYTES + 1)
|
||||||
|
.read_to_end(&mut json)
|
||||||
|
.map_err(|e| TiaBundleError::ManifestInvalid(e.to_string()))?;
|
||||||
|
TiaManifest::parse(&json)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The blocks of `manifest` whose code is analysed by no stage yet (all
|
||||||
|
/// readable ones, until #1093): how many, and in which languages, as a run
|
||||||
|
/// note's subject (`12 (FBD, LAD, SCL)`). `None` when there are none.
|
||||||
|
pub(crate) fn blocks_not_analysed(manifest: &TiaManifest) -> Option<String> {
|
||||||
|
let readable: Vec<_> = manifest.blocks.iter().filter(|b| !b.protected).collect();
|
||||||
|
if readable.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let languages: std::collections::BTreeSet<String> = readable
|
||||||
|
.iter()
|
||||||
|
.filter_map(|b| b.language.as_deref())
|
||||||
|
.map(str::to_ascii_uppercase)
|
||||||
|
.collect();
|
||||||
|
let languages = languages.into_iter().collect::<Vec<_>>().join(", ");
|
||||||
|
Some(if languages.is_empty() {
|
||||||
|
readable.len().to_string()
|
||||||
|
} else {
|
||||||
|
format!("{} ({languages})", readable.len())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[allow(clippy::unwrap_used)]
|
||||||
|
pub(crate) mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::io::Write;
|
||||||
|
|
||||||
|
/// A fresh directory for one test's files.
|
||||||
|
pub(crate) fn scratch() -> std::path::PathBuf {
|
||||||
|
let dir = std::env::temp_dir().join(format!("tia-{}", uuid::Uuid::new_v4()));
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
dir
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A TIA export zip with `files` (name, content) in `dir`.
|
||||||
|
pub(crate) fn bundle(dir: &Path, files: &[(&str, &[u8])]) -> std::path::PathBuf {
|
||||||
|
let path = dir.join("linie1.tia-export.zip");
|
||||||
|
let mut zip = zip::ZipWriter::new(std::fs::File::create(&path).unwrap());
|
||||||
|
for (name, content) in files {
|
||||||
|
zip.start_file(*name, zip::write::SimpleFileOptions::default())
|
||||||
|
.unwrap();
|
||||||
|
zip.write_all(content).unwrap();
|
||||||
|
}
|
||||||
|
zip.finish().unwrap();
|
||||||
|
path
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A manifest with one CPU, one GSD device and three blocks, one of them
|
||||||
|
/// protected.
|
||||||
|
pub(crate) const MANIFEST: &str = r#"{
|
||||||
|
"bundle_version": 1,
|
||||||
|
"tia_version": "V20",
|
||||||
|
"project": {"name": "Linie 1"},
|
||||||
|
"devices": [
|
||||||
|
{"name": "PLC_1", "role": "cpu",
|
||||||
|
"type_identifier": "OrderNumber:6ES7 511-1AK02-0AB0/V2.9"},
|
||||||
|
{"name": "Drittgeraet", "role": "module", "type_identifier": "GSD:VENDOR.XML/DAP1"}
|
||||||
|
],
|
||||||
|
"blocks": [
|
||||||
|
{"device": "PLC_1", "name": "Main", "kind": "ob", "language": "LAD",
|
||||||
|
"file": "blocks/PLC_1/Main.xml"},
|
||||||
|
{"device": "PLC_1", "name": "Pumpe", "kind": "fb", "language": "scl",
|
||||||
|
"file": "blocks/PLC_1/Pumpe.scl"},
|
||||||
|
{"device": "PLC_1", "name": "FB_42", "kind": "fb", "protected": true}
|
||||||
|
]
|
||||||
|
}"#;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_manifest_is_read_from_the_root_of_the_zip() {
|
||||||
|
let dir = scratch();
|
||||||
|
let path = bundle(
|
||||||
|
&dir,
|
||||||
|
&[
|
||||||
|
("manifest.json", MANIFEST.as_bytes()),
|
||||||
|
("blocks/PLC_1/Main.xml", b"<Document/>"),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
let manifest = read_manifest(&path).unwrap();
|
||||||
|
assert_eq!(manifest.project.name, "Linie 1");
|
||||||
|
assert_eq!(
|
||||||
|
blocks_not_analysed(&manifest).as_deref(),
|
||||||
|
Some("2 (LAD, SCL)")
|
||||||
|
);
|
||||||
|
assert_eq!(manifest.protected_blocks(), ["PLC_1/FB_42"]);
|
||||||
|
std::fs::remove_dir_all(&dir).ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_bundle_that_is_not_one_is_refused_with_its_reason() {
|
||||||
|
let dir = scratch();
|
||||||
|
let not_zip = dir.join("x.zip");
|
||||||
|
std::fs::write(¬_zip, b"plain text").unwrap();
|
||||||
|
assert_eq!(read_manifest(¬_zip), Err(TiaBundleError::NotZip));
|
||||||
|
let nested = bundle(&dir, &[("export/manifest.json", MANIFEST.as_bytes())]);
|
||||||
|
assert_eq!(read_manifest(&nested), Err(TiaBundleError::NoManifest));
|
||||||
|
let huge = vec![b' '; MAX_MANIFEST_BYTES as usize + 10];
|
||||||
|
let oversized = bundle(&dir, &[("manifest.json", &huge)]);
|
||||||
|
assert_eq!(
|
||||||
|
read_manifest(&oversized),
|
||||||
|
Err(TiaBundleError::ManifestTooLarge)
|
||||||
|
);
|
||||||
|
std::fs::remove_dir_all(&dir).ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_protected_blocks_leave_nothing_unanalysed() {
|
||||||
|
let mut manifest = TiaManifest::parse(MANIFEST.as_bytes()).unwrap();
|
||||||
|
manifest.blocks.retain(|b| b.protected);
|
||||||
|
assert_eq!(blocks_not_analysed(&manifest), None);
|
||||||
|
manifest.blocks[0].protected = false;
|
||||||
|
manifest.blocks[0].language = None;
|
||||||
|
assert_eq!(blocks_not_analysed(&manifest).as_deref(), Some("1"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -60,6 +60,14 @@ pub struct RepoView {
|
|||||||
/// The target's uploaded build outputs (Yocto image SPDX archives), as
|
/// The target's uploaded build outputs (Yocto image SPDX archives), as
|
||||||
/// ingested. Set by the caller; empty from [`Self::from_target`].
|
/// ingested. Set by the caller; empty from [`Self::from_target`].
|
||||||
pub build_outputs: Vec<std::path::PathBuf>,
|
pub build_outputs: Vec<std::path::PathBuf>,
|
||||||
|
/// The target's supplier SBOMs (#1025) as ingested, each with the name it
|
||||||
|
/// was uploaded under. Set by the caller; empty from [`Self::from_target`].
|
||||||
|
pub supplier_sboms: Vec<(std::path::PathBuf, String)>,
|
||||||
|
/// Who supplies the component, for one bought in (#1025).
|
||||||
|
pub supplier: Option<compliance_core::models::SupplierComponent>,
|
||||||
|
/// The Siemens controllers the target runs on (SPS item 4a): entered,
|
||||||
|
/// and declared by its TIA exports (#1090).
|
||||||
|
pub devices: Vec<compliance_core::models::TargetDevice>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RepoView {
|
impl RepoView {
|
||||||
@@ -95,6 +103,9 @@ impl RepoView {
|
|||||||
yocto_layers: false,
|
yocto_layers: false,
|
||||||
exclude_paths: target.scan_config.exclude_paths.clone(),
|
exclude_paths: target.scan_config.exclude_paths.clone(),
|
||||||
build_outputs: Vec::new(),
|
build_outputs: Vec::new(),
|
||||||
|
supplier_sboms: Vec::new(),
|
||||||
|
supplier: target.supplier.clone(),
|
||||||
|
devices: target.target_devices(),
|
||||||
};
|
};
|
||||||
if let Some(git) = &code.git {
|
if let Some(git) = &code.git {
|
||||||
view.default_branch = git.default_branch.clone();
|
view.default_branch = git.default_branch.clone();
|
||||||
|
|||||||
@@ -0,0 +1,623 @@
|
|||||||
|
//! Why an SBOM is empty or incomplete, as findings (#979).
|
||||||
|
//!
|
||||||
|
//! The SBOM is built from the manifests and lockfiles in the code. Without
|
||||||
|
//! them it is empty, which reads as "no libraries" to someone who is not a
|
||||||
|
//! developer. Two findings say what is missing instead:
|
||||||
|
//!
|
||||||
|
//! - [`NO_MANIFEST_RULE`] (Medium): the tree holds code in a language with a
|
||||||
|
//! package manager, but no manifest or lockfile for it at all;
|
||||||
|
//! - [`UNRESOLVED_RULE`] (Low): a manifest whose dependencies were not
|
||||||
|
//! resolved (no lockfile, or one no tool reads), as
|
||||||
|
//! [`super::unlocked_ecosystems`] reports it.
|
||||||
|
//!
|
||||||
|
//! C and C++ have no standard manifest, and a firmware tree's components come
|
||||||
|
//! from its sources (library headers, the firmware build, a CODESYS archive, a
|
||||||
|
//! Yocto layer tree): such a tree never gets the first finding. Nothing is
|
||||||
|
//! guessed and no code is run to resolve dependencies. Both findings belong
|
||||||
|
//! to [`SCANNER`], which completes on every code scan, so a finding closes at
|
||||||
|
//! the next scan that no longer reports it.
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use compliance_core::models::{Finding, SbomEntry, ScanType, Severity, YOCTO_RECIPE_MANAGER};
|
||||||
|
|
||||||
|
use super::UnlockedEcosystem;
|
||||||
|
use crate::pipeline::dedup::compute_fingerprint;
|
||||||
|
use crate::pipeline::embedded_versions::EMBEDDED_MANAGER;
|
||||||
|
use crate::pipeline::vendor::walk_outside;
|
||||||
|
|
||||||
|
/// The scanner name of these findings.
|
||||||
|
pub(crate) const SCANNER: &str = compliance_core::models::SBOM_COVERAGE_SCANNER;
|
||||||
|
|
||||||
|
/// Code in a language with a package manager, and no manifest for it.
|
||||||
|
pub(crate) const NO_MANIFEST_RULE: &str = "sbom-no-manifest";
|
||||||
|
|
||||||
|
/// A manifest whose dependencies were not resolved.
|
||||||
|
pub(crate) const UNRESOLVED_RULE: &str = "sbom-dependencies-unresolved";
|
||||||
|
|
||||||
|
/// The weakness both findings stand for: components nobody tracks.
|
||||||
|
const CWE: &str = "CWE-1104";
|
||||||
|
|
||||||
|
/// The CRA requirement both findings are evidence against: the SBOM.
|
||||||
|
const SBOM_CONTROL: &str = crate::evidence::compliance::SBOM_CONTROL;
|
||||||
|
|
||||||
|
/// Languages whose code never asks for a manifest: C and C++ have no
|
||||||
|
/// standard one, and a Yocto layer tree's recipes are its inventory.
|
||||||
|
const NO_MANIFEST_LANGUAGES: [&str; 3] = ["c", "cpp", "bitbake"];
|
||||||
|
|
||||||
|
/// The `package_manager` values of components read from the sources rather
|
||||||
|
/// than a manifest: library headers, CODESYS archives, Yocto recipes.
|
||||||
|
const SOURCE_MANAGERS: [&str; 3] = [EMBEDDED_MANAGER, "codesys", YOCTO_RECIPE_MANAGER];
|
||||||
|
|
||||||
|
/// A package ecosystem: the languages that use it, the files that declare
|
||||||
|
/// or pin its dependencies, and how to add them.
|
||||||
|
struct Ecosystem {
|
||||||
|
/// What the finding calls the code (`Python`, `JavaScript/TypeScript`).
|
||||||
|
name: &'static str,
|
||||||
|
/// The language codes of [`crate::pipeline::languages`] it covers.
|
||||||
|
languages: &'static [&'static str],
|
||||||
|
/// The purl types of its SBOM entries: entries of one mean the SBOM
|
||||||
|
/// already lists some of its libraries (from committed jars, DLLs or
|
||||||
|
/// installed packages), so a manifest is not all there is.
|
||||||
|
purl_types: &'static [&'static str],
|
||||||
|
/// Whether a file name (lowercased) is one of its manifests or lockfiles.
|
||||||
|
declares: fn(&str) -> bool,
|
||||||
|
/// Its manifests, as the finding names them.
|
||||||
|
manifests: &'static str,
|
||||||
|
/// A concrete way to add a manifest or lockfile.
|
||||||
|
example: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ecosystems the finding covers, in the order the findings list them.
|
||||||
|
static ECOSYSTEMS: [Ecosystem; 9] = [
|
||||||
|
Ecosystem {
|
||||||
|
name: "Python",
|
||||||
|
languages: &["python"],
|
||||||
|
purl_types: &["pypi"],
|
||||||
|
declares: |f| {
|
||||||
|
(f.starts_with("requirements") && f.ends_with(".txt"))
|
||||||
|
|| matches!(
|
||||||
|
f,
|
||||||
|
"pyproject.toml"
|
||||||
|
| "setup.py"
|
||||||
|
| "setup.cfg"
|
||||||
|
| "pipfile"
|
||||||
|
| "pipfile.lock"
|
||||||
|
| "poetry.lock"
|
||||||
|
| "uv.lock"
|
||||||
|
| "pdm.lock"
|
||||||
|
| "environment.yml"
|
||||||
|
| "environment.yaml"
|
||||||
|
)
|
||||||
|
},
|
||||||
|
manifests: "requirements.txt or pyproject.toml",
|
||||||
|
example: "run pip freeze > requirements.txt in the project's environment, or declare \
|
||||||
|
the dependencies in pyproject.toml and run uv lock or poetry lock",
|
||||||
|
},
|
||||||
|
Ecosystem {
|
||||||
|
name: "JavaScript/TypeScript",
|
||||||
|
languages: &["javascript", "typescript"],
|
||||||
|
purl_types: &["npm"],
|
||||||
|
declares: |f| {
|
||||||
|
matches!(
|
||||||
|
f,
|
||||||
|
"package.json"
|
||||||
|
| "package-lock.json"
|
||||||
|
| "npm-shrinkwrap.json"
|
||||||
|
| "yarn.lock"
|
||||||
|
| "pnpm-lock.yaml"
|
||||||
|
| "bun.lock"
|
||||||
|
| "bun.lockb"
|
||||||
|
| "deno.json"
|
||||||
|
| "deno.jsonc"
|
||||||
|
| "deno.lock"
|
||||||
|
)
|
||||||
|
},
|
||||||
|
manifests: "package.json",
|
||||||
|
example: "declare the dependencies in package.json and run npm install, which writes \
|
||||||
|
package-lock.json",
|
||||||
|
},
|
||||||
|
Ecosystem {
|
||||||
|
name: "Rust",
|
||||||
|
languages: &["rust"],
|
||||||
|
purl_types: &["cargo"],
|
||||||
|
declares: |f| matches!(f, "cargo.toml" | "cargo.lock"),
|
||||||
|
manifests: "Cargo.toml",
|
||||||
|
example: "commit Cargo.toml and Cargo.lock (cargo generate-lockfile writes it)",
|
||||||
|
},
|
||||||
|
Ecosystem {
|
||||||
|
name: "Go",
|
||||||
|
languages: &["go"],
|
||||||
|
purl_types: &["golang"],
|
||||||
|
declares: |f| matches!(f, "go.mod" | "go.sum" | "gopkg.toml" | "gopkg.lock"),
|
||||||
|
manifests: "go.mod",
|
||||||
|
example: "run go mod init and go mod tidy, which write go.mod and go.sum, and commit both",
|
||||||
|
},
|
||||||
|
Ecosystem {
|
||||||
|
name: "Java/Kotlin",
|
||||||
|
languages: &["java", "kotlin"],
|
||||||
|
purl_types: &["maven"],
|
||||||
|
declares: |f| {
|
||||||
|
matches!(
|
||||||
|
f,
|
||||||
|
"pom.xml"
|
||||||
|
| "build.gradle"
|
||||||
|
| "build.gradle.kts"
|
||||||
|
| "settings.gradle"
|
||||||
|
| "settings.gradle.kts"
|
||||||
|
| "gradle.lockfile"
|
||||||
|
| "ivy.xml"
|
||||||
|
)
|
||||||
|
},
|
||||||
|
manifests: "pom.xml or build.gradle",
|
||||||
|
example: "declare the dependencies in a Maven pom.xml or a Gradle build file; with \
|
||||||
|
Gradle, also commit gradle.lockfile (./gradlew dependencies --write-locks)",
|
||||||
|
},
|
||||||
|
Ecosystem {
|
||||||
|
name: "C#",
|
||||||
|
languages: &["csharp"],
|
||||||
|
purl_types: &["nuget"],
|
||||||
|
// A Unity project (`ProjectVersion.txt`) is the build lifecycle
|
||||||
|
// check's: without its package manifest it is a legacy build system.
|
||||||
|
declares: |f| {
|
||||||
|
[".csproj", ".fsproj", ".vbproj", ".nuspec"]
|
||||||
|
.iter()
|
||||||
|
.any(|suffix| f.ends_with(suffix))
|
||||||
|
|| matches!(
|
||||||
|
f,
|
||||||
|
"packages.config"
|
||||||
|
| "packages.lock.json"
|
||||||
|
| "directory.packages.props"
|
||||||
|
| "project.json"
|
||||||
|
| "projectversion.txt"
|
||||||
|
)
|
||||||
|
},
|
||||||
|
manifests: "a .csproj project file",
|
||||||
|
example: "reference the NuGet packages in the .csproj project file, set \
|
||||||
|
RestorePackagesWithLockFile to true and commit the packages.lock.json that \
|
||||||
|
dotnet restore writes",
|
||||||
|
},
|
||||||
|
Ecosystem {
|
||||||
|
name: "PHP",
|
||||||
|
languages: &["php"],
|
||||||
|
purl_types: &["composer"],
|
||||||
|
declares: |f| matches!(f, "composer.json" | "composer.lock"),
|
||||||
|
manifests: "composer.json",
|
||||||
|
example: "declare the dependencies in composer.json and run composer install, which \
|
||||||
|
writes composer.lock; commit both",
|
||||||
|
},
|
||||||
|
Ecosystem {
|
||||||
|
name: "Ruby",
|
||||||
|
languages: &["ruby"],
|
||||||
|
purl_types: &["gem"],
|
||||||
|
declares: |f| {
|
||||||
|
f.ends_with(".gemspec") || matches!(f, "gemfile" | "gemfile.lock" | "gems.rb")
|
||||||
|
},
|
||||||
|
manifests: "a Gemfile",
|
||||||
|
example: "declare the gems in a Gemfile and run bundle install, which writes \
|
||||||
|
Gemfile.lock; commit both",
|
||||||
|
},
|
||||||
|
Ecosystem {
|
||||||
|
name: "Dart",
|
||||||
|
languages: &["dart"],
|
||||||
|
purl_types: &["pub"],
|
||||||
|
declares: |f| matches!(f, "pubspec.yaml" | "pubspec.lock"),
|
||||||
|
manifests: "pubspec.yaml",
|
||||||
|
example: "declare the dependencies in pubspec.yaml and run dart pub get (or flutter pub \
|
||||||
|
get), which writes pubspec.lock; commit both",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
/// What one scan knows about its tree when it asks for these findings.
|
||||||
|
pub(crate) struct ScannedTree<'a> {
|
||||||
|
/// The target (`Finding::repo_id`).
|
||||||
|
pub repo_id: &'a str,
|
||||||
|
/// The working copy, after the left-out paths were pruned.
|
||||||
|
pub root: &'a Path,
|
||||||
|
/// Its vendor directories, which are not the customer's code.
|
||||||
|
pub vendor: &'a [String],
|
||||||
|
/// Its source languages ([`crate::pipeline::languages::source_languages`]).
|
||||||
|
pub languages: &'a [String],
|
||||||
|
/// Whether the tree is read as Yocto layers.
|
||||||
|
pub yocto_layers: bool,
|
||||||
|
/// Whether the target has a firmware SBOM from its sources, which the
|
||||||
|
/// firmware step stored before this scan of the tree.
|
||||||
|
pub firmware_sbom: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The coverage findings of one scan: a [`NO_MANIFEST_RULE`] finding per
|
||||||
|
/// ecosystem the tree's code needs a manifest for and has none, and an
|
||||||
|
/// [`UNRESOLVED_RULE`] finding per entry of `unlocked` (other than a legacy
|
||||||
|
/// build system, which is a finding of the build lifecycle check already).
|
||||||
|
///
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// * `tree` - the scanned tree and what the scan detected in it
|
||||||
|
/// * `sbom` - the components this scan listed, from every source
|
||||||
|
/// * `unlocked` - the manifests whose dependencies were not resolved
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// The findings, with `control_refs` set to the SBOM requirement; empty when
|
||||||
|
/// the SBOM speaks for the whole tree.
|
||||||
|
pub(crate) fn coverage_findings(
|
||||||
|
tree: &ScannedTree<'_>,
|
||||||
|
sbom: &[SbomEntry],
|
||||||
|
unlocked: &[UnlockedEcosystem],
|
||||||
|
) -> Vec<Finding> {
|
||||||
|
let mut findings: Vec<Finding> = missing_manifests(tree, sbom)
|
||||||
|
.into_iter()
|
||||||
|
.map(|eco| no_manifest_finding(tree.repo_id, eco))
|
||||||
|
.collect();
|
||||||
|
findings.extend(
|
||||||
|
unlocked
|
||||||
|
.iter()
|
||||||
|
.filter(|eco| !eco.legacy_build)
|
||||||
|
.map(|eco| unresolved_finding(tree.repo_id, eco)),
|
||||||
|
);
|
||||||
|
findings
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ecosystems whose code the tree holds outside vendor directories, with
|
||||||
|
/// no manifest or lockfile of theirs anywhere outside them and no component
|
||||||
|
/// of theirs in `sbom`. Empty for a tree with C, C++ or Yocto layers, and for
|
||||||
|
/// one whose components come from its sources ([`SOURCE_MANAGERS`], or the
|
||||||
|
/// firmware SBOM).
|
||||||
|
fn missing_manifests(tree: &ScannedTree<'_>, sbom: &[SbomEntry]) -> Vec<&'static Ecosystem> {
|
||||||
|
let has_language = |l: &str| tree.languages.iter().any(|x| x == l);
|
||||||
|
let from_sources = tree.firmware_sbom
|
||||||
|
|| sbom
|
||||||
|
.iter()
|
||||||
|
.any(|e| SOURCE_MANAGERS.contains(&e.package_manager.as_str()));
|
||||||
|
if tree.yocto_layers || from_sources || NO_MANIFEST_LANGUAGES.iter().any(|l| has_language(l)) {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
// `pkg:pypi/requests@2` has the purl type `pypi`.
|
||||||
|
let listed = |eco: &Ecosystem| {
|
||||||
|
sbom.iter().any(|e| {
|
||||||
|
e.purl
|
||||||
|
.as_deref()
|
||||||
|
.and_then(|p| p.strip_prefix("pkg:"))
|
||||||
|
.and_then(|p| p.split('/').next())
|
||||||
|
.is_some_and(|t| eco.purl_types.contains(&t))
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let mut candidates: Vec<&'static Ecosystem> = ECOSYSTEMS
|
||||||
|
.iter()
|
||||||
|
.filter(|eco| eco.languages.iter().any(|l| has_language(l)))
|
||||||
|
.filter(|eco| !listed(eco))
|
||||||
|
.collect();
|
||||||
|
if candidates.is_empty() {
|
||||||
|
return candidates;
|
||||||
|
}
|
||||||
|
// One walk for all of them; it stops once each has shown a manifest.
|
||||||
|
for entry in walk_outside(tree.root, tree.vendor) {
|
||||||
|
if !entry.file_type().is_file() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
|
||||||
|
candidates.retain(|eco| !(eco.declares)(&name));
|
||||||
|
if candidates.is_empty() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
candidates
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The [`NO_MANIFEST_RULE`] finding for `eco` on target `repo_id`.
|
||||||
|
fn no_manifest_finding(repo_id: &str, eco: &Ecosystem) -> Finding {
|
||||||
|
let mut finding = Finding::new(
|
||||||
|
repo_id.to_string(),
|
||||||
|
compute_fingerprint(&[repo_id, NO_MANIFEST_RULE, eco.name]),
|
||||||
|
SCANNER.to_string(),
|
||||||
|
ScanType::Sbom,
|
||||||
|
format!(
|
||||||
|
"No package manifest: the SBOM lists no libraries of the {} code",
|
||||||
|
eco.name
|
||||||
|
),
|
||||||
|
format!(
|
||||||
|
"The code contains {name} files, but no manifest or lockfile (such as {manifests}) \
|
||||||
|
that lists the libraries they use. The SBOM is built from these files, so it shows \
|
||||||
|
none of the {name} libraries, and their known vulnerabilities (CVEs) are not \
|
||||||
|
checked. An empty SBOM here does not mean that the code uses no libraries.",
|
||||||
|
name = eco.name,
|
||||||
|
manifests = eco.manifests,
|
||||||
|
),
|
||||||
|
Severity::Medium,
|
||||||
|
);
|
||||||
|
finding.remediation = Some(format!(
|
||||||
|
"Add a manifest or lockfile and commit it. For {}: {}. The finding closes at the next \
|
||||||
|
scan that finds it.",
|
||||||
|
eco.name, eco.example
|
||||||
|
));
|
||||||
|
stamp(&mut finding, NO_MANIFEST_RULE);
|
||||||
|
finding
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The [`UNRESOLVED_RULE`] finding for `eco` on target `repo_id`.
|
||||||
|
fn unresolved_finding(repo_id: &str, eco: &UnlockedEcosystem) -> Finding {
|
||||||
|
let mut finding = Finding::new(
|
||||||
|
repo_id.to_string(),
|
||||||
|
compute_fingerprint(&[repo_id, UNRESOLVED_RULE, &eco.manifest]),
|
||||||
|
SCANNER.to_string(),
|
||||||
|
ScanType::Sbom,
|
||||||
|
format!(
|
||||||
|
"Dependencies not resolved: the SBOM is incomplete ({})",
|
||||||
|
eco.manifest
|
||||||
|
),
|
||||||
|
format!(
|
||||||
|
"{} {}. So the versions of these libraries, and of the libraries they pull in, are \
|
||||||
|
not known: the SBOM does not list them completely, and their known \
|
||||||
|
vulnerabilities (CVEs) are not checked. Prüfwerk does not run the project's code \
|
||||||
|
to resolve them.",
|
||||||
|
eco.manifest, eco.problem
|
||||||
|
),
|
||||||
|
Severity::Low,
|
||||||
|
);
|
||||||
|
finding.remediation = Some(format!(
|
||||||
|
"{}. The finding closes at the next scan that finds the lockfile.",
|
||||||
|
capitalised(eco.remedy)
|
||||||
|
));
|
||||||
|
finding.file_path = Some(eco.manifest.clone());
|
||||||
|
stamp(&mut finding, UNRESOLVED_RULE);
|
||||||
|
finding
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Give `finding` its rule, weakness and CRA requirement. The control triage
|
||||||
|
/// judges a finding on its code, which these have none of, so the mapping is
|
||||||
|
/// set here, as `cra-ai-23` in the control map binds it.
|
||||||
|
fn stamp(finding: &mut Finding, rule: &str) {
|
||||||
|
finding.rule_id = Some(rule.to_string());
|
||||||
|
finding.cwe = Some(CWE.to_string());
|
||||||
|
finding.control_refs = vec![SBOM_CONTROL.to_string()];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `text` with its first letter upper-case.
|
||||||
|
fn capitalised(text: &str) -> String {
|
||||||
|
let mut chars = text.chars();
|
||||||
|
chars
|
||||||
|
.next()
|
||||||
|
.map(|first| first.to_uppercase().chain(chars).collect())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[allow(clippy::expect_used)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
/// A temporary tree holding `files`, removed on drop.
|
||||||
|
struct Tree(std::path::PathBuf);
|
||||||
|
|
||||||
|
impl Tree {
|
||||||
|
fn with(files: &[&str]) -> Self {
|
||||||
|
let root = std::env::temp_dir().join(format!("cs-coverage-{}", uuid::Uuid::new_v4()));
|
||||||
|
for path in files {
|
||||||
|
let file = root.join(path);
|
||||||
|
std::fs::create_dir_all(file.parent().expect("parent")).expect("mkdir");
|
||||||
|
std::fs::write(file, "x").expect("write");
|
||||||
|
}
|
||||||
|
std::fs::create_dir_all(&root).expect("root");
|
||||||
|
Self(root)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Tree {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = std::fs::remove_dir_all(&self.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn langs(codes: &[&str]) -> Vec<String> {
|
||||||
|
codes.iter().map(|c| c.to_string()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn findings_for(
|
||||||
|
files: &[&str],
|
||||||
|
languages: &[&str],
|
||||||
|
sbom: &[SbomEntry],
|
||||||
|
unlocked: &[UnlockedEcosystem],
|
||||||
|
) -> Vec<Finding> {
|
||||||
|
let tree = Tree::with(files);
|
||||||
|
let languages = langs(languages);
|
||||||
|
let vendor = vec!["vendor".to_string()];
|
||||||
|
coverage_findings(
|
||||||
|
&ScannedTree {
|
||||||
|
repo_id: "t1",
|
||||||
|
root: &tree.0,
|
||||||
|
vendor: &vendor,
|
||||||
|
languages: &languages,
|
||||||
|
yocto_layers: false,
|
||||||
|
firmware_sbom: false,
|
||||||
|
},
|
||||||
|
sbom,
|
||||||
|
unlocked,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn entry(package_manager: &str, purl: Option<&str>) -> SbomEntry {
|
||||||
|
let mut e = SbomEntry::new(
|
||||||
|
"t1".into(),
|
||||||
|
"lib".into(),
|
||||||
|
"1.0".into(),
|
||||||
|
package_manager.into(),
|
||||||
|
);
|
||||||
|
e.purl = purl.map(str::to_string);
|
||||||
|
e
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unlocked(manifest: &str, legacy_build: bool) -> UnlockedEcosystem {
|
||||||
|
UnlockedEcosystem {
|
||||||
|
manifest: manifest.into(),
|
||||||
|
problem: "declares dependencies but no lockfile pins them",
|
||||||
|
remedy: "commit Cargo.lock",
|
||||||
|
legacy_build,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn code_without_any_manifest_is_a_medium_finding_per_ecosystem() {
|
||||||
|
let found = findings_for(
|
||||||
|
&["app/main.py", "web/app.ts", "web/util.js"],
|
||||||
|
&["javascript", "python", "typescript"],
|
||||||
|
&[],
|
||||||
|
&[],
|
||||||
|
);
|
||||||
|
|
||||||
|
let titles: Vec<&str> = found.iter().map(|f| f.title.as_str()).collect();
|
||||||
|
assert_eq!(
|
||||||
|
titles,
|
||||||
|
[
|
||||||
|
"No package manifest: the SBOM lists no libraries of the Python code",
|
||||||
|
"No package manifest: the SBOM lists no libraries of the JavaScript/TypeScript \
|
||||||
|
code",
|
||||||
|
]
|
||||||
|
);
|
||||||
|
let python = &found[0];
|
||||||
|
assert_eq!(python.severity, Severity::Medium);
|
||||||
|
assert_eq!(python.rule_id.as_deref(), Some(NO_MANIFEST_RULE));
|
||||||
|
assert_eq!(python.scanner, SCANNER);
|
||||||
|
assert_eq!(python.control_refs, [SBOM_CONTROL]);
|
||||||
|
assert_eq!(python.file_path, None);
|
||||||
|
assert!(python
|
||||||
|
.remediation
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(|r| r.contains("pip freeze > requirements.txt")));
|
||||||
|
// Stable across scans, one per ecosystem.
|
||||||
|
assert_ne!(found[0].fingerprint, found[1].fingerprint);
|
||||||
|
let again = findings_for(&["main.py"], &["python"], &[], &[]);
|
||||||
|
assert_eq!(again[0].fingerprint, python.fingerprint);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_manifest_or_lockfile_anywhere_outside_vendor_code_counts() {
|
||||||
|
for (manifest, language) in [
|
||||||
|
("backend/requirements-dev.txt", "python"),
|
||||||
|
("pyproject.toml", "python"),
|
||||||
|
("frontend/package.json", "javascript"),
|
||||||
|
("Cargo.lock", "rust"),
|
||||||
|
("svc/go.mod", "go"),
|
||||||
|
("app/build.gradle.kts", "kotlin"),
|
||||||
|
("pom.xml", "java"),
|
||||||
|
("src/App/App.csproj", "csharp"),
|
||||||
|
("composer.json", "php"),
|
||||||
|
("tool.gemspec", "ruby"),
|
||||||
|
("app/pubspec.yaml", "dart"),
|
||||||
|
] {
|
||||||
|
let found = findings_for(&[manifest], &[language], &[], &[]);
|
||||||
|
assert!(found.is_empty(), "{manifest} declares {language}");
|
||||||
|
}
|
||||||
|
// A vendored library's manifest is not the customer code's.
|
||||||
|
let found = findings_for(&["vendor/lib/package.json"], &["javascript"], &[], &[]);
|
||||||
|
assert_eq!(found.len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn c_cpp_firmware_sources_and_yocto_never_ask_for_a_manifest() {
|
||||||
|
// An embedded C tree with a flashing script.
|
||||||
|
assert!(findings_for(&["tools/flash.py"], &["c", "python"], &[], &[]).is_empty());
|
||||||
|
assert!(findings_for(&["tools/flash.py"], &["cpp", "python"], &[], &[]).is_empty());
|
||||||
|
assert!(findings_for(&["lib/oe/x.py"], &["bitbake", "python"], &[], &[]).is_empty());
|
||||||
|
// Components read from the sources are an SBOM.
|
||||||
|
for manager in ["embedded", "codesys", "yocto-recipe"] {
|
||||||
|
let sbom = [entry(manager, None)];
|
||||||
|
assert!(
|
||||||
|
findings_for(&["main.py"], &["python"], &sbom, &[]).is_empty(),
|
||||||
|
"{manager}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// So are the firmware SBOM and a Yocto layer tree.
|
||||||
|
let tree = Tree::with(&["main.py"]);
|
||||||
|
let languages = langs(&["python"]);
|
||||||
|
for (yocto_layers, firmware_sbom) in [(true, false), (false, true)] {
|
||||||
|
let found = coverage_findings(
|
||||||
|
&ScannedTree {
|
||||||
|
repo_id: "t1",
|
||||||
|
root: &tree.0,
|
||||||
|
vendor: &[],
|
||||||
|
languages: &languages,
|
||||||
|
yocto_layers,
|
||||||
|
firmware_sbom,
|
||||||
|
},
|
||||||
|
&[],
|
||||||
|
&[],
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
found.is_empty(),
|
||||||
|
"yocto {yocto_layers}, firmware {firmware_sbom}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn components_of_the_ecosystem_already_listed_need_no_manifest() {
|
||||||
|
// Committed jars give Maven components without a pom.xml.
|
||||||
|
let sbom = [entry("maven", Some("pkg:maven/org.slf4j/slf4j-api@2.0.9"))];
|
||||||
|
assert!(findings_for(&["Main.java"], &["java"], &sbom, &[]).is_empty());
|
||||||
|
// Components of another ecosystem do not.
|
||||||
|
let found = findings_for(&["Main.java", "main.py"], &["java", "python"], &sbom, &[]);
|
||||||
|
assert_eq!(found.len(), 1);
|
||||||
|
assert!(found[0].title.contains("Python"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn dart_is_covered() {
|
||||||
|
let found = findings_for(&["lib/main.dart"], &["dart"], &[], &[]);
|
||||||
|
assert_eq!(found.len(), 1);
|
||||||
|
assert!(found[0]
|
||||||
|
.remediation
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(|r| r.contains("pubspec.lock")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_unresolved_manifest_is_a_low_finding_and_legacy_builds_are_not_repeated() {
|
||||||
|
let found = findings_for(
|
||||||
|
&["Cargo.toml", "src/main.rs"],
|
||||||
|
&["rust"],
|
||||||
|
&[],
|
||||||
|
&[
|
||||||
|
unlocked("Cargo.toml", false),
|
||||||
|
unlocked("app/project.properties", true),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(found.len(), 1);
|
||||||
|
let f = &found[0];
|
||||||
|
assert_eq!(f.severity, Severity::Low);
|
||||||
|
assert_eq!(f.rule_id.as_deref(), Some(UNRESOLVED_RULE));
|
||||||
|
assert_eq!(f.file_path.as_deref(), Some("Cargo.toml"));
|
||||||
|
assert_eq!(f.line_number, None);
|
||||||
|
assert_eq!(f.control_refs, [SBOM_CONTROL]);
|
||||||
|
assert_eq!(
|
||||||
|
f.title,
|
||||||
|
"Dependencies not resolved: the SBOM is incomplete (Cargo.toml)"
|
||||||
|
);
|
||||||
|
assert!(f
|
||||||
|
.description
|
||||||
|
.starts_with("Cargo.toml declares dependencies but no lockfile pins them."));
|
||||||
|
assert_eq!(
|
||||||
|
f.remediation.as_deref(),
|
||||||
|
Some("Commit Cargo.lock. The finding closes at the next scan that finds the lockfile.")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_stamped_requirement_is_the_one_the_control_map_binds() {
|
||||||
|
let map = control_map::ControlMap::cra().expect("map");
|
||||||
|
for rule in [NO_MANIFEST_RULE, UNRESOLVED_RULE] {
|
||||||
|
let controls: Vec<&str> = map
|
||||||
|
.bindings_for_finding(SCANNER, Some(CWE), Some(rule))
|
||||||
|
.into_iter()
|
||||||
|
.map(|(entry, _)| entry.control.as_str())
|
||||||
|
.collect();
|
||||||
|
assert_eq!(controls, [SBOM_CONTROL], "{rule}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_tree_without_package_manager_code_has_no_findings() {
|
||||||
|
assert!(findings_for(&["README.md"], &[], &[], &[]).is_empty());
|
||||||
|
assert!(findings_for(&["App.swift"], &["swift"], &[], &[]).is_empty());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
//! The Siemens controllers a target runs on ([`PlcDevice`], SPS item 4a) as
|
||||||
|
//! SBOM entries: one per device, named and versioned as the customer
|
||||||
|
//! entered it or a TIA export declares it (#1090), with the order number the
|
||||||
|
//! vendor's CSAF advisories name it by (matched in
|
||||||
|
//! [`crate::pipeline::csaf_match`]).
|
||||||
|
|
||||||
|
use compliance_core::models::{SbomEntry, TargetDevice};
|
||||||
|
|
||||||
|
/// The package manager of a device entry.
|
||||||
|
pub(crate) const DEVICE_MANAGER: &str = "siemens-device";
|
||||||
|
|
||||||
|
/// The SBOM entries of target `repo_id`'s devices
|
||||||
|
/// ([`compliance_core::models::OnboardedTarget::target_devices`]). A device
|
||||||
|
/// is named by its order number, so two devices of one type at one firmware
|
||||||
|
/// are one entry; where it is known from, and its label, are kept as
|
||||||
|
/// evidence.
|
||||||
|
pub(crate) fn entries(devices: &[TargetDevice], repo_id: &str) -> Vec<SbomEntry> {
|
||||||
|
let mut entries: Vec<SbomEntry> = Vec::with_capacity(devices.len());
|
||||||
|
for TargetDevice {
|
||||||
|
device,
|
||||||
|
exported_in,
|
||||||
|
} in devices
|
||||||
|
{
|
||||||
|
let evidence = match (exported_in, device.label.as_deref()) {
|
||||||
|
(Some(file), Some(label)) => format!("configured as {label} in the TIA export {file}"),
|
||||||
|
(Some(file), None) => format!("configured in the TIA export {file}"),
|
||||||
|
(None, Some(label)) => format!("entered as {label}"),
|
||||||
|
(None, None) => "entered with the target".to_string(),
|
||||||
|
};
|
||||||
|
if let Some(known) = entries
|
||||||
|
.iter_mut()
|
||||||
|
.find(|e| e.name == device.order_number && e.version == device.firmware)
|
||||||
|
{
|
||||||
|
if !known.evidence.contains(&evidence) {
|
||||||
|
known.evidence.push(evidence);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut entry = SbomEntry::new(
|
||||||
|
repo_id.to_string(),
|
||||||
|
device.order_number.clone(),
|
||||||
|
device.firmware.clone(),
|
||||||
|
DEVICE_MANAGER.to_string(),
|
||||||
|
);
|
||||||
|
entry.order_number = Some(device.order_number.clone());
|
||||||
|
entry.evidence = vec![evidence];
|
||||||
|
entries.push(entry);
|
||||||
|
}
|
||||||
|
entries
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[allow(clippy::unwrap_used)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use compliance_core::models::PlcDevice;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn each_device_type_and_firmware_is_one_entry() {
|
||||||
|
let devices = [
|
||||||
|
PlcDevice::new("6ES7511-1AK02-0AB0", "V3.1.4", Some("Zelle 1")).unwrap(),
|
||||||
|
PlcDevice::new("6es7511-1ak02-0ab0", "3.1.4", Some("Zelle 2")).unwrap(),
|
||||||
|
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.5", None).unwrap(),
|
||||||
|
];
|
||||||
|
|
||||||
|
let devices: Vec<TargetDevice> = devices.into_iter().map(TargetDevice::from).collect();
|
||||||
|
let entries = entries(&devices, "t");
|
||||||
|
|
||||||
|
assert_eq!(entries.len(), 2);
|
||||||
|
let first = &entries[0];
|
||||||
|
assert_eq!(
|
||||||
|
(
|
||||||
|
first.name.as_str(),
|
||||||
|
first.version.as_str(),
|
||||||
|
first.package_manager.as_str()
|
||||||
|
),
|
||||||
|
("6ES7511-1AK02-0AB0", "3.1.4", DEVICE_MANAGER)
|
||||||
|
);
|
||||||
|
assert_eq!(first.order_number.as_deref(), Some("6ES7511-1AK02-0AB0"));
|
||||||
|
assert_eq!(first.evidence, ["entered as Zelle 1", "entered as Zelle 2"]);
|
||||||
|
assert_eq!(entries[1].evidence, ["entered with the target"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_exported_device_says_which_export_configures_it() {
|
||||||
|
let exported = TargetDevice {
|
||||||
|
device: PlcDevice::new("6ES7511-1AK02-0AB0", "2.9", Some("PLC_1")).unwrap(),
|
||||||
|
exported_in: Some("linie1.tia-export.zip".into()),
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
entries(&[exported], "t")[0].evidence,
|
||||||
|
["configured as PLC_1 in the TIA export linie1.tia-export.zip"]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -147,6 +147,7 @@ pub(crate) fn unlocked_mobile_ecosystems(root: &Path) -> Vec<UnlockedEcosystem>
|
|||||||
manifest,
|
manifest,
|
||||||
problem: eco.problem,
|
problem: eco.problem,
|
||||||
remedy: eco.remedy,
|
remedy: eco.remedy,
|
||||||
|
legacy_build: false,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
mod cargo_audit;
|
mod cargo_audit;
|
||||||
pub(crate) mod carthage;
|
pub(crate) mod carthage;
|
||||||
|
pub(crate) mod coverage;
|
||||||
|
pub(crate) mod devices;
|
||||||
mod distribution;
|
mod distribution;
|
||||||
mod gradle;
|
mod gradle;
|
||||||
mod mobile;
|
mod mobile;
|
||||||
@@ -15,6 +17,7 @@ pub(crate) use nuget::nuget_components;
|
|||||||
pub(crate) use nuget_license::{LicenseCache, MongoLicenseCache, NugetRegistry};
|
pub(crate) use nuget_license::{LicenseCache, MongoLicenseCache, NugetRegistry};
|
||||||
pub(crate) use nuget_resolve::enabled as nuget_resolution_enabled;
|
pub(crate) use nuget_resolve::enabled as nuget_resolution_enabled;
|
||||||
pub(crate) use registry_license::RegistryLicenses;
|
pub(crate) use registry_license::RegistryLicenses;
|
||||||
|
pub(crate) mod supplied;
|
||||||
mod syft;
|
mod syft;
|
||||||
pub(crate) mod unity;
|
pub(crate) mod unity;
|
||||||
|
|
||||||
@@ -224,6 +227,9 @@ pub(crate) struct UnlockedEcosystem {
|
|||||||
pub problem: &'static str,
|
pub problem: &'static str,
|
||||||
/// What to commit so they are.
|
/// What to commit so they are.
|
||||||
pub remedy: &'static str,
|
pub remedy: &'static str,
|
||||||
|
/// A legacy build system ([`crate::pipeline::build_lifecycle`]), which
|
||||||
|
/// is a finding of its own already.
|
||||||
|
pub legacy_build: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Lockfiles that pin an npm-registry project. Bun's count: npm must never
|
/// Lockfiles that pin an npm-registry project. Bun's count: npm must never
|
||||||
@@ -266,12 +272,14 @@ pub(crate) fn unlocked_ecosystems(
|
|||||||
manifest: "package.json".into(),
|
manifest: "package.json".into(),
|
||||||
problem: "is locked only by bun.lockb, Bun's binary lockfile, which is not read",
|
problem: "is locked only by bun.lockb, Bun's binary lockfile, which is not read",
|
||||||
remedy: "commit the text bun.lock (`bun install --save-text-lockfile`)",
|
remedy: "commit the text bun.lock (`bun install --save-text-lockfile`)",
|
||||||
|
legacy_build: false,
|
||||||
});
|
});
|
||||||
} else if !readable {
|
} else if !readable {
|
||||||
out.push(UnlockedEcosystem {
|
out.push(UnlockedEcosystem {
|
||||||
manifest: "package.json".into(),
|
manifest: "package.json".into(),
|
||||||
problem: "declares dependencies but no lockfile pins them",
|
problem: "declares dependencies but no lockfile pins them",
|
||||||
remedy: "commit package-lock.json, yarn.lock, pnpm-lock.yaml or bun.lock",
|
remedy: "commit package-lock.json, yarn.lock, pnpm-lock.yaml or bun.lock",
|
||||||
|
legacy_build: false,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -284,6 +292,7 @@ pub(crate) fn unlocked_ecosystems(
|
|||||||
manifest: manifest.into(),
|
manifest: manifest.into(),
|
||||||
problem: "declares dependencies but no lockfile pins them",
|
problem: "declares dependencies but no lockfile pins them",
|
||||||
remedy: "commit requirements.txt, poetry.lock, Pipfile.lock or uv.lock",
|
remedy: "commit requirements.txt, poetry.lock, Pipfile.lock or uv.lock",
|
||||||
|
legacy_build: false,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -292,6 +301,7 @@ pub(crate) fn unlocked_ecosystems(
|
|||||||
manifest: "Cargo.toml".into(),
|
manifest: "Cargo.toml".into(),
|
||||||
problem: "declares dependencies but no lockfile pins them",
|
problem: "declares dependencies but no lockfile pins them",
|
||||||
remedy: "commit Cargo.lock",
|
remedy: "commit Cargo.lock",
|
||||||
|
legacy_build: false,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
out.extend(mobile::unlocked_mobile_ecosystems(repo_path));
|
out.extend(mobile::unlocked_mobile_ecosystems(repo_path));
|
||||||
@@ -307,6 +317,7 @@ pub(crate) fn unlocked_ecosystems(
|
|||||||
Packages/manifest.json) whose dependencies cannot be read",
|
Packages/manifest.json) whose dependencies cannot be read",
|
||||||
remedy: "migrate the build (Gradle with the Android Gradle Plugin, or a \
|
remedy: "migrate the build (Gradle with the Android Gradle Plugin, or a \
|
||||||
current Unity LTS with the Package Manager)",
|
current Unity LTS with the Package Manager)",
|
||||||
|
legacy_build: true,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
out.extend(nuget::unresolved_projects(repo_path, resolved_nuget));
|
out.extend(nuget::unresolved_projects(repo_path, resolved_nuget));
|
||||||
|
|||||||
@@ -250,6 +250,7 @@ pub(crate) fn unresolved_projects(root: &Path, resolved: &[String]) -> Vec<Unloc
|
|||||||
remedy: "set <RestorePackagesWithLockFile>true</RestorePackagesWithLockFile> (in the \
|
remedy: "set <RestorePackagesWithLockFile>true</RestorePackagesWithLockFile> (in the \
|
||||||
project or a Directory.Build.props), restore once and commit \
|
project or a Directory.Build.props), restore once and commit \
|
||||||
packages.lock.json",
|
packages.lock.json",
|
||||||
|
legacy_build: false,
|
||||||
}]
|
}]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -263,7 +263,7 @@ pub(super) fn canonical_purl(purl: String) -> String {
|
|||||||
|
|
||||||
/// Extract the ecosystem/package-manager from a PURL string.
|
/// Extract the ecosystem/package-manager from a PURL string.
|
||||||
/// e.g. "pkg:npm/lodash@4.17.21" -> "npm", "pkg:cargo/serde@1.0" -> "cargo"
|
/// e.g. "pkg:npm/lodash@4.17.21" -> "npm", "pkg:cargo/serde@1.0" -> "cargo"
|
||||||
fn extract_ecosystem_from_purl(purl: &str) -> Option<String> {
|
pub(super) fn extract_ecosystem_from_purl(purl: &str) -> Option<String> {
|
||||||
let rest = purl.strip_prefix("pkg:")?;
|
let rest = purl.strip_prefix("pkg:")?;
|
||||||
let ecosystem = rest.split('/').next()?;
|
let ecosystem = rest.split('/').next()?;
|
||||||
if ecosystem.is_empty() {
|
if ecosystem.is_empty() {
|
||||||
|
|||||||
@@ -2,10 +2,12 @@
|
|||||||
//!
|
//!
|
||||||
//! An alert is stored once per CVE and target. Reported again, it is updated
|
//! An alert is stored once per CVE and target. Reported again, it is updated
|
||||||
//! and counts as open: a `fixed` the scan had stated is withdrawn. When a
|
//! and counts as open: a `fixed` the scan had stated is withdrawn. When a
|
||||||
//! complete lookup no longer reports it (the component removed or updated
|
//! complete lookup no longer reports it, it is marked resolved, and its VEX
|
||||||
//! past the fix), it is marked resolved, and one nobody assessed, or
|
//! status stays as it was: that a CVE is gone is no evidence of a fix, so a
|
||||||
//! assessed as affected, gets the VEX status `fixed` from the scan. A
|
//! scan never states `fixed` for it (#994). A `fixed` scans stated that way
|
||||||
//! person's `not_affected` or `fixed` is never changed by a scan. What a
|
//! before is read as no statement ([`CveAlert::statement`]) and withdrawn
|
||||||
|
//! when the CVE is reported again. A person's statement is never changed by
|
||||||
|
//! a scan. What a
|
||||||
//! scan states from the target's own data (a Yocto recipe's CVE_STATUS or
|
//! scan states from the target's own data (a Yocto recipe's CVE_STATUS or
|
||||||
//! `CVE:` patch) is stated again on every scan, and likewise never replaces
|
//! `CVE:` patch) is stated again on every scan, and likewise never replaces
|
||||||
//! a person's statement. The first
|
//! a person's statement. The first
|
||||||
@@ -20,7 +22,7 @@
|
|||||||
use futures_util::TryStreamExt;
|
use futures_util::TryStreamExt;
|
||||||
use mongodb::bson::doc;
|
use mongodb::bson::doc;
|
||||||
|
|
||||||
use compliance_core::models::{CveAlert, StatusChange, VexAssessment, VexStatus};
|
use compliance_core::models::{CveAlert, VexAssessment};
|
||||||
|
|
||||||
use crate::database::{Database, DatabasePool};
|
use crate::database::{Database, DatabasePool};
|
||||||
use crate::error::AgentError;
|
use crate::error::AgentError;
|
||||||
@@ -110,8 +112,12 @@ pub async fn upsert_reported(db: &Database, alert: &CveAlert) -> Result<(), Agen
|
|||||||
let filter = doc! { "cve_id": &alert.cve_id, "repo_id": &alert.repo_id };
|
let filter = doc! { "cve_id": &alert.cve_id, "repo_id": &alert.repo_id };
|
||||||
// The alert as found now; a VEX statement on it is left as it is (the
|
// The alert as found now; a VEX statement on it is left as it is (the
|
||||||
// alert carries none), and it is reported again.
|
// alert carries none), and it is reported again.
|
||||||
let found = mongodb::bson::to_document(alert)
|
let mut found = mongodb::bson::to_document(alert)
|
||||||
.map_err(|e| AgentError::Other(format!("encode CVE alert: {e}")))?;
|
.map_err(|e| AgentError::Other(format!("encode CVE alert: {e}")))?;
|
||||||
|
// When it was first found is written once (#1041): every scan builds its
|
||||||
|
// alerts anew, and a rescan must neither list it as new again nor move
|
||||||
|
// it later in the CVE history.
|
||||||
|
let first_found = found.remove("created_at");
|
||||||
// A purl is written when the scan knows one and otherwise kept (an alert
|
// A purl is written when the scan knows one and otherwise kept (an alert
|
||||||
// stored before purls were recorded gets one on its next scan); kept only
|
// stored before purls were recorded gets one on its next scan); kept only
|
||||||
// while it is the purl of the same package and version.
|
// while it is the purl of the same package and version.
|
||||||
@@ -128,11 +134,18 @@ pub async fn upsert_reported(db: &Database, alert: &CveAlert) -> Result<(), Agen
|
|||||||
.update_one(other_component, doc! { "$unset": { "purl": "" } })
|
.update_one(other_component, doc! { "$unset": { "purl": "" } })
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
|
// A supplier's statement (#1025) is restated by every scan; one the
|
||||||
|
// supplier no longer makes goes.
|
||||||
|
let mut unset = doc! { "resolved_at": "" };
|
||||||
|
if alert.supplier_vex.is_none() {
|
||||||
|
unset.insert("supplier_vex", "");
|
||||||
|
}
|
||||||
|
let mut update = doc! { "$set": found, "$unset": unset };
|
||||||
|
if let Some(first_found) = first_found {
|
||||||
|
update.insert("$setOnInsert", doc! { "created_at": first_found });
|
||||||
|
}
|
||||||
db.cve_alerts()
|
db.cve_alerts()
|
||||||
.update_one(
|
.update_one(filter.clone(), update)
|
||||||
filter.clone(),
|
|
||||||
doc! { "$set": found, "$unset": { "resolved_at": "" } },
|
|
||||||
)
|
|
||||||
.upsert(true)
|
.upsert(true)
|
||||||
.await?;
|
.await?;
|
||||||
// The first scan that finds it actively exploited starts the CRA's
|
// The first scan that finds it actively exploited starts the CRA's
|
||||||
@@ -297,6 +310,11 @@ pub async fn attach_stored_vex(
|
|||||||
/// Mark resolved the stored alerts of `repo_id` a complete lookup
|
/// Mark resolved the stored alerts of `repo_id` a complete lookup
|
||||||
/// (`complete`) no longer reports in `current`.
|
/// (`complete`) no longer reports in `current`.
|
||||||
///
|
///
|
||||||
|
/// That is what the scan observed, not a VEX statement: each alert keeps the
|
||||||
|
/// statement it has, and one without stays without. A CVE can disappear for
|
||||||
|
/// other reasons than a fix (other scan data, an incomplete inventory, a
|
||||||
|
/// changed identification), so only a person states `fixed` (#994).
|
||||||
|
///
|
||||||
/// # Returns
|
/// # Returns
|
||||||
///
|
///
|
||||||
/// How many were resolved.
|
/// How many were resolved.
|
||||||
@@ -313,52 +331,25 @@ pub async fn resolve_gone(
|
|||||||
if !complete {
|
if !complete {
|
||||||
return Ok(0);
|
return Ok(0);
|
||||||
}
|
}
|
||||||
let now = mongodb::bson::DateTime::now();
|
|
||||||
let seen: Vec<&str> = current.iter().map(|a| a.cve_id.as_str()).collect();
|
let seen: Vec<&str> = current.iter().map(|a| a.cve_id.as_str()).collect();
|
||||||
let gone = doc! {
|
|
||||||
"repo_id": repo_id,
|
|
||||||
"cve_id": { "$nin": seen },
|
|
||||||
"resolved_at": { "$exists": false },
|
|
||||||
};
|
|
||||||
let fixed = VexAssessment {
|
|
||||||
status: VexStatus::Fixed,
|
|
||||||
justification: None,
|
|
||||||
impact_statement: None,
|
|
||||||
action_statement: None,
|
|
||||||
by: StatusChange::SCAN_ACTOR.to_string(),
|
|
||||||
by_name: None,
|
|
||||||
at: chrono::Utc::now(),
|
|
||||||
by_scan: true,
|
|
||||||
};
|
|
||||||
let fixed = mongodb::bson::to_bson(&fixed)
|
|
||||||
.map_err(|e| AgentError::Other(format!("encode VEX: {e}")))?;
|
|
||||||
let mut unassessed = gone.clone();
|
|
||||||
unassessed.insert(
|
|
||||||
"$or",
|
|
||||||
mongodb::bson::bson!([
|
|
||||||
{ "vex": { "$exists": false } },
|
|
||||||
{ "vex.status": { "$in": ["under_investigation", "affected"] } },
|
|
||||||
]),
|
|
||||||
);
|
|
||||||
let became_fixed = db
|
|
||||||
.cve_alerts()
|
|
||||||
.update_many(
|
|
||||||
unassessed,
|
|
||||||
doc! { "$set": { "resolved_at": now, "vex": fixed } },
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
let resolved = db
|
let resolved = db
|
||||||
.cve_alerts()
|
.cve_alerts()
|
||||||
.update_many(gone, doc! { "$set": { "resolved_at": now } })
|
.update_many(
|
||||||
.await?;
|
doc! {
|
||||||
let total = became_fixed.modified_count + resolved.modified_count;
|
"repo_id": repo_id,
|
||||||
if total > 0 {
|
"cve_id": { "$nin": seen },
|
||||||
|
"resolved_at": { "$exists": false },
|
||||||
|
},
|
||||||
|
doc! { "$set": { "resolved_at": mongodb::bson::DateTime::now() } },
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
.modified_count;
|
||||||
|
if resolved > 0 {
|
||||||
tracing::info!(
|
tracing::info!(
|
||||||
repo_id,
|
repo_id,
|
||||||
resolved = total,
|
resolved,
|
||||||
fixed_by_scan = became_fixed.modified_count,
|
|
||||||
"CVE alerts no longer found marked resolved"
|
"CVE alerts no longer found marked resolved"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
Ok(total)
|
Ok(resolved)
|
||||||
}
|
}
|
||||||
@@ -39,6 +39,69 @@ const TOKEN_MARGIN: Duration = Duration::from_secs(30);
|
|||||||
/// client's 30 s.
|
/// client's 30 s.
|
||||||
const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
|
const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
|
||||||
|
|
||||||
|
/// One of the tenant's active connections to another workspace (#1028,
|
||||||
|
/// tenant-registry#138), as a product reads it. The peer's tenant id is for
|
||||||
|
/// delivering to it inside the product; it is never shown to anyone.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||||
|
pub struct Connection {
|
||||||
|
/// The connection's id.
|
||||||
|
pub id: String,
|
||||||
|
/// The other workspace's tenant id.
|
||||||
|
pub peer_tenant_id: String,
|
||||||
|
/// The other workspace's display name: all either side sees of the other.
|
||||||
|
pub peer_name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One connection as the registry checks it
|
||||||
|
/// (`GET /v1/internal/connections/{id}`).
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||||
|
pub struct ConnectionState {
|
||||||
|
/// Whether it is active: accepted and not ended.
|
||||||
|
pub active: bool,
|
||||||
|
/// The two tenants it joins.
|
||||||
|
pub tenant_ids: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ConnectionState {
|
||||||
|
/// The tenant on the other side from `tenant`, while the connection is
|
||||||
|
/// active and `tenant` is one of its two sides; `None` otherwise. What a
|
||||||
|
/// delivery asks right before it writes to another tenant's database.
|
||||||
|
pub fn peer_of(&self, tenant: &str) -> Option<&str> {
|
||||||
|
let [a, b] = self.tenant_ids.as_slice() else {
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
match (self.active, a == b) {
|
||||||
|
(false, _) | (_, true) => None,
|
||||||
|
_ if a == tenant => Some(b),
|
||||||
|
_ if b == tenant => Some(a),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A document of the tenant's store (Dokumentenablage), as the registry
|
||||||
|
/// lists it (`GET /v1/tenants/{id}/store`).
|
||||||
|
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
|
||||||
|
pub struct StoreDocument {
|
||||||
|
pub id: String,
|
||||||
|
pub title: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub filename: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub content_type: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub size_bytes: Option<u64>,
|
||||||
|
/// `legal_web`, `product_public` or `internal`; none for BreakPilot's
|
||||||
|
/// deliveries.
|
||||||
|
#[serde(default)]
|
||||||
|
pub area: Option<String>,
|
||||||
|
/// The product projects it belongs to.
|
||||||
|
#[serde(default)]
|
||||||
|
pub project_ids: Vec<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub created_at: Option<chrono::DateTime<chrono::Utc>>,
|
||||||
|
}
|
||||||
|
|
||||||
/// The registry's `reason` for a member blocked in the tenant.
|
/// The registry's `reason` for a member blocked in the tenant.
|
||||||
pub const MEMBER_BLOCKED: &str = "member_blocked";
|
pub const MEMBER_BLOCKED: &str = "member_blocked";
|
||||||
|
|
||||||
@@ -55,6 +118,72 @@ pub struct EntitlementCheck {
|
|||||||
pub expires_at: Option<String>,
|
pub expires_at: Option<String>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub reason: Option<String>,
|
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 {
|
impl EntitlementCheck {
|
||||||
@@ -71,6 +200,13 @@ impl EntitlementCheck {
|
|||||||
self.limit("included_targets")
|
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
|
/// The plan's monthly quota and the customer's Prüftag cap (t72), from
|
||||||
/// `limits.monthly_pruefungen` and `limits.prueftag_cap`; a missing or
|
/// `limits.monthly_pruefungen` and `limits.prueftag_cap`; a missing or
|
||||||
/// null key is no limit.
|
/// null key is no limit.
|
||||||
@@ -242,6 +378,9 @@ pub struct RegistryClient {
|
|||||||
/// API-key verdicts, valid and invalid, keyed by the key's SHA-256 (never
|
/// API-key verdicts, valid and invalid, keyed by the key's SHA-256 (never
|
||||||
/// the key itself), for [`API_KEY_TTL`].
|
/// the key itself), for [`API_KEY_TTL`].
|
||||||
api_keys: DashMap<String, (Instant, ApiKeyVerify)>,
|
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 {
|
impl std::fmt::Debug for RegistryClient {
|
||||||
@@ -285,6 +424,7 @@ impl RegistryClient {
|
|||||||
cache: DashMap::new(),
|
cache: DashMap::new(),
|
||||||
projects: DashMap::new(),
|
projects: DashMap::new(),
|
||||||
api_keys: DashMap::new(),
|
api_keys: DashMap::new(),
|
||||||
|
logos: DashMap::new(),
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -406,6 +546,113 @@ impl RegistryClient {
|
|||||||
Ok(check)
|
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).
|
/// Drop the cached answer for a tenant (after a platform lifecycle call).
|
||||||
pub fn invalidate(&self, tenant_id: &str) {
|
pub fn invalidate(&self, tenant_id: &str) {
|
||||||
self.cache
|
self.cache
|
||||||
@@ -531,6 +778,107 @@ impl RegistryClient {
|
|||||||
Ok(page.items)
|
Ok(page.items)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The tenant's document store (Dokumentenablage): its published
|
||||||
|
/// documents, by area. Not cached: it is read when a product's box is
|
||||||
|
/// opened on the Lieferkette (#1054).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// The registry could not be asked, or answered with an error.
|
||||||
|
pub async fn list_store(&self, tenant_id: &str) -> Result<Vec<StoreDocument>, String> {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Page {
|
||||||
|
#[serde(default)]
|
||||||
|
items: Vec<StoreDocument>,
|
||||||
|
}
|
||||||
|
let resp = self
|
||||||
|
.request(
|
||||||
|
reqwest::Method::GET,
|
||||||
|
&format!("/v1/tenants/{}/store", urlencoding::encode(tenant_id)),
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("store list failed: {e}"))?;
|
||||||
|
if !resp.status().is_success() {
|
||||||
|
return Err(format!("store list returned {}", resp.status()));
|
||||||
|
}
|
||||||
|
let page: Page = resp
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("store list invalid: {e}"))?;
|
||||||
|
Ok(page.items)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The tenant's active connections to other workspaces (#1028). Not
|
||||||
|
/// cached: a connection ended a second ago must not be offered.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// The registry could not be asked, or answered with an error other than
|
||||||
|
/// 404.
|
||||||
|
pub async fn active_connections(&self, tenant_id: &str) -> Result<Vec<Connection>, String> {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Page {
|
||||||
|
#[serde(default)]
|
||||||
|
items: Vec<Connection>,
|
||||||
|
}
|
||||||
|
let resp = self
|
||||||
|
.request(
|
||||||
|
reqwest::Method::GET,
|
||||||
|
&format!(
|
||||||
|
"/v1/internal/tenants/{}/connections?state=active",
|
||||||
|
urlencoding::encode(tenant_id)
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("connection list failed: {e}"))?;
|
||||||
|
// A registry without connections for the tenant (or, before
|
||||||
|
// tenant-registry#138, without the route) has none to list.
|
||||||
|
if resp.status() == reqwest::StatusCode::NOT_FOUND {
|
||||||
|
return Ok(Vec::new());
|
||||||
|
}
|
||||||
|
if !resp.status().is_success() {
|
||||||
|
return Err(format!("connection list returned {}", resp.status()));
|
||||||
|
}
|
||||||
|
let page: Page = resp
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("connection list invalid: {e}"))?;
|
||||||
|
Ok(page.items)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Connection `id` as the registry knows it now; `None` when it knows no
|
||||||
|
/// such connection. Asked right before every delivery over it.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// The registry could not be asked, or answered with an error other than
|
||||||
|
/// 404.
|
||||||
|
pub async fn connection(&self, id: &str) -> Result<Option<ConnectionState>, String> {
|
||||||
|
let resp = self
|
||||||
|
.request(
|
||||||
|
reqwest::Method::GET,
|
||||||
|
&format!("/v1/internal/connections/{}", urlencoding::encode(id)),
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("connection check failed: {e}"))?;
|
||||||
|
if resp.status() == reqwest::StatusCode::NOT_FOUND {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
if !resp.status().is_success() {
|
||||||
|
return Err(format!("connection check returned {}", resp.status()));
|
||||||
|
}
|
||||||
|
resp.json()
|
||||||
|
.await
|
||||||
|
.map(Some)
|
||||||
|
.map_err(|e| format!("connection check invalid: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
/// Verify a portal-issued API key (`bp_…`), valid or not, reusing a
|
/// Verify a portal-issued API key (`bp_…`), valid or not, reusing a
|
||||||
/// verdict younger than [`API_KEY_TTL`].
|
/// verdict younger than [`API_KEY_TTL`].
|
||||||
///
|
///
|
||||||
@@ -658,6 +1006,42 @@ pub fn scheduler_runs_for(status: &str) -> bool {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_connection_names_the_other_side_only_while_active_and_ours() {
|
||||||
|
let joined = |active: bool, ids: &[&str]| ConnectionState {
|
||||||
|
active,
|
||||||
|
tenant_ids: ids.iter().map(|t| t.to_string()).collect(),
|
||||||
|
};
|
||||||
|
let c = joined(true, &["supplier", "customer"]);
|
||||||
|
assert_eq!(c.peer_of("supplier"), Some("customer"));
|
||||||
|
assert_eq!(c.peer_of("customer"), Some("supplier"));
|
||||||
|
assert_eq!(
|
||||||
|
c.peer_of("someone else"),
|
||||||
|
None,
|
||||||
|
"a third tenant gets nothing"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
joined(false, &["supplier", "customer"]).peer_of("supplier"),
|
||||||
|
None,
|
||||||
|
"ended"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
joined(true, &["supplier", "supplier"]).peer_of("supplier"),
|
||||||
|
None,
|
||||||
|
"itself"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
joined(true, &["supplier"]).peer_of("supplier"),
|
||||||
|
None,
|
||||||
|
"one side"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
joined(true, &["a", "b", "c"]).peer_of("a"),
|
||||||
|
None,
|
||||||
|
"three sides"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_plan_sets_how_many_targets_are_included() {
|
fn the_plan_sets_how_many_targets_are_included() {
|
||||||
let check = |limits: serde_json::Value| -> EntitlementCheck {
|
let check = |limits: serde_json::Value| -> EntitlementCheck {
|
||||||
@@ -677,6 +1061,27 @@ mod tests {
|
|||||||
assert_eq!(check(serde_json::Value::Null).included_targets(), None);
|
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]
|
#[test]
|
||||||
fn the_plan_sets_the_quota_and_the_cap() {
|
fn the_plan_sets_the_quota_and_the_cap() {
|
||||||
let check: EntitlementCheck = serde_json::from_value(serde_json::json!({
|
let check: EntitlementCheck = serde_json::from_value(serde_json::json!({
|
||||||
@@ -735,6 +1140,7 @@ mod tests {
|
|||||||
cache: DashMap::new(),
|
cache: DashMap::new(),
|
||||||
projects: DashMap::new(),
|
projects: DashMap::new(),
|
||||||
api_keys: DashMap::new(),
|
api_keys: DashMap::new(),
|
||||||
|
logos: DashMap::new(),
|
||||||
};
|
};
|
||||||
|
|
||||||
let started = Instant::now();
|
let started = Instant::now();
|
||||||
@@ -791,6 +1197,7 @@ mod tests {
|
|||||||
cache: DashMap::new(),
|
cache: DashMap::new(),
|
||||||
projects: DashMap::new(),
|
projects: DashMap::new(),
|
||||||
api_keys: DashMap::new(),
|
api_keys: DashMap::new(),
|
||||||
|
logos: DashMap::new(),
|
||||||
};
|
};
|
||||||
(client, calls, down)
|
(client, calls, down)
|
||||||
}
|
}
|
||||||
@@ -861,4 +1268,106 @@ mod tests {
|
|||||||
assert!(client.api_keys.contains_key(&key_digest("bp_good")));
|
assert!(client.api_keys.contains_key(&key_digest("bp_good")));
|
||||||
assert!(client.api_keys.iter().all(|e| !e.key().contains("bp_")));
|
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)
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -86,6 +86,7 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError>
|
|||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
crate::pipeline::csaf_feed::refresh_index(&agent.db_pool.admin_db(), agent.net_guard)
|
crate::pipeline::csaf_feed::refresh_index(&agent.db_pool.admin_db(), agent.net_guard)
|
||||||
.await;
|
.await;
|
||||||
|
refresh_supplier_advisories(&agent).await;
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.map_err(|e| AgentError::Scheduler(format!("Failed to create CSAF job: {e}")))?;
|
.map_err(|e| AgentError::Scheduler(format!("Failed to create CSAF job: {e}")))?;
|
||||||
@@ -101,6 +102,7 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError>
|
|||||||
startup_agent.net_guard,
|
startup_agent.net_guard,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
refresh_supplier_advisories(&startup_agent).await;
|
||||||
});
|
});
|
||||||
|
|
||||||
// Managed git sync (#439): the organisation's repositories against the
|
// Managed git sync (#439): the organisation's repositories against the
|
||||||
@@ -191,6 +193,14 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError>
|
|||||||
///
|
///
|
||||||
/// We never panic out of this function — the scheduler must keep
|
/// We never panic out of this function — the scheduler must keep
|
||||||
/// firing even if the registry is offline.
|
/// firing even if the registry is offline.
|
||||||
|
/// Each tenant's supplier CSAF advisories (#1025), one tenant after the
|
||||||
|
/// other, after the shared index.
|
||||||
|
async fn refresh_supplier_advisories(agent: &ComplianceAgent) {
|
||||||
|
for tenant_id in scheduler_tenants(agent).await {
|
||||||
|
crate::pipeline::csaf_feed::refresh_supplier_advisories(agent, &tenant_id).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) async fn scheduler_tenants(agent: &ComplianceAgent) -> Vec<String> {
|
pub(crate) async fn scheduler_tenants(agent: &ComplianceAgent) -> Vec<String> {
|
||||||
if let Some(registry) = agent.registry.as_ref() {
|
if let Some(registry) = agent.registry.as_ref() {
|
||||||
match registry.list_tenants().await {
|
match registry.list_tenants().await {
|
||||||
|
|||||||
@@ -16,24 +16,101 @@ use crate::classify::{classify_target, MockFirmwareDetector};
|
|||||||
use crate::database::Database;
|
use crate::database::Database;
|
||||||
use crate::error::AgentError;
|
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
|
/// Insert a new target for `tenant_id` and emit the `target.added` usage
|
||||||
/// event. Returns the stored record with its id set.
|
/// 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.
|
||||||
pub async fn create_target(
|
pub async fn create_target(
|
||||||
agent: &ComplianceAgent,
|
agent: &ComplianceAgent,
|
||||||
db: &Database,
|
db: &Database,
|
||||||
tenant_id: &str,
|
tenant_id: &str,
|
||||||
mut target: OnboardedTarget,
|
mut target: OnboardedTarget,
|
||||||
) -> Result<OnboardedTarget, AgentError> {
|
) -> 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?;
|
let res = db.onboarded_targets().insert_one(&target).await?;
|
||||||
target.id = res.inserted_id.as_object_id();
|
target.id = res.inserted_id.as_object_id();
|
||||||
// A target beyond the plan's included ones is extra from the start (t72).
|
// A target beyond the plan's included ones is extra from the start (t72).
|
||||||
if let Some((_, billing)) = agent
|
if let Some(plan) = plan {
|
||||||
.refresh_billing(tenant_id, db)
|
if let Some((_, billing)) = agent
|
||||||
.await
|
.assign_billing(tenant_id, db, plan.billed_included())
|
||||||
.into_iter()
|
.await
|
||||||
.find(|(id, _)| Some(*id) == target.id)
|
.into_iter()
|
||||||
{
|
.find(|(id, _)| Some(*id) == target.id)
|
||||||
target.billing = billing;
|
{
|
||||||
|
target.billing = billing;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
|
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
|
||||||
agent.emit_usage(
|
agent.emit_usage(
|
||||||
@@ -111,6 +188,7 @@ pub fn uploaded_artifact(
|
|||||||
ArtifactKind::SourceArchive => Artifact::source_archive(filename),
|
ArtifactKind::SourceArchive => Artifact::source_archive(filename),
|
||||||
ArtifactKind::MobilePackage => Artifact::mobile_package(filename),
|
ArtifactKind::MobilePackage => Artifact::mobile_package(filename),
|
||||||
ArtifactKind::BuildOutput => Artifact::build_output(filename),
|
ArtifactKind::BuildOutput => Artifact::build_output(filename),
|
||||||
|
ArtifactKind::SupplierSbom => Artifact::supplier_sbom(filename),
|
||||||
_ => return None,
|
_ => return None,
|
||||||
};
|
};
|
||||||
artifact.stored_path = Some(stored_path.to_string_lossy().to_string());
|
artifact.stored_path = Some(stored_path.to_string_lossy().to_string());
|
||||||
@@ -142,6 +220,7 @@ pub fn reference_artifact(
|
|||||||
}
|
}
|
||||||
ArtifactKind::PlaintextDescription => Artifact::plaintext(source_ref),
|
ArtifactKind::PlaintextDescription => Artifact::plaintext(source_ref),
|
||||||
ArtifactKind::BuildOutput => Artifact::build_output(source_ref),
|
ArtifactKind::BuildOutput => Artifact::build_output(source_ref),
|
||||||
|
ArtifactKind::SupplierSbom => Artifact::supplier_sbom(source_ref),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -198,6 +277,27 @@ pub async fn detect_target(
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
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]
|
#[test]
|
||||||
fn uploaded_artifact_records_stored_path_for_file_kinds() {
|
fn uploaded_artifact_records_stored_path_for_file_kinds() {
|
||||||
let a = uploaded_artifact(
|
let a = uploaded_artifact(
|
||||||
|
|||||||
@@ -114,7 +114,9 @@ impl GiteaTracker {
|
|||||||
|
|
||||||
/// Every page of a list endpoint, `path` being the URL without `page` and
|
/// Every page of a list endpoint, `path` being the URL without `page` and
|
||||||
/// `limit`. Only an empty page ends the list: an instance may cap the page
|
/// `limit`. Only an empty page ends the list: an instance may cap the page
|
||||||
/// size below ours (`[api] MAX_RESPONSE_ITEMS`).
|
/// size below ours (`[api] MAX_RESPONSE_ITEMS`). Gitea answers some lists
|
||||||
|
/// past their end with `null` instead of `[]` (an issue's timeline does),
|
||||||
|
/// which ends the list the same way.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
///
|
///
|
||||||
@@ -133,10 +135,11 @@ impl GiteaTracker {
|
|||||||
let url = self.api_url(&format!(
|
let url = self.api_url(&format!(
|
||||||
"{path}{separator}page={page}&limit={LIST_PAGE_SIZE}"
|
"{path}{separator}page={page}&limit={LIST_PAGE_SIZE}"
|
||||||
));
|
));
|
||||||
let batch: Vec<T> = self.send_json(what, self.http.get(&url)).await?;
|
// `Option` takes the `null` page; serde reads it as `None`.
|
||||||
if batch.is_empty() {
|
let batch: Option<Vec<T>> = self.send_json(what, self.http.get(&url)).await?;
|
||||||
|
let Some(batch) = batch.filter(|b| !b.is_empty()) else {
|
||||||
return Ok(all);
|
return Ok(all);
|
||||||
}
|
};
|
||||||
all.extend(batch);
|
all.extend(batch);
|
||||||
}
|
}
|
||||||
Err(CoreError::IssueTracker(format!(
|
Err(CoreError::IssueTracker(format!(
|
||||||
@@ -800,6 +803,75 @@ mod tests {
|
|||||||
assert_eq!(seen.lock().unwrap().len(), 4);
|
assert_eq!(seen.lock().unwrap().len(), 4);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A fake Gitea whose issue timeline has one page of `entries`, then
|
||||||
|
/// answers `null` as Gitea does past the end of a timeline.
|
||||||
|
async fn fake_timeline(entries: serde_json::Value) -> String {
|
||||||
|
let app = Router::new()
|
||||||
|
.route(
|
||||||
|
"/api/v1/repos/{owner}/{repo}/issues/{number}/timeline",
|
||||||
|
get(
|
||||||
|
|axum::extract::Query(params): axum::extract::Query<
|
||||||
|
HashMap<String, String>,
|
||||||
|
>,
|
||||||
|
State(entries): State<serde_json::Value>| async move {
|
||||||
|
if params["page"] == "1" {
|
||||||
|
Json(entries)
|
||||||
|
} else {
|
||||||
|
Json(serde_json::Value::Null)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.with_state(entries);
|
||||||
|
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() });
|
||||||
|
format!("http://{addr}")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_null_timeline_page_ends_the_list() {
|
||||||
|
let base = fake_timeline(serde_json::json!([])).await;
|
||||||
|
let tracker =
|
||||||
|
GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap();
|
||||||
|
let entries: Vec<serde_json::Value> = tracker
|
||||||
|
.list_all("issue timeline", "/repos/o/r/issues/1/timeline", 3)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(entries.is_empty());
|
||||||
|
|
||||||
|
let base = fake_timeline(serde_json::json!([{ "id": 1 }, { "id": 2 }])).await;
|
||||||
|
let tracker =
|
||||||
|
GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap();
|
||||||
|
let entries: Vec<serde_json::Value> = tracker
|
||||||
|
.list_all("issue timeline", "/repos/o/r/issues/1/timeline", 3)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(entries.len(), 2, "the page before the null one counts");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_null_first_timeline_page_is_an_empty_timeline() {
|
||||||
|
let app = Router::new().route(
|
||||||
|
"/api/v1/repos/{owner}/{repo}/issues/{number}/timeline",
|
||||||
|
get(|| async { Json(serde_json::Value::Null) }),
|
||||||
|
);
|
||||||
|
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 tracker = GiteaTracker::new(
|
||||||
|
format!("http://{addr}"),
|
||||||
|
SecretString::from("t"),
|
||||||
|
NetGuard::allow_private(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let entries: Vec<serde_json::Value> = tracker
|
||||||
|
.list_all("issue timeline", "/repos/o/r/issues/1/timeline", 3)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(entries.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn a_failed_listing_is_an_error_not_an_empty_list() {
|
async fn a_failed_listing_is_an_error_not_an_empty_list() {
|
||||||
let app = Router::new().route(
|
let app = Router::new().route(
|
||||||
|
|||||||
@@ -147,6 +147,16 @@ impl TestServer {
|
|||||||
.expect("PATCH request failed")
|
.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
|
/// DELETE helper
|
||||||
pub async fn delete(&self, path: &str) -> reqwest::Response {
|
pub async fn delete(&self, path: &str) -> reqwest::Response {
|
||||||
self.client
|
self.client
|
||||||
|
|||||||
@@ -0,0 +1,990 @@
|
|||||||
|
//! Connections between workspaces (#1028) against a fake tenant registry
|
||||||
|
//! (tenant-registry#138): the client lists a tenant's active connections and
|
||||||
|
//! checks one, and the workspace's list shows only each connection's id and
|
||||||
|
//! the other side's name. 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::{Path, Request};
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::middleware::{from_fn, Next};
|
||||||
|
use axum::routing::{get, post};
|
||||||
|
use axum::{Extension, Json, Router};
|
||||||
|
use tower::ServiceExt;
|
||||||
|
|
||||||
|
use compliance_agent::agent::ComplianceAgent;
|
||||||
|
use compliance_agent::api::handlers::connections::list_connections;
|
||||||
|
use compliance_agent::api::handlers::offers::{accept_offer, decline_offer, list_offers};
|
||||||
|
use compliance_agent::api::handlers::onboarding::delete_target;
|
||||||
|
use compliance_agent::api::handlers::releases::{
|
||||||
|
create_release, end_release, list_releases, publish_version, version_draft,
|
||||||
|
};
|
||||||
|
use compliance_agent::api::handlers::supply_chain::get_supply_chain;
|
||||||
|
use compliance_agent::database::DatabasePool;
|
||||||
|
use compliance_core::models::{OnboardedTarget, TargetType};
|
||||||
|
use compliance_core::{OrgRole, TenantContext, TenantStatus};
|
||||||
|
|
||||||
|
use common::dev_config;
|
||||||
|
|
||||||
|
/// A registry where tenant `t-1` is connected to two workspaces and
|
||||||
|
/// connection `c-ended` has ended; `t-down` cannot be listed, `t-unknown`
|
||||||
|
/// is not known (404); `t-3` does not
|
||||||
|
/// hold Prüfwerk.
|
||||||
|
async fn fake_registry() -> String {
|
||||||
|
let app = Router::new()
|
||||||
|
.route(
|
||||||
|
"/v1/internal/tenants/{id}/connections",
|
||||||
|
get(|Path(id): Path<String>| async move {
|
||||||
|
match id.as_str() {
|
||||||
|
"t-1" => Ok(Json(serde_json::json!({ "items": [
|
||||||
|
{ "id": "c-2", "peer_tenant_id": "t-3", "peer_name": "Muster Anlagenbau" },
|
||||||
|
{ "id": "c-1", "peer_tenant_id": "t-2", "peer_name": "beispiel Maschinenbau" },
|
||||||
|
] }))),
|
||||||
|
"t-down" => Err(StatusCode::INTERNAL_SERVER_ERROR),
|
||||||
|
"t-unknown" => Err(StatusCode::NOT_FOUND),
|
||||||
|
_ => Ok(Json(serde_json::json!({ "items": [] }))),
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/v1/internal/entitlements/check",
|
||||||
|
post(|Json(body): Json<serde_json::Value>| async move {
|
||||||
|
let allowed = body["tenant_id"] != "t-3";
|
||||||
|
Json(serde_json::json!({ "allowed": allowed, "status": "active" }))
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/v1/tenants/{id}/projects",
|
||||||
|
get(|| async { Json(serde_json::json!({ "items": [] })) }),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/v1/internal/connections/{id}",
|
||||||
|
get(|Path(id): Path<String>| async move {
|
||||||
|
match id.as_str() {
|
||||||
|
"c-1" => Ok(Json(serde_json::json!({ "active": true, "tenant_ids": ["t-1", "t-2"] }))),
|
||||||
|
"c-2" => Ok(Json(serde_json::json!({ "active": true, "tenant_ids": ["t-1", "t-3"] }))),
|
||||||
|
"c-ended" => Ok(Json(serde_json::json!({ "active": false, "tenant_ids": ["t-1", "t-2"] }))),
|
||||||
|
_ => Err(StatusCode::NOT_FOUND),
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
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!("con_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
|
||||||
|
let Ok(pool) = DatabasePool::connect(&uri, &db_name).await else {
|
||||||
|
eprintln!("SKIP connections: 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: "starter".into(),
|
||||||
|
status: TenantStatus::Active,
|
||||||
|
user_id: "u-1".into(),
|
||||||
|
user_name: None,
|
||||||
|
staff: None,
|
||||||
|
api_key: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `GET /api/v1/connections` as a member of `tenant`.
|
||||||
|
async fn list(agent: Arc<ComplianceAgent>, tenant: &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/connections", get(list_connections))
|
||||||
|
.layer(Extension(agent))
|
||||||
|
.layer(from_fn(inject));
|
||||||
|
let resp = app
|
||||||
|
.oneshot(
|
||||||
|
Request::builder()
|
||||||
|
.uri("/api/v1/connections")
|
||||||
|
.body(Body::empty())
|
||||||
|
.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_client_lists_and_checks_connections() {
|
||||||
|
let base = fake_registry().await;
|
||||||
|
let Some(agent) = agent(&base).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let registry = agent.registry.clone().unwrap();
|
||||||
|
|
||||||
|
let listed = registry.active_connections("t-1").await.unwrap();
|
||||||
|
assert_eq!(listed.len(), 2);
|
||||||
|
assert_eq!(listed[1].peer_tenant_id, "t-2");
|
||||||
|
assert!(registry.active_connections("t-down").await.is_err());
|
||||||
|
assert!(
|
||||||
|
registry
|
||||||
|
.active_connections("t-unknown")
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.is_empty(),
|
||||||
|
"a 404 lists none"
|
||||||
|
);
|
||||||
|
|
||||||
|
let c1 = registry.connection("c-1").await.unwrap().unwrap();
|
||||||
|
assert_eq!(c1.peer_of("t-1"), Some("t-2"));
|
||||||
|
assert_eq!(c1.peer_of("t-9"), None, "a third workspace gets nothing");
|
||||||
|
let ended = registry.connection("c-ended").await.unwrap().unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
ended.peer_of("t-1"),
|
||||||
|
None,
|
||||||
|
"an ended connection delivers nothing"
|
||||||
|
);
|
||||||
|
assert_eq!(registry.connection("c-unknown").await.unwrap(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_workspace_sees_each_connection_by_name_only() {
|
||||||
|
let base = fake_registry().await;
|
||||||
|
let Some(agent) = agent(&base).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
let (status, body) = list(agent.clone(), "t-1").await;
|
||||||
|
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
assert_eq!(
|
||||||
|
body["data"],
|
||||||
|
serde_json::json!([
|
||||||
|
{ "id": "c-1", "peer_name": "beispiel Maschinenbau" },
|
||||||
|
{ "id": "c-2", "peer_name": "Muster Anlagenbau" },
|
||||||
|
]),
|
||||||
|
"by name, without the other tenant's id"
|
||||||
|
);
|
||||||
|
assert!(!body.to_string().contains("t-2"));
|
||||||
|
|
||||||
|
let (status, _) = list(agent, "t-down").await;
|
||||||
|
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `method` `uri` with JSON `body` through the release handlers, as a member
|
||||||
|
/// of `tenant`.
|
||||||
|
async fn release_call(
|
||||||
|
agent: Arc<ComplianceAgent>,
|
||||||
|
tenant: &str,
|
||||||
|
uri: &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}/releases",
|
||||||
|
post(create_release).get(list_releases),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/v1/targets/{id}/releases/{release}/end",
|
||||||
|
post(end_release),
|
||||||
|
)
|
||||||
|
.route("/api/v1/targets/{id}/versions", post(publish_version))
|
||||||
|
.route("/api/v1/targets/{id}/versions/draft", get(version_draft))
|
||||||
|
.route("/api/v1/sbom-offers", get(list_offers))
|
||||||
|
.route("/api/v1/targets/{id}", axum::routing::delete(delete_target))
|
||||||
|
.route("/api/v1/sbom-offers/{id}/accept", post(accept_offer))
|
||||||
|
.route("/api/v1/sbom-offers/{id}/decline", post(decline_offer))
|
||||||
|
.route("/api/v1/supply-chain", get(get_supply_chain))
|
||||||
|
.layer(Extension(agent))
|
||||||
|
.layer(from_fn(inject));
|
||||||
|
// A null body reads, `"delete"` deletes; anything else posts.
|
||||||
|
let request = if body.is_null() {
|
||||||
|
Request::get(uri).body(Body::empty()).unwrap()
|
||||||
|
} else if body == "delete" {
|
||||||
|
Request::delete(uri).body(Body::empty()).unwrap()
|
||||||
|
} else {
|
||||||
|
Request::post(uri)
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.body(Body::from(body.to_string()))
|
||||||
|
.unwrap()
|
||||||
|
};
|
||||||
|
let resp = app.oneshot(request).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_target_is_released_once_over_an_active_connection() {
|
||||||
|
let base = fake_registry().await;
|
||||||
|
let Some(agent) = agent(&base).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let db = agent.db_pool.for_tenant_id("t-1").await.unwrap();
|
||||||
|
let id = db
|
||||||
|
.onboarded_targets()
|
||||||
|
.insert_one(OnboardedTarget::new(
|
||||||
|
"DR-4 Firmware".into(),
|
||||||
|
TargetType::FirmwareRtos,
|
||||||
|
))
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.inserted_id
|
||||||
|
.as_object_id()
|
||||||
|
.unwrap()
|
||||||
|
.to_hex();
|
||||||
|
let uri = format!("/api/v1/targets/{id}/releases");
|
||||||
|
|
||||||
|
let (status, body) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-1",
|
||||||
|
&uri,
|
||||||
|
serde_json::json!({ "connection_id": "c-1" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::CREATED, "{body}");
|
||||||
|
assert_eq!(body["data"]["peer_name"], "beispiel Maschinenbau");
|
||||||
|
assert_eq!(body["data"]["active"], true);
|
||||||
|
assert!(
|
||||||
|
!body.to_string().contains("t-2"),
|
||||||
|
"never the other tenant's id"
|
||||||
|
);
|
||||||
|
let release = body["data"]["id"].as_str().unwrap().to_string();
|
||||||
|
|
||||||
|
let (status, body) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-1",
|
||||||
|
&uri,
|
||||||
|
serde_json::json!({ "connection_id": "c-1" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(
|
||||||
|
(status, body["error"].as_str()),
|
||||||
|
(StatusCode::CONFLICT, Some("released"))
|
||||||
|
);
|
||||||
|
let (status, body) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-1",
|
||||||
|
&uri,
|
||||||
|
serde_json::json!({ "connection_id": "c-unknown" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(
|
||||||
|
(status, body["error"].as_str()),
|
||||||
|
(StatusCode::UNPROCESSABLE_ENTITY, Some("unknown_connection"))
|
||||||
|
);
|
||||||
|
|
||||||
|
let end = format!("{uri}/{release}/end");
|
||||||
|
let (status, body) = release_call(agent.clone(), "t-1", &end, serde_json::json!({})).await;
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
assert_eq!(body["data"]["active"], false);
|
||||||
|
let ended_at = body["data"]["ended_at"].clone();
|
||||||
|
let (_, again) = release_call(agent.clone(), "t-1", &end, serde_json::json!({})).await;
|
||||||
|
assert_eq!(again["data"]["ended_at"], ended_at, "the first end is kept");
|
||||||
|
|
||||||
|
// Ended, it can be released again over the same connection.
|
||||||
|
let (status, _) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-1",
|
||||||
|
&uri,
|
||||||
|
serde_json::json!({ "connection_id": "c-1" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::CREATED);
|
||||||
|
|
||||||
|
// Another workspace cannot reach this target's releases.
|
||||||
|
let (status, _) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-2",
|
||||||
|
&uri,
|
||||||
|
serde_json::json!({ "connection_id": "c-1" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::NOT_FOUND);
|
||||||
|
|
||||||
|
agent.db_pool.drop_tenant("t-1").await.ok();
|
||||||
|
agent.db_pool.drop_tenant("t-2").await.ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A target named `name` in `tenant`'s database, bought in when `supplier`.
|
||||||
|
async fn stored_target(
|
||||||
|
agent: &ComplianceAgent,
|
||||||
|
tenant: &str,
|
||||||
|
name: &str,
|
||||||
|
supplier: bool,
|
||||||
|
) -> String {
|
||||||
|
let db = agent.db_pool.for_tenant_id(tenant).await.unwrap();
|
||||||
|
let mut target = OnboardedTarget::new(name.into(), TargetType::FirmwareRtos);
|
||||||
|
target.supplier = supplier.then(|| compliance_core::models::SupplierComponent {
|
||||||
|
name: "Beispiel".into(),
|
||||||
|
product: None,
|
||||||
|
version: None,
|
||||||
|
csaf_provider: None,
|
||||||
|
});
|
||||||
|
db.onboarded_targets()
|
||||||
|
.insert_one(target)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.inserted_id
|
||||||
|
.as_object_id()
|
||||||
|
.unwrap()
|
||||||
|
.to_hex()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_customer_is_offered_the_release_and_answers_it() {
|
||||||
|
use serde_json::json;
|
||||||
|
let base = fake_registry().await;
|
||||||
|
let Some(agent) = agent(&base).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let product = stored_target(&agent, "t-1", "DR-4 Firmware", false).await;
|
||||||
|
let releases_uri = format!("/api/v1/targets/{product}/releases");
|
||||||
|
let read = serde_json::Value::Null;
|
||||||
|
|
||||||
|
// The supplier (t-1) releases over c-1 to the customer (t-2).
|
||||||
|
let (status, body) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-1",
|
||||||
|
&releases_uri,
|
||||||
|
json!({ "connection_id": "c-1" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::CREATED, "{body}");
|
||||||
|
let release = body["data"]["id"].as_str().unwrap().to_string();
|
||||||
|
|
||||||
|
let (status, offers) =
|
||||||
|
release_call(agent.clone(), "t-2", "/api/v1/sbom-offers", read.clone()).await;
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
let offer = &offers["data"][0];
|
||||||
|
assert_eq!(offer["product_name"], "DR-4 Firmware");
|
||||||
|
assert_eq!(offer["state"], "offered");
|
||||||
|
assert!(offer["supplier_name"].is_string());
|
||||||
|
assert!(
|
||||||
|
!offers.to_string().contains("t-1"),
|
||||||
|
"never the supplier's tenant id"
|
||||||
|
);
|
||||||
|
let offer_id = offer["id"].as_str().unwrap().to_string();
|
||||||
|
|
||||||
|
// Not into a component of the customer's own.
|
||||||
|
let own = stored_target(&agent, "t-2", "Steuerung", false).await;
|
||||||
|
let accept = format!("/api/v1/sbom-offers/{offer_id}/accept");
|
||||||
|
let (status, body) =
|
||||||
|
release_call(agent.clone(), "t-2", &accept, json!({ "target_id": own })).await;
|
||||||
|
assert_eq!(
|
||||||
|
(status, body["error"].as_str()),
|
||||||
|
(
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
Some("not_supplier_component")
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Accepted into a new supplier component.
|
||||||
|
let (status, body) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-2",
|
||||||
|
&accept,
|
||||||
|
json!({ "name": "Antriebsregler DR-4" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::OK, "{body}");
|
||||||
|
assert_eq!(body["data"]["state"], "accepted");
|
||||||
|
let component = body["data"]["target_id"].as_str().unwrap().to_string();
|
||||||
|
let db = agent.db_pool.for_tenant_id("t-2").await.unwrap();
|
||||||
|
let oid = mongodb::bson::oid::ObjectId::parse_str(&component).unwrap();
|
||||||
|
let created = db
|
||||||
|
.onboarded_targets()
|
||||||
|
.find_one(mongodb::bson::doc! { "_id": oid })
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(created.name, "Antriebsregler DR-4");
|
||||||
|
assert_eq!(
|
||||||
|
created.supplier.unwrap().product.as_deref(),
|
||||||
|
Some("DR-4 Firmware")
|
||||||
|
);
|
||||||
|
let (status, body) = release_call(agent.clone(), "t-2", &accept, json!({})).await;
|
||||||
|
assert_eq!(
|
||||||
|
(status, body["error"].as_str()),
|
||||||
|
(StatusCode::CONFLICT, Some("answered"))
|
||||||
|
);
|
||||||
|
|
||||||
|
// The supplier sees the answer.
|
||||||
|
let (_, listed) = release_call(agent.clone(), "t-1", &releases_uri, read.clone()).await;
|
||||||
|
assert_eq!(listed["data"]["releases"][0]["answer"], "accepted");
|
||||||
|
|
||||||
|
// Ending the release ends the customer's offer.
|
||||||
|
let end = format!("{releases_uri}/{release}/end");
|
||||||
|
let (status, _) = release_call(agent.clone(), "t-1", &end, json!({})).await;
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
let (_, offers) = release_call(agent.clone(), "t-2", "/api/v1/sbom-offers", read.clone()).await;
|
||||||
|
assert_eq!(offers["data"][0]["state"], "ended");
|
||||||
|
|
||||||
|
// A second release is declined.
|
||||||
|
let (status, _) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-1",
|
||||||
|
&releases_uri,
|
||||||
|
json!({ "connection_id": "c-1" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::CREATED);
|
||||||
|
let (_, offers) = release_call(agent.clone(), "t-2", "/api/v1/sbom-offers", read.clone()).await;
|
||||||
|
assert_eq!(offers["data"][0]["state"], "offered", "open offers first");
|
||||||
|
let second = offers["data"][0]["id"].as_str().unwrap().to_string();
|
||||||
|
let decline = format!("/api/v1/sbom-offers/{second}/decline");
|
||||||
|
let (status, body) = release_call(agent.clone(), "t-2", &decline, json!({})).await;
|
||||||
|
assert_eq!(
|
||||||
|
(status, body["data"]["state"].as_str()),
|
||||||
|
(StatusCode::OK, Some("declined"))
|
||||||
|
);
|
||||||
|
let (_, listed) = release_call(agent.clone(), "t-1", &releases_uri, read).await;
|
||||||
|
assert_eq!(listed["data"]["releases"][0]["answer"], "declined");
|
||||||
|
|
||||||
|
agent.db_pool.drop_tenant("t-1").await.ok();
|
||||||
|
agent.db_pool.drop_tenant("t-2").await.ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn an_offer_whose_connection_ended_cannot_be_accepted() {
|
||||||
|
use compliance_agent::api::handlers::offers::{OfferState, SbomOffer};
|
||||||
|
let base = fake_registry().await;
|
||||||
|
let Some(agent) = agent(&base).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let db = agent.db_pool.for_tenant_id("t-1").await.unwrap();
|
||||||
|
let offer = SbomOffer {
|
||||||
|
id: mongodb::bson::oid::ObjectId::new(),
|
||||||
|
release_id: mongodb::bson::oid::ObjectId::new().to_hex(),
|
||||||
|
connection_id: "c-ended".into(),
|
||||||
|
supplier_tenant_id: "t-2".into(),
|
||||||
|
supplier_name: "Beispiel".into(),
|
||||||
|
product_name: "HP-7".into(),
|
||||||
|
product_type: TargetType::FirmwareRtos,
|
||||||
|
state: OfferState::Offered,
|
||||||
|
target_id: None,
|
||||||
|
offered_at: mongodb::bson::DateTime::now(),
|
||||||
|
decided_at: None,
|
||||||
|
decided_by: None,
|
||||||
|
ended_at: None,
|
||||||
|
delivered_hash: None,
|
||||||
|
delivered_label: None,
|
||||||
|
delivered_at: None,
|
||||||
|
offered_label: None,
|
||||||
|
offered_components: None,
|
||||||
|
};
|
||||||
|
db.inner()
|
||||||
|
.collection::<SbomOffer>(SbomOffer::COLLECTION)
|
||||||
|
.insert_one(&offer)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let accept = format!("/api/v1/sbom-offers/{}/accept", offer.id.to_hex());
|
||||||
|
|
||||||
|
let (status, body) = release_call(agent.clone(), "t-1", &accept, serde_json::json!({})).await;
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
(status, body["error"].as_str()),
|
||||||
|
(StatusCode::CONFLICT, Some("ended"))
|
||||||
|
);
|
||||||
|
let targets = db
|
||||||
|
.onboarded_targets()
|
||||||
|
.count_documents(mongodb::bson::doc! {})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
targets, 0,
|
||||||
|
"no component is created over an ended connection"
|
||||||
|
);
|
||||||
|
agent.db_pool.drop_tenant("t-1").await.ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first offer listed for `tenant`.
|
||||||
|
async fn first_offer(agent: &Arc<ComplianceAgent>, tenant: &str) -> serde_json::Value {
|
||||||
|
let (_, offers) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
tenant,
|
||||||
|
"/api/v1/sbom-offers",
|
||||||
|
serde_json::Value::Null,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
offers["data"][0].clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_workspace_without_pruefwerk_is_offered_nothing() {
|
||||||
|
let base = fake_registry().await;
|
||||||
|
let Some(agent) = agent(&base).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let product = stored_target(&agent, "t-1", "DR-4 Firmware", false).await;
|
||||||
|
|
||||||
|
// c-2 joins t-1 and t-3, which does not hold Prüfwerk.
|
||||||
|
let (status, body) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-1",
|
||||||
|
&format!("/api/v1/targets/{product}/releases"),
|
||||||
|
serde_json::json!({ "connection_id": "c-2" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
(status, body["error"].as_str()),
|
||||||
|
(StatusCode::UNPROCESSABLE_ENTITY, Some("peer_not_entitled"))
|
||||||
|
);
|
||||||
|
let names = agent.db_pool.client().list_database_names().await.unwrap();
|
||||||
|
let t3 = agent.db_pool.tenant_db_name("t-3");
|
||||||
|
assert!(!names.contains(&t3), "no database is created for it");
|
||||||
|
agent.db_pool.drop_tenant("t-1").await.ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn deleting_either_side_ends_the_offer() {
|
||||||
|
use serde_json::json;
|
||||||
|
let base = fake_registry().await;
|
||||||
|
let Some(agent) = agent(&base).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let releases_of = |id: &str| format!("/api/v1/targets/{id}/releases");
|
||||||
|
|
||||||
|
// The supplier deletes its product while the offer is open.
|
||||||
|
let product = stored_target(&agent, "t-1", "DR-4 Firmware", false).await;
|
||||||
|
let (status, _) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-1",
|
||||||
|
&releases_of(&product),
|
||||||
|
json!({ "connection_id": "c-1" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::CREATED);
|
||||||
|
let offer = first_offer(&agent, "t-2").await;
|
||||||
|
let (status, _) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-1",
|
||||||
|
&format!("/api/v1/targets/{product}"),
|
||||||
|
json!("delete"),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
assert_eq!(first_offer(&agent, "t-2").await["state"], "ended");
|
||||||
|
let accept = format!(
|
||||||
|
"/api/v1/sbom-offers/{}/accept",
|
||||||
|
offer["id"].as_str().unwrap()
|
||||||
|
);
|
||||||
|
let (status, body) = release_call(agent.clone(), "t-2", &accept, json!({})).await;
|
||||||
|
assert_eq!(
|
||||||
|
(status, body["error"].as_str()),
|
||||||
|
(StatusCode::CONFLICT, Some("ended"))
|
||||||
|
);
|
||||||
|
|
||||||
|
// The customer deletes the component it accepted into.
|
||||||
|
let product = stored_target(&agent, "t-1", "HP-7 Firmware", false).await;
|
||||||
|
let (_, _) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-1",
|
||||||
|
&releases_of(&product),
|
||||||
|
json!({ "connection_id": "c-1" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let offer = first_offer(&agent, "t-2").await;
|
||||||
|
assert_eq!(offer["product_name"], "HP-7 Firmware");
|
||||||
|
let accept = format!(
|
||||||
|
"/api/v1/sbom-offers/{}/accept",
|
||||||
|
offer["id"].as_str().unwrap()
|
||||||
|
);
|
||||||
|
let (status, body) = release_call(agent.clone(), "t-2", &accept, json!({})).await;
|
||||||
|
assert_eq!(status, StatusCode::OK, "{body}");
|
||||||
|
let component = body["data"]["target_id"].as_str().unwrap().to_string();
|
||||||
|
let (status, _) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-2",
|
||||||
|
&format!("/api/v1/targets/{component}"),
|
||||||
|
json!("delete"),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
let (_, listed) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-1",
|
||||||
|
&releases_of(&product),
|
||||||
|
serde_json::Value::Null,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(
|
||||||
|
listed["data"]["releases"][0]["answer"], "ended",
|
||||||
|
"the supplier sees it"
|
||||||
|
);
|
||||||
|
|
||||||
|
agent.db_pool.drop_tenant("t-1").await.ok();
|
||||||
|
agent.db_pool.drop_tenant("t-2").await.ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_component_receives_one_release() {
|
||||||
|
use serde_json::json;
|
||||||
|
let base = fake_registry().await;
|
||||||
|
let Some(agent) = agent(&base).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let component = stored_target(&agent, "t-2", "Antriebsregler", true).await;
|
||||||
|
let mut accepts = Vec::new();
|
||||||
|
for name in ["DR-4 Firmware", "DR-5 Firmware"] {
|
||||||
|
let product = stored_target(&agent, "t-1", name, false).await;
|
||||||
|
let (status, _) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-1",
|
||||||
|
&format!("/api/v1/targets/{product}/releases"),
|
||||||
|
json!({ "connection_id": "c-1" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::CREATED);
|
||||||
|
let offer = first_offer(&agent, "t-2").await;
|
||||||
|
accepts.push(format!(
|
||||||
|
"/api/v1/sbom-offers/{}/accept",
|
||||||
|
offer["id"].as_str().unwrap()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
// The id as typed in another case is the same component.
|
||||||
|
let upper = component.to_uppercase();
|
||||||
|
let (status, _) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-2",
|
||||||
|
&accepts[0],
|
||||||
|
json!({ "target_id": component }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
let (status, body) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-2",
|
||||||
|
&accepts[1],
|
||||||
|
json!({ "target_id": upper }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
(status, body["error"].as_str()),
|
||||||
|
(StatusCode::CONFLICT, Some("target_taken"))
|
||||||
|
);
|
||||||
|
let (_, offers) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-2",
|
||||||
|
"/api/v1/sbom-offers",
|
||||||
|
serde_json::Value::Null,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(
|
||||||
|
offers["data"][0]["state"], "offered",
|
||||||
|
"the refused one stays open"
|
||||||
|
);
|
||||||
|
agent.db_pool.drop_tenant("t-1").await.ok();
|
||||||
|
agent.db_pool.drop_tenant("t-2").await.ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn accepted_releases_receive_each_published_version() {
|
||||||
|
use compliance_core::models::{ArtifactKind, SbomEntry};
|
||||||
|
use serde_json::json;
|
||||||
|
let base = fake_registry().await;
|
||||||
|
let Some(agent) = agent(&base).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let product = stored_target(&agent, "t-1", "DR-4 Firmware", false).await;
|
||||||
|
let supplier_db = agent.db_pool.for_tenant_id("t-1").await.unwrap();
|
||||||
|
supplier_db
|
||||||
|
.sbom_entries()
|
||||||
|
.insert_one(SbomEntry::new(
|
||||||
|
product.clone(),
|
||||||
|
"lwip".into(),
|
||||||
|
"2.1.2".into(),
|
||||||
|
"generic".into(),
|
||||||
|
))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let versions = format!("/api/v1/targets/{product}/versions");
|
||||||
|
let releases = format!("/api/v1/targets/{product}/releases");
|
||||||
|
|
||||||
|
// Published before anyone accepted: it arrives on acceptance.
|
||||||
|
let (status, _) =
|
||||||
|
release_call(agent.clone(), "t-1", &versions, json!({ "label": "1.4.0" })).await;
|
||||||
|
assert_eq!(status, StatusCode::CREATED);
|
||||||
|
let (_, body) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-1",
|
||||||
|
&releases,
|
||||||
|
json!({ "connection_id": "c-1" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let release = body["data"]["id"].as_str().unwrap().to_string();
|
||||||
|
let offer = first_offer(&agent, "t-2").await;
|
||||||
|
assert_eq!(
|
||||||
|
(
|
||||||
|
offer["offered_label"].as_str(),
|
||||||
|
offer["offered_components"].as_i64()
|
||||||
|
),
|
||||||
|
(Some("1.4.0"), Some(1)),
|
||||||
|
"the offer names what accepting delivers"
|
||||||
|
);
|
||||||
|
let accept = format!(
|
||||||
|
"/api/v1/sbom-offers/{}/accept",
|
||||||
|
offer["id"].as_str().unwrap()
|
||||||
|
);
|
||||||
|
let (status, body) = release_call(agent.clone(), "t-2", &accept, json!({})).await;
|
||||||
|
assert_eq!(status, StatusCode::OK, "{body}");
|
||||||
|
assert_eq!(body["data"]["delivered_label"], "1.4.0");
|
||||||
|
let component = body["data"]["target_id"].as_str().unwrap().to_string();
|
||||||
|
|
||||||
|
let customer_db = agent.db_pool.for_tenant_id("t-2").await.unwrap();
|
||||||
|
let read_component = || async {
|
||||||
|
let oid = mongodb::bson::oid::ObjectId::parse_str(&component).unwrap();
|
||||||
|
customer_db
|
||||||
|
.onboarded_targets()
|
||||||
|
.find_one(mongodb::bson::doc! { "_id": oid })
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.unwrap()
|
||||||
|
};
|
||||||
|
let sboms = |t: &OnboardedTarget| {
|
||||||
|
t.artifacts
|
||||||
|
.iter()
|
||||||
|
.filter(|a| a.kind == ArtifactKind::SupplierSbom)
|
||||||
|
.count()
|
||||||
|
};
|
||||||
|
let received = read_component().await;
|
||||||
|
assert_eq!(sboms(&received), 1);
|
||||||
|
assert_eq!(
|
||||||
|
received.supplier.as_ref().unwrap().version.as_deref(),
|
||||||
|
Some("1.4.0")
|
||||||
|
);
|
||||||
|
|
||||||
|
// Published after: delivered at once, replacing the one before.
|
||||||
|
let (status, _) =
|
||||||
|
release_call(agent.clone(), "t-1", &versions, json!({ "label": "1.5.0" })).await;
|
||||||
|
assert_eq!(status, StatusCode::CREATED);
|
||||||
|
let received = read_component().await;
|
||||||
|
assert_eq!(sboms(&received), 1, "a new version replaces the one before");
|
||||||
|
assert_eq!(
|
||||||
|
received.supplier.as_ref().unwrap().version.as_deref(),
|
||||||
|
Some("1.5.0")
|
||||||
|
);
|
||||||
|
assert_eq!(first_offer(&agent, "t-2").await["delivered_label"], "1.5.0");
|
||||||
|
let delivery = |chain: serde_json::Value| {
|
||||||
|
chain["data"]["edges"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.find(|e| e["to"] == format!("target:{component}"))
|
||||||
|
.map(|e| e["delivery"].clone())
|
||||||
|
.unwrap()
|
||||||
|
};
|
||||||
|
let (status, chain) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-2",
|
||||||
|
"/api/v1/supply-chain",
|
||||||
|
serde_json::Value::Null,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::OK, "{chain}");
|
||||||
|
let live = delivery(chain);
|
||||||
|
assert_eq!(
|
||||||
|
(live["how"].as_str(), live["version"].as_str()),
|
||||||
|
(Some("release"), Some("1.5.0")),
|
||||||
|
"the Lieferkette draws the release"
|
||||||
|
);
|
||||||
|
let (_, listed) = release_call(agent.clone(), "t-1", &releases, serde_json::Value::Null).await;
|
||||||
|
assert_eq!(
|
||||||
|
listed["data"]["releases"][0]["delivered_label"], "1.5.0",
|
||||||
|
"the supplier sees it"
|
||||||
|
);
|
||||||
|
let customers = |listed: &serde_json::Value| {
|
||||||
|
listed["data"]["versions"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.map(|v| {
|
||||||
|
(
|
||||||
|
v["label"].as_str().unwrap().to_string(),
|
||||||
|
v["customers"].as_u64().unwrap(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
customers(&listed),
|
||||||
|
[("1.5.0".to_string(), 1), ("1.4.0".to_string(), 1)],
|
||||||
|
"each version counts the customer it reached"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Ended, nothing more arrives.
|
||||||
|
let (status, _) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-1",
|
||||||
|
&format!("{releases}/{release}/end"),
|
||||||
|
json!({}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
let (status, _) =
|
||||||
|
release_call(agent.clone(), "t-1", &versions, json!({ "label": "1.6.0" })).await;
|
||||||
|
assert_eq!(status, StatusCode::CREATED);
|
||||||
|
let received = read_component().await;
|
||||||
|
assert_eq!(
|
||||||
|
received.supplier.as_ref().unwrap().version.as_deref(),
|
||||||
|
Some("1.5.0")
|
||||||
|
);
|
||||||
|
let (_, listed) = release_call(agent.clone(), "t-1", &releases, serde_json::Value::Null).await;
|
||||||
|
assert_eq!(customers(&listed)[0], ("1.6.0".to_string(), 0));
|
||||||
|
let (_, chain) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-2",
|
||||||
|
"/api/v1/supply-chain",
|
||||||
|
serde_json::Value::Null,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let ended = delivery(chain);
|
||||||
|
assert_eq!(
|
||||||
|
(ended["how"].as_str(), ended["version"].as_str()),
|
||||||
|
(Some("release_ended"), Some("1.5.0")),
|
||||||
|
"an ended release leaves its version"
|
||||||
|
);
|
||||||
|
|
||||||
|
// The next version's draft, against 1.6.0.
|
||||||
|
supplier_db
|
||||||
|
.sbom_entries()
|
||||||
|
.insert_one(SbomEntry::new(
|
||||||
|
product.clone(),
|
||||||
|
"mbedtls".into(),
|
||||||
|
"3.6.2".into(),
|
||||||
|
"generic".into(),
|
||||||
|
))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let (status, draft) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-1",
|
||||||
|
&format!("{versions}/draft"),
|
||||||
|
serde_json::Value::Null,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::OK, "{draft}");
|
||||||
|
assert_eq!(draft["data"]["components"], 2);
|
||||||
|
assert!(draft["data"]["blocked"].is_null());
|
||||||
|
let changes = &draft["data"]["changes"];
|
||||||
|
assert_eq!(changes["against"], "1.6.0");
|
||||||
|
assert_eq!(
|
||||||
|
(changes["added"].as_u64(), changes["unchanged"].as_u64()),
|
||||||
|
(Some(1), Some(1))
|
||||||
|
);
|
||||||
|
assert_eq!(changes["added_names"], json!(["mbedtls 3.6.2"]));
|
||||||
|
|
||||||
|
agent.db_pool.drop_tenant("t-1").await.ok();
|
||||||
|
agent.db_pool.drop_tenant("t-2").await.ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn an_open_offer_learns_each_published_version() {
|
||||||
|
use compliance_core::models::SbomEntry;
|
||||||
|
use serde_json::json;
|
||||||
|
let base = fake_registry().await;
|
||||||
|
let Some(agent) = agent(&base).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let product = stored_target(&agent, "t-1", "DR-4 Firmware", false).await;
|
||||||
|
let releases = format!("/api/v1/targets/{product}/releases");
|
||||||
|
let versions = format!("/api/v1/targets/{product}/versions");
|
||||||
|
let (status, _) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-1",
|
||||||
|
&releases,
|
||||||
|
json!({ "connection_id": "c-1" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::CREATED);
|
||||||
|
assert!(
|
||||||
|
first_offer(&agent, "t-2").await["offered_label"].is_null(),
|
||||||
|
"nothing published yet"
|
||||||
|
);
|
||||||
|
|
||||||
|
agent
|
||||||
|
.db_pool
|
||||||
|
.for_tenant_id("t-1")
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.sbom_entries()
|
||||||
|
.insert_one(SbomEntry::new(
|
||||||
|
product.clone(),
|
||||||
|
"lwip".into(),
|
||||||
|
"2.1.2".into(),
|
||||||
|
"generic".into(),
|
||||||
|
))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let (status, _) =
|
||||||
|
release_call(agent.clone(), "t-1", &versions, json!({ "label": "1.5.0" })).await;
|
||||||
|
assert_eq!(status, StatusCode::CREATED);
|
||||||
|
|
||||||
|
let offer = first_offer(&agent, "t-2").await;
|
||||||
|
assert_eq!(offer["state"], "offered", "announced, not delivered");
|
||||||
|
assert_eq!(offer["offered_label"], "1.5.0");
|
||||||
|
assert!(offer["delivered_label"].is_null());
|
||||||
|
agent.db_pool.drop_tenant("t-1").await.ok();
|
||||||
|
agent.db_pool.drop_tenant("t-2").await.ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_draft_without_components_says_why() {
|
||||||
|
let base = fake_registry().await;
|
||||||
|
let Some(agent) = agent(&base).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let product = stored_target(&agent, "t-1", "DR-4 Firmware", false).await;
|
||||||
|
|
||||||
|
let (status, draft) = release_call(
|
||||||
|
agent.clone(),
|
||||||
|
"t-1",
|
||||||
|
&format!("/api/v1/targets/{product}/versions/draft"),
|
||||||
|
serde_json::Value::Null,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
assert_eq!(status, StatusCode::OK, "{draft}");
|
||||||
|
assert_eq!(draft["data"]["blocked"], "empty");
|
||||||
|
assert_eq!(draft["data"]["components"], 0);
|
||||||
|
assert!(draft["data"]["changes"].is_null());
|
||||||
|
agent.db_pool.drop_tenant("t-1").await.ok();
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
//! DAST findings join the findings of the target they were found on (#998),
|
||||||
|
//! with their control refs, and a second scan does not add them again. A DAST
|
||||||
|
//! finding is linked to the target's one open code finding with its CWE.
|
||||||
|
//! Drives the real API and pipeline against a live Mongo (`TEST_MONGODB_URI`)
|
||||||
|
//! and a local site, so this binary allows private targets for its process.
|
||||||
|
|
||||||
|
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use axum::http::header::ACCESS_CONTROL_ALLOW_ORIGIN;
|
||||||
|
use axum::Router;
|
||||||
|
use common::TestServer;
|
||||||
|
use compliance_core::models::{Finding, ScanType, Severity};
|
||||||
|
use mongodb::bson::{doc, Document};
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
/// A site that lets any origin read its answers.
|
||||||
|
async fn open_cors_site() -> String {
|
||||||
|
let app = Router::new().fallback(|| async {
|
||||||
|
(
|
||||||
|
[(ACCESS_CONTROL_ALLOW_ORIGIN, "*")],
|
||||||
|
"<html><body>shop</body></html>",
|
||||||
|
)
|
||||||
|
});
|
||||||
|
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() });
|
||||||
|
format!("http://{addr}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Scan target `id` and return the finished scan run.
|
||||||
|
async fn scan(server: &TestServer, runs: &mongodb::Collection<Document>, id: &str) -> Document {
|
||||||
|
let before = runs.count_documents(doc! { "repo_id": id }).await.unwrap();
|
||||||
|
server
|
||||||
|
.post(&format!("/api/v1/targets/{id}/scan"), &json!({}))
|
||||||
|
.await;
|
||||||
|
for _ in 0..240 {
|
||||||
|
let done = runs
|
||||||
|
.count_documents(doc! { "repo_id": id, "status": { "$in": ["completed", "failed"] } })
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
if done > before {
|
||||||
|
return runs
|
||||||
|
.find_one(doc! { "repo_id": id })
|
||||||
|
.sort(doc! { "started_at": -1 })
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
||||||
|
}
|
||||||
|
panic!("the scan of {id} did not finish");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn dast_findings_are_findings_of_the_target_once() {
|
||||||
|
// This binary holds only this test, so the setting reaches no other one.
|
||||||
|
std::env::set_var("PW_ALLOW_PRIVATE_TARGETS", "1");
|
||||||
|
let site = open_cors_site().await;
|
||||||
|
let server = TestServer::start().await;
|
||||||
|
let created: serde_json::Value = server
|
||||||
|
.post(
|
||||||
|
"/api/v1/targets",
|
||||||
|
&json!({
|
||||||
|
"name": "shop",
|
||||||
|
"target_type": "web_app",
|
||||||
|
"artifacts": [{ "kind": "live_url", "source_ref": site }]
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let id = created["data"]["_id"]["$oid"].as_str().unwrap().to_string();
|
||||||
|
let uri = std::env::var("TEST_MONGODB_URI")
|
||||||
|
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||||
|
let db = mongodb::Client::with_uri_str(&uri)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.database(&server.tenant_db_name());
|
||||||
|
let runs = db.collection::<Document>("scan_runs");
|
||||||
|
let findings = db.collection::<Document>("findings");
|
||||||
|
let mut code = Finding::new(
|
||||||
|
id.clone(),
|
||||||
|
"fp-code-cors".into(),
|
||||||
|
"semgrep".into(),
|
||||||
|
ScanType::Sast,
|
||||||
|
"Permissive CORS".into(),
|
||||||
|
"The server allows any origin.".into(),
|
||||||
|
Severity::Medium,
|
||||||
|
);
|
||||||
|
code.cwe = Some("CWE-942".into());
|
||||||
|
code.file_path = Some("src/server.rs".into());
|
||||||
|
let code_id = db
|
||||||
|
.collection::<Finding>("findings")
|
||||||
|
.insert_one(&code)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.inserted_id
|
||||||
|
.as_object_id()
|
||||||
|
.unwrap()
|
||||||
|
.to_hex();
|
||||||
|
|
||||||
|
let first = scan(&server, &runs, &id).await;
|
||||||
|
|
||||||
|
assert_eq!(first.get_str("status").unwrap(), "completed", "{first:?}");
|
||||||
|
let cors = findings
|
||||||
|
.find_one(doc! { "repo_id": &id, "scanner": "dast", "cwe": "CWE-942" })
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.expect("the CORS finding is a finding of the target");
|
||||||
|
assert_eq!(cors.get_str("scan_type").unwrap(), "dast");
|
||||||
|
let refs: Vec<&str> = cors
|
||||||
|
.get_array("control_refs")
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.filter_map(|r| r.as_str())
|
||||||
|
.collect();
|
||||||
|
assert_eq!(refs, ["cra-ai-1"]);
|
||||||
|
let dast_cors = db
|
||||||
|
.collection::<Document>("dast_findings")
|
||||||
|
.find_one(doc! { "cwe": "CWE-942" })
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.expect("the DAST finding is stored with its evidence");
|
||||||
|
assert_eq!(
|
||||||
|
dast_cors.get_str("linked_sast_finding_id").unwrap(),
|
||||||
|
code_id,
|
||||||
|
"linked to the code finding with the same CWE"
|
||||||
|
);
|
||||||
|
let stored = findings
|
||||||
|
.count_documents(doc! { "repo_id": &id, "scanner": "dast" })
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(first.get_i64("new_findings_count").unwrap() >= i64::try_from(stored).unwrap());
|
||||||
|
|
||||||
|
let second = scan(&server, &runs, &id).await;
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
findings
|
||||||
|
.count_documents(doc! { "repo_id": &id, "scanner": "dast" })
|
||||||
|
.await
|
||||||
|
.unwrap(),
|
||||||
|
stored,
|
||||||
|
"a second scan finds the same weaknesses, it does not add them again"
|
||||||
|
);
|
||||||
|
assert_eq!(second.get_i64("new_findings_count").unwrap(), 0);
|
||||||
|
|
||||||
|
server.cleanup().await;
|
||||||
|
}
|
||||||
Loaded 100 of 233 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user