Compare commits

..
Author SHA1 Message Date
Sharang ParnerkarandClaude Opus 5.5 2e45dcab5c docs(design): t83 Testtag charged unless all its runs failed through our fault
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 3m49s
CI / Check (pull_request) Successful in 17m42s
The user's decision (2026-11-07): a run that fails on the customer's
input counts and makes the Testtag chargeable; only a Testtag whose runs
all failed through Breakpilot's fault is free. The charging table, the
usage event, the test plan, the decisions and the LB wording say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 10:55:16 +01:00
Sharang ParnerkarandClaude Opus 5.5 deaa4e9f4e docs(design): t83 review: build network, Testtag billing, ERP codes, data protection
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 4m13s
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 17m22s
- The build runs customer code and fetches packages: same VM sandbox,
  egress only through a package mirror, test phase internal-only.
  Private feeds unsupported in phase 1, or a separately stored
  write-only feed token used only in the build.
- ERP items CRA-CSA-CLD-TST (LIV/LRN reserved); the Probelauf is only a
  count.
- Billed per Testtag: our failures don't use one of the 3 runs, a
  Testtag with no successful run is not charged; booked only when the
  customer starts a run; a monthly cap in the portal.
- Testtage in the plans as a decision.
- Runner host in Germany, AVV and TOM; where logs and artifacts live
  and when they are deleted.
- Live testing out of phase 1; the L1-L7 analysis stays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 09:14:39 +01:00
Sharang ParnerkarandClaude Opus 5.5 61953e2659 docs(design): active testing, a throwaway copy first (t83)
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 4m46s
CI / Check (pull_request) Successful in 19m7s
Proposed design for the user to decide. Active tests run by default against a
copy of the customer's application, built from the repository in a short-lived
sandbox (the Prüfumgebung). The code graph steers them: routes from code, and
static findings confirmed against the copy. Live testing is an optional add-on
with written authorisation. Covers what exists today (checked against the
code), which targets qualify, build failures and charging, limits, the
entitlement, cost and a Testtag price, a stage test plan, and the SKU and LB
wording. Nothing is enabled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 23:09:51 +01:00
236 changed files with 3942 additions and 34507 deletions

No files matched your search

+2 -12
View File
@@ -138,12 +138,6 @@ jobs:
run: cargo clippy -p werkbank-exec --all-targets -- -D warnings
- name: Clippy (control-map)
run: cargo clippy -p control-map --all-targets -- -D warnings
- name: Clippy (graph)
run: cargo clippy -p compliance-graph --all-targets -- -D warnings
# The library only: its test modules still predate the lint
# (items_after_test_module); --all-targets once they are moved.
- name: Clippy (dast)
run: cargo clippy -p compliance-dast -- -D warnings
# Security audit
- name: Security Audit
@@ -152,15 +146,11 @@ jobs:
RUSTC_WRAPPER: ""
# Tests (reuses compilation artifacts from clippy)
- name: Tests (core + agent + graph + werkbank-exec + control-map)
run: cargo test -p compliance-core -p compliance-agent -p compliance-graph -p werkbank-exec -p control-map --lib
- name: Tests (core + agent + werkbank-exec + control-map)
run: cargo test -p compliance-core -p compliance-agent -p werkbank-exec -p control-map --lib
# compliance-core's integration tests need no services.
- name: Tests (core integration)
run: cargo test -p compliance-core --tests
# compliance-dast: unit tests, doc tests and the scan tests against
# local fake sites (no services).
- name: Tests (dast)
run: cargo test -p compliance-dast
# The dashboard crate compiles as the library and as its test harness at
# once, each rustc at about 1.65 GB: two of them exceed the job's 3 GiB
# and get OOM-killed (signal 9). One at a time for these two steps.
+26 -58
View File
@@ -51,6 +51,30 @@ jobs:
env:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: example
# The image main deployed. Dev mode (no Keycloak): the harness talks to
# the unauthenticated dev tenant; source_only matches staging.
agent:
image: repo.breakpilot.com/pruefwerk/compliance-agent:latest
credentials:
username: ${{ secrets.REGISTRY_USERNAME }}
password: ${{ secrets.REGISTRY_PASSWORD }}
env:
APP_ENV: dev
MONGODB_URI: mongodb://root:example@mongo:27017/?authSource=admin
MONGODB_DATABASE: nightly
PW_FEATURES: source_only
# No chat model: LLM triage, code review and the control judge are
# off (LlmClient sends nothing without LITELLM_MODEL, #575). Their
# output never gates the run, and with the model on, ~600 calls of
# 11 s on average (p99 147 s) on the gateway prod also uses kept
# every scan past NIGHTLY_TIMEOUT_SECS from 2026-10-30 on (#573).
# Embeddings stay on: the gateway's embedding model.
LITELLM_URL: ${{ secrets.NIGHTLY_LITELLM_URL }}
LITELLM_API_KEY: ${{ secrets.NIGHTLY_LITELLM_API_KEY }}
LITELLM_EMBED_MODEL: bge-multilingual-gemma2
# Optional. The CODESYS CVE match queries NVD, which rate-limits
# unauthenticated clients; a key keeps those CVEs from going missing.
NVD_API_KEY: ${{ secrets.NIGHTLY_NVD_API_KEY }}
steps:
- name: Checkout
run: |
@@ -125,59 +149,10 @@ jobs:
env:
RUSTC_WRAPPER: ""
# The image main deployed, started here rather than as a service:
# act_runner 0.6.1 hands a service's registry credentials to the job
# container's own pull (map order decides which service wins), so the
# Harbor login reached docker.io about every other night. mongo, the
# only service left, has no credentials. The agent shares this
# container's network: it reaches mongo by name and listens on
# localhost here. The login lands in this container's ~/.docker, which
# goes with it.
# Dev mode (no Keycloak): the harness talks to the unauthenticated dev
# tenant; source_only matches staging.
- name: Start the agent
run: |
curl -fsSL -o /tmp/docker.tgz \
https://download.docker.com/linux/static/stable/x86_64/docker-27.5.1.tgz
echo "4f798b3ee1e0140eab5bf30b0edc4e84f4cdb53255a429dc3bbae9524845d640 /tmp/docker.tgz" \
| sha256sum -c -
tar xzf /tmp/docker.tgz --strip-components=1 -C /usr/local/bin docker/docker
echo "$REGISTRY_PASSWORD" | docker login repo.breakpilot.com -u "$REGISTRY_USERNAME" --password-stdin
# -e NAME without a value passes this step's variable, so no secret
# appears on the command line. The container runs on the runner's
# daemon, outside the job's own limits, so it has its own; the label
# finds one a cancelled job left behind.
docker run -d --pull always --name "nightly-agent-${GITHUB_RUN_ID}" \
--label pruefwerk-nightly --memory 4g --cpus 2 \
--network "container:$(hostname)" \
-e APP_ENV=dev \
-e MONGODB_URI=mongodb://root:example@mongo:27017/?authSource=admin \
-e MONGODB_DATABASE=nightly \
-e PW_FEATURES=source_only \
-e LITELLM_URL -e LITELLM_API_KEY \
-e LITELLM_EMBED_MODEL=bge-multilingual-gemma2 \
-e NVD_API_KEY \
repo.breakpilot.com/pruefwerk/compliance-agent:latest
env:
RUSTC_WRAPPER: ""
REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }}
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
# No chat model: LLM triage, code review and the control judge are
# off (LlmClient sends nothing without LITELLM_MODEL, #575). Their
# output never gates the run, and with the model on, ~600 calls of
# 11 s on average (p99 147 s) on the gateway prod also uses kept
# every scan past NIGHTLY_TIMEOUT_SECS from 2026-10-30 on (#573).
# Embeddings stay on: the gateway's embedding model.
LITELLM_URL: ${{ secrets.NIGHTLY_LITELLM_URL }}
LITELLM_API_KEY: ${{ secrets.NIGHTLY_LITELLM_API_KEY }}
# Optional. The CODESYS CVE match queries NVD, which rate-limits
# unauthenticated clients; a key keeps those CVEs from going missing.
NVD_API_KEY: ${{ secrets.NIGHTLY_NVD_API_KEY }}
- name: Wait for the agent
run: |
for i in $(seq 1 90); do
curl -fsS http://localhost:3001/api/v1/health && exit 0
curl -fsS http://agent:3001/api/v1/health && exit 0
sleep 2
done
echo "agent did not become healthy" >&2
@@ -188,20 +163,13 @@ jobs:
- name: Scan the corpus and compare with the baselines
run: cargo test -p compliance-agent --test nightly -- --nocapture
env:
NIGHTLY_AGENT_URL: http://localhost:3001
NIGHTLY_AGENT_URL: http://agent:3001
NIGHTLY_CODESYS_SAMPLE: /tmp/csv-blackbox.projectarchive
NIGHTLY_ZEPHYR_EXAMPLE: /tmp/zephyr-example.zip
NIGHTLY_IOS_SAMPLE: /tmp/ios-sample.zip
NIGHTLY_ANDROID_SAMPLE: /tmp/android-sample.zip
NIGHTLY_BLESS: ${{ inputs.bless && '1' || '0' }}
# The agent is not a service, so the runner does not remove it.
- name: Stop the agent
if: always()
run: docker rm -f "nightly-agent-${GITHUB_RUN_ID}" || true
env:
RUSTC_WRAPPER: ""
# upload-artifact is a Node action and the Rust image has no node.
- name: Install node for the artifact upload
if: always()
Generated
+14 -90
View File
@@ -601,7 +601,7 @@ dependencies = [
[[package]]
name = "compliance-agent"
version = "0.4.16"
version = "0.4.6"
dependencies = [
"axum",
"base64 0.22.1",
@@ -645,8 +645,6 @@ dependencies = [
"tracing",
"tracing-subscriber",
"urlencoding",
"utoipa",
"utoipa-axum",
"uuid",
"walkdir",
"werkbank-exec",
@@ -657,14 +655,13 @@ dependencies = [
[[package]]
name = "compliance-core"
version = "0.4.16"
version = "0.4.6"
dependencies = [
"aes-gcm",
"axum",
"base64 0.22.1",
"bson",
"chrono",
"encoding_rs",
"hex",
"jsonschema",
"jsonwebtoken",
@@ -689,7 +686,7 @@ dependencies = [
[[package]]
name = "compliance-dashboard"
version = "0.4.16"
version = "0.4.6"
dependencies = [
"async-trait",
"axum",
@@ -727,9 +724,8 @@ dependencies = [
[[package]]
name = "compliance-dast"
version = "0.4.16"
version = "0.4.6"
dependencies = [
"axum",
"base64 0.22.1",
"chrono",
"compliance-core",
@@ -738,7 +734,6 @@ dependencies = [
"reqwest",
"scraper",
"serde_json",
"thiserror 2.0.18",
"tokio",
"tokio-native-tls",
"tokio-tungstenite 0.26.2",
@@ -749,7 +744,7 @@ dependencies = [
[[package]]
name = "compliance-graph"
version = "0.4.16"
version = "0.4.6"
dependencies = [
"bson",
"chrono",
@@ -759,22 +754,18 @@ dependencies = [
"petgraph",
"serde",
"tantivy",
"thiserror 2.0.18",
"tokio",
"tracing",
"tree-sitter",
"tree-sitter-c",
"tree-sitter-c-sharp",
"tree-sitter-javascript",
"tree-sitter-python",
"tree-sitter-rust",
"tree-sitter-typescript",
"tree-sitter-vb-dotnet",
]
[[package]]
name = "compliance-mcp"
version = "0.4.16"
version = "0.4.6"
dependencies = [
"axum",
"bson",
@@ -797,7 +788,7 @@ dependencies = [
[[package]]
name = "compliance-smoke"
version = "0.4.16"
version = "0.4.6"
dependencies = [
"axum",
"compliance-core",
@@ -932,7 +923,7 @@ dependencies = [
[[package]]
name = "control-map"
version = "0.4.16"
version = "0.4.6"
dependencies = [
"serde",
"serde_json",
@@ -4619,16 +4610,16 @@ dependencies = [
[[package]]
name = "quinn-udp"
version = "0.5.16"
version = "0.5.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016"
checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd"
dependencies = [
"cfg_aliases",
"libc",
"once_cell",
"socket2 0.6.2",
"tracing",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -6500,38 +6491,17 @@ dependencies = [
[[package]]
name = "tree-sitter"
version = "0.25.10"
version = "0.24.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78f873475d258561b06f1c595d93308a7ed124d9977cb26b148c2084a4a3cc87"
checksum = "a5387dffa7ffc7d2dae12b50c6f7aab8ff79d6210147c6613561fc3d474c6f75"
dependencies = [
"cc",
"regex",
"regex-syntax",
"serde_json",
"streaming-iterator",
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-c"
version = "0.23.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "afd2b1bf1585dc2ef6d69e87d01db8adb059006649dd5f96f31aa789ee6e9c71"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-c-sharp"
version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67f06accca7b45351758663b8215089e643d53bd9a660ce0349314263737fcb0"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-javascript"
version = "0.23.1"
@@ -6578,16 +6548,6 @@ dependencies = [
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-vb-dotnet"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "180e4a199378505f9305c3d01d6ece8a8d34035f310de1c727693f8a2296025e"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]]
name = "try-lock"
version = "0.2.5"
@@ -6819,42 +6779,6 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
[[package]]
name = "utoipa"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8765fe27aeff71012a3f90fa474cf1df863a7d0dd81ed25de4e63fff2544994f"
dependencies = [
"indexmap",
"serde",
"serde_json",
"utoipa-gen",
]
[[package]]
name = "utoipa-axum"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "865319162dc3d0032e1e40ed11bd49d5b78e8ef576740589fd6823e2e9977423"
dependencies = [
"axum",
"pastey",
"tower-layer",
"tower-service",
"utoipa",
]
[[package]]
name = "utoipa-gen"
version = "6.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d935f1c83fdf8b88f09bbe050d0cea78ea4afee6d7b0317403228c1200b2c8ab"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "uuid"
version = "1.21.0"
@@ -7127,7 +7051,7 @@ dependencies = [
[[package]]
name = "werkbank-exec"
version = "0.4.16"
version = "0.4.6"
dependencies = [
"compliance-core",
"compliance-dast",
-2
View File
@@ -28,8 +28,6 @@ chrono = { version = "0.4", features = ["serde"] }
mongodb = { version = "3", features = ["rustls-tls", "compat-3-0-0"] }
reqwest = { version = "0.12", features = ["json", "rustls-tls", "multipart", "cookies", "stream"], default-features = false }
thiserror = "2"
# Source files in UTF-16 or Windows-1252 (code graph, PLC, .NET).
encoding_rs = "0.8"
sha2 = "0.10"
hex = "0.4"
uuid = { version = "1", features = ["v4", "v5", "serde"] }
+1 -3
View File
@@ -176,8 +176,6 @@ The agent exposes a REST API on port 3001:
|--------|----------|-------------|
| `GET` | `/api/v1/health` | Health check |
| `GET` | `/api/v1/stats/overview` | Summary statistics and trends |
| `GET` | `/api/v1/cve-history?days=30[&target=][&project=][&per_target=true]` | Open CVEs with a fixed version per day (UTC) by severity, for the tenant, a target or a project, with the open critical/high findings |
| `GET` | `/api/v1/targets/{id}/top-updates` | The package updates that close the most of a target's open CVEs with a fix |
| `GET` | `/api/v1/targets` | List targets (Prüfobjekte), each with its newest scan run |
| `POST` | `/api/v1/targets` | Create a target |
| `GET` / `PATCH` / `DELETE` | `/api/v1/targets/{id}` | Read, update (name, type, artifacts, `scan_config` incl. `issue_tracker`) or delete a target |
@@ -195,7 +193,7 @@ The agent exposes a REST API on port 3001:
| `PATCH` | `/api/v1/findings/bulk-status` | Update the status of several findings |
| `GET` | `/api/v1/sbom` | List dependencies |
| `GET` | `/api/v1/sbom/export` | Export a target's SBOM (CycloneDX 1.5 or SPDX 2.3) |
| `GET` | `/api/v1/issues` | List cross-tracker issues (search `q`, `status=open\|closed`, `repo_id`) |
| `GET` | `/api/v1/issues` | List cross-tracker issues |
| `GET` | `/api/v1/scan-runs` | Scan execution history |
| `GET` | `/api/v1/graph/{repo_id}` | Code knowledge graph |
| `POST` | `/api/v1/graph/{repo_id}/build` | Trigger graph build |
+1 -4
View File
@@ -1,15 +1,12 @@
[package]
name = "compliance-agent"
version = "0.4.16"
version = "0.4.6"
edition = "2021"
[lints]
workspace = true
[dependencies]
# The OpenAPI description of the API, generated from the handlers (#1006).
utoipa = "6"
utoipa-axum = "0.3"
compliance-core = { workspace = true, features = ["mongodb", "telemetry", "axum", "secrets"] }
control-map = { workspace = true }
compliance-graph = { path = "../compliance-graph" }
+26 -106
View File
@@ -10,7 +10,7 @@ use crate::database::DatabasePool;
use crate::llm::LlmClient;
use crate::pipeline::orchestrator::PipelineOrchestrator;
use crate::registry::RegistryClient;
use crate::scan_gate::{Admission, HeldTarget, Job, Priority, ScanGate};
use crate::scan_gate::{Admission, HeldTarget, ScanGate};
use crate::secrets::SecretBox;
/// A target whose billing changed, with its new billing (t72).
@@ -262,16 +262,11 @@ impl ComplianceAgent {
}
/// Scan a target, through the [`ScanGate`]: at most `SCAN_CONCURRENCY` scans
/// run at once, a person's before scheduled and webhook ones, and a request
/// for a target that is already queued or being scanned is coalesced — it
/// becomes the one pending follow-up that this task runs next, it takes over
/// a queued scan that was not a person's, or it is dropped as covered. A
/// scheduled scan first waits a random [`crate::scan_gate::start_delay`].
/// Every trigger (click, webhook, scheduler, demo seed) comes through here.
///
/// Each request is recorded at once as a `queued` run, which shows that it
/// waits for a slot (t84); a request that will not run has its queued run
/// removed again.
/// run at once, and a request for a target that is already being scanned is
/// coalesced — it becomes the one pending follow-up that this task runs next,
/// or it is dropped if a follow-up is already pending. A scheduled scan
/// first waits a random [`crate::scan_gate::start_delay`]. Every trigger
/// (click, webhook, scheduler, demo seed) comes through here.
///
/// # Errors
///
@@ -293,22 +288,15 @@ impl ComplianceAgent {
);
tokio::time::sleep(delay).await;
}
let db = self.db_pool.for_tenant_id(tenant_id).await?;
let run_id = queue_run(&db, target_id, &trigger).await;
let key = ScanGate::key(tenant_id, target_id);
match self
.scan_gate
.admit(&key, Job::new(trigger, run_id.clone()))
{
match self.scan_gate.admit(&key, trigger.clone()) {
Admission::Run => {}
Admission::Coalesced { replaced } => {
Admission::Coalesced => {
tracing::info!(
tenant_id,
target_id,
took_over = replaced.is_some(),
"scan already running; follow-up queued"
);
discard_queued_run(&db, replaced.as_deref()).await;
return Ok(());
}
Admission::Dropped => {
@@ -317,43 +305,41 @@ impl ComplianceAgent {
target_id,
"scan and follow-up already queued; dropped"
);
discard_queued_run(&db, run_id.as_deref()).await;
return Ok(());
}
}
// Released on panic or cancellation; a normal finish disarms it.
let held = HeldTarget::new(&self.scan_gate, key.clone());
let mut trigger = trigger;
let result = loop {
// The scan to run is the one current when the slot is granted: a
// person's request may have taken it over while it waited.
let (slot, job) = self
.scan_gate
.start(&key)
.await
.map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?;
let outcome = self.run_one_target_scan(tenant_id, target_id, &job).await;
drop(slot);
let outcome = {
let _slot = self
.scan_gate
.slot()
.await
.map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?;
self.run_one_target_scan(tenant_id, target_id, trigger.clone())
.await
};
if let Err(e) = &outcome {
tracing::error!(tenant_id, target_id, "scan failed: {e}");
fail_queued_run(&db, job.run_id.as_deref(), e).await;
}
if !self.scan_gate.finish(&key) {
break outcome;
match self.scan_gate.finish(&key) {
Some(next) => trigger = next,
None => break outcome,
}
};
held.disarm();
result
}
/// One scan of a target, with no gating: the pipeline plus its usage event,
/// recorded on the run that waited for it and charged as `job` says.
/// One scan of a target, with no gating: the pipeline plus its usage event.
async fn run_one_target_scan(
&self,
tenant_id: &str,
target_id: &str,
job: &Job,
trigger: compliance_core::models::ScanTrigger,
) -> Result<(), crate::error::AgentError> {
let trigger = job.trigger.clone();
let db = self.db_pool.for_tenant_id(tenant_id).await?;
// Whether this target is included or extra decides whether its scan
// counts, and the plan's limits whether a counted one may run (t72).
@@ -367,12 +353,9 @@ impl ComplianceAgent {
.with_nuget_license_cache(self.nuget_license_cache.clone())
.with_exploit_cache(self.exploit_cache.clone())
.with_advisory_index(self.advisory_index.clone())
.with_plan_limits(plan.map(|p| p.limits))
.with_charged_as(job.charged_as.clone());
.with_plan_limits(plan.map(|p| p.limits));
let started = chrono::Utc::now();
let outcome = orchestrator
.run_target(target_id, trigger.clone(), job.run_id.as_deref())
.await?;
let outcome = orchestrator.run_target(target_id, trigger.clone()).await?;
// Support's scans are ours, not the customer's usage; a scheduled scan
// skipped because nothing changed scanned nothing (#465).
if outcome.scanned && trigger != compliance_core::models::ScanTrigger::Support {
@@ -441,7 +424,7 @@ impl ComplianceAgent {
// slot too. Each PR is distinct work, so it is not coalesced.
let _slot = self
.scan_gate
.slot(Priority::Background)
.slot()
.await
.map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?;
let db = self.db_pool.for_tenant_id(tenant_id).await?;
@@ -517,69 +500,6 @@ impl ComplianceAgent {
}
}
/// Record a scan request for `target_id` as a run waiting for a slot (t84),
/// so it shows at once. Returns its id, or `None` when it could not be
/// written: the scan then runs on a run of its own when it starts.
async fn queue_run(
db: &crate::database::Database,
target_id: &str,
trigger: &compliance_core::models::ScanTrigger,
) -> Option<String> {
let run = compliance_core::models::ScanRun::queued(target_id.to_string(), trigger.clone());
match db.scan_runs().insert_one(&run).await {
Ok(insert) => insert.inserted_id.as_object_id().map(|id| id.to_hex()),
Err(e) => {
tracing::warn!(target_id, "queued scan run not recorded: {e}");
None
}
}
}
/// Remove the queued run `run_id` of a request that will not run, because
/// another queued scan covers it or took it over. A run that has started
/// meanwhile is kept.
async fn discard_queued_run(db: &crate::database::Database, run_id: Option<&str>) {
let Some(oid) = run_id.and_then(|id| mongodb::bson::oid::ObjectId::parse_str(id).ok()) else {
return;
};
if let Err(e) = db
.scan_runs()
.delete_one(mongodb::bson::doc! { "_id": oid, "status": "queued" })
.await
{
tracing::warn!(run_id = %oid, "queued scan run not removed: {e}");
}
}
/// Close the queued run `run_id` as failed when its scan ended with `error`
/// before it started (an unknown target, an unreachable database), so it does
/// not stay queued. A run the scan started records its own outcome.
async fn fail_queued_run(
db: &crate::database::Database,
run_id: Option<&str>,
error: &crate::error::AgentError,
) {
let Some(oid) = run_id.and_then(|id| mongodb::bson::oid::ObjectId::parse_str(id).ok()) else {
return;
};
let (code, message) = error.run_failure();
if let Err(e) = db
.scan_runs()
.update_one(
mongodb::bson::doc! { "_id": oid, "status": "queued" },
mongodb::bson::doc! { "$set": {
"status": "failed",
"error_message": message,
"error_code": mongodb::bson::to_bson(&code).unwrap_or_default(),
"completed_at": mongodb::bson::DateTime::now(),
} },
)
.await
{
tracing::warn!(run_id = %oid, "queued scan run not closed: {e}");
}
}
/// Findings of `target_id` first stored since `since`, by severity; `None`
/// when there are none.
async fn new_findings_summary(
+3 -34
View File
@@ -18,18 +18,7 @@ use super::ApiResponse;
type AgentExt = Extension<Arc<ComplianceAgent>>;
/// Ask about a target's code, answered from its code graph.
#[utoipa::path(
post,
path = "/api/v1/chat/{repo_id}",
tag = "Chat",
params(("repo_id" = String, Path, description = "The target's id")),
request_body(content = Object, description = "`message`, and the earlier `history` as `role` and `content`"),
responses(
(status = 200, description = "The answer with its sources"),
(status = 401, description = "No valid bearer token"),
)
)]
/// POST /api/v1/chat/:repo_id — Send a chat message with RAG context
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
pub async fn chat(
Extension(agent): AgentExt,
@@ -144,17 +133,7 @@ pub async fn chat(
}))
}
/// Build the embeddings the chat answers from, in the background.
#[utoipa::path(
post,
path = "/api/v1/chat/{repo_id}/build-embeddings",
tag = "Chat",
params(("repo_id" = String, Path, description = "The target's id")),
responses(
(status = 200, description = "The build was started"),
(status = 401, description = "No valid bearer token"),
)
)]
/// POST /api/v1/chat/:repo_id/build-embeddings — Trigger embedding build
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
pub async fn build_embeddings(
Extension(agent): AgentExt,
@@ -265,17 +244,7 @@ pub async fn build_embeddings(
))
}
/// The status of a target's latest embedding build.
#[utoipa::path(
get,
path = "/api/v1/chat/{repo_id}/status",
tag = "Chat",
params(("repo_id" = String, Path, description = "The target's id")),
responses(
(status = 200, description = "The build, or null"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/chat/:repo_id/status — Get latest embedding build status
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
pub async fn embedding_status(
Extension(agent): AgentExt,
@@ -1,218 +0,0 @@
//! The CVE charts of the overview and a target's page (#952): open CVEs
//! with a fix per day, and the package updates that close the most of them.
//!
//! Both read the tenant's own database; the org-role middleware lets every
//! role that may read call them, like the other target and CVE reads.
use axum::extract::{Extension, Path, Query};
use axum::http::StatusCode;
use axum::Json;
use mongodb::bson::{doc, oid::ObjectId, Document};
use serde::{Deserialize, Deserializer};
use compliance_core::cve_history::{
top_updates, window, CveHistory, OpenFindings, TopUpdate, DEFAULT_DAYS, MAX_DAYS,
};
use compliance_core::models::CveAlert;
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResult};
use super::health::open_findings_by_severity;
use crate::database::Database;
/// The updates a target's "Wo handeln" table lists.
const TOP_UPDATES_SHOWN: usize = 10;
/// The query of [`cve_history`].
#[derive(Debug, Deserialize)]
pub struct HistoryQuery {
/// Days back from today, `1..=90` (clamped); 30 when not given.
#[serde(default = "default_days", deserialize_with = "de_days")]
pub days: u32,
/// Only this target. Takes precedence over `project`.
#[serde(default)]
pub target: Option<String>,
/// Only the targets of this project (`targets.project_ids`).
#[serde(default)]
pub project: Option<String>,
/// Also each target's own series, for the overview's repo cards.
#[serde(default)]
pub per_target: bool,
}
fn default_days() -> u32 {
DEFAULT_DAYS
}
/// Clamp a caller-supplied number of days to `1..=MAX_DAYS`.
fn de_days<'de, D: Deserializer<'de>>(d: D) -> Result<u32, D::Error> {
Ok(u32::deserialize(d)?.clamp(1, MAX_DAYS))
}
/// A non-empty, trimmed query value.
fn given(value: Option<&str>) -> Option<&str> {
value.map(str::trim).filter(|v| !v.is_empty())
}
/// The target ids the query is about: one target, a project's targets, or
/// `None` for every target of the tenant.
async fn scope(db: &Database, query: &HistoryQuery) -> Result<Option<Vec<String>>, StatusCode> {
if let Some(target) = given(query.target.as_deref()) {
return Ok(Some(vec![target.to_string()]));
}
let Some(project) = given(query.project.as_deref()) else {
return Ok(None);
};
let rows: Vec<Document> = collect_cursor_async(
db.onboarded_targets()
.clone_with_type::<Document>()
.find(doc! { "project_ids": project })
.projection(doc! { "_id": 1 })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
)
.await;
Ok(Some(
rows.iter()
.filter_map(|row| row.get_object_id("_id").ok().map(|id| id.to_hex()))
.collect(),
))
}
/// The alerts with a fixed version that may be open at some point after
/// `since`, of `targets` (every target with `None`). The long texts are
/// left out; the history does not need them.
async fn alerts_with_fix(
db: &Database,
targets: Option<&[String]>,
since: chrono::DateTime<chrono::Utc>,
) -> Result<Vec<CveAlert>, StatusCode> {
let mut filter = doc! {
"fixed_versions.0": { "$exists": true },
"$or": [
{ "resolved_at": null },
{ "resolved_at": { "$gte": mongodb::bson::DateTime::from_chrono(since) } },
],
};
if let Some(targets) = targets {
filter.insert("repo_id", doc! { "$in": targets });
}
let cursor = db
.cve_alerts()
.find(filter)
.projection(doc! {
"summary": 0, "llm_impact_summary": 0, "advisories": 0, "exploitation": 0,
})
.await
.map_err(|e| {
tracing::warn!("CVE history: loading alerts failed: {e}");
StatusCode::INTERNAL_SERVER_ERROR
})?;
Ok(collect_cursor_async(cursor).await)
}
/// `GET /api/v1/cve-history?days=30[&target=<id>][&project=<id>][&per_target=true]`
/// — per day (UTC, oldest first, today last) the open CVEs with a fixed
/// version, by severity, for the tenant, one target or one project's
/// targets; plus the open critical and high findings of the same scope.
///
/// A CVE counts on day `d` when, at the end of `d`: its alert was found
/// (`created_at`), not resolved (`resolved_at` unset or later), not settled
/// by a VEX `not_affected` / `fixed` stated by then (`vex.at`), and its
/// advisory names a fixed version. One CVE counts once per target (its
/// GHSA and CVE alias, or two packages, are one), at its highest severity;
/// a tenant's or project's count is the sum over its targets. See
/// [`compliance_core::cve_history`] for what the stored state cannot show.
#[tracing::instrument(skip_all)]
pub async fn cve_history(
Extension(agent): AgentExt,
tenant: TenantCtx,
Query(query): Query<HistoryQuery>,
) -> ApiResult<CveHistory> {
let db = tenant_db(&agent, &tenant).await?;
let now = chrono::Utc::now();
let since = window(now, query.days).first().map_or(now, |(_, end)| *end);
let targets = scope(&db, &query).await?;
let findings_scope = match &targets {
Some(ids) => doc! { "repo_id": { "$in": ids } },
None => doc! {},
};
let (alerts, by_severity) = tokio::join!(
alerts_with_fix(&db, targets.as_deref(), since),
open_findings_by_severity(&db, findings_scope),
);
let mut history = CveHistory::of(&alerts?, now, query.days);
let count = |name: &str| by_severity.get(name).copied().unwrap_or(0);
history.open_findings = OpenFindings {
critical: count("critical"),
high: count("high"),
};
if !query.per_target {
history.targets.clear();
}
Ok(Json(ApiResponse {
data: history,
total: None,
page: None,
}))
}
/// `GET /api/v1/targets/{id}/top-updates` — the package updates that close
/// the most of the target's open CVEs with a fix (at most ten): package,
/// current version, the highest fixed version its alerts name, and how
/// many CVEs (and critical ones) it closes. 404 for a target the tenant
/// does not have.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn target_top_updates(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
) -> ApiResult<Vec<TopUpdate>> {
let oid = ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
let db = tenant_db(&agent, &tenant).await?;
db.onboarded_targets()
.find_one(doc! { "_id": oid })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::NOT_FOUND)?;
let now = chrono::Utc::now();
let ids = [id];
let alerts = alerts_with_fix(&db, Some(&ids), now).await?;
let mut updates = top_updates(&alerts, now);
let total = updates.len() as u64;
updates.truncate(TOP_UPDATES_SHOWN);
Ok(Json(ApiResponse {
data: updates,
total: Some(total),
page: None,
}))
}
#[cfg(test)]
mod tests {
use super::*;
fn query(text: &str) -> HistoryQuery {
let uri: axum::http::Uri = format!("/api/v1/cve-history?{text}").parse().unwrap();
Query::<HistoryQuery>::try_from_uri(&uri).unwrap().0
}
#[test]
fn the_days_are_clamped_and_default_to_thirty() {
assert_eq!(query("").days, 30);
assert_eq!(query("days=0").days, 1);
assert_eq!(query("days=100000").days, MAX_DAYS);
let q = query("days=7&target=t1&per_target=true");
assert_eq!(
(q.days, q.target.as_deref(), q.per_target),
(7, Some("t1"), true)
);
}
#[test]
fn a_blank_scope_means_every_target() {
assert_eq!(given(Some(" ")), None);
assert_eq!(given(Some(" p1 ")), Some("p1"));
assert_eq!(given(None), None);
}
}
@@ -1,114 +0,0 @@
//! A target's CVE alerts counted by severity and VEX status (#957), for the
//! grid the dashboard's "CVEs & VEX" view opens with.
use axum::extract::{Extension, Path};
use axum::http::StatusCode;
use axum::Json;
use mongodb::bson::{doc, Document};
use serde::Deserialize;
use compliance_core::cve_matrix::{CveCell, CveMatrix};
use compliance_core::models::VexStatus;
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResult};
/// The fields of a stored alert the grid reads.
#[derive(Debug, Deserialize)]
struct MatrixRow {
#[serde(default)]
severity: Option<String>,
#[serde(default)]
cvss_score: Option<f64>,
#[serde(default)]
vex: Option<MatrixVex>,
}
/// The status of an alert's VEX statement; the rest of it is not read.
#[derive(Debug, Deserialize)]
struct MatrixVex {
status: VexStatus,
}
impl MatrixRow {
fn cell(&self) -> CveCell {
CveCell::of(
self.severity.as_deref(),
self.cvss_score,
self.vex.as_ref().map(|v| v.status),
)
}
}
/// The alerts of target `id` the grid counts: still reported, as in
/// [`compliance_core::cve_matrix::counts`]. `null` matches a missing
/// `resolved_at` and one stored as `null`.
fn still_reported(id: &str) -> Document {
doc! { "repo_id": id, "resolved_at": null }
}
/// GET /api/v1/targets/{id}/cve-matrix — the target's still-reported CVE
/// alerts counted per severity and VEX status. Scoped to the requester's
/// tenant like `GET /api/v1/targets/{id}/cves`; the org-role middleware
/// lets every reading role in.
///
/// # Errors
///
/// 500 when the tenant's database or the alerts cannot be read.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn target_cve_matrix(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
) -> ApiResult<CveMatrix> {
let db = tenant_db(&agent, &tenant).await?;
// Only the three fields the bucketing reads, not the summaries and
// references of every alert. A row that does not decode is skipped with
// a warning, as the CVE list skips it.
let cursor = db
.cve_alerts()
.clone_with_type::<MatrixRow>()
.find(still_reported(&id))
.projection(doc! { "_id": 0, "severity": 1, "cvss_score": 1, "vex.status": 1 })
.await
.map_err(|e| {
tracing::warn!("CVE matrix not read: {e}");
StatusCode::INTERNAL_SERVER_ERROR
})?;
let rows: Vec<MatrixRow> = collect_cursor_async(cursor).await;
let matrix = CveMatrix::from_cells(rows.iter().map(MatrixRow::cell));
Ok(Json(ApiResponse {
total: Some(matrix.total()),
data: matrix,
page: None,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use compliance_core::cve_matrix::{CveSeverity, VexColumn};
#[test]
fn only_alerts_still_reported_are_read() {
let filter = still_reported("t1");
assert_eq!(filter.get_str("repo_id").ok(), Some("t1"));
assert_eq!(filter.get("resolved_at"), Some(&mongodb::bson::Bson::Null));
}
#[test]
fn a_projected_row_is_bucketed_like_the_alert() {
let row: MatrixRow = mongodb::bson::from_document(doc! {
"severity": "MODERATE",
"vex": { "status": "not_affected" },
})
.expect("a projected alert");
let cell = row.cell();
assert_eq!(cell.severity, CveSeverity::Medium);
assert_eq!(cell.vex, VexColumn::NotAffected);
let bare: MatrixRow = mongodb::bson::from_document(doc! { "severity": null })
.expect("an alert without severity or statement");
assert_eq!(bare.cell(), CveCell::of(None, None, None));
}
}
+14 -120
View File
@@ -6,9 +6,7 @@ use axum::Json;
use mongodb::bson::doc;
use serde::Deserialize;
use compliance_core::models::dast::{
DastAuthConfig, DastFinding, DastScanRun, DastTarget, DastTargetType,
};
use compliance_core::models::dast::{DastFinding, DastScanRun, DastTarget, DastTargetType};
use compliance_core::models::Credentials;
use compliance_core::tenant_ctx::TenantCtx;
@@ -19,41 +17,21 @@ use super::{collect_cursor_async, ApiResponse, PaginationParams};
type AgentExt = Extension<Arc<ComplianceAgent>>;
/// A DAST target to add.
#[derive(Deserialize, utoipa::ToSchema)]
#[derive(Deserialize)]
pub struct AddTargetRequest {
/// A name for the target.
pub name: String,
/// Where the scan starts; must be publicly routable.
pub base_url: String,
/// `web_app` (default), `rest_api` or `graph_ql`.
#[serde(default = "default_target_type")]
#[schema(value_type = Option<String>, example = "web_app")]
pub target_type: DastTargetType,
/// The target (Prüfobjekt) this DAST target belongs to.
pub repo_id: Option<String>,
/// URL paths the scan leaves out.
#[serde(default)]
pub excluded_paths: Vec<String>,
/// How many link levels the crawl follows (default 5).
#[serde(default = "default_crawl_depth")]
#[schema(value_type = Option<u32>)]
pub max_crawl_depth: u32,
/// Requests per second (default 10).
#[serde(default = "default_rate_limit")]
#[schema(value_type = Option<u32>)]
pub rate_limit: u32,
/// Whether the scan may send `PUT`, `PATCH` and `DELETE` (default false).
#[serde(default)]
#[schema(value_type = Option<bool>)]
pub allow_destructive: bool,
/// The login every scan request carries (#1000): `method` `basic`
/// (`username`, `password`), `bearer` (`token`) or `cookie` (`token` =
/// `name=value`), plus optional extra `headers`. Stored encrypted, never
/// returned.
#[serde(default)]
#[schema(value_type = Option<Object>)]
pub auth: Option<DastAuthConfig>,
}
fn default_target_type() -> DastTargetType {
@@ -66,19 +44,7 @@ fn default_rate_limit() -> u32 {
10
}
/// List the tenant's DAST targets.
///
/// Logins are never returned.
#[utoipa::path(
get,
path = "/api/v1/dast/targets",
tag = "DAST",
params(PaginationParams),
responses(
(status = 200, description = "A page of DAST targets"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/dast/targets — List DAST targets
#[tracing::instrument(skip_all)]
pub async fn list_targets(
Extension(agent): AgentExt,
@@ -115,22 +81,7 @@ pub async fn list_targets(
}))
}
/// Add a DAST target.
///
/// Its login is stored encrypted and never returned; the answer is the new
/// target with its id.
#[utoipa::path(
post,
path = "/api/v1/dast/targets",
tag = "DAST",
request_body = AddTargetRequest,
responses(
(status = 200, description = "The new DAST target"),
(status = 400, description = "The base URL is refused (not publicly routable) or the login cannot be sent"),
(status = 401, description = "No valid bearer token"),
(status = 503, description = "The login cannot be stored encrypted"),
)
)]
/// POST /api/v1/dast/targets — Add a new DAST target
#[tracing::instrument(skip_all)]
pub async fn add_target(
Extension(agent): AgentExt,
@@ -143,22 +94,12 @@ pub async fn add_target(
tracing::warn!(tenant_id = %tenant.0.tenant_id, "DAST target refused: {e}");
return Err(StatusCode::BAD_REQUEST);
}
// A login the scan could not send is refused now, not at the first scan.
if let Err(e) = compliance_dast::auth::login_headers(req.auth.as_ref()) {
tracing::warn!(tenant_id = %tenant.0.tenant_id, "DAST target login refused: {e}");
return Err(StatusCode::BAD_REQUEST);
}
let mut target = DastTarget::new(req.name, req.base_url, req.target_type);
target.repo_id = req.repo_id;
target.excluded_paths = req.excluded_paths;
target.max_crawl_depth = req.max_crawl_depth;
target.rate_limit = req.rate_limit;
target.allow_destructive = req.allow_destructive;
target.auth_config = req.auth;
agent
.secrets
.seal_unsealed(&mut target)
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
let db = tenant_db(&agent, &tenant).await?;
let res = db
@@ -166,8 +107,11 @@ pub async fn add_target(
.insert_one(&target)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
target.id = res.inserted_id.as_object_id();
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
let target_id = res
.inserted_id
.as_object_id()
.map(|id| id.to_hex())
.unwrap_or_default();
agent.emit_usage(
&tenant.0.tenant_id,
"target.added",
@@ -182,23 +126,7 @@ pub async fn add_target(
}))
}
/// Start a DAST scan of a target.
///
/// The scan runs in the background; its run and findings appear under the
/// scan-run and finding lists.
#[utoipa::path(
post,
path = "/api/v1/dast/targets/{id}/scan",
tag = "DAST",
params(("id" = String, Path, description = "The DAST target's id")),
responses(
(status = 200, description = "The scan was started"),
(status = 400, description = "Not an id, or the target's address is refused"),
(status = 401, description = "No valid bearer token"),
(status = 404, description = "No such DAST target"),
(status = 409, description = "This deployment does not run DAST"),
)
)]
/// POST /api/v1/dast/targets/:id/scan — Trigger DAST scan
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn trigger_scan(
Extension(agent): AgentExt,
@@ -213,14 +141,12 @@ pub async fn trigger_scan(
let oid = mongodb::bson::oid::ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
let db = tenant_db(&agent, &tenant).await?;
let mut target = db
let target = db
.dast_targets()
.find_one(doc! { "_id": oid })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::NOT_FOUND)?;
// The login is used here, in memory only.
agent.secrets.open_in_place(&mut target);
// Re-check at use: the target may have been stored before this policy
// existed, and a hostname can be repointed after registration.
@@ -271,17 +197,7 @@ pub async fn trigger_scan(
Ok(Json(serde_json::json!({ "status": "dast_scan_triggered" })))
}
/// List the tenant's DAST scan runs.
#[utoipa::path(
get,
path = "/api/v1/dast/scan-runs",
tag = "DAST",
params(PaginationParams),
responses(
(status = 200, description = "A page of DAST scan runs"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/dast/scan-runs — List DAST scan runs
#[tracing::instrument(skip_all)]
pub async fn list_scan_runs(
Extension(agent): AgentExt,
@@ -319,17 +235,7 @@ pub async fn list_scan_runs(
}))
}
/// List the tenant's DAST findings, with their evidence.
#[utoipa::path(
get,
path = "/api/v1/dast/findings",
tag = "DAST",
params(PaginationParams),
responses(
(status = 200, description = "A page of DAST findings"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/dast/findings — List DAST findings
#[tracing::instrument(skip_all)]
pub async fn list_findings(
Extension(agent): AgentExt,
@@ -367,19 +273,7 @@ pub async fn list_findings(
}))
}
/// One DAST finding, with its request and response evidence.
#[utoipa::path(
get,
path = "/api/v1/dast/findings/{id}",
tag = "DAST",
params(("id" = String, Path, description = "The DAST finding's id")),
responses(
(status = 200, description = "The DAST finding"),
(status = 400, description = "Not an id"),
(status = 401, description = "No valid bearer token"),
(status = 404, description = "No such DAST finding"),
)
)]
/// GET /api/v1/dast/findings/:id — Finding detail with evidence
#[tracing::instrument(skip_all, fields(finding_id = %id))]
pub async fn get_finding(
Extension(agent): AgentExt,
+3 -24
View File
@@ -27,16 +27,7 @@ pub struct SeedResponse {
pub seeded: Vec<SeededTarget>,
}
/// The demo targets the agent ships, which seeding would create.
#[utoipa::path(
get,
path = "/api/v1/targets/demo-seed",
tag = "Targets",
responses(
(status = 200, description = "The demo targets"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/targets/demo-seed — what "Add demo targets" would create.
#[tracing::instrument(skip_all)]
pub async fn list_demo_targets(
_tenant: TenantCtx,
@@ -48,20 +39,8 @@ pub async fn list_demo_targets(
Ok(Json(DemoTargetsResponse { targets }))
}
/// Create the demo targets for the tenant and start their scans.
///
/// 202: the targets exist and their scans are running in the background.
#[utoipa::path(
post,
path = "/api/v1/targets/demo-seed",
tag = "Targets",
request_body(content = Option<SeedRequest>, description = "Which demo targets; none seeds all"),
responses(
(status = 202, description = "The targets exist; their scans are running"),
(status = 400, description = "An unknown demo target"),
(status = 401, description = "No valid bearer token"),
)
)]
/// POST /api/v1/targets/demo-seed — seed the caller's tenant. 202: the targets
/// exist and their scans are running in the background.
#[tracing::instrument(skip_all)]
pub async fn seed_demo_targets(
Extension(agent): AgentExt,
+10 -244
View File
@@ -15,17 +15,11 @@ pub const MAX_PAGE_SIZE: i64 = 200;
/// absurd offset. At [`MAX_PAGE_SIZE`] this is still 20M documents deep.
pub const MAX_PAGE: u64 = 100_000;
/// The page of a list a request asks for.
#[derive(Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
#[derive(Deserialize)]
pub struct PaginationParams {
/// The page, from 1 (default 1, at most 100 000).
#[serde(default = "default_page", deserialize_with = "de_page")]
#[param(minimum = 1, maximum = 100_000)]
pub page: u64,
/// Entries per page (default 50, at most 200).
#[serde(default = "default_limit", deserialize_with = "de_limit")]
#[param(minimum = 1, maximum = 200)]
pub limit: i64,
}
@@ -55,57 +49,33 @@ pub(crate) fn de_limit<'de, D: serde::Deserializer<'de>>(d: D) -> Result<i64, D:
Ok(i64::deserialize(d)?.clamp(1, MAX_PAGE_SIZE))
}
/// Which findings a list returns, and in what order.
#[derive(Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
#[derive(Deserialize)]
pub struct FindingsFilter {
/// Only one target's findings (its id).
#[serde(default)]
pub repo_id: Option<String>,
/// Only the findings a given scan run found first (the dashboard reveals
/// them when the run ends).
#[serde(default)]
pub scan_run_id: Option<String>,
/// `info`, `low`, `medium`, `high` or `critical`.
#[serde(default)]
pub severity: Option<String>,
/// Only one kind of scan (`sast`, `cve`, `dast`, …).
#[serde(default)]
pub scan_type: Option<String>,
/// `open`, `triaged`, `false_positive`, `resolved`, `ignored`,
/// `accepted_risk`, `needs_review` or `wrong_mapping`.
#[serde(default)]
pub status: Option<String>,
/// Text the title, description or file path contains (at most 128
/// characters, matched literally).
#[serde(default)]
pub q: Option<String>,
/// Only the findings of one scanner (`Finding::scanner`, e.g.
/// `sbom-coverage`).
#[serde(default)]
pub scanner: Option<String>,
/// Only the findings in one app variant (`Tablet App`): its own, and the
/// groups listing a place in it.
#[serde(default)]
pub variant: Option<String>,
/// Only the findings in one folder, as the folder chart names it
/// ([`path_regex`]).
#[serde(default)]
pub path: Option<String>,
/// `created_at` (default), `updated_at`, `severity`, `scan_type`,
/// `status`, `file_path`, `rule_id`, `repo_id`, `title` or `confidence`.
#[serde(default)]
pub sort_by: Option<String>,
/// `asc`, or newest/highest first (default).
#[serde(default)]
pub sort_order: Option<String>,
/// The page, from 1 (default 1, at most 100 000).
#[serde(default = "default_page", deserialize_with = "de_page")]
#[param(minimum = 1, maximum = 100_000)]
pub page: u64,
/// Entries per page (default 50, at most 200).
#[serde(default = "default_limit", deserialize_with = "de_limit")]
#[param(minimum = 1, maximum = 200)]
pub limit: i64,
}
@@ -118,65 +88,6 @@ impl FindingsFilter {
}
}
/// Open or closed, as the tickets list filters them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TicketState {
/// Open or in progress.
Open,
/// Closed or resolved.
Closed,
}
impl TicketState {
/// The stored statuses (`in_progress`) this state stands for.
pub fn statuses(self) -> Vec<String> {
let closed = self == Self::Closed;
compliance_core::models::IssueStatus::ALL
.iter()
.filter(|s| s.is_closed() == closed)
.map(ToString::to_string)
.collect()
}
}
/// The query of the tickets list (`GET /api/v1/issues`).
#[derive(Deserialize)]
pub struct IssuesFilter {
/// A word of the title or the ticket number (`913`, `#913`, `PROJ-913`).
#[serde(default)]
pub q: Option<String>,
/// Only open or only closed tickets; an unknown value is refused (400).
#[serde(default)]
pub status: Option<TicketState>,
/// Only the tickets of one target: of its findings and its CVEs.
#[serde(default)]
pub repo_id: Option<String>,
#[serde(default = "default_page", deserialize_with = "de_page")]
pub page: u64,
#[serde(default = "default_limit", deserialize_with = "de_limit")]
pub limit: i64,
}
impl IssuesFilter {
/// Documents to skip for this page. Bounded by construction.
pub fn skip(&self) -> u64 {
self.page
.saturating_sub(1)
.saturating_mul(self.limit as u64)
}
/// The search term, trimmed; `None` when there is none.
pub fn search(&self) -> Option<&str> {
self.q.as_deref().map(str::trim).filter(|q| !q.is_empty())
}
/// The target to filter by; `None` for all.
pub fn target(&self) -> Option<&str> {
self.repo_id.as_deref().filter(|id| !id.is_empty())
}
}
/// Fields a caller may sort findings by.
///
/// `sort_by` went into the sort document verbatim, so a caller could sort on
@@ -225,35 +136,6 @@ pub fn literal_regex(term: &str) -> String {
out
}
/// The `file_path` regex of a folder filter, anchored and literal; `None`
/// for an empty filter.
///
/// The keys are those of the folder chart
/// ([`compliance_core::finding_breakdown::FolderBreakdown::path`]):
/// `/` is the files in the root, `src/*` the files directly in `src`, and
/// `src/` (or `src`) everything below `src`. A leading `/` on a stored path
/// is allowed, as the chart ignores it too.
pub fn path_regex(folder: &str) -> Option<String> {
use compliance_core::finding_breakdown::{DIRECT_SUFFIX, ROOT_FOLDER};
let folder = folder.trim();
if folder.is_empty() {
return None;
}
if folder == ROOT_FOLDER {
return Some("^/?[^/]+$".to_string());
}
let (dir, direct) = match folder.strip_suffix(DIRECT_SUFFIX) {
Some(dir) => (dir, true),
None => (folder, false),
};
let dir = literal_regex(dir.trim_matches('/'));
Some(if direct {
format!("^/?{dir}/[^/]+$")
} else {
format!("^/?{dir}/")
})
}
#[derive(Serialize)]
pub struct ApiResponse<T: Serialize> {
pub data: T,
@@ -309,58 +191,39 @@ fn default_branch() -> String {
"main".to_string()
}
/// A finding's new status.
#[derive(Deserialize, utoipa::ToSchema)]
#[derive(Deserialize)]
pub struct UpdateStatusRequest {
/// `open`, `triaged`, `false_positive`, `resolved`, `ignored`,
/// `accepted_risk`, `needs_review` or `wrong_mapping`. Typed, so an
/// unknown status is refused (422) instead of being stored and breaking
/// every later read of the finding.
#[schema(value_type = String, example = "false_positive")]
/// Typed, so an unknown status is refused (422) instead of being stored
/// and breaking every later read of the finding.
pub status: compliance_core::models::FindingStatus,
/// Why; required for `accepted_risk`.
#[serde(default)]
pub reason: Option<String>,
}
/// The same new status for many findings.
#[derive(Deserialize, utoipa::ToSchema)]
#[derive(Deserialize)]
pub struct BulkUpdateStatusRequest {
/// The findings' ids.
pub ids: Vec<String>,
/// The status, as for one finding.
#[schema(value_type = String, example = "resolved")]
pub status: compliance_core::models::FindingStatus,
/// Why; required for `accepted_risk` and `wrong_mapping`.
#[serde(default)]
pub reason: Option<String>,
}
/// A developer's feedback on a finding.
#[derive(Deserialize, utoipa::ToSchema)]
#[derive(Deserialize)]
pub struct UpdateFeedbackRequest {
/// The feedback, as text.
pub feedback: String,
}
/// Which SBOM components a list or summary shows.
#[derive(Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
#[derive(Deserialize)]
pub struct SbomFilter {
/// Only one target's components (its id).
#[serde(default)]
pub repo_id: Option<String>,
/// Only one package manager's components, such as `npm` or `cargo`.
#[serde(default)]
pub package_manager: Option<String>,
/// Only components whose name contains this text.
#[serde(default)]
pub q: Option<String>,
/// Only components with known vulnerabilities (`true`), or only those
/// without (`false`).
#[serde(default)]
pub has_vulns: Option<bool>,
/// Only components with this licence.
#[serde(default)]
pub license: Option<String>,
/// Only components an image is known to contain (`true`), or only the
@@ -371,13 +234,9 @@ pub struct SbomFilter {
/// none and nobody has confirmed one.
#[serde(default)]
pub unresolved: Option<bool>,
/// The page, from 1 (default 1, at most 100 000).
#[serde(default = "default_page", deserialize_with = "de_page")]
#[param(minimum = 1, maximum = 100_000)]
pub page: u64,
/// Entries per page (default 50, at most 200).
#[serde(default = "default_limit", deserialize_with = "de_limit")]
#[param(minimum = 1, maximum = 200)]
pub limit: i64,
}
@@ -390,15 +249,10 @@ impl SbomFilter {
}
}
/// The target and format of an SBOM export.
#[derive(Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
#[derive(Deserialize)]
pub struct SbomExportParams {
/// The target (its id).
pub repo_id: String,
/// `cyclonedx` (default) or `spdx`.
#[serde(default = "default_export_format")]
#[param(example = "cyclonedx")]
pub format: String,
}
@@ -406,13 +260,9 @@ fn default_export_format() -> String {
"cyclonedx".to_string()
}
/// The two targets an SBOM diff compares.
#[derive(Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
#[derive(Deserialize)]
pub struct SbomDiffParams {
/// The first target (its id).
pub repo_a: String,
/// The second target (its id).
pub repo_b: String,
}
@@ -562,41 +412,6 @@ mod tests {
assert_eq!(literal_regex(&long).len(), MAX_SEARCH_LEN);
}
#[test]
fn folder_filters_are_anchored_literal_regexes() {
let matches = |folder: &str, path: &str| {
let re = regex::Regex::new(&path_regex(folder).expect("a filter")).expect("valid");
re.is_match(path)
};
assert_eq!(path_regex(""), None);
assert_eq!(path_regex(" "), None);
// Everything below a folder, with or without the trailing slash.
assert!(matches("src/", "src/api/a.rs"));
assert!(matches("src", "src/a.rs"));
assert!(!matches("src/", "srcfoo/a.rs"));
assert!(!matches("src/", "lib/src/a.rs"));
assert!(matches("src/api/", "/src/api/a.rs"));
// Only the files directly in a folder.
assert!(matches("src/*", "src/main.rs"));
assert!(!matches("src/*", "src/api/a.rs"));
// The root.
assert!(matches("/", "README.md"));
assert!(matches("/", "/Cargo.toml"));
assert!(!matches("/", "src/main.rs"));
// Metacharacters in a folder name are literal.
assert_eq!(path_regex("a.b/").as_deref(), Some(r"^/?a\.b/"));
assert!(!matches("a.b/", "axb/c.rs"));
assert!(matches("(x)/", "(x)/y.rs"));
}
#[test]
fn the_findings_filter_takes_a_folder() {
let f: FindingsFilter = serde_json::from_str(r#"{"path":"src/*"}"#).unwrap();
assert_eq!(f.path.as_deref(), Some("src/*"));
let f: FindingsFilter = serde_json::from_str("{}").unwrap();
assert_eq!(f.path, None);
}
#[test]
fn sbom_filter_clamps_the_same_way() {
let f: SbomFilter = serde_json::from_str(r#"{"limit":10000000,"page":0}"#).unwrap();
@@ -663,55 +478,6 @@ mod tests {
assert_eq!(f.severity.as_deref(), Some(""));
}
// ── IssuesFilter ─────────────────────────────────────────────
#[test]
fn issues_filter_defaults_and_clamps() {
let f: IssuesFilter = serde_json::from_str("{}").unwrap();
assert_eq!(f.search(), None);
assert_eq!(f.status, None);
assert_eq!(f.target(), None);
assert_eq!((f.page, f.limit), (1, 50));
let f: IssuesFilter = serde_json::from_str(r#"{"limit":5000,"page":0}"#).unwrap();
assert_eq!(f.limit, MAX_PAGE_SIZE);
assert_eq!(f.skip(), 0);
}
#[test]
fn issues_filter_ignores_blank_search_and_target() {
let f: IssuesFilter = serde_json::from_str(r#"{"q":" ","repo_id":""}"#).unwrap();
assert_eq!(f.search(), None);
assert_eq!(f.target(), None);
let f: IssuesFilter = serde_json::from_str(r##"{"q":" #913 ","repo_id":"t1"}"##).unwrap();
assert_eq!(f.search(), Some("#913"));
assert_eq!(f.target(), Some("t1"));
}
#[test]
fn issues_filter_status_is_open_or_closed_only() {
let f: IssuesFilter = serde_json::from_str(r#"{"status":"closed"}"#).unwrap();
assert_eq!(f.status, Some(TicketState::Closed));
assert!(serde_json::from_str::<IssuesFilter>(r#"{"status":"$ne"}"#).is_err());
}
#[test]
fn ticket_states_cover_every_stored_status_once() {
assert_eq!(TicketState::Open.statuses(), ["open", "in_progress"]);
assert_eq!(TicketState::Closed.statuses(), ["closed", "resolved"]);
// The names are the stored ones.
for name in TicketState::Open
.statuses()
.into_iter()
.chain(TicketState::Closed.statuses())
{
let status: compliance_core::models::IssueStatus =
serde_json::from_value(json!(name)).unwrap();
assert_eq!(status.to_string(), name);
}
}
// ── ApiResponse ──────────────────────────────────────────────
#[test]
@@ -79,14 +79,9 @@ async fn load_inputs(
.map_err(load_err)?,
)
.await,
// A run still waiting for a slot has examined nothing yet (t84).
last_run: db
.scan_runs()
.find_one({
let mut started = by_target;
started.insert("status", doc! { "$ne": "queued" });
started
})
.find_one(by_target)
.sort(doc! { "started_at": -1 })
.await
.map_err(load_err)?,
@@ -173,9 +168,6 @@ pub async fn compliance_view(
"data": {
"target_id": id,
"target_name": inputs.target.name,
// Whether Prüfwerk opens tickets for the target's findings; the
// finding page offers Breakpilot Git when it does not.
"issue_tracker_connected": inputs.target.issue_tracker_connected(),
"counts": state_counts(&controls),
"last_scan": inputs.last_run,
"sbom_components": inputs.sbom.len(),
@@ -1,70 +0,0 @@
//! `GET /api/v1/targets/{id}/finding-breakdown`: a target's open findings
//! by type and severity, and by folder, for the charts of its findings view
//! (#957).
use axum::extract::{Extension, Path};
use mongodb::bson::doc;
use compliance_core::finding_breakdown::{
breakdown, BreakdownRow, FindingBreakdown, OPEN_STATUSES,
};
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResult};
/// The Mongo filter of a target's open (undecided) findings.
fn open_findings_of(target_id: &str) -> mongodb::bson::Document {
let open: Vec<String> = OPEN_STATUSES.iter().map(ToString::to_string).collect();
doc! { "repo_id": target_id, "status": { "$in": open } }
}
/// The open findings of target `id`, counted by type and severity and by
/// folder. Tenant-scoped like the findings list, and read-only, so every
/// role that may read findings may read it. A target without open findings
/// (or of another tenant, whose findings are not in this tenant's database)
/// gets an empty breakdown.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn finding_breakdown(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
) -> ApiResult<FindingBreakdown> {
let db = tenant_db(&agent, &tenant).await?;
// Only the three fields the counts need cross the wire.
let rows: Vec<BreakdownRow> = match db
.findings()
.clone_with_type::<BreakdownRow>()
.find(open_findings_of(&id))
.projection(doc! { "_id": 0, "scan_type": 1, "severity": 1, "file_path": 1 })
.await
{
// A document that does not read is skipped (and logged), not fatal.
Ok(cursor) => collect_cursor_async(cursor).await,
Err(e) => {
tracing::warn!("open findings for the breakdown not read: {e}");
Vec::new()
}
};
let result = breakdown(&rows);
Ok(axum::Json(ApiResponse {
total: Some(result.total),
data: result,
page: None,
}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_targets_undecided_findings_are_counted() {
assert_eq!(
open_findings_of("t1"),
doc! {
"repo_id": "t1",
"status": { "$in": ["open", "triaged", "needs_review"] },
}
);
}
}
@@ -1,304 +0,0 @@
//! Open findings grouped by rule and file, and one decision for a whole
//! group (#951).
//!
//! The grouping is [`compliance_core::models::finding_group`], a pure
//! function over the findings; nothing about groups is stored. A group
//! decision is a status change of every member through the same path as a
//! bulk change ([`super::findings::apply_status`]), so the status history,
//! the issue sync, the evidence pack and VEX see ordinary per-finding
//! changes.
use axum::extract::{Extension, Query};
use axum::http::StatusCode;
use axum::Json;
use mongodb::bson::{doc, Document};
use serde::Deserialize;
use super::dto::{collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResult};
use super::findings::{apply_status, status_update, Actor};
use super::health::OPEN_STATUSES;
use compliance_core::models::finding_group::{group_findings, members_of, FindingGroup, GroupKey};
use compliance_core::models::{Finding, FindingStatus};
use compliance_core::tenant_ctx::TenantCtx;
/// The query of [`list_finding_groups`].
#[derive(Debug, Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
pub struct GroupsQuery {
/// Only one target's findings (`Finding::repo_id`).
#[serde(default)]
pub target: Option<String>,
}
/// The body of [`decide_finding_group`].
#[derive(Debug, Deserialize, utoipa::ToSchema)]
pub struct DecideGroupRequest {
/// The group, as [`list_finding_groups`] named it.
#[schema(value_type = Object)]
pub key: GroupKey,
/// The decision for every member, a finding status.
#[schema(value_type = String, example = "false_positive")]
pub status: FindingStatus,
/// Why; required for an accepted risk or a wrong mapping.
#[serde(default)]
pub reason: Option<String>,
}
/// The fields a group never shows, left out of the read: the code, the fix
/// and the history are on each finding's own page.
fn light_projection() -> Document {
doc! {
"code_snippet": 0,
"suggested_fix": 0,
"remediation": 0,
"status_history": 0,
"legacy_fingerprints": 0,
}
}
/// The undecided findings `filter` narrows down to.
async fn undecided_findings(
db: &crate::database::Database,
mut filter: Document,
) -> Result<Vec<Finding>, StatusCode> {
filter.insert("status", doc! { "$in": OPEN_STATUSES.to_vec() });
let cursor = db
.findings()
.find(filter)
.projection(light_projection())
.await
.map_err(|e| {
tracing::warn!("Failed to fetch findings to group: {e}");
StatusCode::INTERNAL_SERVER_ERROR
})?;
Ok(collect_cursor_async(cursor).await)
}
/// List the undecided findings, grouped by rule and file.
///
/// Most severe first (see [`compliance_core::models::finding_group`]).
#[utoipa::path(
get,
path = "/api/v1/finding-groups",
tag = "Findings",
params(GroupsQuery),
responses(
(status = 200, description = "The groups, most severe first"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(target = ?query.target))]
pub async fn list_finding_groups(
Extension(agent): AgentExt,
tenant: TenantCtx,
Query(query): Query<GroupsQuery>,
) -> ApiResult<Vec<FindingGroup>> {
let db = tenant_db(&agent, &tenant).await?;
let filter = query
.target
.filter(|t| !t.is_empty())
.map_or_else(Document::new, |target| doc! { "repo_id": target });
let groups = group_findings(undecided_findings(&db, filter).await?);
Ok(Json(ApiResponse {
total: Some(groups.len() as u64),
data: groups,
page: None,
}))
}
/// Whether a person may give a whole group `status`: a decision, not a
/// return to an undecided state (the members are undecided already, and
/// "needs review" is the AI's to set).
fn is_group_decision(status: &FindingStatus) -> bool {
match status {
FindingStatus::FalsePositive
| FindingStatus::AcceptedRisk
| FindingStatus::WrongMapping
| FindingStatus::Ignored
| FindingStatus::Resolved => true,
FindingStatus::Open | FindingStatus::Triaged | FindingStatus::NeedsReview => false,
}
}
/// The status change `req` asks of every member, by `actor`.
///
/// # Errors
///
/// 422 when the status is not a decision, or needs a reason and comes
/// without one.
fn decision_update(req: &DecideGroupRequest, actor: &Actor<'_>) -> Result<Document, StatusCode> {
if !is_group_decision(&req.status) {
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
status_update(&req.status, req.reason.as_deref(), actor)
}
/// The findings that may belong to the group `key`: its rule in its target.
/// The grouping then picks the members from them.
fn candidates_filter(key: &GroupKey) -> Document {
doc! {
"repo_id": &key.repo_id,
"scanner": &key.scanner,
"$or": [
{ "rule_id": &key.rule },
// A finding without a rule id is grouped by its title.
{ "rule_id": { "$in": [null, ""] }, "title": &key.rule },
],
}
}
/// Decide every undecided finding of a group at once.
///
/// Each member gets the same status, as if each were changed on its own.
///
/// The members are found again from the key, so a member someone decided
/// in the meantime keeps that decision. 404 when the group has no undecided
/// member (any more), 422 as [`decision_update`].
#[utoipa::path(
post,
path = "/api/v1/finding-groups/decide",
tag = "Findings",
request_body = DecideGroupRequest,
responses(
(status = 200, description = "The members were decided"),
(status = 404, description = "The group has no undecided member"),
(status = 422, description = "An unknown status, or no reason for one that needs it"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(rule = %req.key.rule, scope = ?req.key.scope))]
pub async fn decide_finding_group(
Extension(agent): AgentExt,
tenant: TenantCtx,
Json(req): Json<DecideGroupRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let update = decision_update(&req, &Actor::of(&tenant.0))?;
let db = tenant_db(&agent, &tenant).await?;
let candidates = undecided_findings(&db, candidates_filter(&req.key)).await?;
let oids = members_of(candidates, &req.key);
if oids.is_empty() {
return Err(StatusCode::NOT_FOUND);
}
let filter = doc! {
"_id": { "$in": oids.clone() },
"status": { "$in": OPEN_STATUSES.to_vec() },
};
let members = oids.len();
let modified_count = apply_status(&agent, db, filter, oids, update).await?;
Ok(Json(serde_json::json!({
"status": "updated",
"members": members,
"modified_count": modified_count,
})))
}
#[cfg(test)]
mod tests {
use super::*;
use compliance_core::models::finding_group::GroupScope;
fn key() -> GroupKey {
GroupKey {
repo_id: "repo-1".into(),
scanner: "gdpr-patterns".into(),
rule: "pii-logged".into(),
scope: GroupScope::File,
place: Some("src/patterns.rs".into()),
}
}
fn request(status: FindingStatus, reason: Option<&str>) -> DecideGroupRequest {
DecideGroupRequest {
key: key(),
status,
reason: reason.map(String::from),
}
}
fn user() -> Actor<'static> {
Actor {
id: "u-1",
name: None,
support: false,
}
}
#[test]
fn a_group_takes_only_decisions() {
for status in [
FindingStatus::Open,
FindingStatus::Triaged,
FindingStatus::NeedsReview,
] {
assert_eq!(
decision_update(&request(status.clone(), Some("why")), &user()).err(),
Some(StatusCode::UNPROCESSABLE_ENTITY),
"{status}"
);
}
for status in [
FindingStatus::FalsePositive,
FindingStatus::Ignored,
FindingStatus::Resolved,
] {
assert!(
decision_update(&request(status.clone(), None), &user()).is_ok(),
"{status}"
);
}
}
#[test]
fn an_accepted_risk_for_a_group_needs_a_reason() {
assert_eq!(
decision_update(&request(FindingStatus::AcceptedRisk, None), &user()).err(),
Some(StatusCode::UNPROCESSABLE_ENTITY)
);
assert_eq!(
decision_update(&request(FindingStatus::AcceptedRisk, Some(" ")), &user()).err(),
Some(StatusCode::UNPROCESSABLE_ENTITY)
);
let update = decision_update(
&request(FindingStatus::AcceptedRisk, Some("isolated network")),
&user(),
)
.unwrap_or_default();
let change = update
.get_document("$push")
.and_then(|p| p.get_document("status_history"))
.cloned()
.unwrap_or_default();
assert_eq!(change.get_str("reason").ok(), Some("isolated network"));
assert_eq!(change.get_str("by").ok(), Some("u-1"));
}
#[test]
fn a_request_reads_the_key_and_refuses_an_unknown_status() {
let wire = serde_json::json!({
"key": {
"repo_id": "repo-1",
"scanner": "gdpr-patterns",
"rule": "pii-logged",
"scope": "file",
"place": "src/patterns.rs",
},
"status": "false_positive",
});
let req = serde_json::from_value::<DecideGroupRequest>(wire.clone());
assert_eq!(req.ok().map(|r| r.key), Some(key()));
let mut bad = wire.clone();
bad["status"] = "wontfix".into();
assert!(serde_json::from_value::<DecideGroupRequest>(bad).is_err());
let mut bad_scope = wire;
bad_scope["key"]["scope"] = "everywhere".into();
assert!(serde_json::from_value::<DecideGroupRequest>(bad_scope).is_err());
}
#[test]
fn the_candidates_are_the_rule_in_the_target() {
let filter = candidates_filter(&key());
assert_eq!(filter.get_str("repo_id").ok(), Some("repo-1"));
assert_eq!(filter.get_str("scanner").ok(), Some("gdpr-patterns"));
assert_eq!(filter.get_array("$or").map(Vec::len).ok(), Some(2));
}
}
+17 -149
View File
@@ -7,17 +7,6 @@ use super::dto::*;
use compliance_core::models::{Finding, FindingStatus, StatusChange};
use compliance_core::tenant_ctx::TenantCtx;
/// List the tenant's findings, filtered, sorted and a page at a time.
#[utoipa::path(
get,
path = "/api/v1/findings",
tag = "Findings",
params(FindingsFilter),
responses(
(status = 200, description = "A page of findings"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(repo_id = ?filter.repo_id, severity = ?filter.severity, scan_type = ?filter.scan_type))]
pub async fn list_findings(
Extension(agent): AgentExt,
@@ -39,14 +28,8 @@ pub async fn list_findings(
if let Some(scan_type) = &filter.scan_type {
query.insert("scan_type", scan_type);
}
if let Some(scanner) = &filter.scanner {
query.insert("scanner", scanner);
}
if let Some(status) = &filter.status {
query.insert("status", status_filter(status));
}
if let Some(regex) = filter.path.as_deref().and_then(path_regex) {
query.insert("file_path", doc! { "$regex": regex });
query.insert("status", status);
}
// Text search across title, description, file_path, rule_id
if let Some(q) = &filter.q {
@@ -126,18 +109,6 @@ pub async fn list_findings(
}))
}
/// The match of a `status` filter: one status, or all undecided ones for
/// [`compliance_core::finding_breakdown::OPEN_STATUS_FILTER`].
fn status_filter(status: &str) -> mongodb::bson::Bson {
use compliance_core::finding_breakdown::{OPEN_STATUSES, OPEN_STATUS_FILTER};
if status == OPEN_STATUS_FILTER {
let open: Vec<String> = OPEN_STATUSES.iter().map(ToString::to_string).collect();
mongodb::bson::Bson::Document(doc! { "$in": open })
} else {
mongodb::bson::Bson::String(status.to_string())
}
}
/// The temporary field the severity sort ranks on.
const SEVERITY_RANK: &str = "_severity_rank";
@@ -155,27 +126,15 @@ fn severity_rank() -> mongodb::bson::Document {
}
/// The query of [`list_finding_variants`].
#[derive(Debug, serde::Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
#[derive(Debug, serde::Deserialize)]
pub struct VariantsQuery {
/// Only one target's variants.
#[serde(default)]
pub repo_id: Option<String>,
}
/// List the app variants the tenant's findings are in.
///
/// Their own and their groups' places, sorted, for the findings filter.
#[utoipa::path(
get,
path = "/api/v1/findings/variants",
tag = "Findings",
params(VariantsQuery),
responses(
(status = 200, description = "The app variant names, sorted"),
(status = 401, description = "No valid bearer token"),
)
)]
/// The app variants the tenant's findings are labelled with (theirs and their
/// groups' places), sorted, for the findings filter.
#[tracing::instrument(skip_all, fields(repo_id = ?query.repo_id))]
pub async fn list_finding_variants(
Extension(agent): AgentExt,
@@ -206,19 +165,6 @@ pub async fn list_finding_variants(
}))
}
/// One finding.
#[utoipa::path(
get,
path = "/api/v1/findings/{id}",
tag = "Findings",
params(("id" = String, Path, description = "The finding's id")),
responses(
(status = 200, description = "The finding"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such finding"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(finding_id = %id))]
pub async fn get_finding(
Extension(agent): AgentExt,
@@ -268,7 +214,7 @@ impl<'a> Actor<'a> {
}
}
pub(crate) fn status_update(
fn status_update(
status: &FindingStatus,
reason: Option<&str>,
actor: &Actor<'_>,
@@ -285,7 +231,6 @@ pub(crate) fn status_update(
at: chrono::Utc::now(),
reason: reason.map(String::from),
scan: None,
tracker: None,
};
let status = mongodb::bson::to_bson(status).map_err(|_| StatusCode::BAD_REQUEST)?;
let change = mongodb::bson::to_bson(&change).map_err(|_| StatusCode::BAD_REQUEST)?;
@@ -309,23 +254,8 @@ fn issue_sync(
}
}
/// Change a finding's status.
///
/// Records who, when and why. 404 when there is no such finding.
#[utoipa::path(
patch,
path = "/api/v1/findings/{id}/status",
tag = "Findings",
params(("id" = String, Path, description = "The finding's id")),
request_body = UpdateStatusRequest,
responses(
(status = 200, description = "The status was changed"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such finding"),
(status = 422, description = "An unknown status, or no reason for one that needs it"),
(status = 401, description = "No valid bearer token"),
)
)]
/// PATCH /api/v1/findings/{id}/status — change the status, recording who,
/// when and why. 404 when there is no such finding.
#[tracing::instrument(skip_all, fields(finding_id = %id))]
pub async fn update_finding_status(
Extension(agent): AgentExt,
@@ -350,19 +280,7 @@ pub async fn update_finding_status(
Ok(Json(serde_json::json!({ "status": "updated" })))
}
/// Change the status of many findings at once.
#[utoipa::path(
patch,
path = "/api/v1/findings/bulk-status",
tag = "Findings",
request_body = BulkUpdateStatusRequest,
responses(
(status = 200, description = "How many findings changed"),
(status = 400, description = "An id that is not one"),
(status = 422, description = "An unknown status, or no reason for one that needs it"),
(status = 401, description = "No valid bearer token"),
)
)]
/// PATCH /api/v1/findings/bulk-status — the same change on many findings.
#[tracing::instrument(skip_all)]
pub async fn bulk_update_finding_status(
Extension(agent): AgentExt,
@@ -381,58 +299,20 @@ pub async fn bulk_update_finding_status(
let update = status_update(&req.status, req.reason.as_deref(), &Actor::of(&tenant.0))?;
let db = tenant_db(&agent, &tenant).await?;
let filter = doc! { "_id": { "$in": oids.clone() } };
let modified_count = apply_status(&agent, db, filter, oids, update).await?;
let result = db
.findings()
.update_many(doc! { "_id": { "$in": oids.clone() } }, update)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
issue_sync(&agent, db).spawn(oids);
Ok(Json(
serde_json::json!({ "status": "updated", "modified_count": modified_count }),
serde_json::json!({ "status": "updated", "modified_count": result.modified_count }),
))
}
/// Apply the status change `update` (from [`status_update`]) to the findings
/// `filter` matches, then carry the new status over to the issues of `oids`
/// (the findings the filter is about) in the background: the one path every
/// change of many findings takes, a bulk change or a group decision (#951).
///
/// # Returns
///
/// How many findings changed.
///
/// # Errors
///
/// 500 when the database refuses the update.
pub(crate) async fn apply_status(
agent: &crate::agent::ComplianceAgent,
db: crate::database::Database,
filter: mongodb::bson::Document,
oids: Vec<mongodb::bson::oid::ObjectId>,
update: mongodb::bson::Document,
) -> Result<u64, StatusCode> {
let result = db
.findings()
.update_many(filter, update)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
issue_sync(agent, db).spawn(oids);
Ok(result.modified_count)
}
/// Store a developer's feedback on a finding.
///
/// 404 when there is no such finding.
#[utoipa::path(
patch,
path = "/api/v1/findings/{id}/feedback",
tag = "Findings",
params(("id" = String, Path, description = "The finding's id")),
request_body = UpdateFeedbackRequest,
responses(
(status = 200, description = "The feedback was stored"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such finding"),
(status = 401, description = "No valid bearer token"),
)
)]
/// PATCH /api/v1/findings/{id}/feedback — store the developer's feedback on a
/// finding. 404 when there is no such finding.
#[tracing::instrument(skip_all, fields(finding_id = %id))]
pub async fn update_finding_feedback(
Extension(agent): AgentExt,
@@ -462,18 +342,6 @@ pub async fn update_finding_feedback(
mod tests {
use super::*;
#[test]
fn the_undecided_filter_matches_every_open_status() {
assert_eq!(
status_filter("undecided"),
mongodb::bson::Bson::Document(doc! { "$in": ["open", "triaged", "needs_review"] })
);
assert_eq!(
status_filter("resolved"),
mongodb::bson::Bson::String("resolved".into())
);
}
#[test]
fn an_accepted_risk_needs_a_reason() {
assert_eq!(
@@ -6,15 +6,15 @@ use axum::http::StatusCode;
use axum::Json;
use compliance_core::models::GitSourceView;
use compliance_core::tenant::OrgRole;
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{tenant_db, AgentExt};
use super::ApiResponse;
/// Whether the caller may see the git source: administrators (IT_ADMIN,
/// OWNER) and support.
/// Whether the caller may see the git source: IT administrators and support.
fn may_view(tenant: &TenantCtx) -> bool {
tenant.0.staff.is_some() || tenant.0.is_admin()
tenant.0.staff.is_some() || tenant.0.org_roles.contains(&OrgRole::ItAdmin)
}
/// The source without secrets, plus the webhook URL; `data: null` when the
+13 -215
View File
@@ -6,9 +6,7 @@ use axum::Json;
use mongodb::bson::doc;
use serde::{Deserialize, Serialize};
use compliance_core::models::graph::{
CodeEdge, CodeNode, GraphBuildRun, GraphBuildStatus, ImpactAnalysis,
};
use compliance_core::models::graph::{CodeEdge, CodeNode, GraphBuildRun, ImpactAnalysis};
use compliance_core::tenant_ctx::TenantCtx;
use crate::agent::ComplianceAgent;
@@ -42,18 +40,14 @@ pub struct GraphData {
pub total_nodes: u64,
}
/// A symbol search.
#[derive(Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
#[derive(Deserialize)]
pub struct SearchParams {
/// The search text.
pub q: String,
/// Clamped to `1..=MAX_PAGE_SIZE` while deserializing, like every list.
#[serde(
default = "default_search_limit",
deserialize_with = "super::dto::de_limit"
)]
#[param(minimum = 1, maximum = 200)]
pub limit: i64,
}
@@ -61,19 +55,7 @@ fn default_search_limit() -> i64 {
50
}
/// A target's code graph: its latest build, nodes and edges.
///
/// Truncated past a size a browser can lay out, and says so.
#[utoipa::path(
get,
path = "/api/v1/graph/{repo_id}",
tag = "Code graph",
params(("repo_id" = String, Path, description = "The target's id")),
responses(
(status = 200, description = "The graph"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/graph/:repo_id — Full graph data
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
pub async fn get_graph(
Extension(agent): AgentExt,
@@ -166,17 +148,7 @@ pub async fn get_graph(
}))
}
/// A target's code graph nodes, a page at a time.
#[utoipa::path(
get,
path = "/api/v1/graph/{repo_id}/nodes",
tag = "Code graph",
params(("repo_id" = String, Path, description = "The target's id"), PaginationParams),
responses(
(status = 200, description = "A page of nodes"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/graph/:repo_id/nodes — List nodes (paginated)
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
pub async fn get_nodes(
Extension(agent): AgentExt,
@@ -216,82 +188,7 @@ pub async fn get_nodes(
}))
}
/// What the target page shows of a code graph.
#[derive(Serialize)]
pub struct GraphSummary {
/// Declarations: functions, methods, types, PLC blocks (nodes that are
/// not files).
pub units: u32,
pub entry_points: u32,
/// Language codes, sorted (`c`, `csharp`, `structured_text`, …).
pub languages: Vec<String>,
/// Source files left out because they could not be read as text; 0 when
/// none were, or the build did not count them.
pub unreadable_files: u32,
}
impl GraphSummary {
/// The summary of a completed build; `None` for one still running, a
/// failed one, or one stored before its files and entry points were
/// counted.
fn of(build: GraphBuildRun) -> Option<Self> {
if build.status != GraphBuildStatus::Completed {
return None;
}
Some(Self {
units: build.node_count.saturating_sub(build.file_count?),
entry_points: build.entry_point_count?,
languages: build.languages_parsed,
// Not `?`: a build from before this count still shows its card.
unreadable_files: build.unreadable_file_count.unwrap_or(0),
})
}
}
/// The counts of a target's latest graph build, without loading any node.
///
/// `data` is `null` when there is none to show.
#[utoipa::path(
get,
path = "/api/v1/graph/{repo_id}/summary",
tag = "Code graph",
params(("repo_id" = String, Path, description = "The target's id")),
responses(
(status = 200, description = "The counts, or null"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
pub async fn get_summary(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(repo_id): Path<String>,
) -> Result<Json<ApiResponse<Option<GraphSummary>>>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let build = db
.graph_builds()
.find_one(doc! { "repo_id": &repo_id })
.sort(doc! { "started_at": -1 })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(ApiResponse {
data: build.and_then(GraphSummary::of),
total: None,
page: None,
}))
}
/// The communities detected in a target's code graph.
#[utoipa::path(
get,
path = "/api/v1/graph/{repo_id}/communities",
tag = "Code graph",
params(("repo_id" = String, Path, description = "The target's id")),
responses(
(status = 200, description = "The communities"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/graph/:repo_id/communities — List detected communities
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
pub async fn get_communities(
Extension(agent): AgentExt,
@@ -359,17 +256,7 @@ pub struct CommunityInfo {
pub members: Vec<String>,
}
/// What a finding reaches in a target's code graph.
#[utoipa::path(
get,
path = "/api/v1/graph/{repo_id}/impact/{finding_id}",
tag = "Code graph",
params(("repo_id" = String, Path, description = "The target's id"), ("finding_id" = String, Path, description = "The finding's id")),
responses(
(status = 200, description = "The impact analysis, or null"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/graph/:repo_id/impact/:finding_id — Impact analysis
#[tracing::instrument(skip_all, fields(repo_id = %repo_id, finding_id = %finding_id))]
pub async fn get_impact(
Extension(agent): AgentExt,
@@ -393,17 +280,7 @@ pub async fn get_impact(
}))
}
/// Search a target's code graph for symbols (BM25).
#[utoipa::path(
get,
path = "/api/v1/graph/{repo_id}/search",
tag = "Code graph",
params(("repo_id" = String, Path, description = "The target's id"), SearchParams),
responses(
(status = 200, description = "The matching nodes"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/graph/:repo_id/search — BM25 symbol search
#[tracing::instrument(skip_all, fields(repo_id = %repo_id, query = %params.q))]
pub async fn search_symbols(
Extension(agent): AgentExt,
@@ -437,19 +314,7 @@ pub async fn search_symbols(
}))
}
/// A source file of a target's checkout.
#[utoipa::path(
get,
path = "/api/v1/graph/{repo_id}/file-content",
tag = "Code graph",
params(("repo_id" = String, Path, description = "The target's id"), FileContentParams),
responses(
(status = 200, description = "The file"),
(status = 403, description = "The path leaves the checkout"),
(status = 404, description = "No such target, checkout or file"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/graph/:repo_id/file-content — Read source file from cloned repo
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
pub async fn get_file_content(
Extension(agent): AgentExt,
@@ -490,9 +355,7 @@ pub async fn get_file_content(
return Err(StatusCode::FORBIDDEN);
}
// Decoded as the graph read it, so a UTF-16 or Windows-1252 file opens.
let content =
compliance_core::encoding::read_source(&canonical).map_err(|_| StatusCode::NOT_FOUND)?;
let content = std::fs::read_to_string(&canonical).map_err(|_| StatusCode::NOT_FOUND)?;
// Cap at 10,000 lines
let truncated: String = content.lines().take(10_000).collect::<Vec<_>>().join("\n");
@@ -510,11 +373,8 @@ pub async fn get_file_content(
}))
}
/// The file of [`get_file_content`].
#[derive(Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
#[derive(Deserialize)]
pub struct FileContentParams {
/// The file's path in the checkout.
pub path: String,
}
@@ -525,17 +385,7 @@ pub struct FileContent {
pub language: String,
}
/// Rebuild a target's code graph in the background.
#[utoipa::path(
post,
path = "/api/v1/graph/{repo_id}/build",
tag = "Code graph",
params(("repo_id" = String, Path, description = "The target's id")),
responses(
(status = 200, description = "The build was started"),
(status = 401, description = "No valid bearer token"),
)
)]
/// POST /api/v1/graph/:repo_id/build — Trigger graph rebuild
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
pub async fn trigger_build(
Extension(agent): AgentExt,
@@ -584,17 +434,10 @@ pub async fn trigger_build(
}
};
// A PLC target's graph is its POUs, as the scan builds it.
let plc_files = crate::pipeline::plan::build_scan_plan(&repo)
.has(compliance_core::models::ScanType::PlcControlLogic)
.then(|| crate::pipeline::plc::read_tree(&repo_path));
let source = match &plc_files {
Some(files) => crate::pipeline::graph_build::GraphSource::Plc(files),
None => crate::pipeline::graph_build::GraphSource::Tree(&repo_path),
};
let graph_build_id = uuid::Uuid::new_v4().to_string();
let engine = compliance_graph::GraphEngine::new(50_000);
match crate::pipeline::graph_build::build_graph(source, &repo_id, &graph_build_id) {
match engine.build_graph(&repo_path, &repo_id, &graph_build_id) {
Ok((code_graph, build_run)) => {
let store = compliance_graph::graph::persistence::GraphStore::new(db.inner());
let _ = store.delete_repo_graph(&repo_id).await;
@@ -617,48 +460,3 @@ pub async fn trigger_build(
serde_json::json!({ "status": "graph_build_triggered" }),
))
}
#[cfg(test)]
mod tests {
use super::*;
fn completed(nodes: u32, files: Option<u32>, entry_points: Option<u32>) -> GraphBuildRun {
let mut build = GraphBuildRun::new("t".to_string());
build.status = GraphBuildStatus::Completed;
build.node_count = nodes;
build.file_count = files;
build.entry_point_count = entry_points;
build.languages_parsed = vec!["c".to_string()];
build
}
#[test]
fn a_completed_build_counts_its_declarations() {
let summary = GraphSummary::of(completed(120, Some(20), Some(7))).expect("shown");
assert_eq!((summary.units, summary.entry_points), (100, 7));
assert_eq!(summary.languages, ["c"]);
}
#[test]
fn running_failed_and_uncounted_builds_show_nothing() {
let mut running = completed(10, Some(2), Some(1));
running.status = GraphBuildStatus::Running;
assert!(GraphSummary::of(running).is_none());
let mut failed = completed(10, Some(2), Some(1));
failed.status = GraphBuildStatus::Failed;
assert!(GraphSummary::of(failed).is_none());
assert!(GraphSummary::of(completed(10, None, None)).is_none());
}
#[test]
fn unreadable_files_are_shown_and_an_uncounted_build_has_none() {
let mut build = completed(10, Some(2), Some(1));
build.unreadable_file_count = Some(3);
assert_eq!(GraphSummary::of(build).expect("shown").unreadable_files, 3);
let uncounted = completed(10, Some(2), Some(1));
assert_eq!(
GraphSummary::of(uncounted).expect("shown").unreadable_files,
0
);
}
}
+4 -9
View File
@@ -57,19 +57,14 @@ fn health_answer(mongo_reachable: bool) -> (axum::http::StatusCode, Json<serde_j
/// positive, not an accepted risk and not ignored.
pub(crate) const OPEN_STATUSES: [&str; 3] = ["open", "triaged", "needs_review"];
/// How many open findings there are of each severity, by severity name;
/// only those matching `scope` (e.g. `{"repo_id": …}`), every one with an
/// empty document.
pub(crate) async fn open_findings_by_severity(
/// How many open findings there are of each severity, by severity name.
async fn open_findings_by_severity(
db: &crate::database::Database,
scope: mongodb::bson::Document,
) -> std::collections::HashMap<String, u64> {
use futures_util::TryStreamExt;
let mut matching = scope;
matching.insert("status", doc! { "$in": OPEN_STATUSES.to_vec() });
let pipeline = vec![
doc! { "$match": matching },
doc! { "$match": { "status": { "$in": OPEN_STATUSES.to_vec() } } },
doc! { "$group": { "_id": "$severity", "n": { "$sum": 1 } } },
];
let rows: Vec<mongodb::bson::Document> = match db.findings().aggregate(pipeline).await {
@@ -121,7 +116,7 @@ pub async fn stats_overview(
.await
.unwrap_or(0)
},
open_findings_by_severity(db, doc! {}),
open_findings_by_severity(db),
);
let severity = |name: &str| by_severity.get(name).copied().unwrap_or(0);
let total_findings = by_severity.values().sum();
+4 -19
View File
@@ -11,21 +11,15 @@ use super::dto::{AgentExt, ApiResponse};
// ── DTOs ─────────────────────────────────────────────────────────────────────
/// An earlier turn of a help chat.
#[derive(Debug, Deserialize, utoipa::ToSchema)]
#[derive(Debug, Deserialize)]
pub struct HelpChatMessage {
/// `user` or `assistant`.
pub role: String,
/// What was said.
pub content: String,
}
/// The body of [`help_chat`].
#[derive(Debug, Deserialize, utoipa::ToSchema)]
#[derive(Debug, Deserialize)]
pub struct HelpChatRequest {
/// The question.
pub message: String,
/// The earlier turns, oldest first.
#[serde(default)]
pub history: Vec<HelpChatMessage>,
}
@@ -176,17 +170,8 @@ fn doc_context() -> &'static str {
// ── Handler ──────────────────────────────────────────────────────────────────
/// Ask about Prüfwerk, answered from its published documentation.
#[utoipa::path(
post,
path = "/api/v1/help/chat",
tag = "Help",
request_body = HelpChatRequest,
responses(
(status = 200, description = "The answer"),
(status = 401, description = "No valid bearer token"),
)
)]
/// POST /api/v1/help/chat — Answer questions about the compliance-scanner
/// using the project documentation as grounding context.
#[tracing::instrument(skip_all)]
pub async fn help_chat(
Extension(agent): AgentExt,
-554
View File
@@ -1,554 +0,0 @@
//! The "Heute" inbox (#950): the workspace's open decisions as cards in four
//! urgency buckets, decisions on a whole card, undo, and putting a card off
//! until a date ("Wiedervorlage").
//!
//! The bucket rules and the cards are [`compliance_core::models::inbox`]'s;
//! this module loads what they are made of and applies decisions through
//! the existing endpoints' code: a finding's status as
//! `PATCH /api/v1/findings/bulk-status` sets it, a CVE alert's VEX statement
//! as `PATCH /api/v1/cves/{id}/vex` does. Writes are role-gated by the org
//! role middleware like every other write.
use std::collections::{BTreeMap, HashMap};
use axum::extract::{Extension, Path, Query};
use axum::http::StatusCode;
use axum::Json;
use chrono::{DateTime, Utc};
use futures_util::StreamExt;
use mongodb::bson::{doc, oid::ObjectId, Bson, Document};
use serde::Deserialize;
use compliance_core::models::inbox::{
alert_undecided, apply_snoozes, cve_cards, finding_cards, view, Bucket, BucketRules, CardKey,
DecideRequest, DecideResponse, InboxAction, InboxCard, InboxFinding, InboxSnooze, InboxView,
OneCardPerFinding, PreviousState, Progress, Reason, SnoozeRequest, SnoozeResponse, UndoRequest,
ViewRequest, DECIDED_STATUSES, DECIDING_VEX, UNDECIDED_STATUSES,
};
use compliance_core::models::{CveAlert, FindingStatus, VexStatus};
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{
collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResult, BulkUpdateStatusRequest,
};
use super::findings::{bulk_update_finding_status, Actor};
use super::vex::{set_cve_vex, VexRequest};
use crate::database::Database;
/// Cards listed when the request names no limit.
const DEFAULT_LIMIT: usize = 100;
/// The most cards one request lists; the counts always cover all.
const MAX_LIMIT: usize = 500;
/// A refusal with its reason, the shape `PATCH /api/v1/cves/{id}/vex` answers
/// with, so the dashboard shows why.
type Refusal = (StatusCode, Json<serde_json::Value>);
fn refuse(code: StatusCode, error: &str) -> Refusal {
(code, Json(serde_json::json!({ "error": error })))
}
/// A database error as a refusal, logged.
fn store_error(e: mongodb::error::Error) -> Refusal {
tracing::warn!("inbox: database error: {e}");
refuse(StatusCode::INTERNAL_SERVER_ERROR, "store")
}
/// The query of [`get_inbox`].
#[derive(Debug, Deserialize)]
pub struct InboxQuery {
/// Only this target's cards, counts and Erstbewertung.
#[serde(default)]
pub target: Option<String>,
/// The bucket whose cards to list (default `today`).
#[serde(default)]
pub bucket: Option<Bucket>,
/// The most cards to list (default 100, at most 500).
#[serde(default)]
pub limit: Option<usize>,
}
/// The bucket rules as configured: the CVE issues' EPSS threshold
/// (`CVE_ISSUE_EPSS_PERCENTILE`, default 0.95), at `now`.
fn rules(now: DateTime<Utc>) -> BucketRules {
BucketRules {
epss_percentile: crate::pipeline::cve_issues::epss_percentile(
std::env::var("CVE_ISSUE_EPSS_PERCENTILE").ok().as_deref(),
),
now,
}
}
/// `values` as a BSON array for an `$in`.
fn bson_list<T: serde::Serialize>(values: &[T]) -> Bson {
mongodb::bson::to_bson(values).unwrap_or_else(|_| Bson::Array(Vec::new()))
}
/// The findings waiting for a decision ([`UNDECIDED_STATUSES`]) matching
/// `filter`, with only the fields the inbox reads.
async fn open_findings(
db: &Database,
mut filter: Document,
) -> Result<Vec<InboxFinding>, mongodb::error::Error> {
filter.insert("status", doc! { "$in": bson_list(&UNDECIDED_STATUSES) });
let projection: Document = InboxFinding::FIELDS
.iter()
.map(|field| ((*field).to_string(), Bson::Int32(1)))
.collect();
let cursor = db
.findings()
.clone_with_type::<InboxFinding>()
.find(filter)
.projection(projection)
.await?;
Ok(collect_cursor_async(cursor).await)
}
/// The CVE alerts waiting for a decision ([`alert_undecided`]) matching
/// `filter`.
async fn open_alerts(
db: &Database,
mut filter: Document,
) -> Result<Vec<CveAlert>, mongodb::error::Error> {
filter.insert("resolved_at", Bson::Null);
filter.insert(
"$or",
vec![
doc! { "vex": Bson::Null },
doc! { "vex.status": VexStatus::UnderInvestigation.as_str() },
],
);
let cursor = db.cve_alerts().find(filter).await?;
let alerts: Vec<CveAlert> = collect_cursor_async(cursor).await;
Ok(alerts.into_iter().filter(alert_undecided).collect())
}
/// The snooze of each card key.
async fn snoozes(db: &Database) -> Result<HashMap<String, InboxSnooze>, mongodb::error::Error> {
let cursor = db.inbox_snoozes().find(doc! {}).await?;
let snoozes: Vec<InboxSnooze> = collect_cursor_async(cursor).await;
Ok(snoozes.into_iter().map(|s| (s.key.clone(), s)).collect())
}
/// The targets' names by id.
async fn target_names(db: &Database) -> Result<HashMap<String, String>, mongodb::error::Error> {
let mut cursor = db
.onboarded_targets()
.clone_with_type::<Document>()
.find(doc! {})
.projection(doc! { "name": 1 })
.await?;
let mut names = HashMap::new();
while let Some(target) = cursor.next().await {
let target = target?;
if let (Ok(id), Ok(name)) = (target.get_object_id("_id"), target.get_str("name")) {
names.insert(id.to_hex(), name.to_string());
}
}
Ok(names)
}
/// The Erstbewertung of `scope` (the workspace, or one target): the open
/// items already loaded, plus the decided ones counted in the database. See
/// [`Progress`] for what counts as decided.
async fn progress(
db: &Database,
target: Option<&str>,
findings: &[InboxFinding],
alerts: &[CveAlert],
) -> Result<Progress, mongodb::error::Error> {
let in_scope = |repo_id: &str| target.is_none_or(|t| t == repo_id);
let scope = || target.map_or_else(Document::new, |t| doc! { "repo_id": t });
let mut decided_findings = scope();
decided_findings.insert("status", doc! { "$in": bson_list(&DECIDED_STATUSES) });
let mut decided_alerts = scope();
decided_alerts.insert("resolved_at", Bson::Null);
decided_alerts.insert("vex.status", doc! { "$in": bson_list(&DECIDING_VEX) });
let decided = db.findings().count_documents(decided_findings).await?
+ db.cve_alerts().count_documents(decided_alerts).await?;
let open = findings.iter().filter(|f| in_scope(&f.repo_id)).count()
+ alerts.iter().filter(|a| in_scope(&a.repo_id)).count();
Ok(Progress {
decided,
total: decided + open as u64,
})
}
/// GET /api/v1/inbox[?target=<id>&bucket=<bucket>&limit=<n>] — the bucket
/// counts, the Erstbewertung, the targets with cards, and the cards of one
/// bucket (default `today`), most urgent first.
///
/// Cards: one per finding, one per target, package and version for CVE
/// alerts. Cards put off until a date are left out until then and come back
/// under `later`.
#[tracing::instrument(skip_all, fields(target = ?query.target, bucket = ?query.bucket))]
pub async fn get_inbox(
Extension(agent): AgentExt,
tenant: TenantCtx,
Query(query): Query<InboxQuery>,
) -> ApiResult<InboxView> {
let db = tenant_db(&agent, &tenant).await?;
let failed = |e: mongodb::error::Error| {
tracing::warn!("inbox: failed to load: {e}");
StatusCode::INTERNAL_SERVER_ERROR
};
let now = Utc::now();
let findings = open_findings(&db, Document::new()).await.map_err(failed)?;
let alerts = open_alerts(&db, Document::new()).await.map_err(failed)?;
let snoozes = snoozes(&db).await.map_err(failed)?;
let names = target_names(&db).await.map_err(failed)?;
let target = query.target.as_deref().filter(|t| !t.is_empty());
let progress = progress(&db, target, &findings, &alerts)
.await
.map_err(failed)?;
let mut cards = finding_cards(&findings, &OneCardPerFinding);
cards.extend(cve_cards(&alerts, &rules(now)));
let request = ViewRequest {
target,
bucket: query.bucket.unwrap_or_default(),
limit: query.limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT),
};
let view = view(
apply_snoozes(cards, &snoozes, now),
&names,
progress,
request,
);
Ok(Json(ApiResponse {
data: view,
total: None,
page: None,
}))
}
/// The card `key` names as it stands now, with what each item is, or why
/// there is none: 400 for a malformed key, 409 when nothing on it waits for
/// a decision any more.
async fn resolve_card(
db: &Database,
key: &str,
) -> Result<(InboxCard, Vec<PreviousState>), Refusal> {
let gone = || {
refuse(
StatusCode::CONFLICT,
"nothing on this card waits for a decision",
)
};
match CardKey::parse(key).ok_or_else(|| refuse(StatusCode::BAD_REQUEST, "bad key"))? {
CardKey::Finding { id } => {
let oid =
ObjectId::parse_str(&id).map_err(|_| refuse(StatusCode::BAD_REQUEST, "bad key"))?;
let findings = open_findings(db, doc! { "_id": oid })
.await
.map_err(store_error)?;
let card = finding_cards(&findings, &OneCardPerFinding)
.into_iter()
.find(|c| c.key == key)
.ok_or_else(gone)?;
let previous = findings
.into_iter()
.map(|f| PreviousState::Finding {
id: f.id.to_hex(),
status: f.status,
})
.collect();
Ok((card, previous))
}
CardKey::CvePackage { target_id } => {
let alerts = open_alerts(db, doc! { "repo_id": &target_id })
.await
.map_err(store_error)?;
let card = cve_cards(&alerts, &rules(Utc::now()))
.into_iter()
.find(|c| c.key == key)
.ok_or_else(gone)?;
let previous = alerts
.into_iter()
.filter_map(|a| {
let id = a.id?.to_hex();
card.item_ids.contains(&id).then(|| PreviousState::Cve {
id,
vex: a.vex.map(|v| v.status),
})
})
.collect();
Ok((card, previous))
}
}
}
/// Set `status` on the findings `ids` the way
/// `PATCH /api/v1/findings/bulk-status` does: recorded in their history with
/// who and why, and their tracker issues closed or reopened.
async fn set_finding_status(
agent: &AgentExt,
tenant: &TenantCtx,
ids: Vec<String>,
status: FindingStatus,
reason: Option<String>,
) -> Result<(), Refusal> {
let request = BulkUpdateStatusRequest {
ids,
status,
reason,
};
bulk_update_finding_status(agent.clone(), tenant.clone(), Json(request))
.await
.map(|_| ())
.map_err(|code| match code {
StatusCode::UNPROCESSABLE_ENTITY => refuse(code, "a reason is required"),
other => refuse(other, "status"),
})
}
/// State `request()` on the alerts `ids` the way `PATCH /api/v1/cves/{id}/vex`
/// does; the first refusal (a missing justification) stops before anything
/// is stored, as every alert gets the same statement.
async fn set_vex(
agent: &AgentExt,
tenant: &TenantCtx,
ids: &[String],
request: impl Fn() -> VexRequest,
) -> Result<(), Refusal> {
for id in ids {
// The answer (the stored statement) is not needed here.
let _stored = set_cve_vex(
agent.clone(),
tenant.clone(),
Path(id.clone()),
Json(request()),
)
.await?;
}
Ok(())
}
/// POST /api/v1/inbox/decide `{key, action, reason?, justification?,
/// statement?}` — apply `action` to every item of card `key`, through the
/// findings' and the VEX endpoints' code, and answer what each item was
/// before (for `POST /api/v1/inbox/undo`). The card's resubmission, if any,
/// is dropped. 409 when nothing on the card waits any more, 422 for an action
/// the card does not offer or without the reason, justification or statement
/// it needs.
#[tracing::instrument(skip_all, fields(key = %req.key, action = ?req.action))]
pub async fn decide(
agent: AgentExt,
tenant: TenantCtx,
Json(req): Json<DecideRequest>,
) -> Result<Json<DecideResponse>, Refusal> {
let db = tenant_db(&agent, &tenant)
.await
.map_err(|code| refuse(code, "tenant"))?;
let (card, previous) = resolve_card(&db, &req.key).await?;
if !card.actions.contains(&req.action) {
return Err(refuse(
StatusCode::UNPROCESSABLE_ENTITY,
"the card does not offer this action",
));
}
let text = |s: &Option<String>| {
s.as_deref()
.map(str::trim)
.filter(|t| !t.is_empty())
.map(String::from)
};
let vex = |status, justification, impact_statement, action_statement| {
move || VexRequest {
status,
justification,
impact_statement: Option::clone(&impact_statement),
action_statement: Option::clone(&action_statement),
}
};
let ids = card.item_ids;
match req.action {
InboxAction::FalsePositive => {
set_finding_status(&agent, &tenant, ids, FindingStatus::FalsePositive, None).await?;
}
InboxAction::AcceptedRisk => {
let reason = text(&req.reason);
set_finding_status(&agent, &tenant, ids, FindingStatus::AcceptedRisk, reason).await?;
}
InboxAction::Confirm => {
set_finding_status(&agent, &tenant, ids, FindingStatus::Triaged, None).await?;
}
InboxAction::NotAffected => {
let statement = vex(
VexStatus::NotAffected,
req.justification,
text(&req.statement),
None,
);
set_vex(&agent, &tenant, &ids, statement).await?;
}
InboxAction::Affected => {
let statement = vex(VexStatus::Affected, None, None, text(&req.statement));
set_vex(&agent, &tenant, &ids, statement).await?;
}
}
db.inbox_snoozes()
.delete_one(doc! { "key": &req.key })
.await
.map_err(store_error)?;
Ok(Json(DecideResponse {
key: req.key,
action: req.action,
previous,
}))
}
/// Whether the items of `previous` are those of card `key`: the finding the
/// key names, or alerts of the key's package version.
async fn belongs_to(db: &Database, key: &str, previous: &[PreviousState]) -> Result<bool, Refusal> {
match CardKey::parse(key).ok_or_else(|| refuse(StatusCode::BAD_REQUEST, "bad key"))? {
CardKey::Finding { id } => Ok(previous
.iter()
.all(|p| matches!(p, PreviousState::Finding { id: item, .. } if *item == id))),
CardKey::CvePackage { .. } => {
let mut oids = Vec::with_capacity(previous.len());
for state in previous {
let PreviousState::Cve { id, .. } = state else {
return Ok(false);
};
oids.push(
ObjectId::parse_str(id)
.map_err(|_| refuse(StatusCode::BAD_REQUEST, "bad id"))?,
);
}
let cursor = db
.cve_alerts()
.find(doc! { "_id": { "$in": &oids } })
.await
.map_err(store_error)?;
let alerts: Vec<CveAlert> = collect_cursor_async(cursor).await;
Ok(alerts.len() == oids.len()
&& alerts.iter().all(|a| {
CardKey::cve_package(&a.repo_id, &a.affected_package, &a.affected_version)
== key
}))
}
}
}
/// POST /api/v1/inbox/undo `{key, previous}` — put the items of a decision
/// on card `key` back, through the same code the decision went through: a
/// finding gets its previous status (a new entry in its history, which keeps
/// the decision on record), an alert `under_investigation` (also when it had
/// no statement before; both leave it open). 422 when an item does not
/// belong to the card or its previous state was not an open one.
#[tracing::instrument(skip_all, fields(key = %req.key))]
pub async fn undo(
agent: AgentExt,
tenant: TenantCtx,
Json(req): Json<UndoRequest>,
) -> Result<Json<serde_json::Value>, Refusal> {
let db = tenant_db(&agent, &tenant)
.await
.map_err(|code| refuse(code, "tenant"))?;
if req.previous.is_empty() || !belongs_to(&db, &req.key, &req.previous).await? {
return Err(refuse(
StatusCode::UNPROCESSABLE_ENTITY,
"the items do not belong to the card",
));
}
let mut by_status: BTreeMap<FindingStatus, Vec<String>> = BTreeMap::new();
let mut alerts = Vec::new();
for state in req.previous {
match state {
PreviousState::Finding { id, status } if UNDECIDED_STATUSES.contains(&status) => {
by_status.entry(status).or_default().push(id);
}
PreviousState::Cve {
id,
vex: None | Some(VexStatus::UnderInvestigation),
} => {
alerts.push(id);
}
PreviousState::Finding { .. } | PreviousState::Cve { .. } => {
return Err(refuse(
StatusCode::UNPROCESSABLE_ENTITY,
"only an open state can be restored",
));
}
}
}
for (status, ids) in by_status {
set_finding_status(&agent, &tenant, ids, status, None).await?;
}
set_vex(&agent, &tenant, &alerts, || VexRequest {
status: VexStatus::UnderInvestigation,
justification: None,
impact_statement: None,
action_statement: None,
})
.await?;
Ok(Json(serde_json::json!({ "status": "restored" })))
}
/// POST /api/v1/inbox/snooze `{key, for}` — put card `key` off: one week, one
/// month, or until a date (`{"kind": "date", "date": "2026-12-01"}`). It is
/// hidden until then and comes back in its own bucket, or earlier when a new
/// CVE or a KEV entry joins it: the snooze records the card's items and
/// whether it was KEV. A second snooze replaces the first. 400 for a
/// malformed key, 409 when nothing on the card waits for a decision, 422 for
/// a date that is not in the future.
#[tracing::instrument(skip_all, fields(key = %req.key))]
pub async fn snooze(
Extension(agent): AgentExt,
tenant: TenantCtx,
Json(req): Json<SnoozeRequest>,
) -> Result<Json<SnoozeResponse>, Refusal> {
if CardKey::parse(&req.key).is_none() {
return Err(refuse(StatusCode::BAD_REQUEST, "bad key"));
}
let now = Utc::now();
let until = req
.snooze_for
.until(now)
.map_err(|e| refuse(StatusCode::UNPROCESSABLE_ENTITY, &e.to_string()))?;
let db = tenant_db(&agent, &tenant)
.await
.map_err(|code| refuse(code, "tenant"))?;
let (card, _) = resolve_card(&db, &req.key).await?;
let actor = Actor::of(&tenant.0);
let record = InboxSnooze {
key: req.key.clone(),
until,
by: actor.id.to_string(),
by_name: actor.name,
at: now,
kev: card.reasons.contains(&Reason::Kev),
items: card.item_ids,
};
db.inbox_snoozes()
.replace_one(doc! { "key": &req.key }, &record)
.upsert(true)
.await
.map_err(store_error)?;
Ok(Json(SnoozeResponse {
key: req.key,
until,
}))
}
/// DELETE /api/v1/inbox/snooze/{key} — take card `key`'s resubmission back
/// (the undo of a snooze); nothing to take back is no error.
#[tracing::instrument(skip_all, fields(key = %key))]
pub async fn unsnooze(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(key): Path<String>,
) -> Result<Json<serde_json::Value>, Refusal> {
if CardKey::parse(&key).is_none() {
return Err(refuse(StatusCode::BAD_REQUEST, "bad key"));
}
let db = tenant_db(&agent, &tenant)
.await
.map_err(|code| refuse(code, "tenant"))?;
db.inbox_snoozes()
.delete_one(doc! { "key": &key })
.await
.map_err(store_error)?;
Ok(Json(serde_json::json!({ "status": "deleted" })))
}
+8 -210
View File
@@ -1,42 +1,32 @@
use axum::extract::{Extension, Query};
use axum::Json;
use mongodb::bson::{doc, Bson, Document};
use mongodb::bson::doc;
use super::dto::*;
use compliance_core::models::issue::cve_issue_prefix;
use compliance_core::models::TrackerIssue;
use compliance_core::tenant_ctx::TenantCtx;
/// The tenant's tickets, newest first, searched and filtered by `filter`.
///
/// A ticket stores no target, only the finding it is about: the target filter
/// first looks up the ids of the target's findings that have a ticket.
#[tracing::instrument(skip_all, fields(repo_id = ?filter.repo_id, status = ?filter.status))]
#[tracing::instrument(skip_all)]
pub async fn list_issues(
Extension(agent): AgentExt,
tenant: TenantCtx,
Query(filter): Query<IssuesFilter>,
Query(params): Query<PaginationParams>,
) -> ApiResult<Vec<TrackerIssue>> {
let db = tenant_db(&agent, &tenant).await?;
let db = &db;
let finding_ids = match filter.target() {
Some(repo_id) => Some(ticketed_finding_ids(db, repo_id).await),
None => None,
};
let query = issues_query(&filter, finding_ids.as_deref());
let skip = filter.skip();
let skip = params.skip();
let total = db
.tracker_issues()
.count_documents(query.clone())
.count_documents(doc! {})
.await
.unwrap_or(0);
let issues = match db
.tracker_issues()
.find(query)
.find(doc! {})
.sort(doc! { "created_at": -1 })
.skip(skip)
.limit(filter.limit)
.limit(params.limit)
.await
{
Ok(cursor) => collect_cursor_async(cursor).await,
@@ -49,198 +39,6 @@ pub async fn list_issues(
Ok(Json(ApiResponse {
data: issues,
total: Some(total),
page: Some(filter.page),
page: Some(params.page),
}))
}
/// The ids (hex) of the findings of target `repo_id` that have a ticket.
///
/// Storing a finding's ticket sets the finding's `tracker_issue_url`
/// (`pipeline::issue_creation`), so the other findings are left out. A failed
/// lookup is logged and leaves only the target's CVE tickets.
async fn ticketed_finding_ids(db: &crate::database::Database, repo_id: &str) -> Vec<String> {
let filter = doc! { "repo_id": repo_id, "tracker_issue_url": { "$ne": Bson::Null } };
match db.findings().distinct("_id", filter).await {
Ok(ids) => ids
.iter()
.filter_map(Bson::as_object_id)
.map(|id| id.to_hex())
.collect(),
Err(e) => {
tracing::warn!("Failed to look up the target's findings: {e}");
Vec::new()
}
}
}
/// The Mongo filter of the tickets list.
///
/// # Arguments
///
/// * `filter` - the caller's search and filters
/// * `finding_ids` - for a target filter, the ids of the target's findings
/// with a ticket ([`ticketed_finding_ids`]); `None` without one
///
/// # Returns
///
/// `{}` for no filter, else an `$and` of the search (title or ticket number),
/// the status and the target.
fn issues_query(filter: &IssuesFilter, finding_ids: Option<&[String]>) -> Document {
let mut clauses: Vec<Document> = Vec::with_capacity(3);
if let Some(term) = filter.search() {
let mut either = vec![doc! { "title": { "$regex": literal_regex(term), "$options": "i" } }];
// `#913` is ticket 913; `913` also finds the Jira key `PROJ-913`.
let number = term.strip_prefix('#').unwrap_or(term).trim();
if !number.is_empty() {
let exact = format!("(^|-){}$", literal_regex(number));
either.push(doc! { "external_id": { "$regex": exact, "$options": "i" } });
}
clauses.push(doc! { "$or": either });
}
if let Some(state) = filter.status {
clauses.push(doc! { "status": { "$in": state.statuses() } });
}
if let (Some(repo_id), Some(ids)) = (filter.target(), finding_ids) {
// A CVE ticket names its target in its key instead of a finding.
let cve = format!("^{}", literal_regex(&cve_issue_prefix(repo_id)));
clauses.push(doc! { "$or": [
{ "finding_id": { "$in": ids } },
{ "finding_id": { "$regex": cve } },
] });
}
if clauses.is_empty() {
Document::new()
} else {
doc! { "$and": clauses }
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
fn filter(json: &str) -> IssuesFilter {
serde_json::from_str(json).unwrap()
}
/// The clauses of the `$and`, by position.
fn clauses(query: &Document) -> Vec<Document> {
query
.get_array("$and")
.unwrap()
.iter()
.map(|c| c.as_document().unwrap().clone())
.collect()
}
/// The external-id regex a search for `term` uses.
fn number_regex(term: &str) -> String {
let query = issues_query(&filter(&format!(r#"{{"q":{term:?}}}"#)), None);
let either = clauses(&query)[0].get_array("$or").unwrap().clone();
let external = either[1].as_document().unwrap();
external
.get_document("external_id")
.unwrap()
.get_str("$regex")
.unwrap()
.to_string()
}
#[test]
fn no_filter_lists_everything() {
assert_eq!(issues_query(&filter("{}"), None), Document::new());
assert_eq!(
issues_query(&filter(r#"{"q":" ","repo_id":""}"#), None),
Document::new()
);
}
#[test]
fn a_number_with_or_without_hash_finds_the_ticket() {
assert_eq!(number_regex("913"), "(^|-)913$");
assert_eq!(number_regex("#913"), "(^|-)913$");
let re = regex::RegexBuilder::new(&number_regex("#913"))
.case_insensitive(true)
.build()
.unwrap();
assert!(re.is_match("913"));
assert!(re.is_match("PROJ-913"));
assert!(!re.is_match("1913"));
assert!(!re.is_match("9130"));
}
#[test]
fn the_search_is_a_literal_title_substring() {
let query = issues_query(&filter(r#"{"q":"(a+)+$"}"#), None);
let either = clauses(&query)[0].get_array("$or").unwrap().clone();
let title = either[0]
.as_document()
.unwrap()
.get_document("title")
.unwrap();
assert_eq!(title.get_str("$regex").unwrap(), r"\(a\+\)\+\$");
assert_eq!(title.get_str("$options").unwrap(), "i");
}
#[test]
fn a_lone_hash_searches_the_title_only() {
let query = issues_query(&filter(r##"{"q":"#"}"##), None);
assert_eq!(clauses(&query)[0].get_array("$or").unwrap().len(), 1);
}
#[test]
fn the_status_filter_takes_both_stored_statuses() {
let query = issues_query(&filter(r#"{"status":"open"}"#), None);
assert_eq!(
clauses(&query)[0],
doc! { "status": { "$in": ["open", "in_progress"] } }
);
}
#[test]
fn the_target_filter_takes_its_findings_and_its_cves() {
let ids = vec!["65a1b2c3d4e5f60718293a4b".to_string()];
let query = issues_query(&filter(r#"{"repo_id":"t1"}"#), Some(&ids));
assert_eq!(
clauses(&query)[0],
doc! { "$or": [
{ "finding_id": { "$in": ["65a1b2c3d4e5f60718293a4b"] } },
{ "finding_id": { "$regex": "^cve:t1:" } },
] }
);
}
#[test]
fn a_target_without_ticketed_findings_still_has_its_cves() {
let query = issues_query(&filter(r#"{"repo_id":"t.1"}"#), Some(&[]));
let either = clauses(&query)[0].get_array("$or").unwrap().clone();
let cve = either[1]
.as_document()
.unwrap()
.get_document("finding_id")
.unwrap();
// The id is matched literally.
assert_eq!(cve.get_str("$regex").unwrap(), r"^cve:t\.1:");
}
#[test]
fn search_status_and_target_all_apply() {
// Search and target are both an `$or`: neither may replace the other.
let query = issues_query(
&filter(r#"{"q":"913","status":"closed","repo_id":"t1"}"#),
Some(&[]),
);
let all = clauses(&query);
assert_eq!(all.len(), 3);
assert!(all[0].get_array("$or").unwrap()[0]
.as_document()
.unwrap()
.contains_key("title"));
assert!(all[1].contains_key("status"));
assert!(all[2].get_array("$or").unwrap()[0]
.as_document()
.unwrap()
.contains_key("finding_id"));
}
}
+19 -153
View File
@@ -35,16 +35,12 @@ use crate::license_conclusions::MAX_CONCLUSIONS;
pub const MAX_COMPONENTS: usize = 500;
/// A component a licence is confirmed for, as the SBOM list shows it.
#[derive(Debug, Clone, Deserialize, utoipa::ToSchema)]
#[derive(Debug, Clone, Deserialize)]
pub struct ComponentRef {
/// The package's name.
pub name: String,
/// Its package manager, such as `npm` or `cargo`.
pub package_manager: String,
/// Its version; empty with `all_versions`.
#[serde(default)]
pub version: String,
/// Its purl, when known.
#[serde(default)]
pub purl: Option<String>,
/// The licence the scan found, as the list shows it. Read only by a
@@ -54,9 +50,8 @@ pub struct ComponentRef {
}
/// The body of [`conclude`].
#[derive(Debug, Deserialize, utoipa::ToSchema)]
#[derive(Debug, Deserialize)]
pub struct ConcludeRequest {
/// The components, at most 500.
pub components: Vec<ComponentRef>,
/// For every version of the packages, not just the listed ones.
#[serde(default)]
@@ -65,38 +60,25 @@ pub struct ConcludeRequest {
/// licence of its own, named in `license_name`.
#[serde(default)]
pub license: Option<String>,
/// The name of a licence of its own.
#[serde(default)]
pub license_name: Option<String>,
/// Used for a licence of its own and where SPDX gives no category, such
/// as `permissive`, `weak_copyleft` or `proprietary`.
/// Used for a licence of its own and where SPDX gives no category.
#[serde(default)]
#[schema(value_type = Option<String>, example = "proprietary")]
pub category: Option<LicenseCategory>,
/// The copyright lines.
#[serde(default)]
pub copyright: Vec<String>,
/// The licence's text.
#[serde(default)]
pub license_text: Option<String>,
/// Where the licence is published.
#[serde(default)]
pub license_url: Option<String>,
/// Where the licence was confirmed, such as a file or a contract.
#[serde(default)]
pub evidence: Option<String>,
/// The contract a licence of its own comes from.
#[serde(default)]
pub contract_ref: Option<String>,
/// When the licence ends.
#[serde(default)]
#[schema(value_type = Option<String>, format = Date)]
pub valid_until: Option<NaiveDate>,
/// `shipped` or `build_only`.
#[serde(default)]
#[schema(value_type = Option<String>, example = "shipped")]
pub usage: Option<LicenseUsage>,
/// A note.
#[serde(default)]
pub note: Option<String>,
}
@@ -214,16 +196,8 @@ fn conclusions_of(
Ok(out)
}
/// Every licence the workspace confirmed, by package name.
#[utoipa::path(
get,
path = "/api/v1/licenses/conclusions",
tag = "Licences",
responses(
(status = 200, description = "The confirmed licences"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/licenses/conclusions — every licence the workspace
/// confirmed, by package name.
#[tracing::instrument(skip_all)]
pub async fn list_conclusions(
Extension(agent): AgentExt,
@@ -238,22 +212,10 @@ pub async fn list_conclusions(
}))
}
/// Confirm a licence for one or more components.
///
/// One version, or every version of their packages. A second confirmation
/// of the same package and version replaces the first. 422 with the reason
/// when the licence or a field is not acceptable.
#[utoipa::path(
put,
path = "/api/v1/licenses/conclusions",
tag = "Licences",
request_body = ConcludeRequest,
responses(
(status = 200, description = "The licence was confirmed"),
(status = 422, description = "The licence or a field is not acceptable; `error` says why"),
(status = 401, description = "No valid bearer token"),
)
)]
/// PUT /api/v1/licenses/conclusions — confirm a licence for one or more
/// components (one version, or every version of their packages). A second
/// confirmation of the same package and version replaces the first. 422
/// with the reason when the licence or a field is not acceptable.
#[tracing::instrument(skip_all)]
pub async fn conclude(
Extension(agent): AgentExt,
@@ -299,26 +261,15 @@ pub async fn conclude(
}
/// The query of [`withdraw`].
#[derive(Debug, Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
#[derive(Debug, Deserialize)]
pub struct WithdrawQuery {
/// The conclusion's id (package and version, see
/// [`license::conclusion_id`]); a query value, as it holds `/` and `@`.
pub id: String,
}
/// Withdraw a confirmed licence; the component shows the detected one again.
#[utoipa::path(
delete,
path = "/api/v1/licenses/conclusions",
tag = "Licences",
params(WithdrawQuery),
responses(
(status = 200, description = "The licence was withdrawn"),
(status = 404, description = "No such confirmed licence"),
(status = 401, description = "No valid bearer token"),
)
)]
/// DELETE /api/v1/licenses/conclusions?id= — withdraw a confirmed licence;
/// the component shows the detected one again. 404 when there is none.
#[tracing::instrument(skip_all)]
pub async fn withdraw(
Extension(agent): AgentExt,
@@ -341,12 +292,12 @@ pub async fn withdraw(
}
/// Whether the requester may change the policy and decide reviews: LEGAL,
/// an administrator (IT_ADMIN, OWNER), or BreakPilot support. USER confirms licences but does not
/// IT_ADMIN, or BreakPilot support. USER confirms licences but does not
/// decide whether they may be used.
fn may_decide(tenant: &TenantCtx) -> bool {
let ctx = &tenant.0;
ctx.api_key.is_none()
&& (ctx.staff.is_some() || ctx.is_admin() || ctx.has_any_role(&[OrgRole::Legal]))
&& (ctx.staff.is_some() || ctx.has_any_role(&[OrgRole::Legal, OrgRole::ItAdmin]))
}
fn refuse_role() -> Refusal {
@@ -355,21 +306,11 @@ fn refuse_role() -> Refusal {
Json(serde_json::json!({
"error": crate::api::role_gate::FORBIDDEN_ROLE,
"access": "read_only",
"needs": ["LEGAL", "IT_ADMIN", "OWNER"],
"needs": ["LEGAL", "IT_ADMIN"],
})),
)
}
/// The workspace's licence policy, and whether the requester may change it.
#[utoipa::path(
get,
path = "/api/v1/licenses/policy",
tag = "Licences",
responses(
(status = 200, description = "The policy"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all)]
pub async fn get_policy(
Extension(agent): AgentExt,
@@ -383,19 +324,6 @@ pub async fn get_policy(
})))
}
/// Replace the workspace's licence policy.
#[utoipa::path(
put,
path = "/api/v1/licenses/policy",
tag = "Licences",
request_body(content = Object, description = "The policy: which licences are allowed, need a review or are forbidden"),
responses(
(status = 200, description = "The policy was saved"),
(status = 403, description = "The role may not decide on licences (LEGAL, IT_ADMIN or OWNER)"),
(status = 422, description = "The policy is not acceptable; `error` says why"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all)]
pub async fn put_policy(
Extension(agent): AgentExt,
@@ -509,11 +437,9 @@ fn decidable(entry: &SbomEntry) -> bool {
.is_some_and(|l| spdx_license::is_spdx_expression(&spdx_license::normalise(l)))
}
/// The query of [`check`].
#[derive(Debug, Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
/// The query of [`check`] and [`notices`].
#[derive(Debug, Deserialize)]
pub struct CheckQuery {
/// Only one target's components; every target's without.
#[serde(default)]
pub repo_id: Option<String>,
}
@@ -521,20 +447,6 @@ pub struct CheckQuery {
/// The most open components one check lists.
pub const MAX_CHECK_ITEMS: usize = 2_000;
/// Judge the components against the licence policy.
///
/// The counts per verdict, and the components that are forbidden, need a
/// review or expire soon, at most 2 000.
#[utoipa::path(
get,
path = "/api/v1/licenses/check",
tag = "Licences",
params(CheckQuery),
responses(
(status = 200, description = "The verdicts"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all)]
pub async fn check(
Extension(agent): AgentExt,
@@ -610,17 +522,13 @@ pub async fn check(
}
/// The body of [`review`].
#[derive(Debug, Deserialize, utoipa::ToSchema)]
#[derive(Debug, Deserialize)]
pub struct ReviewRequest {
/// The components.
pub components: Vec<ComponentRef>,
/// For every version of the packages, not just the listed ones.
#[serde(default)]
pub all_versions: bool,
/// `approved` or `rejected`.
#[schema(value_type = String, example = "approved")]
pub decision: ReviewDecision,
/// Why.
#[serde(default)]
pub note: Option<String>,
}
@@ -731,19 +639,6 @@ fn reviewed(
Ok(out)
}
/// Decide in a legal review whether the components' licences may be used.
#[utoipa::path(
post,
path = "/api/v1/licenses/review",
tag = "Licences",
request_body = ReviewRequest,
responses(
(status = 200, description = "The review was saved"),
(status = 403, description = "The role may not decide on licences (LEGAL, IT_ADMIN or OWNER)"),
(status = 422, description = "A component without a licence to review; `error` says why"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all)]
pub async fn review(
Extension(agent): AgentExt,
@@ -792,19 +687,6 @@ pub async fn review(
})))
}
/// Withdraw a legal review.
#[utoipa::path(
delete,
path = "/api/v1/licenses/review",
tag = "Licences",
params(WithdrawQuery),
responses(
(status = 200, description = "The review was withdrawn"),
(status = 403, description = "The role may not decide on licences (LEGAL, IT_ADMIN or OWNER)"),
(status = 404, description = "No such review"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all)]
pub async fn withdraw_review(
Extension(agent): AgentExt,
@@ -833,31 +715,16 @@ pub async fn withdraw_review(
}
/// The query of [`notices`].
#[derive(Debug, Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
#[derive(Debug, Deserialize)]
pub struct NoticesQuery {
/// The target (its id).
pub repo_id: String,
/// `text` (default) or `markdown`.
#[serde(default)]
#[param(value_type = Option<String>, example = "markdown")]
pub format: NoticeFormat,
/// Also list components only used to build.
#[serde(default)]
pub build_only: bool,
}
/// A target's third-party notices to ship with the product.
#[utoipa::path(
get,
path = "/api/v1/sbom/notices",
tag = "Licences",
params(NoticesQuery),
responses(
(status = 200, description = "The notices file"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all)]
pub async fn notices(
Extension(agent): AgentExt,
@@ -1045,7 +912,6 @@ mod tests {
fn legal_and_it_admin_decide_users_do_not() {
assert!(may_decide(&with_roles(vec![OrgRole::Legal])));
assert!(may_decide(&with_roles(vec![OrgRole::ItAdmin])));
assert!(may_decide(&with_roles(vec![OrgRole::Owner])));
assert!(!may_decide(&with_roles(vec![OrgRole::User])));
assert!(!may_decide(&with_roles(vec![OrgRole::Cxo])));
}
@@ -4,7 +4,7 @@
//!
//! Writing findings into a tenant's record is an administrator's action: the
//! tester is given an account in the customer's organisation with the
//! `IT_ADMIN` (or `OWNER`) role.
//! `IT_ADMIN` role.
use std::sync::Arc;
@@ -16,6 +16,7 @@ use mongodb::bson::{doc, oid::ObjectId};
use serde::{Deserialize, Serialize};
use compliance_core::models::{Finding, ScanType};
use compliance_core::tenant::OrgRole;
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::tenant_db;
@@ -83,10 +84,9 @@ pub struct ImportSummary {
pub duplicates: usize,
}
/// Only an organisation's administrator (IT_ADMIN, OWNER) writes findings by
/// hand.
/// Only an organisation's IT administrator writes findings by hand.
fn require_admin(tenant: &TenantCtx) -> Result<(), StatusCode> {
if tenant.0.is_admin() {
if tenant.0.org_roles.contains(&OrgRole::ItAdmin) {
Ok(())
} else {
Err(StatusCode::FORBIDDEN)
@@ -221,7 +221,7 @@ pub async fn import_findings(
#[cfg(test)]
mod tests {
use super::*;
use compliance_core::tenant::{OrgRole, TenantContext, TenantStatus};
use compliance_core::tenant::{TenantContext, TenantStatus};
fn tenant(roles: Vec<OrgRole>) -> TenantCtx {
TenantCtx(TenantContext {
@@ -241,7 +241,6 @@ mod tests {
#[test]
fn only_an_it_admin_writes_findings() {
assert_eq!(require_admin(&tenant(vec![OrgRole::ItAdmin])), Ok(()));
assert_eq!(require_admin(&tenant(vec![OrgRole::Owner])), Ok(()));
assert_eq!(
require_admin(&tenant(vec![OrgRole::User, OrgRole::Cxo])),
Err(StatusCode::FORBIDDEN)
@@ -1,54 +0,0 @@
//! The tenant's metering this month, for the dashboard's usage view (t72).
use axum::extract::Extension;
use axum::http::StatusCode;
use axum::Json;
use serde::Serialize;
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{tenant_db, AgentExt};
use crate::metering::{month_summary, MonthSummary};
/// The usage view: what was used this month, and what the plan allows.
#[derive(Debug, Serialize)]
struct UsageView {
/// What was used.
#[serde(flatten)]
used: MonthSummary,
/// Whether the plan could be read; without it the limits are unknown,
/// not unlimited.
plan_known: bool,
/// The plan's included targets; `None` is unlimited.
included_targets: Option<u32>,
/// The monthly quota; `None` is unlimited.
monthly_pruefungen: Option<u32>,
/// The customer's Prüftag cap; `None` is no cap.
prueftag_cap: Option<u32>,
}
/// GET /api/v1/metering/usage — the tenant's Prüfungen, Prüftage and extra
/// targets this month (Europe/Berlin), with the plan's limits.
///
/// # Errors
///
/// `500` when the counters cannot be read.
pub async fn get_usage(
Extension(agent): AgentExt,
tenant: TenantCtx,
) -> Result<Json<serde_json::Value>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let used = month_summary(&db, chrono::Utc::now()).await.map_err(|e| {
tracing::error!(tenant_id = %tenant.0.tenant_id, "usage not read: {e}");
StatusCode::INTERNAL_SERVER_ERROR
})?;
let plan = agent.plan(&tenant.0.tenant_id).await;
let view = UsageView {
used,
plan_known: plan.is_some(),
included_targets: plan.and_then(|p| p.included_targets),
monthly_pruefungen: plan.and_then(|p| p.limits.monthly_pruefungen),
prueftag_cap: plan.and_then(|p| p.limits.prueftag_cap),
};
Ok(Json(serde_json::json!({ "data": view })))
}
-8
View File
@@ -1,25 +1,19 @@
pub mod admin;
pub mod chat;
pub mod cve_history;
pub mod cve_matrix;
pub mod dast;
pub mod demo_seed;
pub mod dto;
pub mod evidence;
pub mod finding_breakdown;
pub mod finding_groups;
pub mod findings;
pub mod git_source;
pub mod graph;
pub mod health;
pub mod help_chat;
pub mod inbox;
pub mod issues;
pub mod licenses;
pub mod manual_findings;
pub mod mcp_servers;
pub mod mcp_tokens;
pub mod metering;
pub mod notifications;
pub mod onboarding;
pub mod oscal;
@@ -28,8 +22,6 @@ pub mod platform;
pub mod projects;
pub use pentest_handlers as pentest;
pub mod sbom;
pub mod sbom_ecosystems;
pub mod scan_changes;
pub mod scans;
pub mod support;
pub mod target_input;
+26 -306
View File
@@ -29,36 +29,23 @@ use super::{collect_cursor_async, ApiResponse, PaginationParams};
type AgentExt = Extension<Arc<ComplianceAgent>>;
/// The body of [`create_target`].
#[derive(Deserialize, utoipa::ToSchema)]
#[derive(Deserialize)]
pub struct CreateTargetRequest {
/// The target's name.
pub name: String,
/// What the target is, such as `web_app`, `backend_service` or `plc_project`.
#[schema(value_type = String, example = "web_app")]
pub target_type: TargetType,
/// A free-text description.
#[serde(default)]
pub description: Option<String>,
/// The target's artifacts by reference; files are uploaded afterwards.
#[serde(default)]
pub artifacts: Vec<ArtifactInput>,
}
/// The body of [`update_target`]. A field left out keeps its stored value.
#[derive(Deserialize, utoipa::ToSchema)]
#[derive(Deserialize)]
pub struct UpdateTargetRequest {
/// The target's name.
pub name: Option<String>,
/// What the target is.
#[schema(value_type = Option<String>, example = "web_app")]
pub target_type: Option<TargetType>,
/// Fields left out keep their stored values.
pub scan_config: Option<ScanConfigUpdate>,
/// The frameworks and jurisdiction the target is checked against.
#[schema(value_type = Option<Object>)]
pub compliance_profile: Option<ComplianceProfile>,
/// When the target is scanned on its own, a cron expression.
pub scan_schedule: Option<String>,
/// The tenant's projects this target belongs to; replaces the stored
/// list. Each must be one of the tenant's projects in the registry.
@@ -89,17 +76,8 @@ fn parse_oid(id: &str) -> Result<ObjectId, StatusCode> {
ObjectId::parse_str(id).map_err(|_| StatusCode::BAD_REQUEST)
}
/// List the tenant's targets a page at a time, each with its newest scan run.
#[utoipa::path(
get,
path = "/api/v1/targets",
tag = "Targets",
params(PaginationParams, TargetFilter),
responses(
(status = 200, description = "A page of targets"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/targets — list onboarded targets (paginated), each with its
/// newest scan run.
#[tracing::instrument(skip_all)]
pub async fn list_targets(
Extension(agent): AgentExt,
@@ -136,7 +114,7 @@ pub async fn list_targets(
// `join!` borrows its futures' arguments, so the collections need names.
let (runs, findings) = (db.scan_runs(), db.findings());
let (mut last_scans, counts) = tokio::join!(
latest_scan_runs(&runs, ids.clone(), true),
latest_scan_runs(&runs, ids.clone()),
findings_counts(&findings, ids),
);
let data = targets
@@ -172,8 +150,7 @@ pub struct TargetListItem {
}
/// Which targets a list shows (`?project=<id>`).
#[derive(Debug, Default, serde::Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
#[derive(Debug, Default, serde::Deserialize)]
pub struct TargetFilter {
/// Only the targets that belong to this project.
#[serde(default)]
@@ -202,13 +179,10 @@ impl TargetFilter {
}
}
/// The newest scan run of each target in `target_ids`, in one query; with
/// `with_queued`, also a run still waiting for a slot (t84), which the
/// dashboard shows but which has scanned nothing yet.
/// The newest scan run of each target in `target_ids`, in one query.
pub(crate) async fn latest_scan_runs(
runs: &mongodb::Collection<ScanRun>,
target_ids: Vec<String>,
with_queued: bool,
) -> HashMap<String, ScanRun> {
use futures_util::StreamExt;
@@ -216,12 +190,8 @@ pub(crate) async fn latest_scan_runs(
return HashMap::new();
}
// Runs store their target's id as `repo_id`.
let mut matching = doc! { "repo_id": { "$in": target_ids } };
if !with_queued {
matching.insert("status", doc! { "$ne": "queued" });
}
let pipeline = vec![
doc! { "$match": matching },
doc! { "$match": { "repo_id": { "$in": target_ids } } },
doc! { "$sort": { "started_at": -1 } },
doc! { "$group": { "_id": "$repo_id", "run": { "$first": "$$ROOT" } } },
];
@@ -283,19 +253,7 @@ async fn findings_counts(
}
}
/// Create a target.
#[utoipa::path(
post,
path = "/api/v1/targets",
tag = "Targets",
request_body = CreateTargetRequest,
responses(
(status = 200, description = "The new target"),
(status = 422, description = "A malformed body"),
(status = 503, description = "A credential cannot be sealed"),
(status = 401, description = "No valid bearer token"),
)
)]
/// POST /api/v1/targets — create an onboarded target.
#[tracing::instrument(skip_all)]
pub async fn create_target(
Extension(agent): AgentExt,
@@ -330,19 +288,7 @@ pub async fn create_target(
}))
}
/// One target, credentials redacted.
#[utoipa::path(
get,
path = "/api/v1/targets/{id}",
tag = "Targets",
params(("id" = String, Path, description = "The target's id")),
responses(
(status = 200, description = "The target"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such target"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/targets/{id} — fetch one target.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn get_target(
Extension(agent): AgentExt,
@@ -364,22 +310,9 @@ pub async fn get_target(
}))
}
/// The target's newest webhook deliveries.
///
/// Refused and failed ones included; for a managed target also those of its
/// repository from before the target existed.
#[utoipa::path(
get,
path = "/api/v1/targets/{id}/webhook-deliveries",
tag = "Targets",
params(("id" = String, Path, description = "The target's id")),
responses(
(status = 200, description = "The newest deliveries"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such target"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/targets/{id}/webhook-deliveries — the target's newest
/// webhook deliveries, refused and failed ones included; for a managed
/// target also those of its repository from before the target existed.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn list_webhook_deliveries(
Extension(agent): AgentExt,
@@ -413,22 +346,7 @@ pub async fn list_webhook_deliveries(
}))
}
/// Change a target; a field left out keeps its stored value.
#[utoipa::path(
patch,
path = "/api/v1/targets/{id}",
tag = "Targets",
params(("id" = String, Path, description = "The target's id")),
request_body = UpdateTargetRequest,
responses(
(status = 200, description = "The changed target"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such target"),
(status = 422, description = "A malformed body, or a project that is not the tenant's"),
(status = 503, description = "A credential cannot be sealed"),
(status = 401, description = "No valid bearer token"),
)
)]
/// PATCH /api/v1/targets/{id} — update mutable fields.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn update_target(
Extension(agent): AgentExt,
@@ -548,18 +466,8 @@ async fn remove_target_files(agent: &ComplianceAgent, tenant_id: &str, target: &
tracing::info!(removed = removal.removed, "target files removed");
}
/// Delete a target with its findings, scans and files on disk.
#[utoipa::path(
delete,
path = "/api/v1/targets/{id}",
tag = "Targets",
params(("id" = String, Path, description = "The target's id")),
responses(
(status = 200, description = "The target was deleted"),
(status = 400, description = "Not an id"),
(status = 401, description = "No valid bearer token"),
)
)]
/// DELETE /api/v1/targets/{id} — remove the target, its findings/scans and
/// its files on disk.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn delete_target(
Extension(agent): AgentExt,
@@ -684,21 +592,7 @@ async fn delete_session_data(db: &crate::database::Database, session_id: &str) {
.await;
}
/// Attach an artifact to a target by reference.
#[utoipa::path(
post,
path = "/api/v1/targets/{id}/artifacts",
tag = "Targets",
params(("id" = String, Path, description = "The target's id")),
request_body = ArtifactInput,
responses(
(status = 200, description = "The target with the artifact"),
(status = 400, description = "Not an id"),
(status = 422, description = "A malformed body"),
(status = 503, description = "A credential cannot be sealed"),
(status = 401, description = "No valid bearer token"),
)
)]
/// 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,
@@ -723,26 +617,8 @@ pub async fn add_artifact(
get_target(Extension(agent), tenant, Path(id)).await
}
/// The multipart form of an artifact upload.
// Only the API description reads it: the handler takes the fields as they
// stream in, so the struct is never built.
#[derive(utoipa::ToSchema)]
#[allow(dead_code)]
pub struct UploadArtifactForm {
/// The file, exactly one.
#[schema(value_type = String, format = Binary)]
file: Vec<u8>,
/// What the file is, such as `plc_project`, `firmware_image`,
/// `source_archive` or `mobile_package`.
#[schema(example = "source_archive")]
kind: String,
/// The PLC project's format, for a PLC project.
plc_format: Option<String>,
}
/// Attach an artifact to a target by uploading its file.
///
/// A PLC project, firmware image, source archive or mobile package.
/// POST /api/v1/targets/{id}/artifacts/upload — attach an artifact by uploading
/// its file (PLC project, firmware image, source archive, mobile package).
///
/// The file is **streamed to disk** chunk by chunk as it arrives, never held in
/// memory whole (it used to be read into one buffer of up to 512 MiB, per
@@ -752,21 +628,6 @@ pub struct UploadArtifactForm {
/// Multipart fields: `file` (required, exactly one), `kind` (required,
/// snake_case `ArtifactKind`), `plc_format` (optional, for PLC projects), in
/// any order.
#[utoipa::path(
post,
path = "/api/v1/targets/{id}/artifacts/upload",
tag = "Targets",
params(("id" = String, Path, description = "The target's id")),
request_body(content = UploadArtifactForm, content_type = "multipart/form-data"),
responses(
(status = 200, description = "The target with the artifact"),
(status = 404, description = "No such target"),
(status = 400, description = "Not an id, or a missing or unknown field"),
(status = 413, description = "The file is too large"),
(status = 415, description = "An archive format that cannot be unpacked"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn upload_artifact(
Extension(agent): AgentExt,
@@ -902,13 +763,14 @@ async fn archive_check(path: std::path::PathBuf) -> Result<ArchiveCheck, StatusC
}
/// The body of [`set_archive_password`].
#[derive(Debug, Deserialize, utoipa::ToSchema)]
#[derive(Debug, Deserialize)]
pub struct ArchivePasswordRequest {
/// The archive's password.
pub password: String,
}
/// Set the password of an uploaded, password-protected archive.
/// PUT /api/v1/targets/{id}/artifacts/{artifact_id}/archive-password — set the
/// password of an uploaded, password-protected archive.
///
/// The password is checked against the stored file first, then stored sealed
/// like a git token; the API never returns it. It travels in this JSON body,
@@ -919,25 +781,6 @@ pub struct ArchivePasswordRequest {
/// 404 without the target or artifact; 409 when the artifact is not a
/// password-protected zip; 422 when the password does not open it; 503 when
/// the deployment has no key to seal it with.
#[utoipa::path(
put,
path = "/api/v1/targets/{id}/artifacts/{artifact_id}/archive-password",
tag = "Targets",
params(
("id" = String, Path, description = "The target's id"),
("artifact_id" = String, Path, description = "The artifact's id"),
),
request_body = ArchivePasswordRequest,
responses(
(status = 204, description = "The password opens the archive and is stored"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such target or artifact"),
(status = 409, description = "The artifact is not a password-protected zip"),
(status = 422, description = "The password does not open the archive"),
(status = 503, description = "The password cannot be sealed"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(target_id = %id, artifact_id = %artifact_id))]
pub async fn set_archive_password(
Extension(agent): AgentExt,
@@ -1071,19 +914,7 @@ fn parse_enum<T: for<'de> Deserialize<'de>>(s: &str) -> Option<T> {
serde_json::from_value(serde_json::Value::String(s.to_string())).ok()
}
/// The scans that apply to a target, with why and what each one needs.
#[utoipa::path(
get,
path = "/api/v1/targets/{id}/applicable-scans",
tag = "Targets",
params(("id" = String, Path, description = "The target's id")),
responses(
(status = 200, description = "The applicable scans"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such target"),
(status = 401, description = "No valid bearer token"),
)
)]
/// 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,
@@ -1122,23 +953,11 @@ pub async fn applicable_scans_for_target(
}))
}
/// Classify a target from its artifacts.
/// 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 Firmwerk firmware analysis) is a follow-up background step.
#[utoipa::path(
post,
path = "/api/v1/targets/{id}/detect",
tag = "Targets",
params(("id" = String, Path, description = "The target's id")),
responses(
(status = 200, description = "The classified target"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such target"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn detect_target(
Extension(agent): AgentExt,
@@ -1181,8 +1000,7 @@ pub async fn detect_target(
}
/// Why a scan is asked for (`POST /api/v1/targets/{id}/scan?reason=…`).
#[derive(Debug, Default, serde::Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
#[derive(Debug, Default, serde::Deserialize)]
pub struct ScanReason {
/// `new_content` after the customer created the target or uploaded
/// files (t72): it runs only when something changed, as a change-driven
@@ -1205,108 +1023,10 @@ fn requested_trigger(staff: bool, reason: Option<&str>) -> compliance_core::mode
}
}
/// `POST /api/v1/targets/{id}/billing/swap`: the included target to swap
/// the extra target `{id}` with.
#[derive(Debug, Deserialize, utoipa::ToSchema)]
pub struct SwapRequest {
/// The id of the included target that becomes extra.
pub with: String,
}
/// The JSON `error` of a refused swap, for the dashboard to word.
fn swap_refusal_code(refusal: compliance_core::models::SwapRefusal) -> &'static str {
use compliance_core::models::SwapRefusal;
match refusal {
SwapRefusal::Unlimited => "swap_unlimited",
SwapRefusal::NotExtra => "swap_not_extra",
SwapRefusal::NotIncluded => "swap_not_included",
SwapRefusal::Locked => "swap_locked",
}
}
/// Swap an extra target with an included one.
///
/// The extra target `{id}` becomes included and stays so until the end of
/// the calendar month; the included target `with` becomes extra at once (t72).
/// The number of extra targets, and so the extra-target line, is the same.
///
/// # Errors
///
/// `404` for a target that is not an active one of the tenant, `409` with
/// the reason when the swap is not allowed, `503` when the plan cannot be
/// read.
#[utoipa::path(
post,
path = "/api/v1/targets/{id}/billing/swap",
tag = "Targets",
params(("id" = String, Path, description = "The target's id")),
request_body = SwapRequest,
responses(
(status = 200, description = "The targets were swapped"),
(status = 400, description = "Not an id"),
(status = 404, description = "Not an active target of the tenant"),
(status = 409, description = "The swap is not allowed; `error` says why"),
(status = 503, description = "The plan cannot be read"),
(status = 401, description = "No valid bearer token"),
)
)]
pub async fn swap_target_billing(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
Json(req): Json<SwapRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
let refuse =
|status: StatusCode, error: &str| (status, Json(serde_json::json!({ "error": error })));
let incoming = parse_oid(&id).map_err(|s| refuse(s, "invalid_id"))?;
let outgoing = parse_oid(&req.with).map_err(|s| refuse(s, "invalid_id"))?;
let db = tenant_db(&agent, &tenant)
.await
.map_err(|s| refuse(s, "database_unavailable"))?;
let tenant_id = tenant.0.tenant_id.as_str();
let plan = agent
.plan(tenant_id)
.await
.ok_or_else(|| refuse(StatusCode::SERVICE_UNAVAILABLE, "plan_unavailable"))?;
let outcome = crate::metering::swap(
&db,
incoming,
outgoing,
plan.included_targets.is_some(),
chrono::Utc::now(),
)
.await
.map_err(|e| {
tracing::error!(tenant_id, "swap failed: {e}");
refuse(StatusCode::INTERNAL_SERVER_ERROR, "swap_failed")
})?;
match outcome {
None => Err(refuse(StatusCode::NOT_FOUND, "target_not_found")),
Some(Err(refusal)) => Err(refuse(StatusCode::CONFLICT, swap_refusal_code(refusal))),
Some(Ok(())) => {
agent.refresh_billing(tenant_id, &db).await;
tracing::info!(tenant_id, incoming = %id, outgoing = %req.with, "targets swapped");
Ok(Json(serde_json::json!({ "data": { "swapped": true } })))
}
}
}
/// Start a scan of a target.
/// 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.
#[utoipa::path(
post,
path = "/api/v1/targets/{id}/scan",
tag = "Targets",
params(("id" = String, Path, description = "The target's id"), ScanReason),
responses(
(status = 200, description = "The scan was started"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such target"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn trigger_target_scan(
Extension(agent): AgentExt,
@@ -86,13 +86,6 @@ pub async fn create_session(
if let Err(e) = agent.net_guard.check_url(&config.app_url) {
return Err((StatusCode::BAD_REQUEST, e.to_string()));
}
// The test-user cleanup talks to the target's identity provider, also
// a tenant-chosen URL.
if let Some(access) = &config.auth.cleanup {
if let Err(e) = agent.net_guard.check_url(&access.base_url()) {
return Err((StatusCode::BAD_REQUEST, e.to_string()));
}
}
// Look up or auto-create DastTarget by app_url
let target = match db
@@ -194,21 +187,35 @@ pub async fn create_session(
}
}
// The test user an auto-register session registers, kept on the
// stored session so cleanup and the report find it.
if let Some(cfg) = &session.config {
session.test_user = crate::pentest::cleanup::planned_test_user(cfg, &session_id_str);
}
if let (Some(sid), Some(test_user)) = (session.id, &session.test_user) {
let record = mongodb::bson::to_bson(test_user)
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
db.pentest_sessions()
.update_one(
doc! { "_id": sid },
doc! { "$set": { "test_user": record } },
)
.await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("DB error: {e}")))?;
// Pre-populate test user record for auto-register sessions
if let Some(ref cfg) = session.config {
if cfg.auth.mode == AuthMode::AutoRegister {
let verification_email = cfg.auth.verification_email.clone();
// Build plus-addressed email for this session
let test_email = verification_email.as_deref().map(|email| {
let parts: Vec<&str> = email.splitn(2, '@').collect();
if parts.len() == 2 {
format!("{}+{}@{}", parts[0], session_id_str, parts[1])
} else {
email.to_string()
}
});
// Detect identity provider from keycloak config
let provider = if agent.config.keycloak_url.is_some() {
Some(compliance_core::models::pentest::IdentityProvider::Keycloak)
} else {
None
};
session.test_user = Some(compliance_core::models::pentest::TestUserRecord {
username: None, // LLM will choose; updated after registration
email: test_email,
provider_user_id: None,
provider,
cleaned_up: false,
});
}
}
let initial_message = config
@@ -560,7 +560,7 @@ pub async fn list_targets(
.collect();
let runs = db.scan_runs();
let (mut last_scans, open, vulns) = tokio::join!(
super::onboarding::latest_scan_runs(&runs, ids.clone(), false),
super::onboarding::latest_scan_runs(&runs, ids.clone()),
open_findings_counts(&db, ids.clone()),
open_vulnerabilities_counts(&db, ids),
);
@@ -640,10 +640,6 @@ fn git_source_json(
"webhook_secret".into(),
new_secret.map_or(serde_json::Value::Null, Into::into),
);
obj.insert(
"webhook_events".into(),
crate::git_source::WEBHOOK_EVENTS.as_slice().into(),
);
}
v
}
+5 -79
View File
@@ -16,16 +16,6 @@ pub(crate) const MAX_EXPORT_COMPONENTS: u64 = 100_000;
/// Package names listed per license in the summary; `count` stays exact.
const MAX_LICENSE_PACKAGES: i64 = 100;
/// The package managers and licences the SBOM list can be filtered by.
#[utoipa::path(
get,
path = "/api/v1/sbom/filters",
tag = "SBOM",
responses(
(status = 200, description = "The package managers and licences"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all)]
pub async fn sbom_filters(
Extension(agent): AgentExt,
@@ -41,7 +31,7 @@ pub async fn sbom_filters(
.unwrap_or_default()
.into_iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.filter(|s| compliance_core::sbom_ecosystems::is_filterable_manager(s))
.filter(|s| !s.is_empty() && s != "unknown" && s != "file")
.collect();
let licenses: Vec<String> = db
@@ -60,17 +50,6 @@ pub async fn sbom_filters(
})))
}
/// List the tenant's SBOM components, filtered and a page at a time.
#[utoipa::path(
get,
path = "/api/v1/sbom",
tag = "SBOM",
params(SbomFilter),
responses(
(status = 200, description = "A page of components"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(repo_id = ?filter.repo_id, package_manager = ?filter.package_manager))]
pub async fn list_sbom(
Extension(agent): AgentExt,
@@ -219,20 +198,6 @@ async fn unresolved_ids(
.collect()
}
/// A target's SBOM as a CycloneDX or SPDX document to download.
///
/// Never truncated: a target with more than 100 000 components is refused.
#[utoipa::path(
get,
path = "/api/v1/sbom/export",
tag = "SBOM",
params(SbomExportParams),
responses(
(status = 200, description = "The SBOM document"),
(status = 413, description = "Too many components to export"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all)]
pub async fn export_sbom(
Extension(agent): AgentExt,
@@ -309,27 +274,14 @@ pub async fn export_sbom(
}
/// The target whose SBOM quality is asked for.
#[derive(serde::Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
#[derive(serde::Deserialize)]
pub struct SbomQualityParams {
/// The target (its id).
pub repo_id: String,
}
/// A target's SBOM quality score from its newest scan that scored one.
///
/// sbomqs against BSI TR-03183-2 and NTIA (#496), with that scan's id and
/// end; `data: null` when none did.
#[utoipa::path(
get,
path = "/api/v1/sbom/quality",
tag = "SBOM",
params(SbomQualityParams),
responses(
(status = 200, description = "The score, or null"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/sbom/quality?repo_id= — the target's SBOM quality score
/// (sbomqs against BSI TR-03183-2 and NTIA, #496) from its newest scan that
/// scored one, with that scan's id and end; `data: null` when none did.
#[tracing::instrument(skip_all, fields(repo_id = %params.repo_id))]
pub async fn sbom_quality(
Extension(agent): AgentExt,
@@ -356,19 +308,6 @@ pub async fn sbom_quality(
}))
}
/// The licences of the SBOM components, most components first.
///
/// The confirmed licence where there is one, else the detected one.
#[utoipa::path(
get,
path = "/api/v1/sbom/licenses",
tag = "SBOM",
params(SbomFilter),
responses(
(status = 200, description = "One row per licence"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all)]
pub async fn license_summary(
Extension(agent): AgentExt,
@@ -472,19 +411,6 @@ fn summarize_licenses(
summaries
}
/// Compare the SBOMs of two targets.
///
/// The components only in one of them and those whose version differs.
#[utoipa::path(
get,
path = "/api/v1/sbom/diff",
tag = "SBOM",
params(SbomDiffParams),
responses(
(status = 200, description = "The differences"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all)]
pub async fn sbom_diff(
Extension(agent): AgentExt,
@@ -1,131 +0,0 @@
//! GET /api/v1/targets/{id}/sbom-ecosystems: a target's SBOM components per
//! ecosystem, and how many of them have a known vulnerability (#957).
use axum::extract::{Extension, Path};
use axum::http::StatusCode;
use axum::Json;
use futures_util::TryStreamExt;
use mongodb::bson::{doc, Document};
use serde::Deserialize;
use super::dto::{tenant_db, AgentExt, ApiResponse, ApiResult};
use compliance_core::sbom_ecosystems::{rank, EcosystemCount};
use compliance_core::tenant_ctx::TenantCtx;
/// One row of [`pipeline`]: a package manager with its counts. `_id` is
/// `None` for components stored without one.
#[derive(Debug, Deserialize)]
struct EcosystemRow {
#[serde(rename = "_id")]
package_manager: Option<String>,
components: u64,
with_cve: u64,
}
impl From<EcosystemRow> for EcosystemCount {
fn from(row: EcosystemRow) -> Self {
Self {
package_manager: row.package_manager.unwrap_or_default(),
components: row.components,
with_cve: row.with_cve,
}
}
}
/// The aggregation counting the components of target `repo_id` per package
/// manager in the database, so only one row per ecosystem leaves it (never
/// the components with their vulnerability lists, #67).
fn pipeline(repo_id: &str) -> Vec<Document> {
vec![
doc! { "$match": { "repo_id": repo_id } },
doc! { "$group": {
"_id": "$package_manager",
"components": { "$sum": 1 },
// A component stored without the list counts as without a CVE.
"with_cve": { "$sum": { "$cond": [
{ "$gt": [{ "$size": { "$ifNull": ["$known_vulnerabilities", []] } }, 0] },
1,
0,
] } },
} },
]
}
/// GET /api/v1/targets/{id}/sbom-ecosystems — the SBOM components of target
/// `id` per ecosystem the component table can filter by, the largest first.
///
/// # Errors
///
/// `500` when the aggregation fails, so the dashboard says so instead of
/// showing an empty chart.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn list_sbom_ecosystems(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
) -> ApiResult<Vec<EcosystemCount>> {
let db = tenant_db(&agent, &tenant).await?;
let fail = |e: mongodb::error::Error| {
tracing::warn!("Failed to count the SBOM ecosystems: {e}");
StatusCode::INTERNAL_SERVER_ERROR
};
let rows: Vec<Document> = db
.sbom_entries()
.aggregate(pipeline(&id))
.await
.map_err(fail)?
.try_collect()
.await
.map_err(fail)?;
let counts = rows
.into_iter()
.filter_map(|row| mongodb::bson::from_document::<EcosystemRow>(row).ok())
.map(EcosystemCount::from)
.collect();
let ecosystems = rank(counts);
Ok(Json(ApiResponse {
total: Some(ecosystems.len() as u64),
data: ecosystems,
page: None,
}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_pipeline_counts_one_target_per_package_manager() {
let stages = pipeline("t1");
assert_eq!(stages.len(), 2);
assert_eq!(stages[0], doc! { "$match": { "repo_id": "t1" } });
let group = stages[1].get_document("$group").expect("a $group stage");
assert_eq!(group.get_str("_id").ok(), Some("$package_manager"));
assert_eq!(
group.get_document("components").ok(),
Some(&doc! { "$sum": 1 })
);
assert!(group.contains_key("with_cve"));
}
#[test]
fn a_row_reads_as_its_count_whatever_integer_width_mongo_sums_in() {
let row: EcosystemRow = mongodb::bson::from_document(
doc! { "_id": "npm", "components": 412_i32, "with_cve": 7_i64 },
)
.expect("a row");
assert_eq!(
EcosystemCount::from(row),
EcosystemCount {
package_manager: "npm".into(),
components: 412,
with_cve: 7,
}
);
let nameless: EcosystemRow = mongodb::bson::from_document(
doc! { "_id": null, "components": 2_i32, "with_cve": 0_i32 },
)
.expect("a row without a package manager");
assert_eq!(EcosystemCount::from(nameless).package_manager, "");
}
}
@@ -1,141 +0,0 @@
//! A target's "Verlauf" (#957): what each of its last scans changed, the
//! CVE alerts found new and those found gone ([`compliance_core::scan_changes`]).
//!
//! Reads the tenant's own database; the org-role middleware lets every role
//! that may read call it, like the other target reads.
use axum::extract::{Extension, Path, Query};
use axum::http::StatusCode;
use axum::Json;
use mongodb::bson::{doc, oid::ObjectId, DateTime as BsonDateTime, Document};
use serde::{Deserialize, Deserializer};
use compliance_core::models::{CveAlert, ScanRun};
use compliance_core::scan_changes::{changes, ScanChange, DEFAULT_SCANS, MAX_SCANS};
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResult};
/// The query of [`target_scan_changes`].
#[derive(Debug, Deserialize)]
pub struct ChangesQuery {
/// The last scans to show, `1..=50` (clamped); 20 when not given.
#[serde(default = "default_limit", deserialize_with = "de_limit")]
pub limit: usize,
}
fn default_limit() -> usize {
DEFAULT_SCANS
}
/// Clamp a caller-supplied number of scans to `1..=MAX_SCANS`.
fn de_limit<'de, D: Deserializer<'de>>(d: D) -> Result<usize, D::Error> {
Ok(usize::deserialize(d)?.clamp(1, MAX_SCANS))
}
/// Log a database error and answer 500.
fn db_error(what: &str) -> impl FnOnce(mongodb::error::Error) -> StatusCode + '_ {
move |e| {
tracing::warn!("scan changes: {what} failed: {e}");
StatusCode::INTERNAL_SERVER_ERROR
}
}
/// `GET /api/v1/targets/{id}/scan-changes[?limit=20]` — the target's last
/// scans, oldest first, each with the CVE alerts found new and gone since
/// the completed scan before it (most severe first), its status and its new
/// findings. The target's first completed scan is marked `baseline`. 404
/// for a target the tenant does not have.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn target_scan_changes(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
Query(query): Query<ChangesQuery>,
) -> ApiResult<Vec<ScanChange>> {
let oid = ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
let db = tenant_db(&agent, &tenant).await?;
// Only whether it exists: its id is all that is read.
db.onboarded_targets()
.clone_with_type::<Document>()
.find_one(doc! { "_id": oid })
.projection(doc! { "_id": 1 })
.await
.map_err(db_error("reading the target"))?
.ok_or(StatusCode::NOT_FOUND)?;
let runs: Vec<ScanRun> = collect_cursor_async(
db.scan_runs()
.find(doc! { "repo_id": &id })
.sort(doc! { "started_at": -1 })
.limit(i64::try_from(query.limit).unwrap_or(i64::MAX))
.await
.map_err(db_error("listing the runs"))?,
)
.await;
// Where the window of the oldest shown scan starts: the end of the
// completed scan before it, if there is one.
let since = match runs.iter().map(|r| r.started_at).min() {
Some(oldest) => db
.scan_runs()
.find_one(doc! {
"repo_id": &id,
"status": "completed",
"started_at": { "$lt": BsonDateTime::from_chrono(oldest) },
})
.sort(doc! { "started_at": -1 })
.await
.map_err(db_error("finding the scan before"))?
.and_then(|run| run.completed_at),
None => None,
};
let mut filter = doc! { "repo_id": &id };
if let Some(since) = since {
let since = BsonDateTime::from_chrono(since);
filter.insert(
"$or",
vec![
doc! { "created_at": { "$gt": since } },
doc! { "resolved_at": { "$gt": since } },
],
);
}
let alerts: Vec<CveAlert> = collect_cursor_async(
db.cve_alerts()
.find(filter)
.projection(doc! {
"summary": 0, "llm_impact_summary": 0, "advisories": 0, "exploitation": 0,
})
.await
.map_err(db_error("loading the alerts"))?,
)
.await;
let data = changes(&runs, since, &alerts);
Ok(Json(ApiResponse {
total: Some(data.len() as u64),
data,
page: None,
}))
}
#[cfg(test)]
mod tests {
use super::*;
fn query(text: &str) -> ChangesQuery {
let uri: axum::http::Uri = format!("/x?{text}").parse().unwrap_or_default();
Query::<ChangesQuery>::try_from_uri(&uri)
.map(|q| q.0)
.unwrap_or(ChangesQuery { limit: 0 })
}
#[test]
fn the_limit_is_clamped_and_defaults_to_twenty() {
assert_eq!(query("").limit, DEFAULT_SCANS);
assert_eq!(query("limit=0").limit, 1);
assert_eq!(query("limit=999").limit, MAX_SCANS);
assert_eq!(query("limit=5").limit, 5);
}
}
@@ -21,19 +21,13 @@ const TOKEN_METHOD: &str = "token";
/// A client-supplied artifact spec. The server builds the [`Artifact`] (and its
/// id) from it, so clients never set internal fields.
#[derive(Debug, Deserialize, utoipa::ToSchema)]
#[derive(Debug, Deserialize)]
pub struct ArtifactInput {
/// What the artifact is, such as `git_repo`, `source_archive` or `plc_project`.
#[schema(value_type = String, example = "git_repo")]
pub kind: ArtifactKind,
/// Where it is: a clone URL, or a reference to an uploaded file.
pub source_ref: String,
/// The branch of a git repository.
#[serde(default)]
pub branch: Option<String>,
/// The PLC project's format, for a PLC project.
#[serde(default)]
#[schema(value_type = Option<String>, example = "plcopen_xml")]
pub plc_format: Option<PlcFormat>,
/// A git access token for a private repository (#303). Sent: stored
/// sealed. Sent empty: removed. Left out: the stored one is kept.
@@ -135,27 +129,14 @@ pub fn merge_artifacts(
/// A change to a target's scan config. A field left out keeps its stored
/// value: enabling a scan must not remove the issue tracker (#304).
#[derive(Debug, Default, Deserialize, utoipa::ToSchema)]
#[derive(Debug, Default, Deserialize)]
pub struct ScanConfigUpdate {
/// The scans to run, such as `sast`, `sbom` or `cve`.
#[schema(value_type = Option<Vec<String>>)]
pub enabled_scans: Option<Vec<ScanType>>,
/// The scans not to run.
#[schema(value_type = Option<Vec<String>>)]
pub disabled_scans: Option<Vec<ScanType>>,
/// `development`, `staging` or `production`.
#[schema(value_type = Option<String>, example = "staging")]
pub environment: Option<Environment>,
/// Whether dynamic tests may change data.
pub allow_destructive: Option<bool>,
/// The pentest strategy: `quick`, `comprehensive`, `targeted` or `aggressive`.
#[schema(value_type = Option<String>)]
pub strategy: Option<PentestStrategy>,
/// The pentest's scope and login.
#[schema(value_type = Option<Object>)]
pub pentest: Option<PentestConfig>,
/// Where findings are filed as issues.
#[schema(value_type = Option<Object>)]
pub issue_tracker: Option<IssueTrackerConfig>,
/// Paths left out of every scan; replaces the stored list. Normalised
/// while the request is read, so an invalid path is refused with its
+18 -192
View File
@@ -1,6 +1,5 @@
//! VEX for a target's CVE alerts (#498): list them, state their status (one
//! alert, or every open alert of a component at once, #949), and export the
//! statements as OpenVEX or CycloneDX VEX.
//! VEX for a target's CVE alerts (#498): list them, state their status, and
//! export the statements as OpenVEX or CycloneDX VEX.
use axum::extract::{Extension, Path, Query};
use axum::http::{header, HeaderValue, StatusCode};
@@ -10,7 +9,6 @@ use mongodb::bson::{doc, oid::ObjectId};
use serde::Deserialize;
use compliance_core::csaf_docs;
use compliance_core::cve_groups::{self, CveGroup, PackageKey};
use compliance_core::enisa_docs::{self, EnisaInput, Reportability};
use compliance_core::models::{CveAlert, SbomEntry, VexAssessment, VexJustification, VexStatus};
use compliance_core::tenant_ctx::TenantCtx;
@@ -28,8 +26,18 @@ pub async fn list_target_cves(
Path(id): Path<String>,
) -> ApiResult<Vec<CveAlert>> {
let db = tenant_db(&agent, &tenant).await?;
// An unreadable list reads as empty here, as it always has.
let alerts = target_alerts(&db, &id).await.unwrap_or_default();
let alerts: Vec<CveAlert> = match db
.cve_alerts()
.find(doc! { "repo_id": &id })
.sort(doc! { "created_at": -1 })
.await
{
Ok(cursor) => collect_cursor_async(cursor).await,
Err(e) => {
tracing::warn!("Failed to list CVE alerts: {e}");
Vec::new()
}
};
Ok(Json(ApiResponse {
total: Some(alerts.len() as u64),
data: alerts,
@@ -37,23 +45,6 @@ pub async fn list_target_cves(
}))
}
/// The CVE alerts of target `id`, newest first.
async fn target_alerts(
db: &crate::database::Database,
id: &str,
) -> Result<Vec<CveAlert>, StatusCode> {
let cursor = db
.cve_alerts()
.find(doc! { "repo_id": id })
.sort(doc! { "created_at": -1 })
.await
.map_err(|e| {
tracing::warn!("Failed to list CVE alerts: {e}");
StatusCode::INTERNAL_SERVER_ERROR
})?;
Ok(collect_cursor_async(cursor).await)
}
/// The body of [`set_cve_vex`].
#[derive(Debug, Deserialize)]
pub struct VexRequest {
@@ -66,8 +57,9 @@ pub struct VexRequest {
pub action_statement: Option<String>,
}
/// The statement `req` asks for, by `actor`.
fn statement(req: VexRequest, actor: Actor<'_>) -> VexAssessment {
/// The statement `req` asks for, by the requester of `tenant`.
fn statement(req: VexRequest, tenant: &TenantCtx) -> VexAssessment {
let actor = Actor::of(&tenant.0);
let text = |s: Option<String>| s.map(|t| t.trim().to_string()).filter(|t| !t.is_empty());
VexAssessment {
status: req.status,
@@ -93,7 +85,7 @@ pub async fn set_cve_vex(
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
let fail = |code: StatusCode, error: &str| (code, Json(serde_json::json!({ "error": error })));
let oid = ObjectId::parse_str(&id).map_err(|_| fail(StatusCode::BAD_REQUEST, "bad id"))?;
let vex = statement(req, Actor::of(&tenant.0));
let vex = statement(req, &tenant);
vex.validate()
.map_err(|e| fail(StatusCode::UNPROCESSABLE_ENTITY, &e.to_string()))?;
let db = tenant_db(&agent, &tenant)
@@ -112,90 +104,6 @@ pub async fn set_cve_vex(
Ok(Json(serde_json::json!({ "status": "updated", "vex": vex })))
}
/// GET /api/v1/targets/{id}/cve-groups — the target's open CVE alerts grouped
/// by component (#949): the update that fixes them, their counts per
/// severity, KEV and the highest EPSS score, the most severe group first.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn list_cve_groups(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
) -> ApiResult<Vec<CveGroup>> {
let db = tenant_db(&agent, &tenant).await?;
let groups = cve_groups::group_open_alerts(&target_alerts(&db, &id).await?);
Ok(Json(ApiResponse {
total: Some(groups.len() as u64),
data: groups,
page: None,
}))
}
/// The body of [`set_group_vex`]: the component as [`list_cve_groups`] names
/// it, and the statement as [`set_cve_vex`] takes it.
#[derive(Debug, Deserialize)]
pub struct GroupVexRequest {
#[serde(flatten)]
pub key: PackageKey,
#[serde(flatten)]
pub statement: VexRequest,
}
/// PATCH /api/v1/targets/{id}/cve-groups/vex — state one VEX status on every
/// open alert of a component (#949): one statement per alert, with the
/// validation, author and time of [`set_cve_vex`], so the exports and the
/// CVE issues' auto-close treat them as single decisions. Settled alerts
/// keep their statements. 422 as for one alert, 404 when the component has
/// no open alert.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn set_group_vex(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
Json(req): Json<GroupVexRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
let fail = |code: StatusCode, error: &str| (code, Json(serde_json::json!({ "error": error })));
let vex = statement(req.statement, Actor::of(&tenant.0));
vex.validate()
.map_err(|e| fail(StatusCode::UNPROCESSABLE_ENTITY, &e.to_string()))?;
let db = tenant_db(&agent, &tenant)
.await
.map_err(|code| fail(code, "tenant"))?;
let alerts = target_alerts(&db, &id)
.await
.map_err(|code| fail(code, "load"))?;
let ids = open_alert_ids(&alerts, &req.key);
if ids.is_empty() {
return Err(fail(
StatusCode::NOT_FOUND,
"no open alert of this component",
));
}
let vex_bson = mongodb::bson::to_bson(&vex)
.map_err(|_| fail(StatusCode::INTERNAL_SERVER_ERROR, "encode"))?;
let result = db
.cve_alerts()
.update_many(
doc! { "_id": { "$in": ids }, "repo_id": &id },
doc! { "$set": { "vex": vex_bson } },
)
.await
.map_err(|_| fail(StatusCode::INTERNAL_SERVER_ERROR, "store"))?;
Ok(Json(serde_json::json!({
"status": "updated",
"updated": result.matched_count,
"vex": vex,
})))
}
/// The ids of the open alerts among `alerts` that are about component `key`.
fn open_alert_ids(alerts: &[CveAlert], key: &PackageKey) -> Vec<ObjectId> {
alerts
.iter()
.filter(|a| cve_groups::is_open(a) && key.matches(a))
.filter_map(|a| a.id)
.collect()
}
/// The query of [`export_vex`].
#[derive(Debug, Deserialize)]
pub struct VexExportQuery {
@@ -533,88 +441,6 @@ pub async fn export_enisa(
#[cfg(test)]
mod tests {
use super::*;
use compliance_core::models::{CveSource, VexError};
fn group_request(body: serde_json::Value) -> GroupVexRequest {
serde_json::from_value(body).expect("a group request")
}
fn actor() -> Actor<'static> {
Actor {
id: "u1",
name: Some("Ada Admin".into()),
support: false,
}
}
#[test]
fn a_group_decision_is_validated_like_a_single_one() {
let req = group_request(serde_json::json!({
"package": "vite",
"version": "5.4.21",
"purl": "pkg:npm/vite@5.4.21",
"status": "not_affected",
"impact_statement": " ",
}));
assert_eq!(
req.key,
PackageKey {
package: "vite".into(),
version: "5.4.21".into(),
purl: Some("pkg:npm/vite@5.4.21".into()),
}
);
let vex = statement(req.statement, actor());
assert_eq!(vex.validate(), Err(VexError::NotAffectedWithoutReason));
let req = group_request(serde_json::json!({
"package": "vite",
"version": "5.4.21",
"status": "not_affected",
"justification": "vulnerable_code_not_in_execute_path",
"impact_statement": " Build tool only. ",
}));
assert_eq!(req.key.purl, None);
let vex = statement(req.statement, actor());
assert_eq!(vex.validate(), Ok(()));
assert_eq!(vex.impact_statement.as_deref(), Some("Build tool only."));
assert_eq!(
(vex.by.as_str(), vex.by_name.as_deref(), vex.by_scan),
("u1", Some("Ada Admin"), false)
);
let affected = group_request(serde_json::json!({
"package": "vite",
"version": "5.4.21",
"status": "affected",
}));
assert_eq!(
statement(affected.statement, actor()).validate(),
Err(VexError::AffectedWithoutAction)
);
}
#[test]
fn a_group_decision_reaches_the_open_alerts_of_its_component_only() {
let alert = |cve: &str, version: &str| {
let mut a = CveAlert::new(
cve.into(),
"t1".into(),
"vite".into(),
version.into(),
CveSource::Osv,
);
a.id = Some(ObjectId::new());
a
};
let open = alert("CVE-2025-0001", "5.4.21");
let mut settled = alert("CVE-2025-0002", "5.4.21");
settled.resolved_at = Some(chrono::Utc::now());
let other_version = alert("CVE-2025-0003", "6.0.0");
let alerts = vec![open.clone(), settled, other_version];
let key = PackageKey::of(&open);
assert_eq!(open_alert_ids(&alerts, &key), [open.id.expect("an id")]);
}
#[test]
fn a_publisher_namespace_is_a_web_url_or_the_placeholder() {
-1
View File
@@ -1,6 +1,5 @@
pub mod api_key_gate;
pub mod handlers;
pub mod openapi;
pub mod role_gate;
pub mod routes;
pub mod server;
-73
View File
@@ -1,73 +0,0 @@
//! The OpenAPI description of the customer API (#1006).
//!
//! Generated from the handlers: a route registered through
//! [`utoipa_axum::routes!`] takes its path, method, parameters and body from
//! the handler's `#[utoipa::path]`, so the description cannot drift from the
//! route. The document is served at [`SPEC_PATH`], behind the same
//! authentication as the API, for integrators and for DAST, which seeds its
//! endpoints from it (#997).
use utoipa::openapi::security::{HttpAuthScheme, HttpBuilder, SecurityRequirement, SecurityScheme};
use utoipa::OpenApi;
/// Where the agent serves its OpenAPI document. Under the API prefix, so the
/// customer authentication covers it, and one of the paths DAST tries.
pub const SPEC_PATH: &str = "/api/v1/openapi.json";
/// The name of the bearer scheme in the document.
const BEARER: &str = "bearer";
/// The document's frame; the routes add their paths to it.
#[derive(OpenApi)]
#[openapi(info(
title = "Prüfwerk API",
description = "The customer API of the Prüfwerk agent. Every operation but the health \
check needs a Keycloak access token or an API key as a bearer token."
))]
pub struct ApiDoc;
/// `api` with the bearer scheme, required by every operation except the
/// public ones ([`compliance_core::auth::bypasses_customer_auth`]).
///
/// The scheme goes on each operation rather than once for the document: a
/// reader that only looks at operations (the DAST spec parser) still sees it.
///
/// # Arguments
///
/// * `api` - the document with every described route's path
///
/// # Returns
///
/// The finished document.
pub fn with_bearer_auth(mut api: utoipa::openapi::OpenApi) -> utoipa::openapi::OpenApi {
api.components
.get_or_insert_with(Default::default)
.add_security_scheme(
BEARER,
SecurityScheme::Http(
HttpBuilder::new()
.scheme(HttpAuthScheme::Bearer)
.description(Some("A Keycloak access token or an API key"))
.build(),
),
);
for (path, item) in api.paths.paths.iter_mut() {
if compliance_core::auth::bypasses_customer_auth(path) {
continue;
}
let operations = [
&mut item.get,
&mut item.put,
&mut item.post,
&mut item.delete,
&mut item.options,
&mut item.head,
&mut item.patch,
&mut item.trace,
];
for operation in operations.into_iter().flatten() {
operation.security = Some(vec![SecurityRequirement::new(BEARER, Vec::<String>::new())]);
}
}
api
}
+4 -6
View File
@@ -2,13 +2,12 @@
//!
//! One middleware for every tenant-scoped route, so no handler can forget it:
//!
//! * `OWNER`, `IT_ADMIN`, `USER`, `PSIRT`, `DEVELOPMENT` — read and write.
//! * `CXO`, `LEGAL`, `QUALITY`, `PURCHASING`, `AUDITOR` — read only: `GET` / `HEAD` / `OPTIONS`, plus the few
//! * `IT_ADMIN`, `USER` — read and write.
//! * `CXO`, `LEGAL` — read only: `GET` / `HEAD` / `OPTIONS`, plus the few
//! `POST` routes that only read ([`READ_ONLY_POSTS`]). `LEGAL` also
//! decides about licences: the licence policy and the legal review
//! ([`ROLE_WRITES`], decided 2026-10-15).
//! * `FINANCE`, `PRIVACY`, `EXTERNAL`, or none of these roles — nothing;
//! every request is refused.
//! * `FINANCE`, or none of these roles — nothing; every request is refused.
//!
//! Refusals are `403 {"error": "forbidden_role", "access": "none" | "read_only"}`.
//!
@@ -19,8 +18,7 @@
//! Werkbank runner and admin APIs (their own token middleware), the health
//! check, and support staff who have not chosen a tenant yet.
//!
//! Handlers may still be stricter (manual findings stay for administrators:
//! `IT_ADMIN` and `OWNER`).
//! Handlers may still be stricter (manual findings stay `IT_ADMIN`-only).
//!
//! API keys (tenant-registry ADR 0001) hold no role. They reach only the
//! routes in [`KEY_SCOPES`], each with the scope it names; every other route
@@ -19,19 +19,11 @@ use tower::ServiceExt;
/// Who is calling.
#[derive(Debug, Clone, Copy)]
enum Caller {
Owner,
ItAdmin,
User,
Cxo,
Legal,
Finance,
Psirt,
Development,
Quality,
Purchasing,
Auditor,
Privacy,
External,
NoRoles,
/// BreakPilot support in a customer's tenant (no org roles of its own).
Staff,
@@ -43,19 +35,11 @@ enum Caller {
fn ctx(caller: Caller) -> Option<TenantContext> {
let roles = match caller {
Caller::Owner => vec![OrgRole::Owner],
Caller::ItAdmin => vec![OrgRole::ItAdmin],
Caller::User => vec![OrgRole::User],
Caller::Cxo => vec![OrgRole::Cxo],
Caller::Legal => vec![OrgRole::Legal],
Caller::Finance => vec![OrgRole::Finance],
Caller::Psirt => vec![OrgRole::Psirt],
Caller::Development => vec![OrgRole::Development],
Caller::Quality => vec![OrgRole::Quality],
Caller::Purchasing => vec![OrgRole::Purchasing],
Caller::Auditor => vec![OrgRole::Auditor],
Caller::Privacy => vec![OrgRole::Privacy],
Caller::External => vec![OrgRole::External],
Caller::NoRoles | Caller::Staff | Caller::Key(_) => vec![],
Caller::Service => return None,
};
@@ -142,18 +126,11 @@ fn routes() -> Vec<(Method, String, bool)> {
(Method::GET, format!("/api/v1/findings/{ID}"), false),
(Method::PATCH, format!("/api/v1/findings/{ID}/status"), true),
(Method::PATCH, "/api/v1/findings/bulk-status".into(), true),
(Method::GET, "/api/v1/inbox".into(), false),
(Method::POST, "/api/v1/inbox/decide".into(), true),
(Method::POST, "/api/v1/inbox/undo".into(), true),
(Method::POST, "/api/v1/inbox/snooze".into(), true),
(Method::DELETE, format!("/api/v1/inbox/snooze/f-{ID}"), true),
(
Method::PATCH,
format!("/api/v1/findings/{ID}/feedback"),
true,
),
(Method::GET, "/api/v1/finding-groups".into(), false),
(Method::POST, "/api/v1/finding-groups/decide".into(), true),
(Method::POST, format!("/api/v1/targets/{ID}/findings"), true),
(
Method::POST,
@@ -165,23 +142,7 @@ fn routes() -> Vec<(Method, String, bool)> {
format!("/api/v1/targets/{ID}/evidence-pack"),
false,
),
(
Method::GET,
format!("/api/v1/targets/{ID}/finding-breakdown"),
false,
),
(Method::GET, "/api/v1/sbom/export".into(), false),
(Method::GET, "/api/v1/cve-history?days=30".into(), false),
(
Method::GET,
format!("/api/v1/targets/{ID}/top-updates"),
false,
),
(
Method::GET,
format!("/api/v1/targets/{ID}/scan-changes"),
false,
),
(Method::GET, "/api/v1/licenses/conclusions".into(), false),
(Method::PUT, "/api/v1/licenses/conclusions".into(), true),
(
@@ -212,19 +173,11 @@ fn routes() -> Vec<(Method, String, bool)> {
async fn roles_decide_reads_and_writes() {
// (caller, may read, may write)
let matrix = [
(Caller::Owner, true, true),
(Caller::ItAdmin, true, true),
(Caller::User, true, true),
(Caller::Cxo, true, false),
(Caller::Legal, true, false),
(Caller::Finance, false, false),
(Caller::Psirt, true, true),
(Caller::Development, true, true),
(Caller::Quality, true, false),
(Caller::Purchasing, true, false),
(Caller::Auditor, true, false),
(Caller::Privacy, false, false),
(Caller::External, false, false),
(Caller::NoRoles, false, false),
(Caller::Staff, true, true),
(Caller::Service, true, true),
+138 -290
View File
@@ -1,51 +1,20 @@
use axum::extract::DefaultBodyLimit;
use axum::http::header::CONTENT_TYPE;
use axum::routing::{delete, get, patch, post};
use axum::routing::{delete, get, patch, post, put};
use axum::Router;
use utoipa::OpenApi;
use utoipa_axum::router::{OpenApiRouter, UtoipaMethodRouterExt};
use utoipa_axum::routes;
use crate::api::{handlers, openapi};
use crate::api::handlers;
/// Allowance on top of the file itself for the multipart framing: boundaries,
/// part headers and the small `kind` / `plc_format` text fields.
const MULTIPART_OVERHEAD: usize = 1024 * 1024;
/// The customer API, with its OpenAPI description at [`openapi::SPEC_PATH`]
/// (#1006).
///
/// A route registered with `.routes(routes!(…))` is described by its
/// handler's `#[utoipa::path]`. The plain route calls are the routes not
/// described yet; a test keeps them listed in `UNDESCRIBED`, so a new route
/// cannot be added without its description.
pub fn build_router() -> Router {
let (router, api) = described_routes().split_for_parts();
let spec = std::sync::Arc::<str>::from(
openapi::with_bearer_auth(api)
.to_json()
.unwrap_or_else(|e| {
tracing::error!("OpenAPI description not built: {e}");
"{}".to_string()
}),
);
router.route(
openapi::SPEC_PATH,
get(move || {
let spec = spec.clone();
async move { ([(CONTENT_TYPE, "application/json")], spec.to_string()) }
}),
)
}
fn described_routes() -> OpenApiRouter {
OpenApiRouter::with_openapi(openapi::ApiDoc::openapi())
Router::new()
.route("/api/v1/health", get(handlers::health))
.route("/api/v1/oscal/assess", post(handlers::oscal::assess_target))
.route("/api/v1/stats/overview", get(handlers::stats_overview))
// The tenant's projects (owned by the registry), for assigning targets.
.route("/api/v1/projects", get(handlers::projects::list_projects))
.route("/api/v1/metering/usage", get(handlers::metering::get_usage))
// Whether the caller may use Prüfwerk at all: answered by the
// authentication and entitlement layers in front of it (a blocked
// member gets 403 MEMBER_BLOCKED), for the dashboard's sign-in check.
@@ -65,95 +34,84 @@ fn described_routes() -> OpenApiRouter {
post(handlers::support::open_session),
)
// Unified onboarding targets (#131).
.routes(routes!(
handlers::onboarding::list_targets,
handlers::onboarding::create_target
))
// Curated demo targets (D3).
.routes(routes!(
handlers::demo_seed::list_demo_targets,
handlers::demo_seed::seed_demo_targets
))
.routes(routes!(
handlers::onboarding::get_target,
handlers::onboarding::update_target,
handlers::onboarding::delete_target
))
.routes(routes!(handlers::onboarding::add_artifact))
.routes(routes!(handlers::onboarding::list_webhook_deliveries))
// The one route that takes large bodies — and it streams them to
// disk. Every other route keeps axum's 2 MiB default, so a JSON
// endpoint can no longer be sent a 512 MiB body to buffer.
.routes(
routes!(handlers::onboarding::upload_artifact).layer(DefaultBodyLimit::max(
.route(
"/api/v1/targets",
get(handlers::onboarding::list_targets).post(handlers::onboarding::create_target),
)
// Curated demo targets (D3). Registered before "/targets/{id}" for
// readability; the router matches the literal segment first either way.
.route(
"/api/v1/targets/demo-seed",
get(handlers::demo_seed::list_demo_targets)
.post(handlers::demo_seed::seed_demo_targets),
)
.route(
"/api/v1/targets/{id}",
get(handlers::onboarding::get_target)
.patch(handlers::onboarding::update_target)
.delete(handlers::onboarding::delete_target),
)
.route(
"/api/v1/targets/{id}/artifacts",
post(handlers::onboarding::add_artifact),
)
.route(
"/api/v1/targets/{id}/webhook-deliveries",
get(handlers::onboarding::list_webhook_deliveries),
)
.route(
"/api/v1/targets/{id}/artifacts/upload",
// The one route that takes large bodies — and it streams them to
// disk. Every other route keeps axum's 2 MiB default, so a JSON
// endpoint can no longer be sent a 512 MiB body to buffer.
post(handlers::onboarding::upload_artifact).layer(DefaultBodyLimit::max(
crate::targets::MAX_UPLOAD_BYTES as usize + MULTIPART_OVERHEAD,
)),
)
.routes(routes!(handlers::onboarding::set_archive_password))
.routes(routes!(handlers::onboarding::applicable_scans_for_target))
.routes(routes!(handlers::onboarding::detect_target))
.routes(routes!(handlers::onboarding::trigger_target_scan))
.routes(routes!(handlers::onboarding::swap_target_billing))
.routes(routes!(handlers::list_findings))
.routes(routes!(handlers::list_finding_variants))
.routes(routes!(handlers::get_finding))
.routes(routes!(handlers::update_finding_status))
.routes(routes!(handlers::bulk_update_finding_status))
.routes(routes!(handlers::update_finding_feedback))
// Undecided findings grouped by rule and file; one decision per group (#951).
.routes(routes!(handlers::finding_groups::list_finding_groups))
.routes(routes!(handlers::finding_groups::decide_finding_group))
// The "Heute" inbox (#950): open decisions in urgency buckets.
.route("/api/v1/inbox", get(handlers::inbox::get_inbox))
.route("/api/v1/inbox/decide", post(handlers::inbox::decide))
.route("/api/v1/inbox/undo", post(handlers::inbox::undo))
.route("/api/v1/inbox/snooze", post(handlers::inbox::snooze))
.route(
"/api/v1/inbox/snooze/{key}",
delete(handlers::inbox::unsnooze),
"/api/v1/targets/{id}/artifacts/{artifact_id}/archive-password",
put(handlers::onboarding::set_archive_password),
)
.route(
"/api/v1/targets/{id}/applicable-scans",
get(handlers::onboarding::applicable_scans_for_target),
)
.route(
"/api/v1/targets/{id}/detect",
post(handlers::onboarding::detect_target),
)
.route(
"/api/v1/targets/{id}/scan",
post(handlers::onboarding::trigger_target_scan),
)
.route("/api/v1/findings", get(handlers::list_findings))
.route(
"/api/v1/findings/variants",
get(handlers::list_finding_variants),
)
.route("/api/v1/findings/{id}", get(handlers::get_finding))
.route(
"/api/v1/findings/{id}/status",
patch(handlers::update_finding_status),
)
.route(
"/api/v1/findings/bulk-status",
patch(handlers::bulk_update_finding_status),
)
.route(
"/api/v1/findings/{id}/feedback",
patch(handlers::update_finding_feedback),
)
// VEX on a target's CVE alerts (#498).
.route(
"/api/v1/targets/{id}/cves",
get(handlers::vex::list_target_cves),
)
.route(
"/api/v1/targets/{id}/cve-matrix",
get(handlers::cve_matrix::target_cve_matrix),
)
// Open CVEs with a fix per day, and the updates closing most (#952).
.route(
"/api/v1/cve-history",
get(handlers::cve_history::cve_history),
)
.route(
"/api/v1/targets/{id}/top-updates",
get(handlers::cve_history::target_top_updates),
)
// What each scan changed, for the target's "Verlauf" (#957).
.route(
"/api/v1/targets/{id}/scan-changes",
get(handlers::scan_changes::target_scan_changes),
)
.route("/api/v1/targets/{id}/vex", get(handlers::vex::export_vex))
.route("/api/v1/targets/{id}/csaf", get(handlers::vex::export_csaf))
.route("/api/v1/targets/{id}/enisa", get(handlers::vex::list_enisa))
.route("/api/v1/cves/{id}/enisa", get(handlers::vex::export_enisa))
.route("/api/v1/cves/{id}/vex", patch(handlers::vex::set_cve_vex))
// The open CVE alerts grouped by component, one decision per group (#949).
.route(
"/api/v1/targets/{id}/cve-groups",
get(handlers::vex::list_cve_groups),
)
.route(
"/api/v1/targets/{id}/cve-groups/vex",
patch(handlers::vex::set_group_vex),
)
// The target's SBOM components per ecosystem (#957).
.route(
"/api/v1/targets/{id}/sbom-ecosystems",
get(handlers::sbom_ecosystems::list_sbom_ecosystems),
)
.route(
"/api/v1/targets/{id}/evidence-pack",
get(handlers::evidence::evidence_pack),
@@ -162,10 +120,6 @@ fn described_routes() -> OpenApiRouter {
"/api/v1/targets/{id}/compliance",
get(handlers::evidence::compliance_view),
)
.route(
"/api/v1/targets/{id}/finding-breakdown",
get(handlers::finding_breakdown::finding_breakdown),
)
.route(
"/api/v1/compliance/summary",
get(handlers::evidence::compliance_summary),
@@ -185,30 +139,31 @@ fn described_routes() -> OpenApiRouter {
handlers::manual_findings::MAX_IMPORT_BYTES,
)),
)
.routes(routes!(handlers::list_sbom))
.routes(routes!(handlers::sbom_filters))
.routes(routes!(handlers::export_sbom))
.routes(routes!(handlers::license_summary))
.routes(routes!(handlers::sbom_quality))
.routes(routes!(handlers::sbom_diff))
.route("/api/v1/sbom", get(handlers::list_sbom))
.route("/api/v1/sbom/filters", get(handlers::sbom_filters))
.route("/api/v1/sbom/export", get(handlers::export_sbom))
.route("/api/v1/sbom/licenses", get(handlers::license_summary))
.route("/api/v1/sbom/quality", get(handlers::sbom_quality))
.route("/api/v1/sbom/diff", get(handlers::sbom_diff))
// Licences the workspace confirms for its components.
.routes(routes!(
handlers::licenses::list_conclusions,
handlers::licenses::conclude,
handlers::licenses::withdraw
))
.route(
"/api/v1/licenses/conclusions",
get(handlers::licenses::list_conclusions)
.put(handlers::licenses::conclude)
.delete(handlers::licenses::withdraw),
)
// The licence policy, what it says about each component, and the
// legal review that resolves what it asks a review for.
.routes(routes!(
handlers::licenses::get_policy,
handlers::licenses::put_policy
))
.routes(routes!(handlers::licenses::check))
.routes(routes!(
handlers::licenses::review,
handlers::licenses::withdraw_review
))
.routes(routes!(handlers::licenses::notices))
.route(
"/api/v1/licenses/policy",
get(handlers::licenses::get_policy).put(handlers::licenses::put_policy),
)
.route("/api/v1/licenses/check", get(handlers::licenses::check))
.route(
"/api/v1/licenses/review",
post(handlers::licenses::review).delete(handlers::licenses::withdraw_review),
)
.route("/api/v1/sbom/notices", get(handlers::licenses::notices))
.route("/api/v1/issues", get(handlers::list_issues))
.route("/api/v1/scan-runs", get(handlers::list_scan_runs))
// MCP token management (per-tenant API tokens for the MCP server)
@@ -234,29 +189,59 @@ fn described_routes() -> OpenApiRouter {
delete(handlers::mcp_tokens::revoke_mcp_token),
)
// Graph API endpoints
.routes(routes!(handlers::graph::get_graph))
.routes(routes!(handlers::graph::get_nodes))
.routes(routes!(handlers::graph::get_summary))
.routes(routes!(handlers::graph::get_communities))
.routes(routes!(handlers::graph::get_impact))
.routes(routes!(handlers::graph::search_symbols))
.routes(routes!(handlers::graph::get_file_content))
.routes(routes!(handlers::graph::trigger_build))
.route("/api/v1/graph/{repo_id}", get(handlers::graph::get_graph))
.route(
"/api/v1/graph/{repo_id}/nodes",
get(handlers::graph::get_nodes),
)
.route(
"/api/v1/graph/{repo_id}/communities",
get(handlers::graph::get_communities),
)
.route(
"/api/v1/graph/{repo_id}/impact/{finding_id}",
get(handlers::graph::get_impact),
)
.route(
"/api/v1/graph/{repo_id}/search",
get(handlers::graph::search_symbols),
)
.route(
"/api/v1/graph/{repo_id}/file-content",
get(handlers::graph::get_file_content),
)
.route(
"/api/v1/graph/{repo_id}/build",
post(handlers::graph::trigger_build),
)
// DAST API endpoints
.routes(routes!(
handlers::dast::list_targets,
handlers::dast::add_target
))
.routes(routes!(handlers::dast::trigger_scan))
.routes(routes!(handlers::dast::list_scan_runs))
.routes(routes!(handlers::dast::list_findings))
.routes(routes!(handlers::dast::get_finding))
.route("/api/v1/dast/targets", get(handlers::dast::list_targets))
.route("/api/v1/dast/targets", post(handlers::dast::add_target))
.route(
"/api/v1/dast/targets/{id}/scan",
post(handlers::dast::trigger_scan),
)
.route(
"/api/v1/dast/scan-runs",
get(handlers::dast::list_scan_runs),
)
.route("/api/v1/dast/findings", get(handlers::dast::list_findings))
.route(
"/api/v1/dast/findings/{id}",
get(handlers::dast::get_finding),
)
// Chat / RAG API endpoints
.routes(routes!(handlers::chat::chat))
.routes(routes!(handlers::chat::build_embeddings))
.routes(routes!(handlers::chat::embedding_status))
.route("/api/v1/chat/{repo_id}", post(handlers::chat::chat))
.route(
"/api/v1/chat/{repo_id}/build-embeddings",
post(handlers::chat::build_embeddings),
)
.route(
"/api/v1/chat/{repo_id}/status",
get(handlers::chat::embedding_status),
)
// Help chat (documentation-grounded Q&A)
.routes(routes!(handlers::help_chat::help_chat))
.route("/api/v1/help/chat", post(handlers::help_chat::help_chat))
// CVE notification endpoints
.route(
"/api/v1/notifications",
@@ -338,140 +323,3 @@ fn described_routes() -> OpenApiRouter {
// them here on the API server would mismatch the handler
// signature, so the routes are not exported.
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use std::collections::BTreeSet;
use super::*;
/// The routes the description does not cover yet, as listed.
fn undescribed() -> BTreeSet<&'static str> {
include_str!("undescribed_routes.txt")
.lines()
.map(str::trim)
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.collect()
}
/// The paths of the plain route calls in this file (the ones without
/// `routes!`).
fn plain_routes() -> BTreeSet<String> {
let pattern = regex::Regex::new(r#"\.route\(\s*"([^"]+)""#).unwrap();
pattern
.captures_iter(include_str!("routes.rs"))
.map(|c| c[1].to_string())
.collect()
}
#[test]
fn every_route_is_described_or_listed_as_not_yet() {
let plain = plain_routes();
let listed = undescribed();
let unlisted: Vec<_> = plain
.iter()
.filter(|p| !listed.contains(p.as_str()))
.collect();
assert!(
unlisted.is_empty(),
"describe these routes with #[utoipa::path] and routes!(…): {unlisted:?}"
);
let stale: Vec<_> = listed.iter().filter(|p| !plain.contains(**p)).collect();
assert!(
stale.is_empty(),
"described or gone, delete from undescribed_routes.txt: {stale:?}"
);
}
#[test]
fn the_description_has_the_dast_routes_with_parameters_and_auth() {
let (_, api) = described_routes().split_for_parts();
let api = openapi::with_bearer_auth(api);
let doc: serde_json::Value = serde_json::from_str(&api.to_json().unwrap()).unwrap();
assert!(doc["openapi"].as_str().unwrap().starts_with("3.1"));
let paths = &doc["paths"];
for (path, method) in [
("/api/v1/dast/targets", "get"),
("/api/v1/dast/targets", "post"),
("/api/v1/dast/targets/{id}/scan", "post"),
("/api/v1/dast/scan-runs", "get"),
("/api/v1/dast/findings", "get"),
("/api/v1/dast/findings/{id}", "get"),
] {
let operation = &paths[path][method];
assert!(operation.is_object(), "{method} {path}");
assert_eq!(
operation["security"],
serde_json::json!([{ "bearer": [] }]),
"{method} {path}"
);
}
let id = &paths["/api/v1/dast/findings/{id}"]["get"]["parameters"][0];
assert_eq!(id["name"], "id");
assert_eq!(id["in"], "path");
let page: Vec<&str> = paths["/api/v1/dast/findings"]["get"]["parameters"]
.as_array()
.unwrap()
.iter()
.map(|p| p["name"].as_str().unwrap())
.collect();
assert_eq!(page, ["page", "limit"]);
let body = &paths["/api/v1/dast/targets"]["post"]["requestBody"]["content"];
assert!(body["application/json"].is_object(), "{body}");
assert_eq!(
doc["components"]["securitySchemes"]["bearer"]["scheme"],
"bearer"
);
}
/// Every described operation has a one-line summary (the first paragraph
/// of the handler's doc comment, without the route), and every `{name}`
/// in its path a path parameter of that name: a reader can call it from
/// the description alone.
#[test]
fn every_described_operation_is_complete() {
let (_, api) = described_routes().split_for_parts();
let doc: serde_json::Value = serde_json::from_str(&api.to_json().unwrap()).unwrap();
let placeholder = regex::Regex::new(r"\{([^}]+)\}").unwrap();
for (path, item) in doc["paths"].as_object().unwrap() {
for (method, operation) in item.as_object().unwrap() {
let summary = operation["summary"].as_str().unwrap_or_default();
assert!(
!summary.is_empty()
&& !summary.contains('\n')
&& !["GET ", "POST ", "PUT ", "PATCH ", "DELETE "]
.iter()
.any(|m| summary.starts_with(m))
&& !summary.contains("/api/"),
"{method} {path}: the summary is the doc comment's first line, \
a short sentence without the route: {summary:?}"
);
let in_path: Vec<&str> = operation["parameters"]
.as_array()
.into_iter()
.flatten()
.filter(|p| p["in"] == "path")
.filter_map(|p| p["name"].as_str())
.collect();
for name in placeholder.captures_iter(path) {
assert!(
in_path.contains(&&name[1]),
"{method} {path} has no path parameter {}",
&name[1]
);
}
}
}
}
#[test]
fn the_description_is_behind_the_customer_authentication() {
assert!(!compliance_core::auth::bypasses_customer_auth(
openapi::SPEC_PATH
));
}
}
@@ -1,64 +0,0 @@
# Routes of the customer API (routes.rs) that the OpenAPI description does
# not cover yet (#1006), one path per line. A test fails when a plain
# `.route("...")` in routes.rs is missing here, or when a line here names no
# such route, so the list only ever shrinks. Describe a route with
# `#[utoipa::path]` and `.routes(routes!(...))`, then delete its line.
/api/v1/health
/api/v1/oscal/assess
/api/v1/stats/overview
/api/v1/projects
/api/v1/metering/usage
/api/v1/access
/api/v1/git-source
/api/v1/support/tenants
/api/v1/support/session
/api/v1/inbox
/api/v1/inbox/decide
/api/v1/inbox/undo
/api/v1/inbox/snooze
/api/v1/inbox/snooze/{key}
/api/v1/targets/{id}/cves
/api/v1/targets/{id}/cve-matrix
/api/v1/cve-history
/api/v1/targets/{id}/top-updates
/api/v1/targets/{id}/scan-changes
/api/v1/targets/{id}/vex
/api/v1/targets/{id}/csaf
/api/v1/targets/{id}/enisa
/api/v1/cves/{id}/enisa
/api/v1/cves/{id}/vex
/api/v1/targets/{id}/cve-groups
/api/v1/targets/{id}/cve-groups/vex
/api/v1/targets/{id}/sbom-ecosystems
/api/v1/targets/{id}/evidence-pack
/api/v1/targets/{id}/compliance
/api/v1/targets/{id}/finding-breakdown
/api/v1/compliance/summary
/api/v1/controls
/api/v1/targets/{id}/findings
/api/v1/targets/{id}/findings/import
/api/v1/issues
/api/v1/scan-runs
/api/v1/mcp-servers
/api/v1/mcp-servers/{id}
/api/v1/mcp-servers/{id}/token
/api/v1/mcp-tokens
/api/v1/mcp-tokens/{id}
/api/v1/notifications
/api/v1/notifications/count
/api/v1/notifications/read-all
/api/v1/notifications/{id}/read
/api/v1/notifications/{id}/dismiss
/api/v1/pentest/lookup-repo
/api/v1/pentest/sessions
/api/v1/pentest/sessions/{id}
/api/v1/pentest/sessions/{id}/chat
/api/v1/pentest/sessions/{id}/stop
/api/v1/pentest/sessions/{id}/pause
/api/v1/pentest/sessions/{id}/resume
/api/v1/pentest/sessions/{id}/stream
/api/v1/pentest/sessions/{id}/attack-chain
/api/v1/pentest/sessions/{id}/messages
/api/v1/pentest/sessions/{id}/findings
/api/v1/pentest/sessions/{id}/export
/api/v1/pentest/stats
+2
View File
@@ -87,6 +87,8 @@ fn build_config(app_env: AppEnv) -> Result<AgentConfig, AgentError> {
.unwrap_or_else(|| "/data/compliance-scanner/artifacts".to_string()),
keycloak_url: env_var_opt("KEYCLOAK_URL"),
keycloak_realm: env_var_opt("KEYCLOAK_REALM"),
keycloak_admin_username: env_var_opt("KEYCLOAK_ADMIN_USERNAME"),
keycloak_admin_password: env_secret_opt("KEYCLOAK_ADMIN_PASSWORD"),
pentest_verification_email: env_var_opt("PENTEST_VERIFICATION_EMAIL"),
pentest_imap_host: env_var_opt("PENTEST_IMAP_HOST"),
pentest_imap_port: env_var_opt("PENTEST_IMAP_PORT").and_then(|p| p.parse().ok()),
+2 -4
View File
@@ -98,9 +98,7 @@ pub async fn triage_repo_findings(
// to decide.
TriageOutcome::NeedsReview => {
finding.status = FindingStatus::NeedsReview;
finding.triage_action = Some(
compliance_core::models::finding::TRIAGE_CONTROL_NOT_CONFIRMED.to_string(),
);
finding.triage_action = Some("control_not_confirmed".to_string());
finding.triage_rationale.get_or_insert_with(|| {
"The control check did not confirm the CRA requirements this \
finding maps to. Please review whether it is a real issue."
@@ -217,7 +215,7 @@ pub async fn grounded_surface_findings(
/// Read a window of lines around `line` (1-based) from `repo_path/file`.
fn fetch_region(repo_path: &Path, file: &str, line: u32) -> Option<CandidateRegion> {
let content = compliance_core::encoding::read_source(&repo_path.join(file)).ok()?;
let content = std::fs::read_to_string(repo_path.join(file)).ok()?;
let lines: Vec<&str> = content.lines().collect();
if lines.is_empty() {
return None;
+3 -22
View File
@@ -116,8 +116,8 @@ pub const SURFACES: &[Surface] = &[
/// Source file extensions worth reading (skip binaries/assets/lockfiles).
const CODE_EXTS: &[&str] = &[
"py", "js", "ts", "tsx", "jsx", "go", "java", "rb", "php", "rs", "cs", "vb", "kt", "c", "h",
"cc", "cpp", "hpp",
"py", "js", "ts", "tsx", "jsx", "go", "java", "rb", "php", "rs", "cs", "kt", "c", "h", "cc",
"cpp", "hpp",
];
/// Directories never worth walking.
const SKIP_DIRS: &[&str] = &[
@@ -156,8 +156,7 @@ pub fn retrieve(repo_path: &Path, terms: &[&str], excluded: &[String]) -> Vec<Ca
if !meta.is_file() || meta.len() > MAX_FILE_BYTES {
continue;
}
// UTF-8, UTF-16 with a BOM, or Windows-1252; a binary is skipped.
let Ok(content) = compliance_core::encoding::read_source(path) else {
let Ok(content) = std::fs::read_to_string(path) else {
continue;
};
let rel = path
@@ -287,24 +286,6 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_windows_1252_file_is_read() {
let dir = std::env::temp_dir().join(format!("surface-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
// "Prüfung" as Windows-1252 writes it: 0xFC for "ü".
let path = dir.join("app/Auth.cs");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(
&path,
b"// Pr\xFCfung\nbool Login(string u, string p) { }\n",
)
.unwrap();
let regions = retrieve(&dir, terms_for("cra-ai-11"), &[]);
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(regions.len(), 1);
assert!(regions[0].content.contains("Prüfung"));
}
#[test]
fn firmware_update_code_is_read_but_not_the_vendor_hal() {
let dir = std::env::temp_dir().join(format!("surface-{}", uuid::Uuid::new_v4()));
-19
View File
@@ -618,19 +618,6 @@ impl Database {
)
.await?;
// inbox_snoozes (#950): one per card key, and the resubmissions due
self.inbox_snoozes()
.create_index(
IndexModel::builder()
.keys(doc! { "key": 1 })
.options(IndexOptions::builder().unique(true).build())
.build(),
)
.await?;
self.inbox_snoozes()
.create_index(IndexModel::builder().keys(doc! { "until": 1 }).build())
.await?;
tracing::info!("Database indexes ensured");
Ok(())
}
@@ -798,12 +785,6 @@ impl Database {
self.inner.collection("werkbank_jobs")
}
/// The cards of the "Heute" inbox put off until a date (#950).
pub fn inbox_snoozes(&self) -> Collection<compliance_core::models::inbox::InboxSnooze> {
self.inner
.collection(compliance_core::models::inbox::SNOOZES_COLLECTION)
}
#[allow(dead_code)]
pub fn raw_collection(&self, name: &str) -> Collection<mongodb::bson::Document> {
self.inner.collection(name)
+1 -1
View File
@@ -20,7 +20,7 @@ use crate::fixtures::{DemoTarget, DemoTargets, FixtureError};
use crate::targets;
/// What the caller asked to seed.
#[derive(Debug, Clone, Default, Deserialize, utoipa::ToSchema)]
#[derive(Debug, Clone, Default, Deserialize)]
pub struct SeedRequest {
/// Manifest keys to seed; empty seeds every target.
#[serde(default)]
+1 -27
View File
@@ -72,12 +72,11 @@ pub enum SbomCoverage {
}
/// The tools that check a target's components rather than its code.
const COMPONENT_TOOLS: [&str; 6] = [
const COMPONENT_TOOLS: [&str; 5] = [
"syft",
"osv",
"dotnet-lifecycle",
"build-lifecycle",
compliance_core::models::SBOM_COVERAGE_SCANNER,
"yocto-release",
];
@@ -514,31 +513,6 @@ mod tests {
);
}
#[test]
fn an_sbom_coverage_finding_is_evidence_against_the_sbom_requirement() {
let map = ControlMap::cra().expect("map");
let mut f = finding(SBOM_CONTROL, FindingStatus::Open);
f.scanner = compliance_core::models::SBOM_COVERAGE_SCANNER.into();
f.rule_id = Some("sbom-dependencies-unresolved".into());
let unresolved = SbomCoverage::Unresolved(vec!["Cargo.toml".into()]);
let statuses = control_statuses(&map, &[f], Some(&python()), &[], &unresolved);
let sbom = status_of(&statuses, SBOM_CONTROL);
assert_eq!(sbom.state, ControlState::NotSatisfied);
assert_eq!(sbom.findings.len(), 1);
// The CVE controls still say why their components were not checked.
for control in ["cra-ai-22", "cra-ai-33"] {
assert_eq!(
status_of(&statuses, control).reason,
Some(NotAssessedReason::DependenciesUnresolved {
manifests: vec!["Cargo.toml".into()]
}),
"{control}"
);
}
}
#[test]
fn a_failed_cve_lookup_claims_nothing_about_component_cves() {
let map = ControlMap::cra().expect("map");
+8 -149
View File
@@ -12,9 +12,6 @@ pub enum SourceAction {
/// A push to the default branch: scan the target, creating it first if
/// the `created` delivery was lost.
Push(GiteaRepo),
/// A person closed or reopened an issue (#953): carry it over to the
/// finding or CVE the issue was opened for, if Prüfwerk opened it.
Issue(IssueEvent),
/// Nothing to do, and why.
Ignore(&'static str),
}
@@ -24,40 +21,11 @@ impl SourceAction {
pub fn repo(&self) -> Option<&GiteaRepo> {
match self {
Self::Created(repo) | Self::Deleted(repo) | Self::Push(repo) => Some(repo),
Self::Issue(event) => Some(&event.repo),
Self::Ignore(_) => None,
}
}
}
/// What happened to an issue.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IssueChange {
Closed,
Reopened,
}
/// An issue closed or reopened in a repository of the organisation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IssueEvent {
pub repo: GiteaRepo,
/// The issue number in the repository (`TrackerIssue::external_id`).
pub number: i64,
pub change: IssueChange,
/// The login of the user who closed or reopened it.
pub sender: String,
}
/// Whether Prüfwerk itself caused an issue event: the sender is the issue's
/// author. Prüfwerk opens its issues as the source's bot user and closes and
/// reopens them as that user, so an author acting on their own issue is the
/// bot. The bot token cannot read its own user (`read:user` is not among its
/// scopes), so the author stands in for it. Gitea logins are
/// case-insensitive.
pub fn is_own_event(sender: &str, author: &str) -> bool {
!sender.is_empty() && sender.eq_ignore_ascii_case(author)
}
/// A branch deletion pushes this as the new head.
const ZERO_SHA: &str = "0000000000000000000000000000000000000000";
@@ -65,16 +33,19 @@ const ZERO_SHA: &str = "0000000000000000000000000000000000000000";
/// organisation. Repositories of any other owner are ignored, so a system
/// webhook (which sees the whole instance) is safe to use.
pub fn route_event(event: &str, payload: &serde_json::Value, org: &str) -> SourceAction {
if !super::WEBHOOK_EVENTS.contains(&event) {
return SourceAction::Ignore("event not handled");
}
let Some(repo) = payload
.get("repository")
.cloned()
.and_then(|r| serde_json::from_value::<GiteaRepo>(r).ok())
else {
return SourceAction::Ignore("payload without a repository");
return match event {
"repository" | "push" => SourceAction::Ignore("payload without a repository"),
_ => SourceAction::Ignore("event not handled"),
};
};
if !matches!(event, "repository" | "push") {
return SourceAction::Ignore("event not handled");
}
if !repo.in_org(org) {
return SourceAction::Ignore("repository outside the configured organisation");
}
@@ -84,7 +55,6 @@ pub fn route_event(event: &str, payload: &serde_json::Value, org: &str) -> Sourc
Some("deleted") => SourceAction::Deleted(repo),
_ => SourceAction::Ignore("repository action not handled"),
},
"issues" => route_issue(payload, repo),
_ => {
let git_ref = payload.get("ref").and_then(|r| r.as_str()).unwrap_or("");
let after = payload.get("after").and_then(|a| a.as_str()).unwrap_or("");
@@ -99,41 +69,6 @@ pub fn route_event(event: &str, payload: &serde_json::Value, org: &str) -> Sourc
}
}
/// Route an `issues` delivery of `repo`: a close or reopen by someone other
/// than Prüfwerk's bot user.
fn route_issue(payload: &serde_json::Value, repo: GiteaRepo) -> SourceAction {
let change = match payload.get("action").and_then(|a| a.as_str()) {
Some("closed") => IssueChange::Closed,
Some("reopened") => IssueChange::Reopened,
_ => return SourceAction::Ignore("issue action not handled"),
};
let issue = payload.get("issue");
let Some(number) = payload
.get("number")
.or_else(|| issue.and_then(|i| i.get("number")))
.and_then(serde_json::Value::as_i64)
else {
return SourceAction::Ignore("issue without a number");
};
// `user.login` of the sender and of the issue's author.
let login = |user: Option<&serde_json::Value>| {
user.and_then(|u| u.get("login"))
.and_then(|l| l.as_str())
.unwrap_or_default()
.to_string()
};
let sender = login(payload.get("sender"));
if is_own_event(&sender, &login(issue.and_then(|i| i.get("user")))) {
return SourceAction::Ignore("issue changed by Prüfwerk's bot user");
}
SourceAction::Issue(IssueEvent {
repo,
number,
change,
sender,
})
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
@@ -226,7 +161,7 @@ mod tests {
);
assert_eq!(
route_event("issues", &json!({}), "kunde"),
SourceAction::Ignore("payload without a repository")
SourceAction::Ignore("event not handled")
);
assert_eq!(
route_event("push", &json!({ "ref": "refs/heads/main" }), "kunde"),
@@ -237,80 +172,4 @@ mod tests {
SourceAction::Ignore("event not handled")
);
}
fn issue_event(action: &str, sender: &str, author: &str) -> serde_json::Value {
json!({
"action": action, "number": 12,
"issue": { "number": 12, "state": "closed", "user": { "login": author } },
"sender": { "login": sender },
"repository": repository("kunde"),
})
}
#[test]
fn a_person_closing_or_reopening_an_issue_is_carried_over() {
let closed = issue_event("closed", "dev-anna", "pruefwerk");
match route_event("issues", &closed, "kunde") {
SourceAction::Issue(e) => assert_eq!(
(e.repo.id, e.number, e.change, e.sender.as_str()),
(42, 12, IssueChange::Closed, "dev-anna")
),
other => panic!("{other:?}"),
}
let reopened = issue_event("reopened", "dev-anna", "pruefwerk");
assert!(matches!(
route_event("issues", &reopened, "kunde"),
SourceAction::Issue(IssueEvent {
change: IssueChange::Reopened,
..
})
));
// The number from the issue when the payload has none on top.
let mut p = issue_event("closed", "dev-anna", "pruefwerk");
p.as_object_mut().unwrap().remove("number");
assert!(matches!(
route_event("issues", &p, "kunde"),
SourceAction::Issue(IssueEvent { number: 12, .. })
));
}
#[test]
fn pruefwerks_own_changes_are_ignored_so_nothing_loops() {
// The bot closed or reopened the issue it opened.
for action in ["closed", "reopened"] {
let p = issue_event(action, "pruefwerk", "pruefwerk");
assert_eq!(
route_event("issues", &p, "kunde"),
SourceAction::Ignore("issue changed by Prüfwerk's bot user")
);
}
assert!(is_own_event("Pruefwerk", "pruefwerk"));
assert!(!is_own_event("dev-anna", "pruefwerk"));
// A payload without a sender is not taken for the bot's.
assert!(!is_own_event("", ""));
}
#[test]
fn other_issue_events_are_ignored() {
for action in ["opened", "edited", "label_updated", "assigned"] {
let p = issue_event(action, "dev-anna", "pruefwerk");
assert_eq!(
route_event("issues", &p, "kunde"),
SourceAction::Ignore("issue action not handled")
);
}
let mut p = issue_event("closed", "dev-anna", "pruefwerk");
p.as_object_mut().unwrap().remove("number");
p["issue"].as_object_mut().unwrap().remove("number");
assert_eq!(
route_event("issues", &p, "kunde"),
SourceAction::Ignore("issue without a number")
);
let mut p = issue_event("closed", "dev-anna", "pruefwerk");
p["repository"] = repository("andere");
assert_eq!(
route_event("issues", &p, "kunde"),
SourceAction::Ignore("repository outside the configured organisation")
);
}
}
-27
View File
@@ -34,10 +34,6 @@ use gitea::{GiteaRepo, RepoLister, SourceClient};
pub const DEFAULT_HOST_PATTERN: &str = r"^[a-z0-9-]+\.code(-stage)?\.breakpilot\.com$";
/// Minutes between syncs unless `GIT_SOURCE_SYNC_MINUTES` says otherwise.
pub const DEFAULT_SYNC_MINUTES: u64 = 30;
/// The Gitea events the organisation or system webhook must send: Prüfwerk
/// cannot register or change the webhook itself (the bot has no
/// administration rights), so the platform API names them for provisioning.
pub const WEBHOOK_EVENTS: [&str; 3] = ["repository", "push", "issues"];
/// The webhook path of a tenant's source, below the webhook server's origin.
pub fn webhook_path(tenant_id: &str) -> String {
format!("/webhook/{tenant_id}/gitea-source")
@@ -458,11 +454,6 @@ pub enum Outcome {
Ensured { target_id: String, scan: bool },
/// The repository's target was archived (`false`: there was none).
Archived(bool),
/// An issue closed or reopened in Gitea was carried back (#953).
Issue {
target_id: String,
detail: &'static str,
},
/// Nothing done.
Ignored(&'static str),
}
@@ -504,24 +495,6 @@ pub async fn apply_action(
scan: true,
})
}
SourceAction::Issue(event) => {
// Only the repository's existing target: an issue event never
// creates one.
let Some(target_id) = db
.onboarded_targets()
.find_one(repo_filter(&source.base_url, event.repo.id))
.await?
.and_then(|t| t.id)
else {
return Ok(Outcome::Ignored("repository has no target"));
};
let target_id = target_id.to_hex();
let done = crate::pipeline::issue_backsync::apply(db, &target_id, &event).await?;
Ok(Outcome::Issue {
target_id,
detail: done.detail(event.change),
})
}
}
}
+1 -1
View File
@@ -102,7 +102,7 @@ pub fn normalise_cwe(raw: &str) -> Option<String> {
/// The CRA controls a verified weakness is evidence for (see
/// [`control_map::ControlMap::controls_for_cwe`]).
pub(crate) fn control_refs(cwe: &str) -> Vec<String> {
fn control_refs(cwe: &str) -> Vec<String> {
control_map::ControlMap::cra()
.map(|map| {
map.controls_for_cwe(cwe)
+10 -43
View File
@@ -43,15 +43,14 @@ struct OrphanRule {
}
/// Code scans are what customers see, so they get their own `interrupted`
/// status, also those still waiting for a slot: the queue lives in the agent's
/// memory and is gone after a restart (t84). The rest close as `failed` with [`INTERRUPTED_MESSAGE`]: DAST and
/// status. The rest close as `failed` with [`INTERRUPTED_MESSAGE`]: DAST and
/// pentest are off in production, and graph and embedding builds are steps of
/// a scan. A paused pentest session can only be resumed through in-memory
/// state, so after a restart it is as dead as a running one.
const ORPHAN_RULES: [OrphanRule; 5] = [
OrphanRule {
collection: "scan_runs",
open: &["queued", "running"],
open: &["running"],
closed_as: "interrupted",
},
OrphanRule {
@@ -219,16 +218,12 @@ async fn targets_to_resume(
.await?;
let mut out = Vec::new();
for id in ids.iter().filter_map(|v| v.as_str()) {
// Only scans that had started count: one interrupted while it still
// waited for a slot cannot be what stopped the agent. It never got a
// start time of its own, so it still starts when it was requested.
let interruptions = db
.scan_runs()
.count_documents(doc! {
"repo_id": id,
"status": "interrupted",
"completed_at": { "$gte": window },
"$expr": { "$ne": ["$started_at", "$queued_at"] },
})
.await?;
if interruptions > MAX_RECENT_INTERRUPTIONS {
@@ -248,25 +243,12 @@ async fn targets_to_resume(
.await?;
if active > 0 {
// Resumed as it was started: a scan a person started runs even when
// nothing changed since the last completed one (#465). Of a running
// scan and its queued follow-up, a person's wins.
let triggers = db
// nothing changed since the last completed one (#465).
let trigger = db
.scan_runs()
.distinct(
"trigger",
doc! { "repo_id": id, "status": "interrupted", "completed_at": closed },
)
.await?;
let triggers: Vec<ScanTrigger> = triggers
.into_iter()
.filter_map(|t| mongodb::bson::from_bson(t).ok())
.collect();
let trigger = triggers
.iter()
.find(|t| t.started_by_person())
.or_else(|| triggers.first())
.cloned()
.unwrap_or(ScanTrigger::Scheduled);
.find_one(doc! { "repo_id": id, "status": "interrupted", "completed_at": closed })
.await?
.map_or(ScanTrigger::Scheduled, |run| run.trigger);
out.push((id.to_string(), trigger));
}
}
@@ -383,11 +365,10 @@ mod tests {
let archived = insert(archived_target).await;
let earlier_only = insert(target("earlier-only")).await;
// Arrange: runs left open, plus one interrupted an hour ago. The
// target to resume has a scheduled scan running and a person's
// follow-up queued (t84): one interruption, resumed as the person's.
// Arrange: runs left open, plus one interrupted an hour ago.
// The scan to resume was started by a person.
for (id, trigger) in [
(&resumes, ScanTrigger::Scheduled),
(&resumes, ScanTrigger::Manual),
(&looping, ScanTrigger::Scheduled),
(&archived, ScanTrigger::Scheduled),
] {
@@ -396,10 +377,6 @@ mod tests {
.await
.unwrap();
}
db.scan_runs()
.insert_one(ScanRun::queued(resumes.clone(), ScanTrigger::Manual))
.await
.unwrap();
for id in [&looping, &earlier_only] {
let mut run = ScanRun::new(id.clone(), ScanTrigger::Scheduled);
run.status = compliance_core::models::ScanRunStatus::Interrupted;
@@ -446,16 +423,6 @@ mod tests {
}
}
#[test]
fn queued_code_scans_are_closed_at_startup_too() {
let scan_rule = ORPHAN_RULES
.iter()
.find(|r| r.collection == "scan_runs")
.expect("scan_runs rule");
assert!(scan_rule.open.contains(&"queued"));
assert!(scan_rule.open.contains(&"running"));
}
#[test]
fn code_scans_are_interrupted_not_failed() {
let scan_rule = ORPHAN_RULES
+20 -67
View File
@@ -1,7 +1,7 @@
use std::collections::HashMap;
use std::fmt;
use compliance_core::models::{Exploitation, Finding, FindingStatus, ReviewReason, Severity};
use compliance_core::models::{Exploitation, Finding, FindingStatus, Severity};
use serde::{Deserialize, Deserializer};
use serde_json::Value;
@@ -72,7 +72,7 @@ const RESPONSE_SAMPLE_CHARS: usize = 500;
/// `triage_action` of a finding the LLM triage gave no verdict; the reason is
/// in `triage_rationale`, which starts with `skipped: <reason>`.
pub const SKIPPED_ACTION: &str = compliance_core::models::finding::TRIAGE_SKIPPED;
pub const SKIPPED_ACTION: &str = "skipped";
/// The model the triage asks. A trait so tests can drive the triage with a
/// fake model.
@@ -823,12 +823,12 @@ fn drop_trailing_comma(json: &mut String) {
/// A dismissed or low-confidence finding is kept as
/// [`FindingStatus::NeedsReview`], never deleted: the model's rationale goes
/// with it, and a person decides.
///
/// Which of the two it was is read back from the stored verdict
/// ([`Finding::review_reason`]), so the decision lives in one place
/// ([`ReviewReason::of_verdict`]).
fn apply_action(finding: &mut Finding, action: &str, adjusted_confidence: f64) -> Outcome {
match action {
"dismiss" => {
finding.status = FindingStatus::NeedsReview;
Outcome::Dismissed
}
"downgrade" => {
finding.severity = downgrade_severity(&finding.severity);
finding.status = FindingStatus::Triaged;
@@ -839,31 +839,29 @@ fn apply_action(finding: &mut Finding, action: &str, adjusted_confidence: f64) -
finding.status = FindingStatus::Triaged;
Outcome::Upgraded
}
// "dismiss", "confirm" or unknown: triaged when the model is sure it
// is real, else left to a person.
_ => match ReviewReason::of_verdict(action, adjusted_confidence) {
Some(reason) => {
finding.status = FindingStatus::NeedsReview;
match reason {
ReviewReason::LikelyFalseAlarm => Outcome::Dismissed,
ReviewReason::Unsure => Outcome::LowConfidence,
}
}
None => {
finding.status = FindingStatus::Triaged;
Outcome::Confirmed
}
},
// "confirm" or unknown: kept as reported when the model is confident.
_ if adjusted_confidence >= CONFIDENCE_THRESHOLD => {
finding.status = FindingStatus::Triaged;
Outcome::Confirmed
}
_ => {
finding.status = FindingStatus::NeedsReview;
Outcome::LowConfidence
}
}
}
/// Least confidence (after [`adjust_confidence`]) at which a confirmed
/// finding counts as triaged; below it the finding needs review.
const CONFIDENCE_THRESHOLD: f64 = 3.0;
/// Read ~50 lines of surrounding code from the file at the finding's location
fn read_surrounding_context(finding: &Finding) -> Option<String> {
let file_path = finding.file_path.as_deref()?;
let line = finding.line_number? as usize;
// Try to read the file — this works because the repo is cloned locally
let content = compliance_core::encoding::read_source(std::path::Path::new(file_path)).ok()?;
let content = std::fs::read_to_string(file_path).ok()?;
let lines: Vec<&str> = content.lines().collect();
let start = line.saturating_sub(25);
@@ -1106,51 +1104,6 @@ mod tests {
assert_eq!(unsure.status, FindingStatus::NeedsReview);
}
/// A verdict of the model on finding 1.
fn model_verdict(action: &str, confidence: f64) -> TriageResult {
TriageResult {
id: Some("1".into()),
action: action.into(),
confidence,
rationale: "why".into(),
remediation: None,
}
}
#[test]
fn a_finding_kept_for_review_says_why() {
let mut dismissed = finding();
assert_eq!(
apply_verdict(&mut dismissed, &model_verdict("dismiss", 9.0)),
Outcome::Dismissed
);
assert_eq!(
dismissed.review_reason(),
Some(ReviewReason::LikelyFalseAlarm)
);
assert_eq!(dismissed.triage_rationale.as_deref(), Some("why"));
let mut unsure = finding();
assert_eq!(
apply_verdict(&mut unsure, &model_verdict("confirm", 2.0)),
Outcome::LowConfidence
);
assert_eq!(unsure.review_reason(), Some(ReviewReason::Unsure));
// Test code halves the confidence: a 5 there is unsure.
let mut in_tests = finding();
in_tests.file_path = Some("src/tests/buffer.c".into());
assert_eq!(
apply_verdict(&mut in_tests, &model_verdict("confirm", 5.0)),
Outcome::LowConfidence
);
assert_eq!(in_tests.review_reason(), Some(ReviewReason::Unsure));
let mut confirmed = finding();
apply_verdict(&mut confirmed, &model_verdict("confirm", 7.0));
assert_eq!(confirmed.review_reason(), None);
}
#[test]
fn confirmed_and_rerated_findings_pass() {
let mut f = finding();
+4 -156
View File
@@ -20,8 +20,7 @@ use futures_util::TryStreamExt;
use mongodb::bson::{doc, oid::ObjectId, Document};
use compliance_core::models::{
check_swap, split_included, BillableTarget, DayUsage, IncludedChoice, MonthUsage, PlanLimits,
RunCharge, SwapRefusal, TargetBilling,
split_included, BillableTarget, DayUsage, MonthUsage, PlanLimits, RunCharge, TargetBilling,
};
use crate::database::Database;
@@ -46,12 +45,12 @@ pub async fn assign_billing(
db: &Database,
included: Option<u32>,
) -> Result<Vec<(ObjectId, TargetBilling)>, AgentError> {
// Only the fields the split needs: a whole target holds its artifacts,
// and older documents may lack fields the model requires.
// Only the three fields the split needs: a whole target holds its
// artifacts, and older documents may lack fields the model requires.
let docs: Vec<Document> = db
.raw_collection("onboarded_targets")
.find(doc! { "archived_at": null })
.projection(doc! { "_id": 1, "created_at": 1, "billing": 1, "included_choice": 1 })
.projection(doc! { "_id": 1, "created_at": 1, "billing": 1 })
.await?
.try_collect()
.await?;
@@ -91,89 +90,9 @@ fn billable(target: &Document) -> Option<BillableTarget<ObjectId>> {
.get("billing")
.and_then(|b| mongodb::bson::from_bson(b.clone()).ok())
.unwrap_or_default(),
choice: target
.get("included_choice")
.and_then(|c| mongodb::bson::from_bson(c.clone()).ok()),
})
}
/// The first instant after the calendar month (Europe/Berlin) of `at`: until
/// then a target swapped in at `at` stays included.
pub fn end_of_berlin_month(at: DateTime<Utc>) -> DateTime<Utc> {
use chrono::{Datelike, TimeZone};
let local = at.with_timezone(&chrono_tz::Europe::Berlin);
let (year, month) = if local.month() == 12 {
(local.year() + 1, 1)
} else {
(local.year(), local.month() + 1)
};
// Midnight is never skipped or repeated in Berlin (DST changes at 2–3 h).
chrono_tz::Europe::Berlin
.with_ymd_and_hms(year, month, 1, 0, 0, 0)
.earliest()
.map_or(at, |next| next.with_timezone(&Utc))
}
/// Swap the extra target `incoming` with the included target `outgoing`
/// (t72): the one swapped in stays included until the end of the calendar
/// month, the other becomes extra. It records the customer's choice; the
/// next [`assign_billing`] (which the caller runs) moves the billing.
///
/// # Arguments
///
/// * `limited` - Whether the plan limits the included targets.
///
/// # Returns
///
/// `None` when either target is not an active one of the tenant; else
/// whether the swap was made, or why not.
///
/// # Errors
///
/// Returns an error if the targets cannot be read or updated.
pub async fn swap(
db: &Database,
incoming: ObjectId,
outgoing: ObjectId,
limited: bool,
at: DateTime<Utc>,
) -> Result<Option<Result<(), SwapRefusal>>, AgentError> {
let targets = db.onboarded_targets();
let active = |id: ObjectId| doc! { "_id": id, "archived_at": null };
let (Some(swapped_in), Some(swapped_out)) = (
targets.find_one(active(incoming)).await?,
targets.find_one(active(outgoing)).await?,
) else {
return Ok(None);
};
let locked = swapped_out.included_until.is_some_and(|until| until > at);
if let Err(refusal) = check_swap(limited, swapped_in.billing, swapped_out.billing, locked) {
return Ok(Some(Err(refusal)));
}
let to_bson = |v: IncludedChoice| {
mongodb::bson::to_bson(&v).map_err(|e| AgentError::Other(e.to_string()))
};
targets
.update_one(
doc! { "_id": incoming },
doc! { "$set": {
"included_choice": to_bson(IncludedChoice::Included)?,
"included_until": mongodb::bson::DateTime::from_chrono(end_of_berlin_month(at)),
} },
)
.await?;
targets
.update_one(
doc! { "_id": outgoing },
doc! {
"$set": { "included_choice": to_bson(IncludedChoice::Extra)? },
"$unset": { "included_until": "" },
},
)
.await?;
Ok(Some(Ok(())))
}
/// The tenant's plan as metering reads it from the registry.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Plan {
@@ -397,80 +316,11 @@ pub async fn record_extra_peak(
Ok(Some(peak))
}
/// The tenant's metering this month, for the dashboard (t72).
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
pub struct MonthSummary {
/// The calendar month in Europe/Berlin, `YYYY-MM`.
pub month: String,
/// Counted Prüfungen charged to the quota.
pub pruefungen: u32,
/// Prüftage booked.
pub prueftage: u32,
/// Active targets that are extra now.
pub extra_targets: u32,
/// The highest number of extra targets at once this month, which the
/// extra-target line bills.
pub extra_peak: u32,
}
/// What the tenant used in the month of `at`.
///
/// # Errors
///
/// Returns an error if the counters or the targets cannot be read.
pub async fn month_summary(db: &Database, at: DateTime<Utc>) -> Result<MonthSummary, AgentError> {
let (month, _) = berlin_period(at);
let stored = db
.raw_collection(MONTHS)
.find_one(doc! { "_id": &month })
.await?;
let extra = mongodb::bson::to_bson(&TargetBilling::Extra)
.map_err(|e| AgentError::Other(e.to_string()))?;
let extra_targets = db
.onboarded_targets()
.count_documents(doc! { "archived_at": null, "billing": extra })
.await?;
let extra_targets = u32::try_from(extra_targets).unwrap_or(u32::MAX);
Ok(MonthSummary {
month,
pruefungen: count(stored.as_ref(), "pruefungen"),
prueftage: count(stored.as_ref(), "prueftage"),
extra_targets,
// The peak is recorded when the billing is refreshed; until then
// it is at least what is extra now.
extra_peak: count(stored.as_ref(), "extra_peak").max(extra_targets),
})
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::TimeZone;
#[test]
fn a_swap_holds_until_the_berlin_month_ends() {
let at = |y, m, d, h| {
Utc.with_ymd_and_hms(y, m, d, h, 0, 0)
.single()
.expect("valid")
};
// 1 Dec 00:00 in Berlin (CET) is 30 Nov 23:00 UTC.
assert_eq!(
end_of_berlin_month(at(2026, 11, 6, 9)),
at(2026, 11, 30, 23)
);
// December rolls into January of the next year.
assert_eq!(
end_of_berlin_month(at(2026, 12, 15, 9)),
at(2026, 12, 31, 23)
);
// 1 Aug 00:00 in Berlin (CEST) is 31 Jul 22:00 UTC.
assert_eq!(
end_of_berlin_month(at(2026, 7, 31, 21)),
at(2026, 7, 31, 22)
);
}
#[test]
fn periods_are_calendar_ones_in_berlin() {
let at = |y, m, d, h, min| {
@@ -518,7 +368,6 @@ mod tests {
id,
created_at: at.to_chrono(),
billing: TargetBilling::Extra,
choice: None,
})
);
assert_eq!(
@@ -527,7 +376,6 @@ mod tests {
id,
created_at: DateTime::<Utc>::MIN_UTC,
billing: TargetBilling::Included,
choice: None,
})
);
assert_eq!(billable(&doc! { "name": "no id" }), None);
File diff suppressed because it is too large. Load diff
+48 -57
View File
@@ -14,7 +14,6 @@ use crate::database::Database;
use crate::llm::{
ChatMessage, LlmClient, LlmResponse, ToolCallRequest, ToolCallRequestFunction, ToolDefinition,
};
use crate::pentest::cleanup::CleanupOutcome;
/// Maximum duration for a single pentest session before timeout
const SESSION_TIMEOUT: Duration = Duration::from_secs(30 * 60); // 30 minutes
@@ -25,8 +24,6 @@ pub struct PentestOrchestrator {
pub(crate) db: Database,
pub(crate) event_tx: broadcast::Sender<PentestEvent>,
pub(crate) pause_rx: Option<watch::Receiver<bool>>,
/// Outbound policy for tenant-chosen URLs, the test-user cleanup's too.
pub(crate) net_guard: NetGuard,
}
impl PentestOrchestrator {
@@ -45,55 +42,6 @@ impl PentestOrchestrator {
db,
event_tx,
pause_rx,
net_guard,
}
}
/// Delete the session's test user with the access given for the target's
/// identity provider, and record on the session what became of it.
async fn clean_up_test_user(
&self,
session_id: Option<mongodb::bson::oid::ObjectId>,
test_user: &TestUserRecord,
access: Option<&TestUserCleanup>,
) {
let outcome = match compliance_core::guarded_net::guarded_client_builder(self.net_guard)
.timeout(std::time::Duration::from_secs(30))
.build()
{
Ok(http) => crate::pentest::cleanup::cleanup_test_user(test_user, access, &http).await,
Err(e) => Err(format!("no HTTP client: {e}")),
};
let left_behind = match outcome {
Ok(CleanupOutcome::Deleted) | Ok(CleanupOutcome::NotRegistered) => None,
Ok(CleanupOutcome::LeftBehind(reason)) => Some(reason),
Err(e) => Some(format!("cleanup failed: {e}")),
};
match &left_behind {
None => tracing::info!("Pentest test user deleted"),
Some(reason) => {
tracing::warn!(reason = %reason, "Pentest test user left behind");
let _ = self.event_tx.send(PentestEvent::Message {
content: format!(
"The test user {} is still registered with the application ({reason}); \
delete it by hand.",
test_user.email.as_deref().unwrap_or("(unknown)")
),
});
}
}
if let Some(sid) = session_id {
let _ = self
.db
.pentest_sessions()
.update_one(
doc! { "_id": sid },
doc! { "$set": {
"test_user.cleaned_up": left_behind.is_none(),
"test_user.left_behind": left_behind,
} },
)
.await;
}
}
@@ -551,12 +499,55 @@ impl PentestOrchestrator {
.await;
}
// Delete the test user in the target's identity provider if asked.
if let (Some(cfg), Some(test_user)) = (session.config.as_ref(), session.test_user.as_ref())
// Clean up test user via identity provider API if requested
if session
.config
.as_ref()
.is_some_and(|c| c.auth.cleanup_test_user)
{
if cfg.auth.cleanup_test_user {
self.clean_up_test_user(session.id, test_user, cfg.auth.cleanup.as_ref())
.await;
if let Some(ref test_user) = session.test_user {
let http = reqwest::Client::new();
// We need the AgentConfig — read from env since orchestrator doesn't hold it
let config = crate::config::load_config();
match config {
Ok(cfg) => {
match crate::pentest::cleanup::cleanup_test_user(test_user, &cfg, &http)
.await
{
Ok(true) => {
tracing::info!(
username = test_user.username.as_deref(),
"Test user cleaned up via provider API"
);
// Mark as cleaned up in DB
if let Some(sid) = session.id {
let _ = self
.db
.pentest_sessions()
.update_one(
doc! { "_id": sid },
doc! { "$set": { "test_user.cleaned_up": true } },
)
.await;
}
}
Ok(false) => {
tracing::info!(
"Test user cleanup skipped (no provider configured)"
);
}
Err(e) => {
tracing::warn!(error = %e, "Test user cleanup failed");
let _ = self.event_tx.send(PentestEvent::Error {
message: format!("Test user cleanup failed: {e}"),
});
}
}
}
Err(e) => {
tracing::warn!(error = %e, "Could not load config for cleanup");
}
}
}
}
+8 -10
View File
@@ -6,8 +6,7 @@ use compliance_core::models::sbom::SbomEntry;
use super::orchestrator::PentestOrchestrator;
/// Build additional prompt sections from PentestConfig when present.
/// `test_email` is the address an auto-register session registers with.
fn build_config_sections(config: &PentestConfig, test_email: Option<&str>) -> String {
fn build_config_sections(config: &PentestConfig) -> String {
let mut sections = String::new();
// Authentication section
@@ -36,11 +35,13 @@ fn build_config_sections(config: &PentestConfig, test_email: Option<&str>) -> St
"- **Registration URL**: Not provided — use Playwright to discover the registration page.\n",
);
}
if let Some(email) = test_email {
if let Some(ref email) = config.auth.verification_email {
sections.push_str(&format!(
"- **E-mail address**: Register with exactly `{email}` (no other \
address): the system polls its mailbox for verification links and \
finds the test account by it afterwards.\n",
"- **Verification Email**: Use plus-addressing from `{email}` \
(e.g. `{base}+{{session_id}}@{domain}`) for email verification. \
The system will poll the IMAP mailbox for verification links.\n",
base = email.split('@').next().unwrap_or(email),
domain = email.split('@').nth(1).unwrap_or("example.com"),
));
}
sections.push_str(
@@ -244,10 +245,7 @@ impl PentestOrchestrator {
let config_sections = session
.config
.as_ref()
.map(|c| {
let test_email = session.test_user.as_ref().and_then(|u| u.email.as_deref());
build_config_sections(c, test_email)
})
.map(build_config_sections)
.unwrap_or_default();
format!(
@@ -1,5 +1,5 @@
use super::{html_escape, tool_category};
use compliance_core::models::pentest::{AuthMode, PentestConfig, PentestSession, TestUserRecord};
use compliance_core::models::pentest::{AuthMode, PentestConfig, PentestSession};
pub(super) fn scope(
session: &PentestSession,
@@ -43,9 +43,6 @@ pub(super) fn scope(
AuthMode::AutoRegister => "Auto-register",
};
rows.push_str(&format!("<tr><td>Auth Mode</td><td>{auth_mode}</td></tr>"));
if let Some(user) = &session.test_user {
rows.push_str(&test_user_row(user));
}
if !cfg.scope_exclusions.is_empty() {
let excl = cfg
.scope_exclusions
@@ -128,47 +125,3 @@ pub(super) fn scope(
success_rate = session.success_rate(),
)
}
/// The report row for the session's test user: deleted, or still registered
/// with the application and to be deleted by hand.
fn test_user_row(user: &TestUserRecord) -> String {
let email = html_escape(user.email.as_deref().unwrap_or("(unknown)"));
let state = match (&user.left_behind, user.cleaned_up) {
(Some(reason), _) => format!(
"<strong>Left behind</strong>: still registered with the application, \
delete it by hand ({})",
html_escape(reason)
),
(None, true) => "Deleted after the test".to_string(),
(None, false) => "Not deleted (cleanup was not requested)".to_string(),
};
format!("<tr><td>Test User</td><td><code>{email}</code> &mdash; {state}</td></tr>")
}
#[cfg(test)]
mod test_user_tests {
use super::*;
#[test]
fn a_left_behind_test_user_is_named_with_its_reason() {
let user = TestUserRecord {
email: Some("pentest+1@mail.example.com".into()),
left_behind: Some("no admin access <given>".into()),
..Default::default()
};
let row = test_user_row(&user);
assert!(row.contains("pentest+1@mail.example.com"));
assert!(row.contains("Left behind"));
assert!(row.contains("no admin access &lt;given&gt;"));
}
#[test]
fn a_deleted_test_user_says_so() {
let user = TestUserRecord {
email: Some("pentest+1@mail.example.com".into()),
cleaned_up: true,
..Default::default()
};
assert!(test_user_row(&user).contains("Deleted after the test"));
}
}
@@ -1,178 +0,0 @@
//! Recording what a scan changes in the stored SBOM (#974): before a stage
//! replaces its part of a target's SBOM, the entries it is about to replace
//! are compared with the new ones ([`compliance_core::component_changes`])
//! and the changes are added to the scan run.
//!
//! Each stage owns its part (the code SBOM, the CODESYS libraries, the
//! firmware components) and records only that part's changes, so the run
//! adds up the changes of all of them. Best effort: a failure is logged and
//! the scan goes on, with the run's changes incomplete.
use futures_util::TryStreamExt;
use mongodb::bson::{doc, oid::ObjectId, to_bson, Document};
use compliance_core::component_changes::{diff, MAX_CHANGES};
use compliance_core::models::SbomEntry;
use crate::database::Database;
use crate::error::AgentError;
/// Add to run `scan_run_id` the changes that replacing target `repo_id`'s
/// stored entries matching `scope` with `entries` makes. The run's changes
/// start empty, so a run whose stages changed nothing says so.
///
/// # Arguments
///
/// * `db` - the tenant database
/// * `scan_run_id` - the run (hex id)
/// * `repo_id` - the target
/// * `scope` - the stage's part of the SBOM, as a filter on the entries
/// * `entries` - what the stage stores instead
pub(crate) async fn record(
db: &Database,
scan_run_id: &str,
repo_id: &str,
scope: Document,
entries: &[SbomEntry],
) {
if let Err(e) = try_record(db, scan_run_id, repo_id, scope, entries).await {
tracing::warn!(repo_id, scan_run_id, "component changes not recorded: {e}");
}
}
async fn try_record(
db: &Database,
scan_run_id: &str,
repo_id: &str,
scope: Document,
entries: &[SbomEntry],
) -> Result<(), AgentError> {
let run = ObjectId::parse_str(scan_run_id).map_err(|e| AgentError::Other(e.to_string()))?;
let mut filter = doc! { "repo_id": repo_id };
filter.extend(scope);
let stored: Vec<Document> = db
.sbom_entries()
.clone_with_type::<Document>()
.find(filter)
.projection(doc! { "package_manager": 1, "name": 1, "version": 1, "_id": 0 })
.await?
.try_collect()
.await?;
let field = |d: &Document, key: &str| d.get_str(key).unwrap_or_default().to_string();
let before: Vec<(String, String, String)> = stored
.iter()
.map(|d| {
(
field(d, "package_manager"),
field(d, "name"),
field(d, "version"),
)
})
.collect();
let before: Vec<(&str, &str, &str)> = before
.iter()
.map(|(m, n, v)| (m.as_str(), n.as_str(), v.as_str()))
.collect();
let after: Vec<(&str, &str, &str)> = entries
.iter()
.map(|e| {
(
e.package_manager.as_str(),
e.name.as_str(),
e.version.as_str(),
)
})
.collect();
let changes = to_bson(&diff(&before, &after)).map_err(|e| AgentError::Other(e.to_string()))?;
let max = i64::try_from(MAX_CHANGES).unwrap_or(i64::MAX);
// One pipeline update: the run's list so far (none yet: empty) and this
// stage's changes, at most the cap.
db.scan_runs()
.update_one(
doc! { "_id": run },
vec![doc! { "$set": { "component_changes": { "$slice": [
{ "$concatArrays": [{ "$ifNull": ["$component_changes", []] }, changes] },
max,
] } } }],
)
.await?;
Ok(())
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use compliance_core::component_changes::ComponentChangeKind;
use compliance_core::models::{ScanRun, ScanTrigger};
fn entry(manager: &str, name: &str, version: &str) -> SbomEntry {
SbomEntry::new("t1".into(), name.into(), version.into(), manager.into())
}
#[tokio::test]
async fn each_stage_adds_the_changes_of_its_own_part() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!("cchg_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP component_changes: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id("component-changes").await.unwrap();
// Arrange: a stored SBOM with a code and a firmware part.
let stored = [
entry("npm", "lodash", "4.17.20"),
entry("npm", "left-pad", "1.3.0"),
entry("firmware", "busybox", "1.36.0"),
];
db.sbom_entries().insert_many(&stored).await.unwrap();
let run_id = db
.scan_runs()
.insert_one(ScanRun::new("t1".into(), ScanTrigger::Manual))
.await
.unwrap()
.inserted_id
.as_object_id()
.unwrap()
.to_hex();
// Act: the code stage replaces its part; the firmware stage keeps
// its own unchanged.
record(
&db,
&run_id,
"t1",
doc! { "package_manager": { "$nin": ["firmware"] } },
&[entry("npm", "lodash", "4.17.21")],
)
.await;
record(
&db,
&run_id,
"t1",
doc! { "package_manager": { "$in": ["firmware"] } },
&[entry("firmware", "busybox", "1.36.0")],
)
.await;
// Assert
let run = db
.scan_runs()
.find_one(doc! { "_id": ObjectId::parse_str(&run_id).unwrap() })
.await
.unwrap()
.unwrap();
let changes = run.component_changes.expect("recorded");
let read: Vec<(ComponentChangeKind, &str)> =
changes.iter().map(|c| (c.kind, c.name.as_str())).collect();
assert_eq!(
read,
[
(ComponentChangeKind::Removed, "left-pad"),
(ComponentChangeKind::Updated, "lodash")
]
);
pool.drop_tenant("component-changes").await.ok();
}
}
+16 -72
View File
@@ -7,12 +7,6 @@
//! updated or removed), the issue is closed with a comment; when it comes back,
//! it is reopened.
//!
//! An issue a person closed in Gitea (#953) stays closed while the scan still
//! finds its CVE: closing it was that person's call, and no VEX statement is
//! made from it (one needs a justification). Once a complete scan no longer
//! finds the CVE, that close is forgotten, so a CVE that comes back reopens
//! the issue as usual.
//!
//! A CVE a VEX statement settles (`not_affected` or `fixed`, by a person, the
//! scan or an imported VEX document) gets no issue. Its open issue is closed
//! with a comment naming the status and the reason when `ISSUE_AUTOCLOSE` is
@@ -30,7 +24,6 @@ use std::collections::{BTreeMap, HashMap};
use mongodb::bson::doc;
use compliance_core::config::IssueAutoclose;
use compliance_core::models::issue::cve_issue_prefix;
use compliance_core::models::notification::{parse_severity, NotificationSeverity};
use compliance_core::models::{CveAlert, IssueStatus, TrackerIssue, VexAssessment, VexStatus};
@@ -102,12 +95,7 @@ pub(crate) struct CveIssueCounts {
/// target, package and CVE, so another version of the same package does not
/// open a second issue.
fn issue_key(target_id: &str, alert: &CveAlert) -> String {
format!(
"{}{}:{}",
cve_issue_prefix(target_id),
alert.affected_package,
alert.cve()
)
format!("cve:{target_id}:{}:{}", alert.affected_package, alert.cve())
}
/// A severity as the `severity:` labels name it.
@@ -175,7 +163,7 @@ pub(crate) async fn sync_cve_issues(
alerts: &[CveAlert],
complete: bool,
) -> Result<CveIssueCounts, AgentError> {
let prefix = cve_issue_prefix(target.target_id);
let prefix = format!("cve:{}:", target.target_id);
let mut existing: HashMap<String, TrackerIssue> = HashMap::new();
let mut cursor = target
.db
@@ -201,9 +189,7 @@ pub(crate) async fn sync_cve_issues(
.filter(|(_, a)| !a.is_resolved_by_vex() && issue_worthy(a, target.epss_percentile))
{
match existing.get(key) {
// A person closed it in Gitea while the CVE is unchanged.
Some(issue) if issue.closed_in_tracker.is_some() => {}
Some(issue) if issue.status.is_closed() => {
Some(issue) if is_closed(&issue.status) => {
let comment = "**Prüfwerk:** Bei der Prüfung erneut gefunden, daher wieder geöffnet.\n\nFound again by the scan, so reopened.";
if set_state(target, issue, comment, "open").await {
record(target.db, issue, IssueStatus::Open).await?;
@@ -224,7 +210,7 @@ pub(crate) async fn sync_cve_issues(
.iter()
.filter_map(|(key, alert)| {
let vex = alert.vex.as_ref().filter(|_| alert.is_resolved_by_vex())?;
let issue = existing.get(key).filter(|i| !i.status.is_closed())?;
let issue = existing.get(key).filter(|i| !is_closed(&i.status))?;
Some((issue, vex))
})
.collect();
@@ -232,14 +218,7 @@ pub(crate) async fn sync_cve_issues(
if complete {
for (key, issue) in &existing {
if present.contains_key(key) {
continue;
}
if issue.status.is_closed() {
// Gone now: if it comes back, it is found again.
if issue.closed_in_tracker.is_some() {
record(target.db, issue, IssueStatus::Closed).await?;
}
if present.contains_key(key) || is_closed(&issue.status) {
continue;
}
let comment = "**Prüfwerk:** Die Prüfung findet diese Schwachstelle nicht mehr: Die Abhängigkeit wurde aktualisiert oder entfernt.\n\nThe scan no longer finds this vulnerability: the dependency was updated or removed.";
@@ -332,6 +311,11 @@ fn vex_comment(vex: &VexAssessment) -> String {
)
}
/// Whether an issue is closed.
fn is_closed(status: &IssueStatus) -> bool {
matches!(status, IssueStatus::Closed | IssueStatus::Resolved)
}
/// The Prüfwerk label ids of a Gitea repository, created where missing;
/// `None` for other trackers or when Gitea refuses.
async fn gitea_label_ids(target: &CveIssueTarget<'_>) -> Option<HashMap<String, i64>> {
@@ -514,10 +498,12 @@ async fn record(
let Some(id) = issue.id else {
return Ok(());
};
let update = crate::pipeline::issue_sync::issue_state_update(&status, None)
.map_err(|e| AgentError::Other(e.to_string()))?;
let status = mongodb::bson::to_bson(&status).map_err(|e| AgentError::Other(e.to_string()))?;
db.tracker_issues()
.update_one(doc! { "_id": id }, update)
.update_one(
doc! { "_id": id },
doc! { "$set": { "status": status, "updated_at": mongodb::bson::DateTime::now() } },
)
.await?;
Ok(())
}
@@ -798,9 +784,7 @@ mod tests {
// It comes back: reopened, not opened twice.
assert_eq!(
sync_cve_issues(&target, std::slice::from_ref(&okhttp), true)
.await
.unwrap(),
sync_cve_issues(&target, &[okhttp], true).await.unwrap(),
CveIssueCounts {
reopened: 1,
..Default::default()
@@ -808,46 +792,6 @@ mod tests {
);
assert_eq!(calls.lock().unwrap().last().unwrap(), "state 100: \"open\"");
// A person closes it in Gitea (#953): the scan that still finds the
// CVE leaves it closed and sends nothing.
let key = format!("cve:target-1:okhttp:{}", okhttp.cve());
db.tracker_issues()
.update_one(
doc! { "finding_id": &key },
doc! { "$set": { "status": "closed", "closed_in_tracker": "dev-anna" } },
)
.await
.unwrap();
let sent = calls.lock().unwrap().len();
assert_eq!(
sync_cve_issues(&target, std::slice::from_ref(&okhttp), true)
.await
.unwrap(),
CveIssueCounts::default()
);
assert_eq!(calls.lock().unwrap().len(), sent);
// Updated away, the close is forgotten; back again, it reopens.
sync_cve_issues(&target, &[], true).await.unwrap();
let stored = db
.tracker_issues()
.find_one(doc! { "finding_id": &key })
.await
.unwrap()
.unwrap();
assert_eq!(
(stored.status, stored.closed_in_tracker),
(IssueStatus::Closed, None)
);
assert_eq!(calls.lock().unwrap().len(), sent, "already closed");
assert_eq!(
sync_cve_issues(&target, &[okhttp], true)
.await
.unwrap()
.reopened,
1
);
pool.drop_tenant("cve-issues").await.ok();
}
@@ -1,197 +0,0 @@
//! DAST findings as findings of the target they were found on (#998), so they
//! carry control refs and reach the findings list, the issue tracker and the
//! evidence pack like every other finding. The request and response evidence
//! stays with the DAST finding.
use compliance_core::models::dast::DastFinding;
use compliance_core::models::{Finding, ScanType};
use super::dedup;
use crate::import::{control_refs, normalise_cwe};
/// The scanner name DAST findings are stored under.
pub const SCANNER: &str = "dast";
/// The finding of target `repo_id` that `dast` stands for.
///
/// # Arguments
///
/// * `repo_id` - the target the DAST target belongs to
/// * `dast` - the finding as the DAST scan reported it
///
/// # Returns
///
/// A finding with a fingerprint that is the same for the same weakness at the
/// same endpoint, method and parameter in every scan (so a later scan finds it
/// again instead of adding it twice), the CWE normalised, and the control refs
/// that CWE is evidence for. The endpoint goes into the description, since a
/// DAST finding has no file.
pub fn as_finding(repo_id: &str, dast: &DastFinding) -> Finding {
let fingerprint =
dedup::compute_fingerprint(&[repo_id, SCANNER, &dedup::compute_dast_fingerprint(dast)]);
let parameter = dast
.parameter
.as_deref()
.map(|p| format!(", parameter `{p}`"))
.unwrap_or_default();
let description = format!(
"{}\n\nFound by DAST at {} {}{parameter}.",
dast.description, dast.method, dast.endpoint
);
let mut finding = Finding::new(
repo_id.to_string(),
fingerprint,
SCANNER.to_string(),
ScanType::Dast,
dast.title.clone(),
description,
dast.severity.clone(),
);
finding.rule_id = Some(format!("dast-{}", dast.vuln_type));
finding.cwe = dast.cwe.as_deref().and_then(normalise_cwe);
finding.control_refs = finding.cwe.as_deref().map(control_refs).unwrap_or_default();
finding.remediation = dast.remediation.clone();
finding
}
/// The code finding `dast` is linked to (#998): the one finding in `code`
/// with the same CWE, so the DAST finding shows the file and line its
/// weakness is likely in.
///
/// # Arguments
///
/// * `dast` - the finding the DAST scan reported
/// * `code` - the target's open findings that have a place in the code
///
/// # Returns
///
/// That finding's id, or `None` when `dast` has no CWE, or no finding or
/// several share it: a CWE alone does not say which of several it is.
pub fn linked_code_finding(dast: &DastFinding, code: &[Finding]) -> Option<String> {
let cwe = dast.cwe.as_deref().and_then(normalise_cwe)?;
let mut same = code
.iter()
.filter(|f| f.cwe.as_deref().and_then(normalise_cwe).as_deref() == Some(cwe.as_str()));
let only = same.next()?;
if same.next().is_some() {
return None;
}
only.id.map(|id| id.to_hex())
}
#[cfg(test)]
mod tests {
use compliance_core::models::dast::DastVulnType;
use compliance_core::models::Severity;
use super::*;
fn dast(endpoint: &str, parameter: Option<&str>) -> DastFinding {
let mut f = DastFinding::new(
"run-1".into(),
"dast-target-1".into(),
DastVulnType::CorsMisconfiguration,
"CORS misconfiguration allows arbitrary origins".into(),
"The server allows any origin.".into(),
Severity::Medium,
endpoint.into(),
"GET".into(),
);
f.cwe = Some("cwe-942".into());
f.parameter = parameter.map(str::to_string);
f.remediation = Some("Allow only trusted origins.".into());
f
}
#[test]
fn a_dast_finding_becomes_a_finding_of_the_target() {
let finding = as_finding("target-1", &dast("https://app.example.com/", None));
assert_eq!(finding.repo_id, "target-1");
assert_eq!(finding.scanner, "dast");
assert_eq!(finding.scan_type, ScanType::Dast);
assert_eq!(
finding.rule_id.as_deref(),
Some("dast-cors_misconfiguration")
);
assert_eq!(
finding.title,
"CORS misconfiguration allows arbitrary origins"
);
assert_eq!(finding.severity, Severity::Medium);
assert_eq!(finding.cwe.as_deref(), Some("CWE-942"));
assert_eq!(finding.control_refs, ["cra-ai-1"]);
assert!(finding
.description
.ends_with("Found by DAST at GET https://app.example.com/."));
assert_eq!(
finding.remediation.as_deref(),
Some("Allow only trusted origins.")
);
}
#[test]
fn the_same_weakness_keeps_its_fingerprint_and_others_get_their_own() {
let first = as_finding("target-1", &dast("https://app.example.com/", None));
let again = as_finding("target-1", &dast("https://app.example.com", None));
let elsewhere = as_finding("target-1", &dast("https://app.example.com/login", None));
let other_target = as_finding("target-2", &dast("https://app.example.com/", None));
let with_parameter = as_finding("target-1", &dast("https://app.example.com/", Some("q")));
assert_eq!(first.fingerprint, again.fingerprint);
for other in [&elsewhere, &other_target, &with_parameter] {
assert_ne!(first.fingerprint, other.fingerprint);
}
assert!(with_parameter.description.contains("parameter `q`"));
}
fn code_finding(cwe: &str) -> Finding {
let mut f = Finding::new(
"target-1".into(),
format!("fp-{cwe}"),
"semgrep".into(),
ScanType::Sast,
"Permissive CORS".into(),
"Any origin is allowed.".into(),
Severity::Medium,
);
f.id = Some(mongodb::bson::oid::ObjectId::new());
f.cwe = Some(cwe.into());
f.file_path = Some("src/server.rs".into());
f
}
#[test]
fn a_dast_finding_links_the_one_code_finding_with_its_cwe() {
let cors = code_finding("CWE-942");
let code = [code_finding("CWE-79"), cors.clone()];
assert_eq!(
linked_code_finding(&dast("https://app.example.com/", None), &code),
cors.id.map(|id| id.to_hex())
);
}
#[test]
fn no_link_without_a_cwe_or_with_several_candidates() {
let finding = dast("https://app.example.com/", None);
let mut no_cwe = finding.clone();
no_cwe.cwe = None;
assert_eq!(
linked_code_finding(&finding, &[code_finding("CWE-79")]),
None
);
assert_eq!(
linked_code_finding(&no_cwe, &[code_finding("CWE-942")]),
None
);
assert_eq!(
linked_code_finding(
&finding,
&[code_finding("cwe-942"), code_finding("CWE-942")]
),
None
);
}
}
+21 -3
View File
@@ -145,15 +145,33 @@ pub(crate) fn relative(root: &Path, path: &Path) -> String {
}
/// The text of a file that may start with a byte-order mark (Visual Studio
/// writes UTF-8 with BOM, older tools UTF-16) or be Windows-1252, decoded by
/// [`compliance_core::encoding::read_source`]. `None` for a file too large or
/// writes UTF-8 with BOM, older tools UTF-16). `None` for a file too large or
/// unreadable.
pub(crate) fn read_text(path: &Path) -> Option<String> {
let meta = std::fs::metadata(path).ok()?;
if meta.len() > MAX_FILE_BYTES {
return None;
}
compliance_core::encoding::read_source(path).ok()
let bytes = std::fs::read(path).ok()?;
let utf16 = |bytes: &[u8], le: bool| {
let units: Vec<u16> = bytes
.chunks_exact(2)
.map(|c| {
if le {
u16::from_le_bytes([c[0], c[1]])
} else {
u16::from_be_bytes([c[0], c[1]])
}
})
.collect();
String::from_utf16(&units).ok()
};
match bytes.as_slice() {
[0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8(rest.to_vec()).ok(),
[0xFF, 0xFE, rest @ ..] => utf16(rest, true),
[0xFE, 0xFF, rest @ ..] => utf16(rest, false),
_ => String::from_utf8(bytes).ok(),
}
}
/// Parse XML the way project and configuration files need: a DTD is allowed
@@ -147,8 +147,7 @@ pub fn detect(root: &Path, repo_id: &str) -> Vec<SbomEntry> {
}) {
let small = entry.metadata().is_ok_and(|m| m.len() <= MAX_HEADER_BYTES);
let Some(text) = small
// Vendor SDK headers are often Windows-1252 (a "©" in the banner).
.then(|| compliance_core::encoding::read_source(entry.path()).ok())
.then(|| std::fs::read_to_string(entry.path()).ok())
.flatten()
else {
continue;
+1 -22
View File
@@ -973,8 +973,7 @@ fn content_fingerprints(tree: &Path, findings: &mut [Finding]) {
continue;
};
let lines = files.entry(path.clone()).or_insert_with(|| {
// Decoded like the scanners read it: UTF-8, UTF-16, Windows-1252.
compliance_core::encoding::read_source(&tree.join(&path))
std::fs::read_to_string(tree.join(&path))
.ok()
.map(|text| text.lines().map(normalised).collect())
});
@@ -1250,26 +1249,6 @@ mod tests {
assert!(missing[0].legacy_fingerprints.is_empty());
}
#[test]
fn a_windows_1252_file_is_keyed_by_content_as_its_utf8_version_is() {
let dir = std::env::temp_dir().join(format!("cs-fp-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
// "größe" as Windows-1252 writes it (0xF6 0xDF), then the same file
// saved again as UTF-8.
std::fs::write(dir.join("a.c"), b"int x;\nint gr\xF6\xDFe = read();\n").unwrap();
let ansi = keyed(&dir, vec![at("a.c", 2)]);
std::fs::write(dir.join("a.c"), "int x;\nint größe = read();\n").unwrap();
let utf8 = keyed(&dir, vec![at("a.c", 2)]);
let _ = std::fs::remove_dir_all(&dir);
// Keyed by content, with the line-based key kept to adopt the row
// stored under it while the file could not be read.
let line_key = crate::pipeline::dedup::compute_fingerprint(&["repo-1", "rule", "a.c", "2"]);
assert_eq!(ansi[0].legacy_fingerprints, std::slice::from_ref(&line_key));
assert_ne!(ansi[0].fingerprint, line_key);
// Re-saving the file in another encoding keeps the key.
assert_eq!(ansi[0].fingerprint, utf8[0].fingerprint);
}
#[test]
fn a_scanners_own_content_and_groups_are_respected() {
let dir = std::env::temp_dir().join(format!("cs-fp-{}", uuid::Uuid::new_v4()));
+1 -46
View File
@@ -495,18 +495,7 @@ impl GitOps {
_ => "",
};
// A diff line is UTF-8 or, from an older tool, Windows-1252
// (single-byte, so a line decodes on its own). UTF-16 files are
// binary to git and have no lines here.
let bytes = line.content();
let decoded;
let content = match std::str::from_utf8(bytes) {
Ok(text) => text,
Err(_) => {
decoded = compliance_core::encoding::decode(bytes.to_vec()).unwrap_or_default();
decoded.as_str()
}
};
let content = std::str::from_utf8(line.content()).unwrap_or("");
diff_file.hunks.push_str(prefix);
diff_file.hunks.push_str(content);
@@ -930,38 +919,4 @@ mod tests {
.expect_err("private origin must be refused");
assert!(err.to_string().contains("10.0.0.5"), "{err}");
}
#[test]
fn a_windows_1252_line_shows_in_the_diff() {
// Arrange: a file committed, then a line with "für" as Windows-1252
// writes it (0xFC) added in a second commit.
let dir = source_repo();
let repo = git2::Repository::open(&dir).unwrap();
let old = repo.head().unwrap().peel_to_commit().unwrap();
std::fs::write(
dir.join("README.md"),
b"pump controller\n// f\xFCr Halle 2\n",
)
.unwrap();
let mut index = repo.index().unwrap();
index.add_path(Path::new("README.md")).unwrap();
index.write().unwrap();
let tree = repo.find_tree(index.write_tree().unwrap()).unwrap();
let sig = git2::Signature::now("t", "t@example.com").unwrap();
let new = repo
.commit(Some("HEAD"), &sig, &sig, "note", &tree, &[&old])
.unwrap();
// Act
let diff = GitOps::get_diff_content(&dir, &old.id().to_string(), &new.to_string()).unwrap();
std::fs::remove_dir_all(&dir).unwrap();
// Assert: the added line is there, decoded.
assert_eq!(diff.len(), 1);
assert!(
diff[0].hunks.contains("+// für Halle 2"),
"{}",
diff[0].hunks
);
}
}
+42 -201
View File
@@ -1,74 +1,28 @@
use std::path::Path;
use compliance_core::error::CoreError;
use compliance_core::models::graph::GraphBuildRun;
use compliance_core::models::Finding;
use compliance_graph::graph::engine::CodeGraph;
use super::orchestrator::{GraphContext, PipelineOrchestrator};
use super::plc::PlcFile;
use crate::error::AgentError;
/// How long the DAST stage waits for one target's scan.
const DAST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20 * 60);
/// The most nodes a graph build parses.
const GRAPH_MAX_NODES: u32 = 50_000;
/// What a code graph is built from.
pub(crate) enum GraphSource<'a> {
/// The source files of a checked-out tree, by the graph crate's parsers.
Tree(&'a Path),
/// The POUs of a PLC target, read from every one of its PLC source trees.
Plc(&'a [PlcFile]),
}
/// Build a code graph and detect its communities.
///
/// # Errors
///
/// Returns the graph engine's error when a tree can't be read or the graph
/// can't be assembled.
pub(crate) fn build_graph(
source: GraphSource<'_>,
repo_id: &str,
graph_build_id: &str,
) -> Result<(CodeGraph, GraphBuildRun), CoreError> {
let engine = compliance_graph::GraphEngine::new(GRAPH_MAX_NODES);
match source {
GraphSource::Tree(path) => engine.build_graph(path, repo_id, graph_build_id),
GraphSource::Plc(files) => engine.assemble(
super::plc::graph::parse_output(files, repo_id, graph_build_id),
repo_id,
),
}
}
impl PipelineOrchestrator {
/// Build the code knowledge graph for a repo, store it in place of the
/// previous one and compute the impact of each finding.
/// Build the code knowledge graph for a repo and compute impact analyses
pub(super) async fn build_code_graph(
&self,
source: GraphSource<'_>,
repo_path: &std::path::Path,
repo_id: &str,
findings: &[Finding],
) -> Result<GraphContext, AgentError> {
let graph_build_id = uuid::Uuid::new_v4().to_string();
let built = build_graph(source, repo_id, &graph_build_id)
.map_err(|e| AgentError::Other(format!("Graph build error: {e}")))?;
self.store_code_graph(built, repo_id, &graph_build_id, findings)
.await
}
let engine = compliance_graph::GraphEngine::new(50_000);
/// Replace the repo's stored graph with `built`, and store the impact of
/// each finding that has a file.
async fn store_code_graph(
&self,
(code_graph, build_run): (CodeGraph, GraphBuildRun),
repo_id: &str,
graph_build_id: &str,
findings: &[Finding],
) -> Result<GraphContext, AgentError> {
let (mut code_graph, build_run) =
engine
.build_graph(repo_path, repo_id, &graph_build_id)
.map_err(|e| AgentError::Other(format!("Graph build error: {e}")))?;
// Apply community detection
compliance_graph::graph::community::apply_communities(&mut code_graph);
// Store graph in MongoDB
let store = compliance_graph::graph::persistence::GraphStore::new(self.db.inner());
store
.delete_repo_graph(repo_id)
@@ -88,7 +42,7 @@ impl PipelineOrchestrator {
let impact = analyzer.analyze(
repo_id,
&finding.fingerprint,
graph_build_id,
&graph_build_id,
file_path,
finding.line_number,
);
@@ -108,15 +62,8 @@ impl PipelineOrchestrator {
})
}
/// The DAST stage: scan every DAST target of `repo_id` and wait for the
/// scans (#998). A scan that does not complete is recorded as the `dast`
/// stage with [`SkipCode::ToolFailed`](compliance_core::models::SkipCode);
/// it fails the stage, not the run.
///
/// # Returns
///
/// How many findings the DAST scans added to the target's findings.
pub(super) async fn maybe_trigger_dast(&self, repo_id: &str, scan_run_id: &str) -> u32 {
/// Trigger DAST scan if a target is configured for this repo
pub(super) async fn maybe_trigger_dast(&self, repo_id: &str, scan_run_id: &str) {
use futures_util::TryStreamExt;
if self.source_only() {
@@ -125,151 +72,45 @@ impl PipelineOrchestrator {
compliance_core::models::SkippedStage::feature_disabled("dast"),
)
.await;
return 0;
return;
}
let filter = mongodb::bson::doc! { "repo_id": repo_id };
let targets: Vec<compliance_core::models::DastTarget> =
match self.db.dast_targets().find(filter).await {
Ok(cursor) => cursor.try_collect().await.unwrap_or_default(),
Err(_) => return 0,
Err(_) => return,
};
if targets.is_empty() {
tracing::info!("[{repo_id}] No DAST targets configured, skipping");
return 0;
return;
}
let mut new_count = 0;
for mut target in targets {
self.secrets.open_in_place(&mut target);
match self.run_dast_target(&target, repo_id, scan_run_id).await {
Ok(added) => new_count += added,
Err(failed) => self.skip_stage(scan_run_id, failed).await,
}
for target in targets {
let db = self.db.clone();
let scan_run_id = scan_run_id.to_string();
let net_guard = self.net_guard;
tokio::spawn(async move {
let orchestrator = compliance_dast::DastOrchestrator::new(100, net_guard);
match orchestrator.run_scan(&target, Vec::new()).await {
Ok((mut scan_run, findings)) => {
scan_run.sast_scan_run_id = Some(scan_run_id);
if let Err(e) = db.dast_scan_runs().insert_one(&scan_run).await {
tracing::error!("Failed to store DAST scan run: {e}");
}
for finding in &findings {
if let Err(e) = db.dast_findings().insert_one(finding).await {
tracing::error!("Failed to store DAST finding: {e}");
}
}
tracing::info!("DAST scan complete: {} findings", findings.len());
}
Err(e) => {
tracing::error!("DAST scan failed: {e}");
}
}
});
}
new_count
}
/// Scan one DAST target, waiting for the result (#998), and store the
/// scan run and its findings: as DAST findings, with their evidence, and
/// as findings of the target `repo_id`.
///
/// # Returns
///
/// How many findings the target did not have yet.
///
/// # Errors
///
/// The `dast` stage entry to record when the scan did not complete: it
/// failed, timed out, or its run could not be stored. The error itself
/// goes to the log only.
async fn run_dast_target(
&self,
target: &compliance_core::models::DastTarget,
repo_id: &str,
scan_run_id: &str,
) -> Result<u32, compliance_core::models::SkippedStage> {
use compliance_core::models::{DastScanStatus, SkipCode, SkippedStage};
// The subject names the tool, as for the other stages: the dashboard
// reads it as "DAST did not complete". The log names the target.
let failed = |reason: &str| {
Err(SkippedStage::new("dast", SkipCode::ToolFailed, reason).about("DAST"))
};
let orchestrator = compliance_dast::DastOrchestrator::new(100, self.net_guard);
let scan = tokio::time::timeout(DAST_TIMEOUT, orchestrator.run_scan(target, Vec::new()));
let (mut run, mut findings) = match scan.await {
Ok(Ok(result)) => result,
Ok(Err(e)) => {
tracing::error!(target = %target.name, "DAST scan failed: {e}");
return failed("DAST did not complete");
}
Err(_) => {
tracing::error!(target = %target.name, "DAST scan timed out");
return failed("DAST did not complete in time");
}
};
run.sast_scan_run_id = Some(scan_run_id.to_string());
if let Err(e) = self.db.dast_scan_runs().insert_one(&run).await {
tracing::error!("Failed to store DAST scan run: {e}");
return failed("DAST results could not be stored");
}
let code = self.open_code_findings(repo_id).await;
let mut new_count = 0;
for finding in &mut findings {
finding.linked_sast_finding_id =
super::dast_findings::linked_code_finding(finding, &code);
if let Err(e) = self.db.dast_findings().insert_one(&*finding).await {
tracing::error!("Failed to store DAST finding: {e}");
}
match self.add_dast_finding(repo_id, scan_run_id, finding).await {
Ok(added) => new_count += u32::from(added),
Err(e) => tracing::error!("Failed to store DAST finding as a finding: {e}"),
}
}
tracing::info!(target = %target.name, findings = findings.len(), new = new_count, "DAST scan done");
if run.status == DastScanStatus::Failed {
// `error_message` is the scanner's English reason ("Login: ...",
// "Reconnaissance failed: ..."); the run keeps it in full.
tracing::warn!(target = %target.name, error = ?run.error_message, "DAST scan failed");
return failed("DAST did not complete");
}
Ok(new_count)
}
/// The open findings of target `repo_id` that have a place in the code and
/// a CWE: what a DAST finding can be linked to (#998). Empty when they
/// cannot be read (logged); the DAST findings are then stored unlinked.
async fn open_code_findings(&self, repo_id: &str) -> Vec<compliance_core::models::Finding> {
use futures_util::TryStreamExt;
let filter = mongodb::bson::doc! {
"repo_id": repo_id,
"scanner": { "$ne": super::dast_findings::SCANNER },
"file_path": { "$ne": null },
"cwe": { "$ne": null },
"status": { "$in": ["open", "triaged", "needs_review"] },
};
match self.db.findings().find(filter).await {
Ok(cursor) => cursor.try_collect().await.unwrap_or_else(|e| {
tracing::warn!("Code findings for DAST links not read: {e}");
Vec::new()
}),
Err(e) => {
tracing::warn!("Code findings for DAST links not read: {e}");
Vec::new()
}
}
}
/// Store `dast` as a finding of target `repo_id`, unless the target has
/// it already (the same fingerprint).
///
/// # Returns
///
/// Whether it was new.
///
/// # Errors
///
/// The database's error.
async fn add_dast_finding(
&self,
repo_id: &str,
scan_run_id: &str,
dast: &compliance_core::models::DastFinding,
) -> Result<bool, mongodb::error::Error> {
let mut finding = super::dast_findings::as_finding(repo_id, dast);
finding.scan_run_id = Some(scan_run_id.to_string());
let known = self
.db
.findings()
.find_one(mongodb::bson::doc! { "fingerprint": &finding.fingerprint })
.await?
.is_some();
if !known {
self.db.findings().insert_one(&finding).await?;
}
Ok(!known)
}
}
@@ -1,472 +0,0 @@
//! A person closing or reopening a Prüfwerk issue in Gitea, carried back to
//! the finding (#953).
//!
//! * Closed: an undecided finding becomes resolved, recorded as "closed in the
//! ticket" with the Gitea user's login. The next scan confirms it (not found:
//! it stays resolved) or reopens finding and issue as for any resolved
//! finding found again. A finding a person had already decided keeps that
//! decision; only the issue's state is recorded.
//! * Reopened: a decided finding becomes undecided again (`open`).
//! * CVE issues: only the issue's state and who closed it are recorded. No
//! VEX statement is set, since one needs a justification; the scan leaves
//! the issue closed while the CVE is still there
//! ([`crate::pipeline::cve_issues`]).
//!
//! Nothing here calls the tracker: the issue already is in the state the
//! event (or the poll, [`crate::pipeline::issue_poll`]) reports, and the issue record says so, so the status sync
//! ([`crate::pipeline::issue_sync`]) has nothing to carry over either.
use futures_util::TryStreamExt;
use mongodb::bson::{doc, oid::ObjectId, to_bson, Bson, Document};
use compliance_core::models::{
FindingStatus, IssueStatus, StatusChange, TrackerChangeKind, TrackerIssue, TrackerType,
};
use crate::database::Database;
use crate::error::AgentError;
use crate::git_source::events::{IssueChange, IssueEvent};
use crate::pipeline::issue_creation::ISSUE_STATUSES;
use crate::pipeline::issue_sync::issue_state_update;
/// What carrying an issue event back did, for the delivery record.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum BackSynced {
/// The issue is not one Prüfwerk opened in this repository.
NotOurs,
/// The finding's status changed.
Finding,
/// Only the issue's state was recorded: the finding already had a
/// matching status (a person had decided it, or it was undecided).
IssueOnly,
/// A CVE issue's state was recorded.
Cve,
}
impl BackSynced {
/// The delivery record's detail for this result of `change`.
pub(crate) fn detail(self, change: IssueChange) -> &'static str {
match (self, change) {
(Self::NotOurs, _) => "issue not opened by Prüfwerk",
(Self::Finding, IssueChange::Closed) => "finding resolved: issue closed in Gitea",
(Self::Finding, IssueChange::Reopened) => "finding reopened: issue reopened in Gitea",
(Self::IssueOnly, _) => "issue state recorded; the finding's status already matched",
(Self::Cve, _) => "CVE issue state recorded",
}
}
}
/// The finding statuses `change` moves a finding away from: the undecided
/// ones ([`ISSUE_STATUSES`]) for a close, every other for a reopen.
fn statuses_changed_by(change: IssueChange) -> Document {
let undecided: Vec<String> = ISSUE_STATUSES.iter().map(ToString::to_string).collect();
match change {
IssueChange::Closed => doc! { "$in": undecided },
IssueChange::Reopened => doc! { "$nin": undecided },
}
}
/// The status a finding moves to and how its history records `change`.
fn new_status(change: IssueChange) -> (FindingStatus, TrackerChangeKind) {
match change {
IssueChange::Closed => (FindingStatus::Resolved, TrackerChangeKind::ClosedInTracker),
IssueChange::Reopened => (FindingStatus::Open, TrackerChangeKind::ReopenedInTracker),
}
}
/// Carry `event` back for the managed target `target_id`.
///
/// # Arguments
///
/// * `db` - the tenant database
/// * `target_id` - the target of the event's repository
/// * `event` - the close or reopen, by someone other than Prüfwerk's bot
///
/// # Returns
///
/// What was changed.
///
/// # Errors
///
/// A database error.
pub(crate) async fn apply(
db: &Database,
target_id: &str,
event: &IssueEvent,
) -> Result<BackSynced, AgentError> {
apply_change(db, target_id, event.number, event.change, &event.sender).await
}
/// Carry a close or reopen of issue `number` back for target `target_id`,
/// however it was learnt: a webhook delivery ([`apply`]) or the poll
/// ([`crate::pipeline::issue_poll`]).
///
/// # Arguments
///
/// * `db` - the tenant database
/// * `target_id` - the target of the issue's repository
/// * `number` - the issue number in that repository
/// * `change` - closed or reopened
/// * `sender` - the login of the person who did it, not Prüfwerk's bot
///
/// # Returns
///
/// What was changed.
///
/// # Errors
///
/// A database error.
pub(crate) async fn apply_change(
db: &Database,
target_id: &str,
number: i64,
change: IssueChange,
sender: &str,
) -> Result<BackSynced, AgentError> {
let Some(issue) = find_issue(db, target_id, number).await? else {
return Ok(BackSynced::NotOurs);
};
let (status, closed_by) = match change {
IssueChange::Closed => (IssueStatus::Closed, Some(sender)),
IssueChange::Reopened => (IssueStatus::Open, None),
};
// The issue first: once it reads closed, a status sync running meanwhile
// finds nothing to close (and no comment to write) for the finding.
if let Some(id) = issue.id {
let update =
issue_state_update(&status, closed_by).map_err(|e| AgentError::Other(e.to_string()))?;
let mut filter = doc! { "_id": id };
if closed_by.is_some() {
// A record that already reads closed was closed by Prüfwerk (by
// a bot user other than the issue's author, after a token
// change): there is no person's close to keep.
filter.insert("status", doc! { "$nin": ["closed", "resolved"] });
}
db.tracker_issues().update_one(filter, update).await?;
}
if issue.finding_id.starts_with("cve:") {
return Ok(BackSynced::Cve);
}
let Ok(finding_id) = ObjectId::parse_str(&issue.finding_id) else {
return Ok(BackSynced::IssueOnly);
};
let (new, kind) = new_status(change);
let history = StatusChange::by_tracker(new.clone(), kind, sender);
let to_bson_err = |e: mongodb::bson::ser::Error| AgentError::Other(e.to_string());
// One conditional update, like the scan's status changes: a decision a
// person makes meanwhile is not overwritten.
let res = db
.findings()
.update_one(
doc! { "_id": finding_id, "status": statuses_changed_by(change) },
doc! {
"$set": {
"status": to_bson(&new).map_err(to_bson_err)?,
"updated_at": mongodb::bson::DateTime::now(),
},
"$push": { "status_history": to_bson(&history).map_err(to_bson_err)? },
},
)
.await?;
Ok(if res.modified_count > 0 {
BackSynced::Finding
} else {
BackSynced::IssueOnly
})
}
/// The issue Prüfwerk opened as number `number` in the repository of target
/// `target_id`. Issue numbers repeat across repositories, so a record counts
/// only if it belongs to the target: a CVE issue by its key, a finding issue
/// by its finding.
async fn find_issue(
db: &Database,
target_id: &str,
number: i64,
) -> Result<Option<TrackerIssue>, AgentError> {
let tracker = to_bson(&TrackerType::Gitea).map_err(|e| AgentError::Other(e.to_string()))?;
let candidates: Vec<TrackerIssue> = db
.tracker_issues()
.find(doc! { "external_id": number.to_string(), "tracker_type": tracker })
.await?
.try_collect()
.await?;
let cve_prefix = format!("cve:{target_id}:");
if let Some(cve) = candidates
.iter()
.find(|i| i.finding_id.starts_with(&cve_prefix))
{
return Ok(Some(cve.clone()));
}
let ids: Vec<Bson> = candidates
.iter()
.filter_map(|i| ObjectId::parse_str(&i.finding_id).ok())
.map(Bson::ObjectId)
.collect();
if ids.is_empty() {
return Ok(None);
}
let Some(row) = db
.findings()
.clone_with_type::<Document>()
.find_one(doc! { "_id": { "$in": ids }, "repo_id": target_id })
.projection(doc! { "_id": 1 })
.await?
else {
return Ok(None);
};
let Ok(id) = row.get_object_id("_id") else {
return Ok(None);
};
let id = id.to_hex();
Ok(candidates.into_iter().find(|i| i.finding_id == id))
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use compliance_core::models::{Finding, ScanType, Severity};
use crate::git_source::gitea::GiteaRepo;
#[test]
fn a_close_resolves_undecided_findings_and_a_reopen_reopens_decided_ones() {
assert_eq!(
new_status(IssueChange::Closed),
(FindingStatus::Resolved, TrackerChangeKind::ClosedInTracker)
);
assert_eq!(
new_status(IssueChange::Reopened),
(FindingStatus::Open, TrackerChangeKind::ReopenedInTracker)
);
let closed = statuses_changed_by(IssueChange::Closed);
let moved: Vec<&str> = closed
.get_array("$in")
.unwrap()
.iter()
.filter_map(Bson::as_str)
.collect();
assert_eq!(moved, ["open", "triaged", "needs_review"]);
assert!(statuses_changed_by(IssueChange::Reopened).contains_key("$nin"));
}
#[test]
fn the_delivery_record_says_what_happened() {
assert_eq!(
BackSynced::Finding.detail(IssueChange::Closed),
"finding resolved: issue closed in Gitea"
);
assert_eq!(
BackSynced::NotOurs.detail(IssueChange::Reopened),
"issue not opened by Prüfwerk"
);
}
fn event(change: IssueChange) -> IssueEvent {
let repo: GiteaRepo = serde_json::from_value(serde_json::json!({
"id": 7, "name": "fw", "full_name": "kunde/fw",
}))
.unwrap();
IssueEvent {
repo,
number: 12,
change,
sender: "dev-anna".into(),
}
}
#[tokio::test]
async fn closing_and_reopening_in_gitea_moves_the_finding() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"ibsync_{}",
&uuid::Uuid::new_v4().simple().to_string()[..10]
);
let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP issue_backsync: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id("issue-backsync").await.unwrap();
let target = ObjectId::new().to_hex();
let other_target = ObjectId::new().to_hex();
// Arrange: issue #12 of this target's finding, and #12 of another
// repository's finding (numbers repeat across repositories).
let insert = |repo_id: String, status: FindingStatus| {
let db = db.clone();
async move {
let mut f = Finding::new(
repo_id,
format!("fp-{}", ObjectId::new()),
"semgrep".into(),
ScanType::Sast,
"strcpy".into(),
"d".into(),
Severity::High,
);
f.status = status;
let id = db
.findings()
.insert_one(&f)
.await
.unwrap()
.inserted_id
.as_object_id()
.unwrap();
let issue = TrackerIssue::new(
id.to_hex(),
TrackerType::Gitea,
"12".into(),
"https://kunde.code.breakpilot.com/kunde/fw/issues/12".into(),
"strcpy".into(),
);
db.tracker_issues().insert_one(&issue).await.unwrap();
id
}
};
let other = insert(other_target, FindingStatus::Open).await;
let ours = insert(target.clone(), FindingStatus::NeedsReview).await;
let finding = |id: ObjectId| {
let db = db.clone();
async move {
db.findings()
.find_one(doc! { "_id": id })
.await
.unwrap()
.unwrap()
}
};
let issue_of = |id: ObjectId| {
let db = db.clone();
async move {
db.tracker_issues()
.find_one(doc! { "finding_id": id.to_hex() })
.await
.unwrap()
.unwrap()
}
};
// Act: closed in Gitea.
let done = apply(&db, &target, &event(IssueChange::Closed))
.await
.unwrap();
// Assert: resolved, recorded as closed in the ticket by the user.
assert_eq!(done, BackSynced::Finding);
let f = finding(ours).await;
assert_eq!(f.status, FindingStatus::Resolved);
let last = f.status_history.last().unwrap();
assert_eq!(last.tracker, Some(TrackerChangeKind::ClosedInTracker));
assert_eq!(last.by_name.as_deref(), Some("dev-anna"));
let issue = issue_of(ours).await;
assert_eq!(issue.status, IssueStatus::Closed);
assert_eq!(issue.closed_in_tracker.as_deref(), Some("dev-anna"));
// The other repository's #12 is untouched.
assert_eq!(finding(other).await.status, FindingStatus::Open);
assert_eq!(issue_of(other).await.status, IssueStatus::Open);
// The same delivery again changes nothing more.
let again = apply(&db, &target, &event(IssueChange::Closed))
.await
.unwrap();
assert_eq!(again, BackSynced::IssueOnly);
assert_eq!(finding(ours).await.status_history.len(), 1);
// Reopened in Gitea: undecided again, the closer forgotten.
let done = apply(&db, &target, &event(IssueChange::Reopened))
.await
.unwrap();
assert_eq!(done, BackSynced::Finding);
let f = finding(ours).await;
assert_eq!(f.status, FindingStatus::Open);
assert_eq!(
f.status_history.last().unwrap().tracker,
Some(TrackerChangeKind::ReopenedInTracker)
);
let issue = issue_of(ours).await;
assert_eq!(issue.status, IssueStatus::Open);
assert!(issue.closed_in_tracker.is_none());
// A decision a person made in Prüfwerk is kept on a close.
db.findings()
.update_one(
doc! { "_id": ours },
doc! { "$set": { "status": "accepted_risk" } },
)
.await
.unwrap();
db.tracker_issues()
.update_one(
doc! { "finding_id": ours.to_hex() },
doc! { "$set": { "status": "open" } },
)
.await
.unwrap();
let done = apply(&db, &target, &event(IssueChange::Closed))
.await
.unwrap();
assert_eq!(done, BackSynced::IssueOnly);
assert_eq!(finding(ours).await.status, FindingStatus::AcceptedRisk);
assert_eq!(issue_of(ours).await.status, IssueStatus::Closed);
// An issue Prüfwerk did not open (no record) is not ours.
let mut stranger = event(IssueChange::Closed);
stranger.number = 99;
assert_eq!(
apply(&db, &target, &stranger).await.unwrap(),
BackSynced::NotOurs
);
// A CVE issue: only the record, with who closed it.
let key = format!("cve:{target}:openssl:CVE-2024-0001");
let mut cve = TrackerIssue::new(
key.clone(),
TrackerType::Gitea,
"30".into(),
"https://kunde.code.breakpilot.com/kunde/fw/issues/30".into(),
"[CVE] openssl@3.0.0: CVE-2024-0001".into(),
);
cve.status = IssueStatus::Open;
db.tracker_issues().insert_one(&cve).await.unwrap();
let mut closed = event(IssueChange::Closed);
closed.number = 30;
assert_eq!(apply(&db, &target, &closed).await.unwrap(), BackSynced::Cve);
let stored = db
.tracker_issues()
.find_one(doc! { "finding_id": &key })
.await
.unwrap()
.unwrap();
assert_eq!(stored.status, IssueStatus::Closed);
assert_eq!(stored.closed_in_tracker.as_deref(), Some("dev-anna"));
// Prüfwerk closed it already (the event comes from a bot user other
// than the issue's author, after a token change): no person's close
// is recorded, so a CVE that comes back still reopens it.
let key = format!("cve:{target}:zlib:CVE-2024-0002");
let mut cve = TrackerIssue::new(
key.clone(),
TrackerType::Gitea,
"31".into(),
"https://kunde.code.breakpilot.com/kunde/fw/issues/31".into(),
"[CVE] zlib@1.2.0: CVE-2024-0002".into(),
);
cve.status = IssueStatus::Closed;
db.tracker_issues().insert_one(&cve).await.unwrap();
closed.number = 31;
closed.sender = "pruefwerk-neu".into();
apply(&db, &target, &closed).await.unwrap();
let stored = db
.tracker_issues()
.find_one(doc! { "finding_id": &key })
.await
.unwrap()
.unwrap();
assert!(stored.closed_in_tracker.is_none());
pool.drop_tenant("issue-backsync").await.ok();
}
}
@@ -298,7 +298,6 @@ mod tests {
body: Some(format_issue_body(finding)),
html_url: format!("https://gitea.invalid/o/r/issues/{number}"),
state: "open".into(),
user: None,
}
}
+17 -27
View File
@@ -511,14 +511,9 @@ impl IssueSink<'_> {
finding: &Finding,
title: &str,
) -> Result<TrackerIssue, CoreError> {
let finding_id = finding
.id
.as_ref()
.map(|id| id.to_hex())
.unwrap_or_default();
let mut body = format_issue_body(finding);
if self.managed {
if let Some(link) = finding_link(&self.dashboard, &finding_id) {
if let Some(link) = finding_link(&self.dashboard, self.repo_id) {
body.push_str(&format!(
"\n[Open in Prüfwerk / In Prüfwerk öffnen]({link})"
));
@@ -545,7 +540,11 @@ impl IssueSink<'_> {
.await?
}
};
issue.finding_id = finding_id;
issue.finding_id = finding
.id
.as_ref()
.map(|id| id.to_hex())
.unwrap_or_default();
self.record(finding, &issue).await;
Ok(issue)
}
@@ -707,18 +706,13 @@ fn cra_requirements(control_refs: &[String]) -> Vec<String> {
.collect()
}
/// A finding's page in the Prüfwerk dashboard (#947), where its status is
/// set; a group (#464) has its own id and so its own page. `None` unless the
/// dashboard's public origin is an https URL and the finding has an id.
///
/// # Arguments
///
/// * `dashboard` - the dashboard's public origin (`DASHBOARD_PUBLIC_URL`)
/// * `finding_id` - the finding's id as hex, empty when it has none
fn finding_link(dashboard: &str, finding_id: &str) -> Option<String> {
/// The finding list of a target in the Prüfwerk dashboard; `None` unless the
/// dashboard's public origin is an https URL.
fn finding_link(dashboard: &str, target_id: &str) -> Option<String> {
let dashboard = dashboard.trim_end_matches('/');
(dashboard.starts_with("https://") && !finding_id.is_empty())
.then(|| format!("{dashboard}/findings/{finding_id}"))
dashboard
.starts_with("https://")
.then(|| format!("{dashboard}/findings?target={target_id}"))
}
/// The ids of `names` among the ensured labels; a name without an id is left
@@ -819,7 +813,6 @@ mod tests {
body: body.map(str::to_string),
html_url: format!("https://gitea.invalid/o/r/issues/{number}"),
state: "open".into(),
user: None,
}
}
@@ -931,16 +924,13 @@ mod tests {
}
#[test]
fn links_the_finding_page_of_an_https_dashboard() {
let id = "6560a1b2c3d4e5f601234567";
fn links_only_to_an_https_dashboard() {
assert_eq!(
finding_link("https://pruefwerk.breakpilot.com/", id).as_deref(),
Some("https://pruefwerk.breakpilot.com/findings/6560a1b2c3d4e5f601234567")
finding_link("https://pruefwerk.breakpilot.com/", "t1").as_deref(),
Some("https://pruefwerk.breakpilot.com/findings?target=t1")
);
assert_eq!(finding_link("", id), None);
assert_eq!(finding_link("http://x", id), None);
// a finding without an id has no page to link
assert_eq!(finding_link("https://pruefwerk.breakpilot.com", ""), None);
assert_eq!(finding_link("", "t1"), None);
assert_eq!(finding_link("http://x", "t1"), None);
}
#[test]
-455
View File
@@ -1,455 +0,0 @@
//! Issues closed or reopened in Gitea, learnt by polling (#953).
//!
//! The back-sync ([`super::issue_backsync`]) first came from the managed git
//! source's organisation webhook. Most targets have no such webhook: they are
//! repositories with a Gitea issue tracker. So at every sync interval the poll
//! lists the issues of each target that has Prüfwerk issues (one listing per
//! repository, as a scan makes), compares their state with Prüfwerk's records
//! and, for each that differs, reads from the issue's timeline who closed or
//! reopened it. A person's change is carried back as a webhook delivery is;
//! Prüfwerk's own (its bot user opened the issue) is left alone. Where a
//! webhook delivered the change already, the records match and the poll has
//! nothing to do.
use std::collections::HashMap;
use futures_util::TryStreamExt;
use mongodb::bson::{doc, Bson};
use compliance_core::models::issue::cve_issue_prefix;
use compliance_core::models::{OnboardedTarget, TrackerIssue, TrackerType};
use compliance_core::{AgentConfig, NetGuard};
use crate::agent::ComplianceAgent;
use crate::database::Database;
use crate::error::AgentError;
use crate::git_source::events::{is_own_event, IssueChange};
use crate::pipeline::issue_backsync::{apply_change, BackSynced};
use crate::pipeline::issue_creation::build_tracker;
use crate::pipeline::repo_view::RepoView;
use crate::pipeline::tracker_dispatch::TrackerDispatch;
use crate::secrets::SecretBox;
use crate::trackers::gitea::GiteaIssue;
/// What one poll of a tenant did: counts only, for the log.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub(crate) struct PollSummary {
/// Targets whose issues were listed.
pub targets: u32,
/// Findings resolved or reopened.
pub findings: u32,
/// Issues whose state was recorded without a finding change (a decision
/// a person had made stays; a CVE issue).
pub recorded: u32,
/// Targets whose tracker could not be read.
pub failed: u32,
}
/// What the poll of one target needs, owned by the agent.
#[derive(Clone, Copy)]
struct PollContext<'a> {
db: &'a Database,
config: &'a AgentConfig,
net_guard: NetGuard,
secrets: &'a SecretBox,
}
/// The issues of `listed` whose state differs from Prüfwerk's record of it
/// (`records`: number to closed), with the change and the issue's author.
/// Issues Prüfwerk has no record of are not its own and left out.
fn changes<'a>(
records: &HashMap<i64, bool>,
listed: &'a [GiteaIssue],
) -> Vec<(i64, IssueChange, &'a str)> {
listed
.iter()
.filter_map(
|issue| match (records.get(&issue.number)?, issue.is_closed()) {
(false, true) => Some((issue.number, IssueChange::Closed, issue.author())),
(true, false) => Some((issue.number, IssueChange::Reopened, issue.author())),
(true, true) | (false, false) => None,
},
)
.collect()
}
/// Prüfwerk's Gitea issues of target `target_id`, by number: whether each
/// is closed. A finding's issue is found through the finding (storing an
/// issue sets the finding's `tracker_issue_url`), a CVE issue by its key.
///
/// # Errors
///
/// A database error.
async fn records(db: &Database, target_id: &str) -> Result<HashMap<i64, bool>, AgentError> {
let ticketed = db
.findings()
.distinct(
"_id",
doc! { "repo_id": target_id, "tracker_issue_url": { "$ne": Bson::Null } },
)
.await?;
let finding_ids: Vec<String> = ticketed
.iter()
.filter_map(Bson::as_object_id)
.map(|id| id.to_hex())
.collect();
let cve = format!("^{}", regex::escape(&cve_issue_prefix(target_id)));
let issues: Vec<TrackerIssue> = db
.tracker_issues()
.find(doc! {
"tracker_type": TrackerType::Gitea.to_string(),
"$or": [
{ "finding_id": { "$in": finding_ids } },
{ "finding_id": { "$regex": cve } },
],
})
.await?
.try_collect()
.await?;
Ok(issues
.iter()
.filter_map(|i| Some((i.external_id.parse().ok()?, i.status.is_closed())))
.collect())
}
/// Poll the issues of `target` and carry a person's closes and reopens
/// back. A target without a Gitea tracker or without Prüfwerk issues is
/// skipped without asking Gitea anything.
///
/// # Errors
///
/// The records cannot be read, or Gitea cannot be listed or asked for a
/// timeline: the next poll tries again.
async fn poll_target(
ctx: PollContext<'_>,
target: &OnboardedTarget,
summary: &mut PollSummary,
) -> Result<(), AgentError> {
let (Some(id), Some(code)) = (target.id.map(|id| id.to_hex()), target.code_artifact()) else {
return Ok(());
};
let repo = RepoView::from_target(target, code, ctx.secrets);
let Some(TrackerDispatch::Gitea(gitea)) = build_tracker(ctx.config, ctx.net_guard, &repo)
else {
return Ok(());
};
let (Some(owner), Some(name)) = (repo.tracker_owner.as_deref(), repo.tracker_repo.as_deref())
else {
return Ok(());
};
let records = records(ctx.db, &id).await?;
if records.is_empty() {
return Ok(());
}
summary.targets += 1;
let listed = gitea.list_issues(owner, name).await?;
for (number, change, author) in changes(&records, &listed) {
let closed = change == IssueChange::Closed;
let Some(by) = gitea
.last_state_change_by(owner, name, number, closed)
.await?
.filter(|by| !is_own_event(by, author))
else {
// Prüfwerk's own change whose record was not written, or a
// timeline without the entry: nothing a person decided.
continue;
};
match apply_change(ctx.db, &id, number, change, &by).await? {
BackSynced::Finding => summary.findings += 1,
BackSynced::IssueOnly | BackSynced::Cve => summary.recorded += 1,
BackSynced::NotOurs => {}
}
}
Ok(())
}
/// Poll every active target of tenant `tenant_id`, one after the other so a
/// small Gitea sees one listing at a time.
///
/// # Errors
///
/// Automation is not allowed for the tenant (the same entitlement and
/// ladder rules as the webhook), or its targets cannot be read. A target
/// that fails is counted in [`PollSummary::failed`] and logged.
pub(crate) async fn poll_tenant(
agent: &ComplianceAgent,
tenant_id: &str,
) -> Result<PollSummary, AgentError> {
crate::git_source::automation_allowed(agent, tenant_id)
.await
.map_err(AgentError::Other)?;
let db = agent.db_pool.for_tenant_id(tenant_id).await?;
let targets: Vec<OnboardedTarget> = db
.onboarded_targets()
.find(doc! { "archived_at": null })
.await?
.try_collect()
.await?;
let ctx = PollContext {
db: &db,
config: &agent.config,
net_guard: agent.net_guard,
secrets: &agent.secrets,
};
let mut summary = PollSummary::default();
for target in &targets {
if let Err(e) = poll_target(ctx, target, &mut summary).await {
summary.failed += 1;
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
tracing::warn!(tenant_id, target_id, "issue poll failed: {e}");
}
}
Ok(summary)
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use axum::extract::{Path, Query};
use axum::routing::get;
use axum::{Json, Router};
use compliance_core::models::{
Artifact, Finding, FindingStatus, IssueStatus, IssueTrackerConfig, ScanType, Severity,
TargetType, TrackerChangeKind,
};
use mongodb::bson::oid::ObjectId;
use super::*;
/// A fake Gitea: issue #12 closed by a person, #13 closed by the bot
/// that opened it, #14 reopened by a person, #15 not Prüfwerk's. Every
/// list ends with an empty page, as Gitea's do.
async fn fake_gitea() -> String {
fn page<T: Into<serde_json::Value>>(
q: &HashMap<String, String>,
items: T,
) -> Json<serde_json::Value> {
if q.get("page").map(String::as_str) == Some("1") {
Json(items.into())
} else {
Json(serde_json::json!([]))
}
}
async fn issues(
Path((_o, _r)): Path<(String, String)>,
Query(q): Query<HashMap<String, String>>,
) -> Json<serde_json::Value> {
let issue = |n: i64, state: &str| serde_json::json!({ "number": n, "title": "t", "state": state, "user": { "login": "pruefwerk-bot" } });
page(
&q,
serde_json::json!([
issue(12, "closed"),
issue(13, "closed"),
issue(14, "open"),
issue(15, "closed")
]),
)
}
async fn timeline(
Path((_o, _r, n)): Path<(String, String, i64)>,
Query(q): Query<HashMap<String, String>>,
) -> Json<serde_json::Value> {
let event = |kind: &str, login: &str| serde_json::json!({ "type": kind, "user": { "login": login } });
let events = match n {
12 => serde_json::json!([
event("comment", "pruefwerk-bot"),
event("close", "dev-anna")
]),
13 => serde_json::json!([
event("close", "dev-anna"),
event("reopen", "dev-anna"),
event("close", "Pruefwerk-Bot")
]),
14 => {
serde_json::json!([event("close", "pruefwerk-bot"), event("reopen", "dev-ben")])
}
_ => serde_json::json!([event("close", "dev-anna")]),
};
page(&q, events)
}
let app = Router::new()
.route("/api/v1/repos/{o}/{r}/issues", get(issues))
.route("/api/v1/repos/{o}/{r}/issues/{n}/timeline", get(timeline));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
format!("http://{addr}")
}
#[tokio::test]
async fn a_persons_close_or_reopen_in_gitea_is_carried_back_and_the_bots_is_not() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!("ipoll_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP issue_poll: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id("issue-poll").await.unwrap();
let base = fake_gitea().await;
// Arrange: a target with a Gitea tracker, two open findings with
// issues #12 and #13, and the CVE issue #14 (closed by Prüfwerk).
let mut target = OnboardedTarget::new("fw".into(), TargetType::BackendService);
target
.artifacts
.push(Artifact::git_repo(format!("{base}/kunde/fw.git"), "main"));
target.scan_config.issue_tracker = Some(IssueTrackerConfig {
tracker_type: Some(TrackerType::Gitea),
owner: Some("kunde".into()),
repo: Some("fw".into()),
token: Some("bot-token".into()),
});
let target_id = db
.onboarded_targets()
.insert_one(&target)
.await
.unwrap()
.inserted_id
.as_object_id()
.unwrap();
target.id = Some(target_id);
let target_hex = target_id.to_hex();
let with_issue = |number: &str| {
let db = db.clone();
let target_hex = target_hex.clone();
let base = base.clone();
let number = number.to_string();
async move {
let url = format!("{base}/kunde/fw/issues/{number}");
let mut f = Finding::new(
target_hex,
format!("fp-{number}"),
"semgrep".into(),
ScanType::Sast,
"strcpy".into(),
"d".into(),
Severity::High,
);
f.tracker_issue_url = Some(url.clone());
let id = db
.findings()
.insert_one(&f)
.await
.unwrap()
.inserted_id
.as_object_id()
.unwrap();
let issue = TrackerIssue::new(
id.to_hex(),
TrackerType::Gitea,
number,
url,
"strcpy".into(),
);
db.tracker_issues().insert_one(&issue).await.unwrap();
id
}
};
let closed_by_anna = with_issue("12").await;
let closed_by_bot = with_issue("13").await;
let mut cve = TrackerIssue::new(
format!("{}openssl:CVE-2026-1", cve_issue_prefix(&target_hex)),
TrackerType::Gitea,
"14".into(),
format!("{base}/kunde/fw/issues/14"),
"CVE-2026-1".into(),
);
cve.status = IssueStatus::Closed;
db.tracker_issues().insert_one(&cve).await.unwrap();
let ctx = PollContext {
db: &db,
config: &AgentConfig::default(),
net_guard: NetGuard::allow_private(),
secrets: &SecretBox::without_key(),
};
// Act
let mut summary = PollSummary::default();
poll_target(ctx, &target, &mut summary).await.unwrap();
// Assert: Anna's close resolved her finding, the bot's left the
// other alone, Ben's reopen of the CVE issue is recorded.
assert_eq!(
summary,
PollSummary {
targets: 1,
findings: 1,
recorded: 1,
failed: 0
}
);
let finding = |id: ObjectId| {
let db = db.clone();
async move {
db.findings()
.find_one(doc! { "_id": id })
.await
.unwrap()
.unwrap()
}
};
let resolved = finding(closed_by_anna).await;
assert_eq!(resolved.status, FindingStatus::Resolved);
let last = resolved.status_history.last().unwrap();
assert_eq!(
(last.tracker, last.by_name.as_deref()),
(Some(TrackerChangeKind::ClosedInTracker), Some("dev-anna"))
);
assert_eq!(finding(closed_by_bot).await.status, FindingStatus::Open);
let issue = |number: &str| {
let db = db.clone();
let number = number.to_string();
async move {
db.tracker_issues()
.find_one(doc! { "external_id": number })
.await
.unwrap()
.unwrap()
}
};
let twelve = issue("12").await;
assert_eq!(
(twelve.status, twelve.closed_in_tracker.as_deref()),
(IssueStatus::Closed, Some("dev-anna"))
);
assert_eq!(issue("13").await.status, IssueStatus::Open);
assert_eq!(issue("14").await.status, IssueStatus::Open);
// A second poll finds the records matching (the bot's close aside,
// which stays a person's to decide): nothing more changes.
let mut again = PollSummary::default();
poll_target(ctx, &target, &mut again).await.unwrap();
assert_eq!((again.findings, again.recorded), (0, 0));
pool.drop_tenant("issue-poll").await.ok();
}
fn listed(number: i64, state: &str, author: &str) -> GiteaIssue {
serde_json::from_value(serde_json::json!({
"number": number, "title": "t", "state": state,
"user": { "login": author },
}))
.unwrap()
}
#[test]
fn only_issues_whose_state_differs_from_the_record_are_changes() {
let records: HashMap<i64, bool> = [(1, false), (2, true), (3, false), (4, true)].into();
let issues = [
listed(1, "closed", "bot"),
listed(2, "open", "bot"),
listed(3, "open", "bot"),
listed(4, "closed", "bot"),
// Not Prüfwerk's: no record.
listed(5, "closed", "dev-anna"),
];
assert_eq!(
changes(&records, &issues),
[
(1, IssueChange::Closed, "bot"),
(2, IssueChange::Reopened, "bot")
]
);
}
}
+5 -103
View File
@@ -170,40 +170,19 @@ impl IssueSync {
let Some(id) = issue.id else {
return Ok(());
};
let update = issue_state_update(&status, None).map_err(|e| e.to_string())?;
let status = mongodb::bson::to_bson(&status).map_err(|e| e.to_string())?;
self.db
.tracker_issues()
.update_one(doc! { "_id": id }, update)
.update_one(
doc! { "_id": id },
doc! { "$set": { "status": status, "updated_at": mongodb::bson::DateTime::now() } },
)
.await
.map(drop)
.map_err(|e| e.to_string())
}
}
/// The update that stores an issue's new `status`. `closed_by` is the
/// tracker user who closed it there (#953); when Prüfwerk changes the state,
/// or the issue is reopened, it is `None` and an earlier closer is cleared.
///
/// # Errors
///
/// The status cannot be written as BSON.
pub(crate) fn issue_state_update(
status: &IssueStatus,
closed_by: Option<&str>,
) -> Result<mongodb::bson::Document, mongodb::bson::ser::Error> {
let mut set = doc! {
"status": mongodb::bson::to_bson(status)?,
"updated_at": mongodb::bson::DateTime::now(),
};
Ok(match closed_by {
Some(login) => {
set.insert("closed_in_tracker", login);
doc! { "$set": set }
}
None => doc! { "$set": set, "$unset": { "closed_in_tracker": "" } },
})
}
/// The `risk:accepted` label id per target (`Finding::repo_id`), once
/// resolved; `None` for a target whose repository has no such label.
type RiskLabels = HashMap<String, Option<i64>>;
@@ -513,69 +492,6 @@ mod tests {
assert_eq!(tail, ["state 12: \"closed\"", "labels 12: [42]"]);
}
// Reopened, then a person closes the issue in Gitea (#953): the
// back-sync resolves the finding and records the issue closed, so the
// sync neither comments nor closes it again.
db.findings()
.update_one(
doc! { "_id": finding_id },
doc! { "$set": { "status": "open" } },
)
.await
.unwrap();
sync.sync_one(finding_id, &mut RiskLabels::new())
.await
.unwrap();
assert_eq!(issue_status().await, IssueStatus::Open);
let event = crate::git_source::events::IssueEvent {
repo: serde_json::from_value(serde_json::json!({
"id": 7, "name": "fw", "full_name": "kunde/fw",
}))
.unwrap(),
number: 12,
change: crate::git_source::events::IssueChange::Closed,
sender: "dev-anna".into(),
};
crate::pipeline::issue_backsync::apply(&db, &target_id.to_hex(), &event)
.await
.unwrap();
let before = calls.lock().unwrap().len();
sync.sync_one(finding_id, &mut RiskLabels::new())
.await
.unwrap();
assert_eq!(calls.lock().unwrap().len(), before, "nothing sent to Gitea");
assert_eq!(issue_status().await, IssueStatus::Closed);
// Found again by the next scan: reopened with the usual comment.
db.findings()
.update_one(
doc! { "_id": finding_id },
doc! {
"$set": { "status": "open" },
"$push": { "status_history": mongodb::bson::to_bson(&by_scan(
FindingStatus::Open,
ScanChangeKind::FoundAgain,
)).unwrap() },
},
)
.await
.unwrap();
sync.sync_one(finding_id, &mut RiskLabels::new())
.await
.unwrap();
{
let calls = calls.lock().unwrap();
assert!(calls[before].contains("erneut gefunden"));
assert_eq!(calls[before + 1], "state 12: \"open\"");
}
let reopened = db
.tracker_issues()
.find_one(doc! { "finding_id": finding_id.to_hex() })
.await
.unwrap()
.unwrap();
assert!(reopened.closed_in_tracker.is_none());
pool.drop_tenant("issue-sync").await.ok();
}
@@ -610,20 +526,6 @@ mod tests {
StatusChange::by_scan(status, kind, "run-1")
}
#[test]
fn the_issue_state_keeps_who_closed_it_in_the_tracker_until_it_reopens() {
let closed = issue_state_update(&IssueStatus::Closed, Some("dev-anna")).unwrap();
let set = closed.get_document("$set").unwrap();
assert_eq!(set.get_str("status").unwrap(), "closed");
assert_eq!(set.get_str("closed_in_tracker").unwrap(), "dev-anna");
assert!(!closed.contains_key("$unset"));
let by_pruefwerk = issue_state_update(&IssueStatus::Open, None).unwrap();
assert!(by_pruefwerk
.get_document("$unset")
.unwrap()
.contains_key("closed_in_tracker"));
}
#[test]
fn closing_statuses_close_and_open_ones_reopen() {
assert_eq!(
@@ -27,7 +27,6 @@ fn language_of(extension: &str) -> Option<&'static str> {
"cs" => "csharp",
"vb" => "vb",
"swift" => "swift",
"dart" => "dart",
// Objective-C; `.m` is also MATLAB's extension, which only means
// mobsfscan looks at a tree it finds nothing in.
"m" | "mm" => "objc",
+1 -5
View File
@@ -5,7 +5,6 @@ pub mod change;
pub mod clamav;
pub mod clone_limit;
pub mod code_review;
pub(crate) mod component_changes;
pub mod cppcheck;
pub(crate) mod csaf_feed;
pub(crate) mod csaf_match;
@@ -13,7 +12,6 @@ pub mod cve;
pub(crate) mod cve_enrichment;
pub(crate) mod cve_issues;
pub mod cve_notify;
pub mod dast_findings;
pub mod dedup;
pub mod devskim;
pub mod dotnet;
@@ -25,13 +23,11 @@ pub mod git;
pub mod git_retry;
pub mod git_submodules;
pub mod gitleaks;
pub(crate) mod graph_build;
mod graph_build;
pub mod grouping;
pub mod ios_config;
pub(crate) mod issue_backsync;
mod issue_catchup;
pub(crate) mod issue_creation;
pub(crate) mod issue_poll;
pub(crate) mod issue_sync;
pub mod languages;
pub mod license_policy;
+52 -279
View File
@@ -82,10 +82,6 @@ pub struct PipelineOrchestrator {
/// The tenant's plan limits for metering (t72); `None` when not known,
/// and then counted Prüfungen are neither checked nor charged.
pub(super) plan_limits: Option<PlanLimits>,
/// Set when this person's scan took over a waiting scheduled, webhook or
/// new-content scan (t84): the trigger it is charged as. Change detection
/// then decides whether it counts, as for that scan.
pub(super) charged_as: Option<ScanTrigger>,
}
impl PipelineOrchestrator {
@@ -103,17 +99,9 @@ impl PipelineOrchestrator {
exploit_cache: None,
advisory_index: None,
plan_limits: None,
charged_as: None,
}
}
/// Charge this run as a scan started by `trigger` would be, when a
/// person's request took that waiting scan over (t84).
pub(crate) fn with_charged_as(mut self, trigger: Option<ScanTrigger>) -> Self {
self.charged_as = trigger;
self
}
/// Check and charge counted Prüfungen against `limits` (t72).
pub(crate) fn with_plan_limits(mut self, limits: Option<PlanLimits>) -> Self {
self.plan_limits = limits;
@@ -239,16 +227,6 @@ impl PipelineOrchestrator {
repo.billing,
)
.await?;
} else if let Some(original) = &self.charged_as {
let new_commits =
GitOps::has_new_commits(&repo_path, repo.last_scanned_commit.as_deref())?;
self.charge_as_taken_over(
scan_run_id,
&repo_id,
ScanAttribution::detected(original, new_commits || repo.changed_besides_commits),
repo.billing,
)
.await?;
}
// Submodules are part of what the product ships (a HAL, an RTOS).
@@ -538,8 +516,7 @@ impl PipelineOrchestrator {
// the project's own code, which this deployment may not. Syft reports
// nothing for it, so say so rather than leaving the gap in an SBOM that
// looks complete.
let unlocked = crate::pipeline::sbom::unlocked_ecosystems(&repo_path, &resolved_nuget);
for eco in &unlocked {
for eco in crate::pipeline::sbom::unlocked_ecosystems(&repo_path, &resolved_nuget) {
self.skip_stage(
scan_run_id,
SkippedStage::new(
@@ -550,7 +527,7 @@ impl PipelineOrchestrator {
eco.manifest, eco.problem, eco.remedy
),
)
.about(eco.manifest.clone()),
.about(eco.manifest),
)
.await;
}
@@ -643,49 +620,6 @@ impl PipelineOrchestrator {
}
}
// Why the SBOM is empty or incomplete (#979): code with no manifest
// at all, and manifests whose dependencies were not resolved. Every
// code scan completes this check, so a finding closes at the next
// scan that finds the manifest or lockfile. A firmware SBOM, which
// the firmware step stored before this, counts as an SBOM.
let firmware_sbom = self
.db
.sbom_entries()
.count_documents(doc! {
"repo_id": &repo_id,
"package_manager": {
"$in": crate::pipeline::firmware_sbom::FIRMWARE_MANAGERS.to_vec()
},
})
.limit(1)
.await?
> 0;
let (coverage, entries) = {
let (root, vendor, languages) = (repo_path.clone(), vendor.clone(), languages.clone());
let (target, yocto_layers) = (repo_id.clone(), repo.yocto_layers);
tokio::task::spawn_blocking(move || {
use crate::pipeline::sbom::coverage::{coverage_findings, ScannedTree};
let tree = ScannedTree {
repo_id: &target,
root: &root,
vendor: &vendor,
languages: &languages,
yocto_layers,
firmware_sbom,
};
(
coverage_findings(&tree, &sbom_entries, &unlocked),
sbom_entries,
)
})
.await
.map_err(|e| AgentError::Other(format!("SBOM coverage check: {e}")))?
};
sbom_entries = entries;
run_findings.completed(crate::pipeline::sbom::coverage::SCANNER);
all_findings.extend(coverage);
run_findings.save_new(&self.db, &mut all_findings).await?;
// Stage 3: CVE Scanning
tracing::info!("[{repo_id}] Stage 3: CVE Scanning");
self.update_phase(scan_run_id, ScanPhase::CveScanning).await;
@@ -1004,12 +938,8 @@ impl PipelineOrchestrator {
self.update_phase(scan_run_id, ScanPhase::GraphBuilding)
.await;
let graph_context = match async {
self.build_code_graph(
crate::pipeline::graph_build::GraphSource::Tree(&repo_path),
&repo_id,
&all_findings,
)
.await
self.build_code_graph(&repo_path, &repo_id, &all_findings)
.await
}
.instrument(tracing::info_span!("stage_graph_building"))
.await
@@ -1132,23 +1062,15 @@ impl PipelineOrchestrator {
// nothing, so dependencies removed from a repo used to stay in its SBOM
// forever.
if !sbom_entries.is_empty() {
let scope = doc! {
"package_manager": {
"$nin": crate::pipeline::firmware_sbom::FIRMWARE_MANAGERS.to_vec()
},
};
// What this replaces, for the target's history (#974).
crate::pipeline::component_changes::record(
&self.db,
scan_run_id,
&repo_id,
scope.clone(),
&sbom_entries,
)
.await;
let mut filter = doc! { "repo_id": &repo_id };
filter.extend(scope);
self.db.sbom_entries().delete_many(filter).await?;
self.db
.sbom_entries()
.delete_many(doc! {
"repo_id": &repo_id,
"package_manager": {
"$nin": crate::pipeline::firmware_sbom::FIRMWARE_MANAGERS.to_vec()
},
})
.await?;
}
// Persist SBOM entries
@@ -1233,9 +1155,7 @@ impl PipelineOrchestrator {
/// `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))]
/// Run one scan of the target `target_id`, recorded on the run `queued`
/// that waited for this scan's slot (t84), or on a new run when there is
/// none.
/// Run one scan of the target `target_id`.
///
/// # Returns
///
@@ -1250,7 +1170,6 @@ impl PipelineOrchestrator {
&self,
target_id: &str,
trigger: ScanTrigger,
queued: Option<&str>,
) -> Result<TargetScanOutcome, AgentError> {
let oid = mongodb::bson::oid::ObjectId::parse_str(target_id)
.map_err(|e| AgentError::Other(e.to_string()))?;
@@ -1266,15 +1185,14 @@ impl PipelineOrchestrator {
// detection attributes the others (t72).
if let Some(attribution) = ScanAttribution::of_person(&trigger) {
scan_run.attribution = Some(attribution);
// One that took over a waiting scan counts only as that scan
// would have; change detection decides below (t84).
scan_run.chargeable =
self.charged_as.is_none() && attribution.chargeable(target.billing);
scan_run.chargeable = attribution.chargeable(target.billing);
}
scan_run.charged_as = self.charged_as.clone();
let run_oid = self.start_run(&scan_run, queued).await?;
let scan_run_id = run_oid.to_hex();
let run_id = mongodb::bson::Bson::ObjectId(run_oid);
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();
// A counted Prüfung a person started is checked against the plan
// before anything runs (t72).
@@ -1308,7 +1226,10 @@ impl PipelineOrchestrator {
}
self.db
.scan_runs()
.update_one(doc! { "_id": &run_id }, doc! { "$set": completed })
.update_one(
doc! { "_id": &insert.inserted_id },
doc! { "$set": completed },
)
.await?;
// Refresh the target's cached findings count. The shared pipeline
// (Stage 7) increments `repositories`, which the unified path does
@@ -1345,7 +1266,7 @@ impl PipelineOrchestrator {
self.db
.scan_runs()
.update_one(
doc! { "_id": &run_id },
doc! { "_id": &insert.inserted_id },
doc! { "$set": {
"status": "completed",
"current_phase": "completed",
@@ -1360,7 +1281,7 @@ impl PipelineOrchestrator {
self.db
.scan_runs()
.update_one(
doc! { "_id": &run_id },
doc! { "_id": &insert.inserted_id },
doc! { "$set": {
"status": "failed",
"error_message": message,
@@ -1380,7 +1301,7 @@ impl PipelineOrchestrator {
let run = self
.db
.scan_runs()
.find_one(doc! { "_id": &run_id })
.find_one(doc! { "_id": &insert.inserted_id })
.await
.ok()
.flatten();
@@ -1394,7 +1315,7 @@ impl PipelineOrchestrator {
// A counted Prüfung is charged when it completed, or when it failed on
// the customer's input; a failure of ours never is (t72).
let charged = if chargeable && ((result.is_ok() && !unchanged) || invalid_input) {
self.charge_run(&run_id, target_id).await
self.charge_run(&insert.inserted_id, target_id).await
} else {
None
};
@@ -1409,59 +1330,6 @@ impl PipelineOrchestrator {
})
}
/// Record that `run` starts now: on the run `queued` that waited for the
/// slot, which moves from `queued` to `running`, or as a new run when
/// there is none or it is gone. Returns the run's id.
///
/// # Errors
///
/// The run could not be written.
async fn start_run(
&self,
run: &ScanRun,
queued: Option<&str>,
) -> Result<mongodb::bson::oid::ObjectId, AgentError> {
if let Some(oid) = queued.and_then(|id| mongodb::bson::oid::ObjectId::parse_str(id).ok()) {
let mut started = doc! {
"status": "running",
"trigger": mongodb::bson::to_bson(&run.trigger)
.map_err(|e| AgentError::Other(e.to_string()))?,
"started_at": mongodb::bson::DateTime::from_chrono(run.started_at),
"chargeable": run.chargeable,
};
if let Some(charged_as) = &run.charged_as {
started.insert(
"charged_as",
mongodb::bson::to_bson(charged_as)
.map_err(|e| AgentError::Other(e.to_string()))?,
);
}
if let Some(attribution) = run.attribution {
started.insert(
"attribution",
mongodb::bson::to_bson(&attribution)
.map_err(|e| AgentError::Other(e.to_string()))?,
);
}
let updated = self
.db
.scan_runs()
.update_one(
doc! { "_id": oid, "status": "queued" },
doc! { "$set": started },
)
.await?;
if updated.matched_count == 1 {
return Ok(oid);
}
}
let insert = self.db.scan_runs().insert_one(run).await?;
insert
.inserted_id
.as_object_id()
.ok_or_else(|| AgentError::Other("the scan run got no id".into()))
}
/// Check a counted Prüfung against the plan before it scans (t72):
/// the quota, today's Prüftag on the target, the customer's cap. It runs
/// when the plan's limits or the usage are not known.
@@ -1560,40 +1428,6 @@ impl PipelineOrchestrator {
Ok(())
}
/// Count the run `scan_run_id`, a person's request that took over a
/// waiting scan, only when `detected` (that scan's attribution from change
/// detection) counts on a target billed as `billing`, and then check it
/// against the plan (t84). The run keeps the person's attribution, so its
/// history shows that a person asked. Several code artifacts: a change in
/// any of them counts it, as in [`Self::attribute_run`].
///
/// # Errors
///
/// [`AgentError::NotAdmitted`] when the plan does not allow a counted
/// Prüfung now.
async fn charge_as_taken_over(
&self,
scan_run_id: &str,
target_id: &str,
detected: ScanAttribution,
billing: TargetBilling,
) -> Result<(), AgentError> {
if !detected.chargeable(billing) {
return Ok(());
}
if let Ok(oid) = mongodb::bson::oid::ObjectId::parse_str(scan_run_id) {
if let Err(e) = self
.db
.scan_runs()
.update_one(doc! { "_id": oid }, doc! { "$set": { "chargeable": true } })
.await
{
tracing::warn!(scan_run_id, "scan run not marked as counted: {e}");
}
}
self.admit_run(scan_run_id, target_id).await
}
/// Store `attribution` and `chargeable` on the run, unless it already
/// reads as a change.
async fn record_attribution(
@@ -1668,25 +1502,17 @@ impl PipelineOrchestrator {
return Ok(0);
}
// A git target is attributed where its commits are compared.
if !has_git {
let changed = crate::pipeline::change::content_changed(target);
if !trigger.started_by_person() {
self.attribute_run(
scan_run_id,
&target_id,
ScanAttribution::detected(trigger, changed),
target.billing,
)
.await?;
} else if let Some(original) = &self.charged_as {
self.charge_as_taken_over(
scan_run_id,
&target_id,
ScanAttribution::detected(original, changed),
target.billing,
)
.await?;
}
if !trigger.started_by_person() && !has_git {
self.attribute_run(
scan_run_id,
&target_id,
ScanAttribution::detected(
trigger,
crate::pipeline::change::content_changed(target),
),
target.billing,
)
.await?;
}
let plan = build_scan_plan(target);
// An attached artifact nothing analyses is recorded, never passed over:
@@ -1763,7 +1589,7 @@ impl PipelineOrchestrator {
if plan.has(ScanType::Dast) {
self.update_phase(scan_run_id, ScanPhase::DastScanning)
.await;
new_count += self.maybe_trigger_dast(&target_id, scan_run_id).await;
self.maybe_trigger_dast(&target_id, scan_run_id).await;
}
return Ok(new_count);
}
@@ -1801,8 +1627,7 @@ impl PipelineOrchestrator {
let n = self.run_pipeline(&repo, scan_run_id, trigger).await?;
self.finalize_target(target, &repo, n).await?;
new_count += n;
new_count += self
.dast_after_code_scan(&target_id, &plan, scan_run_id)
self.dast_after_code_scan(&target_id, &plan, scan_run_id)
.await;
}
Some(code) => {
@@ -1819,8 +1644,7 @@ impl PipelineOrchestrator {
let n = self.scan_tree(tree, upload, &repo, scan_run_id).await?;
self.finalize_target(target, &repo, n).await?;
new_count += n;
new_count += self
.dast_after_code_scan(&target_id, &plan, scan_run_id)
self.dast_after_code_scan(&target_id, &plan, scan_run_id)
.await;
}
// The ingest stage recorded why. A run over nothing must not
@@ -1856,7 +1680,7 @@ impl PipelineOrchestrator {
);
self.update_phase(scan_run_id, ScanPhase::DastScanning)
.await;
new_count += self.maybe_trigger_dast(&target_id, scan_run_id).await;
self.maybe_trigger_dast(&target_id, scan_run_id).await;
}
}
}
@@ -1899,8 +1723,6 @@ impl PipelineOrchestrator {
// Each source's findings next to the tree they were found in: the
// control mapping below reads the flagged regions from it.
let mut analysed = Vec::with_capacity(sources.len());
// Every tree's POUs, for the code graph.
let mut plc_files = Vec::new();
let mut all_sbom: Vec<SbomEntry> = Vec::new();
let mut sbom_seen = std::collections::BTreeSet::new();
// CODESYS projects in their native format: their control logic is not
@@ -1919,12 +1741,10 @@ impl PipelineOrchestrator {
left_out.excluded.extend(pruned.excluded);
left_out.test_data.extend(pruned.test_data);
native.extend(crate::pipeline::plc::native_projects(&path));
let files = crate::pipeline::plc::read_tree(&path);
analysed.push((
path.clone(),
crate::pipeline::plc::findings(&files, target_id),
crate::pipeline::plc::analyze_tree(&path, target_id),
));
plc_files.extend(files);
// Control-application SBOM: CODESYS libraries + runtime from a
// `.projectarchive` (uploaded, or committed in the working tree).
let archive = a
@@ -1986,21 +1806,6 @@ impl PipelineOrchestrator {
"PLC control-logic analysis complete"
);
// The POUs and how they use each other, as for a code scan; a stale
// graph is replaced even when no POU was read.
self.update_phase(scan_run_id, ScanPhase::GraphBuilding)
.await;
if let Err(e) = self
.build_code_graph(
crate::pipeline::graph_build::GraphSource::Plc(&plc_files),
target_id,
&all_findings,
)
.await
{
tracing::warn!(target_id, error = %e, "PLC graph building failed");
}
let mut new_count = 0u32;
let mut refreshed_count = 0u32;
for mut finding in all_findings {
@@ -2224,14 +2029,6 @@ impl PipelineOrchestrator {
if entries.is_empty() {
return Ok(());
}
crate::pipeline::component_changes::record(
&self.db,
scan_run_id,
target_id,
doc! { "package_manager": "codesys" },
&entries,
)
.await;
self.db
.sbom_entries()
.delete_many(doc! { "repo_id": target_id, "package_manager": "codesys" })
@@ -2527,16 +2324,6 @@ impl PipelineOrchestrator {
}
};
if !entries.is_empty() {
crate::pipeline::component_changes::record(
&self.db,
scan_run_id,
target_id,
doc! { "package_manager": {
"$in": crate::pipeline::firmware_sbom::FIRMWARE_MANAGERS.to_vec()
} },
&entries,
)
.await;
// Only the firmware entries: a rescan with no new
// commits skips the SBOM stage, so deleting everything
// here wiped the Syft entries until the next commit.
@@ -2610,13 +2397,13 @@ impl PipelineOrchestrator {
target_id: &str,
plan: &crate::pipeline::plan::ScanPlan,
scan_run_id: &str,
) -> u32 {
) {
if !plan.has(ScanType::Dast) {
return 0;
return;
}
self.update_phase(scan_run_id, ScanPhase::DastScanning)
.await;
self.maybe_trigger_dast(target_id, scan_run_id).await
self.maybe_trigger_dast(target_id, scan_run_id).await;
}
/// If the target has a `LiveUrl` artifact and DAST is planned, provision a
@@ -2664,23 +2451,15 @@ impl PipelineOrchestrator {
dast.allow_destructive = web.allow_destructive;
}
if let Some(auth) = &url.auth {
// The artifact keeps one secret (sealed): a password for a basic
// login, otherwise the token or cookie.
let basic = auth.method.eq_ignore_ascii_case("basic");
dast.auth_config = Some(DastAuthConfig {
method: auth.method.clone(),
login_url: auth.login_url.clone(),
username: auth.username.clone(),
password: auth.secret.clone().filter(|_| basic),
token: auth.secret.clone().filter(|_| !basic),
password: None,
token: auth.secret.clone(),
headers: auth.headers.clone(),
});
}
// The copied secret is sealed already; the login headers are not.
if let Err(e) = self.secrets.seal_unsealed(&mut dast) {
tracing::warn!(error = %e, "Unified pipeline: DAST login not stored");
return;
}
if let Err(e) = self.db.dast_targets().insert_one(&dast).await {
tracing::warn!(error = %e, "Unified pipeline: failed to provision DAST target");
}
@@ -3479,7 +3258,6 @@ fn planned_phases(
if config.breakpilot.semantic_mapping {
phases.push(ScanPhase::SemanticControlMapping);
}
phases.push(ScanPhase::GraphBuilding);
if config.plc_runtime.enabled && target.live_url().is_none() {
phases.push(ScanPhase::PlcProvision);
}
@@ -3633,11 +3411,7 @@ mod tests {
assert_eq!(
planned_phases(&target, &plan, &config),
[
ScanPhase::Classification,
ScanPhase::PlcAnalysis,
ScanPhase::GraphBuilding
]
[ScanPhase::Classification, ScanPhase::PlcAnalysis]
);
// The LLM control mapping is a phase of its own, so a long one shows.
@@ -3647,8 +3421,7 @@ mod tests {
[
ScanPhase::Classification,
ScanPhase::PlcAnalysis,
ScanPhase::SemanticControlMapping,
ScanPhase::GraphBuilding
ScanPhase::SemanticControlMapping
]
);
}
+3 -37
View File
@@ -186,17 +186,9 @@ fn scan_with_patterns(
.unwrap_or("")
.to_string();
// Only files a pattern looks at are read at all.
if !patterns.iter().any(|p| p.file_extensions.contains(&ext)) {
continue;
}
// UTF-8, UTF-16 with a BOM, or Windows-1252; a binary is skipped.
let content = match compliance_core::encoding::read_source(path) {
Ok(text) => text,
Err(error) => {
tracing::debug!(file = %path.display(), %error, "pattern scan: file not readable");
continue;
}
let content = match std::fs::read_to_string(path) {
Ok(c) => c,
Err(_) => continue, // skip binary files
};
let relative_path = path
@@ -425,30 +417,4 @@ mod tests {
assert!(!pattern.file_extensions.contains(&"rs".to_string()));
assert!(!pattern.file_extensions.contains(&"py".to_string()));
}
// --- file decoding ---
#[test]
fn a_windows_1252_file_is_scanned_not_skipped() {
// Arrange: a C# file written by an older tool, "Größe" as 0xF6 0xDF.
let dir = std::env::temp_dir().join(format!("cs-pat-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("Log.cs"), b"// Gr\xF6\xDFe\nLog(email);\n").unwrap();
let rule = PatternRule {
id: "pii".into(),
title: "t".into(),
description: "d".into(),
pattern: compile_regex(r"Log\(email\)"),
severity: Severity::Medium,
file_extensions: vec!["cs".into()],
};
// Act
let findings = scan_with_patterns(&dir, "repo", &[rule], ScanType::Gdpr, "t").unwrap();
let _ = std::fs::remove_dir_all(&dir);
// Assert: found on its line.
assert_eq!(findings.len(), 1);
assert_eq!(findings[0].line_number, Some(2));
}
}
+1 -118
View File
@@ -14,96 +14,8 @@ pub struct Pou {
pub vars: Vec<VarDecl>,
/// The statement body.
pub body: Vec<Stmt>,
/// 1-based line where the POU header appears. For a PLCopen POU it is
/// the `<pou>` element's line in the XML; its statements keep the lines
/// of the Structured Text reconstructed from it.
/// 1-based line where the POU header appears (in the source that was parsed).
pub line: u32,
/// 1-based line of its `END_*` keyword (the last line when it is
/// missing); for a PLCopen POU, the `</pou>` line.
pub end_line: u32,
}
impl Pou {
/// Call `visit` with the callee and line of every call in the body, bare
/// (`TON1(IN := x);`) or inside an expression (`LIMIT(0, x, 10)`), in
/// source order.
pub fn for_each_call(&self, mut visit: impl FnMut(&str, u32)) {
for stmt in &self.body {
stmt.for_each_call(&mut visit);
}
}
}
impl Stmt {
/// See [`Pou::for_each_call`]. `visit` is `&mut dyn` so the recursion
/// through nested blocks doesn't instantiate a new closure type per level.
fn for_each_call(&self, visit: &mut dyn FnMut(&str, u32)) {
let block = |body: &[Stmt], visit: &mut dyn FnMut(&str, u32)| {
for stmt in body {
stmt.for_each_call(visit);
}
};
match self {
Stmt::Assign { target, value, .. } => {
target.for_each_call(visit);
value.for_each_call(visit);
}
Stmt::If {
branches,
else_body,
..
} => {
for (cond, body) in branches {
cond.for_each_call(visit);
block(body, visit);
}
if let Some(body) = else_body {
block(body, visit);
}
}
Stmt::Case {
selector,
arms,
else_body,
..
} => {
selector.for_each_call(visit);
for (labels, body) in arms {
for label in labels {
label.for_each_call(visit);
}
block(body, visit);
}
if let Some(body) = else_body {
block(body, visit);
}
}
Stmt::For {
from, to, by, body, ..
} => {
from.for_each_call(visit);
to.for_each_call(visit);
if let Some(by) = by {
by.for_each_call(visit);
}
block(body, visit);
}
Stmt::While { cond, body, .. }
| Stmt::Repeat {
body, until: cond, ..
} => {
cond.for_each_call(visit);
block(body, visit);
}
Stmt::Call { callee, args, line } => {
visit(callee, *line);
for arg in args {
arg.value.for_each_call(visit);
}
}
Stmt::Return { .. } | Stmt::Exit { .. } | Stmt::Jump { .. } | Stmt::Label { .. } => {}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -279,35 +191,6 @@ impl Expr {
}
}
/// See [`Pou::for_each_call`].
fn for_each_call(&self, visit: &mut dyn FnMut(&str, u32)) {
match self {
Expr::Int(..)
| Expr::Real(..)
| Expr::Bool(..)
| Expr::Str(..)
| Expr::Time(..)
| Expr::Ident(..) => {}
Expr::Index { base, index, .. } => {
base.for_each_call(visit);
index.for_each_call(visit);
}
Expr::Member { base, .. } | Expr::Unary { expr: base, .. } => {
base.for_each_call(visit);
}
Expr::Binary { lhs, rhs, .. } => {
lhs.for_each_call(visit);
rhs.for_each_call(visit);
}
Expr::Call { callee, args, line } => {
visit(callee, *line);
for arg in args {
arg.value.for_each_call(visit);
}
}
}
}
/// If this expression is a plain identifier, its name.
pub fn as_ident(&self) -> Option<&str> {
match self {
-295
View File
@@ -1,295 +0,0 @@
//! The POUs of a PLC project as code-graph nodes and edges, for
//! [`compliance_graph::GraphEngine::assemble`].
//!
//! - A `PROGRAM` is a module and an entry point: the PLC's tasks run it.
//! - A `FUNCTION_BLOCK` is a class, since each instance keeps its own state.
//! - A `FUNCTION` is a function.
//!
//! A variable whose type is a function block is a dependency on it (a type
//! reference). A call through an instance (`Pump1(Start := x)`) is a call to
//! its type. Standard blocks such as `TON` or `CTU` have no node, so their
//! edges stay unresolved and the engine drops them.
use std::collections::HashMap;
use std::path::Path;
use compliance_core::models::graph::{CodeEdgeKind, CodeNodeKind};
use compliance_core::traits::graph_builder::ParseOutput;
use compliance_graph::parsers::FileGraph;
use super::ast::{Pou, PouKind};
use super::PlcFile;
/// The nodes and edges of every POU in `files`.
///
/// # Arguments
///
/// * `files` - the PLC source files read from one or more trees
/// * `repo_id`, `graph_build_id` - stamped on every node and edge
pub(crate) fn parse_output(files: &[PlcFile], repo_id: &str, graph_build_id: &str) -> ParseOutput {
let mut output = ParseOutput::default();
for file in files {
let language = if file.plcopen {
"plcopen"
} else {
"structured_text"
};
let mut graph = FileGraph::new(
Path::new(&file.rel),
file.line_count,
repo_id,
graph_build_id,
language,
);
for pou in &file.pous {
add_pou(&mut graph, pou);
}
let part = graph.finish();
output.nodes.extend(part.nodes);
output.edges.extend(part.edges);
}
output
}
/// Add `pou`'s node, its type references and its calls.
fn add_pou(graph: &mut FileGraph<'_>, pou: &Pou) {
let qualified = graph.top_level(&pou.name);
let kind = match pou.kind {
PouKind::Program => CodeNodeKind::Module,
PouKind::FunctionBlock => CodeNodeKind::Class,
PouKind::Function => CodeNodeKind::Function,
};
graph.node_at(
qualified.clone(),
pou.name.clone(),
kind,
(pou.line, pou.end_line),
pou.kind == PouKind::Program,
);
// IEC 61131-3 identifiers are case-insensitive, so the instances are
// looked up by their lowercased name.
let mut instances: HashMap<String, &str> = HashMap::with_capacity(pou.vars.len());
for var in &pou.vars {
if !is_identifier(&var.type_name) {
continue; // ARRAY[..] OF, POINTER TO, STRING(80): not a block type
}
graph.edge_at(&qualified, &var.type_name, CodeEdgeKind::TypeRef, var.line);
instances.insert(var.name.to_ascii_lowercase(), var.type_name.as_str());
}
pou.for_each_call(|callee, line| {
let target = instances
.get(&callee.to_ascii_lowercase())
.copied()
.unwrap_or(callee);
graph.edge_at(&qualified, target, CodeEdgeKind::Calls, line);
});
}
/// Whether a declared type is a plain name (`FB_Pump`, `TON`, `INT`).
fn is_identifier(type_name: &str) -> bool {
!type_name.is_empty()
&& type_name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_')
}
#[cfg(test)]
mod tests {
use super::*;
use crate::pipeline::plc::{parser, plcopen};
fn st_file(rel: &str, source: &str) -> PlcFile {
PlcFile {
rel: rel.to_string(),
plcopen: false,
line_count: source.lines().count() as u32,
pous: parser::parse(source),
}
}
const LINE: &str = "\
FUNCTION_BLOCK FB_Pump
VAR_INPUT
Start : BOOL;
END_VAR
VAR
Delay : TON;
END_VAR
Delay(IN := Start, PT := T#2s);
END_FUNCTION_BLOCK
FUNCTION Clamp : INT
VAR_INPUT
x : INT;
END_VAR
Clamp := LIMIT(0, x, 100);
END_FUNCTION
PROGRAM Main
VAR
pump1 : FB_Pump;
level : INT;
END_VAR
PUMP1(Start := TRUE);
IF Clamp(level) > 50 THEN
level := 0;
END_IF;
END_PROGRAM
";
#[test]
fn pous_become_nodes_and_programs_entry_points() {
let output = parse_output(&[st_file("src/line.st", LINE)], "r", "b");
let node = |name: &str| {
output
.nodes
.iter()
.find(|n| n.name == name)
.unwrap_or_else(|| panic!("no node {name}"))
};
assert_eq!(node("line.st").kind, CodeNodeKind::File);
let pump = node("FB_Pump");
assert_eq!(pump.kind, CodeNodeKind::Class);
assert_eq!(pump.qualified_name, "src/line.st::FB_Pump");
assert_eq!((pump.start_line, pump.end_line), (1, 9));
assert!(!pump.is_entry_point);
assert_eq!(node("Clamp").kind, CodeNodeKind::Function);
let main = node("Main");
assert_eq!(main.kind, CodeNodeKind::Module);
assert_eq!((main.start_line, main.end_line), (18, 27));
assert!(main.is_entry_point);
assert!(output.nodes.iter().all(|n| n.language == "structured_text"));
}
#[test]
fn instances_lead_to_their_type_and_calls_to_the_callee() {
let output = parse_output(&[st_file("line.st", LINE)], "r", "b");
let edges: Vec<(&str, CodeEdgeKind)> = output
.edges
.iter()
.filter(|e| e.source == "line.st::Main")
.map(|e| (e.target.as_str(), e.kind.clone()))
.collect();
// The instance declaration and the call through it (in another case)
// lead to FB_Pump; the function is called by name.
let to = |target: &str, kind: CodeEdgeKind| {
edges
.iter()
.filter(|(t, k)| *t == target && *k == kind)
.count()
};
assert_eq!(to("FB_Pump", CodeEdgeKind::TypeRef), 1);
assert_eq!(to("FB_Pump", CodeEdgeKind::Calls), 1);
assert_eq!(to("Clamp", CodeEdgeKind::Calls), 1);
// A standard block keeps its own name and resolves to nothing.
assert!(output
.edges
.iter()
.any(|e| e.source == "line.st::FB_Pump" && e.target == "TON"));
}
#[test]
fn plcopen_pous_span_their_xml_element() {
let xml = r#"<?xml version="1.0" encoding="utf-8"?>
<project>
<types>
<pous>
<pou name="Main" pouType="program">
<interface>
<localVars>
<variable name="pump1"><type><derived name="FB_Pump"/></type></variable>
</localVars>
</interface>
<body>
<ST><xhtml xmlns="http://www.w3.org/1999/xhtml">pump1(Start := TRUE);</xhtml></ST>
</body>
</pou>
</pous>
</types>
</project>
"#;
let file = PlcFile {
rel: "export.xml".to_string(),
plcopen: true,
line_count: xml.lines().count() as u32,
pous: plcopen::parse_plcopen(xml),
};
let output = parse_output(&[file], "r", "b");
let main = output
.nodes
.iter()
.find(|n| n.name == "Main")
.expect("Main is a node");
assert_eq!((main.start_line, main.end_line), (5, 14));
assert_eq!(main.language, "plcopen");
assert!(output
.edges
.iter()
.any(|e| e.target == "FB_Pump" && e.kind == CodeEdgeKind::Calls));
}
#[test]
fn the_engine_links_instances_and_drops_standard_blocks() {
let output = parse_output(&[st_file("line.st", LINE)], "r", "b");
let (graph, run) = compliance_graph::GraphEngine::new(1_000)
.assemble(output, "r")
.expect("assembles");
let linked = |source: &str, target: &str| {
graph
.edges
.iter()
.any(|e| e.source == source && e.target == target)
};
assert!(linked("line.st::Main", "line.st::FB_Pump"));
assert!(linked("line.st::Main", "line.st::Clamp"));
assert!(!graph.edges.iter().any(|e| e.target == "TON"));
assert_eq!(run.languages_parsed, ["structured_text"]);
}
#[test]
fn every_pou_of_the_demo_project_is_a_node() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../examples/plc-demo");
let mut files = crate::pipeline::plc::read_tree(&root);
files.sort_by(|a, b| a.rel.cmp(&b.rel));
let output = parse_output(&files, "r", "b");
let mut pous: Vec<(&str, bool)> = output
.nodes
.iter()
.filter(|n| n.kind != CodeNodeKind::File)
.map(|n| (n.name.as_str(), n.is_entry_point))
.collect();
pous.sort();
assert_eq!(
pous,
[
("ConveyorCtrl", true),
("PumpFbdCtrl", false),
("PumpStationCtrl", false),
("TrafficLight", true),
]
);
assert_eq!(
output
.nodes
.iter()
.filter(|n| n.kind == CodeNodeKind::File)
.count(),
4
);
}
#[test]
fn only_plain_type_names_are_references() {
assert!(is_identifier("FB_Pump"));
assert!(!is_identifier("ARRAY[0..9] OF INT"));
assert!(!is_identifier("STRING(80)"));
assert!(!is_identifier(""));
}
}
+18 -111
View File
@@ -9,7 +9,6 @@
//! scan says so instead of finding nothing in silence (#165).
pub mod ast;
pub(crate) mod graph;
pub mod lexer;
pub mod parser;
pub mod plcopen;
@@ -46,26 +45,9 @@ impl Scanner for PlcControlLogicScanner {
}
}
/// A PLC source file and the POUs read from it.
pub(crate) struct PlcFile {
/// The path relative to the tree it was found in.
pub(crate) rel: String,
/// Whether it is a PLCopen XML export rather than Structured Text.
pub(crate) plcopen: bool,
/// Its number of lines.
pub(crate) line_count: u32,
pub(crate) pous: Vec<ast::Pou>,
}
/// Read every PLC source file under `root` (Structured Text, and PLCopen XML
/// exports) into its POUs. Files with no POU are left out.
///
/// Each file is decoded by [`compliance_core::encoding::read_source`]:
/// CODESYS and TIA exports are often Windows-1252 or UTF-16. Files still not
/// readable as text are logged as one warning per tree.
pub(crate) fn read_tree(root: &Path) -> Vec<PlcFile> {
let mut files = Vec::new();
let mut unreadable: u32 = 0;
/// Walk a PLC project tree and produce findings.
pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
let mut findings = Vec::new();
for entry in walkdir::WalkDir::new(root)
.into_iter()
.filter_map(|e| e.ok())
@@ -84,17 +66,8 @@ pub(crate) fn read_tree(root: &Path) -> Vec<PlcFile> {
if !is_st && !is_xml {
continue;
}
let content = match compliance_core::encoding::read_source(path) {
Ok(text) => text,
Err(error) => {
// A binary `.project` is CODESYS's native format, which
// [`native_projects`] reports; anything else is a loss.
if ext != "project" {
tracing::debug!(file = %path.display(), %error, "PLC source file not readable");
unreadable += 1;
}
continue;
}
let Ok(content) = std::fs::read_to_string(path) else {
continue;
};
// A `.project` is read only as a PLCopen export; CODESYS's native one
// is binary ([`native_projects`] reports it).
@@ -109,41 +82,16 @@ pub(crate) fn read_tree(root: &Path) -> Vec<PlcFile> {
if pous.is_empty() {
continue;
}
files.push(PlcFile {
rel: path
.strip_prefix(root)
.unwrap_or(path)
.to_string_lossy()
.to_string(),
plcopen: is_xml,
line_count: content.lines().count() as u32,
pous,
});
}
// One line per tree; the paths are logged at debug level only.
if unreadable > 0 {
tracing::warn!(
unreadable_files = unreadable,
"PLC source files left out: not readable as text"
);
}
files
}
/// Run the control-logic rules over the POUs of `files`.
pub(crate) fn findings(files: &[PlcFile], repo_id: &str) -> Vec<Finding> {
let mut findings = Vec::new();
for file in files {
for pou in &file.pous {
let rel = path
.strip_prefix(root)
.unwrap_or(path)
.to_string_lossy()
.to_string();
for pou in &pous {
for hit in rules::analyze(pou) {
let line_s = hit.line.to_string();
let fingerprint = dedup::compute_fingerprint(&[
repo_id,
&file.rel,
hit.rule_id,
&pou.name,
&line_s,
]);
let fingerprint =
dedup::compute_fingerprint(&[repo_id, &rel, hit.rule_id, &pou.name, &line_s]);
let mut f = Finding::new(
repo_id.to_string(),
fingerprint,
@@ -153,7 +101,7 @@ pub(crate) fn findings(files: &[PlcFile], repo_id: &str) -> Vec<Finding> {
hit.description,
hit.severity,
);
f.file_path = Some(file.rel.clone());
f.file_path = Some(rel.clone());
f.line_number = Some(hit.line);
f.rule_id = Some(hit.rule_id.to_string());
f.cwe = hit.cwe.map(String::from);
@@ -165,11 +113,6 @@ pub(crate) fn findings(files: &[PlcFile], repo_id: &str) -> Vec<Finding> {
findings
}
/// Walk a PLC project tree and produce findings.
pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
findings(&read_tree(root), repo_id)
}
/// Whether `content` starts as an XML document (after a byte-order mark and
/// white space).
fn looks_like_xml(content: &str) -> bool {
@@ -209,9 +152,10 @@ pub fn native_projects(root: &Path) -> Vec<String> {
.unwrap_or("")
.to_ascii_lowercase();
let native = match ext.as_str() {
// Decoded as [`read_tree`] reads it: a UTF-16 export is no native one.
"project" => !compliance_core::encoding::read_source(path)
.is_ok_and(|text| looks_like_xml(&text)),
"project" => !std::fs::read(path)
.ok()
.and_then(|bytes| String::from_utf8(bytes).ok())
.is_some_and(|text| looks_like_xml(&text)),
"projectarchive" => sbom::check_archive(path).is_ok(),
_ => false,
};
@@ -405,41 +349,4 @@ mod tests {
// The binary project yields no POUs and no error.
assert!(analyze_tree(&root.0, "t").is_empty());
}
#[test]
fn windows_1252_and_utf16_sources_are_read() {
// Arrange: Structured Text as older CODESYS saves it (Windows-1252:
// "Größe" is F6 DF, "€" is 80), and a PLCopen export in UTF-16 LE.
let root =
Scratch(std::env::temp_dir().join(format!("cs-plc-enc-{}", uuid::Uuid::new_v4())));
std::fs::create_dir_all(&root.0).expect("mkdir");
std::fs::write(
root.0.join("legacy.st"),
b"PROGRAM Legacy\nVAR\n s : STRING := 'Gr\xF6\xDFe in \x80';\nEND_VAR\n\
s := 'x'; (* Gr\xF6\xDFe *)\nEND_PROGRAM\n",
)
.expect("write st");
let xml = "<?xml version=\"1.0\" encoding=\"UTF-16\"?>\
<project xmlns=\"http://www.plcopen.org/xml/tc6_0201\"><types><pous>\
<pou name=\"Wide\" pouType=\"program\"><interface><localVars>\
<variable name=\"Größe\"><type><INT/></type></variable></localVars></interface>\
<body><ST><xhtml xmlns=\"http://www.w3.org/1999/xhtml\">x := 1;</xhtml></ST></body>\
</pou></pous></types></project>";
let utf16: Vec<u8> = [0xFF, 0xFE]
.into_iter()
.chain(xml.encode_utf16().flat_map(u16::to_le_bytes))
.collect();
std::fs::write(root.0.join("wide.xml"), utf16).expect("write xml");
// Act
let files = read_tree(&root.0);
// Assert
let mut pous: Vec<&str> = files
.iter()
.flat_map(|f| f.pous.iter().map(|p| p.name.as_str()))
.collect();
pous.sort_unstable();
assert_eq!(pous, ["Legacy", "Wide"]);
}
}
@@ -119,7 +119,6 @@ impl Parser {
body.push(s);
}
}
let end_line = self.line();
self.eat_kw(end);
Some(Pou {
@@ -128,7 +127,6 @@ impl Parser {
vars,
body,
line,
end_line,
})
}
+1 -10
View File
@@ -49,16 +49,7 @@ pub fn parse_plcopen(xml: &str) -> Vec<Pou> {
_ => "PROGRAM",
};
let synthetic = format!("{kw} {name}\n{var_block}{body}\nEND_{kw}\n");
// Statement lines stay those of the synthetic source (the findings'
// lines and fingerprints use them); the POU itself spans its
// `<pou>` element in the XML, which is what the code graph shows.
let start = doc.text_pos_at(pou.range().start).row;
let end = doc.text_pos_at(pou.range().end).row;
pous.extend(parser::parse(&synthetic).into_iter().map(|mut parsed| {
parsed.line = start;
parsed.end_line = end;
parsed
}));
pous.extend(parser::parse(&synthetic));
}
pous
}
@@ -1,623 +0,0 @@
//! Why an SBOM is empty or incomplete, as findings (#979).
//!
//! The SBOM is built from the manifests and lockfiles in the code. Without
//! them it is empty, which reads as "no libraries" to someone who is not a
//! developer. Two findings say what is missing instead:
//!
//! - [`NO_MANIFEST_RULE`] (Medium): the tree holds code in a language with a
//! package manager, but no manifest or lockfile for it at all;
//! - [`UNRESOLVED_RULE`] (Low): a manifest whose dependencies were not
//! resolved (no lockfile, or one no tool reads), as
//! [`super::unlocked_ecosystems`] reports it.
//!
//! C and C++ have no standard manifest, and a firmware tree's components come
//! from its sources (library headers, the firmware build, a CODESYS archive, a
//! Yocto layer tree): such a tree never gets the first finding. Nothing is
//! guessed and no code is run to resolve dependencies. Both findings belong
//! to [`SCANNER`], which completes on every code scan, so a finding closes at
//! the next scan that no longer reports it.
use std::path::Path;
use compliance_core::models::{Finding, SbomEntry, ScanType, Severity, YOCTO_RECIPE_MANAGER};
use super::UnlockedEcosystem;
use crate::pipeline::dedup::compute_fingerprint;
use crate::pipeline::embedded_versions::EMBEDDED_MANAGER;
use crate::pipeline::vendor::walk_outside;
/// The scanner name of these findings.
pub(crate) const SCANNER: &str = compliance_core::models::SBOM_COVERAGE_SCANNER;
/// Code in a language with a package manager, and no manifest for it.
pub(crate) const NO_MANIFEST_RULE: &str = "sbom-no-manifest";
/// A manifest whose dependencies were not resolved.
pub(crate) const UNRESOLVED_RULE: &str = "sbom-dependencies-unresolved";
/// The weakness both findings stand for: components nobody tracks.
const CWE: &str = "CWE-1104";
/// The CRA requirement both findings are evidence against: the SBOM.
const SBOM_CONTROL: &str = crate::evidence::compliance::SBOM_CONTROL;
/// Languages whose code never asks for a manifest: C and C++ have no
/// standard one, and a Yocto layer tree's recipes are its inventory.
const NO_MANIFEST_LANGUAGES: [&str; 3] = ["c", "cpp", "bitbake"];
/// The `package_manager` values of components read from the sources rather
/// than a manifest: library headers, CODESYS archives, Yocto recipes.
const SOURCE_MANAGERS: [&str; 3] = [EMBEDDED_MANAGER, "codesys", YOCTO_RECIPE_MANAGER];
/// A package ecosystem: the languages that use it, the files that declare
/// or pin its dependencies, and how to add them.
struct Ecosystem {
/// What the finding calls the code (`Python`, `JavaScript/TypeScript`).
name: &'static str,
/// The language codes of [`crate::pipeline::languages`] it covers.
languages: &'static [&'static str],
/// The purl types of its SBOM entries: entries of one mean the SBOM
/// already lists some of its libraries (from committed jars, DLLs or
/// installed packages), so a manifest is not all there is.
purl_types: &'static [&'static str],
/// Whether a file name (lowercased) is one of its manifests or lockfiles.
declares: fn(&str) -> bool,
/// Its manifests, as the finding names them.
manifests: &'static str,
/// A concrete way to add a manifest or lockfile.
example: &'static str,
}
/// The ecosystems the finding covers, in the order the findings list them.
static ECOSYSTEMS: [Ecosystem; 9] = [
Ecosystem {
name: "Python",
languages: &["python"],
purl_types: &["pypi"],
declares: |f| {
(f.starts_with("requirements") && f.ends_with(".txt"))
|| matches!(
f,
"pyproject.toml"
| "setup.py"
| "setup.cfg"
| "pipfile"
| "pipfile.lock"
| "poetry.lock"
| "uv.lock"
| "pdm.lock"
| "environment.yml"
| "environment.yaml"
)
},
manifests: "requirements.txt or pyproject.toml",
example: "run pip freeze > requirements.txt in the project's environment, or declare \
the dependencies in pyproject.toml and run uv lock or poetry lock",
},
Ecosystem {
name: "JavaScript/TypeScript",
languages: &["javascript", "typescript"],
purl_types: &["npm"],
declares: |f| {
matches!(
f,
"package.json"
| "package-lock.json"
| "npm-shrinkwrap.json"
| "yarn.lock"
| "pnpm-lock.yaml"
| "bun.lock"
| "bun.lockb"
| "deno.json"
| "deno.jsonc"
| "deno.lock"
)
},
manifests: "package.json",
example: "declare the dependencies in package.json and run npm install, which writes \
package-lock.json",
},
Ecosystem {
name: "Rust",
languages: &["rust"],
purl_types: &["cargo"],
declares: |f| matches!(f, "cargo.toml" | "cargo.lock"),
manifests: "Cargo.toml",
example: "commit Cargo.toml and Cargo.lock (cargo generate-lockfile writes it)",
},
Ecosystem {
name: "Go",
languages: &["go"],
purl_types: &["golang"],
declares: |f| matches!(f, "go.mod" | "go.sum" | "gopkg.toml" | "gopkg.lock"),
manifests: "go.mod",
example: "run go mod init and go mod tidy, which write go.mod and go.sum, and commit both",
},
Ecosystem {
name: "Java/Kotlin",
languages: &["java", "kotlin"],
purl_types: &["maven"],
declares: |f| {
matches!(
f,
"pom.xml"
| "build.gradle"
| "build.gradle.kts"
| "settings.gradle"
| "settings.gradle.kts"
| "gradle.lockfile"
| "ivy.xml"
)
},
manifests: "pom.xml or build.gradle",
example: "declare the dependencies in a Maven pom.xml or a Gradle build file; with \
Gradle, also commit gradle.lockfile (./gradlew dependencies --write-locks)",
},
Ecosystem {
name: "C#",
languages: &["csharp"],
purl_types: &["nuget"],
// A Unity project (`ProjectVersion.txt`) is the build lifecycle
// check's: without its package manifest it is a legacy build system.
declares: |f| {
[".csproj", ".fsproj", ".vbproj", ".nuspec"]
.iter()
.any(|suffix| f.ends_with(suffix))
|| matches!(
f,
"packages.config"
| "packages.lock.json"
| "directory.packages.props"
| "project.json"
| "projectversion.txt"
)
},
manifests: "a .csproj project file",
example: "reference the NuGet packages in the .csproj project file, set \
RestorePackagesWithLockFile to true and commit the packages.lock.json that \
dotnet restore writes",
},
Ecosystem {
name: "PHP",
languages: &["php"],
purl_types: &["composer"],
declares: |f| matches!(f, "composer.json" | "composer.lock"),
manifests: "composer.json",
example: "declare the dependencies in composer.json and run composer install, which \
writes composer.lock; commit both",
},
Ecosystem {
name: "Ruby",
languages: &["ruby"],
purl_types: &["gem"],
declares: |f| {
f.ends_with(".gemspec") || matches!(f, "gemfile" | "gemfile.lock" | "gems.rb")
},
manifests: "a Gemfile",
example: "declare the gems in a Gemfile and run bundle install, which writes \
Gemfile.lock; commit both",
},
Ecosystem {
name: "Dart",
languages: &["dart"],
purl_types: &["pub"],
declares: |f| matches!(f, "pubspec.yaml" | "pubspec.lock"),
manifests: "pubspec.yaml",
example: "declare the dependencies in pubspec.yaml and run dart pub get (or flutter pub \
get), which writes pubspec.lock; commit both",
},
];
/// What one scan knows about its tree when it asks for these findings.
pub(crate) struct ScannedTree<'a> {
/// The target (`Finding::repo_id`).
pub repo_id: &'a str,
/// The working copy, after the left-out paths were pruned.
pub root: &'a Path,
/// Its vendor directories, which are not the customer's code.
pub vendor: &'a [String],
/// Its source languages ([`crate::pipeline::languages::source_languages`]).
pub languages: &'a [String],
/// Whether the tree is read as Yocto layers.
pub yocto_layers: bool,
/// Whether the target has a firmware SBOM from its sources, which the
/// firmware step stored before this scan of the tree.
pub firmware_sbom: bool,
}
/// The coverage findings of one scan: a [`NO_MANIFEST_RULE`] finding per
/// ecosystem the tree's code needs a manifest for and has none, and an
/// [`UNRESOLVED_RULE`] finding per entry of `unlocked` (other than a legacy
/// build system, which is a finding of the build lifecycle check already).
///
/// # Arguments
///
/// * `tree` - the scanned tree and what the scan detected in it
/// * `sbom` - the components this scan listed, from every source
/// * `unlocked` - the manifests whose dependencies were not resolved
///
/// # Returns
///
/// The findings, with `control_refs` set to the SBOM requirement; empty when
/// the SBOM speaks for the whole tree.
pub(crate) fn coverage_findings(
tree: &ScannedTree<'_>,
sbom: &[SbomEntry],
unlocked: &[UnlockedEcosystem],
) -> Vec<Finding> {
let mut findings: Vec<Finding> = missing_manifests(tree, sbom)
.into_iter()
.map(|eco| no_manifest_finding(tree.repo_id, eco))
.collect();
findings.extend(
unlocked
.iter()
.filter(|eco| !eco.legacy_build)
.map(|eco| unresolved_finding(tree.repo_id, eco)),
);
findings
}
/// The ecosystems whose code the tree holds outside vendor directories, with
/// no manifest or lockfile of theirs anywhere outside them and no component
/// of theirs in `sbom`. Empty for a tree with C, C++ or Yocto layers, and for
/// one whose components come from its sources ([`SOURCE_MANAGERS`], or the
/// firmware SBOM).
fn missing_manifests(tree: &ScannedTree<'_>, sbom: &[SbomEntry]) -> Vec<&'static Ecosystem> {
let has_language = |l: &str| tree.languages.iter().any(|x| x == l);
let from_sources = tree.firmware_sbom
|| sbom
.iter()
.any(|e| SOURCE_MANAGERS.contains(&e.package_manager.as_str()));
if tree.yocto_layers || from_sources || NO_MANIFEST_LANGUAGES.iter().any(|l| has_language(l)) {
return Vec::new();
}
// `pkg:pypi/requests@2` has the purl type `pypi`.
let listed = |eco: &Ecosystem| {
sbom.iter().any(|e| {
e.purl
.as_deref()
.and_then(|p| p.strip_prefix("pkg:"))
.and_then(|p| p.split('/').next())
.is_some_and(|t| eco.purl_types.contains(&t))
})
};
let mut candidates: Vec<&'static Ecosystem> = ECOSYSTEMS
.iter()
.filter(|eco| eco.languages.iter().any(|l| has_language(l)))
.filter(|eco| !listed(eco))
.collect();
if candidates.is_empty() {
return candidates;
}
// One walk for all of them; it stops once each has shown a manifest.
for entry in walk_outside(tree.root, tree.vendor) {
if !entry.file_type().is_file() {
continue;
}
let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
candidates.retain(|eco| !(eco.declares)(&name));
if candidates.is_empty() {
break;
}
}
candidates
}
/// The [`NO_MANIFEST_RULE`] finding for `eco` on target `repo_id`.
fn no_manifest_finding(repo_id: &str, eco: &Ecosystem) -> Finding {
let mut finding = Finding::new(
repo_id.to_string(),
compute_fingerprint(&[repo_id, NO_MANIFEST_RULE, eco.name]),
SCANNER.to_string(),
ScanType::Sbom,
format!(
"No package manifest: the SBOM lists no libraries of the {} code",
eco.name
),
format!(
"The code contains {name} files, but no manifest or lockfile (such as {manifests}) \
that lists the libraries they use. The SBOM is built from these files, so it shows \
none of the {name} libraries, and their known vulnerabilities (CVEs) are not \
checked. An empty SBOM here does not mean that the code uses no libraries.",
name = eco.name,
manifests = eco.manifests,
),
Severity::Medium,
);
finding.remediation = Some(format!(
"Add a manifest or lockfile and commit it. For {}: {}. The finding closes at the next \
scan that finds it.",
eco.name, eco.example
));
stamp(&mut finding, NO_MANIFEST_RULE);
finding
}
/// The [`UNRESOLVED_RULE`] finding for `eco` on target `repo_id`.
fn unresolved_finding(repo_id: &str, eco: &UnlockedEcosystem) -> Finding {
let mut finding = Finding::new(
repo_id.to_string(),
compute_fingerprint(&[repo_id, UNRESOLVED_RULE, &eco.manifest]),
SCANNER.to_string(),
ScanType::Sbom,
format!(
"Dependencies not resolved: the SBOM is incomplete ({})",
eco.manifest
),
format!(
"{} {}. So the versions of these libraries, and of the libraries they pull in, are \
not known: the SBOM does not list them completely, and their known \
vulnerabilities (CVEs) are not checked. Prüfwerk does not run the project's code \
to resolve them.",
eco.manifest, eco.problem
),
Severity::Low,
);
finding.remediation = Some(format!(
"{}. The finding closes at the next scan that finds the lockfile.",
capitalised(eco.remedy)
));
finding.file_path = Some(eco.manifest.clone());
stamp(&mut finding, UNRESOLVED_RULE);
finding
}
/// Give `finding` its rule, weakness and CRA requirement. The control triage
/// judges a finding on its code, which these have none of, so the mapping is
/// set here, as `cra-ai-23` in the control map binds it.
fn stamp(finding: &mut Finding, rule: &str) {
finding.rule_id = Some(rule.to_string());
finding.cwe = Some(CWE.to_string());
finding.control_refs = vec![SBOM_CONTROL.to_string()];
}
/// `text` with its first letter upper-case.
fn capitalised(text: &str) -> String {
let mut chars = text.chars();
chars
.next()
.map(|first| first.to_uppercase().chain(chars).collect())
.unwrap_or_default()
}
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use super::*;
/// A temporary tree holding `files`, removed on drop.
struct Tree(std::path::PathBuf);
impl Tree {
fn with(files: &[&str]) -> Self {
let root = std::env::temp_dir().join(format!("cs-coverage-{}", uuid::Uuid::new_v4()));
for path in files {
let file = root.join(path);
std::fs::create_dir_all(file.parent().expect("parent")).expect("mkdir");
std::fs::write(file, "x").expect("write");
}
std::fs::create_dir_all(&root).expect("root");
Self(root)
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn langs(codes: &[&str]) -> Vec<String> {
codes.iter().map(|c| c.to_string()).collect()
}
fn findings_for(
files: &[&str],
languages: &[&str],
sbom: &[SbomEntry],
unlocked: &[UnlockedEcosystem],
) -> Vec<Finding> {
let tree = Tree::with(files);
let languages = langs(languages);
let vendor = vec!["vendor".to_string()];
coverage_findings(
&ScannedTree {
repo_id: "t1",
root: &tree.0,
vendor: &vendor,
languages: &languages,
yocto_layers: false,
firmware_sbom: false,
},
sbom,
unlocked,
)
}
fn entry(package_manager: &str, purl: Option<&str>) -> SbomEntry {
let mut e = SbomEntry::new(
"t1".into(),
"lib".into(),
"1.0".into(),
package_manager.into(),
);
e.purl = purl.map(str::to_string);
e
}
fn unlocked(manifest: &str, legacy_build: bool) -> UnlockedEcosystem {
UnlockedEcosystem {
manifest: manifest.into(),
problem: "declares dependencies but no lockfile pins them",
remedy: "commit Cargo.lock",
legacy_build,
}
}
#[test]
fn code_without_any_manifest_is_a_medium_finding_per_ecosystem() {
let found = findings_for(
&["app/main.py", "web/app.ts", "web/util.js"],
&["javascript", "python", "typescript"],
&[],
&[],
);
let titles: Vec<&str> = found.iter().map(|f| f.title.as_str()).collect();
assert_eq!(
titles,
[
"No package manifest: the SBOM lists no libraries of the Python code",
"No package manifest: the SBOM lists no libraries of the JavaScript/TypeScript \
code",
]
);
let python = &found[0];
assert_eq!(python.severity, Severity::Medium);
assert_eq!(python.rule_id.as_deref(), Some(NO_MANIFEST_RULE));
assert_eq!(python.scanner, SCANNER);
assert_eq!(python.control_refs, [SBOM_CONTROL]);
assert_eq!(python.file_path, None);
assert!(python
.remediation
.as_deref()
.is_some_and(|r| r.contains("pip freeze > requirements.txt")));
// Stable across scans, one per ecosystem.
assert_ne!(found[0].fingerprint, found[1].fingerprint);
let again = findings_for(&["main.py"], &["python"], &[], &[]);
assert_eq!(again[0].fingerprint, python.fingerprint);
}
#[test]
fn a_manifest_or_lockfile_anywhere_outside_vendor_code_counts() {
for (manifest, language) in [
("backend/requirements-dev.txt", "python"),
("pyproject.toml", "python"),
("frontend/package.json", "javascript"),
("Cargo.lock", "rust"),
("svc/go.mod", "go"),
("app/build.gradle.kts", "kotlin"),
("pom.xml", "java"),
("src/App/App.csproj", "csharp"),
("composer.json", "php"),
("tool.gemspec", "ruby"),
("app/pubspec.yaml", "dart"),
] {
let found = findings_for(&[manifest], &[language], &[], &[]);
assert!(found.is_empty(), "{manifest} declares {language}");
}
// A vendored library's manifest is not the customer code's.
let found = findings_for(&["vendor/lib/package.json"], &["javascript"], &[], &[]);
assert_eq!(found.len(), 1);
}
#[test]
fn c_cpp_firmware_sources_and_yocto_never_ask_for_a_manifest() {
// An embedded C tree with a flashing script.
assert!(findings_for(&["tools/flash.py"], &["c", "python"], &[], &[]).is_empty());
assert!(findings_for(&["tools/flash.py"], &["cpp", "python"], &[], &[]).is_empty());
assert!(findings_for(&["lib/oe/x.py"], &["bitbake", "python"], &[], &[]).is_empty());
// Components read from the sources are an SBOM.
for manager in ["embedded", "codesys", "yocto-recipe"] {
let sbom = [entry(manager, None)];
assert!(
findings_for(&["main.py"], &["python"], &sbom, &[]).is_empty(),
"{manager}"
);
}
// So are the firmware SBOM and a Yocto layer tree.
let tree = Tree::with(&["main.py"]);
let languages = langs(&["python"]);
for (yocto_layers, firmware_sbom) in [(true, false), (false, true)] {
let found = coverage_findings(
&ScannedTree {
repo_id: "t1",
root: &tree.0,
vendor: &[],
languages: &languages,
yocto_layers,
firmware_sbom,
},
&[],
&[],
);
assert!(
found.is_empty(),
"yocto {yocto_layers}, firmware {firmware_sbom}"
);
}
}
#[test]
fn components_of_the_ecosystem_already_listed_need_no_manifest() {
// Committed jars give Maven components without a pom.xml.
let sbom = [entry("maven", Some("pkg:maven/org.slf4j/slf4j-api@2.0.9"))];
assert!(findings_for(&["Main.java"], &["java"], &sbom, &[]).is_empty());
// Components of another ecosystem do not.
let found = findings_for(&["Main.java", "main.py"], &["java", "python"], &sbom, &[]);
assert_eq!(found.len(), 1);
assert!(found[0].title.contains("Python"));
}
#[test]
fn dart_is_covered() {
let found = findings_for(&["lib/main.dart"], &["dart"], &[], &[]);
assert_eq!(found.len(), 1);
assert!(found[0]
.remediation
.as_deref()
.is_some_and(|r| r.contains("pubspec.lock")));
}
#[test]
fn an_unresolved_manifest_is_a_low_finding_and_legacy_builds_are_not_repeated() {
let found = findings_for(
&["Cargo.toml", "src/main.rs"],
&["rust"],
&[],
&[
unlocked("Cargo.toml", false),
unlocked("app/project.properties", true),
],
);
assert_eq!(found.len(), 1);
let f = &found[0];
assert_eq!(f.severity, Severity::Low);
assert_eq!(f.rule_id.as_deref(), Some(UNRESOLVED_RULE));
assert_eq!(f.file_path.as_deref(), Some("Cargo.toml"));
assert_eq!(f.line_number, None);
assert_eq!(f.control_refs, [SBOM_CONTROL]);
assert_eq!(
f.title,
"Dependencies not resolved: the SBOM is incomplete (Cargo.toml)"
);
assert!(f
.description
.starts_with("Cargo.toml declares dependencies but no lockfile pins them."));
assert_eq!(
f.remediation.as_deref(),
Some("Commit Cargo.lock. The finding closes at the next scan that finds the lockfile.")
);
}
#[test]
fn the_stamped_requirement_is_the_one_the_control_map_binds() {
let map = control_map::ControlMap::cra().expect("map");
for rule in [NO_MANIFEST_RULE, UNRESOLVED_RULE] {
let controls: Vec<&str> = map
.bindings_for_finding(SCANNER, Some(CWE), Some(rule))
.into_iter()
.map(|(entry, _)| entry.control.as_str())
.collect();
assert_eq!(controls, [SBOM_CONTROL], "{rule}");
}
}
#[test]
fn a_tree_without_package_manager_code_has_no_findings() {
assert!(findings_for(&["README.md"], &[], &[], &[]).is_empty());
assert!(findings_for(&["App.swift"], &["swift"], &[], &[]).is_empty());
}
}
@@ -147,7 +147,6 @@ pub(crate) fn unlocked_mobile_ecosystems(root: &Path) -> Vec<UnlockedEcosystem>
manifest,
problem: eco.problem,
remedy: eco.remedy,
legacy_build: false,
})
})
.collect()
@@ -1,6 +1,5 @@
mod cargo_audit;
pub(crate) mod carthage;
pub(crate) mod coverage;
mod distribution;
mod gradle;
mod mobile;
@@ -225,9 +224,6 @@ pub(crate) struct UnlockedEcosystem {
pub problem: &'static str,
/// What to commit so they are.
pub remedy: &'static str,
/// A legacy build system ([`crate::pipeline::build_lifecycle`]), which
/// is a finding of its own already.
pub legacy_build: bool,
}
/// Lockfiles that pin an npm-registry project. Bun's count: npm must never
@@ -270,14 +266,12 @@ pub(crate) fn unlocked_ecosystems(
manifest: "package.json".into(),
problem: "is locked only by bun.lockb, Bun's binary lockfile, which is not read",
remedy: "commit the text bun.lock (`bun install --save-text-lockfile`)",
legacy_build: false,
});
} else if !readable {
out.push(UnlockedEcosystem {
manifest: "package.json".into(),
problem: "declares dependencies but no lockfile pins them",
remedy: "commit package-lock.json, yarn.lock, pnpm-lock.yaml or bun.lock",
legacy_build: false,
});
}
}
@@ -290,7 +284,6 @@ pub(crate) fn unlocked_ecosystems(
manifest: manifest.into(),
problem: "declares dependencies but no lockfile pins them",
remedy: "commit requirements.txt, poetry.lock, Pipfile.lock or uv.lock",
legacy_build: false,
});
}
}
@@ -299,7 +292,6 @@ pub(crate) fn unlocked_ecosystems(
manifest: "Cargo.toml".into(),
problem: "declares dependencies but no lockfile pins them",
remedy: "commit Cargo.lock",
legacy_build: false,
});
}
out.extend(mobile::unlocked_mobile_ecosystems(repo_path));
@@ -315,7 +307,6 @@ pub(crate) fn unlocked_ecosystems(
Packages/manifest.json) whose dependencies cannot be read",
remedy: "migrate the build (Gradle with the Android Gradle Plugin, or a \
current Unity LTS with the Package Manager)",
legacy_build: true,
}),
);
out.extend(nuget::unresolved_projects(repo_path, resolved_nuget));
@@ -250,7 +250,6 @@ pub(crate) fn unresolved_projects(root: &Path, resolved: &[String]) -> Vec<Unloc
remedy: "set <RestorePackagesWithLockFile>true</RestorePackagesWithLockFile> (in the \
project or a Directory.Build.props), restore once and commit \
packages.lock.json",
legacy_build: false,
}]
}
+4 -6
View File
@@ -19,10 +19,9 @@ pub fn relative_path(root: &Path, path: &str) -> String {
rel.to_string_lossy().replace('\\', "/")
}
/// The whole text of `root/rel`, decoded by
/// [`compliance_core::encoding::read_source`]. `None` when the file is
/// unreadable or the path would leave `root`: scanner output is not trusted
/// to stay inside the tree.
/// The whole text of `root/rel`. `None` when the file is unreadable or the
/// path would leave `root`: scanner output is not trusted to stay inside the
/// tree.
pub fn read_text(root: &Path, rel: &str) -> Option<String> {
let rel_path = Path::new(rel);
if rel_path.is_absolute()
@@ -32,8 +31,7 @@ pub fn read_text(root: &Path, rel: &str) -> Option<String> {
{
return None;
}
// UTF-16 with a BOM and Windows-1252 too, as the code graph reads them.
compliance_core::encoding::read_source(&root.join(rel_path)).ok()
std::fs::read_to_string(root.join(rel_path)).ok()
}
/// Lines `start..=end` (1-based, inclusive) of `root/rel`, capped at
+87 -688
View File
@@ -1,55 +1,37 @@
//! How many scans run at once, in which order they get a slot, and what
//! happens to a scan requested while the same target is already queued or
//! being scanned.
//! How many scans run at once, and what happens to a scan requested while the
//! same target is already being scanned.
//!
//! Every scan used to be a bare `tokio::spawn` with no limit. A burst of pushes,
//! a scheduler tick and a few clicks could start any number of scans side by
//! side — each one a clone plus semgrep plus syft — on an 8 GB node, and two
//! scans of the same target shared one checkout directory and corrupted each
//! other. These rules now apply to every trigger (click, webhook, scheduler):
//! other. Two rules now apply to every trigger (click, webhook, scheduler):
//!
//! * **Global:** at most `SCAN_CONCURRENCY` scans run at a time; the rest wait
//! for a slot.
//! * **Order:** a scan a person started ([`Priority::Person`]) gets a free slot
//! before scheduled, webhook and new-content scans ([`Priority::Background`]);
//! within a class the first to ask is the first served. So that a stream of
//! clicks never starves the scheduler, a waiting background scan gets the
//! slot after [`PERSON_GRANTS_IN_A_ROW`] person scans in a row (t84).
//! * **Per target — coalesce:** one scan of a target waits or runs, and while
//! it runs at most one more is pending. A request while the scan still waits
//! for its slot is covered by it (it reads the latest code once it starts);
//! a request while one is pending is covered by that one. Ten pushes during
//! a long scan therefore cost two scans, not ten. A person's request takes
//! over a waiting or pending scan that was not a person's, so it runs at
//! person priority and always scans. Requests that do not run are never
//! billed: only a scan that actually ran emits usage.
//!
//! Each admitted request carries the id of the run recorded for it while it
//! waits (status `queued`); the gate tells the caller which of those runs will
//! not happen, so no queued run is left behind.
//! * **Per target — coalesce:** one scan runs and at most one more is pending.
//! A request that arrives while one is pending is dropped, because the pending
//! scan will pick up the latest code anyway. Ten pushes during a long scan
//! therefore cost two scans, not ten. Dropped requests are never billed: only
//! a scan that actually ran emits usage.
//!
//! A scheduled scan also starts after a random delay of up to
//! [`SCHEDULED_SCAN_JITTER`], so the scans of a tenant's repositories (often
//! all on one git host) do not start in the same second.
use std::collections::VecDeque;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::sync::Arc;
use std::time::Duration;
use dashmap::mapref::entry::Entry;
use dashmap::DashMap;
use rand::Rng;
use tokio::sync::oneshot;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use compliance_core::models::ScanTrigger;
/// The longest a scheduled scan waits before it starts.
pub const SCHEDULED_SCAN_JITTER: Duration = Duration::from_secs(30);
/// How many slots in a row go to person-started scans while a background scan
/// waits; the next one goes to the background scan.
pub const PERSON_GRANTS_IN_A_ROW: u32 = 3;
/// How long a scan with `trigger` waits before it starts: a random delay of
/// up to [`SCHEDULED_SCAN_JITTER`] for a scheduled scan, none for a scan a
/// webhook or a person started.
@@ -63,108 +45,33 @@ pub fn start_delay(trigger: &ScanTrigger) -> Duration {
}
}
/// Which queue a scan waits in for a slot.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Priority {
/// Started by a person (the customer or support): served first.
Person,
/// Scheduled, webhook and new-content scans, and PR reviews.
Background,
}
impl Priority {
/// The queue a scan with `trigger` waits in.
pub fn of(trigger: &ScanTrigger) -> Self {
if trigger.started_by_person() {
Self::Person
} else {
Self::Background
}
}
}
/// One scan to run: what started it and the run recorded for it while it
/// waits (`None` when that record could not be written).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Job {
pub trigger: ScanTrigger,
pub run_id: Option<String>,
/// Set when a person's request took over a waiting scan that was not a
/// person's: that scan's trigger, which the run is charged as (t84).
pub charged_as: Option<ScanTrigger>,
}
impl Job {
/// A scan started by `trigger`, recorded as the run `run_id`.
pub fn new(trigger: ScanTrigger, run_id: Option<String>) -> Self {
Self {
trigger,
run_id,
charged_as: None,
}
}
fn priority(&self) -> Priority {
Priority::of(&self.trigger)
}
}
/// What happened to a scan request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Admission {
/// Nothing was queued or running for this target: the caller now holds
/// it and runs its scans through [`ScanGate::start`].
/// Nothing was running for this target: the caller runs the scan now.
Run,
/// The request will run: as the target's pending follow-up, or in place
/// of the target's waiting scan. `replaced` is the run of the request it
/// took over, which will not happen.
Coalesced { replaced: Option<String> },
/// A scan already queued for this target covers the request: its own run
/// will not happen.
/// A scan is running; this request becomes the single pending follow-up,
/// run by the task that holds the target once it finishes.
Coalesced,
/// A scan is running and a follow-up is already pending: nothing to do.
Dropped,
}
/// The scan queue is gone, or the target is no longer held.
#[derive(Debug, thiserror::Error)]
pub enum GateError {
#[error("the scan queue was closed")]
Closed,
#[error("the target is not held")]
NotHeld,
}
/// Global scan slots plus the per-target coalescing state.
#[derive(Debug)]
pub struct ScanGate {
slots: Arc<Slots>,
/// Present while a scan of the key waits or runs.
targets: DashMap<String, Held>,
}
/// The scans of one target that are queued or running.
#[derive(Debug)]
struct Held {
/// The scan that waits for a slot or runs now.
current: Job,
/// Whether `current` has its slot.
running: bool,
/// The follow-up requested while `current` runs.
pending: Option<Job>,
slots: Arc<Semaphore>,
/// Present while a scan of the key is running; the value is the pending
/// follow-up's trigger, if one was requested meanwhile.
running: DashMap<String, Option<ScanTrigger>>,
}
impl ScanGate {
/// A gate allowing `concurrency` scans at once (at least one).
pub fn new(concurrency: usize) -> Self {
Self {
slots: Arc::new(Slots {
queue: Mutex::new(Queue {
free: concurrency.max(1),
person: VecDeque::new(),
background: VecDeque::new(),
person_grants: 0,
}),
}),
targets: DashMap::new(),
slots: Arc::new(Semaphore::new(concurrency.max(1))),
running: DashMap::new(),
}
}
@@ -176,253 +83,60 @@ impl ScanGate {
/// Decide what to do with a scan request for `key`. Atomic per key, so two
/// simultaneous requests can never both be told to [`Admission::Run`].
pub fn admit(&self, key: &str, job: Job) -> Admission {
// Lock order: a target's entry, then the slot queue (in `promote`).
// `start` keeps the same order and `Permit::drop` takes only the queue.
match self.targets.entry(key.to_string()) {
pub fn admit(&self, key: &str, trigger: ScanTrigger) -> Admission {
match self.running.entry(key.to_string()) {
Entry::Vacant(v) => {
v.insert(Held {
current: job,
running: false,
pending: None,
});
v.insert(None);
Admission::Run
}
Entry::Occupied(mut o) => {
let held = o.get_mut();
let person = job.trigger.started_by_person();
// A person's request takes over a queued scan that is not a
// person's: that one might skip as unchanged (#465), theirs
// always scans, e.g. right after they uploaded new files.
let takes_over = |queued: &Job| person && !queued.trigger.started_by_person();
if !held.running {
// The waiting scan reads the latest code once it starts,
// so it covers the request, or the person's takes its
// place, at person priority. It would have run anyway,
// so it is charged as the scan it replaces.
if !takes_over(&held.current) {
return Admission::Dropped;
}
let job = Job {
charged_as: Some(held.current.trigger.clone()),
..job
};
let replaced = std::mem::replace(&mut held.current, job).run_id;
self.slots.promote(key);
return Admission::Coalesced { replaced };
}
match held.pending.as_ref().map(takes_over) {
None => {
held.pending = Some(job);
Admission::Coalesced { replaced: None }
}
Some(true) => {
let replaced = held.pending.replace(job).and_then(|p| p.run_id);
Admission::Coalesced { replaced }
}
Some(false) => Admission::Dropped,
}
Entry::Occupied(mut o) if o.get().is_none() => {
o.insert(Some(trigger));
Admission::Coalesced
}
// A person's request takes over a pending scheduled or webhook
// follow-up: that one may skip as unchanged (#465), theirs always
// scans, e.g. right after they uploaded new files.
Entry::Occupied(mut o)
if trigger.started_by_person()
&& o.get().as_ref().is_some_and(|p| !p.started_by_person()) =>
{
o.insert(Some(trigger));
Admission::Coalesced
}
Entry::Occupied(_) => Admission::Dropped,
}
}
/// Wait for a slot for the held target `key`'s next scan, in the queue of
/// its priority, and return the slot with the scan to run. The scan is the
/// one current when the slot is granted: a person's request may have taken
/// it over meanwhile.
///
/// # Errors
///
/// [`GateError::NotHeld`] if `key` was released meanwhile, and
/// [`GateError::Closed`] if the queue is gone, which this gate never does.
pub async fn start(&self, key: &str) -> Result<(Permit, Job), GateError> {
let waiting = {
let held = self.targets.get(key).ok_or(GateError::NotHeld)?;
self.slots.enqueue(Some(key), held.current.priority())
// The entry's guard is dropped here, before waiting.
};
let permit = waiting.wait().await?;
let mut held = self.targets.get_mut(key).ok_or(GateError::NotHeld)?;
held.running = true;
Ok((permit, held.current.clone()))
}
/// Called by the task holding `key` after each scan. Returns whether a
/// follow-up is pending, to run next through [`Self::start`] (the target
/// stays held), or `false` once there is nothing left, releasing it.
pub fn finish(&self, key: &str) -> bool {
match self.targets.entry(key.to_string()) {
Entry::Occupied(mut o) => {
let held = o.get_mut();
match held.pending.take() {
Some(next) => {
held.current = next;
held.running = false;
true
}
None => {
o.remove();
false
}
/// Called by the task holding `key` after each scan. Returns the pending
/// follow-up to run next (the target stays held), or `None` once there is
/// nothing left, releasing the target.
pub fn finish(&self, key: &str) -> Option<ScanTrigger> {
match self.running.entry(key.to_string()) {
Entry::Occupied(mut o) => match o.get_mut().take() {
Some(next) => Some(next),
None => {
o.remove();
None
}
}
Entry::Vacant(_) => false,
},
Entry::Vacant(_) => None,
}
}
/// Release `key` unconditionally, dropping any pending follow-up. Used when
/// the holding task dies, so the target does not stay "running" forever.
pub fn release(&self, key: &str) {
self.targets.remove(key);
self.running.remove(key);
}
/// Wait for a slot for work that is not a target's scan (a PR review).
/// The slot is freed when the returned permit is dropped.
/// Wait for one of the global scan slots. The slot is freed when the
/// returned permit is dropped.
///
/// # Errors
///
/// Only if the queue is gone, which this gate never does.
pub async fn slot(&self, priority: Priority) -> Result<Permit, GateError> {
self.slots.enqueue(None, priority).wait().await
}
}
/// The slots and the two queues waiting for them.
#[derive(Debug)]
struct Slots {
queue: Mutex<Queue>,
}
#[derive(Debug)]
struct Queue {
/// Slots nobody holds. Only above zero while nobody waits.
free: usize,
person: VecDeque<Waiter>,
background: VecDeque<Waiter>,
/// Person scans granted in a row while a background scan waited.
person_grants: u32,
}
/// One request waiting for a slot; the slot is handed over through `grant`.
#[derive(Debug)]
struct Waiter {
/// The target it is for, so a person's request can move it forward.
key: Option<String>,
grant: oneshot::Sender<Permit>,
}
/// A request in a queue, or a slot already granted.
enum Waiting {
Granted(Permit),
Queued(oneshot::Receiver<Permit>),
}
impl Waiting {
async fn wait(self) -> Result<Permit, GateError> {
match self {
Self::Granted(permit) => Ok(permit),
// The sender only goes away unsent with the gate itself.
Self::Queued(grant) => grant.await.map_err(|_| GateError::Closed),
}
}
}
impl Slots {
/// The queue, also after a thread panicked while holding it: every change
/// to it is a single push or pop, so it is never left half-changed.
fn lock(&self) -> MutexGuard<'_, Queue> {
self.queue.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Take a free slot, or join the queue of `priority`.
fn enqueue(self: &Arc<Self>, key: Option<&str>, priority: Priority) -> Waiting {
let mut queue = self.lock();
if queue.free > 0 {
queue.free -= 1;
return Waiting::Granted(Permit::new(self));
}
let (grant, granted) = oneshot::channel();
let waiter = Waiter {
key: key.map(str::to_string),
grant,
};
match priority {
Priority::Person => queue.person.push_back(waiter),
Priority::Background => queue.background.push_back(waiter),
}
Waiting::Queued(granted)
}
/// Move the background request for `key`, if one waits, to the back of
/// the person queue.
fn promote(&self, key: &str) {
let mut queue = self.lock();
let found = queue
.background
.iter()
.position(|w| w.key.as_deref() == Some(key));
if let Some(waiter) = found.and_then(|i| queue.background.remove(i)) {
queue.person.push_back(waiter);
}
}
/// Hand a freed slot to the next request, or keep it free.
fn release(self: &Arc<Self>) {
let mut queue = self.lock();
while let Some(waiter) = queue.next() {
match waiter.grant.send(Permit::new(self)) {
Ok(()) => return,
// The request was given up (its task ended): the permit comes
// back unused, and the slot goes to the next one.
Err(mut unused) => unused.slots = None,
}
}
queue.free += 1;
}
}
impl Queue {
/// The next request to serve: person scans first, except that a waiting
/// background scan gets the slot after [`PERSON_GRANTS_IN_A_ROW`] person
/// scans in a row.
fn next(&mut self) -> Option<Waiter> {
let background_due = self.person.is_empty() || self.person_grants >= PERSON_GRANTS_IN_A_ROW;
if background_due {
if let Some(waiter) = self.background.pop_front() {
self.person_grants = 0;
return Some(waiter);
}
}
let waiter = self.person.pop_front()?;
self.person_grants = if self.background.is_empty() {
0
} else {
self.person_grants + 1
};
Some(waiter)
}
}
/// One scan slot; freed, and handed to the next request, when dropped.
#[derive(Debug)]
pub struct Permit {
/// `None` once the permit was given back unused.
slots: Option<Arc<Slots>>,
}
impl Permit {
fn new(slots: &Arc<Slots>) -> Self {
Self {
slots: Some(Arc::clone(slots)),
}
}
}
impl Drop for Permit {
fn drop(&mut self) {
if let Some(slots) = self.slots.take() {
slots.release();
}
/// Only if the semaphore was closed, which this gate never does.
pub async fn slot(&self) -> Result<OwnedSemaphorePermit, tokio::sync::AcquireError> {
self.slots.clone().acquire_owned().await
}
}
@@ -461,20 +175,10 @@ impl Drop for HeldTarget<'_> {
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::{
start_delay, Admission, HeldTarget, Job, Priority, ScanGate, PERSON_GRANTS_IN_A_ROW,
SCHEDULED_SCAN_JITTER,
};
use super::{start_delay, Admission, HeldTarget, ScanGate, SCHEDULED_SCAN_JITTER};
use compliance_core::models::ScanTrigger;
use std::sync::{Arc, Mutex};
use std::time::Duration;
type Log = Arc<Mutex<Vec<(String, ScanTrigger)>>>;
fn job(trigger: ScanTrigger, run: &str) -> Job {
Job::new(trigger, Some(run.to_string()))
}
#[test]
fn a_scheduled_scan_waits_within_the_jitter() {
let delays: Vec<Duration> = (0..1000)
@@ -498,163 +202,52 @@ mod tests {
}
#[test]
fn only_a_persons_scan_has_person_priority() {
assert_eq!(Priority::of(&ScanTrigger::Manual), Priority::Person);
assert_eq!(Priority::of(&ScanTrigger::Support), Priority::Person);
for trigger in [
ScanTrigger::Scheduled,
ScanTrigger::Webhook,
ScanTrigger::NewContent,
] {
assert_eq!(Priority::of(&trigger), Priority::Background);
}
}
#[tokio::test]
async fn a_burst_coalesces_into_one_run_and_one_follow_up() {
fn a_burst_coalesces_into_one_run_and_one_follow_up() {
let gate = ScanGate::new(2);
let key = ScanGate::key("acme", "t1");
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r1")),
Admission::Run
);
let (_slot, running) = gate.start(&key).await.unwrap();
assert_eq!(running, job(ScanTrigger::Manual, "r1"));
assert_eq!(
gate.admit(&key, job(ScanTrigger::Webhook, "r2")),
Admission::Coalesced { replaced: None }
);
for i in 0..8 {
let run = format!("drop{i}");
assert_eq!(
gate.admit(&key, job(ScanTrigger::Webhook, &run)),
Admission::Dropped
);
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Coalesced);
for _ in 0..8 {
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Dropped);
}
// The holder runs the one follow-up, then releases the target.
assert!(gate.finish(&key));
let (_next, follow_up) = gate.start(&key).await.unwrap();
assert_eq!(follow_up, job(ScanTrigger::Webhook, "r2"));
assert!(!gate.finish(&key));
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r3")),
Admission::Run
);
assert!(gate.finish(&key).is_some());
assert!(gate.finish(&key).is_none());
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
}
#[test]
fn a_scan_still_waiting_covers_requests_that_are_not_a_persons() {
fn a_persons_request_takes_over_a_pending_scheduled_follow_up() {
let gate = ScanGate::new(1);
let key = ScanGate::key("acme", "t1");
assert_eq!(gate.admit(&key, ScanTrigger::Scheduled), Admission::Run);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Scheduled, "r1")),
Admission::Run
);
// Not started yet, so it will read the push's code anyway.
assert_eq!(
gate.admit(&key, job(ScanTrigger::Webhook, "r2")),
Admission::Dropped
);
}
#[tokio::test]
async fn a_waiting_scan_taken_over_is_charged_as_the_scan_it_replaces() {
let gate = ScanGate::new(1);
let key = ScanGate::key("acme", "t1");
assert_eq!(
gate.admit(&key, job(ScanTrigger::Webhook, "r1")),
Admission::Run
);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r2")),
Admission::Coalesced {
replaced: Some("r1".into())
}
);
let (_slot, run) = gate.start(&key).await.unwrap();
assert_eq!(run.trigger, ScanTrigger::Manual);
assert_eq!(run.charged_as, Some(ScanTrigger::Webhook));
}
#[tokio::test]
async fn a_persons_follow_up_after_a_running_scan_is_charged_as_theirs() {
let gate = ScanGate::new(1);
let key = ScanGate::key("acme", "t1");
assert_eq!(
gate.admit(&key, job(ScanTrigger::Scheduled, "r1")),
Admission::Run
);
let (running, _) = gate.start(&key).await.unwrap();
// Pending behind the running scan, replacing a scheduled follow-up.
assert_eq!(
gate.admit(&key, job(ScanTrigger::Scheduled, "r2")),
Admission::Coalesced { replaced: None }
);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r3")),
Admission::Coalesced {
replaced: Some("r2".into())
}
);
drop(running);
assert!(gate.finish(&key));
let (_slot, follow_up) = gate.start(&key).await.unwrap();
assert_eq!(follow_up, job(ScanTrigger::Manual, "r3"));
assert_eq!(follow_up.charged_as, None);
}
#[tokio::test]
async fn a_persons_request_takes_over_a_pending_scheduled_follow_up() {
let gate = ScanGate::new(1);
let key = ScanGate::key("acme", "t1");
assert_eq!(
gate.admit(&key, job(ScanTrigger::Scheduled, "r1")),
Admission::Run
);
let _slot = gate.start(&key).await.unwrap();
assert_eq!(
gate.admit(&key, job(ScanTrigger::Scheduled, "r2")),
Admission::Coalesced { replaced: None }
gate.admit(&key, ScanTrigger::Scheduled),
Admission::Coalesced
);
// Clicked after uploading new files: the follow-up scans in full, and
// the scheduled follow-up's queued run will not happen.
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r3")),
Admission::Coalesced {
replaced: Some("r2".into())
}
);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Webhook, "r4")),
Admission::Dropped
);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Support, "r5")),
Admission::Dropped
);
// Clicked after uploading new files: the follow-up scans in full.
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Coalesced);
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Dropped);
assert_eq!(gate.admit(&key, ScanTrigger::Support), Admission::Dropped);
assert!(gate.finish(&key));
assert_eq!(gate.finish(&key), Some(ScanTrigger::Manual));
}
#[test]
fn targets_and_tenants_are_independent() {
let gate = ScanGate::new(2);
assert_eq!(
gate.admit(&ScanGate::key("acme", "t1"), job(ScanTrigger::Manual, "a")),
gate.admit(&ScanGate::key("acme", "t1"), ScanTrigger::Manual),
Admission::Run
);
assert_eq!(
gate.admit(&ScanGate::key("acme", "t2"), job(ScanTrigger::Manual, "b")),
gate.admit(&ScanGate::key("acme", "t2"), ScanTrigger::Manual),
Admission::Run
);
// Same target id in another tenant is another target.
assert_eq!(
gate.admit(
&ScanGate::key("globex", "t1"),
job(ScanTrigger::Manual, "c")
),
gate.admit(&ScanGate::key("globex", "t1"), ScanTrigger::Manual),
Admission::Run
);
}
@@ -663,228 +256,34 @@ mod tests {
fn a_dead_holder_does_not_leave_the_target_locked() {
let gate = ScanGate::new(1);
let key = ScanGate::key("acme", "t1");
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r1")),
Admission::Run
);
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
{
// The holding task ends without calling finish (panic / shutdown).
let _held = HeldTarget::new(&gate, key.clone());
}
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r2")),
Admission::Run
);
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
}
#[tokio::test]
async fn a_disarmed_holder_leaves_the_state_to_finish() {
#[test]
fn a_disarmed_holder_leaves_the_state_to_finish() {
let gate = ScanGate::new(1);
let key = ScanGate::key("acme", "t1");
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r1")),
Admission::Run
);
let _slot = gate.start(&key).await.unwrap();
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
HeldTarget::new(&gate, key.clone()).disarm();
// Still held: disarm does not release, finish does.
assert_eq!(
gate.admit(&key, job(ScanTrigger::Webhook, "r2")),
Admission::Coalesced { replaced: None }
);
}
/// What `ComplianceAgent::run_target_scan` does once admitted: take a
/// slot, scan (here: log), and run the pending follow-up, if any.
async fn hold_and_scan(gate: Arc<ScanGate>, key: String, log: Log) {
loop {
{
let (_slot, job) = gate.start(&key).await.unwrap();
log.lock().unwrap().push((key.clone(), job.trigger));
}
if !gate.finish(&key) {
break;
}
}
}
/// Admit `trigger` for each of `targets` of tenant `acme`, each with a
/// task that scans it, queued in that order behind a slot held elsewhere.
async fn queue_targets(
gate: &Arc<ScanGate>,
targets: &[&str],
trigger: ScanTrigger,
log: &Log,
) -> Vec<tokio::task::JoinHandle<()>> {
let mut tasks = Vec::new();
for target in targets {
let key = ScanGate::key("acme", target);
assert_eq!(
gate.admit(&key, job(trigger.clone(), target)),
Admission::Run
);
tasks.push(tokio::spawn(hold_and_scan(gate.clone(), key, log.clone())));
// Let it queue for the slot before the next one does.
tokio::task::yield_now().await;
}
tasks
}
fn triggers(log: &Log) -> Vec<ScanTrigger> {
log.lock().unwrap().iter().map(|(_, t)| t.clone()).collect()
}
#[tokio::test]
async fn a_persons_scan_gets_the_next_slot_before_scheduled_scans() {
let gate = Arc::new(ScanGate::new(1));
let log = Log::default();
// Another tenant's scan has the only slot.
let busy = gate.slot(Priority::Background).await.unwrap();
let mut tasks = queue_targets(&gate, &["t1", "t2"], ScanTrigger::Scheduled, &log).await;
tasks.extend(queue_targets(&gate, &["t3"], ScanTrigger::Manual, &log).await);
drop(busy);
for task in tasks {
task.await.unwrap();
}
assert_eq!(
triggers(&log),
[
ScanTrigger::Manual,
ScanTrigger::Scheduled,
ScanTrigger::Scheduled
]
);
}
#[tokio::test]
async fn a_persons_request_takes_over_a_scheduled_scan_still_waiting() {
let gate = Arc::new(ScanGate::new(1));
let log = Log::default();
// Another tenant's scan has the only slot.
let busy = gate.slot(Priority::Background).await.unwrap();
// A scheduler tick admits three targets; all wait for the slot.
let tasks = queue_targets(&gate, &["t1", "t2", "t3"], ScanTrigger::Scheduled, &log).await;
// A person asks for t3 while its scheduled scan still waits, last.
let t3 = ScanGate::key("acme", "t3");
assert_eq!(
gate.admit(&t3, job(ScanTrigger::Manual, "click")),
Admission::Coalesced {
replaced: Some("t3".into())
}
);
drop(busy);
for task in tasks {
task.await.unwrap();
}
// Their scan runs first, once, in place of the scheduled one, and
// is charged as the scheduled one (asserted on the job below).
let order: Vec<(String, ScanTrigger)> = log.lock().unwrap().clone();
assert_eq!(
order,
[
(t3, ScanTrigger::Manual),
(ScanGate::key("acme", "t1"), ScanTrigger::Scheduled),
(ScanGate::key("acme", "t2"), ScanTrigger::Scheduled),
]
);
}
#[tokio::test]
async fn a_persons_follow_up_waits_only_for_the_running_scan() {
let gate = Arc::new(ScanGate::new(1));
let log = Log::default();
let t1 = ScanGate::key("acme", "t1");
assert_eq!(
gate.admit(&t1, job(ScanTrigger::Scheduled, "t1")),
Admission::Run
);
// t1's scheduled scan runs; two more targets queue behind it.
let (running, _) = gate.start(&t1).await.unwrap();
let tasks = queue_targets(&gate, &["t2", "t3"], ScanTrigger::Scheduled, &log).await;
assert_eq!(
gate.admit(&t1, job(ScanTrigger::Manual, "click")),
Admission::Coalesced { replaced: None }
);
// t1's scan ends; its follow-up queues as a person's.
assert!(gate.finish(&t1));
let follow_up = tokio::spawn(hold_and_scan(gate.clone(), t1.clone(), log.clone()));
tokio::task::yield_now().await;
drop(running);
follow_up.await.unwrap();
for task in tasks {
task.await.unwrap();
}
assert_eq!(
triggers(&log),
[
ScanTrigger::Manual,
ScanTrigger::Scheduled,
ScanTrigger::Scheduled
]
);
}
#[tokio::test]
async fn a_stream_of_clicks_does_not_starve_scheduled_scans() {
let gate = Arc::new(ScanGate::new(1));
let log = Log::default();
let busy = gate.slot(Priority::Background).await.unwrap();
let mut tasks = queue_targets(&gate, &["s1"], ScanTrigger::Scheduled, &log).await;
let clicks: Vec<String> = (0..10).map(|i| format!("p{i}")).collect();
let clicks: Vec<&str> = clicks.iter().map(String::as_str).collect();
tasks.extend(queue_targets(&gate, &clicks, ScanTrigger::Manual, &log).await);
drop(busy);
for task in tasks {
task.await.unwrap();
}
let scheduled_at = triggers(&log)
.iter()
.position(|t| *t == ScanTrigger::Scheduled)
.unwrap();
assert_eq!(scheduled_at, PERSON_GRANTS_IN_A_ROW as usize);
}
#[tokio::test]
async fn a_given_up_request_passes_its_slot_on() {
let gate = Arc::new(ScanGate::new(1));
let busy = gate.slot(Priority::Background).await.unwrap();
// A request that waits and is then given up (its task ends).
let gone = tokio::spawn({
let gate = gate.clone();
async move { gate.slot(Priority::Person).await.map(drop) }
});
tokio::task::yield_now().await;
gone.abort();
let _ = gone.await;
drop(busy);
let next = tokio::time::timeout(Duration::from_millis(50), gate.slot(Priority::Background));
assert!(
next.await.is_ok(),
"the slot is not lost to the given-up request"
);
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Coalesced);
}
#[tokio::test]
async fn slots_bound_how_many_scans_run_at_once() {
let gate = ScanGate::new(2);
let a = gate.slot(Priority::Background).await.unwrap();
let _b = gate.slot(Priority::Background).await.unwrap();
let a = gate.slot().await.unwrap();
let _b = gate.slot().await.unwrap();
// A third slot is not available until one is freed.
let third =
tokio::time::timeout(Duration::from_millis(50), gate.slot(Priority::Person)).await;
let third = tokio::time::timeout(std::time::Duration::from_millis(50), gate.slot()).await;
assert!(third.is_err(), "a third concurrent scan must wait");
drop(a);
let third =
tokio::time::timeout(Duration::from_millis(50), gate.slot(Priority::Person)).await;
let third = tokio::time::timeout(std::time::Duration::from_millis(50), gate.slot()).await;
assert!(third.is_ok(), "a freed slot is reused");
}
}
-28
View File
@@ -126,34 +126,6 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError>
.await
.map_err(|e| AgentError::Scheduler(format!("Failed to add git sync job: {e}")))?;
// Issues a person closed or reopened in Gitea (#953), for the targets no
// webhook reports them for; at the managed git sync's interval.
let poll_agent = agent.clone();
let poll_job = Job::new_repeated_async(agent.git_source.sync_interval, move |_uuid, _lock| {
let agent = poll_agent.clone();
Box::pin(async move {
for tenant_id in scheduler_tenants(&agent).await {
match crate::pipeline::issue_poll::poll_tenant(&agent, &tenant_id).await {
Ok(s) if s.targets > 0 => tracing::info!(
tenant_id,
targets = s.targets,
findings = s.findings,
recorded = s.recorded,
failed = s.failed,
"issue poll done"
),
Ok(_) => {}
Err(e) => tracing::warn!(tenant_id, "issue poll skipped: {e}"),
}
}
})
})
.map_err(|e| AgentError::Scheduler(format!("Failed to create issue poll job: {e}")))?;
sched
.add(poll_job)
.await
.map_err(|e| AgentError::Scheduler(format!("Failed to add issue poll job: {e}")))?;
sched
.start()
.await
+4 -143
View File
@@ -114,9 +114,7 @@ impl GiteaTracker {
/// Every page of a list endpoint, `path` being the URL without `page` and
/// `limit`. Only an empty page ends the list: an instance may cap the page
/// size below ours (`[api] MAX_RESPONSE_ITEMS`). Gitea answers some lists
/// past their end with `null` instead of `[]` (an issue's timeline does),
/// which ends the list the same way.
/// size below ours (`[api] MAX_RESPONSE_ITEMS`).
///
/// # Errors
///
@@ -135,11 +133,10 @@ impl GiteaTracker {
let url = self.api_url(&format!(
"{path}{separator}page={page}&limit={LIST_PAGE_SIZE}"
));
// `Option` takes the `null` page; serde reads it as `None`.
let batch: Option<Vec<T>> = self.send_json(what, self.http.get(&url)).await?;
let Some(batch) = batch.filter(|b| !b.is_empty()) else {
let batch: Vec<T> = self.send_json(what, self.http.get(&url)).await?;
if batch.is_empty() {
return Ok(all);
};
}
all.extend(batch);
}
Err(CoreError::IssueTracker(format!(
@@ -179,39 +176,6 @@ impl GiteaTracker {
.await
}
/// The login of whoever last closed (`closed`) or reopened issue `number`,
/// from its timeline; `None` if the timeline has no such entry. The issue
/// itself does not say who closed it.
///
/// # Errors
///
/// [`CoreError::IssueTracker`] if the timeline cannot be read, or has more
/// than `MAX_TIMELINE_PAGES` pages.
pub async fn last_state_change_by(
&self,
owner: &str,
repo: &str,
number: i64,
closed: bool,
) -> Result<Option<String>, CoreError> {
let kind = if closed { "close" } else { "reopen" };
let events: Vec<GiteaTimelineEvent> = self
.list_all(
"issue timeline",
&format!("/repos/{owner}/{repo}/issues/{number}/timeline"),
MAX_TIMELINE_PAGES,
)
.await?;
// Oldest first: the last matching entry is the current state's.
Ok(events
.into_iter()
.rev()
.find(|e| e.kind == kind)
.and_then(|e| e.user)
.map(|u| u.login)
.filter(|login| !login.is_empty()))
}
/// Make sure the repository has every label in `wanted`, creating the
/// missing ones, and return the id of each by name. Needs write access to
/// the repository's issues, nothing more.
@@ -323,25 +287,6 @@ const LIST_PAGE_SIZE: usize = 50;
const MAX_LABEL_PAGES: usize = 20;
/// Upper bound on issue pages (10 000 issues).
const MAX_ISSUE_PAGES: usize = 200;
/// Upper bound on the timeline pages of one issue (1 000 entries).
const MAX_TIMELINE_PAGES: usize = 20;
/// A Gitea user, by login.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
pub struct GiteaUser {
#[serde(default)]
pub login: String,
}
/// An entry of an issue's timeline, with what a close or reopen needs:
/// `type` is `close`, `reopen`, `comment`, ...
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
struct GiteaTimelineEvent {
#[serde(rename = "type", default)]
kind: String,
#[serde(default)]
user: Option<GiteaUser>,
}
/// An issue as Gitea lists it, with what an issue is matched by.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
@@ -356,21 +301,6 @@ pub struct GiteaIssue {
/// `open` or `closed`.
#[serde(default)]
pub state: String,
/// Who opened it: Prüfwerk's issues are opened by its bot user.
#[serde(default)]
pub user: Option<GiteaUser>,
}
impl GiteaIssue {
/// The login of whoever opened the issue, empty if Gitea did not say.
pub fn author(&self) -> &str {
self.user.as_ref().map_or("", |u| u.login.as_str())
}
/// Whether the issue is closed.
pub fn is_closed(&self) -> bool {
self.state == "closed"
}
}
/// A repository label as Gitea returns it.
@@ -803,75 +733,6 @@ mod tests {
assert_eq!(seen.lock().unwrap().len(), 4);
}
/// A fake Gitea whose issue timeline has one page of `entries`, then
/// answers `null` as Gitea does past the end of a timeline.
async fn fake_timeline(entries: serde_json::Value) -> String {
let app = Router::new()
.route(
"/api/v1/repos/{owner}/{repo}/issues/{number}/timeline",
get(
|axum::extract::Query(params): axum::extract::Query<
HashMap<String, String>,
>,
State(entries): State<serde_json::Value>| async move {
if params["page"] == "1" {
Json(entries)
} else {
Json(serde_json::Value::Null)
}
},
),
)
.with_state(entries);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
format!("http://{addr}")
}
#[tokio::test]
async fn a_null_timeline_page_ends_the_list() {
let base = fake_timeline(serde_json::json!([])).await;
let tracker =
GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap();
let entries: Vec<serde_json::Value> = tracker
.list_all("issue timeline", "/repos/o/r/issues/1/timeline", 3)
.await
.unwrap();
assert!(entries.is_empty());
let base = fake_timeline(serde_json::json!([{ "id": 1 }, { "id": 2 }])).await;
let tracker =
GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap();
let entries: Vec<serde_json::Value> = tracker
.list_all("issue timeline", "/repos/o/r/issues/1/timeline", 3)
.await
.unwrap();
assert_eq!(entries.len(), 2, "the page before the null one counts");
}
#[tokio::test]
async fn a_null_first_timeline_page_is_an_empty_timeline() {
let app = Router::new().route(
"/api/v1/repos/{owner}/{repo}/issues/{number}/timeline",
get(|| async { Json(serde_json::Value::Null) }),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let tracker = GiteaTracker::new(
format!("http://{addr}"),
SecretString::from("t"),
NetGuard::allow_private(),
)
.unwrap();
let entries: Vec<serde_json::Value> = tracker
.list_all("issue timeline", "/repos/o/r/issues/1/timeline", 3)
.await
.unwrap();
assert!(entries.is_empty());
}
#[tokio::test]
async fn a_failed_listing_is_an_error_not_an_empty_list() {
let app = Router::new().route(
+1 -20
View File
@@ -6,9 +6,7 @@
//! source is read through a handle that cannot conjure a tenant database.
//!
//! A verified delivery that asks for work is answered `202 Accepted` at once;
//! the entitlement check, the target and the scan (or, for an issue closed
//! or reopened by a person, the finding's new status, #953) follow in the
//! background,
//! the entitlement check, the target and the scan follow in the background,
//! so a slow registry or Keycloak never runs into Gitea's delivery timeout.
//! What became of it (handled, refused, failed) is recorded for the target
//! page, since Gitea's delivery log only ever sees the `202`.
@@ -201,9 +199,6 @@ fn delivery_of(event: &str, result: &Result<Outcome, NotHandled>) -> WebhookDeli
Ok(Outcome::Archived(false)) => {
(DeliveryResult::Handled, "no active target to archive", None)
}
Ok(Outcome::Issue { target_id, detail }) => {
(DeliveryResult::Handled, *detail, Some(target_id.clone()))
}
Ok(Outcome::Ignored(why)) => (DeliveryResult::Handled, *why, None),
Err(NotHandled::Refused(why)) => (DeliveryResult::Refused, why.as_str(), None),
Err(NotHandled::Failed(why)) => (DeliveryResult::Failed, why.as_str(), None),
@@ -262,20 +257,6 @@ mod tests {
let d = delivery_of("repository", &Ok(ensured(false)));
assert_eq!(d.detail, "target ready, nothing to scan yet");
let issue = Outcome::Issue {
target_id: "t1".into(),
detail: "finding resolved: issue closed in Gitea",
};
let d = delivery_of("issues", &Ok(issue));
assert_eq!(
(d.result, d.detail.as_str(), d.target_id.as_deref()),
(
DeliveryResult::Handled,
"finding resolved: issue closed in Gitea",
Some("t1")
)
);
let d = delivery_of("repository", &Ok(Outcome::Archived(true)));
assert_eq!(
(d.result, d.detail.as_str()),
-151
View File
@@ -1,151 +0,0 @@
//! DAST findings join the findings of the target they were found on (#998),
//! with their control refs, and a second scan does not add them again. A DAST
//! finding is linked to the target's one open code finding with its CWE.
//! Drives the real API and pipeline against a live Mongo (`TEST_MONGODB_URI`)
//! and a local site, so this binary allows private targets for its process.
#![allow(clippy::expect_used, clippy::unwrap_used)]
mod common;
use axum::http::header::ACCESS_CONTROL_ALLOW_ORIGIN;
use axum::Router;
use common::TestServer;
use compliance_core::models::{Finding, ScanType, Severity};
use mongodb::bson::{doc, Document};
use serde_json::json;
/// A site that lets any origin read its answers.
async fn open_cors_site() -> String {
let app = Router::new().fallback(|| async {
(
[(ACCESS_CONTROL_ALLOW_ORIGIN, "*")],
"<html><body>shop</body></html>",
)
});
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
format!("http://{addr}")
}
/// Scan target `id` and return the finished scan run.
async fn scan(server: &TestServer, runs: &mongodb::Collection<Document>, id: &str) -> Document {
let before = runs.count_documents(doc! { "repo_id": id }).await.unwrap();
server
.post(&format!("/api/v1/targets/{id}/scan"), &json!({}))
.await;
for _ in 0..240 {
let done = runs
.count_documents(doc! { "repo_id": id, "status": { "$in": ["completed", "failed"] } })
.await
.unwrap();
if done > before {
return runs
.find_one(doc! { "repo_id": id })
.sort(doc! { "started_at": -1 })
.await
.unwrap()
.unwrap();
}
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
}
panic!("the scan of {id} did not finish");
}
#[tokio::test]
async fn dast_findings_are_findings_of_the_target_once() {
// This binary holds only this test, so the setting reaches no other one.
std::env::set_var("PW_ALLOW_PRIVATE_TARGETS", "1");
let site = open_cors_site().await;
let server = TestServer::start().await;
let created: serde_json::Value = server
.post(
"/api/v1/targets",
&json!({
"name": "shop",
"target_type": "web_app",
"artifacts": [{ "kind": "live_url", "source_ref": site }]
}),
)
.await
.json()
.await
.unwrap();
let id = created["data"]["_id"]["$oid"].as_str().unwrap().to_string();
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db = mongodb::Client::with_uri_str(&uri)
.await
.unwrap()
.database(&server.tenant_db_name());
let runs = db.collection::<Document>("scan_runs");
let findings = db.collection::<Document>("findings");
let mut code = Finding::new(
id.clone(),
"fp-code-cors".into(),
"semgrep".into(),
ScanType::Sast,
"Permissive CORS".into(),
"The server allows any origin.".into(),
Severity::Medium,
);
code.cwe = Some("CWE-942".into());
code.file_path = Some("src/server.rs".into());
let code_id = db
.collection::<Finding>("findings")
.insert_one(&code)
.await
.unwrap()
.inserted_id
.as_object_id()
.unwrap()
.to_hex();
let first = scan(&server, &runs, &id).await;
assert_eq!(first.get_str("status").unwrap(), "completed", "{first:?}");
let cors = findings
.find_one(doc! { "repo_id": &id, "scanner": "dast", "cwe": "CWE-942" })
.await
.unwrap()
.expect("the CORS finding is a finding of the target");
assert_eq!(cors.get_str("scan_type").unwrap(), "dast");
let refs: Vec<&str> = cors
.get_array("control_refs")
.unwrap()
.iter()
.filter_map(|r| r.as_str())
.collect();
assert_eq!(refs, ["cra-ai-1"]);
let dast_cors = db
.collection::<Document>("dast_findings")
.find_one(doc! { "cwe": "CWE-942" })
.await
.unwrap()
.expect("the DAST finding is stored with its evidence");
assert_eq!(
dast_cors.get_str("linked_sast_finding_id").unwrap(),
code_id,
"linked to the code finding with the same CWE"
);
let stored = findings
.count_documents(doc! { "repo_id": &id, "scanner": "dast" })
.await
.unwrap();
assert!(first.get_i64("new_findings_count").unwrap() >= i64::try_from(stored).unwrap());
let second = scan(&server, &runs, &id).await;
assert_eq!(
findings
.count_documents(doc! { "repo_id": &id, "scanner": "dast" })
.await
.unwrap(),
stored,
"a second scan finds the same weaknesses, it does not add them again"
);
assert_eq!(second.get_i64("new_findings_count").unwrap(), 0);
server.cleanup().await;
}
-149
View File
@@ -483,155 +483,6 @@ async fn platform_api_webhook_and_sync() {
h.pool.drop_tenant(TENANT).await.ok();
}
/// An issue a person closes or reopens in Gitea moves its finding (#953);
/// the same done by Prüfwerk's bot user is ignored, so nothing loops.
#[tokio::test]
async fn an_issue_closed_or_reopened_in_gitea_moves_its_finding() {
use compliance_core::models::{
Finding, FindingStatus, IssueStatus, ScanType, Severity, TrackerChangeKind, TrackerIssue,
TrackerType,
};
let Some(h) = start().await else { return };
let (status, created) = h
.put_source(serde_json::json!({
"base_url": "https://kunde.code.breakpilot.com", "org": "kunde",
"bot_token": "bot-pat", "enabled": false
}))
.await;
assert_eq!(status, 200, "{created}");
assert_eq!(
created["webhook_events"],
serde_json::json!(["repository", "push", "issues"])
);
let secret = created["webhook_secret"].as_str().unwrap().to_string();
h.db.git_sources()
.update_one(doc! {}, doc! { "$set": { "enabled": true } })
.await
.unwrap();
let send = |event: &'static str, body: serde_json::Value| {
let sig = sign(&secret, &serde_json::to_vec(&body).unwrap());
let h = &h;
async move { h.deliver(TENANT, event, &body, Some(sig)).await }
};
// Arrange: the repository's target, a finding and its issue #12.
let repo = repo_json(21, "kunde", "fw");
assert_eq!(
send(
"repository",
serde_json::json!({ "action": "created", "repository": repo })
)
.await,
202
);
Harness::eventually("the target", || async { h.target(21).await.is_some() }).await;
let target_id = h.target(21).await.unwrap().id.unwrap().to_hex();
let mut finding = Finding::new(
target_id.clone(),
"fp-backsync".into(),
"semgrep".into(),
ScanType::Sast,
"strcpy".into(),
"d".into(),
Severity::High,
);
finding.status = FindingStatus::NeedsReview;
let finding_id =
h.db.findings()
.insert_one(&finding)
.await
.unwrap()
.inserted_id
.as_object_id()
.unwrap();
let issue = TrackerIssue::new(
finding_id.to_hex(),
TrackerType::Gitea,
"12".into(),
"https://kunde.code.breakpilot.com/kunde/fw/issues/12".into(),
"strcpy".into(),
);
h.db.tracker_issues().insert_one(&issue).await.unwrap();
let issue_event = |action: &str, sender: &str| {
serde_json::json!({
"action": action, "number": 12,
"issue": { "number": 12, "user": { "login": "pruefwerk" } },
"sender": { "login": sender },
"repository": repo,
})
};
let stored = || async {
let f =
h.db.findings()
.find_one(doc! { "_id": finding_id })
.await
.unwrap()
.unwrap();
let i =
h.db.tracker_issues()
.find_one(doc! { "finding_id": finding_id.to_hex() })
.await
.unwrap()
.unwrap();
(f, i)
};
// Prüfwerk's own close (the bot opened the issue): answered at once,
// nothing changes.
assert_eq!(
send("issues", issue_event("closed", "pruefwerk")).await,
200
);
// A person closes it: resolved, as closed in the ticket by them.
assert_eq!(send("issues", issue_event("closed", "dev-anna")).await, 202);
Harness::eventually("the resolved finding", || async {
stored().await.0.status == FindingStatus::Resolved
})
.await;
let (f, i) = stored().await;
let change = f.status_history.last().unwrap();
assert_eq!(change.tracker, Some(TrackerChangeKind::ClosedInTracker));
assert_eq!(change.by_name.as_deref(), Some("dev-anna"));
assert_eq!(f.status_history.len(), 1, "the bot's close changed nothing");
assert_eq!(
(i.status, i.closed_in_tracker.as_deref()),
(IssueStatus::Closed, Some("dev-anna"))
);
let for_target = compliance_agent::webhooks::deliveries::target_filter(&target_id, None);
Harness::eventually("the recorded issue delivery", || async {
h.db.webhook_deliveries()
.count_documents({
let mut f = for_target.clone();
f.insert("detail", "finding resolved: issue closed in Gitea");
f
})
.await
.unwrap()
== 1
})
.await;
// Reopened: undecided again.
assert_eq!(
send("issues", issue_event("reopened", "dev-anna")).await,
202
);
Harness::eventually("the reopened finding", || async {
stored().await.0.status == FindingStatus::Open
})
.await;
let (f, i) = stored().await;
assert_eq!(
f.status_history.last().unwrap().tracker,
Some(TrackerChangeKind::ReopenedInTracker)
);
assert_eq!((i.status, i.closed_in_tracker), (IssueStatus::Open, None));
h.pool.drop_tenant(TENANT).await.ok();
}
/// A deliveries collection written before the indexes were ensured (a plain
/// one) is converted to a capped one.
#[tokio::test]
-386
View File
@@ -1,386 +0,0 @@
//! The "Heute" inbox (#950) through the real API: cards in their buckets,
//! decisions on a card through the findings' and VEX code, undo, and
//! resubmission dates.
//!
//! Runs against a live Mongo (`TEST_MONGODB_URI`) and skips cleanly without
//! one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
mod common;
use chrono::{Duration, Utc};
use compliance_core::models::inbox::{CardKey, InboxSnooze};
use compliance_core::models::{CveAlert, CveSource, Exploitation, KevEntry};
use mongodb::bson::{doc, oid::ObjectId, Document};
use serde_json::{json, Value};
use common::TestServer;
/// A target id and its name.
const TARGET: &str = "665f1c2ab0c4d1e2f3a4b5c6";
/// Whether a Mongo answers at the test URI.
async fn mongo_reachable() -> bool {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let Ok(client) = mongodb::Client::with_uri_str(&uri).await else {
return false;
};
client
.database("admin")
.run_command(doc! { "ping": 1 })
.await
.is_ok()
}
async fn tenant_db(server: &TestServer) -> mongodb::Database {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
mongodb::Client::with_uri_str(&uri)
.await
.unwrap()
.database(&server.tenant_db_name())
}
/// Store a finding; its id.
async fn finding(
db: &mongodb::Database,
title: &str,
scan_type: &str,
severity: &str,
status: &str,
file: &str,
) -> String {
let id = ObjectId::new();
let now = mongodb::bson::DateTime::now();
db.collection::<Document>("findings")
.insert_one(doc! {
"_id": id,
"repo_id": TARGET,
"fingerprint": format!("fp-{title}"),
"scanner": "test",
"scan_type": scan_type,
"title": title,
"description": title,
"severity": severity,
"status": status,
"file_path": file,
"line_number": 7,
"triage_action": if status == "needs_review" { "dismiss" } else { "confirm" },
"status_history": [],
"created_at": now,
"updated_at": now,
})
.await
.unwrap();
id.to_hex()
}
/// Store a CVE alert of log4j-core 2.14.1; its id.
async fn alert(db: &mongodb::Database, cve: &str, kev: bool) -> String {
let mut a = CveAlert::new(
cve.into(),
TARGET.into(),
"log4j-core".into(),
"2.14.1".into(),
CveSource::Osv,
);
let id = ObjectId::new();
a.id = Some(id);
a.severity = Some("CRITICAL".into());
a.fixed_versions = vec!["2.17.1".into()];
if kev {
a.exploitation = Some(Exploitation {
kev: Some(KevEntry {
date_added: "2021-12-10".into(),
known_ransomware: true,
}),
..Exploitation::default()
});
a.exploited_seen_at = Some(Utc::now() - Duration::hours(2));
}
db.collection::<CveAlert>("cve_alerts")
.insert_one(&a)
.await
.unwrap();
id.to_hex()
}
async fn inbox(server: &TestServer, query: &str) -> Value {
let resp = server.get(&format!("/api/v1/inbox{query}")).await;
assert_eq!(resp.status(), 200);
let body: Value = resp.json().await.unwrap();
body["data"].clone()
}
fn counts(view: &Value) -> [u64; 4] {
let c = &view["counts"];
[
c["today"].as_u64().unwrap(),
c["this_week"].as_u64().unwrap(),
c["later"].as_u64().unwrap(),
c["likely_false_positive"].as_u64().unwrap(),
]
}
#[tokio::test]
async fn the_inbox_buckets_decides_undoes_and_resubmits() {
if !mongo_reachable().await {
eprintln!("SKIP inbox: no MongoDB reachable");
return;
}
let server = TestServer::start().await;
let db = tenant_db(&server).await;
db.collection::<Document>("onboarded_targets")
.insert_one(doc! { "_id": ObjectId::parse_str(TARGET).unwrap(), "name": "Pumpe", "target_type": "software" })
.await
.unwrap();
let secret = finding(
&db,
"AWS key",
"secretdetection",
"medium",
"open",
"src/config.rs",
)
.await;
let _test_secret = finding(
&db,
"Test key",
"secretdetection",
"low",
"open",
"tests/keys.env",
)
.await;
let high = finding(&db, "SQL injection", "sast", "high", "triaged", "src/db.rs").await;
let ai = finding(
&db,
"Weak hash",
"sast",
"medium",
"needs_review",
"src/hash.rs",
)
.await;
finding(
&db,
"Old decision",
"sast",
"low",
"false_positive",
"src/a.rs",
)
.await;
let a1 = alert(&db, "CVE-2021-44228", true).await;
let a2 = alert(&db, "CVE-2021-45046", false).await;
// Today: the secret in code and log4j (KEV); this week: the high finding;
// later: the test secret; the AI's: the dismissed one.
let all = inbox(&server, "").await;
assert_eq!(counts(&all), [2, 1, 1, 1]);
assert_eq!(all["progress"], json!({ "decided": 1, "total": 7 }));
assert_eq!(
all["targets"],
json!([{
"id": TARGET,
"name": "Pumpe",
"counts": { "today": 2, "this_week": 1, "later": 1, "likely_false_positive": 1 },
}])
);
let today = all["cards"].as_array().unwrap();
let log4j = today
.iter()
.find(|c| c["kind"] == "cve_package")
.unwrap()
.clone();
let log4j_key = CardKey::cve_package(TARGET, "log4j-core", "2.14.1");
assert_eq!(log4j["key"], log4j_key);
assert_eq!(log4j["count"], 2);
assert_eq!(log4j["fix_version"], "2.17.1");
assert_eq!(log4j["reasons"][0]["kind"], "kev");
assert!(today
.iter()
.any(|c| c["item_ids"] == json!([secret]) && c["reasons"][0]["kind"] == "secret_in_code"));
let ai_card = inbox(&server, "?bucket=likely_false_positive").await["cards"][0].clone();
assert_eq!(ai_card["actions"], json!(["false_positive", "confirm"]));
assert_eq!(inbox(&server, "?target=other").await["counts"]["today"], 0);
// A CVE decision needs its justification; with it, every alert of the
// card gets the statement, and undo puts them back to open.
let refused = server
.post(
"/api/v1/inbox/decide",
&json!({ "key": log4j_key, "action": "not_affected" }),
)
.await;
assert_eq!(refused.status(), 422);
let decided = server
.post(
"/api/v1/inbox/decide",
&json!({
"key": log4j_key,
"action": "not_affected",
"justification": "vulnerable_code_not_in_execute_path",
}),
)
.await;
assert_eq!(decided.status(), 200);
let decided: Value = decided.json().await.unwrap();
let mut previous = decided["previous"].as_array().unwrap().clone();
previous.sort_by_key(|p| p["id"].as_str().unwrap().to_string());
let mut expected = vec![
json!({ "kind": "cve", "id": a1, "vex": null }),
json!({ "kind": "cve", "id": a2, "vex": null }),
];
expected.sort_by_key(|p| p["id"].as_str().unwrap().to_string());
assert_eq!(previous, expected);
let stored = db
.collection::<CveAlert>("cve_alerts")
.find_one(doc! { "_id": ObjectId::parse_str(&a1).unwrap() })
.await
.unwrap()
.unwrap();
assert_eq!(
stored.vex.map(|v| v.status),
Some(compliance_core::models::VexStatus::NotAffected)
);
let after = inbox(&server, "").await;
assert_eq!(counts(&after), [1, 1, 1, 1]);
assert_eq!(after["progress"], json!({ "decided": 3, "total": 7 }));
let again = server
.post(
"/api/v1/inbox/decide",
&json!({ "key": log4j_key, "action": "affected", "statement": "Update" }),
)
.await;
assert_eq!(again.status(), 409, "nothing left to decide");
let undone = server
.post(
"/api/v1/inbox/undo",
&json!({ "key": log4j_key, "previous": decided["previous"] }),
)
.await;
assert_eq!(undone.status(), 200);
assert_eq!(counts(&inbox(&server, "").await), [2, 1, 1, 1]);
// A finding's risk needs a reason; the status change is recorded as the
// findings endpoint records it, and undo restores the previous status.
let high_key = CardKey::finding(&high);
let no_reason = server
.post(
"/api/v1/inbox/decide",
&json!({ "key": high_key, "action": "accepted_risk" }),
)
.await;
assert_eq!(no_reason.status(), 422);
let not_offered = server
.post(
"/api/v1/inbox/decide",
&json!({ "key": high_key, "action": "confirm" }),
)
.await;
assert_eq!(not_offered.status(), 422);
let accepted: Value = server
.post(
"/api/v1/inbox/decide",
&json!({ "key": high_key, "action": "accepted_risk", "reason": "isolated network" }),
)
.await
.json()
.await
.unwrap();
assert_eq!(
accepted["previous"],
json!([{ "kind": "finding", "id": high, "status": "triaged" }])
);
let stored = db
.collection::<Document>("findings")
.find_one(doc! { "_id": ObjectId::parse_str(&high).unwrap() })
.await
.unwrap()
.unwrap();
assert_eq!(stored.get_str("status").ok(), Some("accepted_risk"));
let history = stored.get_array("status_history").unwrap();
assert_eq!(
history[0].as_document().unwrap().get_str("reason").ok(),
Some("isolated network")
);
assert_eq!(counts(&inbox(&server, "").await), [2, 0, 1, 1]);
let undone = server
.post(
"/api/v1/inbox/undo",
&json!({ "key": high_key, "previous": accepted["previous"] }),
)
.await;
assert_eq!(undone.status(), 200);
assert_eq!(counts(&inbox(&server, "").await), [2, 1, 1, 1]);
// Undo only touches the card's own items.
let foreign = server
.post(
"/api/v1/inbox/undo",
&json!({ "key": high_key, "previous": [{ "kind": "finding", "id": ai, "status": "open" }] }),
)
.await;
assert_eq!(foreign.status(), 422);
// The AI was right: the dismissed finding is a false positive.
let confirmed = server
.post(
"/api/v1/inbox/decide",
&json!({ "key": CardKey::finding(&ai), "action": "false_positive" }),
)
.await;
assert_eq!(confirmed.status(), 200);
assert_eq!(counts(&inbox(&server, "").await), [2, 1, 1, 0]);
// Put off: hidden until the date, then back in its own bucket (today).
let secret_key = CardKey::finding(&secret);
let past = server
.post(
"/api/v1/inbox/snooze",
&json!({ "key": secret_key, "for": { "kind": "date", "date": "2020-01-01" } }),
)
.await;
assert_eq!(past.status(), 422);
let snoozed = server
.post(
"/api/v1/inbox/snooze",
&json!({ "key": secret_key, "for": { "kind": "week" } }),
)
.await;
assert_eq!(snoozed.status(), 200);
assert_eq!(counts(&inbox(&server, "").await), [1, 1, 1, 0]);
let record = db
.collection::<InboxSnooze>("inbox_snoozes")
.find_one(doc! { "key": &secret_key })
.await
.unwrap()
.unwrap();
assert_eq!(record.by, "dev-user");
assert!(record.until > Utc::now() + Duration::days(6));
// The card's items are recorded, so a new one would end the snooze early.
assert_eq!(record.items, std::slice::from_ref(&secret));
db.collection::<Document>("inbox_snoozes")
.update_one(
doc! { "key": &secret_key },
doc! { "$set": { "until": mongodb::bson::DateTime::from_chrono(Utc::now() - Duration::hours(1)) } },
)
.await
.unwrap();
let due = inbox(&server, "?bucket=today").await;
assert_eq!(counts(&due), [2, 1, 1, 0]);
assert!(due["cards"]
.as_array()
.unwrap()
.iter()
.any(|c| c["key"] == secret_key && c["reasons"][0]["kind"] == "resubmission"));
let unsnoozed = server
.delete(&format!("/api/v1/inbox/snooze/{secret_key}"))
.await;
assert_eq!(unsnoozed.status(), 200);
assert_eq!(counts(&inbox(&server, "").await), [2, 1, 1, 0]);
server.cleanup().await;
}
@@ -1,5 +1,4 @@
use crate::common::TestServer;
use mongodb::bson::doc;
use serde_json::json;
#[tokio::test]
@@ -47,154 +46,3 @@ async fn list_dast_findings_empty() {
server.cleanup().await;
}
#[tokio::test]
async fn a_targets_login_is_stored_sealed_and_never_returned() {
let server = TestServer::start().await;
let resp = server
.post(
"/api/v1/dast/targets",
&json!({
"name": "members",
"base_url": "https://members.example.com",
"auth": {
"method": "bearer",
"token": "tok-secret",
"headers": { "X-Api-Key": "key-secret" },
},
}),
)
.await;
assert_eq!(resp.status(), 200);
let body: serde_json::Value = resp.json().await.unwrap();
let id = body["data"]["_id"]["$oid"].as_str().expect("the new id");
let returned = body.to_string();
assert!(
!returned.contains("tok-secret") && !returned.contains("key-secret"),
"{returned}"
);
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let stored = client
.database(&server.tenant_db_name())
.collection::<mongodb::bson::Document>("dast_targets")
.find_one(mongodb::bson::doc! {
"_id": mongodb::bson::oid::ObjectId::parse_str(id).unwrap()
})
.await
.unwrap()
.expect("stored under the returned id");
let auth = stored.get_document("auth_config").unwrap();
let token = auth.get_str("token").unwrap();
let header = auth
.get_document("headers")
.unwrap()
.get_str("X-Api-Key")
.unwrap();
assert!(token != "tok-secret" && header != "key-secret", "{auth}");
server.cleanup().await;
}
#[tokio::test]
async fn a_login_the_scan_cannot_send_is_refused() {
let server = TestServer::start().await;
for auth in [
json!({ "method": "form", "login_url": "https://members.example.com/login" }),
json!({ "method": "bearer" }),
json!({ "method": "ntlm", "token": "t" }),
] {
let resp = server
.post(
"/api/v1/dast/targets",
&json!({ "name": "m", "base_url": "https://members.example.com", "auth": auth }),
)
.await;
assert_eq!(resp.status(), 400, "{auth}");
}
let resp = server.get("/api/v1/dast/targets").await;
let body: serde_json::Value = resp.json().await.unwrap();
assert!(body["data"].as_array().unwrap().is_empty());
server.cleanup().await;
}
/// A DAST scan that does not complete is a failed `dast` stage of the scan
/// run, recorded once the stage has waited for it; the run itself completes
/// (#998). The live URL does not resolve, so reconnaissance fails.
#[tokio::test]
async fn a_dast_scan_that_does_not_complete_is_a_failed_stage_of_the_run() {
let server = TestServer::start().await;
let created: serde_json::Value = server
.post(
"/api/v1/targets",
&json!({
"name": "web",
"target_type": "web_app",
"artifacts": [
{ "kind": "live_url", "source_ref": "https://no-such-host.example.com" }
]
}),
)
.await
.json()
.await
.unwrap();
let id = created["data"]["_id"]["$oid"].as_str().unwrap().to_string();
server
.post(&format!("/api/v1/targets/{id}/scan"), &json!({}))
.await;
let client = mongodb::Client::with_uri_str(&server_mongodb_uri())
.await
.unwrap();
let runs = client
.database(&server.tenant_db_name())
.collection::<mongodb::bson::Document>("scan_runs");
let mut run = None;
for _ in 0..120 {
let found = runs
.find_one(doc! { "repo_id": &id, "status": { "$in": ["completed", "failed"] } })
.await
.unwrap();
if found.is_some() {
run = found;
break;
}
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
}
let run = run.expect("the scan run finished");
assert_eq!(run.get_str("status").unwrap(), "completed");
let dast: Vec<_> = run
.get_array("skipped_stages")
.unwrap()
.iter()
.filter_map(|s| s.as_document())
.filter(|s| s.get_str("stage") == Ok("dast"))
.collect();
assert_eq!(dast.len(), 1, "{run:?}");
assert_eq!(dast[0].get_str("code").unwrap(), "tool_failed");
assert_eq!(dast[0].get_str("subject").unwrap(), "DAST");
// The DAST run itself is stored, with the scanner's reason.
let dast_run = client
.database(&server.tenant_db_name())
.collection::<mongodb::bson::Document>("dast_scan_runs")
.find_one(doc! {})
.await
.unwrap()
.expect("the DAST run is stored");
assert_eq!(dast_run.get_str("status").unwrap(), "failed");
server.cleanup().await;
}
fn server_mongodb_uri() -> String {
std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into())
}
@@ -3,6 +3,5 @@ mod dast;
mod findings;
mod health;
mod onboarding;
mod openapi;
mod sbom;
mod stats;
@@ -1,22 +0,0 @@
use crate::common::TestServer;
/// The agent serves its OpenAPI description (#1006), with the described
/// routes and the bearer scheme.
#[tokio::test]
async fn the_agent_serves_its_openapi_description() {
let server = TestServer::start().await;
let resp = server.get("/api/v1/openapi.json").await;
assert_eq!(resp.status(), 200);
assert_eq!(
resp.headers()["content-type"].to_str().unwrap(),
"application/json"
);
let doc: serde_json::Value = resp.json().await.unwrap();
assert_eq!(doc["info"]["title"], "Prüfwerk API");
assert!(doc["paths"]["/api/v1/dast/targets"]["post"].is_object());
assert!(doc["components"]["securitySchemes"]["bearer"].is_object());
server.cleanup().await;
}
+1 -7
View File
@@ -7,7 +7,7 @@
use chrono::{TimeZone, Utc};
use compliance_agent::database::DatabasePool;
use compliance_agent::metering::{charge, month_summary, usage};
use compliance_agent::metering::{charge, usage};
use compliance_core::models::{
admit, Admission, PlanLimits, Refusal, RunCharge, PRUEFUNGEN_PER_PRUEFTAG,
};
@@ -79,11 +79,5 @@ async fn the_quota_then_a_prueftag_of_six_then_nothing() {
assert_eq!(month.prueftage, 1);
assert_eq!(month.pruefungen, 2);
// The usage view reads the same month.
let summary = month_summary(&db, at).await.unwrap();
assert_eq!(summary.month, "2026-11");
assert_eq!((summary.pruefungen, summary.prueftage), (2, 1));
assert_eq!((summary.extra_targets, summary.extra_peak), (0, 0));
pool.drop_tenant(TENANT).await.ok();
}
+3 -4
View File
@@ -563,8 +563,8 @@ async fn collect(agent: &Agent, target_id: &str, run: &Value) -> Collected {
}
/// Wait until each target has a finished scan run that did not exist before
/// seeding. Returns the run per target id; targets still queued or running
/// at the deadline are left out.
/// seeding. Returns the run per target id; targets still running at the
/// deadline are left out.
async fn wait_for_runs(
agent: &Agent,
targets: &[String],
@@ -580,8 +580,7 @@ async fn wait_for_runs(
if done.contains_key(&repo)
|| !targets.contains(&repo)
|| before.contains(&oid(&run))
// Still waiting for a slot (t84) or scanning: not finished.
|| matches!(text(&run, "status").as_str(), "queued" | "running")
|| text(&run, "status") == "running"
{
continue;
}
-187
View File
@@ -1,187 +0,0 @@
//! A target's "Verlauf" (#957) through the real API: per scan the CVE
//! alerts found new and gone since the completed scan before it.
//!
//! Runs against a live Mongo (`TEST_MONGODB_URI`) and skips cleanly without
//! one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
mod common;
use chrono::{DateTime, Duration, Utc};
use compliance_core::component_changes::{ComponentChange, ComponentChangeKind};
use compliance_core::models::{CveAlert, CveSource, ScanRun, ScanRunStatus, ScanTrigger};
use mongodb::bson::{doc, oid::ObjectId, Document};
use serde_json::Value;
use common::TestServer;
const TARGET: &str = "665f1c2ab0c4d1e2f3a4b5c7";
async fn mongo_reachable() -> bool {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let Ok(client) = mongodb::Client::with_uri_str(&uri).await else {
return false;
};
client
.database("admin")
.run_command(doc! { "ping": 1 })
.await
.is_ok()
}
/// Store a run of the target that started `start` and ended `end`, with the
/// component changes it recorded.
async fn run(
db: &mongodb::Database,
status: ScanRunStatus,
start: DateTime<Utc>,
end: Option<DateTime<Utc>>,
components: Option<Vec<ComponentChange>>,
) {
let mut run = ScanRun::new(TARGET.into(), ScanTrigger::Scheduled);
run.status = status;
run.started_at = start;
run.completed_at = end;
run.component_changes = components;
db.collection::<ScanRun>("scan_runs")
.insert_one(&run)
.await
.unwrap();
}
/// Store an alert of the target found at `created`, gone at `resolved`.
async fn alert(
db: &mongodb::Database,
cve: &str,
created: DateTime<Utc>,
resolved: Option<DateTime<Utc>>,
) {
let mut a = CveAlert::new(
cve.into(),
TARGET.into(),
"openssl".into(),
"3.0.9".into(),
CveSource::Osv,
);
a.severity = Some("HIGH".into());
a.created_at = created;
a.resolved_at = resolved;
db.collection::<CveAlert>("cve_alerts")
.insert_one(&a)
.await
.unwrap();
}
/// The CVE ids of a change's `side` (`new_cves` or `gone_cves`).
fn cves(change: &Value, side: &str) -> Vec<String> {
change[side]
.as_array()
.unwrap()
.iter()
.map(|c| c["cve"].as_str().unwrap().to_string())
.collect()
}
#[tokio::test]
async fn each_scan_shows_the_cves_it_found_new_and_gone() {
if !mongo_reachable().await {
eprintln!("SKIP scan_changes: no MongoDB reachable");
return;
}
let server = TestServer::start().await;
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db = mongodb::Client::with_uri_str(&uri)
.await
.unwrap()
.database(&server.tenant_db_name());
db.collection::<Document>("onboarded_targets")
.insert_one(doc! { "_id": ObjectId::parse_str(TARGET).unwrap(), "name": "Pumpe", "target_type": "software" })
.await
.unwrap();
// Arrange: three scans, the middle one failed; one CVE from the first
// scan goes in the last, one comes with it.
let t0 = Utc::now() - Duration::days(3);
let hour = |h: i64| t0 + Duration::hours(h);
run(&db, ScanRunStatus::Completed, hour(0), Some(hour(1)), None).await;
run(&db, ScanRunStatus::Failed, hour(24), Some(hour(25)), None).await;
// The last one recorded its components (#974): openssl was updated.
let updated = ComponentChange {
kind: ComponentChangeKind::Updated,
package_manager: "npm".into(),
name: "openssl".into(),
from: Some("3.0.9".into()),
to: Some("3.0.11".into()),
};
run(
&db,
ScanRunStatus::Completed,
hour(48),
Some(hour(49)),
Some(vec![updated]),
)
.await;
alert(&db, "CVE-2026-1001", hour(1), Some(hour(49))).await;
alert(&db, "CVE-2026-1002", hour(1), None).await;
alert(&db, "CVE-2026-1003", hour(49), None).await;
// Act
let resp = server
.get(&format!("/api/v1/targets/{TARGET}/scan-changes"))
.await;
assert_eq!(resp.status(), 200);
let body: Value = resp.json().await.unwrap();
let changes = body["data"].as_array().unwrap();
// Assert: oldest first; the first is the baseline, the failed one
// changes nothing, the last has one new and one gone.
assert_eq!(changes.len(), 3);
assert_eq!(changes[0]["baseline"], true);
assert!(cves(&changes[0], "new_cves").is_empty());
assert_eq!(changes[1]["status"], "failed");
assert!(cves(&changes[1], "new_cves").is_empty());
assert_eq!(cves(&changes[2], "new_cves"), ["CVE-2026-1003"]);
assert_eq!(cves(&changes[2], "gone_cves"), ["CVE-2026-1001"]);
// The update took the gone CVE (at 3.0.9). The new one names 3.0.9 too,
// which the update left, so no change explains it: an advisory row,
// after the change of the same component.
assert!(changes[0].get("components").is_none(), "not recorded");
let rows = changes[2]["components"].as_array().unwrap();
let read: Vec<(&str, &str, u64, u64)> = rows
.iter()
.map(|r| {
(
r["kind"].as_str().unwrap(),
r["name"].as_str().unwrap(),
r["cves_new"].as_u64().unwrap(),
r["cves_gone"].as_u64().unwrap(),
)
})
.collect();
assert_eq!(
read,
[("updated", "openssl", 0, 1), ("advisory", "openssl", 1, 0)]
);
// With a limit the oldest scans drop out, and the window of the first
// shown one starts at the end of the completed scan before it.
let resp = server
.get(&format!("/api/v1/targets/{TARGET}/scan-changes?limit=1"))
.await;
let body: Value = resp.json().await.unwrap();
let changes = body["data"].as_array().unwrap();
assert_eq!(changes.len(), 1);
assert_eq!(changes[0]["baseline"], false);
assert_eq!(cves(&changes[0], "new_cves"), ["CVE-2026-1003"]);
// An unknown target is a 404.
let resp = server
.get("/api/v1/targets/665f1c2ab0c4d1e2f3a4b5ff/scan-changes")
.await;
assert_eq!(resp.status(), 404);
server.cleanup().await;
}
-250
View File
@@ -1,250 +0,0 @@
//! A scan request shows at once as a run waiting for a slot (t84): the run is
//! recorded `queued` before the scan gets one of the agent's slots, a person's
//! request takes over a waiting webhook scan without leaving its queued run
//! behind, a request covered by the waiting scan leaves none, and the run
//! leaves `queued` once its scan had its turn. Runs against a live Mongo
//! (`TEST_MONGODB_URI`) and skips cleanly without one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
mod common;
use std::sync::Arc;
use std::time::Duration;
use futures_util::TryStreamExt;
use mongodb::bson::doc;
use compliance_agent::agent::ComplianceAgent;
use compliance_agent::database::Database;
use compliance_agent::scan_gate::Priority;
use compliance_core::models::{ScanRun, ScanRunStatus, ScanTrigger};
use common::dev_config;
const TENANT: &str = "scanqueue";
async fn runs(db: &Database, target_id: &str) -> Vec<ScanRun> {
db.scan_runs()
.find(doc! { "repo_id": target_id })
.await
.unwrap()
.try_collect()
.await
.unwrap()
}
/// Wait until the runs of `target_id` satisfy `done`, and return them.
async fn until(db: &Database, target_id: &str, done: impl Fn(&[ScanRun]) -> bool) -> Vec<ScanRun> {
for _ in 0..200 {
let found = runs(db, target_id).await;
if done(&found) {
return found;
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
panic!(
"runs never reached the expected state: {:?}",
runs(db, target_id).await
);
}
#[tokio::test]
async fn a_request_shows_as_queued_until_its_scan_has_a_slot() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db_name = format!("sq_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]);
let Ok(pool) = compliance_agent::database::DatabasePool::connect(&uri, &db_name).await else {
eprintln!("SKIP scan_queue: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
let mut config = dev_config(uri, db_name);
config.scan_concurrency = 1;
let agent = Arc::new(ComplianceAgent::new(config, pool.clone()));
// No such target, so its scan ends at once when it gets the slot.
let target = mongodb::bson::oid::ObjectId::new().to_hex();
// Arrange: another scan has the only slot.
let busy = agent.scan_gate.slot(Priority::Background).await.unwrap();
// Act 1: a push asks for a scan; it waits, recorded as queued.
let holder = tokio::spawn({
let (agent, target) = (agent.clone(), target.clone());
async move {
agent
.run_target_scan(TENANT, &target, ScanTrigger::Webhook)
.await
}
});
let queued = until(&db, &target, |r| r.len() == 1).await;
assert_eq!(queued[0].status, ScanRunStatus::Queued);
assert_eq!(queued[0].trigger, ScanTrigger::Webhook);
assert!(queued[0].queued_at.is_some());
// Act 2: a person asks while it waits: theirs takes its place, and only
// their queued run is left. Another push is covered and leaves none.
agent
.run_target_scan(TENANT, &target, ScanTrigger::Manual)
.await
.unwrap();
agent
.run_target_scan(TENANT, &target, ScanTrigger::Webhook)
.await
.unwrap();
let waiting = runs(&db, &target).await;
assert_eq!(waiting.len(), 1, "one queued run: {waiting:?}");
assert_eq!(waiting[0].status, ScanRunStatus::Queued);
assert_eq!(waiting[0].trigger, ScanTrigger::Manual);
// Act 3: the slot frees; the person's scan has its turn.
drop(busy);
assert!(holder.await.unwrap().is_err(), "the unknown target fails");
// Assert: the same run, no longer queued.
let done = runs(&db, &target).await;
assert_eq!(done.len(), 1);
assert_eq!(done[0].id, waiting[0].id);
assert_eq!(done[0].status, ScanRunStatus::Failed);
assert!(done[0].completed_at.is_some());
pool.drop_tenant(TENANT).await.ok();
}
#[tokio::test]
async fn the_scan_runs_on_the_run_that_waited() {
use compliance_core::models::{OnboardedTarget, TargetType};
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db_name = format!("sq_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]);
let Ok(pool) = compliance_agent::database::DatabasePool::connect(&uri, &db_name).await else {
eprintln!("SKIP scan_queue: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
let mut config = dev_config(uri, db_name);
config.scan_concurrency = 1;
let agent = Arc::new(ComplianceAgent::new(config, pool.clone()));
// A target with nothing attached yet: its scan has nothing to read.
let target = db
.onboarded_targets()
.insert_one(OnboardedTarget::new(
"empty".into(),
TargetType::BackendService,
))
.await
.unwrap()
.inserted_id
.as_object_id()
.unwrap()
.to_hex();
let busy = agent.scan_gate.slot(Priority::Background).await.unwrap();
let holder = tokio::spawn({
let (agent, target) = (agent.clone(), target.clone());
async move {
agent
.run_target_scan(TENANT, &target, ScanTrigger::Manual)
.await
}
});
let queued = until(&db, &target, |r| r.len() == 1).await;
assert_eq!(queued[0].status, ScanRunStatus::Queued);
tokio::time::sleep(Duration::from_millis(20)).await;
drop(busy);
holder.await.unwrap().ok();
// The scan used the queued run: one run, started after it was requested.
let done = runs(&db, &target).await;
assert_eq!(done.len(), 1, "{done:?}");
assert_eq!(done[0].id, queued[0].id);
assert_ne!(done[0].status, ScanRunStatus::Queued);
assert!(done[0].started_at > done[0].queued_at.unwrap());
pool.drop_tenant(TENANT).await.ok();
}
/// The run of `target`'s scan by `trigger`, started while another scan has the
/// only slot; with `takes_over`, a webhook scan waits first and the person's
/// request takes it over.
async fn scan_with_slot_busy(
agent: &Arc<ComplianceAgent>,
db: &Database,
target: &str,
takes_over: bool,
) -> ScanRun {
let busy = agent.scan_gate.slot(Priority::Background).await.unwrap();
let first = if takes_over {
ScanTrigger::Webhook
} else {
ScanTrigger::Manual
};
let holder = tokio::spawn({
let (agent, target) = (agent.clone(), target.to_string());
async move { agent.run_target_scan(TENANT, &target, first).await }
});
until(db, target, |r| r.len() == 1).await;
if takes_over {
agent
.run_target_scan(TENANT, target, ScanTrigger::Manual)
.await
.unwrap();
}
drop(busy);
holder.await.unwrap().ok();
let mut done = runs(db, target).await;
assert_eq!(done.len(), 1, "{done:?}");
done.remove(0)
}
#[tokio::test]
async fn a_taken_over_scan_is_charged_as_the_scan_it_replaces() {
use compliance_core::models::{OnboardedTarget, ScanAttribution, TargetType};
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db_name = format!("sq_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]);
let Ok(pool) = compliance_agent::database::DatabasePool::connect(&uri, &db_name).await else {
eprintln!("SKIP scan_queue: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
let mut config = dev_config(uri, db_name);
config.scan_concurrency = 1;
let agent = Arc::new(ComplianceAgent::new(config, pool.clone()));
let new_target = || {
let db = db.clone();
async move {
let target = OnboardedTarget::new("t".into(), TargetType::BackendService);
db.onboarded_targets()
.insert_one(target)
.await
.unwrap()
.inserted_id
.as_object_id()
.unwrap()
.to_hex()
}
};
// A person's request that took over a waiting webhook scan of an
// included target: their priority and attribution, but not counted, as
// the webhook scan would not have been.
let included = new_target().await;
let run = scan_with_slot_busy(&agent, &db, &included, true).await;
assert_eq!(run.trigger, ScanTrigger::Manual);
assert_eq!(run.attribution, Some(ScanAttribution::Request));
assert_eq!(run.charged_as, Some(ScanTrigger::Webhook));
assert!(!run.chargeable, "it would have run anyway: {run:?}");
// A person's own scan, not taking any over, counts as their request.
let asked = new_target().await;
let run = scan_with_slot_busy(&agent, &db, &asked, false).await;
assert_eq!(run.attribution, Some(ScanAttribution::Request));
assert_eq!(run.charged_as, None);
assert!(run.chargeable);
pool.drop_tenant(TENANT).await.ok();
}
-68
View File
@@ -80,71 +80,3 @@ async fn the_oldest_targets_are_included_and_an_extra_one_moves_up() {
pool.drop_tenant(TENANT).await.ok();
}
#[tokio::test]
async fn a_swap_moves_both_and_holds_the_one_swapped_in_until_month_end() {
use compliance_agent::metering::swap;
use compliance_core::models::SwapRefusal;
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!("swap_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP target_billing swap: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
// Arrange: three targets on a plan with two included: the newest is extra.
let mut ids = Vec::new();
for days in [3, 2, 1] {
let mut target = OnboardedTarget::new(format!("t{days}"), TargetType::FirmwareRtos);
target.created_at = Utc::now() - Duration::days(days);
let res = db.onboarded_targets().insert_one(&target).await.unwrap();
ids.push(res.inserted_id.as_object_id().unwrap());
}
let (oldest, middle, newest) = (ids[0], ids[1], ids[2]);
assign_billing(&db, Some(2)).await.unwrap();
let nov6 = chrono::TimeZone::with_ymd_and_hms(&Utc, 2026, 11, 6, 9, 0, 0)
.single()
.unwrap();
// Act: swap the newest in for the oldest.
let swapped = swap(&db, newest, oldest, true, nov6).await.unwrap();
assign_billing(&db, Some(2)).await.unwrap();
// Assert: they changed places; the count of extra targets is the same.
assert_eq!(swapped, Some(Ok(())));
assert_eq!(billing(&db, newest).await, TargetBilling::Included);
assert_eq!(billing(&db, oldest).await, TargetBilling::Extra);
assert_eq!(billing(&db, middle).await, TargetBilling::Included);
// The one swapped in stays included this month; another may go out.
assert_eq!(
swap(&db, oldest, newest, true, nov6).await.unwrap(),
Some(Err(SwapRefusal::Locked))
);
assert_eq!(
swap(&db, oldest, middle, true, nov6).await.unwrap(),
Some(Ok(()))
);
assign_billing(&db, Some(2)).await.unwrap();
assert_eq!(billing(&db, middle).await, TargetBilling::Extra);
// From December, the target swapped in on 6 Nov may go out again.
let dec1 = chrono::TimeZone::with_ymd_and_hms(&Utc, 2026, 12, 1, 9, 0, 0)
.single()
.unwrap();
assert_eq!(
swap(&db, middle, newest, true, dec1).await.unwrap(),
Some(Ok(()))
);
assert_eq!(
swap(&db, middle, ObjectId::new(), true, dec1)
.await
.unwrap(),
None,
"an unknown target"
);
pool.drop_tenant(TENANT).await.ok();
}
+1 -3
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-core"
version = "0.4.16"
version = "0.4.6"
edition = "2021"
[lints]
@@ -45,8 +45,6 @@ serde = { workspace = true }
serde_json = { workspace = true }
chrono = { workspace = true }
thiserror = { workspace = true }
# Decoding source files: BOM sniffing, UTF-16, Windows-1252
encoding_rs = { workspace = true }
sha2 = { workspace = true }
hex = { workspace = true }
uuid = { workspace = true }
Loaded 100 of 236 files, more files were not shown because too many files have changed in this diff. Show more