feat(api): the agent serves an OpenAPI description, starting with DAST (#1006) (#1012)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Successful in 1m11s
CI / Deploy MCP (push) Successful in 4m56s
CI / Deploy Dashboard (push) Successful in 6m45s
CI / Deploy Agent (push) Successful in 8m52s

This commit was merged in pull request #1012.
This commit is contained in:
sharang committed 2026-11-16 13:10:26 +00:00
1 parent 246e2c4ac5
commit 32332f65bb
11 files changed
+489 -32

No files matched your search

Generated
+42 -4
View File
@@ -645,6 +645,8 @@ dependencies = [
"tracing",
"tracing-subscriber",
"urlencoding",
"utoipa",
"utoipa-axum",
"uuid",
"walkdir",
"werkbank-exec",
@@ -2922,7 +2924,7 @@ dependencies = [
"libc",
"percent-encoding",
"pin-project-lite",
"socket2 0.5.10",
"socket2 0.6.2",
"system-configuration",
"tokio",
"tower-layer",
@@ -4586,7 +4588,7 @@ dependencies = [
"quinn-udp",
"rustc-hash 2.1.1",
"rustls",
"socket2 0.5.10",
"socket2 0.6.2",
"thiserror 2.0.18",
"tokio",
"tracing",
@@ -4624,9 +4626,9 @@ dependencies = [
"cfg_aliases",
"libc",
"once_cell",
"socket2 0.5.10",
"socket2 0.6.2",
"tracing",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -6817,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"
+3
View File
@@ -7,6 +7,9 @@ edition = "2021"
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" }
+94 -10
View File
@@ -19,25 +19,40 @@ 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): `basic` (username,
/// password), `bearer` (token), `cookie` (token = `name=value`), plus
/// optional extra headers. Stored sealed, never returned.
/// 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>,
}
@@ -51,7 +66,17 @@ 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,
@@ -88,7 +113,20 @@ 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,
@@ -140,7 +178,21 @@ 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,
@@ -213,7 +265,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,
@@ -251,7 +313,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,
@@ -289,7 +361,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,
+7 -1
View File
@@ -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,
}
+1
View File
@@ -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;
+73
View File
@@ -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
}
+136 -17
View File
@@ -1,15 +1,45 @@
use axum::extract::DefaultBodyLimit;
use axum::http::header::CONTENT_TYPE;
use axum::routing::{delete, get, patch, post, put};
use axum::Router;
use utoipa::OpenApi;
use utoipa_axum::router::OpenApiRouter;
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))
@@ -278,21 +308,14 @@ pub fn build_router() -> Router {
post(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(
@@ -386,3 +409,99 @@ 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"
);
}
#[test]
fn the_description_is_behind_the_customer_authentication() {
assert!(!compliance_core::auth::bypasses_customer_auth(
openapi::SPEC_PATH
));
}
}
@@ -0,0 +1,106 @@
# 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/targets
/api/v1/targets/demo-seed
/api/v1/targets/{id}
/api/v1/targets/{id}/artifacts
/api/v1/targets/{id}/webhook-deliveries
/api/v1/targets/{id}/artifacts/upload
/api/v1/targets/{id}/artifacts/{artifact_id}/archive-password
/api/v1/targets/{id}/applicable-scans
/api/v1/targets/{id}/detect
/api/v1/targets/{id}/scan
/api/v1/targets/{id}/billing/swap
/api/v1/findings
/api/v1/findings/variants
/api/v1/findings/{id}
/api/v1/findings/{id}/status
/api/v1/findings/bulk-status
/api/v1/findings/{id}/feedback
/api/v1/finding-groups
/api/v1/finding-groups/decide
/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/sbom
/api/v1/sbom/filters
/api/v1/sbom/export
/api/v1/sbom/licenses
/api/v1/sbom/quality
/api/v1/sbom/diff
/api/v1/licenses/conclusions
/api/v1/licenses/policy
/api/v1/licenses/check
/api/v1/licenses/review
/api/v1/sbom/notices
/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/graph/{repo_id}
/api/v1/graph/{repo_id}/nodes
/api/v1/graph/{repo_id}/summary
/api/v1/graph/{repo_id}/communities
/api/v1/graph/{repo_id}/impact/{finding_id}
/api/v1/graph/{repo_id}/search
/api/v1/graph/{repo_id}/file-content
/api/v1/graph/{repo_id}/build
/api/v1/chat/{repo_id}
/api/v1/chat/{repo_id}/build-embeddings
/api/v1/chat/{repo_id}/status
/api/v1/help/chat
/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
@@ -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;
}
+4
View File
@@ -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