Compare commits
156
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
264d784daa | ||
|
|
ecfee6db6e | ||
|
|
30079c6504 | ||
|
|
dd46af6f24 | ||
|
|
1df32d5e1a | ||
|
|
2d3311bd09 | ||
|
|
5b4d8bbe5f | ||
|
|
9274387e85 | ||
|
|
5407e1d7ed | ||
|
|
87b1e281ed | ||
|
|
ddb0068b3e | ||
|
|
f5848f7bad | ||
|
|
d9280939e2 | ||
|
|
600a8f0dd7 | ||
|
|
f59dae4a66 | ||
|
|
ae5d8f1ca8 | ||
|
|
7478ff57df | ||
|
|
a252096810 | ||
|
|
d3500d4be4 | ||
|
|
9da4d83ed0 | ||
|
|
20d56d2301 | ||
|
|
c8a13fecad | ||
|
|
fb8223bc11 | ||
|
|
835bc3fc98 | ||
|
|
f06a347dd7 | ||
|
|
1376efa249 | ||
|
|
40fb69072e | ||
|
|
d979fc1644 | ||
|
|
bc73a61f96 | ||
|
|
240c4d734a | ||
|
|
019ea73e86 | ||
|
|
497318e50d | ||
|
|
dc14c77e84 | ||
|
|
31b8cb9d37 | ||
|
|
c222210a87 | ||
|
|
832f9b13e1 | ||
|
|
eff6f92a33 | ||
|
|
6f42fbd583 | ||
|
|
90d5c8f8d1 | ||
|
|
b5a2dd93fd | ||
|
|
72ef09b981 | ||
|
|
684d3514ab | ||
|
|
0790810afb | ||
|
|
af76e516a1 | ||
|
|
7d0ccd7171 | ||
|
|
d679f9cbf1 | ||
|
|
55091fe02e | ||
|
|
97b8e35a87 | ||
|
|
e521c8fdd9 | ||
|
|
126345aa9d | ||
|
|
8ae561a01a | ||
|
|
668b6814c8 | ||
|
|
48b1a4a47d | ||
|
|
bde53a96dd | ||
|
|
dcfac283e6 | ||
|
|
141176df20 | ||
|
|
32332f65bb | ||
|
|
246e2c4ac5 | ||
|
|
98be82c0d0 | ||
|
|
0ad8bbc3c9 | ||
|
|
cdb84f0967 | ||
|
|
4f5d713bbc | ||
|
|
df16a49c93 | ||
|
|
12206bfac5 | ||
|
|
f5ac5321bd | ||
|
|
fad023e734 | ||
|
|
396cb3cd39 | ||
|
|
064bada213 | ||
|
|
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
|
||||
|
||||
+133
-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,12 @@ jobs:
|
||||
run: cargo clippy -p werkbank-exec --all-targets -- -D warnings
|
||||
- name: Clippy (control-map)
|
||||
run: cargo clippy -p control-map --all-targets -- -D warnings
|
||||
- name: Clippy (graph)
|
||||
run: cargo clippy -p compliance-graph --all-targets -- -D warnings
|
||||
# The library only: its test modules still predate the lint
|
||||
# (items_after_test_module); --all-targets once they are moved.
|
||||
- name: Clippy (dast)
|
||||
run: cargo clippy -p compliance-dast -- -D warnings
|
||||
|
||||
# Security audit
|
||||
- name: Security Audit
|
||||
@@ -131,20 +152,119 @@ 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
|
||||
# compliance-dast: unit tests, doc tests and the scan tests against
|
||||
# local fake sites (no services).
|
||||
- name: Tests (dast)
|
||||
run: cargo test -p compliance-dast
|
||||
# The dashboard crate compiles as the library and as its test harness at
|
||||
# once, each rustc at about 1.65 GB: two of them exceed the job's 3 GiB
|
||||
# and get OOM-killed (signal 9). One at a time for these two steps.
|
||||
- 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 +358,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 +391,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 +431,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 +463,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
+783
-400
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,12 +1,15 @@
|
||||
[package]
|
||||
name = "compliance-agent"
|
||||
version = "0.4.6"
|
||||
version = "0.4.19"
|
||||
edition = "2021"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
# The OpenAPI description of the API, generated from the handlers (#1006).
|
||||
utoipa = "6"
|
||||
utoipa-axum = "0.3"
|
||||
compliance-core = { workspace = true, features = ["mongodb", "telemetry", "axum", "secrets"] }
|
||||
control-map = { workspace = true }
|
||||
compliance-graph = { path = "../compliance-graph" }
|
||||
@@ -33,6 +36,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 +67,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 }
|
||||
|
||||
+256
-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,108 @@ 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`; a plan that
|
||||
/// allows no extra target includes them all. 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.billed_included())
|
||||
.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(),
|
||||
extra_targets: check.extra_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.
|
||||
pub(crate) 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 +295,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 +319,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.billed_included())
|
||||
.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 +443,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 +519,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(
|
||||
|
||||
@@ -18,7 +18,18 @@ use super::ApiResponse;
|
||||
|
||||
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
||||
|
||||
/// POST /api/v1/chat/:repo_id — Send a chat message with RAG context
|
||||
/// Ask about a target's code, answered from its code graph.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/chat/{repo_id}",
|
||||
tag = "Chat",
|
||||
params(("repo_id" = String, Path, description = "The target's id")),
|
||||
request_body(content = Object, description = "`message`, and the earlier `history` as `role` and `content`"),
|
||||
responses(
|
||||
(status = 200, description = "The answer with its sources"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||
pub async fn chat(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -133,7 +144,17 @@ pub async fn chat(
|
||||
}))
|
||||
}
|
||||
|
||||
/// POST /api/v1/chat/:repo_id/build-embeddings — Trigger embedding build
|
||||
/// Build the embeddings the chat answers from, in the background.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/chat/{repo_id}/build-embeddings",
|
||||
tag = "Chat",
|
||||
params(("repo_id" = String, Path, description = "The target's id")),
|
||||
responses(
|
||||
(status = 200, description = "The build was started"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||
pub async fn build_embeddings(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -244,7 +265,17 @@ pub async fn build_embeddings(
|
||||
))
|
||||
}
|
||||
|
||||
/// GET /api/v1/chat/:repo_id/status — Get latest embedding build status
|
||||
/// The status of a target's latest embedding build.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/chat/{repo_id}/status",
|
||||
tag = "Chat",
|
||||
params(("repo_id" = String, Path, description = "The target's id")),
|
||||
responses(
|
||||
(status = 200, description = "The build, or null"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||
pub async fn embedding_status(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
//! The workspace's connections to other workspaces (#1028), held by the
|
||||
//! tenant registry (tenant-registry#138): whom a supplier can release an SBOM
|
||||
//! to. A connection shows only its id and the other workspace's display
|
||||
//! name, never the other tenant's id.
|
||||
|
||||
use axum::extract::Extension;
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use serde::Serialize;
|
||||
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use super::dto::AgentExt;
|
||||
use super::ApiResponse;
|
||||
|
||||
/// A connection as the workspace sees it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
pub struct ConnectionView {
|
||||
/// The connection's id.
|
||||
pub id: String,
|
||||
/// The other workspace's display name.
|
||||
pub peer_name: String,
|
||||
}
|
||||
|
||||
/// The workspace's active connections to other workspaces.
|
||||
///
|
||||
/// Each by its id and the other workspace's display name, by name; nothing
|
||||
/// else of the other workspace. Connections are made and ended in the
|
||||
/// portal. Without a registry (development) there are none.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/connections",
|
||||
tag = "Targets",
|
||||
responses(
|
||||
(status = 200, description = "The active connections (`data`)"),
|
||||
(status = 503, description = "The registry cannot be asked"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn list_connections(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
) -> Result<Json<ApiResponse<Vec<ConnectionView>>>, StatusCode> {
|
||||
let connections = match agent.registry.as_ref() {
|
||||
None => Vec::new(),
|
||||
Some(registry) => registry
|
||||
.active_connections(&tenant.0.tenant_id)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(tenant_id = %tenant.0.tenant_id, "connections unavailable: {e}");
|
||||
StatusCode::SERVICE_UNAVAILABLE
|
||||
})?,
|
||||
};
|
||||
let mut views: Vec<ConnectionView> = connections
|
||||
.into_iter()
|
||||
.map(|c| ConnectionView {
|
||||
id: c.id,
|
||||
peer_name: c.peer_name,
|
||||
})
|
||||
.collect();
|
||||
// One lowercase name per connection, not one per comparison.
|
||||
views.sort_by_cached_key(|v| v.peer_name.to_lowercase());
|
||||
Ok(Json(ApiResponse {
|
||||
data: views,
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,9 @@ use axum::Json;
|
||||
use mongodb::bson::doc;
|
||||
use serde::Deserialize;
|
||||
|
||||
use compliance_core::models::dast::{DastFinding, DastScanRun, DastTarget, DastTargetType};
|
||||
use compliance_core::models::dast::{
|
||||
DastAuthConfig, DastFinding, DastScanRun, DastTarget, DastTargetType,
|
||||
};
|
||||
use compliance_core::models::Credentials;
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
@@ -17,21 +19,41 @@ use super::{collect_cursor_async, ApiResponse, PaginationParams};
|
||||
|
||||
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// A DAST target to add.
|
||||
#[derive(Deserialize, utoipa::ToSchema)]
|
||||
pub struct AddTargetRequest {
|
||||
/// A name for the target.
|
||||
pub name: String,
|
||||
/// Where the scan starts; must be publicly routable.
|
||||
pub base_url: String,
|
||||
/// `web_app` (default), `rest_api` or `graph_ql`.
|
||||
#[serde(default = "default_target_type")]
|
||||
#[schema(value_type = Option<String>, example = "web_app")]
|
||||
pub target_type: DastTargetType,
|
||||
/// The target (Prüfobjekt) this DAST target belongs to.
|
||||
pub repo_id: Option<String>,
|
||||
/// URL paths the scan leaves out.
|
||||
#[serde(default)]
|
||||
pub excluded_paths: Vec<String>,
|
||||
/// How many link levels the crawl follows (default 5).
|
||||
#[serde(default = "default_crawl_depth")]
|
||||
#[schema(value_type = Option<u32>)]
|
||||
pub max_crawl_depth: u32,
|
||||
/// Requests per second (default 10).
|
||||
#[serde(default = "default_rate_limit")]
|
||||
#[schema(value_type = Option<u32>)]
|
||||
pub rate_limit: u32,
|
||||
/// Whether the scan may send `PUT`, `PATCH` and `DELETE` (default false).
|
||||
#[serde(default)]
|
||||
#[schema(value_type = Option<bool>)]
|
||||
pub allow_destructive: bool,
|
||||
/// The login every scan request carries (#1000): `method` `basic`
|
||||
/// (`username`, `password`), `bearer` (`token`) or `cookie` (`token` =
|
||||
/// `name=value`), plus optional extra `headers`. Stored encrypted, never
|
||||
/// returned.
|
||||
#[serde(default)]
|
||||
#[schema(value_type = Option<Object>)]
|
||||
pub auth: Option<DastAuthConfig>,
|
||||
}
|
||||
|
||||
fn default_target_type() -> DastTargetType {
|
||||
@@ -44,7 +66,19 @@ fn default_rate_limit() -> u32 {
|
||||
10
|
||||
}
|
||||
|
||||
/// GET /api/v1/dast/targets — List DAST targets
|
||||
/// List the tenant's DAST targets.
|
||||
///
|
||||
/// Logins are never returned.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/dast/targets",
|
||||
tag = "DAST",
|
||||
params(PaginationParams),
|
||||
responses(
|
||||
(status = 200, description = "A page of DAST targets"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn list_targets(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -81,7 +115,22 @@ pub async fn list_targets(
|
||||
}))
|
||||
}
|
||||
|
||||
/// POST /api/v1/dast/targets — Add a new DAST target
|
||||
/// Add a DAST target.
|
||||
///
|
||||
/// Its login is stored encrypted and never returned; the answer is the new
|
||||
/// target with its id.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/dast/targets",
|
||||
tag = "DAST",
|
||||
request_body = AddTargetRequest,
|
||||
responses(
|
||||
(status = 200, description = "The new DAST target"),
|
||||
(status = 400, description = "The base URL is refused (not publicly routable) or the login cannot be sent"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
(status = 503, description = "The login cannot be stored encrypted"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn add_target(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -94,12 +143,22 @@ pub async fn add_target(
|
||||
tracing::warn!(tenant_id = %tenant.0.tenant_id, "DAST target refused: {e}");
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
// A login the scan could not send is refused now, not at the first scan.
|
||||
if let Err(e) = compliance_dast::auth::login_headers(req.auth.as_ref()) {
|
||||
tracing::warn!(tenant_id = %tenant.0.tenant_id, "DAST target login refused: {e}");
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
let mut target = DastTarget::new(req.name, req.base_url, req.target_type);
|
||||
target.repo_id = req.repo_id;
|
||||
target.excluded_paths = req.excluded_paths;
|
||||
target.max_crawl_depth = req.max_crawl_depth;
|
||||
target.rate_limit = req.rate_limit;
|
||||
target.allow_destructive = req.allow_destructive;
|
||||
target.auth_config = req.auth;
|
||||
agent
|
||||
.secrets
|
||||
.seal_unsealed(&mut target)
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let res = db
|
||||
@@ -107,11 +166,8 @@ pub async fn add_target(
|
||||
.insert_one(&target)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let target_id = res
|
||||
.inserted_id
|
||||
.as_object_id()
|
||||
.map(|id| id.to_hex())
|
||||
.unwrap_or_default();
|
||||
target.id = res.inserted_id.as_object_id();
|
||||
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
|
||||
agent.emit_usage(
|
||||
&tenant.0.tenant_id,
|
||||
"target.added",
|
||||
@@ -126,7 +182,23 @@ pub async fn add_target(
|
||||
}))
|
||||
}
|
||||
|
||||
/// POST /api/v1/dast/targets/:id/scan — Trigger DAST scan
|
||||
/// Start a DAST scan of a target.
|
||||
///
|
||||
/// The scan runs in the background; its run and findings appear under the
|
||||
/// scan-run and finding lists.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/dast/targets/{id}/scan",
|
||||
tag = "DAST",
|
||||
params(("id" = String, Path, description = "The DAST target's id")),
|
||||
responses(
|
||||
(status = 200, description = "The scan was started"),
|
||||
(status = 400, description = "Not an id, or the target's address is refused"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
(status = 404, description = "No such DAST target"),
|
||||
(status = 409, description = "This deployment does not run DAST"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn trigger_scan(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -141,12 +213,14 @@ pub async fn trigger_scan(
|
||||
let oid = mongodb::bson::oid::ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
|
||||
let target = db
|
||||
let mut target = db
|
||||
.dast_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
// The login is used here, in memory only.
|
||||
agent.secrets.open_in_place(&mut target);
|
||||
|
||||
// Re-check at use: the target may have been stored before this policy
|
||||
// existed, and a hostname can be repointed after registration.
|
||||
@@ -197,7 +271,17 @@ pub async fn trigger_scan(
|
||||
Ok(Json(serde_json::json!({ "status": "dast_scan_triggered" })))
|
||||
}
|
||||
|
||||
/// GET /api/v1/dast/scan-runs — List DAST scan runs
|
||||
/// List the tenant's DAST scan runs.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/dast/scan-runs",
|
||||
tag = "DAST",
|
||||
params(PaginationParams),
|
||||
responses(
|
||||
(status = 200, description = "A page of DAST scan runs"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn list_scan_runs(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -235,7 +319,17 @@ pub async fn list_scan_runs(
|
||||
}))
|
||||
}
|
||||
|
||||
/// GET /api/v1/dast/findings — List DAST findings
|
||||
/// List the tenant's DAST findings, with their evidence.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/dast/findings",
|
||||
tag = "DAST",
|
||||
params(PaginationParams),
|
||||
responses(
|
||||
(status = 200, description = "A page of DAST findings"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn list_findings(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -273,7 +367,19 @@ pub async fn list_findings(
|
||||
}))
|
||||
}
|
||||
|
||||
/// GET /api/v1/dast/findings/:id — Finding detail with evidence
|
||||
/// One DAST finding, with its request and response evidence.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/dast/findings/{id}",
|
||||
tag = "DAST",
|
||||
params(("id" = String, Path, description = "The DAST finding's id")),
|
||||
responses(
|
||||
(status = 200, description = "The DAST finding"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
(status = 404, description = "No such DAST finding"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(finding_id = %id))]
|
||||
pub async fn get_finding(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
//! Delivering published SBOM versions to the customers who accepted a
|
||||
//! release (#1028), the second half of phase 4's customer side.
|
||||
//!
|
||||
//! A version reaches a customer's supplier component the way a supplier's
|
||||
//! upload does (`onboarding::attach_upload`): it replaces the component's
|
||||
//! supplier SBOM and a scan starts. Publishing delivers to every accepted
|
||||
//! release of the target, accepting delivers the latest version at once. The
|
||||
//! connection is asked again right before each write into the customer's
|
||||
//! workspace, and the version last delivered is not delivered again. (Each
|
||||
//! publication is its own document, with its own serial number and time,
|
||||
//! so a new version is delivered even when its components are unchanged.)
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use futures_util::TryStreamExt;
|
||||
use mongodb::bson::{doc, oid::ObjectId, DateTime as BsonDateTime};
|
||||
|
||||
use compliance_core::models::{ArtifactKind, ScanTrigger};
|
||||
|
||||
use super::offers::{OfferState, SbomOffer};
|
||||
use super::onboarding::{attach_upload, StoredUpload};
|
||||
use super::releases::{SbomRelease, SbomVersion};
|
||||
use crate::agent::ComplianceAgent;
|
||||
use crate::database::Database;
|
||||
|
||||
/// What became of one delivery.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum Outcome {
|
||||
/// Attached to the customer's component; a scan started.
|
||||
Delivered,
|
||||
/// The customer already has this content.
|
||||
Unchanged,
|
||||
/// Not delivered: the offer is not accepted, its component has gone, or
|
||||
/// the connection no longer joins the two workspaces.
|
||||
Skipped,
|
||||
/// It could not be written; the next publication tries again.
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// Whether `release`'s connection still joins `supplier` and the customer it
|
||||
/// was released to. Without a registry (development) it does not.
|
||||
async fn joined(agent: &ComplianceAgent, supplier: &str, release: &SbomRelease) -> bool {
|
||||
let Some(registry) = agent.registry.as_ref() else {
|
||||
return false;
|
||||
};
|
||||
match registry.connection(&release.connection_id).await {
|
||||
Ok(state) => {
|
||||
state.is_some_and(|s| s.peer_of(supplier) == Some(release.peer_tenant_id.as_str()))
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(release = %release.id, "connection not checked, nothing delivered: {e}");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Deliver `version` of `release` to the customer the release went to, into
|
||||
/// the component its accepted offer names. The caller has checked the
|
||||
/// connection.
|
||||
async fn deliver(
|
||||
agent: &Arc<ComplianceAgent>,
|
||||
release: &SbomRelease,
|
||||
version: &SbomVersion,
|
||||
) -> Outcome {
|
||||
let customer = &release.peer_tenant_id;
|
||||
let db = agent.db_pool.for_existing_tenant_id(customer);
|
||||
let offers = db.inner().collection::<SbomOffer>(SbomOffer::COLLECTION);
|
||||
let offer = match offers
|
||||
.find_one(doc! { "release_id": release.id.to_hex(), "state": "accepted" })
|
||||
.await
|
||||
{
|
||||
Ok(Some(offer)) => offer,
|
||||
Ok(None) => return Outcome::Skipped,
|
||||
Err(e) => {
|
||||
tracing::error!(release = %release.id, "offer not read: {e}");
|
||||
return Outcome::Failed;
|
||||
}
|
||||
};
|
||||
if offer.delivered_hash.as_deref() == Some(version.content_hash.as_str()) {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
let Some(target_id) = offer.target_id.clone() else {
|
||||
return Outcome::Skipped;
|
||||
};
|
||||
let Ok(oid) = ObjectId::parse_str(&target_id) else {
|
||||
return Outcome::Skipped;
|
||||
};
|
||||
let target = match db.onboarded_targets().find_one(doc! { "_id": oid }).await {
|
||||
Ok(Some(target)) => target,
|
||||
Ok(None) => return Outcome::Skipped,
|
||||
Err(e) => {
|
||||
tracing::error!(target_id, "component not read: {e}");
|
||||
return Outcome::Failed;
|
||||
}
|
||||
};
|
||||
match attach(agent, &db, &target, version).await {
|
||||
Ok(()) => {}
|
||||
Err(e) => {
|
||||
tracing::error!(target_id, label = %version.label, "version not delivered: {e}");
|
||||
return Outcome::Failed;
|
||||
}
|
||||
}
|
||||
let now = BsonDateTime::now();
|
||||
let marked = offers
|
||||
.update_one(
|
||||
doc! { "_id": offer.id, "state": "accepted" },
|
||||
doc! { "$set": {
|
||||
"delivered_hash": &version.content_hash,
|
||||
"delivered_label": &version.label,
|
||||
"delivered_at": now,
|
||||
} },
|
||||
)
|
||||
.await;
|
||||
if let Err(e) = marked {
|
||||
tracing::warn!(target_id, "delivery not recorded on the offer: {e}");
|
||||
}
|
||||
let supplier = agent
|
||||
.db_pool
|
||||
.for_existing_tenant_id(&offer.supplier_tenant_id);
|
||||
let shown = supplier
|
||||
.inner()
|
||||
.collection::<SbomRelease>(SbomRelease::COLLECTION)
|
||||
.update_one(
|
||||
doc! { "_id": release.id },
|
||||
doc! { "$set": { "delivered_label": &version.label, "delivered_at": now } },
|
||||
)
|
||||
.await;
|
||||
if let Err(e) = shown {
|
||||
tracing::warn!(release = %release.id, "delivery not recorded on the release: {e}");
|
||||
}
|
||||
// A set: a release delivered the same version again counts once.
|
||||
let counted = supplier
|
||||
.inner()
|
||||
.collection::<SbomVersion>(SbomVersion::COLLECTION)
|
||||
.update_one(
|
||||
doc! { "_id": version.id },
|
||||
doc! { "$addToSet": { "delivered_to": release.id.to_hex() } },
|
||||
)
|
||||
.await;
|
||||
if let Err(e) = counted {
|
||||
tracing::warn!(label = %version.label, "delivery not counted on the version: {e}");
|
||||
}
|
||||
let (agent, customer) = (Arc::clone(agent), customer.clone());
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = agent
|
||||
.run_target_scan(&customer, &target_id, ScanTrigger::NewContent)
|
||||
.await
|
||||
{
|
||||
tracing::error!(target_id, "scan after a delivered SBOM failed: {e}");
|
||||
}
|
||||
});
|
||||
Outcome::Delivered
|
||||
}
|
||||
|
||||
/// Copy `version`'s document into `target`'s upload folder in the
|
||||
/// customer's workspace and attach it as the component's supplier SBOM,
|
||||
/// labelled with the version.
|
||||
async fn attach(
|
||||
agent: &ComplianceAgent,
|
||||
db: &Database,
|
||||
target: &compliance_core::models::OnboardedTarget,
|
||||
version: &SbomVersion,
|
||||
) -> Result<(), String> {
|
||||
let target_id = target.id.map(|o| o.to_hex()).unwrap_or_default();
|
||||
let bytes = tokio::fs::read(&version.stored_path)
|
||||
.await
|
||||
.map_err(|e| format!("the published document is not readable: {e}"))?;
|
||||
let name = format!("release-{}.cdx.json", version.label);
|
||||
let path = crate::targets::store_upload(agent, &target_id, &name, &bytes)
|
||||
.map_err(|e| format!("not stored: {e}"))?;
|
||||
let mut upload = StoredUpload::new(path, name);
|
||||
upload.size = u64::try_from(bytes.len()).unwrap_or(u64::MAX);
|
||||
attach_upload(db, target, ArtifactKind::SupplierSbom, None, upload)
|
||||
.await
|
||||
.map_err(|refusal| format!("refused ({})", refusal.code().unwrap_or("unreadable")))?;
|
||||
if let Some(mut supplier) = target.supplier.clone() {
|
||||
supplier.version = Some(version.label.clone());
|
||||
let set = mongodb::bson::to_bson(&supplier).map_err(|e| e.to_string())?;
|
||||
db.onboarded_targets()
|
||||
.update_one(
|
||||
doc! { "_id": target.id },
|
||||
doc! { "$set": { "supplier": set } },
|
||||
)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Deliver `version` of target `target_id`, just published by `supplier`
|
||||
/// (its database `db`), to every customer that accepted a release of it,
|
||||
/// and tell every customer whose offer is still open that it is now what
|
||||
/// accepting delivers.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// How many customers it was delivered to.
|
||||
pub(super) async fn deliver_published(
|
||||
agent: &Arc<ComplianceAgent>,
|
||||
supplier: &str,
|
||||
db: &Database,
|
||||
target_id: &str,
|
||||
version: &SbomVersion,
|
||||
) -> usize {
|
||||
let live: Vec<SbomRelease> = match db
|
||||
.inner()
|
||||
.collection::<SbomRelease>(SbomRelease::COLLECTION)
|
||||
.find(doc! { "target_id": target_id, "ended_at": null })
|
||||
.await
|
||||
{
|
||||
Ok(cursor) => cursor.try_collect().await.unwrap_or_default(),
|
||||
Err(e) => {
|
||||
tracing::error!(target_id, "releases not read, nothing delivered: {e}");
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
let mut delivered = 0;
|
||||
for release in &live {
|
||||
let open = matches!(release.answer, None | Some(OfferState::Offered));
|
||||
if !(open || release.answer == Some(OfferState::Accepted))
|
||||
|| !joined(agent, supplier, release).await
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if open {
|
||||
let id = release.id.to_hex();
|
||||
super::offers::announce(
|
||||
agent,
|
||||
&release.peer_tenant_id,
|
||||
&id,
|
||||
&version.label,
|
||||
version.components,
|
||||
)
|
||||
.await;
|
||||
} else if deliver(agent, release, version).await == Outcome::Delivered {
|
||||
delivered += 1;
|
||||
}
|
||||
}
|
||||
delivered
|
||||
}
|
||||
|
||||
/// Deliver the latest published version of the release `offer` answers, if
|
||||
/// there is one, right after the customer accepted it. The caller has
|
||||
/// checked the connection and that the release is live.
|
||||
pub(super) async fn deliver_latest(agent: &Arc<ComplianceAgent>, offer: &SbomOffer) -> Outcome {
|
||||
debug_assert_eq!(offer.state, OfferState::Accepted);
|
||||
let Ok(id) = ObjectId::parse_str(&offer.release_id) else {
|
||||
return Outcome::Skipped;
|
||||
};
|
||||
let supplier = agent
|
||||
.db_pool
|
||||
.for_existing_tenant_id(&offer.supplier_tenant_id);
|
||||
let release = match supplier
|
||||
.inner()
|
||||
.collection::<SbomRelease>(SbomRelease::COLLECTION)
|
||||
.find_one(doc! { "_id": id, "ended_at": null })
|
||||
.await
|
||||
{
|
||||
Ok(Some(release)) => release,
|
||||
Ok(None) => return Outcome::Skipped,
|
||||
Err(e) => {
|
||||
tracing::error!(release = %offer.release_id, "release not read: {e}");
|
||||
return Outcome::Failed;
|
||||
}
|
||||
};
|
||||
let latest = supplier
|
||||
.inner()
|
||||
.collection::<SbomVersion>(SbomVersion::COLLECTION)
|
||||
.find_one(doc! { "target_id": &release.target_id })
|
||||
.sort(doc! { "created_at": -1, "_id": -1 })
|
||||
.await;
|
||||
match latest {
|
||||
Ok(Some(version)) => deliver(agent, &release, &version).await,
|
||||
Ok(None) => Outcome::Skipped,
|
||||
Err(e) => {
|
||||
tracing::error!(release = %offer.release_id, "versions not read: {e}");
|
||||
Outcome::Failed
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,16 @@ pub struct SeedResponse {
|
||||
pub seeded: Vec<SeededTarget>,
|
||||
}
|
||||
|
||||
/// GET /api/v1/targets/demo-seed — what "Add demo targets" would create.
|
||||
/// The demo targets the agent ships, which seeding would create.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/targets/demo-seed",
|
||||
tag = "Targets",
|
||||
responses(
|
||||
(status = 200, description = "The demo targets"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn list_demo_targets(
|
||||
_tenant: TenantCtx,
|
||||
@@ -39,8 +48,20 @@ pub async fn list_demo_targets(
|
||||
Ok(Json(DemoTargetsResponse { targets }))
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets/demo-seed — seed the caller's tenant. 202: the targets
|
||||
/// exist and their scans are running in the background.
|
||||
/// Create the demo targets for the tenant and start their scans.
|
||||
///
|
||||
/// 202: the targets exist and their scans are running in the background.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/targets/demo-seed",
|
||||
tag = "Targets",
|
||||
request_body(content = Option<SeedRequest>, description = "Which demo targets; none seeds all"),
|
||||
responses(
|
||||
(status = 202, description = "The targets exist; their scans are running"),
|
||||
(status = 400, description = "An unknown demo target"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn seed_demo_targets(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
//! A target's Siemens controllers against Siemens' advisories (SPS item 4a):
|
||||
//! `GET /api/v1/targets/{id}/devices` for its page, and
|
||||
//! `GET /api/v1/devices/lookup` to recognise an order number while it is
|
||||
//! typed.
|
||||
//!
|
||||
//! Both read the advisory index as it is now, so a device shows its state
|
||||
//! as soon as it is entered; its CVE alerts follow at the target's next scan.
|
||||
|
||||
use axum::extract::{Extension, Path, Query};
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use mongodb::bson::doc;
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::dto::{tenant_db, AgentExt, ApiResponse, ApiResult};
|
||||
use crate::pipeline::csaf_match::{AdvisoryIndex, Wanted};
|
||||
use compliance_core::csaf_ingest::Advisory;
|
||||
use compliance_core::device_check::{DeviceCheck, DeviceLookup};
|
||||
use compliance_core::models::plc_device::normalised_order_number;
|
||||
use compliance_core::models::PlcDevice;
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
/// The provider whose advisories name devices by order number.
|
||||
const PROVIDER: &str = "siemens";
|
||||
|
||||
/// Siemens' advisories naming any of `order_numbers` (normalised).
|
||||
async fn advisories_naming(
|
||||
index: &dyn AdvisoryIndex,
|
||||
order_numbers: Vec<String>,
|
||||
) -> Result<Vec<Advisory>, StatusCode> {
|
||||
let wanted = Wanted {
|
||||
order_numbers,
|
||||
..Wanted::default()
|
||||
};
|
||||
let rows = index.relevant(&wanted).await.map_err(|e| {
|
||||
tracing::warn!("Failed to read the advisory index: {e}");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.filter(|(provider, _)| provider == PROVIDER)
|
||||
.map(|(_, advisory)| advisory)
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Each of `devices` against `advisories`.
|
||||
fn checks(devices: Vec<PlcDevice>, advisories: &[Advisory]) -> Vec<DeviceCheck> {
|
||||
devices
|
||||
.into_iter()
|
||||
.map(|device| DeviceCheck::new(device, advisories))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The Siemens controllers a target runs on.
|
||||
///
|
||||
/// Each with the Siemens advisories naming it.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/targets/{id}/devices",
|
||||
tag = "Targets",
|
||||
params(("id" = String, Path, description = "The target's id")),
|
||||
responses(
|
||||
(status = 200, description = "The target's devices in the order entered, each with the Siemens advisories naming it and whether one affects its firmware"),
|
||||
(status = 400, description = "Not a target id"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
(status = 404, description = "No such target"),
|
||||
(status = 500, description = "The target or the advisory index could not be read"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn list_devices(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
) -> ApiResult<Vec<DeviceCheck>> {
|
||||
let oid = mongodb::bson::oid::ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let target = db
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let mut order_numbers: Vec<String> = target
|
||||
.devices
|
||||
.iter()
|
||||
.map(|d| d.order_number.clone())
|
||||
.collect();
|
||||
order_numbers.sort();
|
||||
order_numbers.dedup();
|
||||
let advisories = if order_numbers.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
advisories_naming(agent.advisory_index.as_ref(), order_numbers).await?
|
||||
};
|
||||
let devices = checks(target.devices, &advisories);
|
||||
Ok(Json(ApiResponse {
|
||||
total: Some(devices.len() as u64),
|
||||
data: devices,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// `?order_number=` of [`lookup_device`].
|
||||
#[derive(Debug, Deserialize, utoipa::IntoParams)]
|
||||
pub struct LookupParams {
|
||||
/// The order number as typed (`6es7511-1ak02-0ab0`).
|
||||
pub order_number: String,
|
||||
}
|
||||
|
||||
/// What Siemens' advisories know of an order number.
|
||||
///
|
||||
/// For recognising one while it is typed. Public data only: nothing of the
|
||||
/// tenant is read.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/devices/lookup",
|
||||
tag = "Targets",
|
||||
params(LookupParams),
|
||||
responses(
|
||||
(status = 200, description = "The order number normalised, whether it has a Siemens order number's shape, and, when advisories name it, the product's name and how many"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
(status = 500, description = "The advisory index could not be read"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn lookup_device(
|
||||
Extension(agent): AgentExt,
|
||||
_tenant: TenantCtx,
|
||||
Query(params): Query<LookupParams>,
|
||||
) -> ApiResult<DeviceLookup> {
|
||||
let order_number = normalised_order_number(¶ms.order_number);
|
||||
// Any firmware: only the shape of the order number is checked here.
|
||||
let Ok(device) = PlcDevice::new(&order_number, "0", None) else {
|
||||
return Ok(Json(ApiResponse {
|
||||
data: DeviceLookup {
|
||||
order_number,
|
||||
valid: false,
|
||||
product: None,
|
||||
advisories: 0,
|
||||
},
|
||||
total: None,
|
||||
page: None,
|
||||
}));
|
||||
};
|
||||
let advisories =
|
||||
advisories_naming(agent.advisory_index.as_ref(), vec![order_number.clone()]).await?;
|
||||
let check = DeviceCheck::new(device, &advisories);
|
||||
Ok(Json(ApiResponse {
|
||||
data: DeviceLookup {
|
||||
order_number,
|
||||
valid: true,
|
||||
product: check.product,
|
||||
advisories: check.advisories.len(),
|
||||
},
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use futures_util::future::BoxFuture;
|
||||
|
||||
/// An index answering with the synthetic Siemens advisory, and a CODESYS
|
||||
/// one that must never reach a device.
|
||||
struct Fixture;
|
||||
|
||||
impl AdvisoryIndex for Fixture {
|
||||
fn relevant<'a>(
|
||||
&'a self,
|
||||
wanted: &'a Wanted,
|
||||
) -> BoxFuture<'a, Result<Vec<(String, Advisory)>, String>> {
|
||||
assert!(wanted.providers.is_empty() && wanted.purls.is_empty());
|
||||
let doc: serde_json::Value = serde_json::from_str(include_str!(
|
||||
"../../../../compliance-core/tests/fixtures/csaf/siemens-synthetic.json"
|
||||
))
|
||||
.unwrap();
|
||||
let siemens = compliance_core::csaf_ingest::parse(&doc).unwrap();
|
||||
let mut codesys = siemens.clone();
|
||||
codesys.id = "VDE-2026-0001".into();
|
||||
Box::pin(async move {
|
||||
Ok(vec![
|
||||
("siemens".to_string(), siemens),
|
||||
("codesys".to_string(), codesys),
|
||||
])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn devices_are_checked_against_siemens_advisories_only() {
|
||||
let advisories = advisories_naming(&Fixture, vec!["6ES7511-1AK02-0AB0".into()])
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(advisories.len(), 1);
|
||||
let devices = checks(
|
||||
vec![
|
||||
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.4", None).unwrap(),
|
||||
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.5", None).unwrap(),
|
||||
PlcDevice::new("6ES7516-3AN02-0AB0", "3.0", None).unwrap(),
|
||||
],
|
||||
&advisories,
|
||||
);
|
||||
use compliance_core::device_check::DeviceState;
|
||||
let states: Vec<DeviceState> = devices.iter().map(DeviceCheck::state).collect();
|
||||
assert_eq!(
|
||||
states,
|
||||
[
|
||||
DeviceState::Affected,
|
||||
DeviceState::NotAffected,
|
||||
DeviceState::NotNamed
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
devices[0].advisories[0].fixed_from.as_deref(),
|
||||
Some("3.1.5")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -15,11 +15,17 @@ pub const MAX_PAGE_SIZE: i64 = 200;
|
||||
/// absurd offset. At [`MAX_PAGE_SIZE`] this is still 20M documents deep.
|
||||
pub const MAX_PAGE: u64 = 100_000;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// The page of a list a request asks for.
|
||||
#[derive(Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct PaginationParams {
|
||||
/// The page, from 1 (default 1, at most 100 000).
|
||||
#[serde(default = "default_page", deserialize_with = "de_page")]
|
||||
#[param(minimum = 1, maximum = 100_000)]
|
||||
pub page: u64,
|
||||
/// Entries per page (default 50, at most 200).
|
||||
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
||||
#[param(minimum = 1, maximum = 200)]
|
||||
pub limit: i64,
|
||||
}
|
||||
|
||||
@@ -49,33 +55,57 @@ pub(crate) fn de_limit<'de, D: serde::Deserializer<'de>>(d: D) -> Result<i64, D:
|
||||
Ok(i64::deserialize(d)?.clamp(1, MAX_PAGE_SIZE))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// Which findings a list returns, and in what order.
|
||||
#[derive(Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct FindingsFilter {
|
||||
/// Only one target's findings (its id).
|
||||
#[serde(default)]
|
||||
pub repo_id: Option<String>,
|
||||
/// Only the findings a given scan run found first (the dashboard reveals
|
||||
/// them when the run ends).
|
||||
#[serde(default)]
|
||||
pub scan_run_id: Option<String>,
|
||||
/// `info`, `low`, `medium`, `high` or `critical`.
|
||||
#[serde(default)]
|
||||
pub severity: Option<String>,
|
||||
/// Only one kind of scan (`sast`, `cve`, `dast`, …).
|
||||
#[serde(default)]
|
||||
pub scan_type: Option<String>,
|
||||
/// `open`, `triaged`, `false_positive`, `resolved`, `ignored`,
|
||||
/// `accepted_risk`, `needs_review` or `wrong_mapping`.
|
||||
#[serde(default)]
|
||||
pub status: Option<String>,
|
||||
/// Text the title, description or file path contains (at most 128
|
||||
/// characters, matched literally).
|
||||
#[serde(default)]
|
||||
pub q: Option<String>,
|
||||
/// Only the findings of one scanner (`Finding::scanner`, e.g.
|
||||
/// `sbom-coverage`).
|
||||
#[serde(default)]
|
||||
pub scanner: Option<String>,
|
||||
/// Only the findings in one app variant (`Tablet App`): its own, and the
|
||||
/// groups listing a place in it.
|
||||
#[serde(default)]
|
||||
pub variant: Option<String>,
|
||||
/// Only the findings in one folder, as the folder chart names it
|
||||
/// ([`path_regex`]).
|
||||
#[serde(default)]
|
||||
pub path: Option<String>,
|
||||
/// `created_at` (default), `updated_at`, `severity`, `scan_type`,
|
||||
/// `status`, `file_path`, `rule_id`, `repo_id`, `title` or `confidence`.
|
||||
#[serde(default)]
|
||||
pub sort_by: Option<String>,
|
||||
/// `asc`, or newest/highest first (default).
|
||||
#[serde(default)]
|
||||
pub sort_order: Option<String>,
|
||||
/// The page, from 1 (default 1, at most 100 000).
|
||||
#[serde(default = "default_page", deserialize_with = "de_page")]
|
||||
#[param(minimum = 1, maximum = 100_000)]
|
||||
pub page: u64,
|
||||
/// Entries per page (default 50, at most 200).
|
||||
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
||||
#[param(minimum = 1, maximum = 200)]
|
||||
pub limit: i64,
|
||||
}
|
||||
|
||||
@@ -88,6 +118,71 @@ 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, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct IssuesFilter {
|
||||
/// A word of the title or the ticket number (`913`, `#913`, `PROJ-913`).
|
||||
#[serde(default)]
|
||||
pub q: Option<String>,
|
||||
/// `open` or `closed`; an unknown value is refused (400).
|
||||
#[serde(default)]
|
||||
#[param(value_type = Option<String>, example = "open")]
|
||||
pub status: Option<TicketState>,
|
||||
/// Only the tickets of one target: of its findings and its CVEs.
|
||||
#[serde(default)]
|
||||
pub repo_id: Option<String>,
|
||||
/// The page, from 1 (default 1, at most 100 000).
|
||||
#[serde(default = "default_page", deserialize_with = "de_page")]
|
||||
#[param(minimum = 1, maximum = 100_000)]
|
||||
pub page: u64,
|
||||
/// Entries per page (default 50, at most 200).
|
||||
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
||||
#[param(minimum = 1, maximum = 200)]
|
||||
pub limit: i64,
|
||||
}
|
||||
|
||||
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 +231,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,
|
||||
@@ -191,39 +315,58 @@ fn default_branch() -> String {
|
||||
"main".to_string()
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// A finding's new status.
|
||||
#[derive(Deserialize, utoipa::ToSchema)]
|
||||
pub struct UpdateStatusRequest {
|
||||
/// Typed, so an unknown status is refused (422) instead of being stored
|
||||
/// and breaking every later read of the finding.
|
||||
/// `open`, `triaged`, `false_positive`, `resolved`, `ignored`,
|
||||
/// `accepted_risk`, `needs_review` or `wrong_mapping`. Typed, so an
|
||||
/// unknown status is refused (422) instead of being stored and breaking
|
||||
/// every later read of the finding.
|
||||
#[schema(value_type = String, example = "false_positive")]
|
||||
pub status: compliance_core::models::FindingStatus,
|
||||
/// Why; required for `accepted_risk`.
|
||||
#[serde(default)]
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// The same new status for many findings.
|
||||
#[derive(Deserialize, utoipa::ToSchema)]
|
||||
pub struct BulkUpdateStatusRequest {
|
||||
/// The findings' ids.
|
||||
pub ids: Vec<String>,
|
||||
/// The status, as for one finding.
|
||||
#[schema(value_type = String, example = "resolved")]
|
||||
pub status: compliance_core::models::FindingStatus,
|
||||
/// Why; required for `accepted_risk` and `wrong_mapping`.
|
||||
#[serde(default)]
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// A developer's feedback on a finding.
|
||||
#[derive(Deserialize, utoipa::ToSchema)]
|
||||
pub struct UpdateFeedbackRequest {
|
||||
/// The feedback, as text.
|
||||
pub feedback: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// Which SBOM components a list or summary shows.
|
||||
#[derive(Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct SbomFilter {
|
||||
/// Only one target's components (its id).
|
||||
#[serde(default)]
|
||||
pub repo_id: Option<String>,
|
||||
/// Only one package manager's components, such as `npm` or `cargo`.
|
||||
#[serde(default)]
|
||||
pub package_manager: Option<String>,
|
||||
/// Only components whose name contains this text.
|
||||
#[serde(default)]
|
||||
pub q: Option<String>,
|
||||
/// Only components with known vulnerabilities (`true`), or only those
|
||||
/// without (`false`).
|
||||
#[serde(default)]
|
||||
pub has_vulns: Option<bool>,
|
||||
/// Only components with this licence.
|
||||
#[serde(default)]
|
||||
pub license: Option<String>,
|
||||
/// Only components an image is known to contain (`true`), or only the
|
||||
@@ -234,9 +377,13 @@ pub struct SbomFilter {
|
||||
/// none and nobody has confirmed one.
|
||||
#[serde(default)]
|
||||
pub unresolved: Option<bool>,
|
||||
/// The page, from 1 (default 1, at most 100 000).
|
||||
#[serde(default = "default_page", deserialize_with = "de_page")]
|
||||
#[param(minimum = 1, maximum = 100_000)]
|
||||
pub page: u64,
|
||||
/// Entries per page (default 50, at most 200).
|
||||
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
||||
#[param(minimum = 1, maximum = 200)]
|
||||
pub limit: i64,
|
||||
}
|
||||
|
||||
@@ -249,10 +396,15 @@ impl SbomFilter {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// The target and format of an SBOM export.
|
||||
#[derive(Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct SbomExportParams {
|
||||
/// The target (its id).
|
||||
pub repo_id: String,
|
||||
/// `cyclonedx` (default) or `spdx`.
|
||||
#[serde(default = "default_export_format")]
|
||||
#[param(example = "cyclonedx")]
|
||||
pub format: String,
|
||||
}
|
||||
|
||||
@@ -260,9 +412,13 @@ fn default_export_format() -> String {
|
||||
"cyclonedx".to_string()
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// The two targets an SBOM diff compares.
|
||||
#[derive(Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct SbomDiffParams {
|
||||
/// The first target (its id).
|
||||
pub repo_a: String,
|
||||
/// The second target (its id).
|
||||
pub repo_b: String,
|
||||
}
|
||||
|
||||
@@ -412,6 +568,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 +669,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)?,
|
||||
@@ -107,9 +112,19 @@ fn state_counts(controls: &[crate::evidence::compliance::ControlStatus]) -> serd
|
||||
/// Targets whose CRA status is computed at the same time for the summary.
|
||||
const SUMMARY_CONCURRENCY: usize = 4;
|
||||
|
||||
/// GET /api/v1/compliance/summary — every target's CRA state counts, for the
|
||||
/// overview. A target too large to evaluate in memory is listed with
|
||||
/// `counts: null` rather than failing the whole summary.
|
||||
/// Every target's CRA control counts per state, for the overview.
|
||||
///
|
||||
/// A target too large to evaluate in memory is listed with `counts: null`
|
||||
/// rather than failing the whole summary.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/compliance/summary",
|
||||
tag = "Compliance",
|
||||
responses(
|
||||
(status = 200, description = "The counts per target"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn compliance_summary(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -153,8 +168,22 @@ pub async fn compliance_summary(
|
||||
Ok(Json(serde_json::json!({ "data": rows })))
|
||||
}
|
||||
|
||||
/// GET /api/v1/targets/{id}/compliance — the target's state against every CRA
|
||||
/// Annex I control, with the findings against each and the last scan.
|
||||
/// A target's state against every CRA Annex I control.
|
||||
///
|
||||
/// With the findings against each and the last scan.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/targets/{id}/compliance",
|
||||
tag = "Compliance",
|
||||
params(("id" = String, Path, description = "The target's id")),
|
||||
responses(
|
||||
(status = 200, description = "The state per control"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 404, description = "No such target"),
|
||||
(status = 413, description = "Too large to evaluate in memory"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn compliance_view(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -168,6 +197,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(),
|
||||
@@ -177,8 +209,22 @@ pub async fn compliance_view(
|
||||
})))
|
||||
}
|
||||
|
||||
/// GET /api/v1/targets/{id}/evidence-pack — 404 for an unknown target, 413
|
||||
/// when it is too large to build in memory.
|
||||
/// A target's evidence pack to download.
|
||||
///
|
||||
/// 404 for an unknown target, 413 when it is too large to build in memory.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/targets/{id}/evidence-pack",
|
||||
tag = "Compliance",
|
||||
params(("id" = String, Path, description = "The target's id")),
|
||||
responses(
|
||||
(status = 200, description = "The evidence pack"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 404, description = "No such target"),
|
||||
(status = 413, description = "Too large to build in memory"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn evidence_pack(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -223,14 +269,28 @@ pub async fn evidence_pack(
|
||||
const MAX_CONTROL_LOOKUP: usize = 50;
|
||||
|
||||
/// The query of [`describe_controls`]: comma-separated control ids.
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
#[derive(Debug, serde::Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct ControlIdsQuery {
|
||||
/// The master control ids, comma-separated, at most 50.
|
||||
#[param(example = "mc-1,mc-2")]
|
||||
ids: String,
|
||||
}
|
||||
|
||||
/// GET /api/v1/controls?ids=mc-1,mc-2 — what the master controls stamped on
|
||||
/// a finding require, for the finding page. Unknown ids are left out; at
|
||||
/// most [`MAX_CONTROL_LOOKUP`] are described.
|
||||
/// What the master controls stamped on a finding require.
|
||||
///
|
||||
/// For the finding page. Unknown ids are left out; at most
|
||||
/// [`MAX_CONTROL_LOOKUP`] are described.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/controls",
|
||||
tag = "Compliance",
|
||||
params(ControlIdsQuery),
|
||||
responses(
|
||||
(status = 200, description = "The controls"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn describe_controls(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
//! `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 } }
|
||||
}
|
||||
|
||||
/// A target's open findings, 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.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/targets/{id}/finding-breakdown",
|
||||
tag = "Findings",
|
||||
params(("id" = String, Path, description = "The target's id")),
|
||||
responses(
|
||||
(status = 200, description = "The breakdown"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[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,304 @@
|
||||
//! Open findings grouped by rule and file, and one decision for a whole
|
||||
//! group (#951).
|
||||
//!
|
||||
//! The grouping is [`compliance_core::models::finding_group`], a pure
|
||||
//! function over the findings; nothing about groups is stored. A group
|
||||
//! decision is a status change of every member through the same path as a
|
||||
//! bulk change ([`super::findings::apply_status`]), so the status history,
|
||||
//! the issue sync, the evidence pack and VEX see ordinary per-finding
|
||||
//! changes.
|
||||
|
||||
use axum::extract::{Extension, Query};
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use mongodb::bson::{doc, Document};
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::dto::{collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResult};
|
||||
use super::findings::{apply_status, status_update, Actor};
|
||||
use super::health::OPEN_STATUSES;
|
||||
use compliance_core::models::finding_group::{group_findings, members_of, FindingGroup, GroupKey};
|
||||
use compliance_core::models::{Finding, FindingStatus};
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
/// The query of [`list_finding_groups`].
|
||||
#[derive(Debug, Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct GroupsQuery {
|
||||
/// Only one target's findings (`Finding::repo_id`).
|
||||
#[serde(default)]
|
||||
pub target: Option<String>,
|
||||
}
|
||||
|
||||
/// The body of [`decide_finding_group`].
|
||||
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||
pub struct DecideGroupRequest {
|
||||
/// The group, as [`list_finding_groups`] named it.
|
||||
#[schema(value_type = Object)]
|
||||
pub key: GroupKey,
|
||||
/// The decision for every member, a finding status.
|
||||
#[schema(value_type = String, example = "false_positive")]
|
||||
pub status: FindingStatus,
|
||||
/// Why; required for an accepted risk or a wrong mapping.
|
||||
#[serde(default)]
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
/// The fields a group never shows, left out of the read: the code, the fix
|
||||
/// and the history are on each finding's own page.
|
||||
fn light_projection() -> Document {
|
||||
doc! {
|
||||
"code_snippet": 0,
|
||||
"suggested_fix": 0,
|
||||
"remediation": 0,
|
||||
"status_history": 0,
|
||||
"legacy_fingerprints": 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The undecided findings `filter` narrows down to.
|
||||
async fn undecided_findings(
|
||||
db: &crate::database::Database,
|
||||
mut filter: Document,
|
||||
) -> Result<Vec<Finding>, StatusCode> {
|
||||
filter.insert("status", doc! { "$in": OPEN_STATUSES.to_vec() });
|
||||
let cursor = db
|
||||
.findings()
|
||||
.find(filter)
|
||||
.projection(light_projection())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::warn!("Failed to fetch findings to group: {e}");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
Ok(collect_cursor_async(cursor).await)
|
||||
}
|
||||
|
||||
/// List the undecided findings, grouped by rule and file.
|
||||
///
|
||||
/// Most severe first (see [`compliance_core::models::finding_group`]).
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/finding-groups",
|
||||
tag = "Findings",
|
||||
params(GroupsQuery),
|
||||
responses(
|
||||
(status = 200, description = "The groups, most severe first"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(target = ?query.target))]
|
||||
pub async fn list_finding_groups(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Query(query): Query<GroupsQuery>,
|
||||
) -> ApiResult<Vec<FindingGroup>> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let filter = query
|
||||
.target
|
||||
.filter(|t| !t.is_empty())
|
||||
.map_or_else(Document::new, |target| doc! { "repo_id": target });
|
||||
let groups = group_findings(undecided_findings(&db, filter).await?);
|
||||
Ok(Json(ApiResponse {
|
||||
total: Some(groups.len() as u64),
|
||||
data: groups,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Whether a person may give a whole group `status`: a decision, not a
|
||||
/// return to an undecided state (the members are undecided already, and
|
||||
/// "needs review" is the AI's to set).
|
||||
fn is_group_decision(status: &FindingStatus) -> bool {
|
||||
match status {
|
||||
FindingStatus::FalsePositive
|
||||
| FindingStatus::AcceptedRisk
|
||||
| FindingStatus::WrongMapping
|
||||
| FindingStatus::Ignored
|
||||
| FindingStatus::Resolved => true,
|
||||
FindingStatus::Open | FindingStatus::Triaged | FindingStatus::NeedsReview => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The status change `req` asks of every member, by `actor`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 422 when the status is not a decision, or needs a reason and comes
|
||||
/// without one.
|
||||
fn decision_update(req: &DecideGroupRequest, actor: &Actor<'_>) -> Result<Document, StatusCode> {
|
||||
if !is_group_decision(&req.status) {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
status_update(&req.status, req.reason.as_deref(), actor)
|
||||
}
|
||||
|
||||
/// The findings that may belong to the group `key`: its rule in its target.
|
||||
/// The grouping then picks the members from them.
|
||||
fn candidates_filter(key: &GroupKey) -> Document {
|
||||
doc! {
|
||||
"repo_id": &key.repo_id,
|
||||
"scanner": &key.scanner,
|
||||
"$or": [
|
||||
{ "rule_id": &key.rule },
|
||||
// A finding without a rule id is grouped by its title.
|
||||
{ "rule_id": { "$in": [null, ""] }, "title": &key.rule },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/// Decide every undecided finding of a group at once.
|
||||
///
|
||||
/// Each member gets the same status, as if each were changed on its own.
|
||||
///
|
||||
/// The members are found again from the key, so a member someone decided
|
||||
/// in the meantime keeps that decision. 404 when the group has no undecided
|
||||
/// member (any more), 422 as [`decision_update`].
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/finding-groups/decide",
|
||||
tag = "Findings",
|
||||
request_body = DecideGroupRequest,
|
||||
responses(
|
||||
(status = 200, description = "The members were decided"),
|
||||
(status = 404, description = "The group has no undecided member"),
|
||||
(status = 422, description = "An unknown status, or no reason for one that needs it"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(rule = %req.key.rule, scope = ?req.key.scope))]
|
||||
pub async fn decide_finding_group(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Json(req): Json<DecideGroupRequest>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let update = decision_update(&req, &Actor::of(&tenant.0))?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let candidates = undecided_findings(&db, candidates_filter(&req.key)).await?;
|
||||
let oids = members_of(candidates, &req.key);
|
||||
if oids.is_empty() {
|
||||
return Err(StatusCode::NOT_FOUND);
|
||||
}
|
||||
let filter = doc! {
|
||||
"_id": { "$in": oids.clone() },
|
||||
"status": { "$in": OPEN_STATUSES.to_vec() },
|
||||
};
|
||||
let members = oids.len();
|
||||
let modified_count = apply_status(&agent, db, filter, oids, update).await?;
|
||||
Ok(Json(serde_json::json!({
|
||||
"status": "updated",
|
||||
"members": members,
|
||||
"modified_count": modified_count,
|
||||
})))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::finding_group::GroupScope;
|
||||
|
||||
fn key() -> GroupKey {
|
||||
GroupKey {
|
||||
repo_id: "repo-1".into(),
|
||||
scanner: "gdpr-patterns".into(),
|
||||
rule: "pii-logged".into(),
|
||||
scope: GroupScope::File,
|
||||
place: Some("src/patterns.rs".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn request(status: FindingStatus, reason: Option<&str>) -> DecideGroupRequest {
|
||||
DecideGroupRequest {
|
||||
key: key(),
|
||||
status,
|
||||
reason: reason.map(String::from),
|
||||
}
|
||||
}
|
||||
|
||||
fn user() -> Actor<'static> {
|
||||
Actor {
|
||||
id: "u-1",
|
||||
name: None,
|
||||
support: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_takes_only_decisions() {
|
||||
for status in [
|
||||
FindingStatus::Open,
|
||||
FindingStatus::Triaged,
|
||||
FindingStatus::NeedsReview,
|
||||
] {
|
||||
assert_eq!(
|
||||
decision_update(&request(status.clone(), Some("why")), &user()).err(),
|
||||
Some(StatusCode::UNPROCESSABLE_ENTITY),
|
||||
"{status}"
|
||||
);
|
||||
}
|
||||
for status in [
|
||||
FindingStatus::FalsePositive,
|
||||
FindingStatus::Ignored,
|
||||
FindingStatus::Resolved,
|
||||
] {
|
||||
assert!(
|
||||
decision_update(&request(status.clone(), None), &user()).is_ok(),
|
||||
"{status}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_accepted_risk_for_a_group_needs_a_reason() {
|
||||
assert_eq!(
|
||||
decision_update(&request(FindingStatus::AcceptedRisk, None), &user()).err(),
|
||||
Some(StatusCode::UNPROCESSABLE_ENTITY)
|
||||
);
|
||||
assert_eq!(
|
||||
decision_update(&request(FindingStatus::AcceptedRisk, Some(" ")), &user()).err(),
|
||||
Some(StatusCode::UNPROCESSABLE_ENTITY)
|
||||
);
|
||||
let update = decision_update(
|
||||
&request(FindingStatus::AcceptedRisk, Some("isolated network")),
|
||||
&user(),
|
||||
)
|
||||
.unwrap_or_default();
|
||||
let change = update
|
||||
.get_document("$push")
|
||||
.and_then(|p| p.get_document("status_history"))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
assert_eq!(change.get_str("reason").ok(), Some("isolated network"));
|
||||
assert_eq!(change.get_str("by").ok(), Some("u-1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_reads_the_key_and_refuses_an_unknown_status() {
|
||||
let wire = serde_json::json!({
|
||||
"key": {
|
||||
"repo_id": "repo-1",
|
||||
"scanner": "gdpr-patterns",
|
||||
"rule": "pii-logged",
|
||||
"scope": "file",
|
||||
"place": "src/patterns.rs",
|
||||
},
|
||||
"status": "false_positive",
|
||||
});
|
||||
let req = serde_json::from_value::<DecideGroupRequest>(wire.clone());
|
||||
assert_eq!(req.ok().map(|r| r.key), Some(key()));
|
||||
let mut bad = wire.clone();
|
||||
bad["status"] = "wontfix".into();
|
||||
assert!(serde_json::from_value::<DecideGroupRequest>(bad).is_err());
|
||||
let mut bad_scope = wire;
|
||||
bad_scope["key"]["scope"] = "everywhere".into();
|
||||
assert!(serde_json::from_value::<DecideGroupRequest>(bad_scope).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_candidates_are_the_rule_in_the_target() {
|
||||
let filter = candidates_filter(&key());
|
||||
assert_eq!(filter.get_str("repo_id").ok(), Some("repo-1"));
|
||||
assert_eq!(filter.get_str("scanner").ok(), Some("gdpr-patterns"));
|
||||
assert_eq!(filter.get_array("$or").map(Vec::len).ok(), Some(2));
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,17 @@ use super::dto::*;
|
||||
use compliance_core::models::{Finding, FindingStatus, StatusChange};
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
/// List the tenant's findings, filtered, sorted and a page at a time.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/findings",
|
||||
tag = "Findings",
|
||||
params(FindingsFilter),
|
||||
responses(
|
||||
(status = 200, description = "A page of findings"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(repo_id = ?filter.repo_id, severity = ?filter.severity, scan_type = ?filter.scan_type))]
|
||||
pub async fn list_findings(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -28,8 +39,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 +126,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";
|
||||
|
||||
@@ -126,15 +155,27 @@ fn severity_rank() -> mongodb::bson::Document {
|
||||
}
|
||||
|
||||
/// The query of [`list_finding_variants`].
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
#[derive(Debug, serde::Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct VariantsQuery {
|
||||
/// Only one target's variants.
|
||||
#[serde(default)]
|
||||
pub repo_id: Option<String>,
|
||||
}
|
||||
|
||||
/// The app variants the tenant's findings are labelled with (theirs and their
|
||||
/// groups' places), sorted, for the findings filter.
|
||||
/// List the app variants the tenant's findings are in.
|
||||
///
|
||||
/// Their own and their groups' places, sorted, for the findings filter.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/findings/variants",
|
||||
tag = "Findings",
|
||||
params(VariantsQuery),
|
||||
responses(
|
||||
(status = 200, description = "The app variant names, sorted"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(repo_id = ?query.repo_id))]
|
||||
pub async fn list_finding_variants(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -165,6 +206,19 @@ pub async fn list_finding_variants(
|
||||
}))
|
||||
}
|
||||
|
||||
/// One finding.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/findings/{id}",
|
||||
tag = "Findings",
|
||||
params(("id" = String, Path, description = "The finding's id")),
|
||||
responses(
|
||||
(status = 200, description = "The finding"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 404, description = "No such finding"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(finding_id = %id))]
|
||||
pub async fn get_finding(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -214,7 +268,7 @@ impl<'a> Actor<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn status_update(
|
||||
pub(crate) fn status_update(
|
||||
status: &FindingStatus,
|
||||
reason: Option<&str>,
|
||||
actor: &Actor<'_>,
|
||||
@@ -231,6 +285,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)?;
|
||||
@@ -254,8 +309,23 @@ fn issue_sync(
|
||||
}
|
||||
}
|
||||
|
||||
/// PATCH /api/v1/findings/{id}/status — change the status, recording who,
|
||||
/// when and why. 404 when there is no such finding.
|
||||
/// Change a finding's status.
|
||||
///
|
||||
/// Records who, when and why. 404 when there is no such finding.
|
||||
#[utoipa::path(
|
||||
patch,
|
||||
path = "/api/v1/findings/{id}/status",
|
||||
tag = "Findings",
|
||||
params(("id" = String, Path, description = "The finding's id")),
|
||||
request_body = UpdateStatusRequest,
|
||||
responses(
|
||||
(status = 200, description = "The status was changed"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 404, description = "No such finding"),
|
||||
(status = 422, description = "An unknown status, or no reason for one that needs it"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(finding_id = %id))]
|
||||
pub async fn update_finding_status(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -280,7 +350,19 @@ pub async fn update_finding_status(
|
||||
Ok(Json(serde_json::json!({ "status": "updated" })))
|
||||
}
|
||||
|
||||
/// PATCH /api/v1/findings/bulk-status — the same change on many findings.
|
||||
/// Change the status of many findings at once.
|
||||
#[utoipa::path(
|
||||
patch,
|
||||
path = "/api/v1/findings/bulk-status",
|
||||
tag = "Findings",
|
||||
request_body = BulkUpdateStatusRequest,
|
||||
responses(
|
||||
(status = 200, description = "How many findings changed"),
|
||||
(status = 400, description = "An id that is not one"),
|
||||
(status = 422, description = "An unknown status, or no reason for one that needs it"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn bulk_update_finding_status(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -299,20 +381,58 @@ 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 }),
|
||||
))
|
||||
}
|
||||
|
||||
/// PATCH /api/v1/findings/{id}/feedback — store the developer's feedback on a
|
||||
/// finding. 404 when there is no such finding.
|
||||
/// Apply the status change `update` (from [`status_update`]) to the findings
|
||||
/// `filter` matches, then carry the new status over to the issues of `oids`
|
||||
/// (the findings the filter is about) in the background: the one path every
|
||||
/// change of many findings takes, a bulk change or a group decision (#951).
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// How many findings changed.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 500 when the database refuses the update.
|
||||
pub(crate) async fn apply_status(
|
||||
agent: &crate::agent::ComplianceAgent,
|
||||
db: crate::database::Database,
|
||||
filter: mongodb::bson::Document,
|
||||
oids: Vec<mongodb::bson::oid::ObjectId>,
|
||||
update: mongodb::bson::Document,
|
||||
) -> Result<u64, StatusCode> {
|
||||
let result = db
|
||||
.findings()
|
||||
.update_many(filter, update)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
issue_sync(agent, db).spawn(oids);
|
||||
Ok(result.modified_count)
|
||||
}
|
||||
|
||||
/// Store a developer's feedback on a finding.
|
||||
///
|
||||
/// 404 when there is no such finding.
|
||||
#[utoipa::path(
|
||||
patch,
|
||||
path = "/api/v1/findings/{id}/feedback",
|
||||
tag = "Findings",
|
||||
params(("id" = String, Path, description = "The finding's id")),
|
||||
request_body = UpdateFeedbackRequest,
|
||||
responses(
|
||||
(status = 200, description = "The feedback was stored"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 404, description = "No such finding"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(finding_id = %id))]
|
||||
pub async fn update_finding_feedback(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -342,6 +462,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,19 +6,31 @@ 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
|
||||
/// workspace has none.
|
||||
/// The workspace's managed git source, without secrets.
|
||||
///
|
||||
/// Plus the webhook URL; `data: null` when the workspace has none. For
|
||||
/// administrators (IT_ADMIN, OWNER) and support.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/git-source",
|
||||
tag = "Workspace",
|
||||
responses(
|
||||
(status = 200, description = "The source, or null"),
|
||||
(status = 403, description = "Not an administrator or support"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
pub async fn get_git_source(
|
||||
axum::extract::Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
|
||||
@@ -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;
|
||||
@@ -40,14 +42,18 @@ pub struct GraphData {
|
||||
pub total_nodes: u64,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// A symbol search.
|
||||
#[derive(Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct SearchParams {
|
||||
/// The search text.
|
||||
pub q: String,
|
||||
/// Clamped to `1..=MAX_PAGE_SIZE` while deserializing, like every list.
|
||||
#[serde(
|
||||
default = "default_search_limit",
|
||||
deserialize_with = "super::dto::de_limit"
|
||||
)]
|
||||
#[param(minimum = 1, maximum = 200)]
|
||||
pub limit: i64,
|
||||
}
|
||||
|
||||
@@ -55,7 +61,19 @@ fn default_search_limit() -> i64 {
|
||||
50
|
||||
}
|
||||
|
||||
/// GET /api/v1/graph/:repo_id — Full graph data
|
||||
/// A target's code graph: its latest build, nodes and edges.
|
||||
///
|
||||
/// Truncated past a size a browser can lay out, and says so.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/graph/{repo_id}",
|
||||
tag = "Code graph",
|
||||
params(("repo_id" = String, Path, description = "The target's id")),
|
||||
responses(
|
||||
(status = 200, description = "The graph"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||
pub async fn get_graph(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -148,7 +166,17 @@ pub async fn get_graph(
|
||||
}))
|
||||
}
|
||||
|
||||
/// GET /api/v1/graph/:repo_id/nodes — List nodes (paginated)
|
||||
/// A target's code graph nodes, a page at a time.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/graph/{repo_id}/nodes",
|
||||
tag = "Code graph",
|
||||
params(("repo_id" = String, Path, description = "The target's id"), PaginationParams),
|
||||
responses(
|
||||
(status = 200, description = "A page of nodes"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||
pub async fn get_nodes(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -188,7 +216,82 @@ pub async fn get_nodes(
|
||||
}))
|
||||
}
|
||||
|
||||
/// GET /api/v1/graph/:repo_id/communities — List detected communities
|
||||
/// What the target page shows of a code graph.
|
||||
#[derive(Serialize)]
|
||||
pub struct GraphSummary {
|
||||
/// Declarations: functions, methods, types, PLC blocks (nodes that are
|
||||
/// not files).
|
||||
pub units: u32,
|
||||
pub entry_points: u32,
|
||||
/// Language codes, sorted (`c`, `csharp`, `structured_text`, …).
|
||||
pub languages: Vec<String>,
|
||||
/// Source files left out because they could not be read as text; 0 when
|
||||
/// none were, or the build did not count them.
|
||||
pub unreadable_files: u32,
|
||||
}
|
||||
|
||||
impl GraphSummary {
|
||||
/// The summary of a completed build; `None` for one still running, a
|
||||
/// failed one, or one stored before its files and entry points were
|
||||
/// counted.
|
||||
fn of(build: GraphBuildRun) -> Option<Self> {
|
||||
if build.status != GraphBuildStatus::Completed {
|
||||
return None;
|
||||
}
|
||||
Some(Self {
|
||||
units: build.node_count.saturating_sub(build.file_count?),
|
||||
entry_points: build.entry_point_count?,
|
||||
languages: build.languages_parsed,
|
||||
// Not `?`: a build from before this count still shows its card.
|
||||
unreadable_files: build.unreadable_file_count.unwrap_or(0),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The counts of a target's latest graph build, without loading any node.
|
||||
///
|
||||
/// `data` is `null` when there is none to show.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/graph/{repo_id}/summary",
|
||||
tag = "Code graph",
|
||||
params(("repo_id" = String, Path, description = "The target's id")),
|
||||
responses(
|
||||
(status = 200, description = "The counts, or null"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||
pub async fn get_summary(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(repo_id): Path<String>,
|
||||
) -> Result<Json<ApiResponse<Option<GraphSummary>>>, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let build = db
|
||||
.graph_builds()
|
||||
.find_one(doc! { "repo_id": &repo_id })
|
||||
.sort(doc! { "started_at": -1 })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
Ok(Json(ApiResponse {
|
||||
data: build.and_then(GraphSummary::of),
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// The communities detected in a target's code graph.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/graph/{repo_id}/communities",
|
||||
tag = "Code graph",
|
||||
params(("repo_id" = String, Path, description = "The target's id")),
|
||||
responses(
|
||||
(status = 200, description = "The communities"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||
pub async fn get_communities(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -256,7 +359,17 @@ pub struct CommunityInfo {
|
||||
pub members: Vec<String>,
|
||||
}
|
||||
|
||||
/// GET /api/v1/graph/:repo_id/impact/:finding_id — Impact analysis
|
||||
/// What a finding reaches in a target's code graph.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/graph/{repo_id}/impact/{finding_id}",
|
||||
tag = "Code graph",
|
||||
params(("repo_id" = String, Path, description = "The target's id"), ("finding_id" = String, Path, description = "The finding's id")),
|
||||
responses(
|
||||
(status = 200, description = "The impact analysis, or null"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id, finding_id = %finding_id))]
|
||||
pub async fn get_impact(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -280,7 +393,17 @@ pub async fn get_impact(
|
||||
}))
|
||||
}
|
||||
|
||||
/// GET /api/v1/graph/:repo_id/search — BM25 symbol search
|
||||
/// Search a target's code graph for symbols (BM25).
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/graph/{repo_id}/search",
|
||||
tag = "Code graph",
|
||||
params(("repo_id" = String, Path, description = "The target's id"), SearchParams),
|
||||
responses(
|
||||
(status = 200, description = "The matching nodes"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id, query = %params.q))]
|
||||
pub async fn search_symbols(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -314,7 +437,19 @@ pub async fn search_symbols(
|
||||
}))
|
||||
}
|
||||
|
||||
/// GET /api/v1/graph/:repo_id/file-content — Read source file from cloned repo
|
||||
/// A source file of a target's checkout.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/graph/{repo_id}/file-content",
|
||||
tag = "Code graph",
|
||||
params(("repo_id" = String, Path, description = "The target's id"), FileContentParams),
|
||||
responses(
|
||||
(status = 200, description = "The file"),
|
||||
(status = 403, description = "The path leaves the checkout"),
|
||||
(status = 404, description = "No such target, checkout or file"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||
pub async fn get_file_content(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -355,7 +490,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");
|
||||
@@ -373,8 +510,11 @@ pub async fn get_file_content(
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// The file of [`get_file_content`].
|
||||
#[derive(Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct FileContentParams {
|
||||
/// The file's path in the checkout.
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
@@ -385,7 +525,17 @@ pub struct FileContent {
|
||||
pub language: String,
|
||||
}
|
||||
|
||||
/// POST /api/v1/graph/:repo_id/build — Trigger graph rebuild
|
||||
/// Rebuild a target's code graph in the background.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/graph/{repo_id}/build",
|
||||
tag = "Code graph",
|
||||
params(("repo_id" = String, Path, description = "The target's id")),
|
||||
responses(
|
||||
(status = 200, description = "The build was started"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||
pub async fn trigger_build(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -434,10 +584,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 +617,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
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -5,31 +5,94 @@ use super::dto::*;
|
||||
use compliance_core::models::ScanRun;
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
/// `GET /api/v1/access`: reached only when the authentication, entitlement
|
||||
/// and role layers let the caller through; they answer the refusals (a
|
||||
/// blocked member gets 403 `MEMBER_BLOCKED`).
|
||||
/// Whether the caller may use Prüfwerk at all.
|
||||
///
|
||||
/// Reached only when the authentication, entitlement and role layers let the
|
||||
/// caller through; they answer the refusals (a blocked member gets 403
|
||||
/// `MEMBER_BLOCKED`).
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/access",
|
||||
tag = "Workspace",
|
||||
responses(
|
||||
(status = 200, description = "The caller may use Prüfwerk"),
|
||||
(status = 403, description = "Not entitled, or a blocked member"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
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);
|
||||
|
||||
/// Whether the agent can serve: MongoDB answers a ping.
|
||||
///
|
||||
/// 200 `{"status":"ok"}` when MongoDB answers, 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.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/health",
|
||||
tag = "Health",
|
||||
responses(
|
||||
(status = 200, description = "MongoDB answers"),
|
||||
(status = 503, description = "MongoDB is unreachable"),
|
||||
)
|
||||
)]
|
||||
#[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 {
|
||||
@@ -53,6 +116,16 @@ async fn open_findings_by_severity(
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The counts the overview page shows for the tenant.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/stats/overview",
|
||||
tag = "Workspace",
|
||||
responses(
|
||||
(status = 200, description = "The counts"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn stats_overview(
|
||||
axum::extract::Extension(agent): AgentExt,
|
||||
@@ -81,7 +154,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 +201,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");
|
||||
}
|
||||
}
|
||||
@@ -11,15 +11,21 @@ use super::dto::{AgentExt, ApiResponse};
|
||||
|
||||
// ── DTOs ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
/// An earlier turn of a help chat.
|
||||
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||
pub struct HelpChatMessage {
|
||||
/// `user` or `assistant`.
|
||||
pub role: String,
|
||||
/// What was said.
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
/// The body of [`help_chat`].
|
||||
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||
pub struct HelpChatRequest {
|
||||
/// The question.
|
||||
pub message: String,
|
||||
/// The earlier turns, oldest first.
|
||||
#[serde(default)]
|
||||
pub history: Vec<HelpChatMessage>,
|
||||
}
|
||||
@@ -170,8 +176,17 @@ fn doc_context() -> &'static str {
|
||||
|
||||
// ── Handler ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/// POST /api/v1/help/chat — Answer questions about the compliance-scanner
|
||||
/// using the project documentation as grounding context.
|
||||
/// Ask about Prüfwerk, answered from its published documentation.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/help/chat",
|
||||
tag = "Help",
|
||||
request_body = HelpChatRequest,
|
||||
responses(
|
||||
(status = 200, description = "The answer"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn help_chat(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -0,0 +1,623 @@
|
||||
//! 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, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct InboxQuery {
|
||||
/// Only this target's cards, counts and Erstbewertung.
|
||||
#[serde(default)]
|
||||
pub target: Option<String>,
|
||||
/// The bucket whose cards to list: `today` (default), `this_week`,
|
||||
/// `later` or `likely_false_positive`.
|
||||
#[serde(default)]
|
||||
#[param(value_type = Option<String>, example = "this_week")]
|
||||
pub bucket: Option<Bucket>,
|
||||
/// The most cards to list (default 100, at most 500).
|
||||
#[serde(default)]
|
||||
#[param(minimum = 1, maximum = 500)]
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
/// The open decisions in urgency buckets, most urgent first.
|
||||
///
|
||||
/// The bucket counts, the Erstbewertung, the targets with cards, and the
|
||||
/// cards of one bucket (default `today`).
|
||||
///
|
||||
/// 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`.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/inbox",
|
||||
tag = "Inbox",
|
||||
params(InboxQuery),
|
||||
responses(
|
||||
(status = 200, description = "The buckets and cards"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[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(())
|
||||
}
|
||||
|
||||
/// Decide on every item of a card.
|
||||
///
|
||||
/// `{key, action, reason?, justification?, statement?}`: apply `action`
|
||||
/// 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.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/inbox/decide",
|
||||
tag = "Inbox",
|
||||
request_body(content = Object, description = "`key`, `action`, and the `reason`, `justification` or `statement` the action needs"),
|
||||
responses(
|
||||
(status = 200, description = "Decided, with what each item was before"),
|
||||
(status = 400, description = "A malformed key"),
|
||||
(status = 409, description = "Nothing on the card waits for a decision"),
|
||||
(status = 422, description = "An action the card does not offer, or what it needs is missing"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[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
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Undo a decision on a card.
|
||||
///
|
||||
/// `{key, previous}`: put the items 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.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/inbox/undo",
|
||||
tag = "Inbox",
|
||||
request_body(content = Object, description = "`key`, and `previous` as the decision answered it"),
|
||||
responses(
|
||||
(status = 200, description = "Put back"),
|
||||
(status = 400, description = "A malformed key or id"),
|
||||
(status = 422, description = "An item not of the card, or not open before"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[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" })))
|
||||
}
|
||||
|
||||
/// Put a card off: one week, one month, or until a date.
|
||||
///
|
||||
/// `{key, for}`, `for` as `{"kind": "week"}`, `{"kind": "month"}` or
|
||||
/// `{"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.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/inbox/snooze",
|
||||
tag = "Inbox",
|
||||
request_body(content = Object, description = "`key`, and `for`: a week, a month or a date"),
|
||||
responses(
|
||||
(status = 200, description = "When the card comes back"),
|
||||
(status = 400, description = "A malformed key"),
|
||||
(status = 409, description = "Nothing on the card waits for a decision"),
|
||||
(status = 422, description = "A date that is not in the future"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[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,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Take a card's resubmission back (the undo of a snooze).
|
||||
///
|
||||
/// Nothing to take back is no error.
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
path = "/api/v1/inbox/snooze/{key}",
|
||||
tag = "Inbox",
|
||||
params(("key" = String, Path, description = "The card's key")),
|
||||
responses(
|
||||
(status = 200, description = "The resubmission is gone"),
|
||||
(status = 400, description = "A malformed key"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[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,53 @@
|
||||
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.
|
||||
///
|
||||
/// 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.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/issues",
|
||||
tag = "Tickets",
|
||||
params(IssuesFilter),
|
||||
responses(
|
||||
(status = 200, description = "A page of tickets"),
|
||||
(status = 400, description = "An unknown status"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[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 +60,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"));
|
||||
}
|
||||
}
|
||||
@@ -35,12 +35,16 @@ use crate::license_conclusions::MAX_CONCLUSIONS;
|
||||
pub const MAX_COMPONENTS: usize = 500;
|
||||
|
||||
/// A component a licence is confirmed for, as the SBOM list shows it.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[derive(Debug, Clone, Deserialize, utoipa::ToSchema)]
|
||||
pub struct ComponentRef {
|
||||
/// The package's name.
|
||||
pub name: String,
|
||||
/// Its package manager, such as `npm` or `cargo`.
|
||||
pub package_manager: String,
|
||||
/// Its version; empty with `all_versions`.
|
||||
#[serde(default)]
|
||||
pub version: String,
|
||||
/// Its purl, when known.
|
||||
#[serde(default)]
|
||||
pub purl: Option<String>,
|
||||
/// The licence the scan found, as the list shows it. Read only by a
|
||||
@@ -50,8 +54,9 @@ pub struct ComponentRef {
|
||||
}
|
||||
|
||||
/// The body of [`conclude`].
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||
pub struct ConcludeRequest {
|
||||
/// The components, at most 500.
|
||||
pub components: Vec<ComponentRef>,
|
||||
/// For every version of the packages, not just the listed ones.
|
||||
#[serde(default)]
|
||||
@@ -60,25 +65,38 @@ pub struct ConcludeRequest {
|
||||
/// licence of its own, named in `license_name`.
|
||||
#[serde(default)]
|
||||
pub license: Option<String>,
|
||||
/// The name of a licence of its own.
|
||||
#[serde(default)]
|
||||
pub license_name: Option<String>,
|
||||
/// Used for a licence of its own and where SPDX gives no category.
|
||||
/// Used for a licence of its own and where SPDX gives no category, such
|
||||
/// as `permissive`, `weak_copyleft` or `proprietary`.
|
||||
#[serde(default)]
|
||||
#[schema(value_type = Option<String>, example = "proprietary")]
|
||||
pub category: Option<LicenseCategory>,
|
||||
/// The copyright lines.
|
||||
#[serde(default)]
|
||||
pub copyright: Vec<String>,
|
||||
/// The licence's text.
|
||||
#[serde(default)]
|
||||
pub license_text: Option<String>,
|
||||
/// Where the licence is published.
|
||||
#[serde(default)]
|
||||
pub license_url: Option<String>,
|
||||
/// Where the licence was confirmed, such as a file or a contract.
|
||||
#[serde(default)]
|
||||
pub evidence: Option<String>,
|
||||
/// The contract a licence of its own comes from.
|
||||
#[serde(default)]
|
||||
pub contract_ref: Option<String>,
|
||||
/// When the licence ends.
|
||||
#[serde(default)]
|
||||
#[schema(value_type = Option<String>, format = Date)]
|
||||
pub valid_until: Option<NaiveDate>,
|
||||
/// `shipped` or `build_only`.
|
||||
#[serde(default)]
|
||||
#[schema(value_type = Option<String>, example = "shipped")]
|
||||
pub usage: Option<LicenseUsage>,
|
||||
/// A note.
|
||||
#[serde(default)]
|
||||
pub note: Option<String>,
|
||||
}
|
||||
@@ -196,8 +214,16 @@ fn conclusions_of(
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// GET /api/v1/licenses/conclusions — every licence the workspace
|
||||
/// confirmed, by package name.
|
||||
/// Every licence the workspace confirmed, by package name.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/licenses/conclusions",
|
||||
tag = "Licences",
|
||||
responses(
|
||||
(status = 200, description = "The confirmed licences"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn list_conclusions(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -212,10 +238,22 @@ pub async fn list_conclusions(
|
||||
}))
|
||||
}
|
||||
|
||||
/// PUT /api/v1/licenses/conclusions — confirm a licence for one or more
|
||||
/// components (one version, or every version of their packages). A second
|
||||
/// confirmation of the same package and version replaces the first. 422
|
||||
/// with the reason when the licence or a field is not acceptable.
|
||||
/// Confirm a licence for one or more components.
|
||||
///
|
||||
/// One version, or every version of their packages. A second confirmation
|
||||
/// of the same package and version replaces the first. 422 with the reason
|
||||
/// when the licence or a field is not acceptable.
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/api/v1/licenses/conclusions",
|
||||
tag = "Licences",
|
||||
request_body = ConcludeRequest,
|
||||
responses(
|
||||
(status = 200, description = "The licence was confirmed"),
|
||||
(status = 422, description = "The licence or a field is not acceptable; `error` says why"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn conclude(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -261,15 +299,26 @@ pub async fn conclude(
|
||||
}
|
||||
|
||||
/// The query of [`withdraw`].
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct WithdrawQuery {
|
||||
/// The conclusion's id (package and version, see
|
||||
/// [`license::conclusion_id`]); a query value, as it holds `/` and `@`.
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
/// DELETE /api/v1/licenses/conclusions?id= — withdraw a confirmed licence;
|
||||
/// the component shows the detected one again. 404 when there is none.
|
||||
/// Withdraw a confirmed licence; the component shows the detected one again.
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
path = "/api/v1/licenses/conclusions",
|
||||
tag = "Licences",
|
||||
params(WithdrawQuery),
|
||||
responses(
|
||||
(status = 200, description = "The licence was withdrawn"),
|
||||
(status = 404, description = "No such confirmed licence"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn withdraw(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -292,12 +341,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,11 +355,21 @@ 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"],
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
/// The workspace's licence policy, and whether the requester may change it.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/licenses/policy",
|
||||
tag = "Licences",
|
||||
responses(
|
||||
(status = 200, description = "The policy"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn get_policy(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -324,6 +383,19 @@ pub async fn get_policy(
|
||||
})))
|
||||
}
|
||||
|
||||
/// Replace the workspace's licence policy.
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/api/v1/licenses/policy",
|
||||
tag = "Licences",
|
||||
request_body(content = Object, description = "The policy: which licences are allowed, need a review or are forbidden"),
|
||||
responses(
|
||||
(status = 200, description = "The policy was saved"),
|
||||
(status = 403, description = "The role may not decide on licences (LEGAL, IT_ADMIN or OWNER)"),
|
||||
(status = 422, description = "The policy is not acceptable; `error` says why"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn put_policy(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -437,9 +509,11 @@ fn decidable(entry: &SbomEntry) -> bool {
|
||||
.is_some_and(|l| spdx_license::is_spdx_expression(&spdx_license::normalise(l)))
|
||||
}
|
||||
|
||||
/// The query of [`check`] and [`notices`].
|
||||
#[derive(Debug, Deserialize)]
|
||||
/// The query of [`check`].
|
||||
#[derive(Debug, Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct CheckQuery {
|
||||
/// Only one target's components; every target's without.
|
||||
#[serde(default)]
|
||||
pub repo_id: Option<String>,
|
||||
}
|
||||
@@ -447,6 +521,20 @@ pub struct CheckQuery {
|
||||
/// The most open components one check lists.
|
||||
pub const MAX_CHECK_ITEMS: usize = 2_000;
|
||||
|
||||
/// Judge the components against the licence policy.
|
||||
///
|
||||
/// The counts per verdict, and the components that are forbidden, need a
|
||||
/// review or expire soon, at most 2 000.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/licenses/check",
|
||||
tag = "Licences",
|
||||
params(CheckQuery),
|
||||
responses(
|
||||
(status = 200, description = "The verdicts"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn check(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -522,13 +610,17 @@ pub async fn check(
|
||||
}
|
||||
|
||||
/// The body of [`review`].
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||
pub struct ReviewRequest {
|
||||
/// The components.
|
||||
pub components: Vec<ComponentRef>,
|
||||
/// For every version of the packages, not just the listed ones.
|
||||
#[serde(default)]
|
||||
pub all_versions: bool,
|
||||
/// `approved` or `rejected`.
|
||||
#[schema(value_type = String, example = "approved")]
|
||||
pub decision: ReviewDecision,
|
||||
/// Why.
|
||||
#[serde(default)]
|
||||
pub note: Option<String>,
|
||||
}
|
||||
@@ -639,6 +731,19 @@ fn reviewed(
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Decide in a legal review whether the components' licences may be used.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/licenses/review",
|
||||
tag = "Licences",
|
||||
request_body = ReviewRequest,
|
||||
responses(
|
||||
(status = 200, description = "The review was saved"),
|
||||
(status = 403, description = "The role may not decide on licences (LEGAL, IT_ADMIN or OWNER)"),
|
||||
(status = 422, description = "A component without a licence to review; `error` says why"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn review(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -687,6 +792,19 @@ pub async fn review(
|
||||
})))
|
||||
}
|
||||
|
||||
/// Withdraw a legal review.
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
path = "/api/v1/licenses/review",
|
||||
tag = "Licences",
|
||||
params(WithdrawQuery),
|
||||
responses(
|
||||
(status = 200, description = "The review was withdrawn"),
|
||||
(status = 403, description = "The role may not decide on licences (LEGAL, IT_ADMIN or OWNER)"),
|
||||
(status = 404, description = "No such review"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn withdraw_review(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -715,16 +833,31 @@ pub async fn withdraw_review(
|
||||
}
|
||||
|
||||
/// The query of [`notices`].
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct NoticesQuery {
|
||||
/// The target (its id).
|
||||
pub repo_id: String,
|
||||
/// `text` (default) or `markdown`.
|
||||
#[serde(default)]
|
||||
#[param(value_type = Option<String>, example = "markdown")]
|
||||
pub format: NoticeFormat,
|
||||
/// Also list components only used to build.
|
||||
#[serde(default)]
|
||||
pub build_only: bool,
|
||||
}
|
||||
|
||||
/// A target's third-party notices to ship with the product.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/sbom/notices",
|
||||
tag = "Licences",
|
||||
params(NoticesQuery),
|
||||
responses(
|
||||
(status = 200, description = "The notices file"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn notices(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -912,6 +1045,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])));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,527 @@
|
||||
//! A machine (#1026): a project of kind `product` in the registry, made of
|
||||
//! the targets assigned to it, in-house ones and components bought in from
|
||||
//! suppliers (#1025). Its documents cover all of them.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use axum::extract::{Extension, Path, Query};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::Json;
|
||||
use chrono::{DateTime, Utc};
|
||||
use futures_util::StreamExt;
|
||||
use mongodb::bson::{doc, oid::ObjectId};
|
||||
use serde::Serialize;
|
||||
|
||||
use compliance_core::cve_groups::{self, CveGroup, SeverityCounts};
|
||||
use compliance_core::models::{
|
||||
CveAlert, OnboardedTarget, ProjectKind, SbomEntry, SupplierComponent, TargetType,
|
||||
};
|
||||
use compliance_core::sbom_docs::{self, MachinePart};
|
||||
use compliance_core::scan_changes::ScanChange;
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use super::dto::{tenant_db, AgentExt};
|
||||
use super::{
|
||||
collect_cursor_async, projects::tenant_projects, sbom::MAX_EXPORT_COMPONENTS, ApiResponse,
|
||||
};
|
||||
use crate::agent::ComplianceAgent;
|
||||
use crate::database::Database;
|
||||
use crate::pipeline::csaf_feed::{supplier_key, MongoAdvisoryStore, SupplierProviderStatus};
|
||||
use crate::pipeline::sbom::supplied::SUPPLIER_PRODUCT_MANAGER;
|
||||
|
||||
/// A machine as its endpoints read it: its name, its parts (its targets that
|
||||
/// are not archived, by name) and their ids, in the same order.
|
||||
struct Machine {
|
||||
name: String,
|
||||
targets: Vec<OnboardedTarget>,
|
||||
ids: Vec<String>,
|
||||
}
|
||||
|
||||
/// Machine `id` of the tenant, and the tenant's database.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// As [`machine_name`]; 500 when the targets cannot be read.
|
||||
async fn machine(
|
||||
agent: &ComplianceAgent,
|
||||
tenant: &TenantCtx,
|
||||
id: &str,
|
||||
) -> Result<(Machine, Database), StatusCode> {
|
||||
let name = machine_name(agent, tenant, id).await?;
|
||||
let db = tenant_db(agent, tenant).await?;
|
||||
let targets: Vec<OnboardedTarget> = collect_cursor_async(
|
||||
db.onboarded_targets()
|
||||
.find(doc! { "project_ids": id, "archived_at": null })
|
||||
.sort(doc! { "name": 1 })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
|
||||
)
|
||||
.await;
|
||||
let ids = targets
|
||||
.iter()
|
||||
.filter_map(|t| t.id.map(|o: ObjectId| o.to_hex()))
|
||||
.collect();
|
||||
Ok((Machine { name, targets, ids }, db))
|
||||
}
|
||||
|
||||
/// The open CVE alerts of the targets `ids`.
|
||||
pub(super) async fn open_alerts(
|
||||
db: &Database,
|
||||
ids: &[String],
|
||||
) -> Result<Vec<CveAlert>, StatusCode> {
|
||||
let alerts: Vec<CveAlert> = collect_cursor_async(
|
||||
db.cve_alerts()
|
||||
.find(doc! { "repo_id": { "$in": ids }, "resolved_at": null })
|
||||
.projection(doc! { "llm_impact_summary": 0 })
|
||||
.sort(doc! { "cve_id": 1 })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
|
||||
)
|
||||
.await;
|
||||
Ok(alerts.into_iter().filter(cve_groups::is_open).collect())
|
||||
}
|
||||
|
||||
/// The name of machine `id`: a product project of the tenant's.
|
||||
///
|
||||
/// Without a registry (development) no project can be looked up, and the
|
||||
/// machine is named by its id.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 404 when the tenant has no such project, 422 when it is a topic rather
|
||||
/// than a product, 503 when the registry cannot be asked.
|
||||
async fn machine_name(
|
||||
agent: &ComplianceAgent,
|
||||
tenant: &TenantCtx,
|
||||
id: &str,
|
||||
) -> Result<String, StatusCode> {
|
||||
let projects = tenant_projects(agent, &tenant.0.tenant_id).await?;
|
||||
match projects.into_iter().find(|p| p.id == id) {
|
||||
Some(p) if p.kind == ProjectKind::Product => Ok(p.name),
|
||||
Some(_) => Err(StatusCode::UNPROCESSABLE_ENTITY),
|
||||
None if agent.registry.is_none() => Ok(id.to_string()),
|
||||
None => Err(StatusCode::NOT_FOUND),
|
||||
}
|
||||
}
|
||||
|
||||
/// The CycloneDX type of a part of target type `kind`: device software is
|
||||
/// firmware, a PLC program and other software an application.
|
||||
fn part_kind(kind: TargetType) -> &'static str {
|
||||
match kind {
|
||||
TargetType::FirmwareBareMetal
|
||||
| TargetType::FirmwareRtos
|
||||
| TargetType::EmbeddedLinuxYocto => "firmware",
|
||||
TargetType::PlcSps
|
||||
| TargetType::WebApp
|
||||
| TargetType::BackendService
|
||||
| TargetType::DesktopApp
|
||||
| TargetType::AndroidApp
|
||||
| TargetType::IosApp => "application",
|
||||
}
|
||||
}
|
||||
|
||||
/// A machine's SBOM as a CycloneDX 1.6 document to download.
|
||||
///
|
||||
/// The machine is a product project; its parts are its targets that are not
|
||||
/// archived, each with its supplier (the workspace for one made in-house)
|
||||
/// and its components beneath it. A component bought in is named by its
|
||||
/// supplier's product and version. Never truncated: a machine with more than
|
||||
/// 100 000 components is refused.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/projects/{id}/sbom",
|
||||
tag = "SBOM",
|
||||
params(("id" = String, Path, description = "The project's id")),
|
||||
responses(
|
||||
(status = 200, description = "The machine's CycloneDX SBOM"),
|
||||
(status = 404, description = "No such project"),
|
||||
(status = 413, description = "Too many components to export"),
|
||||
(status = 422, description = "The project is a topic, not a product, or has no targets"),
|
||||
(status = 503, description = "The registry cannot be asked"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(project_id = %id))]
|
||||
pub async fn export_machine_sbom(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<impl IntoResponse, StatusCode> {
|
||||
let (Machine { name, targets, ids }, db) = machine(&agent, &tenant, &id).await?;
|
||||
// A machine without parts would read as one without components.
|
||||
if targets.is_empty() {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
// The supplier's product is the part itself, not one of its components.
|
||||
let of_parts = doc! {
|
||||
"repo_id": { "$in": &ids },
|
||||
"package_manager": { "$ne": SUPPLIER_PRODUCT_MANAGER },
|
||||
};
|
||||
let components = db
|
||||
.sbom_entries()
|
||||
.count_documents(of_parts.clone())
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
if components > MAX_EXPORT_COMPONENTS {
|
||||
tracing::warn!(
|
||||
components,
|
||||
"machine SBOM refused: too large to build in memory"
|
||||
);
|
||||
return Err(StatusCode::PAYLOAD_TOO_LARGE);
|
||||
}
|
||||
let mut entries: Vec<SbomEntry> = collect_cursor_async(
|
||||
db.sbom_entries()
|
||||
.find(of_parts)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
|
||||
)
|
||||
.await;
|
||||
crate::license_conclusions::attach(&db, &mut entries).await;
|
||||
|
||||
let workspace = super::vex::author(&tenant);
|
||||
let parts: Vec<MachinePart<'_>> = targets
|
||||
.iter()
|
||||
.zip(&ids)
|
||||
.map(|(t, id)| {
|
||||
let supplier = t.supplier.as_ref();
|
||||
MachinePart {
|
||||
id,
|
||||
name: &t.name,
|
||||
kind: part_kind(t.target_type),
|
||||
supplier: supplier.map_or(workspace.as_str(), |s| s.name.as_str()),
|
||||
version: supplier.and_then(|s| s.version.as_deref()),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let body = sbom_docs::machine_cyclonedx(&name, &id, &parts, &entries);
|
||||
super::vex::download(&body, &format!("sbom-machine-{id}-cyclonedx.json"))
|
||||
}
|
||||
|
||||
/// One part of a machine in its overview.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct PartOverview {
|
||||
/// The target's id.
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub target_type: TargetType,
|
||||
/// Its supplier, for a component bought in; none for one made in-house.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub supplier: Option<SupplierComponent>,
|
||||
/// Its open CVEs per severity, a CVE counted once per component.
|
||||
pub open: SeverityCounts,
|
||||
/// When its last scan ended (or started, while it runs); none before
|
||||
/// the first.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub last_scan_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
/// The advisories of a machine's suppliers, as read for the workspace.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct MachineAdvisories {
|
||||
/// The advisories kept, over all its suppliers' providers.
|
||||
pub advisories: u64,
|
||||
/// The suppliers' providers, each once.
|
||||
pub providers: usize,
|
||||
/// When one of them was last read; none before the first refresh.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub checked_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
/// A machine at a glance: its parts and what is open across them.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct MachineOverview {
|
||||
pub name: String,
|
||||
/// Its parts, by name.
|
||||
pub parts: Vec<PartOverview>,
|
||||
/// Its open CVEs per severity: its parts' together, as each part
|
||||
/// decides on its own.
|
||||
pub open: SeverityCounts,
|
||||
/// The open alerts nobody has stated anything on yet.
|
||||
pub undecided: usize,
|
||||
/// Of those, the ones the supplier states something on.
|
||||
pub undecided_with_supplier: usize,
|
||||
/// Its components, each once, however many parts contain it.
|
||||
pub components: u64,
|
||||
/// Of those, the ones more than one part contains.
|
||||
pub shared_components: u64,
|
||||
/// Its suppliers' advisories; none when no part names a CSAF provider.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub advisories: Option<MachineAdvisories>,
|
||||
}
|
||||
|
||||
/// How many components the parts `ids` contain, each once, and how many of
|
||||
/// them more than one part contains, counted by the database. A component
|
||||
/// is known by its purl, else by its package manager, name and version, as
|
||||
/// the SBOM documents name it; the supplier's product is the part itself.
|
||||
async fn component_counts(db: &Database, ids: &[String]) -> Result<(u64, u64), StatusCode> {
|
||||
let pipeline = vec![
|
||||
doc! { "$match": {
|
||||
"repo_id": { "$in": ids },
|
||||
"package_manager": { "$ne": SUPPLIER_PRODUCT_MANAGER },
|
||||
} },
|
||||
doc! { "$group": {
|
||||
"_id": { "$ifNull": [
|
||||
"$purl",
|
||||
{ "$concat": ["$package_manager", ":", "$name", "@", "$version"] },
|
||||
] },
|
||||
"parts": { "$addToSet": "$repo_id" },
|
||||
} },
|
||||
doc! { "$group": {
|
||||
"_id": null,
|
||||
"components": { "$sum": 1 },
|
||||
"shared": { "$sum": { "$cond": [{ "$gt": [{ "$size": "$parts" }, 1] }, 1, 0] } },
|
||||
} },
|
||||
];
|
||||
let mut cursor = db
|
||||
.sbom_entries()
|
||||
.aggregate(pipeline)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let Some(row) = cursor.next().await else {
|
||||
return Ok((0, 0));
|
||||
};
|
||||
let row = row.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let count = |key: &str| {
|
||||
row.get_i32(key)
|
||||
.map(i64::from)
|
||||
.or_else(|_| row.get_i64(key))
|
||||
.map_or(0, |n| u64::try_from(n).unwrap_or(0))
|
||||
};
|
||||
Ok((count("components"), count("shared")))
|
||||
}
|
||||
|
||||
/// The advisories of the suppliers `targets` name, read for the workspace.
|
||||
async fn machine_advisories(
|
||||
db: &Database,
|
||||
targets: &[OnboardedTarget],
|
||||
) -> Result<Option<MachineAdvisories>, StatusCode> {
|
||||
let mut keys: Vec<String> = targets
|
||||
.iter()
|
||||
.filter_map(|t| t.supplier.as_ref()?.csaf_provider.as_deref())
|
||||
.map(supplier_key)
|
||||
.collect();
|
||||
keys.sort_unstable();
|
||||
keys.dedup();
|
||||
if keys.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let advisories = MongoAdvisoryStore::supplier(db.inner())
|
||||
.collection()
|
||||
.count_documents(doc! { "provider": { "$in": &keys } })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let checked_at = db
|
||||
.inner()
|
||||
.collection::<SupplierProviderStatus>(SupplierProviderStatus::COLLECTION)
|
||||
.find_one(doc! { "_id": { "$in": &keys } })
|
||||
.sort(doc! { "checked_at": -1 })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.map(|s| s.checked_at.to_chrono());
|
||||
Ok(Some(MachineAdvisories {
|
||||
advisories,
|
||||
providers: keys.len(),
|
||||
checked_at,
|
||||
}))
|
||||
}
|
||||
|
||||
/// The open CVEs per severity of `alerts`, a CVE counted once per component.
|
||||
pub(super) fn open_counts<'a>(alerts: impl IntoIterator<Item = &'a CveAlert>) -> SeverityCounts {
|
||||
let alerts: Vec<CveAlert> = alerts.into_iter().cloned().collect();
|
||||
cve_groups::group_open_alerts(&alerts)
|
||||
.iter()
|
||||
.fold(SeverityCounts::default(), |sum, g| sum.plus(g.counts))
|
||||
}
|
||||
|
||||
/// Whether nobody has stated anything on `alert` yet: no statement of a
|
||||
/// person's.
|
||||
fn undecided(alert: &CveAlert) -> bool {
|
||||
alert.vex.as_ref().is_none_or(|v| v.by_scan)
|
||||
}
|
||||
|
||||
/// A machine at a glance: its parts and what is open across them.
|
||||
///
|
||||
/// Each part with its supplier, open CVEs and last scan; across them the
|
||||
/// open and undecided CVEs, the components and the suppliers' advisories.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/projects/{id}/overview",
|
||||
tag = "Targets",
|
||||
params(("id" = String, Path, description = "The project's id")),
|
||||
responses(
|
||||
(status = 200, description = "The machine at a glance (`data`)"),
|
||||
(status = 404, description = "No such project"),
|
||||
(status = 422, description = "The project is a topic, not a product"),
|
||||
(status = 503, description = "The registry cannot be asked"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(project_id = %id))]
|
||||
pub async fn machine_overview(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<Json<ApiResponse<MachineOverview>>, StatusCode> {
|
||||
let (machine, db) = machine(&agent, &tenant, &id).await?;
|
||||
let alerts = open_alerts(&db, &machine.ids).await?;
|
||||
let (components, shared_components) = component_counts(&db, &machine.ids).await?;
|
||||
let advisories = machine_advisories(&db, &machine.targets).await?;
|
||||
let mut last_scans =
|
||||
super::onboarding::latest_scan_runs(&db.scan_runs(), machine.ids.clone(), false).await;
|
||||
let mut by_part: HashMap<&str, Vec<&CveAlert>> = HashMap::new();
|
||||
for alert in &alerts {
|
||||
by_part
|
||||
.entry(alert.repo_id.as_str())
|
||||
.or_default()
|
||||
.push(alert);
|
||||
}
|
||||
let parts: Vec<PartOverview> = machine
|
||||
.targets
|
||||
.into_iter()
|
||||
.zip(&machine.ids)
|
||||
.map(|(t, id)| PartOverview {
|
||||
open: open_counts(by_part.remove(id.as_str()).unwrap_or_default()),
|
||||
last_scan_at: last_scans
|
||||
.remove(id)
|
||||
.map(|run| run.completed_at.unwrap_or(run.started_at)),
|
||||
id: id.clone(),
|
||||
name: t.name,
|
||||
target_type: t.target_type,
|
||||
supplier: t.supplier,
|
||||
})
|
||||
.collect();
|
||||
let undecided_alerts: Vec<&CveAlert> = alerts.iter().filter(|a| undecided(a)).collect();
|
||||
Ok(Json(ApiResponse {
|
||||
data: MachineOverview {
|
||||
open: parts
|
||||
.iter()
|
||||
.fold(SeverityCounts::default(), |sum, p| sum.plus(p.open)),
|
||||
parts,
|
||||
name: machine.name,
|
||||
undecided: undecided_alerts.len(),
|
||||
undecided_with_supplier: undecided_alerts
|
||||
.iter()
|
||||
.filter(|a| a.supplier_vex.is_some())
|
||||
.count(),
|
||||
components,
|
||||
shared_components,
|
||||
advisories,
|
||||
},
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// A machine's open CVEs: grouped by component across its parts, and the
|
||||
/// alerts themselves, each with its part (`repo_id`).
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct MachineCves {
|
||||
/// The groups, the most severe first; a group's `alert_ids` may belong
|
||||
/// to several parts.
|
||||
pub groups: Vec<CveGroup>,
|
||||
/// The open alerts, by CVE.
|
||||
pub alerts: Vec<CveAlert>,
|
||||
}
|
||||
|
||||
/// A machine's open CVEs, grouped by component across its parts.
|
||||
///
|
||||
/// A component in several parts is one group, with the alerts of every part
|
||||
/// it is in: whether it affects the machine is stated per part, as the code
|
||||
/// may be reached in one and not in another.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/projects/{id}/cves",
|
||||
tag = "CVEs",
|
||||
params(("id" = String, Path, description = "The project's id")),
|
||||
responses(
|
||||
(status = 200, description = "The groups and the open alerts (`data`)"),
|
||||
(status = 404, description = "No such project"),
|
||||
(status = 422, description = "The project is a topic, not a product"),
|
||||
(status = 503, description = "The registry cannot be asked"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(project_id = %id))]
|
||||
pub async fn machine_cves(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<Json<ApiResponse<MachineCves>>, StatusCode> {
|
||||
let (machine, db) = machine(&agent, &tenant, &id).await?;
|
||||
let alerts = open_alerts(&db, &machine.ids).await?;
|
||||
Ok(Json(ApiResponse {
|
||||
data: MachineCves {
|
||||
groups: cve_groups::group_open_alerts(&alerts),
|
||||
alerts,
|
||||
},
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// One scan of one of a machine's parts, with what it changed.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct MachineChange {
|
||||
/// The part (its target's id).
|
||||
pub part: String,
|
||||
#[serde(flatten)]
|
||||
pub change: ScanChange,
|
||||
}
|
||||
|
||||
/// What changed in a machine: the last scans of its parts, the newest first.
|
||||
///
|
||||
/// Each scan comes with the CVEs it found new and gone and the components
|
||||
/// it added, updated and removed, as a target's own history (`limit`, 20
|
||||
/// when not given, at most 50, over all parts). A supplier's new version
|
||||
/// shows as its product updated (`from` → `to`) in a part bought in.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/projects/{id}/scan-changes",
|
||||
tag = "CVEs",
|
||||
params(
|
||||
("id" = String, Path, description = "The project's id"),
|
||||
("limit" = Option<usize>, Query, description = "The scans to show, 1 to 50"),
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "The parts' scans, each with its part (`data`)"),
|
||||
(status = 404, description = "No such project"),
|
||||
(status = 422, description = "The project is a topic, not a product"),
|
||||
(status = 503, description = "The registry cannot be asked"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(project_id = %id))]
|
||||
pub async fn machine_scan_changes(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
Query(query): Query<super::scan_changes::ChangesQuery>,
|
||||
) -> Result<Json<ApiResponse<Vec<MachineChange>>>, StatusCode> {
|
||||
let (machine, db) = machine(&agent, &tenant, &id).await?;
|
||||
let per_part = futures_util::future::try_join_all(
|
||||
machine
|
||||
.ids
|
||||
.iter()
|
||||
.map(|part| super::scan_changes::target_changes(&db, part, query.limit)),
|
||||
)
|
||||
.await?;
|
||||
let mut data: Vec<MachineChange> = machine
|
||||
.ids
|
||||
.iter()
|
||||
.zip(per_part)
|
||||
.flat_map(|(part, changes)| {
|
||||
changes.into_iter().map(|change| MachineChange {
|
||||
part: part.clone(),
|
||||
change,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
data.sort_by_key(|c| std::cmp::Reverse(c.change.started_at));
|
||||
data.truncate(query.limit);
|
||||
Ok(Json(ApiResponse {
|
||||
total: Some(data.len() as u64),
|
||||
data,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
@@ -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;
|
||||
@@ -47,9 +46,11 @@ impl From<ManualKind> for ScanType {
|
||||
}
|
||||
}
|
||||
|
||||
/// `POST /api/v1/targets/{id}/findings`.
|
||||
#[derive(Debug, Deserialize)]
|
||||
/// The body of [`create_finding`]: a finding from a manual test.
|
||||
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||
pub struct CreateFindingRequest {
|
||||
/// `dast` or `pentest`: the manual test the finding comes from.
|
||||
#[schema(value_type = String, example = "pentest")]
|
||||
pub kind: ManualKind,
|
||||
/// The tool used, if any; `manual` otherwise.
|
||||
#[serde(default)]
|
||||
@@ -67,9 +68,14 @@ pub enum ImportFormat {
|
||||
}
|
||||
|
||||
/// `?format=&kind=` of an import.
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct ImportParams {
|
||||
/// `sarif` or `zap`.
|
||||
#[param(value_type = String, example = "sarif")]
|
||||
pub format: ImportFormat,
|
||||
/// `dast` or `pentest`.
|
||||
#[param(value_type = String, example = "dast")]
|
||||
pub kind: ManualKind,
|
||||
}
|
||||
|
||||
@@ -84,9 +90,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)
|
||||
@@ -124,8 +131,26 @@ async fn insert_new(db: &Database, finding: &mut Finding) -> Result<bool, Status
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets/{id}/findings — add one finding by hand. 409 when the
|
||||
/// same finding (tool, title, location) is already on the target.
|
||||
/// Add a finding from a manual DAST run or penetration test.
|
||||
///
|
||||
/// 409 when the same finding (tool, title, location) is already on the
|
||||
/// target. Only an organisation's administrator (IT_ADMIN, OWNER).
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/targets/{id}/findings",
|
||||
tag = "Findings",
|
||||
params(("id" = String, Path, description = "The target's id")),
|
||||
request_body = CreateFindingRequest,
|
||||
responses(
|
||||
(status = 201, description = "The finding"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 403, description = "Only an administrator adds findings by hand"),
|
||||
(status = 404, description = "No such target"),
|
||||
(status = 409, description = "The same finding is already on the target"),
|
||||
(status = 422, description = "A malformed finding"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn create_finding(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -164,9 +189,26 @@ pub async fn create_finding(
|
||||
))
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets/{id}/findings/import?format=sarif|zap&kind=dast|pentest
|
||||
/// — the body is the report itself. Findings already on the target are
|
||||
/// skipped, so importing a report again adds nothing.
|
||||
/// Import the findings of a SARIF or ZAP report; the body is the report.
|
||||
///
|
||||
/// Findings already on the target are skipped, so importing a report again
|
||||
/// adds nothing. Only an organisation's administrator (IT_ADMIN, OWNER).
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/targets/{id}/findings/import",
|
||||
tag = "Findings",
|
||||
params(("id" = String, Path, description = "The target's id"), ImportParams),
|
||||
request_body(content = Object, description = "The SARIF or ZAP JSON report"),
|
||||
responses(
|
||||
(status = 200, description = "What the import did"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 403, description = "Only an administrator imports findings"),
|
||||
(status = 404, description = "No such target"),
|
||||
(status = 413, description = "The report is larger than 20 MiB"),
|
||||
(status = 422, description = "The report cannot be read"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn import_findings(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -221,7 +263,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 +283,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)
|
||||
|
||||
@@ -49,7 +49,9 @@ const ALL_TOOLS: [&str; 7] = [
|
||||
"dast_scan_summary",
|
||||
];
|
||||
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
/// The query of [`list_mcp_servers`].
|
||||
#[derive(Debug, serde::Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct ListQuery {
|
||||
/// Where the deployment's MCP server answers (the dashboard's
|
||||
/// `MCP_ENDPOINT_URL`), for the default cards of a tenant that has none.
|
||||
@@ -57,18 +59,26 @@ pub struct ListQuery {
|
||||
pub default_endpoint: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
/// The body of [`create_mcp_server`].
|
||||
#[derive(Debug, serde::Deserialize, utoipa::ToSchema)]
|
||||
pub struct CreateRequest {
|
||||
/// The card's name.
|
||||
pub name: String,
|
||||
/// Where the MCP server answers.
|
||||
pub endpoint_url: String,
|
||||
/// The transport, such as `streamable-http`.
|
||||
#[serde(default)]
|
||||
pub transport: String,
|
||||
/// The port, when not in the URL.
|
||||
#[serde(default)]
|
||||
pub port: Option<u16>,
|
||||
/// A description.
|
||||
#[serde(default)]
|
||||
pub description: Option<String>,
|
||||
/// The MongoDB URI the server reads, for a server of its own.
|
||||
#[serde(default)]
|
||||
pub mongodb_uri: Option<String>,
|
||||
/// The MongoDB database the server reads.
|
||||
#[serde(default)]
|
||||
pub mongodb_database: Option<String>,
|
||||
}
|
||||
@@ -126,8 +136,19 @@ async fn seed_defaults(db: &Database, endpoint: &str) -> Result<(), mongodb::err
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `GET /api/v1/mcp-servers` — the tenant's cards, newest first; the access
|
||||
/// tokens only for roles that may change things.
|
||||
/// The tenant's MCP server cards, newest first.
|
||||
///
|
||||
/// The access tokens only for roles that may change things.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/mcp-servers",
|
||||
tag = "MCP",
|
||||
params(ListQuery),
|
||||
responses(
|
||||
(status = 200, description = "The cards"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn list_mcp_servers(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -155,7 +176,18 @@ pub async fn list_mcp_servers(
|
||||
Ok(Json(serde_json::json!({ "data": servers })))
|
||||
}
|
||||
|
||||
/// `POST /api/v1/mcp-servers` — add a card to the tenant.
|
||||
/// Add an MCP server card.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/mcp-servers",
|
||||
tag = "MCP",
|
||||
request_body = CreateRequest,
|
||||
responses(
|
||||
(status = 200, description = "The new card"),
|
||||
(status = 400, description = "No name or no endpoint URL"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn create_mcp_server(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -194,8 +226,19 @@ pub async fn create_mcp_server(
|
||||
Ok(Json(serde_json::json!({ "id": inserted.inserted_id })))
|
||||
}
|
||||
|
||||
/// `DELETE /api/v1/mcp-servers/{id}` — remove one of the tenant's cards; 404
|
||||
/// for an id the tenant has not.
|
||||
/// Remove an MCP server card.
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
path = "/api/v1/mcp-servers/{id}",
|
||||
tag = "MCP",
|
||||
params(("id" = String, Path, description = "The card's id")),
|
||||
responses(
|
||||
(status = 204, description = "Removed"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 404, description = "No such card"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(server_id = %id))]
|
||||
pub async fn delete_mcp_server(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -215,8 +258,19 @@ pub async fn delete_mcp_server(
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
/// `POST /api/v1/mcp-servers/{id}/token` — give one of the tenant's cards a
|
||||
/// new access token; 404 for an id the tenant has not.
|
||||
/// Give an MCP server card a new access token.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/mcp-servers/{id}/token",
|
||||
tag = "MCP",
|
||||
params(("id" = String, Path, description = "The card's id")),
|
||||
responses(
|
||||
(status = 200, description = "The new token"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 404, description = "No such card"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(server_id = %id))]
|
||||
pub async fn regenerate_mcp_server_token(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -33,8 +33,10 @@ const TOKEN_PREFIX: &str = "mcpt_";
|
||||
/// Combined with `mcpt_` → 48-char tokens.
|
||||
const TOKEN_RAND_BYTES: usize = 32;
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
/// The body of [`create_mcp_token`].
|
||||
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
||||
pub struct CreateMcpTokenRequest {
|
||||
/// What the token is for.
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
@@ -46,7 +48,18 @@ pub struct CreateMcpTokenResponse {
|
||||
pub view: McpTokenView,
|
||||
}
|
||||
|
||||
/// `POST /api/v1/mcp-tokens` — mint a new token for the caller's tenant.
|
||||
/// Mint an MCP token for the tenant; it is shown only in this answer.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/mcp-tokens",
|
||||
tag = "MCP",
|
||||
request_body = CreateMcpTokenRequest,
|
||||
responses(
|
||||
(status = 200, description = "The token, once"),
|
||||
(status = 400, description = "No name"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn create_mcp_token(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -85,9 +98,19 @@ pub async fn create_mcp_token(
|
||||
}))
|
||||
}
|
||||
|
||||
/// `GET /api/v1/mcp-tokens` — list tokens for the caller's tenant.
|
||||
/// Hash is never returned; only metadata + the 12-char prefix so the
|
||||
/// user can identify which row is which.
|
||||
/// The tenant's MCP tokens, without the tokens.
|
||||
///
|
||||
/// The hash is never returned; only metadata and the 12-character prefix,
|
||||
/// so the user can tell which row is which.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/mcp-tokens",
|
||||
tag = "MCP",
|
||||
responses(
|
||||
(status = 200, description = "The tokens"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn list_mcp_tokens(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -119,9 +142,22 @@ pub async fn list_mcp_tokens(
|
||||
}))
|
||||
}
|
||||
|
||||
/// `DELETE /api/v1/mcp-tokens/{id}` — revoke (soft delete).
|
||||
/// Revoke an MCP token.
|
||||
///
|
||||
/// Scoped to the caller's tenant: a user can't revoke another tenant's
|
||||
/// token even if they guess its id.
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
path = "/api/v1/mcp-tokens/{id}",
|
||||
tag = "MCP",
|
||||
params(("id" = String, Path, description = "The token's id")),
|
||||
responses(
|
||||
(status = 200, description = "Revoked"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 404, description = "No such token"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(id = %id))]
|
||||
pub async fn revoke_mcp_token(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
//! 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>,
|
||||
}
|
||||
|
||||
/// The tenant's usage this month, with the plan's limits.
|
||||
///
|
||||
/// Prüfungen, Prüftage and extra targets this month (Europe/Berlin).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// `500` when the counters cannot be read.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/metering/usage",
|
||||
tag = "Workspace",
|
||||
responses(
|
||||
(status = 200, description = "The usage"),
|
||||
(status = 500, description = "The counters cannot be read"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
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,28 +1,46 @@
|
||||
pub mod admin;
|
||||
pub mod chat;
|
||||
pub mod connections;
|
||||
pub mod cve_history;
|
||||
pub mod cve_matrix;
|
||||
pub mod dast;
|
||||
mod delivery;
|
||||
pub mod demo_seed;
|
||||
pub mod devices;
|
||||
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 machine;
|
||||
pub mod manual_findings;
|
||||
pub mod mcp_servers;
|
||||
pub mod mcp_tokens;
|
||||
pub mod metering;
|
||||
pub mod notifications;
|
||||
pub mod offers;
|
||||
pub mod onboarding;
|
||||
pub mod oscal;
|
||||
pub mod pentest_handlers;
|
||||
pub mod platform;
|
||||
pub mod projects;
|
||||
pub mod releases;
|
||||
pub use pentest_handlers as pentest;
|
||||
pub mod sbom;
|
||||
pub mod sbom_ecosystems;
|
||||
pub mod scan_changes;
|
||||
pub mod scans;
|
||||
pub mod supplier;
|
||||
pub mod supplier_invites;
|
||||
pub mod supply_chain;
|
||||
pub mod supply_chain_layout;
|
||||
pub mod support;
|
||||
pub mod target_input;
|
||||
pub mod vex;
|
||||
|
||||
@@ -9,7 +9,17 @@ use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use super::dto::{tenant_db, AgentExt, ApiResponse};
|
||||
|
||||
/// GET /api/v1/notifications — List CVE notifications (newest first)
|
||||
/// The tenant's CVE notifications, newest first, a page at a time.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/notifications",
|
||||
tag = "Notifications",
|
||||
params(NotificationFilter),
|
||||
responses(
|
||||
(status = 200, description = "A page of notifications"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn list_notifications(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -85,7 +95,16 @@ pub async fn list_notifications(
|
||||
}))
|
||||
}
|
||||
|
||||
/// GET /api/v1/notifications/count — Count of unread notifications
|
||||
/// The number of unread notifications.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/notifications/count",
|
||||
tag = "Notifications",
|
||||
responses(
|
||||
(status = 200, description = "The count"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn notification_count(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -101,7 +120,19 @@ pub async fn notification_count(
|
||||
Ok(Json(serde_json::json!({ "count": count })))
|
||||
}
|
||||
|
||||
/// PATCH /api/v1/notifications/:id/read — Mark a notification as read
|
||||
/// Mark a notification as read.
|
||||
#[utoipa::path(
|
||||
patch,
|
||||
path = "/api/v1/notifications/{id}/read",
|
||||
tag = "Notifications",
|
||||
params(("id" = String, Path, description = "The notification's id")),
|
||||
responses(
|
||||
(status = 200, description = "Marked as read"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 404, description = "No such notification"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(id = %id))]
|
||||
pub async fn mark_read(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -129,7 +160,19 @@ pub async fn mark_read(
|
||||
Ok(Json(serde_json::json!({ "status": "read" })))
|
||||
}
|
||||
|
||||
/// PATCH /api/v1/notifications/:id/dismiss — Dismiss a notification
|
||||
/// Dismiss a notification.
|
||||
#[utoipa::path(
|
||||
patch,
|
||||
path = "/api/v1/notifications/{id}/dismiss",
|
||||
tag = "Notifications",
|
||||
params(("id" = String, Path, description = "The notification's id")),
|
||||
responses(
|
||||
(status = 200, description = "Dismissed"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 404, description = "No such notification"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(id = %id))]
|
||||
pub async fn dismiss_notification(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -154,7 +197,16 @@ pub async fn dismiss_notification(
|
||||
Ok(Json(serde_json::json!({ "status": "dismissed" })))
|
||||
}
|
||||
|
||||
/// POST /api/v1/notifications/read-all — Mark all new notifications as read
|
||||
/// Mark every new notification as read.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/notifications/read-all",
|
||||
tag = "Notifications",
|
||||
responses(
|
||||
(status = 200, description = "Marked as read"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn mark_all_read(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -178,11 +230,20 @@ pub async fn mark_all_read(
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
/// Which notifications a list shows.
|
||||
#[derive(Debug, Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct NotificationFilter {
|
||||
/// `new`, `read`, `dismissed` or `all`; new and read without it.
|
||||
pub status: Option<String>,
|
||||
/// Only one severity.
|
||||
pub severity: Option<String>,
|
||||
/// Only one target's notifications (its id).
|
||||
pub repo_id: Option<String>,
|
||||
/// The page, from 1 (default 1, at most 100 000).
|
||||
#[param(minimum = 1, maximum = 100_000)]
|
||||
pub page: Option<u64>,
|
||||
/// Entries per page (default 50, at most 200).
|
||||
#[param(minimum = 1, maximum = 200)]
|
||||
pub limit: Option<i64>,
|
||||
}
|
||||
@@ -0,0 +1,702 @@
|
||||
//! SBOM releases, the customer's side (#1028): what a connected supplier
|
||||
//! workspace offers, and the customer's answer.
|
||||
//!
|
||||
//! A supplier's release (`super::releases`) writes an offer into the
|
||||
//! customer's database, after the registry confirmed the connection joins the
|
||||
//! two. The customer accepts it into a supplier component (a new one, or one
|
||||
//! it has) or declines it; the answer is written back to the supplier's
|
||||
//! release. Accepting creates a target, which counts like any other, so it
|
||||
//! is the customer's decision and never automatic.
|
||||
|
||||
use axum::extract::{Extension, Path};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::Json;
|
||||
use chrono::{DateTime, Utc};
|
||||
use futures_util::TryStreamExt;
|
||||
use mongodb::bson::{doc, oid::ObjectId, DateTime as BsonDateTime};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use compliance_core::models::{OnboardedTarget, SupplierComponent, TargetType};
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use super::dto::{tenant_db, AgentExt};
|
||||
use super::releases::SbomRelease;
|
||||
use super::ApiResponse;
|
||||
use crate::agent::ComplianceAgent;
|
||||
use crate::database::Database;
|
||||
|
||||
/// Where an offer stands.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum OfferState {
|
||||
/// Waiting for the customer's answer.
|
||||
Offered,
|
||||
/// Accepted into a supplier component.
|
||||
Accepted,
|
||||
/// Declined by the customer.
|
||||
Declined,
|
||||
/// Ended by the supplier, or the connection ended.
|
||||
Ended,
|
||||
}
|
||||
|
||||
/// A supplier's offer, as stored in the customer's database.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct SbomOffer {
|
||||
#[serde(rename = "_id")]
|
||||
pub id: ObjectId,
|
||||
/// The supplier's release it answers.
|
||||
pub release_id: String,
|
||||
/// The connection it came over.
|
||||
pub connection_id: String,
|
||||
/// The supplier's tenant: for answering and delivering inside Prüfwerk,
|
||||
/// never shown.
|
||||
pub supplier_tenant_id: String,
|
||||
/// The supplier workspace's display name.
|
||||
pub supplier_name: String,
|
||||
/// The supplier's name for the product (its target's name).
|
||||
pub product_name: String,
|
||||
/// The product's type, for the component it becomes.
|
||||
pub product_type: TargetType,
|
||||
pub state: OfferState,
|
||||
/// The component it delivers into, once accepted.
|
||||
#[serde(default)]
|
||||
pub target_id: Option<String>,
|
||||
pub offered_at: BsonDateTime,
|
||||
#[serde(default)]
|
||||
pub decided_at: Option<BsonDateTime>,
|
||||
#[serde(default)]
|
||||
pub decided_by: Option<String>,
|
||||
#[serde(default)]
|
||||
pub ended_at: Option<BsonDateTime>,
|
||||
/// The content hash of the version last delivered, so the same version
|
||||
/// is never delivered twice.
|
||||
#[serde(default)]
|
||||
pub delivered_hash: Option<String>,
|
||||
/// The label of the version last delivered.
|
||||
#[serde(default)]
|
||||
pub delivered_label: Option<String>,
|
||||
#[serde(default)]
|
||||
pub delivered_at: Option<BsonDateTime>,
|
||||
/// While the offer is open: the supplier's latest published version,
|
||||
/// what accepting delivers at once, and how many components it lists.
|
||||
#[serde(default)]
|
||||
pub offered_label: Option<String>,
|
||||
#[serde(default)]
|
||||
pub offered_components: Option<i64>,
|
||||
}
|
||||
|
||||
impl SbomOffer {
|
||||
/// The collection, in the customer's own database.
|
||||
pub const COLLECTION: &'static str = "sbom_offers";
|
||||
}
|
||||
|
||||
/// An offer as the customer reads it: nothing of the supplier's but its
|
||||
/// name, the product's, and the version it offers.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct OfferView {
|
||||
pub id: String,
|
||||
pub supplier_name: String,
|
||||
pub product_name: String,
|
||||
pub product_type: TargetType,
|
||||
pub state: OfferState,
|
||||
pub target_id: Option<String>,
|
||||
pub offered_at: DateTime<Utc>,
|
||||
pub decided_at: Option<DateTime<Utc>>,
|
||||
pub ended_at: Option<DateTime<Utc>>,
|
||||
/// The version last delivered into the component, and when.
|
||||
pub delivered_label: Option<String>,
|
||||
pub delivered_at: Option<DateTime<Utc>>,
|
||||
/// While it is open: the version accepting delivers at once, and how
|
||||
/// many components it lists; `None` before the supplier published one.
|
||||
pub offered_label: Option<String>,
|
||||
pub offered_components: Option<i64>,
|
||||
}
|
||||
|
||||
impl From<SbomOffer> for OfferView {
|
||||
fn from(o: SbomOffer) -> Self {
|
||||
Self {
|
||||
id: o.id.to_hex(),
|
||||
supplier_name: o.supplier_name,
|
||||
product_name: o.product_name,
|
||||
product_type: o.product_type,
|
||||
state: o.state,
|
||||
target_id: o.target_id,
|
||||
offered_at: o.offered_at.to_chrono(),
|
||||
decided_at: o.decided_at.map(BsonDateTime::to_chrono),
|
||||
ended_at: o.ended_at.map(BsonDateTime::to_chrono),
|
||||
delivered_label: o.delivered_label,
|
||||
delivered_at: o.delivered_at.map(BsonDateTime::to_chrono),
|
||||
offered_label: o.offered_label,
|
||||
offered_components: o.offered_components,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The body of an acceptance: into an existing supplier component, or a new
|
||||
/// one with its name and projects.
|
||||
#[derive(Debug, Default, Deserialize, utoipa::ToSchema)]
|
||||
pub struct AcceptOffer {
|
||||
/// An existing supplier component to deliver into.
|
||||
#[serde(default)]
|
||||
pub target_id: Option<String>,
|
||||
/// The new component's name; the product's name when left out.
|
||||
#[serde(default)]
|
||||
pub name: Option<String>,
|
||||
/// The new component's projects.
|
||||
#[serde(default)]
|
||||
pub project_ids: Vec<String>,
|
||||
}
|
||||
|
||||
fn offers(db: &Database) -> mongodb::Collection<SbomOffer> {
|
||||
db.inner().collection(SbomOffer::COLLECTION)
|
||||
}
|
||||
|
||||
fn internal<E: std::fmt::Display>(e: E) -> StatusCode {
|
||||
tracing::error!("offer endpoint failed: {e}");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
|
||||
/// A refusal with its code, as `{"error": …}`.
|
||||
fn refused(status: StatusCode, code: &str) -> axum::response::Response {
|
||||
(status, Json(serde_json::json!({ "error": code }))).into_response()
|
||||
}
|
||||
|
||||
/// Write `offer` into `customer`'s database. The supplier's release calls it
|
||||
/// once the registry has confirmed the connection joins the two.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 500 when it cannot be written.
|
||||
pub(super) async fn offer(
|
||||
agent: &ComplianceAgent,
|
||||
customer: &str,
|
||||
offer: &SbomOffer,
|
||||
) -> Result<(), StatusCode> {
|
||||
let db = agent
|
||||
.db_pool
|
||||
.for_tenant_id(customer)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
offers(&db).insert_one(offer).await.map_err(internal)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Tell `customer`'s open offer of release `release` that `label` (with
|
||||
/// `components` components) is now what accepting delivers. Best-effort:
|
||||
/// the next publication tells it again.
|
||||
pub(super) async fn announce(
|
||||
agent: &ComplianceAgent,
|
||||
customer: &str,
|
||||
release: &str,
|
||||
label: &str,
|
||||
components: i64,
|
||||
) {
|
||||
let db = agent.db_pool.for_existing_tenant_id(customer);
|
||||
let told = offers(&db)
|
||||
.update_one(
|
||||
doc! { "release_id": release, "state": "offered" },
|
||||
doc! { "$set": { "offered_label": label, "offered_components": components } },
|
||||
)
|
||||
.await;
|
||||
if let Err(e) = told {
|
||||
tracing::warn!(release, "new version not announced to the customer: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark the offer of release `release` in `customer`'s database ended: the
|
||||
/// supplier ended the release. Best-effort; a customer that has gone keeps
|
||||
/// nothing to mark.
|
||||
pub(super) async fn end(agent: &ComplianceAgent, customer: &str, release: &str) {
|
||||
let db = agent.db_pool.for_existing_tenant_id(customer);
|
||||
let ended = offers(&db)
|
||||
.update_one(
|
||||
doc! { "release_id": release, "state": { "$in": ["offered", "accepted"] } },
|
||||
doc! { "$set": { "state": "ended", "ended_at": BsonDateTime::now() } },
|
||||
)
|
||||
.await;
|
||||
if let Err(e) = ended {
|
||||
tracing::warn!(release, "ended release not marked at the customer: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Write the customer's answer `state` back to release `release` in the
|
||||
/// supplier's database, for the supplier to see. Best-effort.
|
||||
async fn answer_release(agent: &ComplianceAgent, offer: &SbomOffer, state: OfferState) {
|
||||
let Ok(id) = ObjectId::parse_str(&offer.release_id) else {
|
||||
return;
|
||||
};
|
||||
let db = agent
|
||||
.db_pool
|
||||
.for_existing_tenant_id(&offer.supplier_tenant_id);
|
||||
let answered = db
|
||||
.inner()
|
||||
.collection::<SbomRelease>(SbomRelease::COLLECTION)
|
||||
.update_one(
|
||||
doc! { "_id": id, "connection_id": &offer.connection_id },
|
||||
doc! { "$set": { "answer": mongodb::bson::to_bson(&state).unwrap_or_default() } },
|
||||
)
|
||||
.await;
|
||||
if let Err(e) = answered {
|
||||
tracing::warn!(release = %offer.release_id, "answer not written to the supplier: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `offer` can still be accepted: the connection it came over still
|
||||
/// joins this workspace (`tenant`) and its supplier, and the supplier's
|
||||
/// release still exists and has not ended (a supplier that deleted the
|
||||
/// target, or left Prüfwerk, takes its releases with it).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 503 without a registry or when it cannot be asked.
|
||||
async fn still_open(
|
||||
agent: &ComplianceAgent,
|
||||
tenant: &str,
|
||||
offer: &SbomOffer,
|
||||
) -> Result<bool, StatusCode> {
|
||||
let registry = agent
|
||||
.registry
|
||||
.as_ref()
|
||||
.ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let state = registry
|
||||
.connection(&offer.connection_id)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("connection check unavailable: {e}");
|
||||
StatusCode::SERVICE_UNAVAILABLE
|
||||
})?;
|
||||
if state.is_none_or(|s| s.peer_of(tenant) != Some(offer.supplier_tenant_id.as_str())) {
|
||||
return Ok(false);
|
||||
}
|
||||
let Ok(release) = ObjectId::parse_str(&offer.release_id) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let live = agent
|
||||
.db_pool
|
||||
.for_existing_tenant_id(&offer.supplier_tenant_id)
|
||||
.inner()
|
||||
.collection::<SbomRelease>(SbomRelease::COLLECTION)
|
||||
.count_documents(doc! {
|
||||
"_id": release,
|
||||
"connection_id": &offer.connection_id,
|
||||
"ended_at": null,
|
||||
})
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
Ok(live > 0)
|
||||
}
|
||||
|
||||
/// Whether workspace `peer` may be offered a release: it holds Prüfwerk and
|
||||
/// is neither halted nor archived. An offer is written into its database,
|
||||
/// so a workspace without the product never gets one created. Without a
|
||||
/// registry (development) every workspace may.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 503 when the registry cannot be asked.
|
||||
pub(super) async fn takes_offers(agent: &ComplianceAgent, peer: &str) -> Result<bool, StatusCode> {
|
||||
let Some(registry) = agent.registry.as_ref() else {
|
||||
return Ok(true);
|
||||
};
|
||||
let check = registry
|
||||
.check_entitlement(peer, None, None)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("entitlement check unavailable: {e}");
|
||||
StatusCode::SERVICE_UNAVAILABLE
|
||||
})?;
|
||||
let status = check
|
||||
.status
|
||||
.as_deref()
|
||||
.and_then(compliance_core::TenantStatus::parse);
|
||||
Ok(check.allowed && status.is_none_or(|s| !s.is_halted() && !s.is_archived()))
|
||||
}
|
||||
|
||||
/// Mark `offer` ended in `db`, from whichever state it is in.
|
||||
async fn mark_ended(db: &Database, offer: ObjectId) -> Result<(), StatusCode> {
|
||||
offers(db)
|
||||
.update_one(
|
||||
doc! { "_id": offer, "state": { "$in": ["offered", "accepted"] } },
|
||||
doc! { "$set": { "state": "ended", "ended_at": BsonDateTime::now() } },
|
||||
)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Give back a claim on `offer` that could not be completed: it is open
|
||||
/// again.
|
||||
async fn unclaim(db: &Database, offer: ObjectId) -> Result<(), StatusCode> {
|
||||
offers(db)
|
||||
.update_one(
|
||||
doc! { "_id": offer, "state": "accepted" },
|
||||
doc! {
|
||||
"$set": { "state": "offered" },
|
||||
"$unset": { "target_id": "", "decided_at": "", "decided_by": "" },
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What an accepted offer delivers into.
|
||||
enum Destination {
|
||||
/// A supplier component the workspace has.
|
||||
Existing(OnboardedTarget),
|
||||
/// A new supplier component, not yet stored.
|
||||
New(OnboardedTarget),
|
||||
}
|
||||
|
||||
/// The refusal for an offer that is no longer open: `ended` or `answered`.
|
||||
fn not_open(state: OfferState) -> axum::response::Response {
|
||||
let code = if state == OfferState::Ended {
|
||||
"ended"
|
||||
} else {
|
||||
"answered"
|
||||
};
|
||||
refused(StatusCode::CONFLICT, code)
|
||||
}
|
||||
|
||||
/// What deleting target `target_id` of tenant `tenant_id` (in `db`) means
|
||||
/// for releases: its active releases end at their customers, and offers
|
||||
/// accepted into it end, with `ended` as the answer the supplier sees, so
|
||||
/// nothing is delivered into a component that has gone. Called before the
|
||||
/// target's releases are deleted. Best-effort.
|
||||
pub(super) async fn on_target_deleted(agent: &ComplianceAgent, db: &Database, target_id: &str) {
|
||||
let active: Vec<SbomRelease> = match db
|
||||
.inner()
|
||||
.collection::<SbomRelease>(SbomRelease::COLLECTION)
|
||||
.find(doc! { "target_id": target_id, "ended_at": null })
|
||||
.await
|
||||
{
|
||||
Ok(cursor) => cursor.try_collect().await.unwrap_or_default(),
|
||||
Err(e) => {
|
||||
tracing::warn!(target_id, "releases of a deleted target not read: {e}");
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
for release in active {
|
||||
end(agent, &release.peer_tenant_id, &release.id.to_hex()).await;
|
||||
}
|
||||
let accepted: Vec<SbomOffer> = match offers(db)
|
||||
.find(doc! { "target_id": target_id, "state": "accepted" })
|
||||
.await
|
||||
{
|
||||
Ok(cursor) => cursor.try_collect().await.unwrap_or_default(),
|
||||
Err(e) => {
|
||||
tracing::warn!(target_id, "offers into a deleted target not read: {e}");
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
for offer in accepted {
|
||||
if mark_ended(db, offer.id).await.is_ok() {
|
||||
answer_release(agent, &offer, OfferState::Ended).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Record `action` about `target` in the platform's audit log, in the
|
||||
/// background.
|
||||
fn audit(
|
||||
agent: &ComplianceAgent,
|
||||
tenant: &TenantCtx,
|
||||
action: &str,
|
||||
target: Option<&OnboardedTarget>,
|
||||
offer: &SbomOffer,
|
||||
) {
|
||||
let Some(registry) = agent.registry.clone() else {
|
||||
return;
|
||||
};
|
||||
let mut entry = crate::registry::AuditEntry::by(
|
||||
&tenant.0,
|
||||
action,
|
||||
serde_json::json!({ "supplier_name": offer.supplier_name, "product_name": offer.product_name }),
|
||||
);
|
||||
if let Some(t) = target {
|
||||
entry = entry.about_target(&t.id.map(|o| o.to_hex()).unwrap_or_default(), &t.name);
|
||||
}
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = registry.append_audit(&entry).await {
|
||||
tracing::warn!("offer answer not audited: {e}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Offer `id` of the tenant behind `db`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 404 when it is not an id or there is no such offer.
|
||||
async fn find(db: &Database, id: &str) -> Result<SbomOffer, StatusCode> {
|
||||
let oid = ObjectId::parse_str(id).map_err(|_| StatusCode::NOT_FOUND)?;
|
||||
offers(db)
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::NOT_FOUND)
|
||||
}
|
||||
|
||||
/// The SBOM releases connected suppliers offer the workspace.
|
||||
///
|
||||
/// Open offers first, then the answered and ended ones, each newest first.
|
||||
/// Each names the supplier workspace and its product; nothing else of the
|
||||
/// supplier's is shown.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/sbom-offers",
|
||||
tag = "Targets",
|
||||
responses(
|
||||
(status = 200, description = "The offers (`data`)"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn list_offers(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
) -> Result<Json<ApiResponse<Vec<OfferView>>>, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let mut listed: Vec<SbomOffer> = offers(&db)
|
||||
.find(doc! {})
|
||||
.sort(doc! { "offered_at": -1, "_id": -1 })
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.try_collect()
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
// Open ones first; the sort keeps each group newest first.
|
||||
listed.sort_by_key(|o| o.state != OfferState::Offered);
|
||||
Ok(Json(ApiResponse {
|
||||
data: listed.into_iter().map(OfferView::from).collect(),
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Accept a supplier's SBOM release.
|
||||
///
|
||||
/// Into an existing supplier component (`target_id`), or into a new one
|
||||
/// named `name` (the product's name when left out) in `project_ids`. A new
|
||||
/// component counts like any other target. The supplier sees the answer.
|
||||
/// The connection must still join the two workspaces.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/sbom-offers/{id}/accept",
|
||||
tag = "Targets",
|
||||
params(("id" = String, Path, description = "The offer's id")),
|
||||
request_body = AcceptOffer,
|
||||
responses(
|
||||
(status = 200, description = "Accepted (`data`: the offer)"),
|
||||
(status = 404, description = "No such offer, or no such component"),
|
||||
(status = 409, description = "Already answered (`answered`), the release or connection ended (`ended`), or the component already receives another release (`target_taken`), or the plan allows no further active target (`target_limit`)"),
|
||||
(status = 422, description = "The component is not a supplier component (`not_supplier_component`), or an unknown project"),
|
||||
(status = 503, description = "The registry cannot be asked"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
(status = 403, description = "A read-only role"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(offer_id = %id))]
|
||||
pub async fn accept_offer(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
Json(body): Json<AcceptOffer>,
|
||||
) -> Result<axum::response::Response, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let offer = find(&db, &id).await?;
|
||||
if offer.state != OfferState::Offered {
|
||||
return Ok(not_open(offer.state));
|
||||
}
|
||||
if !still_open(&agent, &tenant.0.tenant_id, &offer).await? {
|
||||
mark_ended(&db, offer.id).await?;
|
||||
return Ok(refused(StatusCode::CONFLICT, "ended"));
|
||||
}
|
||||
|
||||
// What it goes into, checked before anything is claimed or created.
|
||||
let into = match body
|
||||
.target_id
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|t| !t.is_empty())
|
||||
{
|
||||
Some(chosen) => {
|
||||
let oid = ObjectId::parse_str(chosen).map_err(|_| StatusCode::NOT_FOUND)?;
|
||||
let target = db
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
if target.supplier.is_none() {
|
||||
return Ok(refused(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"not_supplier_component",
|
||||
));
|
||||
}
|
||||
Destination::Existing(target)
|
||||
}
|
||||
None => {
|
||||
let known = super::projects::tenant_projects(&agent, &tenant.0.tenant_id).await?;
|
||||
let project_ids = super::projects::validated_project_ids(&body.project_ids, &known)?;
|
||||
let name = body
|
||||
.name
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|n| !n.is_empty())
|
||||
.unwrap_or(&offer.product_name)
|
||||
.to_string();
|
||||
let mut target = OnboardedTarget::new(name, offer.product_type);
|
||||
target.supplier = Some(SupplierComponent {
|
||||
name: offer.supplier_name.clone(),
|
||||
product: Some(offer.product_name.clone()),
|
||||
version: None,
|
||||
csaf_provider: None,
|
||||
});
|
||||
target.project_ids = project_ids;
|
||||
Destination::New(target)
|
||||
}
|
||||
};
|
||||
|
||||
// Claim the offer first: of two acceptances, or an acceptance and the
|
||||
// supplier's end, one wins, and nothing is created for the other.
|
||||
let chosen_id = match &into {
|
||||
Destination::Existing(target) => target.id.map(|o| o.to_hex()),
|
||||
Destination::New(_) => None,
|
||||
};
|
||||
let claimed = offers(&db)
|
||||
.update_one(
|
||||
doc! { "_id": offer.id, "state": "offered" },
|
||||
doc! { "$set": {
|
||||
"state": "accepted",
|
||||
"target_id": chosen_id.as_deref(),
|
||||
"decided_at": BsonDateTime::now(),
|
||||
"decided_by": &tenant.0.user_id,
|
||||
} },
|
||||
)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
if claimed.modified_count == 0 {
|
||||
return Ok(not_open(find(&db, &id).await?.state));
|
||||
}
|
||||
|
||||
let target = match into {
|
||||
Destination::Existing(target) => {
|
||||
// One release per component: of two claims on it, neither keeps
|
||||
// it when they raced, and the next acceptance finds it free.
|
||||
let receiving = offers(&db)
|
||||
.count_documents(doc! { "target_id": chosen_id.as_deref(), "state": "accepted" })
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
if receiving > 1 {
|
||||
unclaim(&db, offer.id).await?;
|
||||
return Ok(refused(StatusCode::CONFLICT, "target_taken"));
|
||||
}
|
||||
target
|
||||
}
|
||||
Destination::New(target) => {
|
||||
let created =
|
||||
match super::onboarding::insert_target(&agent, &db, &tenant.0.tenant_id, target)
|
||||
.await
|
||||
{
|
||||
Ok(created) => created,
|
||||
Err(e) => {
|
||||
unclaim(&db, offer.id).await?;
|
||||
return Ok(super::onboarding::target_refused(e));
|
||||
}
|
||||
};
|
||||
let created_id = created.id.map(|o| o.to_hex()).unwrap_or_default();
|
||||
let linked = offers(&db)
|
||||
.update_one(
|
||||
doc! { "_id": offer.id, "state": "accepted" },
|
||||
doc! { "$set": { "target_id": &created_id } },
|
||||
)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
if linked.matched_count == 0 {
|
||||
// The supplier ended it meanwhile: the new component, still
|
||||
// empty, goes again.
|
||||
if let Some(oid) = created.id {
|
||||
db.onboarded_targets()
|
||||
.delete_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
}
|
||||
return Ok(refused(StatusCode::CONFLICT, "ended"));
|
||||
}
|
||||
created
|
||||
}
|
||||
};
|
||||
answer_release(&agent, &offer, OfferState::Accepted).await;
|
||||
// What the supplier already published arrives at once.
|
||||
let accepted = find(&db, &id).await?;
|
||||
super::delivery::deliver_latest(&agent, &accepted).await;
|
||||
audit(
|
||||
&agent,
|
||||
&tenant,
|
||||
"pruefwerk.sbom_offer_accepted",
|
||||
Some(&target),
|
||||
&offer,
|
||||
);
|
||||
let offer = find(&db, &id).await?;
|
||||
Ok(Json(ApiResponse {
|
||||
data: OfferView::from(offer),
|
||||
total: None,
|
||||
page: None,
|
||||
})
|
||||
.into_response())
|
||||
}
|
||||
|
||||
/// Decline a supplier's SBOM release. The supplier sees the answer.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/sbom-offers/{id}/decline",
|
||||
tag = "Targets",
|
||||
params(("id" = String, Path, description = "The offer's id")),
|
||||
responses(
|
||||
(status = 200, description = "Declined (`data`: the offer)"),
|
||||
(status = 404, description = "No such offer"),
|
||||
(status = 409, description = "Already answered or ended (`answered`)"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
(status = 403, description = "A read-only role"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(offer_id = %id))]
|
||||
pub async fn decline_offer(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<axum::response::Response, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let offer = find(&db, &id).await?;
|
||||
let declined = offers(&db)
|
||||
.update_one(
|
||||
doc! { "_id": offer.id, "state": "offered" },
|
||||
doc! { "$set": {
|
||||
"state": "declined",
|
||||
"decided_at": BsonDateTime::now(),
|
||||
"decided_by": &tenant.0.user_id,
|
||||
} },
|
||||
)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
if declined.modified_count == 0 {
|
||||
return Ok(refused(StatusCode::CONFLICT, "answered"));
|
||||
}
|
||||
answer_release(&agent, &offer, OfferState::Declined).await;
|
||||
audit(
|
||||
&agent,
|
||||
&tenant,
|
||||
"pruefwerk.sbom_offer_declined",
|
||||
None,
|
||||
&offer,
|
||||
);
|
||||
let offer = find(&db, &id).await?;
|
||||
Ok(Json(ApiResponse {
|
||||
data: OfferView::from(offer),
|
||||
total: None,
|
||||
page: None,
|
||||
})
|
||||
.into_response())
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -18,13 +18,24 @@ use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use super::dto::{collect_cursor_async, tenant_db, AgentExt};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
/// The body of [`assess_target`].
|
||||
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||
pub struct AssessRequest {
|
||||
/// The target / repo id whose findings are assessed.
|
||||
pub target_id: String,
|
||||
}
|
||||
|
||||
/// `POST /api/v1/oscal/assess` — OSCAL assessment-results for a target's findings.
|
||||
/// A target's findings as OSCAL assessment results.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/oscal/assess",
|
||||
tag = "Compliance",
|
||||
request_body = AssessRequest,
|
||||
responses(
|
||||
(status = 200, description = "The OSCAL assessment results"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
pub async fn assess_target(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
|
||||
@@ -21,8 +21,10 @@ use super::super::dto::{collect_cursor_async, tenant_db};
|
||||
|
||||
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// The body of [`export_session_report`].
|
||||
#[derive(Deserialize, utoipa::ToSchema)]
|
||||
pub struct ExportBody {
|
||||
/// The password the archive is encrypted with.
|
||||
pub password: String,
|
||||
/// Requester display name (from auth)
|
||||
#[serde(default)]
|
||||
@@ -32,7 +34,20 @@ pub struct ExportBody {
|
||||
pub requester_email: String,
|
||||
}
|
||||
|
||||
/// POST /api/v1/pentest/sessions/:id/export — Export an encrypted pentest report archive
|
||||
/// A session's report as an encrypted archive to download.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/pentest/sessions/{id}/export",
|
||||
tag = "Pentest",
|
||||
params(("id" = String, Path, description = "The session's id")),
|
||||
request_body = ExportBody,
|
||||
responses(
|
||||
(status = 200, description = "The archive"),
|
||||
(status = 400, description = "Not an id, or no password"),
|
||||
(status = 404, description = "No such session"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
||||
pub async fn export_session_report(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -17,13 +17,18 @@ use super::super::dto::{collect_cursor_async, tenant_db, ApiResponse, Pagination
|
||||
|
||||
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// The body of [`create_session`].
|
||||
#[derive(Deserialize, utoipa::ToSchema)]
|
||||
pub struct CreateSessionRequest {
|
||||
/// The target to test, for a session without `config`.
|
||||
pub target_id: Option<String>,
|
||||
/// `quick`, `comprehensive` (default), `targeted` or `aggressive`.
|
||||
#[serde(default = "default_strategy")]
|
||||
pub strategy: String,
|
||||
/// The first instruction.
|
||||
pub message: Option<String>,
|
||||
/// Wizard configuration — if present, takes precedence over legacy fields
|
||||
#[schema(value_type = Option<Object>)]
|
||||
pub config: Option<PentestConfig>,
|
||||
}
|
||||
|
||||
@@ -31,17 +36,37 @@ fn default_strategy() -> String {
|
||||
"comprehensive".to_string()
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// The body of [`send_message`].
|
||||
#[derive(Deserialize, utoipa::ToSchema)]
|
||||
pub struct SendMessageRequest {
|
||||
/// The message.
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// The query of [`lookup_repo`].
|
||||
#[derive(Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct LookupRepoQuery {
|
||||
/// The repository's git URL.
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
/// POST /api/v1/pentest/sessions — Create a new pentest session and start the orchestrator
|
||||
/// Create a pentest session and start it.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/pentest/sessions",
|
||||
tag = "Pentest",
|
||||
request_body = CreateSessionRequest,
|
||||
responses(
|
||||
(status = 200, description = "The session"),
|
||||
(status = 400, description = "A missing disclaimer, target or id, or a URL the agent may not reach"),
|
||||
(status = 404, description = "No such target"),
|
||||
(status = 409, description = "Pentests are not available on this deployment (static analysis only)"),
|
||||
(status = 429, description = "Too many sessions are running"),
|
||||
(status = 503, description = "A credential cannot be sealed"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn create_session(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -86,6 +111,13 @@ pub async fn create_session(
|
||||
if let Err(e) = agent.net_guard.check_url(&config.app_url) {
|
||||
return Err((StatusCode::BAD_REQUEST, e.to_string()));
|
||||
}
|
||||
// The test-user cleanup talks to the target's identity provider, also
|
||||
// a tenant-chosen URL.
|
||||
if let Some(access) = &config.auth.cleanup {
|
||||
if let Err(e) = agent.net_guard.check_url(&access.base_url()) {
|
||||
return Err((StatusCode::BAD_REQUEST, e.to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
// Look up or auto-create DastTarget by app_url
|
||||
let target = match db
|
||||
@@ -187,35 +219,21 @@ pub async fn create_session(
|
||||
}
|
||||
}
|
||||
|
||||
// Pre-populate test user record for auto-register sessions
|
||||
if let Some(ref cfg) = session.config {
|
||||
if cfg.auth.mode == AuthMode::AutoRegister {
|
||||
let verification_email = cfg.auth.verification_email.clone();
|
||||
// Build plus-addressed email for this session
|
||||
let test_email = verification_email.as_deref().map(|email| {
|
||||
let parts: Vec<&str> = email.splitn(2, '@').collect();
|
||||
if parts.len() == 2 {
|
||||
format!("{}+{}@{}", parts[0], session_id_str, parts[1])
|
||||
} else {
|
||||
email.to_string()
|
||||
}
|
||||
});
|
||||
|
||||
// Detect identity provider from keycloak config
|
||||
let provider = if agent.config.keycloak_url.is_some() {
|
||||
Some(compliance_core::models::pentest::IdentityProvider::Keycloak)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
session.test_user = Some(compliance_core::models::pentest::TestUserRecord {
|
||||
username: None, // LLM will choose; updated after registration
|
||||
email: test_email,
|
||||
provider_user_id: None,
|
||||
provider,
|
||||
cleaned_up: false,
|
||||
});
|
||||
}
|
||||
// The test user an auto-register session registers, kept on the
|
||||
// stored session so cleanup and the report find it.
|
||||
if let Some(cfg) = &session.config {
|
||||
session.test_user = crate::pentest::cleanup::planned_test_user(cfg, &session_id_str);
|
||||
}
|
||||
if let (Some(sid), Some(test_user)) = (session.id, &session.test_user) {
|
||||
let record = mongodb::bson::to_bson(test_user)
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
db.pentest_sessions()
|
||||
.update_one(
|
||||
doc! { "_id": sid },
|
||||
doc! { "$set": { "test_user": record } },
|
||||
)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("DB error: {e}")))?;
|
||||
}
|
||||
|
||||
let initial_message = config
|
||||
@@ -356,7 +374,17 @@ fn parse_strategy(s: &str) -> PentestStrategy {
|
||||
}
|
||||
}
|
||||
|
||||
/// GET /api/v1/pentest/lookup-repo — Look up a tracked repository by git URL
|
||||
/// Look up a tracked repository by its git URL.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/pentest/lookup-repo",
|
||||
tag = "Pentest",
|
||||
params(LookupRepoQuery),
|
||||
responses(
|
||||
(status = 200, description = "The repository, or null"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn lookup_repo(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -389,7 +417,17 @@ pub async fn lookup_repo(
|
||||
}))
|
||||
}
|
||||
|
||||
/// GET /api/v1/pentest/sessions — List pentest sessions
|
||||
/// The tenant's pentest sessions, a page at a time.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/pentest/sessions",
|
||||
tag = "Pentest",
|
||||
params(PaginationParams),
|
||||
responses(
|
||||
(status = 200, description = "A page of sessions"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn list_sessions(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -427,7 +465,19 @@ pub async fn list_sessions(
|
||||
}))
|
||||
}
|
||||
|
||||
/// GET /api/v1/pentest/sessions/:id — Get a single pentest session
|
||||
/// One pentest session.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/pentest/sessions/{id}",
|
||||
tag = "Pentest",
|
||||
params(("id" = String, Path, description = "The session's id")),
|
||||
responses(
|
||||
(status = 200, description = "The session"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 404, description = "No such session"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
||||
pub async fn get_session(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -461,7 +511,20 @@ pub async fn get_session(
|
||||
}))
|
||||
}
|
||||
|
||||
/// POST /api/v1/pentest/sessions/:id/chat — Send a user message and trigger next orchestrator iteration
|
||||
/// Send a message to a session, which starts its next iteration.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/pentest/sessions/{id}/chat",
|
||||
tag = "Pentest",
|
||||
params(("id" = String, Path, description = "The session's id")),
|
||||
request_body = SendMessageRequest,
|
||||
responses(
|
||||
(status = 200, description = "The stored message"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 404, description = "No such session"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
||||
pub async fn send_message(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -561,7 +624,19 @@ pub async fn send_message(
|
||||
}))
|
||||
}
|
||||
|
||||
/// POST /api/v1/pentest/sessions/:id/stop — Stop a running pentest session
|
||||
/// Stop a running session.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/pentest/sessions/{id}/stop",
|
||||
tag = "Pentest",
|
||||
params(("id" = String, Path, description = "The session's id")),
|
||||
responses(
|
||||
(status = 200, description = "The stopped session"),
|
||||
(status = 400, description = "Not an id, or the session is not running"),
|
||||
(status = 404, description = "No such session"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
||||
pub async fn stop_session(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -637,7 +712,19 @@ pub async fn stop_session(
|
||||
}))
|
||||
}
|
||||
|
||||
/// POST /api/v1/pentest/sessions/:id/pause — Pause a running pentest session
|
||||
/// Pause a running session.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/pentest/sessions/{id}/pause",
|
||||
tag = "Pentest",
|
||||
params(("id" = String, Path, description = "The session's id")),
|
||||
responses(
|
||||
(status = 200, description = "Paused"),
|
||||
(status = 400, description = "Not an id, or the session is not running"),
|
||||
(status = 404, description = "No such session"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
||||
pub async fn pause_session(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -683,7 +770,19 @@ pub async fn pause_session(
|
||||
}))
|
||||
}
|
||||
|
||||
/// POST /api/v1/pentest/sessions/:id/resume — Resume a paused pentest session
|
||||
/// Resume a paused session.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/pentest/sessions/{id}/resume",
|
||||
tag = "Pentest",
|
||||
params(("id" = String, Path, description = "The session's id")),
|
||||
responses(
|
||||
(status = 200, description = "Resumed"),
|
||||
(status = 400, description = "Not an id, or the session is not paused"),
|
||||
(status = 404, description = "No such session"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
||||
pub async fn resume_session(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -734,7 +833,18 @@ pub async fn resume_session(
|
||||
/// being loaded whole into agent memory.
|
||||
const MAX_ATTACK_CHAIN_NODES: i64 = 2_000;
|
||||
|
||||
/// GET /api/v1/pentest/sessions/:id/attack-chain — Get attack chain nodes for a session
|
||||
/// A session's attack chain.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/pentest/sessions/{id}/attack-chain",
|
||||
tag = "Pentest",
|
||||
params(("id" = String, Path, description = "The session's id")),
|
||||
responses(
|
||||
(status = 200, description = "The nodes"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
||||
pub async fn get_attack_chain(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -774,7 +884,18 @@ pub async fn get_attack_chain(
|
||||
}))
|
||||
}
|
||||
|
||||
/// GET /api/v1/pentest/sessions/:id/messages — Get messages for a session
|
||||
/// A session's messages, a page at a time.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/pentest/sessions/{id}/messages",
|
||||
tag = "Pentest",
|
||||
params(("id" = String, Path, description = "The session's id"), PaginationParams),
|
||||
responses(
|
||||
(status = 200, description = "A page of messages"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
||||
pub async fn get_messages(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -814,7 +935,18 @@ pub async fn get_messages(
|
||||
}))
|
||||
}
|
||||
|
||||
/// GET /api/v1/pentest/sessions/:id/findings — Get DAST findings for a pentest session
|
||||
/// A session's findings, a page at a time.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/pentest/sessions/{id}/findings",
|
||||
tag = "Pentest",
|
||||
params(("id" = String, Path, description = "The session's id"), PaginationParams),
|
||||
responses(
|
||||
(status = 200, description = "A page of findings"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
||||
pub async fn get_session_findings(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -14,7 +14,16 @@ use super::super::dto::{collect_cursor_async, tenant_db, ApiResponse};
|
||||
|
||||
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
||||
|
||||
/// GET /api/v1/pentest/stats — Aggregated pentest statistics
|
||||
/// The tenant's pentest statistics.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/pentest/stats",
|
||||
tag = "Pentest",
|
||||
responses(
|
||||
(status = 200, description = "The statistics"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn pentest_stats(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -19,10 +19,22 @@ use super::super::dto::{collect_cursor_async, tenant_db};
|
||||
|
||||
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
||||
|
||||
/// GET /api/v1/pentest/sessions/:id/stream — SSE endpoint for real-time events
|
||||
/// A session's events as they happen (server-sent events).
|
||||
///
|
||||
/// Replays stored messages/nodes as initial burst, then subscribes to the
|
||||
/// broadcast channel for live updates. Sends keepalive comments every 15s.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/pentest/sessions/{id}/stream",
|
||||
tag = "Pentest",
|
||||
params(("id" = String, Path, description = "The session's id")),
|
||||
responses(
|
||||
(status = 200, description = "The event stream (text/event-stream)"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 404, description = "No such session"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
||||
pub async fn session_stream(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -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!({
|
||||
@@ -477,6 +462,10 @@ pub struct PlatformTarget {
|
||||
pub open_vulnerabilities: u64,
|
||||
/// Its projects that the registry still lists.
|
||||
pub project_ids: Vec<String>,
|
||||
/// Who supplies it, for a component bought in (#1025): the targets a
|
||||
/// supplier can be invited for (#1027). Left out for the tenant's own.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub supplier: Option<compliance_core::models::SupplierComponent>,
|
||||
}
|
||||
|
||||
/// Open findings of each target in `target_ids`, in one query.
|
||||
@@ -575,7 +564,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),
|
||||
);
|
||||
@@ -597,6 +586,7 @@ pub async fn list_targets(
|
||||
},
|
||||
name: t.name,
|
||||
target_type: t.target_type,
|
||||
supplier: t.supplier,
|
||||
id,
|
||||
}
|
||||
})
|
||||
@@ -655,6 +645,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 +801,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::*;
|
||||
|
||||
@@ -106,8 +106,17 @@ pub fn projects_changed_entry(
|
||||
)
|
||||
}
|
||||
|
||||
/// GET /api/v1/projects — the tenant's projects, for choosing and showing
|
||||
/// them in the dashboard.
|
||||
/// The tenant's projects, for choosing and showing them in the dashboard.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/projects",
|
||||
tag = "Workspace",
|
||||
responses(
|
||||
(status = 200, description = "The projects"),
|
||||
(status = 503, description = "The registry cannot be asked"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn list_projects(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -128,6 +137,8 @@ mod tests {
|
||||
name: format!("Projekt {id}"),
|
||||
kind: ProjectKind::Product,
|
||||
description: String::new(),
|
||||
level: None,
|
||||
parent_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -16,6 +16,16 @@ pub(crate) const MAX_EXPORT_COMPONENTS: u64 = 100_000;
|
||||
/// Package names listed per license in the summary; `count` stays exact.
|
||||
const MAX_LICENSE_PACKAGES: i64 = 100;
|
||||
|
||||
/// The package managers and licences the SBOM list can be filtered by.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/sbom/filters",
|
||||
tag = "SBOM",
|
||||
responses(
|
||||
(status = 200, description = "The package managers and licences"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn sbom_filters(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -31,7 +41,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
|
||||
@@ -50,6 +60,17 @@ pub async fn sbom_filters(
|
||||
})))
|
||||
}
|
||||
|
||||
/// List the tenant's SBOM components, filtered and a page at a time.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/sbom",
|
||||
tag = "SBOM",
|
||||
params(SbomFilter),
|
||||
responses(
|
||||
(status = 200, description = "A page of components"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(repo_id = ?filter.repo_id, package_manager = ?filter.package_manager))]
|
||||
pub async fn list_sbom(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -198,6 +219,20 @@ async fn unresolved_ids(
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A target's SBOM as a CycloneDX or SPDX document to download.
|
||||
///
|
||||
/// Never truncated: a target with more than 100 000 components is refused.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/sbom/export",
|
||||
tag = "SBOM",
|
||||
params(SbomExportParams),
|
||||
responses(
|
||||
(status = 200, description = "The SBOM document"),
|
||||
(status = 413, description = "Too many components to export"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn export_sbom(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -274,14 +309,27 @@ pub async fn export_sbom(
|
||||
}
|
||||
|
||||
/// The target whose SBOM quality is asked for.
|
||||
#[derive(serde::Deserialize)]
|
||||
#[derive(serde::Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct SbomQualityParams {
|
||||
/// The target (its id).
|
||||
pub repo_id: String,
|
||||
}
|
||||
|
||||
/// GET /api/v1/sbom/quality?repo_id= — the target's SBOM quality score
|
||||
/// (sbomqs against BSI TR-03183-2 and NTIA, #496) from its newest scan that
|
||||
/// scored one, with that scan's id and end; `data: null` when none did.
|
||||
/// A target's SBOM quality score from its newest scan that scored one.
|
||||
///
|
||||
/// sbomqs against BSI TR-03183-2 and NTIA (#496), with that scan's id and
|
||||
/// end; `data: null` when none did.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/sbom/quality",
|
||||
tag = "SBOM",
|
||||
params(SbomQualityParams),
|
||||
responses(
|
||||
(status = 200, description = "The score, or null"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(repo_id = %params.repo_id))]
|
||||
pub async fn sbom_quality(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -308,6 +356,19 @@ pub async fn sbom_quality(
|
||||
}))
|
||||
}
|
||||
|
||||
/// The licences of the SBOM components, most components first.
|
||||
///
|
||||
/// The confirmed licence where there is one, else the detected one.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/sbom/licenses",
|
||||
tag = "SBOM",
|
||||
params(SbomFilter),
|
||||
responses(
|
||||
(status = 200, description = "One row per licence"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn license_summary(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -411,6 +472,19 @@ fn summarize_licenses(
|
||||
summaries
|
||||
}
|
||||
|
||||
/// Compare the SBOMs of two targets.
|
||||
///
|
||||
/// The components only in one of them and those whose version differs.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/sbom/diff",
|
||||
tag = "SBOM",
|
||||
params(SbomDiffParams),
|
||||
responses(
|
||||
(status = 200, description = "The differences"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn sbom_diff(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -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,155 @@
|
||||
//! 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 data = target_changes(&db, &id, query.limit).await?;
|
||||
Ok(Json(ApiResponse {
|
||||
total: Some(data.len() as u64),
|
||||
data,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// The last `limit` scans of target `id`, oldest first, each with what it
|
||||
/// changed (see [`target_scan_changes`]).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 500 when the database cannot be read.
|
||||
pub(crate) async fn target_changes(
|
||||
db: &crate::database::Database,
|
||||
id: &str,
|
||||
limit: usize,
|
||||
) -> Result<Vec<ScanChange>, StatusCode> {
|
||||
let runs: Vec<ScanRun> = collect_cursor_async(
|
||||
db.scan_runs()
|
||||
.find(doc! { "repo_id": id })
|
||||
.sort(doc! { "started_at": -1 })
|
||||
.limit(i64::try_from(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;
|
||||
|
||||
Ok(changes(&runs, since, &alerts))
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,8 @@ use compliance_core::models::ScanRun;
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
/// Which scan runs to list.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[derive(Debug, Default, Deserialize, utoipa::IntoParams)]
|
||||
#[into_params(parameter_in = Query)]
|
||||
pub struct ScanRunFilter {
|
||||
/// Only the runs of this target (its id), for the target's scan history.
|
||||
#[serde(default)]
|
||||
@@ -25,7 +26,17 @@ impl ScanRunFilter {
|
||||
}
|
||||
}
|
||||
|
||||
/// GET /api/v1/scan-runs?target_id=&page=&limit= — newest first.
|
||||
/// The tenant's scan runs, newest first, a page at a time.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/scan-runs",
|
||||
tag = "Scans",
|
||||
params(PaginationParams, ScanRunFilter),
|
||||
responses(
|
||||
(status = 200, description = "A page of scan runs"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn list_scan_runs(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
//! What Prüfwerk knows of a bought-in component's supplier (#1025): how many
|
||||
//! of its CSAF advisories are kept for the workspace, and when its provider
|
||||
//! was last read.
|
||||
|
||||
use axum::extract::{Extension, Path};
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use mongodb::bson::{doc, oid::ObjectId};
|
||||
use serde::Serialize;
|
||||
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use super::dto::{tenant_db, AgentExt};
|
||||
use super::ApiResponse;
|
||||
use crate::pipeline::csaf_feed::{supplier_key, MongoAdvisoryStore, SupplierProviderStatus};
|
||||
|
||||
/// The advisories of a target's supplier, as the target editor shows them.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct SupplierAdvisories {
|
||||
/// The supplier's advisories kept for the workspace.
|
||||
pub advisories: u64,
|
||||
/// When its provider was last read; none before the first refresh.
|
||||
pub checked_at: Option<chrono::DateTime<chrono::Utc>>,
|
||||
/// Whether its metadata and feeds could be read then; none before the
|
||||
/// first refresh.
|
||||
pub reachable: Option<bool>,
|
||||
}
|
||||
|
||||
/// Count the target's supplier advisories, with their provider's last read.
|
||||
///
|
||||
/// `data` holds `advisories`, `checked_at` and `reachable` (both null before
|
||||
/// the first refresh), or is null when the target names no supplier CSAF
|
||||
/// provider. The
|
||||
/// advisories are the workspace's own: a provider is read for the workspaces
|
||||
/// that name it, daily and right after it is set.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/targets/{id}/supplier-advisories",
|
||||
tag = "Targets",
|
||||
params(("id" = String, Path, description = "The target's id")),
|
||||
responses(
|
||||
(status = 200, description = "The supplier's advisories, or null without a provider"),
|
||||
(status = 400, description = "Not an id"),
|
||||
(status = 404, description = "No such target"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn get_supplier_advisories(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<Json<ApiResponse<Option<SupplierAdvisories>>>, StatusCode> {
|
||||
let oid = ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let target = db
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let Some(url) = target.supplier.and_then(|s| s.csaf_provider) else {
|
||||
return Ok(Json(ApiResponse {
|
||||
data: None,
|
||||
total: None,
|
||||
page: None,
|
||||
}));
|
||||
};
|
||||
let key = supplier_key(&url);
|
||||
let advisories = MongoAdvisoryStore::supplier(db.inner())
|
||||
.collection()
|
||||
.count_documents(doc! { "provider": &key })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let status = db
|
||||
.inner()
|
||||
.collection::<SupplierProviderStatus>(SupplierProviderStatus::COLLECTION)
|
||||
.find_one(doc! { "_id": &key })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
Ok(Json(ApiResponse {
|
||||
data: Some(SupplierAdvisories {
|
||||
advisories,
|
||||
checked_at: status.as_ref().map(|s| s.checked_at.to_chrono()),
|
||||
reachable: status.map(|s| s.reachable),
|
||||
}),
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,904 @@
|
||||
//! Supplier invites (#1027): the customer invites a supplier, through the
|
||||
//! portal, to upload the SBOM of one bought-in component.
|
||||
//!
|
||||
//! The portal owns the secret link and the mail; Prüfwerk keeps the invite in
|
||||
//! the tenant's own database (so the tenant export and erasure cover it, the
|
||||
//! supplier's address included) and refuses what an expired or withdrawn
|
||||
//! invite would allow. The portal calls these endpoints with its platform
|
||||
//! service token ([`super::platform::require_platform_token`]).
|
||||
//!
|
||||
//! An invite is valid for [`INVITE_LIFETIME_DAYS`] from when it is made, and
|
||||
//! serves the component's later SBOM versions until it expires or is
|
||||
//! withdrawn (decided 2026-11-18).
|
||||
//!
|
||||
//! An upload through an invite takes the customer's own upload path
|
||||
//! ([`super::onboarding::attach_upload`]): it becomes the component's SBOM and
|
||||
//! starts a scan. Every upload, refused ones included, is recorded with the
|
||||
//! invite it came through ([`SupplierUpload`]), for the customer and the
|
||||
//! supplier to see.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use axum::extract::{Multipart, Path, Query, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use chrono::{DateTime, Utc};
|
||||
use futures_util::TryStreamExt;
|
||||
use mongodb::bson::{doc, oid::ObjectId, DateTime as BsonDateTime};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use compliance_core::models::{ArtifactKind, OnboardedTarget, ScanTrigger};
|
||||
|
||||
use super::onboarding::{
|
||||
attach_upload, is_https_url, refresh_supplier_csaf, stream_to_disk, StoredUpload,
|
||||
SupplierSbomSummary, UploadRefusal,
|
||||
};
|
||||
use super::platform::PlatformState;
|
||||
use crate::agent::ComplianceAgent;
|
||||
use crate::database::Database;
|
||||
use crate::pipeline::sbom::supplied::MAX_BYTES as MAX_SBOM_BYTES;
|
||||
|
||||
/// How long an invite is valid, in days from when it is made.
|
||||
pub const INVITE_LIFETIME_DAYS: i64 = 90;
|
||||
|
||||
/// The longest e-mail address accepted (RFC 5321's path limit).
|
||||
const MAX_EMAIL_LEN: usize = 254;
|
||||
|
||||
/// The longest `invited_by` / `withdrawn_by` accepted: a portal user's id.
|
||||
const MAX_ACTOR_LEN: usize = 200;
|
||||
|
||||
/// The most uploads one invite takes in a day, refused ones included: each
|
||||
/// accepted one starts a scan the customer pays for.
|
||||
pub const MAX_UPLOADS_PER_DAY: u64 = 20;
|
||||
|
||||
/// The longest file name kept with an upload, in characters.
|
||||
const MAX_FILENAME_CHARS: usize = 200;
|
||||
|
||||
/// An invite as stored, in the tenant's [`SupplierInvite::COLLECTION`].
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct SupplierInvite {
|
||||
/// Its id, which the portal keys its secret link by.
|
||||
#[serde(rename = "_id")]
|
||||
pub id: ObjectId,
|
||||
/// The target (a supplier component) the invite is for.
|
||||
pub target_id: String,
|
||||
/// Who was invited: the supplier's e-mail address, lower case.
|
||||
pub email: String,
|
||||
/// The portal user who sent it.
|
||||
pub invited_by: String,
|
||||
/// When it was made.
|
||||
pub created_at: BsonDateTime,
|
||||
/// When it stops being valid.
|
||||
pub expires_at: BsonDateTime,
|
||||
/// When it was withdrawn; `None` while it is not.
|
||||
#[serde(default)]
|
||||
pub withdrawn_at: Option<BsonDateTime>,
|
||||
/// The portal user who withdrew it.
|
||||
#[serde(default)]
|
||||
pub withdrawn_by: Option<String>,
|
||||
}
|
||||
|
||||
/// Whether an invite still allows an upload.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum InviteState {
|
||||
/// Uploads are accepted.
|
||||
Active,
|
||||
/// Past `expires_at`.
|
||||
Expired,
|
||||
/// Withdrawn by the customer (this wins over expiry).
|
||||
Withdrawn,
|
||||
}
|
||||
|
||||
impl SupplierInvite {
|
||||
/// The collection, in the tenant's own database.
|
||||
pub const COLLECTION: &'static str = "supplier_invites";
|
||||
|
||||
/// A new invite for `target_id`, made at `now`.
|
||||
pub fn new(target_id: String, email: String, invited_by: String, now: DateTime<Utc>) -> Self {
|
||||
Self {
|
||||
id: ObjectId::new(),
|
||||
target_id,
|
||||
email,
|
||||
invited_by,
|
||||
created_at: now.into(),
|
||||
expires_at: (now + chrono::Duration::days(INVITE_LIFETIME_DAYS)).into(),
|
||||
withdrawn_at: None,
|
||||
withdrawn_by: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Its state at `now`.
|
||||
pub fn state(&self, now: DateTime<Utc>) -> InviteState {
|
||||
if self.withdrawn_at.is_some() {
|
||||
InviteState::Withdrawn
|
||||
} else if now >= self.expires_at.to_chrono() {
|
||||
InviteState::Expired
|
||||
} else {
|
||||
InviteState::Active
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An invite as the portal reads it.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct InviteView {
|
||||
/// The invite's id.
|
||||
pub id: String,
|
||||
/// The target it is for.
|
||||
pub target_id: String,
|
||||
/// The supplier's e-mail address.
|
||||
pub email: String,
|
||||
/// The portal user who sent it.
|
||||
pub invited_by: String,
|
||||
/// When it was made.
|
||||
pub created_at: DateTime<Utc>,
|
||||
/// When it stops being valid.
|
||||
pub expires_at: DateTime<Utc>,
|
||||
/// When it was withdrawn, if it was.
|
||||
pub withdrawn_at: Option<DateTime<Utc>>,
|
||||
/// Who withdrew it, if anyone did.
|
||||
pub withdrawn_by: Option<String>,
|
||||
/// Whether it still allows an upload.
|
||||
pub state: InviteState,
|
||||
/// What came through it, newest first.
|
||||
pub uploads: Vec<UploadView>,
|
||||
}
|
||||
|
||||
impl InviteView {
|
||||
/// The view of `invite` at `now`, with its `uploads`.
|
||||
fn of(invite: SupplierInvite, now: DateTime<Utc>, uploads: Vec<UploadView>) -> Self {
|
||||
Self {
|
||||
uploads,
|
||||
state: invite.state(now),
|
||||
id: invite.id.to_hex(),
|
||||
target_id: invite.target_id,
|
||||
email: invite.email,
|
||||
invited_by: invite.invited_by,
|
||||
created_at: invite.created_at.to_chrono(),
|
||||
expires_at: invite.expires_at.to_chrono(),
|
||||
withdrawn_at: invite.withdrawn_at.map(BsonDateTime::to_chrono),
|
||||
withdrawn_by: invite.withdrawn_by,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An upload through an invite, as stored in [`SupplierUpload::COLLECTION`]:
|
||||
/// accepted or refused, with what the file held.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct SupplierUpload {
|
||||
/// Its id.
|
||||
#[serde(rename = "_id")]
|
||||
pub id: ObjectId,
|
||||
/// The invite it came through.
|
||||
pub invite_id: String,
|
||||
/// The target it was for.
|
||||
pub target_id: String,
|
||||
/// When it arrived.
|
||||
pub uploaded_at: BsonDateTime,
|
||||
/// The file's name, as the supplier sent it.
|
||||
pub filename: String,
|
||||
/// Whether it became the component's SBOM.
|
||||
pub accepted: bool,
|
||||
/// Why it was refused: the code of the refusal.
|
||||
#[serde(default)]
|
||||
pub code: Option<String>,
|
||||
/// What an accepted SBOM holds.
|
||||
#[serde(default)]
|
||||
pub summary: Option<SupplierSbomSummary>,
|
||||
/// The artifact an accepted SBOM became.
|
||||
#[serde(default)]
|
||||
pub artifact_id: Option<String>,
|
||||
/// The CSAF provider the supplier gave with it.
|
||||
#[serde(default)]
|
||||
pub csaf_provider: Option<String>,
|
||||
}
|
||||
|
||||
impl SupplierUpload {
|
||||
/// The collection, in the tenant's own database.
|
||||
pub const COLLECTION: &'static str = "supplier_uploads";
|
||||
|
||||
/// A refused upload of `filename` through `invite`, with the refusal's code.
|
||||
fn refused(invite: &SupplierInvite, filename: &str, code: &str) -> Self {
|
||||
Self {
|
||||
id: ObjectId::new(),
|
||||
invite_id: invite.id.to_hex(),
|
||||
target_id: invite.target_id.clone(),
|
||||
uploaded_at: BsonDateTime::now(),
|
||||
filename: filename.to_string(),
|
||||
accepted: false,
|
||||
code: Some(code.to_string()),
|
||||
summary: None,
|
||||
artifact_id: None,
|
||||
csaf_provider: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An upload as the portal shows it, to the customer and to the supplier.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct UploadView {
|
||||
/// Its id.
|
||||
pub id: String,
|
||||
/// When it arrived.
|
||||
pub uploaded_at: DateTime<Utc>,
|
||||
/// The file's name.
|
||||
pub filename: String,
|
||||
/// Whether it became the component's SBOM.
|
||||
pub accepted: bool,
|
||||
/// Why it was refused: `too_large`, `too_many_components`, `empty`,
|
||||
/// `unknown_format`, `malformed` or `csaf_provider`.
|
||||
pub code: Option<String>,
|
||||
/// What an accepted SBOM holds.
|
||||
pub summary: Option<SupplierSbomSummary>,
|
||||
/// The CSAF provider given with it.
|
||||
pub csaf_provider: Option<String>,
|
||||
/// Whether it is the component's SBOM now (a later one replaces it).
|
||||
pub current: bool,
|
||||
}
|
||||
|
||||
impl UploadView {
|
||||
/// The view of `upload`; `current` is the target's SBOM artifact now.
|
||||
fn of(upload: SupplierUpload, current: Option<&str>) -> Self {
|
||||
Self {
|
||||
current: upload.artifact_id.is_some() && upload.artifact_id.as_deref() == current,
|
||||
id: upload.id.to_hex(),
|
||||
uploaded_at: upload.uploaded_at.to_chrono(),
|
||||
filename: upload.filename,
|
||||
accepted: upload.accepted,
|
||||
code: upload.code,
|
||||
summary: upload.summary,
|
||||
csaf_provider: upload.csaf_provider,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the supplier sees of its invite: the component, until when the link
|
||||
/// is valid, and its uploads. Nothing else of the customer's.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct SupplierPage {
|
||||
/// The component, by the customer's name for it.
|
||||
pub component: String,
|
||||
/// The supplier's name for the product, if the customer gave it.
|
||||
pub product: Option<String>,
|
||||
/// The version in use, if the customer gave it.
|
||||
pub version: Option<String>,
|
||||
/// Until when the link is valid.
|
||||
pub expires_at: DateTime<Utc>,
|
||||
/// The CSAF provider kept for the component.
|
||||
pub csaf_provider: Option<String>,
|
||||
/// Its uploads through this invite, newest first.
|
||||
pub uploads: Vec<UploadView>,
|
||||
}
|
||||
|
||||
/// The body of an invite: which component, whom, and who invites.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct CreateInvite {
|
||||
/// The supplier component's target id.
|
||||
pub target_id: String,
|
||||
/// The supplier's e-mail address.
|
||||
pub email: String,
|
||||
/// The portal user who invites.
|
||||
pub invited_by: String,
|
||||
}
|
||||
|
||||
/// The body of a withdrawal.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct WithdrawInvite {
|
||||
/// The portal user who withdraws it.
|
||||
pub withdrawn_by: String,
|
||||
}
|
||||
|
||||
/// The query of the invite list: one target's, or all of them.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
pub struct InviteFilter {
|
||||
/// Only this target's invites.
|
||||
#[serde(default)]
|
||||
pub target: Option<String>,
|
||||
}
|
||||
|
||||
/// `email` trimmed and in lower case, or `None` when it is not an address
|
||||
/// with one `@` between a non-empty local part and a domain holding a dot.
|
||||
fn normalized_email(email: &str) -> Option<String> {
|
||||
let email = email.trim().to_lowercase();
|
||||
let (local, domain) = email.split_once('@')?;
|
||||
let plausible = !local.is_empty()
|
||||
&& domain.contains('.')
|
||||
&& !domain.starts_with('.')
|
||||
&& !domain.ends_with('.')
|
||||
&& !domain.contains('@')
|
||||
&& email.len() <= MAX_EMAIL_LEN
|
||||
&& !email.chars().any(|c| c.is_whitespace() || c.is_control());
|
||||
plausible.then_some(email)
|
||||
}
|
||||
|
||||
/// `actor` trimmed, or `None` when it is empty or too long.
|
||||
fn normalized_actor(actor: &str) -> Option<String> {
|
||||
let actor = actor.trim();
|
||||
(!actor.is_empty() && actor.len() <= MAX_ACTOR_LEN).then(|| actor.to_string())
|
||||
}
|
||||
|
||||
fn invites(db: &Database) -> mongodb::Collection<SupplierInvite> {
|
||||
db.inner().collection(SupplierInvite::COLLECTION)
|
||||
}
|
||||
|
||||
fn uploads(db: &Database) -> mongodb::Collection<SupplierUpload> {
|
||||
db.inner().collection(SupplierUpload::COLLECTION)
|
||||
}
|
||||
|
||||
/// The id of `target`'s supplier SBOM now, if it has one.
|
||||
fn current_sbom(target: &OnboardedTarget) -> Option<&str> {
|
||||
target
|
||||
.artifacts
|
||||
.iter()
|
||||
.find(|a| a.kind == ArtifactKind::SupplierSbom)
|
||||
.map(|a| a.id.as_str())
|
||||
}
|
||||
|
||||
/// `listed` as the portal reads them at `now`, each with its uploads.
|
||||
async fn views(
|
||||
db: &Database,
|
||||
listed: Vec<SupplierInvite>,
|
||||
now: DateTime<Utc>,
|
||||
) -> Result<Vec<InviteView>, StatusCode> {
|
||||
let ids: Vec<String> = listed.iter().map(|i| i.id.to_hex()).collect();
|
||||
let mut by_invite: HashMap<String, Vec<SupplierUpload>> = HashMap::new();
|
||||
let mut cursor = uploads(db)
|
||||
.find(doc! { "invite_id": { "$in": &ids } })
|
||||
.sort(doc! { "uploaded_at": -1, "_id": -1 })
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
while let Some(upload) = cursor.try_next().await.map_err(internal)? {
|
||||
by_invite
|
||||
.entry(upload.invite_id.clone())
|
||||
.or_default()
|
||||
.push(upload);
|
||||
}
|
||||
let target_ids: Vec<ObjectId> = listed
|
||||
.iter()
|
||||
.filter_map(|i| ObjectId::parse_str(&i.target_id).ok())
|
||||
.collect();
|
||||
let targets: Vec<OnboardedTarget> = db
|
||||
.onboarded_targets()
|
||||
.find(doc! { "_id": { "$in": target_ids } })
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.try_collect()
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
let current: HashMap<String, String> = targets
|
||||
.iter()
|
||||
.filter_map(|t| Some((t.id?.to_hex(), current_sbom(t)?.to_string())))
|
||||
.collect();
|
||||
Ok(listed
|
||||
.into_iter()
|
||||
.map(|invite| {
|
||||
let sbom = current.get(&invite.target_id).map(String::as_str);
|
||||
let uploads = by_invite
|
||||
.remove(&invite.id.to_hex())
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|u| UploadView::of(u, sbom))
|
||||
.collect();
|
||||
InviteView::of(invite, now, uploads)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// The invite `invite_id` of the tenant behind `db` while it allows uploads.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 404 when there is no such invite; 410 with the code `expired` or
|
||||
/// `withdrawn` when it no longer allows anything.
|
||||
async fn open_invite(db: &Database, invite_id: &str) -> Result<SupplierInvite, UploadRefusal> {
|
||||
let id = ObjectId::parse_str(invite_id.trim()).map_err(|_| StatusCode::NOT_FOUND)?;
|
||||
let invite = invites(db)
|
||||
.find_one(doc! { "_id": id })
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
match invite.state(Utc::now()) {
|
||||
InviteState::Active => Ok(invite),
|
||||
InviteState::Expired => Err(closed("expired")),
|
||||
InviteState::Withdrawn => Err(closed("withdrawn")),
|
||||
}
|
||||
}
|
||||
|
||||
/// 410: the invite allows nothing more.
|
||||
fn closed(code: &'static str) -> UploadRefusal {
|
||||
UploadRefusal::because(StatusCode::GONE, "the invite is no longer valid", code)
|
||||
}
|
||||
|
||||
/// Whether the tenant may change its data now: not when the registry has it
|
||||
/// read-only, halted or archived. Without a registry (dev) it may.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 403 with the code `read_only` when it may not; 503 when the registry
|
||||
/// cannot answer (access is never widened on doubt).
|
||||
async fn accepts_writes(agent: &ComplianceAgent, tenant_id: &str) -> Result<(), UploadRefusal> {
|
||||
let Some(registry) = agent.registry.as_ref() else {
|
||||
return Ok(());
|
||||
};
|
||||
let check = registry
|
||||
.check_entitlement(tenant_id, None, None)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(tenant_id, "entitlement check unavailable: {e}");
|
||||
StatusCode::SERVICE_UNAVAILABLE
|
||||
})?;
|
||||
// A status it does not name or Prüfwerk does not know limits nothing, as
|
||||
// for a person's request (`require_entitlement`).
|
||||
let status = check
|
||||
.status
|
||||
.as_deref()
|
||||
.and_then(compliance_core::TenantStatus::parse);
|
||||
let writable = check.allowed
|
||||
&& !check.read_only
|
||||
&& status.is_none_or(|s| !s.blocks_writes() && !s.is_halted() && !s.is_archived());
|
||||
if writable {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(UploadRefusal::because(
|
||||
StatusCode::FORBIDDEN,
|
||||
"the workspace takes no uploads now",
|
||||
"read_only",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// The name an upload is shown by: the last part of `name`, at most
|
||||
/// [`MAX_FILENAME_CHARS`] long.
|
||||
fn shown_filename(name: &str) -> String {
|
||||
let base = name.rsplit(['/', '\\']).next().unwrap_or(name).trim();
|
||||
let base = if base.is_empty() { "sbom" } else { base };
|
||||
base.chars().take(MAX_FILENAME_CHARS).collect()
|
||||
}
|
||||
|
||||
fn internal<E: std::fmt::Display>(e: E) -> StatusCode {
|
||||
tracing::error!("supplier invite endpoint failed: {e}");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
|
||||
/// `POST /api/v1/platform/tenants/{id}/supplier-invites`: invite a supplier
|
||||
/// to upload the SBOM of one supplier component. Answers 201 with the
|
||||
/// invite, whose `id` the portal keys its secret link by.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 404 when the tenant has no such target; 422 when the target is not a
|
||||
/// supplier component, or the address or the inviting user is not usable.
|
||||
pub async fn create_invite(
|
||||
State(st): State<PlatformState>,
|
||||
Path(tenant_id): Path<String>,
|
||||
Json(body): Json<CreateInvite>,
|
||||
) -> Result<(StatusCode, Json<InviteView>), StatusCode> {
|
||||
let target = ObjectId::parse_str(body.target_id.trim()).map_err(|_| StatusCode::NOT_FOUND)?;
|
||||
// Looked up without creating anything: an unknown tenant just has no target.
|
||||
let lookup = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
|
||||
let stored = lookup
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "_id": target })
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
if stored.supplier.is_none() {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
let (Some(email), Some(invited_by)) = (
|
||||
normalized_email(&body.email),
|
||||
normalized_actor(&body.invited_by),
|
||||
) else {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
};
|
||||
let now = Utc::now();
|
||||
let invite = SupplierInvite::new(target.to_hex(), email, invited_by, now);
|
||||
let db = st
|
||||
.agent
|
||||
.db_pool
|
||||
.for_tenant_id(&tenant_id)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
invites(&db).insert_one(&invite).await.map_err(internal)?;
|
||||
Ok((
|
||||
StatusCode::CREATED,
|
||||
Json(InviteView::of(invite, now, Vec::new())),
|
||||
))
|
||||
}
|
||||
|
||||
/// `GET /api/v1/platform/tenants/{id}/supplier-invites[?target=<id>]`: the
|
||||
/// tenant's invites, newest first, each with its state.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 500 when the database cannot be read.
|
||||
pub async fn list_invites(
|
||||
State(st): State<PlatformState>,
|
||||
Path(tenant_id): Path<String>,
|
||||
Query(filter): Query<InviteFilter>,
|
||||
) -> Result<Json<Vec<InviteView>>, StatusCode> {
|
||||
let db = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
|
||||
let query = match filter.target.as_deref().map(str::trim) {
|
||||
Some(target) if !target.is_empty() => doc! { "target_id": target },
|
||||
_ => doc! {},
|
||||
};
|
||||
let now = Utc::now();
|
||||
let listed: Vec<SupplierInvite> = invites(&db)
|
||||
.find(query)
|
||||
.sort(doc! { "created_at": -1, "_id": -1 })
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.try_collect()
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
Ok(Json(views(&db, listed, now).await?))
|
||||
}
|
||||
|
||||
/// `POST /api/v1/platform/tenants/{id}/supplier-invites/{invite}/withdraw`:
|
||||
/// withdraw an invite, so its link allows nothing more. Withdrawing one
|
||||
/// already withdrawn keeps the first withdrawal.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 404 when the tenant has no such invite; 422 without a usable
|
||||
/// `withdrawn_by`.
|
||||
pub async fn withdraw_invite(
|
||||
State(st): State<PlatformState>,
|
||||
Path((tenant_id, invite_id)): Path<(String, String)>,
|
||||
Json(body): Json<WithdrawInvite>,
|
||||
) -> Result<Json<InviteView>, StatusCode> {
|
||||
let id = ObjectId::parse_str(invite_id.trim()).map_err(|_| StatusCode::NOT_FOUND)?;
|
||||
let by = normalized_actor(&body.withdrawn_by).ok_or(StatusCode::UNPROCESSABLE_ENTITY)?;
|
||||
let db = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
|
||||
let now = Utc::now();
|
||||
// Only an invite not yet withdrawn is changed; either way it is read back.
|
||||
invites(&db)
|
||||
.update_one(
|
||||
doc! { "_id": id, "withdrawn_at": null },
|
||||
doc! { "$set": {
|
||||
"withdrawn_at": BsonDateTime::from(now),
|
||||
"withdrawn_by": by,
|
||||
} },
|
||||
)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
let invite = invites(&db)
|
||||
.find_one(doc! { "_id": id })
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let mut viewed = views(&db, vec![invite], now).await?;
|
||||
viewed
|
||||
.pop()
|
||||
.map(Json)
|
||||
.ok_or(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
}
|
||||
|
||||
/// `GET /api/v1/platform/tenants/{id}/supplier-invites/{invite}/supplier-view`:
|
||||
/// what the supplier's upload page shows, while the invite is valid.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 404 when there is no such invite, or its component is gone or no longer a
|
||||
/// supplier component; 410 with the code `expired` or `withdrawn`.
|
||||
pub async fn supplier_view(
|
||||
State(st): State<PlatformState>,
|
||||
Path((tenant_id, invite_id)): Path<(String, String)>,
|
||||
) -> Result<Json<SupplierPage>, UploadRefusal> {
|
||||
let db = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
|
||||
let invite = open_invite(&db, &invite_id).await?;
|
||||
let target = invite_target(&db, &invite).await?;
|
||||
let sbom = current_sbom(&target).map(str::to_string);
|
||||
let listed: Vec<UploadView> = uploads(&db)
|
||||
.find(doc! { "invite_id": invite.id.to_hex() })
|
||||
.sort(doc! { "uploaded_at": -1, "_id": -1 })
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.try_collect::<Vec<SupplierUpload>>()
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.into_iter()
|
||||
.map(|u| UploadView::of(u, sbom.as_deref()))
|
||||
.collect();
|
||||
let (product, version, csaf_provider) = target
|
||||
.supplier
|
||||
.map(|s| (s.product, s.version, s.csaf_provider))
|
||||
.unwrap_or_default();
|
||||
Ok(Json(SupplierPage {
|
||||
component: target.name,
|
||||
product,
|
||||
version,
|
||||
expires_at: invite.expires_at.to_chrono(),
|
||||
csaf_provider,
|
||||
uploads: listed,
|
||||
}))
|
||||
}
|
||||
|
||||
/// The component `invite` is for, while it is a supplier component.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 404 when it is gone, or names no supplier any more (the customer removed
|
||||
/// it in the target editor).
|
||||
async fn invite_target(
|
||||
db: &Database,
|
||||
invite: &SupplierInvite,
|
||||
) -> Result<OnboardedTarget, UploadRefusal> {
|
||||
let id = ObjectId::parse_str(&invite.target_id).map_err(|_| StatusCode::NOT_FOUND)?;
|
||||
Ok(db
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "_id": id, "supplier": { "$ne": null } })
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?)
|
||||
}
|
||||
|
||||
/// `POST /api/v1/platform/tenants/{id}/supplier-invites/{invite}/sboms`: the
|
||||
/// supplier uploads an SBOM through its invite.
|
||||
///
|
||||
/// Multipart fields: `file` (exactly one) and, optionally, `csaf_provider`
|
||||
/// (the supplier's `provider-metadata.json`, an https URL). An accepted SBOM
|
||||
/// becomes the component's SBOM, replacing the one before, exactly as a
|
||||
/// customer's upload does, and a scan starts. A CSAF provider given with it
|
||||
/// becomes the component's when it has none yet. Every upload is recorded,
|
||||
/// refused ones with their code; the answer is the record (201).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// - 404: no such invite, or its component is gone or no longer a supplier
|
||||
/// component.
|
||||
/// - 410 (`expired`, `withdrawn`): the invite allows nothing more.
|
||||
/// - 403 (`read_only`): the workspace takes no uploads now; 503 when the
|
||||
/// registry cannot say.
|
||||
/// - 429 (`too_many_uploads`): [`MAX_UPLOADS_PER_DAY`] reached.
|
||||
/// - 400: no file, or more than one.
|
||||
/// - 413 (`too_large`) and 422 (`too_many_components`, `empty`,
|
||||
/// `unknown_format`, `malformed`, `csaf_provider`): refused, and recorded.
|
||||
pub async fn upload_through_invite(
|
||||
State(st): State<PlatformState>,
|
||||
Path((tenant_id, invite_id)): Path<(String, String)>,
|
||||
mut multipart: Multipart,
|
||||
) -> Result<(StatusCode, Json<UploadView>), UploadRefusal> {
|
||||
// Nothing is created before the invite is known to be valid.
|
||||
let lookup = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
|
||||
let invite = open_invite(&lookup, &invite_id).await?;
|
||||
accepts_writes(&st.agent, &tenant_id).await?;
|
||||
let day_ago = BsonDateTime::from(Utc::now() - chrono::Duration::days(1));
|
||||
let recent = uploads(&lookup)
|
||||
.count_documents(
|
||||
doc! { "invite_id": invite.id.to_hex(), "uploaded_at": { "$gte": day_ago } },
|
||||
)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
if recent >= MAX_UPLOADS_PER_DAY {
|
||||
return Err(UploadRefusal::because(
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"too many uploads through this invite today",
|
||||
"too_many_uploads",
|
||||
));
|
||||
}
|
||||
let target = invite_target(&lookup, &invite).await?;
|
||||
let db = st
|
||||
.agent
|
||||
.db_pool
|
||||
.for_tenant_id(&tenant_id)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
|
||||
let mut csaf_provider = None;
|
||||
let mut filename = String::from("sbom");
|
||||
let mut stored: Option<StoredUpload> = None;
|
||||
while let Some(mut field) = multipart.next_field().await.map_err(|e| e.status())? {
|
||||
match field.name().unwrap_or("") {
|
||||
"csaf_provider" => {
|
||||
let url = field.text().await.map_err(|e| e.status())?;
|
||||
csaf_provider = Some(url.trim().to_string()).filter(|u| !u.is_empty());
|
||||
}
|
||||
"file" => {
|
||||
if stored.is_some() {
|
||||
return Err(StatusCode::BAD_REQUEST.into());
|
||||
}
|
||||
filename = shown_filename(field.file_name().unwrap_or_default());
|
||||
let dest = crate::targets::upload_dest(&st.agent, &invite.target_id, &filename)
|
||||
.map_err(internal)?;
|
||||
let mut upload = StoredUpload::new(dest, filename.clone());
|
||||
match stream_to_disk(&mut field, &upload.path, MAX_SBOM_BYTES).await {
|
||||
Ok(size) => upload.size = size,
|
||||
Err(StatusCode::PAYLOAD_TOO_LARGE) => {
|
||||
let refusal = UploadRefusal::because(
|
||||
StatusCode::PAYLOAD_TOO_LARGE,
|
||||
"the SBOM is larger than 20 MiB",
|
||||
"too_large",
|
||||
);
|
||||
return Err(refused(&db, &invite, &filename, refusal).await);
|
||||
}
|
||||
Err(status) => return Err(status.into()),
|
||||
}
|
||||
stored = Some(upload);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let upload = stored.ok_or(StatusCode::BAD_REQUEST)?;
|
||||
if csaf_provider
|
||||
.as_deref()
|
||||
.is_some_and(|url| !is_https_url(url))
|
||||
{
|
||||
let refusal = UploadRefusal::because(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"the CSAF provider must be an https URL",
|
||||
"csaf_provider",
|
||||
);
|
||||
return Err(refused(&db, &invite, &filename, refusal).await);
|
||||
}
|
||||
let attached = match attach_upload(&db, &target, ArtifactKind::SupplierSbom, None, upload).await
|
||||
{
|
||||
Ok(attached) => attached,
|
||||
Err(refusal) => return Err(refused(&db, &invite, &filename, refusal).await),
|
||||
};
|
||||
// Only a component without one takes the supplier's provider: one the
|
||||
// customer set stays. The upload keeps what the supplier gave either way.
|
||||
let unset = target
|
||||
.supplier
|
||||
.clone()
|
||||
.filter(|supplier| supplier.csaf_provider.is_none());
|
||||
if let (Some(url), Some(mut supplier)) = (&csaf_provider, unset) {
|
||||
supplier.csaf_provider = Some(url.clone());
|
||||
let set = mongodb::bson::to_bson(&supplier).map_err(internal)?;
|
||||
db.onboarded_targets()
|
||||
.update_one(
|
||||
doc! { "_id": target.id },
|
||||
doc! { "$set": { "supplier": set } },
|
||||
)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
refresh_supplier_csaf(&st.agent, &tenant_id, Some(&supplier));
|
||||
}
|
||||
let record = SupplierUpload {
|
||||
id: ObjectId::new(),
|
||||
invite_id: invite.id.to_hex(),
|
||||
target_id: invite.target_id.clone(),
|
||||
uploaded_at: BsonDateTime::now(),
|
||||
filename,
|
||||
accepted: true,
|
||||
code: None,
|
||||
summary: attached.summary,
|
||||
artifact_id: Some(attached.artifact_id.clone()),
|
||||
csaf_provider,
|
||||
};
|
||||
uploads(&db).insert_one(&record).await.map_err(internal)?;
|
||||
let (agent, target_id) = (st.agent.clone(), invite.target_id.clone());
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = agent
|
||||
.run_target_scan(&tenant_id, &target_id, ScanTrigger::NewContent)
|
||||
.await
|
||||
{
|
||||
tracing::error!(target_id, "scan after a supplier upload failed: {e}");
|
||||
}
|
||||
});
|
||||
let current = Some(attached.artifact_id.as_str());
|
||||
Ok((StatusCode::CREATED, Json(UploadView::of(record, current))))
|
||||
}
|
||||
|
||||
/// `POST /api/v1/platform/tenants/{id}/supplier-invites/{invite}/sboms/check`:
|
||||
/// what the supplier's page shows of a file before it is uploaded, through a
|
||||
/// valid invite: the same check as `POST /api/v1/supplier-sboms/check`.
|
||||
/// Nothing is stored or recorded.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 404 and 410 as for [`upload_through_invite`]; the check's own refusals.
|
||||
pub async fn check_through_invite(
|
||||
State(st): State<PlatformState>,
|
||||
Path((tenant_id, invite_id)): Path<(String, String)>,
|
||||
multipart: Multipart,
|
||||
) -> Result<Json<super::ApiResponse<SupplierSbomSummary>>, UploadRefusal> {
|
||||
let db = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
|
||||
let invite = open_invite(&db, &invite_id).await?;
|
||||
invite_target(&db, &invite).await?;
|
||||
super::onboarding::check_supplier_sbom(multipart).await
|
||||
}
|
||||
|
||||
/// Record `refusal` of an upload of `filename` through `invite`, when it has a
|
||||
/// code the supplier can act on, and hand it back. A failed record is logged:
|
||||
/// the refusal stands either way.
|
||||
async fn refused(
|
||||
db: &Database,
|
||||
invite: &SupplierInvite,
|
||||
filename: &str,
|
||||
refusal: UploadRefusal,
|
||||
) -> UploadRefusal {
|
||||
if let Some(code) = refusal.code() {
|
||||
let record = SupplierUpload::refused(invite, filename, code);
|
||||
if let Err(e) = uploads(db).insert_one(&record).await {
|
||||
tracing::warn!(invite_id = %invite.id, "refused supplier upload not recorded: {e}");
|
||||
}
|
||||
}
|
||||
refusal
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn invite_at(now: DateTime<Utc>) -> SupplierInvite {
|
||||
SupplierInvite::new("t1".into(), "a@b.example".into(), "u1".into(), now)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invite_is_active_for_ninety_days() {
|
||||
let now = Utc::now();
|
||||
let invite = invite_at(now);
|
||||
assert_eq!(
|
||||
invite.expires_at.to_chrono() - invite.created_at.to_chrono(),
|
||||
chrono::Duration::days(90)
|
||||
);
|
||||
assert_eq!(invite.state(now), InviteState::Active);
|
||||
let last = now + chrono::Duration::days(90) - chrono::Duration::seconds(1);
|
||||
assert_eq!(invite.state(last), InviteState::Active);
|
||||
assert_eq!(
|
||||
invite.state(now + chrono::Duration::days(90)),
|
||||
InviteState::Expired
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_withdrawn_invite_stays_withdrawn_after_it_expires() {
|
||||
let now = Utc::now();
|
||||
let mut invite = invite_at(now);
|
||||
invite.withdrawn_at = Some(now.into());
|
||||
assert_eq!(invite.state(now), InviteState::Withdrawn);
|
||||
assert_eq!(
|
||||
invite.state(now + chrono::Duration::days(200)),
|
||||
InviteState::Withdrawn
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_address_is_kept_in_lower_case_and_nonsense_is_refused() {
|
||||
assert_eq!(
|
||||
normalized_email(" SBOM@Antrieb.Example "),
|
||||
Some("sbom@antrieb.example".into())
|
||||
);
|
||||
for bad in [
|
||||
"",
|
||||
"no-at.example",
|
||||
"@antrieb.example",
|
||||
"a@localhost",
|
||||
"a@.example",
|
||||
"a@example.",
|
||||
"a@b@c.example",
|
||||
"a b@c.example",
|
||||
] {
|
||||
assert_eq!(normalized_email(bad), None, "{bad}");
|
||||
}
|
||||
let long = format!("{}@b.example", "a".repeat(250));
|
||||
assert_eq!(normalized_email(&long), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_upload_is_shown_by_its_file_name_only() {
|
||||
assert_eq!(shown_filename("../../dr4.cdx.json"), "dr4.cdx.json");
|
||||
assert_eq!(shown_filename("C:\\sbom\\dr4.json"), "dr4.json");
|
||||
assert_eq!(shown_filename(" "), "sbom");
|
||||
assert_eq!(shown_filename("dir/"), "sbom");
|
||||
assert_eq!(shown_filename(&"ä".repeat(300)).chars().count(), 200);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_actor_is_required_and_bounded() {
|
||||
assert_eq!(normalized_actor(" u-1 "), Some("u-1".into()));
|
||||
assert_eq!(normalized_actor(" "), None);
|
||||
assert_eq!(normalized_actor(&"u".repeat(201)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invite_round_trips_through_bson() {
|
||||
let invite = invite_at(Utc::now());
|
||||
let stored = mongodb::bson::to_document(&invite).expect("bson");
|
||||
assert!(stored.get_datetime("expires_at").is_ok(), "a BSON date");
|
||||
let back: SupplierInvite = mongodb::bson::from_document(stored).expect("back");
|
||||
assert_eq!(back, invite);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,823 @@
|
||||
//! The supply chain (#1050, #1051): what a workspace's products are made of,
|
||||
//! as a graph for the dashboard to draw.
|
||||
//!
|
||||
//! Suppliers deliver components (targets); components are part of assemblies
|
||||
//! and products (the registry's product projects); assemblies are part of
|
||||
//! products. A component can be part of several products, so the graph is a
|
||||
//! DAG, not a tree. Every component and project carries its open CVEs.
|
||||
|
||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
|
||||
use axum::extract::Extension;
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use chrono::{DateTime, Utc};
|
||||
use mongodb::bson::{doc, oid::ObjectId};
|
||||
use serde::Serialize;
|
||||
|
||||
use compliance_core::cve_groups::SeverityCounts;
|
||||
use compliance_core::models::{
|
||||
ArtifactKind, CveAlert, OnboardedTarget, Project, ProjectKind, ProjectLevel, TargetType,
|
||||
};
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use super::dto::{collect_cursor_async, tenant_db, AgentExt};
|
||||
use super::machine::{open_alerts, open_counts};
|
||||
use super::offers::SbomOffer;
|
||||
use super::projects::tenant_projects;
|
||||
use super::supplier_invites::SupplierInvite;
|
||||
use super::ApiResponse;
|
||||
use crate::database::Database;
|
||||
|
||||
/// The supply chain: its nodes and the edges between them.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct SupplyChain {
|
||||
/// Suppliers, then components, then projects.
|
||||
pub nodes: Vec<ChainNode>,
|
||||
/// From supplier to component, component to project, project to the
|
||||
/// project above it.
|
||||
pub edges: Vec<ChainEdge>,
|
||||
}
|
||||
|
||||
/// What a node stands for.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum NodeKind {
|
||||
/// A supplier, by the name a target gives it.
|
||||
Supplier,
|
||||
/// A component: one of the workspace's targets.
|
||||
Target,
|
||||
/// A product project: a family, product or assembly.
|
||||
Project,
|
||||
}
|
||||
|
||||
/// One node of the supply chain.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct ChainNode {
|
||||
/// Stable across calls, for the arrangement to be kept by:
|
||||
/// `supplier:<name>`, `target:<id>` or `project:<id>`.
|
||||
pub key: String,
|
||||
pub kind: NodeKind,
|
||||
pub name: String,
|
||||
/// A component's type.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub target_type: Option<TargetType>,
|
||||
/// A component bought in from a supplier, rather than the workspace's own.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub bought: bool,
|
||||
/// A project's place in the hierarchy.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub level: Option<ProjectLevel>,
|
||||
/// Open CVEs: a component's own; a project's, the sum over the distinct
|
||||
/// components beneath it. None for a supplier.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub open: Option<SeverityCounts>,
|
||||
}
|
||||
|
||||
/// What an edge means.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum EdgeKind {
|
||||
/// A supplier delivers the component.
|
||||
Supplies,
|
||||
/// The component or project is part of the project.
|
||||
PartOf,
|
||||
}
|
||||
|
||||
/// How a supplier's SBOM reaches its component.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum DeliveryKind {
|
||||
/// A connected supplier's release, accepted into the component (#1028):
|
||||
/// each version it publishes arrives by itself.
|
||||
Release,
|
||||
/// The supplier uploads it through an active invite link (#1027).
|
||||
Invite,
|
||||
/// The release it came by has ended (the supplier ended it, or the
|
||||
/// connection ended); the version last delivered stays.
|
||||
ReleaseEnded,
|
||||
/// Someone in the workspace uploaded it.
|
||||
Upload,
|
||||
/// No SBOM yet.
|
||||
Missing,
|
||||
}
|
||||
|
||||
/// A supplier's delivery to its component.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct Delivery {
|
||||
pub how: DeliveryKind,
|
||||
/// The version in use, as the workspace names it.
|
||||
pub version: Option<String>,
|
||||
/// When the current SBOM arrived.
|
||||
pub at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
/// One edge of the supply chain, `from` and `to` by node key.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct ChainEdge {
|
||||
pub from: String,
|
||||
pub to: String,
|
||||
pub kind: EdgeKind,
|
||||
/// How the SBOM arrives, on a supplier's edge.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub delivery: Option<Delivery>,
|
||||
}
|
||||
|
||||
fn target_key(id: &str) -> String {
|
||||
format!("target:{id}")
|
||||
}
|
||||
|
||||
fn project_key(id: &str) -> String {
|
||||
format!("project:{id}")
|
||||
}
|
||||
|
||||
/// The supplier `target` names, trimmed; `None` for one of its own.
|
||||
fn supplier_name(target: &OnboardedTarget) -> Option<&str> {
|
||||
target
|
||||
.supplier
|
||||
.as_ref()
|
||||
.map(|s| s.name.trim())
|
||||
.filter(|name| !name.is_empty())
|
||||
}
|
||||
|
||||
/// What brings a component's new versions by themselves, if anything does.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Feed {
|
||||
/// An accepted release of a connected supplier.
|
||||
Release,
|
||||
/// An active invite link.
|
||||
Invite,
|
||||
/// A release that delivered, then ended.
|
||||
ReleaseEnded,
|
||||
}
|
||||
|
||||
/// How `target`'s SBOM arrives from its supplier: by its `feed`, else as an
|
||||
/// upload once there is one. An ended release names the SBOM it left.
|
||||
fn delivery(target: &OnboardedTarget, feed: Option<Feed>) -> Delivery {
|
||||
let sbom = target
|
||||
.artifacts
|
||||
.iter()
|
||||
.filter(|a| a.kind == ArtifactKind::SupplierSbom)
|
||||
.max_by_key(|a| a.ingested_at);
|
||||
let how = match (feed, sbom) {
|
||||
(Some(Feed::Release), _) => DeliveryKind::Release,
|
||||
(Some(Feed::Invite), _) => DeliveryKind::Invite,
|
||||
(Some(Feed::ReleaseEnded), Some(_)) => DeliveryKind::ReleaseEnded,
|
||||
(_, Some(_)) => DeliveryKind::Upload,
|
||||
(_, None) => DeliveryKind::Missing,
|
||||
};
|
||||
Delivery {
|
||||
how,
|
||||
version: target.supplier.as_ref().and_then(|s| s.version.clone()),
|
||||
at: sbom.and_then(|a| a.ingested_at),
|
||||
}
|
||||
}
|
||||
|
||||
/// The supply chain of `targets` in `projects`.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `targets` - the workspace's targets, not archived, in display order
|
||||
/// * `projects` - its projects; topics are left out
|
||||
/// * `open` - each target's open CVEs, by id
|
||||
/// * `feeds` - what brings each target's new versions, by id, if anything
|
||||
pub fn supply_chain(
|
||||
targets: &[OnboardedTarget],
|
||||
projects: &[Project],
|
||||
open: &HashMap<String, SeverityCounts>,
|
||||
feeds: &HashMap<String, Feed>,
|
||||
) -> SupplyChain {
|
||||
let products: Vec<&Project> = projects
|
||||
.iter()
|
||||
.filter(|p| p.kind == ProjectKind::Product)
|
||||
.collect();
|
||||
let known: HashSet<&str> = products.iter().map(|p| p.id.as_str()).collect();
|
||||
let mut nodes = Vec::new();
|
||||
let mut edges = Vec::new();
|
||||
|
||||
let mut suppliers = BTreeSet::new();
|
||||
for t in targets {
|
||||
if let Some(name) = supplier_name(t) {
|
||||
suppliers.insert(name);
|
||||
}
|
||||
}
|
||||
nodes.extend(suppliers.into_iter().map(|name| ChainNode {
|
||||
key: format!("supplier:{name}"),
|
||||
kind: NodeKind::Supplier,
|
||||
name: name.to_string(),
|
||||
target_type: None,
|
||||
bought: false,
|
||||
level: None,
|
||||
open: None,
|
||||
}));
|
||||
|
||||
// The targets directly in each project, by id.
|
||||
let mut direct: HashMap<&str, Vec<String>> = HashMap::new();
|
||||
for t in targets {
|
||||
let Some(id) = t.id.map(|o: ObjectId| o.to_hex()) else {
|
||||
continue;
|
||||
};
|
||||
let key = target_key(&id);
|
||||
if let Some(name) = supplier_name(t) {
|
||||
edges.push(ChainEdge {
|
||||
from: format!("supplier:{name}"),
|
||||
to: key.clone(),
|
||||
kind: EdgeKind::Supplies,
|
||||
delivery: Some(delivery(t, feeds.get(&id).copied())),
|
||||
});
|
||||
}
|
||||
for project in t.project_ids.iter().filter(|p| known.contains(p.as_str())) {
|
||||
edges.push(ChainEdge {
|
||||
from: key.clone(),
|
||||
to: project_key(project),
|
||||
kind: EdgeKind::PartOf,
|
||||
delivery: None,
|
||||
});
|
||||
direct.entry(project.as_str()).or_default().push(id.clone());
|
||||
}
|
||||
nodes.push(ChainNode {
|
||||
key,
|
||||
kind: NodeKind::Target,
|
||||
name: t.name.clone(),
|
||||
target_type: Some(t.target_type),
|
||||
bought: t.supplier.is_some(),
|
||||
level: None,
|
||||
open: Some(open.get(&id).copied().unwrap_or_default()),
|
||||
});
|
||||
}
|
||||
|
||||
// Each project's children: the projects whose parent it is.
|
||||
let mut children: HashMap<&str, Vec<&str>> = HashMap::new();
|
||||
for p in &products {
|
||||
if let Some(parent) = p
|
||||
.parent_id
|
||||
.as_deref()
|
||||
.filter(|id| known.contains(id) && *id != p.id)
|
||||
{
|
||||
children.entry(parent).or_default().push(&p.id);
|
||||
edges.push(ChainEdge {
|
||||
from: project_key(&p.id),
|
||||
to: project_key(parent),
|
||||
kind: EdgeKind::PartOf,
|
||||
delivery: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for p in &products {
|
||||
// Every target beneath the project, once, however it is reached.
|
||||
let mut seen: HashSet<&str> = HashSet::new();
|
||||
let mut beneath: HashSet<&String> = HashSet::new();
|
||||
let mut queue = vec![p.id.as_str()];
|
||||
while let Some(cur) = queue.pop() {
|
||||
if !seen.insert(cur) {
|
||||
continue;
|
||||
}
|
||||
beneath.extend(direct.get(cur).into_iter().flatten());
|
||||
queue.extend(children.get(cur).into_iter().flatten().copied());
|
||||
}
|
||||
let sum = beneath
|
||||
.into_iter()
|
||||
.filter_map(|id| open.get(id))
|
||||
.fold(SeverityCounts::default(), |sum, c| sum.plus(*c));
|
||||
nodes.push(ChainNode {
|
||||
key: project_key(&p.id),
|
||||
kind: NodeKind::Project,
|
||||
name: p.name.clone(),
|
||||
target_type: None,
|
||||
bought: false,
|
||||
level: Some(p.level.unwrap_or(ProjectLevel::Product)),
|
||||
open: Some(sum),
|
||||
});
|
||||
}
|
||||
|
||||
SupplyChain { nodes, edges }
|
||||
}
|
||||
|
||||
/// A document of a product's box: one of the store's documents of the
|
||||
/// product, opened in the portal.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct BoxDocument {
|
||||
/// The store's id of the document.
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub filename: String,
|
||||
pub content_type: Option<String>,
|
||||
pub size_bytes: Option<u64>,
|
||||
/// Internal to the workspace rather than published with the product.
|
||||
pub internal: bool,
|
||||
pub created_at: Option<DateTime<Utc>>,
|
||||
/// Where the portal shows it, below the portal's address.
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
/// What a product's box shows besides its graph (#1054): the project's
|
||||
/// description and its documents in the portal's Dokumentenablage.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct ProjectDocuments {
|
||||
/// The project's description, as the portal keeps it.
|
||||
pub description: String,
|
||||
/// Its documents, newest first.
|
||||
pub documents: Vec<BoxDocument>,
|
||||
/// Where the portal's store is, below the portal's address, for adding
|
||||
/// one; empty without a registry.
|
||||
pub store_path: String,
|
||||
}
|
||||
|
||||
/// The documents of `store` that belong to product project `project`, newest
|
||||
/// first, with where the portal of workspace `slug` shows each. Legal web
|
||||
/// documents and BreakPilot's deliveries belong to no product.
|
||||
fn box_documents(
|
||||
store: Vec<crate::registry::StoreDocument>,
|
||||
project: &str,
|
||||
slug: &str,
|
||||
) -> Vec<BoxDocument> {
|
||||
let slug = urlencoding::encode(slug);
|
||||
let mut documents: Vec<BoxDocument> = store
|
||||
.into_iter()
|
||||
.filter(|d| d.project_ids.iter().any(|p| p == project))
|
||||
.filter_map(|d| {
|
||||
let internal = match d.area.as_deref() {
|
||||
Some("product_public") => false,
|
||||
Some("internal") => true,
|
||||
_ => return None,
|
||||
};
|
||||
Some(BoxDocument {
|
||||
path: format!("/{slug}/dokumente/{}/original", urlencoding::encode(&d.id)),
|
||||
id: d.id,
|
||||
title: d.title,
|
||||
filename: d.filename,
|
||||
content_type: d.content_type,
|
||||
size_bytes: d.size_bytes,
|
||||
internal,
|
||||
created_at: d.created_at,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
documents.sort_by_key(|d| std::cmp::Reverse(d.created_at));
|
||||
documents
|
||||
}
|
||||
|
||||
/// A product's description and documents, for its box on the Lieferkette.
|
||||
///
|
||||
/// The description is the project's, and the documents are those of the
|
||||
/// portal's Dokumentenablage that belong to the project (published with the
|
||||
/// product or internal), newest first. Each names where the portal shows it.
|
||||
/// Prüfwerk keeps no copy. Without a registry (development) there is
|
||||
/// nothing to show.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/supply-chain/projects/{id}/documents",
|
||||
tag = "Targets",
|
||||
params(("id" = String, Path, description = "The product project's id")),
|
||||
responses(
|
||||
(status = 200, description = "Its description and documents (`data`)"),
|
||||
(status = 404, description = "No product project of the workspace"),
|
||||
(status = 503, description = "The registry cannot be asked"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(project_id = %id))]
|
||||
pub async fn project_documents(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
axum::extract::Path(id): axum::extract::Path<String>,
|
||||
) -> Result<Json<ApiResponse<ProjectDocuments>>, StatusCode> {
|
||||
let Some(registry) = agent.registry.as_ref() else {
|
||||
return Ok(Json(ApiResponse {
|
||||
data: ProjectDocuments {
|
||||
description: String::new(),
|
||||
documents: Vec::new(),
|
||||
store_path: String::new(),
|
||||
},
|
||||
total: None,
|
||||
page: None,
|
||||
}));
|
||||
};
|
||||
let ctx = &tenant.0;
|
||||
let project = tenant_projects(&agent, &ctx.tenant_id)
|
||||
.await?
|
||||
.into_iter()
|
||||
.find(|p| p.id == id && p.kind == ProjectKind::Product)
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let store = registry.list_store(&ctx.tenant_id).await.map_err(|e| {
|
||||
tracing::error!(tenant_id = %ctx.tenant_id, "store list unavailable: {e}");
|
||||
StatusCode::SERVICE_UNAVAILABLE
|
||||
})?;
|
||||
Ok(Json(ApiResponse {
|
||||
data: ProjectDocuments {
|
||||
description: project.description,
|
||||
documents: box_documents(store, &id, &ctx.tenant_slug),
|
||||
store_path: format!("/{}/dokumente", urlencoding::encode(&ctx.tenant_slug)),
|
||||
},
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Without a registry (development), every project a target names, as a
|
||||
/// product named by its id, as the machine page names it.
|
||||
fn unregistered_projects(targets: &[OnboardedTarget]) -> Vec<Project> {
|
||||
targets
|
||||
.iter()
|
||||
.flat_map(|t| t.project_ids.iter())
|
||||
.collect::<BTreeSet<_>>()
|
||||
.into_iter()
|
||||
.map(|id| Project {
|
||||
id: id.clone(),
|
||||
name: id.clone(),
|
||||
kind: ProjectKind::Product,
|
||||
description: String::new(),
|
||||
level: None,
|
||||
parent_id: None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The targets among `ids` with a supplier invite that is neither withdrawn
|
||||
/// nor expired.
|
||||
async fn invited_targets(db: &Database, ids: &[String]) -> Result<HashSet<String>, StatusCode> {
|
||||
let found = db
|
||||
.inner()
|
||||
.collection::<SupplierInvite>(SupplierInvite::COLLECTION)
|
||||
.distinct(
|
||||
"target_id",
|
||||
doc! {
|
||||
"target_id": { "$in": ids },
|
||||
"withdrawn_at": null,
|
||||
"expires_at": { "$gt": mongodb::bson::DateTime::now() },
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
Ok(found
|
||||
.into_iter()
|
||||
.filter_map(|id| id.as_str().map(str::to_string))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// The targets among `ids` that offers of connected suppliers deliver into,
|
||||
/// in state `state`; for an ended one, only if it delivered a version.
|
||||
async fn offered_targets(
|
||||
db: &Database,
|
||||
ids: &[String],
|
||||
state: &str,
|
||||
) -> Result<HashSet<String>, StatusCode> {
|
||||
let mut filter = doc! { "target_id": { "$in": ids }, "state": state };
|
||||
if state == "ended" {
|
||||
filter.insert("delivered_label", doc! { "$ne": null });
|
||||
}
|
||||
let found = db
|
||||
.inner()
|
||||
.collection::<SbomOffer>(SbomOffer::COLLECTION)
|
||||
.distinct("target_id", filter)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
Ok(found
|
||||
.into_iter()
|
||||
.filter_map(|id| id.as_str().map(str::to_string))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// What brings each of the targets `ids` its new versions: an accepted
|
||||
/// release before an invite link, and either before a release that ended.
|
||||
async fn feeds(db: &Database, ids: &[String]) -> Result<HashMap<String, Feed>, StatusCode> {
|
||||
let mut feeds = HashMap::new();
|
||||
for (found, feed) in [
|
||||
(offered_targets(db, ids, "ended").await?, Feed::ReleaseEnded),
|
||||
(invited_targets(db, ids).await?, Feed::Invite),
|
||||
(offered_targets(db, ids, "accepted").await?, Feed::Release),
|
||||
] {
|
||||
feeds.extend(found.into_iter().map(|id| (id, feed)));
|
||||
}
|
||||
Ok(feeds)
|
||||
}
|
||||
|
||||
/// The workspace's supply chain.
|
||||
///
|
||||
/// Its suppliers, components (targets) and product projects (families,
|
||||
/// products and assemblies) as nodes, and as edges: supplier to component,
|
||||
/// with how its SBOM arrives; component to the projects it is part of;
|
||||
/// project to the project above it. A component can be part of several
|
||||
/// projects. Each component carries its open CVEs, each project the sum over
|
||||
/// the distinct components beneath it. Archived targets and topic projects
|
||||
/// are left out.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/supply-chain",
|
||||
tag = "Targets",
|
||||
responses(
|
||||
(status = 200, description = "The supply chain (`data`: `nodes` and `edges`)"),
|
||||
(status = 503, description = "The registry cannot be asked"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn get_supply_chain(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
) -> Result<Json<ApiResponse<SupplyChain>>, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let targets: Vec<OnboardedTarget> = collect_cursor_async(
|
||||
db.onboarded_targets()
|
||||
.find(doc! { "archived_at": null })
|
||||
.sort(doc! { "name": 1 })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
|
||||
)
|
||||
.await;
|
||||
let projects = match agent.registry {
|
||||
Some(_) => tenant_projects(&agent, &tenant.0.tenant_id).await?,
|
||||
None => unregistered_projects(&targets),
|
||||
};
|
||||
let ids: Vec<String> = targets
|
||||
.iter()
|
||||
.filter_map(|t| t.id.map(|o: ObjectId| o.to_hex()))
|
||||
.collect();
|
||||
let alerts = open_alerts(&db, &ids).await?;
|
||||
let mut by_target: HashMap<&str, Vec<&CveAlert>> = HashMap::new();
|
||||
for alert in &alerts {
|
||||
by_target
|
||||
.entry(alert.repo_id.as_str())
|
||||
.or_default()
|
||||
.push(alert);
|
||||
}
|
||||
let open: HashMap<String, SeverityCounts> = by_target
|
||||
.into_iter()
|
||||
.map(|(id, alerts)| (id.to_string(), open_counts(alerts)))
|
||||
.collect();
|
||||
let feeds = feeds(&db, &ids).await?;
|
||||
Ok(Json(ApiResponse {
|
||||
data: supply_chain(&targets, &projects, &open, &feeds),
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::{Artifact, SupplierComponent};
|
||||
|
||||
fn target(name: &str, supplier: Option<&str>, projects: &[&str]) -> OnboardedTarget {
|
||||
let mut t = OnboardedTarget::new(name.into(), TargetType::FirmwareRtos);
|
||||
t.id = Some(ObjectId::new());
|
||||
t.supplier = supplier.map(|s| SupplierComponent {
|
||||
name: format!(" {s} "),
|
||||
product: None,
|
||||
version: Some("1.4.0".into()),
|
||||
csaf_provider: None,
|
||||
});
|
||||
t.project_ids = projects.iter().map(|p| p.to_string()).collect();
|
||||
t
|
||||
}
|
||||
|
||||
fn project(id: &str, level: ProjectLevel, parent: Option<&str>) -> Project {
|
||||
Project {
|
||||
id: id.into(),
|
||||
name: format!("Projekt {id}"),
|
||||
kind: ProjectKind::Product,
|
||||
description: String::new(),
|
||||
level: Some(level),
|
||||
parent_id: parent.map(String::from),
|
||||
}
|
||||
}
|
||||
|
||||
fn id(t: &OnboardedTarget) -> String {
|
||||
t.id.unwrap().to_hex()
|
||||
}
|
||||
|
||||
fn counts(critical: usize, high: usize, medium: usize) -> SeverityCounts {
|
||||
SeverityCounts {
|
||||
critical,
|
||||
high,
|
||||
medium,
|
||||
..SeverityCounts::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A drive and a sensor in an assembly of product p1; a panel and the
|
||||
/// workspace's own PLC program shared by products p1 and p2.
|
||||
fn machine() -> (Vec<OnboardedTarget>, Vec<Project>) {
|
||||
let mut drive = target("Antrieb", Some("Antriebe GmbH"), &["c1"]);
|
||||
let mut sbom = Artifact::supplier_sbom("drive.cdx.json");
|
||||
sbom.ingested_at = Some(Utc::now());
|
||||
drive.artifacts.push(sbom);
|
||||
let sensor = target("Sensor", Some("Sensorik AG"), &["c1"]);
|
||||
let panel = target("Panel", Some("Display KG"), &["p1", "p2", "t1", "gone"]);
|
||||
let plc = target("Steuerung", None, &["p1", "p2"]);
|
||||
let mut topic = project("t1", ProjectLevel::Product, None);
|
||||
topic.kind = ProjectKind::Topic;
|
||||
topic.level = None;
|
||||
let projects = vec![
|
||||
project("p1", ProjectLevel::Product, None),
|
||||
project("p2", ProjectLevel::Product, None),
|
||||
project("c1", ProjectLevel::Component, Some("p1")),
|
||||
topic,
|
||||
];
|
||||
(vec![drive, sensor, panel, plc], projects)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suppliers_deliver_their_components_and_say_how() {
|
||||
let (targets, projects) = machine();
|
||||
let feeds = HashMap::from([(id(&targets[1]), Feed::Invite)]);
|
||||
|
||||
let chain = supply_chain(&targets, &projects, &HashMap::new(), &feeds);
|
||||
|
||||
let suppliers: Vec<&str> = chain
|
||||
.nodes
|
||||
.iter()
|
||||
.filter(|n| n.kind == NodeKind::Supplier)
|
||||
.map(|n| n.key.as_str())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
suppliers,
|
||||
[
|
||||
"supplier:Antriebe GmbH",
|
||||
"supplier:Display KG",
|
||||
"supplier:Sensorik AG"
|
||||
],
|
||||
"named once each, trimmed"
|
||||
);
|
||||
let how = |target: &OnboardedTarget| {
|
||||
chain
|
||||
.edges
|
||||
.iter()
|
||||
.find(|e| e.kind == EdgeKind::Supplies && e.to == target_key(&id(target)))
|
||||
.and_then(|e| e.delivery.clone())
|
||||
.unwrap()
|
||||
};
|
||||
let drive = how(&targets[0]);
|
||||
assert_eq!(drive.how, DeliveryKind::Upload);
|
||||
assert_eq!(drive.version.as_deref(), Some("1.4.0"));
|
||||
assert!(drive.at.is_some());
|
||||
assert_eq!(how(&targets[1]).how, DeliveryKind::Invite);
|
||||
assert_eq!(how(&targets[2]).how, DeliveryKind::Missing);
|
||||
let plc = chain.nodes.iter().find(|n| n.name == "Steuerung").unwrap();
|
||||
assert!(!plc.bought, "the workspace's own");
|
||||
assert!(!chain
|
||||
.edges
|
||||
.iter()
|
||||
.any(|e| e.to == plc.key && e.kind == EdgeKind::Supplies));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_release_delivers_by_itself_and_leaves_its_version_when_it_ends() {
|
||||
let (targets, _) = machine();
|
||||
let (drive, sensor) = (&targets[0], &targets[1]);
|
||||
|
||||
let live = delivery(drive, Some(Feed::Release));
|
||||
assert_eq!(live.how, DeliveryKind::Release);
|
||||
assert_eq!(live.version.as_deref(), Some("1.4.0"));
|
||||
assert!(live.at.is_some(), "when the version arrived");
|
||||
assert_eq!(
|
||||
delivery(sensor, Some(Feed::Release)).how,
|
||||
DeliveryKind::Release
|
||||
);
|
||||
|
||||
let ended = delivery(drive, Some(Feed::ReleaseEnded));
|
||||
assert_eq!(ended.how, DeliveryKind::ReleaseEnded);
|
||||
assert_eq!(
|
||||
ended.version.as_deref(),
|
||||
Some("1.4.0"),
|
||||
"the version that stays"
|
||||
);
|
||||
assert_eq!(
|
||||
delivery(sensor, Some(Feed::ReleaseEnded)).how,
|
||||
DeliveryKind::Missing,
|
||||
"an ended release that left no SBOM"
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(DeliveryKind::ReleaseEnded).unwrap(),
|
||||
"release_ended"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn components_are_part_of_products_and_assemblies_of_their_product() {
|
||||
let (targets, projects) = machine();
|
||||
let chain = supply_chain(&targets, &projects, &HashMap::new(), &HashMap::new());
|
||||
|
||||
let part_of: BTreeSet<(String, &str)> = chain
|
||||
.edges
|
||||
.iter()
|
||||
.filter(|e| e.kind == EdgeKind::PartOf)
|
||||
.map(|e| {
|
||||
let from = chain
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|n| n.key == e.from)
|
||||
.map(|n| n.name.clone())
|
||||
.unwrap();
|
||||
(from, e.to.as_str())
|
||||
})
|
||||
.collect();
|
||||
let expected: BTreeSet<(String, &str)> = [
|
||||
("Antrieb", "project:c1"),
|
||||
("Sensor", "project:c1"),
|
||||
("Projekt c1", "project:p1"),
|
||||
("Panel", "project:p1"),
|
||||
("Panel", "project:p2"),
|
||||
("Steuerung", "project:p1"),
|
||||
("Steuerung", "project:p2"),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(a, b)| (a.to_string(), b))
|
||||
.collect();
|
||||
assert_eq!(part_of, expected, "no topic, no unknown project");
|
||||
assert!(!chain.nodes.iter().any(|n| n.key == "project:t1"));
|
||||
let c1 = chain.nodes.iter().find(|n| n.key == "project:c1").unwrap();
|
||||
assert_eq!(c1.level, Some(ProjectLevel::Component));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_counts_each_component_beneath_it_once() {
|
||||
let (targets, projects) = machine();
|
||||
let open = HashMap::from([
|
||||
(id(&targets[0]), counts(1, 0, 0)),
|
||||
(id(&targets[1]), counts(0, 2, 0)),
|
||||
(id(&targets[2]), counts(0, 0, 1)),
|
||||
]);
|
||||
|
||||
let chain = supply_chain(&targets, &projects, &open, &HashMap::new());
|
||||
|
||||
let open_of = |key: &str| {
|
||||
chain
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|n| n.key == key)
|
||||
.and_then(|n| n.open)
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(open_of("project:c1"), counts(1, 2, 0));
|
||||
// The assembly's parts and the shared panel; the PLC has none.
|
||||
assert_eq!(open_of("project:p1"), counts(1, 2, 1));
|
||||
assert_eq!(open_of("project:p2"), counts(0, 0, 1));
|
||||
assert_eq!(
|
||||
open_of(&target_key(&id(&targets[3]))),
|
||||
SeverityCounts::default()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cycle_of_parents_ends() {
|
||||
let targets = vec![target("Teil", None, &["a"])];
|
||||
let projects = vec![
|
||||
project("a", ProjectLevel::Component, Some("b")),
|
||||
project("b", ProjectLevel::Component, Some("a")),
|
||||
];
|
||||
let open = HashMap::from([(id(&targets[0]), counts(0, 1, 0))]);
|
||||
let chain = supply_chain(&targets, &projects, &open, &HashMap::new());
|
||||
let b = chain.nodes.iter().find(|n| n.key == "project:b").unwrap();
|
||||
assert_eq!(b.open, Some(counts(0, 1, 0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_box_shows_the_documents_of_its_product_newest_first() {
|
||||
use crate::registry::StoreDocument;
|
||||
let doc = |id: &str, area: Option<&str>, projects: &[&str], day: u32| StoreDocument {
|
||||
id: id.into(),
|
||||
title: format!("Doc {id}"),
|
||||
filename: format!("{id}.pdf"),
|
||||
content_type: Some("application/pdf".into()),
|
||||
size_bytes: Some(1024),
|
||||
area: area.map(String::from),
|
||||
project_ids: projects.iter().map(|p| p.to_string()).collect(),
|
||||
created_at: chrono::NaiveDate::from_ymd_opt(2026, 11, day)
|
||||
.and_then(|d| d.and_hms_opt(9, 0, 0))
|
||||
.map(|d| d.and_utc()),
|
||||
};
|
||||
let store = vec![
|
||||
doc("manual", Some("product_public"), &["p1"], 10),
|
||||
doc("notes", Some("internal"), &["p1", "p2"], 12),
|
||||
doc("other", Some("product_public"), &["p2"], 11),
|
||||
doc("imprint", Some("legal_web"), &["p1"], 13),
|
||||
doc("delivery", None, &["p1"], 14),
|
||||
];
|
||||
|
||||
let shown = box_documents(store, "p1", "beispiel maschinenbau");
|
||||
|
||||
let ids: Vec<(&str, bool)> = shown.iter().map(|d| (d.id.as_str(), d.internal)).collect();
|
||||
assert_eq!(
|
||||
ids,
|
||||
[("notes", true), ("manual", false)],
|
||||
"newest first, its own only"
|
||||
);
|
||||
assert_eq!(
|
||||
shown[1].path,
|
||||
"/beispiel%20maschinenbau/dokumente/manual/original"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_registry_projects_are_named_by_their_id() {
|
||||
let targets = vec![
|
||||
target("Teil", None, &["m1", "m2"]),
|
||||
target("Ander", None, &["m1"]),
|
||||
];
|
||||
let projects = unregistered_projects(&targets);
|
||||
let ids: Vec<&str> = projects.iter().map(|p| p.name.as_str()).collect();
|
||||
assert_eq!(ids, ["m1", "m2"]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
//! The customer's arrangement of the supply chain (#1050, #1052): where each
|
||||
//! box of the Lieferkette sits, kept per workspace.
|
||||
//!
|
||||
//! One document in the tenant's own database, so the workspace export and
|
||||
//! erasure cover it. The positions are a list, not a map keyed by node: a
|
||||
//! supplier's name may hold a dot, which a document key may not. Saving
|
||||
//! replaces the whole arrangement (the last save wins); a node the graph no
|
||||
//! longer has is ignored by the page, and a new one takes its computed place.
|
||||
|
||||
use axum::extract::Extension;
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use chrono::{DateTime, Utc};
|
||||
use mongodb::bson::{doc, DateTime as BsonDateTime};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use super::dto::{tenant_db, AgentExt};
|
||||
use super::ApiResponse;
|
||||
use crate::database::Database;
|
||||
|
||||
/// The collection, in the tenant's own database.
|
||||
pub const COLLECTION: &str = "supply_chain_layout";
|
||||
|
||||
/// The one document's id.
|
||||
const LAYOUT_ID: &str = "layout";
|
||||
|
||||
/// The most boxes an arrangement holds.
|
||||
const MAX_POSITIONS: usize = 5_000;
|
||||
|
||||
/// The longest node key accepted.
|
||||
const MAX_KEY_LEN: usize = 400;
|
||||
|
||||
/// How far a box may sit from the origin, in pixels, either way.
|
||||
const MAX_COORDINATE: i32 = 100_000;
|
||||
|
||||
/// Where one box sits.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)]
|
||||
pub struct NodePosition {
|
||||
/// The node's key, as `GET /api/v1/supply-chain` gives it.
|
||||
pub key: String,
|
||||
/// Its left edge, in pixels.
|
||||
pub x: i32,
|
||||
/// Its top edge, in pixels.
|
||||
pub y: i32,
|
||||
}
|
||||
|
||||
/// The arrangement as the page reads it.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct Layout {
|
||||
/// The boxes the customer placed; any other takes its computed place.
|
||||
pub positions: Vec<NodePosition>,
|
||||
/// When it was last saved; `None` before the first save.
|
||||
pub updated_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
/// The body of a save.
|
||||
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||
pub struct SaveLayout {
|
||||
/// Every placed box. One that is left out takes its computed place.
|
||||
pub positions: Vec<NodePosition>,
|
||||
}
|
||||
|
||||
/// The arrangement as stored.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct StoredLayout {
|
||||
#[serde(rename = "_id")]
|
||||
id: String,
|
||||
positions: Vec<NodePosition>,
|
||||
updated_at: BsonDateTime,
|
||||
updated_by: String,
|
||||
}
|
||||
|
||||
fn layouts(db: &Database) -> mongodb::Collection<StoredLayout> {
|
||||
db.inner().collection(COLLECTION)
|
||||
}
|
||||
|
||||
/// `positions` as kept: each key trimmed and once (the last position given
|
||||
/// wins), in the order first given.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 422 for too many boxes, an empty or overlong key, or a box too far out.
|
||||
fn checked(positions: Vec<NodePosition>) -> Result<Vec<NodePosition>, StatusCode> {
|
||||
if positions.len() > MAX_POSITIONS {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
let mut kept: Vec<NodePosition> = Vec::with_capacity(positions.len());
|
||||
// Where each key sits in `kept`: one lookup per box, not a scan.
|
||||
let mut index: std::collections::HashMap<String, usize> =
|
||||
std::collections::HashMap::with_capacity(positions.len());
|
||||
for p in positions {
|
||||
let key = p.key.trim();
|
||||
let usable = !key.is_empty()
|
||||
&& key.len() <= MAX_KEY_LEN
|
||||
&& p.x.abs() <= MAX_COORDINATE
|
||||
&& p.y.abs() <= MAX_COORDINATE;
|
||||
if !usable {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
match index.get(key) {
|
||||
Some(&i) => (kept[i].x, kept[i].y) = (p.x, p.y),
|
||||
None => {
|
||||
index.insert(key.to_string(), kept.len());
|
||||
kept.push(NodePosition {
|
||||
key: key.to_string(),
|
||||
x: p.x,
|
||||
y: p.y,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(kept)
|
||||
}
|
||||
|
||||
/// The workspace's arrangement of its supply chain.
|
||||
///
|
||||
/// The boxes the customer placed, by node key; an empty list before the
|
||||
/// first save, when every box takes its computed place.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/supply-chain/layout",
|
||||
tag = "Targets",
|
||||
responses(
|
||||
(status = 200, description = "The arrangement (`data`: `positions`, `updated_at`)"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn get_layout(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
) -> Result<Json<ApiResponse<Layout>>, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let stored = layouts(&db)
|
||||
.find_one(doc! { "_id": LAYOUT_ID })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let data = stored.map_or(
|
||||
Layout {
|
||||
positions: Vec::new(),
|
||||
updated_at: None,
|
||||
},
|
||||
|s| Layout {
|
||||
positions: s.positions,
|
||||
updated_at: Some(s.updated_at.to_chrono()),
|
||||
},
|
||||
);
|
||||
Ok(Json(ApiResponse {
|
||||
data,
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Save the workspace's arrangement of its supply chain.
|
||||
///
|
||||
/// Replaces the whole arrangement: the last save wins. Each key is kept once,
|
||||
/// with the last position given for it.
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/api/v1/supply-chain/layout",
|
||||
tag = "Targets",
|
||||
request_body = SaveLayout,
|
||||
responses(
|
||||
(status = 200, description = "The arrangement as kept (`data`)"),
|
||||
(status = 422, description = "Too many boxes, an empty or overlong key, or a box too far out"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
(status = 403, description = "A read-only role"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn save_layout(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Json(body): Json<SaveLayout>,
|
||||
) -> Result<Json<ApiResponse<Layout>>, StatusCode> {
|
||||
let positions = checked(body.positions)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let now = Utc::now();
|
||||
let stored = StoredLayout {
|
||||
id: LAYOUT_ID.to_string(),
|
||||
positions,
|
||||
updated_at: now.into(),
|
||||
updated_by: tenant.0.user_id.clone(),
|
||||
};
|
||||
layouts(&db)
|
||||
.replace_one(doc! { "_id": LAYOUT_ID }, &stored)
|
||||
.upsert(true)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
Ok(Json(ApiResponse {
|
||||
data: Layout {
|
||||
positions: stored.positions,
|
||||
updated_at: Some(stored.updated_at.to_chrono()),
|
||||
},
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Reset the workspace's arrangement: every box takes its computed place.
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
path = "/api/v1/supply-chain/layout",
|
||||
tag = "Targets",
|
||||
responses(
|
||||
(status = 200, description = "The arrangement was reset"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
(status = 403, description = "A read-only role"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn reset_layout(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
layouts(&db)
|
||||
.delete_one(doc! { "_id": LAYOUT_ID })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
Ok(Json(serde_json::json!({ "status": "reset" })))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn at(key: &str, x: i32, y: i32) -> NodePosition {
|
||||
NodePosition {
|
||||
key: key.into(),
|
||||
x,
|
||||
y,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_is_kept_once_with_its_last_position() {
|
||||
let kept = checked(vec![
|
||||
at(" target:a ", 10, 20),
|
||||
at("supplier:Beispiel GmbH & Co. KG", 0, 0),
|
||||
at("target:a", 30, 40),
|
||||
])
|
||||
.expect("usable");
|
||||
assert_eq!(
|
||||
kept,
|
||||
[
|
||||
at("target:a", 30, 40),
|
||||
at("supplier:Beispiel GmbH & Co. KG", 0, 0)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonsense_is_refused() {
|
||||
for bad in [
|
||||
vec![at(" ", 0, 0)],
|
||||
vec![at(&"k".repeat(401), 0, 0)],
|
||||
vec![at("target:a", 100_001, 0)],
|
||||
vec![at("target:a", 0, -100_001)],
|
||||
] {
|
||||
assert_eq!(checked(bad), Err(StatusCode::UNPROCESSABLE_ENTITY));
|
||||
}
|
||||
let many = (0..=MAX_POSITIONS)
|
||||
.map(|i| at(&format!("target:{i}"), 0, 0))
|
||||
.collect();
|
||||
assert_eq!(checked(many), Err(StatusCode::UNPROCESSABLE_ENTITY));
|
||||
assert_eq!(checked(Vec::new()), Ok(Vec::new()));
|
||||
}
|
||||
}
|
||||
@@ -41,8 +41,20 @@ fn picker_order(mut tenants: Vec<SupportTenant>) -> Vec<SupportTenant> {
|
||||
tenants
|
||||
}
|
||||
|
||||
/// GET /api/v1/support/tenants — every tenant, for support to choose from.
|
||||
/// Every tenant, for Breakpilot support to choose from.
|
||||
///
|
||||
/// 403 for anyone but support; 503 without a registry.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/support/tenants",
|
||||
tag = "Support",
|
||||
responses(
|
||||
(status = 200, description = "The tenants"),
|
||||
(status = 403, description = "Not support"),
|
||||
(status = 503, description = "No registry"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn list_tenants(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -60,9 +72,20 @@ pub async fn list_tenants(
|
||||
Ok(Json(serde_json::json!({ "data": tenants })))
|
||||
}
|
||||
|
||||
/// POST /api/v1/support/session — open the tenant named in the header. The
|
||||
/// middleware has confirmed it with the registry and records the opening in
|
||||
/// the audit log; this answers what was opened. 403 for anyone but support.
|
||||
/// Open the tenant named in the `X-Pruefwerk-Tenant` header for support.
|
||||
///
|
||||
/// The middleware has confirmed it with the registry and records the opening
|
||||
/// in the audit log; this answers what was opened. 403 for anyone but support.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/support/session",
|
||||
tag = "Support",
|
||||
responses(
|
||||
(status = 200, description = "The opened tenant"),
|
||||
(status = 403, description = "Not support"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn open_session(tenant: TenantCtx) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
if tenant.0.staff.is_none() {
|
||||
|
||||
@@ -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};
|
||||
@@ -21,13 +21,19 @@ const TOKEN_METHOD: &str = "token";
|
||||
|
||||
/// A client-supplied artifact spec. The server builds the [`Artifact`] (and its
|
||||
/// id) from it, so clients never set internal fields.
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize, utoipa::ToSchema)]
|
||||
pub struct ArtifactInput {
|
||||
/// What the artifact is, such as `git_repo`, `source_archive` or `plc_project`.
|
||||
#[schema(value_type = String, example = "git_repo")]
|
||||
pub kind: ArtifactKind,
|
||||
/// Where it is: a clone URL, or a reference to an uploaded file.
|
||||
pub source_ref: String,
|
||||
/// The branch of a git repository.
|
||||
#[serde(default)]
|
||||
pub branch: Option<String>,
|
||||
/// The PLC project's format, for a PLC project.
|
||||
#[serde(default)]
|
||||
#[schema(value_type = Option<String>, example = "plcopen_xml")]
|
||||
pub plc_format: Option<PlcFormat>,
|
||||
/// A git access token for a private repository (#303). Sent: stored
|
||||
/// sealed. Sent empty: removed. Left out: the stored one is kept.
|
||||
@@ -129,15 +135,44 @@ pub fn merge_artifacts(
|
||||
|
||||
/// A change to a target's scan config. A field left out keeps its stored
|
||||
/// value: enabling a scan must not remove the issue tracker (#304).
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[derive(Debug, Default, Deserialize, utoipa::ToSchema)]
|
||||
pub struct ScanConfigUpdate {
|
||||
/// The scans to run, such as `sast`, `sbom` or `cve`.
|
||||
#[schema(value_type = Option<Vec<String>>)]
|
||||
pub enabled_scans: Option<Vec<ScanType>>,
|
||||
/// The scans not to run.
|
||||
#[schema(value_type = Option<Vec<String>>)]
|
||||
pub disabled_scans: Option<Vec<ScanType>>,
|
||||
/// `development`, `staging` or `production`.
|
||||
#[schema(value_type = Option<String>, example = "staging")]
|
||||
pub environment: Option<Environment>,
|
||||
/// Whether dynamic tests may change data.
|
||||
pub allow_destructive: Option<bool>,
|
||||
/// The pentest strategy: `quick`, `comprehensive`, `targeted` or `aggressive`.
|
||||
#[schema(value_type = Option<String>)]
|
||||
pub strategy: Option<PentestStrategy>,
|
||||
/// The pentest's scope and login.
|
||||
#[schema(value_type = Option<Object>)]
|
||||
pub pentest: Option<PentestConfig>,
|
||||
/// Where findings are filed as issues.
|
||||
#[schema(value_type = Option<Object>)]
|
||||
pub issue_tracker: Option<IssueTrackerConfig>,
|
||||
/// Paths left out of every scan; replaces the stored list. Normalised
|
||||
/// while the request is read, so an invalid path is refused with its
|
||||
/// 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 +204,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 +313,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;
|
||||
@@ -18,7 +20,8 @@ use super::dto::{collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResu
|
||||
use super::findings::Actor;
|
||||
|
||||
/// GET /api/v1/targets/{id}/cves — the target's CVE alerts with their VEX
|
||||
/// statements, newest first.
|
||||
/// statements, newest first. A `fixed` a scan inferred from a CVE no longer
|
||||
/// being found is left out (#994).
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn list_target_cves(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -26,18 +29,9 @@ 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 mut alerts = target_alerts(&db, &id).await.unwrap_or_default();
|
||||
alerts.iter_mut().for_each(CveAlert::drop_inferred_fix);
|
||||
Ok(Json(ApiResponse {
|
||||
total: Some(alerts.len() as u64),
|
||||
data: alerts,
|
||||
@@ -45,6 +39,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 +68,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 +95,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 +114,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 {
|
||||
@@ -161,7 +255,7 @@ async fn load_source(db: &crate::database::Database, id: &str) -> Result<VexSour
|
||||
}
|
||||
|
||||
/// The workspace's name, the author of its VEX statements.
|
||||
fn author(tenant: &TenantCtx) -> String {
|
||||
pub(super) fn author(tenant: &TenantCtx) -> String {
|
||||
if tenant.0.tenant_slug.is_empty() {
|
||||
tenant.0.tenant_id.clone()
|
||||
} else {
|
||||
@@ -170,7 +264,10 @@ fn author(tenant: &TenantCtx) -> String {
|
||||
}
|
||||
|
||||
/// `body` as a JSON file named `filename` to download.
|
||||
fn download(body: &serde_json::Value, filename: &str) -> Result<impl IntoResponse, StatusCode> {
|
||||
pub(super) fn download(
|
||||
body: &serde_json::Value,
|
||||
filename: &str,
|
||||
) -> Result<impl IntoResponse, StatusCode> {
|
||||
let json = serde_json::to_string_pretty(body).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let disposition = HeaderValue::from_str(&format!("attachment; filename=\"{filename}\""))
|
||||
.unwrap_or_else(|_| HeaderValue::from_static("attachment"));
|
||||
@@ -441,6 +538,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() {
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
pub mod api_key_gate;
|
||||
pub mod handlers;
|
||||
pub mod openapi;
|
||||
pub mod role_gate;
|
||||
pub mod routes;
|
||||
pub mod server;
|
||||
pub mod trace;
|
||||
|
||||
pub use server::start_api_server;
|
||||
@@ -0,0 +1,73 @@
|
||||
//! The OpenAPI description of the customer API (#1006).
|
||||
//!
|
||||
//! Generated from the handlers: a route registered through
|
||||
//! [`utoipa_axum::routes!`] takes its path, method, parameters and body from
|
||||
//! the handler's `#[utoipa::path]`, so the description cannot drift from the
|
||||
//! route. The document is served at [`SPEC_PATH`], behind the same
|
||||
//! authentication as the API, for integrators and for DAST, which seeds its
|
||||
//! endpoints from it (#997).
|
||||
|
||||
use utoipa::openapi::security::{HttpAuthScheme, HttpBuilder, SecurityRequirement, SecurityScheme};
|
||||
use utoipa::OpenApi;
|
||||
|
||||
/// Where the agent serves its OpenAPI document. Under the API prefix, so the
|
||||
/// customer authentication covers it, and one of the paths DAST tries.
|
||||
pub const SPEC_PATH: &str = "/api/v1/openapi.json";
|
||||
|
||||
/// The name of the bearer scheme in the document.
|
||||
const BEARER: &str = "bearer";
|
||||
|
||||
/// The document's frame; the routes add their paths to it.
|
||||
#[derive(OpenApi)]
|
||||
#[openapi(info(
|
||||
title = "Prüfwerk API",
|
||||
description = "The customer API of the Prüfwerk agent. Every operation but the health \
|
||||
check needs a Keycloak access token or an API key as a bearer token."
|
||||
))]
|
||||
pub struct ApiDoc;
|
||||
|
||||
/// `api` with the bearer scheme, required by every operation except the
|
||||
/// public ones ([`compliance_core::auth::bypasses_customer_auth`]).
|
||||
///
|
||||
/// The scheme goes on each operation rather than once for the document: a
|
||||
/// reader that only looks at operations (the DAST spec parser) still sees it.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `api` - the document with every described route's path
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The finished document.
|
||||
pub fn with_bearer_auth(mut api: utoipa::openapi::OpenApi) -> utoipa::openapi::OpenApi {
|
||||
api.components
|
||||
.get_or_insert_with(Default::default)
|
||||
.add_security_scheme(
|
||||
BEARER,
|
||||
SecurityScheme::Http(
|
||||
HttpBuilder::new()
|
||||
.scheme(HttpAuthScheme::Bearer)
|
||||
.description(Some("A Keycloak access token or an API key"))
|
||||
.build(),
|
||||
),
|
||||
);
|
||||
for (path, item) in api.paths.paths.iter_mut() {
|
||||
if compliance_core::auth::bypasses_customer_auth(path) {
|
||||
continue;
|
||||
}
|
||||
let operations = [
|
||||
&mut item.get,
|
||||
&mut item.put,
|
||||
&mut item.post,
|
||||
&mut item.delete,
|
||||
&mut item.options,
|
||||
&mut item.head,
|
||||
&mut item.patch,
|
||||
&mut item.trace,
|
||||
];
|
||||
for operation in operations.into_iter().flatten() {
|
||||
operation.security = Some(vec![SecurityRequirement::new(BEARER, Vec::<String>::new())]);
|
||||
}
|
||||
}
|
||||
api
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
+367
-269
@@ -1,321 +1,282 @@
|
||||
use axum::extract::DefaultBodyLimit;
|
||||
use axum::routing::{delete, get, patch, post, put};
|
||||
use axum::http::header::CONTENT_TYPE;
|
||||
use axum::routing::{get, patch};
|
||||
use axum::Router;
|
||||
use utoipa::OpenApi;
|
||||
use utoipa_axum::router::{OpenApiRouter, UtoipaMethodRouterExt};
|
||||
use utoipa_axum::routes;
|
||||
|
||||
use crate::api::handlers;
|
||||
use crate::api::{handlers, openapi};
|
||||
|
||||
/// Allowance on top of the file itself for the multipart framing: boundaries,
|
||||
/// part headers and the small `kind` / `plc_format` text fields.
|
||||
const MULTIPART_OVERHEAD: usize = 1024 * 1024;
|
||||
pub(crate) const MULTIPART_OVERHEAD: usize = 1024 * 1024;
|
||||
|
||||
/// The customer API, with its OpenAPI description at [`openapi::SPEC_PATH`]
|
||||
/// (#1006).
|
||||
///
|
||||
/// A route registered with `.routes(routes!(…))` is described by its
|
||||
/// handler's `#[utoipa::path]`. The plain route calls are the routes not
|
||||
/// described yet; a test keeps them listed in `UNDESCRIBED`, so a new route
|
||||
/// cannot be added without its description.
|
||||
pub fn build_router() -> Router {
|
||||
Router::new()
|
||||
.route("/api/v1/health", get(handlers::health))
|
||||
.route("/api/v1/oscal/assess", post(handlers::oscal::assess_target))
|
||||
.route("/api/v1/stats/overview", get(handlers::stats_overview))
|
||||
let (router, api) = described_routes().split_for_parts();
|
||||
let spec = std::sync::Arc::<str>::from(
|
||||
openapi::with_bearer_auth(api)
|
||||
.to_json()
|
||||
.unwrap_or_else(|e| {
|
||||
tracing::error!("OpenAPI description not built: {e}");
|
||||
"{}".to_string()
|
||||
}),
|
||||
);
|
||||
router.route(
|
||||
openapi::SPEC_PATH,
|
||||
get(move || {
|
||||
let spec = spec.clone();
|
||||
async move { ([(CONTENT_TYPE, "application/json")], spec.to_string()) }
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
fn described_routes() -> OpenApiRouter {
|
||||
OpenApiRouter::with_openapi(openapi::ApiDoc::openapi())
|
||||
.routes(routes!(handlers::health))
|
||||
.routes(routes!(handlers::oscal::assess_target))
|
||||
.routes(routes!(handlers::stats_overview))
|
||||
// The tenant's projects (owned by the registry), for assigning targets.
|
||||
.route("/api/v1/projects", get(handlers::projects::list_projects))
|
||||
.routes(routes!(handlers::projects::list_projects))
|
||||
// A machine: a product project and the targets it is made of (#1026).
|
||||
.routes(routes!(handlers::machine::export_machine_sbom))
|
||||
.routes(routes!(handlers::machine::machine_overview))
|
||||
.routes(routes!(handlers::machine::machine_cves))
|
||||
.routes(routes!(handlers::machine::machine_scan_changes))
|
||||
.routes(routes!(handlers::supply_chain::get_supply_chain))
|
||||
.routes(routes!(handlers::connections::list_connections))
|
||||
// SBOM releases to connected workspaces, the supplier's side (#1028).
|
||||
.routes(routes!(
|
||||
handlers::releases::list_releases,
|
||||
handlers::releases::create_release
|
||||
))
|
||||
.routes(routes!(handlers::releases::end_release))
|
||||
.routes(routes!(handlers::releases::publish_version))
|
||||
.routes(routes!(handlers::releases::preview_version))
|
||||
.routes(routes!(handlers::releases::version_draft))
|
||||
// What connected suppliers offer, the customer's side (#1028).
|
||||
.routes(routes!(handlers::offers::list_offers))
|
||||
.routes(routes!(handlers::offers::accept_offer))
|
||||
.routes(routes!(handlers::offers::decline_offer))
|
||||
.routes(routes!(handlers::supply_chain::project_documents))
|
||||
// The customer's arrangement of the supply chain (#1052).
|
||||
.routes(routes!(
|
||||
handlers::supply_chain_layout::get_layout,
|
||||
handlers::supply_chain_layout::save_layout,
|
||||
handlers::supply_chain_layout::reset_layout
|
||||
))
|
||||
.routes(routes!(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.
|
||||
.route("/api/v1/access", get(handlers::health::access))
|
||||
.routes(routes!(handlers::health::access))
|
||||
// The managed git source, read-only (IT admin and support).
|
||||
.route(
|
||||
"/api/v1/git-source",
|
||||
get(handlers::git_source::get_git_source),
|
||||
)
|
||||
.routes(routes!(handlers::git_source::get_git_source))
|
||||
// BreakPilot support access: choose and open a customer's tenant.
|
||||
.route(
|
||||
"/api/v1/support/tenants",
|
||||
get(handlers::support::list_tenants),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/support/session",
|
||||
post(handlers::support::open_session),
|
||||
)
|
||||
.routes(routes!(handlers::support::list_tenants))
|
||||
.routes(routes!(handlers::support::open_session))
|
||||
// Unified onboarding targets (#131).
|
||||
.route(
|
||||
"/api/v1/targets",
|
||||
get(handlers::onboarding::list_targets).post(handlers::onboarding::create_target),
|
||||
)
|
||||
// Curated demo targets (D3). Registered before "/targets/{id}" for
|
||||
// readability; the router matches the literal segment first either way.
|
||||
.route(
|
||||
"/api/v1/targets/demo-seed",
|
||||
get(handlers::demo_seed::list_demo_targets)
|
||||
.post(handlers::demo_seed::seed_demo_targets),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}",
|
||||
get(handlers::onboarding::get_target)
|
||||
.patch(handlers::onboarding::update_target)
|
||||
.delete(handlers::onboarding::delete_target),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/artifacts",
|
||||
post(handlers::onboarding::add_artifact),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/webhook-deliveries",
|
||||
get(handlers::onboarding::list_webhook_deliveries),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/artifacts/upload",
|
||||
// The one route that takes large bodies — and it streams them to
|
||||
// disk. Every other route keeps axum's 2 MiB default, so a JSON
|
||||
// endpoint can no longer be sent a 512 MiB body to buffer.
|
||||
post(handlers::onboarding::upload_artifact).layer(DefaultBodyLimit::max(
|
||||
.routes(routes!(
|
||||
handlers::onboarding::list_targets,
|
||||
handlers::onboarding::create_target
|
||||
))
|
||||
// Curated demo targets (D3).
|
||||
.routes(routes!(
|
||||
handlers::demo_seed::list_demo_targets,
|
||||
handlers::demo_seed::seed_demo_targets
|
||||
))
|
||||
.routes(routes!(
|
||||
handlers::onboarding::get_target,
|
||||
handlers::onboarding::update_target,
|
||||
handlers::onboarding::delete_target
|
||||
))
|
||||
.routes(routes!(handlers::onboarding::add_artifact))
|
||||
// A target's Siemens controllers against Siemens' advisories (SPS 4a).
|
||||
.routes(routes!(handlers::devices::list_devices))
|
||||
.routes(routes!(handlers::devices::lookup_device))
|
||||
.routes(routes!(handlers::onboarding::list_webhook_deliveries))
|
||||
// The one route that takes large bodies — and it streams them to
|
||||
// disk. Every other route keeps axum's 2 MiB default, so a JSON
|
||||
// endpoint can no longer be sent a 512 MiB body to buffer.
|
||||
.routes(
|
||||
routes!(handlers::onboarding::upload_artifact).layer(DefaultBodyLimit::max(
|
||||
crate::targets::MAX_UPLOAD_BYTES as usize + MULTIPART_OVERHEAD,
|
||||
)),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/artifacts/{artifact_id}/archive-password",
|
||||
put(handlers::onboarding::set_archive_password),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/applicable-scans",
|
||||
get(handlers::onboarding::applicable_scans_for_target),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/detect",
|
||||
post(handlers::onboarding::detect_target),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/scan",
|
||||
post(handlers::onboarding::trigger_target_scan),
|
||||
)
|
||||
.route("/api/v1/findings", get(handlers::list_findings))
|
||||
.route(
|
||||
"/api/v1/findings/variants",
|
||||
get(handlers::list_finding_variants),
|
||||
)
|
||||
.route("/api/v1/findings/{id}", get(handlers::get_finding))
|
||||
.route(
|
||||
"/api/v1/findings/{id}/status",
|
||||
patch(handlers::update_finding_status),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/findings/bulk-status",
|
||||
patch(handlers::bulk_update_finding_status),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/findings/{id}/feedback",
|
||||
patch(handlers::update_finding_feedback),
|
||||
// A supplier SBOM is checked when the wizard adds it, before any
|
||||
// target holds it: up to its own size limit, never kept.
|
||||
.routes(
|
||||
routes!(handlers::onboarding::check_supplier_sbom).layer(DefaultBodyLimit::max(
|
||||
crate::pipeline::sbom::supplied::MAX_BYTES as usize + MULTIPART_OVERHEAD,
|
||||
)),
|
||||
)
|
||||
.routes(routes!(handlers::supplier::get_supplier_advisories))
|
||||
.routes(routes!(handlers::onboarding::set_archive_password))
|
||||
.routes(routes!(handlers::onboarding::applicable_scans_for_target))
|
||||
.routes(routes!(handlers::onboarding::detect_target))
|
||||
.routes(routes!(handlers::onboarding::trigger_target_scan))
|
||||
.routes(routes!(handlers::onboarding::swap_target_billing))
|
||||
.routes(routes!(handlers::list_findings))
|
||||
.routes(routes!(handlers::list_finding_variants))
|
||||
.routes(routes!(handlers::get_finding))
|
||||
.routes(routes!(handlers::update_finding_status))
|
||||
.routes(routes!(handlers::bulk_update_finding_status))
|
||||
.routes(routes!(handlers::update_finding_feedback))
|
||||
// Undecided findings grouped by rule and file; one decision per group (#951).
|
||||
.routes(routes!(handlers::finding_groups::list_finding_groups))
|
||||
.routes(routes!(handlers::finding_groups::decide_finding_group))
|
||||
// The "Heute" inbox (#950): open decisions in urgency buckets.
|
||||
.routes(routes!(handlers::inbox::get_inbox))
|
||||
.routes(routes!(handlers::inbox::decide))
|
||||
.routes(routes!(handlers::inbox::undo))
|
||||
.routes(routes!(handlers::inbox::snooze))
|
||||
.routes(routes!(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}/evidence-pack",
|
||||
get(handlers::evidence::evidence_pack),
|
||||
"/api/v1/targets/{id}/cve-groups",
|
||||
get(handlers::vex::list_cve_groups),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/compliance",
|
||||
get(handlers::evidence::compliance_view),
|
||||
"/api/v1/targets/{id}/cve-groups/vex",
|
||||
patch(handlers::vex::set_group_vex),
|
||||
)
|
||||
// The target's SBOM components per ecosystem (#957).
|
||||
.route(
|
||||
"/api/v1/compliance/summary",
|
||||
get(handlers::evidence::compliance_summary),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/controls",
|
||||
get(handlers::evidence::describe_controls),
|
||||
"/api/v1/targets/{id}/sbom-ecosystems",
|
||||
get(handlers::sbom_ecosystems::list_sbom_ecosystems),
|
||||
)
|
||||
.routes(routes!(handlers::evidence::evidence_pack))
|
||||
.routes(routes!(handlers::evidence::compliance_view))
|
||||
.routes(routes!(handlers::finding_breakdown::finding_breakdown))
|
||||
.routes(routes!(handlers::evidence::compliance_summary))
|
||||
.routes(routes!(handlers::evidence::describe_controls))
|
||||
// Findings from a manual DAST run or penetration test.
|
||||
.route(
|
||||
"/api/v1/targets/{id}/findings",
|
||||
post(handlers::manual_findings::create_finding),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/findings/import",
|
||||
post(handlers::manual_findings::import_findings).layer(DefaultBodyLimit::max(
|
||||
.routes(routes!(handlers::manual_findings::create_finding))
|
||||
.routes(
|
||||
routes!(handlers::manual_findings::import_findings).layer(DefaultBodyLimit::max(
|
||||
handlers::manual_findings::MAX_IMPORT_BYTES,
|
||||
)),
|
||||
)
|
||||
.route("/api/v1/sbom", get(handlers::list_sbom))
|
||||
.route("/api/v1/sbom/filters", get(handlers::sbom_filters))
|
||||
.route("/api/v1/sbom/export", get(handlers::export_sbom))
|
||||
.route("/api/v1/sbom/licenses", get(handlers::license_summary))
|
||||
.route("/api/v1/sbom/quality", get(handlers::sbom_quality))
|
||||
.route("/api/v1/sbom/diff", get(handlers::sbom_diff))
|
||||
.routes(routes!(handlers::list_sbom))
|
||||
.routes(routes!(handlers::sbom_filters))
|
||||
.routes(routes!(handlers::export_sbom))
|
||||
.routes(routes!(handlers::license_summary))
|
||||
.routes(routes!(handlers::sbom_quality))
|
||||
.routes(routes!(handlers::sbom_diff))
|
||||
// Licences the workspace confirms for its components.
|
||||
.route(
|
||||
"/api/v1/licenses/conclusions",
|
||||
get(handlers::licenses::list_conclusions)
|
||||
.put(handlers::licenses::conclude)
|
||||
.delete(handlers::licenses::withdraw),
|
||||
)
|
||||
.routes(routes!(
|
||||
handlers::licenses::list_conclusions,
|
||||
handlers::licenses::conclude,
|
||||
handlers::licenses::withdraw
|
||||
))
|
||||
// The licence policy, what it says about each component, and the
|
||||
// legal review that resolves what it asks a review for.
|
||||
.route(
|
||||
"/api/v1/licenses/policy",
|
||||
get(handlers::licenses::get_policy).put(handlers::licenses::put_policy),
|
||||
)
|
||||
.route("/api/v1/licenses/check", get(handlers::licenses::check))
|
||||
.route(
|
||||
"/api/v1/licenses/review",
|
||||
post(handlers::licenses::review).delete(handlers::licenses::withdraw_review),
|
||||
)
|
||||
.route("/api/v1/sbom/notices", get(handlers::licenses::notices))
|
||||
.route("/api/v1/issues", get(handlers::list_issues))
|
||||
.route("/api/v1/scan-runs", get(handlers::list_scan_runs))
|
||||
.routes(routes!(
|
||||
handlers::licenses::get_policy,
|
||||
handlers::licenses::put_policy
|
||||
))
|
||||
.routes(routes!(handlers::licenses::check))
|
||||
.routes(routes!(
|
||||
handlers::licenses::review,
|
||||
handlers::licenses::withdraw_review
|
||||
))
|
||||
.routes(routes!(handlers::licenses::notices))
|
||||
.routes(routes!(handlers::list_issues))
|
||||
.routes(routes!(handlers::list_scan_runs))
|
||||
// MCP token management (per-tenant API tokens for the MCP server)
|
||||
.route(
|
||||
"/api/v1/mcp-servers",
|
||||
get(handlers::mcp_servers::list_mcp_servers)
|
||||
.post(handlers::mcp_servers::create_mcp_server),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/mcp-servers/{id}",
|
||||
delete(handlers::mcp_servers::delete_mcp_server),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/mcp-servers/{id}/token",
|
||||
post(handlers::mcp_servers::regenerate_mcp_server_token),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/mcp-tokens",
|
||||
get(handlers::mcp_tokens::list_mcp_tokens).post(handlers::mcp_tokens::create_mcp_token),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/mcp-tokens/{id}",
|
||||
delete(handlers::mcp_tokens::revoke_mcp_token),
|
||||
)
|
||||
.routes(routes!(
|
||||
handlers::mcp_servers::list_mcp_servers,
|
||||
handlers::mcp_servers::create_mcp_server
|
||||
))
|
||||
.routes(routes!(handlers::mcp_servers::delete_mcp_server))
|
||||
.routes(routes!(handlers::mcp_servers::regenerate_mcp_server_token))
|
||||
.routes(routes!(
|
||||
handlers::mcp_tokens::list_mcp_tokens,
|
||||
handlers::mcp_tokens::create_mcp_token
|
||||
))
|
||||
.routes(routes!(handlers::mcp_tokens::revoke_mcp_token))
|
||||
// Graph API endpoints
|
||||
.route("/api/v1/graph/{repo_id}", get(handlers::graph::get_graph))
|
||||
.route(
|
||||
"/api/v1/graph/{repo_id}/nodes",
|
||||
get(handlers::graph::get_nodes),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/graph/{repo_id}/communities",
|
||||
get(handlers::graph::get_communities),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/graph/{repo_id}/impact/{finding_id}",
|
||||
get(handlers::graph::get_impact),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/graph/{repo_id}/search",
|
||||
get(handlers::graph::search_symbols),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/graph/{repo_id}/file-content",
|
||||
get(handlers::graph::get_file_content),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/graph/{repo_id}/build",
|
||||
post(handlers::graph::trigger_build),
|
||||
)
|
||||
.routes(routes!(handlers::graph::get_graph))
|
||||
.routes(routes!(handlers::graph::get_nodes))
|
||||
.routes(routes!(handlers::graph::get_summary))
|
||||
.routes(routes!(handlers::graph::get_communities))
|
||||
.routes(routes!(handlers::graph::get_impact))
|
||||
.routes(routes!(handlers::graph::search_symbols))
|
||||
.routes(routes!(handlers::graph::get_file_content))
|
||||
.routes(routes!(handlers::graph::trigger_build))
|
||||
// DAST API endpoints
|
||||
.route("/api/v1/dast/targets", get(handlers::dast::list_targets))
|
||||
.route("/api/v1/dast/targets", post(handlers::dast::add_target))
|
||||
.route(
|
||||
"/api/v1/dast/targets/{id}/scan",
|
||||
post(handlers::dast::trigger_scan),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/dast/scan-runs",
|
||||
get(handlers::dast::list_scan_runs),
|
||||
)
|
||||
.route("/api/v1/dast/findings", get(handlers::dast::list_findings))
|
||||
.route(
|
||||
"/api/v1/dast/findings/{id}",
|
||||
get(handlers::dast::get_finding),
|
||||
)
|
||||
.routes(routes!(
|
||||
handlers::dast::list_targets,
|
||||
handlers::dast::add_target
|
||||
))
|
||||
.routes(routes!(handlers::dast::trigger_scan))
|
||||
.routes(routes!(handlers::dast::list_scan_runs))
|
||||
.routes(routes!(handlers::dast::list_findings))
|
||||
.routes(routes!(handlers::dast::get_finding))
|
||||
// Chat / RAG API endpoints
|
||||
.route("/api/v1/chat/{repo_id}", post(handlers::chat::chat))
|
||||
.route(
|
||||
"/api/v1/chat/{repo_id}/build-embeddings",
|
||||
post(handlers::chat::build_embeddings),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/chat/{repo_id}/status",
|
||||
get(handlers::chat::embedding_status),
|
||||
)
|
||||
.routes(routes!(handlers::chat::chat))
|
||||
.routes(routes!(handlers::chat::build_embeddings))
|
||||
.routes(routes!(handlers::chat::embedding_status))
|
||||
// Help chat (documentation-grounded Q&A)
|
||||
.route("/api/v1/help/chat", post(handlers::help_chat::help_chat))
|
||||
.routes(routes!(handlers::help_chat::help_chat))
|
||||
// CVE notification endpoints
|
||||
.route(
|
||||
"/api/v1/notifications",
|
||||
get(handlers::notifications::list_notifications),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/notifications/count",
|
||||
get(handlers::notifications::notification_count),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/notifications/read-all",
|
||||
post(handlers::notifications::mark_all_read),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/notifications/{id}/read",
|
||||
patch(handlers::notifications::mark_read),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/notifications/{id}/dismiss",
|
||||
patch(handlers::notifications::dismiss_notification),
|
||||
)
|
||||
.routes(routes!(handlers::notifications::list_notifications))
|
||||
.routes(routes!(handlers::notifications::notification_count))
|
||||
.routes(routes!(handlers::notifications::mark_all_read))
|
||||
.routes(routes!(handlers::notifications::mark_read))
|
||||
.routes(routes!(handlers::notifications::dismiss_notification))
|
||||
// Pentest API endpoints
|
||||
.route(
|
||||
"/api/v1/pentest/lookup-repo",
|
||||
get(handlers::pentest::lookup_repo),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/pentest/sessions",
|
||||
get(handlers::pentest::list_sessions).post(handlers::pentest::create_session),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/pentest/sessions/{id}",
|
||||
get(handlers::pentest::get_session),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/pentest/sessions/{id}/chat",
|
||||
post(handlers::pentest::send_message),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/pentest/sessions/{id}/stop",
|
||||
post(handlers::pentest::stop_session),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/pentest/sessions/{id}/pause",
|
||||
post(handlers::pentest::pause_session),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/pentest/sessions/{id}/resume",
|
||||
post(handlers::pentest::resume_session),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/pentest/sessions/{id}/stream",
|
||||
get(handlers::pentest::session_stream),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/pentest/sessions/{id}/attack-chain",
|
||||
get(handlers::pentest::get_attack_chain),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/pentest/sessions/{id}/messages",
|
||||
get(handlers::pentest::get_messages),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/pentest/sessions/{id}/findings",
|
||||
get(handlers::pentest::get_session_findings),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/pentest/sessions/{id}/export",
|
||||
post(handlers::pentest::export_session_report),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/pentest/stats",
|
||||
get(handlers::pentest::pentest_stats),
|
||||
)
|
||||
.routes(routes!(handlers::pentest::lookup_repo))
|
||||
.routes(routes!(
|
||||
handlers::pentest::list_sessions,
|
||||
handlers::pentest::create_session
|
||||
))
|
||||
.routes(routes!(handlers::pentest::get_session))
|
||||
.routes(routes!(handlers::pentest::send_message))
|
||||
.routes(routes!(handlers::pentest::stop_session))
|
||||
.routes(routes!(handlers::pentest::pause_session))
|
||||
.routes(routes!(handlers::pentest::resume_session))
|
||||
.routes(routes!(handlers::pentest::session_stream))
|
||||
.routes(routes!(handlers::pentest::get_attack_chain))
|
||||
.routes(routes!(handlers::pentest::get_messages))
|
||||
.routes(routes!(handlers::pentest::get_session_findings))
|
||||
.routes(routes!(handlers::pentest::export_session_report))
|
||||
.routes(routes!(handlers::pentest::pentest_stats))
|
||||
// Webhook routes live on the separate webhook server (port 3002,
|
||||
// see crate::webhooks::server). The M7.2-C tenant-in-URL form is
|
||||
// `/webhook/{tenant_id}/{platform}/{repo_id}` and the handlers
|
||||
@@ -323,3 +284,140 @@ pub fn build_router() -> Router {
|
||||
// them here on the API server would mismatch the handler
|
||||
// signature, so the routes are not exported.
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The routes the description does not cover yet, as listed.
|
||||
fn undescribed() -> BTreeSet<&'static str> {
|
||||
include_str!("undescribed_routes.txt")
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty() && !l.starts_with('#'))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The paths of the plain route calls in this file (the ones without
|
||||
/// `routes!`).
|
||||
fn plain_routes() -> BTreeSet<String> {
|
||||
let pattern = regex::Regex::new(r#"\.route\(\s*"([^"]+)""#).unwrap();
|
||||
pattern
|
||||
.captures_iter(include_str!("routes.rs"))
|
||||
.map(|c| c[1].to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_route_is_described_or_listed_as_not_yet() {
|
||||
let plain = plain_routes();
|
||||
let listed = undescribed();
|
||||
|
||||
let unlisted: Vec<_> = plain
|
||||
.iter()
|
||||
.filter(|p| !listed.contains(p.as_str()))
|
||||
.collect();
|
||||
assert!(
|
||||
unlisted.is_empty(),
|
||||
"describe these routes with #[utoipa::path] and routes!(…): {unlisted:?}"
|
||||
);
|
||||
let stale: Vec<_> = listed.iter().filter(|p| !plain.contains(**p)).collect();
|
||||
assert!(
|
||||
stale.is_empty(),
|
||||
"described or gone, delete from undescribed_routes.txt: {stale:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_description_has_the_dast_routes_with_parameters_and_auth() {
|
||||
let (_, api) = described_routes().split_for_parts();
|
||||
let api = openapi::with_bearer_auth(api);
|
||||
let doc: serde_json::Value = serde_json::from_str(&api.to_json().unwrap()).unwrap();
|
||||
|
||||
assert!(doc["openapi"].as_str().unwrap().starts_with("3.1"));
|
||||
let paths = &doc["paths"];
|
||||
for (path, method) in [
|
||||
("/api/v1/dast/targets", "get"),
|
||||
("/api/v1/dast/targets", "post"),
|
||||
("/api/v1/dast/targets/{id}/scan", "post"),
|
||||
("/api/v1/dast/scan-runs", "get"),
|
||||
("/api/v1/dast/findings", "get"),
|
||||
("/api/v1/dast/findings/{id}", "get"),
|
||||
] {
|
||||
let operation = &paths[path][method];
|
||||
assert!(operation.is_object(), "{method} {path}");
|
||||
assert_eq!(
|
||||
operation["security"],
|
||||
serde_json::json!([{ "bearer": [] }]),
|
||||
"{method} {path}"
|
||||
);
|
||||
}
|
||||
let id = &paths["/api/v1/dast/findings/{id}"]["get"]["parameters"][0];
|
||||
assert_eq!(id["name"], "id");
|
||||
assert_eq!(id["in"], "path");
|
||||
let page: Vec<&str> = paths["/api/v1/dast/findings"]["get"]["parameters"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|p| p["name"].as_str().unwrap())
|
||||
.collect();
|
||||
assert_eq!(page, ["page", "limit"]);
|
||||
let body = &paths["/api/v1/dast/targets"]["post"]["requestBody"]["content"];
|
||||
assert!(body["application/json"].is_object(), "{body}");
|
||||
assert_eq!(
|
||||
doc["components"]["securitySchemes"]["bearer"]["scheme"],
|
||||
"bearer"
|
||||
);
|
||||
}
|
||||
|
||||
/// Every described operation has a one-line summary (the first paragraph
|
||||
/// of the handler's doc comment, without the route), and every `{name}`
|
||||
/// in its path a path parameter of that name: a reader can call it from
|
||||
/// the description alone.
|
||||
#[test]
|
||||
fn every_described_operation_is_complete() {
|
||||
let (_, api) = described_routes().split_for_parts();
|
||||
let doc: serde_json::Value = serde_json::from_str(&api.to_json().unwrap()).unwrap();
|
||||
let placeholder = regex::Regex::new(r"\{([^}]+)\}").unwrap();
|
||||
|
||||
for (path, item) in doc["paths"].as_object().unwrap() {
|
||||
for (method, operation) in item.as_object().unwrap() {
|
||||
let summary = operation["summary"].as_str().unwrap_or_default();
|
||||
assert!(
|
||||
!summary.is_empty()
|
||||
&& !summary.contains('\n')
|
||||
&& !["GET ", "POST ", "PUT ", "PATCH ", "DELETE "]
|
||||
.iter()
|
||||
.any(|m| summary.starts_with(m))
|
||||
&& !summary.contains("/api/"),
|
||||
"{method} {path}: the summary is the doc comment's first line, \
|
||||
a short sentence without the route: {summary:?}"
|
||||
);
|
||||
let in_path: Vec<&str> = operation["parameters"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|p| p["in"] == "path")
|
||||
.filter_map(|p| p["name"].as_str())
|
||||
.collect();
|
||||
for name in placeholder.captures_iter(path) {
|
||||
assert!(
|
||||
in_path.contains(&&name[1]),
|
||||
"{method} {path} has no path parameter {}",
|
||||
&name[1]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_description_is_behind_the_customer_authentication() {
|
||||
assert!(!compliance_core::auth::bypasses_customer_auth(
|
||||
openapi::SPEC_PATH
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ use compliance_core::{OrgRole, TenantContext, TenantStatus};
|
||||
use crate::agent::ComplianceAgent;
|
||||
use crate::api::handlers;
|
||||
use crate::api::handlers::platform::{self, PlatformState};
|
||||
use crate::api::handlers::supplier_invites;
|
||||
use crate::api::{role_gate, routes};
|
||||
use crate::error::AgentError;
|
||||
|
||||
@@ -365,6 +366,32 @@ pub async fn start_api_server(
|
||||
.put(platform::put_git_source)
|
||||
.delete(platform::delete_git_source),
|
||||
)
|
||||
// Supplier invites (#1027): the portal invites a supplier to upload
|
||||
// one component's SBOM.
|
||||
.route(
|
||||
"/api/v1/platform/tenants/{id}/supplier-invites",
|
||||
get(supplier_invites::list_invites).post(supplier_invites::create_invite),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/withdraw",
|
||||
post(supplier_invites::withdraw_invite),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/supplier-view",
|
||||
get(supplier_invites::supplier_view),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/sboms",
|
||||
post(supplier_invites::upload_through_invite).layer(DefaultBodyLimit::max(
|
||||
crate::pipeline::sbom::supplied::MAX_BYTES as usize + routes::MULTIPART_OVERHEAD,
|
||||
)),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/sboms/check",
|
||||
post(supplier_invites::check_through_invite).layer(DefaultBodyLimit::max(
|
||||
crate::pipeline::sbom::supplied::MAX_BYTES as usize + routes::MULTIPART_OVERHEAD,
|
||||
)),
|
||||
)
|
||||
.layer(middleware::from_fn_with_state(
|
||||
platform_state.clone(),
|
||||
platform::require_platform_token,
|
||||
@@ -444,7 +471,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:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
# Routes of the customer API (routes.rs) that the OpenAPI description does
|
||||
# not cover yet (#1006), one path per line. A test fails when a plain
|
||||
# `.route("...")` in routes.rs is missing here, or when a line here names no
|
||||
# such route, so the list only ever shrinks. Describe a route with
|
||||
# `#[utoipa::path]` and `.routes(routes!(...))`, then delete its line.
|
||||
/api/v1/targets/{id}/cves
|
||||
/api/v1/targets/{id}/cve-matrix
|
||||
/api/v1/cve-history
|
||||
/api/v1/targets/{id}/top-updates
|
||||
/api/v1/targets/{id}/scan-changes
|
||||
/api/v1/targets/{id}/vex
|
||||
/api/v1/targets/{id}/csaf
|
||||
/api/v1/targets/{id}/enisa
|
||||
/api/v1/cves/{id}/enisa
|
||||
/api/v1/cves/{id}/vex
|
||||
/api/v1/targets/{id}/cve-groups
|
||||
/api/v1/targets/{id}/cve-groups/vex
|
||||
/api/v1/targets/{id}/sbom-ecosystems
|
||||
@@ -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"),
|
||||
@@ -82,8 +87,6 @@ fn build_config(app_env: AppEnv) -> Result<AgentConfig, AgentError> {
|
||||
.unwrap_or_else(|| "/data/compliance-scanner/artifacts".to_string()),
|
||||
keycloak_url: env_var_opt("KEYCLOAK_URL"),
|
||||
keycloak_realm: env_var_opt("KEYCLOAK_REALM"),
|
||||
keycloak_admin_username: env_var_opt("KEYCLOAK_ADMIN_USERNAME"),
|
||||
keycloak_admin_password: env_secret_opt("KEYCLOAK_ADMIN_PASSWORD"),
|
||||
pentest_verification_email: env_var_opt("PENTEST_VERIFICATION_EMAIL"),
|
||||
pentest_imap_host: env_var_opt("PENTEST_IMAP_HOST"),
|
||||
pentest_imap_port: env_var_opt("PENTEST_IMAP_PORT").and_then(|p| p.parse().ok()),
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -20,7 +20,7 @@ use crate::fixtures::{DemoTarget, DemoTargets, FixtureError};
|
||||
use crate::targets;
|
||||
|
||||
/// What the caller asked to seed.
|
||||
#[derive(Debug, Clone, Default, Deserialize)]
|
||||
#[derive(Debug, Clone, Default, Deserialize, utoipa::ToSchema)]
|
||||
pub struct SeedRequest {
|
||||
/// Manifest keys to seed; empty seeds every target.
|
||||
#[serde(default)]
|
||||
@@ -166,6 +166,8 @@ async fn seed_one(
|
||||
let mut target =
|
||||
compliance_core::models::OnboardedTarget::new(full_name.to_string(), demo.target_type);
|
||||
target.description = demo.description.clone();
|
||||
target.demo = true;
|
||||
target.devices = demo.devices.clone();
|
||||
for a in demo.artifacts.iter().filter(|a| !a.is_upload()) {
|
||||
match a.resolved_source_ref() {
|
||||
Some(source_ref) => target.artifacts.push(targets::reference_artifact(
|
||||
|
||||
@@ -42,6 +42,16 @@ 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),
|
||||
|
||||
/// A new target the plan has no room for: as many targets are active
|
||||
/// as it allows (the entry plan's `extra_targets: 0`).
|
||||
#[error("the plan allows {0} active targets")]
|
||||
TargetLimit(u32),
|
||||
|
||||
#[error("{0}")]
|
||||
Other(String),
|
||||
}
|
||||
@@ -73,6 +83,8 @@ impl AgentError {
|
||||
| Self::Config(_)
|
||||
| Self::Secret(_)
|
||||
| Self::Exec(_)
|
||||
| Self::NotAdmitted(_)
|
||||
| Self::TargetLimit(_)
|
||||
| Self::Other(_) => (
|
||||
RunErrorCode::Internal,
|
||||
"the scan stopped because of an internal error",
|
||||
@@ -85,6 +97,7 @@ impl From<AgentError> for axum::http::StatusCode {
|
||||
fn from(err: AgentError) -> Self {
|
||||
match err {
|
||||
AgentError::Core(CoreError::NotFound(_)) => axum::http::StatusCode::NOT_FOUND,
|
||||
AgentError::TargetLimit(_) => axum::http::StatusCode::CONFLICT,
|
||||
_ => axum::http::StatusCode::INTERNAL_SERVER_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");
|
||||
|
||||
@@ -349,7 +349,7 @@ fn json<T: Serialize>(value: &T) -> Result<Vec<u8>, AgentError> {
|
||||
/// The findings as CSV, one row each, for a spreadsheet.
|
||||
fn findings_csv(findings: &[Finding]) -> String {
|
||||
let mut out =
|
||||
String::from("id,severity,status,type,scanner,rule_id,cwe,location,title,cra_controls\n");
|
||||
String::from("id,severity,status,type,scanner,rule_id,cwe,location,title,cra_controls,cra_requirements\n");
|
||||
for f in findings {
|
||||
let location = match (&f.file_path, f.line_number) {
|
||||
(Some(file), Some(line)) => format!("{file}:{line}"),
|
||||
@@ -367,6 +367,13 @@ fn findings_csv(findings: &[Finding]) -> String {
|
||||
location,
|
||||
f.title.clone(),
|
||||
f.control_refs.join(" "),
|
||||
// The same requirements by name, for a person reading the sheet.
|
||||
f.control_refs
|
||||
.iter()
|
||||
.filter_map(|id| compliance_core::cra_requirements::name(id))
|
||||
.map(|name| name.de)
|
||||
.collect::<Vec<_>>()
|
||||
.join("; "),
|
||||
];
|
||||
let cells: Vec<String> = row.iter().map(|c| csv_cell(c)).collect();
|
||||
out.push_str(&cells.join(","));
|
||||
@@ -531,7 +538,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,
|
||||
@@ -633,6 +643,10 @@ mod tests {
|
||||
"{csv}"
|
||||
);
|
||||
assert!(csv.contains("Core/Src/comms.c:9"));
|
||||
assert!(
|
||||
csv.contains(",cra-ai-8,Keine Standardpasswörter\n"),
|
||||
"{csv}"
|
||||
);
|
||||
assert_eq!(csv_cell("=HYPERLINK(1)"), "'=HYPERLINK(1)");
|
||||
assert_eq!(csv_cell("plain"), "plain");
|
||||
}
|
||||
|
||||
@@ -117,6 +117,10 @@ pub struct DemoTarget {
|
||||
/// Applied by the nightly harness to the fixtures it onboards itself.
|
||||
#[serde(default)]
|
||||
pub enabled_scans: Vec<String>,
|
||||
/// Siemens controllers the target runs on (SPS item 4a), stored with the
|
||||
/// target so its SBOM lists them and Siemens' advisories match them.
|
||||
#[serde(default)]
|
||||
pub devices: Vec<compliance_core::models::PlcDevice>,
|
||||
/// Golden baseline for the nightly regression.
|
||||
#[serde(default)]
|
||||
pub expect: Expect,
|
||||
@@ -491,6 +495,32 @@ mod tests {
|
||||
assert_eq!(on_disk.name_prefix, bundled.name_prefix);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn demo_devices_are_stored_as_the_api_would_store_them() {
|
||||
// Arrange
|
||||
let m = manifest();
|
||||
let pump = m
|
||||
.targets
|
||||
.iter()
|
||||
.find(|t| t.key == "plc-pump-station")
|
||||
.expect("pump station in the manifest");
|
||||
|
||||
// Assert: a controller on a firmware Siemens names as affected
|
||||
// (SSA-876787: below V2.9.8), so the demo SBOM is not empty.
|
||||
assert!(!pump.devices.is_empty());
|
||||
for t in &m.targets {
|
||||
for d in &t.devices {
|
||||
let normalised = compliance_core::models::PlcDevice::new(
|
||||
&d.order_number,
|
||||
&d.firmware,
|
||||
d.label.as_deref(),
|
||||
)
|
||||
.expect("a valid controller");
|
||||
assert_eq!(&normalised, d, "{}: store it normalised", t.key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manifest_is_well_formed() {
|
||||
let m = manifest();
|
||||
@@ -589,6 +619,7 @@ mod tests {
|
||||
optional: true,
|
||||
}],
|
||||
enabled_scans: Vec::new(),
|
||||
devices: Vec::new(),
|
||||
expect: Expect::default(),
|
||||
};
|
||||
assert!(t.source_only());
|
||||
|
||||
@@ -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,10 +458,19 @@ 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),
|
||||
}
|
||||
|
||||
/// Why a delivery for a repository without a target makes none: the plan's
|
||||
/// targets are all active (`extra_targets: 0`).
|
||||
const NO_ROOM: &str = "the plan allows no further active target";
|
||||
|
||||
/// Carry out a routed delivery for `tenant_id`.
|
||||
///
|
||||
/// # Errors
|
||||
@@ -476,7 +489,10 @@ pub async fn apply_action(
|
||||
archive_target(db, &source.base_url, repo.id).await?,
|
||||
)),
|
||||
SourceAction::Created(repo) => {
|
||||
let ensured = ensure_target(agent, db, tenant_id, source, &repo).await?;
|
||||
let ensured = match ensure_target(agent, db, tenant_id, source, &repo).await {
|
||||
Err(AgentError::TargetLimit(_)) => return Ok(Outcome::Ignored(NO_ROOM)),
|
||||
ensured => ensured?,
|
||||
};
|
||||
// An empty repository has nothing to scan; its first push will.
|
||||
let scan = ensured.created && !repo.empty;
|
||||
if scan {
|
||||
@@ -488,13 +504,34 @@ pub async fn apply_action(
|
||||
})
|
||||
}
|
||||
SourceAction::Push(repo) => {
|
||||
let ensured = ensure_target(agent, db, tenant_id, source, &repo).await?;
|
||||
let ensured = match ensure_target(agent, db, tenant_id, source, &repo).await {
|
||||
Err(AgentError::TargetLimit(_)) => return Ok(Outcome::Ignored(NO_ROOM)),
|
||||
ensured => ensured?,
|
||||
};
|
||||
spawn_scan(agent, tenant_id, &ensured.target_id, ScanTrigger::Webhook);
|
||||
Ok(Outcome::Ensured {
|
||||
target_id: ensured.target_id,
|
||||
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),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -581,6 +618,11 @@ pub async fn sync_with<L: RepoLister>(
|
||||
}
|
||||
}
|
||||
Ok(_) => report.refreshed += 1,
|
||||
// Not an error: the next sync tries again, once a target is
|
||||
// archived or the plan changed.
|
||||
Err(AgentError::TargetLimit(cap)) => {
|
||||
tracing::info!(tenant_id, repo = %repo.full_name, cap, "managed git sync: no target, the plan's targets are all active");
|
||||
}
|
||||
Err(err) => {
|
||||
tracing::warn!(tenant_id, repo = %repo.full_name, "managed git sync: {err}");
|
||||
}
|
||||
|
||||
@@ -18,15 +18,20 @@ const MAX_EVIDENCE_CHARS: usize = 4_000;
|
||||
|
||||
/// What a finding from a manual test says, whether typed into the form or
|
||||
/// read from a report.
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq)]
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq, utoipa::ToSchema)]
|
||||
pub struct ManualFinding {
|
||||
/// What was found.
|
||||
pub title: String,
|
||||
/// The finding in detail.
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
/// `info`, `low`, `medium`, `high` or `critical`.
|
||||
#[schema(value_type = String, example = "high")]
|
||||
pub severity: Severity,
|
||||
/// `CWE-79`, or just `79`.
|
||||
#[serde(default)]
|
||||
pub cwe: Option<String>,
|
||||
/// The CVSS base score.
|
||||
#[serde(default)]
|
||||
pub cvss_score: Option<f64>,
|
||||
/// Where it was found: a URL, an endpoint, a file.
|
||||
@@ -35,8 +40,10 @@ pub struct ManualFinding {
|
||||
/// A request or response excerpt that shows it.
|
||||
#[serde(default)]
|
||||
pub evidence: Option<String>,
|
||||
/// How to reproduce it.
|
||||
#[serde(default)]
|
||||
pub reproduction: Option<String>,
|
||||
/// How to fix it.
|
||||
#[serde(default)]
|
||||
pub remediation: Option<String>,
|
||||
/// The tool's rule or plugin id, for an imported finding.
|
||||
@@ -102,7 +109,7 @@ pub fn normalise_cwe(raw: &str) -> Option<String> {
|
||||
|
||||
/// The CRA controls a verified weakness is evidence for (see
|
||||
/// [`control_map::ControlMap::controls_for_cwe`]).
|
||||
fn control_refs(cwe: &str) -> Vec<String> {
|
||||
pub(crate) fn control_refs(cwe: &str) -> Vec<String> {
|
||||
control_map::ControlMap::cra()
|
||||
.map(|map| {
|
||||
map.controls_for_cwe(cwe)
|
||||
|
||||
@@ -189,7 +189,11 @@ 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, and a
|
||||
// supplier's SBOM is read as the document it is.
|
||||
ArtifactKind::FirmwareImage | ArtifactKind::BuildOutput | ArtifactKind::SupplierSbom => {
|
||||
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,584 @@
|
||||
//! 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.
|
||||
//! A plan that allows no extra target (the entry plan) includes them all.
|
||||
//! 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>,
|
||||
/// How many extra targets may be active besides; `None` is unlimited.
|
||||
pub extra_targets: Option<u32>,
|
||||
/// The quota and the customer's Prüftag cap.
|
||||
pub limits: PlanLimits,
|
||||
}
|
||||
|
||||
impl Plan {
|
||||
/// How many targets may be active at once: the included ones and the
|
||||
/// extra ones the plan allows. `None` when either is unlimited, as on
|
||||
/// every plan that bills extra targets.
|
||||
pub fn target_cap(&self) -> Option<u32> {
|
||||
Some(self.included_targets?.saturating_add(self.extra_targets?))
|
||||
}
|
||||
|
||||
/// How many targets the billing split includes; `None` includes every
|
||||
/// active target. A plan that allows no extra target bills none as
|
||||
/// extra, not even those already active beyond its included ones.
|
||||
pub fn billed_included(&self) -> Option<u32> {
|
||||
match self.extra_targets {
|
||||
Some(0) => None,
|
||||
_ => self.included_targets,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 only_a_plan_capping_both_counts_caps_the_active_targets() {
|
||||
let plan = |included_targets, extra_targets| Plan {
|
||||
included_targets,
|
||||
extra_targets,
|
||||
..Plan::default()
|
||||
};
|
||||
assert_eq!(plan(Some(3), Some(0)).target_cap(), Some(3), "entry");
|
||||
assert_eq!(plan(Some(3), Some(2)).target_cap(), Some(5));
|
||||
assert_eq!(plan(Some(5), None).target_cap(), None, "extras billed");
|
||||
assert_eq!(plan(None, Some(0)).target_cap(), None, "all included");
|
||||
assert_eq!(plan(Some(u32::MAX), Some(1)).target_cap(), Some(u32::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plan_allowing_no_extra_target_bills_none_as_extra() {
|
||||
let plan = |included_targets, extra_targets| Plan {
|
||||
included_targets,
|
||||
extra_targets,
|
||||
limits: PlanLimits::default(),
|
||||
};
|
||||
assert_eq!(plan(Some(2), Some(0)).billed_included(), None, "entry");
|
||||
assert_eq!(plan(Some(5), None).billed_included(), Some(5));
|
||||
assert_eq!(plan(Some(5), Some(2)).billed_included(), Some(5));
|
||||
assert_eq!(plan(None, None).billed_included(), None);
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -14,6 +14,7 @@ use crate::database::Database;
|
||||
use crate::llm::{
|
||||
ChatMessage, LlmClient, LlmResponse, ToolCallRequest, ToolCallRequestFunction, ToolDefinition,
|
||||
};
|
||||
use crate::pentest::cleanup::CleanupOutcome;
|
||||
|
||||
/// Maximum duration for a single pentest session before timeout
|
||||
const SESSION_TIMEOUT: Duration = Duration::from_secs(30 * 60); // 30 minutes
|
||||
@@ -24,6 +25,8 @@ pub struct PentestOrchestrator {
|
||||
pub(crate) db: Database,
|
||||
pub(crate) event_tx: broadcast::Sender<PentestEvent>,
|
||||
pub(crate) pause_rx: Option<watch::Receiver<bool>>,
|
||||
/// Outbound policy for tenant-chosen URLs, the test-user cleanup's too.
|
||||
pub(crate) net_guard: NetGuard,
|
||||
}
|
||||
|
||||
impl PentestOrchestrator {
|
||||
@@ -42,6 +45,55 @@ impl PentestOrchestrator {
|
||||
db,
|
||||
event_tx,
|
||||
pause_rx,
|
||||
net_guard,
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete the session's test user with the access given for the target's
|
||||
/// identity provider, and record on the session what became of it.
|
||||
async fn clean_up_test_user(
|
||||
&self,
|
||||
session_id: Option<mongodb::bson::oid::ObjectId>,
|
||||
test_user: &TestUserRecord,
|
||||
access: Option<&TestUserCleanup>,
|
||||
) {
|
||||
let outcome = match compliance_core::guarded_net::guarded_client_builder(self.net_guard)
|
||||
.timeout(std::time::Duration::from_secs(30))
|
||||
.build()
|
||||
{
|
||||
Ok(http) => crate::pentest::cleanup::cleanup_test_user(test_user, access, &http).await,
|
||||
Err(e) => Err(format!("no HTTP client: {e}")),
|
||||
};
|
||||
let left_behind = match outcome {
|
||||
Ok(CleanupOutcome::Deleted) | Ok(CleanupOutcome::NotRegistered) => None,
|
||||
Ok(CleanupOutcome::LeftBehind(reason)) => Some(reason),
|
||||
Err(e) => Some(format!("cleanup failed: {e}")),
|
||||
};
|
||||
match &left_behind {
|
||||
None => tracing::info!("Pentest test user deleted"),
|
||||
Some(reason) => {
|
||||
tracing::warn!(reason = %reason, "Pentest test user left behind");
|
||||
let _ = self.event_tx.send(PentestEvent::Message {
|
||||
content: format!(
|
||||
"The test user {} is still registered with the application ({reason}); \
|
||||
delete it by hand.",
|
||||
test_user.email.as_deref().unwrap_or("(unknown)")
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(sid) = session_id {
|
||||
let _ = self
|
||||
.db
|
||||
.pentest_sessions()
|
||||
.update_one(
|
||||
doc! { "_id": sid },
|
||||
doc! { "$set": {
|
||||
"test_user.cleaned_up": left_behind.is_none(),
|
||||
"test_user.left_behind": left_behind,
|
||||
} },
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -499,55 +551,12 @@ impl PentestOrchestrator {
|
||||
.await;
|
||||
}
|
||||
|
||||
// Clean up test user via identity provider API if requested
|
||||
if session
|
||||
.config
|
||||
.as_ref()
|
||||
.is_some_and(|c| c.auth.cleanup_test_user)
|
||||
// Delete the test user in the target's identity provider if asked.
|
||||
if let (Some(cfg), Some(test_user)) = (session.config.as_ref(), session.test_user.as_ref())
|
||||
{
|
||||
if let Some(ref test_user) = session.test_user {
|
||||
let http = reqwest::Client::new();
|
||||
// We need the AgentConfig — read from env since orchestrator doesn't hold it
|
||||
let config = crate::config::load_config();
|
||||
match config {
|
||||
Ok(cfg) => {
|
||||
match crate::pentest::cleanup::cleanup_test_user(test_user, &cfg, &http)
|
||||
.await
|
||||
{
|
||||
Ok(true) => {
|
||||
tracing::info!(
|
||||
username = test_user.username.as_deref(),
|
||||
"Test user cleaned up via provider API"
|
||||
);
|
||||
// Mark as cleaned up in DB
|
||||
if let Some(sid) = session.id {
|
||||
let _ = self
|
||||
.db
|
||||
.pentest_sessions()
|
||||
.update_one(
|
||||
doc! { "_id": sid },
|
||||
doc! { "$set": { "test_user.cleaned_up": true } },
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
Ok(false) => {
|
||||
tracing::info!(
|
||||
"Test user cleanup skipped (no provider configured)"
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "Test user cleanup failed");
|
||||
let _ = self.event_tx.send(PentestEvent::Error {
|
||||
message: format!("Test user cleanup failed: {e}"),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "Could not load config for cleanup");
|
||||
}
|
||||
}
|
||||
if cfg.auth.cleanup_test_user {
|
||||
self.clean_up_test_user(session.id, test_user, cfg.auth.cleanup.as_ref())
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,8 @@ use compliance_core::models::sbom::SbomEntry;
|
||||
use super::orchestrator::PentestOrchestrator;
|
||||
|
||||
/// Build additional prompt sections from PentestConfig when present.
|
||||
fn build_config_sections(config: &PentestConfig) -> String {
|
||||
/// `test_email` is the address an auto-register session registers with.
|
||||
fn build_config_sections(config: &PentestConfig, test_email: Option<&str>) -> String {
|
||||
let mut sections = String::new();
|
||||
|
||||
// Authentication section
|
||||
@@ -35,13 +36,11 @@ fn build_config_sections(config: &PentestConfig) -> String {
|
||||
"- **Registration URL**: Not provided — use Playwright to discover the registration page.\n",
|
||||
);
|
||||
}
|
||||
if let Some(ref email) = config.auth.verification_email {
|
||||
if let Some(email) = test_email {
|
||||
sections.push_str(&format!(
|
||||
"- **Verification Email**: Use plus-addressing from `{email}` \
|
||||
(e.g. `{base}+{{session_id}}@{domain}`) for email verification. \
|
||||
The system will poll the IMAP mailbox for verification links.\n",
|
||||
base = email.split('@').next().unwrap_or(email),
|
||||
domain = email.split('@').nth(1).unwrap_or("example.com"),
|
||||
"- **E-mail address**: Register with exactly `{email}` (no other \
|
||||
address): the system polls its mailbox for verification links and \
|
||||
finds the test account by it afterwards.\n",
|
||||
));
|
||||
}
|
||||
sections.push_str(
|
||||
@@ -245,7 +244,10 @@ impl PentestOrchestrator {
|
||||
let config_sections = session
|
||||
.config
|
||||
.as_ref()
|
||||
.map(build_config_sections)
|
||||
.map(|c| {
|
||||
let test_email = session.test_user.as_ref().and_then(|u| u.email.as_deref());
|
||||
build_config_sections(c, test_email)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
format!(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::{html_escape, tool_category};
|
||||
use compliance_core::models::pentest::{AuthMode, PentestConfig, PentestSession};
|
||||
use compliance_core::models::pentest::{AuthMode, PentestConfig, PentestSession, TestUserRecord};
|
||||
|
||||
pub(super) fn scope(
|
||||
session: &PentestSession,
|
||||
@@ -43,6 +43,9 @@ pub(super) fn scope(
|
||||
AuthMode::AutoRegister => "Auto-register",
|
||||
};
|
||||
rows.push_str(&format!("<tr><td>Auth Mode</td><td>{auth_mode}</td></tr>"));
|
||||
if let Some(user) = &session.test_user {
|
||||
rows.push_str(&test_user_row(user));
|
||||
}
|
||||
if !cfg.scope_exclusions.is_empty() {
|
||||
let excl = cfg
|
||||
.scope_exclusions
|
||||
@@ -125,3 +128,47 @@ pub(super) fn scope(
|
||||
success_rate = session.success_rate(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The report row for the session's test user: deleted, or still registered
|
||||
/// with the application and to be deleted by hand.
|
||||
fn test_user_row(user: &TestUserRecord) -> String {
|
||||
let email = html_escape(user.email.as_deref().unwrap_or("(unknown)"));
|
||||
let state = match (&user.left_behind, user.cleaned_up) {
|
||||
(Some(reason), _) => format!(
|
||||
"<strong>Left behind</strong>: still registered with the application, \
|
||||
delete it by hand ({})",
|
||||
html_escape(reason)
|
||||
),
|
||||
(None, true) => "Deleted after the test".to_string(),
|
||||
(None, false) => "Not deleted (cleanup was not requested)".to_string(),
|
||||
};
|
||||
format!("<tr><td>Test User</td><td><code>{email}</code> — {state}</td></tr>")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test_user_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_left_behind_test_user_is_named_with_its_reason() {
|
||||
let user = TestUserRecord {
|
||||
email: Some("pentest+1@mail.example.com".into()),
|
||||
left_behind: Some("no admin access <given>".into()),
|
||||
..Default::default()
|
||||
};
|
||||
let row = test_user_row(&user);
|
||||
assert!(row.contains("pentest+1@mail.example.com"));
|
||||
assert!(row.contains("Left behind"));
|
||||
assert!(row.contains("no admin access <given>"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deleted_test_user_says_so() {
|
||||
let user = TestUserRecord {
|
||||
email: Some("pentest+1@mail.example.com".into()),
|
||||
cleaned_up: true,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(test_user_row(&user).contains("Deleted after the test"));
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -93,6 +93,46 @@ impl Provider {
|
||||
max_age: Some(CISA_MAX_AGE),
|
||||
}
|
||||
}
|
||||
|
||||
/// A supplier's provider a tenant named for a bought-in component (#1025),
|
||||
/// keyed by its metadata URL ([`supplier_key`]).
|
||||
pub(crate) fn supplier(metadata_url: &str) -> Self {
|
||||
Self {
|
||||
name: supplier_key(metadata_url),
|
||||
metadata_url: metadata_url.to_string(),
|
||||
feed_filter: None,
|
||||
max_age: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// When a supplier's provider was last read, and whether it could be
|
||||
/// (#1025): kept per tenant in [`SupplierProviderStatus::COLLECTION`], so the
|
||||
/// target editor can tell a provider without advisories from one never or no
|
||||
/// longer read.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) struct SupplierProviderStatus {
|
||||
/// The provider's key ([`supplier_key`]).
|
||||
#[serde(rename = "_id")]
|
||||
pub provider: String,
|
||||
/// When the last refresh read it.
|
||||
pub checked_at: mongodb::bson::DateTime,
|
||||
/// Whether its metadata and feeds could be read then.
|
||||
pub reachable: bool,
|
||||
}
|
||||
|
||||
impl SupplierProviderStatus {
|
||||
/// The collection, in the tenant's own database.
|
||||
pub(crate) const COLLECTION: &'static str = "supplier_csaf_providers";
|
||||
}
|
||||
|
||||
/// The prefix of a supplier provider's key, which tells its advisories from
|
||||
/// the shared providers' ([`Provider::supplier`]).
|
||||
pub(crate) const SUPPLIER_PREFIX: &str = "supplier:";
|
||||
|
||||
/// The key a supplier's advisories are stored and matched under.
|
||||
pub(crate) fn supplier_key(metadata_url: &str) -> String {
|
||||
format!("{SUPPLIER_PREFIX}{}", metadata_url.trim())
|
||||
}
|
||||
|
||||
/// The providers `PW_CSAF_PROVIDERS` names: `off` (none), unset or `default`
|
||||
@@ -224,6 +264,19 @@ impl MongoAdvisoryStore {
|
||||
pub(crate) fn collection(&self) -> &mongodb::Collection<StoredAdvisory> {
|
||||
&self.collection
|
||||
}
|
||||
|
||||
/// The collection of a tenant's supplier advisories (#1025), in the
|
||||
/// tenant's own database.
|
||||
pub(crate) const SUPPLIER_COLLECTION: &'static str = "supplier_csaf_advisories";
|
||||
|
||||
/// The advisories of the suppliers a tenant named (#1025), in its own
|
||||
/// database: a provider one tenant chooses is never matched against
|
||||
/// another tenant's components.
|
||||
pub(crate) fn supplier(tenant_db: &mongodb::Database) -> Self {
|
||||
Self {
|
||||
collection: tenant_db.collection(Self::SUPPLIER_COLLECTION),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AdvisoryStore for MongoAdvisoryStore {
|
||||
@@ -316,6 +369,8 @@ pub(crate) struct Counts {
|
||||
pub failed: usize,
|
||||
/// Left for a later run (over the limits).
|
||||
pub deferred: usize,
|
||||
/// The provider's metadata or feeds could not be read at all.
|
||||
pub unreachable: bool,
|
||||
}
|
||||
|
||||
/// One advisory a feed lists.
|
||||
@@ -456,6 +511,7 @@ pub(crate) async fn refresh(
|
||||
Err(e) => {
|
||||
tracing::warn!(provider = %provider.name, "CSAF provider not read: {e}");
|
||||
counts.failed = 1;
|
||||
counts.unreachable = true;
|
||||
out.insert(provider.name.clone(), counts);
|
||||
continue;
|
||||
}
|
||||
@@ -566,6 +622,99 @@ pub(crate) async fn refresh_index(admin_db: &mongodb::Database, guard: NetGuard)
|
||||
refresh(&fetch, &store, &providers, Limits::default()).await;
|
||||
}
|
||||
|
||||
/// The supplier providers a tenant's active targets name (#1025), once each.
|
||||
pub(crate) fn supplier_providers(
|
||||
targets: &[compliance_core::models::OnboardedTarget],
|
||||
) -> Vec<Provider> {
|
||||
let mut urls: Vec<&str> = targets
|
||||
.iter()
|
||||
.filter(|t| t.archived_at.is_none())
|
||||
.filter_map(|t| t.supplier.as_ref()?.csaf_provider.as_deref())
|
||||
.map(str::trim)
|
||||
.filter(|u| !u.is_empty())
|
||||
.collect();
|
||||
urls.sort_unstable();
|
||||
urls.dedup();
|
||||
urls.into_iter().map(Provider::supplier).collect()
|
||||
}
|
||||
|
||||
/// Bounds of one refresh of a tenant's supplier advisories: fewer than the
|
||||
/// shared index, as one tenant's suppliers publish fewer.
|
||||
fn supplier_limits() -> Limits {
|
||||
Limits {
|
||||
max_advisories: 200,
|
||||
concurrency: 2,
|
||||
budget: Duration::from_secs(5 * 60),
|
||||
}
|
||||
}
|
||||
|
||||
/// Refresh the advisories of the supplier providers tenant `tenant_id`'s
|
||||
/// targets name (#1025), into its own database, through the guarded client.
|
||||
/// Logs and returns on any failure.
|
||||
pub(crate) async fn refresh_supplier_advisories(
|
||||
agent: &crate::agent::ComplianceAgent,
|
||||
tenant_id: &str,
|
||||
) {
|
||||
let db = match agent.db_pool.for_tenant_id(tenant_id).await {
|
||||
Ok(db) => db,
|
||||
Err(e) => {
|
||||
tracing::warn!(tenant_id, "supplier CSAF advisories not refreshed: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let targets: Vec<compliance_core::models::OnboardedTarget> = match db
|
||||
.onboarded_targets()
|
||||
.find(doc! { "supplier.csaf_provider": { "$exists": true }, "archived_at": null })
|
||||
.await
|
||||
{
|
||||
Ok(cursor) => cursor.try_collect().await.unwrap_or_default(),
|
||||
Err(e) => {
|
||||
tracing::warn!(tenant_id, "supplier CSAF providers not read: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let providers = supplier_providers(&targets);
|
||||
if providers.is_empty() {
|
||||
return;
|
||||
}
|
||||
let fetch = match HttpFetch::new(agent.net_guard) {
|
||||
Ok(fetch) => fetch,
|
||||
Err(e) => {
|
||||
tracing::warn!(tenant_id, "supplier CSAF advisories not refreshed: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let store = MongoAdvisoryStore::supplier(db.inner());
|
||||
let counts = refresh(&fetch, &store, &providers, supplier_limits()).await;
|
||||
let statuses = db
|
||||
.inner()
|
||||
.collection::<SupplierProviderStatus>(SupplierProviderStatus::COLLECTION);
|
||||
let checked_at = mongodb::bson::DateTime::now();
|
||||
for (provider, c) in &counts {
|
||||
let status = SupplierProviderStatus {
|
||||
provider: provider.clone(),
|
||||
checked_at,
|
||||
reachable: !c.unreachable,
|
||||
};
|
||||
if let Err(e) = statuses
|
||||
.replace_one(doc! { "_id": provider }, &status)
|
||||
.upsert(true)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(tenant_id, provider, "supplier CSAF status not kept: {e}");
|
||||
}
|
||||
}
|
||||
let stored: usize = counts.values().map(|c| c.stored).sum();
|
||||
let failed: usize = counts.values().map(|c| c.failed).sum();
|
||||
tracing::info!(
|
||||
tenant_id,
|
||||
providers = providers.len(),
|
||||
stored,
|
||||
failed,
|
||||
"supplier CSAF advisories refreshed"
|
||||
);
|
||||
}
|
||||
|
||||
/// A store for tests: advisories in memory.
|
||||
#[cfg(test)]
|
||||
#[derive(Default)]
|
||||
@@ -632,6 +781,33 @@ impl AdvisoryStore for MemoryStore {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_tenants_supplier_providers_are_its_active_targets_once_each() {
|
||||
use compliance_core::models::{OnboardedTarget, SupplierComponent, TargetType};
|
||||
let url = "https://supplier.example/.well-known/csaf/provider-metadata.json";
|
||||
let target = |provider: Option<&str>, archived: bool| {
|
||||
let mut t = OnboardedTarget::new("c".into(), TargetType::FirmwareBareMetal);
|
||||
t.supplier = Some(SupplierComponent {
|
||||
name: "Example GmbH".into(),
|
||||
product: None,
|
||||
version: None,
|
||||
csaf_provider: provider.map(String::from),
|
||||
});
|
||||
t.archived_at = archived.then(chrono::Utc::now);
|
||||
t
|
||||
};
|
||||
let providers = supplier_providers(&[
|
||||
target(Some(url), false),
|
||||
target(Some(&format!(" {url} ")), false),
|
||||
target(Some("https://gone.example/provider-metadata.json"), true),
|
||||
target(None, false),
|
||||
]);
|
||||
assert_eq!(providers.len(), 1);
|
||||
assert_eq!(providers[0].metadata_url, url);
|
||||
assert_eq!(providers[0].name, format!("{SUPPLIER_PREFIX}{url}"));
|
||||
assert!(providers[0].feed_filter.is_none() && providers[0].max_age.is_none());
|
||||
}
|
||||
|
||||
/// A provider answering from a table; counts requests.
|
||||
#[derive(Default)]
|
||||
struct Fake(HashMap<String, Vec<u8>>, std::sync::Mutex<Vec<String>>);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! A target's components against the vendor CSAF advisories in the index
|
||||
//! (#515, see [`super::csaf_feed`]): a CODESYS runtime or library by its
|
||||
//! name and version against CODESYS's advisories, any component with a purl
|
||||
//! against an advisory product with the same purl. A match raises a CVE
|
||||
//! name and version against CODESYS's advisories, a Siemens device by its
|
||||
//! order number and firmware against Siemens' (SPS item 4a), and any
|
||||
//! component with a purl against an advisory product with the same purl. A match raises a CVE
|
||||
//! alert with source `csaf`, or, where OSV or NVD already reported the CVE,
|
||||
//! adds the advisory to that alert; either way the alert links the advisory
|
||||
//! and carries the vendor's remediation and fixed versions.
|
||||
@@ -17,6 +18,10 @@ use compliance_core::version::Vers;
|
||||
|
||||
use super::csaf_feed::{MongoAdvisoryStore, StoredAdvisory};
|
||||
|
||||
/// The provider whose advisories name devices by order number
|
||||
/// ([`compliance_core::models::PlcDevice`]).
|
||||
const ORDER_NUMBER_PROVIDER: &str = "siemens";
|
||||
|
||||
/// The provider whose advisories name the components of a package manager
|
||||
/// by product name.
|
||||
fn provider_for(package_manager: &str) -> Option<&'static str> {
|
||||
@@ -26,29 +31,46 @@ fn provider_for(package_manager: &str) -> Option<&'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the advisory index is asked for, for some components ([`wanted`]).
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct Wanted {
|
||||
/// Providers whose advisories all count ([`provider_for`]).
|
||||
pub providers: Vec<String>,
|
||||
/// Purls without version.
|
||||
pub purls: Vec<String>,
|
||||
/// Device order numbers, normalised.
|
||||
pub order_numbers: Vec<String>,
|
||||
}
|
||||
|
||||
impl Wanted {
|
||||
fn is_empty(&self) -> bool {
|
||||
self.providers.is_empty() && self.purls.is_empty() && self.order_numbers.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the advisory index, behind a trait so tests keep it in memory.
|
||||
pub(crate) trait AdvisoryIndex: Send + Sync {
|
||||
/// The advisories of `providers`, and those naming any of `purls`
|
||||
/// (without version), as `(provider, advisory)`.
|
||||
/// The advisories of `wanted`'s providers, and those naming any of its
|
||||
/// purls (without version) or, of [`ORDER_NUMBER_PROVIDER`], any of its
|
||||
/// order numbers, as `(provider, advisory)`.
|
||||
fn relevant<'a>(
|
||||
&'a self,
|
||||
providers: &'a [String],
|
||||
purls: &'a [String],
|
||||
wanted: &'a Wanted,
|
||||
) -> BoxFuture<'a, Result<Vec<(String, Advisory)>, String>>;
|
||||
}
|
||||
|
||||
impl AdvisoryIndex for MongoAdvisoryStore {
|
||||
fn relevant<'a>(
|
||||
&'a self,
|
||||
providers: &'a [String],
|
||||
purls: &'a [String],
|
||||
wanted: &'a Wanted,
|
||||
) -> BoxFuture<'a, Result<Vec<(String, Advisory)>, String>> {
|
||||
Box::pin(async move {
|
||||
if providers.is_empty() && purls.is_empty() {
|
||||
if wanted.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
// A product's purl may carry a version; compare from the start.
|
||||
let purl_patterns: Vec<mongodb::bson::Regex> = purls
|
||||
let purl_patterns: Vec<mongodb::bson::Regex> = wanted
|
||||
.purls
|
||||
.iter()
|
||||
.map(|p| mongodb::bson::Regex {
|
||||
pattern: format!("^{}(@|$)", regex::escape(p)),
|
||||
@@ -58,8 +80,12 @@ impl AdvisoryIndex for MongoAdvisoryStore {
|
||||
let rows: Vec<StoredAdvisory> = self
|
||||
.collection()
|
||||
.find(doc! { "$or": [
|
||||
{ "provider": { "$in": providers } },
|
||||
{ "provider": { "$in": &wanted.providers } },
|
||||
{ "advisory.products.purl": { "$in": purl_patterns } },
|
||||
{
|
||||
"provider": ORDER_NUMBER_PROVIDER,
|
||||
"advisory.products.model_numbers": { "$in": &wanted.order_numbers },
|
||||
},
|
||||
] })
|
||||
.await
|
||||
.map_err(|e| e.to_string())?
|
||||
@@ -83,11 +109,24 @@ fn purl_base(purl: &str) -> Option<String> {
|
||||
/// Whether advisory product `p` (of `provider`) is `entry`'s component at
|
||||
/// its version.
|
||||
fn names(p: &AdvisoryProduct, provider: &str, entry: &SbomEntry) -> bool {
|
||||
// A device, by its order number and firmware, only in the advisories of
|
||||
// the vendor whose order numbers they are.
|
||||
if let Some(order_number) = entry.order_number.as_deref() {
|
||||
return provider == ORDER_NUMBER_PROVIDER && p.covers_device(order_number, &entry.version);
|
||||
}
|
||||
if provider_for(&entry.package_manager) == Some(provider)
|
||||
&& p.covers(&entry.name, &entry.version)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
// A bought-in product (#1025), by its supplier's name for it, only in
|
||||
// that supplier's own advisories.
|
||||
if entry.package_manager == crate::pipeline::sbom::supplied::SUPPLIER_PRODUCT_MANAGER
|
||||
&& provider.starts_with(crate::pipeline::csaf_feed::SUPPLIER_PREFIX)
|
||||
&& p.covers(&entry.name, &entry.version)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
let (Some(theirs), Some(ours)) = (p.purl.as_deref(), entry.purl.as_deref()) else {
|
||||
return false;
|
||||
};
|
||||
@@ -195,7 +234,12 @@ pub(crate) fn apply(
|
||||
aliases: Vec::new(),
|
||||
});
|
||||
}
|
||||
let fixed = hit.advisory.fixed_versions(hit.vulnerability, &entry.name);
|
||||
let fixed = match entry.order_number.as_deref() {
|
||||
Some(order_number) => hit
|
||||
.advisory
|
||||
.fixed_device_versions(hit.vulnerability, order_number),
|
||||
None => hit.advisory.fixed_versions(hit.vulnerability, &entry.name),
|
||||
};
|
||||
let alert = match alerts.iter_mut().position(|a| a.cve_id == hit.cve) {
|
||||
Some(i) => &mut alerts[i],
|
||||
None => {
|
||||
@@ -247,23 +291,27 @@ pub(crate) fn apply(
|
||||
count
|
||||
}
|
||||
|
||||
/// The providers and purls the index is asked for, for `entries`.
|
||||
pub(crate) fn wanted(entries: &[SbomEntry]) -> (Vec<String>, Vec<String>) {
|
||||
let mut providers: Vec<String> = Vec::new();
|
||||
let mut purls: Vec<String> = Vec::new();
|
||||
/// What the index is asked for, for `entries`.
|
||||
pub(crate) fn wanted(entries: &[SbomEntry]) -> Wanted {
|
||||
let mut wanted = Wanted::default();
|
||||
for entry in entries {
|
||||
if let Some(p) = provider_for(&entry.package_manager) {
|
||||
if !providers.iter().any(|q| q == p) {
|
||||
providers.push(p.to_string());
|
||||
if !wanted.providers.iter().any(|q| q == p) {
|
||||
wanted.providers.push(p.to_string());
|
||||
}
|
||||
}
|
||||
if let Some(base) = entry.purl.as_deref().and_then(purl_base) {
|
||||
if !purls.contains(&base) {
|
||||
purls.push(base);
|
||||
if !wanted.purls.contains(&base) {
|
||||
wanted.purls.push(base);
|
||||
}
|
||||
}
|
||||
if let Some(order_number) = entry.order_number.as_deref() {
|
||||
if !wanted.order_numbers.iter().any(|o| o == order_number) {
|
||||
wanted.order_numbers.push(order_number.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
(providers, purls)
|
||||
wanted
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -292,6 +340,52 @@ mod tests {
|
||||
e
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bought_in_product_is_matched_only_by_its_own_suppliers_advisory() {
|
||||
// #1025: the product itself, named as its supplier names it, against
|
||||
// that supplier's advisories; the same advisory under a shared
|
||||
// provider's key does not name it.
|
||||
let advisory = codesys_advisory();
|
||||
let product = |version: &str| {
|
||||
let mut e = SbomEntry::new(
|
||||
"t".into(),
|
||||
"CODESYS Control for Linux SL".into(),
|
||||
version.into(),
|
||||
crate::pipeline::sbom::supplied::SUPPLIER_PRODUCT_MANAGER.into(),
|
||||
);
|
||||
e.evidence = vec!["supplied by Example GmbH".into()];
|
||||
e
|
||||
};
|
||||
let supplier = crate::pipeline::csaf_feed::supplier_key(
|
||||
"https://supplier.example/.well-known/csaf/provider-metadata.json",
|
||||
);
|
||||
|
||||
let mut entries = vec![product("3.5.16.0"), product("3.5.22.40")];
|
||||
let mut alerts = Vec::new();
|
||||
let n = apply(
|
||||
"t",
|
||||
&mut entries,
|
||||
&[(supplier, advisory.clone())],
|
||||
&mut alerts,
|
||||
);
|
||||
assert_eq!(n, 1, "only the version below the fix");
|
||||
assert_eq!(alerts[0].cve_id, "CVE-2026-90001");
|
||||
assert_eq!(alerts[0].affected_version, "3.5.16.0");
|
||||
|
||||
let mut entries = vec![product("3.5.16.0")];
|
||||
let mut alerts = Vec::new();
|
||||
let n = apply(
|
||||
"t",
|
||||
&mut entries,
|
||||
&[("siemens".to_string(), advisory)],
|
||||
&mut alerts,
|
||||
);
|
||||
assert_eq!(
|
||||
n, 0,
|
||||
"a shared provider's advisory does not name a supplier product"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_codesys_runtime_below_the_fix_gets_the_advisory() {
|
||||
let advisories = vec![("codesys".to_string(), codesys_advisory())];
|
||||
@@ -410,10 +504,104 @@ mod tests {
|
||||
assert_eq!(alerts[0].affected_version, "3.1.0");
|
||||
assert_eq!(
|
||||
wanted(&entries),
|
||||
(
|
||||
Vec::new(),
|
||||
vec!["pkg:generic/example/fieldbus-stack".to_string()]
|
||||
)
|
||||
Wanted {
|
||||
purls: vec!["pkg:generic/example/fieldbus-stack".to_string()],
|
||||
..Wanted::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/// The synthetic Siemens-shaped advisory of the core fixtures, as
|
||||
/// `provider`'s.
|
||||
fn siemens_advisory(provider: &str) -> (String, Advisory) {
|
||||
let doc: serde_json::Value = serde_json::from_str(include_str!(
|
||||
"../../../compliance-core/tests/fixtures/csaf/siemens-synthetic.json"
|
||||
))
|
||||
.unwrap();
|
||||
(
|
||||
provider.to_string(),
|
||||
compliance_core::csaf_ingest::parse(&doc).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
fn device(order_number: &str, firmware: &str) -> SbomEntry {
|
||||
let device = compliance_core::models::PlcDevice::new(order_number, firmware, None).unwrap();
|
||||
crate::pipeline::sbom::devices::entries(&[device], "t").remove(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_device_matches_the_advisories_naming_its_order_number_and_firmware() {
|
||||
let advisories = vec![siemens_advisory(ORDER_NUMBER_PROVIDER)];
|
||||
let mut entries = vec![
|
||||
device("6es7511-1ak02-0ab0", "V3.1.4"),
|
||||
device("6ES7511-1AK02-0AB0", "3.1.5"),
|
||||
device("6ES7513-1AL02-0AB0", "2.9.7"),
|
||||
device("6ES7512-1DK01-0AB0", "1.0"),
|
||||
];
|
||||
let mut alerts = Vec::new();
|
||||
|
||||
let matched = apply("t", &mut entries, &advisories, &mut alerts);
|
||||
|
||||
// Below the fixed firmware, and in an advisory for every version; not
|
||||
// at the fixed firmware, and not a CPU the advisory does not name.
|
||||
assert_eq!(matched, 2);
|
||||
let affected: Vec<(&str, &str)> = alerts
|
||||
.iter()
|
||||
.map(|a| (a.affected_package.as_str(), a.affected_version.as_str()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
affected,
|
||||
[("6ES7511-1AK02-0AB0", "3.1.4")],
|
||||
"one alert per CVE"
|
||||
);
|
||||
let alert = &alerts[0];
|
||||
assert_eq!(alert.cve_id, "CVE-2026-90101");
|
||||
assert_eq!(alert.fixed_versions, ["3.1.5"]);
|
||||
assert_eq!(alert.severity.as_deref(), Some("HIGH"));
|
||||
let advisory = &alert.advisories[0];
|
||||
assert_eq!(advisory.id, "SSA-900001");
|
||||
assert!(advisory
|
||||
.remediation
|
||||
.as_deref()
|
||||
.is_some_and(|r| r.contains("Update to V3.1.5")));
|
||||
assert!(entries[2]
|
||||
.known_vulnerabilities
|
||||
.iter()
|
||||
.any(|v| v.id == "CVE-2026-90101"));
|
||||
assert!(entries[1].known_vulnerabilities.is_empty());
|
||||
assert!(entries[3].known_vulnerabilities.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_device_is_matched_only_against_the_vendor_of_its_order_number() {
|
||||
let advisories = vec![siemens_advisory("codesys"), siemens_advisory("supplier:x")];
|
||||
let mut entries = vec![device("6ES7511-1AK02-0AB0", "3.1.4")];
|
||||
let mut alerts = Vec::new();
|
||||
assert_eq!(apply("t", &mut entries, &advisories, &mut alerts), 0);
|
||||
|
||||
// And a component with that name is not a device.
|
||||
let named = SbomEntry::new(
|
||||
"t".into(),
|
||||
"Example S7-1500 CPU 1511-1 PN (6ES7511-1AK02-0AB0)".into(),
|
||||
"3.1.4".into(),
|
||||
"supplier-product".into(),
|
||||
);
|
||||
let advisories = vec![siemens_advisory(ORDER_NUMBER_PROVIDER)];
|
||||
assert_eq!(apply("t", &mut [named], &advisories, &mut alerts), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_index_is_asked_for_each_order_number_once() {
|
||||
let entries = vec![
|
||||
device("6ES7511-1AK02-0AB0", "3.1.4"),
|
||||
device("6es7511-1ak02-0ab0", "3.1.5"),
|
||||
];
|
||||
assert_eq!(
|
||||
wanted(&entries),
|
||||
Wanted {
|
||||
order_numbers: vec!["6ES7511-1AK02-0AB0".to_string()],
|
||||
..Wanted::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -565,6 +565,10 @@ const PURL_TYPES_WITHOUT_OSV: &[&str] = &["pkg:cocoapods/"];
|
||||
/// Whether `entry` belongs to a package manager OSV has no advisories for.
|
||||
fn without_osv_advisories(entry: &SbomEntry) -> bool {
|
||||
entry.package_manager == crate::pipeline::sbom::unity::UNITY_MANAGER
|
||||
// A supplier SBOM's component without a purl (#1025): nothing else
|
||||
// looks it up, so it is not checked rather than free of CVEs.
|
||||
|| (entry.package_manager == crate::pipeline::sbom::supplied::SUPPLIER_MANAGER
|
||||
&& entry.purl.is_none())
|
||||
|| entry
|
||||
.purl
|
||||
.as_deref()
|
||||
@@ -687,6 +691,40 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_supplier_sboms_components_are_matched_like_any_others() {
|
||||
// #1025: the parts of a bought-in component, read from its
|
||||
// supplier's CycloneDX SBOM, go through the same OSV lookup; one
|
||||
// without a purl is reported as not checked, not as free of CVEs.
|
||||
let (url, hits) = fake_osv().await;
|
||||
let scanner = CveScanner::new(NetGuard::allow_private(), None)
|
||||
.unwrap()
|
||||
.with_osv_api(url);
|
||||
let sbom = r#"{"bomFormat": "CycloneDX", "specVersion": "1.5", "components": [
|
||||
{"type": "library", "name": "lodash", "version": "4.17.20",
|
||||
"purl": "pkg:npm/lodash@4.17.20"},
|
||||
{"type": "library", "name": "vendor-blob", "version": "2.0"}
|
||||
]}"#;
|
||||
let mut entries = crate::pipeline::sbom::supplied::parse_with_statements(
|
||||
sbom.as_bytes(),
|
||||
"t",
|
||||
"pump.cdx.json",
|
||||
)
|
||||
.unwrap()
|
||||
.entries;
|
||||
|
||||
let lookup = scanner.scan_dependencies("t", &mut entries).await.unwrap();
|
||||
|
||||
assert_eq!(hits.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(lookup.alerts.len(), 1);
|
||||
assert_eq!(lookup.alerts[0].affected_package, "lodash");
|
||||
assert_eq!(
|
||||
lookup.alerts[0].purl.as_deref(),
|
||||
Some("pkg:npm/lodash@4.17.20")
|
||||
);
|
||||
assert_eq!(lookup.unchecked, ["vendor-blob 2.0"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn yocto_recipes_are_left_to_nvd_not_asked_of_osv() {
|
||||
let (url, hits) = fake_osv().await;
|
||||
|
||||
@@ -3,9 +3,16 @@
|
||||
//! For a target from a managed git source (#439), every critical or high CVE
|
||||
//! in its components becomes one issue per package and CVE, labelled like the
|
||||
//! finding issues plus `cve`, with the fixed version where the advisory names
|
||||
//! one. When a later complete scan no longer finds the CVE (the dependency was
|
||||
//! updated or removed), the issue is closed with a comment; when it comes back,
|
||||
//! it is reopened.
|
||||
//! one. When a later complete scan no longer finds the CVE, the issue stays
|
||||
//! open and is told so once (#994): a CVE can disappear without a fix (other
|
||||
//! scan data, a changed identification), so a person checks and closes it.
|
||||
//! When the CVE comes back, the next disappearance is told again.
|
||||
//!
|
||||
//! 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
|
||||
@@ -24,6 +31,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};
|
||||
|
||||
@@ -89,13 +97,20 @@ pub(crate) struct CveIssueCounts {
|
||||
pub created: u32,
|
||||
pub reopened: u32,
|
||||
pub closed: u32,
|
||||
/// Open issues told that the scan no longer finds their CVE.
|
||||
pub noted_gone: u32,
|
||||
}
|
||||
|
||||
/// The key a CVE issue is stored under (`TrackerIssue::finding_id`): one per
|
||||
/// 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.
|
||||
@@ -153,7 +168,8 @@ fn issue_worthy(alert: &CveAlert, epss_percentile: Option<f64>) -> bool {
|
||||
/// its stored VEX statement
|
||||
/// ([`crate::pipeline::vex_lifecycle::attach_stored_vex`])
|
||||
/// * `complete` - whether every component was matched; only then is a CVE
|
||||
/// that is missing from `alerts` known to be gone, and its issue closed
|
||||
/// that is missing from `alerts` known to be gone, and its open issue told
|
||||
/// so (once; it stays open)
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
@@ -163,7 +179,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 +205,14 @@ 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() => {}
|
||||
// Found again after it was gone: a later disappearance is told
|
||||
// again.
|
||||
Some(issue) if issue.gone_noted_at.is_some() && !issue.status.is_closed() => {
|
||||
note_gone(target.db, issue, false).await?;
|
||||
}
|
||||
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 +233,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,13 +241,32 @@ 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;
|
||||
}
|
||||
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.";
|
||||
if set_state(target, issue, comment, "closed").await {
|
||||
record(target.db, issue, IssueStatus::Closed).await?;
|
||||
counts.closed += 1;
|
||||
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;
|
||||
}
|
||||
if issue.gone_noted_at.is_some() {
|
||||
continue;
|
||||
}
|
||||
let number = issue.external_id.as_str();
|
||||
match target
|
||||
.tracker
|
||||
.add_comment(target.owner, target.repo, number, GONE_COMMENT)
|
||||
.await
|
||||
{
|
||||
Ok(()) => {
|
||||
note_gone(target.db, issue, true).await?;
|
||||
counts.noted_gone += 1;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(issue = number, error = %e, "could not comment on the CVE issue");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -311,11 +353,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>> {
|
||||
@@ -429,10 +466,6 @@ fn issue_body(alert: &CveAlert, severity: &str, target_id: &str, dashboard: &str
|
||||
.push_str("- Behoben in / Fixed in: keine Version bekannt / no fixed version known\n"),
|
||||
fixed => body.push_str(&format!("- Behoben in / Fixed in: {}\n", fixed.join(", "))),
|
||||
}
|
||||
body.push_str(&format!(
|
||||
"- Advisory: https://osv.dev/vulnerability/{}\n",
|
||||
alert.cve_id
|
||||
));
|
||||
if alert
|
||||
.exploitation
|
||||
.as_ref()
|
||||
@@ -444,14 +477,8 @@ fn issue_body(alert: &CveAlert, severity: &str, target_id: &str, dashboard: &str
|
||||
));
|
||||
}
|
||||
body.push_str("\n### CRA\n\n");
|
||||
let map = control_map::ControlMap::cra().ok();
|
||||
for id in CVE_CONTROLS {
|
||||
let title = map
|
||||
.as_ref()
|
||||
.and_then(|m| m.coverage(id))
|
||||
.map(|c| c.title.clone())
|
||||
.unwrap_or_default();
|
||||
body.push_str(&format!("- {id} — {title} (Annex I)\n"));
|
||||
for requirement in crate::pipeline::issue_creation::cra_requirements(&CVE_CONTROLS) {
|
||||
body.push_str(&format!("- {requirement}\n"));
|
||||
}
|
||||
let dashboard = dashboard.trim_end_matches('/');
|
||||
if dashboard.starts_with("https://") {
|
||||
@@ -489,6 +516,27 @@ async fn set_state(
|
||||
}
|
||||
}
|
||||
|
||||
/// The comment an open issue gets once when a complete scan no longer finds
|
||||
/// its CVE. It stays open: that the CVE is gone is no proof of a fix (#994).
|
||||
const GONE_COMMENT: &str = "**Prüfwerk:** Die Prüfung findet diese Schwachstelle nicht mehr. Das allein belegt keine Behebung: Bitte prüfen Sie, ob sie behoben ist, und schließen Sie das Issue dann selbst. In Prüfwerk können Sie dazu den VEX-Status \"Behoben\" mit Begründung setzen.\n\nThe scan no longer finds this vulnerability. That alone does not prove a fix: please check whether it is fixed and close the issue yourself. In Prüfwerk you can set the VEX status \"fixed\" with a reason.";
|
||||
|
||||
/// Store that `issue` was told its CVE is gone (`gone`), or that the CVE was
|
||||
/// found again.
|
||||
async fn note_gone(db: &Database, issue: &TrackerIssue, gone: bool) -> Result<(), AgentError> {
|
||||
let Some(id) = issue.id else {
|
||||
return Ok(());
|
||||
};
|
||||
let update = if gone {
|
||||
doc! { "$set": { "gone_noted_at": mongodb::bson::DateTime::now() } }
|
||||
} else {
|
||||
doc! { "$unset": { "gone_noted_at": "" } }
|
||||
};
|
||||
db.tracker_issues()
|
||||
.update_one(doc! { "_id": id }, update)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Store an issue's new state.
|
||||
async fn record(
|
||||
db: &Database,
|
||||
@@ -498,12 +546,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(())
|
||||
}
|
||||
@@ -705,7 +751,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn severe_cves_open_issues_that_close_when_the_dependency_is_fixed() {
|
||||
async fn severe_cves_open_issues_a_person_closes_once_the_cve_is_gone() {
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let prefix = format!(
|
||||
@@ -753,7 +799,8 @@ mod tests {
|
||||
// pruefwerk (1), cra:annex-i (2), severity:high (4), cve (7).
|
||||
assert!(calls[0].ends_with("labels=[1,2,4,7]"), "{}", calls[0]);
|
||||
assert!(calls[1].contains("Fixed in: 4.9.2"));
|
||||
assert!(calls[1].contains("cra-ai-22"));
|
||||
assert!(calls[1].contains("Bekannte Schwachstellen in Komponenten"));
|
||||
assert!(!calls[1].contains("cra-ai-22"));
|
||||
assert!(calls[1].contains("https://pruefwerk.example/targets/target-1"));
|
||||
}
|
||||
|
||||
@@ -769,28 +816,90 @@ mod tests {
|
||||
CveIssueCounts::default()
|
||||
);
|
||||
|
||||
// The dependency is updated: the complete scan finds it no more.
|
||||
// The complete scan finds it no more: the issue is told so once and
|
||||
// stays open, since a CVE that is gone is no proof of a fix (#994).
|
||||
let noted = CveIssueCounts {
|
||||
noted_gone: 1,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
sync_cve_issues(&target, &[minor], true).await.unwrap(),
|
||||
CveIssueCounts {
|
||||
closed: 1,
|
||||
..Default::default()
|
||||
}
|
||||
sync_cve_issues(&target, std::slice::from_ref(&minor), true)
|
||||
.await
|
||||
.unwrap(),
|
||||
noted
|
||||
);
|
||||
{
|
||||
let calls = calls.lock().unwrap();
|
||||
let last = calls.last().unwrap();
|
||||
assert!(
|
||||
last.starts_with("comment 100: ") && last.contains("no longer finds"),
|
||||
"{last}"
|
||||
);
|
||||
assert!(calls.iter().all(|c| !c.starts_with("state ")), "{calls:?}");
|
||||
}
|
||||
let sent = calls.lock().unwrap().len();
|
||||
assert_eq!(
|
||||
calls.lock().unwrap().last().unwrap(),
|
||||
"state 100: \"closed\""
|
||||
sync_cve_issues(&target, std::slice::from_ref(&minor), true)
|
||||
.await
|
||||
.unwrap(),
|
||||
CveIssueCounts::default(),
|
||||
"told once"
|
||||
);
|
||||
assert_eq!(calls.lock().unwrap().len(), sent);
|
||||
|
||||
// It comes back: reopened, not opened twice.
|
||||
// It comes back: the issue is still open, so nothing is sent; gone
|
||||
// again, it is told again.
|
||||
assert_eq!(
|
||||
sync_cve_issues(&target, &[okhttp], true).await.unwrap(),
|
||||
CveIssueCounts {
|
||||
reopened: 1,
|
||||
..Default::default()
|
||||
}
|
||||
sync_cve_issues(&target, std::slice::from_ref(&okhttp), true)
|
||||
.await
|
||||
.unwrap(),
|
||||
CveIssueCounts::default()
|
||||
);
|
||||
assert_eq!(calls.lock().unwrap().len(), sent);
|
||||
assert_eq!(sync_cve_issues(&target, &[], true).await.unwrap(), noted);
|
||||
sync_cve_issues(&target, std::slice::from_ref(&okhttp), true)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// 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
|
||||
);
|
||||
assert_eq!(calls.lock().unwrap().last().unwrap(), "state 100: \"open\"");
|
||||
|
||||
pool.drop_tenant("cve-issues").await.ok();
|
||||
}
|
||||
@@ -941,6 +1050,55 @@ mod tests {
|
||||
pool.drop_tenant("cve-issues-vex").await.ok();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_cve_gone_from_the_scan_is_never_closed_as_vex_fixed() {
|
||||
let Some((pool, db)) = test_db("cve-issues-gone").await else {
|
||||
return;
|
||||
};
|
||||
let calls: Calls = Arc::default();
|
||||
let tracker = tracker_at(fake_gitea(calls.clone()).await);
|
||||
let target = vex_target(&db, &tracker, IssueAutoclose::On);
|
||||
// The `fixed` scans inferred from a CVE no longer found (#994).
|
||||
let mut log4j = alert("log4j-core", "2.14.1", "CVE-2021-44228", "CRITICAL");
|
||||
log4j.vex = Some(VexAssessment {
|
||||
by: "pruefwerk-scan".into(),
|
||||
by_scan: true,
|
||||
..vex(VexStatus::Fixed)
|
||||
});
|
||||
|
||||
// Reported with it: no statement, so the issue opens.
|
||||
let counts = sync_cve_issues(&target, std::slice::from_ref(&log4j), true)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
counts,
|
||||
CveIssueCounts {
|
||||
created: 1,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
|
||||
// Gone: never closed, neither for being gone nor with a VEX status;
|
||||
// the issue is told once that the scan no longer finds the CVE.
|
||||
assert_eq!(
|
||||
sync_cve_issues(&target, &[], true).await.unwrap(),
|
||||
CveIssueCounts {
|
||||
noted_gone: 1,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
{
|
||||
let calls = calls.lock().unwrap();
|
||||
assert!(calls.iter().all(|c| !c.starts_with("state ")), "{calls:?}");
|
||||
assert!(
|
||||
calls.iter().any(|c| c.contains("no longer finds")),
|
||||
"{calls:?}"
|
||||
);
|
||||
}
|
||||
|
||||
pool.drop_tenant("cve-issues-gone").await.ok();
|
||||
}
|
||||
|
||||
/// Log lines written while the returned guard lives (on this thread; a
|
||||
/// `#[tokio::test]` runs on one).
|
||||
fn capture_logs() -> (Arc<Mutex<Vec<u8>>>, tracing::subscriber::DefaultGuard) {
|
||||
|
||||
Loaded 100 of 400 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user