Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f231632ea | ||
|
|
045746488c | ||
|
|
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
|
||||
- name: Clippy (graph)
|
||||
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
|
||||
- name: Security Audit
|
||||
@@ -153,6 +157,10 @@ jobs:
|
||||
# compliance-core's integration tests need no services.
|
||||
- name: Tests (core integration)
|
||||
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
|
||||
# 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.
|
||||
|
||||
Generated
+52
-12
@@ -601,7 +601,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "compliance-agent"
|
||||
version = "0.4.6"
|
||||
version = "0.4.16"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"base64 0.22.1",
|
||||
@@ -645,6 +645,8 @@ dependencies = [
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"urlencoding",
|
||||
"utoipa",
|
||||
"utoipa-axum",
|
||||
"uuid",
|
||||
"walkdir",
|
||||
"werkbank-exec",
|
||||
@@ -655,7 +657,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "compliance-core"
|
||||
version = "0.4.6"
|
||||
version = "0.4.16"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"axum",
|
||||
@@ -687,7 +689,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "compliance-dashboard"
|
||||
version = "0.4.6"
|
||||
version = "0.4.16"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"axum",
|
||||
@@ -725,8 +727,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "compliance-dast"
|
||||
version = "0.4.6"
|
||||
version = "0.4.16"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"compliance-core",
|
||||
@@ -735,6 +738,7 @@ dependencies = [
|
||||
"reqwest",
|
||||
"scraper",
|
||||
"serde_json",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tokio-native-tls",
|
||||
"tokio-tungstenite 0.26.2",
|
||||
@@ -745,7 +749,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "compliance-graph"
|
||||
version = "0.4.6"
|
||||
version = "0.4.16"
|
||||
dependencies = [
|
||||
"bson",
|
||||
"chrono",
|
||||
@@ -770,7 +774,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "compliance-mcp"
|
||||
version = "0.4.6"
|
||||
version = "0.4.16"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"bson",
|
||||
@@ -793,7 +797,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "compliance-smoke"
|
||||
version = "0.4.6"
|
||||
version = "0.4.16"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"compliance-core",
|
||||
@@ -928,7 +932,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "control-map"
|
||||
version = "0.4.6"
|
||||
version = "0.4.16"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4615,16 +4619,16 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "quinn-udp"
|
||||
version = "0.5.14"
|
||||
version = "0.5.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd"
|
||||
checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016"
|
||||
dependencies = [
|
||||
"cfg_aliases",
|
||||
"libc",
|
||||
"once_cell",
|
||||
"socket2 0.6.2",
|
||||
"tracing",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6815,6 +6819,42 @@ version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
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]]
|
||||
name = "uuid"
|
||||
version = "1.21.0"
|
||||
@@ -7087,7 +7127,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "werkbank-exec"
|
||||
version = "0.4.6"
|
||||
version = "0.4.16"
|
||||
dependencies = [
|
||||
"compliance-core",
|
||||
"compliance-dast",
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
[package]
|
||||
name = "compliance-agent"
|
||||
version = "0.4.6"
|
||||
version = "0.4.16"
|
||||
edition = "2021"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[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"] }
|
||||
control-map = { workspace = true }
|
||||
compliance-graph = { path = "../compliance-graph" }
|
||||
|
||||
@@ -18,7 +18,18 @@ use super::ApiResponse;
|
||||
|
||||
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))]
|
||||
pub async fn chat(
|
||||
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))]
|
||||
pub async fn build_embeddings(
|
||||
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))]
|
||||
pub async fn embedding_status(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -6,7 +6,9 @@ use axum::Json;
|
||||
use mongodb::bson::doc;
|
||||
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::tenant_ctx::TenantCtx;
|
||||
|
||||
@@ -17,21 +19,41 @@ use super::{collect_cursor_async, ApiResponse, PaginationParams};
|
||||
|
||||
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// A DAST target to add.
|
||||
#[derive(Deserialize, utoipa::ToSchema)]
|
||||
pub struct AddTargetRequest {
|
||||
/// A name for the target.
|
||||
pub name: String,
|
||||
/// Where the scan starts; must be publicly routable.
|
||||
pub base_url: String,
|
||||
/// `web_app` (default), `rest_api` or `graph_ql`.
|
||||
#[serde(default = "default_target_type")]
|
||||
#[schema(value_type = Option<String>, example = "web_app")]
|
||||
pub target_type: DastTargetType,
|
||||
/// The target (Prüfobjekt) this DAST target belongs to.
|
||||
pub repo_id: Option<String>,
|
||||
/// URL paths the scan leaves out.
|
||||
#[serde(default)]
|
||||
pub excluded_paths: Vec<String>,
|
||||
/// How many link levels the crawl follows (default 5).
|
||||
#[serde(default = "default_crawl_depth")]
|
||||
#[schema(value_type = Option<u32>)]
|
||||
pub max_crawl_depth: u32,
|
||||
/// Requests per second (default 10).
|
||||
#[serde(default = "default_rate_limit")]
|
||||
#[schema(value_type = Option<u32>)]
|
||||
pub rate_limit: u32,
|
||||
/// Whether the scan may send `PUT`, `PATCH` and `DELETE` (default false).
|
||||
#[serde(default)]
|
||||
#[schema(value_type = Option<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 {
|
||||
@@ -44,7 +66,19 @@ fn default_rate_limit() -> u32 {
|
||||
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)]
|
||||
pub async fn list_targets(
|
||||
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)]
|
||||
pub async fn add_target(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -94,12 +143,22 @@ pub async fn add_target(
|
||||
tracing::warn!(tenant_id = %tenant.0.tenant_id, "DAST target refused: {e}");
|
||||
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);
|
||||
target.repo_id = req.repo_id;
|
||||
target.excluded_paths = req.excluded_paths;
|
||||
target.max_crawl_depth = req.max_crawl_depth;
|
||||
target.rate_limit = req.rate_limit;
|
||||
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 res = db
|
||||
@@ -107,11 +166,8 @@ pub async fn add_target(
|
||||
.insert_one(&target)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let target_id = res
|
||||
.inserted_id
|
||||
.as_object_id()
|
||||
.map(|id| id.to_hex())
|
||||
.unwrap_or_default();
|
||||
target.id = res.inserted_id.as_object_id();
|
||||
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
|
||||
agent.emit_usage(
|
||||
&tenant.0.tenant_id,
|
||||
"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))]
|
||||
pub async fn trigger_scan(
|
||||
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 db = tenant_db(&agent, &tenant).await?;
|
||||
|
||||
let target = db
|
||||
let mut target = db
|
||||
.dast_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.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
|
||||
// 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" })))
|
||||
}
|
||||
|
||||
/// 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)]
|
||||
pub async fn list_scan_runs(
|
||||
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)]
|
||||
pub async fn list_findings(
|
||||
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))]
|
||||
pub async fn get_finding(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -27,7 +27,16 @@ pub struct SeedResponse {
|
||||
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)]
|
||||
pub async fn list_demo_targets(
|
||||
_tenant: TenantCtx,
|
||||
@@ -39,8 +48,20 @@ pub async fn list_demo_targets(
|
||||
Ok(Json(DemoTargetsResponse { targets }))
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets/demo-seed — seed the caller's tenant. 202: the targets
|
||||
/// exist and their scans are running in the background.
|
||||
/// Create the demo targets for the tenant and start their scans.
|
||||
///
|
||||
/// 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)]
|
||||
pub async fn seed_demo_targets(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -15,11 +15,17 @@ pub const MAX_PAGE_SIZE: i64 = 200;
|
||||
/// absurd offset. At [`MAX_PAGE_SIZE`] this is still 20M documents deep.
|
||||
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 {
|
||||
/// The page, from 1 (default 1, at most 100 000).
|
||||
#[serde(default = "default_page", deserialize_with = "de_page")]
|
||||
#[param(minimum = 1, maximum = 100_000)]
|
||||
pub page: u64,
|
||||
/// Entries per page (default 50, at most 200).
|
||||
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
||||
#[param(minimum = 1, maximum = 200)]
|
||||
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))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// Which findings a list returns, and in what order.
|
||||
#[derive(Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct FindingsFilter {
|
||||
/// Only one target's findings (its id).
|
||||
#[serde(default)]
|
||||
pub repo_id: Option<String>,
|
||||
/// Only the findings a given scan run found first (the dashboard reveals
|
||||
/// them when the run ends).
|
||||
#[serde(default)]
|
||||
pub scan_run_id: Option<String>,
|
||||
/// `info`, `low`, `medium`, `high` or `critical`.
|
||||
#[serde(default)]
|
||||
pub severity: Option<String>,
|
||||
/// Only one kind of scan (`sast`, `cve`, `dast`, …).
|
||||
#[serde(default)]
|
||||
pub scan_type: Option<String>,
|
||||
/// `open`, `triaged`, `false_positive`, `resolved`, `ignored`,
|
||||
/// `accepted_risk`, `needs_review` or `wrong_mapping`.
|
||||
#[serde(default)]
|
||||
pub status: Option<String>,
|
||||
/// Text the title, description or file path contains (at most 128
|
||||
/// characters, matched literally).
|
||||
#[serde(default)]
|
||||
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
|
||||
/// groups listing a place in it.
|
||||
#[serde(default)]
|
||||
@@ -73,13 +92,20 @@ pub struct FindingsFilter {
|
||||
/// ([`path_regex`]).
|
||||
#[serde(default)]
|
||||
pub path: Option<String>,
|
||||
/// `created_at` (default), `updated_at`, `severity`, `scan_type`,
|
||||
/// `status`, `file_path`, `rule_id`, `repo_id`, `title` or `confidence`.
|
||||
#[serde(default)]
|
||||
pub sort_by: Option<String>,
|
||||
/// `asc`, or newest/highest first (default).
|
||||
#[serde(default)]
|
||||
pub sort_order: Option<String>,
|
||||
/// The page, from 1 (default 1, at most 100 000).
|
||||
#[serde(default = "default_page", deserialize_with = "de_page")]
|
||||
#[param(minimum = 1, maximum = 100_000)]
|
||||
pub page: u64,
|
||||
/// Entries per page (default 50, at most 200).
|
||||
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
||||
#[param(minimum = 1, maximum = 200)]
|
||||
pub limit: i64,
|
||||
}
|
||||
|
||||
@@ -283,39 +309,58 @@ fn default_branch() -> String {
|
||||
"main".to_string()
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// A finding's new status.
|
||||
#[derive(Deserialize, utoipa::ToSchema)]
|
||||
pub struct UpdateStatusRequest {
|
||||
/// Typed, so an unknown status is refused (422) instead of being stored
|
||||
/// and breaking every later read of the finding.
|
||||
/// `open`, `triaged`, `false_positive`, `resolved`, `ignored`,
|
||||
/// `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,
|
||||
/// Why; required for `accepted_risk`.
|
||||
#[serde(default)]
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// The same new status for many findings.
|
||||
#[derive(Deserialize, utoipa::ToSchema)]
|
||||
pub struct BulkUpdateStatusRequest {
|
||||
/// The findings' ids.
|
||||
pub ids: Vec<String>,
|
||||
/// The status, as for one finding.
|
||||
#[schema(value_type = String, example = "resolved")]
|
||||
pub status: compliance_core::models::FindingStatus,
|
||||
/// Why; required for `accepted_risk` and `wrong_mapping`.
|
||||
#[serde(default)]
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// A developer's feedback on a finding.
|
||||
#[derive(Deserialize, utoipa::ToSchema)]
|
||||
pub struct UpdateFeedbackRequest {
|
||||
/// The feedback, as text.
|
||||
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 {
|
||||
/// Only one target's components (its id).
|
||||
#[serde(default)]
|
||||
pub repo_id: Option<String>,
|
||||
/// Only one package manager's components, such as `npm` or `cargo`.
|
||||
#[serde(default)]
|
||||
pub package_manager: Option<String>,
|
||||
/// Only components whose name contains this text.
|
||||
#[serde(default)]
|
||||
pub q: Option<String>,
|
||||
/// Only components with known vulnerabilities (`true`), or only those
|
||||
/// without (`false`).
|
||||
#[serde(default)]
|
||||
pub has_vulns: Option<bool>,
|
||||
/// Only components with this licence.
|
||||
#[serde(default)]
|
||||
pub license: Option<String>,
|
||||
/// Only components an image is known to contain (`true`), or only the
|
||||
@@ -326,9 +371,13 @@ pub struct SbomFilter {
|
||||
/// none and nobody has confirmed one.
|
||||
#[serde(default)]
|
||||
pub unresolved: Option<bool>,
|
||||
/// The page, from 1 (default 1, at most 100 000).
|
||||
#[serde(default = "default_page", deserialize_with = "de_page")]
|
||||
#[param(minimum = 1, maximum = 100_000)]
|
||||
pub page: u64,
|
||||
/// Entries per page (default 50, at most 200).
|
||||
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
||||
#[param(minimum = 1, maximum = 200)]
|
||||
pub limit: i64,
|
||||
}
|
||||
|
||||
@@ -341,10 +390,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 {
|
||||
/// The target (its id).
|
||||
pub repo_id: String,
|
||||
/// `cyclonedx` (default) or `spdx`.
|
||||
#[serde(default = "default_export_format")]
|
||||
#[param(example = "cyclonedx")]
|
||||
pub format: String,
|
||||
}
|
||||
|
||||
@@ -352,9 +406,13 @@ fn default_export_format() -> 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 {
|
||||
/// The first target (its id).
|
||||
pub repo_a: String,
|
||||
/// The second target (its id).
|
||||
pub repo_b: String,
|
||||
}
|
||||
|
||||
|
||||
@@ -173,6 +173,9 @@ pub async fn compliance_view(
|
||||
"data": {
|
||||
"target_id": id,
|
||||
"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),
|
||||
"last_scan": inputs.last_run,
|
||||
"sbom_components": inputs.sbom.len(),
|
||||
|
||||
@@ -22,7 +22,8 @@ use compliance_core::models::{Finding, FindingStatus};
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
/// The query of [`list_finding_groups`].
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct GroupsQuery {
|
||||
/// Only one target's findings (`Finding::repo_id`).
|
||||
#[serde(default)]
|
||||
@@ -30,11 +31,13 @@ pub struct GroupsQuery {
|
||||
}
|
||||
|
||||
/// The body of [`decide_finding_group`].
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||
pub struct DecideGroupRequest {
|
||||
/// The group, as [`list_finding_groups`] named it.
|
||||
#[schema(value_type = Object)]
|
||||
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,
|
||||
/// Why; required for an accepted risk or a wrong mapping.
|
||||
#[serde(default)]
|
||||
@@ -71,9 +74,19 @@ async fn undecided_findings(
|
||||
Ok(collect_cursor_async(cursor).await)
|
||||
}
|
||||
|
||||
/// GET /api/v1/finding-groups[?target=] — the undecided findings, grouped
|
||||
/// by rule and file (see [`compliance_core::models::finding_group`]), most
|
||||
/// severe first.
|
||||
/// List the undecided findings, grouped by rule and file.
|
||||
///
|
||||
/// 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))]
|
||||
pub async fn list_finding_groups(
|
||||
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
|
||||
/// group the same status, as if each were changed on its own.
|
||||
/// Decide every undecided finding of a group at once.
|
||||
///
|
||||
/// 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
|
||||
/// in the meantime keeps that decision. 404 when the group has no undecided
|
||||
/// 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))]
|
||||
pub async fn decide_finding_group(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -7,6 +7,17 @@ use super::dto::*;
|
||||
use compliance_core::models::{Finding, FindingStatus, StatusChange};
|
||||
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))]
|
||||
pub async fn list_findings(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -28,6 +39,9 @@ pub async fn list_findings(
|
||||
if let Some(scan_type) = &filter.scan_type {
|
||||
query.insert("scan_type", scan_type);
|
||||
}
|
||||
if let Some(scanner) = &filter.scanner {
|
||||
query.insert("scanner", scanner);
|
||||
}
|
||||
if let Some(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`].
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
#[derive(Debug, serde::Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct VariantsQuery {
|
||||
/// Only one target's variants.
|
||||
#[serde(default)]
|
||||
pub repo_id: Option<String>,
|
||||
}
|
||||
|
||||
/// The app variants the tenant's findings are labelled with (theirs and their
|
||||
/// groups' places), sorted, for the findings filter.
|
||||
/// List the app variants the tenant's findings are in.
|
||||
///
|
||||
/// 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))]
|
||||
pub async fn list_finding_variants(
|
||||
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))]
|
||||
pub async fn get_finding(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -270,8 +309,23 @@ fn issue_sync(
|
||||
}
|
||||
}
|
||||
|
||||
/// PATCH /api/v1/findings/{id}/status — change the status, recording who,
|
||||
/// when and why. 404 when there is no such finding.
|
||||
/// Change a finding's status.
|
||||
///
|
||||
/// 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))]
|
||||
pub async fn update_finding_status(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -296,7 +350,19 @@ pub async fn update_finding_status(
|
||||
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)]
|
||||
pub async fn bulk_update_finding_status(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -351,8 +417,22 @@ pub(crate) async fn apply_status(
|
||||
Ok(result.modified_count)
|
||||
}
|
||||
|
||||
/// PATCH /api/v1/findings/{id}/feedback — store the developer's feedback on a
|
||||
/// finding. 404 when there is no such finding.
|
||||
/// Store a developer's feedback on a 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))]
|
||||
pub async fn update_finding_feedback(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -6,15 +6,15 @@ use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
|
||||
use compliance_core::models::GitSourceView;
|
||||
use compliance_core::tenant::OrgRole;
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use super::dto::{tenant_db, AgentExt};
|
||||
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 {
|
||||
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
|
||||
|
||||
@@ -42,14 +42,18 @@ pub struct GraphData {
|
||||
pub total_nodes: u64,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// A symbol search.
|
||||
#[derive(Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct SearchParams {
|
||||
/// The search text.
|
||||
pub q: String,
|
||||
/// Clamped to `1..=MAX_PAGE_SIZE` while deserializing, like every list.
|
||||
#[serde(
|
||||
default = "default_search_limit",
|
||||
deserialize_with = "super::dto::de_limit"
|
||||
)]
|
||||
#[param(minimum = 1, maximum = 200)]
|
||||
pub limit: i64,
|
||||
}
|
||||
|
||||
@@ -57,7 +61,19 @@ fn default_search_limit() -> i64 {
|
||||
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))]
|
||||
pub async fn get_graph(
|
||||
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))]
|
||||
pub async fn get_nodes(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -222,8 +248,19 @@ impl GraphSummary {
|
||||
}
|
||||
}
|
||||
|
||||
/// GET /api/v1/graph/:repo_id/summary — The latest build's counts, without
|
||||
/// loading any node: `data` is `null` when there is none to show.
|
||||
/// The counts of a target's latest graph build, without loading any node.
|
||||
///
|
||||
/// `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))]
|
||||
pub async fn get_summary(
|
||||
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))]
|
||||
pub async fn get_communities(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -312,7 +359,17 @@ pub struct CommunityInfo {
|
||||
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))]
|
||||
pub async fn get_impact(
|
||||
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))]
|
||||
pub async fn search_symbols(
|
||||
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))]
|
||||
pub async fn get_file_content(
|
||||
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 {
|
||||
/// The file's path in the checkout.
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
@@ -443,7 +525,17 @@ pub struct FileContent {
|
||||
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))]
|
||||
pub async fn trigger_build(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -11,15 +11,21 @@ use super::dto::{AgentExt, ApiResponse};
|
||||
|
||||
// ── DTOs ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
/// An earlier turn of a help chat.
|
||||
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||
pub struct HelpChatMessage {
|
||||
/// `user` or `assistant`.
|
||||
pub role: String,
|
||||
/// What was said.
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
/// The body of [`help_chat`].
|
||||
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||
pub struct HelpChatRequest {
|
||||
/// The question.
|
||||
pub message: String,
|
||||
/// The earlier turns, oldest first.
|
||||
#[serde(default)]
|
||||
pub history: Vec<HelpChatMessage>,
|
||||
}
|
||||
@@ -170,8 +176,17 @@ fn doc_context() -> &'static str {
|
||||
|
||||
// ── Handler ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/// POST /api/v1/help/chat — Answer questions about the compliance-scanner
|
||||
/// using the project documentation as grounding context.
|
||||
/// Ask about Prüfwerk, answered from its published documentation.
|
||||
#[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)]
|
||||
pub async fn help_chat(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -35,12 +35,16 @@ use crate::license_conclusions::MAX_CONCLUSIONS;
|
||||
pub const MAX_COMPONENTS: usize = 500;
|
||||
|
||||
/// 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 {
|
||||
/// The package's name.
|
||||
pub name: String,
|
||||
/// Its package manager, such as `npm` or `cargo`.
|
||||
pub package_manager: String,
|
||||
/// Its version; empty with `all_versions`.
|
||||
#[serde(default)]
|
||||
pub version: String,
|
||||
/// Its purl, when known.
|
||||
#[serde(default)]
|
||||
pub purl: Option<String>,
|
||||
/// 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`].
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||
pub struct ConcludeRequest {
|
||||
/// The components, at most 500.
|
||||
pub components: Vec<ComponentRef>,
|
||||
/// For every version of the packages, not just the listed ones.
|
||||
#[serde(default)]
|
||||
@@ -60,25 +65,38 @@ pub struct ConcludeRequest {
|
||||
/// licence of its own, named in `license_name`.
|
||||
#[serde(default)]
|
||||
pub license: Option<String>,
|
||||
/// The name of a licence of its own.
|
||||
#[serde(default)]
|
||||
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)]
|
||||
#[schema(value_type = Option<String>, example = "proprietary")]
|
||||
pub category: Option<LicenseCategory>,
|
||||
/// The copyright lines.
|
||||
#[serde(default)]
|
||||
pub copyright: Vec<String>,
|
||||
/// The licence's text.
|
||||
#[serde(default)]
|
||||
pub license_text: Option<String>,
|
||||
/// Where the licence is published.
|
||||
#[serde(default)]
|
||||
pub license_url: Option<String>,
|
||||
/// Where the licence was confirmed, such as a file or a contract.
|
||||
#[serde(default)]
|
||||
pub evidence: Option<String>,
|
||||
/// The contract a licence of its own comes from.
|
||||
#[serde(default)]
|
||||
pub contract_ref: Option<String>,
|
||||
/// When the licence ends.
|
||||
#[serde(default)]
|
||||
#[schema(value_type = Option<String>, format = Date)]
|
||||
pub valid_until: Option<NaiveDate>,
|
||||
/// `shipped` or `build_only`.
|
||||
#[serde(default)]
|
||||
#[schema(value_type = Option<String>, example = "shipped")]
|
||||
pub usage: Option<LicenseUsage>,
|
||||
/// A note.
|
||||
#[serde(default)]
|
||||
pub note: Option<String>,
|
||||
}
|
||||
@@ -196,8 +214,16 @@ fn conclusions_of(
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// GET /api/v1/licenses/conclusions — every licence the workspace
|
||||
/// confirmed, by package name.
|
||||
/// Every licence the workspace 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)]
|
||||
pub async fn list_conclusions(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -212,10 +238,22 @@ pub async fn list_conclusions(
|
||||
}))
|
||||
}
|
||||
|
||||
/// PUT /api/v1/licenses/conclusions — confirm a licence for one or more
|
||||
/// components (one version, or every version of their packages). A second
|
||||
/// confirmation of the same package and version replaces the first. 422
|
||||
/// with the reason when the licence or a field is not acceptable.
|
||||
/// Confirm a licence for one or more components.
|
||||
///
|
||||
/// One version, or every version of their packages. A second confirmation
|
||||
/// 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)]
|
||||
pub async fn conclude(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -261,15 +299,26 @@ pub async fn conclude(
|
||||
}
|
||||
|
||||
/// The query of [`withdraw`].
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct WithdrawQuery {
|
||||
/// The conclusion's id (package and version, see
|
||||
/// [`license::conclusion_id`]); a query value, as it holds `/` and `@`.
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
/// DELETE /api/v1/licenses/conclusions?id= — withdraw a confirmed licence;
|
||||
/// the component shows the detected one again. 404 when there is none.
|
||||
/// Withdraw a confirmed licence; the component shows the detected one again.
|
||||
#[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)]
|
||||
pub async fn withdraw(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -292,12 +341,12 @@ pub async fn withdraw(
|
||||
}
|
||||
|
||||
/// 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.
|
||||
fn may_decide(tenant: &TenantCtx) -> bool {
|
||||
let ctx = &tenant.0;
|
||||
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 {
|
||||
@@ -306,11 +355,21 @@ fn refuse_role() -> Refusal {
|
||||
Json(serde_json::json!({
|
||||
"error": crate::api::role_gate::FORBIDDEN_ROLE,
|
||||
"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)]
|
||||
pub async fn get_policy(
|
||||
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)]
|
||||
pub async fn put_policy(
|
||||
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)))
|
||||
}
|
||||
|
||||
/// The query of [`check`] and [`notices`].
|
||||
#[derive(Debug, Deserialize)]
|
||||
/// The query of [`check`].
|
||||
#[derive(Debug, Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct CheckQuery {
|
||||
/// Only one target's components; every target's without.
|
||||
#[serde(default)]
|
||||
pub repo_id: Option<String>,
|
||||
}
|
||||
@@ -447,6 +521,20 @@ pub struct CheckQuery {
|
||||
/// The most open components one check lists.
|
||||
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)]
|
||||
pub async fn check(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -522,13 +610,17 @@ pub async fn check(
|
||||
}
|
||||
|
||||
/// The body of [`review`].
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||
pub struct ReviewRequest {
|
||||
/// The components.
|
||||
pub components: Vec<ComponentRef>,
|
||||
/// For every version of the packages, not just the listed ones.
|
||||
#[serde(default)]
|
||||
pub all_versions: bool,
|
||||
/// `approved` or `rejected`.
|
||||
#[schema(value_type = String, example = "approved")]
|
||||
pub decision: ReviewDecision,
|
||||
/// Why.
|
||||
#[serde(default)]
|
||||
pub note: Option<String>,
|
||||
}
|
||||
@@ -639,6 +731,19 @@ fn reviewed(
|
||||
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)]
|
||||
pub async fn review(
|
||||
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)]
|
||||
pub async fn withdraw_review(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -715,16 +833,31 @@ pub async fn withdraw_review(
|
||||
}
|
||||
|
||||
/// The query of [`notices`].
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct NoticesQuery {
|
||||
/// The target (its id).
|
||||
pub repo_id: String,
|
||||
/// `text` (default) or `markdown`.
|
||||
#[serde(default)]
|
||||
#[param(value_type = Option<String>, example = "markdown")]
|
||||
pub format: NoticeFormat,
|
||||
/// Also list components only used to build.
|
||||
#[serde(default)]
|
||||
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)]
|
||||
pub async fn notices(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -912,6 +1045,7 @@ mod tests {
|
||||
fn legal_and_it_admin_decide_users_do_not() {
|
||||
assert!(may_decide(&with_roles(vec![OrgRole::Legal])));
|
||||
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::Cxo])));
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//!
|
||||
//! 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
|
||||
//! `IT_ADMIN` role.
|
||||
//! `IT_ADMIN` (or `OWNER`) role.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -16,7 +16,6 @@ use mongodb::bson::{doc, oid::ObjectId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use compliance_core::models::{Finding, ScanType};
|
||||
use compliance_core::tenant::OrgRole;
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use super::dto::tenant_db;
|
||||
@@ -84,9 +83,10 @@ pub struct ImportSummary {
|
||||
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> {
|
||||
if tenant.0.org_roles.contains(&OrgRole::ItAdmin) {
|
||||
if tenant.0.is_admin() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(StatusCode::FORBIDDEN)
|
||||
@@ -221,7 +221,7 @@ pub async fn import_findings(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::tenant::{TenantContext, TenantStatus};
|
||||
use compliance_core::tenant::{OrgRole, TenantContext, TenantStatus};
|
||||
|
||||
fn tenant(roles: Vec<OrgRole>) -> TenantCtx {
|
||||
TenantCtx(TenantContext {
|
||||
@@ -241,6 +241,7 @@ mod tests {
|
||||
#[test]
|
||||
fn only_an_it_admin_writes_findings() {
|
||||
assert_eq!(require_admin(&tenant(vec![OrgRole::ItAdmin])), Ok(()));
|
||||
assert_eq!(require_admin(&tenant(vec![OrgRole::Owner])), Ok(()));
|
||||
assert_eq!(
|
||||
require_admin(&tenant(vec![OrgRole::User, OrgRole::Cxo])),
|
||||
Err(StatusCode::FORBIDDEN)
|
||||
|
||||
@@ -29,23 +29,36 @@ use super::{collect_cursor_async, ApiResponse, PaginationParams};
|
||||
|
||||
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// The body of [`create_target`].
|
||||
#[derive(Deserialize, utoipa::ToSchema)]
|
||||
pub struct CreateTargetRequest {
|
||||
/// The target's name.
|
||||
pub name: String,
|
||||
/// What the target is, such as `web_app`, `backend_service` or `plc_project`.
|
||||
#[schema(value_type = String, example = "web_app")]
|
||||
pub target_type: TargetType,
|
||||
/// A free-text description.
|
||||
#[serde(default)]
|
||||
pub description: Option<String>,
|
||||
/// The target's artifacts by reference; files are uploaded afterwards.
|
||||
#[serde(default)]
|
||||
pub artifacts: Vec<ArtifactInput>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// The body of [`update_target`]. A field left out keeps its stored value.
|
||||
#[derive(Deserialize, utoipa::ToSchema)]
|
||||
pub struct UpdateTargetRequest {
|
||||
/// The target's name.
|
||||
pub name: Option<String>,
|
||||
/// What the target is.
|
||||
#[schema(value_type = Option<String>, example = "web_app")]
|
||||
pub target_type: Option<TargetType>,
|
||||
/// Fields left out keep their stored values.
|
||||
pub scan_config: Option<ScanConfigUpdate>,
|
||||
/// The frameworks and jurisdiction the target is checked against.
|
||||
#[schema(value_type = Option<Object>)]
|
||||
pub compliance_profile: Option<ComplianceProfile>,
|
||||
/// When the target is scanned on its own, a cron expression.
|
||||
pub scan_schedule: Option<String>,
|
||||
/// The tenant's projects this target belongs to; replaces the stored
|
||||
/// list. Each must be one of the tenant's projects in the registry.
|
||||
@@ -76,8 +89,17 @@ fn parse_oid(id: &str) -> Result<ObjectId, StatusCode> {
|
||||
ObjectId::parse_str(id).map_err(|_| StatusCode::BAD_REQUEST)
|
||||
}
|
||||
|
||||
/// GET /api/v1/targets — list onboarded targets (paginated), each with its
|
||||
/// newest scan run.
|
||||
/// List the tenant's targets a page at a time, each with its newest scan run.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/targets",
|
||||
tag = "Targets",
|
||||
params(PaginationParams, TargetFilter),
|
||||
responses(
|
||||
(status = 200, description = "A page of targets"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn list_targets(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -150,7 +172,8 @@ pub struct TargetListItem {
|
||||
}
|
||||
|
||||
/// Which targets a list shows (`?project=<id>`).
|
||||
#[derive(Debug, Default, serde::Deserialize)]
|
||||
#[derive(Debug, Default, serde::Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct TargetFilter {
|
||||
/// Only the targets that belong to this project.
|
||||
#[serde(default)]
|
||||
@@ -260,7 +283,19 @@ async fn findings_counts(
|
||||
}
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets — create an onboarded target.
|
||||
/// Create a target.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/targets",
|
||||
tag = "Targets",
|
||||
request_body = CreateTargetRequest,
|
||||
responses(
|
||||
(status = 200, description = "The new target"),
|
||||
(status = 422, description = "A malformed body"),
|
||||
(status = 503, description = "A credential cannot be sealed"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn create_target(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -295,7 +330,19 @@ pub async fn create_target(
|
||||
}))
|
||||
}
|
||||
|
||||
/// GET /api/v1/targets/{id} — fetch one target.
|
||||
/// One target, credentials redacted.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/targets/{id}",
|
||||
tag = "Targets",
|
||||
params(("id" = String, Path, description = "The target's id")),
|
||||
responses(
|
||||
(status = 200, description = "The target"),
|
||||
(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_target(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -317,9 +364,22 @@ pub async fn get_target(
|
||||
}))
|
||||
}
|
||||
|
||||
/// GET /api/v1/targets/{id}/webhook-deliveries — the target's newest
|
||||
/// webhook deliveries, refused and failed ones included; for a managed
|
||||
/// target also those of its repository from before the target existed.
|
||||
/// The target's newest webhook deliveries.
|
||||
///
|
||||
/// Refused and failed ones included; for a managed target also those of its
|
||||
/// repository from before the target existed.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/targets/{id}/webhook-deliveries",
|
||||
tag = "Targets",
|
||||
params(("id" = String, Path, description = "The target's id")),
|
||||
responses(
|
||||
(status = 200, description = "The newest deliveries"),
|
||||
(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 list_webhook_deliveries(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -353,7 +413,22 @@ pub async fn list_webhook_deliveries(
|
||||
}))
|
||||
}
|
||||
|
||||
/// PATCH /api/v1/targets/{id} — update mutable fields.
|
||||
/// Change a target; a field left out keeps its stored value.
|
||||
#[utoipa::path(
|
||||
patch,
|
||||
path = "/api/v1/targets/{id}",
|
||||
tag = "Targets",
|
||||
params(("id" = String, Path, description = "The target's id")),
|
||||
request_body = UpdateTargetRequest,
|
||||
responses(
|
||||
(status = 200, description = "The changed target"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 404, description = "No such target"),
|
||||
(status = 422, description = "A malformed body, or a project that is not the tenant's"),
|
||||
(status = 503, description = "A credential cannot be sealed"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn update_target(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -473,8 +548,18 @@ async fn remove_target_files(agent: &ComplianceAgent, tenant_id: &str, target: &
|
||||
tracing::info!(removed = removal.removed, "target files removed");
|
||||
}
|
||||
|
||||
/// DELETE /api/v1/targets/{id} — remove the target, its findings/scans and
|
||||
/// its files on disk.
|
||||
/// Delete a target with its findings, scans and files on disk.
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
path = "/api/v1/targets/{id}",
|
||||
tag = "Targets",
|
||||
params(("id" = String, Path, description = "The target's id")),
|
||||
responses(
|
||||
(status = 200, description = "The target was deleted"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn delete_target(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -599,7 +684,21 @@ async fn delete_session_data(db: &crate::database::Database, session_id: &str) {
|
||||
.await;
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets/{id}/artifacts — attach an artifact (by reference).
|
||||
/// Attach an artifact to a target by reference.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/targets/{id}/artifacts",
|
||||
tag = "Targets",
|
||||
params(("id" = String, Path, description = "The target's id")),
|
||||
request_body = ArtifactInput,
|
||||
responses(
|
||||
(status = 200, description = "The target with the artifact"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 422, description = "A malformed body"),
|
||||
(status = 503, description = "A credential cannot be sealed"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn add_artifact(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -624,8 +723,26 @@ pub async fn add_artifact(
|
||||
get_target(Extension(agent), tenant, Path(id)).await
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets/{id}/artifacts/upload — attach an artifact by uploading
|
||||
/// its file (PLC project, firmware image, source archive, mobile package).
|
||||
/// The multipart form of an artifact upload.
|
||||
// Only the API description reads it: the handler takes the fields as they
|
||||
// stream in, so the struct is never built.
|
||||
#[derive(utoipa::ToSchema)]
|
||||
#[allow(dead_code)]
|
||||
pub struct UploadArtifactForm {
|
||||
/// The file, exactly one.
|
||||
#[schema(value_type = String, format = Binary)]
|
||||
file: Vec<u8>,
|
||||
/// What the file is, such as `plc_project`, `firmware_image`,
|
||||
/// `source_archive` or `mobile_package`.
|
||||
#[schema(example = "source_archive")]
|
||||
kind: String,
|
||||
/// The PLC project's format, for a PLC project.
|
||||
plc_format: Option<String>,
|
||||
}
|
||||
|
||||
/// Attach an artifact to a target by uploading its file.
|
||||
///
|
||||
/// A PLC project, firmware image, source archive or mobile package.
|
||||
///
|
||||
/// The file is **streamed to disk** chunk by chunk as it arrives, never held in
|
||||
/// memory whole (it used to be read into one buffer of up to 512 MiB, per
|
||||
@@ -635,6 +752,21 @@ pub async fn add_artifact(
|
||||
/// Multipart fields: `file` (required, exactly one), `kind` (required,
|
||||
/// snake_case `ArtifactKind`), `plc_format` (optional, for PLC projects), in
|
||||
/// any order.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/targets/{id}/artifacts/upload",
|
||||
tag = "Targets",
|
||||
params(("id" = String, Path, description = "The target's id")),
|
||||
request_body(content = UploadArtifactForm, content_type = "multipart/form-data"),
|
||||
responses(
|
||||
(status = 200, description = "The target with the artifact"),
|
||||
(status = 404, description = "No such target"),
|
||||
(status = 400, description = "Not an id, or a missing or unknown field"),
|
||||
(status = 413, description = "The file is too large"),
|
||||
(status = 415, description = "An archive format that cannot be unpacked"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn upload_artifact(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -770,14 +902,13 @@ async fn archive_check(path: std::path::PathBuf) -> Result<ArchiveCheck, StatusC
|
||||
}
|
||||
|
||||
/// The body of [`set_archive_password`].
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||
pub struct ArchivePasswordRequest {
|
||||
/// The archive's password.
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
/// PUT /api/v1/targets/{id}/artifacts/{artifact_id}/archive-password — set the
|
||||
/// password of an uploaded, password-protected archive.
|
||||
/// Set the password of an uploaded, password-protected archive.
|
||||
///
|
||||
/// The password is checked against the stored file first, then stored sealed
|
||||
/// like a git token; the API never returns it. It travels in this JSON body,
|
||||
@@ -788,6 +919,25 @@ pub struct ArchivePasswordRequest {
|
||||
/// 404 without the target or artifact; 409 when the artifact is not a
|
||||
/// password-protected zip; 422 when the password does not open it; 503 when
|
||||
/// the deployment has no key to seal it with.
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/api/v1/targets/{id}/artifacts/{artifact_id}/archive-password",
|
||||
tag = "Targets",
|
||||
params(
|
||||
("id" = String, Path, description = "The target's id"),
|
||||
("artifact_id" = String, Path, description = "The artifact's id"),
|
||||
),
|
||||
request_body = ArchivePasswordRequest,
|
||||
responses(
|
||||
(status = 204, description = "The password opens the archive and is stored"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 404, description = "No such target or artifact"),
|
||||
(status = 409, description = "The artifact is not a password-protected zip"),
|
||||
(status = 422, description = "The password does not open the archive"),
|
||||
(status = 503, description = "The password cannot be sealed"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id, artifact_id = %artifact_id))]
|
||||
pub async fn set_archive_password(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -921,7 +1071,19 @@ fn parse_enum<T: for<'de> Deserialize<'de>>(s: &str) -> Option<T> {
|
||||
serde_json::from_value(serde_json::Value::String(s.to_string())).ok()
|
||||
}
|
||||
|
||||
/// GET /api/v1/targets/{id}/applicable-scans — the scan-applicability matrix.
|
||||
/// The scans that apply to a target, with why and what each one needs.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/targets/{id}/applicable-scans",
|
||||
tag = "Targets",
|
||||
params(("id" = String, Path, description = "The target's id")),
|
||||
responses(
|
||||
(status = 200, description = "The applicable scans"),
|
||||
(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 applicable_scans_for_target(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -960,11 +1122,23 @@ pub async fn applicable_scans_for_target(
|
||||
}))
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets/{id}/detect — classify the target from its artifacts.
|
||||
/// Classify a target from its artifacts.
|
||||
///
|
||||
/// This is the lightweight pass: it classifies from artifact kinds without
|
||||
/// ingesting (cloning) sources, so it returns immediately. Deep detection (after
|
||||
/// ingest, with Firmwerk firmware analysis) is a follow-up background step.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/targets/{id}/detect",
|
||||
tag = "Targets",
|
||||
params(("id" = String, Path, description = "The target's id")),
|
||||
responses(
|
||||
(status = 200, description = "The classified target"),
|
||||
(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 detect_target(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -1007,7 +1181,8 @@ pub async fn detect_target(
|
||||
}
|
||||
|
||||
/// Why a scan is asked for (`POST /api/v1/targets/{id}/scan?reason=…`).
|
||||
#[derive(Debug, Default, serde::Deserialize)]
|
||||
#[derive(Debug, Default, serde::Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct ScanReason {
|
||||
/// `new_content` after the customer created the target or uploaded
|
||||
/// files (t72): it runs only when something changed, as a change-driven
|
||||
@@ -1032,7 +1207,7 @@ fn requested_trigger(staff: bool, reason: Option<&str>) -> compliance_core::mode
|
||||
|
||||
/// `POST /api/v1/targets/{id}/billing/swap`: the included target to swap
|
||||
/// the extra target `{id}` with.
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||
pub struct SwapRequest {
|
||||
/// The id of the included target that becomes extra.
|
||||
pub with: String,
|
||||
@@ -1049,9 +1224,10 @@ fn swap_refusal_code(refusal: compliance_core::models::SwapRefusal) -> &'static
|
||||
}
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets/{id}/billing/swap — swap the extra target `{id}`
|
||||
/// with the included target `with` (t72): `{id}` becomes included and stays
|
||||
/// so until the end of the calendar month, `with` becomes extra at once.
|
||||
/// Swap an extra target with an included one.
|
||||
///
|
||||
/// The extra target `{id}` becomes included and stays so until the end of
|
||||
/// the calendar month; the included target `with` becomes extra at once (t72).
|
||||
/// The number of extra targets, and so the extra-target line, is the same.
|
||||
///
|
||||
/// # Errors
|
||||
@@ -1059,6 +1235,21 @@ fn swap_refusal_code(refusal: compliance_core::models::SwapRefusal) -> &'static
|
||||
/// `404` for a target that is not an active one of the tenant, `409` with
|
||||
/// the reason when the swap is not allowed, `503` when the plan cannot be
|
||||
/// read.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/targets/{id}/billing/swap",
|
||||
tag = "Targets",
|
||||
params(("id" = String, Path, description = "The target's id")),
|
||||
request_body = SwapRequest,
|
||||
responses(
|
||||
(status = 200, description = "The targets were swapped"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 404, description = "Not an active target of the tenant"),
|
||||
(status = 409, description = "The swap is not allowed; `error` says why"),
|
||||
(status = 503, description = "The plan cannot be read"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
pub async fn swap_target_billing(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
@@ -1100,10 +1291,22 @@ pub async fn swap_target_billing(
|
||||
}
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets/{id}/scan — trigger a scan for the target.
|
||||
/// Start a scan of a target.
|
||||
///
|
||||
/// Dispatches to the unified pipeline when `UNIFIED_PIPELINE` is set (else the
|
||||
/// legacy path). Runs in the background and returns immediately.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/targets/{id}/scan",
|
||||
tag = "Targets",
|
||||
params(("id" = String, Path, description = "The target's id"), ScanReason),
|
||||
responses(
|
||||
(status = 200, description = "The scan was started"),
|
||||
(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 trigger_target_scan(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -86,6 +86,13 @@ pub async fn create_session(
|
||||
if let Err(e) = agent.net_guard.check_url(&config.app_url) {
|
||||
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
|
||||
let target = match db
|
||||
@@ -187,35 +194,21 @@ pub async fn create_session(
|
||||
}
|
||||
}
|
||||
|
||||
// Pre-populate test user record for auto-register sessions
|
||||
if let Some(ref cfg) = session.config {
|
||||
if cfg.auth.mode == AuthMode::AutoRegister {
|
||||
let verification_email = cfg.auth.verification_email.clone();
|
||||
// Build plus-addressed email for this session
|
||||
let test_email = verification_email.as_deref().map(|email| {
|
||||
let parts: Vec<&str> = email.splitn(2, '@').collect();
|
||||
if parts.len() == 2 {
|
||||
format!("{}+{}@{}", parts[0], session_id_str, parts[1])
|
||||
} else {
|
||||
email.to_string()
|
||||
}
|
||||
});
|
||||
|
||||
// Detect identity provider from keycloak config
|
||||
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,
|
||||
});
|
||||
}
|
||||
// The test user an auto-register session registers, kept on the
|
||||
// stored session so cleanup and the report find it.
|
||||
if let Some(cfg) = &session.config {
|
||||
session.test_user = crate::pentest::cleanup::planned_test_user(cfg, &session_id_str);
|
||||
}
|
||||
if let (Some(sid), Some(test_user)) = (session.id, &session.test_user) {
|
||||
let record = mongodb::bson::to_bson(test_user)
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
db.pentest_sessions()
|
||||
.update_one(
|
||||
doc! { "_id": sid },
|
||||
doc! { "$set": { "test_user": record } },
|
||||
)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("DB error: {e}")))?;
|
||||
}
|
||||
|
||||
let initial_message = config
|
||||
|
||||
@@ -16,6 +16,16 @@ pub(crate) const MAX_EXPORT_COMPONENTS: u64 = 100_000;
|
||||
/// Package names listed per license in the summary; `count` stays exact.
|
||||
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)]
|
||||
pub async fn sbom_filters(
|
||||
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))]
|
||||
pub async fn list_sbom(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -198,6 +219,20 @@ async fn unresolved_ids(
|
||||
.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)]
|
||||
pub async fn export_sbom(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -274,14 +309,27 @@ pub async fn export_sbom(
|
||||
}
|
||||
|
||||
/// The target whose SBOM quality is asked for.
|
||||
#[derive(serde::Deserialize)]
|
||||
#[derive(serde::Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct SbomQualityParams {
|
||||
/// The target (its id).
|
||||
pub repo_id: String,
|
||||
}
|
||||
|
||||
/// GET /api/v1/sbom/quality?repo_id= — the target's SBOM quality score
|
||||
/// (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.
|
||||
/// A target's SBOM quality score from its newest scan that scored one.
|
||||
///
|
||||
/// 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))]
|
||||
pub async fn sbom_quality(
|
||||
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)]
|
||||
pub async fn license_summary(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -411,6 +472,19 @@ fn summarize_licenses(
|
||||
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)]
|
||||
pub async fn sbom_diff(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -21,13 +21,19 @@ const TOKEN_METHOD: &str = "token";
|
||||
|
||||
/// A client-supplied artifact spec. The server builds the [`Artifact`] (and its
|
||||
/// id) from it, so clients never set internal fields.
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||
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,
|
||||
/// Where it is: a clone URL, or a reference to an uploaded file.
|
||||
pub source_ref: String,
|
||||
/// The branch of a git repository.
|
||||
#[serde(default)]
|
||||
pub branch: Option<String>,
|
||||
/// The PLC project's format, for a PLC project.
|
||||
#[serde(default)]
|
||||
#[schema(value_type = Option<String>, example = "plcopen_xml")]
|
||||
pub plc_format: Option<PlcFormat>,
|
||||
/// A git access token for a private repository (#303). Sent: stored
|
||||
/// 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
|
||||
/// value: enabling a scan must not remove the issue tracker (#304).
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[derive(Debug, Default, Deserialize, utoipa::ToSchema)]
|
||||
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>>,
|
||||
/// The scans not to run.
|
||||
#[schema(value_type = Option<Vec<String>>)]
|
||||
pub disabled_scans: Option<Vec<ScanType>>,
|
||||
/// `development`, `staging` or `production`.
|
||||
#[schema(value_type = Option<String>, example = "staging")]
|
||||
pub environment: Option<Environment>,
|
||||
/// Whether dynamic tests may change data.
|
||||
pub allow_destructive: Option<bool>,
|
||||
/// The pentest strategy: `quick`, `comprehensive`, `targeted` or `aggressive`.
|
||||
#[schema(value_type = Option<String>)]
|
||||
pub strategy: Option<PentestStrategy>,
|
||||
/// The pentest's scope and login.
|
||||
#[schema(value_type = Option<Object>)]
|
||||
pub pentest: Option<PentestConfig>,
|
||||
/// Where findings are filed as issues.
|
||||
#[schema(value_type = Option<Object>)]
|
||||
pub issue_tracker: Option<IssueTrackerConfig>,
|
||||
/// Paths left out of every scan; replaces the stored list. Normalised
|
||||
/// while the request is read, so an invalid path is refused with its
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
pub mod api_key_gate;
|
||||
pub mod handlers;
|
||||
pub mod openapi;
|
||||
pub mod role_gate;
|
||||
pub mod routes;
|
||||
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:
|
||||
//!
|
||||
//! * `IT_ADMIN`, `USER` — read and write.
|
||||
//! * `CXO`, `LEGAL` — read only: `GET` / `HEAD` / `OPTIONS`, plus the few
|
||||
//! * `OWNER`, `IT_ADMIN`, `USER`, `PSIRT`, `DEVELOPMENT` — read and write.
|
||||
//! * `CXO`, `LEGAL`, `QUALITY`, `PURCHASING`, `AUDITOR` — read only: `GET` / `HEAD` / `OPTIONS`, plus the few
|
||||
//! `POST` routes that only read ([`READ_ONLY_POSTS`]). `LEGAL` also
|
||||
//! decides about licences: the licence policy and the legal review
|
||||
//! ([`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"}`.
|
||||
//!
|
||||
@@ -18,7 +19,8 @@
|
||||
//! Werkbank runner and admin APIs (their own token middleware), the health
|
||||
//! 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
|
||||
//! routes in [`KEY_SCOPES`], each with the scope it names; every other route
|
||||
|
||||
@@ -19,11 +19,19 @@ use tower::ServiceExt;
|
||||
/// Who is calling.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum Caller {
|
||||
Owner,
|
||||
ItAdmin,
|
||||
User,
|
||||
Cxo,
|
||||
Legal,
|
||||
Finance,
|
||||
Psirt,
|
||||
Development,
|
||||
Quality,
|
||||
Purchasing,
|
||||
Auditor,
|
||||
Privacy,
|
||||
External,
|
||||
NoRoles,
|
||||
/// BreakPilot support in a customer's tenant (no org roles of its own).
|
||||
Staff,
|
||||
@@ -35,11 +43,19 @@ enum Caller {
|
||||
|
||||
fn ctx(caller: Caller) -> Option<TenantContext> {
|
||||
let roles = match caller {
|
||||
Caller::Owner => vec![OrgRole::Owner],
|
||||
Caller::ItAdmin => vec![OrgRole::ItAdmin],
|
||||
Caller::User => vec![OrgRole::User],
|
||||
Caller::Cxo => vec![OrgRole::Cxo],
|
||||
Caller::Legal => vec![OrgRole::Legal],
|
||||
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::Service => return None,
|
||||
};
|
||||
@@ -196,11 +212,19 @@ fn routes() -> Vec<(Method, String, bool)> {
|
||||
async fn roles_decide_reads_and_writes() {
|
||||
// (caller, may read, may write)
|
||||
let matrix = [
|
||||
(Caller::Owner, true, true),
|
||||
(Caller::ItAdmin, true, true),
|
||||
(Caller::User, true, true),
|
||||
(Caller::Cxo, true, false),
|
||||
(Caller::Legal, true, 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::Staff, true, true),
|
||||
(Caller::Service, true, true),
|
||||
|
||||
+245
-156
@@ -1,15 +1,45 @@
|
||||
use axum::extract::DefaultBodyLimit;
|
||||
use axum::routing::{delete, get, patch, post, put};
|
||||
use axum::http::header::CONTENT_TYPE;
|
||||
use axum::routing::{delete, get, patch, post};
|
||||
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,
|
||||
/// part headers and the small `kind` / `plc_format` text fields.
|
||||
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 {
|
||||
Router::new()
|
||||
let (router, api) = described_routes().split_for_parts();
|
||||
let spec = std::sync::Arc::<str>::from(
|
||||
openapi::with_bearer_auth(api)
|
||||
.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())
|
||||
.route("/api/v1/health", get(handlers::health))
|
||||
.route("/api/v1/oscal/assess", post(handlers::oscal::assess_target))
|
||||
.route("/api/v1/stats/overview", get(handlers::stats_overview))
|
||||
@@ -35,87 +65,44 @@ pub fn build_router() -> Router {
|
||||
post(handlers::support::open_session),
|
||||
)
|
||||
// Unified onboarding targets (#131).
|
||||
.route(
|
||||
"/api/v1/targets",
|
||||
get(handlers::onboarding::list_targets).post(handlers::onboarding::create_target),
|
||||
)
|
||||
// Curated demo targets (D3). Registered before "/targets/{id}" for
|
||||
// readability; the router matches the literal segment first either way.
|
||||
.route(
|
||||
"/api/v1/targets/demo-seed",
|
||||
get(handlers::demo_seed::list_demo_targets)
|
||||
.post(handlers::demo_seed::seed_demo_targets),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}",
|
||||
get(handlers::onboarding::get_target)
|
||||
.patch(handlers::onboarding::update_target)
|
||||
.delete(handlers::onboarding::delete_target),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/artifacts",
|
||||
post(handlers::onboarding::add_artifact),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/webhook-deliveries",
|
||||
get(handlers::onboarding::list_webhook_deliveries),
|
||||
)
|
||||
.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(
|
||||
.routes(routes!(
|
||||
handlers::onboarding::list_targets,
|
||||
handlers::onboarding::create_target
|
||||
))
|
||||
// Curated demo targets (D3).
|
||||
.routes(routes!(
|
||||
handlers::demo_seed::list_demo_targets,
|
||||
handlers::demo_seed::seed_demo_targets
|
||||
))
|
||||
.routes(routes!(
|
||||
handlers::onboarding::get_target,
|
||||
handlers::onboarding::update_target,
|
||||
handlers::onboarding::delete_target
|
||||
))
|
||||
.routes(routes!(handlers::onboarding::add_artifact))
|
||||
.routes(routes!(handlers::onboarding::list_webhook_deliveries))
|
||||
// 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.
|
||||
.routes(
|
||||
routes!(handlers::onboarding::upload_artifact).layer(DefaultBodyLimit::max(
|
||||
crate::targets::MAX_UPLOAD_BYTES as usize + MULTIPART_OVERHEAD,
|
||||
)),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/artifacts/{artifact_id}/archive-password",
|
||||
put(handlers::onboarding::set_archive_password),
|
||||
)
|
||||
.route(
|
||||
"/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::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).
|
||||
.route(
|
||||
"/api/v1/finding-groups",
|
||||
get(handlers::finding_groups::list_finding_groups),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/finding-groups/decide",
|
||||
post(handlers::finding_groups::decide_finding_group),
|
||||
)
|
||||
.routes(routes!(handlers::finding_groups::list_finding_groups))
|
||||
.routes(routes!(handlers::finding_groups::decide_finding_group))
|
||||
// The "Heute" inbox (#950): open decisions in urgency buckets.
|
||||
.route("/api/v1/inbox", get(handlers::inbox::get_inbox))
|
||||
.route("/api/v1/inbox/decide", post(handlers::inbox::decide))
|
||||
@@ -198,31 +185,30 @@ pub fn build_router() -> Router {
|
||||
handlers::manual_findings::MAX_IMPORT_BYTES,
|
||||
)),
|
||||
)
|
||||
.route("/api/v1/sbom", get(handlers::list_sbom))
|
||||
.route("/api/v1/sbom/filters", get(handlers::sbom_filters))
|
||||
.route("/api/v1/sbom/export", get(handlers::export_sbom))
|
||||
.route("/api/v1/sbom/licenses", get(handlers::license_summary))
|
||||
.route("/api/v1/sbom/quality", get(handlers::sbom_quality))
|
||||
.route("/api/v1/sbom/diff", get(handlers::sbom_diff))
|
||||
.routes(routes!(handlers::list_sbom))
|
||||
.routes(routes!(handlers::sbom_filters))
|
||||
.routes(routes!(handlers::export_sbom))
|
||||
.routes(routes!(handlers::license_summary))
|
||||
.routes(routes!(handlers::sbom_quality))
|
||||
.routes(routes!(handlers::sbom_diff))
|
||||
// Licences the workspace confirms for its components.
|
||||
.route(
|
||||
"/api/v1/licenses/conclusions",
|
||||
get(handlers::licenses::list_conclusions)
|
||||
.put(handlers::licenses::conclude)
|
||||
.delete(handlers::licenses::withdraw),
|
||||
)
|
||||
.routes(routes!(
|
||||
handlers::licenses::list_conclusions,
|
||||
handlers::licenses::conclude,
|
||||
handlers::licenses::withdraw
|
||||
))
|
||||
// The licence policy, what it says about each component, and the
|
||||
// legal review that resolves what it asks a review for.
|
||||
.route(
|
||||
"/api/v1/licenses/policy",
|
||||
get(handlers::licenses::get_policy).put(handlers::licenses::put_policy),
|
||||
)
|
||||
.route("/api/v1/licenses/check", get(handlers::licenses::check))
|
||||
.route(
|
||||
"/api/v1/licenses/review",
|
||||
post(handlers::licenses::review).delete(handlers::licenses::withdraw_review),
|
||||
)
|
||||
.route("/api/v1/sbom/notices", get(handlers::licenses::notices))
|
||||
.routes(routes!(
|
||||
handlers::licenses::get_policy,
|
||||
handlers::licenses::put_policy
|
||||
))
|
||||
.routes(routes!(handlers::licenses::check))
|
||||
.routes(routes!(
|
||||
handlers::licenses::review,
|
||||
handlers::licenses::withdraw_review
|
||||
))
|
||||
.routes(routes!(handlers::licenses::notices))
|
||||
.route("/api/v1/issues", get(handlers::list_issues))
|
||||
.route("/api/v1/scan-runs", get(handlers::list_scan_runs))
|
||||
// MCP token management (per-tenant API tokens for the MCP server)
|
||||
@@ -248,63 +234,29 @@ pub fn build_router() -> Router {
|
||||
delete(handlers::mcp_tokens::revoke_mcp_token),
|
||||
)
|
||||
// Graph API endpoints
|
||||
.route("/api/v1/graph/{repo_id}", get(handlers::graph::get_graph))
|
||||
.route(
|
||||
"/api/v1/graph/{repo_id}/nodes",
|
||||
get(handlers::graph::get_nodes),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/graph/{repo_id}/summary",
|
||||
get(handlers::graph::get_summary),
|
||||
)
|
||||
.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),
|
||||
)
|
||||
.routes(routes!(handlers::graph::get_graph))
|
||||
.routes(routes!(handlers::graph::get_nodes))
|
||||
.routes(routes!(handlers::graph::get_summary))
|
||||
.routes(routes!(handlers::graph::get_communities))
|
||||
.routes(routes!(handlers::graph::get_impact))
|
||||
.routes(routes!(handlers::graph::search_symbols))
|
||||
.routes(routes!(handlers::graph::get_file_content))
|
||||
.routes(routes!(handlers::graph::trigger_build))
|
||||
// DAST API endpoints
|
||||
.route("/api/v1/dast/targets", get(handlers::dast::list_targets))
|
||||
.route("/api/v1/dast/targets", post(handlers::dast::add_target))
|
||||
.route(
|
||||
"/api/v1/dast/targets/{id}/scan",
|
||||
post(handlers::dast::trigger_scan),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/dast/scan-runs",
|
||||
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),
|
||||
)
|
||||
.routes(routes!(
|
||||
handlers::dast::list_targets,
|
||||
handlers::dast::add_target
|
||||
))
|
||||
.routes(routes!(handlers::dast::trigger_scan))
|
||||
.routes(routes!(handlers::dast::list_scan_runs))
|
||||
.routes(routes!(handlers::dast::list_findings))
|
||||
.routes(routes!(handlers::dast::get_finding))
|
||||
// Chat / RAG API endpoints
|
||||
.route("/api/v1/chat/{repo_id}", post(handlers::chat::chat))
|
||||
.route(
|
||||
"/api/v1/chat/{repo_id}/build-embeddings",
|
||||
post(handlers::chat::build_embeddings),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/chat/{repo_id}/status",
|
||||
get(handlers::chat::embedding_status),
|
||||
)
|
||||
.routes(routes!(handlers::chat::chat))
|
||||
.routes(routes!(handlers::chat::build_embeddings))
|
||||
.routes(routes!(handlers::chat::embedding_status))
|
||||
// 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
|
||||
.route(
|
||||
"/api/v1/notifications",
|
||||
@@ -386,3 +338,140 @@ pub fn build_router() -> Router {
|
||||
// them here on the API server would mismatch the handler
|
||||
// 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
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
# 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/health
|
||||
/api/v1/oscal/assess
|
||||
/api/v1/stats/overview
|
||||
/api/v1/projects
|
||||
/api/v1/metering/usage
|
||||
/api/v1/access
|
||||
/api/v1/git-source
|
||||
/api/v1/support/tenants
|
||||
/api/v1/support/session
|
||||
/api/v1/inbox
|
||||
/api/v1/inbox/decide
|
||||
/api/v1/inbox/undo
|
||||
/api/v1/inbox/snooze
|
||||
/api/v1/inbox/snooze/{key}
|
||||
/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
|
||||
/api/v1/targets/{id}/evidence-pack
|
||||
/api/v1/targets/{id}/compliance
|
||||
/api/v1/targets/{id}/finding-breakdown
|
||||
/api/v1/compliance/summary
|
||||
/api/v1/controls
|
||||
/api/v1/targets/{id}/findings
|
||||
/api/v1/targets/{id}/findings/import
|
||||
/api/v1/issues
|
||||
/api/v1/scan-runs
|
||||
/api/v1/mcp-servers
|
||||
/api/v1/mcp-servers/{id}
|
||||
/api/v1/mcp-servers/{id}/token
|
||||
/api/v1/mcp-tokens
|
||||
/api/v1/mcp-tokens/{id}
|
||||
/api/v1/notifications
|
||||
/api/v1/notifications/count
|
||||
/api/v1/notifications/read-all
|
||||
/api/v1/notifications/{id}/read
|
||||
/api/v1/notifications/{id}/dismiss
|
||||
/api/v1/pentest/lookup-repo
|
||||
/api/v1/pentest/sessions
|
||||
/api/v1/pentest/sessions/{id}
|
||||
/api/v1/pentest/sessions/{id}/chat
|
||||
/api/v1/pentest/sessions/{id}/stop
|
||||
/api/v1/pentest/sessions/{id}/pause
|
||||
/api/v1/pentest/sessions/{id}/resume
|
||||
/api/v1/pentest/sessions/{id}/stream
|
||||
/api/v1/pentest/sessions/{id}/attack-chain
|
||||
/api/v1/pentest/sessions/{id}/messages
|
||||
/api/v1/pentest/sessions/{id}/findings
|
||||
/api/v1/pentest/sessions/{id}/export
|
||||
/api/v1/pentest/stats
|
||||
@@ -87,8 +87,6 @@ fn build_config(app_env: AppEnv) -> Result<AgentConfig, AgentError> {
|
||||
.unwrap_or_else(|| "/data/compliance-scanner/artifacts".to_string()),
|
||||
keycloak_url: env_var_opt("KEYCLOAK_URL"),
|
||||
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_imap_host: env_var_opt("PENTEST_IMAP_HOST"),
|
||||
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;
|
||||
|
||||
/// What the caller asked to seed.
|
||||
#[derive(Debug, Clone, Default, Deserialize)]
|
||||
#[derive(Debug, Clone, Default, Deserialize, utoipa::ToSchema)]
|
||||
pub struct SeedRequest {
|
||||
/// Manifest keys to seed; empty seeds every target.
|
||||
#[serde(default)]
|
||||
|
||||
@@ -72,11 +72,12 @@ pub enum SbomCoverage {
|
||||
}
|
||||
|
||||
/// The tools that check a target's components rather than its code.
|
||||
const COMPONENT_TOOLS: [&str; 5] = [
|
||||
const COMPONENT_TOOLS: [&str; 6] = [
|
||||
"syft",
|
||||
"osv",
|
||||
"dotnet-lifecycle",
|
||||
"build-lifecycle",
|
||||
compliance_core::models::SBOM_COVERAGE_SCANNER,
|
||||
"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]
|
||||
fn a_failed_cve_lookup_claims_nothing_about_component_cves() {
|
||||
let map = ControlMap::cra().expect("map");
|
||||
|
||||
@@ -102,7 +102,7 @@ pub fn normalise_cwe(raw: &str) -> Option<String> {
|
||||
|
||||
/// The CRA controls a verified weakness is evidence for (see
|
||||
/// [`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()
|
||||
.map(|map| {
|
||||
map.controls_for_cwe(cwe)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -14,6 +14,7 @@ use crate::database::Database;
|
||||
use crate::llm::{
|
||||
ChatMessage, LlmClient, LlmResponse, ToolCallRequest, ToolCallRequestFunction, ToolDefinition,
|
||||
};
|
||||
use crate::pentest::cleanup::CleanupOutcome;
|
||||
|
||||
/// Maximum duration for a single pentest session before timeout
|
||||
const SESSION_TIMEOUT: Duration = Duration::from_secs(30 * 60); // 30 minutes
|
||||
@@ -24,6 +25,8 @@ pub struct PentestOrchestrator {
|
||||
pub(crate) db: Database,
|
||||
pub(crate) event_tx: broadcast::Sender<PentestEvent>,
|
||||
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 {
|
||||
@@ -42,6 +45,55 @@ impl PentestOrchestrator {
|
||||
db,
|
||||
event_tx,
|
||||
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;
|
||||
}
|
||||
|
||||
// Clean up test user via identity provider API if requested
|
||||
if session
|
||||
.config
|
||||
.as_ref()
|
||||
.is_some_and(|c| c.auth.cleanup_test_user)
|
||||
// Delete the test user in the target's identity provider if asked.
|
||||
if let (Some(cfg), Some(test_user)) = (session.config.as_ref(), session.test_user.as_ref())
|
||||
{
|
||||
if let Some(ref test_user) = session.test_user {
|
||||
let http = reqwest::Client::new();
|
||||
// We need the AgentConfig — read from env since orchestrator doesn't hold it
|
||||
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");
|
||||
}
|
||||
}
|
||||
if cfg.auth.cleanup_test_user {
|
||||
self.clean_up_test_user(session.id, test_user, cfg.auth.cleanup.as_ref())
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,8 @@ use compliance_core::models::sbom::SbomEntry;
|
||||
use super::orchestrator::PentestOrchestrator;
|
||||
|
||||
/// 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();
|
||||
|
||||
// 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",
|
||||
);
|
||||
}
|
||||
if let Some(ref email) = config.auth.verification_email {
|
||||
if let Some(email) = test_email {
|
||||
sections.push_str(&format!(
|
||||
"- **Verification Email**: Use plus-addressing from `{email}` \
|
||||
(e.g. `{base}+{{session_id}}@{domain}`) for email verification. \
|
||||
The system will poll the IMAP mailbox for verification links.\n",
|
||||
base = email.split('@').next().unwrap_or(email),
|
||||
domain = email.split('@').nth(1).unwrap_or("example.com"),
|
||||
"- **E-mail address**: Register with exactly `{email}` (no other \
|
||||
address): the system polls its mailbox for verification links and \
|
||||
finds the test account by it afterwards.\n",
|
||||
));
|
||||
}
|
||||
sections.push_str(
|
||||
@@ -245,7 +244,10 @@ impl PentestOrchestrator {
|
||||
let config_sections = session
|
||||
.config
|
||||
.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();
|
||||
|
||||
format!(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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(
|
||||
session: &PentestSession,
|
||||
@@ -43,6 +43,9 @@ pub(super) fn scope(
|
||||
AuthMode::AutoRegister => "Auto-register",
|
||||
};
|
||||
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() {
|
||||
let excl = cfg
|
||||
.scope_exclusions
|
||||
@@ -125,3 +128,47 @@ pub(super) fn scope(
|
||||
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"));
|
||||
}
|
||||
}
|
||||
@@ -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 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.
|
||||
const GRAPH_MAX_NODES: u32 = 50_000;
|
||||
|
||||
@@ -105,8 +108,15 @@ impl PipelineOrchestrator {
|
||||
})
|
||||
}
|
||||
|
||||
/// Trigger DAST scan if a target is configured for this repo
|
||||
pub(super) async fn maybe_trigger_dast(&self, repo_id: &str, scan_run_id: &str) {
|
||||
/// The DAST stage: scan every DAST target of `repo_id` and wait for the
|
||||
/// 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;
|
||||
|
||||
if self.source_only() {
|
||||
@@ -115,45 +125,151 @@ impl PipelineOrchestrator {
|
||||
compliance_core::models::SkippedStage::feature_disabled("dast"),
|
||||
)
|
||||
.await;
|
||||
return;
|
||||
return 0;
|
||||
}
|
||||
|
||||
let filter = mongodb::bson::doc! { "repo_id": repo_id };
|
||||
let targets: Vec<compliance_core::models::DastTarget> =
|
||||
match self.db.dast_targets().find(filter).await {
|
||||
Ok(cursor) => cursor.try_collect().await.unwrap_or_default(),
|
||||
Err(_) => return,
|
||||
Err(_) => return 0,
|
||||
};
|
||||
|
||||
if targets.is_empty() {
|
||||
tracing::info!("[{repo_id}] No DAST targets configured, skipping");
|
||||
return;
|
||||
return 0;
|
||||
}
|
||||
|
||||
for target in targets {
|
||||
let db = self.db.clone();
|
||||
let scan_run_id = scan_run_id.to_string();
|
||||
let net_guard = self.net_guard;
|
||||
tokio::spawn(async move {
|
||||
let orchestrator = compliance_dast::DastOrchestrator::new(100, net_guard);
|
||||
match orchestrator.run_scan(&target, Vec::new()).await {
|
||||
Ok((mut scan_run, findings)) => {
|
||||
scan_run.sast_scan_run_id = Some(scan_run_id);
|
||||
if let Err(e) = db.dast_scan_runs().insert_one(&scan_run).await {
|
||||
tracing::error!("Failed to store DAST scan run: {e}");
|
||||
}
|
||||
for finding in &findings {
|
||||
if let Err(e) = db.dast_findings().insert_one(finding).await {
|
||||
tracing::error!("Failed to store DAST finding: {e}");
|
||||
}
|
||||
}
|
||||
tracing::info!("DAST scan complete: {} findings", findings.len());
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("DAST scan failed: {e}");
|
||||
}
|
||||
}
|
||||
});
|
||||
let mut new_count = 0;
|
||||
for mut target in targets {
|
||||
self.secrets.open_in_place(&mut target);
|
||||
match self.run_dast_target(&target, repo_id, scan_run_id).await {
|
||||
Ok(added) => new_count += added,
|
||||
Err(failed) => self.skip_stage(scan_run_id, failed).await,
|
||||
}
|
||||
}
|
||||
new_count
|
||||
}
|
||||
|
||||
/// Scan one DAST target, waiting for the result (#998), and store the
|
||||
/// scan run and its findings: as DAST findings, with their evidence, and
|
||||
/// as findings of the target `repo_id`.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// How many findings the target did not have yet.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 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)
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ fn language_of(extension: &str) -> Option<&'static str> {
|
||||
"cs" => "csharp",
|
||||
"vb" => "vb",
|
||||
"swift" => "swift",
|
||||
"dart" => "dart",
|
||||
// Objective-C; `.m` is also MATLAB's extension, which only means
|
||||
// mobsfscan looks at a tree it finds nothing in.
|
||||
"m" | "mm" => "objc",
|
||||
|
||||
@@ -13,6 +13,7 @@ pub mod cve;
|
||||
pub(crate) mod cve_enrichment;
|
||||
pub(crate) mod cve_issues;
|
||||
pub mod cve_notify;
|
||||
pub mod dast_findings;
|
||||
pub mod dedup;
|
||||
pub mod devskim;
|
||||
pub mod dotnet;
|
||||
|
||||
@@ -538,7 +538,8 @@ impl PipelineOrchestrator {
|
||||
// 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
|
||||
// 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(
|
||||
scan_run_id,
|
||||
SkippedStage::new(
|
||||
@@ -549,7 +550,7 @@ impl PipelineOrchestrator {
|
||||
eco.manifest, eco.problem, eco.remedy
|
||||
),
|
||||
)
|
||||
.about(eco.manifest),
|
||||
.about(eco.manifest.clone()),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
@@ -642,6 +643,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
|
||||
tracing::info!("[{repo_id}] Stage 3: CVE Scanning");
|
||||
self.update_phase(scan_run_id, ScanPhase::CveScanning).await;
|
||||
@@ -1719,7 +1763,7 @@ impl PipelineOrchestrator {
|
||||
if plan.has(ScanType::Dast) {
|
||||
self.update_phase(scan_run_id, ScanPhase::DastScanning)
|
||||
.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);
|
||||
}
|
||||
@@ -1757,7 +1801,8 @@ impl PipelineOrchestrator {
|
||||
let n = self.run_pipeline(&repo, scan_run_id, trigger).await?;
|
||||
self.finalize_target(target, &repo, n).await?;
|
||||
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;
|
||||
}
|
||||
Some(code) => {
|
||||
@@ -1774,7 +1819,8 @@ impl PipelineOrchestrator {
|
||||
let n = self.scan_tree(tree, upload, &repo, scan_run_id).await?;
|
||||
self.finalize_target(target, &repo, n).await?;
|
||||
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;
|
||||
}
|
||||
// The ingest stage recorded why. A run over nothing must not
|
||||
@@ -1810,7 +1856,7 @@ impl PipelineOrchestrator {
|
||||
);
|
||||
self.update_phase(scan_run_id, ScanPhase::DastScanning)
|
||||
.await;
|
||||
self.maybe_trigger_dast(&target_id, scan_run_id).await;
|
||||
new_count += self.maybe_trigger_dast(&target_id, scan_run_id).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2564,13 +2610,13 @@ impl PipelineOrchestrator {
|
||||
target_id: &str,
|
||||
plan: &crate::pipeline::plan::ScanPlan,
|
||||
scan_run_id: &str,
|
||||
) {
|
||||
) -> u32 {
|
||||
if !plan.has(ScanType::Dast) {
|
||||
return;
|
||||
return 0;
|
||||
}
|
||||
self.update_phase(scan_run_id, ScanPhase::DastScanning)
|
||||
.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
|
||||
@@ -2618,15 +2664,23 @@ impl PipelineOrchestrator {
|
||||
dast.allow_destructive = web.allow_destructive;
|
||||
}
|
||||
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 {
|
||||
method: auth.method.clone(),
|
||||
login_url: auth.login_url.clone(),
|
||||
username: auth.username.clone(),
|
||||
password: None,
|
||||
token: auth.secret.clone(),
|
||||
password: auth.secret.clone().filter(|_| basic),
|
||||
token: auth.secret.clone().filter(|_| !basic),
|
||||
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 {
|
||||
tracing::warn!(error = %e, "Unified pipeline: failed to provision DAST target");
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -147,6 +147,7 @@ pub(crate) fn unlocked_mobile_ecosystems(root: &Path) -> Vec<UnlockedEcosystem>
|
||||
manifest,
|
||||
problem: eco.problem,
|
||||
remedy: eco.remedy,
|
||||
legacy_build: false,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
mod cargo_audit;
|
||||
pub(crate) mod carthage;
|
||||
pub(crate) mod coverage;
|
||||
mod distribution;
|
||||
mod gradle;
|
||||
mod mobile;
|
||||
@@ -224,6 +225,9 @@ pub(crate) struct UnlockedEcosystem {
|
||||
pub problem: &'static str,
|
||||
/// What to commit so they are.
|
||||
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
|
||||
@@ -266,12 +270,14 @@ pub(crate) fn unlocked_ecosystems(
|
||||
manifest: "package.json".into(),
|
||||
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`)",
|
||||
legacy_build: false,
|
||||
});
|
||||
} else if !readable {
|
||||
out.push(UnlockedEcosystem {
|
||||
manifest: "package.json".into(),
|
||||
problem: "declares dependencies but no lockfile pins them",
|
||||
remedy: "commit package-lock.json, yarn.lock, pnpm-lock.yaml or bun.lock",
|
||||
legacy_build: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -284,6 +290,7 @@ pub(crate) fn unlocked_ecosystems(
|
||||
manifest: manifest.into(),
|
||||
problem: "declares dependencies but no lockfile pins them",
|
||||
remedy: "commit requirements.txt, poetry.lock, Pipfile.lock or uv.lock",
|
||||
legacy_build: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -292,6 +299,7 @@ pub(crate) fn unlocked_ecosystems(
|
||||
manifest: "Cargo.toml".into(),
|
||||
problem: "declares dependencies but no lockfile pins them",
|
||||
remedy: "commit Cargo.lock",
|
||||
legacy_build: false,
|
||||
});
|
||||
}
|
||||
out.extend(mobile::unlocked_mobile_ecosystems(repo_path));
|
||||
@@ -307,6 +315,7 @@ pub(crate) fn unlocked_ecosystems(
|
||||
Packages/manifest.json) whose dependencies cannot be read",
|
||||
remedy: "migrate the build (Gradle with the Android Gradle Plugin, or a \
|
||||
current Unity LTS with the Package Manager)",
|
||||
legacy_build: true,
|
||||
}),
|
||||
);
|
||||
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 \
|
||||
project or a Directory.Build.props), restore once and commit \
|
||||
packages.lock.json",
|
||||
legacy_build: false,
|
||||
}]
|
||||
}
|
||||
|
||||
|
||||
@@ -114,7 +114,9 @@ impl GiteaTracker {
|
||||
|
||||
/// 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
|
||||
/// 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
|
||||
///
|
||||
@@ -133,10 +135,11 @@ impl GiteaTracker {
|
||||
let url = self.api_url(&format!(
|
||||
"{path}{separator}page={page}&limit={LIST_PAGE_SIZE}"
|
||||
));
|
||||
let batch: Vec<T> = self.send_json(what, self.http.get(&url)).await?;
|
||||
if batch.is_empty() {
|
||||
// `Option` takes the `null` page; serde reads it as `None`.
|
||||
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);
|
||||
}
|
||||
};
|
||||
all.extend(batch);
|
||||
}
|
||||
Err(CoreError::IssueTracker(format!(
|
||||
@@ -800,6 +803,75 @@ mod tests {
|
||||
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]
|
||||
async fn a_failed_listing_is_an_error_not_an_empty_list() {
|
||||
let app = Router::new().route(
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::common::TestServer;
|
||||
use mongodb::bson::doc;
|
||||
use serde_json::json;
|
||||
|
||||
#[tokio::test]
|
||||
@@ -46,3 +47,154 @@ async fn list_dast_findings_empty() {
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_targets_login_is_stored_sealed_and_never_returned() {
|
||||
let server = TestServer::start().await;
|
||||
|
||||
let resp = server
|
||||
.post(
|
||||
"/api/v1/dast/targets",
|
||||
&json!({
|
||||
"name": "members",
|
||||
"base_url": "https://members.example.com",
|
||||
"auth": {
|
||||
"method": "bearer",
|
||||
"token": "tok-secret",
|
||||
"headers": { "X-Api-Key": "key-secret" },
|
||||
},
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(resp.status(), 200);
|
||||
let body: serde_json::Value = resp.json().await.unwrap();
|
||||
let id = body["data"]["_id"]["$oid"].as_str().expect("the new id");
|
||||
let returned = body.to_string();
|
||||
assert!(
|
||||
!returned.contains("tok-secret") && !returned.contains("key-secret"),
|
||||
"{returned}"
|
||||
);
|
||||
|
||||
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
|
||||
let stored = client
|
||||
.database(&server.tenant_db_name())
|
||||
.collection::<mongodb::bson::Document>("dast_targets")
|
||||
.find_one(mongodb::bson::doc! {
|
||||
"_id": mongodb::bson::oid::ObjectId::parse_str(id).unwrap()
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("stored under the returned id");
|
||||
let auth = stored.get_document("auth_config").unwrap();
|
||||
let token = auth.get_str("token").unwrap();
|
||||
let header = auth
|
||||
.get_document("headers")
|
||||
.unwrap()
|
||||
.get_str("X-Api-Key")
|
||||
.unwrap();
|
||||
assert!(token != "tok-secret" && header != "key-secret", "{auth}");
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_login_the_scan_cannot_send_is_refused() {
|
||||
let server = TestServer::start().await;
|
||||
|
||||
for auth in [
|
||||
json!({ "method": "form", "login_url": "https://members.example.com/login" }),
|
||||
json!({ "method": "bearer" }),
|
||||
json!({ "method": "ntlm", "token": "t" }),
|
||||
] {
|
||||
let resp = server
|
||||
.post(
|
||||
"/api/v1/dast/targets",
|
||||
&json!({ "name": "m", "base_url": "https://members.example.com", "auth": auth }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(resp.status(), 400, "{auth}");
|
||||
}
|
||||
let resp = server.get("/api/v1/dast/targets").await;
|
||||
let body: serde_json::Value = resp.json().await.unwrap();
|
||||
assert!(body["data"].as_array().unwrap().is_empty());
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
|
||||
/// A DAST scan that does not complete is a failed `dast` stage of the scan
|
||||
/// run, recorded once the stage has waited for it; the run itself completes
|
||||
/// (#998). The live URL does not resolve, so reconnaissance fails.
|
||||
#[tokio::test]
|
||||
async fn a_dast_scan_that_does_not_complete_is_a_failed_stage_of_the_run() {
|
||||
let server = TestServer::start().await;
|
||||
let created: serde_json::Value = server
|
||||
.post(
|
||||
"/api/v1/targets",
|
||||
&json!({
|
||||
"name": "web",
|
||||
"target_type": "web_app",
|
||||
"artifacts": [
|
||||
{ "kind": "live_url", "source_ref": "https://no-such-host.example.com" }
|
||||
]
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.json()
|
||||
.await
|
||||
.unwrap();
|
||||
let id = created["data"]["_id"]["$oid"].as_str().unwrap().to_string();
|
||||
|
||||
server
|
||||
.post(&format!("/api/v1/targets/{id}/scan"), &json!({}))
|
||||
.await;
|
||||
|
||||
let client = mongodb::Client::with_uri_str(&server_mongodb_uri())
|
||||
.await
|
||||
.unwrap();
|
||||
let runs = client
|
||||
.database(&server.tenant_db_name())
|
||||
.collection::<mongodb::bson::Document>("scan_runs");
|
||||
let mut run = None;
|
||||
for _ in 0..120 {
|
||||
let found = runs
|
||||
.find_one(doc! { "repo_id": &id, "status": { "$in": ["completed", "failed"] } })
|
||||
.await
|
||||
.unwrap();
|
||||
if found.is_some() {
|
||||
run = found;
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
||||
}
|
||||
let run = run.expect("the scan run finished");
|
||||
|
||||
assert_eq!(run.get_str("status").unwrap(), "completed");
|
||||
let dast: Vec<_> = run
|
||||
.get_array("skipped_stages")
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|s| s.as_document())
|
||||
.filter(|s| s.get_str("stage") == Ok("dast"))
|
||||
.collect();
|
||||
assert_eq!(dast.len(), 1, "{run:?}");
|
||||
assert_eq!(dast[0].get_str("code").unwrap(), "tool_failed");
|
||||
assert_eq!(dast[0].get_str("subject").unwrap(), "DAST");
|
||||
// The DAST run itself is stored, with the scanner's reason.
|
||||
let dast_run = client
|
||||
.database(&server.tenant_db_name())
|
||||
.collection::<mongodb::bson::Document>("dast_scan_runs")
|
||||
.find_one(doc! {})
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("the DAST run is stored");
|
||||
assert_eq!(dast_run.get_str("status").unwrap(), "failed");
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
|
||||
fn server_mongodb_uri() -> String {
|
||||
std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into())
|
||||
}
|
||||
@@ -3,5 +3,6 @@ mod dast;
|
||||
mod findings;
|
||||
mod health;
|
||||
mod onboarding;
|
||||
mod openapi;
|
||||
mod sbom;
|
||||
mod stats;
|
||||
@@ -0,0 +1,22 @@
|
||||
use crate::common::TestServer;
|
||||
|
||||
/// The agent serves its OpenAPI description (#1006), with the described
|
||||
/// routes and the bearer scheme.
|
||||
#[tokio::test]
|
||||
async fn the_agent_serves_its_openapi_description() {
|
||||
let server = TestServer::start().await;
|
||||
|
||||
let resp = server.get("/api/v1/openapi.json").await;
|
||||
|
||||
assert_eq!(resp.status(), 200);
|
||||
assert_eq!(
|
||||
resp.headers()["content-type"].to_str().unwrap(),
|
||||
"application/json"
|
||||
);
|
||||
let doc: serde_json::Value = resp.json().await.unwrap();
|
||||
assert_eq!(doc["info"]["title"], "Prüfwerk API");
|
||||
assert!(doc["paths"]["/api/v1/dast/targets"]["post"].is_object());
|
||||
assert!(doc["components"]["securitySchemes"]["bearer"].is_object());
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "compliance-core"
|
||||
version = "0.4.6"
|
||||
version = "0.4.16"
|
||||
edition = "2021"
|
||||
|
||||
[lints]
|
||||
|
||||
@@ -39,8 +39,6 @@ pub struct AgentConfig {
|
||||
pub artifact_store_base_path: String,
|
||||
pub keycloak_url: Option<String>,
|
||||
pub keycloak_realm: Option<String>,
|
||||
pub keycloak_admin_username: Option<String>,
|
||||
pub keycloak_admin_password: Option<SecretString>,
|
||||
// Pentest defaults
|
||||
pub pentest_verification_email: Option<String>,
|
||||
pub pentest_imap_host: Option<String>,
|
||||
@@ -349,8 +347,6 @@ impl Default for AgentConfig {
|
||||
artifact_store_base_path: "/data/compliance-scanner/artifacts".to_string(),
|
||||
keycloak_url: None,
|
||||
keycloak_realm: None,
|
||||
keycloak_admin_username: None,
|
||||
keycloak_admin_password: None,
|
||||
pentest_verification_email: None,
|
||||
pentest_imap_host: None,
|
||||
pentest_imap_port: None,
|
||||
|
||||
@@ -6,17 +6,25 @@
|
||||
//! every one before a record leaves the service, and a field added later only
|
||||
//! has to be listed here.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::dast::{DastAuthConfig, DastTarget};
|
||||
use super::onboarding::{
|
||||
Artifact, ArtifactAuth, IssueTrackerConfig, OnboardedTarget, TargetScanConfig,
|
||||
};
|
||||
use super::pentest::{PentestAuthConfig, PentestConfig, PentestSession};
|
||||
use super::pentest::{PentestAuthConfig, PentestConfig, PentestSession, TestUserCleanup};
|
||||
|
||||
/// A record that carries stored credentials.
|
||||
pub trait Credentials {
|
||||
/// Every credential field of the record, for sealing before a write.
|
||||
fn credentials_mut(&mut self) -> Vec<&mut Option<String>>;
|
||||
|
||||
/// Maps whose every value is a credential (login headers), sealed and
|
||||
/// opened value by value. None by default.
|
||||
fn credential_maps_mut(&mut self) -> Vec<&mut HashMap<String, String>> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Remove every credential before the record leaves the service.
|
||||
fn redact(&mut self) {
|
||||
for slot in self.credentials_mut() {
|
||||
@@ -39,6 +47,12 @@ impl<T: Credentials> Credentials for Option<T> {
|
||||
self.as_mut().map(T::credentials_mut).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn credential_maps_mut(&mut self) -> Vec<&mut HashMap<String, String>> {
|
||||
self.as_mut()
|
||||
.map(T::credential_maps_mut)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn redact(&mut self) {
|
||||
if let Some(inner) = self {
|
||||
inner.redact();
|
||||
@@ -51,6 +65,10 @@ impl<T: Credentials> Credentials for Vec<T> {
|
||||
self.iter_mut().flat_map(T::credentials_mut).collect()
|
||||
}
|
||||
|
||||
fn credential_maps_mut(&mut self) -> Vec<&mut HashMap<String, String>> {
|
||||
self.iter_mut().flat_map(T::credential_maps_mut).collect()
|
||||
}
|
||||
|
||||
fn redact(&mut self) {
|
||||
self.iter_mut().for_each(T::redact);
|
||||
}
|
||||
@@ -88,7 +106,20 @@ impl Credentials for IssueTrackerConfig {
|
||||
|
||||
impl Credentials for PentestAuthConfig {
|
||||
fn credentials_mut(&mut self) -> Vec<&mut Option<String>> {
|
||||
vec![&mut self.password, &mut self.imap_password]
|
||||
let mut slots = vec![&mut self.password, &mut self.imap_password];
|
||||
slots.extend(self.cleanup.credentials_mut());
|
||||
slots
|
||||
}
|
||||
}
|
||||
|
||||
impl Credentials for TestUserCleanup {
|
||||
fn credentials_mut(&mut self) -> Vec<&mut Option<String>> {
|
||||
match self {
|
||||
Self::Keycloak { client_secret, .. } | Self::Auth0 { client_secret, .. } => {
|
||||
vec![client_secret]
|
||||
}
|
||||
Self::Okta { api_token, .. } => vec![api_token],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,6 +157,12 @@ impl Credentials for DastAuthConfig {
|
||||
vec![&mut self.password, &mut self.token]
|
||||
}
|
||||
|
||||
/// Login headers (an API key, a session cookie) are sent with every scan
|
||||
/// request, so they are sealed like the token (#1000).
|
||||
fn credential_maps_mut(&mut self) -> Vec<&mut HashMap<String, String>> {
|
||||
self.headers.as_mut().into_iter().collect()
|
||||
}
|
||||
|
||||
fn redact(&mut self) {
|
||||
self.password = None;
|
||||
self.token = None;
|
||||
@@ -138,6 +175,10 @@ impl Credentials for DastTarget {
|
||||
self.auth_config.credentials_mut()
|
||||
}
|
||||
|
||||
fn credential_maps_mut(&mut self) -> Vec<&mut HashMap<String, String>> {
|
||||
self.auth_config.credential_maps_mut()
|
||||
}
|
||||
|
||||
fn redact(&mut self) {
|
||||
self.auth_config.redact();
|
||||
}
|
||||
@@ -218,6 +259,12 @@ mod tests {
|
||||
username: Some("tester".into()),
|
||||
password: Some("pw".into()),
|
||||
imap_password: Some("imap".into()),
|
||||
cleanup: Some(TestUserCleanup::Keycloak {
|
||||
base_url: "https://login.example.com".into(),
|
||||
realm: "app".into(),
|
||||
client_id: "cleanup".into(),
|
||||
client_secret: Some("kc-secret".into()),
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
custom_headers: HashMap::new(),
|
||||
@@ -239,5 +286,14 @@ mod tests {
|
||||
assert_eq!(auth.username.as_deref(), Some("tester"));
|
||||
assert_eq!(auth.password, None);
|
||||
assert_eq!(auth.imap_password, None);
|
||||
assert_eq!(
|
||||
auth.cleanup,
|
||||
Some(TestUserCleanup::Keycloak {
|
||||
base_url: "https://login.example.com".into(),
|
||||
realm: "app".into(),
|
||||
client_id: "cleanup".into(),
|
||||
client_secret: None,
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -91,6 +91,7 @@ pub enum DastScanPhase {
|
||||
Reconnaissance,
|
||||
Crawling,
|
||||
VulnerabilityAnalysis,
|
||||
/// Recorded without doing anything; only in runs from before #998.
|
||||
Exploitation,
|
||||
Reporting,
|
||||
Completed,
|
||||
|
||||
@@ -85,7 +85,7 @@ pub use project::{Project, ProjectKind};
|
||||
pub use repository::ScanTrigger;
|
||||
pub use sbom::{
|
||||
ComponentHash, InImage, InImageBasis, SbomEntry, SbomQuality, SbomQualityCheck,
|
||||
SbomQualityProfile, VulnRef, YOCTO_RECIPE_MANAGER, YOCTO_RECIPE_SOURCE,
|
||||
SbomQualityProfile, VulnRef, SBOM_COVERAGE_SCANNER, YOCTO_RECIPE_MANAGER, YOCTO_RECIPE_SOURCE,
|
||||
};
|
||||
pub use scan::{
|
||||
RunErrorCode, RunNote, ScanPhase, ScanRun, ScanRunStatus, ScanStep, ScanType, SkipCode,
|
||||
|
||||
@@ -569,6 +569,19 @@ impl OnboardedTarget {
|
||||
&& classification.suggested != self.target_type;
|
||||
detected.then_some(classification.suggested)
|
||||
}
|
||||
|
||||
/// Whether Prüfwerk opens tickets for this target's findings on its own:
|
||||
/// the target came from a managed git source, or an issue tracker of a
|
||||
/// known type is configured on it. A tracker block without a type opens
|
||||
/// nothing, so it does not count.
|
||||
pub fn issue_tracker_connected(&self) -> bool {
|
||||
self.source_repo.is_some()
|
||||
|| self
|
||||
.scan_config
|
||||
.issue_tracker
|
||||
.as_ref()
|
||||
.is_some_and(|tracker| tracker.tracker_type.is_some())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn default_compliance_profile(target_type: TargetType) -> ComplianceProfile {
|
||||
@@ -802,6 +815,28 @@ mod tests {
|
||||
assert_eq!(onboarded.detected_type(&android), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_target_has_a_tracker_when_one_is_set_or_it_is_managed() {
|
||||
let mut target = OnboardedTarget::new("fw".into(), TargetType::BackendService);
|
||||
assert!(!target.issue_tracker_connected());
|
||||
// A tracker block without a type cannot open tickets.
|
||||
target.scan_config.issue_tracker = Some(IssueTrackerConfig::default());
|
||||
assert!(!target.issue_tracker_connected());
|
||||
target.scan_config.issue_tracker = Some(IssueTrackerConfig {
|
||||
tracker_type: Some(TrackerType::GitLab),
|
||||
..Default::default()
|
||||
});
|
||||
assert!(target.issue_tracker_connected());
|
||||
// A managed repository's issues are opened by its git source.
|
||||
let mut managed = OnboardedTarget::new("gt-mobile".into(), TargetType::BackendService);
|
||||
managed.source_repo = Some(super::super::git_source::SourceRepo {
|
||||
base_url: "https://kunde.code.example".into(),
|
||||
repo_id: 7,
|
||||
full_name: "kunde/gt-mobile".into(),
|
||||
});
|
||||
assert!(managed.issue_tracker_connected());
|
||||
}
|
||||
|
||||
fn sample_target() -> OnboardedTarget {
|
||||
let mut t = OnboardedTarget::new("acme-web".to_string(), TargetType::WebApp);
|
||||
t.artifacts.push(Artifact::git_repo(
|
||||
|
||||
@@ -110,6 +110,66 @@ pub struct PentestAuthConfig {
|
||||
pub imap_password: Option<String>,
|
||||
#[serde(default)]
|
||||
pub cleanup_test_user: bool,
|
||||
/// Admin access to the target's own identity provider, given for this
|
||||
/// session, so the test user can be deleted afterwards. Without it the
|
||||
/// test user is left behind and the report says so: the agent never uses
|
||||
/// its own identity provider for this.
|
||||
#[serde(default)]
|
||||
pub cleanup: Option<TestUserCleanup>,
|
||||
}
|
||||
|
||||
/// Where and how the test user of an auto-register session is deleted: the
|
||||
/// target's identity provider, with credentials given for the session.
|
||||
///
|
||||
/// The user is looked up by the session's own e-mail address
|
||||
/// (`base+{session_id}@domain`), which no real account carries.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(tag = "provider", rename_all = "snake_case")]
|
||||
pub enum TestUserCleanup {
|
||||
/// A Keycloak realm, through a confidential client whose service account
|
||||
/// may manage that realm's users (`realm-management: manage-users`).
|
||||
Keycloak {
|
||||
/// Keycloak's base URL, e.g. `https://login.example.com`.
|
||||
base_url: String,
|
||||
/// The realm the test user registered in.
|
||||
realm: String,
|
||||
client_id: String,
|
||||
client_secret: Option<String>,
|
||||
},
|
||||
/// An Auth0 tenant, through a machine-to-machine application with the
|
||||
/// Management API scopes `read:users` and `delete:users`.
|
||||
Auth0 {
|
||||
/// The tenant's domain, e.g. `example.eu.auth0.com`.
|
||||
domain: String,
|
||||
client_id: String,
|
||||
client_secret: Option<String>,
|
||||
},
|
||||
/// An Okta org, through an API token allowed to manage users.
|
||||
Okta {
|
||||
/// The org's domain, e.g. `example.okta.com`.
|
||||
domain: String,
|
||||
api_token: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
impl TestUserCleanup {
|
||||
/// The identity provider this cleanup acts on.
|
||||
pub fn provider(&self) -> IdentityProvider {
|
||||
match self {
|
||||
Self::Keycloak { .. } => IdentityProvider::Keycloak,
|
||||
Self::Auth0 { .. } => IdentityProvider::Auth0,
|
||||
Self::Okta { .. } => IdentityProvider::Okta,
|
||||
}
|
||||
}
|
||||
|
||||
/// The URL the cleanup talks to, for the outbound check before a session
|
||||
/// starts.
|
||||
pub fn base_url(&self) -> String {
|
||||
match self {
|
||||
Self::Keycloak { base_url, .. } => base_url.trim_end_matches('/').to_string(),
|
||||
Self::Auth0 { domain, .. } | Self::Okta { domain, .. } => format!("https://{domain}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Full wizard configuration for a pentest session
|
||||
@@ -150,7 +210,8 @@ pub struct PentestConfig {
|
||||
pub skip_mode: bool,
|
||||
}
|
||||
|
||||
/// Identity provider type for cleanup routing
|
||||
/// The identity provider that holds a test user. `Firebase` and `Custom`
|
||||
/// remain so older session records still read; neither is cleaned up.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum IdentityProvider {
|
||||
@@ -176,6 +237,10 @@ pub struct TestUserRecord {
|
||||
/// Whether cleanup has been completed
|
||||
#[serde(default)]
|
||||
pub cleaned_up: bool,
|
||||
/// Why the test user was not deleted, when cleanup was asked for: it is
|
||||
/// still in the target's identity provider and has to go by hand.
|
||||
#[serde(default)]
|
||||
pub left_behind: Option<String>,
|
||||
}
|
||||
|
||||
/// A pentest session initiated via the chat interface
|
||||
|
||||
@@ -27,6 +27,11 @@ impl VulnRef {
|
||||
/// in a layer tree, without a build.
|
||||
pub const YOCTO_RECIPE_MANAGER: &str = "yocto-recipe";
|
||||
|
||||
/// The scanner (`Finding::scanner`) of the findings that say why a target's
|
||||
/// SBOM is empty or incomplete: code without a manifest, and manifests whose
|
||||
/// dependencies were not resolved (#979).
|
||||
pub const SBOM_COVERAGE_SCANNER: &str = "sbom-coverage";
|
||||
|
||||
/// Where a [`YOCTO_RECIPE_MANAGER`] component comes from, as the SBOM view,
|
||||
/// the exports and the evidence say it. Layer overrides, PACKAGECONFIG and
|
||||
/// what the image installs are not resolved, so the inventory lists more than
|
||||
|
||||
@@ -206,6 +206,17 @@ impl SecretBox {
|
||||
for slot in record.credentials_mut() {
|
||||
*slot = self.open_opt(slot.as_ref(), "stored record");
|
||||
}
|
||||
for map in record.credential_maps_mut() {
|
||||
map.retain(
|
||||
|_, value| match self.open_opt(Some(value), "stored header") {
|
||||
Some(plaintext) => {
|
||||
*value = plaintext;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Seal every credential of `record` that is not sealed yet.
|
||||
@@ -227,6 +238,16 @@ impl SecretBox {
|
||||
*slot = Some(sealed);
|
||||
changed = true;
|
||||
}
|
||||
for value in record
|
||||
.credential_maps_mut()
|
||||
.into_iter()
|
||||
.flat_map(|map| map.values_mut())
|
||||
{
|
||||
if !Self::is_sealed(value) {
|
||||
*value = self.seal(value)?;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
Ok(changed)
|
||||
}
|
||||
}
|
||||
@@ -349,4 +370,67 @@ mod tests {
|
||||
assert_eq!(secrets.open(&token).unwrap(), "plain-tracker");
|
||||
assert!(!secrets.seal_unsealed(&mut target).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dast_login_headers_are_sealed_and_opened_value_by_value() {
|
||||
use crate::models::dast::{DastAuthConfig, DastTarget, DastTargetType};
|
||||
use std::collections::HashMap;
|
||||
|
||||
let secrets = keyed();
|
||||
let mut target = DastTarget::new(
|
||||
"t".into(),
|
||||
"https://app.example.com".into(),
|
||||
DastTargetType::WebApp,
|
||||
);
|
||||
target.auth_config = Some(DastAuthConfig {
|
||||
method: "bearer".into(),
|
||||
login_url: None,
|
||||
username: None,
|
||||
password: None,
|
||||
token: Some("tok".into()),
|
||||
headers: Some(HashMap::from([("X-Api-Key".into(), "key-1".into())])),
|
||||
});
|
||||
|
||||
assert!(secrets.seal_unsealed(&mut target).unwrap());
|
||||
let auth = target.auth_config.as_ref().unwrap();
|
||||
let stored = &auth.headers.as_ref().unwrap()["X-Api-Key"];
|
||||
assert!(SecretBox::is_sealed(stored), "{stored}");
|
||||
assert!(SecretBox::is_sealed(auth.token.as_deref().unwrap()));
|
||||
assert!(!secrets.seal_unsealed(&mut target).unwrap(), "sealed once");
|
||||
|
||||
secrets.open_in_place(&mut target);
|
||||
let auth = target.auth_config.as_ref().unwrap();
|
||||
assert_eq!(auth.headers.as_ref().unwrap()["X-Api-Key"], "key-1");
|
||||
assert_eq!(auth.token.as_deref(), Some("tok"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_that_does_not_open_is_dropped() {
|
||||
use crate::models::dast::{DastAuthConfig, DastTarget, DastTargetType};
|
||||
use std::collections::HashMap;
|
||||
|
||||
let mut target = DastTarget::new(
|
||||
"t".into(),
|
||||
"https://app.example.com".into(),
|
||||
DastTargetType::WebApp,
|
||||
);
|
||||
target.auth_config = Some(DastAuthConfig {
|
||||
method: "none".into(),
|
||||
login_url: None,
|
||||
username: None,
|
||||
password: None,
|
||||
token: None,
|
||||
headers: Some(HashMap::from([
|
||||
("X-Sealed".into(), keyed().seal("k").unwrap()),
|
||||
("X-Plain".into(), "legacy".into()),
|
||||
])),
|
||||
});
|
||||
// Another key cannot open the sealed value.
|
||||
SecretBox::from_key(&[7u8; 32])
|
||||
.unwrap()
|
||||
.open_in_place(&mut target);
|
||||
let headers = target.auth_config.unwrap().headers.unwrap();
|
||||
assert_eq!(headers.len(), 1);
|
||||
assert_eq!(headers["X-Plain"], "legacy");
|
||||
}
|
||||
}
|
||||
@@ -93,11 +93,28 @@ impl std::fmt::Display for TenantStatus {
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "UPPERCASE")]
|
||||
pub enum OrgRole {
|
||||
/// The organisation's owner: in Prüfwerk the same rights as `IT_ADMIN`,
|
||||
/// as on the rest of the platform.
|
||||
Owner,
|
||||
ItAdmin,
|
||||
Cxo,
|
||||
Finance,
|
||||
Legal,
|
||||
User,
|
||||
/// Product security (RBAC step 4): full access, triages and scans.
|
||||
Psirt,
|
||||
/// Development (RBAC step 4): full access, triages and scans.
|
||||
Development,
|
||||
/// Quality (RBAC step 4): read only.
|
||||
Quality,
|
||||
/// Privacy (RBAC step 4): no access to Prüfwerk.
|
||||
Privacy,
|
||||
/// Purchasing (RBAC step 4): read only.
|
||||
Purchasing,
|
||||
/// Auditor (RBAC step 4): read only.
|
||||
Auditor,
|
||||
/// External (RBAC step 4): no access to Prüfwerk.
|
||||
External,
|
||||
/// Anything we haven't enumerated yet — forwards-compatible.
|
||||
#[serde(other)]
|
||||
Unknown,
|
||||
@@ -108,23 +125,43 @@ impl OrgRole {
|
||||
/// `CXO`, etc.). Round-trips with the JSON layer.
|
||||
pub fn parse(s: &str) -> Self {
|
||||
match s {
|
||||
"OWNER" => OrgRole::Owner,
|
||||
"IT_ADMIN" => OrgRole::ItAdmin,
|
||||
"CXO" => OrgRole::Cxo,
|
||||
"FINANCE" => OrgRole::Finance,
|
||||
"LEGAL" => OrgRole::Legal,
|
||||
"USER" => OrgRole::User,
|
||||
"PSIRT" => OrgRole::Psirt,
|
||||
"DEVELOPMENT" => OrgRole::Development,
|
||||
"QUALITY" => OrgRole::Quality,
|
||||
"PRIVACY" => OrgRole::Privacy,
|
||||
"PURCHASING" => OrgRole::Purchasing,
|
||||
"AUDITOR" => OrgRole::Auditor,
|
||||
"EXTERNAL" => OrgRole::External,
|
||||
_ => OrgRole::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the role administers the organisation: `IT_ADMIN` or `OWNER`.
|
||||
/// What only an administrator may do (manual findings, the git source)
|
||||
/// asks this, not for `IT_ADMIN` alone.
|
||||
pub fn is_admin(&self) -> bool {
|
||||
matches!(self, OrgRole::Owner | OrgRole::ItAdmin)
|
||||
}
|
||||
}
|
||||
|
||||
/// What an organisation member may do in Prüfwerk, by their org roles
|
||||
/// (decided 2026-09-30):
|
||||
///
|
||||
/// * `IT_ADMIN`, `USER` — [`ProductAccess::Full`]: read and write.
|
||||
/// * `CXO`, `LEGAL` — [`ProductAccess::ReadOnly`]: findings, reports, SBOM,
|
||||
/// evidence and exports, but no change of any kind.
|
||||
/// * `FINANCE`, or none of these roles — [`ProductAccess::None`].
|
||||
/// * `OWNER`, `IT_ADMIN`, `USER`, `PSIRT`, `DEVELOPMENT` —
|
||||
/// [`ProductAccess::Full`]: read and write (`OWNER` added 2026-11-12: it has
|
||||
/// `IT_ADMIN`'s rights platform-wide; `PSIRT` and `DEVELOPMENT` from RBAC
|
||||
/// step 4, decided 2026-11-12).
|
||||
/// * `CXO`, `LEGAL`, `QUALITY`, `PURCHASING`, `AUDITOR` —
|
||||
/// [`ProductAccess::ReadOnly`]: findings, reports, SBOM, evidence and
|
||||
/// exports, but no change of any kind.
|
||||
/// * `FINANCE`, `PRIVACY`, `EXTERNAL`, or none of these roles —
|
||||
/// [`ProductAccess::None`].
|
||||
///
|
||||
/// The strongest role a user holds wins. BreakPilot support sessions are not
|
||||
/// judged by org roles (see [`TenantContext::product_access`]).
|
||||
@@ -143,15 +180,20 @@ pub enum ProductAccess {
|
||||
impl ProductAccess {
|
||||
/// The access the org `roles` grant.
|
||||
pub fn for_roles(roles: &[OrgRole]) -> Self {
|
||||
if roles
|
||||
.iter()
|
||||
.any(|r| matches!(r, OrgRole::ItAdmin | OrgRole::User))
|
||||
{
|
||||
if roles.iter().any(|r| {
|
||||
r.is_admin() || matches!(r, OrgRole::User | OrgRole::Psirt | OrgRole::Development)
|
||||
}) {
|
||||
Self::Full
|
||||
} else if roles
|
||||
.iter()
|
||||
.any(|r| matches!(r, OrgRole::Cxo | OrgRole::Legal))
|
||||
{
|
||||
} else if roles.iter().any(|r| {
|
||||
matches!(
|
||||
r,
|
||||
OrgRole::Cxo
|
||||
| OrgRole::Legal
|
||||
| OrgRole::Quality
|
||||
| OrgRole::Purchasing
|
||||
| OrgRole::Auditor
|
||||
)
|
||||
}) {
|
||||
Self::ReadOnly
|
||||
} else {
|
||||
Self::None
|
||||
@@ -293,6 +335,11 @@ impl TenantContext {
|
||||
ProductAccess::for_roles(&self.org_roles)
|
||||
}
|
||||
|
||||
/// True if the caller holds `IT_ADMIN` or `OWNER`.
|
||||
pub fn is_admin(&self) -> bool {
|
||||
self.org_roles.iter().any(OrgRole::is_admin)
|
||||
}
|
||||
|
||||
/// True if the caller holds at least one of the listed roles.
|
||||
pub fn has_any_role(&self, roles: &[OrgRole]) -> bool {
|
||||
self.org_roles.iter().any(|r| roles.contains(r))
|
||||
@@ -306,6 +353,14 @@ mod tests {
|
||||
#[test]
|
||||
fn org_role_parses_known_values() {
|
||||
assert_eq!(OrgRole::parse("IT_ADMIN"), OrgRole::ItAdmin);
|
||||
assert_eq!(OrgRole::parse("OWNER"), OrgRole::Owner);
|
||||
assert_eq!(OrgRole::parse("PSIRT"), OrgRole::Psirt);
|
||||
assert_eq!(OrgRole::parse("DEVELOPMENT"), OrgRole::Development);
|
||||
assert_eq!(OrgRole::parse("QUALITY"), OrgRole::Quality);
|
||||
assert_eq!(OrgRole::parse("PRIVACY"), OrgRole::Privacy);
|
||||
assert_eq!(OrgRole::parse("PURCHASING"), OrgRole::Purchasing);
|
||||
assert_eq!(OrgRole::parse("AUDITOR"), OrgRole::Auditor);
|
||||
assert_eq!(OrgRole::parse("EXTERNAL"), OrgRole::External);
|
||||
assert_eq!(OrgRole::parse("CXO"), OrgRole::Cxo);
|
||||
assert_eq!(OrgRole::parse("USER"), OrgRole::User);
|
||||
}
|
||||
@@ -338,6 +393,15 @@ mod tests {
|
||||
use OrgRole::*;
|
||||
let cases: &[(&[OrgRole], ProductAccess)] = &[
|
||||
(&[ItAdmin], ProductAccess::Full),
|
||||
(&[Owner], ProductAccess::Full),
|
||||
(&[Psirt], ProductAccess::Full),
|
||||
(&[Development], ProductAccess::Full),
|
||||
(&[Quality], ProductAccess::ReadOnly),
|
||||
(&[Purchasing], ProductAccess::ReadOnly),
|
||||
(&[Auditor], ProductAccess::ReadOnly),
|
||||
(&[Privacy], ProductAccess::None),
|
||||
(&[External], ProductAccess::None),
|
||||
(&[External, Auditor], ProductAccess::ReadOnly),
|
||||
(&[User], ProductAccess::Full),
|
||||
(&[Cxo], ProductAccess::ReadOnly),
|
||||
(&[Legal], ProductAccess::ReadOnly),
|
||||
|
||||
@@ -466,6 +466,7 @@ fn pentest_config_serde_roundtrip() {
|
||||
imap_username: None,
|
||||
imap_password: None,
|
||||
cleanup_test_user: true,
|
||||
cleanup: None,
|
||||
},
|
||||
custom_headers: [("X-Token".to_string(), "abc".to_string())]
|
||||
.into_iter()
|
||||
@@ -525,6 +526,7 @@ fn test_user_record_serde_roundtrip() {
|
||||
provider_user_id: Some("kc-uuid-123".into()),
|
||||
provider: Some(pentest::IdentityProvider::Keycloak),
|
||||
cleaned_up: false,
|
||||
left_behind: None,
|
||||
};
|
||||
let json = serde_json::to_string(&r).unwrap();
|
||||
let back: pentest::TestUserRecord = serde_json::from_str(&json).unwrap();
|
||||
@@ -559,6 +561,7 @@ fn pentest_session_with_test_user() {
|
||||
provider_user_id: None,
|
||||
provider: Some(pentest::IdentityProvider::Auth0),
|
||||
cleaned_up: false,
|
||||
left_behind: None,
|
||||
});
|
||||
let bson_doc = bson::to_document(&s).unwrap();
|
||||
let back: pentest::PentestSession = bson::from_document(bson_doc).unwrap();
|
||||
@@ -605,3 +608,34 @@ fn opt_bson_datetime_roundtrip_with_some() {
|
||||
let back: pentest::PentestSession = bson::from_document(bson_doc).unwrap();
|
||||
assert!(back.completed_at.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_user_cleanup_is_tagged_by_provider() {
|
||||
let access: pentest::TestUserCleanup = serde_json::from_value(serde_json::json!({
|
||||
"provider": "keycloak",
|
||||
"base_url": "https://login.example.com/",
|
||||
"realm": "app",
|
||||
"client_id": "cleanup",
|
||||
"client_secret": "s"
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(access.provider(), pentest::IdentityProvider::Keycloak);
|
||||
assert_eq!(access.base_url(), "https://login.example.com");
|
||||
|
||||
let okta: pentest::TestUserCleanup = serde_json::from_value(serde_json::json!({
|
||||
"provider": "okta", "domain": "example.okta.com", "api_token": "t"
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(okta.base_url(), "https://example.okta.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_older_test_user_record_still_reads() {
|
||||
let back: pentest::TestUserRecord = serde_json::from_value(serde_json::json!({
|
||||
"username": null, "email": "a+1@b.c", "provider_user_id": null,
|
||||
"provider": "firebase", "cleaned_up": false
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(back.left_behind, None);
|
||||
assert_eq!(back.provider, Some(pentest::IdentityProvider::Firebase));
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "compliance-dashboard"
|
||||
version = "0.4.6"
|
||||
version = "0.4.16"
|
||||
edition = "2021"
|
||||
default-run = "compliance-dashboard"
|
||||
|
||||
|
||||
@@ -638,6 +638,56 @@ code {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
/* ── A finding as ticket text, and the Breakpilot Git hint ── */
|
||||
|
||||
.ticket-bar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px 12px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.ticket-bar .btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12.5px;
|
||||
padding: 5px 10px;
|
||||
}
|
||||
|
||||
.ticket-copied {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
font-size: 12.5px;
|
||||
color: var(--success);
|
||||
}
|
||||
|
||||
.ticket-copy-failed {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.ticket-hint {
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 4px 6px;
|
||||
margin: 0;
|
||||
font-size: 12.5px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.ticket-hint svg {
|
||||
color: var(--accent);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.ticket-hint a {
|
||||
color: var(--accent);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
|
||||
/* ── Page Header ── */
|
||||
|
||||
@@ -1275,6 +1325,108 @@ tbody tr:last-child td {
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
/* A dialog never grows past the window: its content scrolls, and the actions
|
||||
stay pinned at the bottom so Save is always reachable. */
|
||||
.modal-dialog {
|
||||
max-height: calc(100vh - 32px);
|
||||
max-height: calc(100dvh - 32px);
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
|
||||
.modal-dialog .modal-actions {
|
||||
position: sticky;
|
||||
bottom: -18px;
|
||||
margin: 20px -18px -18px;
|
||||
padding: 12px 18px;
|
||||
background: var(--bg-card-solid);
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
/* Forms with sections (the target editor). */
|
||||
.modal-dialog.modal-wide {
|
||||
max-width: 680px;
|
||||
}
|
||||
|
||||
.modal-section {
|
||||
border-top: 1px solid var(--border);
|
||||
margin-top: 16px;
|
||||
padding-top: 14px;
|
||||
}
|
||||
|
||||
.modal-section > .target-subhead {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
/* A stored artifact: its reference, token state and actions on one line. */
|
||||
.artifact-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 6px 0;
|
||||
}
|
||||
|
||||
.artifact-row-ref {
|
||||
flex: 1 1 100%;
|
||||
font-size: 13px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.form-fields .artifact-row input {
|
||||
flex: 1 1 200px;
|
||||
width: auto;
|
||||
}
|
||||
|
||||
/* Adding a reference: kind and reference on one line, branch, token and the
|
||||
button on the next, all filling the width. */
|
||||
.artifact-add {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-end;
|
||||
gap: 10px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.artifact-add .form-group {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.artifact-add-kind {
|
||||
flex: 1 1 200px;
|
||||
}
|
||||
|
||||
.artifact-add-ref {
|
||||
flex: 1 1 280px;
|
||||
}
|
||||
|
||||
.artifact-add-branch {
|
||||
flex: 1 1 160px;
|
||||
}
|
||||
|
||||
.artifact-add-token {
|
||||
flex: 1 1 200px;
|
||||
}
|
||||
|
||||
/* Inside a dialog the project picker is a section like the others, not a
|
||||
framed box. */
|
||||
.modal-dialog .project-picker {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.modal-dialog .project-picker legend {
|
||||
padding: 0;
|
||||
margin-bottom: 6px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
/* The portal's default button: surface, hairline border. */
|
||||
.btn-secondary {
|
||||
background: var(--bg-card);
|
||||
@@ -2725,6 +2877,33 @@ tbody tr:last-child td {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
/* The empty component table (#979): why, and what to add. */
|
||||
.sbom-empty p {
|
||||
margin: 0 0 10px;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.sbom-empty-findings {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.sbom-empty-findings li {
|
||||
padding: 10px 12px;
|
||||
border-left: 3px solid var(--accent);
|
||||
background: var(--accent-muted);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.sbom-empty-findings li p {
|
||||
margin: 4px 0 6px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.sbom-quality-head {
|
||||
margin: 0 0 4px;
|
||||
font-size: 15px;
|
||||
@@ -5726,13 +5905,19 @@ tbody tr:last-child td {
|
||||
.artifact-upload-row .form-group {
|
||||
margin: 0;
|
||||
min-width: 160px;
|
||||
flex: 1 1 200px;
|
||||
}
|
||||
|
||||
.artifact-upload-file {
|
||||
flex: 1;
|
||||
flex: 2 1 260px;
|
||||
min-width: 220px;
|
||||
}
|
||||
|
||||
/* The archive password gets its own line: its label is long. */
|
||||
.artifact-upload-row .artifact-upload-password {
|
||||
flex: 1 1 100%;
|
||||
}
|
||||
|
||||
.artifact-upload-note {
|
||||
font-size: 12.5px;
|
||||
color: var(--success);
|
||||
|
||||
@@ -66,7 +66,7 @@ pub fn ArtifactUpload(target_id: String, on_uploaded: EventHandler<()>) -> Eleme
|
||||
}
|
||||
// Firmware images and build outputs are never unpacked.
|
||||
if kind() != "firmware_image" && kind() != "build_output" {
|
||||
div { class: "form-group",
|
||||
div { class: "form-group artifact-upload-password",
|
||||
label { {common::ARCHIVE_PASSWORD.get(lang)} }
|
||||
input {
|
||||
r#type: "password",
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
use dioxus::prelude::*;
|
||||
|
||||
use crate::app::Route;
|
||||
use crate::i18n::texts::{common, cra_tiles as tx};
|
||||
use crate::i18n::texts::{common, compliance, cra_tiles as tx};
|
||||
use crate::i18n::use_lang;
|
||||
use crate::infrastructure::evidence::fetch_compliance;
|
||||
use crate::pages::compliance::{ControlRow, STATES};
|
||||
@@ -157,7 +157,7 @@ pub fn CraTiles(target_id: String, control: Option<String>) -> Element {
|
||||
}
|
||||
}
|
||||
}
|
||||
p { class: "ct-hint", {tx::HINT.get(lang)} }
|
||||
p { class: "ct-hint", {tx::HINT.get(lang)} " " {compliance::NOT_LEGAL_ADVICE.get(lang)} }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -514,7 +514,10 @@ pub fn phase(phase: &ScanPhase) -> Text {
|
||||
ScanPhase::MobileStatic => ("Mobile-App-Analyse", "Mobile app analysis"),
|
||||
ScanPhase::ContainerScan => ("Container-Analyse", "Container analysis"),
|
||||
ScanPhase::LlmTriage => ("Befunde bewerten", "Triaging findings"),
|
||||
ScanPhase::ControlTriage => ("CRA-Anforderungen zuordnen", "Mapping CRA requirements"),
|
||||
ScanPhase::ControlTriage => (
|
||||
"Bezug zu CRA-Themen ermitteln (technischer Hinweis)",
|
||||
"Finding links to CRA topics (technical hint)",
|
||||
),
|
||||
ScanPhase::SemanticControlMapping => ("Controls zuordnen", "Mapping controls"),
|
||||
ScanPhase::GroundedControlChecks => {
|
||||
("Controls im Code prüfen", "Checking controls in code")
|
||||
|
||||
@@ -2131,8 +2131,8 @@ pub mod findings {
|
||||
en: "CRA",
|
||||
};
|
||||
pub const CONTROLS_HINT: Text = Text {
|
||||
de: "CRA-Anforderungen, für die dieser Befund relevant ist",
|
||||
en: "CRA requirements this finding is evidence for",
|
||||
de: "CRA-Themen, auf die dieser Befund hinweist",
|
||||
en: "CRA topics this finding points to",
|
||||
};
|
||||
pub const COL_STATUS: Text = Text {
|
||||
de: "Status",
|
||||
@@ -2183,8 +2183,8 @@ pub mod findings {
|
||||
en: "The target's CRA status",
|
||||
};
|
||||
pub const CRA_REFS: Text = Text {
|
||||
de: "CRA-Anforderungen (Anhang I)",
|
||||
en: "CRA requirements (Annex I)",
|
||||
de: "CRA-Themen (Anhang I)",
|
||||
en: "CRA topics (Annex I)",
|
||||
};
|
||||
pub const CONFIDENCE: Text = Text {
|
||||
de: "Konfidenz",
|
||||
@@ -2240,6 +2240,42 @@ pub mod findings {
|
||||
de: "Erfasst von",
|
||||
en: "Reported by",
|
||||
};
|
||||
/// The button that copies one finding as Markdown for a ticket.
|
||||
pub const COPY_TICKET: Text = Text {
|
||||
de: "Als Ticket-Text kopieren",
|
||||
en: "Copy as ticket text",
|
||||
};
|
||||
pub const COPIED: Text = Text {
|
||||
de: "Kopiert",
|
||||
en: "Copied",
|
||||
};
|
||||
pub const COPY_FAILED: Text = Text {
|
||||
de: "Kopieren fehlgeschlagen",
|
||||
en: "Copy failed",
|
||||
};
|
||||
/// Shown on a finding whose target opens no tickets on its own.
|
||||
pub const TICKET_HINT: Text = Text {
|
||||
de: "Mit Breakpilot Git werden Tickets automatisch angelegt.",
|
||||
en: "With Breakpilot Git, tickets are created automatically.",
|
||||
};
|
||||
pub const CONNECT_TRACKER: Text = Text {
|
||||
de: "Tracker für dieses Prüfobjekt anbinden",
|
||||
en: "Connect a tracker to this target",
|
||||
};
|
||||
pub const MANAGED_GIT_GUIDE: Text = Text {
|
||||
de: "Anleitung Managed Git",
|
||||
en: "Managed Git guide",
|
||||
};
|
||||
/// The copied ticket text's section on the CRA topics.
|
||||
pub const CRA_TOPICS: Text = Text {
|
||||
de: "CRA-Themen",
|
||||
en: "CRA topics",
|
||||
};
|
||||
/// The copied ticket text's link back to the finding.
|
||||
pub const OPEN_IN_PRUEFWERK: Text = Text {
|
||||
de: "Im Prüfwerk öffnen",
|
||||
en: "Open in Prüfwerk",
|
||||
};
|
||||
|
||||
/// A finding status in words. Exhaustive: a new status needs both.
|
||||
pub fn status(status: &FindingStatus) -> Text {
|
||||
@@ -2481,6 +2517,10 @@ pub mod findings {
|
||||
de: "Build-System und Plattform",
|
||||
en: "Build system and platform",
|
||||
},
|
||||
compliance_core::models::SBOM_COVERAGE_SCANNER => Text {
|
||||
de: "Vollständigkeit der Stückliste",
|
||||
en: "SBOM completeness",
|
||||
},
|
||||
"clamav" => Text {
|
||||
de: "Schadsoftware (ClamAV)",
|
||||
en: "Malware (ClamAV)",
|
||||
@@ -2858,6 +2898,41 @@ pub mod sbom {
|
||||
de: "Die Komponenten Ihrer Software, ihre Lizenzen und bekannte Schwachstellen (CVE)",
|
||||
en: "Software bill of materials: dependencies, licenses and known vulnerabilities",
|
||||
};
|
||||
/// The empty state of the component table (#979).
|
||||
pub const EMPTY_TITLE: Text = Text {
|
||||
de: "Keine Komponenten gefunden",
|
||||
en: "No components found",
|
||||
};
|
||||
/// Why the component table is empty.
|
||||
pub const EMPTY_WHY: Text = Text {
|
||||
de: "Die Stückliste entsteht aus den Paketmanifesten und Lockfiles im Code (etwa \
|
||||
requirements.txt, package-lock.json oder Cargo.lock), aus den Firmware-Quellen \
|
||||
oder aus einem SPS-Projektarchiv. Die letzte Prüfung hat dort keine Komponenten \
|
||||
gefunden. Das heißt nicht, dass die Software keine Bibliotheken verwendet.",
|
||||
en: "The SBOM is built from the package manifests and lockfiles in the code (such as \
|
||||
requirements.txt, package-lock.json or Cargo.lock), from the firmware sources or \
|
||||
from a PLC project archive. The last scan found no components there. That does \
|
||||
not mean the software uses no libraries.",
|
||||
};
|
||||
/// How to fill the component table, by example.
|
||||
pub const EMPTY_EXAMPLE: Text = Text {
|
||||
de: "Zum Beispiel: Für Python schreibt pip freeze > requirements.txt die Bibliotheken \
|
||||
in eine requirements.txt, für JavaScript schreibt npm install die \
|
||||
package-lock.json, für Rust gehört die Cargo.lock ins Repository. Nach der \
|
||||
nächsten Prüfung stehen die Komponenten hier.",
|
||||
en: "For example: for Python, pip freeze > requirements.txt writes the libraries to a \
|
||||
requirements.txt; for JavaScript, npm install writes package-lock.json; for Rust, \
|
||||
commit Cargo.lock. After the next scan the components are listed here.",
|
||||
};
|
||||
/// Above the open findings that say what is missing.
|
||||
pub const EMPTY_FINDINGS: Text = Text {
|
||||
de: "Was in diesem Prüfobjekt fehlt und wie Sie es ergänzen:",
|
||||
en: "What this target is missing, and how to add it:",
|
||||
};
|
||||
pub const OPEN_FINDING: Text = Text {
|
||||
de: "Zum Befund",
|
||||
en: "Open the finding",
|
||||
};
|
||||
pub const PACKAGES_TAB: Text = Text {
|
||||
de: "Pakete",
|
||||
en: "Packages",
|
||||
@@ -3681,8 +3756,13 @@ pub mod compliance {
|
||||
en: "CRA status",
|
||||
};
|
||||
pub const SUBTITLE: Text = Text {
|
||||
de: "Befunde aus der Prüfung, zugeordnet zu den grundlegenden Anforderungen des Cyber Resilience Act (Anhang I)",
|
||||
en: "Scan findings mapped to the Cyber Resilience Act's essential requirements (Annex I)",
|
||||
de: "Befunde aus der Prüfung mit Bezug zu den Themen der grundlegenden Anforderungen des Cyber Resilience Act (Anhang I)",
|
||||
en: "Scan findings linked to the topics of the Cyber Resilience Act's essential requirements (Annex I)",
|
||||
};
|
||||
/// Shown with every CRA status view: the mapping is a technical hint (#978).
|
||||
pub const NOT_LEGAL_ADVICE: Text = Text {
|
||||
de: "Technische Hinweise, keine rechtliche Bewertung.",
|
||||
en: "Technical hints, not a legal assessment.",
|
||||
};
|
||||
pub const OPEN: Text = Text {
|
||||
de: "CRA-Status anzeigen",
|
||||
@@ -3856,6 +3936,7 @@ pub mod compliance {
|
||||
"csharp" => "C#",
|
||||
"vb" => "Visual Basic",
|
||||
"swift" => "Swift",
|
||||
"dart" => "Dart",
|
||||
"structured_text" => "Structured Text",
|
||||
"plcopen" => "PLCopen XML",
|
||||
other => other,
|
||||
@@ -4651,8 +4732,9 @@ mod run_error_tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a user's org role allows (`IT_ADMIN` / `USER` everything, `CXO` /
|
||||
/// `LEGAL` reading, `FINANCE` and no role nothing).
|
||||
/// What a user's org role allows (`OWNER` / `IT_ADMIN` / `USER` / `PSIRT` /
|
||||
/// `DEVELOPMENT` everything; `CXO` / `LEGAL` / `QUALITY` / `PURCHASING` /
|
||||
/// `AUDITOR` reading; `FINANCE`, `PRIVACY`, `EXTERNAL` and no role nothing).
|
||||
pub mod access {
|
||||
use super::Text;
|
||||
|
||||
@@ -5043,8 +5125,8 @@ pub mod license_review {
|
||||
en: "No licence is known for this component. Confirm its licence first; then it can be approved or rejected.",
|
||||
};
|
||||
pub const CONFIRM_FIRST_OTHERS: Text = Text {
|
||||
de: "Lizenz zuerst bestätigen (IT_ADMIN oder USER)",
|
||||
en: "Licence to be confirmed first (IT_ADMIN or USER)",
|
||||
de: "Lizenz zuerst bestätigen (eine Rolle mit Schreibzugriff)",
|
||||
en: "Licence to be confirmed first (a role that may change data)",
|
||||
};
|
||||
pub const IN_TARGETS: Text = Text {
|
||||
de: "in {n} Prüfobjekten",
|
||||
@@ -5143,12 +5225,12 @@ pub mod license_review {
|
||||
en: "Licence policy",
|
||||
};
|
||||
pub const POLICY_HINT: Text = Text {
|
||||
de: "Was eine Lizenz braucht, bevor die Komponente verwendet wird. Ändern dürfen LEGAL und IT_ADMIN.",
|
||||
en: "What a licence needs before the component is used. LEGAL and IT_ADMIN may change it.",
|
||||
de: "Was eine Lizenz braucht, bevor die Komponente verwendet wird. Ändern dürfen LEGAL, IT_ADMIN und OWNER.",
|
||||
en: "What a licence needs before the component is used. LEGAL, IT_ADMIN and OWNER may change it.",
|
||||
};
|
||||
pub const POLICY_READ_ONLY: Text = Text {
|
||||
de: "Nur LEGAL und IT_ADMIN können die Richtlinie ändern.",
|
||||
en: "Only LEGAL and IT_ADMIN can change the policy.",
|
||||
de: "Nur LEGAL, IT_ADMIN und OWNER können die Richtlinie ändern.",
|
||||
en: "Only LEGAL, IT_ADMIN and OWNER can change the policy.",
|
||||
};
|
||||
pub const POLICY_CATEGORY: Text = Text {
|
||||
de: "Art der Lizenz",
|
||||
|
||||
@@ -18,6 +18,8 @@ pub struct FindingsQuery {
|
||||
pub status: String,
|
||||
pub repo_id: String,
|
||||
pub q: String,
|
||||
/// One scanner (`Finding::scanner`), or empty for all.
|
||||
pub scanner: String,
|
||||
/// One app variant (`Tablet App`), or empty for all.
|
||||
pub variant: String,
|
||||
/// One folder of the folder chart (`src/`, `src/*`, `/`), or empty.
|
||||
@@ -104,6 +106,9 @@ pub async fn fetch_findings(query: FindingsQuery) -> Result<FindingsListResponse
|
||||
if !query.status.is_empty() {
|
||||
path.push_str(&format!("&status={}", query.status));
|
||||
}
|
||||
if !query.scanner.is_empty() {
|
||||
path.push_str(&format!("&scanner={}", query.scanner));
|
||||
}
|
||||
if !query.repo_id.is_empty() {
|
||||
path.push_str(&format!("&repo_id={}", query.repo_id));
|
||||
}
|
||||
|
||||
@@ -193,7 +193,7 @@ pub struct LicenseCheckData {
|
||||
/// Whether the requester may decide reviews and change the policy.
|
||||
#[serde(default)]
|
||||
pub may_decide: bool,
|
||||
/// Whether the requester may confirm licences (IT_ADMIN, USER).
|
||||
/// Whether the requester may confirm licences (any role with full access).
|
||||
#[serde(default)]
|
||||
pub may_confirm: bool,
|
||||
}
|
||||
|
||||
@@ -79,6 +79,7 @@ pub fn CompliancePage(id: String) -> Element {
|
||||
div { class: "target-head-text",
|
||||
h2 { {tx::TITLE.get(lang)} }
|
||||
p { class: "target-head-meta", {tx::SUBTITLE.get(lang)} }
|
||||
p { class: "target-head-meta", {tx::NOT_LEGAL_ADVICE.get(lang)} }
|
||||
}
|
||||
div { class: "target-head-actions",
|
||||
EvidencePackButton { target_id: id.clone() }
|
||||
|
||||
@@ -7,14 +7,14 @@ use crate::components::code_snippet::CodeSnippet;
|
||||
use crate::components::markdown::render_markdown;
|
||||
use crate::components::page_header::PageHeader;
|
||||
use crate::components::severity_badge::SeverityBadge;
|
||||
use crate::i18n::texts::{common, findings as tx, graph as graph_tx};
|
||||
use crate::i18n::{format_count, format_time, use_lang};
|
||||
use crate::i18n::texts::{common, finding_breakdown, findings as tx, graph as graph_tx};
|
||||
use crate::i18n::{format_count, format_time, use_lang, Lang};
|
||||
use crate::infrastructure::evidence::{fetch_catalog_controls, CatalogControl};
|
||||
use crate::infrastructure::findings::{location, mask_secrets, wire_name};
|
||||
use crate::infrastructure::graph::fetch_impact;
|
||||
use crate::pages::findings::status_icon;
|
||||
use crate::pages::graph_view::impact_has_content;
|
||||
use compliance_core::models::{FindingStatus, ReviewReason, ScanType};
|
||||
use compliance_core::models::{Finding, FindingStatus, ReviewReason, ScanType};
|
||||
|
||||
/// What happened to the last save on this page, shown next to what was saved.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
@@ -38,6 +38,9 @@ pub fn FindingDetailPage(id: String) -> Element {
|
||||
// before it is saved.
|
||||
let mut reasoning_for = use_signal(|| Option::<FindingStatus>::None);
|
||||
let mut risk_reason = use_signal(String::new);
|
||||
// The last copy as ticket text: `Some(true)` copied, `Some(false)` the
|
||||
// browser refused; cleared after a moment.
|
||||
let mut ticket_copied = use_signal(|| Option::<bool>::None);
|
||||
|
||||
let mut finding = use_resource(move || {
|
||||
let fid = finding_id.clone();
|
||||
@@ -137,6 +140,58 @@ pub fn FindingDetailPage(id: String) -> Element {
|
||||
.iter()
|
||||
.cloned()
|
||||
.partition(|c| c.starts_with("cra-"));
|
||||
let cra_topics: Vec<(String, Option<String>)> = cra_refs
|
||||
.into_iter()
|
||||
.map(|c| {
|
||||
let title = control_title(&c);
|
||||
(c, title)
|
||||
})
|
||||
.collect();
|
||||
// Offer Breakpilot Git only once the agent said the target opens
|
||||
// no tickets (not while loading), and not on a finding with one.
|
||||
let show_ticket_hint = f.tracker_issue_url.is_none()
|
||||
&& status_data
|
||||
.as_ref()
|
||||
.and_then(|d| d["issue_tracker_connected"].as_bool())
|
||||
== Some(false);
|
||||
let tracker_guide = docs_page(
|
||||
&me.docs_url,
|
||||
"guide/repositories#connecting-an-issue-tracker",
|
||||
);
|
||||
// The same path in both languages: the customer docs site
|
||||
// (prod's `DOCS_URL`) keeps each page at one path per language
|
||||
// root and has no `-en` pages.
|
||||
let managed_git_guide = docs_page(&me.docs_url, "guide/managed-git");
|
||||
// `move` closures take ownership (like a Python closure capturing
|
||||
// by value), so the copy handler gets its own clones.
|
||||
let finding_for_copy = f.clone();
|
||||
let topics_for_copy = cra_topics.clone();
|
||||
let finding_id_for_copy = id.clone();
|
||||
let copy_ticket = move |_: MouseEvent| {
|
||||
let link = format!(
|
||||
"{}{}",
|
||||
page_origin(),
|
||||
Route::FindingDetailPage {
|
||||
id: finding_id_for_copy.clone()
|
||||
}
|
||||
);
|
||||
let text = ticket_markdown(&finding_for_copy, &topics_for_copy, &link, lang);
|
||||
spawn(async move {
|
||||
// A JSON string is a valid JavaScript string literal.
|
||||
let copied = match serde_json::to_string(&text) {
|
||||
Ok(literal) => document::eval(&format!(
|
||||
"await navigator.clipboard.writeText({literal}); return true;"
|
||||
))
|
||||
.await
|
||||
.is_ok(),
|
||||
Err(_) => false,
|
||||
};
|
||||
ticket_copied.set(Some(copied));
|
||||
#[cfg(feature = "web")]
|
||||
gloo_timers::future::TimeoutFuture::new(2_000).await;
|
||||
ticket_copied.set(None);
|
||||
});
|
||||
};
|
||||
rsx! {
|
||||
div { class: "back-nav",
|
||||
button {
|
||||
@@ -176,6 +231,40 @@ pub fn FindingDetailPage(id: String) -> Element {
|
||||
}
|
||||
}
|
||||
|
||||
div { class: "ticket-bar",
|
||||
button {
|
||||
class: "btn btn-ghost",
|
||||
onclick: copy_ticket,
|
||||
Icon { icon: BsClipboard, width: 14, height: 14 }
|
||||
" {tx::COPY_TICKET.get(lang)}"
|
||||
}
|
||||
span { class: "ticket-copied", role: "status",
|
||||
match ticket_copied() {
|
||||
Some(true) => rsx! {
|
||||
Icon { icon: BsCheckLg, width: 14, height: 14 }
|
||||
" {tx::COPIED.get(lang)}"
|
||||
},
|
||||
Some(false) => rsx! {
|
||||
span { class: "ticket-copy-failed", {tx::COPY_FAILED.get(lang)} }
|
||||
},
|
||||
None => rsx! {},
|
||||
}
|
||||
}
|
||||
if show_ticket_hint {
|
||||
p { class: "ticket-hint",
|
||||
Icon { icon: BsInfoCircle, width: 14, height: 14 }
|
||||
span { {tx::TICKET_HINT.get(lang)} }
|
||||
a { href: "{tracker_guide}", target: "_blank", rel: "noopener",
|
||||
{tx::CONNECT_TRACKER.get(lang)}
|
||||
}
|
||||
span { "·" }
|
||||
a { href: "{managed_git_guide}", target: "_blank", rel: "noopener",
|
||||
{tx::MANAGED_GIT_GUIDE.get(lang)}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
div { class: "card",
|
||||
div { class: "card-header", {tx::DESCRIPTION.get(lang)} }
|
||||
// A semgrep rule's message is Markdown (paragraphs, code
|
||||
@@ -220,10 +309,10 @@ pub fn FindingDetailPage(id: String) -> Element {
|
||||
if !f.control_refs.is_empty() {
|
||||
span { style: "opacity: 0.7;", {tx::CRA_REFS.get(lang)} }
|
||||
ul { class: "finding-refs",
|
||||
for c in cra_refs {
|
||||
for (c, title) in cra_topics {
|
||||
li {
|
||||
span { class: "badge badge-info", "{c}" }
|
||||
if let Some(title) = control_title(&c) {
|
||||
if let Some(title) = title {
|
||||
span { " {title}" }
|
||||
}
|
||||
}
|
||||
@@ -579,10 +668,92 @@ fn tracker_note(
|
||||
Some(format!("{} {login}", tx::tracker_change(kind).get(lang)))
|
||||
}
|
||||
|
||||
/// One finding as Markdown for a ticket the user opens by hand: title,
|
||||
/// severity, status, location, description, the AI's assessment, the CRA
|
||||
/// topics and a link back. A committed secret is shortened as on screen.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `finding` - the finding shown on the page
|
||||
/// * `cra_topics` - its CRA control ids, each with its title when known
|
||||
/// * `link` - the finding's page in Prüfwerk
|
||||
/// * `lang` - the UI language, for the labels
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The Markdown text, ending in a newline.
|
||||
fn ticket_markdown(
|
||||
finding: &Finding,
|
||||
cra_topics: &[(String, Option<String>)],
|
||||
link: &str,
|
||||
lang: Lang,
|
||||
) -> String {
|
||||
let shown = |text: &str| {
|
||||
if finding.scan_type == ScanType::SecretDetection {
|
||||
mask_secrets(text.trim())
|
||||
} else {
|
||||
text.trim().to_string()
|
||||
}
|
||||
};
|
||||
let mut md = format!(
|
||||
"## {}\n\n- **{}:** {}\n- **{}:** {}\n",
|
||||
finding.title,
|
||||
tx::COL_SEVERITY.get(lang),
|
||||
finding_breakdown::severity(&finding.severity).get(lang),
|
||||
tx::COL_STATUS.get(lang),
|
||||
tx::finding_status(finding).get(lang),
|
||||
);
|
||||
if let Some(place) = location(finding.file_path.as_deref(), finding.line_number) {
|
||||
md.push_str(&format!("- **{}:** `{place}`\n", tx::WHERE.get(lang)));
|
||||
}
|
||||
md.push_str(&format!(
|
||||
"\n### {}\n\n{}\n",
|
||||
tx::DESCRIPTION.get(lang),
|
||||
shown(&finding.description)
|
||||
));
|
||||
if let Some(rationale) = &finding.triage_rationale {
|
||||
md.push_str(&format!(
|
||||
"\n### {}\n\n{}\n",
|
||||
tx::TRIAGE.get(lang),
|
||||
shown(rationale)
|
||||
));
|
||||
}
|
||||
if !cra_topics.is_empty() {
|
||||
md.push_str(&format!("\n### {}\n\n", tx::CRA_TOPICS.get(lang)));
|
||||
for (id, title) in cra_topics {
|
||||
match title {
|
||||
Some(title) => md.push_str(&format!("- `{id}` {title}\n")),
|
||||
None => md.push_str(&format!("- `{id}`\n")),
|
||||
}
|
||||
}
|
||||
}
|
||||
md.push_str(&format!(
|
||||
"\n[{}]({link})\n",
|
||||
tx::OPEN_IN_PRUEFWERK.get(lang)
|
||||
));
|
||||
md
|
||||
}
|
||||
|
||||
/// A page of the docs site: `docs_url` is the site's root as configured
|
||||
/// (`/docs/` or a full URL, with or without the trailing slash), `page` the
|
||||
/// path below it (`guide/managed-git`).
|
||||
fn docs_page(docs_url: &str, page: &str) -> String {
|
||||
format!("{}/{page}", docs_url.trim_end_matches('/'))
|
||||
}
|
||||
|
||||
/// The dashboard's origin (`https://pruefwerk.example`) in the browser; empty
|
||||
/// elsewhere, which leaves a link relative.
|
||||
fn page_origin() -> String {
|
||||
#[cfg(feature = "web")]
|
||||
if let Some(origin) = web_sys::window().and_then(|w| w.location().origin().ok()) {
|
||||
return origin;
|
||||
}
|
||||
String::new()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::i18n::Lang;
|
||||
use compliance_core::models::{AuthInfo, StatusChange};
|
||||
|
||||
fn change(by: &str, by_name: Option<&str>) -> StatusChange {
|
||||
@@ -664,4 +835,85 @@ mod tests {
|
||||
assert_eq!(changed_by(&c, &me(), Lang::De), "Benutzer 0b7d51aa");
|
||||
assert_eq!(changed_by(&c, &me(), Lang::En), "User 0b7d51aa");
|
||||
}
|
||||
|
||||
fn sql_injection() -> Finding {
|
||||
let mut f = Finding::new(
|
||||
"repo".to_string(),
|
||||
"fp".to_string(),
|
||||
"semgrep".to_string(),
|
||||
ScanType::Sast,
|
||||
"SQL-Injection im Login".to_string(),
|
||||
"Die Abfrage setzt Benutzereingaben direkt ein.\n".to_string(),
|
||||
compliance_core::models::Severity::High,
|
||||
);
|
||||
f.file_path = Some("src/login.rs".to_string());
|
||||
f.line_number = Some(42);
|
||||
f.triage_rationale = Some("Erreichbar über das Login-Formular.".to_string());
|
||||
f
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ticket_text_holds_the_finding_and_a_link_back() {
|
||||
let topics = vec![
|
||||
(
|
||||
"cra-ai-2c".to_string(),
|
||||
Some("Schutz vor unbefugtem Zugriff".to_string()),
|
||||
),
|
||||
("cra-ai-2f".to_string(), None),
|
||||
];
|
||||
let md = ticket_markdown(
|
||||
&sql_injection(),
|
||||
&topics,
|
||||
"https://pruefwerk.example/findings/abc",
|
||||
Lang::De,
|
||||
);
|
||||
assert_eq!(
|
||||
md,
|
||||
"## SQL-Injection im Login\n\n\
|
||||
- **Schweregrad:** Hoch\n\
|
||||
- **Status:** Offen\n\
|
||||
- **Fundstelle:** `src/login.rs:42`\n\
|
||||
\n### Beschreibung\n\nDie Abfrage setzt Benutzereingaben direkt ein.\n\
|
||||
\n### Einschätzung\n\nErreichbar über das Login-Formular.\n\
|
||||
\n### CRA-Themen\n\n\
|
||||
- `cra-ai-2c` Schutz vor unbefugtem Zugriff\n\
|
||||
- `cra-ai-2f`\n\
|
||||
\n[Im Prüfwerk öffnen](https://pruefwerk.example/findings/abc)\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ticket_text_leaves_out_what_the_finding_lacks() {
|
||||
let mut f = sql_injection();
|
||||
f.file_path = None;
|
||||
f.triage_rationale = None;
|
||||
let md = ticket_markdown(&f, &[], "/findings/abc", Lang::En);
|
||||
assert!(md.contains("- **Severity:** High\n"));
|
||||
assert!(!md.contains("Location"));
|
||||
assert!(!md.contains("Triage"));
|
||||
assert!(!md.contains("CRA topics"));
|
||||
assert!(md.ends_with("\n[Open in Prüfwerk](/findings/abc)\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ticket_text_shortens_a_committed_secret() {
|
||||
let mut f = sql_injection();
|
||||
f.scan_type = ScanType::SecretDetection;
|
||||
f.description = "Token ghp_a1B2c3D4e5F6g7H8i9J0 im Code".to_string();
|
||||
let md = ticket_markdown(&f, &[], "/findings/abc", Lang::De);
|
||||
assert!(!md.contains("ghp_a1B2c3D4e5F6g7H8i9J0"));
|
||||
assert!(md.contains("ghp_••••••••"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_docs_page_joins_the_configured_root() {
|
||||
assert_eq!(
|
||||
docs_page("/docs/", "guide/managed-git"),
|
||||
"/docs/guide/managed-git"
|
||||
);
|
||||
assert_eq!(
|
||||
docs_page("https://docs.example/pruefwerk/", "guide/managed-git"),
|
||||
"https://docs.example/pruefwerk/guide/managed-git"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -99,6 +99,7 @@ pub fn FindingsPage(
|
||||
path: path_filter(),
|
||||
sort_by: sort_by(),
|
||||
sort_order: sort_order(),
|
||||
..Default::default()
|
||||
};
|
||||
async move {
|
||||
if grouped_view {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use compliance_core::models::{LicenseConclusion, YOCTO_RECIPE_MANAGER};
|
||||
use compliance_core::finding_breakdown::OPEN_STATUS_FILTER;
|
||||
use compliance_core::models::{LicenseConclusion, SBOM_COVERAGE_SCANNER, YOCTO_RECIPE_MANAGER};
|
||||
use dioxus::prelude::*;
|
||||
|
||||
use crate::app::Route;
|
||||
@@ -13,6 +14,7 @@ use crate::components::pagination::Pagination;
|
||||
use crate::components::toast::{ToastType, Toasts};
|
||||
use crate::i18n::texts::{common, license_edit as lx, license_review as rx, sbom as tx};
|
||||
use crate::i18n::{use_lang, Lang};
|
||||
use crate::infrastructure::findings::{fetch_findings, FindingsQuery};
|
||||
use crate::infrastructure::sbom::*;
|
||||
use compliance_core::models::ReviewDecision;
|
||||
|
||||
@@ -109,6 +111,16 @@ pub fn SbomPage(target: String, #[props(default)] ecosystem: String) -> Element
|
||||
}
|
||||
});
|
||||
|
||||
// Only the target narrows the table: an empty one then means the SBOM
|
||||
// is empty, not that nothing matched a filter.
|
||||
let unfiltered = move || {
|
||||
pm_filter().is_empty()
|
||||
&& search_q().is_empty()
|
||||
&& vuln_toggle().is_none()
|
||||
&& license_filter().is_empty()
|
||||
&& in_image_filter().is_none()
|
||||
};
|
||||
|
||||
// ── SBOM quality of the selected target (#496) ──
|
||||
let sbom_quality = use_resource(move || {
|
||||
let repo = repo_filter();
|
||||
@@ -336,6 +348,9 @@ pub fn SbomPage(target: String, #[props(default)] ecosystem: String) -> Element
|
||||
|
||||
// ── SBOM table ──
|
||||
match &*sbom.read() {
|
||||
Some(Some(resp)) if resp.data.is_empty() && unfiltered() => rsx! {
|
||||
SbomEmpty { target_id: repo_filter() }
|
||||
},
|
||||
Some(Some(resp)) => {
|
||||
let total_pages = resp.total.unwrap_or(0).div_ceil(50).max(1);
|
||||
rsx! {
|
||||
@@ -1039,6 +1054,61 @@ fn epss_label(epss: &EpssData) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// The component table's empty state (#979): why the SBOM is empty, and the
|
||||
/// target's open findings that say what it is missing and how to add it, or
|
||||
/// an example where there are none (all targets, or code such as C that has
|
||||
/// no standard manifest).
|
||||
#[component]
|
||||
fn SbomEmpty(target_id: ReadSignal<String>) -> Element {
|
||||
let lang = use_lang()();
|
||||
let findings = use_resource(move || async move {
|
||||
let repo_id = target_id();
|
||||
if repo_id.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
fetch_findings(FindingsQuery {
|
||||
page: 1,
|
||||
repo_id,
|
||||
scanner: SBOM_COVERAGE_SCANNER.to_string(),
|
||||
status: OPEN_STATUS_FILTER.to_string(),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.map(|resp| resp.data)
|
||||
.unwrap_or_default()
|
||||
});
|
||||
let findings = findings.read().clone().unwrap_or_default();
|
||||
rsx! {
|
||||
section { class: "card sbom-empty",
|
||||
h3 { class: "sbom-quality-head", {tx::EMPTY_TITLE.get(lang)} }
|
||||
p { {tx::EMPTY_WHY.get(lang)} }
|
||||
if findings.is_empty() {
|
||||
p { {tx::EMPTY_EXAMPLE.get(lang)} }
|
||||
} else {
|
||||
p { {tx::EMPTY_FINDINGS.get(lang)} }
|
||||
ul { class: "sbom-empty-findings",
|
||||
for finding in findings {
|
||||
{
|
||||
let id = finding.id.map(|id| id.to_hex()).unwrap_or_default();
|
||||
rsx! {
|
||||
li { key: "{id}",
|
||||
strong { "{finding.title}" }
|
||||
if let Some(remediation) = &finding.remediation {
|
||||
p { "{remediation}" }
|
||||
}
|
||||
Link { to: Route::FindingDetailPage { id: id.clone() },
|
||||
{tx::OPEN_FINDING.get(lang)}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The selected target's SBOM quality score: one line per profile, the checks
|
||||
/// it does not meet folded under it.
|
||||
fn sbom_quality_card(resp: SbomQualityResponse, lang: Lang) -> Element {
|
||||
|
||||
@@ -573,7 +573,7 @@ fn TargetEditor(
|
||||
};
|
||||
rsx! {
|
||||
div { class: "modal-overlay",
|
||||
div { class: "modal-dialog form-fields",
|
||||
div { class: "modal-dialog modal-wide form-fields",
|
||||
h3 { {tx::EDIT_TITLE.get(lang)} }
|
||||
div { class: "form-group",
|
||||
label { {tx::COL_NAME.get(lang)} }
|
||||
@@ -609,10 +609,11 @@ fn TargetEditor(
|
||||
}
|
||||
}
|
||||
}
|
||||
label { style: "font-weight: 600;", {tx::ARTIFACTS.get(lang)} }
|
||||
div { class: "modal-section",
|
||||
h4 { class: "target-subhead", {tx::ARTIFACTS.get(lang)} }
|
||||
for (i, a) in edit_arts().iter().enumerate() {
|
||||
div { style: "display: flex; justify-content: space-between; align-items: center; gap: 8px; padding: 4px 0; flex-wrap: wrap;",
|
||||
span { style: "font-size: 0.9em;",
|
||||
div { class: "artifact-row",
|
||||
span { class: "artifact-row-ref",
|
||||
span { style: "opacity: 0.7;", "{kinds::artifact_kind(&a.kind, lang)}: " }
|
||||
span { style: "font-family: monospace;", "{a.source_ref}" }
|
||||
if a.token.as_deref() == Some("") {
|
||||
@@ -626,7 +627,6 @@ fn TargetEditor(
|
||||
r#type: "password",
|
||||
autocomplete: "off",
|
||||
placeholder: tx::NEW_TOKEN.get(lang),
|
||||
style: "flex: 1; min-width: 180px;",
|
||||
oninput: move |e| {
|
||||
let v = e.value();
|
||||
edit_arts.write()[i].token = (!v.is_empty()).then_some(v);
|
||||
@@ -655,8 +655,8 @@ fn TargetEditor(
|
||||
}
|
||||
}
|
||||
}
|
||||
div { style: "display: flex; gap: 8px; align-items: flex-end; margin-top: 8px;",
|
||||
div { class: "form-group", style: "margin: 0;",
|
||||
div { class: "artifact-add",
|
||||
div { class: "form-group artifact-add-kind",
|
||||
label { {tx::KIND.get(lang)} }
|
||||
select {
|
||||
value: "{e_kind}",
|
||||
@@ -669,7 +669,7 @@ fn TargetEditor(
|
||||
}
|
||||
}
|
||||
}
|
||||
div { class: "form-group", style: "margin: 0; flex: 1;",
|
||||
div { class: "form-group artifact-add-ref",
|
||||
label { {tx::REFERENCE.get(lang)} }
|
||||
input {
|
||||
r#type: "text",
|
||||
@@ -678,7 +678,7 @@ fn TargetEditor(
|
||||
}
|
||||
}
|
||||
if e_kind() == "git_repo" {
|
||||
div { class: "form-group", style: "margin: 0;",
|
||||
div { class: "form-group artifact-add-branch",
|
||||
label { {tx::BRANCH.get(lang)} }
|
||||
input {
|
||||
r#type: "text",
|
||||
@@ -686,7 +686,7 @@ fn TargetEditor(
|
||||
oninput: move |e| e_branch.set(e.value()),
|
||||
}
|
||||
}
|
||||
div { class: "form-group", style: "margin: 0;",
|
||||
div { class: "form-group artifact-add-token",
|
||||
label { {tx::TOKEN.get(lang)} }
|
||||
input {
|
||||
r#type: "password",
|
||||
@@ -724,6 +724,8 @@ fn TargetEditor(
|
||||
if let Some(err) = e_source_err.clone() {
|
||||
div { style: "color: var(--danger, #d33); font-size: 0.85em;", "{err}" }
|
||||
}
|
||||
}
|
||||
div { class: "modal-section",
|
||||
h4 { class: "target-subhead", {tx::UPLOAD_TITLE.get(lang)} }
|
||||
ArtifactUpload {
|
||||
target_id: eid.clone(),
|
||||
@@ -734,7 +736,8 @@ fn TargetEditor(
|
||||
on_saved.call(());
|
||||
},
|
||||
}
|
||||
div { class: "form-group",
|
||||
}
|
||||
div { class: "modal-section form-group",
|
||||
label { {tx::EXCLUDE_TITLE.get(lang)} }
|
||||
textarea {
|
||||
rows: "3",
|
||||
@@ -751,6 +754,7 @@ fn TargetEditor(
|
||||
div { style: "color: var(--danger, #d33); font-size: 0.85em;", "{err}" }
|
||||
}
|
||||
}
|
||||
div { class: "modal-section",
|
||||
match projects.read().clone() {
|
||||
Some(Ok(list)) => rsx! { ProjectPicker { projects: list, selected: edit_projects } },
|
||||
Some(Err(e)) => rsx! {
|
||||
@@ -758,6 +762,7 @@ fn TargetEditor(
|
||||
},
|
||||
None => rsx! {},
|
||||
}
|
||||
}
|
||||
div { class: "modal-actions",
|
||||
button {
|
||||
class: "btn btn-secondary",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "compliance-dast"
|
||||
version = "0.4.6"
|
||||
version = "0.4.16"
|
||||
edition = "2021"
|
||||
|
||||
[lints]
|
||||
@@ -14,6 +14,7 @@ tracing = { workspace = true }
|
||||
uuid = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
reqwest = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
# HTML parsing
|
||||
scraper = "0.25"
|
||||
@@ -29,3 +30,6 @@ base64 = "0.22"
|
||||
|
||||
# Serialization
|
||||
url = "2"
|
||||
|
||||
[dev-dependencies]
|
||||
axum = "0.8"
|
||||
@@ -29,7 +29,6 @@ impl ApiFuzzerAgent {
|
||||
("/.well-known/openid-configuration", "OIDC config"),
|
||||
("/server-status", "Apache server status"),
|
||||
("/phpinfo.php", "PHP info exposure"),
|
||||
("/robots.txt", "Robots.txt"),
|
||||
("/sitemap.xml", "Sitemap"),
|
||||
("/.htaccess", "htaccess exposure"),
|
||||
("/backup.sql", "SQL backup exposure"),
|
||||
@@ -160,6 +159,11 @@ impl DastAgent for ApiFuzzerAgent {
|
||||
}
|
||||
}
|
||||
|
||||
// robots.txt is public by design; only the paths it names can matter.
|
||||
if let Some(f) = self.check_robots(base, &target_id).await {
|
||||
findings.push(f);
|
||||
}
|
||||
|
||||
// Phase 2: CORS misconfiguration check
|
||||
let cors_finding = self.check_cors(base, &target_id).await;
|
||||
if let Some(f) = cors_finding {
|
||||
@@ -223,7 +227,115 @@ impl DastAgent for ApiFuzzerAgent {
|
||||
}
|
||||
}
|
||||
|
||||
/// Words that make a path named in robots.txt worth a look.
|
||||
const SENSITIVE_PATH_WORDS: &[&str] = &[
|
||||
"admin", "backup", "config", "debug", "dump", "internal", "private", "secret", "staging",
|
||||
".env", ".git", ".sql",
|
||||
];
|
||||
|
||||
/// Most robots.txt paths that are fetched to see whether they are reachable.
|
||||
const MAX_ROBOTS_PATHS: usize = 20;
|
||||
|
||||
/// The literal paths `robots` disallows that look sensitive, in file order,
|
||||
/// without duplicates. Patterns (`*`, `$`) and `Disallow: /` are skipped: they
|
||||
/// name no single resource.
|
||||
fn sensitive_disallowed(robots: &str) -> Vec<String> {
|
||||
let mut paths: Vec<String> = Vec::new();
|
||||
for line in robots.lines() {
|
||||
// A `#` starts a comment; the directive name is case-insensitive.
|
||||
let line = line.split('#').next().unwrap_or("").trim();
|
||||
let Some((key, value)) = line.split_once(':') else {
|
||||
continue;
|
||||
};
|
||||
let path = value.trim();
|
||||
let literal = path.len() > 1 && path.starts_with('/') && !path.contains(['*', '$']);
|
||||
let lower = path.to_ascii_lowercase();
|
||||
if key.trim().eq_ignore_ascii_case("disallow")
|
||||
&& literal
|
||||
&& SENSITIVE_PATH_WORDS.iter().any(|w| lower.contains(w))
|
||||
&& !paths.iter().any(|p| p == path)
|
||||
{
|
||||
paths.push(path.to_string());
|
||||
}
|
||||
}
|
||||
paths.truncate(MAX_ROBOTS_PATHS);
|
||||
paths
|
||||
}
|
||||
|
||||
impl ApiFuzzerAgent {
|
||||
/// An Info finding when robots.txt names sensitive paths that answer with
|
||||
/// their own content. A page that only repeats what the site sends for a
|
||||
/// made-up path (a single-page app's catch-all, a login redirect) is not
|
||||
/// reachable in that sense.
|
||||
async fn check_robots(&self, base: &str, target_id: &str) -> Option<DastFinding> {
|
||||
let robots_url = format!("{base}/robots.txt");
|
||||
let response = self.http.get(&robots_url).send().await.ok()?;
|
||||
if !response.status().is_success() {
|
||||
return None;
|
||||
}
|
||||
let robots = response.text().await.ok()?;
|
||||
let candidates = sensitive_disallowed(&robots);
|
||||
if candidates.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let made_up = format!("{base}/nonexistent-path-{}", uuid::Uuid::new_v4());
|
||||
let catch_all = match self.http.get(&made_up).send().await {
|
||||
Ok(r) if r.status().is_success() => r.text().await.ok(),
|
||||
_ => None,
|
||||
};
|
||||
let mut reachable = Vec::new();
|
||||
for path in candidates {
|
||||
let Ok(r) = self.http.get(format!("{base}{path}")).send().await else {
|
||||
continue;
|
||||
};
|
||||
if !r.status().is_success() {
|
||||
continue;
|
||||
}
|
||||
let body = r.text().await.unwrap_or_default();
|
||||
if catch_all.as_deref() != Some(body.as_str()) {
|
||||
reachable.push(path);
|
||||
}
|
||||
}
|
||||
if reachable.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let listed = reachable.join(", ");
|
||||
let mut finding = DastFinding::new(
|
||||
String::new(),
|
||||
target_id.to_string(),
|
||||
DastVulnType::InformationDisclosure,
|
||||
"robots.txt names reachable sensitive paths".to_string(),
|
||||
format!(
|
||||
"robots.txt asks crawlers to skip {listed}, and these paths answer with \
|
||||
their own content. robots.txt is public, so it points everyone to them."
|
||||
),
|
||||
Severity::Info,
|
||||
robots_url.clone(),
|
||||
"GET".to_string(),
|
||||
);
|
||||
finding.evidence = vec![DastEvidence {
|
||||
request_method: "GET".to_string(),
|
||||
request_url: robots_url,
|
||||
request_headers: None,
|
||||
request_body: None,
|
||||
response_status: 200,
|
||||
response_headers: None,
|
||||
response_snippet: Some(robots.chars().take(500).collect()),
|
||||
screenshot_path: None,
|
||||
payload: None,
|
||||
response_time_ms: None,
|
||||
}];
|
||||
finding.cwe = Some("CWE-200".to_string());
|
||||
finding.remediation = Some(
|
||||
"Protect these paths with authentication or remove them; robots.txt does not \
|
||||
hide anything."
|
||||
.to_string(),
|
||||
);
|
||||
Some(finding)
|
||||
}
|
||||
|
||||
async fn check_cors(&self, base_url: &str, target_id: &str) -> Option<DastFinding> {
|
||||
let response = self
|
||||
.http
|
||||
@@ -299,3 +411,27 @@ impl ApiFuzzerAgent {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_literal_sensitive_disallowed_paths_count() {
|
||||
let robots = "User-agent: *\n\
|
||||
Disallow: /\n\
|
||||
Disallow: /Admin/ # staff only\n\
|
||||
disallow:/backup.tar\n\
|
||||
Disallow: /*.sql$\n\
|
||||
Disallow: /search\n\
|
||||
Allow: /config-help\n\
|
||||
Disallow: /Admin/\n";
|
||||
assert_eq!(sensitive_disallowed(robots), ["/Admin/", "/backup.tar"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_robots_txt_without_sensitive_paths_names_nothing() {
|
||||
assert!(sensitive_disallowed("User-agent: *\nDisallow: /\n").is_empty());
|
||||
assert!(sensitive_disallowed("").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -89,14 +89,19 @@ impl DastAgent for AuthBypassAgent {
|
||||
}
|
||||
}
|
||||
|
||||
// Test 2: HTTP method tampering
|
||||
let methods = ["PUT", "PATCH", "DELETE", "OPTIONS"];
|
||||
// Test 2: HTTP method tampering. A write method changes the target's
|
||||
// data, so it is sent only with destructive tests allowed.
|
||||
let methods: &[&str] = if target.allow_destructive {
|
||||
&["PUT", "PATCH", "DELETE"]
|
||||
} else {
|
||||
&[]
|
||||
};
|
||||
for endpoint in &context.endpoints {
|
||||
if endpoint.method != "GET" && endpoint.method != "POST" {
|
||||
continue;
|
||||
}
|
||||
|
||||
for method in &methods {
|
||||
for method in methods {
|
||||
let response = match self
|
||||
.http
|
||||
.request(
|
||||
@@ -113,8 +118,8 @@ impl DastAgent for AuthBypassAgent {
|
||||
|
||||
let status = response.status().as_u16();
|
||||
|
||||
// If a non-standard method returns 200 when it shouldn't
|
||||
if status == 200 && *method == "DELETE" && !target.allow_destructive {
|
||||
// A stranger's write accepted on a page meant to be read.
|
||||
if (200..300).contains(&status) {
|
||||
let evidence = DastEvidence {
|
||||
request_method: method.to_string(),
|
||||
request_url: endpoint.url.clone(),
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
//! The login a DAST scan sends with every request to its target (#1000).
|
||||
//!
|
||||
//! A target's [`DastAuthConfig`] becomes default headers on the scan's HTTP
|
||||
//! client. The crawler and the agents stay on the target's origin, and
|
||||
//! reqwest drops `Authorization` and `Cookie` on a redirect to another host, so
|
||||
//! the login only reaches the target.
|
||||
|
||||
use base64::Engine;
|
||||
use compliance_core::models::dast::DastAuthConfig;
|
||||
use reqwest::header::{HeaderMap, HeaderName, HeaderValue, AUTHORIZATION, COOKIE};
|
||||
|
||||
/// Why a target's login cannot be sent.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum LoginError {
|
||||
/// A method this scanner does not know.
|
||||
#[error("login method `{0}` is not known (none, basic, bearer, cookie)")]
|
||||
UnknownMethod(String),
|
||||
/// Form login drives a browser and is not available yet.
|
||||
#[error("form login is not supported yet")]
|
||||
FormNotSupported,
|
||||
/// The method lacks a value it needs.
|
||||
#[error("the {method} login needs {missing}")]
|
||||
Missing {
|
||||
method: &'static str,
|
||||
missing: &'static str,
|
||||
},
|
||||
/// A header name or value that HTTP cannot carry.
|
||||
#[error("header `{0}` cannot be sent")]
|
||||
InvalidHeader(String),
|
||||
}
|
||||
|
||||
/// The headers that log a scan in with `auth`; empty without a login.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `auth` - the target's login, its secrets already opened
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `Authorization` (basic, bearer) or `Cookie` (cookie), plus the login's
|
||||
/// extra headers. Secret values are marked sensitive, so they never appear in
|
||||
/// a `Debug` print of the headers.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`LoginError`] when the method is unknown or form login, a value the
|
||||
/// method needs is missing, or a header cannot be sent.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use compliance_core::models::dast::DastAuthConfig;
|
||||
/// let auth = DastAuthConfig {
|
||||
/// method: "bearer".into(),
|
||||
/// login_url: None,
|
||||
/// username: None,
|
||||
/// password: None,
|
||||
/// token: Some("t0ken".into()),
|
||||
/// headers: None,
|
||||
/// };
|
||||
/// let headers = compliance_dast::auth::login_headers(Some(&auth)).unwrap();
|
||||
/// assert_eq!(headers["authorization"], "Bearer t0ken");
|
||||
/// ```
|
||||
pub fn login_headers(auth: Option<&DastAuthConfig>) -> Result<HeaderMap, LoginError> {
|
||||
let mut headers = HeaderMap::new();
|
||||
let Some(auth) = auth else {
|
||||
return Ok(headers);
|
||||
};
|
||||
match auth.method.to_ascii_lowercase().as_str() {
|
||||
"" | "none" => {}
|
||||
"basic" => {
|
||||
let user = secret("basic", auth.username.as_ref(), "a username")?;
|
||||
let password = secret("basic", auth.password.as_ref(), "a password")?;
|
||||
let encoded =
|
||||
base64::engine::general_purpose::STANDARD.encode(format!("{user}:{password}"));
|
||||
headers.insert(
|
||||
AUTHORIZATION,
|
||||
sensitive("Authorization", &format!("Basic {encoded}"))?,
|
||||
);
|
||||
}
|
||||
"bearer" => {
|
||||
let token = secret("bearer", auth.token.as_ref(), "a token")?;
|
||||
headers.insert(
|
||||
AUTHORIZATION,
|
||||
sensitive("Authorization", &format!("Bearer {token}"))?,
|
||||
);
|
||||
}
|
||||
"cookie" => {
|
||||
let cookie = secret("cookie", auth.token.as_ref(), "the cookie (name=value)")?;
|
||||
headers.insert(COOKIE, sensitive("Cookie", cookie)?);
|
||||
}
|
||||
"form" => return Err(LoginError::FormNotSupported),
|
||||
other => return Err(LoginError::UnknownMethod(other.to_string())),
|
||||
}
|
||||
for (name, value) in auth.headers.iter().flatten() {
|
||||
let header = HeaderName::try_from(name.as_str())
|
||||
.map_err(|_| LoginError::InvalidHeader(name.clone()))?;
|
||||
headers.insert(header, sensitive(name, value)?);
|
||||
}
|
||||
Ok(headers)
|
||||
}
|
||||
|
||||
/// `value` when set and not empty, else what the `method` login is missing.
|
||||
fn secret<'a>(
|
||||
method: &'static str,
|
||||
value: Option<&'a String>,
|
||||
missing: &'static str,
|
||||
) -> Result<&'a str, LoginError> {
|
||||
value
|
||||
.map(String::as_str)
|
||||
.filter(|v| !v.is_empty())
|
||||
.ok_or(LoginError::Missing { method, missing })
|
||||
}
|
||||
|
||||
/// A header value marked sensitive.
|
||||
fn sensitive(name: &str, value: &str) -> Result<HeaderValue, LoginError> {
|
||||
let mut value =
|
||||
HeaderValue::from_str(value).map_err(|_| LoginError::InvalidHeader(name.to_string()))?;
|
||||
value.set_sensitive(true);
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn auth(method: &str) -> DastAuthConfig {
|
||||
DastAuthConfig {
|
||||
method: method.into(),
|
||||
login_url: None,
|
||||
username: None,
|
||||
password: None,
|
||||
token: None,
|
||||
headers: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_login_sends_nothing() {
|
||||
assert!(login_headers(None).unwrap().is_empty());
|
||||
assert!(login_headers(Some(&auth("none"))).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn basic_login_encodes_user_and_password() {
|
||||
let mut a = auth("basic");
|
||||
a.username = Some("scan".into());
|
||||
a.password = Some("pw".into());
|
||||
let headers = login_headers(Some(&a)).unwrap();
|
||||
// base64("scan:pw")
|
||||
assert_eq!(headers[AUTHORIZATION], "Basic c2Nhbjpwdw==");
|
||||
assert!(headers[AUTHORIZATION].is_sensitive());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cookie_and_extra_headers_are_sent_and_sensitive() {
|
||||
let mut a = auth("Cookie");
|
||||
a.token = Some("session=abc".into());
|
||||
a.headers = Some(HashMap::from([("X-Api-Key".into(), "k".into())]));
|
||||
let headers = login_headers(Some(&a)).unwrap();
|
||||
assert_eq!(headers[COOKIE], "session=abc");
|
||||
assert_eq!(headers["x-api-key"], "k");
|
||||
assert!(headers["x-api-key"].is_sensitive());
|
||||
assert!(!format!("{headers:?}").contains("abc"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_login_without_its_secret_is_refused() {
|
||||
assert_eq!(
|
||||
login_headers(Some(&auth("bearer"))),
|
||||
Err(LoginError::Missing {
|
||||
method: "bearer",
|
||||
missing: "a token"
|
||||
})
|
||||
);
|
||||
let mut a = auth("basic");
|
||||
a.username = Some("scan".into());
|
||||
assert!(matches!(
|
||||
login_headers(Some(&a)),
|
||||
Err(LoginError::Missing {
|
||||
missing: "a password",
|
||||
..
|
||||
})
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn form_and_unknown_methods_are_refused() {
|
||||
assert_eq!(
|
||||
login_headers(Some(&auth("form"))),
|
||||
Err(LoginError::FormNotSupported)
|
||||
);
|
||||
assert_eq!(
|
||||
login_headers(Some(&auth("ntlm"))),
|
||||
Err(LoginError::UnknownMethod("ntlm".into()))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_http_cannot_carry_is_refused() {
|
||||
let mut a = auth("none");
|
||||
a.headers = Some(HashMap::from([("X-Bad".into(), "a\nb".into())]));
|
||||
assert_eq!(
|
||||
login_headers(Some(&a)),
|
||||
Err(LoginError::InvalidHeader("X-Bad".into()))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
//! One Chrome tab driven over the Chrome DevTools Protocol (CDP).
|
||||
//!
|
||||
//! Each tab lives in its own browser context, Chrome's equivalent of a fresh
|
||||
//! profile: its cookies and storage are invisible to every other tab, so one
|
||||
//! scan's or pentest session's login never shows up in another's.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use serde_json::{json, Value};
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
|
||||
type WsStream =
|
||||
tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
|
||||
|
||||
/// How long one CDP command may take to answer.
|
||||
const COMMAND_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// A tab in its own browser context, closed with [`CdpTab::close`].
|
||||
pub(crate) struct CdpTab {
|
||||
ws: WsStream,
|
||||
next_id: u64,
|
||||
session_id: String,
|
||||
target_id: String,
|
||||
context_id: String,
|
||||
}
|
||||
|
||||
impl CdpTab {
|
||||
/// Open a blank tab in a new browser context of the Chrome at
|
||||
/// `CHROME_WS_URL`, with the `Page` and `Runtime` domains on.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Why Chrome cannot be reached or refused a command.
|
||||
pub(crate) async fn open() -> Result<Self, String> {
|
||||
let ws_url = std::env::var("CHROME_WS_URL").map_err(|_| {
|
||||
"CHROME_WS_URL not set — headless Chrome is required for browser actions".to_string()
|
||||
})?;
|
||||
// `/json/version` names the browser's own WebSocket endpoint.
|
||||
let http_url = ws_url
|
||||
.replacen("ws://", "http://", 1)
|
||||
.replacen("wss://", "https://", 1);
|
||||
let version_url = format!("{}/json/version", http_url.trim_end_matches('/'));
|
||||
let version: Value = reqwest::get(&version_url)
|
||||
.await
|
||||
.map_err(|e| format!("Cannot reach Chrome at {version_url}: {e}"))?
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| format!("Invalid /json/version response: {e}"))?;
|
||||
let browser_ws = version["webSocketDebuggerUrl"]
|
||||
.as_str()
|
||||
.ok_or_else(|| "No webSocketDebuggerUrl in /json/version".to_string())?;
|
||||
let (ws, _) = tokio_tungstenite::connect_async(browser_ws)
|
||||
.await
|
||||
.map_err(|e| format!("WebSocket connect failed: {e}"))?;
|
||||
|
||||
let mut tab = Self {
|
||||
ws,
|
||||
next_id: 1,
|
||||
session_id: String::new(),
|
||||
target_id: String::new(),
|
||||
context_id: String::new(),
|
||||
};
|
||||
let context = tab
|
||||
.browser(
|
||||
"Target.createBrowserContext",
|
||||
json!({ "disposeOnDetach": true }),
|
||||
)
|
||||
.await?;
|
||||
tab.context_id = string_at(&context, "browserContextId")?;
|
||||
let target = tab
|
||||
.browser(
|
||||
"Target.createTarget",
|
||||
json!({ "url": "about:blank", "browserContextId": tab.context_id }),
|
||||
)
|
||||
.await?;
|
||||
tab.target_id = string_at(&target, "targetId")?;
|
||||
let attached = tab
|
||||
.browser(
|
||||
"Target.attachToTarget",
|
||||
json!({ "targetId": tab.target_id, "flatten": true }),
|
||||
)
|
||||
.await?;
|
||||
tab.session_id = string_at(&attached, "sessionId")?;
|
||||
for domain in ["Page.enable", "Runtime.enable"] {
|
||||
tab.call(domain, json!({})).await?;
|
||||
}
|
||||
Ok(tab)
|
||||
}
|
||||
|
||||
/// Send `method` to the tab and return the command's `result`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The CDP error, a broken connection, or no answer in time.
|
||||
pub(crate) async fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
let message = json!({
|
||||
"id": self.next_id,
|
||||
"sessionId": self.session_id,
|
||||
"method": method,
|
||||
"params": params,
|
||||
});
|
||||
self.send(message).await
|
||||
}
|
||||
|
||||
/// Evaluate `expression` in the page and return its value as a string
|
||||
/// (JSON for anything that is not a string; empty for `undefined`).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// As [`Self::call`].
|
||||
pub(crate) async fn evaluate(&mut self, expression: &str) -> Result<String, String> {
|
||||
let resp = self
|
||||
.call(
|
||||
"Runtime.evaluate",
|
||||
json!({ "expression": expression, "returnByValue": true }),
|
||||
)
|
||||
.await?;
|
||||
Ok(match resp.get("result").and_then(|r| r.get("value")) {
|
||||
Some(Value::String(s)) => s.clone(),
|
||||
Some(v) => v.to_string(),
|
||||
None => String::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Close the tab and dispose of its browser context with every cookie in
|
||||
/// it. Best effort: Chrome also disposes of the context when the
|
||||
/// connection drops.
|
||||
pub(crate) async fn close(&mut self) {
|
||||
let _ = self
|
||||
.browser("Target.closeTarget", json!({ "targetId": self.target_id }))
|
||||
.await;
|
||||
let _ = self
|
||||
.browser(
|
||||
"Target.disposeBrowserContext",
|
||||
json!({ "browserContextId": self.context_id }),
|
||||
)
|
||||
.await;
|
||||
let _ = self.ws.close(None).await;
|
||||
}
|
||||
|
||||
/// Send `method` to the browser itself rather than the tab.
|
||||
async fn browser(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
let message = json!({ "id": self.next_id, "method": method, "params": params });
|
||||
self.send(message).await
|
||||
}
|
||||
|
||||
async fn send(&mut self, message: Value) -> Result<Value, String> {
|
||||
let id = self.next_id;
|
||||
self.next_id += 1;
|
||||
self.ws
|
||||
.send(Message::Text(message.to_string().into()))
|
||||
.await
|
||||
.map_err(|e| format!("WS send failed: {e}"))?;
|
||||
let deadline = tokio::time::Instant::now() + COMMAND_TIMEOUT;
|
||||
loop {
|
||||
let msg = tokio::time::timeout_at(deadline, self.ws.next())
|
||||
.await
|
||||
.map_err(|_| format!("Timeout waiting for CDP response id={id}"))?
|
||||
.ok_or_else(|| "WebSocket closed unexpectedly".to_string())?
|
||||
.map_err(|e| format!("WebSocket read error: {e}"))?;
|
||||
// Events and other commands' answers share the socket; skip them.
|
||||
let Message::Text(text) = msg else { continue };
|
||||
let Ok(val) = serde_json::from_str::<Value>(&text) else {
|
||||
continue;
|
||||
};
|
||||
if val.get("id").and_then(Value::as_u64) != Some(id) {
|
||||
continue;
|
||||
}
|
||||
if let Some(err) = val.get("error") {
|
||||
return Err(format!("CDP error: {err}"));
|
||||
}
|
||||
return Ok(val.get("result").cloned().unwrap_or(Value::Null));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The string field `key` of a CDP result.
|
||||
fn string_at(result: &Value, key: &str) -> Result<String, String> {
|
||||
result
|
||||
.get(key)
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)
|
||||
.ok_or_else(|| format!("No {key} in CDP response"))
|
||||
}
|
||||
|
||||
// Needs a real Chrome: set `CHROME_WS_URL` (e.g. `chromedp/headless-shell`
|
||||
// on the host network). Without it the test passes without checking.
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use axum::extract::{Request, State};
|
||||
use axum::http::header::{COOKIE, SET_COOKIE};
|
||||
use axum::response::IntoResponse;
|
||||
use axum::Router;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The `Cookie` header of every request the site saw.
|
||||
type Seen = Arc<Mutex<Vec<Option<String>>>>;
|
||||
|
||||
/// A site that sets a cookie on every answer and records what came back.
|
||||
async fn cookie_site(seen: Seen) -> String {
|
||||
async fn any(State(seen): State<Seen>, request: Request) -> impl IntoResponse {
|
||||
let cookie = request
|
||||
.headers()
|
||||
.get(COOKIE)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(str::to_string);
|
||||
seen.lock().unwrap().push(cookie);
|
||||
([(SET_COOKIE, "visited=1; Path=/")], "<html></html>")
|
||||
}
|
||||
let app = Router::new().fallback(any).with_state(seen);
|
||||
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 tabs_do_not_share_cookies() {
|
||||
if std::env::var("CHROME_WS_URL").is_err() {
|
||||
return;
|
||||
}
|
||||
let seen: Seen = Arc::default();
|
||||
let site = cookie_site(seen.clone()).await;
|
||||
|
||||
let mut first = CdpTab::open().await.unwrap();
|
||||
let mut second = CdpTab::open().await.unwrap();
|
||||
let navigate = json!({ "url": site });
|
||||
first.call("Page.navigate", navigate.clone()).await.unwrap();
|
||||
first.call("Page.navigate", navigate.clone()).await.unwrap();
|
||||
second.call("Page.navigate", navigate).await.unwrap();
|
||||
first.close().await;
|
||||
second.close().await;
|
||||
|
||||
let seen = seen.lock().unwrap().clone();
|
||||
assert_eq!(
|
||||
seen,
|
||||
[None, Some("visited=1".to_string()), None],
|
||||
"the first tab keeps its cookie, the second never sees it"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
//! The deterministic checks every DAST scan runs (#998): security headers,
|
||||
//! Content-Security-Policy, cookies and TLS. They read what the target sends
|
||||
//! and judge it by fixed rules, so the same site gives the same findings in
|
||||
//! every scan. Until now only the LLM pentest could call them.
|
||||
//!
|
||||
//! CORS is checked by the API fuzzer agent, which every scan runs already.
|
||||
|
||||
use compliance_core::models::dast::{DastFinding, DastTarget};
|
||||
use compliance_core::traits::pentest_tool::{PentestTool, PentestToolContext};
|
||||
use compliance_core::NetGuard;
|
||||
use serde_json::json;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::tools::cookie_analyzer::CookieAnalyzerTool;
|
||||
use crate::tools::csp_analyzer::CspAnalyzerTool;
|
||||
use crate::tools::security_headers::SecurityHeadersTool;
|
||||
use crate::tools::tls_analyzer::TlsAnalyzerTool;
|
||||
|
||||
/// Run every check against `target`'s base URL.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `target` - the DAST target; its findings name it
|
||||
/// * `http` - the scan's client, with the target's login, so the checks see
|
||||
/// the pages a logged-in visitor gets
|
||||
/// * `guard` - where the TLS and cookie checks may connect
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The findings of all checks. A check that cannot run (the site does not
|
||||
/// answer it) is logged and adds nothing; the others still run.
|
||||
pub async fn run_checks(
|
||||
target: &DastTarget,
|
||||
http: &reqwest::Client,
|
||||
guard: NetGuard,
|
||||
) -> Vec<DastFinding> {
|
||||
let checks: [Box<dyn PentestTool>; 4] = [
|
||||
Box::new(SecurityHeadersTool::new(http.clone())),
|
||||
Box::new(CspAnalyzerTool::new(http.clone())),
|
||||
Box::new(CookieAnalyzerTool::new(http.clone(), guard)),
|
||||
Box::new(TlsAnalyzerTool::new(http.clone(), guard)),
|
||||
];
|
||||
let context = PentestToolContext {
|
||||
target: target.clone(),
|
||||
session_id: String::new(),
|
||||
sast_findings: Vec::new(),
|
||||
sbom_entries: Vec::new(),
|
||||
code_context: Vec::new(),
|
||||
rate_limit: target.rate_limit,
|
||||
allow_destructive: target.allow_destructive,
|
||||
};
|
||||
let input = json!({ "url": target.base_url });
|
||||
|
||||
let mut findings = Vec::new();
|
||||
for check in &checks {
|
||||
match check.execute(input.clone(), &context).await {
|
||||
Ok(result) => findings.extend(result.findings),
|
||||
Err(e) => warn!(check = check.name(), error = %e, "DAST check did not run"),
|
||||
}
|
||||
}
|
||||
findings
|
||||
}
|
||||
@@ -128,6 +128,11 @@ impl WebCrawler {
|
||||
let form_url = self
|
||||
.resolve_url(&base, &url, action)
|
||||
.unwrap_or_else(|| url.clone());
|
||||
// A form that posts to another site is out of scope: the
|
||||
// agents would send their payloads (and the login) there.
|
||||
if !self.is_same_origin(&base, &form_url) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut params = Vec::new();
|
||||
for input in form.select(&input_selector) {
|
||||
@@ -185,11 +190,9 @@ impl WebCrawler {
|
||||
current.join(href).ok().map(|u| u.to_string())
|
||||
}
|
||||
|
||||
/// Scheme, host and port all equal: another port on the same host is
|
||||
/// another service, not the target.
|
||||
fn is_same_origin(&self, base: &Url, url: &str) -> bool {
|
||||
if let Ok(parsed) = Url::parse(url) {
|
||||
parsed.host() == base.host() && parsed.scheme() == base.scheme()
|
||||
} else {
|
||||
false
|
||||
}
|
||||
Url::parse(url).is_ok_and(|parsed| parsed.origin() == base.origin())
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
pub mod agents;
|
||||
pub mod auth;
|
||||
mod cdp;
|
||||
pub mod checks;
|
||||
pub mod crawler;
|
||||
pub mod orchestrator;
|
||||
pub mod recon;
|
||||
|
||||
@@ -13,7 +13,9 @@ use crate::recon::ReconAgent;
|
||||
|
||||
/// State machine orchestrator for DAST scanning
|
||||
pub struct DastOrchestrator {
|
||||
/// Without the target's login: the auth-bypass checks ask as a stranger.
|
||||
http: reqwest::Client,
|
||||
guard: NetGuard,
|
||||
rate_limit_ms: u64,
|
||||
}
|
||||
|
||||
@@ -28,10 +30,29 @@ impl DastOrchestrator {
|
||||
http: guarded_client_builder(guard)
|
||||
.build()
|
||||
.expect("failed to build HTTP client"),
|
||||
guard,
|
||||
rate_limit_ms,
|
||||
}
|
||||
}
|
||||
|
||||
/// The client that carries `target`'s login (#1000), or the anonymous one
|
||||
/// when it has none.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Why the login cannot be sent, for the scan run's error message.
|
||||
fn login_client(&self, target: &DastTarget) -> Result<reqwest::Client, String> {
|
||||
let headers =
|
||||
crate::auth::login_headers(target.auth_config.as_ref()).map_err(|e| e.to_string())?;
|
||||
if headers.is_empty() {
|
||||
return Ok(self.http.clone());
|
||||
}
|
||||
guarded_client_builder(self.guard)
|
||||
.default_headers(headers)
|
||||
.build()
|
||||
.map_err(|e| format!("no HTTP client: {e}"))
|
||||
}
|
||||
|
||||
/// Run a complete DAST scan against a target
|
||||
pub async fn run_scan(
|
||||
&self,
|
||||
@@ -48,9 +69,22 @@ impl DastOrchestrator {
|
||||
|
||||
info!(target = %target.base_url, "Starting DAST scan");
|
||||
|
||||
// A login that cannot be sent fails the scan: testing anonymously
|
||||
// instead would look like a logged-in scan that found nothing.
|
||||
let http = match self.login_client(target) {
|
||||
Ok(http) => http,
|
||||
Err(e) => {
|
||||
error!(error = %e, "DAST login unusable");
|
||||
scan_run.status = DastScanStatus::Failed;
|
||||
scan_run.error_message = Some(format!("Login: {e}"));
|
||||
scan_run.completed_at = Some(Utc::now());
|
||||
return Ok((scan_run, all_findings));
|
||||
}
|
||||
};
|
||||
|
||||
// Phase 1: Reconnaissance
|
||||
scan_run.current_phase = DastScanPhase::Reconnaissance;
|
||||
let recon = ReconAgent::new(self.http.clone());
|
||||
let recon = ReconAgent::new(http.clone());
|
||||
let recon_result = match recon.scan(&target.base_url).await {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
@@ -73,11 +107,7 @@ impl DastOrchestrator {
|
||||
|
||||
// Phase 2: Crawling
|
||||
scan_run.current_phase = DastScanPhase::Crawling;
|
||||
let crawler = WebCrawler::new(
|
||||
self.http.clone(),
|
||||
target.max_crawl_depth,
|
||||
self.rate_limit_ms,
|
||||
);
|
||||
let crawler = WebCrawler::new(http.clone(), target.max_crawl_depth, self.rate_limit_ms);
|
||||
let endpoints = match crawler
|
||||
.crawl(&target.base_url, &target.excluded_paths)
|
||||
.await
|
||||
@@ -103,20 +133,18 @@ impl DastOrchestrator {
|
||||
sast_hints,
|
||||
};
|
||||
|
||||
// Phase 3: Vulnerability Analysis
|
||||
// Phase 3: Vulnerability Analysis: the fixed checks, then the agents
|
||||
scan_run.current_phase = DastScanPhase::VulnerabilityAnalysis;
|
||||
let vuln_findings = self.run_vulnerability_agents(target, &context).await?;
|
||||
all_findings.extend(crate::checks::run_checks(target, &http, self.guard).await);
|
||||
let vuln_findings = self
|
||||
.run_vulnerability_agents(target, &context, http)
|
||||
.await?;
|
||||
all_findings.extend(vuln_findings);
|
||||
scan_run
|
||||
.phases_completed
|
||||
.push(DastScanPhase::VulnerabilityAnalysis);
|
||||
|
||||
// Phase 4: Exploitation (verify findings)
|
||||
scan_run.current_phase = DastScanPhase::Exploitation;
|
||||
// Exploitation is handled within each agent's evidence collection
|
||||
scan_run.phases_completed.push(DastScanPhase::Exploitation);
|
||||
|
||||
// Phase 5: Reporting
|
||||
// Phase 4: Reporting
|
||||
scan_run.current_phase = DastScanPhase::Reporting;
|
||||
scan_run.findings_count = all_findings.len() as u32;
|
||||
scan_run.exploitable_count = all_findings.iter().filter(|f| f.exploitable).count() as u32;
|
||||
@@ -136,15 +164,16 @@ impl DastOrchestrator {
|
||||
}
|
||||
|
||||
/// Run all vulnerability testing agents in parallel
|
||||
/// `http` carries the target's login; the auth-bypass agent gets the
|
||||
/// anonymous client instead, since it asks what a stranger may do.
|
||||
async fn run_vulnerability_agents(
|
||||
&self,
|
||||
target: &DastTarget,
|
||||
context: &DastContext,
|
||||
http: reqwest::Client,
|
||||
) -> Result<Vec<DastFinding>, CoreError> {
|
||||
use compliance_core::traits::DastAgent;
|
||||
|
||||
let http = self.http.clone();
|
||||
|
||||
// Spawn each agent as a separate tokio task
|
||||
let t1 = target.clone();
|
||||
let c1 = context.clone();
|
||||
@@ -163,7 +192,7 @@ impl DastOrchestrator {
|
||||
|
||||
let t3 = target.clone();
|
||||
let c3 = context.clone();
|
||||
let h3 = http.clone();
|
||||
let h3 = self.http.clone();
|
||||
let auth_handle = tokio::spawn(async move {
|
||||
crate::agents::auth_bypass::AuthBypassAgent::new(h3)
|
||||
.run(&t3, &c3)
|
||||
|
||||
@@ -6,14 +6,11 @@ use std::time::Duration;
|
||||
use base64::Engine;
|
||||
use compliance_core::error::CoreError;
|
||||
use compliance_core::traits::pentest_tool::{PentestTool, PentestToolContext, PentestToolResult};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use serde_json::json;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use tracing::info;
|
||||
|
||||
type WsStream =
|
||||
tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
|
||||
use crate::cdp::CdpTab;
|
||||
|
||||
/// Global pool of persistent browser sessions keyed by pentest session ID.
|
||||
/// Each pentest session gets one Chrome tab that stays alive across tool calls.
|
||||
@@ -102,7 +99,7 @@ impl PentestTool for BrowserTool {
|
||||
if action == "close" {
|
||||
let mut pool = BROWSER_SESSIONS.lock().await;
|
||||
if let Some(mut sess) = pool.remove(&session_key) {
|
||||
let _ = sess.close().await;
|
||||
sess.close().await;
|
||||
}
|
||||
return Ok(PentestToolResult {
|
||||
summary: "Browser session closed".to_string(),
|
||||
@@ -142,7 +139,7 @@ impl PentestTool for BrowserTool {
|
||||
// If the session errored, remove it so the next call creates a fresh one
|
||||
if result.is_err() {
|
||||
if let Some(mut dead) = pool.remove(&session_key) {
|
||||
let _ = dead.close().await;
|
||||
dead.close().await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,114 +173,35 @@ impl PentestTool for BrowserTool {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A single CDP session wrapping a browser tab.
|
||||
/// The pentest tool's tab: a [`CdpTab`] plus the actions the LLM may take.
|
||||
struct BrowserSession {
|
||||
ws: WsStream,
|
||||
next_id: u64,
|
||||
session_id: String,
|
||||
target_id: String,
|
||||
tab: CdpTab,
|
||||
}
|
||||
|
||||
impl BrowserSession {
|
||||
/// Connect to headless Chrome and create a new tab.
|
||||
/// Open a tab in its own browser context, so this pentest session sees
|
||||
/// no other session's cookies.
|
||||
async fn connect() -> Result<Self, String> {
|
||||
let ws_url = std::env::var("CHROME_WS_URL").map_err(|_| {
|
||||
"CHROME_WS_URL not set — headless Chrome is required for browser actions".to_string()
|
||||
})?;
|
||||
|
||||
// Discover browser WS endpoint
|
||||
let http_url = ws_url
|
||||
.replace("ws://", "http://")
|
||||
.replace("wss://", "https://");
|
||||
let version_url = format!("{http_url}/json/version");
|
||||
|
||||
let version: serde_json::Value = reqwest::get(&version_url)
|
||||
.await
|
||||
.map_err(|e| format!("Cannot reach Chrome at {version_url}: {e}"))?
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| format!("Invalid /json/version response: {e}"))?;
|
||||
|
||||
let browser_ws = version["webSocketDebuggerUrl"]
|
||||
.as_str()
|
||||
.ok_or_else(|| "No webSocketDebuggerUrl in /json/version".to_string())?;
|
||||
|
||||
let (mut ws, _) = tokio_tungstenite::connect_async(browser_ws)
|
||||
.await
|
||||
.map_err(|e| format!("WebSocket connect failed: {e}"))?;
|
||||
|
||||
let mut next_id: u64 = 1;
|
||||
|
||||
// Create tab
|
||||
let resp = cdp_send(
|
||||
&mut ws,
|
||||
next_id,
|
||||
"Target.createTarget",
|
||||
json!({ "url": "about:blank" }),
|
||||
)
|
||||
.await?;
|
||||
next_id += 1;
|
||||
|
||||
let target_id = resp
|
||||
.get("result")
|
||||
.and_then(|r| r.get("targetId"))
|
||||
.and_then(|t| t.as_str())
|
||||
.ok_or("No targetId in createTarget response")?
|
||||
.to_string();
|
||||
|
||||
// Attach
|
||||
let resp = cdp_send(
|
||||
&mut ws,
|
||||
next_id,
|
||||
"Target.attachToTarget",
|
||||
json!({ "targetId": target_id, "flatten": true }),
|
||||
)
|
||||
.await?;
|
||||
next_id += 1;
|
||||
|
||||
let session_id = resp
|
||||
.get("result")
|
||||
.and_then(|r| r.get("sessionId"))
|
||||
.and_then(|s| s.as_str())
|
||||
.ok_or("No sessionId in attachToTarget response")?
|
||||
.to_string();
|
||||
|
||||
// Enable domains
|
||||
cdp_send_session(&mut ws, next_id, &session_id, "Page.enable", json!({})).await?;
|
||||
next_id += 1;
|
||||
|
||||
cdp_send_session(&mut ws, next_id, &session_id, "Runtime.enable", json!({})).await?;
|
||||
next_id += 1;
|
||||
|
||||
Ok(Self {
|
||||
ws,
|
||||
next_id,
|
||||
session_id,
|
||||
target_id,
|
||||
tab: CdpTab::open().await?,
|
||||
})
|
||||
}
|
||||
|
||||
async fn navigate(&mut self, url: &str, wait_ms: u64) -> Result<serde_json::Value, String> {
|
||||
cdp_send_session(
|
||||
&mut self.ws,
|
||||
self.next_id,
|
||||
&self.session_id,
|
||||
"Page.navigate",
|
||||
json!({ "url": url }),
|
||||
)
|
||||
.await?;
|
||||
self.next_id += 1;
|
||||
|
||||
self.tab
|
||||
.call("Page.navigate", json!({ "url": url }))
|
||||
.await?;
|
||||
tokio::time::sleep(Duration::from_millis(wait_ms)).await;
|
||||
|
||||
// Get page title and current URL (may have redirected)
|
||||
let title = self
|
||||
.evaluate_raw("document.title")
|
||||
.tab
|
||||
.evaluate("document.title")
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let page_url = self
|
||||
.evaluate_raw("window.location.href")
|
||||
.tab
|
||||
.evaluate("window.location.href")
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
|
||||
@@ -298,7 +216,7 @@ impl BrowserSession {
|
||||
});
|
||||
return JSON.stringify(items);
|
||||
})()"#;
|
||||
let elements_json = self.evaluate_raw(links_js).await.unwrap_or_default();
|
||||
let elements_json = self.tab.evaluate(links_js).await.unwrap_or_default();
|
||||
let elements: serde_json::Value = serde_json::from_str(&elements_json).unwrap_or(json!([]));
|
||||
|
||||
// Auto-capture screenshot after every navigation
|
||||
@@ -315,19 +233,15 @@ impl BrowserSession {
|
||||
|
||||
/// Capture a screenshot and return the base64 string (empty on failure).
|
||||
async fn capture_screenshot_b64(&mut self) -> Result<String, String> {
|
||||
let resp = cdp_send_session(
|
||||
&mut self.ws,
|
||||
self.next_id,
|
||||
&self.session_id,
|
||||
"Page.captureScreenshot",
|
||||
json!({ "format": "png", "quality": 80 }),
|
||||
)
|
||||
.await?;
|
||||
self.next_id += 1;
|
||||
|
||||
let resp = self
|
||||
.tab
|
||||
.call(
|
||||
"Page.captureScreenshot",
|
||||
json!({ "format": "png", "quality": 80 }),
|
||||
)
|
||||
.await?;
|
||||
Ok(resp
|
||||
.get("result")
|
||||
.and_then(|r| r.get("data"))
|
||||
.get("data")
|
||||
.and_then(|d| d.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string())
|
||||
@@ -366,16 +280,18 @@ impl BrowserSession {
|
||||
raw = selector.replace('"', r#"\""#),
|
||||
);
|
||||
|
||||
let result = self.evaluate_raw(&js).await?;
|
||||
let result = self.tab.evaluate(&js).await?;
|
||||
tokio::time::sleep(Duration::from_millis(wait_ms)).await;
|
||||
|
||||
// After click, get current URL (may have navigated)
|
||||
let current_url = self
|
||||
.evaluate_raw("window.location.href")
|
||||
.tab
|
||||
.evaluate("window.location.href")
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let title = self
|
||||
.evaluate_raw("document.title")
|
||||
.tab
|
||||
.evaluate("document.title")
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
|
||||
@@ -400,89 +316,36 @@ impl BrowserSession {
|
||||
value: &str,
|
||||
wait_ms: u64,
|
||||
) -> Result<serde_json::Value, String> {
|
||||
// Step 1: Focus the element via JS
|
||||
let focus_js = format!(
|
||||
"(function(){{var e=document.querySelector({sel});\
|
||||
if(!e)return 'notfound';e.focus();e.select();return 'ok'}})()",
|
||||
sel = serde_json::to_string(selector).unwrap_or_default(),
|
||||
);
|
||||
let found = self.evaluate_raw(&focus_js).await?;
|
||||
if found == "notfound" {
|
||||
if !type_into(&mut self.tab, selector, value).await? {
|
||||
return Ok(json!({ "error": format!("Element not found: {selector}") }));
|
||||
}
|
||||
|
||||
// Step 2: Clear existing content with Select All + Delete
|
||||
cdp_send_session(
|
||||
&mut self.ws,
|
||||
self.next_id,
|
||||
&self.session_id,
|
||||
"Input.dispatchKeyEvent",
|
||||
json!({"type": "keyDown", "key": "a", "code": "KeyA", "modifiers": 2}),
|
||||
)
|
||||
.await?;
|
||||
self.next_id += 1;
|
||||
cdp_send_session(
|
||||
&mut self.ws,
|
||||
self.next_id,
|
||||
&self.session_id,
|
||||
"Input.dispatchKeyEvent",
|
||||
json!({"type": "keyUp", "key": "a", "code": "KeyA", "modifiers": 2}),
|
||||
)
|
||||
.await?;
|
||||
self.next_id += 1;
|
||||
cdp_send_session(
|
||||
&mut self.ws,
|
||||
self.next_id,
|
||||
&self.session_id,
|
||||
"Input.dispatchKeyEvent",
|
||||
json!({"type": "keyDown", "key": "Backspace", "code": "Backspace"}),
|
||||
)
|
||||
.await?;
|
||||
self.next_id += 1;
|
||||
cdp_send_session(
|
||||
&mut self.ws,
|
||||
self.next_id,
|
||||
&self.session_id,
|
||||
"Input.dispatchKeyEvent",
|
||||
json!({"type": "keyUp", "key": "Backspace", "code": "Backspace"}),
|
||||
)
|
||||
.await?;
|
||||
self.next_id += 1;
|
||||
|
||||
// Step 3: Insert the text using Input.insertText (single CDP command, no JS eval)
|
||||
cdp_send_session(
|
||||
&mut self.ws,
|
||||
self.next_id,
|
||||
&self.session_id,
|
||||
"Input.insertText",
|
||||
json!({"text": value}),
|
||||
)
|
||||
.await?;
|
||||
self.next_id += 1;
|
||||
|
||||
// Step 4: Verify the value was set
|
||||
// Whether the field now holds the value; the value itself stays out
|
||||
// of the result, since it may be a password.
|
||||
let verify_js = format!(
|
||||
"(function(){{var e=document.querySelector({sel});return e?e.value:''}})()",
|
||||
"(function(){{var e=document.querySelector({sel});return e?e.value.length:-1}})()",
|
||||
sel = serde_json::to_string(selector).unwrap_or_default(),
|
||||
);
|
||||
let final_value = self.evaluate_raw(&verify_js).await.unwrap_or_default();
|
||||
let length = self.tab.evaluate(&verify_js).await.unwrap_or_default();
|
||||
|
||||
tokio::time::sleep(Duration::from_millis(wait_ms)).await;
|
||||
|
||||
Ok(json!({
|
||||
"filled": true,
|
||||
"selector": selector,
|
||||
"value": final_value,
|
||||
"value_set": length == value.chars().count().to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
async fn get_content(&mut self) -> Result<serde_json::Value, String> {
|
||||
let title = self
|
||||
.evaluate_raw("document.title")
|
||||
.tab
|
||||
.evaluate("document.title")
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let url = self
|
||||
.evaluate_raw("window.location.href")
|
||||
.tab
|
||||
.evaluate("window.location.href")
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
|
||||
@@ -528,7 +391,7 @@ impl BrowserSession {
|
||||
return JSON.stringify(result);
|
||||
})()"#;
|
||||
|
||||
let summary = self.evaluate_raw(summary_js).await.unwrap_or_default();
|
||||
let summary = self.tab.evaluate(summary_js).await.unwrap_or_default();
|
||||
let page_data: serde_json::Value = serde_json::from_str(&summary).unwrap_or(json!({}));
|
||||
|
||||
Ok(json!({
|
||||
@@ -539,49 +402,14 @@ impl BrowserSession {
|
||||
}
|
||||
|
||||
async fn evaluate(&mut self, expression: &str) -> Result<serde_json::Value, String> {
|
||||
let result = self.evaluate_raw(expression).await?;
|
||||
let result = self.tab.evaluate(expression).await?;
|
||||
Ok(json!({
|
||||
"result": result,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Execute JS and return the string result.
|
||||
async fn evaluate_raw(&mut self, expression: &str) -> Result<String, String> {
|
||||
let resp = cdp_send_session(
|
||||
&mut self.ws,
|
||||
self.next_id,
|
||||
&self.session_id,
|
||||
"Runtime.evaluate",
|
||||
json!({
|
||||
"expression": expression,
|
||||
"returnByValue": true,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
self.next_id += 1;
|
||||
|
||||
let result = resp
|
||||
.get("result")
|
||||
.and_then(|r| r.get("result"))
|
||||
.and_then(|r| r.get("value"));
|
||||
|
||||
match result {
|
||||
Some(serde_json::Value::String(s)) => Ok(s.clone()),
|
||||
Some(v) => Ok(v.to_string()),
|
||||
None => Ok(String::new()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn close(&mut self) -> Result<(), String> {
|
||||
let _ = cdp_send(
|
||||
&mut self.ws,
|
||||
self.next_id,
|
||||
"Target.closeTarget",
|
||||
json!({ "targetId": self.target_id }),
|
||||
)
|
||||
.await;
|
||||
let _ = self.ws.close(None).await;
|
||||
Ok(())
|
||||
async fn close(&mut self) {
|
||||
self.tab.close().await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -589,62 +417,37 @@ impl BrowserSession {
|
||||
pub async fn cleanup_browser_session(session_id: &str) {
|
||||
let mut pool = BROWSER_SESSIONS.lock().await;
|
||||
if let Some(mut sess) = pool.remove(session_id) {
|
||||
let _ = sess.close().await;
|
||||
sess.close().await;
|
||||
}
|
||||
}
|
||||
|
||||
// ── CDP helpers ──
|
||||
|
||||
async fn cdp_send(
|
||||
ws: &mut WsStream,
|
||||
id: u64,
|
||||
method: &str,
|
||||
params: serde_json::Value,
|
||||
) -> Result<serde_json::Value, String> {
|
||||
let msg = json!({ "id": id, "method": method, "params": params });
|
||||
ws.send(Message::Text(msg.to_string().into()))
|
||||
.await
|
||||
.map_err(|e| format!("WS send failed: {e}"))?;
|
||||
read_until_result(ws, id).await
|
||||
}
|
||||
|
||||
async fn cdp_send_session(
|
||||
ws: &mut WsStream,
|
||||
id: u64,
|
||||
session_id: &str,
|
||||
method: &str,
|
||||
params: serde_json::Value,
|
||||
) -> Result<serde_json::Value, String> {
|
||||
let msg = json!({
|
||||
"id": id,
|
||||
"sessionId": session_id,
|
||||
"method": method,
|
||||
"params": params,
|
||||
});
|
||||
ws.send(Message::Text(msg.to_string().into()))
|
||||
.await
|
||||
.map_err(|e| format!("WS send failed: {e}"))?;
|
||||
read_until_result(ws, id).await
|
||||
}
|
||||
|
||||
async fn read_until_result(ws: &mut WsStream, id: u64) -> Result<serde_json::Value, String> {
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
let msg = tokio::time::timeout_at(deadline, ws.next())
|
||||
.await
|
||||
.map_err(|_| format!("Timeout waiting for CDP response id={id}"))?
|
||||
.ok_or_else(|| "WebSocket closed unexpectedly".to_string())?
|
||||
.map_err(|e| format!("WebSocket read error: {e}"))?;
|
||||
|
||||
if let Message::Text(text) = msg {
|
||||
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&text) {
|
||||
if val.get("id").and_then(|i| i.as_u64()) == Some(id) {
|
||||
if let Some(err) = val.get("error") {
|
||||
return Err(format!("CDP error: {err}"));
|
||||
}
|
||||
return Ok(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Replace the content of the field at `selector` with `text`, typed through
|
||||
/// CDP input events: `text` never becomes part of a script, so a password
|
||||
/// cannot leak through one. `false` when no element matches.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// A CDP command failed.
|
||||
async fn type_into(tab: &mut CdpTab, selector: &str, text: &str) -> Result<bool, String> {
|
||||
let focus_js = format!(
|
||||
"(function(){{var e=document.querySelector({sel});\
|
||||
if(!e)return 'notfound';e.focus();if(e.select)e.select();return 'ok'}})()",
|
||||
sel = serde_json::to_string(selector).unwrap_or_default(),
|
||||
);
|
||||
if tab.evaluate(&focus_js).await? == "notfound" {
|
||||
return Ok(false);
|
||||
}
|
||||
// Select all (Ctrl+A) and delete, then insert the text in one command.
|
||||
let keys = [
|
||||
json!({"type": "keyDown", "key": "a", "code": "KeyA", "modifiers": 2}),
|
||||
json!({"type": "keyUp", "key": "a", "code": "KeyA", "modifiers": 2}),
|
||||
json!({"type": "keyDown", "key": "Backspace", "code": "Backspace"}),
|
||||
json!({"type": "keyUp", "key": "Backspace", "code": "Backspace"}),
|
||||
];
|
||||
for key in keys {
|
||||
tab.call("Input.dispatchKeyEvent", key).await?;
|
||||
}
|
||||
tab.call("Input.insertText", json!({ "text": text }))
|
||||
.await?;
|
||||
Ok(true)
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
//! Every DAST scan runs the fixed checks (#998): a site without a
|
||||
//! Content-Security-Policy and with a session cookie lacking its flags gets
|
||||
//! those findings, and a site that sends a policy does not get the missing
|
||||
//! one.
|
||||
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use axum::http::header::{CONTENT_SECURITY_POLICY, SET_COOKIE};
|
||||
use axum::response::IntoResponse;
|
||||
use axum::Router;
|
||||
use compliance_core::models::dast::{DastFinding, DastTarget, DastTargetType, DastVulnType};
|
||||
use compliance_core::NetGuard;
|
||||
use compliance_dast::DastOrchestrator;
|
||||
|
||||
async fn serve(app: Router) -> String {
|
||||
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}")
|
||||
}
|
||||
|
||||
async fn scan(base: &str) -> Vec<DastFinding> {
|
||||
let mut target = DastTarget::new("site".into(), base.into(), DastTargetType::WebApp);
|
||||
target.max_crawl_depth = 1;
|
||||
let (_run, findings) = DastOrchestrator::new(0, NetGuard::allow_private())
|
||||
.run_scan(&target, Vec::new())
|
||||
.await
|
||||
.unwrap();
|
||||
findings
|
||||
}
|
||||
|
||||
fn missing_csp(findings: &[DastFinding]) -> bool {
|
||||
findings
|
||||
.iter()
|
||||
.any(|f| f.vuln_type == DastVulnType::CspIssue && f.title.contains("Missing"))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_site_without_a_policy_gets_the_header_and_cookie_findings() {
|
||||
let base = serve(Router::new().fallback(|| async {
|
||||
(
|
||||
[(SET_COOKIE, "session=abc")],
|
||||
"<html><body>shop</body></html>",
|
||||
)
|
||||
.into_response()
|
||||
}))
|
||||
.await;
|
||||
|
||||
let findings = scan(&base).await;
|
||||
|
||||
assert!(missing_csp(&findings), "{findings:#?}");
|
||||
assert!(
|
||||
findings
|
||||
.iter()
|
||||
.any(|f| f.vuln_type == DastVulnType::CookieSecurity),
|
||||
"{findings:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_site_with_a_policy_does_not_get_the_missing_one() {
|
||||
let base = serve(Router::new().fallback(|| async {
|
||||
(
|
||||
[(CONTENT_SECURITY_POLICY, "default-src 'self'")],
|
||||
"<html><body>shop</body></html>",
|
||||
)
|
||||
.into_response()
|
||||
}))
|
||||
.await;
|
||||
|
||||
assert!(!missing_csp(&scan(&base).await));
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
//! A DAST scan logs in with the target's credentials (#1000), stays on the
|
||||
//! target's origin, and never sends a write method unless destructive tests
|
||||
//! are allowed.
|
||||
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use axum::extract::{Request, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{Html, IntoResponse, Response};
|
||||
use axum::Router;
|
||||
use compliance_core::models::dast::{DastAuthConfig, DastScanStatus, DastTarget, DastTargetType};
|
||||
use compliance_core::NetGuard;
|
||||
use compliance_dast::crawler::WebCrawler;
|
||||
use compliance_dast::DastOrchestrator;
|
||||
|
||||
/// What the fake site saw: method, path, and whether the login came along.
|
||||
type Seen = Arc<Mutex<Vec<(String, String, bool)>>>;
|
||||
|
||||
const TOKEN: &str = "Bearer t0ken";
|
||||
|
||||
/// A site whose pages are only for a logged-in visitor. `/` links to
|
||||
/// `/secret` and carries a form to itself, one to another site and one to
|
||||
/// another port of the same host.
|
||||
async fn fake_site(seen: Seen) -> String {
|
||||
async fn any(State(seen): State<Seen>, request: Request) -> Response {
|
||||
let authed = request
|
||||
.headers()
|
||||
.get("authorization")
|
||||
.is_some_and(|v| v == TOKEN);
|
||||
let path = request.uri().path().to_string();
|
||||
seen.lock()
|
||||
.unwrap()
|
||||
.push((request.method().to_string(), path.clone(), authed));
|
||||
if !authed {
|
||||
return StatusCode::UNAUTHORIZED.into_response();
|
||||
}
|
||||
match path.as_str() {
|
||||
"/" => Html(
|
||||
r#"<html><body>
|
||||
<a href="/secret">secret</a>
|
||||
<form action="/search" method="get"><input name="q"></form>
|
||||
<form action="https://elsewhere.invalid/steal" method="post"><input name="x"></form>
|
||||
<form action="http://127.0.0.1:1/other" method="post"><input name="y"></form>
|
||||
</body></html>"#,
|
||||
)
|
||||
.into_response(),
|
||||
"/secret" => Html("<html><body>only for members</body></html>").into_response(),
|
||||
_ => StatusCode::NOT_FOUND.into_response(),
|
||||
}
|
||||
}
|
||||
let app = Router::new().fallback(any).with_state(seen);
|
||||
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}")
|
||||
}
|
||||
|
||||
fn bearer() -> DastAuthConfig {
|
||||
DastAuthConfig {
|
||||
method: "bearer".into(),
|
||||
login_url: None,
|
||||
username: None,
|
||||
password: None,
|
||||
token: Some("t0ken".into()),
|
||||
headers: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn target(base: &str, auth: Option<DastAuthConfig>) -> DastTarget {
|
||||
let mut t = DastTarget::new("site".into(), base.into(), DastTargetType::WebApp);
|
||||
t.auth_config = auth;
|
||||
t.max_crawl_depth = 2;
|
||||
t
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_logged_in_crawl_reaches_member_pages_and_keeps_to_the_origin() {
|
||||
let seen: Seen = Arc::default();
|
||||
let base = fake_site(seen.clone()).await;
|
||||
let headers = compliance_dast::auth::login_headers(Some(&bearer())).unwrap();
|
||||
let http = reqwest::Client::builder()
|
||||
.default_headers(headers)
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
let endpoints = WebCrawler::new(http, 2, 0).crawl(&base, &[]).await.unwrap();
|
||||
|
||||
let urls: Vec<&str> = endpoints.iter().map(|e| e.url.as_str()).collect();
|
||||
assert!(
|
||||
urls.contains(&format!("{base}/secret").as_str()),
|
||||
"{urls:?}"
|
||||
);
|
||||
assert!(
|
||||
urls.contains(&format!("{base}/search").as_str()),
|
||||
"{urls:?}"
|
||||
);
|
||||
assert!(
|
||||
urls.iter().all(|u| u.starts_with(&base)),
|
||||
"a form to another site or port is out of scope: {urls:?}"
|
||||
);
|
||||
assert!(endpoints.iter().all(|e| !e.requires_auth));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_scan_sends_the_login_except_for_the_strangers_checks() {
|
||||
let seen: Seen = Arc::default();
|
||||
let base = fake_site(seen.clone()).await;
|
||||
|
||||
let (run, _findings) = DastOrchestrator::new(0, NetGuard::allow_private())
|
||||
.run_scan(&target(&base, Some(bearer())), Vec::new())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
run.status,
|
||||
DastScanStatus::Completed,
|
||||
"{:?}",
|
||||
run.error_message
|
||||
);
|
||||
let seen = seen.lock().unwrap();
|
||||
assert!(
|
||||
seen.iter().any(|(_, p, authed)| p == "/secret" && *authed),
|
||||
"the member page was asked for with the login: {seen:?}"
|
||||
);
|
||||
// The auth-bypass agent's path probes ask as a stranger.
|
||||
assert!(
|
||||
seen.iter()
|
||||
.filter(|(_, p, _)| p.eq_ignore_ascii_case("/admin"))
|
||||
.all(|(_, _, authed)| !authed),
|
||||
"{seen:?}"
|
||||
);
|
||||
// Destructive tests are off: no write method reached the site.
|
||||
assert!(
|
||||
seen.iter()
|
||||
.all(|(m, _, _)| !["PUT", "PATCH", "DELETE"].contains(&m.as_str())),
|
||||
"{seen:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unusable_login_fails_the_scan_before_any_request() {
|
||||
let seen: Seen = Arc::default();
|
||||
let base = fake_site(seen.clone()).await;
|
||||
let mut form = bearer();
|
||||
form.method = "form".into();
|
||||
|
||||
let (run, findings) = DastOrchestrator::new(0, NetGuard::allow_private())
|
||||
.run_scan(&target(&base, Some(form)), Vec::new())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(run.status, DastScanStatus::Failed);
|
||||
assert_eq!(
|
||||
run.error_message.as_deref(),
|
||||
Some("Login: form login is not supported yet")
|
||||
);
|
||||
assert!(findings.is_empty());
|
||||
assert!(seen.lock().unwrap().is_empty());
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
//! robots.txt is public by design: only sensitive paths it names that answer
|
||||
//! with their own content are worth a finding, and only an Info one (#997).
|
||||
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::get;
|
||||
use axum::Router;
|
||||
use compliance_core::models::dast::{DastTarget, DastTargetType};
|
||||
use compliance_core::models::Severity;
|
||||
use compliance_core::traits::dast_agent::{DastAgent, DastContext};
|
||||
use compliance_dast::agents::api_fuzzer::ApiFuzzerAgent;
|
||||
|
||||
const ROBOTS: &str = "User-agent: *\nDisallow: /\nDisallow: /admin\n";
|
||||
|
||||
async fn serve(app: Router) -> String {
|
||||
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}")
|
||||
}
|
||||
|
||||
/// The robots.txt findings of a scan of `base`.
|
||||
async fn robots_findings(base: &str) -> Vec<(String, Severity)> {
|
||||
let target = DastTarget::new("site".into(), base.into(), DastTargetType::WebApp);
|
||||
let context = DastContext {
|
||||
endpoints: Vec::new(),
|
||||
technologies: Vec::new(),
|
||||
sast_hints: Vec::new(),
|
||||
};
|
||||
ApiFuzzerAgent::new(reqwest::Client::new())
|
||||
.run(&target, &context)
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.filter(|f| f.title.contains("robots.txt"))
|
||||
.map(|f| (f.title, f.severity))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_reachable_sensitive_path_is_an_info_finding() {
|
||||
let base = serve(
|
||||
Router::new()
|
||||
.route("/robots.txt", get(|| async { ROBOTS }))
|
||||
.route("/admin", get(|| async { "admin console" }))
|
||||
.fallback(|| async { StatusCode::NOT_FOUND }),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
robots_findings(&base).await,
|
||||
[(
|
||||
"robots.txt names reachable sensitive paths".to_string(),
|
||||
Severity::Info
|
||||
)]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_single_page_apps_catch_all_is_no_finding() {
|
||||
async fn shell() -> Response {
|
||||
"<html><div id=main></div></html>".into_response()
|
||||
}
|
||||
let base = serve(
|
||||
Router::new()
|
||||
.route("/robots.txt", get(|| async { ROBOTS }))
|
||||
.fallback(shell),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(robots_findings(&base).await.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disallow_everything_is_no_finding() {
|
||||
let base = serve(
|
||||
Router::new()
|
||||
.route(
|
||||
"/robots.txt",
|
||||
get(|| async { "User-agent: *\nDisallow: /\n" }),
|
||||
)
|
||||
.fallback(|| async { StatusCode::NOT_FOUND }),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(robots_findings(&base).await.is_empty());
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "compliance-graph"
|
||||
version = "0.4.6"
|
||||
version = "0.4.16"
|
||||
edition = "2021"
|
||||
|
||||
[lints]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "compliance-mcp"
|
||||
version = "0.4.6"
|
||||
version = "0.4.16"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "compliance-smoke"
|
||||
version = "0.4.6"
|
||||
version = "0.4.16"
|
||||
edition = "2021"
|
||||
description = "Tiny Axum service exercising compliance-core M7.1 tenant gating. Run smoke.sh against it before merging anything that touches the auth/tenant path."
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "control-map"
|
||||
version = "0.4.6"
|
||||
version = "0.4.16"
|
||||
edition = "2021"
|
||||
|
||||
[lints]
|
||||
|
||||
@@ -137,6 +137,18 @@
|
||||
"yocto-local-conf-no-security-flags"
|
||||
],
|
||||
"check": "The image's shipped configuration must be secure by default: an sshd_config that permits root or password logins, or a distro built without security_flags.inc (stack protector, FORTIFY_SOURCE, PIE, RELRO), violates it."
|
||||
},
|
||||
{
|
||||
"tool": "dast",
|
||||
"scan_type": "dast",
|
||||
"languages": [],
|
||||
"cwe": [
|
||||
"CWE-16",
|
||||
"CWE-693"
|
||||
],
|
||||
"rules": [],
|
||||
"check": "The running application leaves a browser protection off by default: a missing or weak Content-Security-Policy or another missing security header on what it serves.",
|
||||
"attach_only": true
|
||||
}
|
||||
],
|
||||
"note": null,
|
||||
@@ -1254,6 +1266,29 @@
|
||||
"legacy-build-system-no-sbom"
|
||||
],
|
||||
"check": "The product's components must be declared in a machine-readable form an SBOM can be built from; a build system that declares none (Eclipse/ADT, Unity without its package manifest) violates it."
|
||||
},
|
||||
{
|
||||
"tool": "sbom-coverage",
|
||||
"scan_type": "sbom",
|
||||
"languages": [
|
||||
"python",
|
||||
"javascript",
|
||||
"typescript",
|
||||
"rust",
|
||||
"go",
|
||||
"java",
|
||||
"kotlin",
|
||||
"csharp",
|
||||
"php",
|
||||
"ruby",
|
||||
"dart"
|
||||
],
|
||||
"cwe": [],
|
||||
"rules": [
|
||||
"sbom-no-manifest",
|
||||
"sbom-dependencies-unresolved"
|
||||
],
|
||||
"check": "The product's components must be declared in a manifest or lockfile an SBOM can be built from; code in a language with a package manager and no manifest, or a manifest whose dependencies are not resolved, violates it."
|
||||
}
|
||||
],
|
||||
"note": null,
|
||||
|
||||
+27
-3
@@ -231,6 +231,29 @@ mod tests {
|
||||
assert!(map.controls_for_cwe("CWE-0").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_content_security_policy_is_evidence_for_secure_defaults() {
|
||||
// DAST reports a missing CSP as CWE-16 and a missing protection
|
||||
// mechanism as CWE-693 (#998). Neither makes the control count as
|
||||
// checked: the DAST checks look at what one URL serves.
|
||||
let map = ControlMap::cra().expect("map");
|
||||
for cwe in ["CWE-16", "CWE-693"] {
|
||||
let ids: Vec<&str> = map
|
||||
.controls_for_cwe(cwe)
|
||||
.iter()
|
||||
.map(|c| c.control.as_str())
|
||||
.collect();
|
||||
assert_eq!(ids, ["cra-ai-1"], "{cwe}");
|
||||
}
|
||||
let dast = map
|
||||
.coverage("cra-ai-1")
|
||||
.and_then(|c| c.scans.iter().find(|s| s.tool == "dast"))
|
||||
.expect("a dast binding");
|
||||
assert!(dast.attach_only);
|
||||
// So the CRA status never reads "checked" because of it.
|
||||
assert!(!dast.applies_to(&["python".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cra_map_loads_all_40_controls() {
|
||||
let map = ControlMap::cra().expect("CRA map should parse");
|
||||
@@ -306,14 +329,15 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn every_code_binding_names_its_languages() {
|
||||
// Only tools that do not read source code may be language-independent;
|
||||
// a rule binding without languages would claim every language.
|
||||
// Only tools that do not read source code may be language-independent
|
||||
// (DAST tests the running application); a rule binding without
|
||||
// languages would claim every language.
|
||||
let map = ControlMap::cra().expect("map");
|
||||
for control in &map.controls {
|
||||
for scan in &control.scans {
|
||||
let reads_code = !matches!(
|
||||
scan.tool.as_str(),
|
||||
"gitleaks" | "secret-files" | "syft" | "osv" | "binary-inventory"
|
||||
"gitleaks" | "secret-files" | "syft" | "osv" | "binary-inventory" | "dast"
|
||||
);
|
||||
assert_eq!(
|
||||
reads_code,
|
||||
|
||||
@@ -52,7 +52,7 @@ export default withMermaid(defineConfig({
|
||||
{ text: 'Stückliste (SBOM) und Lizenzen', link: '/guide/sbom' },
|
||||
{ text: 'Schwachstellen bewerten (VEX)', link: '/guide/vex' },
|
||||
{ text: 'Assessing vulnerabilities (English)', link: '/guide/vex-en' },
|
||||
{ text: 'CRA-Anforderungen', link: '/features/control-mapping' },
|
||||
{ text: 'Bezug zu CRA-Themen', link: '/features/control-mapping' },
|
||||
{ text: 'Daten und Aufbewahrung', link: '/guide/data-retention' },
|
||||
],
|
||||
},
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
# Compliance Control Mapping
|
||||
|
||||
::: info Technical hint, not a legal assessment
|
||||
The link between a finding and a CRA topic is a technical hint from the scan.
|
||||
It is not a legal assessment and not a conformity assessment.
|
||||
:::
|
||||
|
||||
Control mapping connects the scanner's raw output — deterministic tool findings and the code itself — to the **compliance controls** each piece of evidence supports. A hardcoded credential stops being just "CWE-798 from semgrep" and becomes evidence for *"cra-ai-8: no default passwords"* and, at scale, master control *`mc-31761` hardcoded_secrets_detection*. Findings carry those references (`control_refs`) into the dashboard and out over the MCP server as OSCAL, so the compliance report is built from real, grounded findings rather than a questionnaire.
|
||||
|
||||
## The core principle: tools detect, the LLM judges
|
||||
@@ -31,6 +36,7 @@ For the **CRA** framework (40 controls) the split is **21 covered · 0 needs_too
|
||||
- **mobsfscan** for Android and iOS apps, bound **by CWE** (a mobsfscan binding only ever attaches mobsfscan findings): `cra-ai-1` (debuggable, exported components, outdated `minSdkVersion`), `7`, `8`, `9`, `13`, `14`, `15` (cleartext, TLS, App Transport Security), `16` and `20`. Each binding lists only the languages mobsfscan has rules for under those CWEs, so `cra-ai-1` covers Java and Kotlin (its manifest checks) but not Swift.
|
||||
- **DevSkim** for C# and VB.NET (#494), bound **by CWE** (each DevSkim rule gets its CWE in `pipeline/devskim.rs`; its SARIF carries none): `cra-ai-1` (tracing), `8`, `10` (cookies without Secure), `13`, `14` (DPAPI without entropy), `15`, `16` and `20` (deserialisation, XXE).
|
||||
- **Yocto recipe lint** (oelint-adv and our `yocto-config` rules), bound **by rule id** with the language `bitbake`: `cra-ai-1` (debug and root-login image features, sshd root/password logins, a distro without `security_flags.inc`), `cra-ai-8` (empty-password image features, passwords in `EXTRA_USERS_PARAMS`) `cra-ai-6` (downloads without a checksum, `AUTOREV`, git tags) and `cra-ai-2` (network access in tasks, `http://` fetches). `cra-ai-2` stays not code-checkable; these are its only bindings, so the CRA status assesses it only where the scanned languages include `bitbake` (a Yocto layer tree), and shows it as not code-checkable everywhere else.
|
||||
- **DAST** (#998), bound **by CWE** and `attach_only`: `cra-ai-1` for a missing or weak Content-Security-Policy (CWE-16) and a missing protection mechanism (CWE-693) on what the running application serves. The DAST checks look at one URL, so the binding attaches these findings to the control but never makes it count as checked. DAST findings with other CWEs get the controls any binding lists for their CWE.
|
||||
- **8 grounded surface checks** (`cra-ai-6`, `11`, `12`, `24`, `27`, `28`, `29`, `30`): the absence-based controls (no rate limiting, no security logging, no update-signature check…) that have no syntactic pattern.
|
||||
- **Marked not_code_checkable** (`cra-ai-2`, `3`, `4`, `5`, among the 19): minimal attack surface, secure architecture, least privilege, tamper protection. A not-code-checkable control with a binding that applies to the scanned languages is assessed like a covered one there; today that is only `cra-ai-2` on Yocto layer trees.
|
||||
|
||||
|
||||
+23
-10
@@ -39,15 +39,21 @@ Each target supports these settings:
|
||||
|
||||
### Authentication
|
||||
|
||||
DAST supports authenticated scanning so it can test pages behind login:
|
||||
A scan can log in, so it reaches the pages and API routes behind a login. Every request of the crawl and of the tests carries the login. The exception is the authentication-bypass checks, which ask as a stranger on purpose.
|
||||
|
||||
| Method | Description |
|
||||
|--------|------------|
|
||||
| **None** | No authentication |
|
||||
| **Basic** | HTTP Basic Auth with username and password |
|
||||
| **Bearer** | Bearer token in the Authorization header |
|
||||
| **Cookie** | Session cookie value |
|
||||
| **Form** | Login form with URL, field names, and credentials |
|
||||
| Method | What is sent | Fields |
|
||||
|--------|--------------|--------|
|
||||
| **None** | nothing | – |
|
||||
| **Basic** | `Authorization: Basic …` | `username`, `password` |
|
||||
| **Bearer** | `Authorization: Bearer …` | `token` |
|
||||
| **Cookie** | `Cookie: …` | `token` (e.g. `session=abc123`) |
|
||||
| **Form** | not available yet: logging in through a login page (incl. Keycloak) is the next step | – |
|
||||
|
||||
Every method can add extra headers (`headers`, e.g. an API key). The password, the token and the header values are stored encrypted and never returned by the API.
|
||||
|
||||
A login that cannot be sent fails the scan with the reason ("Login: …"); the scan never runs without the login instead. Through the API, the login goes in the `auth` block of `POST /api/v1/dast/targets`, and the answer returns the new target with its id.
|
||||
|
||||
The scan stays on the target's origin (scheme, host and port): links and forms that lead elsewhere are not followed. Write requests (`PUT`, `PATCH`, `DELETE`) are sent only when **Destructive Tests** is on.
|
||||
|
||||
::: warning
|
||||
Authenticated scans access more of the application surface. Only test applications you own or have explicit authorization to test.
|
||||
@@ -58,8 +64,15 @@ Authenticated scans access more of the application surface. Only test applicatio
|
||||
Click the **Scan** button on any target row. The scan progresses through:
|
||||
|
||||
1. **Crawl** -- discovers pages, forms, and API endpoints by following links and analyzing JavaScript
|
||||
2. **Test** -- sends attack payloads to discovered parameters
|
||||
3. **Report** -- collects results and generates findings
|
||||
2. **Check** -- fixed checks of what the base URL sends: security headers, Content-Security-Policy, cookie flags (`Secure`, `HttpOnly`, `SameSite`) and TLS. They follow fixed rules, so the same site gives the same findings in every scan.
|
||||
3. **Test** -- sends attack payloads to discovered parameters
|
||||
4. **Report** -- collects results and generates findings
|
||||
|
||||
### DAST in a target's scan
|
||||
|
||||
A target with a live URL gets a DAST scan in each of its scans, where the deployment runs DAST. The scan waits for it like for its other stages. When the DAST scan does not complete (the site cannot be reached, the login cannot be sent, or it takes longer than 20 minutes), the scan shows the DAST stage as not completed. The rest of the scan is not affected, and the DAST run keeps the reason.
|
||||
|
||||
Its findings are findings of the target too: they appear in the target's findings list with the other findings (scanner `dast`), count as new findings of the scan, and carry the CRA controls their CWE is evidence for. A later scan that finds the same weakness at the same endpoint, method and parameter does not add it again. The request and response evidence stays with the finding under **DAST > Findings**. When exactly one open code finding of the target has the same CWE, the DAST finding is linked to it, so it shows the file and line where the weakness likely is. With several, the CWE alone does not say which one, so it stays unlinked.
|
||||
|
||||
## Viewing DAST Findings
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ Click **New Pentest** on the dashboard to open the 4-step onboarding wizard:
|
||||
- **Registration URL** (optional) — auto-discovered via Playwright if omitted
|
||||
- **Verification Email** (optional) — override the agent's default mailbox. Uses plus-addressing (`base+sessionid@domain`) and polls IMAP for verification links
|
||||
- **IMAP Settings** — collapsible section to override host/port/credentials
|
||||
- **Delete the test user afterwards** — deletes the account in the application's own identity provider when the session ends. It needs admin access to that provider, given for the session through the API (`config.auth.cleanup`): a Keycloak realm (a client whose service account may manage users), an Auth0 tenant (a machine-to-machine application with `read:users` and `delete:users`) or an Okta org (an API token). The account is found by the session's own address and deleted only if exactly one account carries it. Without that access, or if the provider refuses, the report lists the test user as **left behind**, to be deleted by hand. Prüfwerk never uses its own login service for this.
|
||||
|
||||
### Step 3 — Strategy & Instructions
|
||||
|
||||
|
||||
@@ -39,6 +39,10 @@ Person vorbehalten.
|
||||
|
||||
## Gut zu wissen
|
||||
|
||||
- **API-Beschreibung:** `GET /api/v1/openapi.json` liefert die Beschreibung
|
||||
der API als OpenAPI 3.1, aus dem Code erzeugt. Sie wächst Route für Route;
|
||||
noch nicht beschriebene Routen fehlen darin. Sie ist mit der Anmeldung
|
||||
einer Person erreichbar, noch nicht mit einem API-Schlüssel.
|
||||
- **Nicht für MCP.** Ein LLM-Werkzeug (Claude Code, Cursor, …) meldet sich an
|
||||
der MCP-Schnittstelle mit einem eigenen MCP-Token (`mcpt_…`) an, nicht mit
|
||||
einem API-Schlüssel. MCP-Tokens legt eine angemeldete Person im Dashboard
|
||||
|
||||
+21
-2
@@ -75,8 +75,8 @@ in this order:
|
||||
- **Beschreibung** (Description) -- what the issue is.
|
||||
- **Fundstelle** (Location) -- the **Prüfobjekt** (a click opens its CRA
|
||||
status), **Datei** (file and line), **Werkzeug** (tool), **Regel** (rule) and
|
||||
**CRA-Anforderungen (Anhang I)**: the CRA Annex I requirements the finding is
|
||||
mapped to, each with its title. Controls from the BreakPilot catalog are
|
||||
**CRA-Themen (Anhang I)**: the CRA Annex I topics the finding points to (a
|
||||
technical hint, not a legal assessment), each with its title. Controls from the BreakPilot catalog are
|
||||
folded under **+N Kontrollen aus dem BreakPilot-Katalog**; click it to see
|
||||
each control with what it requires.
|
||||
- **Einschätzung** (Triage rationale) -- the automated review's reasoning, where
|
||||
@@ -93,6 +93,24 @@ in this order:
|
||||
- **Ihre Einschätzung** (Developer feedback) -- a free-text note, saved when you
|
||||
leave the field.
|
||||
|
||||
### Turning a finding into a ticket
|
||||
|
||||
Below the badges, **Als Ticket-Text kopieren** (Copy as ticket text) copies
|
||||
this one finding to the clipboard as Markdown: title, severity, status,
|
||||
location (file and line), description, the automated review's assessment, the
|
||||
**CRA-Themen** (CRA topics) and a link back to the finding in Prüfwerk. Paste
|
||||
it into a new ticket in any tracker; **Kopiert** (Copied) confirms the copy.
|
||||
The labels follow the dashboard's language, and a committed secret is
|
||||
shortened as on the page.
|
||||
|
||||
When the finding's target has no issue tracker connected and the finding has
|
||||
no ticket yet, a hint beside the button reads "Mit Breakpilot Git werden
|
||||
Tickets automatisch angelegt" (With Breakpilot Git, tickets are created
|
||||
automatically). It links to
|
||||
[Connecting an Issue Tracker](/guide/repositories#connecting-an-issue-tracker)
|
||||
and to [Managed Git](/guide/managed-git). A target counts as connected when an
|
||||
issue tracker is configured on it or its repository comes from Managed Git.
|
||||
|
||||
## Severity Levels
|
||||
|
||||
| Severity | Description | Typical Examples |
|
||||
@@ -116,6 +134,7 @@ The most common types in a scan of source code:
|
||||
| **OAuth** | Prüfwerk's own pattern rules |
|
||||
| **Code-Qualität** (Lint) | Linters, where the deployment runs them |
|
||||
| **SPS-Steuerungslogik** (PLC control logic) | Prüfwerk's PLC analyser, see [SPS / PLC (CODESYS)](/guide/plc) |
|
||||
| **Vollständigkeit der Stückliste** (SBOM completeness) | Code without a manifest or lockfile, and manifests whose dependencies were not resolved, see [SBOM](/guide/sbom#when-the-sbom-is-empty-or-incomplete) |
|
||||
| **Penetrationstest**, **Dynamische Prüfung (DAST)** | Entered or imported by hand, see [Befunde aus manuellen Tests](/guide/manual-findings) |
|
||||
|
||||
## Statuses
|
||||
|
||||
@@ -17,8 +17,8 @@ in the sidebar switches it to English.
|
||||
- **PLC control logic** -- security rules for IEC 61131-3 programs
|
||||
- **AI triage** -- an LLM reviews each new finding and gives a confidence,
|
||||
a rationale and a remediation; findings it doubts are marked for review
|
||||
- **CRA mapping** -- findings are assigned to the CRA Annex I requirements they
|
||||
are evidence for
|
||||
- **CRA topics** -- each finding is linked to the CRA Annex I topics it points
|
||||
to (a technical hint, not a legal assessment)
|
||||
|
||||
## The Overview
|
||||
|
||||
@@ -35,11 +35,11 @@ What you can do in Prüfwerk depends on your role in the workspace:
|
||||
|
||||
| Role | Prüfwerk |
|
||||
| --- | --- |
|
||||
| `IT_ADMIN`, `USER` | everything: add targets, run scans, triage findings |
|
||||
| `CXO`, `LEGAL` | read only: view and export findings, reports, SBOM, evidence |
|
||||
| `FINANCE`, or none of these | no access |
|
||||
| `OWNER`, `IT_ADMIN`, `USER`, `PSIRT`, `DEVELOPMENT` | everything: add targets, run scans, triage findings |
|
||||
| `CXO`, `LEGAL`, `QUALITY`, `PURCHASING`, `AUDITOR` | read only: view and export findings, reports, SBOM, evidence |
|
||||
| `FINANCE`, `PRIVACY`, `EXTERNAL`, or none of these | no access |
|
||||
|
||||
Only `IT_ADMIN` can add or import findings by hand.
|
||||
Only `IT_ADMIN` and `OWNER` can add or import findings by hand.
|
||||
|
||||
## Quick Walkthrough
|
||||
|
||||
@@ -67,7 +67,7 @@ again later, click **Prüfung starten** (Run scan) in the target's row on the
|
||||
### 3. View findings
|
||||
|
||||
Open **Befunde** (Findings) in the sidebar. Each finding has a severity, a
|
||||
description, the code where it was found, the CRA requirements it concerns and,
|
||||
description, the code where it was found, the CRA topics it points to and,
|
||||
where available, a remediation. Record your decision with the status buttons.
|
||||
|
||||
## Next Steps
|
||||
|
||||
@@ -38,9 +38,9 @@ Was Sie in Prüfwerk tun können, hängt von Ihrer Rolle im Arbeitsbereich ab:
|
||||
|
||||
| Rolle | Prüfwerk |
|
||||
| --- | --- |
|
||||
| IT-Administration (`IT_ADMIN`), Benutzer (`USER`) | alles: Prüfobjekte anlegen, prüfen, Befunde bewerten |
|
||||
| Geschäftsführung (`CXO`), Recht (`LEGAL`) | nur lesen: Befunde, Berichte, Stückliste, Nachweise ansehen und exportieren |
|
||||
| Finanzen (`FINANCE`) oder keine dieser Rollen | kein Zugriff |
|
||||
| Inhaber (`OWNER`), IT-Administration (`IT_ADMIN`), Benutzer (`USER`), Produktsicherheit (`PSIRT`), Entwicklung (`DEVELOPMENT`) | alles: Prüfobjekte anlegen, prüfen, Befunde bewerten |
|
||||
| Geschäftsführung (`CXO`), Recht (`LEGAL`), Qualität (`QUALITY`), Einkauf (`PURCHASING`), Prüfer (`AUDITOR`) | nur lesen: Befunde, Berichte, Stückliste, Nachweise ansehen und exportieren |
|
||||
| Finanzen (`FINANCE`), Datenschutz (`PRIVACY`), Extern (`EXTERNAL`) oder keine dieser Rollen | kein Zugriff |
|
||||
|
||||
Befunde von Hand anlegen oder importieren kann nur die IT-Administration.
|
||||
|
||||
@@ -126,7 +126,7 @@ Zeile), das **Werkzeug**, das ihn gefunden hat, und in der Spalte **CRA** die
|
||||
Anforderungen, für die er relevant ist.
|
||||
|
||||
Ein Klick auf einen Befund öffnet die Einzelheiten: **Beschreibung**,
|
||||
**Fundstelle**, den betroffenen **Code**, die **CRA-Anforderungen (Anhang I)**
|
||||
**Fundstelle**, den betroffenen **Code**, die **CRA-Themen (Anhang I)**
|
||||
und, wo vorhanden, eine **Behebung**. Mit **Status ändern** halten Sie fest, wie
|
||||
Sie mit dem Befund umgehen, zum Beispiel **Behoben**, **Fehlalarm – Regel**
|
||||
(die Regel hat bei unproblematischem Code angeschlagen),
|
||||
@@ -172,7 +172,8 @@ dieses Prüfobjekts:
|
||||
„Geprüft, keine Befunde“ erscheint also nur dort, wo tatsächlich geprüft wurde.
|
||||
Befunde werden am Code nachgeprüft, bevor sie einer Anforderung zugeordnet
|
||||
werden. Der CRA-Status zeigt, welche Anforderungen im Code geprüft sind; er ist
|
||||
keine Konformitätsbewertung.
|
||||
keine Konformitätsbewertung. Die Zuordnung der Befunde ist ein technischer
|
||||
Hinweis, keine rechtliche Bewertung.
|
||||
|
||||
## 7. Nachweispaket
|
||||
|
||||
@@ -210,8 +211,8 @@ Sie echte Befunde, bevor Sie eigenen Code hochladen. Siehe
|
||||
CODESYS-Projekt auswertet
|
||||
- [Prüfungen](/guide/scanning): wie Prüfungen ausgelöst werden und welche
|
||||
Schritte sie haben
|
||||
- [CRA-Anforderungen](/features/control-mapping): wie Befunde den
|
||||
Anforderungen zugeordnet werden
|
||||
- [Bezug zu CRA-Themen](/features/control-mapping): wie Befunde mit den
|
||||
Themen des CRA verknüpft werden (technischer Hinweis)
|
||||
- [Daten und Aufbewahrung](/guide/data-retention): wo Prüfwerk Ihren Code und
|
||||
die Ergebnisse speichert und wann sie gelöscht werden
|
||||
|
||||
|
||||
@@ -80,3 +80,7 @@ Issues are deduplicated using the same fingerprint hash that deduplicates findin
|
||||
## Linked Issues in Finding Detail
|
||||
|
||||
When viewing a [finding's detail page](/guide/findings#finding-detail), you will see a **Verknüpftes Ticket** (Linked issue) section if an issue was created for that finding. This provides a direct link to the external tracker issue, making it easy to jump between the security context in Prüfwerk and the development workflow in your tracker.
|
||||
|
||||
## Without a Connected Tracker
|
||||
|
||||
Without a tracker, open the ticket by hand: **Als Ticket-Text kopieren** (Copy as ticket text) on the finding's page copies the finding as Markdown, ready to paste into a new ticket. On a target without a tracker the page also points to Breakpilot Git, where tickets are created automatically. See [Turning a finding into a ticket](/guide/findings#turning-a-finding-into-a-ticket).
|
||||
@@ -10,7 +10,7 @@ Two ways to add them, both on a target's details under **Targets**:
|
||||
- **Import a report**: a tool's report as a whole, in SARIF 2.1.0 or OWASP
|
||||
ZAP's JSON report.
|
||||
|
||||
Only the organisation's administrators (`IT_ADMIN`) can add or import findings.
|
||||
Only the organisation's administrators (`IT_ADMIN`, `OWNER`) can add or import findings.
|
||||
A tester working for a customer is invited into that customer's organisation
|
||||
with that role.
|
||||
|
||||
@@ -59,4 +59,4 @@ curl -X POST "$AGENT/api/v1/targets/$TARGET/findings/import?format=sarif&kind=pe
|
||||
|
||||
`format` is `sarif` or `zap`; `kind` is `pentest` or `dast`. The import answers
|
||||
with `{"total": …, "imported": …, "duplicates": …}`. A document that is not
|
||||
the named format is refused with 422, and a user without `IT_ADMIN` with 403.
|
||||
the named format is refused with 422, and a user without `IT_ADMIN` or `OWNER` with 403.
|
||||
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user