Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f231632ea | ||
|
|
045746488c | ||
|
|
48b1a4a47d | ||
|
|
bde53a96dd | ||
|
|
dcfac283e6 | ||
|
|
141176df20 | ||
|
|
32332f65bb | ||
|
|
246e2c4ac5 | ||
|
|
98be82c0d0 | ||
|
|
0ad8bbc3c9 | ||
|
|
cdb84f0967 | ||
|
|
4f5d713bbc | ||
|
|
df16a49c93 | ||
|
|
12206bfac5 | ||
|
|
f5ac5321bd | ||
|
|
fad023e734 | ||
|
|
396cb3cd39 | ||
|
|
064bada213 |
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.15"
|
||||
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.15"
|
||||
version = "0.4.16"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"axum",
|
||||
@@ -687,7 +689,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "compliance-dashboard"
|
||||
version = "0.4.15"
|
||||
version = "0.4.16"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"axum",
|
||||
@@ -725,8 +727,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "compliance-dast"
|
||||
version = "0.4.15"
|
||||
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.15"
|
||||
version = "0.4.16"
|
||||
dependencies = [
|
||||
"bson",
|
||||
"chrono",
|
||||
@@ -770,7 +774,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "compliance-mcp"
|
||||
version = "0.4.15"
|
||||
version = "0.4.16"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"bson",
|
||||
@@ -793,7 +797,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "compliance-smoke"
|
||||
version = "0.4.15"
|
||||
version = "0.4.16"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"compliance-core",
|
||||
@@ -928,7 +932,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "control-map"
|
||||
version = "0.4.15"
|
||||
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.15"
|
||||
version = "0.4.16"
|
||||
dependencies = [
|
||||
"compliance-core",
|
||||
"compliance-dast",
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
[package]
|
||||
name = "compliance-agent"
|
||||
version = "0.4.15"
|
||||
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,20 +55,29 @@ 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.
|
||||
@@ -77,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,
|
||||
}
|
||||
|
||||
@@ -287,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
|
||||
@@ -330,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,
|
||||
}
|
||||
|
||||
@@ -345,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,
|
||||
}
|
||||
|
||||
@@ -356,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,
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
@@ -144,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,
|
||||
@@ -183,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,
|
||||
@@ -273,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,
|
||||
@@ -299,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,
|
||||
@@ -354,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,
|
||||
|
||||
@@ -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,
|
||||
@@ -311,6 +360,16 @@ fn refuse_role() -> Refusal {
|
||||
)
|
||||
}
|
||||
|
||||
/// 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,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
+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)]
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -1763,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);
|
||||
}
|
||||
@@ -1801,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) => {
|
||||
@@ -1818,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
|
||||
@@ -1854,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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2608,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
|
||||
@@ -2662,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");
|
||||
}
|
||||
|
||||
@@ -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.15"
|
||||
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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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.15"
|
||||
version = "0.4.16"
|
||||
edition = "2021"
|
||||
default-run = "compliance-dashboard"
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "compliance-dast"
|
||||
version = "0.4.15"
|
||||
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.15"
|
||||
version = "0.4.16"
|
||||
edition = "2021"
|
||||
|
||||
[lints]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "compliance-mcp"
|
||||
version = "0.4.15"
|
||||
version = "0.4.16"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "compliance-smoke"
|
||||
version = "0.4.15"
|
||||
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.15"
|
||||
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,
|
||||
|
||||
+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,
|
||||
|
||||
@@ -36,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
|
||||
|
||||
@@ -417,6 +417,7 @@ Every connection the agent opens, in one place. **Guarded** means: the HTTP clie
|
||||
| Git remotes (clone, fetch, submodules, linked artifacts) | `pipeline/git.rs`, `ingest/` | `check_git_url` and the resolved address before every clone and fetch; redirects off |
|
||||
| Gitea API of a git source or tracker (managed Git) | `git_source/gitea.rs`, `trackers/gitea.rs` | guarded |
|
||||
| DAST and pentest targets | `api/handlers/dast.rs`, `pentest/orchestrator.rs`, `compliance-dast` | base URL checked with `check_url`; the DAST tools share a guarded client |
|
||||
| The target's identity provider, for deleting a pentest test user (Keycloak, Auth0, Okta; given per session) | `pentest/cleanup.rs` | URL checked with `check_url` when the session is created; guarded client |
|
||||
|
||||
### Operator-configured services (not guarded)
|
||||
|
||||
@@ -428,7 +429,6 @@ These are set by the operator in the agent's environment, not by a tenant, and o
|
||||
| Tenant registry (entitlements, projects) | `registry.rs` | `TENANT_REGISTRY_URL` |
|
||||
| breakpilot-compliance OSCAL catalog | `controls/oscal_provider.rs` | `BREAKPILOT_BASE_URL` |
|
||||
| GitLab and Jira issue trackers | `trackers/gitlab.rs`, `trackers/jira.rs` | `GITLAB_URL`, `JIRA_URL` |
|
||||
| Identity providers for pentest test-user cleanup (Keycloak, Auth0, Okta) | `pentest/cleanup.rs` | `KEYCLOAK_URL`, `AUTH0_DOMAIN`, `OKTA_DOMAIN` |
|
||||
| Headless Chrome for PDF reports | `pentest/report/pdf.rs` | `CHROME_WS_URL` |
|
||||
| MongoDB | `database.rs` | `MONGODB_URI` |
|
||||
| ClamAV service (clamd, plain TCP; the tree's files are streamed to it) | `pipeline/clamav.rs` | `CLAMD_ADDRESS` |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "werkbank-exec"
|
||||
version = "0.4.15"
|
||||
version = "0.4.16"
|
||||
edition = "2021"
|
||||
description = "Shared dynamic-execution logic: soft-PLC provisioning + industrial-protocol probing, used by the compliance agent and the Werkbank runner."
|
||||
|
||||
|
||||
Reference in new issue
Block a user