Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9919afa0ee | ||
|
|
9ec07ff7a1 | ||
|
|
0e57c2d7a7 | ||
|
|
c6a02f0ac3 | ||
|
|
17f788858d | ||
|
|
c6b5622113 | ||
|
|
a204f0c59c |
+14
-3
@@ -191,13 +191,18 @@ jobs:
|
||||
image: docker:27-cli
|
||||
steps:
|
||||
- name: Build, push and trigger orca redeploy
|
||||
env:
|
||||
# PAT for fetching the private tramiton-core git dependency during the
|
||||
# image build (injected as a BuildKit secret, never baked into a layer).
|
||||
TRAMITON_FETCH_TOKEN: ${{ secrets.TRAMITON_FETCH_TOKEN }}
|
||||
run: |
|
||||
apk add --no-cache git curl openssl
|
||||
git init && git remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git"
|
||||
git fetch --depth=1 origin "${GITHUB_SHA}" && git checkout FETCH_HEAD
|
||||
IMAGE=registry.meghsakha.com/compliance-agent
|
||||
echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login registry.meghsakha.com -u "${{ secrets.REGISTRY_USERNAME }}" --password-stdin
|
||||
docker build -f Dockerfile.agent -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
|
||||
DOCKER_BUILDKIT=1 docker build --secret id=tramiton_token,env=TRAMITON_FETCH_TOKEN \
|
||||
-f Dockerfile.agent -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
|
||||
docker push "$IMAGE:latest" && docker push "$IMAGE:${GITHUB_SHA}"
|
||||
PAYLOAD=$(printf '{"ref":"refs/heads/main","repository":{"full_name":"sharang/compliance-scanner-agent"},"head_commit":{"id":"%s","message":"deploy agent"}}' "${GITHUB_SHA}")
|
||||
SIG=$(printf '%s' "$PAYLOAD" | openssl dgst -sha256 -hmac "${{ secrets.ORCA_WEBHOOK_SECRET }}" | awk '{print $2}')
|
||||
@@ -212,13 +217,16 @@ jobs:
|
||||
image: docker:27-cli
|
||||
steps:
|
||||
- name: Build, push and trigger orca redeploy
|
||||
env:
|
||||
TRAMITON_FETCH_TOKEN: ${{ secrets.TRAMITON_FETCH_TOKEN }}
|
||||
run: |
|
||||
apk add --no-cache git curl openssl
|
||||
git init && git remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git"
|
||||
git fetch --depth=1 origin "${GITHUB_SHA}" && git checkout FETCH_HEAD
|
||||
IMAGE=registry.meghsakha.com/compliance-dashboard
|
||||
echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login registry.meghsakha.com -u "${{ secrets.REGISTRY_USERNAME }}" --password-stdin
|
||||
docker build -f Dockerfile.dashboard -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
|
||||
DOCKER_BUILDKIT=1 docker build --secret id=tramiton_token,env=TRAMITON_FETCH_TOKEN \
|
||||
-f Dockerfile.dashboard -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
|
||||
docker push "$IMAGE:latest" && docker push "$IMAGE:${GITHUB_SHA}"
|
||||
PAYLOAD=$(printf '{"ref":"refs/heads/main","repository":{"full_name":"sharang/compliance-scanner-agent"},"head_commit":{"id":"%s","message":"deploy dashboard"}}' "${GITHUB_SHA}")
|
||||
SIG=$(printf '%s' "$PAYLOAD" | openssl dgst -sha256 -hmac "${{ secrets.ORCA_WEBHOOK_SECRET }}" | awk '{print $2}')
|
||||
@@ -254,13 +262,16 @@ jobs:
|
||||
image: docker:27-cli
|
||||
steps:
|
||||
- name: Build, push and trigger orca redeploy
|
||||
env:
|
||||
TRAMITON_FETCH_TOKEN: ${{ secrets.TRAMITON_FETCH_TOKEN }}
|
||||
run: |
|
||||
apk add --no-cache git curl openssl
|
||||
git init && git remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git"
|
||||
git fetch --depth=1 origin "${GITHUB_SHA}" && git checkout FETCH_HEAD
|
||||
IMAGE=registry.meghsakha.com/compliance-mcp
|
||||
echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login registry.meghsakha.com -u "${{ secrets.REGISTRY_USERNAME }}" --password-stdin
|
||||
docker build -f Dockerfile.mcp -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
|
||||
DOCKER_BUILDKIT=1 docker build --secret id=tramiton_token,env=TRAMITON_FETCH_TOKEN \
|
||||
-f Dockerfile.mcp -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
|
||||
docker push "$IMAGE:latest" && docker push "$IMAGE:${GITHUB_SHA}"
|
||||
PAYLOAD=$(printf '{"ref":"refs/heads/main","repository":{"full_name":"sharang/compliance-scanner-agent"},"head_commit":{"id":"%s","message":"deploy mcp"}}' "${GITHUB_SHA}")
|
||||
SIG=$(printf '%s' "$PAYLOAD" | openssl dgst -sha256 -hmac "${{ secrets.ORCA_WEBHOOK_SECRET }}" | awk '{print $2}')
|
||||
|
||||
+10
-1
@@ -2,7 +2,16 @@ FROM rust:1.94-bookworm AS builder
|
||||
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
RUN cargo build --release -p compliance-agent
|
||||
# compliance-agent depends on the private tramiton-core git repo. Authenticate
|
||||
# the fetch with a PAT passed as a BuildKit secret (never baked into a layer).
|
||||
# Build with: DOCKER_BUILDKIT=1 docker build --secret id=tramiton_token,env=TRAMITON_FETCH_TOKEN ...
|
||||
RUN --mount=type=secret,id=tramiton_token \
|
||||
if [ -s /run/secrets/tramiton_token ]; then \
|
||||
git config --global \
|
||||
url."https://sharang:$(cat /run/secrets/tramiton_token)@gitea.meghsakha.com/".insteadOf \
|
||||
"ssh://git@gitea.meghsakha.com:22222/"; \
|
||||
fi && \
|
||||
CARGO_NET_GIT_FETCH_WITH_CLI=true cargo build --release -p compliance-agent
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
RUN apt-get update && apt-get install -y ca-certificates libssl3 git curl python3 python3-pip npm golang-go php-cli && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
+10
-1
@@ -7,7 +7,16 @@ ARG DOCS_URL=/docs
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
ENV DOCS_URL=${DOCS_URL}
|
||||
RUN dx build --release --package compliance-dashboard
|
||||
# compliance-agent (a workspace member) depends on the private tramiton-core git
|
||||
# repo, so the workspace resolve needs it even to build the dashboard.
|
||||
# Authenticate the fetch with a PAT passed as a BuildKit secret.
|
||||
RUN --mount=type=secret,id=tramiton_token \
|
||||
if [ -s /run/secrets/tramiton_token ]; then \
|
||||
git config --global \
|
||||
url."https://sharang:$(cat /run/secrets/tramiton_token)@gitea.meghsakha.com/".insteadOf \
|
||||
"ssh://git@gitea.meghsakha.com:22222/"; \
|
||||
fi && \
|
||||
CARGO_NET_GIT_FETCH_WITH_CLI=true dx build --release --package compliance-dashboard
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
RUN apt-get update && apt-get install -y ca-certificates libssl3 && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
+10
-1
@@ -2,7 +2,16 @@ FROM rust:1.94-bookworm AS builder
|
||||
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
RUN cargo build --release -p compliance-mcp
|
||||
# compliance-agent (a workspace member) depends on the private tramiton-core git
|
||||
# repo, so the workspace resolve needs it even to build the mcp binary.
|
||||
# Authenticate the fetch with a PAT passed as a BuildKit secret.
|
||||
RUN --mount=type=secret,id=tramiton_token \
|
||||
if [ -s /run/secrets/tramiton_token ]; then \
|
||||
git config --global \
|
||||
url."https://sharang:$(cat /run/secrets/tramiton_token)@gitea.meghsakha.com/".insteadOf \
|
||||
"ssh://git@gitea.meghsakha.com:22222/"; \
|
||||
fi && \
|
||||
CARGO_NET_GIT_FETCH_WITH_CLI=true cargo build --release -p compliance-mcp
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
RUN apt-get update && apt-get install -y ca-certificates libssl3 && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
@@ -63,7 +63,11 @@ impl ComplianceAgent {
|
||||
let db = self.db_pool.for_tenant_id(tenant_id).await?;
|
||||
let orchestrator =
|
||||
PipelineOrchestrator::new(self.config.clone(), db, self.llm.clone(), self.http.clone());
|
||||
orchestrator.run(repo_id, trigger).await
|
||||
if self.config.unified_pipeline {
|
||||
orchestrator.run_target(repo_id, trigger).await
|
||||
} else {
|
||||
orchestrator.run(repo_id, trigger).await
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a PR review: scan the diff and post review comments.
|
||||
|
||||
@@ -9,6 +9,7 @@ pub mod help_chat;
|
||||
pub mod issues;
|
||||
pub mod mcp_tokens;
|
||||
pub mod notifications;
|
||||
pub mod onboarding;
|
||||
pub mod pentest_handlers;
|
||||
pub use pentest_handlers as pentest;
|
||||
pub mod repos;
|
||||
|
||||
@@ -0,0 +1,390 @@
|
||||
//! Onboarding API — CRUD for unified targets, artifact add, classification, and
|
||||
//! the scan-applicability matrix. The wizard (and future integrations) drive
|
||||
//! onboarding through these endpoints.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::{Extension, Path, Query};
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use mongodb::bson::{doc, oid::ObjectId, to_bson};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use compliance_core::models::{
|
||||
Artifact, ArtifactKind, ComplianceProfile, OnboardedTarget, PlcFormat, TargetScanConfig,
|
||||
TargetType,
|
||||
};
|
||||
use compliance_core::scan_matrix::{applicable_scans, supports_pentest};
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use crate::agent::ComplianceAgent;
|
||||
use crate::classify::{classify_target, MockFirmwareDetector};
|
||||
|
||||
use super::dto::tenant_db;
|
||||
use super::{collect_cursor_async, ApiResponse, PaginationParams};
|
||||
|
||||
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
||||
|
||||
/// A client-supplied artifact spec. The server builds the [`Artifact`] (and its
|
||||
/// id) from it, so clients never set internal fields.
|
||||
#[derive(Deserialize)]
|
||||
pub struct ArtifactInput {
|
||||
pub kind: ArtifactKind,
|
||||
pub source_ref: String,
|
||||
#[serde(default)]
|
||||
pub branch: Option<String>,
|
||||
#[serde(default)]
|
||||
pub plc_format: Option<PlcFormat>,
|
||||
}
|
||||
|
||||
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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct CreateTargetRequest {
|
||||
pub name: String,
|
||||
pub target_type: TargetType,
|
||||
#[serde(default)]
|
||||
pub description: Option<String>,
|
||||
#[serde(default)]
|
||||
pub artifacts: Vec<ArtifactInput>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct UpdateTargetRequest {
|
||||
pub name: Option<String>,
|
||||
pub target_type: Option<TargetType>,
|
||||
pub scan_config: Option<TargetScanConfig>,
|
||||
pub compliance_profile: Option<ComplianceProfile>,
|
||||
pub scan_schedule: Option<String>,
|
||||
}
|
||||
|
||||
/// One applicable-scan option, serialized for the wizard.
|
||||
#[derive(Serialize)]
|
||||
pub struct ScanOptionDto {
|
||||
pub scan: String,
|
||||
pub default_on: bool,
|
||||
pub rationale: String,
|
||||
pub required_artifact: Option<String>,
|
||||
pub blocked_reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct ApplicableScansResponse {
|
||||
pub scans: Vec<ScanOptionDto>,
|
||||
pub pentest_supported: bool,
|
||||
}
|
||||
|
||||
fn parse_oid(id: &str) -> Result<ObjectId, StatusCode> {
|
||||
ObjectId::parse_str(id).map_err(|_| StatusCode::BAD_REQUEST)
|
||||
}
|
||||
|
||||
/// GET /api/v1/targets — list onboarded targets (paginated).
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn list_targets(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Query(params): Query<PaginationParams>,
|
||||
) -> Result<Json<ApiResponse<Vec<OnboardedTarget>>>, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let skip = (params.page.saturating_sub(1)) * params.limit as u64;
|
||||
let total = db
|
||||
.onboarded_targets()
|
||||
.count_documents(doc! {})
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
let targets = match db
|
||||
.onboarded_targets()
|
||||
.find(doc! {})
|
||||
.skip(skip)
|
||||
.limit(params.limit)
|
||||
.await
|
||||
{
|
||||
Ok(cursor) => collect_cursor_async(cursor).await,
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to fetch onboarded targets: {e}");
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
Ok(Json(ApiResponse {
|
||||
data: targets,
|
||||
total: Some(total),
|
||||
page: Some(params.page),
|
||||
}))
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets — create an onboarded target.
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn create_target(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Json(req): Json<CreateTargetRequest>,
|
||||
) -> Result<Json<ApiResponse<OnboardedTarget>>, StatusCode> {
|
||||
let mut target = OnboardedTarget::new(req.name, req.target_type);
|
||||
target.description = req.description;
|
||||
target.artifacts = req.artifacts.iter().map(ArtifactInput::build).collect();
|
||||
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let res = db
|
||||
.onboarded_targets()
|
||||
.insert_one(&target)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
target.id = res.inserted_id.as_object_id();
|
||||
Ok(Json(ApiResponse {
|
||||
data: target,
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// GET /api/v1/targets/{id} — fetch one target.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn get_target(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<Json<ApiResponse<OnboardedTarget>>, StatusCode> {
|
||||
let oid = parse_oid(&id)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let target = db
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
Ok(Json(ApiResponse {
|
||||
data: target,
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// PATCH /api/v1/targets/{id} — update mutable fields.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn update_target(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
Json(req): Json<UpdateTargetRequest>,
|
||||
) -> Result<Json<ApiResponse<OnboardedTarget>>, StatusCode> {
|
||||
let oid = parse_oid(&id)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
|
||||
let mut set = doc! { "updated_at": mongodb::bson::DateTime::now() };
|
||||
if let Some(name) = req.name {
|
||||
set.insert("name", name);
|
||||
}
|
||||
if let Some(tt) = req.target_type {
|
||||
set.insert(
|
||||
"target_type",
|
||||
to_bson(&tt).map_err(|_| StatusCode::BAD_REQUEST)?,
|
||||
);
|
||||
}
|
||||
if let Some(sc) = req.scan_config {
|
||||
set.insert(
|
||||
"scan_config",
|
||||
to_bson(&sc).map_err(|_| StatusCode::BAD_REQUEST)?,
|
||||
);
|
||||
}
|
||||
if let Some(cp) = req.compliance_profile {
|
||||
set.insert(
|
||||
"compliance_profile",
|
||||
to_bson(&cp).map_err(|_| StatusCode::BAD_REQUEST)?,
|
||||
);
|
||||
}
|
||||
if let Some(ss) = req.scan_schedule {
|
||||
set.insert("scan_schedule", ss);
|
||||
}
|
||||
|
||||
db.onboarded_targets()
|
||||
.update_one(doc! { "_id": oid }, doc! { "$set": set })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
get_target(Extension(agent), tenant, Path(id)).await
|
||||
}
|
||||
|
||||
/// DELETE /api/v1/targets/{id} — remove the target and its findings/scans.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn delete_target(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let oid = parse_oid(&id)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
db.onboarded_targets()
|
||||
.delete_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
// Cascade the collections keyed by repo_id == target id (best-effort).
|
||||
let by_repo = doc! { "repo_id": &id };
|
||||
let _ = db.findings().delete_many(by_repo.clone()).await;
|
||||
let _ = db.scan_runs().delete_many(by_repo.clone()).await;
|
||||
let _ = db.sbom_entries().delete_many(by_repo.clone()).await;
|
||||
let _ = db.cve_alerts().delete_many(by_repo).await;
|
||||
Ok(Json(serde_json::json!({ "status": "deleted" })))
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets/{id}/artifacts — attach an artifact (by reference).
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn add_artifact(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
Json(input): Json<ArtifactInput>,
|
||||
) -> Result<Json<ApiResponse<OnboardedTarget>>, StatusCode> {
|
||||
let oid = parse_oid(&id)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let artifact = to_bson(&input.build()).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
db.onboarded_targets()
|
||||
.update_one(
|
||||
doc! { "_id": oid },
|
||||
doc! { "$push": { "artifacts": artifact }, "$set": { "updated_at": mongodb::bson::DateTime::now() } },
|
||||
)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
get_target(Extension(agent), tenant, Path(id)).await
|
||||
}
|
||||
|
||||
/// GET /api/v1/targets/{id}/applicable-scans — the scan-applicability matrix.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn applicable_scans_for_target(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<Json<ApiResponse<ApplicableScansResponse>>, StatusCode> {
|
||||
let oid = parse_oid(&id)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let target = db
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
|
||||
let scans = applicable_scans(&target)
|
||||
.into_iter()
|
||||
.map(|o| ScanOptionDto {
|
||||
scan: o.scan.to_string(),
|
||||
default_on: o.default_on,
|
||||
rationale: o.rationale,
|
||||
required_artifact: o.required_artifact.map(|k| k.to_string()),
|
||||
blocked_reason: o.blocked_reason,
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(Json(ApiResponse {
|
||||
data: ApplicableScansResponse {
|
||||
scans,
|
||||
pentest_supported: supports_pentest(target.target_type),
|
||||
},
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets/{id}/detect — classify the 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 tramiton firmware analysis) is a follow-up background step.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn detect_target(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<Json<ApiResponse<OnboardedTarget>>, StatusCode> {
|
||||
let oid = parse_oid(&id)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let mut target = db
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
|
||||
// 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
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
let classification_bson =
|
||||
to_bson(&classification).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
db.onboarded_targets()
|
||||
.update_one(
|
||||
doc! { "_id": oid },
|
||||
doc! { "$set": { "classification": classification_bson, "updated_at": mongodb::bson::DateTime::now() } },
|
||||
)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
target.classification = Some(classification);
|
||||
|
||||
Ok(Json(ApiResponse {
|
||||
data: target,
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets/{id}/scan — trigger a scan for the target.
|
||||
///
|
||||
/// Dispatches to the unified pipeline when `UNIFIED_PIPELINE` is set (else the
|
||||
/// legacy path). Runs in the background and returns immediately.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn trigger_target_scan(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let oid = parse_oid(&id)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
// 404 if the target doesn't exist for this tenant.
|
||||
if db
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.is_none()
|
||||
{
|
||||
return Err(StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
let agent_clone = (*agent).clone();
|
||||
let tenant_id = tenant.0.tenant_id.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = agent_clone
|
||||
.run_scan(
|
||||
&tenant_id,
|
||||
&id,
|
||||
compliance_core::models::ScanTrigger::Manual,
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::error!("Manual target scan failed for {id}: {e}");
|
||||
}
|
||||
});
|
||||
Ok(Json(serde_json::json!({ "status": "scan_triggered" })))
|
||||
}
|
||||
@@ -25,6 +25,33 @@ pub fn build_router() -> Router {
|
||||
"/api/v1/repositories/{id}/webhook-config",
|
||||
get(handlers::get_webhook_config),
|
||||
)
|
||||
// Unified onboarding targets (#131).
|
||||
.route(
|
||||
"/api/v1/targets",
|
||||
get(handlers::onboarding::list_targets).post(handlers::onboarding::create_target),
|
||||
)
|
||||
.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}/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/findings", get(handlers::list_findings))
|
||||
.route("/api/v1/findings/{id}", get(handlers::get_finding))
|
||||
.route(
|
||||
|
||||
@@ -47,6 +47,9 @@ pub fn load_config() -> Result<AgentConfig, AgentError> {
|
||||
.unwrap_or_else(|| "/tmp/compliance-scanner/repos".to_string()),
|
||||
artifact_store_base_path: env_var_opt("ARTIFACT_STORE_BASE_PATH")
|
||||
.unwrap_or_else(|| "/data/compliance-scanner/artifacts".to_string()),
|
||||
unified_pipeline: env_var_opt("UNIFIED_PIPELINE")
|
||||
.map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
|
||||
.unwrap_or(false),
|
||||
ssh_key_path: env_var_opt("SSH_KEY_PATH")
|
||||
.unwrap_or_else(|| "/data/compliance-scanner/ssh/id_ed25519".to_string()),
|
||||
keycloak_url: env_var_opt("KEYCLOAK_URL"),
|
||||
|
||||
@@ -342,6 +342,7 @@ mod tests {
|
||||
pentest_imap_password: None,
|
||||
admin_api_token: None,
|
||||
tenant_registry_url: None,
|
||||
unified_pipeline: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ mod issue_creation;
|
||||
pub mod lint;
|
||||
pub mod orchestrator;
|
||||
pub mod patterns;
|
||||
pub mod plan;
|
||||
mod pr_review;
|
||||
pub mod sbom;
|
||||
pub mod semgrep;
|
||||
|
||||
@@ -15,6 +15,7 @@ use crate::pipeline::git::GitOps;
|
||||
use crate::pipeline::gitleaks::GitleaksScanner;
|
||||
use crate::pipeline::lint::LintScanner;
|
||||
use crate::pipeline::patterns::{GdprPatternScanner, OAuthPatternScanner};
|
||||
use crate::pipeline::plan::build_scan_plan;
|
||||
use crate::pipeline::sbom::SbomScanner;
|
||||
use crate::pipeline::semgrep::SemgrepScanner;
|
||||
|
||||
@@ -419,6 +420,260 @@ impl PipelineOrchestrator {
|
||||
Ok(new_count)
|
||||
}
|
||||
|
||||
/// Unified entry point (behind `UNIFIED_PIPELINE`): run a scan for an
|
||||
/// `OnboardedTarget`. Mirrors [`Self::run`] but sources the target from
|
||||
/// `onboarded_targets` and dispatches by the scan plan.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %target_id, trigger = ?trigger))]
|
||||
pub async fn run_target(
|
||||
&self,
|
||||
target_id: &str,
|
||||
trigger: ScanTrigger,
|
||||
) -> Result<(), AgentError> {
|
||||
let oid = mongodb::bson::oid::ObjectId::parse_str(target_id)
|
||||
.map_err(|e| AgentError::Other(e.to_string()))?;
|
||||
let target = self
|
||||
.db
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await?
|
||||
.ok_or_else(|| AgentError::Other(format!("Onboarded target {target_id} not found")))?;
|
||||
|
||||
let scan_run = ScanRun::new(target_id.to_string(), trigger);
|
||||
let insert = self.db.scan_runs().insert_one(&scan_run).await?;
|
||||
let scan_run_id = insert
|
||||
.inserted_id
|
||||
.as_object_id()
|
||||
.map(|id| id.to_hex())
|
||||
.unwrap_or_default();
|
||||
|
||||
let result = self.run_target_pipeline(&target, &scan_run_id).await;
|
||||
match &result {
|
||||
Ok(count) => {
|
||||
self.db
|
||||
.scan_runs()
|
||||
.update_one(
|
||||
doc! { "_id": &insert.inserted_id },
|
||||
doc! { "$set": {
|
||||
"status": "completed",
|
||||
"current_phase": "completed",
|
||||
"new_findings_count": *count as i64,
|
||||
"completed_at": mongodb::bson::DateTime::now(),
|
||||
} },
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!(target_id, error = %e, "Unified scan pipeline failed");
|
||||
self.db
|
||||
.scan_runs()
|
||||
.update_one(
|
||||
doc! { "_id": &insert.inserted_id },
|
||||
doc! { "$set": {
|
||||
"status": "failed",
|
||||
"error_message": e.to_string(),
|
||||
"completed_at": mongodb::bson::DateTime::now(),
|
||||
} },
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
result.map(|_| ())
|
||||
}
|
||||
|
||||
/// Run the applicable scans for a target. For a code target this reuses the
|
||||
/// full legacy pipeline over the code artifact (clone → SAST umbrella →
|
||||
/// triage → persist → issues → DAST); firmware/PLC/mobile scanners are
|
||||
/// follow-ups (#128/#129/#130). Returns the number of new findings.
|
||||
async fn run_target_pipeline(
|
||||
&self,
|
||||
target: &OnboardedTarget,
|
||||
scan_run_id: &str,
|
||||
) -> Result<u32, AgentError> {
|
||||
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
|
||||
let plan = build_scan_plan(target);
|
||||
tracing::info!(
|
||||
target_id = %target_id,
|
||||
target_type = %target.target_type,
|
||||
planned_steps = plan.steps.len(),
|
||||
"Unified pipeline: scan plan built"
|
||||
);
|
||||
|
||||
// Ingest + classify (tramiton for firmware) and store the detected type.
|
||||
self.classify_and_store(target, &target_id, scan_run_id)
|
||||
.await;
|
||||
// Provision a DAST target from a LiveUrl artifact so DAST fires for
|
||||
// wizard-created targets, not just migrated ones.
|
||||
self.ensure_dast_target(target, &plan).await;
|
||||
|
||||
match target.code_artifact() {
|
||||
Some(code) if code.kind == ArtifactKind::GitRepo => {
|
||||
let repo = repo_view_from_target(target, code);
|
||||
let new_count = self.run_pipeline(&repo, scan_run_id).await?;
|
||||
self.finalize_target(target, &repo, new_count).await?;
|
||||
Ok(new_count)
|
||||
}
|
||||
Some(_) => {
|
||||
tracing::warn!(
|
||||
target_id = %target_id,
|
||||
"Unified pipeline: source-archive scanning not yet wired; skipping"
|
||||
);
|
||||
Ok(0)
|
||||
}
|
||||
None => {
|
||||
// No code to scan. Firmware/PLC/mobile static scanners land in
|
||||
// #128/#129/#130; DAST for a running URL still works when a
|
||||
// DastTarget row exists (migrated targets).
|
||||
tracing::info!(
|
||||
target_id = %target_id,
|
||||
"Unified pipeline: no code artifact; attempting DAST only"
|
||||
);
|
||||
self.update_phase(scan_run_id, "dast_scanning").await;
|
||||
self.maybe_trigger_dast(&target_id, scan_run_id).await;
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ingest the target's artifacts, classify (tramiton for firmware/RTOS/Yocto,
|
||||
/// heuristics otherwise), and store the detected classification on the target.
|
||||
/// Best-effort — never fails the scan.
|
||||
async fn classify_and_store(
|
||||
&self,
|
||||
target: &OnboardedTarget,
|
||||
target_id: &str,
|
||||
scan_run_id: &str,
|
||||
) {
|
||||
self.update_phase(scan_run_id, "classification").await;
|
||||
let ctx = crate::ingest::IngestContext::from_config(&self.config, target_id);
|
||||
let ingest_set = match crate::ingest::ingest_all(target, &ctx) {
|
||||
Ok(set) => set,
|
||||
Err(e) => {
|
||||
tracing::warn!(target_id, error = %e, "Unified pipeline: ingest for classification failed");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let working_paths = ingest_set.working_paths();
|
||||
match crate::classify::classify_target(
|
||||
target,
|
||||
&working_paths,
|
||||
&crate::classify::TramitonNative,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(classification) => {
|
||||
tracing::info!(
|
||||
target_id,
|
||||
suggested = %classification.suggested,
|
||||
"Unified pipeline: classified target"
|
||||
);
|
||||
if let (Some(oid), Ok(bson)) = (target.id, mongodb::bson::to_bson(&classification))
|
||||
{
|
||||
let _ = self
|
||||
.db
|
||||
.onboarded_targets()
|
||||
.update_one(
|
||||
doc! { "_id": oid },
|
||||
doc! { "$set": { "classification": bson } },
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(target_id, error = %e, "Unified pipeline: classification failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// If the target has a `LiveUrl` artifact and DAST is planned, provision a
|
||||
/// `DastTarget` (keyed by `repo_id` = target id) so the existing DAST trigger
|
||||
/// fires for wizard-created targets. Idempotent.
|
||||
async fn ensure_dast_target(
|
||||
&self,
|
||||
target: &OnboardedTarget,
|
||||
plan: &crate::pipeline::plan::ScanPlan,
|
||||
) {
|
||||
if !plan.has(ScanType::Dast) {
|
||||
return;
|
||||
}
|
||||
let (Some(url), Some(oid)) = (target.live_url(), target.id) else {
|
||||
return;
|
||||
};
|
||||
let target_id = oid.to_hex();
|
||||
if self
|
||||
.db
|
||||
.dast_targets()
|
||||
.find_one(doc! { "repo_id": &target_id })
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_some()
|
||||
{
|
||||
return; // already provisioned
|
||||
}
|
||||
let kind = url
|
||||
.web
|
||||
.as_ref()
|
||||
.map(|w| w.target_kind.clone())
|
||||
.unwrap_or(DastTargetType::WebApp);
|
||||
let mut dast = DastTarget::new(target.name.clone(), url.source_ref.clone(), kind);
|
||||
dast.repo_id = Some(target_id);
|
||||
if let Some(web) = &url.web {
|
||||
dast.excluded_paths = web.excluded_paths.clone();
|
||||
dast.max_crawl_depth = web.max_crawl_depth;
|
||||
dast.rate_limit = web.rate_limit;
|
||||
dast.allow_destructive = web.allow_destructive;
|
||||
}
|
||||
if let Some(auth) = &url.auth {
|
||||
dast.auth_config = Some(DastAuthConfig {
|
||||
method: auth.method.clone(),
|
||||
login_url: auth.login_url.clone(),
|
||||
username: auth.username.clone(),
|
||||
password: None,
|
||||
token: auth.secret.clone(),
|
||||
headers: auth.headers.clone(),
|
||||
});
|
||||
}
|
||||
if let Err(e) = self.db.dast_targets().insert_one(&dast).await {
|
||||
tracing::warn!(error = %e, "Unified pipeline: failed to provision DAST target");
|
||||
}
|
||||
}
|
||||
|
||||
/// Sync the onboarded-target document after a scan: bump `findings_count`
|
||||
/// and advance the git artifact's `last_scanned_commit` watermark.
|
||||
async fn finalize_target(
|
||||
&self,
|
||||
target: &OnboardedTarget,
|
||||
repo: &TrackedRepository,
|
||||
new_count: u32,
|
||||
) -> Result<(), AgentError> {
|
||||
let oid = match target.id {
|
||||
Some(id) => id,
|
||||
None => return Ok(()),
|
||||
};
|
||||
self.db
|
||||
.onboarded_targets()
|
||||
.update_one(
|
||||
doc! { "_id": oid },
|
||||
doc! {
|
||||
"$inc": { "findings_count": new_count as i64 },
|
||||
"$set": { "updated_at": mongodb::bson::DateTime::now() },
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
let repo_path = std::path::Path::new(&self.config.git_clone_base_path).join(&repo.name);
|
||||
if let (Ok(sha), Some(code)) = (GitOps::get_head_sha(&repo_path), target.code_artifact()) {
|
||||
self.db
|
||||
.onboarded_targets()
|
||||
.update_one(
|
||||
doc! { "_id": oid, "artifacts.id": &code.id },
|
||||
doc! { "$set": { "artifacts.$.git.last_scanned_commit": sha } },
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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
|
||||
@@ -436,6 +691,37 @@ impl PipelineOrchestrator {
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a legacy `TrackedRepository` view from an onboarded target's code
|
||||
/// artifact, so the unified pipeline can reuse the existing repo pipeline. The
|
||||
/// inverse of the migration's `repo_to_target`. `_id` is preserved so findings
|
||||
/// and DAST lookups resolve against the same key.
|
||||
fn repo_view_from_target(target: &OnboardedTarget, code: &Artifact) -> TrackedRepository {
|
||||
let mut repo = TrackedRepository::new(target.name.clone(), code.source_ref.clone());
|
||||
repo.id = target.id;
|
||||
if let Some(git) = &code.git {
|
||||
repo.default_branch = git.default_branch.clone();
|
||||
repo.last_scanned_commit = git.last_scanned_commit.clone();
|
||||
repo.local_path = git.local_path.clone();
|
||||
}
|
||||
if let Some(auth) = &code.auth {
|
||||
repo.auth_token = auth.secret.clone();
|
||||
repo.auth_username = auth.username.clone();
|
||||
}
|
||||
if let Some(it) = &target.scan_config.issue_tracker {
|
||||
repo.tracker_type = it.tracker_type.clone();
|
||||
repo.tracker_owner = it.owner.clone();
|
||||
repo.tracker_repo = it.repo.clone();
|
||||
repo.tracker_token = it.token.clone();
|
||||
}
|
||||
repo.scan_schedule = target.scan_schedule.clone();
|
||||
repo.webhook_enabled = target.webhook_enabled;
|
||||
repo.webhook_secret = target.webhook_secret.clone();
|
||||
repo.findings_count = target.findings_count;
|
||||
repo.created_at = target.created_at;
|
||||
repo.updated_at = target.updated_at;
|
||||
repo
|
||||
}
|
||||
|
||||
/// Extract the scheme + host from a git URL.
|
||||
/// e.g. "https://gitea.example.com/owner/repo.git" -> "https://gitea.example.com"
|
||||
/// e.g. "ssh://git@gitea.example.com:22/owner/repo.git" -> "https://gitea.example.com"
|
||||
@@ -460,3 +746,50 @@ pub(super) fn extract_base_url(git_url: &str) -> Option<String> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::{
|
||||
Artifact, ArtifactAuth, IssueTrackerConfig, TargetType, TrackerType,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn repo_view_preserves_id_git_auth_and_tracker() {
|
||||
let mut target = OnboardedTarget::new("acme".to_string(), TargetType::WebApp);
|
||||
target.id = Some(mongodb::bson::oid::ObjectId::new());
|
||||
target.findings_count = 3;
|
||||
target.scan_config.issue_tracker = Some(IssueTrackerConfig {
|
||||
tracker_type: Some(TrackerType::Gitea),
|
||||
owner: Some("acme".to_string()),
|
||||
repo: Some("web".to_string()),
|
||||
token: Some("tt".to_string()),
|
||||
});
|
||||
|
||||
let mut artifact = Artifact::git_repo("https://git/acme.git", "develop");
|
||||
if let Some(git) = artifact.git.as_mut() {
|
||||
git.last_scanned_commit = Some("abc123".to_string());
|
||||
}
|
||||
artifact.auth = Some(ArtifactAuth {
|
||||
method: "token".to_string(),
|
||||
username: Some("bob".to_string()),
|
||||
secret: Some("pat".to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
target.artifacts.push(artifact);
|
||||
|
||||
let code = target.code_artifact().expect("code artifact");
|
||||
let repo = repo_view_from_target(&target, code);
|
||||
|
||||
assert_eq!(repo.id, target.id); // preserved
|
||||
assert_eq!(repo.git_url, "https://git/acme.git");
|
||||
assert_eq!(repo.default_branch, "develop");
|
||||
assert_eq!(repo.last_scanned_commit.as_deref(), Some("abc123"));
|
||||
assert_eq!(repo.auth_token.as_deref(), Some("pat"));
|
||||
assert_eq!(repo.auth_username.as_deref(), Some("bob"));
|
||||
assert_eq!(repo.tracker_type, Some(TrackerType::Gitea));
|
||||
assert_eq!(repo.tracker_owner.as_deref(), Some("acme"));
|
||||
assert_eq!(repo.findings_count, 3);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
//! The scan plan.
|
||||
//!
|
||||
//! [`build_scan_plan`] turns an [`OnboardedTarget`] into the concrete ordered
|
||||
//! list of scans to run, each bound to the artifact it consumes. It intersects
|
||||
//! the scan-applicability matrix ([`applicable_scans`]) with the target's
|
||||
//! `scan_config` overrides: a scan runs when its required artifact is present and
|
||||
//! it is either on by default or explicitly enabled, and is not explicitly
|
||||
//! disabled. This is the decision engine the unified pipeline (`run_target`)
|
||||
//! executes.
|
||||
|
||||
use compliance_core::models::{Artifact, ArtifactKind, OnboardedTarget, ScanPhase, ScanType};
|
||||
use compliance_core::scan_matrix::applicable_scans;
|
||||
|
||||
/// One scan to run, bound to the artifact it operates on.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ScanStep {
|
||||
/// The scan to run.
|
||||
pub scan_type: ScanType,
|
||||
/// The pipeline phase to report while it runs.
|
||||
pub phase: ScanPhase,
|
||||
/// The id of the artifact this scan consumes ([`Artifact::id`]).
|
||||
pub artifact_id: String,
|
||||
}
|
||||
|
||||
/// The ordered set of scans to run for a target.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct ScanPlan {
|
||||
/// The scans, in matrix order.
|
||||
pub steps: Vec<ScanStep>,
|
||||
}
|
||||
|
||||
impl ScanPlan {
|
||||
/// Whether the plan contains a step for the given scan type.
|
||||
pub fn has(&self, scan: ScanType) -> bool {
|
||||
self.steps.iter().any(|s| s.scan_type == scan)
|
||||
}
|
||||
|
||||
/// Whether the plan is empty (nothing to run).
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.steps.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the scan plan for a target: matrix defaults ∩ `scan_config`, each scan
|
||||
/// bound to the artifact it consumes. Scans whose required artifact is absent, or
|
||||
/// that are disabled, or off-by-default and not explicitly enabled, are dropped.
|
||||
pub fn build_scan_plan(target: &OnboardedTarget) -> ScanPlan {
|
||||
let enabled = &target.scan_config.enabled_scans;
|
||||
let disabled = &target.scan_config.disabled_scans;
|
||||
|
||||
let mut steps = Vec::new();
|
||||
for option in applicable_scans(target) {
|
||||
// Required artifact missing → not runnable.
|
||||
if option.blocked_reason.is_some() {
|
||||
continue;
|
||||
}
|
||||
// Explicit opt-out wins.
|
||||
if disabled.contains(&option.scan) {
|
||||
continue;
|
||||
}
|
||||
// Run if on by default, or explicitly enabled.
|
||||
if !option.default_on && !enabled.contains(&option.scan) {
|
||||
continue;
|
||||
}
|
||||
let Some(artifact) = resolve_artifact(target, option.required_artifact) else {
|
||||
continue;
|
||||
};
|
||||
steps.push(ScanStep {
|
||||
scan_type: option.scan,
|
||||
phase: phase_for(option.scan),
|
||||
artifact_id: artifact.id.clone(),
|
||||
});
|
||||
}
|
||||
ScanPlan { steps }
|
||||
}
|
||||
|
||||
/// Resolve the artifact a scan consumes. A "code" requirement (represented by
|
||||
/// `GitRepo`) is satisfied by a git repo *or* a source archive.
|
||||
fn resolve_artifact(target: &OnboardedTarget, required: Option<ArtifactKind>) -> Option<&Artifact> {
|
||||
match required {
|
||||
Some(ArtifactKind::GitRepo) => target.code_artifact(),
|
||||
Some(kind) => target.first_of(kind),
|
||||
None => target.code_artifact().or_else(|| target.artifacts.first()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The pipeline phase reported while a given scan runs.
|
||||
fn phase_for(scan: ScanType) -> ScanPhase {
|
||||
match scan {
|
||||
ScanType::Sast => ScanPhase::Sast,
|
||||
ScanType::Sbom => ScanPhase::SbomGeneration,
|
||||
ScanType::Cve => ScanPhase::CveScanning,
|
||||
ScanType::Gdpr | ScanType::OAuth => ScanPhase::PatternScanning,
|
||||
ScanType::SecretDetection => ScanPhase::SecretDetection,
|
||||
ScanType::Lint => ScanPhase::LintScanning,
|
||||
ScanType::CodeReview => ScanPhase::CodeReview,
|
||||
ScanType::Graph => ScanPhase::GraphBuilding,
|
||||
ScanType::Dast => ScanPhase::DastScanning,
|
||||
ScanType::FirmwareStatic => ScanPhase::FirmwareStatic,
|
||||
ScanType::PlcControlLogic => ScanPhase::PlcAnalysis,
|
||||
ScanType::MobileStatic => ScanPhase::MobileStatic,
|
||||
ScanType::ContainerScan => ScanPhase::ContainerScan,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::{PlcFormat, TargetType};
|
||||
|
||||
fn target(target_type: TargetType, artifacts: Vec<Artifact>) -> OnboardedTarget {
|
||||
let mut t = OnboardedTarget::new("t".to_string(), target_type);
|
||||
t.artifacts = artifacts;
|
||||
t
|
||||
}
|
||||
|
||||
fn step_for<'a>(plan: &'a ScanPlan, scan: ScanType) -> Option<&'a ScanStep> {
|
||||
plan.steps.iter().find(|s| s.scan_type == scan)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn webapp_with_code_and_url_runs_sast_and_dast_bound_to_the_right_artifacts() {
|
||||
let code = Artifact::git_repo("https://git/x", "main");
|
||||
let url = Artifact::live_url("https://x");
|
||||
let (code_id, url_id) = (code.id.clone(), url.id.clone());
|
||||
let t = target(TargetType::WebApp, vec![code, url]);
|
||||
|
||||
let plan = build_scan_plan(&t);
|
||||
let sast = step_for(&plan, ScanType::Sast).expect("sast planned");
|
||||
assert_eq!(sast.artifact_id, code_id);
|
||||
assert_eq!(sast.phase, ScanPhase::Sast);
|
||||
let dast = step_for(&plan, ScanType::Dast).expect("dast planned");
|
||||
assert_eq!(dast.artifact_id, url_id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn webapp_without_url_omits_dast() {
|
||||
let t = target(TargetType::WebApp, vec![Artifact::git_repo("u", "main")]);
|
||||
let plan = build_scan_plan(&t);
|
||||
assert!(plan.has(ScanType::Sast));
|
||||
assert!(!plan.has(ScanType::Dast));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_scan_binds_to_source_archive_when_no_git_repo() {
|
||||
let arc = Artifact::source_archive("src.zip");
|
||||
let arc_id = arc.id.clone();
|
||||
let t = target(TargetType::BackendService, vec![arc]);
|
||||
let plan = build_scan_plan(&t);
|
||||
let sast = step_for(&plan, ScanType::Sast).expect("sast planned");
|
||||
assert_eq!(sast.artifact_id, arc_id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn firmware_sbom_and_cve_bind_to_the_firmware_image() {
|
||||
let fw = Artifact::firmware_image("fw.bin");
|
||||
let fw_id = fw.id.clone();
|
||||
let t = target(TargetType::FirmwareBareMetal, vec![fw]);
|
||||
let plan = build_scan_plan(&t);
|
||||
let sbom = step_for(&plan, ScanType::Sbom).expect("sbom planned");
|
||||
assert_eq!(sbom.artifact_id, fw_id);
|
||||
assert!(step_for(&plan, ScanType::FirmwareStatic).is_some());
|
||||
assert!(!plan.has(ScanType::Dast));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plc_plans_only_control_logic() {
|
||||
let plc = Artifact::plc_project("p.xml", PlcFormat::PlcopenXml);
|
||||
let t = target(TargetType::PlcSps, vec![plc]);
|
||||
let plan = build_scan_plan(&t);
|
||||
assert_eq!(plan.steps.len(), 1);
|
||||
assert_eq!(plan.steps[0].scan_type, ScanType::PlcControlLogic);
|
||||
assert_eq!(plan.steps[0].phase, ScanPhase::PlcAnalysis);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_scan_is_dropped_and_off_by_default_can_be_enabled() {
|
||||
let mut t = target(TargetType::WebApp, vec![Artifact::git_repo("u", "main")]);
|
||||
t.scan_config.disabled_scans = vec![ScanType::Lint];
|
||||
// CodeReview is off by default for web; enable it explicitly.
|
||||
t.scan_config.enabled_scans = vec![ScanType::CodeReview];
|
||||
let plan = build_scan_plan(&t);
|
||||
assert!(!plan.has(ScanType::Lint));
|
||||
assert!(plan.has(ScanType::CodeReview));
|
||||
assert!(plan.has(ScanType::Sast));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_code_artifact_yields_empty_plan_for_web() {
|
||||
let t = target(TargetType::WebApp, vec![]);
|
||||
let plan = build_scan_plan(&t);
|
||||
assert!(plan.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -25,8 +25,9 @@ impl TestServer {
|
||||
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
|
||||
// Unique database name per test run to avoid collisions
|
||||
let db_name = format!("test_{}", uuid::Uuid::new_v4().simple());
|
||||
// Unique db-name prefix per run. Must fit the pool's 30-char cap
|
||||
// (`<prefix>_<32 hex>` <= 63), so use a 16-hex-char suffix.
|
||||
let db_name = format!("t_{}", &uuid::Uuid::new_v4().simple().to_string()[..16]);
|
||||
|
||||
let db_pool = DatabasePool::connect(&mongodb_uri, &db_name)
|
||||
.await
|
||||
@@ -69,6 +70,7 @@ impl TestServer {
|
||||
pentest_imap_password: None,
|
||||
admin_api_token: None,
|
||||
tenant_registry_url: None,
|
||||
unified_pipeline: false,
|
||||
};
|
||||
|
||||
let agent = ComplianceAgent::new(config, db_pool);
|
||||
|
||||
@@ -2,5 +2,6 @@ mod cascade_delete;
|
||||
mod dast;
|
||||
mod findings;
|
||||
mod health;
|
||||
mod onboarding;
|
||||
mod repositories;
|
||||
mod stats;
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
use crate::common::TestServer;
|
||||
use serde_json::json;
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_list_and_applicable_scans() {
|
||||
let server = TestServer::start().await;
|
||||
|
||||
// Initially empty.
|
||||
let resp = server.get("/api/v1/targets").await;
|
||||
assert_eq!(resp.status(), 200);
|
||||
let body: serde_json::Value = resp.json().await.unwrap();
|
||||
assert_eq!(body["data"].as_array().unwrap().len(), 0);
|
||||
|
||||
// Create a web-app target with a git repo + a live URL.
|
||||
let resp = server
|
||||
.post(
|
||||
"/api/v1/targets",
|
||||
&json!({
|
||||
"name": "acme-web",
|
||||
"target_type": "web_app",
|
||||
"artifacts": [
|
||||
{ "kind": "git_repo", "source_ref": "https://git/acme.git", "branch": "main" },
|
||||
{ "kind": "live_url", "source_ref": "https://acme.example.com" }
|
||||
]
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(resp.status(), 200);
|
||||
let body: serde_json::Value = resp.json().await.unwrap();
|
||||
let id = body["data"]["_id"]["$oid"].as_str().unwrap().to_string();
|
||||
assert!(!id.is_empty());
|
||||
assert_eq!(body["data"]["artifacts"].as_array().unwrap().len(), 2);
|
||||
|
||||
// List returns it.
|
||||
let resp = server.get("/api/v1/targets").await;
|
||||
let body: serde_json::Value = resp.json().await.unwrap();
|
||||
assert_eq!(body["data"].as_array().unwrap().len(), 1);
|
||||
|
||||
// Applicable scans: SAST present + DAST offered (live URL present), pentest supported.
|
||||
let resp = server
|
||||
.get(&format!("/api/v1/targets/{id}/applicable-scans"))
|
||||
.await;
|
||||
assert_eq!(resp.status(), 200);
|
||||
let body: serde_json::Value = resp.json().await.unwrap();
|
||||
let scans = body["data"]["scans"].as_array().unwrap();
|
||||
let names: Vec<&str> = scans.iter().filter_map(|s| s["scan"].as_str()).collect();
|
||||
assert!(names.contains(&"sast"));
|
||||
assert!(names.contains(&"dast"));
|
||||
assert_eq!(body["data"]["pentest_supported"], true);
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn detect_classifies_a_plc_target() {
|
||||
let server = TestServer::start().await;
|
||||
|
||||
// A PLC project artifact is a strong kind-based signal.
|
||||
let resp = server
|
||||
.post(
|
||||
"/api/v1/targets",
|
||||
&json!({
|
||||
"name": "line-controller",
|
||||
"target_type": "backend_service", // deliberately wrong; detect should suggest PLC
|
||||
"artifacts": [
|
||||
{ "kind": "plc_project", "source_ref": "line.xml", "plc_format": "plcopen_xml" }
|
||||
]
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let body: serde_json::Value = resp.json().await.unwrap();
|
||||
let id = body["data"]["_id"]["$oid"].as_str().unwrap().to_string();
|
||||
|
||||
let resp = server
|
||||
.post(&format!("/api/v1/targets/{id}/detect"), &json!({}))
|
||||
.await;
|
||||
assert_eq!(resp.status(), 200);
|
||||
let body: serde_json::Value = resp.json().await.unwrap();
|
||||
assert_eq!(body["data"]["classification"]["suggested"], "plc_sps");
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn add_artifact_and_delete_target() {
|
||||
let server = TestServer::start().await;
|
||||
|
||||
let resp = server
|
||||
.post(
|
||||
"/api/v1/targets",
|
||||
&json!({ "name": "svc", "target_type": "backend_service" }),
|
||||
)
|
||||
.await;
|
||||
let body: serde_json::Value = resp.json().await.unwrap();
|
||||
let id = body["data"]["_id"]["$oid"].as_str().unwrap().to_string();
|
||||
|
||||
// Attach a git repo.
|
||||
let resp = server
|
||||
.post(
|
||||
&format!("/api/v1/targets/{id}/artifacts"),
|
||||
&json!({ "kind": "git_repo", "source_ref": "https://git/svc.git" }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(resp.status(), 200);
|
||||
let body: serde_json::Value = resp.json().await.unwrap();
|
||||
assert_eq!(body["data"]["artifacts"].as_array().unwrap().len(), 1);
|
||||
|
||||
// Delete it.
|
||||
let resp = server.delete(&format!("/api/v1/targets/{id}")).await;
|
||||
assert_eq!(resp.status(), 200);
|
||||
let resp = server.get(&format!("/api/v1/targets/{id}")).await;
|
||||
assert_eq!(resp.status(), 404);
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
@@ -49,6 +49,10 @@ pub struct AgentConfig {
|
||||
/// of tenants to iterate. When `None` or unreachable, scheduler
|
||||
/// falls back to `SCHEDULER_TENANT_IDS` env (M7.2-C).
|
||||
pub tenant_registry_url: Option<String>,
|
||||
/// When true, `run_scan` dispatches to the unified `run_target` pipeline
|
||||
/// (reads `onboarded_targets`) instead of the legacy repository pipeline.
|
||||
/// Env `UNIFIED_PIPELINE`. Defaults off during the transition.
|
||||
pub unified_pipeline: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
|
||||
@@ -12,6 +12,8 @@ pub enum Route {
|
||||
OverviewPage {},
|
||||
#[route("/repositories")]
|
||||
RepositoriesPage {},
|
||||
#[route("/onboard")]
|
||||
OnboardingPage {},
|
||||
#[route("/findings")]
|
||||
FindingsPage {},
|
||||
#[route("/findings/:id")]
|
||||
|
||||
@@ -28,6 +28,11 @@ pub fn Sidebar() -> Element {
|
||||
route: Route::RepositoriesPage {},
|
||||
icon: rsx! { Icon { icon: BsFolder2Open, width: 18, height: 18 } },
|
||||
},
|
||||
NavItem {
|
||||
label: "Onboard",
|
||||
route: Route::OnboardingPage {},
|
||||
icon: rsx! { Icon { icon: BsPlusCircle, width: 18, height: 18 } },
|
||||
},
|
||||
NavItem {
|
||||
label: "Findings",
|
||||
route: Route::FindingsPage {},
|
||||
|
||||
@@ -10,6 +10,7 @@ pub mod issues;
|
||||
pub mod mcp;
|
||||
pub mod mcp_tokens;
|
||||
pub mod notifications;
|
||||
pub mod onboarding;
|
||||
pub mod pentest;
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub mod repositories;
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Server functions for the onboarding wizard — proxy to the agent's
|
||||
//! `/api/v1/targets` endpoints.
|
||||
|
||||
use dioxus::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// One artifact the wizard collects for a target.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
|
||||
pub struct ArtifactInputDto {
|
||||
pub kind: String,
|
||||
pub source_ref: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub branch: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub plc_format: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct TargetsResponse {
|
||||
pub data: Vec<serde_json::Value>,
|
||||
pub total: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct TargetResponse {
|
||||
pub data: serde_json::Value,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct ApplicableScansData {
|
||||
#[serde(default)]
|
||||
pub scans: Vec<serde_json::Value>,
|
||||
#[serde(default)]
|
||||
pub pentest_supported: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct ApplicableScansResponse {
|
||||
pub data: ApplicableScansData,
|
||||
}
|
||||
|
||||
/// List onboarded targets.
|
||||
#[server]
|
||||
pub async fn fetch_targets() -> Result<TargetsResponse, ServerFnError> {
|
||||
let resp = super::agent_client::agent_get("/api/v1/targets")
|
||||
.await?
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
resp.json()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))
|
||||
}
|
||||
|
||||
/// Create a target with the collected artifacts.
|
||||
#[server]
|
||||
pub async fn create_target(
|
||||
name: String,
|
||||
target_type: String,
|
||||
description: Option<String>,
|
||||
artifacts: Vec<ArtifactInputDto>,
|
||||
) -> Result<TargetResponse, ServerFnError> {
|
||||
let body = serde_json::json!({
|
||||
"name": name,
|
||||
"target_type": target_type,
|
||||
"description": description,
|
||||
"artifacts": artifacts,
|
||||
});
|
||||
let resp = super::agent_client::agent_request(reqwest::Method::POST, "/api/v1/targets")
|
||||
.await?
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
resp.json()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))
|
||||
}
|
||||
|
||||
/// Run kind-based classification on a target.
|
||||
#[server]
|
||||
pub async fn detect_target(id: String) -> Result<TargetResponse, ServerFnError> {
|
||||
let resp = super::agent_client::agent_request(
|
||||
reqwest::Method::POST,
|
||||
&format!("/api/v1/targets/{id}/detect"),
|
||||
)
|
||||
.await?
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
resp.json()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))
|
||||
}
|
||||
|
||||
/// Fetch the scan-applicability matrix for a target.
|
||||
#[server]
|
||||
pub async fn fetch_applicable_scans(id: String) -> Result<ApplicableScansResponse, ServerFnError> {
|
||||
let resp = super::agent_client::agent_get(&format!("/api/v1/targets/{id}/applicable-scans"))
|
||||
.await?
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
resp.json()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))
|
||||
}
|
||||
|
||||
/// Trigger a scan for a target.
|
||||
#[server]
|
||||
pub async fn trigger_target_scan(id: String) -> Result<serde_json::Value, ServerFnError> {
|
||||
let resp = super::agent_client::agent_request(
|
||||
reqwest::Method::POST,
|
||||
&format!("/api/v1/targets/{id}/scan"),
|
||||
)
|
||||
.await?
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
resp.json()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))
|
||||
}
|
||||
@@ -12,6 +12,7 @@ pub mod impact_analysis;
|
||||
pub mod issues;
|
||||
pub mod mcp_servers;
|
||||
pub mod mcp_tokens;
|
||||
pub mod onboarding;
|
||||
pub mod overview;
|
||||
pub mod pentest_dashboard;
|
||||
pub mod pentest_session;
|
||||
@@ -32,6 +33,7 @@ pub use impact_analysis::ImpactAnalysisPage;
|
||||
pub use issues::IssuesPage;
|
||||
pub use mcp_servers::McpServersPage;
|
||||
pub use mcp_tokens::McpTokensPage;
|
||||
pub use onboarding::OnboardingPage;
|
||||
pub use overview::OverviewPage;
|
||||
pub use pentest_dashboard::PentestDashboardPage;
|
||||
pub use pentest_session::PentestSessionPage;
|
||||
|
||||
@@ -0,0 +1,402 @@
|
||||
use dioxus::prelude::*;
|
||||
|
||||
use crate::components::page_header::PageHeader;
|
||||
use crate::infrastructure::onboarding::{
|
||||
create_target, detect_target, fetch_applicable_scans, trigger_target_scan, ArtifactInputDto,
|
||||
};
|
||||
|
||||
/// (value, label, one-line description) for the 9 target families.
|
||||
const TARGET_TYPES: &[(&str, &str, &str)] = &[
|
||||
("web_app", "Web Application", "Front end + server"),
|
||||
("backend_service", "Backend / API", "REST, GraphQL, gRPC"),
|
||||
("desktop_app", "Desktop App", "Windows / macOS / Linux"),
|
||||
("android_app", "Android App", "APK / AAB"),
|
||||
("ios_app", "iOS App", "IPA"),
|
||||
(
|
||||
"firmware_bare_metal",
|
||||
"Firmware — bare metal",
|
||||
"No operating system",
|
||||
),
|
||||
("firmware_rtos", "Firmware — RTOS", "Zephyr, FreeRTOS, ..."),
|
||||
(
|
||||
"embedded_linux_yocto",
|
||||
"Embedded Linux / Yocto",
|
||||
"BSP + image",
|
||||
),
|
||||
("plc_sps", "PLC / SPS", "IEC 61131-3"),
|
||||
];
|
||||
|
||||
/// (value, label) for the artifact kinds a user can attach.
|
||||
const ARTIFACT_KINDS: &[(&str, &str)] = &[
|
||||
("git_repo", "Git repository"),
|
||||
("source_archive", "Source archive (zip)"),
|
||||
("firmware_image", "Firmware image"),
|
||||
("mobile_package", "Mobile package (APK/IPA)"),
|
||||
("container_image", "Container image"),
|
||||
("live_url", "Live URL"),
|
||||
("plc_project", "PLC project"),
|
||||
("plaintext_description", "Description (text)"),
|
||||
];
|
||||
|
||||
const STEP_LABELS: &[&str] = &["Target type", "Artifacts", "Review", "Done"];
|
||||
|
||||
/// One row in the applicable-scans list on the success step.
|
||||
#[component]
|
||||
fn ScanRow(scan: serde_json::Value) -> Element {
|
||||
let name = scan
|
||||
.get("scan")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("?")
|
||||
.to_string();
|
||||
let rationale = scan
|
||||
.get("rationale")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let blocked = scan
|
||||
.get("blocked_reason")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(String::from);
|
||||
let default_on = scan
|
||||
.get("default_on")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
let badge_class = if blocked.is_some() {
|
||||
"badge badge-info"
|
||||
} else if default_on {
|
||||
"badge badge-success"
|
||||
} else {
|
||||
"badge"
|
||||
};
|
||||
rsx! {
|
||||
div { style: "display: flex; gap: 8px; align-items: center; padding: 6px 0;",
|
||||
span { class: "{badge_class}", "{name}" }
|
||||
span { style: "opacity: 0.8;", "{rationale}" }
|
||||
if let Some(b) = blocked {
|
||||
span { style: "opacity: 0.6; font-style: italic;", "— {b}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn kind_label(kind: &str) -> &str {
|
||||
ARTIFACT_KINDS
|
||||
.iter()
|
||||
.find(|(v, _)| *v == kind)
|
||||
.map(|(_, l)| *l)
|
||||
.unwrap_or(kind)
|
||||
}
|
||||
|
||||
fn type_label(value: &str) -> &str {
|
||||
TARGET_TYPES
|
||||
.iter()
|
||||
.find(|(v, _, _)| *v == value)
|
||||
.map(|(_, l, _)| *l)
|
||||
.unwrap_or(value)
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn OnboardingPage() -> Element {
|
||||
let mut step = use_signal(|| 0usize);
|
||||
let mut name = use_signal(String::new);
|
||||
let mut target_type = use_signal(String::new);
|
||||
let mut description = use_signal(String::new);
|
||||
let mut artifacts = use_signal(Vec::<ArtifactInputDto>::new);
|
||||
|
||||
// "Add artifact" mini-form.
|
||||
let mut new_kind = use_signal(|| "git_repo".to_string());
|
||||
let mut new_source = use_signal(String::new);
|
||||
let mut new_branch = use_signal(|| "main".to_string());
|
||||
|
||||
// Create + result state.
|
||||
let mut creating = use_signal(|| false);
|
||||
let mut error = use_signal(|| Option::<String>::None);
|
||||
let mut scans = use_signal(Vec::<serde_json::Value>::new);
|
||||
let mut suggested = use_signal(|| Option::<String>::None);
|
||||
let mut created_id = use_signal(|| Option::<String>::None);
|
||||
let mut scan_msg = use_signal(|| Option::<String>::None);
|
||||
|
||||
let step_now = step();
|
||||
let can_advance_type = !name().trim().is_empty() && !target_type().trim().is_empty();
|
||||
let has_artifacts = !artifacts().is_empty();
|
||||
|
||||
rsx! {
|
||||
PageHeader {
|
||||
title: "Onboard a target",
|
||||
description: "Add a target, attach its artifacts, and see which scans apply.",
|
||||
}
|
||||
|
||||
// Stepper.
|
||||
div { class: "wizard-steps",
|
||||
for (i, label) in STEP_LABELS.iter().enumerate() {
|
||||
div {
|
||||
class: if i == step_now { "wizard-step wizard-step-active" } else { "wizard-step" },
|
||||
span { class: "wizard-step-dot", "{i + 1}" }
|
||||
span { class: "wizard-step-label", "{label}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(err) = error() {
|
||||
div { class: "card", style: "border-color: var(--danger, #d33); margin-bottom: 12px;",
|
||||
div { class: "card-header", "Error" }
|
||||
div { style: "padding: 12px;", "{err}" }
|
||||
}
|
||||
}
|
||||
|
||||
div { class: "card",
|
||||
// ---- Step 0: target type + name ----
|
||||
if step_now == 0 {
|
||||
div { class: "card-header", "What kind of software is this?" }
|
||||
div { style: "padding: 16px;",
|
||||
div { class: "form-group",
|
||||
label { "Name" }
|
||||
input {
|
||||
r#type: "text",
|
||||
placeholder: "acme-web",
|
||||
value: "{name}",
|
||||
oninput: move |e| name.set(e.value()),
|
||||
}
|
||||
}
|
||||
div {
|
||||
style: "display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 12px; margin-top: 12px;",
|
||||
for (value, tlabel, tdesc) in TARGET_TYPES.iter().copied() {
|
||||
div {
|
||||
class: "card",
|
||||
style: if target_type() == value {
|
||||
"padding: 12px; cursor: pointer; border: 2px solid var(--accent, #3b82f6);"
|
||||
} else {
|
||||
"padding: 12px; cursor: pointer;"
|
||||
},
|
||||
onclick: move |_| target_type.set(value.to_string()),
|
||||
div { style: "font-weight: 600;", "{tlabel}" }
|
||||
div { style: "font-size: 0.85em; opacity: 0.7;", "{tdesc}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Step 1: artifacts ----
|
||||
if step_now == 1 {
|
||||
div { class: "card-header", "Attach artifacts" }
|
||||
div { style: "padding: 16px;",
|
||||
div { style: "display: flex; gap: 8px; flex-wrap: wrap; align-items: flex-end;",
|
||||
div { class: "form-group", style: "margin: 0;",
|
||||
label { "Kind" }
|
||||
select {
|
||||
value: "{new_kind}",
|
||||
oninput: move |e| new_kind.set(e.value()),
|
||||
for (value, klabel) in ARTIFACT_KINDS.iter().copied() {
|
||||
option { value: "{value}", "{klabel}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
div { class: "form-group", style: "margin: 0; flex: 1; min-width: 240px;",
|
||||
label { "Reference (URL / path / text)" }
|
||||
input {
|
||||
r#type: "text",
|
||||
placeholder: "https://git.example.com/acme.git",
|
||||
value: "{new_source}",
|
||||
oninput: move |e| new_source.set(e.value()),
|
||||
}
|
||||
}
|
||||
if new_kind() == "git_repo" {
|
||||
div { class: "form-group", style: "margin: 0;",
|
||||
label { "Branch" }
|
||||
input {
|
||||
r#type: "text",
|
||||
value: "{new_branch}",
|
||||
oninput: move |e| new_branch.set(e.value()),
|
||||
}
|
||||
}
|
||||
}
|
||||
button {
|
||||
class: "btn btn-secondary",
|
||||
onclick: move |_| {
|
||||
let kind = new_kind();
|
||||
if !new_source().trim().is_empty() {
|
||||
let branch = if kind == "git_repo" { Some(new_branch()) } else { None };
|
||||
artifacts.write().push(ArtifactInputDto {
|
||||
kind,
|
||||
source_ref: new_source(),
|
||||
branch,
|
||||
plc_format: None,
|
||||
});
|
||||
new_source.set(String::new());
|
||||
}
|
||||
},
|
||||
"+ Add"
|
||||
}
|
||||
}
|
||||
|
||||
div { style: "margin-top: 16px;",
|
||||
if has_artifacts {
|
||||
for (i, a) in artifacts().iter().enumerate() {
|
||||
div {
|
||||
style: "display: flex; justify-content: space-between; align-items: center; padding: 8px 12px; border: 1px solid var(--border, #333); border-radius: 6px; margin-bottom: 6px;",
|
||||
span {
|
||||
span { style: "opacity: 0.7;", "{kind_label(&a.kind)}: " }
|
||||
"{a.source_ref}"
|
||||
}
|
||||
button {
|
||||
class: "btn btn-ghost-danger btn-sm",
|
||||
onclick: move |_| { artifacts.write().remove(i); },
|
||||
"Remove"
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
div { style: "opacity: 0.6;", "No artifacts yet. Add at least one." }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Step 2: review + create ----
|
||||
if step_now == 2 {
|
||||
div { class: "card-header", "Review" }
|
||||
div { style: "padding: 16px;",
|
||||
div { class: "wizard-summary",
|
||||
div { strong { "Name: " } "{name()}" }
|
||||
div { strong { "Type: " } "{type_label(&target_type())}" }
|
||||
div { strong { "Artifacts:" } }
|
||||
ul {
|
||||
for a in artifacts() {
|
||||
li { "{kind_label(&a.kind)}: {a.source_ref}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
div { style: "margin-top: 12px; opacity: 0.7; font-size: 0.9em;",
|
||||
"The applicable scans (SAST / DAST / firmware / PLC) are shown after the target is created."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Step 3: created ----
|
||||
if step_now == 3 {
|
||||
div { class: "card-header", "Target onboarded" }
|
||||
div { style: "padding: 16px;",
|
||||
p {
|
||||
strong { "{name()}" }
|
||||
" was created."
|
||||
if let Some(s) = suggested() {
|
||||
span { " Suggested type from detection: " strong { "{type_label(&s)}" } "." }
|
||||
}
|
||||
}
|
||||
h4 { style: "margin-top: 16px;", "Applicable scans" }
|
||||
if scans().is_empty() {
|
||||
div { style: "opacity: 0.6;", "No scans available (no code / URL / firmware artifact present)." }
|
||||
} else {
|
||||
for s in scans() {
|
||||
ScanRow { scan: s }
|
||||
}
|
||||
}
|
||||
if let Some(msg) = scan_msg() {
|
||||
div { style: "margin-top: 8px; color: var(--success, #2a2);", "{msg}" }
|
||||
}
|
||||
div { style: "margin-top: 16px; display: flex; gap: 8px;",
|
||||
button {
|
||||
class: "btn btn-primary",
|
||||
onclick: move |_| {
|
||||
if let Some(id) = created_id() {
|
||||
scan_msg.set(Some("Scan triggered...".to_string()));
|
||||
spawn(async move {
|
||||
match trigger_target_scan(id).await {
|
||||
Ok(_) => scan_msg.set(Some(
|
||||
"Scan started — findings will appear as it runs.".to_string(),
|
||||
)),
|
||||
Err(e) => scan_msg.set(Some(format!("Failed to start scan: {e}"))),
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
"Run scan"
|
||||
}
|
||||
button {
|
||||
class: "btn btn-secondary",
|
||||
onclick: move |_| {
|
||||
step.set(0);
|
||||
name.set(String::new());
|
||||
target_type.set(String::new());
|
||||
description.set(String::new());
|
||||
artifacts.write().clear();
|
||||
scans.write().clear();
|
||||
suggested.set(None);
|
||||
created_id.set(None);
|
||||
scan_msg.set(None);
|
||||
error.set(None);
|
||||
},
|
||||
"Onboard another"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Footer navigation ----
|
||||
if step_now < 3 {
|
||||
div { style: "display: flex; justify-content: space-between; margin-top: 16px;",
|
||||
button {
|
||||
class: "btn btn-back",
|
||||
disabled: step_now == 0,
|
||||
onclick: move |_| { if step() > 0 { step.set(step() - 1); } },
|
||||
"Back"
|
||||
}
|
||||
if step_now < 2 {
|
||||
button {
|
||||
class: "btn btn-primary",
|
||||
disabled: (step_now == 0 && !can_advance_type) || (step_now == 1 && !has_artifacts),
|
||||
onclick: move |_| step.set(step() + 1),
|
||||
"Next"
|
||||
}
|
||||
} else {
|
||||
button {
|
||||
class: "btn btn-primary",
|
||||
disabled: creating(),
|
||||
onclick: move |_| {
|
||||
let n = name();
|
||||
let tt = target_type();
|
||||
let desc = description();
|
||||
let arts = artifacts();
|
||||
let d = if desc.trim().is_empty() { None } else { Some(desc) };
|
||||
creating.set(true);
|
||||
error.set(None);
|
||||
spawn(async move {
|
||||
match create_target(n, tt, d, arts).await {
|
||||
Ok(resp) => {
|
||||
let id = resp
|
||||
.data
|
||||
.get("_id")
|
||||
.and_then(|o| o.get("$oid"))
|
||||
.and_then(|s| s.as_str())
|
||||
.map(String::from);
|
||||
if let Some(id) = id {
|
||||
created_id.set(Some(id.clone()));
|
||||
if let Ok(sc) = fetch_applicable_scans(id.clone()).await {
|
||||
scans.set(sc.data.scans);
|
||||
}
|
||||
if let Ok(det) = detect_target(id).await {
|
||||
suggested.set(
|
||||
det.data
|
||||
.get("classification")
|
||||
.and_then(|c| c.get("suggested"))
|
||||
.and_then(|s| s.as_str())
|
||||
.map(String::from),
|
||||
);
|
||||
}
|
||||
}
|
||||
step.set(3);
|
||||
}
|
||||
Err(e) => error.set(Some(e.to_string())),
|
||||
}
|
||||
creating.set(false);
|
||||
});
|
||||
},
|
||||
if creating() { "Creating..." } else { "Create target" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user