Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
deda6d4867 | ||
|
|
783e075891 | ||
|
|
ea1b48dd37 | ||
|
|
867453b63e | ||
|
|
ca8a662b60 | ||
|
|
fc72b6a1f4 | ||
|
|
aa022b0d0f | ||
|
|
5ea49661d0 | ||
|
|
f5697ff21d | ||
|
|
31886d226c | ||
|
|
692840df59 | ||
|
|
f5ed826b99 | ||
|
|
5017c6286e | ||
|
|
ad0fde9106 | ||
|
|
d6986d23b1 | ||
|
|
7b7731f46d | ||
|
|
03dd8f8df4 | ||
|
|
f1123e1adb | ||
|
|
6e97a0bf4c | ||
|
|
cd90a26558 | ||
|
|
32cd11bb2f | ||
|
|
88682c6c6a | ||
|
|
f57a1020db | ||
|
|
29e38c8b80 | ||
|
|
ef9c578948 | ||
|
|
589c3b440b | ||
|
|
b9acabb6ba | ||
|
|
d274c68ecb | ||
|
|
29d3c91f5a | ||
|
|
5a11a3b602 | ||
|
|
ca66b9a7b1 | ||
|
|
b420b28ea8 | ||
|
|
d3c8eee393 | ||
|
|
c8deabd4d9 | ||
|
|
c1a70b025c | ||
|
|
37888af374 | ||
|
|
1569100721 | ||
|
|
d9fcc75792 | ||
|
|
a2699a3ec3 | ||
|
|
3bdaf28737 | ||
|
|
168cbe98f8 | ||
|
|
9f2e78c6c4 | ||
|
|
9ce3b868bb | ||
|
|
a7355ffdc8 | ||
|
|
ce786b716b | ||
|
|
c28f9e186b | ||
|
|
4480e8b509 | ||
|
|
aa1c9b5d2b | ||
|
|
b2b9fd2a02 | ||
|
|
8d839ed5ad | ||
|
|
b079cf9267 | ||
|
|
2157ae2d42 | ||
|
|
13d09dc830 | ||
|
|
01a24f4556 | ||
|
|
3d7deee4a8 | ||
|
|
360c905894 | ||
|
|
b531227b45 | ||
|
|
919cac01e9 | ||
|
|
7f5ddf69fc | ||
|
|
c2fbffd2c6 | ||
|
|
e637964c02 | ||
|
|
2ca87d1920 | ||
|
|
60b2eeda5f | ||
|
|
e911e75c09 | ||
|
|
c16e91f981 | ||
|
|
b645769f67 | ||
|
|
533d5f35b5 | ||
|
|
8ede373353 | ||
|
|
e01d2146e9 | ||
|
|
ac95126af2 | ||
|
|
5b0bf08478 | ||
|
|
93b98965b3 | ||
|
|
2523ecb018 | ||
|
|
7d73893485 | ||
|
|
3300bb1851 | ||
|
|
70be25650b | ||
|
|
34243b208d | ||
|
|
9d4e46c34f | ||
|
|
0cbabb73fd | ||
|
|
1135b65b9e | ||
|
|
330d492578 | ||
|
|
794a3aa525 | ||
|
|
24001850ec | ||
|
|
fad23c20a9 | ||
|
|
c739f1b7e5 | ||
|
|
b247c5b359 | ||
|
|
4ded72ce32 | ||
|
|
f77e78c5d2 |
No files matched your search
+5
-19
@@ -1,23 +1,9 @@
|
||||
[advisories]
|
||||
ignore = [
|
||||
# hickory-proto 0.25.x pulled in transitively via mongodb → hickory-resolver.
|
||||
# MongoDB 3.x has not yet released with hickory-resolver 0.26.x, so we cannot
|
||||
# upgrade past this without a mongodb release. Both are DNS-layer DoS vectors
|
||||
# requiring a MITM/controlled DNS server against MongoDB's hostname resolution —
|
||||
# not a realistic attack surface here. Revisit when mongodb bumps hickory.
|
||||
# hickory-proto, pulled in transitively via mongodb → hickory-resolver
|
||||
# (0.26.3 since mongodb 3.10, which fixed RUSTSEC-2026-0119). The NSEC3 loop
|
||||
# is in DNSSEC validation, which the driver does not use, and needs a
|
||||
# MITM/controlled DNS server against MongoDB's hostname resolution — not a
|
||||
# realistic attack surface here. Revisit when hickory ships a fix.
|
||||
"RUSTSEC-2026-0118", # NSEC3 loop, no fix available upstream
|
||||
"RUSTSEC-2026-0119", # O(n²) name compression, fixed in hickory-proto >=0.26.1
|
||||
|
||||
# rmcp 0.16.0 — DNS rebinding in Streamable HTTP server transport (missing
|
||||
# Host header validation). Patched in rmcp >= 1.4.0, which is a major API
|
||||
# version jump from our pin; rmcp shipped 0.x → 1.x → 2.x in three months
|
||||
# and the migration touches every tool handler + the auth middleware we
|
||||
# just landed in #92. Threat model in our deployment: the MCP server is
|
||||
# exposed at a public hostname (comp-mcp-dev.breakpilot.com) behind orca's
|
||||
# TLS-terminating ingress with per-tenant bearer auth — the attack model
|
||||
# (browser DNS-rebinding into localhost MCP server) doesn't directly apply.
|
||||
# Defense-in-depth Host-header check is still a worthwhile follow-up.
|
||||
# FOLLOW-UP: bump rmcp to 2.x in a dedicated PR (M7.3 follow-up, sized
|
||||
# multi-hour due to API surface change).
|
||||
"RUSTSEC-2026-0189",
|
||||
]
|
||||
+10
-1
@@ -5,7 +5,11 @@ MONGODB_DATABASE=compliance_scanner
|
||||
# LiteLLM
|
||||
LITELLM_URL=http://localhost:4000
|
||||
LITELLM_API_KEY=
|
||||
LITELLM_MODEL=gpt-4o
|
||||
LITELLM_MODEL=Qwen3.8-27B
|
||||
LITELLM_EMBED_MODEL=bge-multilingual-gemma2
|
||||
# Seconds one LLM call may take in total, the gateway's queue included. Keep it
|
||||
# at the gateway's request timeout (LiteLLM: 600).
|
||||
LLM_TIMEOUT_SECS=600
|
||||
|
||||
# GitHub
|
||||
GITHUB_TOKEN=
|
||||
@@ -142,6 +146,11 @@ DASHBOARD_SESSION_KEY=
|
||||
|
||||
# MCP Server
|
||||
MCP_ENDPOINT_URL=http://localhost:8090
|
||||
# The hostnames (or host:port) clients reach the MCP server at, comma-separated:
|
||||
# the public hostname behind the ingress and the in-network name the dashboard
|
||||
# uses. Requests with another Host header are refused (DNS rebinding
|
||||
# protection). Unset, the Host header is not checked and a warning is logged.
|
||||
# MCP_ALLOWED_HOSTS=pruefwerk-stage.breakpilot.com,compliance-mcp:8090
|
||||
# Absolute health URL for the default MCP server card. Set it where an ingress
|
||||
# routes /mcp/* to a server that serves /health at its own root (staging:
|
||||
# https://pruefwerk-stage.breakpilot.com/mcp/health). Derived from
|
||||
|
||||
+125
-6
@@ -16,6 +16,12 @@ env:
|
||||
COSIGN_PASSWORD: ${{ secrets.COSIGN_PASSWORD }}
|
||||
CARGO_TERM_COLOR: always
|
||||
RUSTFLAGS: "-D warnings"
|
||||
# Job containers on the OVH runners get --cpus=2 --memory=3g, but cargo sees
|
||||
# the host's 8 cores and ran up to 8 rustc with full debug info: the dashboard
|
||||
# build was OOM-killed (signal 9). Two jobs to match the CPUs, and line tables
|
||||
# only (backtraces keep file:line, no full variable info).
|
||||
CARGO_BUILD_JOBS: "2"
|
||||
CARGO_PROFILE_DEV_DEBUG: line-tables-only
|
||||
# Compile cache: sccache -> Hetzner S3 (breakpilot-sccache), runner-independent
|
||||
# and persistent across CI runs (own key prefix). Reuses the shared cluster S3
|
||||
# creds (same bucket as werkpilot). Requires repo secrets HETZNER_S3_ACCESS_KEY
|
||||
@@ -107,6 +113,15 @@ jobs:
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
# The repository's Python scripts (the EOL table check, the CODESYS
|
||||
# export script customers download) have offline tests.
|
||||
- name: Script tests
|
||||
run: |
|
||||
command -v python3 >/dev/null || { apt-get update -qq && apt-get install -y -qq --no-install-recommends python3; }
|
||||
python3 -B -I -m unittest discover -s scripts -p "test_*.py"
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
# Clippy (compiles once, sccache reuses across feature sets). --all-targets
|
||||
# lints test code too; tests may unwrap (clippy.toml), production may not.
|
||||
- name: Clippy (core)
|
||||
@@ -123,6 +138,8 @@ 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
|
||||
|
||||
# Security audit
|
||||
- name: Security Audit
|
||||
@@ -131,20 +148,115 @@ jobs:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
# Tests (reuses compilation artifacts from clippy)
|
||||
- name: Tests (core + agent + werkbank-exec + control-map)
|
||||
run: cargo test -p compliance-core -p compliance-agent -p werkbank-exec -p control-map --lib
|
||||
- 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
|
||||
# compliance-core's integration tests need no services.
|
||||
- name: Tests (core integration)
|
||||
run: cargo test -p compliance-core --tests
|
||||
# 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.
|
||||
- name: Tests (dashboard server)
|
||||
env:
|
||||
CARGO_BUILD_JOBS: "1"
|
||||
run: cargo test -p compliance-dashboard --features server --no-default-features
|
||||
- name: Tests (dashboard web)
|
||||
env:
|
||||
CARGO_BUILD_JOBS: "1"
|
||||
run: cargo test -p compliance-dashboard --features web --no-default-features
|
||||
|
||||
- name: Show sccache stats
|
||||
run: sccache --show-stats
|
||||
if: always()
|
||||
|
||||
# compliance-agent's integration tests (compliance-agent/tests) need MongoDB.
|
||||
# Every test opens its own database, so WiredTiger keeps a file open per
|
||||
# collection and index: with the containers' default of 1024 open files
|
||||
# mongod aborts mid-run ("Too many open files"), which is what took the
|
||||
# mongo service down in #584. mongod runs as a process in this job
|
||||
# container with a raised limit, and its log is printed when a test fails.
|
||||
agent-integration:
|
||||
name: Agent integration
|
||||
if: github.event_name == 'pull_request'
|
||||
runs-on: docker
|
||||
container:
|
||||
image: rust:1.94-bookworm
|
||||
env:
|
||||
MONGODB_VERSION: "7.0.45"
|
||||
MONGODB_SHA256: e97e79211a7106a065d9119039ead401f32cfbbfa1681977fdeba4b4a4bf1f63
|
||||
steps:
|
||||
- name: Checkout
|
||||
run: |
|
||||
git init
|
||||
git remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git"
|
||||
git fetch --depth=1 origin "${GITHUB_SHA}"
|
||||
git checkout FETCH_HEAD
|
||||
- name: Use Kellnr crates.io mirror
|
||||
run: |
|
||||
: "${CARGO_HOME:=/usr/local/cargo}"
|
||||
mkdir -p "$CARGO_HOME"
|
||||
{
|
||||
echo '[source.crates-io]'
|
||||
echo 'replace-with = "kellnr"'
|
||||
echo '[registries.kellnr]'
|
||||
echo 'index = "sparse+https://crates.breakpilot.com/api/v1/cratesio/"'
|
||||
} >> "$CARGO_HOME/config.toml"
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
- name: Install sccache
|
||||
run: |
|
||||
curl -fsSL https://github.com/mozilla/sccache/releases/download/v0.10.0/sccache-v0.10.0-x86_64-unknown-linux-musl.tar.gz \
|
||||
| tar xz --strip-components=1 -C /usr/local/bin/ sccache-v0.10.0-x86_64-unknown-linux-musl/sccache
|
||||
chmod +x /usr/local/bin/sccache
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
- name: Configure git auth for the private firmwerk dependency
|
||||
run: |
|
||||
git config --global \
|
||||
url."https://platform-ci:${{ secrets.PLATFORM_CI_TOKEN }}@git.breakpilot.com/".insteadOf \
|
||||
"ssh://git@git.breakpilot.com:22222/"
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
# Build first, so compiling and mongod never share the job's 3 GB.
|
||||
- name: Build the agent integration tests
|
||||
run: cargo test -p compliance-agent --test '*' --no-run
|
||||
|
||||
# The official Debian 12 build, checked against its sha256; a small
|
||||
# WiredTiger cache, no auth (the job container is its only client).
|
||||
- name: Start MongoDB
|
||||
run: |
|
||||
T="mongodb-linux-x86_64-debian12-${MONGODB_VERSION}"
|
||||
curl -fsSL "https://fastdl.mongodb.org/linux/${T}.tgz" -o /tmp/mongodb.tgz
|
||||
echo "${MONGODB_SHA256} /tmp/mongodb.tgz" | sha256sum -c -
|
||||
tar -xzf /tmp/mongodb.tgz -C /opt
|
||||
mkdir -p /tmp/mongo-db
|
||||
ulimit -n 64000 2>/dev/null || ulimit -n "$(ulimit -Hn)"
|
||||
echo "open files: soft $(ulimit -Sn), hard $(ulimit -Hn)"
|
||||
"/opt/${T}/bin/mongod" --dbpath /tmp/mongo-db --bind_ip 127.0.0.1 --port 27017 \
|
||||
--wiredTigerCacheSizeGB 0.25 --fork --logpath /tmp/mongod.log
|
||||
for i in $(seq 1 30); do
|
||||
if (exec 3<>/dev/tcp/127.0.0.1/27017) 2>/dev/null; then echo "mongod is up"; exit 0; fi
|
||||
sleep 1
|
||||
done
|
||||
echo "mongod did not start"; tail -50 /tmp/mongod.log; exit 1
|
||||
shell: bash
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
- name: Tests (agent integration)
|
||||
run: cargo test -p compliance-agent --test '*'
|
||||
env:
|
||||
TEST_MONGODB_URI: mongodb://127.0.0.1:27017/
|
||||
|
||||
- name: MongoDB log
|
||||
if: failure()
|
||||
run: |
|
||||
pgrep -a mongod || echo "mongod is not running"
|
||||
tail -100 /tmp/mongod.log || true
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Stage 2: Deploy (only on main, after checks pass)
|
||||
# Each service only deploys when its relevant files changed.
|
||||
@@ -238,7 +350,7 @@ jobs:
|
||||
echo "version: ${PRUEFWERK_VERSION:-crate} commit: ${GITHUB_SHA}"
|
||||
IMAGE=repo.breakpilot.com/pruefwerk/compliance-agent
|
||||
echo "$REGISTRY_PASSWORD" | docker login repo.breakpilot.com -u "$REGISTRY_USERNAME" --password-stdin
|
||||
DOCKER_BUILDKIT=1 docker build --secret id=git_token,env=PLATFORM_CI_TOKEN \
|
||||
DOCKER_BUILDKIT=1 docker build --pull --secret id=git_token,env=PLATFORM_CI_TOKEN \
|
||||
--build-arg PRUEFWERK_VERSION="${PRUEFWERK_VERSION}" \
|
||||
--build-arg PRUEFWERK_COMMIT="${GITHUB_SHA}" \
|
||||
-f Dockerfile.agent -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
|
||||
@@ -271,9 +383,16 @@ jobs:
|
||||
apk add --no-cache git curl openssl
|
||||
git init && git remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git"
|
||||
git fetch --depth=1 origin "${GITHUB_SHA}" && git checkout FETCH_HEAD
|
||||
# service.version in telemetry: the latest release tag without its v,
|
||||
# as for the agent. No tag → empty, and the crate version is used.
|
||||
git fetch --quiet --unshallow --tags origin || true
|
||||
TAG=$(git describe --tags --abbrev=0 --match 'v[0-9]*' 2>/dev/null || true)
|
||||
PRUEFWERK_VERSION="${TAG#v}"
|
||||
echo "version: ${PRUEFWERK_VERSION:-crate}"
|
||||
IMAGE=repo.breakpilot.com/pruefwerk/compliance-dashboard
|
||||
echo "$REGISTRY_PASSWORD" | docker login repo.breakpilot.com -u "$REGISTRY_USERNAME" --password-stdin
|
||||
DOCKER_BUILDKIT=1 docker build --secret id=git_token,env=PLATFORM_CI_TOKEN \
|
||||
DOCKER_BUILDKIT=1 docker build --pull --secret id=git_token,env=PLATFORM_CI_TOKEN \
|
||||
--build-arg PRUEFWERK_VERSION="${PRUEFWERK_VERSION}" \
|
||||
-f Dockerfile.dashboard -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
|
||||
docker push "$IMAGE:latest" && docker push "$IMAGE:${GITHUB_SHA}"
|
||||
{ command -v cosign >/dev/null 2>&1 || curl -sSfLo /usr/local/bin/cosign https://github.com/sigstore/cosign/releases/download/v2.4.3/cosign-linux-amd64 || wget -qO /usr/local/bin/cosign https://github.com/sigstore/cosign/releases/download/v2.4.3/cosign-linux-amd64; } || echo "::warning::cosign fetch failed"
|
||||
@@ -304,7 +423,7 @@ jobs:
|
||||
git fetch --depth=1 origin "${GITHUB_SHA}" && git checkout FETCH_HEAD
|
||||
IMAGE=repo.breakpilot.com/pruefwerk/compliance-docs
|
||||
echo "$REGISTRY_PASSWORD" | docker login repo.breakpilot.com -u "$REGISTRY_USERNAME" --password-stdin
|
||||
docker build -f Dockerfile.docs -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
|
||||
docker build --pull -f Dockerfile.docs -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
|
||||
docker push "$IMAGE:latest" && docker push "$IMAGE:${GITHUB_SHA}"
|
||||
{ command -v cosign >/dev/null 2>&1 || curl -sSfLo /usr/local/bin/cosign https://github.com/sigstore/cosign/releases/download/v2.4.3/cosign-linux-amd64 || wget -qO /usr/local/bin/cosign https://github.com/sigstore/cosign/releases/download/v2.4.3/cosign-linux-amd64; } || echo "::warning::cosign fetch failed"
|
||||
chmod +x /usr/local/bin/cosign 2>/dev/null || true
|
||||
@@ -336,7 +455,7 @@ jobs:
|
||||
git fetch --depth=1 origin "${GITHUB_SHA}" && git checkout FETCH_HEAD
|
||||
IMAGE=repo.breakpilot.com/pruefwerk/compliance-mcp
|
||||
echo "$REGISTRY_PASSWORD" | docker login repo.breakpilot.com -u "$REGISTRY_USERNAME" --password-stdin
|
||||
DOCKER_BUILDKIT=1 docker build --secret id=git_token,env=PLATFORM_CI_TOKEN \
|
||||
DOCKER_BUILDKIT=1 docker build --pull --secret id=git_token,env=PLATFORM_CI_TOKEN \
|
||||
-f Dockerfile.mcp -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
|
||||
docker push "$IMAGE:latest" && docker push "$IMAGE:${GITHUB_SHA}"
|
||||
{ command -v cosign >/dev/null 2>&1 || curl -sSfLo /usr/local/bin/cosign https://github.com/sigstore/cosign/releases/download/v2.4.3/cosign-linux-amd64 || wget -qO /usr/local/bin/cosign https://github.com/sigstore/cosign/releases/download/v2.4.3/cosign-linux-amd64; } || echo "::warning::cosign fetch failed"
|
||||
|
||||
@@ -51,25 +51,6 @@ 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
|
||||
# Optional. Without an LLM the control judge stamps no control refs,
|
||||
# which the report lists as advisory; it never fails the run.
|
||||
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 }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
run: |
|
||||
@@ -144,10 +125,59 @@ 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://agent:3001/api/v1/health && exit 0
|
||||
curl -fsS http://localhost:3001/api/v1/health && exit 0
|
||||
sleep 2
|
||||
done
|
||||
echo "agent did not become healthy" >&2
|
||||
@@ -158,13 +188,20 @@ jobs:
|
||||
- name: Scan the corpus and compare with the baselines
|
||||
run: cargo test -p compliance-agent --test nightly -- --nocapture
|
||||
env:
|
||||
NIGHTLY_AGENT_URL: http://agent:3001
|
||||
NIGHTLY_AGENT_URL: http://localhost: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()
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# Made-up secrets in Prüfwerk's own tests, found by the secret scanner in the
|
||||
# git history (commit:file:rule:line, as gitleaks fingerprints them). Neither is
|
||||
# a real credential; the history keeps them, so they are listed here.
|
||||
#
|
||||
# A Firebase-shaped key in the test that the real scanner still finds Firebase
|
||||
# keys (compliance-agent/src/pipeline/gitleaks.rs).
|
||||
6c9756bebf599eb16112d693c769cd752292d6a9:compliance-agent/src/pipeline/gitleaks.rs:gcp-api-key:278
|
||||
d42b429273668bd285440596fd78e564d34b01ef:compliance-agent/src/pipeline/gitleaks.rs:gcp-api-key:278
|
||||
# The throwaway MongoDB root password of a CI test container.
|
||||
3ef5c28a97f169ed03009f70a9a20a7c9095f0b2:.gitea/workflows/ci.yml:generic-password:170
|
||||
5424074d26552882c6529c2dd9d309b9cc37376a:.gitea/workflows/ci.yml:generic-password:72
|
||||
Generated
+733
-390
File diff suppressed because it is too large.
Load diff
+3
-1
@@ -28,12 +28,14 @@ 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"] }
|
||||
secrecy = { version = "0.10", features = ["serde"] }
|
||||
regex = "1"
|
||||
zip = { version = "2", features = ["aes-crypto", "deflate"] }
|
||||
zip = { version = "9", features = ["aes-crypto", "deflate"] }
|
||||
# Uploaded tar and tar.gz source archives (ingest).
|
||||
tar = "0.4"
|
||||
flate2 = "1"
|
||||
|
||||
+5
-1
@@ -11,7 +11,7 @@ ARG BETTERLEAKS_SHA256=f8b185a39ffcece2a1ca82bf3a4e7435cd81963ffd16b7a9128daf75f
|
||||
# in the release's checksums.txt.
|
||||
ARG SBOMQS_VERSION=2.1.2
|
||||
ARG SBOMQS_SHA256=451c800019c81059f86eac2c1344c57572b3436e7e0ffeaa076459d195a39ab8
|
||||
ARG SEMGREP_VERSION=1.177.0
|
||||
ARG SEMGREP_VERSION=1.179.0
|
||||
ARG RUFF_VERSION=0.16.8
|
||||
# mobsfscan pins an older semgrep; it is installed without its dependencies so
|
||||
# it runs on the semgrep above, and its other dependencies are pinned here.
|
||||
@@ -80,6 +80,10 @@ RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
ca-certificates libssl3 git curl python3 python3-pip npm cppcheck \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
# eMudhra (Mozilla bug 2083449, Oct 2026): fail the build if the image still
|
||||
# trusts the compromised root. Also keeps a cached layer with the old store
|
||||
# from being reused.
|
||||
RUN test ! -e /usr/share/ca-certificates/mozilla/emSign_ECC_Root_CA_-_G3.crt
|
||||
|
||||
# Cargo resolves Rust lockfiles and metadata for the SBOM stage. Installed
|
||||
# system-wide so the unprivileged user can run it; its caches go to the user's
|
||||
|
||||
@@ -5,6 +5,9 @@ RUN cargo install dioxus-cli --version 0.7.3 --locked
|
||||
# Legal pages linked from the sidebar; the defaults are breakpilot.com's.
|
||||
ARG IMPRINT_URL=https://breakpilot.com/impressum
|
||||
ARG PRIVACY_URL=https://breakpilot.com/datenschutz
|
||||
# The release telemetry reports as service.version (CI passes the latest
|
||||
# release tag); empty falls back to the crate version.
|
||||
ARG PRUEFWERK_VERSION=
|
||||
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
@@ -27,6 +30,10 @@ RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates libssl3 curl \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& useradd --uid 10001 --user-group --no-create-home --shell /usr/sbin/nologin app
|
||||
# eMudhra (Mozilla bug 2083449, Oct 2026): fail the build if the image still
|
||||
# trusts the compromised root. Also keeps a cached layer with the old store
|
||||
# from being reused.
|
||||
RUN test ! -e /usr/share/ca-certificates/mozilla/emSign_ECC_Root_CA_-_G3.crt
|
||||
|
||||
WORKDIR /app
|
||||
COPY --from=builder /app/target/dx/compliance-dashboard/release/web/compliance-dashboard /app/compliance-dashboard
|
||||
|
||||
@@ -8,6 +8,8 @@ COPY docs/ .
|
||||
RUN npm run build
|
||||
|
||||
FROM nginx:alpine
|
||||
# Patched Alpine packages (the nginx base lags behind, e.g. brotli in Oct 2026).
|
||||
RUN apk upgrade --no-cache
|
||||
RUN rm /etc/nginx/conf.d/default.conf
|
||||
COPY docs/nginx.conf /etc/nginx/conf.d/default.conf
|
||||
# base is /docs/ (see docs/.vitepress/config.mts) — the site lives under /docs/
|
||||
|
||||
@@ -19,6 +19,10 @@ RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates libssl3 curl \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& useradd --uid 10001 --user-group --no-create-home --shell /usr/sbin/nologin app
|
||||
# eMudhra (Mozilla bug 2083449, Oct 2026): fail the build if the image still
|
||||
# trusts the compromised root. Also keeps a cached layer with the old store
|
||||
# from being reused.
|
||||
RUN test ! -e /usr/share/ca-certificates/mozilla/emSign_ECC_Root_CA_-_G3.crt
|
||||
|
||||
COPY --from=builder /app/target/release/compliance-mcp /usr/local/bin/compliance-mcp
|
||||
|
||||
|
||||
@@ -176,6 +176,8 @@ 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 |
|
||||
@@ -193,7 +195,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 |
|
||||
| `GET` | `/api/v1/issues` | List cross-tracker issues (search `q`, `status=open\|closed`, `repo_id`) |
|
||||
| `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,6 +1,6 @@
|
||||
[package]
|
||||
name = "compliance-agent"
|
||||
version = "0.4.6"
|
||||
version = "0.4.15"
|
||||
edition = "2021"
|
||||
|
||||
[lints]
|
||||
@@ -33,6 +33,8 @@ tokio = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
# Calendar days and months of metering in Europe/Berlin (t72).
|
||||
chrono-tz = "0.10"
|
||||
mongodb = { workspace = true }
|
||||
reqwest = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
@@ -62,6 +64,8 @@ urlencoding = "2"
|
||||
futures-util = "0.3"
|
||||
zip = { workspace = true }
|
||||
tar = { workspace = true }
|
||||
# Yocto image SPDX archives (`*.spdx.tar.zst`); already in the tree via zip.
|
||||
zstd = "0.14"
|
||||
flate2 = { workspace = true }
|
||||
tokio-tungstenite = { version = "0.26", features = ["rustls-tls-webpki-roots"] }
|
||||
dashmap = { workspace = true }
|
||||
|
||||
+254
-35
@@ -10,9 +10,15 @@ use crate::database::DatabasePool;
|
||||
use crate::llm::LlmClient;
|
||||
use crate::pipeline::orchestrator::PipelineOrchestrator;
|
||||
use crate::registry::RegistryClient;
|
||||
use crate::scan_gate::{Admission, HeldTarget, ScanGate};
|
||||
use crate::scan_gate::{Admission, HeldTarget, Job, Priority, ScanGate};
|
||||
use crate::secrets::SecretBox;
|
||||
|
||||
/// A target whose billing changed, with its new billing (t72).
|
||||
pub type BillingChange = (
|
||||
mongodb::bson::oid::ObjectId,
|
||||
compliance_core::models::TargetBilling,
|
||||
);
|
||||
|
||||
/// Default maximum concurrent pentest sessions.
|
||||
const DEFAULT_MAX_CONCURRENT_SESSIONS: usize = 5;
|
||||
|
||||
@@ -56,12 +62,22 @@ pub struct ComplianceAgent {
|
||||
|
||||
impl ComplianceAgent {
|
||||
pub fn new(config: AgentConfig, db_pool: DatabasePool) -> Self {
|
||||
let llm = Arc::new(LlmClient::new(
|
||||
config.litellm_url.clone(),
|
||||
config.litellm_api_key.clone(),
|
||||
config.litellm_model.clone(),
|
||||
config.litellm_embed_model.clone(),
|
||||
));
|
||||
if config.litellm_model.is_empty() || config.litellm_embed_model.is_empty() {
|
||||
tracing::warn!(
|
||||
chat = !config.litellm_model.is_empty(),
|
||||
embeddings = !config.litellm_embed_model.is_empty(),
|
||||
"LITELLM_MODEL / LITELLM_EMBED_MODEL not set: those LLM parts are off"
|
||||
);
|
||||
}
|
||||
let llm = Arc::new(
|
||||
LlmClient::new(
|
||||
config.litellm_url.clone(),
|
||||
config.litellm_api_key.clone(),
|
||||
config.litellm_model.clone(),
|
||||
config.litellm_embed_model.clone(),
|
||||
)
|
||||
.with_timeout(std::time::Duration::from_secs(config.llm_timeout_secs)),
|
||||
);
|
||||
let http = reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(30))
|
||||
.connect_timeout(std::time::Duration::from_secs(10))
|
||||
@@ -123,6 +139,19 @@ impl ComplianceAgent {
|
||||
metric: &str,
|
||||
key: String,
|
||||
properties: serde_json::Value,
|
||||
) {
|
||||
self.emit_usage_quantity(tenant_id, metric, key, 1.0, properties);
|
||||
}
|
||||
|
||||
/// [`Self::emit_usage`] with a `quantity` other than one, such as the
|
||||
/// month's peak of extra targets (t72).
|
||||
pub fn emit_usage_quantity(
|
||||
&self,
|
||||
tenant_id: &str,
|
||||
metric: &str,
|
||||
key: String,
|
||||
quantity: f64,
|
||||
properties: serde_json::Value,
|
||||
) {
|
||||
let Some(registry) = self.registry.clone() else {
|
||||
return;
|
||||
@@ -132,7 +161,7 @@ impl ComplianceAgent {
|
||||
tenant_id: tenant_id.to_string(),
|
||||
product: registry.product().to_string(),
|
||||
metric: metric.to_string(),
|
||||
quantity: 1.0,
|
||||
quantity,
|
||||
occurred_at: chrono::Utc::now().to_rfc3339(),
|
||||
properties: Some(properties),
|
||||
};
|
||||
@@ -143,12 +172,106 @@ impl ComplianceAgent {
|
||||
});
|
||||
}
|
||||
|
||||
/// Store which of the tenant's targets are the plan's included ones and
|
||||
/// which are extra (t72), from the plan's `included_targets`. Without a
|
||||
/// registry every target is included. Best-effort: when the plan cannot
|
||||
/// be read or the targets not updated, the stored split stays.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The targets whose billing changed, with their new billing.
|
||||
pub async fn refresh_billing(
|
||||
&self,
|
||||
tenant_id: &str,
|
||||
db: &crate::database::Database,
|
||||
) -> Vec<BillingChange> {
|
||||
match self.plan(tenant_id).await {
|
||||
Some(plan) => {
|
||||
self.assign_billing(tenant_id, db, plan.included_targets)
|
||||
.await
|
||||
}
|
||||
None => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The tenant's plan for metering (t72), from its entitlement; without
|
||||
/// a registry, no limits at all. `None` when the registry did not
|
||||
/// answer: then the stored billing stays, and counted Prüfungen are
|
||||
/// neither checked nor charged.
|
||||
pub async fn plan(&self, tenant_id: &str) -> Option<crate::metering::Plan> {
|
||||
let Some(registry) = &self.registry else {
|
||||
return Some(crate::metering::Plan::default());
|
||||
};
|
||||
match registry.check_entitlement(tenant_id, None, None).await {
|
||||
Ok(check) => Some(crate::metering::Plan {
|
||||
included_targets: check.included_targets(),
|
||||
limits: check.plan_limits(),
|
||||
}),
|
||||
Err(e) => {
|
||||
tracing::warn!(tenant_id, "plan not read, metering waits: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Store the billing of the tenant's targets for a plan that includes
|
||||
/// `included` targets; best-effort.
|
||||
async fn assign_billing(
|
||||
&self,
|
||||
tenant_id: &str,
|
||||
db: &crate::database::Database,
|
||||
included: Option<u32>,
|
||||
) -> Vec<BillingChange> {
|
||||
let changes = match crate::metering::assign_billing(db, included).await {
|
||||
Ok(changes) => {
|
||||
if !changes.is_empty() {
|
||||
tracing::info!(tenant_id, changed = changes.len(), "target billing updated");
|
||||
}
|
||||
changes
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(tenant_id, "target billing not updated: {e}");
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
self.report_extra_peak(tenant_id, db).await;
|
||||
changes
|
||||
}
|
||||
|
||||
/// Send the month's peak of extra targets as `target.extra` when it
|
||||
/// rose, and once a day besides (t72). The key carries the peak, so the
|
||||
/// registry keeps every rise and drops the daily re-send as a duplicate;
|
||||
/// billing takes the highest quantity per tenant-month. Count only: no
|
||||
/// target names leave Prüfwerk. Best-effort.
|
||||
async fn report_extra_peak(&self, tenant_id: &str, db: &crate::database::Database) {
|
||||
let now = chrono::Utc::now();
|
||||
match crate::metering::record_extra_peak(db, now).await {
|
||||
Ok(Some(peak)) => {
|
||||
let (month, _) = crate::metering::berlin_period(now);
|
||||
self.emit_usage_quantity(
|
||||
tenant_id,
|
||||
"target.extra",
|
||||
format!("target-extra:{tenant_id}:{month}:{peak}"),
|
||||
f64::from(peak),
|
||||
serde_json::json!({ "month": month }),
|
||||
);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => tracing::warn!(tenant_id, "extra targets not recorded: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Scan a target, through the [`ScanGate`]: at most `SCAN_CONCURRENCY` scans
|
||||
/// 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.
|
||||
/// 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.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
@@ -170,15 +293,22 @@ 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, trigger.clone()) {
|
||||
match self
|
||||
.scan_gate
|
||||
.admit(&key, Job::new(trigger, run_id.clone()))
|
||||
{
|
||||
Admission::Run => {}
|
||||
Admission::Coalesced => {
|
||||
Admission::Coalesced { replaced } => {
|
||||
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 => {
|
||||
@@ -187,57 +317,83 @@ 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 {
|
||||
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
|
||||
};
|
||||
// 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);
|
||||
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;
|
||||
}
|
||||
match self.scan_gate.finish(&key) {
|
||||
Some(next) => trigger = next,
|
||||
None => break outcome,
|
||||
if !self.scan_gate.finish(&key) {
|
||||
break outcome;
|
||||
}
|
||||
};
|
||||
held.disarm();
|
||||
result
|
||||
}
|
||||
|
||||
/// One scan of a target, with no gating: the pipeline plus its usage event.
|
||||
/// 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.
|
||||
async fn run_one_target_scan(
|
||||
&self,
|
||||
tenant_id: &str,
|
||||
target_id: &str,
|
||||
trigger: compliance_core::models::ScanTrigger,
|
||||
job: &Job,
|
||||
) -> 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).
|
||||
let plan = self.plan(tenant_id).await;
|
||||
if let Some(plan) = &plan {
|
||||
self.assign_billing(tenant_id, &db, plan.included_targets)
|
||||
.await;
|
||||
}
|
||||
let orchestrator =
|
||||
PipelineOrchestrator::new(self.config.clone(), tenant_id, db.clone(), self.llm.clone())
|
||||
.with_nuget_license_cache(self.nuget_license_cache.clone())
|
||||
.with_exploit_cache(self.exploit_cache.clone())
|
||||
.with_advisory_index(self.advisory_index.clone());
|
||||
.with_advisory_index(self.advisory_index.clone())
|
||||
.with_plan_limits(plan.map(|p| p.limits))
|
||||
.with_charged_as(job.charged_as.clone());
|
||||
let started = chrono::Utc::now();
|
||||
let scanned = orchestrator.run_target(target_id, trigger.clone()).await?;
|
||||
let outcome = orchestrator
|
||||
.run_target(target_id, trigger.clone(), job.run_id.as_deref())
|
||||
.await?;
|
||||
// Support's scans are ours, not the customer's usage; a scheduled scan
|
||||
// skipped because nothing changed scanned nothing (#465).
|
||||
if scanned && trigger != compliance_core::models::ScanTrigger::Support {
|
||||
if outcome.scanned && trigger != compliance_core::models::ScanTrigger::Support {
|
||||
self.emit_usage(
|
||||
tenant_id,
|
||||
"scan.completed",
|
||||
format!("scan:{tenant_id}:{target_id}:{}", started.timestamp()),
|
||||
serde_json::json!({ "target_id": target_id, "trigger": format!("{trigger:?}") }),
|
||||
serde_json::json!({
|
||||
"target_id": target_id,
|
||||
"trigger": format!("{trigger:?}"),
|
||||
"attribution": outcome.attribution,
|
||||
"counted": outcome.chargeable,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if let Some(day) = &outcome.booked_prueftag {
|
||||
self.emit_usage(
|
||||
tenant_id,
|
||||
"prueftag.booked",
|
||||
format!("prueftag:{tenant_id}:{target_id}:{day}"),
|
||||
serde_json::json!({ "target_id": target_id, "day": day }),
|
||||
);
|
||||
}
|
||||
self.notify_new_findings(tenant_id, target_id, &db, started);
|
||||
@@ -285,7 +441,7 @@ impl ComplianceAgent {
|
||||
// slot too. Each PR is distinct work, so it is not coalesced.
|
||||
let _slot = self
|
||||
.scan_gate
|
||||
.slot()
|
||||
.slot(Priority::Background)
|
||||
.await
|
||||
.map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?;
|
||||
let db = self.db_pool.for_tenant_id(tenant_id).await?;
|
||||
@@ -361,6 +517,69 @@ 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(
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
//! 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
//! 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));
|
||||
}
|
||||
}
|
||||
@@ -65,10 +65,18 @@ pub struct FindingsFilter {
|
||||
pub status: Option<String>,
|
||||
#[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>,
|
||||
#[serde(default)]
|
||||
pub sort_by: Option<String>,
|
||||
#[serde(default)]
|
||||
@@ -88,6 +96,65 @@ 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
|
||||
@@ -136,6 +203,35 @@ 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,
|
||||
@@ -412,6 +508,41 @@ 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();
|
||||
@@ -478,6 +609,55 @@ 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,9 +79,14 @@ 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(by_target)
|
||||
.find_one({
|
||||
let mut started = by_target;
|
||||
started.insert("status", doc! { "$ne": "queued" });
|
||||
started
|
||||
})
|
||||
.sort(doc! { "started_at": -1 })
|
||||
.await
|
||||
.map_err(load_err)?,
|
||||
@@ -168,6 +173,9 @@ 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(),
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
//! `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"] },
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
//! 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)]
|
||||
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)]
|
||||
pub struct DecideGroupRequest {
|
||||
/// The group, as [`list_finding_groups`] named it.
|
||||
pub key: GroupKey,
|
||||
/// The decision for every member.
|
||||
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)
|
||||
}
|
||||
|
||||
/// GET /api/v1/finding-groups[?target=] — the undecided findings, grouped
|
||||
/// by rule and file (see [`compliance_core::models::finding_group`]), most
|
||||
/// severe first.
|
||||
#[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 },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/// POST /api/v1/finding-groups/decide — give every undecided member of a
|
||||
/// group 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`].
|
||||
#[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));
|
||||
}
|
||||
}
|
||||
@@ -28,8 +28,14 @@ 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);
|
||||
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 });
|
||||
}
|
||||
// Text search across title, description, file_path, rule_id
|
||||
if let Some(q) = &filter.q {
|
||||
@@ -109,6 +115,18 @@ 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";
|
||||
|
||||
@@ -214,7 +232,7 @@ impl<'a> Actor<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn status_update(
|
||||
pub(crate) fn status_update(
|
||||
status: &FindingStatus,
|
||||
reason: Option<&str>,
|
||||
actor: &Actor<'_>,
|
||||
@@ -231,6 +249,7 @@ 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)?;
|
||||
@@ -299,18 +318,42 @@ 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 result = db
|
||||
.findings()
|
||||
.update_many(doc! { "_id": { "$in": oids.clone() } }, update)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
issue_sync(&agent, db).spawn(oids);
|
||||
let filter = doc! { "_id": { "$in": oids.clone() } };
|
||||
let modified_count = apply_status(&agent, db, filter, oids, update).await?;
|
||||
|
||||
Ok(Json(
|
||||
serde_json::json!({ "status": "updated", "modified_count": result.modified_count }),
|
||||
serde_json::json!({ "status": "updated", "modified_count": 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)
|
||||
}
|
||||
|
||||
/// 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))]
|
||||
@@ -342,6 +385,18 @@ 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: IT administrators and support.
|
||||
/// Whether the caller may see the git source: administrators (IT_ADMIN,
|
||||
/// OWNER) and support.
|
||||
fn may_view(tenant: &TenantCtx) -> bool {
|
||||
tenant.0.staff.is_some() || tenant.0.org_roles.contains(&OrgRole::ItAdmin)
|
||||
tenant.0.staff.is_some() || tenant.0.is_admin()
|
||||
}
|
||||
|
||||
/// The source without secrets, plus the webhook URL; `data: null` when the
|
||||
|
||||
@@ -6,7 +6,9 @@ use axum::Json;
|
||||
use mongodb::bson::doc;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use compliance_core::models::graph::{CodeEdge, CodeNode, GraphBuildRun, ImpactAnalysis};
|
||||
use compliance_core::models::graph::{
|
||||
CodeEdge, CodeNode, GraphBuildRun, GraphBuildStatus, ImpactAnalysis,
|
||||
};
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use crate::agent::ComplianceAgent;
|
||||
@@ -188,6 +190,60 @@ 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),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// GET /api/v1/graph/:repo_id/summary — The latest build's counts, without
|
||||
/// loading any node: `data` is `null` when there is none to show.
|
||||
#[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,
|
||||
}))
|
||||
}
|
||||
|
||||
/// GET /api/v1/graph/:repo_id/communities — List detected communities
|
||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||
pub async fn get_communities(
|
||||
@@ -355,7 +411,9 @@ pub async fn get_file_content(
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
|
||||
let content = std::fs::read_to_string(&canonical).map_err(|_| StatusCode::NOT_FOUND)?;
|
||||
// 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)?;
|
||||
|
||||
// Cap at 10,000 lines
|
||||
let truncated: String = content.lines().take(10_000).collect::<Vec<_>>().join("\n");
|
||||
@@ -434,10 +492,17 @@ 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 engine.build_graph(&repo_path, &repo_id, &graph_build_id) {
|
||||
match crate::pipeline::graph_build::build_graph(source, &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;
|
||||
@@ -460,3 +525,48 @@ 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
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -13,23 +13,63 @@ pub async fn access() -> Json<serde_json::Value> {
|
||||
Json(serde_json::json!({ "access": true }))
|
||||
}
|
||||
|
||||
/// How long the health check waits for MongoDB before it reports it down.
|
||||
const DB_PING_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
|
||||
|
||||
/// `GET /api/v1/health`: 200 `{"status":"ok"}` when MongoDB answers a ping,
|
||||
/// 503 `{"status":"degraded","mongo":"unreachable"}` when it does not, so a
|
||||
/// load balancer and the container health check stop sending traffic to an
|
||||
/// instance that cannot serve it (#60). Public, untraced, no tenant.
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn health() -> Json<serde_json::Value> {
|
||||
Json(serde_json::json!({ "status": "ok" }))
|
||||
pub async fn health(
|
||||
axum::extract::Extension(agent): AgentExt,
|
||||
) -> (axum::http::StatusCode, Json<serde_json::Value>) {
|
||||
let reachable = match tokio::time::timeout(DB_PING_TIMEOUT, agent.db_pool.ping()).await {
|
||||
Ok(Ok(())) => true,
|
||||
Ok(Err(e)) => {
|
||||
tracing::warn!(error = %e, "health: MongoDB ping failed");
|
||||
false
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::warn!("health: MongoDB ping timed out");
|
||||
false
|
||||
}
|
||||
};
|
||||
health_answer(reachable)
|
||||
}
|
||||
|
||||
/// The health answer for whether MongoDB answered.
|
||||
fn health_answer(mongo_reachable: bool) -> (axum::http::StatusCode, Json<serde_json::Value>) {
|
||||
if mongo_reachable {
|
||||
(
|
||||
axum::http::StatusCode::OK,
|
||||
Json(serde_json::json!({ "status": "ok" })),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
axum::http::StatusCode::SERVICE_UNAVAILABLE,
|
||||
Json(serde_json::json!({ "status": "degraded", "mongo": "unreachable" })),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Findings that still need someone's attention: not resolved, not a false
|
||||
/// 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.
|
||||
async fn open_findings_by_severity(
|
||||
/// 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(
|
||||
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": { "status": { "$in": OPEN_STATUSES.to_vec() } } },
|
||||
doc! { "$match": matching },
|
||||
doc! { "$group": { "_id": "$severity", "n": { "$sum": 1 } } },
|
||||
];
|
||||
let rows: Vec<mongodb::bson::Document> = match db.findings().aggregate(pipeline).await {
|
||||
@@ -81,7 +121,7 @@ pub async fn stats_overview(
|
||||
.await
|
||||
.unwrap_or(0)
|
||||
},
|
||||
open_findings_by_severity(db),
|
||||
open_findings_by_severity(db, doc! {}),
|
||||
);
|
||||
let severity = |name: &str| by_severity.get(name).copied().unwrap_or(0);
|
||||
let total_findings = by_severity.values().sum();
|
||||
@@ -128,3 +168,20 @@ pub async fn stats_overview(
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_health_answer_follows_the_database() {
|
||||
let (status, Json(body)) = health_answer(true);
|
||||
assert_eq!(status, axum::http::StatusCode::OK);
|
||||
assert_eq!(body, serde_json::json!({ "status": "ok" }));
|
||||
|
||||
let (status, Json(body)) = health_answer(false);
|
||||
assert_eq!(status, axum::http::StatusCode::SERVICE_UNAVAILABLE);
|
||||
assert_eq!(body["status"], "degraded");
|
||||
assert_eq!(body["mongo"], "unreachable");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
//! 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" })))
|
||||
}
|
||||
@@ -1,32 +1,42 @@
|
||||
use axum::extract::{Extension, Query};
|
||||
use axum::Json;
|
||||
use mongodb::bson::doc;
|
||||
use mongodb::bson::{doc, Bson, Document};
|
||||
|
||||
use super::dto::*;
|
||||
use compliance_core::models::issue::cve_issue_prefix;
|
||||
use compliance_core::models::TrackerIssue;
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
#[tracing::instrument(skip_all)]
|
||||
/// 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))]
|
||||
pub async fn list_issues(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Query(params): Query<PaginationParams>,
|
||||
Query(filter): Query<IssuesFilter>,
|
||||
) -> ApiResult<Vec<TrackerIssue>> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let db = &db;
|
||||
let skip = params.skip();
|
||||
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 total = db
|
||||
.tracker_issues()
|
||||
.count_documents(doc! {})
|
||||
.count_documents(query.clone())
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
|
||||
let issues = match db
|
||||
.tracker_issues()
|
||||
.find(doc! {})
|
||||
.find(query)
|
||||
.sort(doc! { "created_at": -1 })
|
||||
.skip(skip)
|
||||
.limit(params.limit)
|
||||
.limit(filter.limit)
|
||||
.await
|
||||
{
|
||||
Ok(cursor) => collect_cursor_async(cursor).await,
|
||||
@@ -39,6 +49,198 @@ pub async fn list_issues(
|
||||
Ok(Json(ApiResponse {
|
||||
data: issues,
|
||||
total: Some(total),
|
||||
page: Some(params.page),
|
||||
page: Some(filter.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"));
|
||||
}
|
||||
}
|
||||
@@ -292,12 +292,12 @@ pub async fn withdraw(
|
||||
}
|
||||
|
||||
/// Whether the requester may change the policy and decide reviews: LEGAL,
|
||||
/// IT_ADMIN, or BreakPilot support. USER confirms licences but does not
|
||||
/// an administrator (IT_ADMIN, OWNER), 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.has_any_role(&[OrgRole::Legal, OrgRole::ItAdmin]))
|
||||
&& (ctx.staff.is_some() || ctx.is_admin() || ctx.has_any_role(&[OrgRole::Legal]))
|
||||
}
|
||||
|
||||
fn refuse_role() -> Refusal {
|
||||
@@ -306,7 +306,7 @@ fn refuse_role() -> Refusal {
|
||||
Json(serde_json::json!({
|
||||
"error": crate::api::role_gate::FORBIDDEN_ROLE,
|
||||
"access": "read_only",
|
||||
"needs": ["LEGAL", "IT_ADMIN"],
|
||||
"needs": ["LEGAL", "IT_ADMIN", "OWNER"],
|
||||
})),
|
||||
)
|
||||
}
|
||||
@@ -912,6 +912,7 @@ 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` role.
|
||||
//! `IT_ADMIN` (or `OWNER`) role.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -16,7 +16,6 @@ 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;
|
||||
@@ -84,9 +83,10 @@ pub struct ImportSummary {
|
||||
pub duplicates: usize,
|
||||
}
|
||||
|
||||
/// Only an organisation's IT administrator writes findings by hand.
|
||||
/// Only an organisation's administrator (IT_ADMIN, OWNER) writes findings by
|
||||
/// hand.
|
||||
fn require_admin(tenant: &TenantCtx) -> Result<(), StatusCode> {
|
||||
if tenant.0.org_roles.contains(&OrgRole::ItAdmin) {
|
||||
if tenant.0.is_admin() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(StatusCode::FORBIDDEN)
|
||||
@@ -221,7 +221,7 @@ pub async fn import_findings(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::tenant::{TenantContext, TenantStatus};
|
||||
use compliance_core::tenant::{OrgRole, TenantContext, TenantStatus};
|
||||
|
||||
fn tenant(roles: Vec<OrgRole>) -> TenantCtx {
|
||||
TenantCtx(TenantContext {
|
||||
@@ -241,6 +241,7 @@ 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)
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
//! 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 })))
|
||||
}
|
||||
@@ -1,19 +1,25 @@
|
||||
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;
|
||||
@@ -22,6 +28,8 @@ 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;
|
||||
|
||||
@@ -114,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()),
|
||||
latest_scan_runs(&runs, ids.clone(), true),
|
||||
findings_counts(&findings, ids),
|
||||
);
|
||||
let data = targets
|
||||
@@ -179,10 +179,13 @@ impl TargetFilter {
|
||||
}
|
||||
}
|
||||
|
||||
/// The newest scan run of each target in `target_ids`, in one query.
|
||||
/// 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.
|
||||
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;
|
||||
|
||||
@@ -190,8 +193,12 @@ 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": { "repo_id": { "$in": target_ids } } },
|
||||
doc! { "$match": matching },
|
||||
doc! { "$sort": { "started_at": -1 } },
|
||||
doc! { "$group": { "_id": "$repo_id", "run": { "$first": "$$ROOT" } } },
|
||||
];
|
||||
@@ -516,36 +523,13 @@ pub async fn delete_target(
|
||||
.await;
|
||||
|
||||
// DAST targets linked to this target, and all their downstream data.
|
||||
if let Ok(mut cursor) = db.dast_targets().find(doc! { "repo_id": &id }).await {
|
||||
use futures_util::StreamExt;
|
||||
while let Some(Ok(dt)) = cursor.next().await {
|
||||
let dast_target_id = dt.id.map(|oid| oid.to_hex()).unwrap_or_default();
|
||||
if !dast_target_id.is_empty() {
|
||||
cascade_delete_dast_target(db, &dast_target_id).await;
|
||||
}
|
||||
}
|
||||
for dast_target_id in ids_of(db.dast_targets(), doc! { "repo_id": &id }).await {
|
||||
cascade_delete_dast_target(db, &dast_target_id).await;
|
||||
}
|
||||
|
||||
// Pentest sessions linked directly to this target (not via a DAST target).
|
||||
if let Ok(mut cursor) = db.pentest_sessions().find(doc! { "repo_id": &id }).await {
|
||||
use futures_util::StreamExt;
|
||||
while let Some(Ok(session)) = cursor.next().await {
|
||||
let session_id = session.id.map(|oid| oid.to_hex()).unwrap_or_default();
|
||||
if !session_id.is_empty() {
|
||||
let _ = db
|
||||
.attack_chain_nodes()
|
||||
.delete_many(doc! { "session_id": &session_id })
|
||||
.await;
|
||||
let _ = db
|
||||
.pentest_messages()
|
||||
.delete_many(doc! { "session_id": &session_id })
|
||||
.await;
|
||||
let _ = db
|
||||
.dast_findings()
|
||||
.delete_many(doc! { "session_id": &session_id })
|
||||
.await;
|
||||
}
|
||||
}
|
||||
for session_id in ids_of(db.pentest_sessions(), doc! { "repo_id": &id }).await {
|
||||
delete_session_data(db, &session_id).await;
|
||||
}
|
||||
let _ = db
|
||||
.pentest_sessions()
|
||||
@@ -555,32 +539,32 @@ pub async fn delete_target(
|
||||
Ok(Json(serde_json::json!({ "status": "deleted" })))
|
||||
}
|
||||
|
||||
/// The `_id`s (hex) of the documents in `coll` that match `filter`, read raw
|
||||
/// with only `_id` projected: a document stored in another shape (an older
|
||||
/// version, a manual insert) is still found, so a cascade never stops at it
|
||||
/// and leaves its downstream data behind.
|
||||
async fn ids_of<T: Send + Sync>(
|
||||
coll: mongodb::Collection<T>,
|
||||
filter: mongodb::bson::Document,
|
||||
) -> Vec<String> {
|
||||
use futures_util::StreamExt;
|
||||
let raw = coll.clone_with_type::<mongodb::bson::Document>();
|
||||
let mut out = Vec::new();
|
||||
if let Ok(mut cursor) = raw.find(filter).projection(doc! { "_id": 1 }).await {
|
||||
while let Some(next) = cursor.next().await {
|
||||
if let Ok(Ok(oid)) = next.as_ref().map(|d| d.get_object_id("_id")) {
|
||||
out.push(oid.to_hex());
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Delete a DAST target and everything downstream of it (pentest sessions +
|
||||
/// their attack chains / messages / findings, DAST scan runs + findings).
|
||||
async fn cascade_delete_dast_target(db: &crate::database::Database, target_id: &str) {
|
||||
use futures_util::StreamExt;
|
||||
if let Ok(mut cursor) = db
|
||||
.pentest_sessions()
|
||||
.find(doc! { "target_id": target_id })
|
||||
.await
|
||||
{
|
||||
while let Some(Ok(session)) = cursor.next().await {
|
||||
let session_id = session.id.map(|oid| oid.to_hex()).unwrap_or_default();
|
||||
if !session_id.is_empty() {
|
||||
let _ = db
|
||||
.attack_chain_nodes()
|
||||
.delete_many(doc! { "session_id": &session_id })
|
||||
.await;
|
||||
let _ = db
|
||||
.pentest_messages()
|
||||
.delete_many(doc! { "session_id": &session_id })
|
||||
.await;
|
||||
let _ = db
|
||||
.dast_findings()
|
||||
.delete_many(doc! { "session_id": &session_id })
|
||||
.await;
|
||||
}
|
||||
}
|
||||
for session_id in ids_of(db.pentest_sessions(), doc! { "target_id": target_id }).await {
|
||||
delete_session_data(db, &session_id).await;
|
||||
}
|
||||
let _ = db
|
||||
.pentest_sessions()
|
||||
@@ -599,6 +583,22 @@ async fn cascade_delete_dast_target(db: &crate::database::Database, target_id: &
|
||||
}
|
||||
}
|
||||
|
||||
/// The attack chain, messages and findings of one pentest session.
|
||||
async fn delete_session_data(db: &crate::database::Database, session_id: &str) {
|
||||
let _ = db
|
||||
.attack_chain_nodes()
|
||||
.delete_many(doc! { "session_id": session_id })
|
||||
.await;
|
||||
let _ = db
|
||||
.pentest_messages()
|
||||
.delete_many(doc! { "session_id": session_id })
|
||||
.await;
|
||||
let _ = db
|
||||
.dast_findings()
|
||||
.delete_many(doc! { "session_id": session_id })
|
||||
.await;
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets/{id}/artifacts — attach an artifact (by reference).
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn add_artifact(
|
||||
@@ -1006,6 +1006,100 @@ pub async fn detect_target(
|
||||
}))
|
||||
}
|
||||
|
||||
/// Why a scan is asked for (`POST /api/v1/targets/{id}/scan?reason=…`).
|
||||
#[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
|
||||
/// Prüfung. Absent: the customer asks for a Prüfung, which always runs
|
||||
/// and counts.
|
||||
#[serde(default)]
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
/// The trigger of a scan the customer (`staff: false`) or support asked
|
||||
/// for, for `reason`. Support's scans are never the customer's usage.
|
||||
fn requested_trigger(staff: bool, reason: Option<&str>) -> compliance_core::models::ScanTrigger {
|
||||
use compliance_core::models::ScanTrigger;
|
||||
if staff {
|
||||
ScanTrigger::Support
|
||||
} else if reason == Some("new_content") {
|
||||
ScanTrigger::NewContent
|
||||
} else {
|
||||
ScanTrigger::Manual
|
||||
}
|
||||
}
|
||||
|
||||
/// `POST /api/v1/targets/{id}/billing/swap`: the included target to swap
|
||||
/// the extra target `{id}` with.
|
||||
#[derive(Debug, Deserialize)]
|
||||
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",
|
||||
}
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets/{id}/billing/swap — swap the extra target `{id}`
|
||||
/// with the included target `with` (t72): `{id}` becomes included and stays
|
||||
/// so until the end of the calendar month, `with` becomes extra at once.
|
||||
/// 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.
|
||||
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 } })))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets/{id}/scan — trigger a scan for the target.
|
||||
///
|
||||
/// Dispatches to the unified pipeline when `UNIFIED_PIPELINE` is set (else the
|
||||
@@ -1015,6 +1109,7 @@ pub async fn trigger_target_scan(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
Query(reason): Query<ScanReason>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let oid = parse_oid(&id)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
@@ -1031,12 +1126,7 @@ pub async fn trigger_target_scan(
|
||||
|
||||
let agent_clone = (*agent).clone();
|
||||
let tenant_id = tenant.0.tenant_id.clone();
|
||||
// A scan support starts is not the customer's usage.
|
||||
let trigger = if tenant.0.staff.is_some() {
|
||||
compliance_core::models::ScanTrigger::Support
|
||||
} else {
|
||||
compliance_core::models::ScanTrigger::Manual
|
||||
};
|
||||
let trigger = requested_trigger(tenant.0.staff.is_some(), reason.reason.as_deref());
|
||||
tokio::spawn(async move {
|
||||
// Always the unified target pipeline — this endpoint is about an
|
||||
// onboarded target by construction, independent of the global
|
||||
@@ -1052,6 +1142,22 @@ pub async fn trigger_target_scan(
|
||||
mod filter_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_scan_asked_for_new_content_is_change_driven() {
|
||||
use compliance_core::models::ScanTrigger;
|
||||
assert_eq!(requested_trigger(false, None), ScanTrigger::Manual);
|
||||
assert_eq!(
|
||||
requested_trigger(false, Some("new_content")),
|
||||
ScanTrigger::NewContent
|
||||
);
|
||||
assert_eq!(requested_trigger(false, Some("other")), ScanTrigger::Manual);
|
||||
assert_eq!(
|
||||
requested_trigger(true, Some("new_content")),
|
||||
ScanTrigger::Support,
|
||||
"support's scans are never the customer's usage"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_filter_matches_its_targets() {
|
||||
let filter = TargetFilter {
|
||||
|
||||
@@ -18,6 +18,8 @@ use mongodb::bson::{doc, Document};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use compliance_core::auth::{validate_service_token, JwksState};
|
||||
// Re-exported: the VEX, evidence and change-detection code import them from here.
|
||||
pub use compliance_core::build_info::{BUILD_COMMIT, BUILD_VERSION};
|
||||
|
||||
use crate::agent::ComplianceAgent;
|
||||
|
||||
@@ -432,23 +434,6 @@ pub async fn usage(
|
||||
}))
|
||||
}
|
||||
|
||||
/// The build version: `PRUEFWERK_VERSION` at compile time (CI: the latest
|
||||
/// release tag without its `v`), else the crate version.
|
||||
pub const BUILD_VERSION: &str =
|
||||
non_empty_or(option_env!("PRUEFWERK_VERSION"), env!("CARGO_PKG_VERSION"));
|
||||
|
||||
/// The commit the build is from: `PRUEFWERK_COMMIT` at compile time (CI:
|
||||
/// the full SHA), else "unknown". The portal's version line shows 8 characters.
|
||||
pub const BUILD_COMMIT: &str = non_empty_or(option_env!("PRUEFWERK_COMMIT"), "unknown");
|
||||
|
||||
/// A Docker build arg left empty is an empty env var, not an unset one.
|
||||
const fn non_empty_or(value: Option<&'static str>, fallback: &'static str) -> &'static str {
|
||||
match value {
|
||||
Some(v) if !v.is_empty() => v,
|
||||
_ => fallback,
|
||||
}
|
||||
}
|
||||
|
||||
/// `GET /api/v1/platform/version` — contract handshake (§4.1 /version).
|
||||
pub async fn version(State(st): State<PlatformState>) -> Json<serde_json::Value> {
|
||||
Json(serde_json::json!({
|
||||
@@ -575,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()),
|
||||
super::onboarding::latest_scan_runs(&runs, ids.clone(), false),
|
||||
open_findings_counts(&db, ids.clone()),
|
||||
open_vulnerabilities_counts(&db, ids),
|
||||
);
|
||||
@@ -655,6 +640,10 @@ 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
|
||||
}
|
||||
@@ -807,20 +796,6 @@ pub async fn delete_git_source(
|
||||
})))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod build_info_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_unset_or_empty_build_value_falls_back() {
|
||||
assert_eq!(non_empty_or(None, "0.4.4"), "0.4.4");
|
||||
assert_eq!(non_empty_or(Some(""), "unknown"), "unknown");
|
||||
assert_eq!(non_empty_or(Some("0.4.5"), "0.4.4"), "0.4.5");
|
||||
assert!(!BUILD_VERSION.is_empty());
|
||||
assert!(!BUILD_COMMIT.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod target_count_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -31,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| !s.is_empty() && s != "unknown" && s != "file")
|
||||
.filter(|s| compliance_core::sbom_ecosystems::is_filterable_manager(s))
|
||||
.collect();
|
||||
|
||||
let licenses: Vec<String> = db
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
//! 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, "");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
//! 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);
|
||||
}
|
||||
}
|
||||
@@ -7,11 +7,11 @@
|
||||
//! its token and its uploaded file, and a scan config keeps every field the
|
||||
//! request does not name (#304).
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::{Deserialize, Deserializer};
|
||||
|
||||
use compliance_core::models::{
|
||||
Artifact, ArtifactAuth, ArtifactKind, Environment, IssueTrackerConfig, PentestConfig,
|
||||
PentestStrategy, PlcFormat, ScanType, TargetScanConfig,
|
||||
normalise_exclude_paths, Artifact, ArtifactAuth, ArtifactKind, Environment, IssueTrackerConfig,
|
||||
PentestConfig, PentestStrategy, PlcFormat, ScanType, TargetScanConfig,
|
||||
};
|
||||
|
||||
use crate::secrets::{SecretBox, SecretError};
|
||||
@@ -138,6 +138,22 @@ pub struct ScanConfigUpdate {
|
||||
pub strategy: Option<PentestStrategy>,
|
||||
pub pentest: Option<PentestConfig>,
|
||||
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
|
||||
/// reason (axum answers 422 with the message).
|
||||
#[serde(default, deserialize_with = "exclude_paths")]
|
||||
pub exclude_paths: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
/// `exclude_paths` as [`normalise_exclude_paths`] stores them; an invalid
|
||||
/// entry fails the request with the reason naming it.
|
||||
fn exclude_paths<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
Option::<Vec<String>>::deserialize(deserializer)?
|
||||
.map(|paths| normalise_exclude_paths(&paths).map_err(serde::de::Error::custom))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
impl ScanConfigUpdate {
|
||||
@@ -169,6 +185,9 @@ impl ScanConfigUpdate {
|
||||
if let Some(v) = self.strategy {
|
||||
merged.strategy = Some(v);
|
||||
}
|
||||
if let Some(v) = self.exclude_paths {
|
||||
merged.exclude_paths = v;
|
||||
}
|
||||
if let Some(mut tracker) = self.issue_tracker {
|
||||
let kept = stored.issue_tracker.as_ref().and_then(|t| t.token.as_ref());
|
||||
secrets.take_update(&mut tracker.token, kept)?;
|
||||
@@ -275,6 +294,32 @@ mod tests {
|
||||
assert!(cleared.auth.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn excluded_paths_are_normalised_or_refused_with_the_reason() {
|
||||
let update: ScanConfigUpdate =
|
||||
serde_json::from_str(r#"{"exclude_paths": ["./docs/samples/", "", "tools\\old"]}"#)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
update.exclude_paths.as_deref(),
|
||||
Some(&["docs/samples".to_string(), "tools/old".to_string()][..])
|
||||
);
|
||||
let stored = TargetScanConfig {
|
||||
exclude_paths: vec!["old".into()],
|
||||
..Default::default()
|
||||
};
|
||||
let merged = update.apply(&secrets(), &stored).unwrap();
|
||||
assert_eq!(merged.exclude_paths, ["docs/samples", "tools/old"]);
|
||||
|
||||
// Left out: the stored list stays.
|
||||
let untouched: ScanConfigUpdate = serde_json::from_str("{}").unwrap();
|
||||
let kept = untouched.apply(&secrets(), &stored).unwrap();
|
||||
assert_eq!(kept.exclude_paths, ["old"]);
|
||||
|
||||
let err = serde_json::from_str::<ScanConfigUpdate>(r#"{"exclude_paths": ["../etc"]}"#)
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("../etc"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enabling_a_scan_keeps_the_tracker_and_its_token() {
|
||||
let s = secrets();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! VEX for a target's CVE alerts (#498): list them, state their status, and
|
||||
//! export the statements as OpenVEX or CycloneDX VEX.
|
||||
//! 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.
|
||||
|
||||
use axum::extract::{Extension, Path, Query};
|
||||
use axum::http::{header, HeaderValue, StatusCode};
|
||||
@@ -9,6 +10,7 @@ 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;
|
||||
@@ -26,18 +28,8 @@ pub async fn list_target_cves(
|
||||
Path(id): Path<String>,
|
||||
) -> ApiResult<Vec<CveAlert>> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
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()
|
||||
}
|
||||
};
|
||||
// An unreadable list reads as empty here, as it always has.
|
||||
let alerts = target_alerts(&db, &id).await.unwrap_or_default();
|
||||
Ok(Json(ApiResponse {
|
||||
total: Some(alerts.len() as u64),
|
||||
data: alerts,
|
||||
@@ -45,6 +37,23 @@ 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 {
|
||||
@@ -57,9 +66,8 @@ pub struct VexRequest {
|
||||
pub action_statement: Option<String>,
|
||||
}
|
||||
|
||||
/// The statement `req` asks for, by the requester of `tenant`.
|
||||
fn statement(req: VexRequest, tenant: &TenantCtx) -> VexAssessment {
|
||||
let actor = Actor::of(&tenant.0);
|
||||
/// The statement `req` asks for, by `actor`.
|
||||
fn statement(req: VexRequest, actor: Actor<'_>) -> VexAssessment {
|
||||
let text = |s: Option<String>| s.map(|t| t.trim().to_string()).filter(|t| !t.is_empty());
|
||||
VexAssessment {
|
||||
status: req.status,
|
||||
@@ -85,7 +93,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, &tenant);
|
||||
let vex = statement(req, Actor::of(&tenant.0));
|
||||
vex.validate()
|
||||
.map_err(|e| fail(StatusCode::UNPROCESSABLE_ENTITY, &e.to_string()))?;
|
||||
let db = tenant_db(&agent, &tenant)
|
||||
@@ -104,6 +112,90 @@ 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 {
|
||||
@@ -441,6 +533,88 @@ 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() {
|
||||
|
||||
@@ -3,5 +3,6 @@ pub mod handlers;
|
||||
pub mod role_gate;
|
||||
pub mod routes;
|
||||
pub mod server;
|
||||
pub mod trace;
|
||||
|
||||
pub use server::start_api_server;
|
||||
@@ -2,12 +2,13 @@
|
||||
//!
|
||||
//! One middleware for every tenant-scoped route, so no handler can forget it:
|
||||
//!
|
||||
//! * `IT_ADMIN`, `USER` — read and write.
|
||||
//! * `CXO`, `LEGAL` — read only: `GET` / `HEAD` / `OPTIONS`, plus the few
|
||||
//! * `OWNER`, `IT_ADMIN`, `USER`, `PSIRT`, `DEVELOPMENT` — read and write.
|
||||
//! * `CXO`, `LEGAL`, `QUALITY`, `PURCHASING`, `AUDITOR` — 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`, or none of these roles — nothing; every request is refused.
|
||||
//! * `FINANCE`, `PRIVACY`, `EXTERNAL`, or none of these roles — nothing;
|
||||
//! every request is refused.
|
||||
//!
|
||||
//! Refusals are `403 {"error": "forbidden_role", "access": "none" | "read_only"}`.
|
||||
//!
|
||||
@@ -18,7 +19,8 @@
|
||||
//! 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 `IT_ADMIN`-only).
|
||||
//! Handlers may still be stricter (manual findings stay for administrators:
|
||||
//! `IT_ADMIN` and `OWNER`).
|
||||
//!
|
||||
//! 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,11 +19,19 @@ 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,
|
||||
@@ -35,11 +43,19 @@ 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,
|
||||
};
|
||||
@@ -126,11 +142,18 @@ 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,
|
||||
@@ -142,7 +165,23 @@ 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),
|
||||
(
|
||||
@@ -173,11 +212,19 @@ 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),
|
||||
|
||||
@@ -15,6 +15,7 @@ pub fn build_router() -> Router {
|
||||
.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.
|
||||
@@ -84,6 +85,10 @@ pub fn build_router() -> Router {
|
||||
"/api/v1/targets/{id}/scan",
|
||||
post(handlers::onboarding::trigger_target_scan),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/billing/swap",
|
||||
post(handlers::onboarding::swap_target_billing),
|
||||
)
|
||||
.route("/api/v1/findings", get(handlers::list_findings))
|
||||
.route(
|
||||
"/api/v1/findings/variants",
|
||||
@@ -102,16 +107,66 @@ pub fn build_router() -> Router {
|
||||
"/api/v1/findings/{id}/feedback",
|
||||
patch(handlers::update_finding_feedback),
|
||||
)
|
||||
// Undecided findings grouped by rule and file; one decision per group (#951).
|
||||
.route(
|
||||
"/api/v1/finding-groups",
|
||||
get(handlers::finding_groups::list_finding_groups),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/finding-groups/decide",
|
||||
post(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),
|
||||
)
|
||||
// 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),
|
||||
@@ -120,6 +175,10 @@ pub fn build_router() -> Router {
|
||||
"/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),
|
||||
@@ -194,6 +253,10 @@ pub fn build_router() -> Router {
|
||||
"/api/v1/graph/{repo_id}/nodes",
|
||||
get(handlers::graph::get_nodes),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/graph/{repo_id}/summary",
|
||||
get(handlers::graph::get_summary),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/graph/{repo_id}/communities",
|
||||
get(handlers::graph::get_communities),
|
||||
|
||||
@@ -444,7 +444,11 @@ pub async fn start_api_server(
|
||||
&agent.config.cors_allowed_origins,
|
||||
agent.config.app_env,
|
||||
))
|
||||
.layer(TraceLayer::new_for_http())
|
||||
.layer(
|
||||
TraceLayer::new_for_http()
|
||||
.make_span_with(crate::api::trace::make_span)
|
||||
.on_response(crate::api::trace::on_response),
|
||||
)
|
||||
// Security headers (defense-in-depth, primary enforcement via Traefik)
|
||||
.layer(SetResponseHeaderLayer::overriding(
|
||||
axum::http::header::STRICT_TRANSPORT_SECURITY,
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
//! One server span per HTTP request, for `TraceLayer` (instrumentation plan,
|
||||
//! research/observability/2026-10-28-instrumentation-portal-registry-db.md).
|
||||
//!
|
||||
//! The default `TraceLayer` span is DEBUG (so the INFO filter drops it) and
|
||||
//! records the full URI. This one is INFO, named after the route template
|
||||
//! (`GET /api/v1/targets/{id}`), continues an incoming `traceparent` (portal,
|
||||
//! registry) and records no path, query or client address.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::extract::{MatchedPath, Request};
|
||||
use axum::response::Response;
|
||||
use tracing::Span;
|
||||
|
||||
/// The health route is polled every few seconds and gets no span.
|
||||
const UNTRACED: &[&str] = &["/api/v1/health"];
|
||||
|
||||
pub fn make_span(req: &Request) -> Span {
|
||||
let route = req
|
||||
.extensions()
|
||||
.get::<MatchedPath>()
|
||||
.map(MatchedPath::as_str);
|
||||
if route.is_some_and(|r| UNTRACED.contains(&r)) {
|
||||
return Span::none();
|
||||
}
|
||||
let method = req.method().as_str();
|
||||
let span = tracing::info_span!(
|
||||
"http",
|
||||
otel.name = %format!("{method} {}", route.unwrap_or("unmatched")),
|
||||
otel.kind = "server",
|
||||
otel.status_code = tracing::field::Empty,
|
||||
http.request.method = %method,
|
||||
http.route = route.unwrap_or(""),
|
||||
http.response.status_code = tracing::field::Empty,
|
||||
);
|
||||
let header = |name: &str| req.headers().get(name).and_then(|v| v.to_str().ok());
|
||||
compliance_core::telemetry::continue_trace(&span, header("traceparent"), header("tracestate"));
|
||||
span
|
||||
}
|
||||
|
||||
pub fn on_response(res: &Response, _latency: Duration, span: &Span) {
|
||||
span.record("http.response.status_code", res.status().as_u16());
|
||||
if res.status().is_server_error() {
|
||||
span.record("otel.status_code", "ERROR");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use axum::body::Body;
|
||||
use axum::routing::get;
|
||||
use axum::Router;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tower::ServiceExt as _;
|
||||
use tower_http::trace::TraceLayer;
|
||||
use tracing::field::{Field, Visit};
|
||||
use tracing::span::{Attributes, Id, Record};
|
||||
use tracing_subscriber::layer::{Context, SubscriberExt as _};
|
||||
use tracing_subscriber::Layer;
|
||||
|
||||
/// Every field recorded on any span, as "name=value".
|
||||
#[derive(Clone, Default)]
|
||||
struct Fields(Arc<Mutex<Vec<String>>>);
|
||||
struct Collect<'a>(&'a Mutex<Vec<String>>);
|
||||
impl Visit for Collect<'_> {
|
||||
fn record_debug(&mut self, f: &Field, v: &dyn std::fmt::Debug) {
|
||||
self.0.lock().unwrap().push(format!("{}={v:?}", f.name()));
|
||||
}
|
||||
fn record_str(&mut self, f: &Field, v: &str) {
|
||||
self.0.lock().unwrap().push(format!("{}={v}", f.name()));
|
||||
}
|
||||
}
|
||||
impl<S: tracing::Subscriber> Layer<S> for Fields {
|
||||
fn on_new_span(&self, a: &Attributes<'_>, _: &Id, _: Context<'_, S>) {
|
||||
a.record(&mut Collect(&self.0));
|
||||
}
|
||||
fn on_record(&self, _: &Id, r: &Record<'_>, _: Context<'_, S>) {
|
||||
r.record(&mut Collect(&self.0));
|
||||
}
|
||||
}
|
||||
|
||||
async fn call(path: &str, status: u16) -> Vec<String> {
|
||||
let fields = Fields::default();
|
||||
let sub = tracing_subscriber::registry().with(fields.clone());
|
||||
let _guard = tracing::subscriber::set_default(sub);
|
||||
let app = Router::new()
|
||||
.route("/api/v1/health", get(|| async { "ok" }))
|
||||
.route(
|
||||
"/api/v1/targets/{id}",
|
||||
get(move || async move { axum::http::StatusCode::from_u16(status).unwrap() }),
|
||||
)
|
||||
.layer(
|
||||
TraceLayer::new_for_http()
|
||||
.make_span_with(make_span)
|
||||
.on_response(on_response),
|
||||
);
|
||||
let req = Request::builder().uri(path).body(Body::empty()).unwrap();
|
||||
app.oneshot(req).await.unwrap();
|
||||
let out = fields.0.lock().unwrap().clone();
|
||||
out
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn names_the_span_after_the_route_and_keeps_the_path_out() {
|
||||
let f = call("/api/v1/targets/acme-firmware?token=x", 200).await;
|
||||
assert!(
|
||||
f.contains(&"otel.name=GET /api/v1/targets/{id}".to_string()),
|
||||
"{f:?}"
|
||||
);
|
||||
assert!(
|
||||
f.contains(&"http.route=/api/v1/targets/{id}".to_string()),
|
||||
"{f:?}"
|
||||
);
|
||||
assert!(
|
||||
f.contains(&"http.response.status_code=200".to_string()),
|
||||
"{f:?}"
|
||||
);
|
||||
assert!(
|
||||
f.iter()
|
||||
.all(|x| !x.contains("acme") && !x.contains("token")),
|
||||
"{f:?}"
|
||||
);
|
||||
assert!(
|
||||
!f.iter().any(|x| x.starts_with("otel.status_code")),
|
||||
"{f:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_server_error_marks_the_span() {
|
||||
let f = call("/api/v1/targets/1", 503).await;
|
||||
assert!(f.contains(&"otel.status_code=ERROR".to_string()), "{f:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn health_and_unmatched() {
|
||||
assert!(
|
||||
call("/api/v1/health", 200).await.is_empty(),
|
||||
"health gets no span"
|
||||
);
|
||||
let f = call("/nope/acme", 200).await;
|
||||
assert!(f.contains(&"otel.name=GET unmatched".to_string()), "{f:?}");
|
||||
}
|
||||
}
|
||||
@@ -390,6 +390,13 @@ impl HeuristicClassifier {
|
||||
ArtifactKind::SourceArchive if lower.ends_with(".projectarchive") => out.push(
|
||||
verdict(TargetType::PlcSps, 0.85, "CODESYS project archive", vec![]),
|
||||
),
|
||||
// A Yocto image's SPDX archive is Yocto by itself.
|
||||
ArtifactKind::BuildOutput if lower.ends_with(".spdx.tar.zst") => out.push(verdict(
|
||||
TargetType::EmbeddedLinuxYocto,
|
||||
0.7,
|
||||
"Yocto image SPDX archive",
|
||||
vec![],
|
||||
)),
|
||||
ArtifactKind::LiveUrl if input.artifacts.len() == 1 => {
|
||||
out.push(verdict(TargetType::WebApp, 0.3, "live URL only", vec![]))
|
||||
}
|
||||
|
||||
@@ -49,9 +49,14 @@ fn build_config(app_env: AppEnv) -> Result<AgentConfig, AgentError> {
|
||||
litellm_url: env_var_opt("LITELLM_URL")
|
||||
.unwrap_or_else(|| "http://localhost:4000".to_string()),
|
||||
litellm_api_key: SecretString::from(env_var_opt("LITELLM_API_KEY").unwrap_or_default()),
|
||||
litellm_model: env_var_opt("LITELLM_MODEL").unwrap_or_else(|| "gpt-4o".to_string()),
|
||||
litellm_embed_model: env_var_opt("LITELLM_EMBED_MODEL")
|
||||
.unwrap_or_else(|| "text-embedding-3-small".to_string()),
|
||||
// No default model: our gateway serves none of the OpenAI names, so an
|
||||
// unset model means the LLM parts are off (LlmClient refuses to call).
|
||||
litellm_model: env_var_opt("LITELLM_MODEL").unwrap_or_default(),
|
||||
litellm_embed_model: env_var_opt("LITELLM_EMBED_MODEL").unwrap_or_default(),
|
||||
llm_timeout_secs: env_var_opt("LLM_TIMEOUT_SECS")
|
||||
.and_then(|v| v.parse::<u64>().ok())
|
||||
.filter(|n| *n > 0)
|
||||
.unwrap_or(600),
|
||||
github_token: env_secret_opt("GITHUB_TOKEN"),
|
||||
github_webhook_secret: env_secret_opt("GITHUB_WEBHOOK_SECRET"),
|
||||
gitlab_url: env_var_opt("GITLAB_URL"),
|
||||
|
||||
@@ -98,7 +98,9 @@ pub async fn triage_repo_findings(
|
||||
// to decide.
|
||||
TriageOutcome::NeedsReview => {
|
||||
finding.status = FindingStatus::NeedsReview;
|
||||
finding.triage_action = Some("control_not_confirmed".to_string());
|
||||
finding.triage_action = Some(
|
||||
compliance_core::models::finding::TRIAGE_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."
|
||||
@@ -215,7 +217,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 = std::fs::read_to_string(repo_path.join(file)).ok()?;
|
||||
let content = compliance_core::encoding::read_source(&repo_path.join(file)).ok()?;
|
||||
let lines: Vec<&str> = content.lines().collect();
|
||||
if lines.is_empty() {
|
||||
return None;
|
||||
|
||||
@@ -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", "kt", "c", "h", "cc",
|
||||
"cpp", "hpp",
|
||||
"py", "js", "ts", "tsx", "jsx", "go", "java", "rb", "php", "rs", "cs", "vb", "kt", "c", "h",
|
||||
"cc", "cpp", "hpp",
|
||||
];
|
||||
/// Directories never worth walking.
|
||||
const SKIP_DIRS: &[&str] = &[
|
||||
@@ -156,7 +156,8 @@ pub fn retrieve(repo_path: &Path, terms: &[&str], excluded: &[String]) -> Vec<Ca
|
||||
if !meta.is_file() || meta.len() > MAX_FILE_BYTES {
|
||||
continue;
|
||||
}
|
||||
let Ok(content) = std::fs::read_to_string(path) else {
|
||||
// UTF-8, UTF-16 with a BOM, or Windows-1252; a binary is skipped.
|
||||
let Ok(content) = compliance_core::encoding::read_source(path) else {
|
||||
continue;
|
||||
};
|
||||
let rel = path
|
||||
@@ -286,6 +287,24 @@ 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()));
|
||||
|
||||
@@ -168,6 +168,20 @@ impl DatabasePool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask MongoDB whether it answers (`ping` on the `admin` database), for
|
||||
/// the health check.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The driver's error when the server cannot be reached or refuses.
|
||||
pub async fn ping(&self) -> Result<(), mongodb::error::Error> {
|
||||
self.client
|
||||
.database("admin")
|
||||
.run_command(doc! { "ping": 1 })
|
||||
.await
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
/// Raw client handle. Reserved for cross-tenant admin flows that
|
||||
/// must opt in explicitly (tenant listing, drop-on-offboard).
|
||||
pub fn client(&self) -> &Client {
|
||||
@@ -604,6 +618,19 @@ 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(())
|
||||
}
|
||||
@@ -771,6 +798,12 @@ 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)
|
||||
|
||||
@@ -42,6 +42,11 @@ pub enum AgentError {
|
||||
#[error("the archive password set on the target does not open it")]
|
||||
ArchivePasswordWrong,
|
||||
|
||||
/// A counted Prüfung the plan does not allow now (t72): not an error of
|
||||
/// the scan, which ends without scanning.
|
||||
#[error("not run: {0:?}")]
|
||||
NotAdmitted(compliance_core::models::Refusal),
|
||||
|
||||
#[error("{0}")]
|
||||
Other(String),
|
||||
}
|
||||
@@ -73,6 +78,7 @@ impl AgentError {
|
||||
| Self::Config(_)
|
||||
| Self::Secret(_)
|
||||
| Self::Exec(_)
|
||||
| Self::NotAdmitted(_)
|
||||
| Self::Other(_) => (
|
||||
RunErrorCode::Internal,
|
||||
"the scan stopped because of an internal error",
|
||||
|
||||
@@ -72,11 +72,12 @@ pub enum SbomCoverage {
|
||||
}
|
||||
|
||||
/// The tools that check a target's components rather than its code.
|
||||
const COMPONENT_TOOLS: [&str; 5] = [
|
||||
const COMPONENT_TOOLS: [&str; 6] = [
|
||||
"syft",
|
||||
"osv",
|
||||
"dotnet-lifecycle",
|
||||
"build-lifecycle",
|
||||
compliance_core::models::SBOM_COVERAGE_SCANNER,
|
||||
"yocto-release",
|
||||
];
|
||||
|
||||
@@ -513,6 +514,31 @@ 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");
|
||||
|
||||
@@ -531,7 +531,10 @@ mod tests {
|
||||
let (zip_bytes, listed) = build_pack(&inputs(), Utc::now()).expect("pack");
|
||||
let mut archive =
|
||||
zip::ZipArchive::new(std::io::Cursor::new(zip_bytes)).expect("a valid zip");
|
||||
let mut names: Vec<String> = archive.file_names().map(String::from).collect();
|
||||
let mut names: Vec<String> = archive
|
||||
.file_names()
|
||||
.map(|n| n.expect("a UTF-8 entry name").into_owned())
|
||||
.collect();
|
||||
names.sort();
|
||||
assert_eq!(
|
||||
names,
|
||||
|
||||
@@ -12,6 +12,9 @@ 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),
|
||||
}
|
||||
@@ -21,11 +24,40 @@ 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";
|
||||
|
||||
@@ -33,19 +65,16 @@ 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 match event {
|
||||
"repository" | "push" => SourceAction::Ignore("payload without a repository"),
|
||||
_ => SourceAction::Ignore("event not handled"),
|
||||
};
|
||||
return SourceAction::Ignore("payload without a repository");
|
||||
};
|
||||
if !matches!(event, "repository" | "push") {
|
||||
return SourceAction::Ignore("event not handled");
|
||||
}
|
||||
if !repo.in_org(org) {
|
||||
return SourceAction::Ignore("repository outside the configured organisation");
|
||||
}
|
||||
@@ -55,6 +84,7 @@ 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("");
|
||||
@@ -69,6 +99,41 @@ 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 {
|
||||
@@ -161,7 +226,7 @@ mod tests {
|
||||
);
|
||||
assert_eq!(
|
||||
route_event("issues", &json!({}), "kunde"),
|
||||
SourceAction::Ignore("event not handled")
|
||||
SourceAction::Ignore("payload without a repository")
|
||||
);
|
||||
assert_eq!(
|
||||
route_event("push", &json!({ "ref": "refs/heads/main" }), "kunde"),
|
||||
@@ -172,4 +237,80 @@ 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")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,10 @@ 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")
|
||||
@@ -454,6 +458,11 @@ 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),
|
||||
}
|
||||
@@ -495,6 +504,24 @@ 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),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -189,7 +189,10 @@ pub fn ingest_artifact(
|
||||
ArtifactKind::SourceArchive | ArtifactKind::MobilePackage | ArtifactKind::PlcProject => {
|
||||
ingest_blob(artifact, ctx, true)
|
||||
}
|
||||
ArtifactKind::FirmwareImage => ingest_blob(artifact, ctx, false),
|
||||
// Stored as uploaded: the SPDX reader opens the archive itself.
|
||||
ArtifactKind::FirmwareImage | ArtifactKind::BuildOutput => {
|
||||
ingest_blob(artifact, ctx, false)
|
||||
}
|
||||
ArtifactKind::ContainerImage => Ok(metadata_only(
|
||||
artifact,
|
||||
DetectedFact::new("container_ref", artifact.source_ref.as_str(), "ingest"),
|
||||
|
||||
@@ -17,6 +17,7 @@ pub mod ingest;
|
||||
pub mod license_conclusions;
|
||||
pub mod lifecycle;
|
||||
pub mod llm;
|
||||
pub mod metering;
|
||||
pub mod pentest;
|
||||
pub mod pipeline;
|
||||
pub mod rag;
|
||||
|
||||
@@ -43,14 +43,15 @@ struct OrphanRule {
|
||||
}
|
||||
|
||||
/// Code scans are what customers see, so they get their own `interrupted`
|
||||
/// status. The rest close as `failed` with [`INTERRUPTED_MESSAGE`]: DAST and
|
||||
/// 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
|
||||
/// 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: &["running"],
|
||||
open: &["queued", "running"],
|
||||
closed_as: "interrupted",
|
||||
},
|
||||
OrphanRule {
|
||||
@@ -218,12 +219,16 @@ 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 {
|
||||
@@ -243,12 +248,25 @@ 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).
|
||||
let trigger = db
|
||||
// nothing changed since the last completed one (#465). Of a running
|
||||
// scan and its queued follow-up, a person's wins.
|
||||
let triggers = db
|
||||
.scan_runs()
|
||||
.find_one(doc! { "repo_id": id, "status": "interrupted", "completed_at": closed })
|
||||
.await?
|
||||
.map_or(ScanTrigger::Scheduled, |run| run.trigger);
|
||||
.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);
|
||||
out.push((id.to_string(), trigger));
|
||||
}
|
||||
}
|
||||
@@ -365,10 +383,11 @@ 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 scan to resume was started by a person.
|
||||
// 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.
|
||||
for (id, trigger) in [
|
||||
(&resumes, ScanTrigger::Manual),
|
||||
(&resumes, ScanTrigger::Scheduled),
|
||||
(&looping, ScanTrigger::Scheduled),
|
||||
(&archived, ScanTrigger::Scheduled),
|
||||
] {
|
||||
@@ -377,6 +396,10 @@ 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;
|
||||
@@ -423,6 +446,16 @@ 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
|
||||
|
||||
@@ -19,20 +19,22 @@ impl LlmClient {
|
||||
model: String,
|
||||
embed_model: String,
|
||||
) -> Self {
|
||||
let http = reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(300))
|
||||
.connect_timeout(std::time::Duration::from_secs(10))
|
||||
.build()
|
||||
.unwrap_or_default();
|
||||
Self {
|
||||
base_url,
|
||||
api_key,
|
||||
model,
|
||||
embed_model,
|
||||
http,
|
||||
http: http_client(DEFAULT_TIMEOUT),
|
||||
}
|
||||
}
|
||||
|
||||
/// The same client with `timeout` for each call in total (connecting, the
|
||||
/// gateway's queue and the answer).
|
||||
pub fn with_timeout(mut self, timeout: std::time::Duration) -> Self {
|
||||
self.http = http_client(timeout);
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn chat_url(&self) -> String {
|
||||
format!(
|
||||
"{}/v1/chat/completions",
|
||||
@@ -255,6 +257,9 @@ impl LlmClient {
|
||||
&self,
|
||||
request_body: &B,
|
||||
) -> Result<(LlmResponse, Option<String>), AgentError> {
|
||||
if self.model.is_empty() {
|
||||
return Err(AgentError::Other(NO_CHAT_MODEL.to_string()));
|
||||
}
|
||||
let mut req = self
|
||||
.http
|
||||
.post(self.chat_url())
|
||||
@@ -319,6 +324,9 @@ impl LlmClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// The error when no chat model is configured: the request is not sent.
|
||||
pub(crate) const NO_CHAT_MODEL: &str = "LLM off: LITELLM_MODEL is not set";
|
||||
|
||||
/// A text answer, and whether the model stopped at its token budget.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ChatAnswer {
|
||||
@@ -332,6 +340,18 @@ pub struct ChatAnswer {
|
||||
/// model was still reasoning.
|
||||
const REASONING_RETRY_TOKENS: u32 = 16384;
|
||||
|
||||
/// Total time per LLM call unless the deployment sets one (`LLM_TIMEOUT_SECS`):
|
||||
/// our LiteLLM gateway's own request timeout.
|
||||
const DEFAULT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600);
|
||||
|
||||
fn http_client(timeout: std::time::Duration) -> reqwest::Client {
|
||||
reqwest::Client::builder()
|
||||
.timeout(timeout)
|
||||
.connect_timeout(std::time::Duration::from_secs(10))
|
||||
.build()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The error when the model gave no answer even with
|
||||
/// [`REASONING_RETRY_TOKENS`].
|
||||
const REASONING_EXHAUSTED: &str =
|
||||
@@ -448,6 +468,19 @@ mod budget_tests {
|
||||
assert_eq!(seen.lock().unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn no_chat_model_makes_no_request() {
|
||||
let seen: Seen = Arc::default();
|
||||
let mut llm = client(fake_gateway(seen.clone(), 0).await);
|
||||
llm.model = String::new();
|
||||
let err = llm.chat("s", "u", None).await.unwrap_err();
|
||||
assert_eq!(err.to_string(), NO_CHAT_MODEL);
|
||||
assert!(
|
||||
seen.lock().unwrap().is_empty(),
|
||||
"no request may reach the gateway"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_answer_in_budget_is_one_request() {
|
||||
let seen: Seen = Arc::default();
|
||||
|
||||
@@ -29,6 +29,53 @@ const EMBED_BATCH_SIZE: usize = 16;
|
||||
// The bge backend takes at most 25 inputs per request.
|
||||
const _: () = assert!(EMBED_BATCH_SIZE <= 25);
|
||||
|
||||
/// Token budget of one embedding request. bge-multilingual-gemma2 takes 8192
|
||||
/// tokens; on prod a batch of 16 code chunks came to ~51k and was refused, so a
|
||||
/// request now carries only as many inputs as fit, and one input never more.
|
||||
const EMBED_MAX_REQUEST_TOKENS: usize = 7000;
|
||||
|
||||
/// Conservative bytes per token: code tokenizes denser than prose (the chunker's
|
||||
/// own estimate of 4 chars per token undercounts it).
|
||||
const EMBED_BYTES_PER_TOKEN: usize = 3;
|
||||
|
||||
fn estimated_tokens(text: &str) -> usize {
|
||||
text.len().div_ceil(EMBED_BYTES_PER_TOKEN)
|
||||
}
|
||||
|
||||
/// Shorten `text` (at a char boundary) so it fits a request on its own. The
|
||||
/// head of a chunk carries its context header and signature, which is what
|
||||
/// retrieval needs.
|
||||
fn fit_text(mut text: String) -> String {
|
||||
let max_bytes = EMBED_MAX_REQUEST_TOKENS * EMBED_BYTES_PER_TOKEN;
|
||||
if text.len() > max_bytes {
|
||||
let mut cut = max_bytes;
|
||||
while !text.is_char_boundary(cut) {
|
||||
cut -= 1;
|
||||
}
|
||||
text.truncate(cut);
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// Split `texts` into consecutive batches of at most [`EMBED_BATCH_SIZE`]
|
||||
/// inputs and [`EMBED_MAX_REQUEST_TOKENS`] estimated tokens, keeping order.
|
||||
fn plan_batches(texts: &[String]) -> Vec<std::ops::Range<usize>> {
|
||||
let mut out = Vec::new();
|
||||
let (mut start, mut tokens) = (0, 0);
|
||||
for (i, t) in texts.iter().enumerate() {
|
||||
let n = estimated_tokens(t);
|
||||
if i > start && (i - start == EMBED_BATCH_SIZE || tokens + n > EMBED_MAX_REQUEST_TOKENS) {
|
||||
out.push(start..i);
|
||||
(start, tokens) = (i, 0);
|
||||
}
|
||||
tokens += n;
|
||||
}
|
||||
if start < texts.len() {
|
||||
out.push(start..texts.len());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ── Embedding implementation ───────────────────────────────────
|
||||
|
||||
impl LlmClient {
|
||||
@@ -37,20 +84,26 @@ impl LlmClient {
|
||||
}
|
||||
|
||||
/// Generate embeddings for a batch of texts, chunking into backend-sized
|
||||
/// requests and preserving input order across chunks.
|
||||
/// requests (input count and token budget) and preserving input order.
|
||||
pub async fn embed(&self, texts: Vec<String>) -> Result<Vec<Vec<f64>>, AgentError> {
|
||||
if texts.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let texts: Vec<String> = texts.into_iter().map(fit_text).collect();
|
||||
let mut out = Vec::with_capacity(texts.len());
|
||||
for chunk in texts.chunks(EMBED_BATCH_SIZE) {
|
||||
out.extend(self.embed_batch(chunk.to_vec()).await?);
|
||||
for range in plan_batches(&texts) {
|
||||
out.extend(self.embed_batch(texts[range].to_vec()).await?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Embed one backend-sized batch (≤ [`EMBED_BATCH_SIZE`]) in a single request.
|
||||
async fn embed_batch(&self, texts: Vec<String>) -> Result<Vec<Vec<f64>>, AgentError> {
|
||||
if self.embed_model.is_empty() {
|
||||
return Err(AgentError::Other(
|
||||
"embeddings off: LITELLM_EMBED_MODEL is not set".to_string(),
|
||||
));
|
||||
}
|
||||
let url = format!("{}/v1/embeddings", self.base_url.trim_end_matches('/'));
|
||||
|
||||
let request_body = EmbeddingRequest {
|
||||
@@ -113,4 +166,39 @@ mod tests {
|
||||
let out = client().embed(Vec::new()).await.unwrap();
|
||||
assert!(out.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batches_respect_count_and_token_budget() {
|
||||
// 40 short texts: count-bound, 16 + 16 + 8
|
||||
let short: Vec<String> = (0..40).map(|i| format!("fn f{i}() {{}}")).collect();
|
||||
let b = plan_batches(&short);
|
||||
assert_eq!(b, vec![0..16, 16..32, 32..40]);
|
||||
|
||||
// 8 KiB code chunks (~2731 tokens each): two per request, never three
|
||||
let big: Vec<String> = (0..5).map(|_| "x".repeat(8192)).collect();
|
||||
let b = plan_batches(&big);
|
||||
assert_eq!(b, vec![0..2, 2..4, 4..5]);
|
||||
for r in &b {
|
||||
let tokens: usize = big[r.clone()].iter().map(|t| estimated_tokens(t)).sum();
|
||||
assert!(tokens <= EMBED_MAX_REQUEST_TOKENS, "{r:?}: {tokens}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_text_is_cut_to_fit_alone_at_a_char_boundary() {
|
||||
let long = "ä".repeat(30_000); // 60 000 bytes, 2 bytes per char
|
||||
let cut = fit_text(long);
|
||||
assert!(estimated_tokens(&cut) <= EMBED_MAX_REQUEST_TOKENS);
|
||||
assert!(cut.chars().all(|c| c == 'ä'));
|
||||
assert_eq!(plan_batches(&[cut.clone(), "y".into()]), vec![0..1, 1..2]);
|
||||
assert_eq!(fit_text("short".into()), "short");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn no_embed_model_makes_no_request() {
|
||||
let mut llm = client();
|
||||
llm.embed_model = String::new();
|
||||
let err = llm.embed(vec!["x".into()]).await.unwrap_err();
|
||||
assert!(err.to_string().contains("LITELLM_EMBED_MODEL"), "{err}");
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
|
||||
use compliance_core::models::{Exploitation, Finding, FindingStatus, Severity};
|
||||
use compliance_core::models::{Exploitation, Finding, FindingStatus, ReviewReason, Severity};
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use serde_json::Value;
|
||||
|
||||
@@ -65,12 +65,14 @@ Respond with a JSON array, one entry per finding (no markdown fences). "id" is t
|
||||
const TRIAGE_MAX_FINDINGS: usize = 600;
|
||||
/// Triage calls in flight at once.
|
||||
const TRIAGE_CONCURRENCY: usize = 4;
|
||||
/// Calls in flight that must all fail before the model is taken as down.
|
||||
const MODEL_DOWN_AFTER: usize = 2;
|
||||
/// How much of an unreadable model answer goes to the debug log.
|
||||
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 = "skipped";
|
||||
pub const SKIPPED_ACTION: &str = compliance_core::models::finding::TRIAGE_SKIPPED;
|
||||
|
||||
/// The model the triage asks. A trait so tests can drive the triage with a
|
||||
/// fake model.
|
||||
@@ -492,10 +494,13 @@ async fn ask_in_chunks<M: TriageModel>(
|
||||
.map(|chunk| triage_chunk(model, findings, chunk, graph_context, exploitation)),
|
||||
)
|
||||
.await;
|
||||
// Every call at once failed: the model is down (or hangs until the
|
||||
// client's timeout), not cutting answers short. Asking about the
|
||||
// rest, chunk by chunk and then one by one, would only take hours.
|
||||
if answers.iter().all(Result::is_err) {
|
||||
// Several calls at once all failed: the model is down (or hangs until
|
||||
// the client's timeout), not cutting answers short. Asking about the
|
||||
// rest, chunk by chunk and then one by one, would only take hours. A
|
||||
// single failed call proves nothing (one slow answer under load), so
|
||||
// the next try still runs: in a small scan the one-by-one try for the
|
||||
// critical and high findings is all that gets them a verdict.
|
||||
if group.len() >= MODEL_DOWN_AFTER && answers.iter().all(Result::is_err) {
|
||||
return (answered, Some(ModelDown));
|
||||
}
|
||||
answered.extend(answers.into_iter().flatten().flatten());
|
||||
@@ -514,8 +519,9 @@ const TRIES: [(usize, Severity); 3] = [
|
||||
];
|
||||
|
||||
/// Ask the model about every finding at `sent`, and again by id about those it
|
||||
/// gave no verdict (see [`TRIES`]). Once every call in flight fails at once,
|
||||
/// the model is taken as down and nothing more is asked.
|
||||
/// gave no verdict (see [`TRIES`]). Once several calls in flight fail at once
|
||||
/// ([`MODEL_DOWN_AFTER`]), the model is taken as down and nothing more is
|
||||
/// asked.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
@@ -817,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;
|
||||
@@ -833,29 +839,31 @@ fn apply_action(finding: &mut Finding, action: &str, adjusted_confidence: f64) -
|
||||
finding.status = FindingStatus::Triaged;
|
||||
Outcome::Upgraded
|
||||
}
|
||||
// "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
|
||||
}
|
||||
// "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
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 = std::fs::read_to_string(file_path).ok()?;
|
||||
let content = compliance_core::encoding::read_source(std::path::Path::new(file_path)).ok()?;
|
||||
let lines: Vec<&str> = content.lines().collect();
|
||||
|
||||
let start = line.saturating_sub(25);
|
||||
@@ -1098,6 +1106,51 @@ 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();
|
||||
@@ -1491,6 +1544,18 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Fails the first `failures` calls (a timeout), then answers as
|
||||
/// [`Self::scripted`].
|
||||
fn failing_first(failures: usize, answers: &[&str]) -> Self {
|
||||
let model = Self::scripted(answers);
|
||||
model
|
||||
.script
|
||||
.lock()
|
||||
.unwrap()
|
||||
.extend((0..failures).map(|_| Err("operation timed out".to_string())));
|
||||
model
|
||||
}
|
||||
|
||||
fn confirming() -> Self {
|
||||
Self {
|
||||
confirm_all: true,
|
||||
@@ -1618,17 +1683,43 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_model_that_is_down_skips_but_keeps_every_finding() {
|
||||
let mut findings: Vec<Finding> = (1..=3).map(|n| numbered(n, Severity::Critical)).collect();
|
||||
let mut findings: Vec<Finding> =
|
||||
(1..=15).map(|n| numbered(n, Severity::Critical)).collect();
|
||||
let model = FakeModel::scripted(&[]);
|
||||
let summary = triage_findings(&model, &mut findings, None, None).await;
|
||||
assert_eq!(findings.len(), 3);
|
||||
assert_eq!(findings.len(), 15);
|
||||
assert!(findings
|
||||
.iter()
|
||||
.all(|f| f.triage_action.as_deref() == Some(SKIPPED_ACTION)
|
||||
&& f.status == FindingStatus::Open));
|
||||
assert_eq!(summary.skipped_no_answer_severe, 3);
|
||||
// The first call fails: the model is down, nothing is asked again.
|
||||
assert_eq!(summary.calls, 1);
|
||||
assert_eq!(summary.skipped_no_answer_severe, 15);
|
||||
// Both calls of the first try fail: the model is down, nothing is
|
||||
// asked again.
|
||||
assert_eq!(summary.calls, 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn one_failed_call_still_asks_the_severe_findings_one_by_one() {
|
||||
// A small scan: the first try is one call, and it times out.
|
||||
let mut findings: Vec<Finding> = vec![
|
||||
numbered(1, Severity::Critical),
|
||||
numbered(2, Severity::Medium),
|
||||
numbered(3, Severity::Medium),
|
||||
];
|
||||
// The second try (one call again) fails as well; the critical one,
|
||||
// asked on its own, is answered.
|
||||
let model = FakeModel::failing_first(
|
||||
2,
|
||||
&[r#"{"id":1,"action":"confirm","confidence":9,"rationale":"reachable"}"#],
|
||||
);
|
||||
let summary = triage_findings(&model, &mut findings, None, None).await;
|
||||
|
||||
let asked = model.asked();
|
||||
assert_eq!(asked.len(), 3);
|
||||
assert_eq!(asked[2], ["finding 1"]);
|
||||
assert_eq!(findings[0].triage_action.as_deref(), Some("confirm"));
|
||||
assert_eq!(summary.skipped_no_answer, 2);
|
||||
assert_eq!(summary.skipped_no_answer_severe, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1644,7 +1735,9 @@ mod tests {
|
||||
// The first four chunks are answered, then the model is gone.
|
||||
let model = FakeModel::scripted(&[&full, &full, &full, &full]);
|
||||
let summary = triage_findings(&model, &mut findings, None, None).await;
|
||||
assert_eq!(summary.calls, 5);
|
||||
// The fifth call fails alone, so the five are asked once more (one
|
||||
// call); the last try is for critical and high findings only.
|
||||
assert_eq!(summary.calls, 6);
|
||||
assert_eq!(summary.confirmed, 40);
|
||||
assert_eq!(summary.skipped_no_answer, 5);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,535 @@
|
||||
//! Metering of a tenant's Prüfungen (t72).
|
||||
//!
|
||||
//! **Included and extra targets.** The oldest active targets are included,
|
||||
//! up to the plan's `included_targets`; every other active target is extra.
|
||||
//! The split is stored on each target ([`OnboardedTarget::billing`]) and
|
||||
//! brought up to date before each scan and when a target is created, so
|
||||
//! archiving an included target moves the oldest extra one up.
|
||||
//!
|
||||
//! **Counters.** A counted Prüfung is checked against the plan when it
|
||||
//! starts ([`usage`] and [`compliance_core::models::admit`]) and charged
|
||||
//! when it completes ([`charge`]): to the month's quota, else to the
|
||||
//! target's Prüftag for the day, booking one if none is. Months and days
|
||||
//! are calendar ones in Europe/Berlin. A run that fails because of us is
|
||||
//! never charged, so nothing is refunded.
|
||||
//!
|
||||
//! [`OnboardedTarget::billing`]: compliance_core::models::OnboardedTarget::billing
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
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,
|
||||
};
|
||||
|
||||
use crate::database::Database;
|
||||
use crate::error::AgentError;
|
||||
|
||||
/// Store the billing of the tenant's active targets for a plan that
|
||||
/// includes `included` targets.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `db` - The tenant's database.
|
||||
/// * `included` - How many targets the plan includes; `None` is unlimited.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The targets whose billing changed, with their new billing.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the targets cannot be read or updated.
|
||||
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.
|
||||
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 })
|
||||
.await?
|
||||
.try_collect()
|
||||
.await?;
|
||||
let targets: Vec<BillableTarget<ObjectId>> = docs.iter().filter_map(billable).collect();
|
||||
let changes = split_included(&targets, included);
|
||||
for wanted in [TargetBilling::Included, TargetBilling::Extra] {
|
||||
let ids: Vec<ObjectId> = changes
|
||||
.iter()
|
||||
.filter(|(_, billing)| *billing == wanted)
|
||||
.map(|(id, _)| *id)
|
||||
.collect();
|
||||
if ids.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let value =
|
||||
mongodb::bson::to_bson(&wanted).map_err(|e| AgentError::Other(e.to_string()))?;
|
||||
db.onboarded_targets()
|
||||
.update_many(
|
||||
doc! { "_id": { "$in": ids } },
|
||||
doc! { "$set": { "billing": value } },
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Ok(changes)
|
||||
}
|
||||
|
||||
/// A stored target as the split sees it; `None` without an id. A target
|
||||
/// without a creation time counts as the oldest, one without a billing as
|
||||
/// included (stored before metering).
|
||||
fn billable(target: &Document) -> Option<BillableTarget<ObjectId>> {
|
||||
Some(BillableTarget {
|
||||
id: target.get_object_id("_id").ok()?,
|
||||
created_at: target
|
||||
.get_datetime("created_at")
|
||||
.map_or(DateTime::<Utc>::MIN_UTC, |at| at.to_chrono()),
|
||||
billing: target
|
||||
.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 {
|
||||
/// How many targets the plan includes; `None` is unlimited.
|
||||
pub included_targets: Option<u32>,
|
||||
/// The quota and the customer's Prüftag cap.
|
||||
pub limits: PlanLimits,
|
||||
}
|
||||
|
||||
/// The tenant's counted Prüfungen and booked Prüftage per month.
|
||||
const MONTHS: &str = "metering_months";
|
||||
/// Each target's Prüftag per day, once the quota was used up.
|
||||
const DAYS: &str = "metering_days";
|
||||
|
||||
/// The calendar month and day of `at` in Europe/Berlin, as `YYYY-MM` and
|
||||
/// `YYYY-MM-DD`: the periods the contract counts in.
|
||||
pub fn berlin_period(at: DateTime<Utc>) -> (String, String) {
|
||||
let local = at.with_timezone(&chrono_tz::Europe::Berlin);
|
||||
(
|
||||
local.format("%Y-%m").to_string(),
|
||||
local.format("%Y-%m-%d").to_string(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The id of a target's counter for one day.
|
||||
fn day_id(target_id: &str, day: &str) -> String {
|
||||
format!("{target_id}:{day}")
|
||||
}
|
||||
|
||||
/// A stored counter as a `u32`; missing or negative reads as 0.
|
||||
fn count(document: Option<&Document>, field: &str) -> u32 {
|
||||
document
|
||||
.and_then(|d| d.get(field))
|
||||
.and_then(mongodb::bson::Bson::as_i64)
|
||||
.or_else(|| document.and_then(|d| d.get_i32(field).ok()).map(i64::from))
|
||||
.and_then(|n| u32::try_from(n).ok())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// What the tenant used this month and `target_id` today, at `at`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the counters cannot be read.
|
||||
pub async fn usage(
|
||||
db: &Database,
|
||||
target_id: &str,
|
||||
at: DateTime<Utc>,
|
||||
) -> Result<(MonthUsage, DayUsage), AgentError> {
|
||||
let (month, day) = berlin_period(at);
|
||||
let month_doc = db
|
||||
.raw_collection(MONTHS)
|
||||
.find_one(doc! { "_id": &month })
|
||||
.await?;
|
||||
let day_doc = db
|
||||
.raw_collection(DAYS)
|
||||
.find_one(doc! { "_id": day_id(target_id, &day) })
|
||||
.await?;
|
||||
Ok((
|
||||
MonthUsage {
|
||||
pruefungen: count(month_doc.as_ref(), "pruefungen"),
|
||||
prueftage: count(month_doc.as_ref(), "prueftage"),
|
||||
},
|
||||
DayUsage {
|
||||
prueftag_booked: day_doc
|
||||
.as_ref()
|
||||
.and_then(|d| d.get_bool("prueftag_booked").ok())
|
||||
.unwrap_or(false),
|
||||
prueftag_pruefungen: count(day_doc.as_ref(), "prueftag_pruefungen"),
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// What [`charge`] charged a completed Prüfung to.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Charged {
|
||||
/// The quota or the target's Prüftag.
|
||||
pub charge: RunCharge,
|
||||
/// The Berlin day (`YYYY-MM-DD`) of a Prüftag this Prüfung booked; it
|
||||
/// goes to the registry as `prueftag.booked`.
|
||||
pub booked_prueftag: Option<String>,
|
||||
}
|
||||
|
||||
/// Charge one completed, counted Prüfung on `target_id` at `at`: to the
|
||||
/// month's quota while it lasts, else to the target's Prüftag that day,
|
||||
/// booking it if none is. The start of the run checked the limits, so this
|
||||
/// never refuses; scans of several targets finishing at once can take the
|
||||
/// quota or a Prüftag over by the ones that raced.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the counters cannot be written.
|
||||
pub async fn charge(
|
||||
db: &Database,
|
||||
target_id: &str,
|
||||
limits: PlanLimits,
|
||||
at: DateTime<Utc>,
|
||||
) -> Result<Charged, AgentError> {
|
||||
let (month, day) = berlin_period(at);
|
||||
let months = db.raw_collection(MONTHS);
|
||||
months
|
||||
.update_one(
|
||||
doc! { "_id": &month },
|
||||
doc! { "$setOnInsert": { "pruefungen": 0_i64, "prueftage": 0_i64 } },
|
||||
)
|
||||
.upsert(true)
|
||||
.await?;
|
||||
let quota_filter = match limits.monthly_pruefungen {
|
||||
// `$not $gte` also matches a month document without the counter.
|
||||
Some(quota) => doc! {
|
||||
"_id": &month,
|
||||
"pruefungen": { "$not": { "$gte": i64::from(quota) } },
|
||||
},
|
||||
None => doc! { "_id": &month },
|
||||
};
|
||||
let in_quota = months
|
||||
.update_one(quota_filter, doc! { "$inc": { "pruefungen": 1_i64 } })
|
||||
.await?;
|
||||
if in_quota.matched_count == 1 {
|
||||
return Ok(Charged {
|
||||
charge: RunCharge::Quota,
|
||||
booked_prueftag: None,
|
||||
});
|
||||
}
|
||||
|
||||
let days = db.raw_collection(DAYS);
|
||||
let id = day_id(target_id, &day);
|
||||
days.update_one(
|
||||
doc! { "_id": &id },
|
||||
doc! { "$setOnInsert": {
|
||||
"target_id": target_id,
|
||||
"day": &day,
|
||||
"month": &month,
|
||||
"prueftag_booked": false,
|
||||
"prueftag_pruefungen": 0_i64,
|
||||
} },
|
||||
)
|
||||
.upsert(true)
|
||||
.await?;
|
||||
let booked = days
|
||||
.update_one(
|
||||
doc! { "_id": &id, "prueftag_booked": false },
|
||||
doc! { "$set": { "prueftag_booked": true, "prueftag_pruefungen": 1_i64 } },
|
||||
)
|
||||
.await?;
|
||||
if booked.matched_count == 1 {
|
||||
months
|
||||
.update_one(
|
||||
doc! { "_id": &month },
|
||||
doc! { "$inc": { "prueftage": 1_i64 } },
|
||||
)
|
||||
.await?;
|
||||
return Ok(Charged {
|
||||
charge: RunCharge::Prueftag,
|
||||
booked_prueftag: Some(day),
|
||||
});
|
||||
}
|
||||
days.update_one(
|
||||
doc! { "_id": &id },
|
||||
doc! { "$inc": { "prueftag_pruefungen": 1_i64 } },
|
||||
)
|
||||
.await?;
|
||||
Ok(Charged {
|
||||
charge: RunCharge::Prueftag,
|
||||
booked_prueftag: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Record how many of the tenant's active targets are extra at `at`, as
|
||||
/// the month's peak (t72): the 5,99 € line bills the highest number of
|
||||
/// extra targets at once in the calendar month (Europe/Berlin).
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The month's peak when it goes to the registry as `target.extra`: when it
|
||||
/// rose, and once a day besides (a re-send the registry drops as a
|
||||
/// duplicate of its key). `None` otherwise, and while no target was extra.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the targets or the month's counters cannot be read
|
||||
/// or written.
|
||||
pub async fn record_extra_peak(
|
||||
db: &Database,
|
||||
at: DateTime<Utc>,
|
||||
) -> Result<Option<u32>, AgentError> {
|
||||
let extra = mongodb::bson::to_bson(&TargetBilling::Extra)
|
||||
.map_err(|e| AgentError::Other(e.to_string()))?;
|
||||
let now = db
|
||||
.onboarded_targets()
|
||||
.count_documents(doc! { "archived_at": null, "billing": extra })
|
||||
.await?;
|
||||
let now = u32::try_from(now).unwrap_or(u32::MAX);
|
||||
let (month, day) = berlin_period(at);
|
||||
let months = db.raw_collection(MONTHS);
|
||||
// The document before the update: the peak and the day it was last sent.
|
||||
let before = months
|
||||
.find_one_and_update(
|
||||
doc! { "_id": &month },
|
||||
doc! {
|
||||
"$max": { "extra_peak": i64::from(now) },
|
||||
"$setOnInsert": { "pruefungen": 0_i64, "prueftage": 0_i64 },
|
||||
},
|
||||
)
|
||||
.upsert(true)
|
||||
.await?;
|
||||
let previous = count(before.as_ref(), "extra_peak");
|
||||
let sent_on = before
|
||||
.as_ref()
|
||||
.and_then(|d| d.get_str("extra_sent_on").ok());
|
||||
let peak = previous.max(now);
|
||||
if peak == 0 || (peak == previous && sent_on == Some(day.as_str())) {
|
||||
return Ok(None);
|
||||
}
|
||||
months
|
||||
.update_one(
|
||||
doc! { "_id": &month },
|
||||
doc! { "$set": { "extra_sent_on": &day } },
|
||||
)
|
||||
.await?;
|
||||
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| {
|
||||
Utc.with_ymd_and_hms(y, m, d, h, min, 0)
|
||||
.single()
|
||||
.expect("valid")
|
||||
};
|
||||
|
||||
// 23:30 UTC on 31 Oct is already 1 Nov in Berlin (CET, UTC+1).
|
||||
assert_eq!(
|
||||
berlin_period(at(2026, 10, 31, 23, 30)),
|
||||
("2026-11".to_string(), "2026-11-01".to_string())
|
||||
);
|
||||
// In summer (CEST, UTC+2) the day turns at 22:00 UTC.
|
||||
assert_eq!(berlin_period(at(2026, 7, 14, 21, 59)).1, "2026-07-14");
|
||||
assert_eq!(berlin_period(at(2026, 7, 14, 22, 0)).1, "2026-07-15");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_counter_reads_as_zero_when_missing() {
|
||||
let stored = doc! { "pruefungen": 7_i64, "small": 3_i32, "negative": -1_i64 };
|
||||
assert_eq!(count(Some(&stored), "pruefungen"), 7);
|
||||
assert_eq!(count(Some(&stored), "small"), 3);
|
||||
assert_eq!(count(Some(&stored), "negative"), 0);
|
||||
assert_eq!(count(Some(&stored), "absent"), 0);
|
||||
assert_eq!(count(None, "pruefungen"), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stored_target_reads_with_defaults_for_what_it_lacks() {
|
||||
// Arrange
|
||||
let id = ObjectId::new();
|
||||
let at = mongodb::bson::DateTime::from_millis(1_700_000_000_000);
|
||||
let extra = doc! { "_id": id, "created_at": at, "billing": "extra" };
|
||||
let old = doc! { "_id": id };
|
||||
|
||||
// Act
|
||||
let extra = billable(&extra);
|
||||
let old = billable(&old);
|
||||
|
||||
// Assert
|
||||
assert_eq!(
|
||||
extra,
|
||||
Some(BillableTarget {
|
||||
id,
|
||||
created_at: at.to_chrono(),
|
||||
billing: TargetBilling::Extra,
|
||||
choice: None,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
old,
|
||||
Some(BillableTarget {
|
||||
id,
|
||||
created_at: DateTime::<Utc>::MIN_UTC,
|
||||
billing: TargetBilling::Included,
|
||||
choice: None,
|
||||
})
|
||||
);
|
||||
assert_eq!(billable(&doc! { "name": "no id" }), None);
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,22 @@ pub fn uploads_allow_git_skip(target: &OnboardedTarget) -> bool {
|
||||
upload_skip_enabled() && uploads_match(target)
|
||||
}
|
||||
|
||||
/// Whether a file uploaded to `target` changed since its last completed
|
||||
/// scan: it has uploads, and they are not the ones that scan read. For
|
||||
/// metering (t72), independent of [`upload_skip_enabled`].
|
||||
pub fn uploads_changed(target: &OnboardedTarget) -> bool {
|
||||
target.artifacts.iter().any(is_upload) && !uploads_match(target)
|
||||
}
|
||||
|
||||
/// Whether the customer changed what `target`, which has no git repository,
|
||||
/// gives a scan to read since its last completed one: it was never scanned,
|
||||
/// its uploads changed, or it has a live URL (the service changes on its
|
||||
/// own). A scheduled scan that runs without such a change is our own rescan
|
||||
/// (t72).
|
||||
pub fn content_changed(target: &OnboardedTarget) -> bool {
|
||||
target.live_url().is_some() || target.last_scan.is_none() || uploads_changed(target)
|
||||
}
|
||||
|
||||
/// Whether the uploads of `target` are the ones its last completed scan read.
|
||||
fn uploads_match(target: &OnboardedTarget) -> bool {
|
||||
target
|
||||
@@ -219,4 +235,31 @@ mod tests {
|
||||
let unhashed = target(vec![upload("a", None)]);
|
||||
assert_eq!(upload_inputs(&unhashed), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_change_the_customer_made_is_a_content_change() {
|
||||
// Arrange: a target scanned once, by an older build.
|
||||
let mut t = target(vec![upload("a", Some("h1"))]);
|
||||
assert!(content_changed(&t), "never scanned");
|
||||
t.last_scan = Some(LastScan {
|
||||
build: "0.0.1+old".into(),
|
||||
inputs: upload_inputs(&t),
|
||||
});
|
||||
|
||||
// Act / Assert: a new build alone is no change of the customer's.
|
||||
assert!(!content_changed(&t));
|
||||
assert!(!uploads_changed(&t));
|
||||
|
||||
t.artifacts[0].content_hash = Some("h2".into());
|
||||
assert!(content_changed(&t), "another upload");
|
||||
assert!(uploads_changed(&t));
|
||||
|
||||
let mut live = target(vec![Artifact::live_url("https://pump.example.com")]);
|
||||
live.last_scan = Some(LastScan {
|
||||
build: build_id(),
|
||||
inputs: None,
|
||||
});
|
||||
assert!(content_changed(&live), "a live service changes on its own");
|
||||
assert!(!uploads_changed(&live), "nothing uploaded");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
//! 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();
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,12 @@
|
||||
//! 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
|
||||
@@ -24,6 +30,7 @@ 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};
|
||||
|
||||
@@ -95,7 +102,12 @@ 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:{target_id}:{}:{}", alert.affected_package, alert.cve())
|
||||
format!(
|
||||
"{}{}:{}",
|
||||
cve_issue_prefix(target_id),
|
||||
alert.affected_package,
|
||||
alert.cve()
|
||||
)
|
||||
}
|
||||
|
||||
/// A severity as the `severity:` labels name it.
|
||||
@@ -163,7 +175,7 @@ pub(crate) async fn sync_cve_issues(
|
||||
alerts: &[CveAlert],
|
||||
complete: bool,
|
||||
) -> Result<CveIssueCounts, AgentError> {
|
||||
let prefix = format!("cve:{}:", target.target_id);
|
||||
let prefix = cve_issue_prefix(target.target_id);
|
||||
let mut existing: HashMap<String, TrackerIssue> = HashMap::new();
|
||||
let mut cursor = target
|
||||
.db
|
||||
@@ -189,7 +201,9 @@ pub(crate) async fn sync_cve_issues(
|
||||
.filter(|(_, a)| !a.is_resolved_by_vex() && issue_worthy(a, target.epss_percentile))
|
||||
{
|
||||
match existing.get(key) {
|
||||
Some(issue) if is_closed(&issue.status) => {
|
||||
// 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() => {
|
||||
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?;
|
||||
@@ -210,7 +224,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| !is_closed(&i.status))?;
|
||||
let issue = existing.get(key).filter(|i| !i.status.is_closed())?;
|
||||
Some((issue, vex))
|
||||
})
|
||||
.collect();
|
||||
@@ -218,7 +232,14 @@ pub(crate) async fn sync_cve_issues(
|
||||
|
||||
if complete {
|
||||
for (key, issue) in &existing {
|
||||
if present.contains_key(key) || is_closed(&issue.status) {
|
||||
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?;
|
||||
}
|
||||
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.";
|
||||
@@ -311,11 +332,6 @@ 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>> {
|
||||
@@ -498,12 +514,10 @@ async fn record(
|
||||
let Some(id) = issue.id else {
|
||||
return Ok(());
|
||||
};
|
||||
let status = mongodb::bson::to_bson(&status).map_err(|e| AgentError::Other(e.to_string()))?;
|
||||
let update = crate::pipeline::issue_sync::issue_state_update(&status, None)
|
||||
.map_err(|e| AgentError::Other(e.to_string()))?;
|
||||
db.tracker_issues()
|
||||
.update_one(
|
||||
doc! { "_id": id },
|
||||
doc! { "$set": { "status": status, "updated_at": mongodb::bson::DateTime::now() } },
|
||||
)
|
||||
.update_one(doc! { "_id": id }, update)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -784,7 +798,9 @@ mod tests {
|
||||
|
||||
// It comes back: reopened, not opened twice.
|
||||
assert_eq!(
|
||||
sync_cve_issues(&target, &[okhttp], true).await.unwrap(),
|
||||
sync_cve_issues(&target, std::slice::from_ref(&okhttp), true)
|
||||
.await
|
||||
.unwrap(),
|
||||
CveIssueCounts {
|
||||
reopened: 1,
|
||||
..Default::default()
|
||||
@@ -792,6 +808,46 @@ 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();
|
||||
}
|
||||
|
||||
|
||||
@@ -145,33 +145,15 @@ 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). `None` for a file too large or
|
||||
/// 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
|
||||
/// 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;
|
||||
}
|
||||
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(),
|
||||
}
|
||||
compliance_core::encoding::read_source(path).ok()
|
||||
}
|
||||
|
||||
/// Parse XML the way project and configuration files need: a DTD is allowed
|
||||
|
||||
@@ -147,7 +147,8 @@ 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
|
||||
.then(|| std::fs::read_to_string(entry.path()).ok())
|
||||
// Vendor SDK headers are often Windows-1252 (a "©" in the banner).
|
||||
.then(|| compliance_core::encoding::read_source(entry.path()).ok())
|
||||
.flatten()
|
||||
else {
|
||||
continue;
|
||||
|
||||
@@ -45,6 +45,13 @@ pub struct RunFindings {
|
||||
variants: AppVariants,
|
||||
/// The scanned tree: the flagged lines fingerprints are made of (#491).
|
||||
tree: Option<PathBuf>,
|
||||
/// The test-data directories left out of the scanned tree
|
||||
/// ([`crate::pipeline::test_data`]): a finding stored in one is closed as
|
||||
/// test data, not as fixed.
|
||||
test_data: Vec<String>,
|
||||
/// The paths the target's settings left out of the scanned tree: a
|
||||
/// finding stored in one is closed as excluded, not as fixed.
|
||||
excluded: Vec<String>,
|
||||
}
|
||||
|
||||
/// One place a group lists: scanner, rule, file, line.
|
||||
@@ -75,9 +82,25 @@ impl RunFindings {
|
||||
grouped: HashSet::new(),
|
||||
variants: AppVariants::default(),
|
||||
tree: None,
|
||||
test_data: Vec::new(),
|
||||
excluded: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Name the paths the target's settings left out of the tree, so the
|
||||
/// findings an earlier scan stored there close as excluded.
|
||||
pub fn with_excluded(mut self, paths: Vec<String>) -> Self {
|
||||
self.excluded = paths;
|
||||
self
|
||||
}
|
||||
|
||||
/// Name the test-data directories the scan left out of the tree, so the
|
||||
/// findings an earlier scan stored there close as test data.
|
||||
pub fn with_test_data(mut self, dirs: Vec<String>) -> Self {
|
||||
self.test_data = dirs;
|
||||
self
|
||||
}
|
||||
|
||||
/// Key the findings of this run by the content of the code they flag in
|
||||
/// the tree under `tree`, not by its line number (#491).
|
||||
pub fn with_tree(mut self, tree: PathBuf) -> Self {
|
||||
@@ -697,7 +720,8 @@ impl RunFindings {
|
||||
.await?
|
||||
.try_collect()
|
||||
.await?;
|
||||
let (mut fixed, mut vendored, mut grouped) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let (mut fixed, mut vendored, mut test_data, mut excluded, mut grouped) =
|
||||
(Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new());
|
||||
for row in &candidates {
|
||||
let (Ok(id), Ok(fingerprint)) = (row.get_object_id("_id"), row.get_str("fingerprint"))
|
||||
else {
|
||||
@@ -706,9 +730,13 @@ impl RunFindings {
|
||||
if self.inserted.contains_key(fingerprint) || self.earlier.contains(fingerprint) {
|
||||
continue;
|
||||
}
|
||||
let in_vendor = row
|
||||
.get_str("file_path")
|
||||
.is_ok_and(|file| crate::pipeline::vendor::in_vendor_dir(file, vendor));
|
||||
let file = row.get_str("file_path").ok();
|
||||
let in_vendor = file.is_some_and(|f| crate::pipeline::vendor::in_vendor_dir(f, vendor));
|
||||
// The same membership test as for the vendor directories.
|
||||
let in_test_data =
|
||||
file.is_some_and(|f| crate::pipeline::vendor::in_vendor_dir(f, &self.test_data));
|
||||
let in_excluded =
|
||||
file.is_some_and(|f| crate::pipeline::vendor::in_vendor_dir(f, &self.excluded));
|
||||
let completed = row
|
||||
.get_str("scanner")
|
||||
.is_ok_and(|scanner| self.completed.contains(scanner));
|
||||
@@ -716,6 +744,10 @@ impl RunFindings {
|
||||
grouped.push(id);
|
||||
} else if !completed {
|
||||
continue;
|
||||
} else if in_excluded {
|
||||
excluded.push(id);
|
||||
} else if in_test_data {
|
||||
test_data.push(id);
|
||||
} else if in_vendor {
|
||||
vendored.push(id);
|
||||
} else {
|
||||
@@ -725,18 +757,24 @@ impl RunFindings {
|
||||
for (ids, kind) in [
|
||||
(&fixed, ScanChangeKind::NoLongerFound),
|
||||
(&vendored, ScanChangeKind::NowVendorCode),
|
||||
(&test_data, ScanChangeKind::NowTestData),
|
||||
(&excluded, ScanChangeKind::NowExcluded),
|
||||
(&grouped, ScanChangeKind::Grouped),
|
||||
] {
|
||||
self.set_status(db, ids, &UNDECIDED, FindingStatus::Resolved, kind)
|
||||
.await?;
|
||||
}
|
||||
let closed =
|
||||
u32::try_from(fixed.len() + vendored.len() + grouped.len()).unwrap_or(u32::MAX);
|
||||
let closed = u32::try_from(
|
||||
fixed.len() + vendored.len() + test_data.len() + excluded.len() + grouped.len(),
|
||||
)
|
||||
.unwrap_or(u32::MAX);
|
||||
if closed > 0 {
|
||||
tracing::info!(
|
||||
scan_run_id = %self.scan_run_id,
|
||||
fixed = fixed.len(),
|
||||
vendored = vendored.len(),
|
||||
test_data = test_data.len(),
|
||||
excluded = excluded.len(),
|
||||
grouped = grouped.len(),
|
||||
"resolved findings the scan no longer reports"
|
||||
);
|
||||
@@ -744,6 +782,94 @@ impl RunFindings {
|
||||
Ok(closed)
|
||||
}
|
||||
|
||||
/// Close the undecided findings on target `target_id` whose file lies in
|
||||
/// the excluded paths or the test data this run left out
|
||||
/// ([`Self::with_excluded`], [`Self::with_test_data`]), each with its
|
||||
/// reason. Nothing is closed as fixed; only what was left out.
|
||||
///
|
||||
/// [`Self::resolve_missing`] only closes what a scanner that completed no
|
||||
/// longer reports. A scanner that did not run cannot close its findings in
|
||||
/// a left-out path, although nothing can see them any more: cppcheck runs
|
||||
/// only on a tree with C, so once a fixture held the tree's only C, its
|
||||
/// findings would stay open for good. This closes them, whichever scanner
|
||||
/// stored them. A finding this run reported again is kept.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `db` - the tenant database
|
||||
/// * `target_id` - the scanned target (`Finding::repo_id`)
|
||||
/// * `scanner` - only this scanner's findings (a stage that stores its
|
||||
/// findings without this object, the PLC analysis), or `None` for all
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// How many findings were closed.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// A database error.
|
||||
pub async fn resolve_left_out(
|
||||
&mut self,
|
||||
db: &Database,
|
||||
target_id: &str,
|
||||
scanner: Option<&str>,
|
||||
) -> Result<u32, AgentError> {
|
||||
if self.excluded.is_empty() && self.test_data.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
let mut filter = doc! {
|
||||
"repo_id": target_id,
|
||||
"status": { "$in": UNDECIDED.to_vec() },
|
||||
};
|
||||
if let Some(scanner) = scanner {
|
||||
filter.insert("scanner", scanner);
|
||||
}
|
||||
let rows: Vec<Document> = db
|
||||
.findings()
|
||||
.clone_with_type::<Document>()
|
||||
.find(filter)
|
||||
.projection(doc! { "fingerprint": 1, "file_path": 1 })
|
||||
.await?
|
||||
.try_collect()
|
||||
.await?;
|
||||
let (mut excluded, mut test_data) = (Vec::new(), Vec::new());
|
||||
for row in &rows {
|
||||
let (Ok(id), Ok(file)) = (row.get_object_id("_id"), row.get_str("file_path")) else {
|
||||
continue;
|
||||
};
|
||||
// Something in this run still reports it, so it is not left out:
|
||||
// closing it would only see it reopened by the next run.
|
||||
let reported = row
|
||||
.get_str("fingerprint")
|
||||
.is_ok_and(|fp| self.inserted.contains_key(fp) || self.earlier.contains(fp));
|
||||
if reported {
|
||||
continue;
|
||||
}
|
||||
if crate::pipeline::vendor::in_vendor_dir(file, &self.excluded) {
|
||||
excluded.push(id);
|
||||
} else if crate::pipeline::vendor::in_vendor_dir(file, &self.test_data) {
|
||||
test_data.push(id);
|
||||
}
|
||||
}
|
||||
self.set_status(
|
||||
db,
|
||||
&excluded,
|
||||
&UNDECIDED,
|
||||
FindingStatus::Resolved,
|
||||
ScanChangeKind::NowExcluded,
|
||||
)
|
||||
.await?;
|
||||
self.set_status(
|
||||
db,
|
||||
&test_data,
|
||||
&UNDECIDED,
|
||||
FindingStatus::Resolved,
|
||||
ScanChangeKind::NowTestData,
|
||||
)
|
||||
.await?;
|
||||
Ok(u32::try_from(excluded.len() + test_data.len()).unwrap_or(u32::MAX))
|
||||
}
|
||||
|
||||
/// Move the findings `ids` whose status is still one of `from` to `to`,
|
||||
/// with a history entry saying this run did it and why. The `from` guard
|
||||
/// leaves alone a finding a person changed in the meantime.
|
||||
@@ -847,7 +973,8 @@ fn content_fingerprints(tree: &Path, findings: &mut [Finding]) {
|
||||
continue;
|
||||
};
|
||||
let lines = files.entry(path.clone()).or_insert_with(|| {
|
||||
std::fs::read_to_string(tree.join(&path))
|
||||
// Decoded like the scanners read it: UTF-8, UTF-16, Windows-1252.
|
||||
compliance_core::encoding::read_source(&tree.join(&path))
|
||||
.ok()
|
||||
.map(|text| text.lines().map(normalised).collect())
|
||||
});
|
||||
@@ -1123,6 +1250,26 @@ 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()));
|
||||
|
||||
@@ -399,7 +399,14 @@ impl GitOps {
|
||||
let head_name = head_ref.name().unwrap_or("HEAD");
|
||||
|
||||
repo.reference(head_name, fetch_commit.id(), true, "fast-forward")?;
|
||||
repo.checkout_head(Some(git2::build::CheckoutBuilder::default().force()))?;
|
||||
// `recreate_missing`: a scan takes the test data out of its working
|
||||
// copy (`pipeline::test_data`); every fetch puts it back, so what is
|
||||
// left out always follows the current rules.
|
||||
repo.checkout_head(Some(
|
||||
git2::build::CheckoutBuilder::default()
|
||||
.force()
|
||||
.recreate_missing(true),
|
||||
))?;
|
||||
|
||||
tracing::info!("Fetched and fast-forwarded {}", repo_path.display());
|
||||
Ok(())
|
||||
@@ -488,7 +495,18 @@ impl GitOps {
|
||||
_ => "",
|
||||
};
|
||||
|
||||
let content = std::str::from_utf8(line.content()).unwrap_or("");
|
||||
// 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()
|
||||
}
|
||||
};
|
||||
diff_file.hunks.push_str(prefix);
|
||||
diff_file.hunks.push_str(content);
|
||||
|
||||
@@ -912,4 +930,38 @@ 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
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,28 +1,71 @@
|
||||
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;
|
||||
|
||||
/// 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 and compute impact analyses
|
||||
/// Build the code knowledge graph for a repo, store it in place of the
|
||||
/// previous one and compute the impact of each finding.
|
||||
pub(super) async fn build_code_graph(
|
||||
&self,
|
||||
repo_path: &std::path::Path,
|
||||
source: GraphSource<'_>,
|
||||
repo_id: &str,
|
||||
findings: &[Finding],
|
||||
) -> Result<GraphContext, AgentError> {
|
||||
let graph_build_id = uuid::Uuid::new_v4().to_string();
|
||||
let engine = compliance_graph::GraphEngine::new(50_000);
|
||||
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 (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
|
||||
/// 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 store = compliance_graph::graph::persistence::GraphStore::new(self.db.inner());
|
||||
store
|
||||
.delete_repo_graph(repo_id)
|
||||
@@ -42,7 +85,7 @@ impl PipelineOrchestrator {
|
||||
let impact = analyzer.analyze(
|
||||
repo_id,
|
||||
&finding.fingerprint,
|
||||
&graph_build_id,
|
||||
graph_build_id,
|
||||
file_path,
|
||||
finding.line_number,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,472 @@
|
||||
//! 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();
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,10 @@
|
||||
//! most [`MAX_NEW_ISSUES`] per scan, highest severity and oldest first. The
|
||||
//! rest wait for the next scans. Gitea only: it matches against the listing
|
||||
//! the scan made anyway; the other trackers would need a search per finding.
|
||||
//!
|
||||
//! A scheduled scan that change detection skips (no new commits) still runs
|
||||
//! the catch-up when findings are [`waiting`] for an issue, so a backlog
|
||||
//! does not wait for the next push.
|
||||
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
@@ -119,26 +123,50 @@ pub(super) async fn catch_up(
|
||||
Ok(run(sink, &candidates, index, mode).await)
|
||||
}
|
||||
|
||||
/// The target's open medium+ findings without an issue, as stored.
|
||||
async fn load_candidates(sink: &IssueSink<'_>) -> Result<Vec<Finding>, AgentError> {
|
||||
/// The target's open medium+ findings without an issue, as a query.
|
||||
fn candidate_filter(repo_id: &str) -> mongodb::bson::Document {
|
||||
let severities: Vec<String> = ISSUE_SEVERITIES.iter().map(Severity::to_string).collect();
|
||||
let statuses: Vec<String> = ISSUE_STATUSES.iter().map(ToString::to_string).collect();
|
||||
// `tracker_issue_url: null` matches a missing field too.
|
||||
doc! {
|
||||
"repo_id": repo_id,
|
||||
"tracker_issue_url": null,
|
||||
"severity": { "$in": severities },
|
||||
"status": { "$in": statuses },
|
||||
}
|
||||
}
|
||||
|
||||
/// The target's open medium+ findings without an issue, as stored.
|
||||
async fn load_candidates(sink: &IssueSink<'_>) -> Result<Vec<Finding>, AgentError> {
|
||||
let findings = sink
|
||||
.db
|
||||
.findings()
|
||||
.find(doc! {
|
||||
"repo_id": sink.repo_id,
|
||||
"tracker_issue_url": null,
|
||||
"severity": { "$in": severities },
|
||||
"status": { "$in": statuses },
|
||||
})
|
||||
.find(candidate_filter(sink.repo_id))
|
||||
.await?
|
||||
.try_collect()
|
||||
.await?;
|
||||
Ok(findings)
|
||||
}
|
||||
|
||||
/// Whether target `repo_id` has findings waiting for an issue: one query,
|
||||
/// so a skipped scan with nothing to catch up never lists the tracker.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The findings cannot be read.
|
||||
pub(super) async fn waiting(
|
||||
db: &crate::database::Database,
|
||||
repo_id: &str,
|
||||
) -> Result<bool, AgentError> {
|
||||
let one = db
|
||||
.findings()
|
||||
.clone_with_type::<mongodb::bson::Document>()
|
||||
.find_one(candidate_filter(repo_id))
|
||||
.projection(doc! { "_id": 1 })
|
||||
.await?;
|
||||
Ok(one.is_some())
|
||||
}
|
||||
|
||||
/// The findings that want an issue and have none, highest severity first,
|
||||
/// then oldest first.
|
||||
fn select(findings: Vec<Finding>) -> Vec<Finding> {
|
||||
@@ -270,6 +298,7 @@ mod tests {
|
||||
body: Some(format_issue_body(finding)),
|
||||
html_url: format!("https://gitea.invalid/o/r/issues/{number}"),
|
||||
state: "open".into(),
|
||||
user: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -515,6 +544,8 @@ mod tests {
|
||||
}
|
||||
};
|
||||
|
||||
assert!(waiting(&db, "target-1").await.unwrap());
|
||||
|
||||
// A dry run changes nothing.
|
||||
let dry = catch_up(&sink, &index, IssueCatchup::DryRun).await.unwrap();
|
||||
assert_eq!((dry.created.total(), dry.linked.total()), (1, 1));
|
||||
@@ -554,10 +585,12 @@ mod tests {
|
||||
.expect("the link is recorded for the status sync");
|
||||
assert_eq!(record.external_id, "7");
|
||||
|
||||
// The next scan finds nothing left to do.
|
||||
// The next scan finds nothing left to do, and a skipped one would
|
||||
// not even list the tracker.
|
||||
let again = catch_up(&sink, &index, IssueCatchup::On).await.unwrap();
|
||||
assert_eq!((again.created.total(), again.linked.total()), (0, 0));
|
||||
assert_eq!(posts(&seen), 1);
|
||||
assert!(!waiting(&db, "target-1").await.unwrap());
|
||||
pool.drop_tenant("issue-catchup").await.ok();
|
||||
}
|
||||
}
|
||||
@@ -160,6 +160,35 @@ impl PipelineOrchestrator {
|
||||
}
|
||||
}
|
||||
|
||||
impl PipelineOrchestrator {
|
||||
/// The issue catch-up for a scan that change detection skipped: without
|
||||
/// it, findings deferred by [`crate::pipeline::issue_catchup::MAX_NEW_ISSUES`]
|
||||
/// wait for the next push. Runs only with the catch-up on (or in dry
|
||||
/// run), on a Gitea tracker, and when findings are waiting for an issue,
|
||||
/// so an idle repository costs one query and no tracker request. A
|
||||
/// failure is logged; the skipped scan stays skipped.
|
||||
pub(super) async fn catch_up_unchanged(&self, repo: &RepoView, repo_id: &str) {
|
||||
if self.config.issue_catchup == IssueCatchup::Off {
|
||||
return;
|
||||
}
|
||||
let Some(TrackerDispatch::Gitea(_)) = self.build_tracker(repo) else {
|
||||
return;
|
||||
};
|
||||
match crate::pipeline::issue_catchup::waiting(&self.db, repo_id).await {
|
||||
Ok(true) => {}
|
||||
Ok(false) => return,
|
||||
Err(e) => {
|
||||
tracing::warn!("[{repo_id}] Issue catch-up check failed: {e}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
tracing::info!("[{repo_id}] Unchanged repository: issue catch-up only");
|
||||
if let Err(e) = self.create_tracker_issues(repo, repo_id, &[]).await {
|
||||
tracing::warn!("[{repo_id}] Issue catch-up failed: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What opening, reopening and closing a target's CVE issues needs: the
|
||||
/// tracker configuration, where tracker calls may connect, and the tenant's
|
||||
/// database. Shared by the scans and the CVE monitor.
|
||||
@@ -482,9 +511,14 @@ 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, self.repo_id) {
|
||||
if let Some(link) = finding_link(&self.dashboard, &finding_id) {
|
||||
body.push_str(&format!(
|
||||
"\n[Open in Prüfwerk / In Prüfwerk öffnen]({link})"
|
||||
));
|
||||
@@ -511,11 +545,7 @@ impl IssueSink<'_> {
|
||||
.await?
|
||||
}
|
||||
};
|
||||
issue.finding_id = finding
|
||||
.id
|
||||
.as_ref()
|
||||
.map(|id| id.to_hex())
|
||||
.unwrap_or_default();
|
||||
issue.finding_id = finding_id;
|
||||
self.record(finding, &issue).await;
|
||||
Ok(issue)
|
||||
}
|
||||
@@ -677,13 +707,18 @@ fn cra_requirements(control_refs: &[String]) -> Vec<String> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
/// 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> {
|
||||
let dashboard = dashboard.trim_end_matches('/');
|
||||
dashboard
|
||||
.starts_with("https://")
|
||||
.then(|| format!("{dashboard}/findings?target={target_id}"))
|
||||
(dashboard.starts_with("https://") && !finding_id.is_empty())
|
||||
.then(|| format!("{dashboard}/findings/{finding_id}"))
|
||||
}
|
||||
|
||||
/// The ids of `names` among the ensured labels; a name without an id is left
|
||||
@@ -784,6 +819,7 @@ mod tests {
|
||||
body: body.map(str::to_string),
|
||||
html_url: format!("https://gitea.invalid/o/r/issues/{number}"),
|
||||
state: "open".into(),
|
||||
user: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -895,13 +931,16 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn links_only_to_an_https_dashboard() {
|
||||
fn links_the_finding_page_of_an_https_dashboard() {
|
||||
let id = "6560a1b2c3d4e5f601234567";
|
||||
assert_eq!(
|
||||
finding_link("https://pruefwerk.breakpilot.com/", "t1").as_deref(),
|
||||
Some("https://pruefwerk.breakpilot.com/findings?target=t1")
|
||||
finding_link("https://pruefwerk.breakpilot.com/", id).as_deref(),
|
||||
Some("https://pruefwerk.breakpilot.com/findings/6560a1b2c3d4e5f601234567")
|
||||
);
|
||||
assert_eq!(finding_link("", "t1"), None);
|
||||
assert_eq!(finding_link("http://x", "t1"), None);
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,455 @@
|
||||
//! 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")
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -170,19 +170,40 @@ impl IssueSync {
|
||||
let Some(id) = issue.id else {
|
||||
return Ok(());
|
||||
};
|
||||
let status = mongodb::bson::to_bson(&status).map_err(|e| e.to_string())?;
|
||||
let update = issue_state_update(&status, None).map_err(|e| e.to_string())?;
|
||||
self.db
|
||||
.tracker_issues()
|
||||
.update_one(
|
||||
doc! { "_id": id },
|
||||
doc! { "$set": { "status": status, "updated_at": mongodb::bson::DateTime::now() } },
|
||||
)
|
||||
.update_one(doc! { "_id": id }, update)
|
||||
.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>>;
|
||||
@@ -235,6 +256,14 @@ fn comment(status: &FindingStatus, change: Option<&StatusChange>) -> String {
|
||||
"Die Datei gilt jetzt als Herstellercode und ist von den Befunden ausgenommen.",
|
||||
"The file now counts as vendor code, which is left out of the findings.",
|
||||
),
|
||||
(FindingStatus::Resolved, Some(ScanChangeKind::NowTestData)) => (
|
||||
"Die Datei liegt in Testdaten (z. B. fixtures/ oder testdata/), die von der Prüfung ausgenommen sind.",
|
||||
"The file lies in test data (such as fixtures/ or testdata/), which is left out of the scan.",
|
||||
),
|
||||
(FindingStatus::Resolved, Some(ScanChangeKind::NowExcluded)) => (
|
||||
"Die Datei liegt in einem Pfad, den die Einstellungen des Prüfobjekts von der Prüfung ausnehmen.",
|
||||
"The file lies in a path the target's settings leave out of the scan.",
|
||||
),
|
||||
(FindingStatus::Resolved, _) => (
|
||||
"In Prüfwerk als behoben markiert.",
|
||||
"Marked resolved in Prüfwerk.",
|
||||
@@ -484,6 +513,69 @@ 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();
|
||||
}
|
||||
|
||||
@@ -518,6 +610,20 @@ 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,6 +27,7 @@ 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",
|
||||
|
||||
@@ -258,8 +258,24 @@ struct Metadata {
|
||||
severity: String,
|
||||
}
|
||||
|
||||
/// Rule-id prefixes of mobsfscan's AndroidManifest rules.
|
||||
const MANIFEST_RULE_PREFIXES: &[&str] = &["android_manifest_", "android_task_hijacking"];
|
||||
|
||||
/// Whether a match of `rule` at `file` can be real: a manifest rule only
|
||||
/// applies to an `AndroidManifest.xml`. mobsfscan has reported one on another
|
||||
/// XML file of the tree (`copyright.xml:1`, beside the same finding on the
|
||||
/// real manifest), nondeterministically, in the nightly (#573).
|
||||
fn applies_to(rule: &str, file: &str) -> bool {
|
||||
let manifest_rule = MANIFEST_RULE_PREFIXES.iter().any(|p| rule.starts_with(p));
|
||||
!manifest_rule
|
||||
|| Path::new(file)
|
||||
.file_name()
|
||||
.is_some_and(|name| name.eq_ignore_ascii_case("AndroidManifest.xml"))
|
||||
}
|
||||
|
||||
impl Report {
|
||||
/// One finding per rule and location.
|
||||
/// One finding per rule and location; a manifest rule's match outside an
|
||||
/// `AndroidManifest.xml` is dropped ([`applies_to`]).
|
||||
fn findings(self, root: &Path, repo_id: &str) -> Vec<Finding> {
|
||||
self.results
|
||||
.into_iter()
|
||||
@@ -267,6 +283,7 @@ impl Report {
|
||||
result
|
||||
.files
|
||||
.iter()
|
||||
.filter(|m| applies_to(&rule, &m.file_path))
|
||||
.map(|m| finding(root, repo_id, &rule, &result.metadata, m))
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
@@ -475,6 +492,45 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_manifest_rule_counts_only_on_a_manifest() {
|
||||
assert!(applies_to(
|
||||
"android_manifest_missing_explicit_allow_backup",
|
||||
"/tree/app/src/main/AndroidManifest.xml"
|
||||
));
|
||||
assert!(!applies_to(
|
||||
"android_manifest_missing_explicit_allow_backup",
|
||||
"copyright.xml"
|
||||
));
|
||||
assert!(!applies_to(
|
||||
"android_task_hijacking2",
|
||||
"res/values/strings.xml"
|
||||
));
|
||||
// Code rules match wherever they match.
|
||||
assert!(applies_to("android_kotlin_logging", "app/src/Main.kt"));
|
||||
|
||||
let dir = tree(&[
|
||||
("app/src/main/AndroidManifest.xml", MANIFEST),
|
||||
("spotless/copyright.xml", "<!-- Copyright -->\n"),
|
||||
]);
|
||||
// The same manifest match, reported a second time on copyright.xml.
|
||||
let mut json: serde_json::Value = serde_json::from_str(&report(&dir.0)).expect("json");
|
||||
let files = json["results"]["android_manifest_debugging_enabled"]["files"]
|
||||
.as_array_mut()
|
||||
.expect("files");
|
||||
let mut stray = files[0].clone();
|
||||
stray["file_path"] = format!("{}/spotless/copyright.xml", dir.0.display()).into();
|
||||
files.push(stray);
|
||||
let json = json.to_string();
|
||||
let parsed: Report = serde_json::from_str(&json).expect("report");
|
||||
let findings = parsed.findings(&dir.0, "t");
|
||||
assert_eq!(findings.len(), 1);
|
||||
assert_eq!(
|
||||
findings[0].file_path.as_deref(),
|
||||
Some("app/src/main/AndroidManifest.xml")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_setting_key_is_read_only_from_a_comparison() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -5,6 +5,7 @@ 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;
|
||||
@@ -23,11 +24,13 @@ pub mod git;
|
||||
pub mod git_retry;
|
||||
pub mod git_submodules;
|
||||
pub mod gitleaks;
|
||||
mod graph_build;
|
||||
pub(crate) 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;
|
||||
@@ -47,11 +50,16 @@ pub mod sbom;
|
||||
pub mod sbom_quality;
|
||||
pub mod semgrep;
|
||||
pub mod source_text;
|
||||
pub mod test_data;
|
||||
pub mod tool_cmd;
|
||||
mod tracker_dispatch;
|
||||
pub(crate) mod unity_settings;
|
||||
pub mod variants;
|
||||
pub mod vendor;
|
||||
pub mod vex_lifecycle;
|
||||
pub mod yocto_build;
|
||||
pub mod yocto_cve_check;
|
||||
pub mod yocto_inventory;
|
||||
pub mod yocto_pins;
|
||||
pub mod yocto_spdx;
|
||||
pub mod yocto_spdx3;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -186,9 +186,17 @@ fn scan_with_patterns(
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
|
||||
let content = match std::fs::read_to_string(path) {
|
||||
Ok(c) => c,
|
||||
Err(_) => continue, // skip binary files
|
||||
// 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 relative_path = path
|
||||
@@ -386,8 +394,12 @@ mod tests {
|
||||
fn oauth_token_url_matches() {
|
||||
let scanner = OAuthPatternScanner::new();
|
||||
let pattern = &scanner.patterns[3]; // oauth-token-url
|
||||
assert!(pattern.pattern.is_match("access_token = build_url(query)"));
|
||||
assert!(pattern.pattern.is_match("bearer = url.param"));
|
||||
// Split, so this file's own line does not match the rule it tests
|
||||
// when Prüfwerk scans its own repository.
|
||||
assert!(pattern
|
||||
.pattern
|
||||
.is_match(concat!("access_", "token = build_url(query)")));
|
||||
assert!(pattern.pattern.is_match(concat!("bear", "er = url.param")));
|
||||
}
|
||||
|
||||
// --- Pattern rule file extension filtering ---
|
||||
@@ -413,4 +425,30 @@ 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));
|
||||
}
|
||||
}
|
||||
@@ -14,8 +14,96 @@ pub struct Pou {
|
||||
pub vars: Vec<VarDecl>,
|
||||
/// The statement body.
|
||||
pub body: Vec<Stmt>,
|
||||
/// 1-based line where the POU header appears (in the source that was parsed).
|
||||
/// 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.
|
||||
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)]
|
||||
@@ -191,6 +279,35 @@ 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 {
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
//! 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(""));
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,13 @@
|
||||
//! Parses Structured Text (raw `.st`/`.scl`/`.exp` files and PLCopen-XML
|
||||
//! projects) into an AST and runs semantic control-logic security rules over it.
|
||||
//! Implements [`ScanType::PlcControlLogic`].
|
||||
//!
|
||||
//! A CODESYS project in its native format (the binary `.project`, also inside
|
||||
//! a `.projectarchive`) cannot be read; [`native_projects`] lists them so the
|
||||
//! 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;
|
||||
@@ -41,9 +46,26 @@ impl Scanner for PlcControlLogicScanner {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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();
|
||||
/// 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;
|
||||
for entry in walkdir::WalkDir::new(root)
|
||||
.into_iter()
|
||||
.filter_map(|e| e.ok())
|
||||
@@ -62,9 +84,23 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
|
||||
if !is_st && !is_xml {
|
||||
continue;
|
||||
}
|
||||
let Ok(content) = std::fs::read_to_string(path) else {
|
||||
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;
|
||||
}
|
||||
};
|
||||
// A `.project` is read only as a PLCopen export; CODESYS's native one
|
||||
// is binary ([`native_projects`] reports it).
|
||||
if ext == "project" && !looks_like_xml(&content) {
|
||||
continue;
|
||||
}
|
||||
let pous = if is_xml {
|
||||
plcopen::parse_plcopen(&content)
|
||||
} else {
|
||||
@@ -73,16 +109,41 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
|
||||
if pous.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let rel = path
|
||||
.strip_prefix(root)
|
||||
.unwrap_or(path)
|
||||
.to_string_lossy()
|
||||
.to_string();
|
||||
for pou in &pous {
|
||||
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 {
|
||||
for hit in rules::analyze(pou) {
|
||||
let line_s = hit.line.to_string();
|
||||
let fingerprint =
|
||||
dedup::compute_fingerprint(&[repo_id, &rel, hit.rule_id, &pou.name, &line_s]);
|
||||
let fingerprint = dedup::compute_fingerprint(&[
|
||||
repo_id,
|
||||
&file.rel,
|
||||
hit.rule_id,
|
||||
&pou.name,
|
||||
&line_s,
|
||||
]);
|
||||
let mut f = Finding::new(
|
||||
repo_id.to_string(),
|
||||
fingerprint,
|
||||
@@ -92,7 +153,7 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
|
||||
hit.description,
|
||||
hit.severity,
|
||||
);
|
||||
f.file_path = Some(rel.clone());
|
||||
f.file_path = Some(file.rel.clone());
|
||||
f.line_number = Some(hit.line);
|
||||
f.rule_id = Some(hit.rule_id.to_string());
|
||||
f.cwe = hit.cwe.map(String::from);
|
||||
@@ -104,6 +165,71 @@ pub(crate) fn analyze_tree(root: &Path, 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 {
|
||||
content
|
||||
.trim_start_matches('\u{feff}')
|
||||
.trim_start()
|
||||
.starts_with('<')
|
||||
}
|
||||
|
||||
/// The CODESYS projects under `root` in their native format, which the
|
||||
/// control-logic analysis cannot read: a `.project` that is not a PLCopen XML
|
||||
/// export, and a readable `.projectarchive` (a zip around one). Paths are
|
||||
/// relative to `root`, `/`-separated, sorted; `.git` is skipped. A
|
||||
/// `.projectarchive` that does not open is left out: the SBOM stage reports
|
||||
/// it as unreadable.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `root` - the tree, or a single uploaded file
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The native project files, e.g. `["LineControl.project"]`.
|
||||
pub fn native_projects(root: &Path) -> Vec<String> {
|
||||
let mut found = Vec::new();
|
||||
let walker = walkdir::WalkDir::new(root)
|
||||
.into_iter()
|
||||
.filter_entry(|e| e.file_name() != ".git");
|
||||
for entry in walker.filter_map(Result::ok) {
|
||||
if !entry.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
let path = entry.path();
|
||||
let ext = path
|
||||
.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.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)),
|
||||
"projectarchive" => sbom::check_archive(path).is_ok(),
|
||||
_ => false,
|
||||
};
|
||||
if native {
|
||||
let rel = path.strip_prefix(root).unwrap_or(path);
|
||||
let rel = if rel.as_os_str().is_empty() {
|
||||
// `root` is the file itself.
|
||||
path.file_name().map(Path::new).unwrap_or(path)
|
||||
} else {
|
||||
rel
|
||||
};
|
||||
found.push(rel.to_string_lossy().replace('\\', "/"));
|
||||
}
|
||||
}
|
||||
found.sort();
|
||||
found
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -231,4 +357,89 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A scratch directory, removed on drop.
|
||||
struct Scratch(PathBuf);
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_codesys_projects_are_listed_and_exports_are_not() {
|
||||
let root =
|
||||
Scratch(std::env::temp_dir().join(format!("cs-plc-native-{}", uuid::Uuid::new_v4())));
|
||||
let write = |rel: &str, bytes: &[u8]| {
|
||||
let path = root.0.join(rel);
|
||||
std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
|
||||
std::fs::write(path, bytes).expect("write");
|
||||
};
|
||||
// A binary native project, and one that is text but not XML.
|
||||
write("App/Line.project", b"\x00\x01CODESYS\xff");
|
||||
write("Other.project", b"fixture");
|
||||
// A PLCopen export saved as `.project` is read, not reported.
|
||||
write(
|
||||
"Export.project",
|
||||
b"\xef\xbb\xbf <?xml version=\"1.0\"?><project/>",
|
||||
);
|
||||
// A readable archive is native; a corrupt one is left to the SBOM stage.
|
||||
let fixtures = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixtures/nightly/plc");
|
||||
std::fs::copy(
|
||||
fixtures.join("line_control.projectarchive"),
|
||||
root.0.join("Line.projectarchive"),
|
||||
)
|
||||
.expect("copy archive");
|
||||
write("Broken.projectarchive", b"not a zip");
|
||||
write(".git/x.project", b"\x00");
|
||||
|
||||
assert_eq!(
|
||||
native_projects(&root.0),
|
||||
["App/Line.project", "Line.projectarchive", "Other.project"]
|
||||
);
|
||||
// An uploaded file on its own is named by its file name.
|
||||
assert_eq!(
|
||||
native_projects(&root.0.join("Other.project")),
|
||||
["Other.project"]
|
||||
);
|
||||
// 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,6 +119,7 @@ impl Parser {
|
||||
body.push(s);
|
||||
}
|
||||
}
|
||||
let end_line = self.line();
|
||||
self.eat_kw(end);
|
||||
|
||||
Some(Pou {
|
||||
@@ -127,6 +128,7 @@ impl Parser {
|
||||
vars,
|
||||
body,
|
||||
line,
|
||||
end_line,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -49,7 +49,16 @@ pub fn parse_plcopen(xml: &str) -> Vec<Pou> {
|
||||
_ => "PROGRAM",
|
||||
};
|
||||
let synthetic = format!("{kw} {name}\n{var_block}{body}\nEND_{kw}\n");
|
||||
pous.extend(parser::parse(&synthetic));
|
||||
// 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
|
||||
}
|
||||
|
||||
@@ -96,9 +96,13 @@ pub fn projectarchive_sbom(archive: &Path, repo_id: &str) -> Vec<SbomEntry> {
|
||||
let Ok(entry) = zip.by_index_raw(i) else {
|
||||
continue;
|
||||
};
|
||||
// zip 9: a name that does not decode is skipped like an unreadable entry.
|
||||
let Ok(entry_name) = entry.name() else {
|
||||
continue;
|
||||
};
|
||||
// Entry paths use `\` (Windows-authored) and/or `/` separators; the
|
||||
// component id is one path segment.
|
||||
for seg in entry.name().split(['/', '\\']) {
|
||||
for seg in entry_name.split(['/', '\\']) {
|
||||
if let Some((name, version)) = parse_library(seg).or_else(|| parse_runtime(seg)) {
|
||||
if seen.insert((name.clone(), version.clone())) {
|
||||
let mut e = SbomEntry::new(
|
||||
|
||||
@@ -45,10 +45,21 @@ pub struct RepoView {
|
||||
/// Whether the target's uploaded files let a scheduled scan without new
|
||||
/// commits be skipped ([`crate::pipeline::change::uploads_allow_git_skip`]).
|
||||
pub uploads_allow_skip: bool,
|
||||
/// Whether the customer changed something besides the commits since the
|
||||
/// last completed scan: an uploaded file, or a live URL to probe (t72).
|
||||
pub changed_besides_commits: bool,
|
||||
/// How the target is billed, for whether its scan counts (t72).
|
||||
pub billing: compliance_core::models::TargetBilling,
|
||||
/// Whether the tree is read as Yocto layers (its recipe inventory): it
|
||||
/// was classified as one, or the target is a Yocto target. Set by the
|
||||
/// caller after classification; `false` from [`Self::from_target`].
|
||||
pub yocto_layers: bool,
|
||||
/// Directories and files the target's settings leave out of every scan
|
||||
/// stage (`scan_config.exclude_paths`).
|
||||
pub exclude_paths: Vec<String>,
|
||||
/// The target's uploaded build outputs (Yocto image SPDX archives), as
|
||||
/// ingested. Set by the caller; empty from [`Self::from_target`].
|
||||
pub build_outputs: Vec<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
impl RepoView {
|
||||
@@ -78,7 +89,12 @@ impl RepoView {
|
||||
findings_count: target.findings_count,
|
||||
managed: target.source_repo.is_some(),
|
||||
uploads_allow_skip: crate::pipeline::change::uploads_allow_git_skip(target),
|
||||
changed_besides_commits: target.live_url().is_some()
|
||||
|| crate::pipeline::change::uploads_changed(target),
|
||||
billing: target.billing,
|
||||
yocto_layers: false,
|
||||
exclude_paths: target.scan_config.exclude_paths.clone(),
|
||||
build_outputs: Vec::new(),
|
||||
};
|
||||
if let Some(git) = &code.git {
|
||||
view.default_branch = git.default_branch.clone();
|
||||
|
||||
@@ -0,0 +1,623 @@
|
||||
//! 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,6 +147,7 @@ pub(crate) fn unlocked_mobile_ecosystems(root: &Path) -> Vec<UnlockedEcosystem>
|
||||
manifest,
|
||||
problem: eco.problem,
|
||||
remedy: eco.remedy,
|
||||
legacy_build: false,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
mod cargo_audit;
|
||||
pub(crate) mod carthage;
|
||||
pub(crate) mod coverage;
|
||||
mod distribution;
|
||||
mod gradle;
|
||||
mod mobile;
|
||||
@@ -224,6 +225,9 @@ 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
|
||||
@@ -266,12 +270,14 @@ 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,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -284,6 +290,7 @@ 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,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -292,6 +299,7 @@ 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));
|
||||
@@ -307,6 +315,7 @@ 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,6 +250,7 @@ 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,
|
||||
}]
|
||||
}
|
||||
|
||||
|
||||
@@ -19,9 +19,10 @@ pub fn relative_path(root: &Path, path: &str) -> String {
|
||||
rel.to_string_lossy().replace('\\', "/")
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// 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.
|
||||
pub fn read_text(root: &Path, rel: &str) -> Option<String> {
|
||||
let rel_path = Path::new(rel);
|
||||
if rel_path.is_absolute()
|
||||
@@ -31,7 +32,8 @@ pub fn read_text(root: &Path, rel: &str) -> Option<String> {
|
||||
{
|
||||
return None;
|
||||
}
|
||||
std::fs::read_to_string(root.join(rel_path)).ok()
|
||||
// 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()
|
||||
}
|
||||
|
||||
/// Lines `start..=end` (1-based, inclusive) of `root/rel`, capped at
|
||||
|
||||
@@ -0,0 +1,509 @@
|
||||
//! Test data inside a scanned tree: fixtures, sample projects, golden files.
|
||||
//!
|
||||
//! A repository's test data is not what it ships. Its sample lockfiles name
|
||||
//! old, vulnerable dependencies on purpose, its sample code holds the flaws a
|
||||
//! test expects to find, and none of it is the product's to fix. Scanned as
|
||||
//! product code, it buries the real findings: the CVE issues of a test
|
||||
//! fixture's `struts2 2.3.30` read exactly like those of a dependency the
|
||||
//! product uses.
|
||||
//!
|
||||
//! So the directories that hold test data by a common convention are taken
|
||||
//! out of the scan's working copy before the first stage runs, and every
|
||||
//! stage — code findings, SBOM, CVE match — sees the tree without them. The
|
||||
//! working copy is a git clone, restored on every fetch, or an unpacked
|
||||
//! upload, unpacked again on every scan, so nothing is lost.
|
||||
//!
|
||||
//! Matching is by directory name, and narrow: `tests/` and `spec/` hold test
|
||||
//! code that can leak a real secret, and `examples/` or `demo/` are often the
|
||||
//! product's own code, so neither is matched.
|
||||
//!
|
||||
//! One more kind is found by its content: a Semgrep rule pack. Semgrep's own
|
||||
//! test convention puts each rule `X.yaml` next to the sample it is tested
|
||||
//! on, `X.py` or `X.cs`, and the samples hold the flaws the rules must find.
|
||||
//! A directory with such a pair is test data with everything below it (a
|
||||
//! vendored pack's manifests too), unless it is the tree itself.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Directory names that hold test data by convention, compared
|
||||
/// case-insensitively: `fixtures` (Rails, pytest, Jest's `__fixtures__`),
|
||||
/// Go's `testdata`, and their spellings.
|
||||
const TEST_DATA_DIR_NAMES: &[&str] = &[
|
||||
"fixtures",
|
||||
"__fixtures__",
|
||||
"testdata",
|
||||
"test_data",
|
||||
"test-data",
|
||||
"test-fixtures",
|
||||
"test_fixtures",
|
||||
];
|
||||
|
||||
/// A rule file larger than this is not read: Semgrep rule files are a few
|
||||
/// kilobytes, and a large YAML file is data, not a rule pack.
|
||||
const MAX_RULE_FILE_BYTES: u64 = 1024 * 1024;
|
||||
|
||||
/// The top-most test-data directories under `root`, relative to it with `/`
|
||||
/// separators, sorted: those named like test data, and Semgrep rule packs
|
||||
/// with their samples. A directory inside one that already matched is not
|
||||
/// listed again, `root` itself is never listed, and a symbolic link is never
|
||||
/// followed or listed.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `root` - the scanned tree
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The directories to leave out of the scan, e.g. `["fixtures",
|
||||
/// "pkg/parser/testdata"]`.
|
||||
pub fn test_data_dirs(root: &Path) -> Vec<String> {
|
||||
let mut found = Vec::new();
|
||||
// YAML files outside the test data found so far: rule pack candidates,
|
||||
// checked once the walk is done.
|
||||
let mut yaml_files = Vec::new();
|
||||
let mut walker = walkdir::WalkDir::new(root).min_depth(1).into_iter();
|
||||
while let Some(entry) = walker.next() {
|
||||
let Ok(entry) = entry else {
|
||||
continue;
|
||||
};
|
||||
// `file_type()` does not follow links: a link to a directory is a
|
||||
// link here, never a directory.
|
||||
if entry.file_type().is_file() {
|
||||
if is_yaml(entry.path()) {
|
||||
yaml_files.push(entry.into_path());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !entry.file_type().is_dir() {
|
||||
continue;
|
||||
}
|
||||
let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
|
||||
if name == ".git" {
|
||||
walker.skip_current_dir();
|
||||
continue;
|
||||
}
|
||||
if TEST_DATA_DIR_NAMES.contains(&name.as_str()) {
|
||||
if let Ok(rel) = entry.path().strip_prefix(root) {
|
||||
found.push(rel.to_string_lossy().replace('\\', "/"));
|
||||
}
|
||||
walker.skip_current_dir();
|
||||
}
|
||||
}
|
||||
found.extend(rule_pack_dirs(root, &yaml_files));
|
||||
top_most(found)
|
||||
}
|
||||
|
||||
/// The directories, relative to `root`, of the `yaml_files` that are Semgrep
|
||||
/// rules with a sample of the same name next to them. Each directory is read
|
||||
/// once, and a rule file only when such a sample exists.
|
||||
fn rule_pack_dirs(root: &Path, yaml_files: &[PathBuf]) -> Vec<String> {
|
||||
// Per directory: the names (without extension) of its files that are not
|
||||
// YAML, the possible samples.
|
||||
let mut samples: HashMap<&Path, HashSet<OsString>> = HashMap::new();
|
||||
let mut packs: HashSet<&Path> = HashSet::new();
|
||||
for rule in yaml_files {
|
||||
let (Some(dir), Some(stem)) = (rule.parent(), rule.file_stem()) else {
|
||||
continue;
|
||||
};
|
||||
if dir == root || packs.contains(dir) {
|
||||
continue;
|
||||
}
|
||||
let names = samples.entry(dir).or_insert_with(|| sample_stems(dir));
|
||||
if names.contains(stem) && is_semgrep_rule_file(rule) {
|
||||
packs.insert(dir);
|
||||
}
|
||||
}
|
||||
packs
|
||||
.into_iter()
|
||||
.filter_map(|dir| dir.strip_prefix(root).ok())
|
||||
.map(|rel| rel.to_string_lossy().replace('\\', "/"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The names without extension of the regular files in `dir` that are not
|
||||
/// YAML.
|
||||
fn sample_stems(dir: &Path) -> HashSet<OsString> {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return HashSet::new();
|
||||
};
|
||||
entries
|
||||
.flatten()
|
||||
.filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
|
||||
.map(|e| e.path())
|
||||
.filter(|p| !is_yaml(p))
|
||||
.filter_map(|p| p.file_stem().map(OsString::from))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether `path` ends in `.yaml` or `.yml`.
|
||||
fn is_yaml(path: &Path) -> bool {
|
||||
path.extension()
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("yaml") || ext.eq_ignore_ascii_case("yml"))
|
||||
}
|
||||
|
||||
/// Whether the file at `path` is a Semgrep rule file: a `rules` list with at
|
||||
/// least one rule naming its `id`, `languages` and `message`, which Semgrep
|
||||
/// requires of every rule.
|
||||
fn is_semgrep_rule_file(path: &Path) -> bool {
|
||||
if !std::fs::metadata(path).is_ok_and(|m| m.len() <= MAX_RULE_FILE_BYTES) {
|
||||
return false;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(path) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(docs) = yaml_rust2::YamlLoader::load_from_str(&text) else {
|
||||
return false;
|
||||
};
|
||||
docs.first()
|
||||
.and_then(|doc| doc["rules"].as_vec())
|
||||
.is_some_and(|rules| {
|
||||
rules.iter().any(|rule| {
|
||||
rule["id"].as_str().is_some()
|
||||
&& !rule["languages"].is_badvalue()
|
||||
&& !rule["message"].is_badvalue()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// `dirs` sorted, without those inside another one listed.
|
||||
fn top_most(mut dirs: Vec<String>) -> Vec<String> {
|
||||
dirs.sort();
|
||||
dirs.dedup();
|
||||
let mut kept: Vec<String> = Vec::with_capacity(dirs.len());
|
||||
for dir in dirs {
|
||||
let inside = kept.iter().any(|outer| {
|
||||
dir.strip_prefix(outer.as_str())
|
||||
.is_some_and(|rest| rest.starts_with('/'))
|
||||
});
|
||||
if !inside {
|
||||
kept.push(dir);
|
||||
}
|
||||
}
|
||||
kept
|
||||
}
|
||||
|
||||
/// Remove the `paths` (the [`test_data_dirs`], or the directories and files
|
||||
/// a target's settings exclude) from the working copy at `root`.
|
||||
///
|
||||
/// Only a working copy the agent made may lose files: `root` must lie under
|
||||
/// one of `owned_bases` (the clone base and the artifact store). Anything
|
||||
/// else is refused, so the call can never delete a directory it was pointed
|
||||
/// at by mistake. A path is only removed when it lies inside `root` without
|
||||
/// passing a symbolic link: `src/link/x` with `src/link` pointing elsewhere
|
||||
/// is left alone, and so is a link itself.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `root` - the scan's working copy
|
||||
/// * `paths` - directories or files relative to `root`, `/`-separated
|
||||
/// * `owned_bases` - the directories the agent's working copies live under
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The paths that were removed; one that is not in the tree is left out, and
|
||||
/// one that could not be removed is logged and left out.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`PruneError::NotOwned`] when `root` lies under none of `owned_bases`;
|
||||
/// nothing is removed then.
|
||||
pub fn prune(
|
||||
root: &Path,
|
||||
paths: &[String],
|
||||
owned_bases: &[&Path],
|
||||
) -> Result<Vec<String>, PruneError> {
|
||||
let owned = owned_bases
|
||||
.iter()
|
||||
.any(|base| !base.as_os_str().is_empty() && root.starts_with(base) && root != *base);
|
||||
if !owned {
|
||||
return Err(PruneError::NotOwned);
|
||||
}
|
||||
let mut removed = Vec::with_capacity(paths.len());
|
||||
for rel in paths {
|
||||
let Some(path) = inside_without_links(root, rel) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(meta) = std::fs::symlink_metadata(&path) else {
|
||||
continue;
|
||||
};
|
||||
let outcome = if meta.is_dir() {
|
||||
std::fs::remove_dir_all(&path)
|
||||
} else if meta.is_file() {
|
||||
std::fs::remove_file(&path)
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
match outcome {
|
||||
Ok(()) => removed.push(rel.clone()),
|
||||
Err(e) => tracing::warn!(path = %rel, error = %e, "left-out path not removed"),
|
||||
}
|
||||
}
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
/// `root` joined with `rel` when every component of `rel` is a plain name
|
||||
/// and none of the directories on the way is a symbolic link; `None`
|
||||
/// otherwise (also when a part does not exist).
|
||||
fn inside_without_links(root: &Path, rel: &str) -> Option<std::path::PathBuf> {
|
||||
let rel_path = Path::new(rel);
|
||||
if rel_path.is_absolute() {
|
||||
return None;
|
||||
}
|
||||
let mut path = root.to_path_buf();
|
||||
for component in rel_path.components() {
|
||||
let std::path::Component::Normal(name) = component else {
|
||||
tracing::warn!(path = %rel, "left-out path outside the tree; not removed");
|
||||
return None;
|
||||
};
|
||||
path.push(name);
|
||||
let meta = std::fs::symlink_metadata(&path).ok()?;
|
||||
if meta.file_type().is_symlink() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
(path != root).then_some(path)
|
||||
}
|
||||
|
||||
/// Why [`prune`] removed nothing.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum PruneError {
|
||||
/// The tree is not a working copy the agent made.
|
||||
#[error("the tree is not under the agent's clone or artifact directories")]
|
||||
NotOwned,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn write(root: &Path, rel: &str) {
|
||||
let path = root.join(rel);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, "x").unwrap();
|
||||
}
|
||||
|
||||
/// A scratch directory, removed on drop.
|
||||
struct Scratch(std::path::PathBuf);
|
||||
impl Scratch {
|
||||
fn new() -> Self {
|
||||
let dir = std::env::temp_dir().join(format!("cs-testdata-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
Self(dir)
|
||||
}
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A working copy under a fake clone base: `(base, tree)`.
|
||||
fn tree() -> (Scratch, std::path::PathBuf) {
|
||||
let base = Scratch::new();
|
||||
let root = base.path().join("tenant").join("repo");
|
||||
for file in [
|
||||
"src/main.rs",
|
||||
"src/fixtures_helper.rs",
|
||||
"src/fixtures.rs",
|
||||
"fixtures/nightly/eco/maven/pom.xml",
|
||||
"fixtures/nightly/eco/maven/fixtures/inner.txt",
|
||||
"pkg/parser/testdata/input.json",
|
||||
"web/__fixtures__/user.json",
|
||||
"Tests/Test-Data/sample.csv",
|
||||
"tests/integration.rs",
|
||||
"examples/demo.rs",
|
||||
".git/fixtures/HEAD",
|
||||
] {
|
||||
write(&root, file);
|
||||
}
|
||||
(base, root)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_data_is_found_by_name_and_reported_once() {
|
||||
let (_base, root) = tree();
|
||||
assert_eq!(
|
||||
test_data_dirs(&root),
|
||||
[
|
||||
"Tests/Test-Data",
|
||||
"fixtures",
|
||||
"pkg/parser/testdata",
|
||||
"web/__fixtures__",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// A Semgrep rule file with one rule.
|
||||
const RULE: &str = "rules:\n - id: no-exec\n languages: [python]\n \
|
||||
message: exec runs code\n severity: ERROR\n pattern: exec(...)\n";
|
||||
|
||||
fn write_text(root: &Path, rel: &str, text: &str) {
|
||||
let path = root.join(rel);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_semgrep_rule_pack_with_its_samples_is_test_data() {
|
||||
let (_base, root) = tree();
|
||||
// A pack: a rule and its sample, with a vendored pack below it.
|
||||
write_text(&root, "agent/rules/cra.yaml", RULE);
|
||||
write(&root, "agent/rules/cra.py");
|
||||
write(&root, "agent/rules/vendor/gitlab/java/pom.xml");
|
||||
write_text(
|
||||
&root,
|
||||
"agent/rules/vendor/gitlab/java/inject/ognl.yml",
|
||||
RULE,
|
||||
);
|
||||
write(&root, "agent/rules/vendor/gitlab/java/inject/ognl.java");
|
||||
// Not packs: a configuration next to the code it configures, a rule
|
||||
// without a sample, and a rule pack that is the tree itself.
|
||||
write_text(&root, "app/settings.yaml", "debug: true\n");
|
||||
write(&root, "app/settings.py");
|
||||
write_text(&root, "ci/.semgrep.yml", RULE);
|
||||
write(&root, "ci/build.sh");
|
||||
write_text(&root, "local.yaml", RULE);
|
||||
write(&root, "local.py");
|
||||
|
||||
let dirs = test_data_dirs(&root);
|
||||
|
||||
assert!(dirs.contains(&"agent/rules".to_string()));
|
||||
assert!(
|
||||
!dirs.iter().any(|d| d.starts_with("agent/rules/")),
|
||||
"a pack inside the pack is not listed again: {dirs:?}"
|
||||
);
|
||||
for not_test_data in ["app", "ci", ""] {
|
||||
assert!(
|
||||
!dirs.contains(¬_test_data.to_string()),
|
||||
"{not_test_data}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_large_or_unreadable_yaml_file_is_not_a_rule_file() {
|
||||
let base = Scratch::new();
|
||||
write_text(base.path(), "big.yaml", &"x: 1\n".repeat(300_000));
|
||||
write_text(base.path(), "broken.yaml", "rules: [\n");
|
||||
write_text(base.path(), "rule.yaml", RULE);
|
||||
assert!(!is_semgrep_rule_file(&base.path().join("big.yaml")));
|
||||
assert!(!is_semgrep_rule_file(&base.path().join("broken.yaml")));
|
||||
assert!(is_semgrep_rule_file(&base.path().join("rule.yaml")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_top_most_directories_are_kept() {
|
||||
let dirs = ["a/b", "a", "a-x", "a/b/c", "b"].map(String::from).to_vec();
|
||||
assert_eq!(top_most(dirs), ["a", "a-x", "b"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tree_itself_is_never_test_data() {
|
||||
let base = Scratch::new();
|
||||
let root = base.path().join("fixtures");
|
||||
write(&root, "package-lock.json");
|
||||
assert!(test_data_dirs(&root).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pruning_removes_the_test_data_and_keeps_the_rest() {
|
||||
let (base, root) = tree();
|
||||
let dirs = test_data_dirs(&root);
|
||||
let removed = prune(&root, &dirs, &[base.path()]).unwrap();
|
||||
assert_eq!(removed, dirs);
|
||||
assert!(!root.join("fixtures").exists());
|
||||
assert!(!root.join("pkg/parser/testdata").exists());
|
||||
assert!(root.join("pkg/parser").is_dir());
|
||||
for kept in [
|
||||
"src/main.rs",
|
||||
"src/fixtures_helper.rs",
|
||||
"src/fixtures.rs",
|
||||
"tests/integration.rs",
|
||||
"examples/demo.rs",
|
||||
".git/fixtures/HEAD",
|
||||
] {
|
||||
assert!(root.join(kept).is_file(), "{kept} must stay");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tree_the_agent_did_not_make_is_never_pruned() {
|
||||
let (_base, root) = tree();
|
||||
let elsewhere = Scratch::new();
|
||||
let dirs = test_data_dirs(&root);
|
||||
assert_eq!(
|
||||
prune(&root, &dirs, &[elsewhere.path()]),
|
||||
Err(PruneError::NotOwned)
|
||||
);
|
||||
// The base itself is not a working copy, and an empty base owns nothing.
|
||||
assert_eq!(
|
||||
prune(&root, &dirs, &[root.as_path(), Path::new("")]),
|
||||
Err(PruneError::NotOwned)
|
||||
);
|
||||
assert!(root.join("fixtures").is_dir());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_configured_file_or_directory_is_removed_and_a_missing_one_skipped() {
|
||||
let (base, root) = tree();
|
||||
let removed = prune(
|
||||
&root,
|
||||
&[
|
||||
"src/main.rs".to_string(),
|
||||
"examples".to_string(),
|
||||
"not/there".to_string(),
|
||||
],
|
||||
&[base.path()],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(removed, ["src/main.rs", "examples"]);
|
||||
assert!(!root.join("src/main.rs").exists());
|
||||
assert!(root.join("src/fixtures.rs").is_file());
|
||||
assert!(!root.join("examples").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_path_through_a_link_is_never_followed() {
|
||||
let (base, root) = tree();
|
||||
let outside = base.path().join("outside");
|
||||
write(&outside, "keep/me.txt");
|
||||
std::os::unix::fs::symlink(&outside, root.join("src/link")).unwrap();
|
||||
let removed = prune(&root, &["src/link/keep".to_string()], &[base.path()]).unwrap();
|
||||
assert!(removed.is_empty());
|
||||
assert!(outside.join("keep/me.txt").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_outside_the_tree_is_never_removed() {
|
||||
let (base, root) = tree();
|
||||
let removed = prune(
|
||||
&root,
|
||||
&["../repo/src".to_string(), "/etc".to_string()],
|
||||
&[base.path()],
|
||||
)
|
||||
.unwrap();
|
||||
assert!(removed.is_empty());
|
||||
assert!(root.join("src/main.rs").is_file());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_link_named_like_test_data_is_left_alone() {
|
||||
let (base, root) = tree();
|
||||
let target = base.path().join("outside");
|
||||
write(&target, "keep.txt");
|
||||
std::os::unix::fs::symlink(&target, root.join("src/testdata")).unwrap();
|
||||
let dirs = test_data_dirs(&root);
|
||||
assert!(!dirs.contains(&"src/testdata".to_string()));
|
||||
prune(&root, &["src/testdata".to_string()], &[base.path()]).unwrap();
|
||||
assert!(target.join("keep.txt").is_file());
|
||||
assert!(root.join("src/testdata").exists());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,715 @@
|
||||
//! A Yocto build's own evidence (its image SPDX, [`crate::pipeline::yocto_spdx`])
|
||||
//! combined with the recipe inventory of the layer tree
|
||||
//! ([`crate::pipeline::yocto_inventory`]).
|
||||
//!
|
||||
//! The two name the same recipes differently: the inventory reads PV as
|
||||
//! written (`linux-yocto 6.6`), the build records what it built
|
||||
//! (`6.6.151+git`). So they are joined by recipe name, and for a recipe in
|
||||
//! both the build wins: its version, CPE and licence, and its image marking
|
||||
//! ([`InImageBasis::Built`]). An image the build's SPDX covers is
|
||||
//! authoritative: a recipe the inventory declares in it but the build did not
|
||||
//! install loses that marking; images the SPDX does not cover keep theirs.
|
||||
//!
|
||||
//! The build also says which CVEs its patches fixed; those become `fixed`
|
||||
//! VEX statements on the matching alerts, ahead of what the recipes state.
|
||||
//! Its cve-check report ([`crate::pipeline::yocto_cve_check`]), when it was
|
||||
//! uploaded too, goes first: Yocto's verdict on every CVE it looked at, and
|
||||
//! the CVEs it found unpatched that NVD's match here did not.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
|
||||
use compliance_core::models::{
|
||||
CveAlert, InImage, InImageBasis, SbomEntry, VexAssessment, VexJustification, VexStatus,
|
||||
YOCTO_RECIPE_MANAGER,
|
||||
};
|
||||
|
||||
use crate::pipeline::nvd_cpe::NvdCve;
|
||||
use crate::pipeline::yocto_cve_check::{CheckStatus, CheckedIssue, CveCheck};
|
||||
use crate::pipeline::yocto_inventory::{self, CpeProduct, NvdQuery, Recipe};
|
||||
use crate::pipeline::yocto_spdx::{BuiltImage, NotAffectedCve};
|
||||
|
||||
/// What the build installed, across its images, by recipe name.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Built<'a> {
|
||||
/// One component per recipe (the first image's, with every image named).
|
||||
components: BTreeMap<String, SbomEntry>,
|
||||
/// The images the SPDX covers (`core-image-minimal`).
|
||||
images: BTreeSet<String>,
|
||||
/// The CVEs fixed per recipe name.
|
||||
fixed: HashMap<String, BTreeSet<&'a str>>,
|
||||
/// What the build's SPDX 3.0 VEX says does not affect each recipe, by CVE.
|
||||
not_affected: HashMap<&'a str, HashMap<&'a str, &'a NotAffectedCve>>,
|
||||
/// Yocto's cve-check verdicts per recipe name, by CVE.
|
||||
checked: HashMap<&'a str, HashMap<&'a str, &'a CheckedIssue>>,
|
||||
/// The version cve-check names each recipe at.
|
||||
checked_versions: BTreeMap<&'a str, &'a str>,
|
||||
}
|
||||
|
||||
impl<'a> Built<'a> {
|
||||
/// Gather `images` (from one or more build-output archives) and the
|
||||
/// cve-check reports `checks`.
|
||||
pub fn new(images: &'a [BuiltImage], checks: &'a [CveCheck]) -> Self {
|
||||
let mut built = Self::default();
|
||||
for package in checks.iter().flat_map(|c| &c.packages) {
|
||||
built
|
||||
.checked_versions
|
||||
.insert(package.name.as_str(), package.version.as_str());
|
||||
let issues = built.checked.entry(package.name.as_str()).or_default();
|
||||
for issue in &package.issues {
|
||||
issues.insert(issue.id.as_str(), issue);
|
||||
}
|
||||
}
|
||||
for image in images {
|
||||
built.images.insert(image.image.clone());
|
||||
for entry in &image.entries {
|
||||
match built.components.get_mut(&entry.name) {
|
||||
Some(known) => add_image(known, &image.image),
|
||||
None => {
|
||||
built.components.insert(entry.name.clone(), entry.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
for fixed in &image.fixed {
|
||||
built
|
||||
.fixed
|
||||
.entry(fixed.component.clone())
|
||||
.or_default()
|
||||
.insert(fixed.cve.as_str());
|
||||
}
|
||||
for na in &image.not_affected {
|
||||
built
|
||||
.not_affected
|
||||
.entry(na.component.as_str())
|
||||
.or_default()
|
||||
.insert(na.cve.as_str(), na);
|
||||
}
|
||||
}
|
||||
built
|
||||
}
|
||||
|
||||
/// Whether the build listed nothing.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.components.is_empty() && self.checked.is_empty()
|
||||
}
|
||||
|
||||
/// The CVEs cve-check found unpatched that `alerts` do not have, per
|
||||
/// recipe and version (the built one where the build lists the recipe),
|
||||
/// for recipes `known` (components of the scan) only.
|
||||
pub fn unpatched_missing(
|
||||
&self,
|
||||
alerts: &[CveAlert],
|
||||
known: impl Fn(&str) -> bool,
|
||||
) -> Vec<(String, String, Vec<NvdCve>)> {
|
||||
let mut out = Vec::new();
|
||||
for (name, issues) in &self.checked {
|
||||
if !known(name) {
|
||||
continue;
|
||||
}
|
||||
let version = self
|
||||
.components
|
||||
.get(*name)
|
||||
.map(|c| c.version.as_str())
|
||||
.or_else(|| self.checked_versions.get(name).copied())
|
||||
.unwrap_or_default();
|
||||
let mut missing: Vec<NvdCve> = issues
|
||||
.values()
|
||||
.filter(|i| i.status == CheckStatus::Unpatched)
|
||||
.filter(|i| {
|
||||
!alerts
|
||||
.iter()
|
||||
.any(|a| a.affected_package == *name && a.cve_id == i.id)
|
||||
})
|
||||
.map(|i| NvdCve {
|
||||
id: i.id.clone(),
|
||||
summary: i.summary.clone(),
|
||||
cvss: i.cvss(),
|
||||
})
|
||||
.collect();
|
||||
if missing.is_empty() {
|
||||
continue;
|
||||
}
|
||||
missing.sort_by(|a, b| a.id.cmp(&b.id));
|
||||
out.push((name.to_string(), version.to_string(), missing));
|
||||
}
|
||||
out.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
out
|
||||
}
|
||||
|
||||
/// Yocto's cve-check verdict on `cve` of `package`, as a statement:
|
||||
/// Patched is fixed, Ignored as its CVE_STATUS reason says, Unpatched
|
||||
/// none.
|
||||
fn checked_statement(&self, package: &str, cve: &str) -> Option<VexAssessment> {
|
||||
let issue = self.checked.get(package)?.get(cve)?;
|
||||
let (status, justification) = match issue.status {
|
||||
CheckStatus::Unpatched => return None,
|
||||
// Yocto's kernel CVE report (improve_kernel_cve_report.py) says
|
||||
// Patched when the version is outside the affected range: not
|
||||
// affected rather than fixed.
|
||||
CheckStatus::Patched if issue.detail.as_deref() == Some("version-not-in-range") => (
|
||||
VexStatus::NotAffected,
|
||||
Some(VexJustification::VulnerableCodeNotPresent),
|
||||
),
|
||||
CheckStatus::Patched => (VexStatus::Fixed, None),
|
||||
CheckStatus::Ignored => {
|
||||
yocto_inventory::status_statement(issue.detail.as_deref().unwrap_or("ignored"))?
|
||||
}
|
||||
};
|
||||
let verdict = match issue.status {
|
||||
CheckStatus::Patched => "Patched",
|
||||
CheckStatus::Ignored => "Ignored",
|
||||
CheckStatus::Unpatched => "Unpatched",
|
||||
};
|
||||
let mut because = format!("Yocto cve-check: {verdict}");
|
||||
if let Some(detail) = issue.detail.as_deref() {
|
||||
because.push_str(&format!(" ({detail})"));
|
||||
}
|
||||
if let Some(note) = issue.description.as_deref().filter(|n| !n.is_empty()) {
|
||||
because.push_str(&format!(": {note}"));
|
||||
}
|
||||
Some(yocto_inventory::scan_statement(
|
||||
status,
|
||||
justification,
|
||||
because,
|
||||
))
|
||||
}
|
||||
|
||||
/// The SBOM components: `inventory` (the recipe inventory's) joined with
|
||||
/// what the build installed, by recipe name. See the module docs.
|
||||
pub fn merge(&self, inventory: Vec<SbomEntry>) -> Vec<SbomEntry> {
|
||||
let mut out = Vec::with_capacity(inventory.len() + self.components.len());
|
||||
let mut joined = BTreeSet::new();
|
||||
for mut entry in inventory {
|
||||
if entry.package_manager != YOCTO_RECIPE_MANAGER {
|
||||
out.push(entry);
|
||||
continue;
|
||||
}
|
||||
match self.components.get(&entry.name) {
|
||||
Some(built) => {
|
||||
joined.insert(entry.name.clone());
|
||||
out.push(self.joined(entry, built));
|
||||
}
|
||||
None => {
|
||||
self.uncover(&mut entry);
|
||||
out.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.extend(
|
||||
self.components
|
||||
.values()
|
||||
.filter(|c| !joined.contains(&c.name))
|
||||
.cloned(),
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
/// `inventory`'s component with what the build says about it.
|
||||
fn joined(&self, inventory: SbomEntry, built: &SbomEntry) -> SbomEntry {
|
||||
let mut entry = built.clone();
|
||||
// The inventory knows where the recipe is and what it fetches.
|
||||
entry.download_url = built.download_url.clone().or(inventory.download_url);
|
||||
entry.license = built.license.clone().or(inventory.license);
|
||||
entry.cpe = built.cpe.clone().or(inventory.cpe);
|
||||
let declared_elsewhere: Vec<String> = inventory
|
||||
.in_image
|
||||
.as_ref()
|
||||
.filter(|i| i.basis == InImageBasis::Declared)
|
||||
.map(|i| {
|
||||
i.images
|
||||
.iter()
|
||||
.filter(|image| !self.images.contains(*image))
|
||||
.cloned()
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let mut evidence: Vec<String> = inventory
|
||||
.evidence
|
||||
.into_iter()
|
||||
.filter(|line| !line.starts_with(InImageBasis::Declared.describe()))
|
||||
.collect();
|
||||
if !declared_elsewhere.is_empty() {
|
||||
evidence.push(
|
||||
InImage {
|
||||
basis: InImageBasis::Declared,
|
||||
images: declared_elsewhere,
|
||||
}
|
||||
.describe(),
|
||||
);
|
||||
}
|
||||
for line in built.evidence.iter() {
|
||||
if !evidence.contains(line) {
|
||||
evidence.push(line.clone());
|
||||
}
|
||||
}
|
||||
entry.evidence = evidence;
|
||||
entry
|
||||
}
|
||||
|
||||
/// Take the images the build covers out of `entry`'s declared marking:
|
||||
/// the build installed it there, or it is not there.
|
||||
fn uncover(&self, entry: &mut SbomEntry) {
|
||||
let Some(in_image) = entry
|
||||
.in_image
|
||||
.as_mut()
|
||||
.filter(|i| i.basis == InImageBasis::Declared)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let before = in_image.describe();
|
||||
in_image.images.retain(|image| !self.images.contains(image));
|
||||
let after = (!in_image.images.is_empty()).then(|| in_image.describe());
|
||||
if after.is_none() {
|
||||
entry.in_image = None;
|
||||
}
|
||||
entry.evidence.retain(|line| *line != before);
|
||||
entry.evidence.extend(after);
|
||||
}
|
||||
|
||||
/// What to ask NVD: the inventory's `queries`, with the build's version
|
||||
/// and CPE for a recipe the build installed, and a query for each built
|
||||
/// recipe the inventory does not have. Returns the queries and the
|
||||
/// components that cannot be asked about (no release version).
|
||||
pub fn nvd_queries(&self, queries: Vec<NvdQuery>) -> (Vec<NvdQuery>, Vec<String>) {
|
||||
let mut out: Vec<NvdQuery> = queries
|
||||
.into_iter()
|
||||
.filter(|q| !self.components.contains_key(&q.name))
|
||||
.collect();
|
||||
let mut unversioned = Vec::new();
|
||||
for component in self.components.values() {
|
||||
let products: Vec<CpeProduct> =
|
||||
component.cpe.iter().filter_map(|c| product(c)).collect();
|
||||
if products.is_empty() {
|
||||
continue;
|
||||
}
|
||||
match yocto_inventory::release_of(&component.version) {
|
||||
Some(cve_version) => out.push(NvdQuery {
|
||||
name: component.name.clone(),
|
||||
version: component.version.clone(),
|
||||
cve_version,
|
||||
products,
|
||||
}),
|
||||
None => unversioned.push(format!("{} (no release version)", component.name)),
|
||||
}
|
||||
}
|
||||
(out, unversioned)
|
||||
}
|
||||
|
||||
/// The VEX statements on `alerts`: `fixed` for a CVE the build's patches
|
||||
/// fixed in the component, else what its recipe in the tree states
|
||||
/// (joined by name, whatever version either side names), else what
|
||||
/// [`yocto_inventory::vex_statements`] finds.
|
||||
pub fn statements(
|
||||
&self,
|
||||
recipes: &[Recipe],
|
||||
alerts: &[CveAlert],
|
||||
) -> Vec<(String, VexAssessment)> {
|
||||
let (built_alerts, other): (Vec<&CveAlert>, Vec<&CveAlert>) =
|
||||
alerts.iter().partition(|a| {
|
||||
self.components.contains_key(&a.affected_package)
|
||||
|| self.checked.contains_key(a.affected_package.as_str())
|
||||
});
|
||||
let mut out: Vec<(String, VexAssessment)> = built_alerts
|
||||
.iter()
|
||||
.filter_map(|alert| {
|
||||
if let Some(checked) =
|
||||
self.checked_statement(&alert.affected_package, &alert.cve_id)
|
||||
{
|
||||
return Some((alert.cve_id.clone(), checked));
|
||||
}
|
||||
if let Some(na) = self
|
||||
.not_affected
|
||||
.get(alert.affected_package.as_str())
|
||||
.and_then(|cves| cves.get(alert.cve_id.as_str()))
|
||||
{
|
||||
return Some((alert.cve_id.clone(), not_affected_statement(na)));
|
||||
}
|
||||
let fixed = self
|
||||
.fixed
|
||||
.get(&alert.affected_package)
|
||||
.is_some_and(|cves| cves.contains(alert.cve_id.as_str()));
|
||||
let statement = if fixed {
|
||||
Some(yocto_inventory::scan_statement(
|
||||
VexStatus::Fixed,
|
||||
None,
|
||||
format!(
|
||||
"Fixed by a patch the build applied to {} (Yocto create-spdx: CVEs \
|
||||
fixed)",
|
||||
alert.affected_package
|
||||
),
|
||||
))
|
||||
} else {
|
||||
recipes
|
||||
.iter()
|
||||
.find(|r| r.bpn == alert.affected_package)
|
||||
.and_then(|r| yocto_inventory::recipe_statement(r, &alert.cve_id))
|
||||
};
|
||||
statement.map(|vex| (alert.cve_id.clone(), vex))
|
||||
})
|
||||
.collect();
|
||||
let rest: Vec<CveAlert> = other.into_iter().cloned().collect();
|
||||
out.extend(yocto_inventory::vex_statements(recipes, &rest));
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The statement the build's SPDX 3.0 makes that `na` does not affect its
|
||||
/// component, with its justification and impact statement.
|
||||
fn not_affected_statement(na: &NotAffectedCve) -> VexAssessment {
|
||||
let justification = match na.justification.as_deref() {
|
||||
Some("componentNotPresent") => Some(VexJustification::ComponentNotPresent),
|
||||
Some("vulnerableCodeNotPresent") => Some(VexJustification::VulnerableCodeNotPresent),
|
||||
Some("vulnerableCodeNotInExecutePath") => {
|
||||
Some(VexJustification::VulnerableCodeNotInExecutePath)
|
||||
}
|
||||
Some("vulnerableCodeCannotBeControlledByAdversary") => {
|
||||
Some(VexJustification::VulnerableCodeCannotBeControlledByAdversary)
|
||||
}
|
||||
Some("inlineMitigationsAlreadyExist") => {
|
||||
Some(VexJustification::InlineMitigationsAlreadyExist)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let mut because = "Yocto SPDX 3.0 VEX: not affected".to_string();
|
||||
if let Some(statement) = na.statement.as_deref().filter(|s| !s.is_empty()) {
|
||||
because.push_str(&format!(": {statement}"));
|
||||
}
|
||||
yocto_inventory::scan_statement(VexStatus::NotAffected, justification, because)
|
||||
}
|
||||
|
||||
/// Add `image` to `entry`'s built marking and its evidence line.
|
||||
fn add_image(entry: &mut SbomEntry, image: &str) {
|
||||
let Some(in_image) = entry.in_image.as_mut() else {
|
||||
return;
|
||||
};
|
||||
if in_image.images.iter().any(|i| i == image) {
|
||||
return;
|
||||
}
|
||||
let before = in_image.describe();
|
||||
in_image.images.push(image.to_string());
|
||||
let after = in_image.describe();
|
||||
for line in entry.evidence.iter_mut() {
|
||||
if *line == before {
|
||||
line.clone_from(&after);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The product a CPE 2.3 name names (`cpe:2.3:*:openssl:openssl:3.5.9:…` →
|
||||
/// vendor `openssl`, product `openssl`; a `*` vendor is any vendor).
|
||||
fn product(cpe: &str) -> Option<CpeProduct> {
|
||||
let mut parts = cpe.split(':');
|
||||
if parts.next()? != "cpe" || parts.next()? != "2.3" {
|
||||
return None;
|
||||
}
|
||||
let _part = parts.next()?;
|
||||
let vendor = parts.next()?;
|
||||
let product = parts.next()?;
|
||||
if product.is_empty() || product == "*" {
|
||||
return None;
|
||||
}
|
||||
Some(CpeProduct {
|
||||
vendor: (vendor != "*" && !vendor.is_empty()).then(|| vendor.replace('\\', "")),
|
||||
product: product.replace('\\', ""),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::pipeline::yocto_spdx::{read_dir, ReadLimits};
|
||||
|
||||
fn built_images() -> Vec<BuiltImage> {
|
||||
let dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../fixtures/yocto/spdx-scarthgap");
|
||||
read_dir(&dir, "t", ReadLimits::default()).unwrap()
|
||||
}
|
||||
|
||||
/// An inventory component as the recipe inventory makes it.
|
||||
fn inventory(name: &str, version: &str, declared: &[&str]) -> SbomEntry {
|
||||
let mut e = SbomEntry::new(
|
||||
"t".into(),
|
||||
name.into(),
|
||||
version.into(),
|
||||
YOCTO_RECIPE_MANAGER.into(),
|
||||
);
|
||||
e.evidence.push(format!(
|
||||
"Yocto recipe inventory: recipes-core/{name}/{name}.bb"
|
||||
));
|
||||
if !declared.is_empty() {
|
||||
let in_image = InImage {
|
||||
basis: InImageBasis::Declared,
|
||||
images: declared.iter().map(|s| s.to_string()).collect(),
|
||||
};
|
||||
e.evidence.push(in_image.describe());
|
||||
e.in_image = Some(in_image);
|
||||
}
|
||||
e
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_build_wins_by_recipe_name_whatever_version_the_tree_names() {
|
||||
let images = built_images();
|
||||
let built = Built::new(&images, &[]);
|
||||
let merged = built.merge(vec![
|
||||
// PV in the tree differs from what the build recorded.
|
||||
inventory("busybox", "1.36", &["core-image-minimal", "rescue-image"]),
|
||||
inventory("dropbear", "2024.85", &["core-image-minimal"]),
|
||||
inventory("tool", "1.0", &["rescue-image"]),
|
||||
SbomEntry::new("t".into(), "serde".into(), "1.0".into(), "cargo".into()),
|
||||
]);
|
||||
let by_name = |n: &str| merged.iter().find(|e| e.name == n).unwrap();
|
||||
|
||||
let busybox = by_name("busybox");
|
||||
assert_eq!(busybox.version, "1.36.1");
|
||||
assert_eq!(
|
||||
busybox.in_image.as_ref().map(|i| i.basis),
|
||||
Some(InImageBasis::Built)
|
||||
);
|
||||
assert!(busybox.evidence[0].starts_with("Yocto recipe inventory"));
|
||||
// The image the SPDX does not cover keeps its declaration as evidence.
|
||||
assert!(busybox.evidence.iter().any(
|
||||
|l| l.starts_with(InImageBasis::Declared.describe()) && l.ends_with("rescue-image")
|
||||
));
|
||||
// The built image's declaration is gone: the build says where it is.
|
||||
assert!(!busybox
|
||||
.evidence
|
||||
.iter()
|
||||
.any(|l| l.starts_with(InImageBasis::Declared.describe())
|
||||
&& l.contains("core-image-minimal")));
|
||||
|
||||
// Declared in the built image but not installed by the build: unmarked.
|
||||
assert!(by_name("dropbear").in_image.is_none());
|
||||
assert_eq!(by_name("dropbear").evidence.len(), 1);
|
||||
// Another image's declaration is left alone.
|
||||
assert_eq!(
|
||||
by_name("tool").in_image.as_ref().map(|i| i.images.clone()),
|
||||
Some(vec!["rescue-image".to_string()])
|
||||
);
|
||||
// Built only: added. Not a recipe component: untouched.
|
||||
assert!(merged
|
||||
.iter()
|
||||
.any(|e| e.name == "openssl" && e.version == "3.5.9"));
|
||||
assert_eq!(by_name("serde").package_manager, "cargo");
|
||||
assert_eq!(merged.iter().filter(|e| e.name == "busybox").count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nvd_is_asked_with_the_built_version_and_cpe() {
|
||||
let images = built_images();
|
||||
let built = Built::new(&images, &[]);
|
||||
let stale = NvdQuery {
|
||||
name: "busybox".into(),
|
||||
version: "1.36".into(),
|
||||
cve_version: "1.36".into(),
|
||||
products: vec![],
|
||||
};
|
||||
let other = NvdQuery {
|
||||
name: "zlib".into(),
|
||||
version: "1.3".into(),
|
||||
cve_version: "1.3".into(),
|
||||
products: vec![],
|
||||
};
|
||||
let (queries, unversioned) = built.nvd_queries(vec![stale, other]);
|
||||
let names: Vec<(&str, &str)> = queries
|
||||
.iter()
|
||||
.map(|q| (q.name.as_str(), q.version.as_str()))
|
||||
.collect();
|
||||
assert!(names.contains(&("zlib", "1.3")), "{names:?}");
|
||||
assert!(names.contains(&("busybox", "1.36.1")), "{names:?}");
|
||||
assert!(!names.contains(&("busybox", "1.36")));
|
||||
let openssl = queries.iter().find(|q| q.name == "openssl").unwrap();
|
||||
assert_eq!(
|
||||
openssl.products,
|
||||
[CpeProduct {
|
||||
vendor: Some("openssl".into()),
|
||||
product: "openssl".into()
|
||||
}]
|
||||
);
|
||||
// The package group has no CPE: nothing to ask, nothing missing.
|
||||
assert!(!queries.iter().any(|q| q.name == "packagegroup-core-boot"));
|
||||
assert!(unversioned.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cve_the_build_patched_is_stated_fixed() {
|
||||
let images = built_images();
|
||||
let built = Built::new(&images, &[]);
|
||||
let alert = |package: &str, cve: &str| {
|
||||
CveAlert::new(
|
||||
cve.into(),
|
||||
"t".into(),
|
||||
package.into(),
|
||||
"1.36.1".into(),
|
||||
compliance_core::models::CveSource::Nvd,
|
||||
)
|
||||
};
|
||||
let statements = built.statements(
|
||||
&[],
|
||||
&[
|
||||
alert("busybox", "CVE-2022-48174"),
|
||||
alert("busybox", "CVE-2099-0001"),
|
||||
],
|
||||
);
|
||||
assert_eq!(statements.len(), 1);
|
||||
assert_eq!(statements[0].0, "CVE-2022-48174");
|
||||
assert_eq!(statements[0].1.status, VexStatus::Fixed);
|
||||
assert!(statements[0].1.by_scan);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpe_products_are_read_from_cpe_names() {
|
||||
assert_eq!(
|
||||
product("cpe:2.3:*:*:busybox:1.36.1:*:*:*:*:*:*:*"),
|
||||
Some(CpeProduct {
|
||||
vendor: None,
|
||||
product: "busybox".into()
|
||||
})
|
||||
);
|
||||
assert_eq!(product("cpe:2.3:a:*:*:1:*"), None);
|
||||
assert_eq!(product("cpe:/a:x:y"), None);
|
||||
}
|
||||
|
||||
fn checks() -> Vec<CveCheck> {
|
||||
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../fixtures/yocto/core-image-minimal-qemuarm64.rootfs.cve.json");
|
||||
vec![crate::pipeline::yocto_cve_check::read(&path).unwrap()]
|
||||
}
|
||||
|
||||
fn alert(package: &str, version: &str, cve: &str) -> CveAlert {
|
||||
CveAlert::new(
|
||||
cve.into(),
|
||||
"t".into(),
|
||||
package.into(),
|
||||
version.into(),
|
||||
compliance_core::models::CveSource::Nvd,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn yoctos_own_verdict_comes_first() {
|
||||
let images = built_images();
|
||||
let checks = checks();
|
||||
let built = Built::new(&images, &checks);
|
||||
let statements = built.statements(
|
||||
&[],
|
||||
&[
|
||||
// Patched, with the reason.
|
||||
alert("glibc", "2.39+git", "CVE-2024-2961"),
|
||||
// Ignored as disputed: still to be assessed, with the note.
|
||||
alert("glibc", "2.39+git", "CVE-2019-1010022"),
|
||||
// Ignored as not applicable to the configuration.
|
||||
alert("zlib", "1.3.1", "CVE-2026-22184"),
|
||||
// Unpatched: no statement.
|
||||
alert("glibc", "2.39+git", "CVE-2026-5450"),
|
||||
],
|
||||
);
|
||||
let by_cve = |cve: &str| statements.iter().find(|(c, _)| c == cve).map(|(_, v)| v);
|
||||
let patched = by_cve("CVE-2024-2961").unwrap();
|
||||
assert_eq!(patched.status, VexStatus::Fixed);
|
||||
assert!(patched
|
||||
.impact_statement
|
||||
.as_deref()
|
||||
.unwrap()
|
||||
.starts_with("Yocto cve-check: Patched (cpe-stable-backport)"));
|
||||
assert_eq!(
|
||||
by_cve("CVE-2019-1010022").unwrap().status,
|
||||
VexStatus::UnderInvestigation
|
||||
);
|
||||
assert_eq!(
|
||||
by_cve("CVE-2026-22184").unwrap().status,
|
||||
VexStatus::NotAffected
|
||||
);
|
||||
assert!(by_cve("CVE-2026-5450").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unpatched_cves_the_match_missed_are_added() {
|
||||
let images = built_images();
|
||||
let checks = checks();
|
||||
let built = Built::new(&images, &checks);
|
||||
let have = [alert("glibc", "2.39+git", "CVE-2026-5450")];
|
||||
let missing = built.unpatched_missing(&have, |name| name != "zlib");
|
||||
assert_eq!(missing.len(), 1);
|
||||
let (name, version, cves) = &missing[0];
|
||||
assert_eq!((name.as_str(), version.as_str()), ("glibc", "2.39+git"));
|
||||
let ids: Vec<&str> = cves.iter().map(|c| c.id.as_str()).collect();
|
||||
assert_eq!(ids, ["CVE-2010-4756", "CVE-2026-5928"]);
|
||||
assert_eq!(cves[1].cvss, Some(7.5));
|
||||
// A recipe that is not a component of the scan gets nothing.
|
||||
assert!(built.unpatched_missing(&have, |_| false).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_kernel_report_filtered_by_compiled_files_settles_kernel_cves() {
|
||||
// Yocto's improve_kernel_cve_report.py over a real scarthgap kernel
|
||||
// (linux-yocto 6.6.151) with its compiled sources and the kernel
|
||||
// CNA's data, trimmed to two CVEs of each verdict.
|
||||
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../fixtures/yocto/linux-yocto.improved-cve-report.json");
|
||||
let checks = vec![crate::pipeline::yocto_cve_check::read(&path).unwrap()];
|
||||
let built = Built::new(&[], &checks);
|
||||
let version = "6.6.151+git";
|
||||
let status = |cve: &str| {
|
||||
built
|
||||
.statements(&[], &[alert("linux-yocto", version, cve)])
|
||||
.first()
|
||||
.map(|(_, v)| (v.status, v.justification))
|
||||
};
|
||||
// Its files are not compiled into this kernel.
|
||||
assert_eq!(
|
||||
status("CVE-2023-52586"),
|
||||
Some((
|
||||
VexStatus::NotAffected,
|
||||
Some(VexJustification::VulnerableCodeNotPresent)
|
||||
))
|
||||
);
|
||||
// Withdrawn by the kernel's CNA.
|
||||
assert_eq!(
|
||||
status("CVE-2021-46907").map(|s| s.0),
|
||||
Some(VexStatus::NotAffected)
|
||||
);
|
||||
// Outside the affected versions: not affected, not "fixed".
|
||||
assert_eq!(
|
||||
status("CVE-2024-0053"),
|
||||
Some((
|
||||
VexStatus::NotAffected,
|
||||
Some(VexJustification::VulnerableCodeNotPresent)
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
status("CVE-2019-25160").map(|s| s.0),
|
||||
Some(VexStatus::Fixed)
|
||||
);
|
||||
assert_eq!(
|
||||
status("CVE-2022-48669").map(|s| s.0),
|
||||
Some(VexStatus::Fixed)
|
||||
);
|
||||
// In range and not patched: open.
|
||||
assert_eq!(status("CVE-2024-42067"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_spdx3_vex_settles_what_it_says_does_not_affect() {
|
||||
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../fixtures/yocto/core-image-minimal-qemuarm64.rootfs.spdx3.json");
|
||||
let images = crate::pipeline::yocto_spdx3::read(&path, "t").unwrap();
|
||||
let built = Built::new(&images, &[]);
|
||||
let statements = built.statements(
|
||||
&[],
|
||||
&[
|
||||
alert("glibc", "2.39+git", "CVE-2019-1010022"),
|
||||
alert("busybox", "1.36.1", "CVE-2022-48174"),
|
||||
],
|
||||
);
|
||||
let by_cve = |cve: &str| statements.iter().find(|(c, _)| c == cve).map(|(_, v)| v);
|
||||
let glibc = by_cve("CVE-2019-1010022").unwrap();
|
||||
assert_eq!(glibc.status, VexStatus::NotAffected);
|
||||
assert!(glibc
|
||||
.impact_statement
|
||||
.as_deref()
|
||||
.unwrap()
|
||||
.starts_with("Yocto SPDX 3.0 VEX: not affected"));
|
||||
assert_eq!(by_cve("CVE-2022-48174").unwrap().status, VexStatus::Fixed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
//! What Yocto's own CVE check says about an image: its `cve-check` JSON.
|
||||
//!
|
||||
//! With `INHERIT += "cve-check"` a build matches every recipe against NVD
|
||||
//! and writes, next to the image, `<image>.json`: per recipe (`package`)
|
||||
//! its version and the CVEs NVD records for its products, each `Patched`
|
||||
//! (a patch or the version fixes it), `Ignored` (a CVE_STATUS sets it aside,
|
||||
//! with the reason as `detail`) or `Unpatched`. Unlike the SPDX's
|
||||
//! "CVEs fixed", this covers every CVE the build looked at, with Yocto's
|
||||
//! reason.
|
||||
//!
|
||||
//! [`read`] parses the file; [`is_cve_check`] recognises one among a target's
|
||||
//! build outputs.
|
||||
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
/// Bytes a cve-check JSON may have (a large product image's is ~50 MB).
|
||||
pub const MAX_BYTES: u64 = 256 * 1024 * 1024;
|
||||
|
||||
/// Yocto's verdict on one CVE of one recipe.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
|
||||
pub enum CheckStatus {
|
||||
Patched,
|
||||
Unpatched,
|
||||
Ignored,
|
||||
}
|
||||
|
||||
/// One CVE of one recipe, as cve-check reports it.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct CheckedIssue {
|
||||
pub id: String,
|
||||
pub status: CheckStatus,
|
||||
/// The CVE_STATUS reason (`fixed-version`, `cpe-stable-backport`,
|
||||
/// `not-applicable-config`, `disputed`, …), where one applies.
|
||||
#[serde(default)]
|
||||
pub detail: Option<String>,
|
||||
/// The CVE_STATUS note the recipe gives with it.
|
||||
#[serde(default)]
|
||||
pub description: Option<String>,
|
||||
/// NVD's description.
|
||||
#[serde(default)]
|
||||
pub summary: Option<String>,
|
||||
/// CVSS v3 base score as text (`"9.8"`, `"0.0"` for none).
|
||||
#[serde(default)]
|
||||
pub scorev3: Option<String>,
|
||||
}
|
||||
|
||||
impl CheckedIssue {
|
||||
/// The CVSS v3 base score, `None` when NVD gives none.
|
||||
pub fn cvss(&self) -> Option<f64> {
|
||||
self.scorev3
|
||||
.as_deref()
|
||||
.and_then(|s| s.parse::<f64>().ok())
|
||||
.filter(|s| *s > 0.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// One recipe of the image.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct CheckedPackage {
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
#[serde(default, rename = "issue")]
|
||||
pub issues: Vec<CheckedIssue>,
|
||||
}
|
||||
|
||||
/// A cve-check report.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct CveCheck {
|
||||
#[serde(rename = "package")]
|
||||
pub packages: Vec<CheckedPackage>,
|
||||
}
|
||||
|
||||
/// Why a cve-check JSON could not be read.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum CveCheckError {
|
||||
#[error("cannot read the cve-check report: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error("the cve-check report is larger than {MAX_BYTES} bytes")]
|
||||
TooLarge,
|
||||
#[error("not a Yocto cve-check JSON report: {0}")]
|
||||
NotCveCheck(String),
|
||||
}
|
||||
|
||||
/// Whether the file starting with `head` is a cve-check report: a JSON
|
||||
/// object whose first keys include `package` or `version`.
|
||||
pub fn is_cve_check(head: &[u8]) -> bool {
|
||||
let text = String::from_utf8_lossy(head);
|
||||
let text = text.trim_start();
|
||||
text.starts_with('{') && (text.contains("\"package\"") || text.contains("\"version\""))
|
||||
}
|
||||
|
||||
/// Read the cve-check report at `path`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The file cannot be read, is larger than [`MAX_BYTES`], or is not a
|
||||
/// cve-check report.
|
||||
pub fn read(path: &Path) -> Result<CveCheck, CveCheckError> {
|
||||
let file = std::fs::File::open(path)?;
|
||||
let mut bytes = Vec::new();
|
||||
file.take(MAX_BYTES + 1).read_to_end(&mut bytes)?;
|
||||
if bytes.len() as u64 > MAX_BYTES {
|
||||
return Err(CveCheckError::TooLarge);
|
||||
}
|
||||
serde_json::from_slice(&bytes).map_err(|e| CveCheckError::NotCveCheck(e.to_string()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A trimmed copy of a real scarthgap (5.0.21) core-image-minimal's
|
||||
/// cve-check report: glibc, busybox and zlib with each status.
|
||||
fn fixture() -> std::path::PathBuf {
|
||||
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../fixtures/yocto/core-image-minimal-qemuarm64.rootfs.cve.json")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_report_lists_each_recipe_with_yoctos_verdicts() {
|
||||
let check = read(&fixture()).unwrap();
|
||||
let names: Vec<(&str, &str)> = check
|
||||
.packages
|
||||
.iter()
|
||||
.map(|p| (p.name.as_str(), p.version.as_str()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
("glibc", "2.39+git"),
|
||||
("busybox", "1.36.1"),
|
||||
("zlib", "1.3.1")
|
||||
]
|
||||
);
|
||||
let glibc = &check.packages[0];
|
||||
let status = |id: &str| glibc.issues.iter().find(|i| i.id == id).unwrap();
|
||||
assert_eq!(status("CVE-2024-2961").status, CheckStatus::Patched);
|
||||
assert_eq!(
|
||||
status("CVE-2024-2961").detail.as_deref(),
|
||||
Some("cpe-stable-backport")
|
||||
);
|
||||
assert_eq!(status("CVE-2019-1010022").status, CheckStatus::Ignored);
|
||||
assert_eq!(
|
||||
status("CVE-2019-1010022").detail.as_deref(),
|
||||
Some("disputed")
|
||||
);
|
||||
assert!(status("CVE-2019-1010022").description.is_some());
|
||||
let unpatched: Vec<&str> = glibc
|
||||
.issues
|
||||
.iter()
|
||||
.filter(|i| i.status == CheckStatus::Unpatched)
|
||||
.map(|i| i.id.as_str())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
unpatched,
|
||||
["CVE-2010-4756", "CVE-2026-5450", "CVE-2026-5928"]
|
||||
);
|
||||
assert_eq!(status("CVE-2026-5450").cvss(), Some(9.8));
|
||||
// "0.0" is no score.
|
||||
assert_eq!(status("CVE-2010-4756").cvss(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_report_is_recognised_by_its_start() {
|
||||
let head = std::fs::read(fixture()).unwrap();
|
||||
assert!(is_cve_check(&head[..64.min(head.len())]));
|
||||
assert!(!is_cve_check(&[0x28, 0xb5, 0x2f, 0xfd]));
|
||||
assert!(!is_cve_check(b"[1, 2]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn something_else_is_refused() {
|
||||
let dir = std::env::temp_dir().join(format!("cs-cvecheck-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("x.json");
|
||||
std::fs::write(&path, br#"{"spdxVersion": "SPDX-2.2"}"#).unwrap();
|
||||
assert!(matches!(read(&path), Err(CveCheckError::NotCveCheck(_))));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -323,7 +323,7 @@ impl RecipeVersion {
|
||||
/// The release part of a PV: what precedes a git or SCM suffix or a variable
|
||||
/// the tree does not define (`1.0+git${SRCPV}` → `1.0`). `None` when nothing
|
||||
/// is left (`git`, `+git`).
|
||||
fn release_of(pv: &str) -> Option<String> {
|
||||
pub(crate) fn release_of(pv: &str) -> Option<String> {
|
||||
let end = ["${", "+git", "AUTOINC", "+svn", "+hg", "+cvs"]
|
||||
.iter()
|
||||
.filter_map(|marker| pv.find(marker))
|
||||
@@ -820,7 +820,7 @@ pub fn nvd_queries(recipes: &[Recipe]) -> (Vec<NvdQuery>, Vec<String>) {
|
||||
/// set aside (`upstream-wontfix`, `disputed`, `ignored`) `under_investigation`
|
||||
/// with the reason as a note. `unpatched` and `vulnerable-investigation` make
|
||||
/// none: the alert stays open for a person to assess.
|
||||
fn status_statement(status: &str) -> Option<(VexStatus, Option<VexJustification>)> {
|
||||
pub(crate) fn status_statement(status: &str) -> Option<(VexStatus, Option<VexJustification>)> {
|
||||
match status {
|
||||
"backported-patch" | "cpe-stable-backport" | "fixed-version" => {
|
||||
Some((VexStatus::Fixed, None))
|
||||
@@ -829,6 +829,8 @@ fn status_statement(status: &str) -> Option<(VexStatus, Option<VexJustification>
|
||||
VexStatus::NotAffected,
|
||||
Some(VexJustification::ComponentNotPresent),
|
||||
)),
|
||||
// The CVE was withdrawn by its CNA (Yocto's kernel CVE report).
|
||||
"rejected" => Some((VexStatus::NotAffected, None)),
|
||||
"not-applicable-platform" | "not-applicable-config" => Some((
|
||||
VexStatus::NotAffected,
|
||||
Some(VexJustification::VulnerableCodeNotPresent),
|
||||
@@ -842,7 +844,7 @@ fn status_statement(status: &str) -> Option<(VexStatus, Option<VexJustification>
|
||||
}
|
||||
|
||||
/// A statement the scan makes, saying where it comes from.
|
||||
fn scan_statement(
|
||||
pub(crate) fn scan_statement(
|
||||
status: VexStatus,
|
||||
justification: Option<VexJustification>,
|
||||
because: String,
|
||||
|
||||
@@ -0,0 +1,650 @@
|
||||
//! What a Yocto build put into an image, read from the build's own SPDX 2.2.
|
||||
//!
|
||||
//! Yocto's `create-spdx` class (the default since kirkstone; scarthgap writes
|
||||
//! SPDX 2.2) archives one document per image, binary package, recipe and
|
||||
//! runtime set into `<image>.spdx.tar.zst` next to the image. The image
|
||||
//! document `CONTAINS` the packages that are installed, each package is
|
||||
//! `GENERATED_FROM` its recipe, and the documents point at each other through
|
||||
//! `externalDocumentRefs` by namespace. Unlike the recipe inventory
|
||||
//! ([`crate::pipeline::yocto_inventory`]), which reads the recipes as written,
|
||||
//! this is what the build resolved: overrides, PACKAGECONFIG and the machine
|
||||
//! applied, only what is in the image.
|
||||
//!
|
||||
//! [`read_archive`] (or [`read_dir`] for an extracted archive) returns one
|
||||
//! [`BuiltImage`] per image document: an SBOM component per recipe with
|
||||
//! packages in the image (recipe version, declared licence, the CPEs NVD
|
||||
//! knows it by), marked [`InImageBasis::Built`], and the CVEs the recipe's
|
||||
//! patches fix (`sourceInfo: "CVEs fixed: …"`), which settle those CVEs as
|
||||
//! fixed. References that cannot be resolved are listed, not guessed.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use compliance_core::models::{InImage, InImageBasis, SbomEntry, YOCTO_RECIPE_MANAGER};
|
||||
use compliance_core::purl::encode;
|
||||
|
||||
/// Where a component read from the build's SPDX comes from, on its evidence.
|
||||
pub const SOURCE: &str = "Yocto build SPDX";
|
||||
|
||||
/// The scan run's stage id for the build's image SPDX.
|
||||
pub const STAGE: &str = "build_spdx";
|
||||
|
||||
/// Limits on an uploaded archive: it is untrusted input.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ReadLimits {
|
||||
/// Documents read at most.
|
||||
pub max_documents: usize,
|
||||
/// Bytes one document may have once decompressed.
|
||||
pub max_document_bytes: u64,
|
||||
/// Bytes all documents may have together once decompressed.
|
||||
pub max_total_bytes: u64,
|
||||
}
|
||||
|
||||
impl Default for ReadLimits {
|
||||
fn default() -> Self {
|
||||
// A core-image-minimal archive holds ~380 documents and ~11 MB; a
|
||||
// large product image a few thousand.
|
||||
Self {
|
||||
max_documents: 20_000,
|
||||
max_document_bytes: 64 * 1024 * 1024,
|
||||
max_total_bytes: 1024 * 1024 * 1024,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the build's SPDX could not be read.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum YoctoSpdxError {
|
||||
#[error("cannot read the SPDX archive: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error("the SPDX archive exceeds its limits: {0}")]
|
||||
TooLarge(&'static str),
|
||||
#[error("{file} is not an SPDX 2.2 JSON document: {reason}")]
|
||||
NotSpdx { file: String, reason: String },
|
||||
#[error("no image document (an SPDX package `SPDXRef-Image-…`) in the archive")]
|
||||
NoImage,
|
||||
}
|
||||
|
||||
/// One image as the build made it.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BuiltImage {
|
||||
/// The image recipe (`core-image-minimal`).
|
||||
pub image: String,
|
||||
/// The image document's package id, which carries the machine and build
|
||||
/// time (`SPDXRef-Image-core-image-minimal-qemuarm64.rootfs-…`).
|
||||
pub image_id: String,
|
||||
/// One component per recipe with packages in the image, sorted by name.
|
||||
pub entries: Vec<SbomEntry>,
|
||||
/// The CVEs the recipes' patches fix, per component, sorted.
|
||||
pub fixed: Vec<FixedCve>,
|
||||
/// Packages the image contains whose documents are not in the archive,
|
||||
/// or whose recipe is not (`missing-pkg`), sorted.
|
||||
pub unresolved: Vec<String>,
|
||||
/// The CVEs the build's SPDX states do not affect a component (SPDX 3.0
|
||||
/// VEX), sorted; SPDX 2.2 states none.
|
||||
pub not_affected: Vec<NotAffectedCve>,
|
||||
}
|
||||
|
||||
/// A CVE the build's SPDX says does not affect a component, and why.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct NotAffectedCve {
|
||||
pub component: String,
|
||||
pub version: String,
|
||||
pub cve: String,
|
||||
/// The SPDX 3.0 justification (`vulnerableCodeNotPresent`, …).
|
||||
pub justification: Option<String>,
|
||||
/// The impact statement (`This issue has kernel fixes …`).
|
||||
pub statement: Option<String>,
|
||||
}
|
||||
|
||||
/// A CVE a recipe's patch fixes in the component built from it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct FixedCve {
|
||||
pub component: String,
|
||||
pub version: String,
|
||||
pub cve: String,
|
||||
}
|
||||
|
||||
/// Read the images of a `<image>.spdx.tar.zst` archive.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The archive cannot be read, exceeds `limits`, holds a document that is
|
||||
/// not SPDX JSON, or holds no image document.
|
||||
pub fn read_archive(
|
||||
archive: &Path,
|
||||
repo_id: &str,
|
||||
limits: ReadLimits,
|
||||
) -> Result<Vec<BuiltImage>, YoctoSpdxError> {
|
||||
let file = std::fs::File::open(archive)?;
|
||||
let decoder = zstd::stream::read::Decoder::new(file)?;
|
||||
let mut tar = tar::Archive::new(decoder);
|
||||
let mut documents = Vec::new();
|
||||
let mut total = 0u64;
|
||||
for entry in tar.entries()? {
|
||||
let entry = entry?;
|
||||
if !entry.header().entry_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
let name = entry.path()?.to_string_lossy().into_owned();
|
||||
if !name.ends_with(".spdx.json") {
|
||||
continue;
|
||||
}
|
||||
if documents.len() >= limits.max_documents {
|
||||
return Err(YoctoSpdxError::TooLarge("too many documents"));
|
||||
}
|
||||
// `take` caps what is read whatever the header claims.
|
||||
let mut bytes = Vec::new();
|
||||
entry
|
||||
.take(limits.max_document_bytes + 1)
|
||||
.read_to_end(&mut bytes)?;
|
||||
if bytes.len() as u64 > limits.max_document_bytes {
|
||||
return Err(YoctoSpdxError::TooLarge("a document is too large"));
|
||||
}
|
||||
total += bytes.len() as u64;
|
||||
if total > limits.max_total_bytes {
|
||||
return Err(YoctoSpdxError::TooLarge(
|
||||
"the documents are too large together",
|
||||
));
|
||||
}
|
||||
documents.push((name, bytes));
|
||||
}
|
||||
images(&parse(documents)?, repo_id)
|
||||
}
|
||||
|
||||
/// Read the images of an extracted archive: every `*.spdx.json` directly in
|
||||
/// `dir`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// As [`read_archive`].
|
||||
pub fn read_dir(
|
||||
dir: &Path,
|
||||
repo_id: &str,
|
||||
limits: ReadLimits,
|
||||
) -> Result<Vec<BuiltImage>, YoctoSpdxError> {
|
||||
let mut documents = Vec::new();
|
||||
let mut total = 0u64;
|
||||
let mut paths: Vec<_> = std::fs::read_dir(dir)?
|
||||
.filter_map(Result::ok)
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.is_file() && p.to_string_lossy().ends_with(".spdx.json"))
|
||||
.collect();
|
||||
paths.sort();
|
||||
if paths.len() > limits.max_documents {
|
||||
return Err(YoctoSpdxError::TooLarge("too many documents"));
|
||||
}
|
||||
for path in paths {
|
||||
let size = std::fs::metadata(&path)?.len();
|
||||
if size > limits.max_document_bytes {
|
||||
return Err(YoctoSpdxError::TooLarge("a document is too large"));
|
||||
}
|
||||
total += size;
|
||||
if total > limits.max_total_bytes {
|
||||
return Err(YoctoSpdxError::TooLarge(
|
||||
"the documents are too large together",
|
||||
));
|
||||
}
|
||||
let name = path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
documents.push((name, std::fs::read(&path)?));
|
||||
}
|
||||
images(&parse(documents)?, repo_id)
|
||||
}
|
||||
|
||||
/// An SPDX 2.2 document, as far as it is read here.
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Document {
|
||||
#[serde(rename = "documentNamespace")]
|
||||
namespace: String,
|
||||
#[serde(default)]
|
||||
packages: Vec<Package>,
|
||||
#[serde(default)]
|
||||
relationships: Vec<Relationship>,
|
||||
#[serde(default, rename = "externalDocumentRefs")]
|
||||
external: Vec<ExternalRef>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Package {
|
||||
#[serde(rename = "SPDXID")]
|
||||
id: String,
|
||||
name: String,
|
||||
#[serde(default, rename = "versionInfo")]
|
||||
version: Option<String>,
|
||||
#[serde(default, rename = "licenseDeclared")]
|
||||
license: Option<String>,
|
||||
#[serde(default, rename = "externalRefs")]
|
||||
refs: Vec<PackageRef>,
|
||||
#[serde(default, rename = "sourceInfo")]
|
||||
source_info: Option<String>,
|
||||
#[serde(default)]
|
||||
homepage: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct PackageRef {
|
||||
#[serde(rename = "referenceType")]
|
||||
kind: String,
|
||||
#[serde(rename = "referenceLocator")]
|
||||
locator: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Relationship {
|
||||
#[serde(rename = "spdxElementId")]
|
||||
from: String,
|
||||
#[serde(rename = "relationshipType")]
|
||||
kind: String,
|
||||
#[serde(rename = "relatedSpdxElement")]
|
||||
to: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ExternalRef {
|
||||
#[serde(rename = "externalDocumentId")]
|
||||
id: String,
|
||||
#[serde(rename = "spdxDocument")]
|
||||
namespace: String,
|
||||
}
|
||||
|
||||
/// The documents by namespace.
|
||||
fn parse(documents: Vec<(String, Vec<u8>)>) -> Result<HashMap<String, Document>, YoctoSpdxError> {
|
||||
let mut by_namespace = HashMap::with_capacity(documents.len());
|
||||
for (file, bytes) in documents {
|
||||
let doc: Document =
|
||||
serde_json::from_slice(&bytes).map_err(|e| YoctoSpdxError::NotSpdx {
|
||||
file: file.clone(),
|
||||
reason: e.to_string(),
|
||||
})?;
|
||||
by_namespace.insert(doc.namespace.clone(), doc);
|
||||
}
|
||||
Ok(by_namespace)
|
||||
}
|
||||
|
||||
/// The package `local` of the document `doc` refers to as `reference`
|
||||
/// (`DocumentRef-busybox:SPDXRef-Package-busybox`), with its document.
|
||||
fn resolve<'a>(
|
||||
docs: &'a HashMap<String, Document>,
|
||||
doc: &Document,
|
||||
reference: &str,
|
||||
) -> Option<(&'a Document, &'a Package)> {
|
||||
let (doc_ref, local) = reference.split_once(':')?;
|
||||
let namespace = &doc.external.iter().find(|e| e.id == doc_ref)?.namespace;
|
||||
let target = docs.get(namespace)?;
|
||||
let package = target.packages.iter().find(|p| p.id == local)?;
|
||||
Some((target, package))
|
||||
}
|
||||
|
||||
/// Every image of `docs`.
|
||||
fn images(
|
||||
docs: &HashMap<String, Document>,
|
||||
repo_id: &str,
|
||||
) -> Result<Vec<BuiltImage>, YoctoSpdxError> {
|
||||
let mut out = Vec::new();
|
||||
for doc in docs.values() {
|
||||
for image in doc
|
||||
.packages
|
||||
.iter()
|
||||
.filter(|p| p.id.starts_with("SPDXRef-Image-"))
|
||||
{
|
||||
out.push(built_image(docs, doc, image, repo_id));
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Err(YoctoSpdxError::NoImage);
|
||||
}
|
||||
out.sort_by(|a, b| a.image_id.cmp(&b.image_id));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A recipe with packages in the image, and those packages.
|
||||
struct RecipeInImage<'a> {
|
||||
recipe: &'a Package,
|
||||
packages: BTreeSet<&'a str>,
|
||||
}
|
||||
|
||||
/// The image `image` of the document `doc`.
|
||||
fn built_image(
|
||||
docs: &HashMap<String, Document>,
|
||||
doc: &Document,
|
||||
image: &Package,
|
||||
repo_id: &str,
|
||||
) -> BuiltImage {
|
||||
let mut recipes: BTreeMap<(String, String), RecipeInImage<'_>> = BTreeMap::new();
|
||||
let mut unresolved = BTreeSet::new();
|
||||
let contained = doc
|
||||
.relationships
|
||||
.iter()
|
||||
.filter(|r| r.from == image.id && r.kind == "CONTAINS");
|
||||
for rel in contained {
|
||||
let Some((package_doc, package)) = resolve(docs, doc, &rel.to) else {
|
||||
unresolved.insert(package_name(&rel.to));
|
||||
continue;
|
||||
};
|
||||
let recipe = package_doc
|
||||
.relationships
|
||||
.iter()
|
||||
.filter(|r| r.from == package.id && r.kind == "GENERATED_FROM")
|
||||
.find_map(|r| resolve(docs, package_doc, &r.to))
|
||||
.map(|(_, recipe)| recipe)
|
||||
.filter(|recipe| recipe.id.starts_with("SPDXRef-Recipe-"));
|
||||
let Some(recipe) = recipe else {
|
||||
unresolved.insert(package.name.clone());
|
||||
continue;
|
||||
};
|
||||
let version = recipe
|
||||
.version
|
||||
.clone()
|
||||
.or_else(|| package.version.clone())
|
||||
.unwrap_or_default();
|
||||
recipes
|
||||
.entry((recipe.name.clone(), version))
|
||||
.or_insert_with(|| RecipeInImage {
|
||||
recipe,
|
||||
packages: BTreeSet::new(),
|
||||
})
|
||||
.packages
|
||||
.insert(package.name.as_str());
|
||||
}
|
||||
|
||||
let mut entries = Vec::with_capacity(recipes.len());
|
||||
let mut fixed = Vec::new();
|
||||
for ((name, version), found) in &recipes {
|
||||
let facts = ComponentFacts {
|
||||
name,
|
||||
version,
|
||||
license: found.recipe.license.as_deref(),
|
||||
cpe: cpes(found.recipe).into_iter().next(),
|
||||
homepage: found.recipe.homepage.as_deref(),
|
||||
packages: found.packages.iter().copied().collect(),
|
||||
};
|
||||
let label = image.id.trim_start_matches("SPDXRef-Image-");
|
||||
entries.push(component(facts, &image.name, label, repo_id));
|
||||
fixed.extend(fixed_cves(found.recipe).into_iter().map(|cve| FixedCve {
|
||||
component: name.clone(),
|
||||
version: version.clone(),
|
||||
cve,
|
||||
}));
|
||||
}
|
||||
fixed.sort();
|
||||
BuiltImage {
|
||||
image: image.name.clone(),
|
||||
image_id: image.id.clone(),
|
||||
entries,
|
||||
fixed,
|
||||
unresolved: unresolved.into_iter().collect(),
|
||||
not_affected: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the build's SPDX (2.2 or 3.0) says about one recipe in the image.
|
||||
pub(crate) struct ComponentFacts<'a> {
|
||||
pub name: &'a str,
|
||||
pub version: &'a str,
|
||||
/// The declared licence as written (document prefixes are dropped here).
|
||||
pub license: Option<&'a str>,
|
||||
/// The first CPE 2.3 name it is known by.
|
||||
pub cpe: Option<String>,
|
||||
pub homepage: Option<&'a str>,
|
||||
/// Its packages in the image, sorted.
|
||||
pub packages: Vec<&'a str>,
|
||||
}
|
||||
|
||||
/// The SBOM component of one recipe in the image `image`, whose SPDX the
|
||||
/// evidence names as `label` (the image document's id).
|
||||
pub(crate) fn component(
|
||||
facts: ComponentFacts<'_>,
|
||||
image: &str,
|
||||
label: &str,
|
||||
repo_id: &str,
|
||||
) -> SbomEntry {
|
||||
let (name, version) = (facts.name, facts.version);
|
||||
let mut entry = SbomEntry::new(
|
||||
repo_id.to_string(),
|
||||
name.to_string(),
|
||||
version.to_string(),
|
||||
YOCTO_RECIPE_MANAGER.to_string(),
|
||||
);
|
||||
entry.purl = Some(if version.is_empty() {
|
||||
format!("pkg:generic/{}", encode(name))
|
||||
} else {
|
||||
format!("pkg:generic/{}@{}", encode(name), encode(version))
|
||||
});
|
||||
entry.license = facts.license.and_then(license);
|
||||
entry.cpe = facts.cpe;
|
||||
entry.manufacturer_url = facts
|
||||
.homepage
|
||||
.filter(|h| h.starts_with("https://") || h.starts_with("http://"))
|
||||
.map(str::to_string);
|
||||
entry.evidence.push(format!(
|
||||
"{SOURCE} ({label}): packages {}",
|
||||
facts.packages.join(", ")
|
||||
));
|
||||
let in_image = InImage {
|
||||
basis: InImageBasis::Built,
|
||||
images: vec![image.to_string()],
|
||||
};
|
||||
entry.evidence.push(in_image.describe());
|
||||
entry.in_image = Some(in_image);
|
||||
entry
|
||||
}
|
||||
|
||||
/// The package name of an unresolved reference
|
||||
/// (`DocumentRef-x:SPDXRef-Package-busybox` → `busybox`).
|
||||
fn package_name(reference: &str) -> String {
|
||||
let local = reference.split_once(':').map_or(reference, |(_, l)| l);
|
||||
local
|
||||
.strip_prefix("SPDXRef-Package-")
|
||||
.unwrap_or(local)
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// A declared licence as an SPDX expression, without the document prefix of
|
||||
/// a licence defined in another document (`DocumentRef-recipe-busybox:
|
||||
/// LicenseRef-bzip2-1.0.4` → `LicenseRef-bzip2-1.0.4`); `None` for
|
||||
/// NOASSERTION, NONE or nothing.
|
||||
pub(crate) fn license(declared: &str) -> Option<String> {
|
||||
let cleaned: Vec<String> = declared
|
||||
.split_whitespace()
|
||||
.map(|token| {
|
||||
let (open, rest) = token.split_at(token.len() - token.trim_start_matches('(').len());
|
||||
let inner = rest.trim_end_matches(')');
|
||||
let close = &rest[inner.len()..];
|
||||
let inner = match inner.split_once(':') {
|
||||
Some((doc, id)) if doc.starts_with("DocumentRef-") => id,
|
||||
_ => inner,
|
||||
};
|
||||
format!("{open}{inner}{close}")
|
||||
})
|
||||
.collect();
|
||||
let expression = cleaned.join(" ");
|
||||
match expression.as_str() {
|
||||
"" | "NOASSERTION" | "NONE" => None,
|
||||
_ => Some(expression),
|
||||
}
|
||||
}
|
||||
|
||||
/// The CPE 2.3 names a recipe is known by (CVE_PRODUCT), in order.
|
||||
fn cpes(recipe: &Package) -> Vec<String> {
|
||||
recipe
|
||||
.refs
|
||||
.iter()
|
||||
.filter(|r| r.kind.ends_with("cpe23Type"))
|
||||
.map(|r| r.locator.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The CVEs a recipe's patches fix: create-spdx writes them into the
|
||||
/// recipe's `sourceInfo` as `CVEs fixed: CVE-… CVE-…`.
|
||||
fn fixed_cves(recipe: &Package) -> Vec<String> {
|
||||
let Some(rest) = recipe
|
||||
.source_info
|
||||
.as_deref()
|
||||
.and_then(|s| s.split_once("CVEs fixed:"))
|
||||
.map(|(_, rest)| rest)
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut cves: Vec<String> = rest
|
||||
.split(|c: char| c.is_whitespace() || c == ',')
|
||||
.filter(|t| t.starts_with("CVE-") && t.len() > 4)
|
||||
.map(str::to_string)
|
||||
.collect();
|
||||
cves.sort();
|
||||
cves.dedup();
|
||||
cves
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A trimmed copy of a real scarthgap (5.0.21) core-image-minimal for
|
||||
/// qemuarm64: four recipes and one package whose document is missing.
|
||||
fn fixtures() -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixtures/yocto")
|
||||
}
|
||||
|
||||
fn check(images: &[BuiltImage]) {
|
||||
assert_eq!(images.len(), 1);
|
||||
let image = &images[0];
|
||||
assert_eq!(image.image, "core-image-minimal");
|
||||
assert!(image.image_id.contains("qemuarm64"), "{}", image.image_id);
|
||||
|
||||
let names: Vec<(&str, &str)> = image
|
||||
.entries
|
||||
.iter()
|
||||
.map(|e| (e.name.as_str(), e.version.as_str()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
("base-files", "3.0.14"),
|
||||
("busybox", "1.36.1"),
|
||||
("openssl", "3.5.9"),
|
||||
("packagegroup-core-boot", "1.0"),
|
||||
]
|
||||
);
|
||||
|
||||
let busybox = &image.entries[1];
|
||||
assert_eq!(busybox.package_manager, YOCTO_RECIPE_MANAGER);
|
||||
assert_eq!(busybox.purl.as_deref(), Some("pkg:generic/busybox@1.36.1"));
|
||||
assert_eq!(
|
||||
busybox.license.as_deref(),
|
||||
Some("GPL-2.0-only AND LicenseRef-bzip2-1.0.4")
|
||||
);
|
||||
assert_eq!(
|
||||
busybox.cpe.as_deref(),
|
||||
Some("cpe:2.3:*:*:busybox:1.36.1:*:*:*:*:*:*:*")
|
||||
);
|
||||
let in_image = busybox.in_image.as_ref().expect("in the image");
|
||||
assert_eq!(in_image.basis, InImageBasis::Built);
|
||||
assert_eq!(in_image.images, ["core-image-minimal"]);
|
||||
// Its three packages are one component.
|
||||
assert!(
|
||||
busybox.evidence[0].ends_with("packages busybox, busybox-syslog, busybox-udhcpc"),
|
||||
"{:?}",
|
||||
busybox.evidence
|
||||
);
|
||||
|
||||
let openssl = &image.entries[2];
|
||||
assert_eq!(
|
||||
openssl.cpe.as_deref(),
|
||||
Some("cpe:2.3:*:openssl:openssl:3.5.9:*:*:*:*:*:*:*")
|
||||
);
|
||||
// A package group has no CPE: NVD knows nothing by that name.
|
||||
assert_eq!(image.entries[3].cpe, None);
|
||||
|
||||
let busybox_fixed: Vec<&str> = image
|
||||
.fixed
|
||||
.iter()
|
||||
.filter(|f| f.component == "busybox")
|
||||
.map(|f| f.cve.as_str())
|
||||
.collect();
|
||||
assert_eq!(busybox_fixed.len(), 15);
|
||||
assert!(busybox_fixed.contains(&"CVE-2022-48174"));
|
||||
assert!(busybox_fixed.windows(2).all(|w| w[0] < w[1]), "sorted");
|
||||
|
||||
assert_eq!(image.unresolved, ["missing-pkg"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_extracted_archive_lists_what_the_build_installed() {
|
||||
let images = read_dir(
|
||||
&fixtures().join("spdx-scarthgap"),
|
||||
"t",
|
||||
ReadLimits::default(),
|
||||
)
|
||||
.unwrap();
|
||||
check(&images);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_image_archive_reads_the_same() {
|
||||
let images = read_archive(
|
||||
&fixtures().join("core-image-minimal-qemuarm64.rootfs.spdx.tar.zst"),
|
||||
"t",
|
||||
ReadLimits::default(),
|
||||
)
|
||||
.unwrap();
|
||||
check(&images);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_archive_past_its_limits_is_refused() {
|
||||
let archive = fixtures().join("core-image-minimal-qemuarm64.rootfs.spdx.tar.zst");
|
||||
let few = ReadLimits {
|
||||
max_documents: 3,
|
||||
..ReadLimits::default()
|
||||
};
|
||||
assert!(matches!(
|
||||
read_archive(&archive, "t", few),
|
||||
Err(YoctoSpdxError::TooLarge(_))
|
||||
));
|
||||
let small = ReadLimits {
|
||||
max_document_bytes: 100,
|
||||
..ReadLimits::default()
|
||||
};
|
||||
assert!(matches!(
|
||||
read_archive(&archive, "t", small),
|
||||
Err(YoctoSpdxError::TooLarge(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn documents_without_an_image_or_not_spdx_are_refused() {
|
||||
let docs = vec![(
|
||||
"recipe-x.spdx.json".to_string(),
|
||||
br#"{"documentNamespace": "urn:x", "packages": [{"SPDXID": "SPDXRef-Recipe-x", "name": "x"}]}"#.to_vec(),
|
||||
)];
|
||||
assert!(matches!(
|
||||
images(&parse(docs).unwrap(), "t"),
|
||||
Err(YoctoSpdxError::NoImage)
|
||||
));
|
||||
let broken = vec![("a.spdx.json".to_string(), b"{".to_vec())];
|
||||
assert!(matches!(parse(broken), Err(YoctoSpdxError::NotSpdx { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn licences_lose_the_document_prefix_and_noassertion_is_none() {
|
||||
assert_eq!(
|
||||
license("GPL-2.0-only AND DocumentRef-recipe-busybox:LicenseRef-bzip2-1.0.4")
|
||||
.as_deref(),
|
||||
Some("GPL-2.0-only AND LicenseRef-bzip2-1.0.4")
|
||||
);
|
||||
assert_eq!(
|
||||
license("(MIT OR DocumentRef-r:LicenseRef-x)").as_deref(),
|
||||
Some("(MIT OR LicenseRef-x)")
|
||||
);
|
||||
assert_eq!(license("NOASSERTION"), None);
|
||||
assert_eq!(license(" "), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
//! What a Yocto build put into an image, read from the build's own SPDX 3.0.
|
||||
//!
|
||||
//! With `create-spdx-3.0` (the default from Styhead 5.1 on, available in
|
||||
//! Scarthgap) a build writes one JSON-LD document per image,
|
||||
//! `<image>.rootfs.spdx.json`, holding the whole graph:
|
||||
//!
|
||||
//! - the image is a `software_Package` whose purpose is `archive`, output
|
||||
//! (`hasOutput`) of the rootfs `build_Build`;
|
||||
//! - the packages installed in it are that build's inputs (`hasInput`), each
|
||||
//! a `software_Package` of purpose `install` with its version, CPE and
|
||||
//! homepage, its licence through `hasConcludedLicense`;
|
||||
//! - each package is output of its recipe's build,
|
||||
//! `<recipe>:do_create_spdx:recipe`;
|
||||
//! - the build's VEX: `security_Vulnerability` elements with their CVE id,
|
||||
//! `fixedIn` and `doesNotAffect` assessments on the packages.
|
||||
//!
|
||||
//! [`read`] returns the same [`BuiltImage`] as the SPDX 2.2 reader
|
||||
//! ([`crate::pipeline::yocto_spdx`]), with the not-affected statements too.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::io::Read as _;
|
||||
use std::path::Path;
|
||||
|
||||
use serde::{Deserialize, Deserializer};
|
||||
|
||||
use crate::pipeline::yocto_spdx::{
|
||||
component, BuiltImage, ComponentFacts, FixedCve, NotAffectedCve, YoctoSpdxError,
|
||||
};
|
||||
|
||||
/// Bytes an SPDX 3.0 image document may have (core-image-minimal's is
|
||||
/// ~7 MB; a product image with sources listed can be far larger).
|
||||
pub const MAX_BYTES: u64 = 512 * 1024 * 1024;
|
||||
|
||||
/// Whether the file starting with `head` is an SPDX 3 JSON-LD document.
|
||||
pub fn is_spdx3(head: &[u8]) -> bool {
|
||||
let text = String::from_utf8_lossy(head);
|
||||
text.trim_start().starts_with('{')
|
||||
&& text.contains("\"@context\"")
|
||||
&& text.contains("spdx.org/rdf/3")
|
||||
}
|
||||
|
||||
/// One element of the graph, as far as it is read here.
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Element {
|
||||
#[serde(rename = "type", default)]
|
||||
kind: String,
|
||||
#[serde(rename = "spdxId", default)]
|
||||
id: Option<String>,
|
||||
#[serde(default)]
|
||||
name: Option<String>,
|
||||
#[serde(rename = "software_primaryPurpose", default)]
|
||||
purpose: Option<String>,
|
||||
#[serde(rename = "software_packageVersion", default)]
|
||||
version: Option<String>,
|
||||
#[serde(rename = "software_homePage", default)]
|
||||
homepage: Option<String>,
|
||||
#[serde(rename = "externalIdentifier", default)]
|
||||
identifiers: Vec<Identifier>,
|
||||
#[serde(default)]
|
||||
from: Option<String>,
|
||||
#[serde(default, deserialize_with = "one_or_many")]
|
||||
to: Vec<String>,
|
||||
#[serde(rename = "relationshipType", default)]
|
||||
relationship: Option<String>,
|
||||
#[serde(rename = "simplelicensing_licenseExpression", default)]
|
||||
license_expression: Option<String>,
|
||||
#[serde(rename = "security_impactStatement", default)]
|
||||
impact: Option<String>,
|
||||
#[serde(rename = "security_justificationType", default)]
|
||||
justification: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Identifier {
|
||||
#[serde(rename = "externalIdentifierType")]
|
||||
kind: String,
|
||||
identifier: String,
|
||||
}
|
||||
|
||||
/// `to` is a list, or one id.
|
||||
fn one_or_many<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<String>, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum OneOrMany {
|
||||
One(String),
|
||||
Many(Vec<String>),
|
||||
}
|
||||
Ok(match Option::<OneOrMany>::deserialize(deserializer)? {
|
||||
Some(OneOrMany::One(id)) => vec![id],
|
||||
Some(OneOrMany::Many(ids)) => ids,
|
||||
None => Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Document {
|
||||
#[serde(rename = "@graph")]
|
||||
graph: Vec<Element>,
|
||||
}
|
||||
|
||||
/// Read the images of an SPDX 3.0 image document.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The file cannot be read, is larger than [`MAX_BYTES`], is not an SPDX 3
|
||||
/// JSON-LD document, or names no image.
|
||||
pub fn read(path: &Path, repo_id: &str) -> Result<Vec<BuiltImage>, YoctoSpdxError> {
|
||||
let mut bytes = Vec::new();
|
||||
std::fs::File::open(path)?
|
||||
.take(MAX_BYTES + 1)
|
||||
.read_to_end(&mut bytes)?;
|
||||
if bytes.len() as u64 > MAX_BYTES {
|
||||
return Err(YoctoSpdxError::TooLarge(
|
||||
"the SPDX 3.0 document is too large",
|
||||
));
|
||||
}
|
||||
let file = path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
let doc: Document = serde_json::from_slice(&bytes).map_err(|e| YoctoSpdxError::NotSpdx {
|
||||
file,
|
||||
reason: e.to_string(),
|
||||
})?;
|
||||
images(&doc.graph, repo_id)
|
||||
}
|
||||
|
||||
/// The graph's elements by id, and its relationships.
|
||||
struct Graph<'a> {
|
||||
by_id: HashMap<&'a str, &'a Element>,
|
||||
relationships: Vec<&'a Element>,
|
||||
}
|
||||
|
||||
impl<'a> Graph<'a> {
|
||||
fn new(elements: &'a [Element]) -> Self {
|
||||
let mut by_id = HashMap::with_capacity(elements.len());
|
||||
let mut relationships = Vec::new();
|
||||
for e in elements {
|
||||
if let Some(id) = e.id.as_deref() {
|
||||
by_id.insert(id, e);
|
||||
}
|
||||
if e.relationship.is_some() {
|
||||
relationships.push(e);
|
||||
}
|
||||
}
|
||||
Self {
|
||||
by_id,
|
||||
relationships,
|
||||
}
|
||||
}
|
||||
|
||||
/// The relationships of `kind`.
|
||||
fn of(&self, kind: &'a str) -> impl Iterator<Item = &'a Element> + '_ {
|
||||
self.relationships
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(move |r| r.relationship.as_deref() == Some(kind))
|
||||
}
|
||||
}
|
||||
|
||||
/// Every image of `elements`.
|
||||
fn images(elements: &[Element], repo_id: &str) -> Result<Vec<BuiltImage>, YoctoSpdxError> {
|
||||
let graph = Graph::new(elements);
|
||||
let mut out: Vec<BuiltImage> = elements
|
||||
.iter()
|
||||
.filter(|e| e.kind == "software_Package" && e.purpose.as_deref() == Some("archive"))
|
||||
.filter_map(|image| built_image(&graph, image, repo_id))
|
||||
.collect();
|
||||
if out.is_empty() {
|
||||
return Err(YoctoSpdxError::NoImage);
|
||||
}
|
||||
out.sort_by(|a, b| a.image_id.cmp(&b.image_id));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The image `image`, if a build outputs it.
|
||||
fn built_image(graph: &Graph<'_>, image: &Element, repo_id: &str) -> Option<BuiltImage> {
|
||||
let image_id = image.id.as_deref()?;
|
||||
let image_name = image.name.clone().unwrap_or_default();
|
||||
// The builds whose output the image is (the rootfs build).
|
||||
let rootfs: BTreeSet<&str> = graph
|
||||
.of("hasOutput")
|
||||
.filter(|r| r.to.iter().any(|t| t == image_id))
|
||||
.filter_map(|r| r.from.as_deref())
|
||||
.collect();
|
||||
let installed: BTreeSet<&str> = graph
|
||||
.of("hasInput")
|
||||
.filter(|r| r.from.as_deref().is_some_and(|f| rootfs.contains(f)))
|
||||
.flat_map(|r| r.to.iter().map(String::as_str))
|
||||
.collect();
|
||||
if rootfs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Each package's recipe: the name of the recipe build that outputs it.
|
||||
let mut recipe_of: HashMap<&str, &str> = HashMap::new();
|
||||
for r in graph.of("hasOutput") {
|
||||
let Some(build) = r.from.as_deref().and_then(|f| graph.by_id.get(f)) else {
|
||||
continue;
|
||||
};
|
||||
let Some(recipe) = build
|
||||
.name
|
||||
.as_deref()
|
||||
.and_then(|n| n.strip_suffix(":do_create_spdx:recipe"))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
for t in &r.to {
|
||||
recipe_of.insert(t.as_str(), recipe);
|
||||
}
|
||||
}
|
||||
let license_of: HashMap<&str, &str> = graph
|
||||
.of("hasConcludedLicense")
|
||||
.filter_map(|r| {
|
||||
let expression =
|
||||
r.to.iter()
|
||||
.filter_map(|t| graph.by_id.get(t.as_str()))
|
||||
.find_map(|e| e.license_expression.as_deref())?;
|
||||
Some((r.from.as_deref()?, expression))
|
||||
})
|
||||
.collect();
|
||||
|
||||
/// A recipe with packages in the image.
|
||||
struct Found<'a> {
|
||||
package: &'a Element,
|
||||
packages: BTreeSet<&'a str>,
|
||||
ids: BTreeSet<&'a str>,
|
||||
}
|
||||
let mut recipes: BTreeMap<(&str, &str), Found<'_>> = BTreeMap::new();
|
||||
let mut unresolved = BTreeSet::new();
|
||||
for id in &installed {
|
||||
let package = graph.by_id.get(id).copied();
|
||||
let recipe = package.and_then(|_| recipe_of.get(id).copied());
|
||||
let (Some(package), Some(recipe)) = (package, recipe) else {
|
||||
unresolved.insert(package_name(id));
|
||||
continue;
|
||||
};
|
||||
if package.purpose.as_deref() != Some("install") {
|
||||
continue;
|
||||
}
|
||||
let version = package.version.as_deref().unwrap_or_default();
|
||||
let found = recipes.entry((recipe, version)).or_insert_with(|| Found {
|
||||
package,
|
||||
packages: BTreeSet::new(),
|
||||
ids: BTreeSet::new(),
|
||||
});
|
||||
found
|
||||
.packages
|
||||
.insert(package.name.as_deref().unwrap_or_default());
|
||||
found.ids.insert(*id);
|
||||
}
|
||||
|
||||
// The CVE ids of the vulnerabilities, and what the VEX says per package.
|
||||
let cve_of = |id: &str| -> Option<&str> {
|
||||
graph.by_id.get(id)?.identifiers.iter().find_map(|i| {
|
||||
(i.kind == "cve" || i.identifier.starts_with("CVE-")).then_some(i.identifier.as_str())
|
||||
})
|
||||
};
|
||||
let mut entries = Vec::with_capacity(recipes.len());
|
||||
let mut fixed = BTreeSet::new();
|
||||
let mut not_affected = BTreeSet::new();
|
||||
for ((recipe, version), found) in &recipes {
|
||||
let facts = ComponentFacts {
|
||||
name: recipe,
|
||||
version,
|
||||
license: found.ids.iter().find_map(|id| license_of.get(id).copied()),
|
||||
cpe: found
|
||||
.package
|
||||
.identifiers
|
||||
.iter()
|
||||
.find(|i| i.kind == "cpe23")
|
||||
.map(|i| i.identifier.clone()),
|
||||
homepage: found.package.homepage.as_deref(),
|
||||
packages: found.packages.iter().copied().collect(),
|
||||
};
|
||||
let label = format!("{image_name}, SPDX 3.0");
|
||||
entries.push(component(facts, &image_name, &label, repo_id));
|
||||
for r in graph.of("fixedIn") {
|
||||
if r.to.iter().any(|t| found.ids.contains(t.as_str())) {
|
||||
if let Some(cve) = r.from.as_deref().and_then(cve_of) {
|
||||
fixed.insert(FixedCve {
|
||||
component: recipe.to_string(),
|
||||
version: version.to_string(),
|
||||
cve: cve.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
for r in graph.of("doesNotAffect") {
|
||||
if r.to.iter().any(|t| found.ids.contains(t.as_str())) {
|
||||
if let Some(cve) = r.from.as_deref().and_then(cve_of) {
|
||||
not_affected.insert(NotAffectedCve {
|
||||
component: recipe.to_string(),
|
||||
version: version.to_string(),
|
||||
cve: cve.to_string(),
|
||||
justification: r.justification.clone(),
|
||||
statement: r.impact.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(BuiltImage {
|
||||
image: image_name,
|
||||
image_id: image_id.to_string(),
|
||||
entries,
|
||||
fixed: fixed.into_iter().collect(),
|
||||
unresolved: unresolved.into_iter().collect(),
|
||||
not_affected: not_affected.into_iter().collect(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The package name at the end of a package id (`…/package/busybox`).
|
||||
fn package_name(id: &str) -> String {
|
||||
id.rsplit('/').next().unwrap_or(id).to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::{InImageBasis, YOCTO_RECIPE_MANAGER};
|
||||
|
||||
/// A trimmed copy of a real Scarthgap (5.0.21) core-image-minimal for
|
||||
/// qemuarm64 built with create-spdx-3.0: six recipes and one installed
|
||||
/// package whose element is missing.
|
||||
fn fixture() -> std::path::PathBuf {
|
||||
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../fixtures/yocto/core-image-minimal-qemuarm64.rootfs.spdx3.json")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_spdx3_image_lists_what_the_build_installed() {
|
||||
let images = read(&fixture(), "t").unwrap();
|
||||
assert_eq!(images.len(), 1);
|
||||
let image = &images[0];
|
||||
assert_eq!(image.image, "core-image-minimal");
|
||||
|
||||
let names: Vec<(&str, &str)> = image
|
||||
.entries
|
||||
.iter()
|
||||
.map(|e| (e.name.as_str(), e.version.as_str()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
("base-files", "3.0.14"),
|
||||
("busybox", "1.36.1"),
|
||||
("glibc", "2.39+git"),
|
||||
("libxml2", "2.12.10"),
|
||||
("openssl", "3.5.9"),
|
||||
("packagegroup-core-boot", "1.0"),
|
||||
]
|
||||
);
|
||||
let busybox = &image.entries[1];
|
||||
assert_eq!(busybox.package_manager, YOCTO_RECIPE_MANAGER);
|
||||
assert_eq!(
|
||||
busybox.cpe.as_deref(),
|
||||
Some("cpe:2.3:*:*:busybox:1.36.1:*:*:*:*:*:*:*")
|
||||
);
|
||||
assert!(busybox.license.is_some());
|
||||
assert_eq!(
|
||||
busybox.in_image.as_ref().map(|i| i.basis),
|
||||
Some(InImageBasis::Built)
|
||||
);
|
||||
assert!(
|
||||
busybox.evidence[0].ends_with("packages busybox, busybox-syslog, busybox-udhcpc"),
|
||||
"{:?}",
|
||||
busybox.evidence
|
||||
);
|
||||
// libc6 and ldconfig are one glibc component.
|
||||
assert!(image.entries[2].evidence[0].ends_with("packages ldconfig, libc6"));
|
||||
|
||||
assert!(image
|
||||
.fixed
|
||||
.iter()
|
||||
.any(|f| f.component == "busybox" && f.cve == "CVE-2022-48174"));
|
||||
let glibc_not_affected: Vec<&NotAffectedCve> = image
|
||||
.not_affected
|
||||
.iter()
|
||||
.filter(|n| n.component == "glibc")
|
||||
.collect();
|
||||
assert!(!glibc_not_affected.is_empty());
|
||||
assert!(glibc_not_affected.iter().all(|n| n.cve.starts_with("CVE-")));
|
||||
assert_eq!(image.unresolved, ["missing-pkg"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_spdx3_document_is_recognised_by_its_start() {
|
||||
let head = std::fs::read(fixture()).unwrap();
|
||||
assert!(is_spdx3(&head[..400.min(head.len())]));
|
||||
assert!(!is_spdx3(br#"{"package": [], "version": "1"}"#));
|
||||
assert!(!is_spdx3(&[0x28, 0xb5, 0x2f, 0xfd]));
|
||||
}
|
||||
}
|
||||
@@ -63,6 +63,30 @@ impl EntitlementCheck {
|
||||
pub fn member_blocked(&self) -> bool {
|
||||
!self.allowed && self.reason.as_deref() == Some(MEMBER_BLOCKED)
|
||||
}
|
||||
|
||||
/// How many targets the tenant's plan includes (t72):
|
||||
/// `limits.included_targets`. `None` when the plan sets no limit (no
|
||||
/// limits, the key missing or null), so every target is included.
|
||||
pub fn included_targets(&self) -> Option<u32> {
|
||||
self.limit("included_targets")
|
||||
}
|
||||
|
||||
/// The plan's monthly quota and the customer's Prüftag cap (t72), from
|
||||
/// `limits.monthly_pruefungen` and `limits.prueftag_cap`; a missing or
|
||||
/// null key is no limit.
|
||||
pub fn plan_limits(&self) -> compliance_core::models::PlanLimits {
|
||||
compliance_core::models::PlanLimits {
|
||||
monthly_pruefungen: self.limit("monthly_pruefungen"),
|
||||
prueftag_cap: self.limit("prueftag_cap"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole-number limit `key`; `None` when absent or null.
|
||||
fn limit(&self, key: &str) -> Option<u32> {
|
||||
let n = self.limits.as_ref()?.get(key)?.as_u64()?;
|
||||
// A count beyond u32 is no limit in practice.
|
||||
Some(u32::try_from(n).unwrap_or(u32::MAX))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
@@ -328,6 +352,10 @@ impl RegistryClient {
|
||||
if let Some(tok) = self.bearer().await? {
|
||||
rb = rb.bearer_auth(tok);
|
||||
}
|
||||
// traceparent: the registry's spans join this request's trace.
|
||||
for (name, value) in compliance_core::telemetry::trace_context_headers() {
|
||||
rb = rb.header(name, value);
|
||||
}
|
||||
Ok(rb)
|
||||
}
|
||||
|
||||
@@ -630,6 +658,46 @@ pub fn scheduler_runs_for(status: &str) -> bool {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_plan_sets_how_many_targets_are_included() {
|
||||
let check = |limits: serde_json::Value| -> EntitlementCheck {
|
||||
serde_json::from_value(serde_json::json!({ "allowed": true, "limits": limits }))
|
||||
.expect("an entitlement answer")
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
check(serde_json::json!({ "included_targets": 5 })).included_targets(),
|
||||
Some(5)
|
||||
);
|
||||
assert_eq!(
|
||||
check(serde_json::json!({ "included_targets": null })).included_targets(),
|
||||
None
|
||||
);
|
||||
assert_eq!(check(serde_json::json!({})).included_targets(), None);
|
||||
assert_eq!(check(serde_json::Value::Null).included_targets(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_plan_sets_the_quota_and_the_cap() {
|
||||
let check: EntitlementCheck = serde_json::from_value(serde_json::json!({
|
||||
"allowed": true,
|
||||
"limits": { "included_targets": 5, "monthly_pruefungen": 100, "prueftag_cap": 0 },
|
||||
}))
|
||||
.expect("an entitlement answer");
|
||||
assert_eq!(
|
||||
check.plan_limits(),
|
||||
compliance_core::models::PlanLimits {
|
||||
monthly_pruefungen: Some(100),
|
||||
prueftag_cap: Some(0),
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
EntitlementCheck::default().plan_limits(),
|
||||
compliance_core::models::PlanLimits::default(),
|
||||
"Enterprise: no limits"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ladder_filter() {
|
||||
for s in ["active", "trial", "demo", "warning", ""] {
|
||||
|
||||
@@ -1,74 +1,170 @@
|
||||
//! How many scans run at once, and what happens to a scan requested while the
|
||||
//! same target is already being scanned.
|
||||
//! 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.
|
||||
//!
|
||||
//! 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. Two rules now apply to every trigger (click, webhook, scheduler):
|
||||
//! other. These 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.
|
||||
//! * **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.
|
||||
//! * **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.
|
||||
//!
|
||||
//! 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::sync::Arc;
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
use dashmap::mapref::entry::Entry;
|
||||
use dashmap::DashMap;
|
||||
use rand::Rng;
|
||||
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
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.
|
||||
pub fn start_delay(trigger: &ScanTrigger) -> Duration {
|
||||
match trigger {
|
||||
ScanTrigger::Scheduled => rand::rng().random_range(Duration::ZERO..=SCHEDULED_SCAN_JITTER),
|
||||
ScanTrigger::Webhook | ScanTrigger::Manual | ScanTrigger::Support => Duration::ZERO,
|
||||
ScanTrigger::Webhook
|
||||
| ScanTrigger::Manual
|
||||
| ScanTrigger::Support
|
||||
| ScanTrigger::NewContent => Duration::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 running for this target: the caller runs the scan now.
|
||||
/// Nothing was queued or running for this target: the caller now holds
|
||||
/// it and runs its scans through [`ScanGate::start`].
|
||||
Run,
|
||||
/// 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.
|
||||
/// 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.
|
||||
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<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>>,
|
||||
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>,
|
||||
}
|
||||
|
||||
impl ScanGate {
|
||||
/// A gate allowing `concurrency` scans at once (at least one).
|
||||
pub fn new(concurrency: usize) -> Self {
|
||||
Self {
|
||||
slots: Arc::new(Semaphore::new(concurrency.max(1))),
|
||||
running: DashMap::new(),
|
||||
slots: Arc::new(Slots {
|
||||
queue: Mutex::new(Queue {
|
||||
free: concurrency.max(1),
|
||||
person: VecDeque::new(),
|
||||
background: VecDeque::new(),
|
||||
person_grants: 0,
|
||||
}),
|
||||
}),
|
||||
targets: DashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,60 +176,253 @@ 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, trigger: ScanTrigger) -> Admission {
|
||||
match self.running.entry(key.to_string()) {
|
||||
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()) {
|
||||
Entry::Vacant(v) => {
|
||||
v.insert(None);
|
||||
v.insert(Held {
|
||||
current: job,
|
||||
running: false,
|
||||
pending: None,
|
||||
});
|
||||
Admission::Run
|
||||
}
|
||||
Entry::Occupied(mut o) if o.get().is_none() => {
|
||||
o.insert(Some(trigger));
|
||||
Admission::Coalesced
|
||||
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,
|
||||
}
|
||||
}
|
||||
// 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,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// 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
|
||||
}
|
||||
}
|
||||
},
|
||||
Entry::Vacant(_) => None,
|
||||
}
|
||||
Entry::Vacant(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.running.remove(key);
|
||||
self.targets.remove(key);
|
||||
}
|
||||
|
||||
/// Wait for one of the global scan slots. The slot is freed when the
|
||||
/// returned permit is dropped.
|
||||
/// 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.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 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
|
||||
/// 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,10 +461,20 @@ impl Drop for HeldTarget<'_> {
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::{start_delay, Admission, HeldTarget, ScanGate, SCHEDULED_SCAN_JITTER};
|
||||
use super::{
|
||||
start_delay, Admission, HeldTarget, Job, Priority, ScanGate, PERSON_GRANTS_IN_A_ROW,
|
||||
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)
|
||||
@@ -187,63 +486,175 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn webhook_manual_and_support_scans_start_at_once() {
|
||||
fn webhook_manual_support_and_new_content_scans_start_at_once() {
|
||||
for trigger in [
|
||||
ScanTrigger::Webhook,
|
||||
ScanTrigger::Manual,
|
||||
ScanTrigger::Support,
|
||||
ScanTrigger::NewContent,
|
||||
] {
|
||||
assert_eq!(start_delay(&trigger), Duration::ZERO);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_burst_coalesces_into_one_run_and_one_follow_up() {
|
||||
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() {
|
||||
let gate = ScanGate::new(2);
|
||||
let key = ScanGate::key("acme", "t1");
|
||||
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);
|
||||
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
|
||||
);
|
||||
}
|
||||
// The holder runs the one follow-up, then releases the target.
|
||||
assert!(gate.finish(&key).is_some());
|
||||
assert!(gate.finish(&key).is_none());
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_persons_request_takes_over_a_pending_scheduled_follow_up() {
|
||||
fn a_scan_still_waiting_covers_requests_that_are_not_a_persons() {
|
||||
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, ScanTrigger::Scheduled),
|
||||
Admission::Coalesced
|
||||
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 }
|
||||
);
|
||||
|
||||
// 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);
|
||||
// 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
|
||||
);
|
||||
|
||||
assert_eq!(gate.finish(&key), Some(ScanTrigger::Manual));
|
||||
assert!(gate.finish(&key));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn targets_and_tenants_are_independent() {
|
||||
let gate = ScanGate::new(2);
|
||||
assert_eq!(
|
||||
gate.admit(&ScanGate::key("acme", "t1"), ScanTrigger::Manual),
|
||||
gate.admit(&ScanGate::key("acme", "t1"), job(ScanTrigger::Manual, "a")),
|
||||
Admission::Run
|
||||
);
|
||||
assert_eq!(
|
||||
gate.admit(&ScanGate::key("acme", "t2"), ScanTrigger::Manual),
|
||||
gate.admit(&ScanGate::key("acme", "t2"), job(ScanTrigger::Manual, "b")),
|
||||
Admission::Run
|
||||
);
|
||||
// Same target id in another tenant is another target.
|
||||
assert_eq!(
|
||||
gate.admit(&ScanGate::key("globex", "t1"), ScanTrigger::Manual),
|
||||
gate.admit(
|
||||
&ScanGate::key("globex", "t1"),
|
||||
job(ScanTrigger::Manual, "c")
|
||||
),
|
||||
Admission::Run
|
||||
);
|
||||
}
|
||||
@@ -252,34 +663,228 @@ 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, ScanTrigger::Manual), Admission::Run);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Manual, "r1")),
|
||||
Admission::Run
|
||||
);
|
||||
{
|
||||
// The holding task ends without calling finish (panic / shutdown).
|
||||
let _held = HeldTarget::new(&gate, key.clone());
|
||||
}
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Manual, "r2")),
|
||||
Admission::Run
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_disarmed_holder_leaves_the_state_to_finish() {
|
||||
#[tokio::test]
|
||||
async 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, ScanTrigger::Manual), Admission::Run);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Manual, "r1")),
|
||||
Admission::Run
|
||||
);
|
||||
let _slot = gate.start(&key).await.unwrap();
|
||||
HeldTarget::new(&gate, key.clone()).disarm();
|
||||
// Still held: disarm does not release, finish does.
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Coalesced);
|
||||
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"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn slots_bound_how_many_scans_run_at_once() {
|
||||
let gate = ScanGate::new(2);
|
||||
let a = gate.slot().await.unwrap();
|
||||
let _b = gate.slot().await.unwrap();
|
||||
let a = gate.slot(Priority::Background).await.unwrap();
|
||||
let _b = gate.slot(Priority::Background).await.unwrap();
|
||||
// A third slot is not available until one is freed.
|
||||
let third = tokio::time::timeout(std::time::Duration::from_millis(50), gate.slot()).await;
|
||||
let third =
|
||||
tokio::time::timeout(Duration::from_millis(50), gate.slot(Priority::Person)).await;
|
||||
assert!(third.is_err(), "a third concurrent scan must wait");
|
||||
drop(a);
|
||||
let third = tokio::time::timeout(std::time::Duration::from_millis(50), gate.slot()).await;
|
||||
let third =
|
||||
tokio::time::timeout(Duration::from_millis(50), gate.slot(Priority::Person)).await;
|
||||
assert!(third.is_ok(), "a freed slot is reused");
|
||||
}
|
||||
}
|
||||
@@ -31,9 +31,15 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError>
|
||||
tenant_count = tenants.len(),
|
||||
"Scheduled scan: tenants resolved"
|
||||
);
|
||||
for tenant_id in tenants {
|
||||
scan_all_repos(&agent, &tenant_id).await;
|
||||
}
|
||||
// Every tenant and target at once: each scan waits for one of the
|
||||
// `SCAN_CONCURRENCY` slots, so a slow repository holds one slot,
|
||||
// not the whole tick (#61).
|
||||
futures_util::future::join_all(
|
||||
tenants
|
||||
.iter()
|
||||
.map(|tenant_id| scan_all_repos(&agent, tenant_id)),
|
||||
)
|
||||
.await;
|
||||
})
|
||||
})
|
||||
.map_err(|e| AgentError::Scheduler(format!("Failed to create scan job: {e}")))?;
|
||||
@@ -120,6 +126,34 @@ 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
|
||||
@@ -232,18 +266,22 @@ async fn scan_all_repos(agent: &ComplianceAgent, tenant_id: &str) {
|
||||
|
||||
let targets: Vec<_> = cursor.filter_map(|r| async { r.ok() }).collect().await;
|
||||
|
||||
for target in targets {
|
||||
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
|
||||
if let Err(e) = agent
|
||||
.run_target_scan(tenant_id, &target_id, ScanTrigger::Scheduled)
|
||||
.await
|
||||
{
|
||||
tracing::error!(
|
||||
"Scheduled scan failed for {} (tenant '{tenant_id}'): {e}",
|
||||
target.name
|
||||
);
|
||||
}
|
||||
}
|
||||
// Started together; the scan slots (`SCAN_CONCURRENCY`) decide how many
|
||||
// run, and each scan's start jitter spreads them out.
|
||||
futures_util::stream::iter(targets)
|
||||
.for_each_concurrent(None, |target| async move {
|
||||
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
|
||||
if let Err(e) = agent
|
||||
.run_target_scan(tenant_id, &target_id, ScanTrigger::Scheduled)
|
||||
.await
|
||||
{
|
||||
tracing::error!(
|
||||
"Scheduled scan failed for {} (tenant '{tenant_id}'): {e}",
|
||||
target.name
|
||||
);
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn monitor_cves(agent: &ComplianceAgent, tenant_id: &str) {
|
||||
|
||||
@@ -26,6 +26,15 @@ pub async fn create_target(
|
||||
) -> Result<OnboardedTarget, AgentError> {
|
||||
let res = db.onboarded_targets().insert_one(&target).await?;
|
||||
target.id = res.inserted_id.as_object_id();
|
||||
// A target beyond the plan's included ones is extra from the start (t72).
|
||||
if let Some((_, billing)) = agent
|
||||
.refresh_billing(tenant_id, db)
|
||||
.await
|
||||
.into_iter()
|
||||
.find(|(id, _)| Some(*id) == target.id)
|
||||
{
|
||||
target.billing = billing;
|
||||
}
|
||||
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
|
||||
agent.emit_usage(
|
||||
tenant_id,
|
||||
@@ -101,6 +110,7 @@ pub fn uploaded_artifact(
|
||||
ArtifactKind::FirmwareImage => Artifact::firmware_image(filename),
|
||||
ArtifactKind::SourceArchive => Artifact::source_archive(filename),
|
||||
ArtifactKind::MobilePackage => Artifact::mobile_package(filename),
|
||||
ArtifactKind::BuildOutput => Artifact::build_output(filename),
|
||||
_ => return None,
|
||||
};
|
||||
artifact.stored_path = Some(stored_path.to_string_lossy().to_string());
|
||||
@@ -131,6 +141,7 @@ pub fn reference_artifact(
|
||||
Artifact::plc_project(source_ref, plc_format.unwrap_or(PlcFormat::PlcopenXml))
|
||||
}
|
||||
ArtifactKind::PlaintextDescription => Artifact::plaintext(source_ref),
|
||||
ArtifactKind::BuildOutput => Artifact::build_output(source_ref),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 291 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user