Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6d95070f7b | ||
|
|
616e97ff71 | ||
|
|
6e3c42a14d |
+3
-14
@@ -191,18 +191,13 @@ 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_BUILDKIT=1 docker build --secret id=tramiton_token,env=TRAMITON_FETCH_TOKEN \
|
||||
-f Dockerfile.agent -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
|
||||
docker build -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}')
|
||||
@@ -217,16 +212,13 @@ 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_BUILDKIT=1 docker build --secret id=tramiton_token,env=TRAMITON_FETCH_TOKEN \
|
||||
-f Dockerfile.dashboard -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
|
||||
docker build -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}')
|
||||
@@ -262,16 +254,13 @@ 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_BUILDKIT=1 docker build --secret id=tramiton_token,env=TRAMITON_FETCH_TOKEN \
|
||||
-f Dockerfile.mcp -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
|
||||
docker build -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}')
|
||||
|
||||
+1
-10
@@ -2,16 +2,7 @@ FROM rust:1.94-bookworm AS builder
|
||||
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
# 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
|
||||
RUN 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/*
|
||||
|
||||
+1
-10
@@ -7,16 +7,7 @@ ARG DOCS_URL=/docs
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
ENV DOCS_URL=${DOCS_URL}
|
||||
# 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
|
||||
RUN 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/*
|
||||
|
||||
+1
-10
@@ -2,16 +2,7 @@ FROM rust:1.94-bookworm AS builder
|
||||
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
# 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
|
||||
RUN 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,12 +63,8 @@ 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());
|
||||
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.
|
||||
pub async fn run_pr_review(
|
||||
|
||||
@@ -9,7 +9,6 @@ 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;
|
||||
|
||||
@@ -1,350 +0,0 @@
|
||||
//! 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,
|
||||
}))
|
||||
}
|
||||
@@ -25,29 +25,6 @@ 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/findings", get(handlers::list_findings))
|
||||
.route("/api/v1/findings/{id}", get(handlers::get_finding))
|
||||
.route(
|
||||
|
||||
@@ -47,9 +47,6 @@ 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,7 +342,6 @@ mod tests {
|
||||
pentest_imap_password: None,
|
||||
admin_api_token: None,
|
||||
tenant_registry_url: None,
|
||||
unified_pipeline: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ 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,7 +15,6 @@ 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;
|
||||
|
||||
@@ -420,149 +419,6 @@ 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"
|
||||
);
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -580,37 +436,6 @@ 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"
|
||||
@@ -635,50 +460,3 @@ 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,195 +0,0 @@
|
||||
//! 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,9 +25,8 @@ impl TestServer {
|
||||
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
|
||||
// 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]);
|
||||
// Unique database name per test run to avoid collisions
|
||||
let db_name = format!("test_{}", uuid::Uuid::new_v4().simple());
|
||||
|
||||
let db_pool = DatabasePool::connect(&mongodb_uri, &db_name)
|
||||
.await
|
||||
@@ -70,7 +69,6 @@ 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,6 +2,5 @@ mod cascade_delete;
|
||||
mod dast;
|
||||
mod findings;
|
||||
mod health;
|
||||
mod onboarding;
|
||||
mod repositories;
|
||||
mod stats;
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
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,10 +49,6 @@ 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)]
|
||||
|
||||
Reference in New Issue
Block a user