diff --git a/.env.example b/.env.example index 0d54e8a..c48db2b 100644 --- a/.env.example +++ b/.env.example @@ -87,6 +87,12 @@ KEYCLOAK_CLIENT_ID=compliance-dashboard REDIRECT_URI=http://localhost:8080/auth/callback APP_URL=http://localhost:8080 +# Deployment feature flags (comma list). `source_only` = static analysis only: +# the scan pipeline skips DAST, pentest, the ICS probe and the ephemeral PLC +# runtime (recorded as skipped stages, not failures), and the dashboard hides +# those actions. Staging runs with it until that infrastructure is deployed. +# PW_FEATURES=source_only + # OpenTelemetry (optional - omit to disable) # OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 # OTEL_SERVICE_NAME=compliance-agent diff --git a/compliance-agent/src/api/handlers/dast.rs b/compliance-agent/src/api/handlers/dast.rs index e1f2f26..6eb9181 100644 --- a/compliance-agent/src/api/handlers/dast.rs +++ b/compliance-agent/src/api/handlers/dast.rs @@ -126,6 +126,11 @@ pub async fn trigger_scan( tenant: TenantCtx, Path(id): Path, ) -> Result, StatusCode> { + // A source-only deployment has no browser/runtime infrastructure, so a DAST + // run could only fail at reconnaissance. Say so instead. + if agent.config.features.source_only() { + return Err(StatusCode::CONFLICT); + } let oid = mongodb::bson::oid::ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?; let db = tenant_db(&agent, &tenant).await?; diff --git a/compliance-agent/src/api/handlers/demo_seed.rs b/compliance-agent/src/api/handlers/demo_seed.rs new file mode 100644 index 0000000..43cbae4 --- /dev/null +++ b/compliance-agent/src/api/handlers/demo_seed.rs @@ -0,0 +1,63 @@ +//! Demo-target seeding from the dashboard. +//! +//! `GET /api/v1/targets/demo-seed` lists the curated targets the agent ships; +//! `POST` creates them for the caller's tenant and starts a scan for each. The +//! work itself lives in [`crate::demo_seed`], which the nightly `demo/reset` +//! calls with no user token. + +use axum::extract::Extension; +use axum::http::StatusCode; +use axum::Json; +use serde::Serialize; + +use compliance_core::tenant_ctx::TenantCtx; + +use crate::demo_seed::{self, DemoTargetSummary, SeedRequest, SeededTarget}; + +use super::dto::tenant_db; +use super::AgentExt; + +#[derive(Serialize)] +pub struct DemoTargetsResponse { + pub targets: Vec, +} + +#[derive(Serialize)] +pub struct SeedResponse { + pub seeded: Vec, +} + +/// GET /api/v1/targets/demo-seed — what "Add demo targets" would create. +#[tracing::instrument(skip_all)] +pub async fn list_demo_targets( + _tenant: TenantCtx, +) -> Result, StatusCode> { + let targets = demo_seed::manifest_summary().map_err(|e| { + tracing::error!(error = %e, "bundled demo manifest is unreadable"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + 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. +#[tracing::instrument(skip_all)] +pub async fn seed_demo_targets( + Extension(agent): AgentExt, + tenant: TenantCtx, + body: Option>, +) -> Result<(StatusCode, Json), StatusCode> { + let req = body.map(|Json(b)| b).unwrap_or_default(); + let db = tenant_db(&agent, &tenant).await?; + let seeded = demo_seed::seed_tenant(&agent, &db, &tenant.0.tenant_id, &req) + .await + .map_err(|e| { + // An unknown key is the caller's mistake; anything else is ours. + tracing::warn!(error = %e, "demo seed rejected"); + match e { + crate::fixtures::FixtureError::UnknownKeys(_) => StatusCode::BAD_REQUEST, + _ => StatusCode::INTERNAL_SERVER_ERROR, + } + })?; + Ok((StatusCode::ACCEPTED, Json(SeedResponse { seeded }))) +} diff --git a/compliance-agent/src/api/handlers/mod.rs b/compliance-agent/src/api/handlers/mod.rs index a002624..39d6139 100644 --- a/compliance-agent/src/api/handlers/mod.rs +++ b/compliance-agent/src/api/handlers/mod.rs @@ -1,6 +1,7 @@ pub mod admin; pub mod chat; pub mod dast; +pub mod demo_seed; pub mod dto; pub mod findings; pub mod graph; diff --git a/compliance-agent/src/api/handlers/onboarding.rs b/compliance-agent/src/api/handlers/onboarding.rs index e9bd6e0..3b12c52 100644 --- a/compliance-agent/src/api/handlers/onboarding.rs +++ b/compliance-agent/src/api/handlers/onboarding.rs @@ -40,21 +40,12 @@ pub struct ArtifactInput { impl ArtifactInput { fn build(&self) -> Artifact { - let s = self.source_ref.clone(); - match self.kind { - ArtifactKind::GitRepo => { - Artifact::git_repo(s, self.branch.clone().unwrap_or_else(|| "main".to_string())) - } - ArtifactKind::LiveUrl => Artifact::live_url(s), - ArtifactKind::FirmwareImage => Artifact::firmware_image(s), - ArtifactKind::SourceArchive => Artifact::source_archive(s), - ArtifactKind::MobilePackage => Artifact::mobile_package(s), - ArtifactKind::ContainerImage => Artifact::container_image(s), - ArtifactKind::PlcProject => { - Artifact::plc_project(s, self.plc_format.unwrap_or(PlcFormat::PlcopenXml)) - } - ArtifactKind::PlaintextDescription => Artifact::plaintext(s), - } + crate::targets::reference_artifact( + self.kind, + self.source_ref.clone(), + self.branch.clone(), + self.plc_format, + ) } } diff --git a/compliance-agent/src/api/handlers/pentest_handlers/session.rs b/compliance-agent/src/api/handlers/pentest_handlers/session.rs index 579d781..3320642 100644 --- a/compliance-agent/src/api/handlers/pentest_handlers/session.rs +++ b/compliance-agent/src/api/handlers/pentest_handlers/session.rs @@ -47,6 +47,14 @@ pub async fn create_session( tenant: TenantCtx, Json(req): Json, ) -> Result>, (StatusCode, String)> { + // Source-only deployment: no runtime target to attack, no tooling deployed. + if agent.config.features.source_only() { + return Err(( + StatusCode::CONFLICT, + "Pentest sessions are not available in this environment (static analysis only)." + .to_string(), + )); + } // Try to acquire a concurrency permit let permit = agent .session_semaphore diff --git a/compliance-agent/src/api/handlers/platform.rs b/compliance-agent/src/api/handlers/platform.rs index 20add8e..38cbcae 100644 --- a/compliance-agent/src/api/handlers/platform.rs +++ b/compliance-agent/src/api/handlers/platform.rs @@ -87,6 +87,10 @@ pub struct LifecycleBody { pub confirm: Option, #[serde(default)] pub tenant_id: Option, + /// `demo/reset` only: repopulate the tenant with the bundled demo targets + /// and start their scans (the nightly sales-demo reset). + #[serde(default)] + pub seed: bool, } async fn set_marker( @@ -261,27 +265,45 @@ pub async fn delete_data( } /// `POST /api/v1/platform/tenants/demo/reset` — drops and re-creates the -/// demo tenant database. Fixtures (platform/seed-data) are loaded later. +/// demo tenant database. With `{"seed": true}` it then re-seeds the bundled +/// demo targets and starts their scans, which is what the nightly reset of the +/// sales demo tenant needs: no user token, same code path as the dashboard's +/// "Add demo targets". pub async fn demo_reset( State(st): State, body: Option>, ) -> Result, StatusCode> { - let tenant_id = body - .and_then(|Json(b)| b.tenant_id) - .unwrap_or_else(|| "demo".to_string()); + let b = body.map(|Json(b)| b).unwrap_or_default(); + let tenant_id = b.tenant_id.unwrap_or_else(|| "demo".to_string()); st.agent .db_pool .drop_tenant(&tenant_id) .await .map_err(internal)?; - st.agent + let db = st + .agent .db_pool .for_tenant_id(&tenant_id) .await .map_err(internal)?; - Ok(Json( - serde_json::json!({ "status": "reset", "tenant_id": tenant_id }), - )) + if !b.seed { + return Ok(Json( + serde_json::json!({ "status": "reset", "tenant_id": tenant_id }), + )); + } + let seeded = crate::demo_seed::seed_tenant( + &st.agent, + &db, + &tenant_id, + &crate::demo_seed::SeedRequest::default(), + ) + .await + .map_err(internal)?; + Ok(Json(serde_json::json!({ + "status": "reset", + "tenant_id": tenant_id, + "seeded": seeded, + }))) } #[derive(Deserialize)] @@ -383,5 +405,8 @@ pub async fn version(State(st): State) -> Json "product": st.agent.config.product_key, "version": env!("CARGO_PKG_VERSION"), "contract": "2.0", + // Deployment feature flags (PW_FEATURES). The dashboard reads the same + // set the agent enforces instead of carrying its own copy of the env. + "features": st.agent.config.features.flags(), })) } diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index e9413dc..d544489 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -17,6 +17,13 @@ pub fn build_router() -> Router { "/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) diff --git a/compliance-agent/src/config.rs b/compliance-agent/src/config.rs index 91efbdb..5d99df4 100644 --- a/compliance-agent/src/config.rs +++ b/compliance-agent/src/config.rs @@ -1,4 +1,4 @@ -use compliance_core::config::{BreakpilotConfig, PlcRuntimeConfig}; +use compliance_core::config::{BreakpilotConfig, Features, PlcRuntimeConfig}; use compliance_core::AgentConfig; use secrecy::SecretString; @@ -93,6 +93,7 @@ pub fn load_config() -> Result { v } }, + features: Features::parse(&env_var_opt("PW_FEATURES").unwrap_or_default()), }) } diff --git a/compliance-agent/src/demo_seed.rs b/compliance-agent/src/demo_seed.rs new file mode 100644 index 0000000..f61c311 --- /dev/null +++ b/compliance-agent/src/demo_seed.rs @@ -0,0 +1,276 @@ +//! Seed a tenant with the curated demo targets. +//! +//! The demo manifest ([`crate::fixtures`]) is compiled into the agent, so a +//! prospect on a fresh trial can populate their workspace from the dashboard +//! ("Add demo targets") instead of running the ops curl script, and the nightly +//! `demo/reset` can repopulate the sales tenant with no user token in sight. +//! +//! Everything runs through [`crate::targets`] — the same create → upload → +//! detect path the onboarding API takes — so seeded targets are ordinary +//! targets: same records, same `target.added` usage events, same scans. + +use mongodb::bson::{doc, oid::ObjectId}; +use serde::{Deserialize, Serialize}; + +use compliance_core::models::ScanTrigger; + +use crate::agent::ComplianceAgent; +use crate::database::Database; +use crate::fixtures::{DemoTarget, DemoTargets, FixtureError}; +use crate::targets; + +/// What the caller asked to seed. +#[derive(Debug, Clone, Default, Deserialize)] +pub struct SeedRequest { + /// Manifest keys to seed; empty seeds every target. + #[serde(default)] + pub names: Vec, + /// Re-run the scan for a target that already exists. + #[serde(default)] + pub rescan: bool, +} + +/// Per-target result. `status` is `queued` (created, scan started), `exists` +/// (already there, nothing done) or `failed`. +#[derive(Debug, Clone, Serialize, PartialEq, Eq)] +pub struct SeededTarget { + /// The manifest key. + pub name: String, + pub target_id: Option, + /// Always `None` today: the scan is started in the background and its + /// `ScanRun` id does not exist yet when this returns. + pub scan_id: Option, + pub status: String, + pub error: Option, +} + +impl SeededTarget { + const QUEUED: &'static str = "queued"; + const EXISTS: &'static str = "exists"; + const FAILED: &'static str = "failed"; + + fn queued(key: &str, target_id: String) -> Self { + Self { + name: key.to_string(), + target_id: Some(target_id), + scan_id: None, + status: Self::QUEUED.to_string(), + error: None, + } + } + + fn exists(key: &str, target_id: String) -> Self { + Self { + name: key.to_string(), + target_id: Some(target_id), + scan_id: None, + status: Self::EXISTS.to_string(), + error: None, + } + } + + fn failed(key: &str, err: impl std::fmt::Display) -> Self { + Self { + name: key.to_string(), + target_id: None, + scan_id: None, + status: Self::FAILED.to_string(), + error: Some(err.to_string()), + } + } +} + +/// One manifest entry as the dashboard lists it before seeding. +#[derive(Debug, Clone, Serialize, PartialEq, Eq)] +pub struct DemoTargetSummary { + /// Manifest key — what [`SeedRequest::names`] takes. + pub key: String, + /// Display name, prefix included (what the target is called once seeded). + pub name: String, + /// Target type token (`plc_sps`, `backend_service`, …). + pub kind: String, + pub description: Option, + /// True when no required artifact needs a live endpoint — the only kind of + /// target a `source_only` deployment can scan end to end. + pub source_only: bool, +} + +/// The bundled manifest, summarised for the dashboard. +pub fn manifest_summary() -> Result, FixtureError> { + let manifest = DemoTargets::bundled()?; + Ok(manifest + .targets + .iter() + .map(|t| DemoTargetSummary { + key: t.key.clone(), + name: manifest.full_name(t), + kind: format!("{:?}", t.target_type).to_lowercase(), + description: t.description.clone(), + source_only: t.source_only(), + }) + .collect()) +} + +/// Seed `tenant_id` with the selected demo targets and start a scan for each +/// newly created one. Never fails as a whole: a target that cannot be seeded is +/// reported as `failed` and the rest continue. +pub async fn seed_tenant( + agent: &ComplianceAgent, + db: &Database, + tenant_id: &str, + req: &SeedRequest, +) -> Result, FixtureError> { + let manifest = DemoTargets::bundled()?; + let selected = manifest.select(&req.names)?; + let mut out = Vec::with_capacity(selected.len()); + for t in selected { + let full_name = manifest.full_name(t); + out.push( + match seed_one(agent, db, tenant_id, t, &full_name, req.rescan).await { + Ok(r) => r, + Err(e) => { + tracing::warn!(tenant_id, key = %t.key, error = %e, "demo seed failed"); + SeededTarget::failed(&t.key, e) + } + }, + ); + } + Ok(out) +} + +async fn seed_one( + agent: &ComplianceAgent, + db: &Database, + tenant_id: &str, + demo: &DemoTarget, + full_name: &str, + rescan: bool, +) -> Result { + // Idempotent by display name: the seeder owns the "Demo · " prefix, so a + // second call finds its own targets rather than duplicating them. + if let Some(existing) = db + .onboarded_targets() + .find_one(doc! { "name": full_name }) + .await? + { + let id = existing.id.map(|i| i.to_hex()).unwrap_or_default(); + if !rescan { + return Ok(SeededTarget::exists(&demo.key, id)); + } + spawn_scan(agent, tenant_id, &id); + return Ok(SeededTarget::queued(&demo.key, id)); + } + + // Reference artifacts (git repo, live URL, …) go in at creation; uploads + // need the target id for their blob path, so they are attached after. + let mut target = + compliance_core::models::OnboardedTarget::new(full_name.to_string(), demo.target_type); + target.description = demo.description.clone(); + for a in demo.artifacts.iter().filter(|a| !a.is_upload()) { + match a.resolved_source_ref() { + Some(source_ref) => target.artifacts.push(targets::reference_artifact( + a.kind, + source_ref, + a.branch.clone(), + a.plc_format, + )), + // Optional env-only artifacts (a live PLC, a firmware image) are + // simply absent where that infrastructure is not deployed. + None if a.optional || a.env_only() => continue, + None => { + return Err(crate::error::AgentError::Other(format!( + "demo target {}: artifact {:?} has no source_ref", + demo.key, a.kind + ))) + } + } + } + + let target = targets::create_target(agent, db, tenant_id, target).await?; + let oid: ObjectId = target + .id + .ok_or_else(|| crate::error::AgentError::Other("target insert returned no id".into()))?; + let target_id = oid.to_hex(); + + for a in demo.artifacts.iter().filter(|a| a.is_upload()) { + let content = a + .upload_content() + .map_err(|e| crate::error::AgentError::Other(e.to_string()))?; + let Some(content) = content else { + if a.optional || a.env_only() { + continue; + } + return Err(crate::error::AgentError::Other(format!( + "demo target {}: upload fixture missing", + demo.key + ))); + }; + let stored = targets::store_upload(agent, &target_id, &content.filename, &content.bytes)?; + let Some(artifact) = targets::uploaded_artifact( + a.kind, + a.plc_format, + &content.filename, + &stored, + content.bytes.len() as u64, + ) else { + return Err(crate::error::AgentError::Other(format!( + "demo target {}: {:?} is not an upload kind", + demo.key, a.kind + ))); + }; + targets::attach_artifact(db, oid, &artifact).await?; + } + + targets::detect_target(db, oid).await?; + spawn_scan(agent, tenant_id, &target_id); + Ok(SeededTarget::queued(&demo.key, target_id)) +} + +/// Start a scan in the background, exactly as the manual "Run scan" button +/// does. The scan run is created inside the pipeline, so there is no id to +/// return here. +fn spawn_scan(agent: &ComplianceAgent, tenant_id: &str, target_id: &str) { + let agent = agent.clone(); + let tenant_id = tenant_id.to_string(); + let target_id = target_id.to_string(); + tokio::spawn(async move { + if let Err(e) = agent + .run_target_scan(&tenant_id, &target_id, ScanTrigger::Manual) + .await + { + tracing::error!(tenant_id, target_id, error = %e, "demo seed scan failed"); + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn summary_lists_the_bundled_manifest() { + let s = manifest_summary().expect("bundled manifest"); + assert!(!s.is_empty()); + // Every shipped demo target is scannable without live infrastructure. + assert!(s.iter().all(|t| t.source_only), "{s:?}"); + assert!(s.iter().all(|t| t.name.starts_with("Demo · ")), "{s:?}"); + let keys: Vec<&str> = s.iter().map(|t| t.key.as_str()).collect(); + assert!(keys.contains(&"git-cra-vuln-demo"), "{keys:?}"); + } + + #[test] + fn seed_request_defaults_to_everything_without_rescan() { + let r: SeedRequest = serde_json::from_str("{}").expect("empty body"); + assert!(r.names.is_empty()); + assert!(!r.rescan); + } + + #[test] + fn unknown_keys_are_rejected_before_anything_is_created() { + let manifest = DemoTargets::bundled().expect("bundled"); + let err = manifest + .select(&["nope".to_string()]) + .expect_err("unknown key"); + assert!(matches!(err, FixtureError::UnknownKeys(_)), "{err:?}"); + } +} diff --git a/compliance-agent/src/fixtures.rs b/compliance-agent/src/fixtures.rs index 0d74900..10e3c82 100644 --- a/compliance-agent/src/fixtures.rs +++ b/compliance-agent/src/fixtures.rs @@ -2,22 +2,29 @@ //! //! `fixtures/demo-targets/targets.json` is the versioned, reproducible set of //! representative targets every scan path can be exercised against: PlcSps -//! (composite), a plain git SAST repo, a WebApp (git + live URL) and an RTOS +//! (composite and pure control logic), a plain git SAST repo and an RTOS //! firmware repo. The manifest is consumed by: //! -//! * `scripts/seed-demo-targets.sh` — onboards the targets through the -//! public API (optionally triggering a first scan), +//! * the demo seeder ([`crate::demo_seed`]) behind +//! `POST /api/v1/targets/demo-seed` and the platform `demo/reset` — which +//! onboards the targets in-process (no HTTP self-calls), +//! * `scripts/seed-demo-targets.sh` — a thin ops wrapper around that endpoint, //! * the nightly regression (#188) — the `expect` block is the golden //! baseline per target, //! * the lib tests below — which keep the manifest well-formed and assert the //! PLC baselines offline (no Mongo, no network) on every CI run. //! +//! The manifest *and* every `upload` fixture it references are compiled into +//! the agent binary ([`MANIFEST_JSON`], [`bundled_upload`]) so a deployed +//! agent seeds without a checkout; [`DemoTargets::load`] still reads the +//! on-disk copy for tooling that wants an edited manifest. +//! //! Artifacts come in two flavours: `source_ref` (git URL / live URL / image //! ref; may be overridden by the env var named in `source_ref_env`) and -//! `upload` (a file path relative to the workspace root, pushed through -//! `POST /targets/{id}/artifacts/upload`; may instead come from the env var -//! named in `upload_env`). Artifacts flagged `optional` are skipped when their -//! env var is unset, so the set seeds cleanly on a laptop without OT infra. +//! `upload` (a workspace-relative file bundled into the binary; may instead +//! come from the env var named in `upload_env`). Artifacts flagged `optional` +//! are skipped when their env var is unset, so the set seeds cleanly without +//! OT infra. use std::collections::BTreeMap; use std::path::{Path, PathBuf}; @@ -28,6 +35,39 @@ use serde::{Deserialize, Serialize}; /// Manifest path, relative to the workspace root. pub const MANIFEST_PATH: &str = "fixtures/demo-targets/targets.json"; +/// The manifest as compiled into the binary. +pub const MANIFEST_JSON: &str = include_str!("../../fixtures/demo-targets/targets.json"); + +/// Upload fixtures compiled into the binary, keyed by their manifest `upload` +/// path. Every `upload` in [`MANIFEST_JSON`] must have an entry here — the +/// `manifest_is_well_formed` test enforces it. +const BUNDLED_UPLOADS: &[(&str, &[u8])] = &[ + ( + "examples/plc-demo/pump_station.st", + include_bytes!("../../examples/plc-demo/pump_station.st"), + ), + ( + "examples/plc-demo/pump_fbd.xml", + include_bytes!("../../examples/plc-demo/pump_fbd.xml"), + ), + ( + "examples/plc-demo/conveyor.xml", + include_bytes!("../../examples/plc-demo/conveyor.xml"), + ), + ( + "examples/plc-demo/traffic_light.st", + include_bytes!("../../examples/plc-demo/traffic_light.st"), + ), +]; + +/// The bytes of a bundled upload fixture, by manifest `upload` path. +pub fn bundled_upload(path: &str) -> Option<&'static [u8]> { + BUNDLED_UPLOADS + .iter() + .find(|(p, _)| *p == path) + .map(|(_, bytes)| *bytes) +} + /// Why a manifest could not be loaded. #[derive(Debug, thiserror::Error)] pub enum FixtureError { @@ -43,6 +83,9 @@ pub enum FixtureError { #[source] source: serde_json::Error, }, + /// `select` was asked for keys the manifest does not define. + #[error("unknown demo target(s): {}", .0.join(", "))] + UnknownKeys(Vec), } /// The whole demo-target set. @@ -59,8 +102,8 @@ pub struct DemoTargets { /// One curated target. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DemoTarget { - /// Stable machine key (used in baseline reports and as the default - /// `repo_id`-ish handle in nightly output). + /// Stable machine key (used in baseline reports, as the `name` on the + /// demo-seed API and as the default `repo_id`-ish handle in nightly output). pub key: String, /// Human name (without the prefix). pub name: String, @@ -74,6 +117,18 @@ pub struct DemoTarget { pub expect: Expect, } +impl DemoTarget { + /// True when every *required* artifact is static (no live endpoint the + /// scan would need to reach). Optional env-only live URLs don't count — + /// they are skipped when their env var is unset. + pub fn source_only(&self) -> bool { + !self + .artifacts + .iter() + .any(|a| a.kind == ArtifactKind::LiveUrl && !a.optional) + } +} + /// One artifact of a curated target. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DemoArtifact { @@ -107,24 +162,93 @@ pub struct DemoArtifact { pub optional: bool, } +/// The content of an upload-style artifact, resolved for seeding. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UploadContent { + /// File name the artifact is recorded under. + pub filename: String, + pub bytes: Vec, +} + impl DemoArtifact { /// The upload path, resolved against the workspace root. `None` for /// reference-style artifacts or env-only uploads whose var is unset. pub fn upload_path(&self, root: &Path) -> Option { - if let Some(var) = &self.upload_env { - if let Ok(p) = std::env::var(var) { - if !p.is_empty() { - return Some(PathBuf::from(p)); - } - } + if let Some(p) = self.upload_env_path() { + return Some(p); } self.upload.as_ref().map(|p| root.join(p)) } + /// Absolute path from `upload_env`, when that var is set and non-empty. + fn upload_env_path(&self) -> Option { + let var = self.upload_env.as_ref()?; + std::env::var(var) + .ok() + .filter(|p| !p.is_empty()) + .map(PathBuf::from) + } + /// True when this artifact only exists if its env var is provided. pub fn env_only(&self) -> bool { self.upload.is_none() && self.source_ref.is_none() } + + /// True for upload-style artifacts (bundled file or env-provided path). + pub fn is_upload(&self) -> bool { + self.upload.is_some() || self.upload_env.is_some() + } + + /// The reference to onboard for a reference-style artifact: the env + /// override when set, else the literal `source_ref`. `None` when neither + /// is available (an optional env-only artifact without its var). + pub fn resolved_source_ref(&self) -> Option { + if let Some(var) = &self.source_ref_env { + if let Ok(v) = std::env::var(var) { + if !v.is_empty() { + return Some(v); + } + } + } + self.source_ref.clone() + } + + /// The bytes to upload for an upload-style artifact: the file named by + /// `upload_env` when that var is set, else the bundled fixture. `Ok(None)` + /// when there is nothing to upload (env var unset, no bundled path). + pub fn upload_content(&self) -> Result, FixtureError> { + if let Some(path) = self.upload_env_path() { + let bytes = std::fs::read(&path).map_err(|source| FixtureError::Io { + path: path.clone(), + source, + })?; + let filename = path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| "upload.bin".to_string()); + return Ok(Some(UploadContent { filename, bytes })); + } + let Some(rel) = self.upload.as_deref() else { + return Ok(None); + }; + let Some(bytes) = bundled_upload(rel) else { + return Err(FixtureError::Io { + path: PathBuf::from(rel), + source: std::io::Error::new( + std::io::ErrorKind::NotFound, + "fixture not bundled into the agent binary", + ), + }); + }; + let filename = Path::new(rel) + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| rel.to_string()); + Ok(Some(UploadContent { + filename, + bytes: bytes.to_vec(), + })) + } } /// Golden baseline; every field is optional so a target can assert only what @@ -165,7 +289,15 @@ impl DemoTargets { .unwrap_or_else(|| PathBuf::from(".")) } - /// Load the checked-in manifest. + /// The manifest compiled into the binary — what a deployed agent seeds. + pub fn bundled() -> Result { + serde_json::from_str(MANIFEST_JSON).map_err(|source| FixtureError::Parse { + path: PathBuf::from(MANIFEST_PATH), + source, + }) + } + + /// Load the checked-in manifest from disk. pub fn load() -> Result { Self::load_from(&Self::workspace_root().join(MANIFEST_PATH)) } @@ -182,10 +314,32 @@ impl DemoTargets { }) } - /// Display name as the seed script creates it. + /// Display name as the seeder creates it. pub fn full_name(&self, t: &DemoTarget) -> String { format!("{}{}", self.name_prefix, t.name) } + + /// The targets with the given keys, in manifest order. An empty `keys` + /// selects every target; any key the manifest lacks is an error (so a typo + /// never silently seeds nothing). + pub fn select(&self, keys: &[String]) -> Result, FixtureError> { + if keys.is_empty() { + return Ok(self.targets.iter().collect()); + } + let unknown: Vec = keys + .iter() + .filter(|k| !self.targets.iter().any(|t| &t.key == *k)) + .cloned() + .collect(); + if !unknown.is_empty() { + return Err(FixtureError::UnknownKeys(unknown)); + } + Ok(self + .targets + .iter() + .filter(|t| keys.contains(&t.key)) + .collect()) + } } #[cfg(test)] @@ -195,7 +349,16 @@ mod tests { use std::collections::{BTreeSet, HashSet}; fn manifest() -> DemoTargets { - DemoTargets::load().expect("demo manifest loads") + DemoTargets::bundled().expect("bundled demo manifest parses") + } + + #[test] + fn bundled_manifest_matches_checked_in_file() { + let on_disk = DemoTargets::load().expect("demo manifest loads from disk"); + let bundled = manifest(); + let keys = |m: &DemoTargets| m.targets.iter().map(|t| t.key.clone()).collect::>(); + assert_eq!(keys(&on_disk), keys(&bundled)); + assert_eq!(on_disk.name_prefix, bundled.name_prefix); } #[test] @@ -221,6 +384,12 @@ mod tests { ); if let Some(p) = &a.upload { assert!(root.join(p).is_file(), "{}: upload {p} missing", t.key); + // The deployed agent seeds from the binary, so every upload + // must be bundled and byte-identical to the checked-in file. + let bundled = + bundled_upload(p).unwrap_or_else(|| panic!("{}: {p} not bundled", t.key)); + let on_disk = std::fs::read(root.join(p)).expect("fixture readable"); + assert_eq!(bundled, on_disk.as_slice(), "{}: {p} bundle drifted", t.key); } match a.kind { ArtifactKind::PlcProject => { @@ -239,16 +408,108 @@ mod tests { } } - // Coverage the story asks for: PlcSps, firmware, web app, plain git. + // Coverage the demo asks for: PlcSps, firmware, plain git — every one + // scannable from source alone (the staging demo runs `source_only`). let types: HashSet = m.targets.iter().map(|t| t.target_type).collect(); for want in [ TargetType::PlcSps, TargetType::FirmwareRtos, - TargetType::WebApp, TargetType::BackendService, ] { assert!(types.contains(&want), "manifest lacks a {want:?} target"); } + for t in &m.targets { + assert!(t.source_only(), "{}: demo set must be source-only", t.key); + } + } + + #[test] + fn demo_set_has_the_expected_targets() { + let m = manifest(); + let keys: Vec<&str> = m.targets.iter().map(|t| t.key.as_str()).collect(); + assert_eq!( + keys, + [ + "plc-pump-station", + "plc-conveyor-line", + "git-cra-vuln-demo", + "firmware-zephyr-example", + ] + ); + } + + #[test] + fn source_only_ignores_optional_live_urls() { + let mut t = DemoTarget { + key: "k".into(), + name: "n".into(), + target_type: TargetType::WebApp, + description: None, + artifacts: vec![DemoArtifact { + kind: ArtifactKind::LiveUrl, + source_ref: Some("http://x".into()), + source_ref_env: None, + upload: None, + upload_env: None, + branch: None, + pin: None, + pin_tag: None, + plc_format: None, + optional: true, + }], + expect: Expect::default(), + }; + assert!(t.source_only()); + t.artifacts[0].optional = false; + assert!(!t.source_only()); + } + + #[test] + fn select_all_some_and_unknown() { + let m = manifest(); + assert_eq!(m.select(&[]).unwrap().len(), m.targets.len()); + + let some = m + .select(&[ + "git-cra-vuln-demo".to_string(), + "plc-pump-station".to_string(), + ]) + .unwrap(); + // Manifest order, not request order. + let keys: Vec<&str> = some.iter().map(|t| t.key.as_str()).collect(); + assert_eq!(keys, ["plc-pump-station", "git-cra-vuln-demo"]); + + let err = m + .select(&["plc-pump-station".to_string(), "nope".to_string()]) + .unwrap_err(); + assert!(matches!(err, FixtureError::UnknownKeys(ref k) if k == &["nope".to_string()])); + } + + #[test] + fn upload_content_comes_from_the_bundle() { + let m = manifest(); + let pump = m + .targets + .iter() + .find(|t| t.key == "plc-pump-station") + .unwrap(); + let st = pump + .artifacts + .iter() + .find(|a| a.upload.as_deref() == Some("examples/plc-demo/pump_station.st")) + .unwrap(); + let content = st.upload_content().unwrap().expect("bundled"); + assert_eq!(content.filename, "pump_station.st"); + assert!(!content.bytes.is_empty()); + + // Optional env-only uploads resolve to nothing when their var is unset. + let fw = pump + .artifacts + .iter() + .find(|a| a.kind == ArtifactKind::FirmwareImage) + .unwrap(); + assert!(fw.optional && fw.env_only()); + assert!(fw.upload_content().unwrap().is_none()); } /// Offline golden baseline: the checked-in PLC fixtures must keep producing diff --git a/compliance-agent/src/lib.rs b/compliance-agent/src/lib.rs index 9133088..9162361 100644 --- a/compliance-agent/src/lib.rs +++ b/compliance-agent/src/lib.rs @@ -6,6 +6,7 @@ pub mod classify; pub mod config; pub mod controls; pub mod database; +pub mod demo_seed; pub mod error; pub mod fixtures; pub mod ingest; @@ -16,6 +17,7 @@ pub mod rag; pub mod registry; pub mod scheduler; pub mod ssh; +pub mod targets; #[allow(dead_code)] pub mod trackers; pub mod webhooks; diff --git a/compliance-agent/src/pentest/cleanup.rs b/compliance-agent/src/pentest/cleanup.rs index c719861..575eaa8 100644 --- a/compliance-agent/src/pentest/cleanup.rs +++ b/compliance-agent/src/pentest/cleanup.rs @@ -351,6 +351,7 @@ mod tests { tenant_registry_client_secret: None, cors_allowed_origins: vec![], platform_allowed_clients: vec![], + features: compliance_core::Features::default(), } } diff --git a/compliance-agent/src/pipeline/graph_build.rs b/compliance-agent/src/pipeline/graph_build.rs index b4c9aef..d9835a5 100644 --- a/compliance-agent/src/pipeline/graph_build.rs +++ b/compliance-agent/src/pipeline/graph_build.rs @@ -66,6 +66,16 @@ impl PipelineOrchestrator { pub(super) async fn maybe_trigger_dast(&self, repo_id: &str, scan_run_id: &str) { use futures_util::TryStreamExt; + if self.source_only() { + self.skip_stage( + scan_run_id, + "dast", + compliance_core::models::SkippedStage::FEATURE_DISABLED, + ) + .await; + return; + } + let filter = mongodb::bson::doc! { "repo_id": repo_id }; let targets: Vec = match self.db.dast_targets().find(filter).await { diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 2bf4450..670e5e5 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -682,6 +682,15 @@ impl PipelineOrchestrator { target_id: &str, scan_run_id: &str, ) -> Result { + if self.source_only() { + self.skip_stage( + scan_run_id, + "plc_runtime", + compliance_core::models::SkippedStage::FEATURE_DISABLED, + ) + .await; + return Ok(0); + } self.update_phase(scan_run_id, "plc_provision").await; // Locate a loadable control-logic program among the PLC-source artifacts @@ -770,6 +779,15 @@ impl PipelineOrchestrator { target_id: &str, scan_run_id: &str, ) -> Result { + if self.source_only() { + self.skip_stage( + scan_run_id, + "ics_probe", + compliance_core::models::SkippedStage::FEATURE_DISABLED, + ) + .await; + return Ok(0); + } self.update_phase(scan_run_id, "ics_probe").await; let Some(endpoint) = target.live_url().map(|a| a.source_ref.clone()) else { tracing::warn!(target_id, "ICS probe: no live URL"); @@ -1044,7 +1062,7 @@ impl PipelineOrchestrator { target: &OnboardedTarget, plan: &crate::pipeline::plan::ScanPlan, ) { - if !plan.has(ScanType::Dast) { + if !plan.has(ScanType::Dast) || self.source_only() { return; } let (Some(url), Some(oid)) = (target.live_url(), target.id) else { @@ -1126,6 +1144,39 @@ impl PipelineOrchestrator { Ok(()) } + /// True in a deployment that only does static analysis (`PW_FEATURES` + /// contains `source_only`): no DAST, pentest, ICS probe or ephemeral PLC + /// runtime, because none of that infrastructure is deployed. + pub(super) fn source_only(&self) -> bool { + self.config.features.source_only() + } + + /// Record a stage the pipeline deliberately did not run. A skipped stage is + /// not an error: the scan completes, and the dashboard shows it as skipped + /// rather than failed. + pub(super) async fn skip_stage(&self, scan_run_id: &str, stage: &str, reason: &str) { + tracing::info!(scan_run_id, stage, reason, "pipeline stage skipped"); + let Ok(oid) = mongodb::bson::oid::ObjectId::parse_str(scan_run_id) else { + return; + }; + let skipped = compliance_core::models::SkippedStage { + stage: stage.to_string(), + status: "skipped".to_string(), + reason: reason.to_string(), + }; + let Ok(entry) = mongodb::bson::to_bson(&skipped) else { + return; + }; + let _ = self + .db + .scan_runs() + .update_one( + doc! { "_id": oid }, + doc! { "$push": { "skipped_stages": entry } }, + ) + .await; + } + pub(super) async fn update_phase(&self, scan_run_id: &str, phase: &str) { if let Ok(oid) = mongodb::bson::oid::ObjectId::parse_str(scan_run_id) { let _ = self diff --git a/compliance-agent/src/targets.rs b/compliance-agent/src/targets.rs new file mode 100644 index 0000000..34d6250 --- /dev/null +++ b/compliance-agent/src/targets.rs @@ -0,0 +1,203 @@ +//! Target lifecycle shared by the onboarding API and the demo seeder: +//! create → attach/upload artifact → detect. The HTTP handlers in +//! [`crate::api::handlers::onboarding`] are thin wrappers over these so an +//! in-process caller (the seeder, `demo/reset`) takes the exact same path — +//! same records, same usage events — without an HTTP self-call. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use mongodb::bson::{doc, oid::ObjectId, to_bson}; + +use compliance_core::models::{Artifact, ArtifactKind, OnboardedTarget, PlcFormat}; + +use crate::agent::ComplianceAgent; +use crate::classify::{classify_target, MockFirmwareDetector}; +use crate::database::Database; +use crate::error::AgentError; + +/// Insert a new target for `tenant_id` and emit the `target.added` usage +/// event. Returns the stored record with its id set. +pub async fn create_target( + agent: &ComplianceAgent, + db: &Database, + tenant_id: &str, + mut target: OnboardedTarget, +) -> Result { + let res = db.onboarded_targets().insert_one(&target).await?; + 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_id, + "target.added", + format!("target:{tenant_id}:{target_id}"), + serde_json::json!({ "target_id": target_id, "target_type": format!("{:?}", target.target_type) }), + ); + Ok(target) +} + +/// Write uploaded bytes into the artifact blob store under +/// `/uploads//_` and return the path. +pub fn store_upload( + agent: &ComplianceAgent, + target_id: &str, + filename: &str, + bytes: &[u8], +) -> Result { + let safe_name: String = filename + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') { + c + } else { + '_' + } + }) + .collect(); + let dir = Path::new(&agent.config.artifact_store_base_path) + .join("uploads") + .join(target_id); + std::fs::create_dir_all(&dir)?; + let dest = dir.join(format!("{}_{safe_name}", uuid::Uuid::new_v4())); + std::fs::write(&dest, bytes)?; + Ok(dest) +} + +/// Build the artifact record for an uploaded file. `None` for kinds that are +/// references, not files (git repo, live URL, container ref, text) — those go +/// through [`Artifact`]'s constructors directly. +pub fn uploaded_artifact( + kind: ArtifactKind, + plc_format: Option, + filename: &str, + stored_path: &Path, + size_bytes: u64, +) -> Option { + let mut artifact = match kind { + ArtifactKind::PlcProject => { + Artifact::plc_project(filename, plc_format.unwrap_or(PlcFormat::PlcopenXml)) + } + ArtifactKind::FirmwareImage => Artifact::firmware_image(filename), + ArtifactKind::SourceArchive => Artifact::source_archive(filename), + ArtifactKind::MobilePackage => Artifact::mobile_package(filename), + _ => return None, + }; + artifact.stored_path = Some(stored_path.to_string_lossy().to_string()); + artifact.size_bytes = Some(size_bytes); + Some(artifact) +} + +/// Build a reference-style artifact (git repo, live URL, container image, +/// plaintext) or a file artifact whose content is not uploaded here. The +/// onboarding API's `ArtifactInput` and the demo seeder share this so a seeded +/// target is indistinguishable from one a user onboarded. +pub fn reference_artifact( + kind: ArtifactKind, + source_ref: String, + branch: Option, + plc_format: Option, +) -> Artifact { + match kind { + ArtifactKind::GitRepo => { + Artifact::git_repo(source_ref, branch.unwrap_or_else(|| "main".to_string())) + } + ArtifactKind::LiveUrl => Artifact::live_url(source_ref), + ArtifactKind::FirmwareImage => Artifact::firmware_image(source_ref), + ArtifactKind::SourceArchive => Artifact::source_archive(source_ref), + ArtifactKind::MobilePackage => Artifact::mobile_package(source_ref), + ArtifactKind::ContainerImage => Artifact::container_image(source_ref), + ArtifactKind::PlcProject => { + Artifact::plc_project(source_ref, plc_format.unwrap_or(PlcFormat::PlcopenXml)) + } + ArtifactKind::PlaintextDescription => Artifact::plaintext(source_ref), + } +} + +/// Append an artifact to an existing target. +pub async fn attach_artifact( + db: &Database, + target_oid: ObjectId, + artifact: &Artifact, +) -> Result<(), AgentError> { + let artifact = to_bson(artifact).map_err(|e| AgentError::Other(e.to_string()))?; + db.onboarded_targets() + .update_one( + doc! { "_id": target_oid }, + doc! { "$push": { "artifacts": artifact }, "$set": { "updated_at": mongodb::bson::DateTime::now() } }, + ) + .await?; + Ok(()) +} + +/// Lightweight detection: classify the target from its artifact kinds (no +/// ingest / clone), persist the classification and return the updated record. +/// `Ok(None)` when the target does not exist. +pub async fn detect_target( + db: &Database, + target_oid: ObjectId, +) -> Result, AgentError> { + let Some(mut target) = db + .onboarded_targets() + .find_one(doc! { "_id": target_oid }) + .await? + else { + return Ok(None); + }; + + // No ingested working paths here → kind-based classification only; the mock + // firmware detector is never invoked (no firmware working path present). + let empty = HashMap::new(); + let detector = MockFirmwareDetector { detection: None }; + let classification = classify_target(&target, &empty, &detector).await?; + + let classification_bson = + to_bson(&classification).map_err(|e| AgentError::Other(e.to_string()))?; + db.onboarded_targets() + .update_one( + doc! { "_id": target_oid }, + doc! { "$set": { "classification": classification_bson, "updated_at": mongodb::bson::DateTime::now() } }, + ) + .await?; + target.classification = Some(classification); + Ok(Some(target)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn uploaded_artifact_records_stored_path_for_file_kinds() { + let a = uploaded_artifact( + ArtifactKind::PlcProject, + Some(PlcFormat::StructuredText), + "pump.st", + Path::new("/data/uploads/x/uuid_pump.st"), + 42, + ) + .expect("file kind"); + assert_eq!(a.kind, ArtifactKind::PlcProject); + assert_eq!(a.source_ref, "pump.st"); + assert_eq!( + a.stored_path.as_deref(), + Some("/data/uploads/x/uuid_pump.st") + ); + assert_eq!(a.size_bytes, Some(42)); + assert_eq!( + a.plc.as_ref().map(|p| p.format), + Some(PlcFormat::StructuredText) + ); + } + + #[test] + fn uploaded_artifact_rejects_reference_kinds() { + for kind in [ + ArtifactKind::GitRepo, + ArtifactKind::LiveUrl, + ArtifactKind::ContainerImage, + ArtifactKind::PlaintextDescription, + ] { + assert!(uploaded_artifact(kind, None, "f", Path::new("/p"), 1).is_none()); + } + } +} diff --git a/compliance-agent/tests/common/mod.rs b/compliance-agent/tests/common/mod.rs index 3fe13bd..104d05b 100644 --- a/compliance-agent/tests/common/mod.rs +++ b/compliance-agent/tests/common/mod.rs @@ -67,6 +67,7 @@ pub fn dev_config(mongodb_uri: String, db_name: String) -> AgentConfig { tenant_registry_client_secret: None, cors_allowed_origins: vec![], platform_allowed_clients: vec![], + features: compliance_core::Features::default(), } } diff --git a/compliance-agent/tests/demo_seed.rs b/compliance-agent/tests/demo_seed.rs new file mode 100644 index 0000000..f4e9cf4 --- /dev/null +++ b/compliance-agent/tests/demo_seed.rs @@ -0,0 +1,51 @@ +//! Demo-target seeding API (needs Mongo; not part of the CI `--lib` run). +mod common; + +use common::TestServer; + +#[tokio::test] +async fn lists_the_bundled_demo_targets() { + let server = TestServer::start().await; + let res = server + .client + .get(format!("{}/api/v1/targets/demo-seed", server.base_url)) + .send() + .await + .expect("request"); + assert_eq!(res.status(), 200); + let body: serde_json::Value = res.json().await.expect("json"); + let targets = body["targets"].as_array().expect("targets array"); + assert!(!targets.is_empty()); + for t in targets { + assert!(t["key"].is_string(), "{t}"); + assert_eq!(t["source_only"], serde_json::json!(true), "{t}"); + assert!( + t["name"].as_str().expect("name").starts_with("Demo · "), + "{t}" + ); + } +} + +#[tokio::test] +async fn unknown_target_key_is_a_client_error_and_seeds_nothing() { + let server = TestServer::start().await; + let res = server + .client + .post(format!("{}/api/v1/targets/demo-seed", server.base_url)) + .json(&serde_json::json!({ "names": ["not-a-demo-target"] })) + .send() + .await + .expect("request"); + assert_eq!(res.status(), 400); + + let listed: serde_json::Value = server + .client + .get(format!("{}/api/v1/targets", server.base_url)) + .send() + .await + .expect("list") + .json() + .await + .expect("json"); + assert_eq!(listed["data"].as_array().map(Vec::len), Some(0)); +} diff --git a/compliance-core/src/config.rs b/compliance-core/src/config.rs index bc5a434..e797450 100644 --- a/compliance-core/src/config.rs +++ b/compliance-core/src/config.rs @@ -77,6 +77,78 @@ pub struct AgentConfig { pub cors_allowed_origins: Vec, /// Keycloak clients (JWT `azp`) allowed to call `/api/v1/platform/*`. pub platform_allowed_clients: Vec, + /// Deployment feature flags (`PW_FEATURES`, comma list). Exposed on the + /// public `/api/v1/platform/version` handshake so the dashboard reads the + /// same set the agent enforces. + pub features: Features, +} + +/// Deployment feature flags (`PW_FEATURES`). +/// +/// Flags are free-form lowercase tokens; the ones the agent acts on are the +/// associated constants below. Unknown tokens are kept (and reported on the +/// handshake) so a dashboard-only flag needs no agent release. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(transparent)] +pub struct Features { + flags: Vec, +} + +impl Features { + /// Static-analysis only: the scan pipeline skips every stage that needs + /// live infrastructure (DAST, pentest, ICS probe, ephemeral PLC runtime) + /// and records them as `skipped` on the scan run instead of failing. + pub const SOURCE_ONLY: &'static str = "source_only"; + + /// Parse a comma-separated flag list. Tokens are trimmed and lowercased; + /// empty tokens are dropped; duplicates collapse. + pub fn parse(csv: &str) -> Self { + let mut flags: Vec = Vec::new(); + for raw in csv.split(',') { + let f = raw.trim().to_ascii_lowercase(); + if !f.is_empty() && !flags.contains(&f) { + flags.push(f); + } + } + Self { flags } + } + + /// Whether `flag` is set. + pub fn has(&self, flag: &str) -> bool { + self.flags.iter().any(|f| f == flag) + } + + /// Shorthand for [`Self::has`] with [`Self::SOURCE_ONLY`]. + pub fn source_only(&self) -> bool { + self.has(Self::SOURCE_ONLY) + } + + /// All set flags, in `PW_FEATURES` order. + pub fn flags(&self) -> &[String] { + &self.flags + } +} + +#[cfg(test)] +mod features_tests { + use super::Features; + + #[test] + fn parse_trims_lowercases_and_dedups() { + let f = Features::parse(" Source_Only ,, foo,foo "); + assert_eq!(f.flags(), ["source_only", "foo"]); + assert!(f.source_only()); + assert!(f.has("foo")); + assert!(!f.has("bar")); + } + + #[test] + fn empty_means_no_flags() { + let f = Features::parse(""); + assert!(f.flags().is_empty()); + assert!(!f.source_only()); + assert_eq!(f, Features::default()); + } } /// Where to pull the OSCAL control catalog from breakpilot-compliance, and where diff --git a/compliance-core/src/lib.rs b/compliance-core/src/lib.rs index 260b045..0d4c021 100644 --- a/compliance-core/src/lib.rs +++ b/compliance-core/src/lib.rs @@ -14,6 +14,6 @@ pub mod auth; #[cfg(feature = "axum")] pub mod tenant_ctx; -pub use config::{AgentConfig, DashboardConfig, PlcRuntimeConfig}; +pub use config::{AgentConfig, DashboardConfig, Features, PlcRuntimeConfig}; pub use error::CoreError; pub use tenant::{OrgRole, TenantContext, TenantStatus}; diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index b850955..d1f3354 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -51,7 +51,7 @@ pub use pentest::{ }; pub use repository::ScanTrigger; pub use sbom::{SbomEntry, VulnRef}; -pub use scan::{ScanPhase, ScanRun, ScanRunStatus, ScanType}; +pub use scan::{ScanPhase, ScanRun, ScanRunStatus, ScanType, SkippedStage}; pub use werkbank::{ CompleteRequest, CompleteResponse, DastCollect, Executor, HeartbeatAck, HeartbeatRequest, InputRef, Job, JobCollect, JobRecord, JobResult, JobRuntime, JobStatus, JobType, LeaseRequest, diff --git a/compliance-core/src/models/scan.rs b/compliance-core/src/models/scan.rs index 33be968..abd25a5 100644 --- a/compliance-core/src/models/scan.rs +++ b/compliance-core/src/models/scan.rs @@ -100,6 +100,60 @@ pub struct ScanRun { pub started_at: DateTime, #[serde(default, with = "super::serde_helpers::opt_bson_datetime")] pub completed_at: Option>, + /// Stages the pipeline deliberately did not run (e.g. a deployment + /// feature flag turned them off). Distinct from `error_message`: a + /// skipped stage is not a failure. + #[serde(default)] + pub skipped_stages: Vec, +} + +/// A pipeline stage that was planned but intentionally not executed. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct SkippedStage { + /// Stage id (`dast`, `pentest`, `ics_probe`, `plc_runtime`, …). + pub stage: String, + /// Always `skipped` — present so the entry reads like a stage result. + pub status: String, + /// Why it was skipped (`feature disabled`, …). + pub reason: String, +} + +impl SkippedStage { + /// The reason recorded when a deployment feature flag disables a stage. + pub const FEATURE_DISABLED: &'static str = "feature disabled"; + + pub fn feature_disabled(stage: impl Into) -> Self { + Self { + stage: stage.into(), + status: "skipped".to_string(), + reason: Self::FEATURE_DISABLED.to_string(), + } + } +} + +#[cfg(test)] +mod skipped_stage_tests { + use super::{ScanRun, ScanTrigger, SkippedStage}; + + #[test] + fn feature_disabled_reads_like_a_stage_result() { + let s = SkippedStage::feature_disabled("dast"); + assert_eq!(s.stage, "dast"); + assert_eq!(s.status, "skipped"); + assert_eq!(s.reason, SkippedStage::FEATURE_DISABLED); + let j = serde_json::to_value(&s).expect("serialize"); + assert_eq!(j["stage"], "dast"); + assert_eq!(j["status"], "skipped"); + } + + #[test] + fn scan_runs_without_the_field_deserialize_as_nothing_skipped() { + let run = ScanRun::new("repo".into(), ScanTrigger::Manual); + let mut j = serde_json::to_value(&run).expect("serialize"); + j.as_object_mut().expect("object").remove("skipped_stages"); + let back: ScanRun = serde_json::from_value(j).expect("older document"); + assert!(back.skipped_stages.is_empty()); + } } impl ScanRun { @@ -116,6 +170,7 @@ impl ScanRun { error_message: None, started_at: Utc::now(), completed_at: None, + skipped_stages: Vec::new(), } } } diff --git a/docs/guide/demo-targets.md b/docs/guide/demo-targets.md index 5ca9eaf..5360145 100644 --- a/docs/guide/demo-targets.md +++ b/docs/guide/demo-targets.md @@ -4,7 +4,14 @@ Prüfwerk ships a small, versioned set of **demo targets** — representative inputs that exercise every scan path repeatably. They double as the fixture set for the nightly regression and as a ready-made walkthrough for demos. -The set lives in [`fixtures/demo-targets/targets.json`](https://git.breakpilot.com/sharang/compliance-scanner-agent/src/branch/main/fixtures/demo-targets/targets.json). +The set lives in [`fixtures/demo-targets/targets.json`](https://git.breakpilot.com/platform/pruefwerk/src/branch/main/fixtures/demo-targets/targets.json) +and is compiled into the agent binary, so a deployed agent can seed itself. + +The shipped set is **source-only**: every required artifact is a file or a git +repository, so the whole set scans in an environment with no browser, no +soft-PLC and no reachable devices (`PW_FEATURES=source_only`). The web-app +target, which needed a running Juice Shop for DAST and pentest, is not part of +it any more. ## What is in the set @@ -13,7 +20,6 @@ The set lives in [`fixtures/demo-targets/targets.json`](https://git.breakpilot.c | `plc-pump-station` | PLC / SPS (composite) | `pump_station.st`, `pump_fbd.xml`, optional Modbus live URL, optional firmware image | PLC control-logic SAST (ST **and** FBD-as-XML), ICS probe, semantic CRA/master-control mapping | | `plc-conveyor-line` | PLC / SPS | `conveyor.xml`, `traffic_light.st` | Pure control-logic SAST on a PLCopen-XML program plus a realistic OpenPLC-style sample with three planted defects | | `git-cra-vuln-demo` | Backend service | git `sharang/cra-vuln-demo` | Plain git SAST: Semgrep → CWE → CRA control refs (`cra-ai-8/13/20`) | -| `web-juice-shop` | Web app | git `juice-shop/juice-shop` @ v19.2.1 + live URL | SAST + SBOM/CVE on a large Node app, DAST + pentest against the running instance | | `firmware-zephyr-example` | Firmware (RTOS) | git `zephyrproject-rtos/example-application` | Tramiton detect handoff (`build_system = zephyr`), firmware source SBOM | The PLC files are the same ones under `examples/plc-demo/` that the PLC rule @@ -32,13 +38,38 @@ every CI run (`compliance-agent::fixtures` tests). | Env var | Used by | Meaning | |---------|---------|---------| -| `DEMO_WEB_URL` | `web-juice-shop` | Live URL for DAST/pentest. Default `http://localhost:3000` — run `docker run -d -p 3000:3000 bkimminich/juice-shop:v19.2.1`. | | `DEMO_PLC_MODBUS_URL` | `plc-pump-station` | Modbus endpoint for the ICS probe (in-cluster default `modbus://plc-sim:502`). Skipped when unset. | | `DEMO_PLC_FIRMWARE_IMAGE` | `plc-pump-station` | Absolute path to a device firmware image to attach. Skipped when unset. | ## Seeding the targets +### From the dashboard (what a trial user does) + +A fresh tenant's empty targets page offers **Add demo targets**. It calls the +agent, which creates each target from its bundled manifest, attaches the +artifacts, runs detection and starts a scan — the same code path as the +onboarding wizard, so the result is ordinary targets, findings and usage +events. Seeding twice is harmless: a target that is already there is reported +as `exists` and nothing is re-run unless a rescan is asked for. + +The endpoints behind the button: + +| Request | Meaning | +|---------|---------| +| `GET /api/v1/targets/demo-seed` | What would be created: `key`, display `name`, `kind`, `description`, `source_only`. | +| `POST /api/v1/targets/demo-seed` | Seed them. Body `{"names": ["…"], "rescan": false}`; empty `names` seeds all. Answers `202` with one row per target: `status` = `queued` \| `exists` \| `failed`. | + +The nightly reset of the sales demo tenant uses the same seeding code through +`POST /api/v1/platform/tenants/demo/reset {"tenant_id": "…", "seed": true}` +with a service token, so it needs no user session. + +### From the command line (ops) + ```bash +# let the agent seed itself from its own manifest +scripts/seed-demo-targets.sh --api + + # against a local dev agent (no Keycloak → dev tenant) scripts/seed-demo-targets.sh @@ -46,7 +77,7 @@ scripts/seed-demo-targets.sh scripts/seed-demo-targets.sh --scan # only some targets -scripts/seed-demo-targets.sh --only web-juice-shop,git-cra-vuln-demo +scripts/seed-demo-targets.sh --only plc-pump-station,git-cra-vuln-demo # wipe every "Demo · " target and reseed scripts/seed-demo-targets.sh --reset --scan @@ -71,8 +102,9 @@ Each target can also be created through the onboarding wizard: [PLC / SPS (CODESYS)](/guide/plc). 2. **Git targets** — pick the type, add the git URL and branch from the manifest. Public repos need no credentials. -3. **Web app** — add the git repo *and* the live URL; enable DAST and, if - wanted, pentest on the scan-selection step. +3. **Web app** — not part of the shipped set: add the git repo *and* a live + URL yourself, then enable DAST and, if wanted, pentest on the + scan-selection step. Both are unavailable while `PW_FEATURES=source_only`. ## Golden baselines diff --git a/fixtures/demo-targets/targets.json b/fixtures/demo-targets/targets.json index 15ccb1c..7a3d338 100644 --- a/fixtures/demo-targets/targets.json +++ b/fixtures/demo-targets/targets.json @@ -105,35 +105,6 @@ ] } }, - { - "key": "web-juice-shop", - "name": "Web app · OWASP Juice Shop", - "target_type": "web_app", - "description": "WebApp target: git repo for SAST/SBOM/CVE plus a live URL for DAST + pentest. Run the instance locally with `docker run -d -p 3000:3000 bkimminich/juice-shop:v19.2.1` or point DEMO_WEB_URL at a deployed copy.", - "artifacts": [ - { - "kind": "git_repo", - "source_ref": "https://github.com/juice-shop/juice-shop.git", - "branch": "master", - "pin": "f87c6f58c49b61c9de20e4d69a9bdb1fbd4f3bd3", - "pin_tag": "v19.2.1" - }, - { - "kind": "live_url", - "source_ref_env": "DEMO_WEB_URL", - "source_ref": "http://localhost:3000" - } - ], - "expect": { - "min_findings": 10, - "min_sbom_components": 500, - "scans_offered": [ - "sast", - "dast" - ], - "pentest_supported": true - } - }, { "key": "firmware-zephyr-example", "name": "Firmware RTOS · Zephyr example-application", diff --git a/scripts/seed-demo-targets.sh b/scripts/seed-demo-targets.sh index c35ea01..ad1767a 100755 --- a/scripts/seed-demo-targets.sh +++ b/scripts/seed-demo-targets.sh @@ -1,20 +1,29 @@ #!/usr/bin/env bash # Seed the curated demo targets (#187) into a running compliance-agent. # +# The agent seeds itself now: `POST /api/v1/targets/demo-seed` runs the same +# create → upload → detect → scan sequence server-side from the manifest +# compiled into its binary, which is what the dashboard's "Add demo targets" +# button and the nightly demo reset use. `--api` below calls that endpoint; the +# client-side path stays for seeding an agent whose bundled manifest is older +# than this checkout, and for --reset. +# # Reads fixtures/demo-targets/targets.json and, for every target: # 1. POST /api/v1/targets (name = name_prefix + name) # 2. POST /api/v1/targets/{id}/artifacts/upload for each `upload` artifact # 3. POST /api/v1/targets/{id}/detect (surface detected facts) # 4. POST /api/v1/targets/{id}/scan (only with --scan) # -# Artifact env overrides (see the manifest): DEMO_WEB_URL, DEMO_PLC_MODBUS_URL, +# Artifact env overrides (see the manifest): DEMO_PLC_MODBUS_URL, # DEMO_PLC_FIRMWARE_IMAGE. Optional artifacts whose env var is unset are # skipped, so the set seeds on a bare laptop; set them on comp-dev / Orca. # # Usage: # scripts/seed-demo-targets.sh # seed all # scripts/seed-demo-targets.sh --scan # seed + trigger first scan -# scripts/seed-demo-targets.sh --only web-juice-shop,git-cra-vuln-demo +# scripts/seed-demo-targets.sh --only plc-pump-station,git-cra-vuln-demo +# scripts/seed-demo-targets.sh --api # let the agent seed itself +# scripts/seed-demo-targets.sh --api --scan # … and rescan what exists # scripts/seed-demo-targets.sh --reset # delete every "Demo · " target # scripts/seed-demo-targets.sh --reset --scan # reset, reseed, scan # @@ -31,11 +40,13 @@ MANIFEST="${MANIFEST:-$ROOT/fixtures/demo-targets/targets.json}" DO_SCAN=0 DO_RESET=0 +USE_API=0 ONLY="" while [[ $# -gt 0 ]]; do case "$1" in --scan) DO_SCAN=1 ;; --reset) DO_RESET=1 ;; + --api) USE_API=1 ;; --only) ONLY="$2"; shift ;; -h|--help) sed -n '2,25p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; *) echo "unknown arg: $1" >&2; exit 2 ;; @@ -72,6 +83,26 @@ api() { PREFIX="$(jq -r '.name_prefix' "$MANIFEST")" +# --api: hand the whole job to the agent, which seeds from the manifest baked +# into its own binary. --only selects keys, --scan means rescan what exists. +seed_via_api() { + local names="[]" + if [[ -n "$ONLY" ]]; then + names=$(jq -cn --arg o "$ONLY" '$o | split(",")') + fi + local rescan="false" + [[ "$DO_SCAN" == 1 ]] && rescan="true" + local body out + body=$(jq -cn --argjson n "$names" --argjson r "$rescan" '{names: $n, rescan: $r}') + out=$(api POST "/api/v1/targets/demo-seed" -H 'Content-Type: application/json' -d "$body") + jq -r '.seeded[] | " \(.status)\t\(.name)\t\(.error // "")"' <<<"$out" + if jq -e '.seeded[] | select(.status == "failed")' <<<"$out" >/dev/null; then + echo "$(red "some targets failed")" >&2 + return 1 + fi + echo "$(green "seeded")" +} + reset_targets() { echo "== reset: deleting targets named '${PREFIX}*'" local list ids @@ -168,6 +199,13 @@ seed_target() { [[ "$DO_RESET" == 1 ]] && reset_targets +if [[ "$USE_API" == 1 ]]; then + echo "== seeding via the agent's own manifest → $AGENT_URL" + seed_via_api + echo "== done" + exit 0 +fi + echo "== seeding from $MANIFEST → $AGENT_URL" jq -c '.targets[]' "$MANIFEST" | while IFS= read -r t; do key=$(jq -r '.key' <<<"$t")