From dcfac283e66104cb4450e1cd3d80c3f0490e74e9 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Mon, 16 Nov 2026 15:45:28 +0000 Subject: [PATCH] feat(api): the OpenAPI description covers the target routes (#1006) (#1014) --- .../src/api/handlers/demo_seed.rs | 27 +- .../src/api/handlers/onboarding.rs | 257 ++++++++++++++++-- .../src/api/handlers/target_input.rs | 23 +- compliance-agent/src/api/routes.rs | 81 ++---- .../src/api/undescribed_routes.txt | 11 - compliance-agent/src/demo_seed.rs | 2 +- 6 files changed, 304 insertions(+), 97 deletions(-) diff --git a/compliance-agent/src/api/handlers/demo_seed.rs b/compliance-agent/src/api/handlers/demo_seed.rs index 43cbae4..6445e93 100644 --- a/compliance-agent/src/api/handlers/demo_seed.rs +++ b/compliance-agent/src/api/handlers/demo_seed.rs @@ -27,7 +27,16 @@ pub struct SeedResponse { pub seeded: Vec, } -/// 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, 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, diff --git a/compliance-agent/src/api/handlers/onboarding.rs b/compliance-agent/src/api/handlers/onboarding.rs index 82b4832..abbea9c 100644 --- a/compliance-agent/src/api/handlers/onboarding.rs +++ b/compliance-agent/src/api/handlers/onboarding.rs @@ -29,23 +29,36 @@ use super::{collect_cursor_async, ApiResponse, PaginationParams}; type AgentExt = Extension>; -#[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, + /// The target's artifacts by reference; files are uploaded afterwards. #[serde(default)] pub artifacts: Vec, } -#[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, + /// What the target is. + #[schema(value_type = Option, example = "web_app")] pub target_type: Option, /// Fields left out keep their stored values. pub scan_config: Option, + /// The frameworks and jurisdiction the target is checked against. + #[schema(value_type = Option)] pub compliance_profile: Option, + /// When the target is scanned on its own, a cron expression. pub scan_schedule: Option, /// 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::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=`). -#[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, + /// 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, +} + +/// 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 Deserialize<'de>>(s: &str) -> Option { 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, diff --git a/compliance-agent/src/api/handlers/target_input.rs b/compliance-agent/src/api/handlers/target_input.rs index b5085b4..1699c29 100644 --- a/compliance-agent/src/api/handlers/target_input.rs +++ b/compliance-agent/src/api/handlers/target_input.rs @@ -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, + /// The PLC project's format, for a PLC project. #[serde(default)] + #[schema(value_type = Option, example = "plcopen_xml")] pub plc_format: Option, /// 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>)] pub enabled_scans: Option>, + /// The scans not to run. + #[schema(value_type = Option>)] pub disabled_scans: Option>, + /// `development`, `staging` or `production`. + #[schema(value_type = Option, example = "staging")] pub environment: Option, + /// Whether dynamic tests may change data. pub allow_destructive: Option, + /// The pentest strategy: `quick`, `comprehensive`, `targeted` or `aggressive`. + #[schema(value_type = Option)] pub strategy: Option, + /// The pentest's scope and login. + #[schema(value_type = Option)] pub pentest: Option, + /// Where findings are filed as issues. + #[schema(value_type = Option)] pub issue_tracker: Option, /// Paths left out of every scan; replaces the stored list. Normalised /// while the request is read, so an invalid path is refused with its diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index b0c7426..60e6c11 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -1,9 +1,9 @@ use axum::extract::DefaultBodyLimit; use axum::http::header::CONTENT_TYPE; -use axum::routing::{delete, get, patch, post, put}; +use axum::routing::{delete, get, patch, post}; use axum::Router; use utoipa::OpenApi; -use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::router::{OpenApiRouter, UtoipaMethodRouterExt}; use utoipa_axum::routes; use crate::api::{handlers, openapi}; @@ -65,60 +65,35 @@ fn described_routes() -> OpenApiRouter { 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), - ) + .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)) diff --git a/compliance-agent/src/api/undescribed_routes.txt b/compliance-agent/src/api/undescribed_routes.txt index 61a0469..c86d591 100644 --- a/compliance-agent/src/api/undescribed_routes.txt +++ b/compliance-agent/src/api/undescribed_routes.txt @@ -12,17 +12,6 @@ /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/inbox /api/v1/inbox/decide /api/v1/inbox/undo diff --git a/compliance-agent/src/demo_seed.rs b/compliance-agent/src/demo_seed.rs index f61c311..345f9b0 100644 --- a/compliance-agent/src/demo_seed.rs +++ b/compliance-agent/src/demo_seed.rs @@ -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)]