Compare commits

...
44 Commits
Author SHA1 Message Date
sharang 01a24f4556 test(nightly): a Yocto target with only its SPDX 3.0 image document (#150) (#860)
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Agent (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Check (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-05 01:06:34 +00:00
sharang 3d7deee4a8 feat(yocto): read the build's SPDX 3.0 image document (#150) (#859)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Successful in 1m7s
CI / Deploy Agent (push) Successful in 5m30s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-05 00:30:35 +00:00
sharang 360c905894 feat(yocto): a target with only its build output is scanned (#150) (#857)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m9s
CI / Deploy Agent (push) Successful in 5m48s
CI / Deploy MCP (push) Successful in 4m0s
CI / Deploy Dashboard (push) Successful in 5m15s
2026-11-05 00:13:11 +00:00
sharang b531227b45 feat(yocto): kernel CVEs the kernel configuration does not build (#150) (#858)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m8s
CI / Deploy Agent (push) Successful in 6m10s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-05 00:00:50 +00:00
sharang 919cac01e9 test(nightly): a Yocto layer with its build's SPDX and cve-check (#150) (#856)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Agent (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-04 23:35:36 +00:00
sharang 7f5ddf69fc feat(yocto): build output in the wizard and the guide (#150) (#855)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m4s
CI / Deploy Agent (push) Successful in 8m27s
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Successful in 6m16s
2026-11-04 23:18:50 +00:00
sharang c2fbffd2c6 feat(yocto): Yocto's own cve-check verdicts join the scan (#150) (#854)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m29s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-04 23:00:08 +00:00
sharang e637964c02 feat(yocto): a target's build output joins the scan (#150) (#853)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 6m59s
CI / Deploy MCP (push) Successful in 3m0s
CI / Deploy Dashboard (push) Successful in 4m57s
2026-11-04 22:42:48 +00:00
sharang 2ca87d1920 feat(yocto): read what a build installed from its SPDX 2.2 (#150) (#852)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 8m1s
CI / Deploy MCP (push) Successful in 4m29s
CI / Deploy Dashboard (push) Successful in 5m58s
2026-11-04 21:47:00 +00:00
sharang 60b2eeda5f fix(docs): the CODESYS export script link carries the /docs/ base (#830)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m12s
CI / Deploy Agent (push) Successful in 5m33s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-04 11:53:59 +00:00
sharang e911e75c09 feat(plc): a CODESYS script that exports PLCopen XML for Prüfwerk (#165) (#829)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Successful in 1m10s
CI / Deploy Agent (push) Successful in 6m30s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-04 11:10:09 +00:00
sharang c16e91f981 fix(plc): test data and excluded paths leave the PLC analysis too (#828)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Successful in 1m7s
CI / Deploy Agent (push) Successful in 5m24s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-04 09:32:36 +00:00
sharang b645769f67 feat(plc): say when a native CODESYS project is not analysed (#165) (#827)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m11s
CI / Deploy Agent (push) Successful in 8m56s
CI / Deploy MCP (push) Successful in 4m52s
CI / Deploy Dashboard (push) Successful in 6m46s
2026-11-04 09:13:00 +00:00
sharang 533d5f35b5 fix(issues): a skipped scan still catches up the deferred issues (#826)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 7s
CI / Deploy Docs (push) Successful in 1m13s
CI / Deploy Agent (push) Successful in 6m45s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-04 08:50:51 +00:00
sharang 8ede373353 feat(scan): per-target excluded paths, left out of the whole scan (#825)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Successful in 1m14s
CI / Deploy Agent (push) Successful in 10m50s
CI / Deploy MCP (push) Successful in 2m53s
CI / Deploy Dashboard (push) Successful in 7m56s
2026-11-04 08:48:40 +00:00
sharang e01d2146e9 fix(nightly): no chat model, and GitHub Actions by major version (#573) (#821)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m23s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-04 08:29:03 +00:00
sharang ac95126af2 feat(scan): leave test data (fixtures, testdata) out of the whole scan (#820)
CI / Detect Changes (push) Successful in 6s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Deploy Agent (push) Canceled after 0s
CI / Deploy Docs (push) Successful in 1m16s
CI / Deploy MCP (push) Successful in 4m57s
CI / Deploy Dashboard (push) Successful in 6m46s
2026-11-04 08:28:51 +00:00
sharang 5b0bf08478 fix(mobile): a manifest rule counts only on an AndroidManifest.xml (#824)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 9m15s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-04 08:28:14 +00:00
sharang 93b98965b3 fix(scheduler): start a tick's scans together; the slots cap them (#61) (#823)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m54s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-04 08:17:57 +00:00
sharang 2523ecb018 fix(health): answer 503 when MongoDB does not answer (#60) (#822)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 7s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Canceled after 0s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-04 08:17:15 +00:00
sharang 7d73893485 fix(llm): configurable call timeout; one failed triage call is not "model down" (#588)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 8m51s
CI / Deploy Dashboard (push) Successful in 4m21s
CI / Deploy MCP (push) Successful in 4m17s
2026-11-04 08:10:46 +00:00
sharang 3300bb1851 ci: agent integration tests with mongod inside the job (#586)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Agent (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-02 21:27:12 +00:00
sharang 70be25650b fix(deps): pulldown-cmark 0.13.6 (RUSTSEC-2026-0433) (#587)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 8m11s
CI / Deploy Dashboard (push) Successful in 3m51s
CI / Deploy MCP (push) Successful in 4m23s
2026-11-02 21:08:01 +00:00
sharang 34243b208d fix(i18n): CRA status names mapped findings, not verdicts (#585)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m9s
CI / Deploy Agent (push) Successful in 7m36s
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Successful in 5m26s
2026-10-31 23:55:08 +00:00
sharang 9d4e46c34f fix(agent): cascade delete reads ids raw; integration tests fixed (#584)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m34s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-10-30 08:28:13 +00:00
sharang 0cbabb73fd fix(deps): zip 9 and tantivy 0.27 (zstd 0.14), drop seven audit ignores (#583)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 6m1s
CI / Deploy MCP (push) Successful in 3m23s
CI / Deploy Dashboard (push) Successful in 3m56s
2026-10-30 07:23:58 +00:00
sharang 1135b65b9e fix(llm): embedding requests within the model's token budget (#582)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 6m15s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-10-30 07:22:30 +00:00
sharangandSharang Parnerkar 330d492578 fix(docker): Upgrade Alpine packages in the docs image (#581)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m37s
CI / Deploy Agent (push) Successful in 12m9s
CI / Deploy MCP (push) Successful in 6m3s
CI / Deploy Dashboard (push) Successful in 14m17s
vuln-watch flags CVE-2026-111497 (critical, brotli decoder out-of-bounds write) in compliance-docs. nginx:alpine (3.24) still ships brotli-libs 1.2.0-r1; Alpine already has 1.2.1-r0. Dockerfile.docs now runs `apk upgrade --no-cache` in the nginx stage (CI already builds it with `--pull`).

Tested locally: image builds, brotli-libs 1.2.1-r0, `nginx -t` passes, site present under /docs.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Reviewed-on: #581
2026-10-29 16:44:59 +00:00
sharangandSharang Parnerkar 794a3aa525 fix(agent): Semgrep 1.179.0 for PyJWT 2.15, fresh base images (#580)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 7m33s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
vuln-watch flags PyJWT 2.13.0 in compliance-agent (CVE-2026-102268, critical, fixed in 2.14.0). semgrep 1.177.0 pins pyjwt~=2.13.0; 1.179.0 is the first release that allows >=2.15.0. Tested in debian:bookworm-slim: semgrep 1.179.0 + ruff 0.16.8 install, PyJWT 2.15.1, mobsfscan still installs with --no-deps (its semgrep==1.172.0 mismatch already existed), a sample rule still finds its match. All four image builds now use `--pull`.

Note: a semgrep minor bump can shift findings; watch the nightly baseline run after merge. Prod stays on its pinned digest until it is promoted.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Reviewed-on: #580
2026-10-29 14:31:09 +00:00
sharang 24001850ec fix(telemetry): console logs to WARN+ while logs go out over OTLP (#579)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 6m0s
CI / Deploy MCP (push) Successful in 3m28s
CI / Deploy Dashboard (push) Successful in 4m17s
2026-10-29 11:58:25 +00:00
sharang fad23c20a9 feat(telemetry): W3C propagation, route-named spans, trace-linked logs (#577)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 7m38s
CI / Deploy MCP (push) Successful in 4m19s
CI / Deploy Dashboard (push) Successful in 5m41s
2026-10-29 10:13:33 +00:00
sharang c739f1b7e5 ci: two cargo jobs and line-tables-only debug info on the runners (#578)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Agent (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-10-29 09:58:03 +00:00
sharang b247c5b359 fix(llm): nightly uses the gateway's models; no OpenAI defaults (#575)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m25s
CI / Deploy Agent (push) Successful in 10m24s
CI / Deploy MCP (push) Successful in 5m21s
CI / Deploy Dashboard (push) Successful in 11m57s
2026-10-29 07:43:21 +00:00
sharang 4ded72ce32 fix(deps): pulldown-cmark 0.13.5; zstd advisories until zip 9.x (#576)
CI / Detect Changes (push) Successful in 4s
CI / Check (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 10m24s
CI / Deploy MCP (push) Successful in 5m18s
CI / Deploy Dashboard (push) Successful in 6m40s
2026-10-28 22:11:42 +00:00
sharangandClaude Opus 5.5 f77e78c5d2 fix(deps): Distrust the compromised eMudhra root (webpki-roots 1.0.10) (#574)
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 12m40s
CI / Check (push) Skipped
CI / Deploy MCP (push) Successful in 5m41s
CI / Deploy Dashboard (push) Successful in 14m39s
webpki-roots 1.0.10 and rustls-webpki 0.103.16 drop emSign ECC Root CA - G3 from the compiled-in roots (Mozilla bug 2083449); agent, dashboard and MCP final stages fail the build if Debian's store still ships it. zip extract() advisories RUSTSEC-2026-0367/0368/0369 ignored with reason (we never call extract()); zip 9.x follow-up.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:48:20 +00:00
sharang ed71ced9b3 fix(licenses): confirm a licence before its review; one row per package (#571)
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 7m28s
CI / Check (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Successful in 5m29s
2026-10-15 15:09:59 +00:00
sharang 41c337138d feat(licenses): licence policy, legal review, third-party notices (licence review v2) (#570)
CI / Deploy Docs (push) Successful in 1m11s
CI / Deploy Agent (push) Successful in 8m13s
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Dashboard (push) Successful in 6m22s
CI / Deploy MCP (push) Successful in 4m37s
2026-10-15 14:35:43 +00:00
sharang e65aa76ef5 feat(sbom): confirm the licence of components (licence review) (#569)
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m16s
CI / Deploy Agent (push) Successful in 8m39s
CI / Check (push) Skipped
CI / Deploy MCP (push) Successful in 4m49s
CI / Deploy Dashboard (push) Successful in 6m40s
2026-10-15 12:03:29 +00:00
sharang 70125b4556 ci: a weekly check compares the bundled end-of-life tables with endoflife.date (#563)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Successful in 1m12s
CI / Deploy Agent (push) Successful in 5m25s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-10-15 10:19:49 +00:00
sharang 43d8ff1589 feat(platform): count open vulnerabilities in the portal's target list (#568)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m35s
CI / Deploy MCP (push) Successful in 3m48s
CI / Deploy Dashboard (push) Successful in 4m44s
2026-10-14 18:20:55 +00:00
sharangandSharang Parnerkar 5ce496303d feat(audit): API-key writes carry the caller's address to the registry (#567)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m6s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
Audit entries for API-key writes recorded the agent's container address (172.17.0.6 on stage), because the registry stores the peer of its own request. With this change they carry the caller's address.

- The API host's proxy puts the caller's address in `X-BP-Client-IP`, overwriting anything the client sent. That proxy change is a separate orca-platform PR on `pruefwerk-stage/api-proxy.conf`.
- `audit_delegated_writes` reads the header for **API-key requests only** and keeps it only if it parses as an IP address, because the registry stores it as Postgres `inet` and garbage would sink the whole entry.
- `AuditEntry.source_ip` is sent as `source_ip` and skipped when empty.
- The registry ignores the field until tenant-registry accepts it (separate PR), so the deploy order doesn't matter.
- The address is informational: nothing decides on it.
- Support writes via the dashboard still show the dashboard's address.

Tests: unit test for the header parse (v4, v6, a list, junk, missing); `tests/api_key_access.rs` checks `source_ip` in the posted audit entry. Not run locally (RAM); CI runs them.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Reviewed-on: #567
2026-10-14 09:33:24 +00:00
sharang a84681918b fix(findings): feedback on an unknown finding answers 404 (#566)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m41s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-10-14 08:52:54 +00:00
sharang 07ba0d6665 feat(api): the customer API accepts portal-issued API keys (#564)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m23s
CI / Deploy Agent (push) Successful in 5m32s
CI / Deploy Dashboard (push) Successful in 3m53s
CI / Deploy MCP (push) Successful in 3m1s
2026-10-13 22:22:21 +00:00
sharang 171ff9a9f8 fix(deps): quinn-proto 0.11.19 for RUSTSEC-2026-0338..0342 (#565)
CI / Deploy Docs (push) Skipped
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Agent (push) Successful in 9m55s
CI / Deploy MCP (push) Successful in 4m36s
CI / Deploy Dashboard (push) Successful in 10m29s
2026-10-13 22:07:02 +00:00
175 changed files with 18020 additions and 984 deletions

No files matched your search

+5 -1
View File
@@ -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=
+107 -4
View File
@@ -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)
@@ -145,6 +160,94 @@ jobs:
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 +341,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}" .
@@ -273,7 +376,7 @@ jobs:
git fetch --depth=1 origin "${GITHUB_SHA}" && git checkout FETCH_HEAD
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 \
-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 +407,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 +439,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"
+57
View File
@@ -0,0 +1,57 @@
name: End-of-life tables
# Compares the bundled end-of-life tables (compliance-agent/data/eol/: Yocto
# releases, .NET target frameworks, the oldest patched Android and iOS
# releases) with endoflife.date once a week. A difference (a new release, a
# changed end-of-life date) opens one issue, or updates the open one, labelled
# "eol-tables"; the tables themselves are updated by hand after checking the
# vendor's page. A separate workflow, so it never fails main CI.
#
# The issue is written with NIGHTLY_ALERT_TOKEN, the token the nightly
# regression already uses for its alert issue (issue write on this repo).
# Without it the differences are only printed in the log.
on:
schedule:
- cron: '0 5 * * 1' # Mondays, 5 AM UTC
workflow_dispatch:
inputs:
dry_run:
description: "Print the differences only, write no issue"
type: boolean
default: false
concurrency:
group: eol-tables
cancel-in-progress: true
jobs:
check:
name: Compare with endoflife.date
runs-on: docker
container:
image: python:3.12-alpine
steps:
- name: Checkout
run: |
apk add --no-cache git
git init
git remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git"
git fetch --depth=1 origin "${GITHUB_SHA}"
git checkout FETCH_HEAD
- name: Test the check
run: python3 -I -m unittest discover -s scripts -p "test_check_eol_tables.py"
- name: Compare and file the issue
env:
GITEA_TOKEN: ${{ secrets.NIGHTLY_ALERT_TOKEN }}
GITEA_API: ${{ github.server_url }}/api/v1
GITEA_REPO: ${{ github.repository }}
DRY_RUN: ${{ inputs.dry_run }}
run: |
if [ "$DRY_RUN" = "true" ]; then
python3 -I scripts/check-eol-tables.py --dry-run
else
python3 -I scripts/check-eol-tables.py
fi
+7 -2
View File
@@ -63,10 +63,15 @@ jobs:
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.
# No chat model: LLM triage, code review and the control judge are
# off (LlmClient sends nothing without LITELLM_MODEL, #575). Their
# output never gates the run, and with the model on, ~600 calls of
# 11 s on average (p99 147 s) on the gateway prod also uses kept
# every scan past NIGHTLY_TIMEOUT_SECS from 2026-10-30 on (#573).
# Embeddings stay on: the gateway's embedding model.
LITELLM_URL: ${{ secrets.NIGHTLY_LITELLM_URL }}
LITELLM_API_KEY: ${{ secrets.NIGHTLY_LITELLM_API_KEY }}
LITELLM_EMBED_MODEL: bge-multilingual-gemma2
# Optional. The CODESYS CVE match queries NVD, which rate-limits
# unauthenticated clients; a key keeps those CVEs from going missing.
NVD_API_KEY: ${{ secrets.NIGHTLY_NVD_API_KEY }}
Generated
+497 -324
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -33,7 +33,7 @@ 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
View File
@@ -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
+4
View File
@@ -27,6 +27,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
+2
View File
@@ -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/
+4
View File
@@ -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
+2
View File
@@ -62,6 +62,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 }
+136
View File
@@ -0,0 +1,136 @@
{
"source": "https://learn.microsoft.com/lifecycle/products/microsoft-net-framework and https://dotnet.microsoft.com/platform/support/policy/dotnet-core",
"endoflife_products": [
"dotnet",
"dotnetfx"
],
"checked_on": "2026-10-05",
"notes": "Microsoft's end of support per target framework moniker. Monikers not listed are supported (.NET Framework 4.7 to 4.8.1 follow the Windows they ship with).",
"frameworks": [
{
"moniker": "net11",
"end_of_support": "2011-07-12",
"product": ".NET Framework 1.1"
},
{
"moniker": "net20",
"end_of_support": "2011-07-12",
"product": ".NET Framework 2.0"
},
{
"moniker": "net30",
"end_of_support": "2011-07-12",
"product": ".NET Framework 3.0"
},
{
"moniker": "net35",
"end_of_support": "2029-01-09",
"product": ".NET Framework 3.5 SP1"
},
{
"moniker": "net40",
"end_of_support": "2016-01-12",
"product": ".NET Framework 4.0"
},
{
"moniker": "net403",
"end_of_support": "2016-01-12",
"product": ".NET Framework 4.0.3"
},
{
"moniker": "net45",
"end_of_support": "2016-01-12",
"product": ".NET Framework 4.5"
},
{
"moniker": "net451",
"end_of_support": "2016-01-12",
"product": ".NET Framework 4.5.1"
},
{
"moniker": "net452",
"end_of_support": "2022-04-26",
"product": ".NET Framework 4.5.2"
},
{
"moniker": "net46",
"end_of_support": "2022-04-26",
"product": ".NET Framework 4.6"
},
{
"moniker": "net461",
"end_of_support": "2022-04-26",
"product": ".NET Framework 4.6.1"
},
{
"moniker": "net462",
"end_of_support": "2027-01-12",
"product": ".NET Framework 4.6.2"
},
{
"moniker": "netcoreapp1.0",
"end_of_support": "2019-06-27",
"product": ".NET Core 1.0"
},
{
"moniker": "netcoreapp1.1",
"end_of_support": "2019-06-27",
"product": ".NET Core 1.1"
},
{
"moniker": "netcoreapp2.0",
"end_of_support": "2018-10-01",
"product": ".NET Core 2.0"
},
{
"moniker": "netcoreapp2.1",
"end_of_support": "2021-08-21",
"product": ".NET Core 2.1"
},
{
"moniker": "netcoreapp2.2",
"end_of_support": "2019-12-23",
"product": ".NET Core 2.2"
},
{
"moniker": "netcoreapp3.0",
"end_of_support": "2020-03-03",
"product": ".NET Core 3.0"
},
{
"moniker": "netcoreapp3.1",
"end_of_support": "2022-12-13",
"product": ".NET Core 3.1"
},
{
"moniker": "net5.0",
"end_of_support": "2022-05-10",
"product": ".NET 5"
},
{
"moniker": "net6.0",
"end_of_support": "2024-11-12",
"product": ".NET 6"
},
{
"moniker": "net7.0",
"end_of_support": "2024-05-14",
"product": ".NET 7"
},
{
"moniker": "net8.0",
"end_of_support": "2026-11-10",
"product": ".NET 8"
},
{
"moniker": "net9.0",
"end_of_support": "2026-11-10",
"product": ".NET 9"
},
{
"moniker": "net10.0",
"end_of_support": "2028-11-14",
"product": ".NET 10"
}
]
}
+14
View File
@@ -0,0 +1,14 @@
{
"android": {
"oldest_patched_api": 29,
"oldest_patched_release": "Android 10",
"endoflife_product": "android",
"notes": "Below this API level no Android release receives security updates."
},
"ios": {
"oldest_patched": "15.0",
"endoflife_product": "ios",
"notes": "The oldest iOS release that still receives security updates: iOS 15 got 15.8.8 in May 2026, while iOS 14 was last updated in October 2021 and the older iOS 12 line in January 2026, both now end of life (endoflife.date). Judged conservatively: below it is certainly unpatched."
},
"checked_on": "2026-10-05"
}
+163
View File
@@ -0,0 +1,163 @@
{
"source": "https://wiki.yoctoproject.org/wiki/Releases",
"dates_source": "https://endoflife.date/yocto",
"endoflife_product": "yocto",
"checked_on": "2026-10-09",
"notes": "Codename, version, LTS and support status from the Yocto Project releases wiki (page last updated 2026-09-10). The wiki gives months only; the exact release and end-of-life days are endoflife.date's, which agree with the wiki's months except Walnascar (wiki: EOL since November 2025, endoflife.date: 2025-12-07). For Thud and older, which endoflife.date does not list, the end of life is the last day of the month of the release's last point release (wiki), and the release day the first of its month. Releases are added once they are released. Oldest first.",
"releases": [
{
"codename": "jethro",
"version": "2.0",
"lts": false,
"released": "2015-11-01",
"end_of_life": "2017-01-31"
},
{
"codename": "krogoth",
"version": "2.1",
"lts": false,
"released": "2016-04-01",
"end_of_life": "2017-07-31"
},
{
"codename": "morty",
"version": "2.2",
"lts": false,
"released": "2016-11-01",
"end_of_life": "2018-07-31"
},
{
"codename": "pyro",
"version": "2.3",
"lts": false,
"released": "2017-05-01",
"end_of_life": "2018-07-31"
},
{
"codename": "rocko",
"version": "2.4",
"lts": false,
"released": "2017-10-01",
"end_of_life": "2018-11-30"
},
{
"codename": "sumo",
"version": "2.5",
"lts": false,
"released": "2018-04-01",
"end_of_life": "2019-04-30"
},
{
"codename": "thud",
"version": "2.6",
"lts": false,
"released": "2018-11-01",
"end_of_life": "2019-10-31"
},
{
"codename": "warrior",
"version": "2.7",
"lts": false,
"released": "2019-05-01",
"end_of_life": "2020-06-01"
},
{
"codename": "zeus",
"version": "3.0",
"lts": false,
"released": "2019-10-22",
"end_of_life": "2020-08-01"
},
{
"codename": "dunfell",
"version": "3.1",
"lts": true,
"released": "2020-04-21",
"end_of_life": "2024-04-30"
},
{
"codename": "gatesgarth",
"version": "3.2",
"lts": false,
"released": "2020-11-03",
"end_of_life": "2021-05-01"
},
{
"codename": "hardknott",
"version": "3.3",
"lts": false,
"released": "2021-04-19",
"end_of_life": "2022-04-20"
},
{
"codename": "honister",
"version": "3.4",
"lts": false,
"released": "2021-10-25",
"end_of_life": "2022-05-01"
},
{
"codename": "kirkstone",
"version": "4.0",
"lts": true,
"released": "2022-04-25",
"end_of_life": "2026-04-27"
},
{
"codename": "langdale",
"version": "4.1",
"lts": false,
"released": "2022-10-23",
"end_of_life": "2023-05-27"
},
{
"codename": "mickledore",
"version": "4.2",
"lts": false,
"released": "2023-05-03",
"end_of_life": "2023-11-05"
},
{
"codename": "nanbield",
"version": "4.3",
"lts": false,
"released": "2023-11-09",
"end_of_life": "2024-06-09"
},
{
"codename": "scarthgap",
"version": "5.0",
"lts": true,
"released": "2024-04-29",
"end_of_life": "2028-04-30"
},
{
"codename": "styhead",
"version": "5.1",
"lts": false,
"released": "2024-10-16",
"end_of_life": "2025-05-16"
},
{
"codename": "walnascar",
"version": "5.2",
"lts": false,
"released": "2025-05-07",
"end_of_life": "2025-12-07"
},
{
"codename": "whinlatter",
"version": "5.3",
"lts": false,
"released": "2025-12-15",
"end_of_life": "2026-06-15"
},
{
"codename": "wrynose",
"version": "6.0",
"lts": true,
"released": "2026-05-13",
"end_of_life": "2030-04-30"
}
]
}
+16 -6
View File
@@ -56,12 +56,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))
+243
View File
@@ -0,0 +1,243 @@
//! Portal-issued API keys on the customer API (tenant-registry ADR 0001, §4).
//!
//! A `Bearer bp_…` token is an API key; every other bearer goes on to the
//! JWT middleware unchanged. The key is verified with the registry (answers
//! cached for [`crate::registry::API_KEY_TTL`]) and becomes a
//! [`TenantContext`] carrying [`ApiKeyAccess`]:
//!
//! * the tenant, scopes and ladder status come only from the registry's
//! answer; no header, path or body can name another tenant, and the support
//! header is never read;
//! * the key holds no org role, so `role_gate` judges it by its scopes;
//! * `X-BP-Actor` is recorded as who the caller acts for, never trusted.
//!
//! `401 {"error": "invalid_api_key"}` for a key the registry rejects, `503`
//! when the registry cannot answer and no fresh verdict is cached.
use std::sync::Arc;
use axum::{
extract::{Request, State},
http::{header, StatusCode},
middleware::Next,
response::{IntoResponse, Response},
Json,
};
use compliance_core::auth::bypasses_customer_auth;
use compliance_core::{ApiKeyAccess, TenantContext, TenantStatus};
use super::role_gate::LEGACY_SCOPES;
use crate::agent::ComplianceAgent;
use crate::registry::ApiKeyVerify;
/// Every portal-issued API key starts with this.
pub const API_KEY_PREFIX: &str = "bp_";
/// The header a caller (e.g. a Werkmeister block) names the person it acts
/// for in. Informational: logged and audited, never used to authorise.
pub const ACTOR_HEADER: &str = "x-bp-actor";
/// The longest `X-BP-Actor` value kept; the rest is cut off.
const ACTOR_MAX_CHARS: usize = 120;
/// The JSON `error` for a key the registry does not accept.
pub const INVALID_API_KEY: &str = "invalid_api_key";
/// The middleware. Mounted outside the JWT middleware, which lets through a
/// request this one has given a key context.
pub async fn require_api_key(
State(agent): State<Arc<ComplianceAgent>>,
mut request: Request,
next: Next,
) -> Response {
if bypasses_customer_auth(request.uri().path()) {
return next.run(request).await;
}
let Some(key) = presented_key(&request) else {
return next.run(request).await;
};
let Some(registry) = agent.registry.as_ref() else {
return invalid_key();
};
let verdict = match registry.verify_api_key(&key).await {
Ok(v) => v,
Err(e) => {
tracing::error!("api-key verify unavailable: {e}");
return (
StatusCode::SERVICE_UNAVAILABLE,
Json(serde_json::json!({ "error": "api_key_verify_unavailable" })),
)
.into_response();
}
};
let on_behalf_of = request
.headers()
.get(ACTOR_HEADER)
.and_then(|v| v.to_str().ok())
.and_then(clean_actor);
let Some(ctx) = key_context(verdict, registry.product(), on_behalf_of) else {
return invalid_key();
};
request.extensions_mut().insert(ctx);
next.run(request).await
}
/// The `bp_…` token of an `Authorization: Bearer` header, if it is one.
fn presented_key(request: &Request) -> Option<String> {
request
.headers()
.get(header::AUTHORIZATION)?
.to_str()
.ok()?
.strip_prefix("Bearer ")
.map(str::trim)
.filter(|t| t.starts_with(API_KEY_PREFIX))
.map(str::to_owned)
}
fn invalid_key() -> Response {
(
StatusCode::UNAUTHORIZED,
Json(serde_json::json!({ "error": INVALID_API_KEY })),
)
.into_response()
}
/// The context for a verified key, or `None` if the registry rejected it.
/// `product` is this product's registry key, which a legacy key must name
/// (or name none) to get [`LEGACY_SCOPES`].
fn key_context(
v: ApiKeyVerify,
product: &str,
on_behalf_of: Option<String>,
) -> Option<TenantContext> {
if !v.valid || v.tenant_id.is_empty() {
return None;
}
let scopes =
if v.legacy && v.scopes.is_empty() && (v.product.is_empty() || v.product == product) {
LEGACY_SCOPES.iter().map(|s| (*s).to_string()).collect()
} else {
v.scopes
};
let key_id = if v.key_id.is_empty() {
"unknown".to_string()
} else {
v.key_id
};
Some(TenantContext {
tenant_id: v.tenant_id,
tenant_slug: String::new(),
org_roles: Vec::new(),
products: Vec::new(),
plan: String::new(),
// An older registry sends no status: read-only until it does.
status: TenantStatus::parse(&v.tenant_status).unwrap_or(TenantStatus::Restricted),
user_id: format!("apikey:{key_id}"),
user_name: v.holder.clone().filter(|h| !h.trim().is_empty()),
staff: None,
api_key: Some(Box::new(ApiKeyAccess {
key_id,
kind: v.kind,
holder: v.holder,
scopes,
legacy: v.legacy,
on_behalf_of,
})),
})
}
/// An `X-BP-Actor` value fit for a log line: no control characters, at most
/// [`ACTOR_MAX_CHARS`], `None` if nothing is left.
fn clean_actor(raw: &str) -> Option<String> {
let cleaned: String = raw
.chars()
.filter(|c| !c.is_control())
.take(ACTOR_MAX_CHARS)
.collect();
let trimmed = cleaned.trim();
(!trimmed.is_empty()).then(|| trimmed.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
fn verdict() -> ApiKeyVerify {
serde_json::from_value(serde_json::json!({
"valid": true,
"tenant_id": "11111111-1111-1111-1111-111111111111",
"product": "pruefwerk",
"scopes": ["pruefwerk:findings.write"],
"key_id": "k1",
"kind": "service",
"holder": "CI",
"tenant_status": "active",
"legacy": false,
}))
.expect("verdict")
}
#[test]
fn a_valid_key_becomes_a_roleless_context_of_its_tenant() {
let ctx = key_context(verdict(), "pruefwerk", Some("someone".into())).expect("ctx");
assert_eq!(ctx.tenant_id, "11111111-1111-1111-1111-111111111111");
assert_eq!(ctx.user_id, "apikey:k1");
assert_eq!(ctx.actor_label(), "CI");
assert!(ctx.org_roles.is_empty());
assert_eq!(ctx.status, TenantStatus::Active);
let key = ctx.api_key.expect("key");
assert_eq!(key.scopes, ["pruefwerk:findings.write"]);
assert_eq!(key.on_behalf_of.as_deref(), Some("someone"));
}
#[test]
fn a_rejected_or_tenantless_key_gets_no_context() {
let mut v = verdict();
v.valid = false;
assert!(key_context(v, "pruefwerk", None).is_none());
let mut v = verdict();
v.tenant_id.clear();
assert!(key_context(v, "pruefwerk", None).is_none());
}
#[test]
fn a_legacy_key_reads_only_and_only_for_this_product() {
let mut v = verdict();
v.legacy = true;
v.scopes.clear();
let key = key_context(v.clone(), "pruefwerk", None)
.and_then(|c| c.api_key)
.expect("key");
assert_eq!(key.scopes, LEGACY_SCOPES);
v.product = "werkbank".into();
let key = key_context(v, "pruefwerk", None)
.and_then(|c| c.api_key)
.expect("key");
assert!(key.scopes.is_empty());
}
#[test]
fn an_older_registry_answer_is_read_only_and_anonymous() {
let v: ApiKeyVerify = serde_json::from_value(serde_json::json!({
"valid": true,
"tenant_id": "t",
"product": "pruefwerk",
"scopes": ["pruefwerk:findings.read"],
}))
.expect("old shape decodes");
let ctx = key_context(v, "pruefwerk", None).expect("ctx");
assert_eq!(ctx.status, TenantStatus::Restricted);
assert_eq!(ctx.user_id, "apikey:unknown");
}
#[test]
fn the_actor_header_is_cleaned_and_capped() {
assert_eq!(clean_actor(" a\nb\u{7}c "), Some("abc".into()));
assert_eq!(clean_actor(" \t "), None);
assert_eq!(
clean_actor(&"x".repeat(500)).map(|s| s.len()),
Some(ACTOR_MAX_CHARS)
);
}
}
+13
View File
@@ -230,6 +230,10 @@ pub struct SbomFilter {
/// others (`false`); see [`compliance_core::models::InImage`].
#[serde(default)]
pub in_image: Option<bool>,
/// Only components whose licence is still open (`true`): the scan found
/// none and nobody has confirmed one.
#[serde(default)]
pub unresolved: Option<bool>,
#[serde(default = "default_page", deserialize_with = "de_page")]
pub page: u64,
#[serde(default = "default_limit", deserialize_with = "de_limit")]
@@ -267,6 +271,11 @@ pub struct LicenseSummary {
pub license: String,
pub count: u64,
pub is_copyleft: bool,
/// What the licence allows (`permissive`, `weak_copyleft`, ...); for a
/// confirmed licence the category the person chose.
pub category: compliance_core::models::LicenseCategory,
/// How many of the components a person confirmed this licence for.
pub confirmed: u64,
pub packages: Vec<String>,
}
@@ -659,12 +668,16 @@ mod tests {
license: "MIT".to_string(),
count: 42,
is_copyleft: false,
category: compliance_core::models::LicenseCategory::Permissive,
confirmed: 3,
packages: vec!["serde".to_string()],
};
let v = serde_json::to_value(&ls).unwrap();
assert_eq!(v["license"], "MIT");
assert_eq!(v["is_copyleft"], false);
assert_eq!(v["count"], 42);
assert_eq!(v["category"], "permissive");
assert_eq!(v["confirmed"], 3);
}
// ── Default helper functions ─────────────────────────────────
+11 -7
View File
@@ -54,6 +54,15 @@ async fn load_inputs(
tracing::warn!("evidence: {e}");
StatusCode::INTERNAL_SERVER_ERROR
};
let mut sbom = collect_cursor_async(
db.sbom_entries()
.find(by_target.clone())
.await
.map_err(load_err)?,
)
.await;
// The licences a person confirmed are part of the evidence's SBOM.
crate::license_conclusions::attach(db, &mut sbom).await;
Ok(EvidenceInputs {
findings: collect_cursor_async(
db.findings()
@@ -62,13 +71,7 @@ async fn load_inputs(
.map_err(load_err)?,
)
.await,
sbom: collect_cursor_async(
db.sbom_entries()
.find(by_target.clone())
.await
.map_err(load_err)?,
)
.await,
sbom,
cves: collect_cursor_async(
db.cve_alerts()
.find(by_target.clone())
@@ -85,6 +88,7 @@ async fn load_inputs(
catalog: crate::controls::cra_catalog(&agent.config).await,
target,
author: String::new(),
license_policy: crate::license_conclusions::load_policy(db).await,
})
}
@@ -311,7 +311,9 @@ pub async fn bulk_update_finding_status(
))
}
#[tracing::instrument(skip_all)]
/// PATCH /api/v1/findings/{id}/feedback — store the developer's feedback on a
/// finding. 404 when there is no such finding.
#[tracing::instrument(skip_all, fields(finding_id = %id))]
pub async fn update_finding_feedback(
Extension(agent): AgentExt,
tenant: TenantCtx,
@@ -321,13 +323,17 @@ pub async fn update_finding_feedback(
let oid = mongodb::bson::oid::ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
let db = tenant_db(&agent, &tenant).await?;
db.findings()
let result = db
.findings()
.update_one(
doc! { "_id": oid },
doc! { "$set": { "developer_feedback": &req.feedback, "updated_at": mongodb::bson::DateTime::now() } },
)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if result.matched_count == 0 {
return Err(StatusCode::NOT_FOUND);
}
Ok(Json(serde_json::json!({ "status": "updated" })))
}
+54 -2
View File
@@ -13,9 +13,44 @@ pub async fn access() -> Json<serde_json::Value> {
Json(serde_json::json!({ "access": true }))
}
/// How long the health check waits for MongoDB before it reports it down.
const DB_PING_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
/// `GET /api/v1/health`: 200 `{"status":"ok"}` when MongoDB answers a ping,
/// 503 `{"status":"degraded","mongo":"unreachable"}` when it does not, so a
/// load balancer and the container health check stop sending traffic to an
/// instance that cannot serve it (#60). Public, untraced, no tenant.
#[tracing::instrument(skip_all)]
pub async fn health() -> Json<serde_json::Value> {
Json(serde_json::json!({ "status": "ok" }))
pub async fn health(
axum::extract::Extension(agent): AgentExt,
) -> (axum::http::StatusCode, Json<serde_json::Value>) {
let reachable = match tokio::time::timeout(DB_PING_TIMEOUT, agent.db_pool.ping()).await {
Ok(Ok(())) => true,
Ok(Err(e)) => {
tracing::warn!(error = %e, "health: MongoDB ping failed");
false
}
Err(_) => {
tracing::warn!("health: MongoDB ping timed out");
false
}
};
health_answer(reachable)
}
/// The health answer for whether MongoDB answered.
fn health_answer(mongo_reachable: bool) -> (axum::http::StatusCode, Json<serde_json::Value>) {
if mongo_reachable {
(
axum::http::StatusCode::OK,
Json(serde_json::json!({ "status": "ok" })),
)
} else {
(
axum::http::StatusCode::SERVICE_UNAVAILABLE,
Json(serde_json::json!({ "status": "degraded", "mongo": "unreachable" })),
)
}
}
/// Findings that still need someone's attention: not resolved, not a false
@@ -128,3 +163,20 @@ pub async fn stats_overview(
page: None,
}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_health_answer_follows_the_database() {
let (status, Json(body)) = health_answer(true);
assert_eq!(status, axum::http::StatusCode::OK);
assert_eq!(body, serde_json::json!({ "status": "ok" }));
let (status, Json(body)) = health_answer(false);
assert_eq!(status, axum::http::StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(body["status"], "degraded");
assert_eq!(body["mongo"], "unreachable");
}
}
@@ -0,0 +1,986 @@
//! Licences a workspace confirms for its components: list them, confirm one
//! for one or many components at once, and withdraw one. The scanned
//! licence stays as detected; the confirmed one is merged in when the
//! components are read and exported ([`crate::license_conclusions`]).
//!
//! Writes are for the roles that may change Prüfwerk (IT_ADMIN, USER), as
//! the role gate decides for every `PUT` and `DELETE`.
use axum::extract::{Extension, Query};
use axum::http::{header, StatusCode};
use axum::response::IntoResponse;
use axum::Json;
use chrono::NaiveDate;
use futures_util::TryStreamExt;
use mongodb::bson::doc;
use serde::Deserialize;
use compliance_core::license_notices::{self, NoticeFormat};
use compliance_core::models::license::{
self, conclusion_id, package_key, LicenseCategory, LicenseConclusion, LicenseUsage,
};
use compliance_core::models::license_policy::{
self, LegalReview, LicensePolicy, PolicyAction, ReviewDecision, VerdictCounts,
};
use compliance_core::models::SbomEntry;
use compliance_core::spdx_license;
use compliance_core::tenant_ctx::TenantCtx;
use compliance_core::OrgRole;
use super::dto::{tenant_db, AgentExt, ApiResponse, ApiResult};
use super::findings::Actor;
use crate::license_conclusions::MAX_CONCLUSIONS;
/// The most components one request confirms.
pub const MAX_COMPONENTS: usize = 500;
/// A component a licence is confirmed for, as the SBOM list shows it.
#[derive(Debug, Clone, Deserialize)]
pub struct ComponentRef {
pub name: String,
pub package_manager: String,
#[serde(default)]
pub version: String,
#[serde(default)]
pub purl: Option<String>,
/// The licence the scan found, as the list shows it. Read only by a
/// review of a component nobody confirmed a licence for.
#[serde(default)]
pub license: Option<String>,
}
/// The body of [`conclude`].
#[derive(Debug, Deserialize)]
pub struct ConcludeRequest {
pub components: Vec<ComponentRef>,
/// For every version of the packages, not just the listed ones.
#[serde(default)]
pub all_versions: bool,
/// An SPDX licence expression or a licence name SPDX knows. Empty for a
/// licence of its own, named in `license_name`.
#[serde(default)]
pub license: Option<String>,
#[serde(default)]
pub license_name: Option<String>,
/// Used for a licence of its own and where SPDX gives no category.
#[serde(default)]
pub category: Option<LicenseCategory>,
#[serde(default)]
pub copyright: Vec<String>,
#[serde(default)]
pub license_text: Option<String>,
#[serde(default)]
pub license_url: Option<String>,
#[serde(default)]
pub evidence: Option<String>,
#[serde(default)]
pub contract_ref: Option<String>,
#[serde(default)]
pub valid_until: Option<NaiveDate>,
#[serde(default)]
pub usage: Option<LicenseUsage>,
#[serde(default)]
pub note: Option<String>,
}
type Refusal = (StatusCode, Json<serde_json::Value>);
fn refuse(code: StatusCode, error: impl Into<String>) -> Refusal {
(code, Json(serde_json::json!({ "error": error.into() })))
}
/// Trimmed, `None` when empty.
fn text(value: Option<String>) -> Option<String> {
value
.map(|t| t.trim().to_string())
.filter(|t| !t.is_empty())
}
/// The licence `req` states, as stored: the SPDX expression and its
/// category, or a `LicenseRef-` with the name and the category asked for.
///
/// # Errors
///
/// Neither a licence nor a name, or a licence SPDX cannot read.
fn licence_of(req: &ConcludeRequest) -> Result<(String, Option<String>, LicenseCategory), String> {
let asked = req.category.unwrap_or(LicenseCategory::Unclear);
if let Some(license) = text(req.license.clone()) {
let spdx = spdx_license::normalise(&license).into_owned();
if !spdx_license::is_spdx_expression(&spdx) {
return Err(format!(
"not an SPDX licence expression: {license}. For a licence SPDX does not list, give its name instead"
));
}
let derived = spdx_license::category(&spdx);
let category = if derived == LicenseCategory::Unclear {
asked
} else {
derived
};
return Ok((spdx, None, category));
}
match text(req.license_name.clone()) {
Some(name) => Ok((license::license_ref(&name), Some(name), asked)),
None => Err("licence missing: give an SPDX licence or the name of the licence".into()),
}
}
/// The conclusions `req` asks for, one per component (several components of
/// one package and version are one conclusion), by the requester of
/// `tenant`.
///
/// # Errors
///
/// Why the request cannot be stored.
fn conclusions_of(
req: ConcludeRequest,
tenant: &TenantCtx,
) -> Result<Vec<LicenseConclusion>, String> {
if req.components.is_empty() {
return Err("no component given".into());
}
if req.components.len() > MAX_COMPONENTS {
return Err(format!("at most {MAX_COMPONENTS} components at once"));
}
let (license, license_name, category) = licence_of(&req)?;
let actor = Actor::of(&tenant.0);
let at = chrono::Utc::now();
let copyright: Vec<String> = req
.copyright
.iter()
.flat_map(|c| c.lines())
.map(str::trim)
.filter(|c| !c.is_empty())
.map(String::from)
.collect();
let mut out: Vec<LicenseConclusion> = Vec::new();
for component in &req.components {
let name = component.name.trim();
if name.is_empty() {
return Err("a component without a name".into());
}
let key = package_key(name, &component.package_manager, component.purl.as_deref());
let version = (!req.all_versions)
.then(|| component.version.trim().to_string())
.filter(|v| !v.is_empty());
let id = conclusion_id(&key, version.as_deref());
if out.iter().any(|c| c.id == id) {
continue;
}
let conclusion = LicenseConclusion {
id,
package_key: key,
name: name.to_string(),
package_manager: component.package_manager.trim().to_string(),
version,
license: license.clone(),
license_name: license_name.clone(),
category,
copyright: copyright.clone(),
license_text: text(req.license_text.clone()),
license_url: text(req.license_url.clone()),
evidence: text(req.evidence.clone()),
contract_ref: text(req.contract_ref.clone()),
valid_until: req.valid_until,
usage: req.usage,
note: text(req.note.clone()),
by: actor.id.to_string(),
by_name: actor.name.clone(),
support: actor.support,
at,
review: None,
};
conclusion.validate()?;
out.push(conclusion);
}
Ok(out)
}
/// GET /api/v1/licenses/conclusions — every licence the workspace
/// confirmed, by package name.
#[tracing::instrument(skip_all)]
pub async fn list_conclusions(
Extension(agent): AgentExt,
tenant: TenantCtx,
) -> ApiResult<Vec<LicenseConclusion>> {
let db = tenant_db(&agent, &tenant).await?;
let conclusions = crate::license_conclusions::load(&db).await;
Ok(Json(ApiResponse {
total: Some(conclusions.len() as u64),
data: conclusions,
page: None,
}))
}
/// PUT /api/v1/licenses/conclusions — confirm a licence for one or more
/// components (one version, or every version of their packages). A second
/// confirmation of the same package and version replaces the first. 422
/// with the reason when the licence or a field is not acceptable.
#[tracing::instrument(skip_all)]
pub async fn conclude(
Extension(agent): AgentExt,
tenant: TenantCtx,
Json(req): Json<ConcludeRequest>,
) -> Result<Json<serde_json::Value>, Refusal> {
let conclusions =
conclusions_of(req, &tenant).map_err(|e| refuse(StatusCode::UNPROCESSABLE_ENTITY, e))?;
let db = tenant_db(&agent, &tenant)
.await
.map_err(|code| refuse(code, "tenant"))?;
let stored = db
.license_conclusions()
.count_documents(doc! {})
.await
.map_err(|_| refuse(StatusCode::INTERNAL_SERVER_ERROR, "store"))?;
if stored.saturating_add(conclusions.len() as u64) > MAX_CONCLUSIONS as u64 {
return Err(refuse(
StatusCode::UNPROCESSABLE_ENTITY,
format!("at most {MAX_CONCLUSIONS} confirmed licences per workspace"),
));
}
for c in &conclusions {
db.license_conclusions()
.replace_one(doc! { "_id": &c.id }, c)
.upsert(true)
.await
.map_err(|e| {
tracing::warn!("license conclusion not stored: {e}");
refuse(StatusCode::INTERNAL_SERVER_ERROR, "store")
})?;
}
tracing::info!(
count = conclusions.len(),
license = %conclusions[0].license,
"license confirmed"
);
Ok(Json(serde_json::json!({
"status": "saved",
"saved": conclusions.len(),
"conclusions": conclusions,
})))
}
/// The query of [`withdraw`].
#[derive(Debug, Deserialize)]
pub struct WithdrawQuery {
/// The conclusion's id (package and version, see
/// [`license::conclusion_id`]); a query value, as it holds `/` and `@`.
pub id: String,
}
/// DELETE /api/v1/licenses/conclusions?id= — withdraw a confirmed licence;
/// the component shows the detected one again. 404 when there is none.
#[tracing::instrument(skip_all)]
pub async fn withdraw(
Extension(agent): AgentExt,
tenant: TenantCtx,
Query(query): Query<WithdrawQuery>,
) -> Result<Json<serde_json::Value>, Refusal> {
let db = tenant_db(&agent, &tenant)
.await
.map_err(|code| refuse(code, "tenant"))?;
let result = db
.license_conclusions()
.delete_one(doc! { "_id": &query.id })
.await
.map_err(|_| refuse(StatusCode::INTERNAL_SERVER_ERROR, "store"))?;
if result.deleted_count == 0 {
return Err(refuse(StatusCode::NOT_FOUND, "no such confirmed licence"));
}
tracing::info!("license conclusion withdrawn");
Ok(Json(serde_json::json!({ "status": "withdrawn" })))
}
/// Whether the requester may change the policy and decide reviews: LEGAL,
/// IT_ADMIN, or BreakPilot support. USER confirms licences but does not
/// decide whether they may be used.
fn may_decide(tenant: &TenantCtx) -> bool {
let ctx = &tenant.0;
ctx.api_key.is_none()
&& (ctx.staff.is_some() || ctx.has_any_role(&[OrgRole::Legal, OrgRole::ItAdmin]))
}
fn refuse_role() -> Refusal {
(
StatusCode::FORBIDDEN,
Json(serde_json::json!({
"error": crate::api::role_gate::FORBIDDEN_ROLE,
"access": "read_only",
"needs": ["LEGAL", "IT_ADMIN"],
})),
)
}
#[tracing::instrument(skip_all)]
pub async fn get_policy(
Extension(agent): AgentExt,
tenant: TenantCtx,
) -> Result<Json<serde_json::Value>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let policy = crate::license_conclusions::load_policy(&db).await;
Ok(Json(serde_json::json!({
"data": policy,
"may_edit": may_decide(&tenant),
})))
}
#[tracing::instrument(skip_all)]
pub async fn put_policy(
Extension(agent): AgentExt,
tenant: TenantCtx,
Json(policy): Json<LicensePolicy>,
) -> Result<Json<serde_json::Value>, Refusal> {
if !may_decide(&tenant) {
return Err(refuse_role());
}
let actor = Actor::of(&tenant.0);
let mut policy = policy
.normalised()
.map_err(|e| refuse(StatusCode::UNPROCESSABLE_ENTITY, e))?;
policy.updated_by = Some(actor.id.to_string());
policy.updated_by_name = actor.name.clone();
policy.updated_at = Some(chrono::Utc::now());
let db = tenant_db(&agent, &tenant)
.await
.map_err(|code| refuse(code, "tenant"))?;
db.license_policy()
.replace_one(doc! { "_id": license_policy::POLICY_ID }, &policy)
.upsert(true)
.await
.map_err(|e| {
tracing::warn!("license policy not stored: {e}");
refuse(StatusCode::INTERNAL_SERVER_ERROR, "store")
})?;
tracing::info!(
rules = policy.licenses.len(),
support = actor.support,
"license policy changed"
);
Ok(Json(
serde_json::json!({ "status": "saved", "data": policy }),
))
}
/// The fields of a component the policy is judged on.
#[derive(Debug, Deserialize)]
struct CheckRow {
repo_id: String,
name: String,
#[serde(default)]
version: String,
#[serde(default)]
package_manager: String,
#[serde(default)]
purl: Option<String>,
#[serde(default)]
license: Option<String>,
}
impl CheckRow {
fn entry(self) -> SbomEntry {
let mut e = SbomEntry::new(self.repo_id, self.name, self.version, self.package_manager);
e.purl = self.purl;
e.license = self.license;
e
}
}
/// The components a check or notice reads, at most
/// [`super::sbom::MAX_EXPORT_COMPONENTS`], conclusions and verdicts attached.
async fn judged_components(
db: &crate::database::Database,
repo_id: Option<&str>,
) -> (Vec<SbomEntry>, LicensePolicy) {
let mut query = doc! {};
if let Some(repo_id) = repo_id {
query.insert("repo_id", repo_id);
}
let rows: Vec<CheckRow> = match db
.sbom_entries()
.clone_with_type::<CheckRow>()
.find(query)
.projection(doc! {
"_id": 0, "repo_id": 1, "name": 1, "version": 1,
"package_manager": 1, "purl": 1, "license": 1,
})
.sort(doc! { "name": 1, "version": 1 })
.limit(i64::try_from(super::sbom::MAX_EXPORT_COMPONENTS).unwrap_or(i64::MAX))
.await
{
Ok(cursor) => cursor.try_collect().await.unwrap_or_else(|e| {
tracing::warn!("components for the licence check not read: {e}");
Vec::new()
}),
Err(e) => {
tracing::warn!("components for the licence check not read: {e}");
Vec::new()
}
};
let mut entries: Vec<SbomEntry> = rows.into_iter().map(CheckRow::entry).collect();
let conclusions = crate::license_conclusions::load(db).await;
license::apply(&mut entries, &conclusions);
let policy = crate::license_conclusions::load_policy(db).await;
crate::license_conclusions::judge(&mut entries, &policy);
(entries, policy)
}
/// Whether a legal review can decide about `entry`: a licence was confirmed
/// for it, or the scan found an SPDX licence that a review confirms as it is.
/// Anything else needs its licence confirmed first.
fn decidable(entry: &SbomEntry) -> bool {
entry.concluded.is_some()
|| entry
.license
.as_deref()
.map(str::trim)
.filter(|l| !l.is_empty())
.is_some_and(|l| spdx_license::is_spdx_expression(&spdx_license::normalise(l)))
}
/// The query of [`check`] and [`notices`].
#[derive(Debug, Deserialize)]
pub struct CheckQuery {
#[serde(default)]
pub repo_id: Option<String>,
}
/// The most open components one check lists.
pub const MAX_CHECK_ITEMS: usize = 2_000;
#[tracing::instrument(skip_all)]
pub async fn check(
Extension(agent): AgentExt,
tenant: TenantCtx,
Query(query): Query<CheckQuery>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let (entries, policy) = judged_components(&db, query.repo_id.as_deref()).await;
let mut counts = VerdictCounts::default();
// One row per package and version: a confirmation and a review are made
// for the package, whichever target it is in.
let mut items: Vec<serde_json::Value> = Vec::new();
let mut rows: std::collections::HashMap<(String, String, String), usize> =
std::collections::HashMap::new();
for e in &entries {
let Some(verdict) = e.policy.as_ref() else {
continue;
};
counts.add(verdict);
let expiring = verdict
.reasons
.iter()
.any(|r| matches!(r, license_policy::VerdictReason::ExpiresSoon { .. }));
if !(verdict.is_open() || expiring || verdict.required != PolicyAction::Allow) {
continue;
}
let row = (e.package_manager.clone(), e.name.clone(), e.version.clone());
if let Some(&at) = rows.get(&row) {
if let Some(item) = items.get_mut(at) {
let targets = item["targets"].as_u64().unwrap_or(1);
item["targets"] = serde_json::json!(targets + 1);
}
continue;
}
if items.len() >= MAX_CHECK_ITEMS {
continue;
}
rows.insert(row, items.len());
items.push(serde_json::json!({
"repo_id": e.repo_id,
"targets": 1,
"name": e.name,
"version": e.version,
"package_manager": e.package_manager,
"purl": e.purl,
"license": e.effective_license(),
"detected": e.license,
"conclusion_id": e.concluded.as_ref().map(|c| c.id.clone()),
"review": e.concluded.as_ref().and_then(|c| c.review.clone()),
"decidable": decidable(e),
"verdict": verdict,
}));
}
// Forbidden first, then what needs a review, then the rest.
items.sort_by_key(|i| match i["verdict"]["action"].as_str() {
Some("forbid") => 0,
Some("review") => 1,
_ => 2,
});
let listed = items.len();
Ok(Json(serde_json::json!({
"data": {
"counts": counts,
"components": entries.len(),
"items": items,
"truncated": listed >= MAX_CHECK_ITEMS,
"policy": policy,
"may_decide": may_decide(&tenant),
"may_confirm": tenant.0.api_key.is_none()
&& tenant.0.product_access() == compliance_core::ProductAccess::Full,
}
})))
}
/// The body of [`review`].
#[derive(Debug, Deserialize)]
pub struct ReviewRequest {
pub components: Vec<ComponentRef>,
/// For every version of the packages, not just the listed ones.
#[serde(default)]
pub all_versions: bool,
pub decision: ReviewDecision,
#[serde(default)]
pub note: Option<String>,
}
/// The conclusions `req` decides on: each component's confirmed licence with
/// the review set, or, where none was confirmed, the licence the scan found
/// confirmed as it is, by the reviewer.
///
/// # Errors
///
/// Why the review cannot be stored: no component, a component without a
/// licence anyone could review.
fn reviewed(
req: ReviewRequest,
conclusions: &[LicenseConclusion],
tenant: &TenantCtx,
) -> Result<Vec<LicenseConclusion>, String> {
if req.components.is_empty() {
return Err("no component given".into());
}
if req.components.len() > MAX_COMPONENTS {
return Err(format!("at most {MAX_COMPONENTS} components at once"));
}
let note = text(req.note);
if note
.as_deref()
.is_some_and(|n| n.chars().count() > license::MAX_FIELD_CHARS)
{
return Err("note too long".into());
}
let actor = Actor::of(&tenant.0);
let at = chrono::Utc::now();
let review = LegalReview {
decision: req.decision,
by: actor.id.to_string(),
by_name: actor.name.clone(),
support: actor.support,
note,
at,
};
let mut out: Vec<LicenseConclusion> = Vec::new();
for component in &req.components {
let name = component.name.trim();
if name.is_empty() {
return Err("a component without a name".into());
}
let key = package_key(name, &component.package_manager, component.purl.as_deref());
let version = component.version.trim();
let existing = if req.all_versions {
let id = conclusion_id(&key, None);
conclusions.iter().find(|c| c.id == id)
} else {
license::find_for(
conclusions,
name,
&component.package_manager,
version,
component.purl.as_deref(),
)
};
let mut conclusion = match existing {
Some(c) => c.clone(),
None => {
let detected = text(component.license.clone()).ok_or_else(|| {
format!("{name}: no licence to review; confirm the licence first")
})?;
let spdx = spdx_license::normalise(&detected).into_owned();
if !spdx_license::is_spdx_expression(&spdx) {
return Err(format!(
"{name}: the licence found ({detected}) is no SPDX licence; confirm the licence first"
));
}
let version =
(!req.all_versions && !version.is_empty()).then(|| version.to_string());
LicenseConclusion {
id: conclusion_id(&key, version.as_deref()),
package_key: key,
name: name.to_string(),
package_manager: component.package_manager.trim().to_string(),
version,
category: spdx_license::category(&spdx),
license: spdx,
license_name: None,
copyright: Vec::new(),
license_text: None,
license_url: None,
evidence: Some(
"Licence as the scan found it, confirmed in the legal review".into(),
),
contract_ref: None,
valid_until: None,
usage: None,
note: None,
by: actor.id.to_string(),
by_name: actor.name.clone(),
support: actor.support,
at,
review: None,
}
}
};
if out.iter().any(|c| c.id == conclusion.id) {
continue;
}
conclusion.review = Some(review.clone());
out.push(conclusion);
}
Ok(out)
}
#[tracing::instrument(skip_all)]
pub async fn review(
Extension(agent): AgentExt,
tenant: TenantCtx,
Json(req): Json<ReviewRequest>,
) -> Result<Json<serde_json::Value>, Refusal> {
if !may_decide(&tenant) {
return Err(refuse_role());
}
let db = tenant_db(&agent, &tenant)
.await
.map_err(|code| refuse(code, "tenant"))?;
let conclusions = crate::license_conclusions::load(&db).await;
let decision = req.decision;
let reviewed = reviewed(req, &conclusions, &tenant)
.map_err(|e| refuse(StatusCode::UNPROCESSABLE_ENTITY, e))?;
let new = reviewed
.iter()
.filter(|r| !conclusions.iter().any(|c| c.id == r.id))
.count();
if conclusions.len().saturating_add(new) > usize::try_from(MAX_CONCLUSIONS).unwrap_or(0) {
return Err(refuse(
StatusCode::UNPROCESSABLE_ENTITY,
format!("at most {MAX_CONCLUSIONS} confirmed licences per workspace"),
));
}
for c in &reviewed {
db.license_conclusions()
.replace_one(doc! { "_id": &c.id }, c)
.upsert(true)
.await
.map_err(|e| {
tracing::warn!("license review not stored: {e}");
refuse(StatusCode::INTERNAL_SERVER_ERROR, "store")
})?;
}
tracing::info!(
count = reviewed.len(),
decision = decision.as_str(),
"license reviewed"
);
Ok(Json(serde_json::json!({
"status": "saved",
"saved": reviewed.len(),
"conclusions": reviewed,
})))
}
#[tracing::instrument(skip_all)]
pub async fn withdraw_review(
Extension(agent): AgentExt,
tenant: TenantCtx,
Query(query): Query<WithdrawQuery>,
) -> Result<Json<serde_json::Value>, Refusal> {
if !may_decide(&tenant) {
return Err(refuse_role());
}
let db = tenant_db(&agent, &tenant)
.await
.map_err(|code| refuse(code, "tenant"))?;
let result = db
.license_conclusions()
.update_one(
doc! { "_id": &query.id, "review": { "$exists": true } },
doc! { "$unset": { "review": "" } },
)
.await
.map_err(|_| refuse(StatusCode::INTERNAL_SERVER_ERROR, "store"))?;
if result.matched_count == 0 {
return Err(refuse(StatusCode::NOT_FOUND, "no such review"));
}
tracing::info!("license review withdrawn");
Ok(Json(serde_json::json!({ "status": "withdrawn" })))
}
/// The query of [`notices`].
#[derive(Debug, Deserialize)]
pub struct NoticesQuery {
pub repo_id: String,
#[serde(default)]
pub format: NoticeFormat,
/// Also list components only used to build.
#[serde(default)]
pub build_only: bool,
}
#[tracing::instrument(skip_all)]
pub async fn notices(
Extension(agent): AgentExt,
tenant: TenantCtx,
Query(query): Query<NoticesQuery>,
) -> Result<impl IntoResponse, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let (entries, _) = judged_components(&db, Some(&query.repo_id)).await;
let product = target_name(&db, &query.repo_id).await;
let body = license_notices::render(
&entries,
&license_notices::NoticeOptions {
product: &product,
format: query.format,
include_build_only: query.build_only,
},
);
let disposition = format!("attachment; filename=\"{}\"", query.format.file_name());
Ok((
[
(
header::CONTENT_TYPE,
header::HeaderValue::from_static(query.format.content_type()),
),
(
header::CONTENT_DISPOSITION,
header::HeaderValue::from_str(&disposition)
.unwrap_or_else(|_| header::HeaderValue::from_static("attachment")),
),
],
body,
))
}
/// The name of the target `repo_id`, as the exports name the product.
pub(crate) async fn target_name(db: &crate::database::Database, repo_id: &str) -> String {
let target = match mongodb::bson::oid::ObjectId::parse_str(repo_id) {
Ok(oid) => db
.onboarded_targets()
.find_one(doc! { "_id": oid })
.await
.ok()
.flatten(),
Err(_) => None,
};
target.map_or_else(|| format!("repo-{repo_id}"), |t| t.name)
}
#[cfg(test)]
mod tests {
use super::*;
fn req(license: Option<&str>, name: Option<&str>) -> ConcludeRequest {
ConcludeRequest {
components: vec![
ComponentRef {
name: "left-pad".into(),
package_manager: "npm".into(),
version: "1.3.0".into(),
purl: Some("pkg:npm/left-pad@1.3.0".into()),
license: None,
},
// The same package and version twice is one conclusion.
ComponentRef {
name: "left-pad".into(),
package_manager: "npm".into(),
version: "1.3.0".into(),
purl: Some("pkg:npm/left-pad@1.3.0".into()),
license: None,
},
ComponentRef {
name: "PumpSdk".into(),
package_manager: "nuget".into(),
version: "".into(),
purl: None,
license: None,
},
],
all_versions: false,
license: license.map(String::from),
license_name: name.map(String::from),
category: Some(LicenseCategory::Proprietary),
copyright: vec!["© 2019 Example GmbH\n\n© 2021 Other AG".into()],
license_text: Some(" ".into()),
license_url: None,
evidence: Some(" LICENSE.txt ".into()),
contract_ref: None,
valid_until: None,
usage: Some(LicenseUsage::Shipped),
note: None,
}
}
fn tenant() -> TenantCtx {
TenantCtx(compliance_core::TenantContext {
tenant_id: "t-1".to_string(),
tenant_slug: "acme".to_string(),
org_roles: Vec::new(),
products: Vec::new(),
plan: String::new(),
status: compliance_core::TenantStatus::Active,
user_id: "u-1".to_string(),
user_name: Some("Erika Muster".to_string()),
staff: None,
api_key: None,
})
}
#[test]
fn an_spdx_licence_gets_its_own_category() {
let out =
conclusions_of(req(Some("Apache License, Version 2.0"), None), &tenant()).unwrap();
assert_eq!(out.len(), 2, "duplicates are merged");
assert_eq!(out[0].license, "Apache-2.0");
assert_eq!(
out[0].category,
LicenseCategory::Permissive,
"not the asked category"
);
assert_eq!(out[0].version.as_deref(), Some("1.3.0"));
assert_eq!(out[0].id, "pkg:npm/left-pad@1.3.0");
assert_eq!(out[1].id, "nuget:PumpSdk@*", "no version is every version");
assert_eq!(out[0].copyright, ["© 2019 Example GmbH", "© 2021 Other AG"]);
assert_eq!(out[0].license_text, None);
assert_eq!(out[0].evidence.as_deref(), Some("LICENSE.txt"));
}
#[test]
fn a_licence_of_its_own_gets_a_license_ref() {
let out = conclusions_of(req(None, Some("Pump EULA")), &tenant()).unwrap();
assert_eq!(out[0].license, "LicenseRef-Pump-EULA");
assert_eq!(out[0].license_name.as_deref(), Some("Pump EULA"));
assert_eq!(out[0].category, LicenseCategory::Proprietary);
}
#[test]
fn every_version_drops_the_version() {
let mut r = req(Some("MIT"), None);
r.all_versions = true;
let out = conclusions_of(r, &tenant()).unwrap();
assert_eq!(out[0].id, "pkg:npm/left-pad@*");
assert_eq!(out[0].version, None);
}
#[test]
fn bad_requests_are_refused_with_a_reason() {
assert!(conclusions_of(req(None, None), &tenant()).is_err());
assert!(conclusions_of(req(Some("Custom thing"), None), &tenant()).is_err());
let mut none = req(Some("MIT"), None);
none.components.clear();
assert!(conclusions_of(none, &tenant()).is_err());
let mut many = req(Some("MIT"), None);
many.components = vec![many.components[0].clone(); MAX_COMPONENTS + 1];
assert!(conclusions_of(many, &tenant()).is_err());
let mut nameless = req(Some("MIT"), None);
nameless.components[0].name = " ".into();
assert!(conclusions_of(nameless, &tenant()).is_err());
let mut url = req(Some("MIT"), None);
url.license_url = Some("file:///etc/passwd".into());
assert!(conclusions_of(url, &tenant()).is_err());
}
fn with_roles(roles: Vec<OrgRole>) -> TenantCtx {
let mut t = tenant();
t.0.org_roles = roles;
t
}
fn review_req(license: Option<&str>, decision: ReviewDecision) -> ReviewRequest {
ReviewRequest {
components: vec![ComponentRef {
name: "readline".into(),
package_manager: "deb".into(),
version: "8.2".into(),
purl: None,
license: license.map(String::from),
}],
all_versions: false,
decision,
note: Some(" ok for the firmware ".into()),
}
}
#[test]
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::User])));
assert!(!may_decide(&with_roles(vec![OrgRole::Cxo])));
}
#[test]
fn a_review_without_a_confirmed_licence_confirms_the_detected_one() {
let out = reviewed(
review_req(Some("gpl-3.0-only"), ReviewDecision::Approved),
&[],
&with_roles(vec![OrgRole::Legal]),
)
.unwrap_or_default();
assert_eq!(out.len(), 1);
assert_eq!(out[0].license, "GPL-3.0-only");
assert_eq!(out[0].category, LicenseCategory::StrongCopyleft);
assert_eq!(out[0].version.as_deref(), Some("8.2"));
let review = out[0].review.as_ref().map(|r| (r.decision, r.note.clone()));
assert_eq!(
review,
Some((ReviewDecision::Approved, Some("ok for the firmware".into())))
);
}
#[test]
fn a_review_keeps_the_confirmed_licence_and_needs_one() {
let confirmed = conclusions_of(req(None, Some("Pump EULA")), &tenant()).unwrap_or_default();
let mut r = review_req(None, ReviewDecision::Rejected);
r.components[0] = ComponentRef {
name: "PumpSdk".into(),
package_manager: "nuget".into(),
version: "".into(),
purl: None,
license: None,
};
let out = reviewed(r, &confirmed, &tenant()).unwrap_or_default();
assert_eq!(out.len(), 1);
assert_eq!(out[0].license_name.as_deref(), Some("Pump EULA"));
assert_eq!(
out[0].review.as_ref().map(|r| r.decision),
Some(ReviewDecision::Rejected)
);
assert!(reviewed(review_req(None, ReviewDecision::Approved), &[], &tenant()).is_err());
assert!(reviewed(
review_req(Some("Some EULA"), ReviewDecision::Approved),
&[],
&tenant()
)
.is_err());
}
#[test]
fn only_a_confirmed_or_spdx_licence_can_be_decided() {
let entry = |license: Option<&str>| {
let mut e = SbomEntry::new("r".into(), "lib".into(), "1".into(), "npm".into());
e.license = license.map(String::from);
e
};
assert!(decidable(&entry(Some("Apache License, Version 2.0"))));
assert!(decidable(&entry(Some("MIT OR GPL-3.0-only"))));
assert!(!decidable(&entry(None)));
assert!(!decidable(&entry(Some(
"http://go.microsoft.com/fwlink/?LinkID=262998"
))));
let mut confirmed = entry(None);
confirmed.concluded = conclusions_of(req(Some("MIT"), None), &tenant())
.unwrap()
.into_iter()
.next();
assert!(decidable(&confirmed));
}
}
@@ -234,6 +234,7 @@ mod tests {
user_id: "u".into(),
user_name: None,
staff: None,
api_key: None,
})
}
+1
View File
@@ -10,6 +10,7 @@ pub mod graph;
pub mod health;
pub mod help_chat;
pub mod issues;
pub mod licenses;
pub mod manual_findings;
pub mod mcp_servers;
pub mod mcp_tokens;
+43 -50
View File
@@ -516,36 +516,13 @@ pub async fn delete_target(
.await;
// DAST targets linked to this target, and all their downstream data.
if let Ok(mut cursor) = db.dast_targets().find(doc! { "repo_id": &id }).await {
use futures_util::StreamExt;
while let Some(Ok(dt)) = cursor.next().await {
let dast_target_id = dt.id.map(|oid| oid.to_hex()).unwrap_or_default();
if !dast_target_id.is_empty() {
cascade_delete_dast_target(db, &dast_target_id).await;
}
}
for dast_target_id in ids_of(db.dast_targets(), doc! { "repo_id": &id }).await {
cascade_delete_dast_target(db, &dast_target_id).await;
}
// Pentest sessions linked directly to this target (not via a DAST target).
if let Ok(mut cursor) = db.pentest_sessions().find(doc! { "repo_id": &id }).await {
use futures_util::StreamExt;
while let Some(Ok(session)) = cursor.next().await {
let session_id = session.id.map(|oid| oid.to_hex()).unwrap_or_default();
if !session_id.is_empty() {
let _ = db
.attack_chain_nodes()
.delete_many(doc! { "session_id": &session_id })
.await;
let _ = db
.pentest_messages()
.delete_many(doc! { "session_id": &session_id })
.await;
let _ = db
.dast_findings()
.delete_many(doc! { "session_id": &session_id })
.await;
}
}
for session_id in ids_of(db.pentest_sessions(), doc! { "repo_id": &id }).await {
delete_session_data(db, &session_id).await;
}
let _ = db
.pentest_sessions()
@@ -555,32 +532,32 @@ pub async fn delete_target(
Ok(Json(serde_json::json!({ "status": "deleted" })))
}
/// The `_id`s (hex) of the documents in `coll` that match `filter`, read raw
/// with only `_id` projected: a document stored in another shape (an older
/// version, a manual insert) is still found, so a cascade never stops at it
/// and leaves its downstream data behind.
async fn ids_of<T: Send + Sync>(
coll: mongodb::Collection<T>,
filter: mongodb::bson::Document,
) -> Vec<String> {
use futures_util::StreamExt;
let raw = coll.clone_with_type::<mongodb::bson::Document>();
let mut out = Vec::new();
if let Ok(mut cursor) = raw.find(filter).projection(doc! { "_id": 1 }).await {
while let Some(next) = cursor.next().await {
if let Ok(Ok(oid)) = next.as_ref().map(|d| d.get_object_id("_id")) {
out.push(oid.to_hex());
}
}
}
out
}
/// Delete a DAST target and everything downstream of it (pentest sessions +
/// their attack chains / messages / findings, DAST scan runs + findings).
async fn cascade_delete_dast_target(db: &crate::database::Database, target_id: &str) {
use futures_util::StreamExt;
if let Ok(mut cursor) = db
.pentest_sessions()
.find(doc! { "target_id": target_id })
.await
{
while let Some(Ok(session)) = cursor.next().await {
let session_id = session.id.map(|oid| oid.to_hex()).unwrap_or_default();
if !session_id.is_empty() {
let _ = db
.attack_chain_nodes()
.delete_many(doc! { "session_id": &session_id })
.await;
let _ = db
.pentest_messages()
.delete_many(doc! { "session_id": &session_id })
.await;
let _ = db
.dast_findings()
.delete_many(doc! { "session_id": &session_id })
.await;
}
}
for session_id in ids_of(db.pentest_sessions(), doc! { "target_id": target_id }).await {
delete_session_data(db, &session_id).await;
}
let _ = db
.pentest_sessions()
@@ -599,6 +576,22 @@ async fn cascade_delete_dast_target(db: &crate::database::Database, target_id: &
}
}
/// The attack chain, messages and findings of one pentest session.
async fn delete_session_data(db: &crate::database::Database, session_id: &str) {
let _ = db
.attack_chain_nodes()
.delete_many(doc! { "session_id": session_id })
.await;
let _ = db
.pentest_messages()
.delete_many(doc! { "session_id": session_id })
.await;
let _ = db
.dast_findings()
.delete_many(doc! { "session_id": session_id })
.await;
}
/// POST /api/v1/targets/{id}/artifacts — attach an artifact (by reference).
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn add_artifact(
+100 -14
View File
@@ -472,6 +472,9 @@ pub struct PlatformTarget {
pub last_scan_at: Option<chrono::DateTime<chrono::Utc>>,
/// Findings that still need attention.
pub open_findings: u64,
/// Known vulnerabilities in its components that are still open: CVE
/// alerts neither resolved nor assessed `not_affected` / `fixed`.
pub open_vulnerabilities: u64,
/// Its projects that the registry still lists.
pub project_ids: Vec<String>,
}
@@ -481,23 +484,56 @@ async fn open_findings_counts(
db: &crate::database::Database,
target_ids: Vec<String>,
) -> Result<std::collections::HashMap<String, u64>, StatusCode> {
let pipeline = vec![
doc! { "$match": {
"repo_id": { "$in": target_ids },
"status": { "$in": super::health::OPEN_STATUSES.to_vec() },
} },
doc! { "$group": { "_id": "$repo_id", "n": { "$sum": 1 } } },
];
let rows: Vec<Document> = db
.findings()
.aggregate(pipeline)
.aggregate(count_by_target(doc! {
"repo_id": { "$in": target_ids },
"status": { "$in": super::health::OPEN_STATUSES.to_vec() },
}))
.await
.map_err(internal)?
.try_collect()
.await
.map_err(internal)?;
Ok(rows
.iter()
Ok(counts_by_target(&rows))
}
/// The CVE alerts that still need a decision: not resolved by a later scan
/// and not assessed as `not_affected` or `fixed` in VEX.
fn open_vulnerabilities_filter(target_ids: Vec<String>) -> Document {
doc! {
"repo_id": { "$in": target_ids },
"resolved_at": null,
"vex.status": { "$nin": ["not_affected", "fixed"] },
}
}
/// Open vulnerabilities (CVE alerts) of each target in `target_ids`, in one
/// query.
async fn open_vulnerabilities_counts(
db: &crate::database::Database,
target_ids: Vec<String>,
) -> Result<std::collections::HashMap<String, u64>, StatusCode> {
let rows: Vec<Document> = db
.cve_alerts()
.aggregate(count_by_target(open_vulnerabilities_filter(target_ids)))
.await
.map_err(internal)?
.try_collect()
.await
.map_err(internal)?;
Ok(counts_by_target(&rows))
}
fn count_by_target(filter: Document) -> Vec<Document> {
vec![
doc! { "$match": filter },
doc! { "$group": { "_id": "$repo_id", "n": { "$sum": 1 } } },
]
}
fn counts_by_target(rows: &[Document]) -> std::collections::HashMap<String, u64> {
rows.iter()
.filter_map(|row| {
let id = row.get_str("_id").ok()?.to_string();
let n = row
@@ -507,7 +543,7 @@ async fn open_findings_counts(
.ok()?;
Some((id, u64::try_from(n).ok()?))
})
.collect())
.collect()
}
/// `GET /api/v1/platform/tenants/{id}/targets?project=<id>` — the tenant's
@@ -538,11 +574,12 @@ pub async fn list_targets(
.filter_map(|t| t.id.map(|id| id.to_hex()))
.collect();
let runs = db.scan_runs();
let (mut last_scans, open) = tokio::join!(
let (mut last_scans, open, vulns) = tokio::join!(
super::onboarding::latest_scan_runs(&runs, ids.clone()),
open_findings_counts(&db, ids),
open_findings_counts(&db, ids.clone()),
open_vulnerabilities_counts(&db, ids),
);
let open = open?;
let (open, vulns) = (open?, vulns?);
let known = super::projects::tenant_projects(&st.agent, &tenant_id)
.await
.ok();
@@ -553,6 +590,7 @@ pub async fn list_targets(
PlatformTarget {
last_scan_at: last_scans.remove(&id).map(|run| run.started_at),
open_findings: open.get(&id).copied().unwrap_or(0),
open_vulnerabilities: vulns.get(&id).copied().unwrap_or(0),
project_ids: match known.as_deref() {
Some(known) => super::projects::known_project_ids(&t.project_ids, known),
None => t.project_ids,
@@ -782,3 +820,51 @@ mod build_info_tests {
assert!(!BUILD_COMMIT.is_empty());
}
}
#[cfg(test)]
mod target_count_tests {
use super::*;
#[test]
fn open_vulnerabilities_leave_out_resolved_and_assessed_alerts() {
let f = open_vulnerabilities_filter(vec!["a".into(), "b".into()]);
assert_eq!(
f.get_document("repo_id")
.unwrap()
.get_array("$in")
.unwrap()
.len(),
2
);
assert_eq!(f.get("resolved_at"), Some(&mongodb::bson::Bson::Null));
let nin = f
.get_document("vex.status")
.unwrap()
.get_array("$nin")
.unwrap();
assert_eq!(
nin,
&vec![
mongodb::bson::Bson::from("not_affected"),
mongodb::bson::Bson::from("fixed")
]
);
}
#[test]
fn counts_are_read_per_target_whatever_the_integer_width() {
let rows = vec![
doc! { "_id": "a", "n": 3_i32 },
doc! { "_id": "b", "n": 5_i64 },
doc! { "_id": "c", "n": -1_i64 },
doc! { "n": 2_i32 },
];
let counts = counts_by_target(&rows);
assert_eq!(counts.get("a"), Some(&3));
assert_eq!(counts.get("b"), Some(&5));
assert_eq!(counts.len(), 2);
let stages = count_by_target(doc! { "x": 1 });
assert_eq!(stages.len(), 2);
assert!(stages[0].contains_key("$match") && stages[1].contains_key("$group"));
}
}
@@ -165,6 +165,7 @@ mod tests {
user_id: "u-1".to_string(),
user_name: Some("Sharang".to_string()),
}),
api_key: None,
}
}
+230 -45
View File
@@ -87,15 +87,37 @@ pub async fn list_sbom(
if let Some(in_image) = filter.in_image {
query.insert("in_image", doc! { "$exists": in_image });
}
let conclusions = crate::license_conclusions::load(db).await;
let skip = filter.skip();
let total = db
.sbom_entries()
.count_documents(query.clone())
.await
.unwrap_or(0);
let mut skip = filter.skip();
let mut total = None;
if filter.unresolved == Some(true) {
// No licence found by the scan; `null` also matches a missing field.
query.insert("license", doc! { "$in": [mongodb::bson::Bson::Null, ""] });
if !conclusions.is_empty() {
// Which of them nobody confirmed a licence for is known only
// here, so the page is cut from the open ones.
let open = unresolved_ids(db, &query, &conclusions).await;
total = Some(open.len() as u64);
let page: Vec<_> = open
.into_iter()
.skip(usize::try_from(skip).unwrap_or(usize::MAX))
.take(usize::try_from(filter.limit).unwrap_or(0))
.collect();
query = doc! { "_id": { "$in": page } };
skip = 0;
}
}
let total = match total {
Some(total) => total,
None => db
.sbom_entries()
.count_documents(query.clone())
.await
.unwrap_or(0),
};
let entries = match db
let mut entries: Vec<SbomEntry> = match db
.sbom_entries()
.find(query)
.sort(list_order())
@@ -109,6 +131,9 @@ pub async fn list_sbom(
Vec::new()
}
};
compliance_core::models::license::apply(&mut entries, &conclusions);
let policy = crate::license_conclusions::load_policy(db).await;
crate::license_conclusions::judge(&mut entries, &policy);
Ok(Json(ApiResponse {
data: entries,
@@ -123,6 +148,56 @@ fn list_order() -> mongodb::bson::Document {
doc! { "in_image.basis": -1, "name": 1 }
}
/// The fields a licence conclusion is matched on.
#[derive(serde::Deserialize)]
struct LicenseKeyRow {
#[serde(rename = "_id")]
id: mongodb::bson::oid::ObjectId,
name: String,
version: String,
package_manager: String,
#[serde(default)]
purl: Option<String>,
#[serde(default)]
license: Option<String>,
}
/// The components of `query` (in list order) nobody confirmed a licence for.
async fn unresolved_ids(
db: &crate::database::Database,
query: &mongodb::bson::Document,
conclusions: &[compliance_core::models::LicenseConclusion],
) -> Vec<mongodb::bson::oid::ObjectId> {
let rows: Vec<LicenseKeyRow> = match db
.sbom_entries()
.clone_with_type::<LicenseKeyRow>()
.find(query.clone())
.projection(doc! { "_id": 1, "name": 1, "version": 1, "package_manager": 1, "purl": 1 })
.sort(list_order())
.limit(i64::try_from(MAX_EXPORT_COMPONENTS).unwrap_or(i64::MAX))
.await
{
Ok(cursor) => collect_cursor_async(cursor).await,
Err(e) => {
tracing::warn!("Failed to fetch open licences: {e}");
Vec::new()
}
};
rows.into_iter()
.filter(|r| {
compliance_core::models::license::find_for(
conclusions,
&r.name,
&r.package_manager,
&r.version,
r.purl.as_deref(),
)
.is_none()
})
.map(|r| r.id)
.collect()
}
#[tracing::instrument(skip_all)]
pub async fn export_sbom(
Extension(agent): AgentExt,
@@ -143,7 +218,7 @@ pub async fn export_sbom(
);
return Err(StatusCode::PAYLOAD_TOO_LARGE);
}
let entries: Vec<SbomEntry> = match db
let mut entries: Vec<SbomEntry> = match db
.sbom_entries()
.find(doc! { "repo_id": &params.repo_id })
.await
@@ -154,6 +229,7 @@ pub async fn export_sbom(
Vec::new()
}
};
crate::license_conclusions::attach(db, &mut entries).await;
let body = if params.format == "spdx" {
compliance_core::sbom_docs::spdx(&entries, &params.repo_id)
@@ -245,53 +321,96 @@ pub async fn license_summary(
query.insert("repo_id", repo_id);
}
// Grouped in Mongo: this used to load every SBOM entry of the tenant (with
// its vulnerability list) into the agent when no repo was given (#67).
#[derive(serde::Deserialize)]
struct LicenseRow {
#[serde(rename = "_id")]
license: String,
count: i64,
packages: Vec<String>,
}
let pipeline = vec![
doc! { "$match": query },
doc! { "$group": {
"_id": { "$ifNull": ["$license", "Unknown"] },
"count": { "$sum": 1 },
"packages": { "$firstN": { "input": "$name", "n": MAX_LICENSE_PACKAGES } },
} },
];
let mut summaries: Vec<LicenseSummary> = match db.sbom_entries().aggregate(pipeline).await {
Ok(cursor) => {
use futures_util::StreamExt;
cursor
.filter_map(|row| async move {
let row: LicenseRow = mongodb::bson::from_document(row.ok()?).ok()?;
Some(LicenseSummary {
is_copyleft: compliance_core::spdx_license::is_copyleft(&row.license),
license: row.license,
count: u64::try_from(row.count).unwrap_or(0),
packages: row.packages,
})
})
.collect()
.await
}
// Only the fields the grouping needs, never whole entries with their
// vulnerability lists (#67). Grouped here rather than in Mongo, as a
// licence a person confirmed counts instead of the detected one.
let rows: Vec<LicenseKeyRow> = match db
.sbom_entries()
.clone_with_type::<LicenseKeyRow>()
.find(query)
.projection(doc! {
"_id": 1, "name": 1, "version": 1, "package_manager": 1, "purl": 1, "license": 1,
})
.limit(i64::try_from(MAX_EXPORT_COMPONENTS).unwrap_or(i64::MAX))
.await
{
Ok(cursor) => collect_cursor_async(cursor).await,
Err(e) => {
tracing::warn!("Failed to aggregate SBOM licenses: {e}");
tracing::warn!("Failed to read SBOM licenses: {e}");
Vec::new()
}
};
summaries.sort_by_key(|s| std::cmp::Reverse(s.count));
let conclusions = crate::license_conclusions::load(db).await;
Ok(Json(ApiResponse {
data: summaries,
data: summarize_licenses(&rows, &conclusions),
total: None,
page: None,
}))
}
/// One summary row per licence, most components first: the confirmed
/// licence where there is one, else the detected one, else `Unknown`.
fn summarize_licenses(
rows: &[LicenseKeyRow],
conclusions: &[compliance_core::models::LicenseConclusion],
) -> Vec<LicenseSummary> {
use compliance_core::models::LicenseCategory;
use compliance_core::spdx_license;
let mut by_license: std::collections::HashMap<String, LicenseSummary> =
std::collections::HashMap::new();
for r in rows {
let concluded = compliance_core::models::license::find_for(
conclusions,
&r.name,
&r.package_manager,
&r.version,
r.purl.as_deref(),
);
let detected = r
.license
.as_deref()
.map(str::trim)
.filter(|l| !l.is_empty());
let (label, category, is_copyleft) = match (concluded, detected) {
(Some(c), _) => (
c.display().to_string(),
c.category,
c.category.is_copyleft(),
),
(None, Some(l)) => (
l.to_string(),
spdx_license::category(l),
spdx_license::is_copyleft(l),
),
(None, None) => ("Unknown".to_string(), LicenseCategory::Unclear, false),
};
let row = by_license
.entry(label.clone())
.or_insert_with(|| LicenseSummary {
license: label,
count: 0,
is_copyleft,
category,
confirmed: 0,
packages: Vec::new(),
});
row.count += 1;
if concluded.is_some() {
row.confirmed += 1;
}
if (row.packages.len() as i64) < MAX_LICENSE_PACKAGES && !row.packages.contains(&r.name) {
row.packages.push(r.name.clone());
}
}
let mut summaries: Vec<LicenseSummary> = by_license.into_values().collect();
summaries.sort_by(|a, b| {
b.count
.cmp(&a.count)
.then_with(|| a.license.cmp(&b.license))
});
summaries
}
#[tracing::instrument(skip_all)]
pub async fn sbom_diff(
Extension(agent): AgentExt,
@@ -396,3 +515,69 @@ async fn diff_rows(db: &crate::database::Database, repo_id: &str) -> Vec<DiffRow
}
}
}
#[cfg(test)]
mod license_summary_tests {
use super::*;
use compliance_core::models::license::{conclusion_id, package_key};
use compliance_core::models::{LicenseCategory, LicenseConclusion};
fn row(name: &str, license: Option<&str>) -> LicenseKeyRow {
LicenseKeyRow {
id: mongodb::bson::oid::ObjectId::new(),
name: name.into(),
version: "1.0".into(),
package_manager: "npm".into(),
purl: Some(format!("pkg:npm/{name}@1.0")),
license: license.map(String::from),
}
}
#[test]
fn a_confirmed_licence_counts_instead_of_the_detected_one() {
let key = package_key("pump", "npm", Some("pkg:npm/pump@1.0"));
let conclusion = LicenseConclusion {
id: conclusion_id(&key, None),
package_key: key,
name: "pump".into(),
package_manager: "npm".into(),
version: None,
license: "LicenseRef-Pump-EULA".into(),
license_name: Some("Pump EULA".into()),
category: LicenseCategory::Proprietary,
copyright: Vec::new(),
license_text: None,
license_url: None,
evidence: None,
contract_ref: None,
valid_until: None,
usage: None,
note: None,
by: "u".into(),
by_name: None,
support: false,
at: chrono::Utc::now(),
review: None,
};
let rows = [
row("a", Some("MIT")),
row("b", Some("MIT")),
row("c", Some("LGPL-2.1-only")),
row("d", None),
row("pump", None),
];
let summary = summarize_licenses(&rows, &[conclusion]);
let get = |l: &str| summary.iter().find(|s| s.license == l).unwrap();
assert_eq!(summary[0].license, "MIT");
assert_eq!(get("MIT").count, 2);
assert_eq!(get("MIT").category, LicenseCategory::Permissive);
assert_eq!(get("LGPL-2.1-only").category, LicenseCategory::WeakCopyleft);
assert_eq!(
get("Unknown").count,
1,
"the confirmed one is no longer unknown"
);
assert_eq!(get("Pump EULA").confirmed, 1);
assert_eq!(get("Pump EULA").category, LicenseCategory::Proprietary);
}
}
@@ -7,11 +7,11 @@
//! its token and its uploaded file, and a scan config keeps every field the
//! request does not name (#304).
use serde::Deserialize;
use serde::{Deserialize, Deserializer};
use compliance_core::models::{
Artifact, ArtifactAuth, ArtifactKind, Environment, IssueTrackerConfig, PentestConfig,
PentestStrategy, PlcFormat, ScanType, TargetScanConfig,
normalise_exclude_paths, Artifact, ArtifactAuth, ArtifactKind, Environment, IssueTrackerConfig,
PentestConfig, PentestStrategy, PlcFormat, ScanType, TargetScanConfig,
};
use crate::secrets::{SecretBox, SecretError};
@@ -138,6 +138,22 @@ pub struct ScanConfigUpdate {
pub strategy: Option<PentestStrategy>,
pub pentest: Option<PentestConfig>,
pub issue_tracker: Option<IssueTrackerConfig>,
/// Paths left out of every scan; replaces the stored list. Normalised
/// while the request is read, so an invalid path is refused with its
/// reason (axum answers 422 with the message).
#[serde(default, deserialize_with = "exclude_paths")]
pub exclude_paths: Option<Vec<String>>,
}
/// `exclude_paths` as [`normalise_exclude_paths`] stores them; an invalid
/// entry fails the request with the reason naming it.
fn exclude_paths<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
where
D: Deserializer<'de>,
{
Option::<Vec<String>>::deserialize(deserializer)?
.map(|paths| normalise_exclude_paths(&paths).map_err(serde::de::Error::custom))
.transpose()
}
impl ScanConfigUpdate {
@@ -169,6 +185,9 @@ impl ScanConfigUpdate {
if let Some(v) = self.strategy {
merged.strategy = Some(v);
}
if let Some(v) = self.exclude_paths {
merged.exclude_paths = v;
}
if let Some(mut tracker) = self.issue_tracker {
let kept = stored.issue_tracker.as_ref().and_then(|t| t.token.as_ref());
secrets.take_update(&mut tracker.token, kept)?;
@@ -275,6 +294,32 @@ mod tests {
assert!(cleared.auth.is_none());
}
#[test]
fn excluded_paths_are_normalised_or_refused_with_the_reason() {
let update: ScanConfigUpdate =
serde_json::from_str(r#"{"exclude_paths": ["./docs/samples/", "", "tools\\old"]}"#)
.unwrap();
assert_eq!(
update.exclude_paths.as_deref(),
Some(&["docs/samples".to_string(), "tools/old".to_string()][..])
);
let stored = TargetScanConfig {
exclude_paths: vec!["old".into()],
..Default::default()
};
let merged = update.apply(&secrets(), &stored).unwrap();
assert_eq!(merged.exclude_paths, ["docs/samples", "tools/old"]);
// Left out: the stored list stays.
let untouched: ScanConfigUpdate = serde_json::from_str("{}").unwrap();
let kept = untouched.apply(&secrets(), &stored).unwrap();
assert_eq!(kept.exclude_paths, ["old"]);
let err = serde_json::from_str::<ScanConfigUpdate>(r#"{"exclude_paths": ["../etc"]}"#)
.unwrap_err();
assert!(err.to_string().contains("../etc"), "{err}");
}
#[test]
fn enabling_a_scan_keeps_the_tracker_and_its_token() {
let s = secrets();
+2
View File
@@ -1,6 +1,8 @@
pub mod api_key_gate;
pub mod handlers;
pub mod role_gate;
pub mod routes;
pub mod server;
pub mod trace;
pub use server::start_api_server;
+112 -2
View File
@@ -4,7 +4,9 @@
//!
//! * `IT_ADMIN`, `USER` — read and write.
//! * `CXO`, `LEGAL` — read only: `GET` / `HEAD` / `OPTIONS`, plus the few
//! `POST` routes that only read ([`READ_ONLY_POSTS`]).
//! `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.
//!
//! Refusals are `403 {"error": "forbidden_role", "access": "none" | "read_only"}`.
@@ -17,6 +19,10 @@
//! check, and support staff who have not chosen a tenant yet.
//!
//! Handlers may still be stricter (manual findings stay `IT_ADMIN`-only).
//!
//! API keys (tenant-registry ADR 0001) hold no role. They reach only the
//! routes in [`KEY_SCOPES`], each with the scope it names; every other route
//! answers `403 {"error": "scope_missing"}`.
use axum::{
extract::{MatchedPath, Request},
@@ -25,11 +31,81 @@ use axum::{
response::{IntoResponse, Response},
Json,
};
use compliance_core::{ProductAccess, TenantContext};
use compliance_core::{ApiKeyAccess, OrgRole, ProductAccess, TenantContext};
/// The JSON `error` of a refusal.
pub const FORBIDDEN_ROLE: &str = "forbidden_role";
/// The JSON `error` when an API key lacks the route's scope, or the route
/// takes no key at all.
pub const SCOPE_MISSING: &str = "scope_missing";
/// Every route an API key may call: method, route template, required scope.
/// Anything not listed (manual findings, credentials, target admin,
/// settings, releasing an ENISA draft) is unreachable with a key.
pub const KEY_SCOPES: &[(Method, &str, &str)] = &[
(Method::GET, "/api/v1/findings", FINDINGS_READ),
(Method::GET, "/api/v1/findings/variants", FINDINGS_READ),
(Method::GET, "/api/v1/findings/{id}", FINDINGS_READ),
(
Method::PATCH,
"/api/v1/findings/{id}/status",
FINDINGS_WRITE,
),
(
Method::PATCH,
"/api/v1/findings/bulk-status",
FINDINGS_WRITE,
),
(
Method::PATCH,
"/api/v1/findings/{id}/feedback",
FINDINGS_WRITE,
),
(Method::GET, "/api/v1/sbom", SBOM_READ),
(Method::GET, "/api/v1/sbom/filters", SBOM_READ),
(Method::GET, "/api/v1/sbom/export", SBOM_READ),
(Method::GET, "/api/v1/sbom/licenses", SBOM_READ),
(Method::GET, "/api/v1/sbom/quality", SBOM_READ),
(Method::GET, "/api/v1/sbom/diff", SBOM_READ),
(Method::GET, "/api/v1/sbom/notices", SBOM_READ),
(Method::GET, "/api/v1/licenses/check", SBOM_READ),
(Method::GET, "/api/v1/licenses/policy", SBOM_READ),
(Method::GET, "/api/v1/scan-runs", SCANS_READ),
(Method::POST, "/api/v1/targets/{id}/scan", SCANS_RUN),
(Method::POST, "/api/v1/dast/targets/{id}/scan", SCANS_RUN),
(Method::GET, "/api/v1/targets/{id}/enisa", ENISA_READ),
(Method::GET, "/api/v1/cves/{id}/enisa", ENISA_READ),
];
const FINDINGS_READ: &str = "pruefwerk:findings.read";
const FINDINGS_WRITE: &str = "pruefwerk:findings.write";
const SBOM_READ: &str = "pruefwerk:sbom.read";
const SCANS_READ: &str = "pruefwerk:scans.read";
const SCANS_RUN: &str = "pruefwerk:scans.run";
const ENISA_READ: &str = "pruefwerk:enisa.read";
/// What a legacy key (issued before scopes, no scopes of its own) may do:
/// read, never write or run. Such keys never reached this API before.
pub const LEGACY_SCOPES: &[&str] = &[FINDINGS_READ, SBOM_READ, SCANS_READ, ENISA_READ];
/// The scope `key` lacks for `method` on `template`, if any. A route that is
/// not in [`KEY_SCOPES`] (or matched no route) lacks `None`: no scope opens it.
pub fn key_refusal(
key: &ApiKeyAccess,
method: &Method,
template: Option<&str>,
) -> Option<Option<&'static str>> {
let required = KEY_SCOPES
.iter()
.find(|(m, t, _)| m == method && Some(*t) == template)
.map(|(_, _, scope)| *scope);
match required {
Some(scope) if key.has_scope(scope) => None,
missing => Some(missing),
}
}
/// `POST` routes that only read: a query or an export with a body. Matched
/// against the route template, so an id in the path does not matter. Every
/// other `POST`, `PUT`, `PATCH` and `DELETE` is a write.
@@ -44,6 +120,21 @@ pub const READ_ONLY_POSTS: &[&str] = &[
"/api/v1/help/chat",
];
/// Writes a read-only role may still make: method, route template, the
/// roles that may. The handler decides who else may (IT_ADMIN, support).
pub const ROLE_WRITES: &[(Method, &str, &[OrgRole])] = &[
(Method::PUT, "/api/v1/licenses/policy", &[OrgRole::Legal]),
(Method::POST, "/api/v1/licenses/review", &[OrgRole::Legal]),
(Method::DELETE, "/api/v1/licenses/review", &[OrgRole::Legal]),
];
/// Whether `ctx` holds a role [`ROLE_WRITES`] lets write `method` on `template`.
pub fn role_may_write(ctx: &TenantContext, method: &Method, template: Option<&str>) -> bool {
ROLE_WRITES
.iter()
.any(|(m, t, roles)| m == method && Some(*t) == template && ctx.has_any_role(roles))
}
/// Whether a request with `method` to the route `template` changes anything.
/// A request that matched no route counts by its method alone.
pub fn is_write(method: &Method, template: Option<&str>) -> bool {
@@ -62,6 +153,7 @@ pub fn refusal(
match ctx.product_access() {
ProductAccess::Full => None,
ProductAccess::ReadOnly if !is_write(method, template) => None,
ProductAccess::ReadOnly if role_may_write(ctx, method, template) => None,
denied => Some(denied),
}
}
@@ -76,6 +168,24 @@ pub async fn require_org_role(request: Request, next: Next) -> Response {
.extensions()
.get::<MatchedPath>()
.map(MatchedPath::as_str);
if let Some(key) = ctx.api_key.as_ref() {
let Some(required) = key_refusal(key, request.method(), template) else {
return next.run(request).await;
};
tracing::info!(
tenant_id = %ctx.tenant_id,
key_id = %key.key_id,
method = %request.method(),
route = template.unwrap_or("-"),
required = required.unwrap_or("-"),
"request refused: API key scope"
);
return (
StatusCode::FORBIDDEN,
Json(serde_json::json!({ "error": SCOPE_MISSING, "required": required })),
)
.into_response();
}
let Some(access) = refusal(ctx, request.method(), template) else {
return next.run(request).await;
};
@@ -4,7 +4,7 @@
//! these tests, so a request the gate lets through fails later (500, missing
//! extension); what is checked is only whether the gate refused it.
use super::{require_org_role, READ_ONLY_POSTS};
use super::{require_org_role, KEY_SCOPES, LEGACY_SCOPES, READ_ONLY_POSTS, ROLE_WRITES};
use crate::api::routes::build_router;
use axum::{
body::{to_bytes, Body},
@@ -13,7 +13,7 @@ use axum::{
middleware::{from_fn, Next},
Router,
};
use compliance_core::{OrgRole, StaffAccess, TenantContext, TenantStatus};
use compliance_core::{ApiKeyAccess, OrgRole, StaffAccess, TenantContext, TenantStatus};
use tower::ServiceExt;
/// Who is calling.
@@ -29,6 +29,8 @@ enum Caller {
Staff,
/// A service / machine client: no tenant context reaches the gate.
Service,
/// A portal-issued API key with these scopes (no org roles).
Key(&'static [&'static str]),
}
fn ctx(caller: Caller) -> Option<TenantContext> {
@@ -38,7 +40,7 @@ fn ctx(caller: Caller) -> Option<TenantContext> {
Caller::Cxo => vec![OrgRole::Cxo],
Caller::Legal => vec![OrgRole::Legal],
Caller::Finance => vec![OrgRole::Finance],
Caller::NoRoles | Caller::Staff => vec![],
Caller::NoRoles | Caller::Staff | Caller::Key(_) => vec![],
Caller::Service => return None,
};
Some(TenantContext {
@@ -54,6 +56,17 @@ fn ctx(caller: Caller) -> Option<TenantContext> {
user_id: "u-1".to_string(),
user_name: None,
}),
api_key: match caller {
Caller::Key(scopes) => Some(Box::new(ApiKeyAccess {
key_id: "k-1".to_string(),
kind: "service".to_string(),
holder: None,
scopes: scopes.iter().map(|s| (*s).to_string()).collect(),
legacy: false,
on_behalf_of: None,
})),
_ => None,
},
})
}
@@ -76,6 +89,11 @@ fn router(caller: Caller) -> Router {
/// Whether the gate refused the request (403 `forbidden_role`).
async fn refused(caller: Caller, method: Method, path: &str) -> bool {
refusal(caller, method, path).await.as_deref() == Some("forbidden_role")
}
/// The gate's `error`, if it refused the request.
async fn refusal(caller: Caller, method: Method, path: &str) -> Option<String> {
let req = Request::builder()
.method(method)
.uri(path)
@@ -84,11 +102,11 @@ async fn refused(caller: Caller, method: Method, path: &str) -> bool {
.expect("request");
let resp = router(caller).oneshot(req).await.expect("oneshot");
if resp.status() != StatusCode::FORBIDDEN {
return false;
return None;
}
let body = to_bytes(resp.into_body(), 64 * 1024).await.expect("body");
let json: serde_json::Value = serde_json::from_slice(&body).unwrap_or_default();
json["error"] == "forbidden_role"
json["error"].as_str().map(str::to_owned)
}
const ID: &str = "65f000000000000000000001";
@@ -125,6 +143,16 @@ fn routes() -> Vec<(Method, String, bool)> {
false,
),
(Method::GET, "/api/v1/sbom/export".into(), false),
(Method::GET, "/api/v1/licenses/conclusions".into(), false),
(Method::PUT, "/api/v1/licenses/conclusions".into(), true),
(
Method::DELETE,
"/api/v1/licenses/conclusions?id=pkg%3Anpm%2Fa%40*".into(),
true,
),
(Method::GET, "/api/v1/licenses/policy".into(), false),
(Method::GET, "/api/v1/licenses/check".into(), false),
(Method::GET, "/api/v1/sbom/notices".into(), false),
(Method::POST, "/api/v1/mcp-tokens".into(), true),
(Method::DELETE, format!("/api/v1/mcp-tokens/{ID}"), true),
(Method::POST, "/api/v1/notifications/read-all".into(), true),
@@ -166,6 +194,54 @@ async fn roles_decide_reads_and_writes() {
}
}
#[tokio::test]
async fn legal_decides_about_licences_and_changes_nothing_else() {
let decisions = [
(Method::PUT, "/api/v1/licenses/policy".to_string()),
(Method::POST, "/api/v1/licenses/review".to_string()),
(
Method::DELETE,
"/api/v1/licenses/review?id=pkg%3Anpm%2Fa%40*".to_string(),
),
];
for (method, path) in &decisions {
assert!(
!refused(Caller::Legal, method.clone(), path).await,
"LEGAL {method} {path}"
);
assert!(
refused(Caller::Cxo, method.clone(), path).await,
"CXO {method} {path}"
);
assert!(
refused(Caller::Finance, method.clone(), path).await,
"FINANCE {method} {path}"
);
}
// Confirming a licence stays a write LEGAL may not make.
assert!(refused(Caller::Legal, Method::PUT, "/api/v1/licenses/conclusions").await);
// Every exception names a real route.
for (method, template, _) in ROLE_WRITES {
let resp = router(Caller::ItAdmin)
.oneshot(
Request::builder()
.method(method.clone())
.uri(*template)
.header("content-type", "application/json")
.body(Body::from("{}"))
.expect("request"),
)
.await
.expect("oneshot");
assert_ne!(resp.status(), StatusCode::NOT_FOUND, "{method} {template}");
assert_ne!(
resp.status(),
StatusCode::METHOD_NOT_ALLOWED,
"{method} {template}"
);
}
}
#[tokio::test]
async fn every_read_only_post_is_a_real_route() {
// A template that no longer matches a route would silently turn back
@@ -211,3 +287,133 @@ async fn a_refusal_says_which_access_the_role_has() {
serde_json::json!({ "error": "forbidden_role", "access": "none" })
);
}
/// Every scope of the key table.
const ALL_SCOPES: &[&str] = &[
"pruefwerk:findings.write",
"pruefwerk:sbom.read",
"pruefwerk:scans.read",
"pruefwerk:scans.run",
"pruefwerk:enisa.read",
];
fn concrete(template: &str) -> String {
template.replace("{id}", ID)
}
#[tokio::test]
async fn every_key_route_is_real_and_needs_its_scope() {
for (method, template, scope) in KEY_SCOPES {
let path = concrete(template);
// A template that matches no route would refuse every key.
assert_eq!(
refusal(Caller::Key(ALL_SCOPES), method.clone(), &path).await,
None,
"{method} {template}"
);
let lacking_sets: [&'static [&'static str]; 2] = [&[], &["werkbank:runner"]];
for lacking in lacking_sets {
assert_eq!(
refusal(Caller::Key(lacking), method.clone(), &path)
.await
.as_deref(),
Some("scope_missing"),
"{method} {template} {lacking:?}"
);
}
// Another row's scope does not open this one.
let other = KEY_SCOPES
.iter()
.map(|(_, _, s)| *s)
.find(|s| s.split('.').next() != scope.split('.').next())
.expect("the table has several scope families");
let other = ALL_SCOPES
.iter()
.find(|s| s.split('.').next() == other.split('.').next())
.expect("every family is in ALL_SCOPES");
assert_eq!(
refusal(
Caller::Key(std::slice::from_ref(other)),
method.clone(),
&path
)
.await
.as_deref(),
Some("scope_missing"),
"{method} {template} {other}"
);
}
}
#[tokio::test]
async fn a_write_scope_grants_the_read_but_not_the_reverse() {
let path = format!("/api/v1/findings/{ID}");
let write = Caller::Key(&["pruefwerk:findings.write"]);
let read = Caller::Key(&["pruefwerk:findings.read"]);
assert_eq!(refusal(write, Method::GET, &path).await, None);
assert_eq!(refusal(read, Method::GET, &path).await, None);
assert_eq!(
refusal(read, Method::PATCH, &format!("{path}/status"))
.await
.as_deref(),
Some("scope_missing")
);
// `scans.run` is not a write of `scans.read`.
assert_eq!(
refusal(
Caller::Key(&["pruefwerk:scans.run"]),
Method::GET,
"/api/v1/scan-runs"
)
.await
.as_deref(),
Some("scope_missing")
);
}
#[tokio::test]
async fn a_key_reaches_nothing_outside_the_table() {
let in_table = |m: &Method, p: &str| {
KEY_SCOPES
.iter()
.any(|(km, t, _)| km == m && concrete(t) == p)
};
for (method, path, _) in routes() {
if in_table(&method, &path) {
continue;
}
assert_eq!(
refusal(Caller::Key(ALL_SCOPES), method.clone(), &path)
.await
.as_deref(),
Some("scope_missing"),
"{method} {path}"
);
}
// A listed route with another method is not listed.
assert_eq!(
refusal(
Caller::Key(ALL_SCOPES),
Method::DELETE,
&format!("/api/v1/findings/{ID}")
)
.await
.as_deref(),
Some("scope_missing")
);
}
#[tokio::test]
async fn a_legacy_key_reads_but_never_writes_or_runs() {
let legacy = Caller::Key(LEGACY_SCOPES);
for (method, template, scope) in KEY_SCOPES {
let read = scope.ends_with(".read");
assert_eq!(
refusal(legacy, method.clone(), &concrete(template))
.await
.is_none(),
read,
"{method} {template}"
);
}
}
+19
View File
@@ -145,6 +145,25 @@ pub fn build_router() -> Router {
.route("/api/v1/sbom/licenses", get(handlers::license_summary))
.route("/api/v1/sbom/quality", get(handlers::sbom_quality))
.route("/api/v1/sbom/diff", get(handlers::sbom_diff))
// Licences the workspace confirms for its components.
.route(
"/api/v1/licenses/conclusions",
get(handlers::licenses::list_conclusions)
.put(handlers::licenses::conclude)
.delete(handlers::licenses::withdraw),
)
// The licence policy, what it says about each component, and the
// legal review that resolves what it asks a review for.
.route(
"/api/v1/licenses/policy",
get(handlers::licenses::get_policy).put(handlers::licenses::put_policy),
)
.route("/api/v1/licenses/check", get(handlers::licenses::check))
.route(
"/api/v1/licenses/review",
post(handlers::licenses::review).delete(handlers::licenses::withdraw_review),
)
.route("/api/v1/sbom/notices", get(handlers::licenses::notices))
.route("/api/v1/issues", get(handlers::list_issues))
.route("/api/v1/scan-runs", get(handlers::list_scan_runs))
// MCP token management (per-tenant API tokens for the MCP server)
+83 -17
View File
@@ -53,6 +53,7 @@ pub async fn inject_dev_tenant(mut request: Request, next: Next) -> Response {
user_id: "dev-user".to_string(),
user_name: None,
staff: None,
api_key: None,
};
request.extensions_mut().insert(ctx);
}
@@ -114,6 +115,11 @@ pub async fn require_entitlement(
let Some(ctx) = request.extensions().get::<TenantContext>().cloned() else {
return next.run(request).await;
};
// An API key: the registry's verify answer already intersected its
// scopes with the tenant's entitlements and carried the ladder status.
if ctx.api_key.is_some() {
return next.run(request).await;
}
// A person's token (support took its own branch above; service tokens
// carry no tenant context here): the registry also says whether this
// member is blocked in the tenant.
@@ -182,11 +188,11 @@ fn confirmed_support_context(
ctx
}
/// Record every change BreakPilot support makes in a tenant, refused ones
/// included, in the platform's audit log. Reads are not logged one by one;
/// opening a tenant is (`POST /api/v1/support/session`). Background and
/// best-effort: an unreachable registry never blocks support.
pub async fn audit_support_writes(
/// Record every change BreakPilot support or an API key makes in a tenant,
/// refused ones included, in the platform's audit log. Reads are not logged
/// one by one; opening a tenant is (`POST /api/v1/support/session`).
/// Background and best-effort: an unreachable registry never blocks either.
pub async fn audit_delegated_writes(
State(agent): State<Arc<ComplianceAgent>>,
request: Request,
next: Next,
@@ -194,10 +200,16 @@ pub async fn audit_support_writes(
let staff_ctx = request
.extensions()
.get::<TenantContext>()
.filter(|c| c.staff.is_some())
.filter(|c| c.staff.is_some() || c.api_key.is_some())
.cloned();
let method = request.method().clone();
let path = request.uri().path().to_string();
// Only the API host's proxy sets this header, and it overwrites whatever
// the caller sent; support requests arrive through the dashboard.
let client_ip = staff_ctx
.as_ref()
.filter(|c| c.api_key.is_some())
.and_then(|_| client_ip(request.headers()));
let response = next.run(request).await;
let (Some(ctx), Some(registry)) = (staff_ctx, agent.registry.clone()) else {
return response;
@@ -205,26 +217,50 @@ pub async fn audit_support_writes(
if matches!(method, Method::GET | Method::HEAD | Method::OPTIONS) {
return response;
}
let entry = support_audit_entry(&ctx, method.as_str(), &path, response.status().as_u16());
let mut entry = delegated_audit_entry(&ctx, method.as_str(), &path, response.status().as_u16());
entry.source_ip = client_ip.map(|ip| ip.to_string()).unwrap_or_default();
tokio::spawn(async move {
if let Err(e) = registry.append_audit(&entry).await {
tracing::warn!(tenant_id = %entry.tenant_id, "support audit not recorded: {e}");
tracing::warn!(tenant_id = %entry.tenant_id, "write audit not recorded: {e}");
}
});
response
}
/// The audit entry for a support request. The path names the resource; the
/// query and body are left out, as they may carry customer data.
fn support_audit_entry(
/// The header the API host's proxy puts the caller's address in
/// (orca-platform `pruefwerk-*/api-proxy.conf`).
const CLIENT_IP_HEADER: &str = "x-bp-client-ip";
/// The caller's address from [`CLIENT_IP_HEADER`], or `None` when it is
/// missing or not an IP address (the registry stores it as Postgres `inet`,
/// which would refuse the whole entry).
fn client_ip(headers: &axum::http::HeaderMap) -> Option<std::net::IpAddr> {
headers
.get(CLIENT_IP_HEADER)?
.to_str()
.ok()?
.trim()
.parse()
.ok()
}
/// The audit entry for a support or API-key request. The path names the
/// resource; the query and body are left out, as they may carry customer
/// data.
fn delegated_audit_entry(
ctx: &TenantContext,
method: &str,
path: &str,
status: u16,
) -> crate::registry::AuditEntry {
let action = if ctx.api_key.is_some() {
"pruefwerk.api_key_write"
} else {
"pruefwerk.support_access"
};
crate::registry::AuditEntry::by(
ctx,
"pruefwerk.support_access",
action,
serde_json::json!({ "method": method, "path": path, "status": status }),
)
}
@@ -408,7 +444,11 @@ pub async fn start_api_server(
&agent.config.cors_allowed_origins,
agent.config.app_env,
))
.layer(TraceLayer::new_for_http())
.layer(
TraceLayer::new_for_http()
.make_span_with(crate::api::trace::make_span)
.on_response(crate::api::trace::on_response),
)
// Security headers (defense-in-depth, primary enforcement via Traefik)
.layer(SetResponseHeaderLayer::overriding(
axum::http::header::STRICT_TRANSPORT_SECURITY,
@@ -433,13 +473,14 @@ pub async fn start_api_server(
registry = agent.registry.is_some(),
"Keycloak JWT auth enabled"
);
// Layers execute outermost-first: Extension(jwks) → JWT → org roles
// → entitlement (registry) → support audit → status ladder → handlers.
// Layers execute outermost-first: Extension(jwks) → API key → JWT →
// org roles / key scopes → entitlement (registry) → support and key
// audit → status ladder → handlers.
app = app
.layer(middleware::from_fn(require_tenant_status))
.layer(middleware::from_fn_with_state(
shared.clone(),
audit_support_writes,
audit_delegated_writes,
))
.layer(middleware::from_fn_with_state(
shared.clone(),
@@ -447,6 +488,10 @@ pub async fn start_api_server(
))
.layer(middleware::from_fn(role_gate::require_org_role))
.layer(middleware::from_fn(require_jwt_auth))
.layer(middleware::from_fn_with_state(
shared.clone(),
super::api_key_gate::require_api_key,
))
.layer(Extension(jwks_state));
} else if agent.config.app_env.is_hardened() {
// `validate_deployment` rejects this configuration at load time; this
@@ -502,6 +547,7 @@ mod support_tests {
user_id: "s-1".to_string(),
user_name: Some("Sharang".to_string()),
}),
api_key: None,
}
}
@@ -527,10 +573,30 @@ mod support_tests {
assert_eq!(ctx.status, TenantStatus::Restricted);
}
#[test]
fn the_client_ip_is_taken_only_when_it_is_an_address() {
let headers = |value: &str| {
let mut map = axum::http::HeaderMap::new();
map.insert(CLIENT_IP_HEADER, HeaderValue::from_str(value).unwrap());
map
};
assert_eq!(
client_ip(&headers(" 203.0.113.7 ")).map(|ip| ip.to_string()),
Some("203.0.113.7".to_string())
);
assert_eq!(
client_ip(&headers("2001:db8::1")).map(|ip| ip.to_string()),
Some("2001:db8::1".to_string())
);
assert_eq!(client_ip(&headers("203.0.113.7, 10.0.0.1")), None);
assert_eq!(client_ip(&headers("evil")), None);
assert_eq!(client_ip(&axum::http::HeaderMap::new()), None);
}
#[test]
fn a_support_change_is_audited_without_its_content() {
let entry =
support_audit_entry(&support_ctx(), "PATCH", "/api/v1/findings/abc/status", 200);
delegated_audit_entry(&support_ctx(), "PATCH", "/api/v1/findings/abc/status", 200);
assert_eq!(entry.tenant_id, "00000000-0000-0000-0000-000000000002");
assert_eq!(entry.action, "pruefwerk.support_access");
assert_eq!(entry.actor_id, "s-1");
+146
View File
@@ -0,0 +1,146 @@
//! One server span per HTTP request, for `TraceLayer` (instrumentation plan,
//! research/observability/2026-10-28-instrumentation-portal-registry-db.md).
//!
//! The default `TraceLayer` span is DEBUG (so the INFO filter drops it) and
//! records the full URI. This one is INFO, named after the route template
//! (`GET /api/v1/targets/{id}`), continues an incoming `traceparent` (portal,
//! registry) and records no path, query or client address.
use std::time::Duration;
use axum::extract::{MatchedPath, Request};
use axum::response::Response;
use tracing::Span;
/// The health route is polled every few seconds and gets no span.
const UNTRACED: &[&str] = &["/api/v1/health"];
pub fn make_span(req: &Request) -> Span {
let route = req
.extensions()
.get::<MatchedPath>()
.map(MatchedPath::as_str);
if route.is_some_and(|r| UNTRACED.contains(&r)) {
return Span::none();
}
let method = req.method().as_str();
let span = tracing::info_span!(
"http",
otel.name = %format!("{method} {}", route.unwrap_or("unmatched")),
otel.kind = "server",
otel.status_code = tracing::field::Empty,
http.request.method = %method,
http.route = route.unwrap_or(""),
http.response.status_code = tracing::field::Empty,
);
let header = |name: &str| req.headers().get(name).and_then(|v| v.to_str().ok());
compliance_core::telemetry::continue_trace(&span, header("traceparent"), header("tracestate"));
span
}
pub fn on_response(res: &Response, _latency: Duration, span: &Span) {
span.record("http.response.status_code", res.status().as_u16());
if res.status().is_server_error() {
span.record("otel.status_code", "ERROR");
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use axum::body::Body;
use axum::routing::get;
use axum::Router;
use std::sync::{Arc, Mutex};
use tower::ServiceExt as _;
use tower_http::trace::TraceLayer;
use tracing::field::{Field, Visit};
use tracing::span::{Attributes, Id, Record};
use tracing_subscriber::layer::{Context, SubscriberExt as _};
use tracing_subscriber::Layer;
/// Every field recorded on any span, as "name=value".
#[derive(Clone, Default)]
struct Fields(Arc<Mutex<Vec<String>>>);
struct Collect<'a>(&'a Mutex<Vec<String>>);
impl Visit for Collect<'_> {
fn record_debug(&mut self, f: &Field, v: &dyn std::fmt::Debug) {
self.0.lock().unwrap().push(format!("{}={v:?}", f.name()));
}
fn record_str(&mut self, f: &Field, v: &str) {
self.0.lock().unwrap().push(format!("{}={v}", f.name()));
}
}
impl<S: tracing::Subscriber> Layer<S> for Fields {
fn on_new_span(&self, a: &Attributes<'_>, _: &Id, _: Context<'_, S>) {
a.record(&mut Collect(&self.0));
}
fn on_record(&self, _: &Id, r: &Record<'_>, _: Context<'_, S>) {
r.record(&mut Collect(&self.0));
}
}
async fn call(path: &str, status: u16) -> Vec<String> {
let fields = Fields::default();
let sub = tracing_subscriber::registry().with(fields.clone());
let _guard = tracing::subscriber::set_default(sub);
let app = Router::new()
.route("/api/v1/health", get(|| async { "ok" }))
.route(
"/api/v1/targets/{id}",
get(move || async move { axum::http::StatusCode::from_u16(status).unwrap() }),
)
.layer(
TraceLayer::new_for_http()
.make_span_with(make_span)
.on_response(on_response),
);
let req = Request::builder().uri(path).body(Body::empty()).unwrap();
app.oneshot(req).await.unwrap();
let out = fields.0.lock().unwrap().clone();
out
}
#[tokio::test]
async fn names_the_span_after_the_route_and_keeps_the_path_out() {
let f = call("/api/v1/targets/acme-firmware?token=x", 200).await;
assert!(
f.contains(&"otel.name=GET /api/v1/targets/{id}".to_string()),
"{f:?}"
);
assert!(
f.contains(&"http.route=/api/v1/targets/{id}".to_string()),
"{f:?}"
);
assert!(
f.contains(&"http.response.status_code=200".to_string()),
"{f:?}"
);
assert!(
f.iter()
.all(|x| !x.contains("acme") && !x.contains("token")),
"{f:?}"
);
assert!(
!f.iter().any(|x| x.starts_with("otel.status_code")),
"{f:?}"
);
}
#[tokio::test]
async fn a_server_error_marks_the_span() {
let f = call("/api/v1/targets/1", 503).await;
assert!(f.contains(&"otel.status_code=ERROR".to_string()), "{f:?}");
}
#[tokio::test]
async fn health_and_unmatched() {
assert!(
call("/api/v1/health", 200).await.is_empty(),
"health gets no span"
);
let f = call("/nope/acme", 200).await;
assert!(f.contains(&"otel.name=GET unmatched".to_string()), "{f:?}");
}
}
@@ -390,6 +390,13 @@ impl HeuristicClassifier {
ArtifactKind::SourceArchive if lower.ends_with(".projectarchive") => out.push(
verdict(TargetType::PlcSps, 0.85, "CODESYS project archive", vec![]),
),
// A Yocto image's SPDX archive is Yocto by itself.
ArtifactKind::BuildOutput if lower.ends_with(".spdx.tar.zst") => out.push(verdict(
TargetType::EmbeddedLinuxYocto,
0.7,
"Yocto image SPDX archive",
vec![],
)),
ArtifactKind::LiveUrl if input.artifacts.len() == 1 => {
out.push(verdict(TargetType::WebApp, 0.3, "live URL only", vec![]))
}
+8 -3
View File
@@ -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"),
+34
View File
@@ -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 {
@@ -334,6 +348,15 @@ impl Database {
)
.await?;
// license_conclusions: looked up by package (the _id is package + version)
self.license_conclusions()
.create_index(
IndexModel::builder()
.keys(doc! { "package_key": 1 })
.build(),
)
.await?;
// cve_alerts: unique cve_id + repo_id
self.cve_alerts()
.create_index(
@@ -646,6 +669,17 @@ impl Database {
self.inner.collection("sbom_entries")
}
/// Licences the workspace confirmed for its packages; merged into the
/// components when they are read (see [`crate::license_conclusions`]).
pub fn license_conclusions(&self) -> Collection<LicenseConclusion> {
self.inner.collection("license_conclusions")
}
/// The workspace's licence policy: one document, [`compliance_core::models::license_policy::POLICY_ID`].
pub fn license_policy(&self) -> Collection<compliance_core::models::LicensePolicy> {
self.inner.collection("license_policy")
}
pub fn cve_alerts(&self) -> Collection<CveAlert> {
self.inner.collection("cve_alerts")
}
+54 -1
View File
@@ -37,6 +37,8 @@ pub struct EvidenceInputs {
pub catalog: std::collections::HashMap<String, compliance_core::traits::Control>,
/// Who states the VEX (the workspace); the target's name when empty.
pub author: String,
/// The workspace's licence policy, judged on the SBOM in `license-check.json`.
pub license_policy: compliance_core::models::LicensePolicy,
}
/// One file of the pack, as `manifest.json` lists it.
@@ -62,6 +64,36 @@ struct Manifest {
files: Vec<ManifestFile>,
}
/// What the licence policy says about each component of the pack's SBOM.
fn license_check(inputs: &EvidenceInputs, at: DateTime<Utc>) -> serde_json::Value {
use compliance_core::models::license_policy::{evaluate, VerdictCounts};
let today = at.date_naive();
let mut counts = VerdictCounts::default();
let components: Vec<serde_json::Value> = inputs
.sbom
.iter()
.map(|e| {
let verdict = evaluate(e, &inputs.license_policy, today);
counts.add(&verdict);
serde_json::json!({
"name": e.name,
"version": e.version,
"package_manager": e.package_manager,
"purl": e.purl,
"license": e.effective_license(),
"review": e.concluded.as_ref().and_then(|c| c.review.clone()),
"verdict": verdict,
})
})
.collect();
serde_json::json!({
"date": today,
"policy": inputs.license_policy,
"counts": counts,
"components": components,
})
}
/// The pack as a ZIP, and the manifest's file list.
///
/// # Errors
@@ -133,6 +165,21 @@ pub fn build_pack(
if !enisa.is_empty() {
files.push(("enisa-drafts.json", json(&enisa)?));
}
// The third-party notices and what the licence policy says about each
// component, as on the day the pack is made.
files.push((
"THIRD-PARTY-NOTICES.txt",
compliance_core::license_notices::render(
&inputs.sbom,
&compliance_core::license_notices::NoticeOptions {
product: subject,
format: compliance_core::license_notices::NoticeFormat::Text,
include_build_only: false,
},
)
.into_bytes(),
));
files.push(("license-check.json", json(&license_check(inputs, at))?));
// The SBOM's quality score of the last scan (sbomqs, #496), when it was
// scored.
if let Some(quality) = sbom_quality(inputs) {
@@ -378,6 +425,7 @@ mod tests {
last_run: None,
catalog: Default::default(),
author: String::new(),
license_policy: Default::default(),
}
}
@@ -483,16 +531,21 @@ 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,
[
"THIRD-PARTY-NOTICES.txt",
"cra-compliance.json",
"csaf-vex.json",
"cve-alerts.json",
"findings.csv",
"findings.json",
"license-check.json",
"manifest.json",
"oscal-assessment-results.json",
"sbom.cdx.json",
+4 -1
View File
@@ -189,7 +189,10 @@ pub fn ingest_artifact(
ArtifactKind::SourceArchive | ArtifactKind::MobilePackage | ArtifactKind::PlcProject => {
ingest_blob(artifact, ctx, true)
}
ArtifactKind::FirmwareImage => ingest_blob(artifact, ctx, false),
// Stored as uploaded: the SPDX reader opens the archive itself.
ArtifactKind::FirmwareImage | ArtifactKind::BuildOutput => {
ingest_blob(artifact, ctx, false)
}
ArtifactKind::ContainerImage => Ok(metadata_only(
artifact,
DetectedFact::new("container_ref", artifact.source_ref.as_str(), "ingest"),
+1
View File
@@ -14,6 +14,7 @@ pub mod fixtures;
pub mod git_source;
pub mod import;
pub mod ingest;
pub mod license_conclusions;
pub mod lifecycle;
pub mod llm;
pub mod pentest;
@@ -0,0 +1,72 @@
//! The licences a workspace confirmed, merged into its
//! components wherever they are read: the SBOM list and licence summary, the
//! SBOM exports, the evidence pack and the SBOM quality score. A scan
//! rewrites the components, so the conclusions live in their own collection.
use compliance_core::models::license::{self, LicenseConclusion};
use compliance_core::models::license_policy::{self, LicensePolicy};
use compliance_core::models::SbomEntry;
use futures_util::TryStreamExt;
use mongodb::bson::doc;
use crate::database::Database;
/// The most conclusions one workspace keeps. Each is a person's decision,
/// so a workspace reaching this is far beyond normal use.
pub const MAX_CONCLUSIONS: i64 = 50_000;
/// Every conclusion of the workspace, by package name. Empty when they
/// cannot be read: the components then show what the scan found.
pub async fn load(db: &Database) -> Vec<LicenseConclusion> {
let found = db
.license_conclusions()
.find(doc! {})
.sort(doc! { "name": 1, "_id": 1 })
.limit(MAX_CONCLUSIONS)
.await;
match found {
Ok(cursor) => cursor.try_collect().await.unwrap_or_else(|e| {
tracing::warn!("license conclusions not read: {e}");
Vec::new()
}),
Err(e) => {
tracing::warn!("license conclusions not read: {e}");
Vec::new()
}
}
}
/// Attach to `entries` the conclusions that apply to them.
pub async fn attach(db: &Database, entries: &mut [SbomEntry]) {
if entries.is_empty() {
return;
}
let conclusions = load(db).await;
license::apply(entries, &conclusions);
}
/// The workspace's licence policy; the default one when it has none or it
/// cannot be read.
pub async fn load_policy(db: &Database) -> LicensePolicy {
match db
.license_policy()
.find_one(doc! { "_id": license_policy::POLICY_ID })
.await
{
Ok(Some(policy)) => policy,
Ok(None) => LicensePolicy::default(),
Err(e) => {
tracing::warn!("license policy not read, the default applies: {e}");
LicensePolicy::default()
}
}
}
/// Attach to `entries` (their conclusions attached) what `policy` says
/// about each of them today.
pub fn judge(entries: &mut [SbomEntry], policy: &LicensePolicy) {
let today = chrono::Utc::now().date_naive();
for entry in entries.iter_mut() {
entry.policy = Some(license_policy::evaluate(entry, policy, today));
}
}
+39 -6
View File
@@ -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();
+91 -3
View File
@@ -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}");
}
}
+58 -12
View File
@@ -65,6 +65,8 @@ 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;
@@ -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
///
@@ -1491,6 +1497,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 +1636,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 +1688,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);
}
@@ -22,15 +22,24 @@ use crate::pipeline::dotnet::config::{into_finding, Hit};
/// The scanner name of these findings.
pub const SCANNER: &str = "build-lifecycle";
/// Below this Android API level (Android 10) no Android release receives
/// security updates any more.
const OLDEST_PATCHED_ANDROID_API: u32 = 29;
/// The oldest Android release that still receives security updates, from
/// the bundled table (`data/eol/platforms.json`): its API level, below which
/// no release is patched, and its name.
fn android_floor() -> Option<(u32, &'static str)> {
crate::pipeline::eol_tables::platforms().map(|p| {
(
p.android.oldest_patched_api,
p.android.oldest_patched_release.as_str(),
)
})
}
/// The oldest iOS release that still receives security updates: iOS 15 got
/// 15.8.8 in May 2026, while iOS 14 was last updated in October 2021 and the
/// older iOS 12 line in January 2026, both now end of life (endoflife.date).
/// Judged conservatively like Unity: below it is certainly unpatched.
const OLDEST_PATCHED_IOS: (u32, u32) = (15, 0);
/// The oldest iOS release that still receives security updates, from the
/// bundled table (`data/eol/platforms.json`); judged conservatively: below
/// it is certainly unpatched.
fn ios_floor() -> Option<(u32, u32)> {
crate::pipeline::eol_tables::platforms().and_then(|p| version_pair(&p.ios.oldest_patched))
}
/// The oldest Swift language version a supported Xcode builds: Xcode 10.2
/// dropped Swift 3 mode, and current Swift compilers accept 4, 4.2, 5 and 6.
@@ -174,27 +183,29 @@ fn check_adt_project(root: &Path, dir: &Path) -> Vec<Hit> {
path: path.clone(),
line: Some(line),
}];
if let Some(api) = target.and_then(|(_, l)| android_api(l)) {
if api < OLDEST_PATCHED_ANDROID_API {
hits.push(Hit {
scanner: SCANNER,
scan_type: ScanType::Sbom,
rule_id: "android-sdk-end-of-support",
title: format!("Android API {api} receives no security updates"),
description: format!(
"{} builds against Android API {api}. Android releases below API \
{OLDEST_PATCHED_ANDROID_API} (Android 10) receive no security updates, \
so the platform the app is built for stays vulnerable.",
relative(root, dir)
),
remediation: "Raise the target and minimum API level to a supported Android \
release (after migrating the build to Gradle) and test on it.",
severity: Severity::High,
cwe: "CWE-1104",
path,
line: Some(line),
});
}
let below_floor = target
.and_then(|(_, l)| android_api(l))
.zip(android_floor())
.filter(|(api, (floor, _))| api < floor);
if let Some((api, (floor, floor_name))) = below_floor {
hits.push(Hit {
scanner: SCANNER,
scan_type: ScanType::Sbom,
rule_id: "android-sdk-end-of-support",
title: format!("Android API {api} receives no security updates"),
description: format!(
"{} builds against Android API {api}. Android releases below API \
{floor} ({floor_name}) receive no security updates, so the platform the \
app is built for stays vulnerable.",
relative(root, dir)
),
remediation: "Raise the target and minimum API level to a supported Android \
release (after migrating the build to Gradle) and test on it.",
severity: Severity::High,
cwe: "CWE-1104",
path,
line: Some(line),
});
}
hits
}
@@ -289,8 +300,9 @@ fn ios_deployment_target(
path: String,
line: u32,
) -> Option<Hit> {
let (oldest, _) = OLDEST_PATCHED_IOS;
((major, minor) < OLDEST_PATCHED_IOS).then(|| Hit {
let floor = ios_floor()?;
let (oldest, _) = floor;
((major, minor) < floor).then(|| Hit {
scanner: SCANNER,
scan_type: ScanType::Sbom,
rule_id: "ios-deployment-target-end-of-support",
@@ -337,8 +349,13 @@ fn unity_platform_hits(root: &Path, project: &Path) -> Vec<Hit> {
}
let android_min = platforms.android.and_then(|p| p.min_os);
if let Some(setting) = android_min {
let api = setting.value.parse::<u32>().ok();
if let Some(api) = api.filter(|api| *api < OLDEST_PATCHED_ANDROID_API) {
let below_floor = setting
.value
.parse::<u32>()
.ok()
.zip(android_floor())
.filter(|(api, (floor, _))| api < floor);
if let Some((api, (floor, floor_name))) = below_floor {
hits.push(Hit {
scanner: SCANNER,
scan_type: ScanType::Sbom,
@@ -349,7 +366,7 @@ fn unity_platform_hits(root: &Path, project: &Path) -> Vec<Hit> {
description: format!(
"{label} sets its minimum Android API level to {api}: the app installs and \
runs on devices still on that release. Android releases below API \
{OLDEST_PATCHED_ANDROID_API} (Android 10) receive no security updates, so \
{floor} ({floor_name}) receive no security updates, so \
those devices stay vulnerable whatever the app does. The app also runs on \
current Android releases."
),
+7 -44
View File
@@ -295,52 +295,15 @@ pub fn runtime_of(moniker: &str) -> Option<Runtime> {
})
}
/// Microsoft's end of support for each target framework that has one, as an
/// ISO date and the name customers know it by. Versions not listed are
/// supported (.NET Framework 4.8 and 4.8.1 follow the Windows they ship with).
///
/// Sources: the .NET Framework and .NET lifecycle pages on
/// learn.microsoft.com (.NET Framework 4.5.2, 4.6 and 4.6.1 ended
/// 2022-04-26, 4.6.2 ends 2027-01-12; .NET 8 and .NET 9 end 2026-11-10).
const END_OF_SUPPORT: &[(&str, &str, &str)] = &[
("net11", "2011-07-12", ".NET Framework 1.1"),
("net20", "2011-07-12", ".NET Framework 2.0"),
("net30", "2011-07-12", ".NET Framework 3.0"),
("net35", "2029-01-09", ".NET Framework 3.5 SP1"),
("net40", "2016-01-12", ".NET Framework 4.0"),
("net403", "2016-01-12", ".NET Framework 4.0.3"),
("net45", "2016-01-12", ".NET Framework 4.5"),
("net451", "2016-01-12", ".NET Framework 4.5.1"),
("net452", "2022-04-26", ".NET Framework 4.5.2"),
("net46", "2022-04-26", ".NET Framework 4.6"),
("net461", "2022-04-26", ".NET Framework 4.6.1"),
("net462", "2027-01-12", ".NET Framework 4.6.2"),
("netcoreapp1.0", "2019-06-27", ".NET Core 1.0"),
("netcoreapp1.1", "2019-06-27", ".NET Core 1.1"),
("netcoreapp2.0", "2018-10-01", ".NET Core 2.0"),
("netcoreapp2.1", "2021-08-21", ".NET Core 2.1"),
("netcoreapp2.2", "2019-12-23", ".NET Core 2.2"),
("netcoreapp3.0", "2020-03-03", ".NET Core 3.0"),
("netcoreapp3.1", "2022-12-13", ".NET Core 3.1"),
("net5.0", "2022-05-10", ".NET 5"),
("net6.0", "2024-11-12", ".NET 6"),
("net7.0", "2024-05-14", ".NET 7"),
("net8.0", "2026-11-10", ".NET 8"),
("net9.0", "2026-11-10", ".NET 9"),
("net10.0", "2028-11-14", ".NET 10"),
];
/// When `moniker` lost (or loses) Microsoft's support, and its product name.
/// `None` for a version without an announced end, or one not known here.
/// When `moniker` lost (or loses) Microsoft's support, and its product name,
/// from the bundled table (`data/eol/dotnet.json`). `None` for a version
/// without an announced end (.NET Framework 4.7 to 4.8.1 follow the Windows
/// they ship with), or one not known here.
pub fn end_of_support(moniker: &str) -> Option<(chrono::NaiveDate, &'static str)> {
END_OF_SUPPORT
crate::pipeline::eol_tables::dotnet_frameworks()
.iter()
.find(|(m, _, _)| *m == moniker)
.and_then(|(_, date, name)| {
chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d")
.ok()
.map(|d| (d, *name))
})
.find(|f| f.moniker == moniker)
.map(|f| (f.end_of_support, f.product.as_str()))
}
#[cfg(test)]
+131
View File
@@ -0,0 +1,131 @@
//! The end-of-life tables the lifecycle checks judge by, bundled from
//! `compliance-agent/data/eol/*.json`.
//!
//! The JSON files are the one place the tables live: the agent compiles them
//! in here, and the weekly CI check (`scripts/check-eol-tables.py`) compares
//! them with endoflife.date and files an issue when they drift.
use std::sync::LazyLock;
use chrono::NaiveDate;
use serde::Deserialize;
/// One Yocto Project release.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct YoctoReleaseInfo {
/// The codename, lower case.
pub codename: String,
/// The Yocto Project version.
pub version: String,
/// A long term support release.
pub lts: bool,
/// Its release day.
pub released: NaiveDate,
/// The day its support ends (or ended).
pub end_of_life: NaiveDate,
}
/// The Yocto release table and where it comes from.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct YoctoTable {
/// The primary source (the Yocto Project releases wiki).
pub source: String,
/// When the table was last checked against its sources (`YYYY-MM-DD`).
pub checked_on: String,
/// The releases, oldest first.
pub releases: Vec<YoctoReleaseInfo>,
}
/// Microsoft's end of support for one target framework moniker.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct DotnetFramework {
/// The moniker (`net452`, `netcoreapp3.1`, `net8.0`).
pub moniker: String,
/// The day support ends (or ended).
pub end_of_support: NaiveDate,
/// The name customers know it by.
pub product: String,
}
#[derive(Debug, Clone, Default, Deserialize)]
struct DotnetTable {
frameworks: Vec<DotnetFramework>,
}
/// The oldest Android release that still gets security updates.
#[derive(Debug, Clone, Deserialize)]
pub struct AndroidFloor {
/// Its API level: below it no release is patched.
pub oldest_patched_api: u32,
/// Its name (`Android 10`).
pub oldest_patched_release: String,
}
/// The oldest iOS release that still gets security updates.
#[derive(Debug, Clone, Deserialize)]
pub struct IosFloor {
/// `major.minor`.
pub oldest_patched: String,
}
/// The platform floors.
#[derive(Debug, Clone, Deserialize)]
pub struct Platforms {
/// Android.
pub android: AndroidFloor,
/// iOS.
pub ios: IosFloor,
}
const YOCTO_JSON: &str = include_str!("../../data/eol/yocto.json");
const DOTNET_JSON: &str = include_str!("../../data/eol/dotnet.json");
const PLATFORMS_JSON: &str = include_str!("../../data/eol/platforms.json");
/// `text` (the bundled file `name`) parsed; logged and `None` when it does
/// not parse, which the tests below rule out for the files shipped.
fn parse<T: for<'de> Deserialize<'de>>(name: &str, text: &str) -> Option<T> {
serde_json::from_str(text)
.map_err(|e| tracing::error!(file = name, "bundled end-of-life table does not parse: {e}"))
.ok()
}
static YOCTO: LazyLock<YoctoTable> =
LazyLock::new(|| parse("yocto.json", YOCTO_JSON).unwrap_or_default());
static DOTNET: LazyLock<DotnetTable> =
LazyLock::new(|| parse("dotnet.json", DOTNET_JSON).unwrap_or_default());
static PLATFORMS: LazyLock<Option<Platforms>> =
LazyLock::new(|| parse("platforms.json", PLATFORMS_JSON));
/// The Yocto release table.
pub fn yocto() -> &'static YoctoTable {
&YOCTO
}
/// The .NET target frameworks with an end of support.
pub fn dotnet_frameworks() -> &'static [DotnetFramework] {
&DOTNET.frameworks
}
/// The Android and iOS floors; `None` only if the bundled file does not
/// parse, and then no platform is judged.
pub fn platforms() -> Option<&'static Platforms> {
PLATFORMS.as_ref()
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
#[test]
fn every_bundled_table_parses() {
let yocto: YoctoTable = serde_json::from_str(YOCTO_JSON).expect("yocto.json");
assert!(!yocto.releases.is_empty());
assert!(NaiveDate::parse_from_str(&yocto.checked_on, "%Y-%m-%d").is_ok());
let dotnet: DotnetTable = serde_json::from_str(DOTNET_JSON).expect("dotnet.json");
assert!(!dotnet.frameworks.is_empty());
let platforms: Platforms = serde_json::from_str(PLATFORMS_JSON).expect("platforms.json");
assert!(platforms.android.oldest_patched_api > 0);
assert!(platforms.ios.oldest_patched.contains('.'));
}
}
+109 -6
View File
@@ -45,6 +45,13 @@ pub struct RunFindings {
variants: AppVariants,
/// The scanned tree: the flagged lines fingerprints are made of (#491).
tree: Option<PathBuf>,
/// The test-data directories left out of the scanned tree
/// ([`crate::pipeline::test_data`]): a finding stored in one is closed as
/// test data, not as fixed.
test_data: Vec<String>,
/// The paths the target's settings left out of the scanned tree: a
/// finding stored in one is closed as excluded, not as fixed.
excluded: Vec<String>,
}
/// One place a group lists: scanner, rule, file, line.
@@ -75,9 +82,25 @@ impl RunFindings {
grouped: HashSet::new(),
variants: AppVariants::default(),
tree: None,
test_data: Vec::new(),
excluded: Vec::new(),
}
}
/// Name the paths the target's settings left out of the tree, so the
/// findings an earlier scan stored there close as excluded.
pub fn with_excluded(mut self, paths: Vec<String>) -> Self {
self.excluded = paths;
self
}
/// Name the test-data directories the scan left out of the tree, so the
/// findings an earlier scan stored there close as test data.
pub fn with_test_data(mut self, dirs: Vec<String>) -> Self {
self.test_data = dirs;
self
}
/// Key the findings of this run by the content of the code they flag in
/// the tree under `tree`, not by its line number (#491).
pub fn with_tree(mut self, tree: PathBuf) -> Self {
@@ -697,7 +720,8 @@ impl RunFindings {
.await?
.try_collect()
.await?;
let (mut fixed, mut vendored, mut grouped) = (Vec::new(), Vec::new(), Vec::new());
let (mut fixed, mut vendored, mut test_data, mut excluded, mut grouped) =
(Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new());
for row in &candidates {
let (Ok(id), Ok(fingerprint)) = (row.get_object_id("_id"), row.get_str("fingerprint"))
else {
@@ -706,9 +730,13 @@ impl RunFindings {
if self.inserted.contains_key(fingerprint) || self.earlier.contains(fingerprint) {
continue;
}
let in_vendor = row
.get_str("file_path")
.is_ok_and(|file| crate::pipeline::vendor::in_vendor_dir(file, vendor));
let file = row.get_str("file_path").ok();
let in_vendor = file.is_some_and(|f| crate::pipeline::vendor::in_vendor_dir(f, vendor));
// The same membership test as for the vendor directories.
let in_test_data =
file.is_some_and(|f| crate::pipeline::vendor::in_vendor_dir(f, &self.test_data));
let in_excluded =
file.is_some_and(|f| crate::pipeline::vendor::in_vendor_dir(f, &self.excluded));
let completed = row
.get_str("scanner")
.is_ok_and(|scanner| self.completed.contains(scanner));
@@ -716,6 +744,10 @@ impl RunFindings {
grouped.push(id);
} else if !completed {
continue;
} else if in_excluded {
excluded.push(id);
} else if in_test_data {
test_data.push(id);
} else if in_vendor {
vendored.push(id);
} else {
@@ -725,18 +757,24 @@ impl RunFindings {
for (ids, kind) in [
(&fixed, ScanChangeKind::NoLongerFound),
(&vendored, ScanChangeKind::NowVendorCode),
(&test_data, ScanChangeKind::NowTestData),
(&excluded, ScanChangeKind::NowExcluded),
(&grouped, ScanChangeKind::Grouped),
] {
self.set_status(db, ids, &UNDECIDED, FindingStatus::Resolved, kind)
.await?;
}
let closed =
u32::try_from(fixed.len() + vendored.len() + grouped.len()).unwrap_or(u32::MAX);
let closed = u32::try_from(
fixed.len() + vendored.len() + test_data.len() + excluded.len() + grouped.len(),
)
.unwrap_or(u32::MAX);
if closed > 0 {
tracing::info!(
scan_run_id = %self.scan_run_id,
fixed = fixed.len(),
vendored = vendored.len(),
test_data = test_data.len(),
excluded = excluded.len(),
grouped = grouped.len(),
"resolved findings the scan no longer reports"
);
@@ -744,6 +782,71 @@ impl RunFindings {
Ok(closed)
}
/// Close the undecided findings of `scanner` on target `target_id` whose
/// file lies in the excluded paths or the test data this run left out
/// ([`Self::with_excluded`], [`Self::with_test_data`]), each with its
/// reason. For a stage that stores its findings without this object (the
/// PLC analysis), so nothing it no longer sees is closed as fixed; only
/// what was left out.
///
/// # Returns
///
/// How many findings were closed.
///
/// # Errors
///
/// A database error.
pub async fn resolve_left_out(
&mut self,
db: &Database,
target_id: &str,
scanner: &str,
) -> Result<u32, AgentError> {
if self.excluded.is_empty() && self.test_data.is_empty() {
return Ok(0);
}
let rows: Vec<Document> = db
.findings()
.clone_with_type::<Document>()
.find(doc! {
"repo_id": target_id,
"scanner": scanner,
"status": { "$in": UNDECIDED.to_vec() },
})
.projection(doc! { "file_path": 1 })
.await?
.try_collect()
.await?;
let (mut excluded, mut test_data) = (Vec::new(), Vec::new());
for row in &rows {
let (Ok(id), Ok(file)) = (row.get_object_id("_id"), row.get_str("file_path")) else {
continue;
};
if crate::pipeline::vendor::in_vendor_dir(file, &self.excluded) {
excluded.push(id);
} else if crate::pipeline::vendor::in_vendor_dir(file, &self.test_data) {
test_data.push(id);
}
}
self.set_status(
db,
&excluded,
&UNDECIDED,
FindingStatus::Resolved,
ScanChangeKind::NowExcluded,
)
.await?;
self.set_status(
db,
&test_data,
&UNDECIDED,
FindingStatus::Resolved,
ScanChangeKind::NowTestData,
)
.await?;
Ok(u32::try_from(excluded.len() + test_data.len()).unwrap_or(u32::MAX))
}
/// Move the findings `ids` whose status is still one of `from` to `to`,
/// with a history entry saying this run did it and why. The `from` guard
/// leaves alone a finding a person changed in the meantime.
+8 -1
View File
@@ -399,7 +399,14 @@ impl GitOps {
let head_name = head_ref.name().unwrap_or("HEAD");
repo.reference(head_name, fetch_commit.id(), true, "fast-forward")?;
repo.checkout_head(Some(git2::build::CheckoutBuilder::default().force()))?;
// `recreate_missing`: a scan takes the test data out of its working
// copy (`pipeline::test_data`); every fetch puts it back, so what is
// left out always follows the current rules.
repo.checkout_head(Some(
git2::build::CheckoutBuilder::default()
.force()
.recreate_missing(true),
))?;
tracing::info!("Fetched and fast-forwarded {}", repo_path.display());
Ok(())
+41 -9
View File
@@ -9,6 +9,10 @@
//! most [`MAX_NEW_ISSUES`] per scan, highest severity and oldest first. The
//! rest wait for the next scans. Gitea only: it matches against the listing
//! the scan made anyway; the other trackers would need a search per finding.
//!
//! A scheduled scan that change detection skips (no new commits) still runs
//! the catch-up when findings are [`waiting`] for an issue, so a backlog
//! does not wait for the next push.
use std::collections::{BTreeMap, HashSet};
@@ -119,26 +123,50 @@ pub(super) async fn catch_up(
Ok(run(sink, &candidates, index, mode).await)
}
/// The target's open medium+ findings without an issue, as stored.
async fn load_candidates(sink: &IssueSink<'_>) -> Result<Vec<Finding>, AgentError> {
/// The target's open medium+ findings without an issue, as a query.
fn candidate_filter(repo_id: &str) -> mongodb::bson::Document {
let severities: Vec<String> = ISSUE_SEVERITIES.iter().map(Severity::to_string).collect();
let statuses: Vec<String> = ISSUE_STATUSES.iter().map(ToString::to_string).collect();
// `tracker_issue_url: null` matches a missing field too.
doc! {
"repo_id": repo_id,
"tracker_issue_url": null,
"severity": { "$in": severities },
"status": { "$in": statuses },
}
}
/// The target's open medium+ findings without an issue, as stored.
async fn load_candidates(sink: &IssueSink<'_>) -> Result<Vec<Finding>, AgentError> {
let findings = sink
.db
.findings()
.find(doc! {
"repo_id": sink.repo_id,
"tracker_issue_url": null,
"severity": { "$in": severities },
"status": { "$in": statuses },
})
.find(candidate_filter(sink.repo_id))
.await?
.try_collect()
.await?;
Ok(findings)
}
/// Whether target `repo_id` has findings waiting for an issue: one query,
/// so a skipped scan with nothing to catch up never lists the tracker.
///
/// # Errors
///
/// The findings cannot be read.
pub(super) async fn waiting(
db: &crate::database::Database,
repo_id: &str,
) -> Result<bool, AgentError> {
let one = db
.findings()
.clone_with_type::<mongodb::bson::Document>()
.find_one(candidate_filter(repo_id))
.projection(doc! { "_id": 1 })
.await?;
Ok(one.is_some())
}
/// The findings that want an issue and have none, highest severity first,
/// then oldest first.
fn select(findings: Vec<Finding>) -> Vec<Finding> {
@@ -515,6 +543,8 @@ mod tests {
}
};
assert!(waiting(&db, "target-1").await.unwrap());
// A dry run changes nothing.
let dry = catch_up(&sink, &index, IssueCatchup::DryRun).await.unwrap();
assert_eq!((dry.created.total(), dry.linked.total()), (1, 1));
@@ -554,10 +584,12 @@ mod tests {
.expect("the link is recorded for the status sync");
assert_eq!(record.external_id, "7");
// The next scan finds nothing left to do.
// The next scan finds nothing left to do, and a skipped one would
// not even list the tracker.
let again = catch_up(&sink, &index, IssueCatchup::On).await.unwrap();
assert_eq!((again.created.total(), again.linked.total()), (0, 0));
assert_eq!(posts(&seen), 1);
assert!(!waiting(&db, "target-1").await.unwrap());
pool.drop_tenant("issue-catchup").await.ok();
}
}
@@ -160,6 +160,35 @@ impl PipelineOrchestrator {
}
}
impl PipelineOrchestrator {
/// The issue catch-up for a scan that change detection skipped: without
/// it, findings deferred by [`crate::pipeline::issue_catchup::MAX_NEW_ISSUES`]
/// wait for the next push. Runs only with the catch-up on (or in dry
/// run), on a Gitea tracker, and when findings are waiting for an issue,
/// so an idle repository costs one query and no tracker request. A
/// failure is logged; the skipped scan stays skipped.
pub(super) async fn catch_up_unchanged(&self, repo: &RepoView, repo_id: &str) {
if self.config.issue_catchup == IssueCatchup::Off {
return;
}
let Some(TrackerDispatch::Gitea(_)) = self.build_tracker(repo) else {
return;
};
match crate::pipeline::issue_catchup::waiting(&self.db, repo_id).await {
Ok(true) => {}
Ok(false) => return,
Err(e) => {
tracing::warn!("[{repo_id}] Issue catch-up check failed: {e}");
return;
}
}
tracing::info!("[{repo_id}] Unchanged repository: issue catch-up only");
if let Err(e) = self.create_tracker_issues(repo, repo_id, &[]).await {
tracing::warn!("[{repo_id}] Issue catch-up failed: {e}");
}
}
}
/// What opening, reopening and closing a target's CVE issues needs: the
/// tracker configuration, where tracker calls may connect, and the tenant's
/// database. Shared by the scans and the CVE monitor.
@@ -235,6 +235,14 @@ fn comment(status: &FindingStatus, change: Option<&StatusChange>) -> String {
"Die Datei gilt jetzt als Herstellercode und ist von den Befunden ausgenommen.",
"The file now counts as vendor code, which is left out of the findings.",
),
(FindingStatus::Resolved, Some(ScanChangeKind::NowTestData)) => (
"Die Datei liegt in Testdaten (z. B. fixtures/ oder testdata/), die von der Prüfung ausgenommen sind.",
"The file lies in test data (such as fixtures/ or testdata/), which is left out of the scan.",
),
(FindingStatus::Resolved, Some(ScanChangeKind::NowExcluded)) => (
"Die Datei liegt in einem Pfad, den die Einstellungen des Prüfobjekts von der Prüfung ausnehmen.",
"The file lies in a path the target's settings leave out of the scan.",
),
(FindingStatus::Resolved, _) => (
"In Prüfwerk als behoben markiert.",
"Marked resolved in Prüfwerk.",
@@ -0,0 +1,225 @@
//! The licence policy as findings: each component whose licence the
//! workspace's policy forbids (or whose bought licence ended) is a finding,
//! and the components still waiting for a legal review are one finding per
//! target, so a new licence to review shows up with the scan's other results
//! without one finding per unknown licence.
//!
//! The policy, the confirmed licences and the reviews are read at scan time;
//! a change to them shows in the licence check at once and in the findings
//! with the next scan.
use chrono::NaiveDate;
use compliance_core::models::license::{self, package_key, LicenseConclusion};
use compliance_core::models::license_policy::{
self, LicensePolicy, LicenseVerdict, PolicyAction, VerdictReason,
};
use compliance_core::models::{Finding, SbomEntry, ScanType, Severity};
use super::dedup;
/// The scanner name of the findings.
pub const SCANNER: &str = "license-policy";
/// A component the policy forbids.
pub const RULE_FORBIDDEN: &str = "license-forbidden";
/// A bought licence that ended.
pub const RULE_EXPIRED: &str = "license-expired";
/// Components that wait for a legal review.
pub const RULE_REVIEW: &str = "license-review-pending";
/// The most components a review finding names.
const MAX_LISTED: usize = 25;
fn component(entry: &SbomEntry) -> String {
if entry.version.trim().is_empty() {
entry.name.clone()
} else {
format!("{} {}", entry.name, entry.version)
}
}
fn licence(entry: &SbomEntry) -> &str {
entry.effective_license().unwrap_or("no licence found")
}
/// The findings of `repo_id`'s components on `today`.
pub fn findings(
repo_id: &str,
entries: &[SbomEntry],
conclusions: &[LicenseConclusion],
policy: &LicensePolicy,
today: NaiveDate,
) -> Vec<Finding> {
let mut out = Vec::new();
let mut review: Vec<String> = Vec::new();
let mut seen: Vec<String> = Vec::new();
for scanned in entries {
let mut entry = scanned.clone();
entry.concluded = license::find(conclusions, &entry).cloned();
let verdict = license_policy::evaluate(&entry, policy, today);
let key = package_key(&entry.name, &entry.package_manager, entry.purl.as_deref());
let id = format!("{key}@{}", entry.version);
if seen.contains(&id) {
continue;
}
seen.push(id);
match verdict.action {
PolicyAction::Forbid => out.push(forbidden(repo_id, &entry, &key, &verdict)),
PolicyAction::Review => {
review.push(format!("{} ({})", component(&entry), licence(&entry)))
}
PolicyAction::Allow => {}
}
}
if !review.is_empty() {
review.sort();
let count = review.len();
let mut listed: Vec<String> = review.iter().take(MAX_LISTED).cloned().collect();
if count > MAX_LISTED {
listed.push(format!("… and {} more", count - MAX_LISTED));
}
let mut finding = Finding::new(
repo_id.to_string(),
dedup::compute_fingerprint(&[repo_id, RULE_REVIEW]),
SCANNER.to_string(),
ScanType::Sbom,
format!("{count} components wait for a licence review"),
format!(
"The workspace's licence policy asks for a legal review of these components \
before they are used: {}.",
listed.join("; ")
),
Severity::Low,
);
finding.rule_id = Some(RULE_REVIEW.to_string());
finding.remediation = Some(
"Open SBOM → Licences → Licence check. Confirm the licences that are unknown; a \
person with the LEGAL role approves or rejects each one."
.to_string(),
);
out.push(finding);
}
out
}
fn forbidden(repo_id: &str, entry: &SbomEntry, key: &str, verdict: &LicenseVerdict) -> Finding {
let expired = verdict.reasons.iter().find_map(|r| match r {
VerdictReason::Expired { valid_until } => Some(*valid_until),
_ => None,
});
let rejected = verdict.reasons.contains(&VerdictReason::Rejected);
let rule = if expired.is_some() {
RULE_EXPIRED
} else {
RULE_FORBIDDEN
};
let (title, why) = match expired {
Some(until) => (
format!("The licence of {} ended on {until}", component(entry)),
format!(
"The bought licence ({}) of {} was valid until {until}.",
licence(entry),
component(entry)
),
),
None if rejected => (
format!(
"Licence of {} rejected in the legal review",
component(entry)
),
format!(
"A legal review rejected the use of {} under {}.",
component(entry),
licence(entry)
),
),
None => (
format!("{} is under a licence the policy forbids", component(entry)),
format!(
"{} is under {}, which the workspace's licence policy does not allow{}.",
component(entry),
licence(entry),
if verdict.shipped {
" in what is shipped"
} else {
""
}
),
),
};
let mut finding = Finding::new(
repo_id.to_string(),
dedup::compute_fingerprint(&[repo_id, rule, key, &entry.version]),
SCANNER.to_string(),
ScanType::Sbom,
title,
why,
Severity::High,
);
finding.rule_id = Some(rule.to_string());
finding.file_path = entry.evidence.first().cloned();
finding.remediation = Some(match expired {
Some(_) => "Renew the licence and enter its new end date, or replace the component.".into(),
None => "Replace the component, obtain it under another licence, or have the licence \
policy changed by the LEGAL role."
.into(),
});
finding
}
#[cfg(test)]
mod tests {
use super::*;
fn entry(name: &str, license: Option<&str>) -> SbomEntry {
let mut e = SbomEntry::new("r".into(), name.into(), "1.0".into(), "npm".into());
e.license = license.map(String::from);
e
}
fn today() -> NaiveDate {
NaiveDate::from_ymd_opt(2026, 10, 15).unwrap_or_default()
}
#[test]
fn forbidden_licences_are_findings_and_reviews_one_summary() {
let mut policy = LicensePolicy::default();
policy.licenses.push(license_policy::LicenseRule {
license: "AGPL-3.0-only".into(),
action: PolicyAction::Forbid,
note: None,
});
let entries = vec![
entry("ok", Some("MIT")),
entry("bad", Some("AGPL-3.0-only")),
entry("bad", Some("AGPL-3.0-only")),
entry("gpl", Some("GPL-2.0-only")),
entry("unknown", None),
];
let out = findings("r", &entries, &[], &policy, today());
assert_eq!(out.len(), 2);
assert_eq!(out[0].rule_id.as_deref(), Some(RULE_FORBIDDEN));
assert_eq!(out[0].severity, Severity::High);
assert!(out[0].title.contains("bad 1.0"));
assert_eq!(out[1].rule_id.as_deref(), Some(RULE_REVIEW));
assert!(out[1].title.starts_with("2 components"));
assert!(out[1]
.description
.contains("unknown 1.0 (no licence found)"));
// Stable across scans.
let again = findings("r", &entries, &[], &policy, today());
assert_eq!(out[0].fingerprint, again[0].fingerprint);
assert_eq!(out[1].fingerprint, again[1].fingerprint);
}
#[test]
fn nothing_open_is_no_finding() {
let out = findings(
"r",
&[entry("ok", Some("MIT"))],
&[],
&LicensePolicy::default(),
today(),
);
assert!(out.is_empty());
}
}
+57 -1
View File
@@ -258,8 +258,24 @@ struct Metadata {
severity: String,
}
/// Rule-id prefixes of mobsfscan's AndroidManifest rules.
const MANIFEST_RULE_PREFIXES: &[&str] = &["android_manifest_", "android_task_hijacking"];
/// Whether a match of `rule` at `file` can be real: a manifest rule only
/// applies to an `AndroidManifest.xml`. mobsfscan has reported one on another
/// XML file of the tree (`copyright.xml:1`, beside the same finding on the
/// real manifest), nondeterministically, in the nightly (#573).
fn applies_to(rule: &str, file: &str) -> bool {
let manifest_rule = MANIFEST_RULE_PREFIXES.iter().any(|p| rule.starts_with(p));
!manifest_rule
|| Path::new(file)
.file_name()
.is_some_and(|name| name.eq_ignore_ascii_case("AndroidManifest.xml"))
}
impl Report {
/// One finding per rule and location.
/// One finding per rule and location; a manifest rule's match outside an
/// `AndroidManifest.xml` is dropped ([`applies_to`]).
fn findings(self, root: &Path, repo_id: &str) -> Vec<Finding> {
self.results
.into_iter()
@@ -267,6 +283,7 @@ impl Report {
result
.files
.iter()
.filter(|m| applies_to(&rule, &m.file_path))
.map(|m| finding(root, repo_id, &rule, &result.metadata, m))
.collect::<Vec<_>>()
})
@@ -475,6 +492,45 @@ mod tests {
);
}
#[test]
fn a_manifest_rule_counts_only_on_a_manifest() {
assert!(applies_to(
"android_manifest_missing_explicit_allow_backup",
"/tree/app/src/main/AndroidManifest.xml"
));
assert!(!applies_to(
"android_manifest_missing_explicit_allow_backup",
"copyright.xml"
));
assert!(!applies_to(
"android_task_hijacking2",
"res/values/strings.xml"
));
// Code rules match wherever they match.
assert!(applies_to("android_kotlin_logging", "app/src/Main.kt"));
let dir = tree(&[
("app/src/main/AndroidManifest.xml", MANIFEST),
("spotless/copyright.xml", "<!-- Copyright -->\n"),
]);
// The same manifest match, reported a second time on copyright.xml.
let mut json: serde_json::Value = serde_json::from_str(&report(&dir.0)).expect("json");
let files = json["results"]["android_manifest_debugging_enabled"]["files"]
.as_array_mut()
.expect("files");
let mut stray = files[0].clone();
stray["file_path"] = format!("{}/spotless/copyright.xml", dir.0.display()).into();
files.push(stray);
let json = json.to_string();
let parsed: Report = serde_json::from_str(&json).expect("report");
let findings = parsed.findings(&dir.0, "t");
assert_eq!(findings.len(), 1);
assert_eq!(
findings[0].file_path.as_deref(),
Some("app/src/main/AndroidManifest.xml")
);
}
#[test]
fn a_setting_key_is_read_only_from_a_comparison() {
assert_eq!(
+7
View File
@@ -16,6 +16,7 @@ pub mod dedup;
pub mod devskim;
pub mod dotnet;
pub mod embedded_versions;
pub mod eol_tables;
pub mod finding_store;
pub mod firmware_sbom;
pub mod git;
@@ -29,6 +30,7 @@ mod issue_catchup;
pub(crate) mod issue_creation;
pub(crate) mod issue_sync;
pub mod languages;
pub mod license_policy;
pub mod lint;
pub mod mobsfscan;
pub mod nvd_cpe;
@@ -45,11 +47,16 @@ pub mod sbom;
pub mod sbom_quality;
pub mod semgrep;
pub mod source_text;
pub mod test_data;
pub mod tool_cmd;
mod tracker_dispatch;
pub(crate) mod unity_settings;
pub mod variants;
pub mod vendor;
pub mod vex_lifecycle;
pub mod yocto_build;
pub mod yocto_cve_check;
pub mod yocto_inventory;
pub mod yocto_pins;
pub mod yocto_spdx;
pub mod yocto_spdx3;
+402 -5
View File
@@ -37,6 +37,16 @@ pub struct GraphContext {
pub impacts: Vec<compliance_core::models::graph::ImpactAnalysis>,
}
/// What a scan left out of its working copy before the first stage, as
/// paths relative to the tree.
#[derive(Debug, Default)]
struct LeftOut {
/// Removed because the target's settings exclude them.
excluded: Vec<String>,
/// Detected test data ([`crate::pipeline::test_data`]).
test_data: Vec<String>,
}
pub struct PipelineOrchestrator {
pub(super) config: AgentConfig,
/// The tenant this run belongs to. Carried explicitly because the on-disk
@@ -180,6 +190,8 @@ impl PipelineOrchestrator {
),
)
.await;
// Findings deferred by the catch-up's cap still get their issues.
self.catch_up_unchanged(repo, &repo_id).await;
return Ok(0);
}
@@ -225,6 +237,14 @@ impl PipelineOrchestrator {
let repo_id = repo.id.as_ref().map(|id| id.to_hex()).unwrap_or_default();
let repo_path = tree.to_path_buf();
// What the target's settings exclude, and test data (`fixtures/`,
// `testdata/`), which is not what the product ships, leave the working
// copy before any stage reads it, so no stage reports them — no code
// findings, no SBOM components, no CVEs.
let left_out = self
.prune_left_out(&repo_path, &repo.exclude_paths, scan_run_id)
.await;
let mut all_findings: Vec<Finding> = Vec::new();
// Each scanner stage saves its new findings at once, so they show while
// the scan runs (#372); triage updates them at the end.
@@ -237,7 +257,9 @@ impl PipelineOrchestrator {
.unwrap_or_default();
let mut run_findings = crate::pipeline::finding_store::RunFindings::new(scan_run_id)
.with_variants(variants)
.with_tree(repo_path.clone());
.with_tree(repo_path.clone())
.with_excluded(left_out.excluded)
.with_test_data(left_out.test_data);
// Stage 1: SAST. Vendor SDK code (HAL, CMSIS, third-party middleware) is
// not the customer's to fix, so both analysers skip it and the run says
@@ -428,6 +450,7 @@ impl PipelineOrchestrator {
.await;
let mut sbom_entries = generated.entries;
let syft_failure = generated.syft_failure;
let sbom_complete = syft_failure.is_none();
let unmapped_assemblies = generated.unmapped_assemblies;
let resolved_nuget = generated.resolved_nuget;
// Syft reads the lockfiles and archives: without it the SBOM is short
@@ -534,7 +557,15 @@ impl PipelineOrchestrator {
)
.await;
}
let yocto_entries = yocto_inventory::entries(&yocto.recipes, &declarations, &repo_id);
// What the build installed, from its image SPDX: joined with the
// inventory by recipe name, the build's version and image marking win.
let (built_images, cve_checks) = self.read_build_outputs(repo, &repo_id, scan_run_id).await;
let built = crate::pipeline::yocto_build::Built::new(&built_images, &cve_checks);
let yocto_entries = built.merge(yocto_inventory::entries(
&yocto.recipes,
&declarations,
&repo_id,
));
let yocto_recipes = yocto.recipes;
for entry in embedded.into_iter().chain(codesys).chain(yocto_entries) {
let known = sbom_entries
@@ -665,8 +696,10 @@ impl PipelineOrchestrator {
// A Yocto recipe inventory's components: NVD by CPE, within a budget
// of their own (a layer tree can name hundreds of products).
if !yocto_recipes.is_empty() {
let (queries, unversioned) = yocto_inventory::nvd_queries(&yocto_recipes);
if !yocto_recipes.is_empty() || !built.is_empty() {
let (inventory_queries, mut unversioned) = yocto_inventory::nvd_queries(&yocto_recipes);
let (queries, built_unversioned) = built.nvd_queries(inventory_queries);
unversioned.extend(built_unversioned);
let lookup = cve_scanner
.scan_yocto(
&repo_id,
@@ -688,6 +721,22 @@ impl PipelineOrchestrator {
.await;
}
}
// What the build's cve-check found unpatched and the match above did
// not (another version range, a CPE NVD's API matches differently).
let missing = built.unpatched_missing(&cve_alerts, |name| {
sbom_entries
.iter()
.any(|e| e.package_manager == YOCTO_RECIPE_MANAGER && e.name == name)
});
for (name, version, cves) in missing {
cve_alerts.extend(crate::pipeline::cve::record_nvd(
&repo_id,
&mut sbom_entries,
&name,
&version,
cves,
));
}
self.match_advisories(&repo_id, &mut sbom_entries, &mut cve_alerts)
.await;
@@ -695,6 +744,23 @@ impl PipelineOrchestrator {
self.enrich_cves(&repo_id, &mut cve_alerts, &mut sbom_entries)
.await;
// The licence policy over the components just found: forbidden
// licences, ended licences, and what waits for a legal review. Only
// a complete SBOM may close the findings an earlier scan reported.
if sbom_complete && !sbom_entries.is_empty() {
let conclusions = crate::license_conclusions::load(&self.db).await;
let policy = crate::license_conclusions::load_policy(&self.db).await;
let licence_findings = crate::pipeline::license_policy::findings(
&repo_id,
&sbom_entries,
&conclusions,
&policy,
chrono::Utc::now().date_naive(),
);
run_findings.completed(crate::pipeline::license_policy::SCANNER);
all_findings.extend(licence_findings);
}
// Stage 4: Pattern Scanning (GDPR + OAuth)
tracing::info!("[{repo_id}] Stage 4: Pattern Scanning");
self.update_phase(scan_run_id, ScanPhase::PatternScanning)
@@ -981,7 +1047,7 @@ impl PipelineOrchestrator {
// stated again after the alerts were stored, never over a person's,
// and before the notifications, which a `not_affected` or `fixed`
// suppresses.
let statements = yocto_inventory::vex_statements(&yocto_recipes, &cve_alerts);
let statements = built.statements(&yocto_recipes, &cve_alerts);
if !statements.is_empty() {
match crate::pipeline::vex_lifecycle::apply_scan_statements(
&self.db,
@@ -1305,6 +1371,7 @@ impl PipelineOrchestrator {
}
let mut repo = RepoView::from_target(target, code, &self.secrets);
repo.yocto_layers = yocto_layers;
repo.build_outputs = build_output_paths(target, &working_paths);
let n = self.run_pipeline(&repo, scan_run_id, trigger).await?;
self.finalize_target(target, &repo, n).await?;
new_count += n;
@@ -1320,6 +1387,7 @@ impl PipelineOrchestrator {
Some(tree) => {
let mut repo = RepoView::from_target(target, code, &self.secrets);
repo.yocto_layers = yocto_layers;
repo.build_outputs = build_output_paths(target, &working_paths);
let upload = crate::pipeline::plc::sbom::uploaded_archive(code);
let n = self.scan_tree(tree, upload, &repo, scan_run_id).await?;
self.finalize_target(target, &repo, n).await?;
@@ -1338,6 +1406,14 @@ impl PipelineOrchestrator {
}
}
}
// Only what a build wrote about its image (an image SPDX archive,
// a cve-check report): the same stages run over an empty tree, so
// the SBOM, CVEs and VEX come from the build output alone.
None if target.has(ArtifactKind::BuildOutput) => {
new_count += self
.scan_build_output_only(target, &target_id, &working_paths, scan_run_id)
.await?;
}
None => {
// No code to scan. DAST is attempted for a target the matrix
// plans it for, and for a migrated DAST target, which carries no
@@ -1397,10 +1473,22 @@ impl PipelineOrchestrator {
let mut analysed = Vec::with_capacity(sources.len());
let mut all_sbom: Vec<SbomEntry> = Vec::new();
let mut sbom_seen = std::collections::BTreeSet::new();
// CODESYS projects in their native format: their control logic is not
// read, and the run says so (#165).
let mut native = std::collections::BTreeSet::new();
// What the target's settings exclude and the test data leave each tree
// first, as in a code scan (#820, #825).
let mut left_out = LeftOut::default();
for a in &sources {
let Some(path) = ingest_set.get(&a.id).and_then(|ia| ia.working_path.clone()) else {
continue;
};
let pruned = self
.prune_left_out(&path, &target.scan_config.exclude_paths, scan_run_id)
.await;
left_out.excluded.extend(pruned.excluded);
left_out.test_data.extend(pruned.test_data);
native.extend(crate::pipeline::plc::native_projects(&path));
analysed.push((
path.clone(),
crate::pipeline::plc::analyze_tree(&path, target_id),
@@ -1441,6 +1529,23 @@ impl PipelineOrchestrator {
}
}
}
if !native.is_empty() {
let list = native.into_iter().collect::<Vec<_>>().join(", ");
self.skip_stage(
scan_run_id,
SkippedStage::new(
"plc_native_project",
SkipCode::NativePlcProject,
format!(
"CODESYS projects in their native format are not analysed for control \
logic: {list}; export the POUs as PLCopen XML (Project > Export \
PLCopenXML) and add the export to the target"
),
)
.about(list),
)
.await;
}
let all_findings = self.map_plc_findings(scan_run_id, analysed).await;
tracing::info!(
target_id,
@@ -1483,6 +1588,24 @@ impl PipelineOrchestrator {
"Refreshed control_refs on {refreshed_count} existing PLC findings"
);
}
// Findings an earlier scan stored in what is now left out close with
// that reason, and their issues follow.
let mut left_out_run = crate::pipeline::finding_store::RunFindings::new(scan_run_id)
.with_excluded(left_out.excluded)
.with_test_data(left_out.test_data);
let closed = left_out_run
.resolve_left_out(&self.db, target_id, "plc-control-logic")
.await?;
if closed > 0 {
tracing::info!(target_id, closed, "PLC findings in left-out paths resolved");
crate::pipeline::issue_sync::IssueSync {
db: self.db.clone(),
config: self.config.clone(),
secrets: self.secrets.clone(),
net_guard: self.net_guard,
}
.spawn(left_out_run.status_changed().to_vec());
}
if !all_sbom.is_empty() {
if let Err(e) = self
@@ -2257,6 +2380,100 @@ impl PipelineOrchestrator {
.await;
}
/// Take what the target's settings exclude (`excluded`, relative paths)
/// and the test data ([`crate::pipeline::test_data`]) out of the working
/// copy at `tree`, and note on the run what was left out. Only a working
/// copy under the clone or artifact directories is touched; the git
/// fetch and the archive unpack restore it next scan.
///
/// # Returns
///
/// The paths removed, relative to `tree`; empty when there were none or
/// the tree is not the agent's own.
async fn prune_left_out(
&self,
tree: &std::path::Path,
excluded: &[String],
scan_run_id: &str,
) -> LeftOut {
let root = tree.to_path_buf();
let configured = excluded.to_vec();
let clones = std::path::PathBuf::from(&self.config.git_clone_base_path);
let artifacts = std::path::PathBuf::from(&self.config.artifact_store_base_path);
let pruned = tokio::task::spawn_blocking(move || {
use crate::pipeline::test_data::{prune, test_data_dirs};
let owned = [clones.as_path(), artifacts.as_path()];
// Nothing to remove needs no ownership check (and no warning for
// a tree outside the agent's directories).
let prune_some = |paths: &[String]| {
if paths.is_empty() {
Ok(Vec::new())
} else {
prune(&root, paths, &owned)
}
};
// The configured paths first: test data inside them is gone with
// them and not listed twice.
let excluded = prune_some(&configured)?;
let missing: Vec<String> = configured
.into_iter()
.filter(|p| !excluded.contains(p))
.collect();
let test_data = prune_some(&test_data_dirs(&root))?;
Ok::<_, crate::pipeline::test_data::PruneError>((
LeftOut {
excluded,
test_data,
},
missing,
))
})
.await;
let (left_out, missing) = match pruned {
Ok(Ok(done)) => done,
Ok(Err(e)) => {
tracing::warn!(scan_run_id, error = %e, "nothing taken out of the scan");
return LeftOut::default();
}
Err(e) => {
tracing::warn!(scan_run_id, error = %e, "left-out walk failed");
return LeftOut::default();
}
};
if !left_out.excluded.is_empty() || !missing.is_empty() {
let list = left_out.excluded.join(", ");
let mut reason = format!(
"excluded in the target's settings, left out of the whole scan (code findings, \
SBOM, CVE match): {list}"
);
if !missing.is_empty() {
reason.push_str(&format!("; not in the tree: {}", missing.join(", ")));
}
self.skip_stage(
scan_run_id,
SkippedStage::new("excluded_paths", SkipCode::ExcludedPaths, reason).about(list),
)
.await;
}
if !left_out.test_data.is_empty() {
let list = left_out.test_data.join(", ");
self.skip_stage(
scan_run_id,
SkippedStage::new(
"test_data",
SkipCode::TestData,
format!(
"test data is left out of the whole scan (code findings, SBOM, CVE \
match): {list}"
),
)
.about(list),
)
.await;
}
left_out
}
/// The recipe lint of a tree whose `languages` include BitBake, outside
/// the `vendor` directories: the findings, and the scanners that
/// completed. Upstream layers left out and findings suppressed in the
@@ -2436,6 +2653,167 @@ impl PipelineOrchestrator {
/// The recipes, images and package groups of a Yocto layer tree. A parser
/// that failed, a tree with no layer, or recipes the parser could not read
/// are recorded on the run.
/// Scan a target whose only code-like input is its build output: the
/// stages run over an empty working directory (nothing to find there),
/// with the build outputs read as for a layer tree. The run says that
/// there was no source code.
///
/// # Returns
///
/// How many findings were new.
///
/// # Errors
///
/// The working directory cannot be made, or a stage fails as in
/// [`Self::scan_tree`].
async fn scan_build_output_only(
&self,
target: &OnboardedTarget,
target_id: &str,
working_paths: &std::collections::HashMap<String, std::path::PathBuf>,
scan_run_id: &str,
) -> Result<u32, AgentError> {
let Some(first) = target
.artifacts
.iter()
.find(|a| a.kind == ArtifactKind::BuildOutput)
else {
return Ok(0);
};
self.skip_stage(
scan_run_id,
SkippedStage::new(
"source_code",
SkipCode::NotAnalysedYet,
"the target has no source code (a git repository or a source archive): only \
its build output is read; code analysis, the recipe inventory and the recipe \
lint need the layer tree",
),
)
.await;
// Under the agent's own work directory, so it is never a tree the
// scan may not touch, and empty on every run.
let tree = crate::ingest::blob::work_dir(
std::path::Path::new(&self.config.artifact_store_base_path),
target_id,
"build-output-only",
);
let _ = std::fs::remove_dir_all(&tree);
std::fs::create_dir_all(&tree)
.map_err(|e| AgentError::Other(format!("build-output work directory: {e}")))?;
let mut repo = RepoView::from_target(target, first, &self.secrets);
repo.build_outputs = build_output_paths(target, working_paths);
let scanned = self.scan_tree(&tree, None, &repo, scan_run_id).await;
let _ = std::fs::remove_dir_all(&tree);
let n = scanned?;
self.finalize_target(target, &repo, n).await?;
Ok(n)
}
/// What the target's build outputs say: the images their SPDX archives
/// describe ([`crate::pipeline::yocto_spdx`]) and their cve-check reports
/// ([`crate::pipeline::yocto_cve_check`]), told apart by content. One
/// that cannot be read is noted on the run (and skipped), and so are
/// packages an archive lists in an image without their documents.
async fn read_build_outputs(
&self,
repo: &RepoView,
repo_id: &str,
scan_run_id: &str,
) -> (
Vec<crate::pipeline::yocto_spdx::BuiltImage>,
Vec<crate::pipeline::yocto_cve_check::CveCheck>,
) {
/// One build output, read as what it is.
enum Read {
Images(Vec<crate::pipeline::yocto_spdx::BuiltImage>),
Check(crate::pipeline::yocto_cve_check::CveCheck),
}
let mut images = Vec::new();
let mut checks = Vec::new();
for path in &repo.build_outputs {
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let file = path.clone();
let id = repo_id.to_string();
let read = tokio::task::spawn_blocking(move || -> Result<Read, String> {
let mut head = [0u8; 512];
let n = {
use std::io::Read as _;
std::fs::File::open(&file)
.and_then(|mut f| f.read(&mut head))
.map_err(|e| e.to_string())?
};
// An SPDX 3.0 image document is JSON too: recognised first.
if crate::pipeline::yocto_spdx3::is_spdx3(&head[..n]) {
return crate::pipeline::yocto_spdx3::read(&file, &id)
.map(Read::Images)
.map_err(|e| e.to_string());
}
if crate::pipeline::yocto_cve_check::is_cve_check(&head[..n]) {
return crate::pipeline::yocto_cve_check::read(&file)
.map(Read::Check)
.map_err(|e| e.to_string());
}
crate::pipeline::yocto_spdx::read_archive(
&file,
&id,
crate::pipeline::yocto_spdx::ReadLimits::default(),
)
.map(Read::Images)
.map_err(|e| e.to_string())
})
.await;
match read {
Ok(Ok(Read::Images(read))) => images.extend(read),
Ok(Ok(Read::Check(check))) => checks.push(check),
Ok(Err(e)) => {
tracing::warn!(scan_run_id, file = %name, error = %e, "build output not read");
self.skip_stage(
scan_run_id,
SkippedStage::new(
crate::pipeline::yocto_spdx::STAGE,
SkipCode::ArtifactNotIngested,
format!(
"{name} was not read as a Yocto image SPDX archive \
(<image>.spdx.tar.zst), SPDX 3.0 image document \
(<image>.spdx.json) or cve-check report (<image>.json): {e}"
),
)
.about(name),
)
.await;
}
Err(e) => tracing::warn!(scan_run_id, error = %e, "build output read failed"),
}
}
let unresolved: Vec<String> = images
.iter()
.flat_map(|i| i.unresolved.iter().cloned())
.collect::<std::collections::BTreeSet<_>>()
.into_iter()
.collect();
if !unresolved.is_empty() {
let list = component_list(&unresolved);
self.skip_stage(
scan_run_id,
SkippedStage::new(
crate::pipeline::yocto_spdx::STAGE,
SkipCode::BuildPackagesUnresolved,
format!(
"the image SPDX lists these packages in the image without their \
documents, so their recipes are not known: {list}"
),
)
.about(list),
)
.await;
}
(images, checks)
}
async fn yocto_recipes(&self, tree: &std::path::Path, scan_run_id: &str) -> Inventory {
match yocto_inventory::read(tree).await {
Ok(inventory) if inventory.recipes.is_empty() && inventory.errors.is_empty() => {
@@ -2715,6 +3093,25 @@ pub(super) fn extract_base_url(git_url: &str) -> Option<String> {
}
}
/// The ingested files of `target`'s build outputs (Yocto image SPDX
/// archives), or the stored upload where ingest recorded no working path.
fn build_output_paths(
target: &OnboardedTarget,
working_paths: &std::collections::HashMap<String, std::path::PathBuf>,
) -> Vec<std::path::PathBuf> {
target
.artifacts
.iter()
.filter(|a| a.kind == ArtifactKind::BuildOutput)
.filter_map(|a| {
working_paths
.get(&a.id)
.cloned()
.or_else(|| a.stored_path.as_deref().map(std::path::PathBuf::from))
})
.collect()
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
+118
View File
@@ -3,6 +3,10 @@
//! Parses Structured Text (raw `.st`/`.scl`/`.exp` files and PLCopen-XML
//! projects) into an AST and runs semantic control-logic security rules over it.
//! Implements [`ScanType::PlcControlLogic`].
//!
//! A CODESYS project in its native format (the binary `.project`, also inside
//! a `.projectarchive`) cannot be read; [`native_projects`] lists them so the
//! scan says so instead of finding nothing in silence (#165).
pub mod ast;
pub mod lexer;
@@ -65,6 +69,11 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
let Ok(content) = std::fs::read_to_string(path) else {
continue;
};
// A `.project` is read only as a PLCopen export; CODESYS's native one
// is binary ([`native_projects`] reports it).
if ext == "project" && !looks_like_xml(&content) {
continue;
}
let pous = if is_xml {
plcopen::parse_plcopen(&content)
} else {
@@ -104,6 +113,67 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
findings
}
/// Whether `content` starts as an XML document (after a byte-order mark and
/// white space).
fn looks_like_xml(content: &str) -> bool {
content
.trim_start_matches('\u{feff}')
.trim_start()
.starts_with('<')
}
/// The CODESYS projects under `root` in their native format, which the
/// control-logic analysis cannot read: a `.project` that is not a PLCopen XML
/// export, and a readable `.projectarchive` (a zip around one). Paths are
/// relative to `root`, `/`-separated, sorted; `.git` is skipped. A
/// `.projectarchive` that does not open is left out: the SBOM stage reports
/// it as unreadable.
///
/// # Arguments
///
/// * `root` - the tree, or a single uploaded file
///
/// # Returns
///
/// The native project files, e.g. `["LineControl.project"]`.
pub fn native_projects(root: &Path) -> Vec<String> {
let mut found = Vec::new();
let walker = walkdir::WalkDir::new(root)
.into_iter()
.filter_entry(|e| e.file_name() != ".git");
for entry in walker.filter_map(Result::ok) {
if !entry.file_type().is_file() {
continue;
}
let path = entry.path();
let ext = path
.extension()
.and_then(|e| e.to_str())
.unwrap_or("")
.to_ascii_lowercase();
let native = match ext.as_str() {
"project" => !std::fs::read(path)
.ok()
.and_then(|bytes| String::from_utf8(bytes).ok())
.is_some_and(|text| looks_like_xml(&text)),
"projectarchive" => sbom::check_archive(path).is_ok(),
_ => false,
};
if native {
let rel = path.strip_prefix(root).unwrap_or(path);
let rel = if rel.as_os_str().is_empty() {
// `root` is the file itself.
path.file_name().map(Path::new).unwrap_or(path)
} else {
rel
};
found.push(rel.to_string_lossy().replace('\\', "/"));
}
}
found.sort();
found
}
#[cfg(test)]
mod tests {
use super::*;
@@ -231,4 +301,52 @@ mod tests {
);
}
}
/// A scratch directory, removed on drop.
struct Scratch(PathBuf);
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn native_codesys_projects_are_listed_and_exports_are_not() {
let root =
Scratch(std::env::temp_dir().join(format!("cs-plc-native-{}", uuid::Uuid::new_v4())));
let write = |rel: &str, bytes: &[u8]| {
let path = root.0.join(rel);
std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
std::fs::write(path, bytes).expect("write");
};
// A binary native project, and one that is text but not XML.
write("App/Line.project", b"\x00\x01CODESYS\xff");
write("Other.project", b"fixture");
// A PLCopen export saved as `.project` is read, not reported.
write(
"Export.project",
b"\xef\xbb\xbf <?xml version=\"1.0\"?><project/>",
);
// A readable archive is native; a corrupt one is left to the SBOM stage.
let fixtures = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixtures/nightly/plc");
std::fs::copy(
fixtures.join("line_control.projectarchive"),
root.0.join("Line.projectarchive"),
)
.expect("copy archive");
write("Broken.projectarchive", b"not a zip");
write(".git/x.project", b"\x00");
assert_eq!(
native_projects(&root.0),
["App/Line.project", "Line.projectarchive", "Other.project"]
);
// An uploaded file on its own is named by its file name.
assert_eq!(
native_projects(&root.0.join("Other.project")),
["Other.project"]
);
// The binary project yields no POUs and no error.
assert!(analyze_tree(&root.0, "t").is_empty());
}
}
+5 -1
View File
@@ -96,9 +96,13 @@ pub fn projectarchive_sbom(archive: &Path, repo_id: &str) -> Vec<SbomEntry> {
let Ok(entry) = zip.by_index_raw(i) else {
continue;
};
// zip 9: a name that does not decode is skipped like an unreadable entry.
let Ok(entry_name) = entry.name() else {
continue;
};
// Entry paths use `\` (Windows-authored) and/or `/` separators; the
// component id is one path segment.
for seg in entry.name().split(['/', '\\']) {
for seg in entry_name.split(['/', '\\']) {
if let Some((name, version)) = parse_library(seg).or_else(|| parse_runtime(seg)) {
if seen.insert((name.clone(), version.clone())) {
let mut e = SbomEntry::new(
@@ -49,6 +49,12 @@ pub struct RepoView {
/// was classified as one, or the target is a Yocto target. Set by the
/// caller after classification; `false` from [`Self::from_target`].
pub yocto_layers: bool,
/// Directories and files the target's settings leave out of every scan
/// stage (`scan_config.exclude_paths`).
pub exclude_paths: Vec<String>,
/// The target's uploaded build outputs (Yocto image SPDX archives), as
/// ingested. Set by the caller; empty from [`Self::from_target`].
pub build_outputs: Vec<std::path::PathBuf>,
}
impl RepoView {
@@ -79,6 +85,8 @@ impl RepoView {
managed: target.source_repo.is_some(),
uploads_allow_skip: crate::pipeline::change::uploads_allow_git_skip(target),
yocto_layers: false,
exclude_paths: target.scan_config.exclude_paths.clone(),
build_outputs: Vec::new(),
};
if let Some(git) = &code.git {
view.default_branch = git.default_branch.clone();
@@ -178,13 +178,15 @@ impl crate::pipeline::orchestrator::PipelineOrchestrator {
if count == 0 || count > crate::api::handlers::sbom::MAX_EXPORT_COMPONENTS {
return None;
}
let entries: Vec<SbomEntry> = match self.db.sbom_entries().find(filter).await {
let mut entries: Vec<SbomEntry> = match self.db.sbom_entries().find(filter).await {
Ok(cursor) => cursor.try_collect().await.ok()?,
Err(e) => {
tracing::warn!(target_id, "SBOM not scored: {e}");
return None;
}
};
// Scored as exported: with the licences a person confirmed.
crate::license_conclusions::attach(&self.db, &mut entries).await;
match score(&entries, subject).await {
Ok(quality) => {
tracing::info!(
+334
View File
@@ -0,0 +1,334 @@
//! Test data inside a scanned tree: fixtures, sample projects, golden files.
//!
//! A repository's test data is not what it ships. Its sample lockfiles name
//! old, vulnerable dependencies on purpose, its sample code holds the flaws a
//! test expects to find, and none of it is the product's to fix. Scanned as
//! product code, it buries the real findings: the CVE issues of a test
//! fixture's `struts2 2.3.30` read exactly like those of a dependency the
//! product uses.
//!
//! So the directories that hold test data by a common convention are taken
//! out of the scan's working copy before the first stage runs, and every
//! stage — code findings, SBOM, CVE match — sees the tree without them. The
//! working copy is a git clone, restored on every fetch, or an unpacked
//! upload, unpacked again on every scan, so nothing is lost.
//!
//! Matching is by directory name only, and narrow: `tests/` and `spec/`
//! hold test code that can leak a real secret, and `examples/` or `demo/` are
//! often the product's own code, so neither is matched.
use std::path::Path;
/// Directory names that hold test data by convention, compared
/// case-insensitively: `fixtures` (Rails, pytest, Jest's `__fixtures__`),
/// Go's `testdata`, and their spellings.
const TEST_DATA_DIR_NAMES: &[&str] = &[
"fixtures",
"__fixtures__",
"testdata",
"test_data",
"test-data",
"test-fixtures",
"test_fixtures",
];
/// The top-most test-data directories under `root`, relative to it with `/`
/// separators, sorted. A directory inside one that already matched is not
/// listed again, `root` itself is never listed, and a symbolic link is never
/// followed or listed.
///
/// # Arguments
///
/// * `root` - the scanned tree
///
/// # Returns
///
/// The directories to leave out of the scan, e.g. `["fixtures",
/// "pkg/parser/testdata"]`.
pub fn test_data_dirs(root: &Path) -> Vec<String> {
let mut found = Vec::new();
let mut walker = walkdir::WalkDir::new(root).min_depth(1).into_iter();
while let Some(entry) = walker.next() {
let Ok(entry) = entry else {
continue;
};
// `file_type()` does not follow links: a link to a directory is a
// link here, never a directory.
if !entry.file_type().is_dir() {
continue;
}
let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
if name == ".git" {
walker.skip_current_dir();
continue;
}
if TEST_DATA_DIR_NAMES.contains(&name.as_str()) {
if let Ok(rel) = entry.path().strip_prefix(root) {
found.push(rel.to_string_lossy().replace('\\', "/"));
}
walker.skip_current_dir();
}
}
found.sort();
found
}
/// Remove the `paths` (the [`test_data_dirs`], or the directories and files
/// a target's settings exclude) from the working copy at `root`.
///
/// Only a working copy the agent made may lose files: `root` must lie under
/// one of `owned_bases` (the clone base and the artifact store). Anything
/// else is refused, so the call can never delete a directory it was pointed
/// at by mistake. A path is only removed when it lies inside `root` without
/// passing a symbolic link: `src/link/x` with `src/link` pointing elsewhere
/// is left alone, and so is a link itself.
///
/// # Arguments
///
/// * `root` - the scan's working copy
/// * `paths` - directories or files relative to `root`, `/`-separated
/// * `owned_bases` - the directories the agent's working copies live under
///
/// # Returns
///
/// The paths that were removed; one that is not in the tree is left out, and
/// one that could not be removed is logged and left out.
///
/// # Errors
///
/// [`PruneError::NotOwned`] when `root` lies under none of `owned_bases`;
/// nothing is removed then.
pub fn prune(
root: &Path,
paths: &[String],
owned_bases: &[&Path],
) -> Result<Vec<String>, PruneError> {
let owned = owned_bases
.iter()
.any(|base| !base.as_os_str().is_empty() && root.starts_with(base) && root != *base);
if !owned {
return Err(PruneError::NotOwned);
}
let mut removed = Vec::with_capacity(paths.len());
for rel in paths {
let Some(path) = inside_without_links(root, rel) else {
continue;
};
let Ok(meta) = std::fs::symlink_metadata(&path) else {
continue;
};
let outcome = if meta.is_dir() {
std::fs::remove_dir_all(&path)
} else if meta.is_file() {
std::fs::remove_file(&path)
} else {
continue;
};
match outcome {
Ok(()) => removed.push(rel.clone()),
Err(e) => tracing::warn!(path = %rel, error = %e, "left-out path not removed"),
}
}
Ok(removed)
}
/// `root` joined with `rel` when every component of `rel` is a plain name
/// and none of the directories on the way is a symbolic link; `None`
/// otherwise (also when a part does not exist).
fn inside_without_links(root: &Path, rel: &str) -> Option<std::path::PathBuf> {
let rel_path = Path::new(rel);
if rel_path.is_absolute() {
return None;
}
let mut path = root.to_path_buf();
for component in rel_path.components() {
let std::path::Component::Normal(name) = component else {
tracing::warn!(path = %rel, "left-out path outside the tree; not removed");
return None;
};
path.push(name);
let meta = std::fs::symlink_metadata(&path).ok()?;
if meta.file_type().is_symlink() {
return None;
}
}
(path != root).then_some(path)
}
/// Why [`prune`] removed nothing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum PruneError {
/// The tree is not a working copy the agent made.
#[error("the tree is not under the agent's clone or artifact directories")]
NotOwned,
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
fn write(root: &Path, rel: &str) {
let path = root.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "x").unwrap();
}
/// A scratch directory, removed on drop.
struct Scratch(std::path::PathBuf);
impl Scratch {
fn new() -> Self {
let dir = std::env::temp_dir().join(format!("cs-testdata-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
Self(dir)
}
fn path(&self) -> &Path {
&self.0
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// A working copy under a fake clone base: `(base, tree)`.
fn tree() -> (Scratch, std::path::PathBuf) {
let base = Scratch::new();
let root = base.path().join("tenant").join("repo");
for file in [
"src/main.rs",
"src/fixtures_helper.rs",
"src/fixtures.rs",
"fixtures/nightly/eco/maven/pom.xml",
"fixtures/nightly/eco/maven/fixtures/inner.txt",
"pkg/parser/testdata/input.json",
"web/__fixtures__/user.json",
"Tests/Test-Data/sample.csv",
"tests/integration.rs",
"examples/demo.rs",
".git/fixtures/HEAD",
] {
write(&root, file);
}
(base, root)
}
#[test]
fn test_data_is_found_by_name_and_reported_once() {
let (_base, root) = tree();
assert_eq!(
test_data_dirs(&root),
[
"Tests/Test-Data",
"fixtures",
"pkg/parser/testdata",
"web/__fixtures__",
]
);
}
#[test]
fn the_tree_itself_is_never_test_data() {
let base = Scratch::new();
let root = base.path().join("fixtures");
write(&root, "package-lock.json");
assert!(test_data_dirs(&root).is_empty());
}
#[test]
fn pruning_removes_the_test_data_and_keeps_the_rest() {
let (base, root) = tree();
let dirs = test_data_dirs(&root);
let removed = prune(&root, &dirs, &[base.path()]).unwrap();
assert_eq!(removed, dirs);
assert!(!root.join("fixtures").exists());
assert!(!root.join("pkg/parser/testdata").exists());
assert!(root.join("pkg/parser").is_dir());
for kept in [
"src/main.rs",
"src/fixtures_helper.rs",
"src/fixtures.rs",
"tests/integration.rs",
"examples/demo.rs",
".git/fixtures/HEAD",
] {
assert!(root.join(kept).is_file(), "{kept} must stay");
}
}
#[test]
fn a_tree_the_agent_did_not_make_is_never_pruned() {
let (_base, root) = tree();
let elsewhere = Scratch::new();
let dirs = test_data_dirs(&root);
assert_eq!(
prune(&root, &dirs, &[elsewhere.path()]),
Err(PruneError::NotOwned)
);
// The base itself is not a working copy, and an empty base owns nothing.
assert_eq!(
prune(&root, &dirs, &[root.as_path(), Path::new("")]),
Err(PruneError::NotOwned)
);
assert!(root.join("fixtures").is_dir());
}
#[test]
fn a_configured_file_or_directory_is_removed_and_a_missing_one_skipped() {
let (base, root) = tree();
let removed = prune(
&root,
&[
"src/main.rs".to_string(),
"examples".to_string(),
"not/there".to_string(),
],
&[base.path()],
)
.unwrap();
assert_eq!(removed, ["src/main.rs", "examples"]);
assert!(!root.join("src/main.rs").exists());
assert!(root.join("src/fixtures.rs").is_file());
assert!(!root.join("examples").exists());
}
#[cfg(unix)]
#[test]
fn a_path_through_a_link_is_never_followed() {
let (base, root) = tree();
let outside = base.path().join("outside");
write(&outside, "keep/me.txt");
std::os::unix::fs::symlink(&outside, root.join("src/link")).unwrap();
let removed = prune(&root, &["src/link/keep".to_string()], &[base.path()]).unwrap();
assert!(removed.is_empty());
assert!(outside.join("keep/me.txt").is_file());
}
#[test]
fn a_path_outside_the_tree_is_never_removed() {
let (base, root) = tree();
let removed = prune(
&root,
&["../repo/src".to_string(), "/etc".to_string()],
&[base.path()],
)
.unwrap();
assert!(removed.is_empty());
assert!(root.join("src/main.rs").is_file());
}
#[cfg(unix)]
#[test]
fn a_link_named_like_test_data_is_left_alone() {
let (base, root) = tree();
let target = base.path().join("outside");
write(&target, "keep.txt");
std::os::unix::fs::symlink(&target, root.join("src/testdata")).unwrap();
let dirs = test_data_dirs(&root);
assert!(!dirs.contains(&"src/testdata".to_string()));
prune(&root, &["src/testdata".to_string()], &[base.path()]).unwrap();
assert!(target.join("keep.txt").is_file());
assert!(root.join("src/testdata").exists());
}
}
@@ -0,0 +1,715 @@
//! A Yocto build's own evidence (its image SPDX, [`crate::pipeline::yocto_spdx`])
//! combined with the recipe inventory of the layer tree
//! ([`crate::pipeline::yocto_inventory`]).
//!
//! The two name the same recipes differently: the inventory reads PV as
//! written (`linux-yocto 6.6`), the build records what it built
//! (`6.6.151+git`). So they are joined by recipe name, and for a recipe in
//! both the build wins: its version, CPE and licence, and its image marking
//! ([`InImageBasis::Built`]). An image the build's SPDX covers is
//! authoritative: a recipe the inventory declares in it but the build did not
//! install loses that marking; images the SPDX does not cover keep theirs.
//!
//! The build also says which CVEs its patches fixed; those become `fixed`
//! VEX statements on the matching alerts, ahead of what the recipes state.
//! Its cve-check report ([`crate::pipeline::yocto_cve_check`]), when it was
//! uploaded too, goes first: Yocto's verdict on every CVE it looked at, and
//! the CVEs it found unpatched that NVD's match here did not.
use std::collections::{BTreeMap, BTreeSet, HashMap};
use compliance_core::models::{
CveAlert, InImage, InImageBasis, SbomEntry, VexAssessment, VexJustification, VexStatus,
YOCTO_RECIPE_MANAGER,
};
use crate::pipeline::nvd_cpe::NvdCve;
use crate::pipeline::yocto_cve_check::{CheckStatus, CheckedIssue, CveCheck};
use crate::pipeline::yocto_inventory::{self, CpeProduct, NvdQuery, Recipe};
use crate::pipeline::yocto_spdx::{BuiltImage, NotAffectedCve};
/// What the build installed, across its images, by recipe name.
#[derive(Debug, Default)]
pub struct Built<'a> {
/// One component per recipe (the first image's, with every image named).
components: BTreeMap<String, SbomEntry>,
/// The images the SPDX covers (`core-image-minimal`).
images: BTreeSet<String>,
/// The CVEs fixed per recipe name.
fixed: HashMap<String, BTreeSet<&'a str>>,
/// What the build's SPDX 3.0 VEX says does not affect each recipe, by CVE.
not_affected: HashMap<&'a str, HashMap<&'a str, &'a NotAffectedCve>>,
/// Yocto's cve-check verdicts per recipe name, by CVE.
checked: HashMap<&'a str, HashMap<&'a str, &'a CheckedIssue>>,
/// The version cve-check names each recipe at.
checked_versions: BTreeMap<&'a str, &'a str>,
}
impl<'a> Built<'a> {
/// Gather `images` (from one or more build-output archives) and the
/// cve-check reports `checks`.
pub fn new(images: &'a [BuiltImage], checks: &'a [CveCheck]) -> Self {
let mut built = Self::default();
for package in checks.iter().flat_map(|c| &c.packages) {
built
.checked_versions
.insert(package.name.as_str(), package.version.as_str());
let issues = built.checked.entry(package.name.as_str()).or_default();
for issue in &package.issues {
issues.insert(issue.id.as_str(), issue);
}
}
for image in images {
built.images.insert(image.image.clone());
for entry in &image.entries {
match built.components.get_mut(&entry.name) {
Some(known) => add_image(known, &image.image),
None => {
built.components.insert(entry.name.clone(), entry.clone());
}
}
}
for fixed in &image.fixed {
built
.fixed
.entry(fixed.component.clone())
.or_default()
.insert(fixed.cve.as_str());
}
for na in &image.not_affected {
built
.not_affected
.entry(na.component.as_str())
.or_default()
.insert(na.cve.as_str(), na);
}
}
built
}
/// Whether the build listed nothing.
pub fn is_empty(&self) -> bool {
self.components.is_empty() && self.checked.is_empty()
}
/// The CVEs cve-check found unpatched that `alerts` do not have, per
/// recipe and version (the built one where the build lists the recipe),
/// for recipes `known` (components of the scan) only.
pub fn unpatched_missing(
&self,
alerts: &[CveAlert],
known: impl Fn(&str) -> bool,
) -> Vec<(String, String, Vec<NvdCve>)> {
let mut out = Vec::new();
for (name, issues) in &self.checked {
if !known(name) {
continue;
}
let version = self
.components
.get(*name)
.map(|c| c.version.as_str())
.or_else(|| self.checked_versions.get(name).copied())
.unwrap_or_default();
let mut missing: Vec<NvdCve> = issues
.values()
.filter(|i| i.status == CheckStatus::Unpatched)
.filter(|i| {
!alerts
.iter()
.any(|a| a.affected_package == *name && a.cve_id == i.id)
})
.map(|i| NvdCve {
id: i.id.clone(),
summary: i.summary.clone(),
cvss: i.cvss(),
})
.collect();
if missing.is_empty() {
continue;
}
missing.sort_by(|a, b| a.id.cmp(&b.id));
out.push((name.to_string(), version.to_string(), missing));
}
out.sort_by(|a, b| a.0.cmp(&b.0));
out
}
/// Yocto's cve-check verdict on `cve` of `package`, as a statement:
/// Patched is fixed, Ignored as its CVE_STATUS reason says, Unpatched
/// none.
fn checked_statement(&self, package: &str, cve: &str) -> Option<VexAssessment> {
let issue = self.checked.get(package)?.get(cve)?;
let (status, justification) = match issue.status {
CheckStatus::Unpatched => return None,
// Yocto's kernel CVE report (improve_kernel_cve_report.py) says
// Patched when the version is outside the affected range: not
// affected rather than fixed.
CheckStatus::Patched if issue.detail.as_deref() == Some("version-not-in-range") => (
VexStatus::NotAffected,
Some(VexJustification::VulnerableCodeNotPresent),
),
CheckStatus::Patched => (VexStatus::Fixed, None),
CheckStatus::Ignored => {
yocto_inventory::status_statement(issue.detail.as_deref().unwrap_or("ignored"))?
}
};
let verdict = match issue.status {
CheckStatus::Patched => "Patched",
CheckStatus::Ignored => "Ignored",
CheckStatus::Unpatched => "Unpatched",
};
let mut because = format!("Yocto cve-check: {verdict}");
if let Some(detail) = issue.detail.as_deref() {
because.push_str(&format!(" ({detail})"));
}
if let Some(note) = issue.description.as_deref().filter(|n| !n.is_empty()) {
because.push_str(&format!(": {note}"));
}
Some(yocto_inventory::scan_statement(
status,
justification,
because,
))
}
/// The SBOM components: `inventory` (the recipe inventory's) joined with
/// what the build installed, by recipe name. See the module docs.
pub fn merge(&self, inventory: Vec<SbomEntry>) -> Vec<SbomEntry> {
let mut out = Vec::with_capacity(inventory.len() + self.components.len());
let mut joined = BTreeSet::new();
for mut entry in inventory {
if entry.package_manager != YOCTO_RECIPE_MANAGER {
out.push(entry);
continue;
}
match self.components.get(&entry.name) {
Some(built) => {
joined.insert(entry.name.clone());
out.push(self.joined(entry, built));
}
None => {
self.uncover(&mut entry);
out.push(entry);
}
}
}
out.extend(
self.components
.values()
.filter(|c| !joined.contains(&c.name))
.cloned(),
);
out
}
/// `inventory`'s component with what the build says about it.
fn joined(&self, inventory: SbomEntry, built: &SbomEntry) -> SbomEntry {
let mut entry = built.clone();
// The inventory knows where the recipe is and what it fetches.
entry.download_url = built.download_url.clone().or(inventory.download_url);
entry.license = built.license.clone().or(inventory.license);
entry.cpe = built.cpe.clone().or(inventory.cpe);
let declared_elsewhere: Vec<String> = inventory
.in_image
.as_ref()
.filter(|i| i.basis == InImageBasis::Declared)
.map(|i| {
i.images
.iter()
.filter(|image| !self.images.contains(*image))
.cloned()
.collect()
})
.unwrap_or_default();
let mut evidence: Vec<String> = inventory
.evidence
.into_iter()
.filter(|line| !line.starts_with(InImageBasis::Declared.describe()))
.collect();
if !declared_elsewhere.is_empty() {
evidence.push(
InImage {
basis: InImageBasis::Declared,
images: declared_elsewhere,
}
.describe(),
);
}
for line in built.evidence.iter() {
if !evidence.contains(line) {
evidence.push(line.clone());
}
}
entry.evidence = evidence;
entry
}
/// Take the images the build covers out of `entry`'s declared marking:
/// the build installed it there, or it is not there.
fn uncover(&self, entry: &mut SbomEntry) {
let Some(in_image) = entry
.in_image
.as_mut()
.filter(|i| i.basis == InImageBasis::Declared)
else {
return;
};
let before = in_image.describe();
in_image.images.retain(|image| !self.images.contains(image));
let after = (!in_image.images.is_empty()).then(|| in_image.describe());
if after.is_none() {
entry.in_image = None;
}
entry.evidence.retain(|line| *line != before);
entry.evidence.extend(after);
}
/// What to ask NVD: the inventory's `queries`, with the build's version
/// and CPE for a recipe the build installed, and a query for each built
/// recipe the inventory does not have. Returns the queries and the
/// components that cannot be asked about (no release version).
pub fn nvd_queries(&self, queries: Vec<NvdQuery>) -> (Vec<NvdQuery>, Vec<String>) {
let mut out: Vec<NvdQuery> = queries
.into_iter()
.filter(|q| !self.components.contains_key(&q.name))
.collect();
let mut unversioned = Vec::new();
for component in self.components.values() {
let products: Vec<CpeProduct> =
component.cpe.iter().filter_map(|c| product(c)).collect();
if products.is_empty() {
continue;
}
match yocto_inventory::release_of(&component.version) {
Some(cve_version) => out.push(NvdQuery {
name: component.name.clone(),
version: component.version.clone(),
cve_version,
products,
}),
None => unversioned.push(format!("{} (no release version)", component.name)),
}
}
(out, unversioned)
}
/// The VEX statements on `alerts`: `fixed` for a CVE the build's patches
/// fixed in the component, else what its recipe in the tree states
/// (joined by name, whatever version either side names), else what
/// [`yocto_inventory::vex_statements`] finds.
pub fn statements(
&self,
recipes: &[Recipe],
alerts: &[CveAlert],
) -> Vec<(String, VexAssessment)> {
let (built_alerts, other): (Vec<&CveAlert>, Vec<&CveAlert>) =
alerts.iter().partition(|a| {
self.components.contains_key(&a.affected_package)
|| self.checked.contains_key(a.affected_package.as_str())
});
let mut out: Vec<(String, VexAssessment)> = built_alerts
.iter()
.filter_map(|alert| {
if let Some(checked) =
self.checked_statement(&alert.affected_package, &alert.cve_id)
{
return Some((alert.cve_id.clone(), checked));
}
if let Some(na) = self
.not_affected
.get(alert.affected_package.as_str())
.and_then(|cves| cves.get(alert.cve_id.as_str()))
{
return Some((alert.cve_id.clone(), not_affected_statement(na)));
}
let fixed = self
.fixed
.get(&alert.affected_package)
.is_some_and(|cves| cves.contains(alert.cve_id.as_str()));
let statement = if fixed {
Some(yocto_inventory::scan_statement(
VexStatus::Fixed,
None,
format!(
"Fixed by a patch the build applied to {} (Yocto create-spdx: CVEs \
fixed)",
alert.affected_package
),
))
} else {
recipes
.iter()
.find(|r| r.bpn == alert.affected_package)
.and_then(|r| yocto_inventory::recipe_statement(r, &alert.cve_id))
};
statement.map(|vex| (alert.cve_id.clone(), vex))
})
.collect();
let rest: Vec<CveAlert> = other.into_iter().cloned().collect();
out.extend(yocto_inventory::vex_statements(recipes, &rest));
out
}
}
/// The statement the build's SPDX 3.0 makes that `na` does not affect its
/// component, with its justification and impact statement.
fn not_affected_statement(na: &NotAffectedCve) -> VexAssessment {
let justification = match na.justification.as_deref() {
Some("componentNotPresent") => Some(VexJustification::ComponentNotPresent),
Some("vulnerableCodeNotPresent") => Some(VexJustification::VulnerableCodeNotPresent),
Some("vulnerableCodeNotInExecutePath") => {
Some(VexJustification::VulnerableCodeNotInExecutePath)
}
Some("vulnerableCodeCannotBeControlledByAdversary") => {
Some(VexJustification::VulnerableCodeCannotBeControlledByAdversary)
}
Some("inlineMitigationsAlreadyExist") => {
Some(VexJustification::InlineMitigationsAlreadyExist)
}
_ => None,
};
let mut because = "Yocto SPDX 3.0 VEX: not affected".to_string();
if let Some(statement) = na.statement.as_deref().filter(|s| !s.is_empty()) {
because.push_str(&format!(": {statement}"));
}
yocto_inventory::scan_statement(VexStatus::NotAffected, justification, because)
}
/// Add `image` to `entry`'s built marking and its evidence line.
fn add_image(entry: &mut SbomEntry, image: &str) {
let Some(in_image) = entry.in_image.as_mut() else {
return;
};
if in_image.images.iter().any(|i| i == image) {
return;
}
let before = in_image.describe();
in_image.images.push(image.to_string());
let after = in_image.describe();
for line in entry.evidence.iter_mut() {
if *line == before {
line.clone_from(&after);
}
}
}
/// The product a CPE 2.3 name names (`cpe:2.3:*:openssl:openssl:3.5.9:…` →
/// vendor `openssl`, product `openssl`; a `*` vendor is any vendor).
fn product(cpe: &str) -> Option<CpeProduct> {
let mut parts = cpe.split(':');
if parts.next()? != "cpe" || parts.next()? != "2.3" {
return None;
}
let _part = parts.next()?;
let vendor = parts.next()?;
let product = parts.next()?;
if product.is_empty() || product == "*" {
return None;
}
Some(CpeProduct {
vendor: (vendor != "*" && !vendor.is_empty()).then(|| vendor.replace('\\', "")),
product: product.replace('\\', ""),
})
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use crate::pipeline::yocto_spdx::{read_dir, ReadLimits};
fn built_images() -> Vec<BuiltImage> {
let dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../fixtures/yocto/spdx-scarthgap");
read_dir(&dir, "t", ReadLimits::default()).unwrap()
}
/// An inventory component as the recipe inventory makes it.
fn inventory(name: &str, version: &str, declared: &[&str]) -> SbomEntry {
let mut e = SbomEntry::new(
"t".into(),
name.into(),
version.into(),
YOCTO_RECIPE_MANAGER.into(),
);
e.evidence.push(format!(
"Yocto recipe inventory: recipes-core/{name}/{name}.bb"
));
if !declared.is_empty() {
let in_image = InImage {
basis: InImageBasis::Declared,
images: declared.iter().map(|s| s.to_string()).collect(),
};
e.evidence.push(in_image.describe());
e.in_image = Some(in_image);
}
e
}
#[test]
fn the_build_wins_by_recipe_name_whatever_version_the_tree_names() {
let images = built_images();
let built = Built::new(&images, &[]);
let merged = built.merge(vec![
// PV in the tree differs from what the build recorded.
inventory("busybox", "1.36", &["core-image-minimal", "rescue-image"]),
inventory("dropbear", "2024.85", &["core-image-minimal"]),
inventory("tool", "1.0", &["rescue-image"]),
SbomEntry::new("t".into(), "serde".into(), "1.0".into(), "cargo".into()),
]);
let by_name = |n: &str| merged.iter().find(|e| e.name == n).unwrap();
let busybox = by_name("busybox");
assert_eq!(busybox.version, "1.36.1");
assert_eq!(
busybox.in_image.as_ref().map(|i| i.basis),
Some(InImageBasis::Built)
);
assert!(busybox.evidence[0].starts_with("Yocto recipe inventory"));
// The image the SPDX does not cover keeps its declaration as evidence.
assert!(busybox.evidence.iter().any(
|l| l.starts_with(InImageBasis::Declared.describe()) && l.ends_with("rescue-image")
));
// The built image's declaration is gone: the build says where it is.
assert!(!busybox
.evidence
.iter()
.any(|l| l.starts_with(InImageBasis::Declared.describe())
&& l.contains("core-image-minimal")));
// Declared in the built image but not installed by the build: unmarked.
assert!(by_name("dropbear").in_image.is_none());
assert_eq!(by_name("dropbear").evidence.len(), 1);
// Another image's declaration is left alone.
assert_eq!(
by_name("tool").in_image.as_ref().map(|i| i.images.clone()),
Some(vec!["rescue-image".to_string()])
);
// Built only: added. Not a recipe component: untouched.
assert!(merged
.iter()
.any(|e| e.name == "openssl" && e.version == "3.5.9"));
assert_eq!(by_name("serde").package_manager, "cargo");
assert_eq!(merged.iter().filter(|e| e.name == "busybox").count(), 1);
}
#[test]
fn nvd_is_asked_with_the_built_version_and_cpe() {
let images = built_images();
let built = Built::new(&images, &[]);
let stale = NvdQuery {
name: "busybox".into(),
version: "1.36".into(),
cve_version: "1.36".into(),
products: vec![],
};
let other = NvdQuery {
name: "zlib".into(),
version: "1.3".into(),
cve_version: "1.3".into(),
products: vec![],
};
let (queries, unversioned) = built.nvd_queries(vec![stale, other]);
let names: Vec<(&str, &str)> = queries
.iter()
.map(|q| (q.name.as_str(), q.version.as_str()))
.collect();
assert!(names.contains(&("zlib", "1.3")), "{names:?}");
assert!(names.contains(&("busybox", "1.36.1")), "{names:?}");
assert!(!names.contains(&("busybox", "1.36")));
let openssl = queries.iter().find(|q| q.name == "openssl").unwrap();
assert_eq!(
openssl.products,
[CpeProduct {
vendor: Some("openssl".into()),
product: "openssl".into()
}]
);
// The package group has no CPE: nothing to ask, nothing missing.
assert!(!queries.iter().any(|q| q.name == "packagegroup-core-boot"));
assert!(unversioned.is_empty());
}
#[test]
fn a_cve_the_build_patched_is_stated_fixed() {
let images = built_images();
let built = Built::new(&images, &[]);
let alert = |package: &str, cve: &str| {
CveAlert::new(
cve.into(),
"t".into(),
package.into(),
"1.36.1".into(),
compliance_core::models::CveSource::Nvd,
)
};
let statements = built.statements(
&[],
&[
alert("busybox", "CVE-2022-48174"),
alert("busybox", "CVE-2099-0001"),
],
);
assert_eq!(statements.len(), 1);
assert_eq!(statements[0].0, "CVE-2022-48174");
assert_eq!(statements[0].1.status, VexStatus::Fixed);
assert!(statements[0].1.by_scan);
}
#[test]
fn cpe_products_are_read_from_cpe_names() {
assert_eq!(
product("cpe:2.3:*:*:busybox:1.36.1:*:*:*:*:*:*:*"),
Some(CpeProduct {
vendor: None,
product: "busybox".into()
})
);
assert_eq!(product("cpe:2.3:a:*:*:1:*"), None);
assert_eq!(product("cpe:/a:x:y"), None);
}
fn checks() -> Vec<CveCheck> {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../fixtures/yocto/core-image-minimal-qemuarm64.rootfs.cve.json");
vec![crate::pipeline::yocto_cve_check::read(&path).unwrap()]
}
fn alert(package: &str, version: &str, cve: &str) -> CveAlert {
CveAlert::new(
cve.into(),
"t".into(),
package.into(),
version.into(),
compliance_core::models::CveSource::Nvd,
)
}
#[test]
fn yoctos_own_verdict_comes_first() {
let images = built_images();
let checks = checks();
let built = Built::new(&images, &checks);
let statements = built.statements(
&[],
&[
// Patched, with the reason.
alert("glibc", "2.39+git", "CVE-2024-2961"),
// Ignored as disputed: still to be assessed, with the note.
alert("glibc", "2.39+git", "CVE-2019-1010022"),
// Ignored as not applicable to the configuration.
alert("zlib", "1.3.1", "CVE-2026-22184"),
// Unpatched: no statement.
alert("glibc", "2.39+git", "CVE-2026-5450"),
],
);
let by_cve = |cve: &str| statements.iter().find(|(c, _)| c == cve).map(|(_, v)| v);
let patched = by_cve("CVE-2024-2961").unwrap();
assert_eq!(patched.status, VexStatus::Fixed);
assert!(patched
.impact_statement
.as_deref()
.unwrap()
.starts_with("Yocto cve-check: Patched (cpe-stable-backport)"));
assert_eq!(
by_cve("CVE-2019-1010022").unwrap().status,
VexStatus::UnderInvestigation
);
assert_eq!(
by_cve("CVE-2026-22184").unwrap().status,
VexStatus::NotAffected
);
assert!(by_cve("CVE-2026-5450").is_none());
}
#[test]
fn unpatched_cves_the_match_missed_are_added() {
let images = built_images();
let checks = checks();
let built = Built::new(&images, &checks);
let have = [alert("glibc", "2.39+git", "CVE-2026-5450")];
let missing = built.unpatched_missing(&have, |name| name != "zlib");
assert_eq!(missing.len(), 1);
let (name, version, cves) = &missing[0];
assert_eq!((name.as_str(), version.as_str()), ("glibc", "2.39+git"));
let ids: Vec<&str> = cves.iter().map(|c| c.id.as_str()).collect();
assert_eq!(ids, ["CVE-2010-4756", "CVE-2026-5928"]);
assert_eq!(cves[1].cvss, Some(7.5));
// A recipe that is not a component of the scan gets nothing.
assert!(built.unpatched_missing(&have, |_| false).is_empty());
}
#[test]
fn the_kernel_report_filtered_by_compiled_files_settles_kernel_cves() {
// Yocto's improve_kernel_cve_report.py over a real scarthgap kernel
// (linux-yocto 6.6.151) with its compiled sources and the kernel
// CNA's data, trimmed to two CVEs of each verdict.
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../fixtures/yocto/linux-yocto.improved-cve-report.json");
let checks = vec![crate::pipeline::yocto_cve_check::read(&path).unwrap()];
let built = Built::new(&[], &checks);
let version = "6.6.151+git";
let status = |cve: &str| {
built
.statements(&[], &[alert("linux-yocto", version, cve)])
.first()
.map(|(_, v)| (v.status, v.justification))
};
// Its files are not compiled into this kernel.
assert_eq!(
status("CVE-2023-52586"),
Some((
VexStatus::NotAffected,
Some(VexJustification::VulnerableCodeNotPresent)
))
);
// Withdrawn by the kernel's CNA.
assert_eq!(
status("CVE-2021-46907").map(|s| s.0),
Some(VexStatus::NotAffected)
);
// Outside the affected versions: not affected, not "fixed".
assert_eq!(
status("CVE-2024-0053"),
Some((
VexStatus::NotAffected,
Some(VexJustification::VulnerableCodeNotPresent)
))
);
assert_eq!(
status("CVE-2019-25160").map(|s| s.0),
Some(VexStatus::Fixed)
);
assert_eq!(
status("CVE-2022-48669").map(|s| s.0),
Some(VexStatus::Fixed)
);
// In range and not patched: open.
assert_eq!(status("CVE-2024-42067"), None);
}
#[test]
fn the_spdx3_vex_settles_what_it_says_does_not_affect() {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../fixtures/yocto/core-image-minimal-qemuarm64.rootfs.spdx3.json");
let images = crate::pipeline::yocto_spdx3::read(&path, "t").unwrap();
let built = Built::new(&images, &[]);
let statements = built.statements(
&[],
&[
alert("glibc", "2.39+git", "CVE-2019-1010022"),
alert("busybox", "1.36.1", "CVE-2022-48174"),
],
);
let by_cve = |cve: &str| statements.iter().find(|(c, _)| c == cve).map(|(_, v)| v);
let glibc = by_cve("CVE-2019-1010022").unwrap();
assert_eq!(glibc.status, VexStatus::NotAffected);
assert!(glibc
.impact_statement
.as_deref()
.unwrap()
.starts_with("Yocto SPDX 3.0 VEX: not affected"));
assert_eq!(by_cve("CVE-2022-48174").unwrap().status, VexStatus::Fixed);
}
}
@@ -0,0 +1,184 @@
//! What Yocto's own CVE check says about an image: its `cve-check` JSON.
//!
//! With `INHERIT += "cve-check"` a build matches every recipe against NVD
//! and writes, next to the image, `<image>.json`: per recipe (`package`)
//! its version and the CVEs NVD records for its products, each `Patched`
//! (a patch or the version fixes it), `Ignored` (a CVE_STATUS sets it aside,
//! with the reason as `detail`) or `Unpatched`. Unlike the SPDX's
//! "CVEs fixed", this covers every CVE the build looked at, with Yocto's
//! reason.
//!
//! [`read`] parses the file; [`is_cve_check`] recognises one among a target's
//! build outputs.
use std::io::Read;
use std::path::Path;
use serde::Deserialize;
/// Bytes a cve-check JSON may have (a large product image's is ~50 MB).
pub const MAX_BYTES: u64 = 256 * 1024 * 1024;
/// Yocto's verdict on one CVE of one recipe.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
pub enum CheckStatus {
Patched,
Unpatched,
Ignored,
}
/// One CVE of one recipe, as cve-check reports it.
#[derive(Debug, Clone, Deserialize)]
pub struct CheckedIssue {
pub id: String,
pub status: CheckStatus,
/// The CVE_STATUS reason (`fixed-version`, `cpe-stable-backport`,
/// `not-applicable-config`, `disputed`, …), where one applies.
#[serde(default)]
pub detail: Option<String>,
/// The CVE_STATUS note the recipe gives with it.
#[serde(default)]
pub description: Option<String>,
/// NVD's description.
#[serde(default)]
pub summary: Option<String>,
/// CVSS v3 base score as text (`"9.8"`, `"0.0"` for none).
#[serde(default)]
pub scorev3: Option<String>,
}
impl CheckedIssue {
/// The CVSS v3 base score, `None` when NVD gives none.
pub fn cvss(&self) -> Option<f64> {
self.scorev3
.as_deref()
.and_then(|s| s.parse::<f64>().ok())
.filter(|s| *s > 0.0)
}
}
/// One recipe of the image.
#[derive(Debug, Clone, Deserialize)]
pub struct CheckedPackage {
pub name: String,
pub version: String,
#[serde(default, rename = "issue")]
pub issues: Vec<CheckedIssue>,
}
/// A cve-check report.
#[derive(Debug, Clone, Deserialize)]
pub struct CveCheck {
#[serde(rename = "package")]
pub packages: Vec<CheckedPackage>,
}
/// Why a cve-check JSON could not be read.
#[derive(Debug, thiserror::Error)]
pub enum CveCheckError {
#[error("cannot read the cve-check report: {0}")]
Io(#[from] std::io::Error),
#[error("the cve-check report is larger than {MAX_BYTES} bytes")]
TooLarge,
#[error("not a Yocto cve-check JSON report: {0}")]
NotCveCheck(String),
}
/// Whether the file starting with `head` is a cve-check report: a JSON
/// object whose first keys include `package` or `version`.
pub fn is_cve_check(head: &[u8]) -> bool {
let text = String::from_utf8_lossy(head);
let text = text.trim_start();
text.starts_with('{') && (text.contains("\"package\"") || text.contains("\"version\""))
}
/// Read the cve-check report at `path`.
///
/// # Errors
///
/// The file cannot be read, is larger than [`MAX_BYTES`], or is not a
/// cve-check report.
pub fn read(path: &Path) -> Result<CveCheck, CveCheckError> {
let file = std::fs::File::open(path)?;
let mut bytes = Vec::new();
file.take(MAX_BYTES + 1).read_to_end(&mut bytes)?;
if bytes.len() as u64 > MAX_BYTES {
return Err(CveCheckError::TooLarge);
}
serde_json::from_slice(&bytes).map_err(|e| CveCheckError::NotCveCheck(e.to_string()))
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
/// A trimmed copy of a real scarthgap (5.0.21) core-image-minimal's
/// cve-check report: glibc, busybox and zlib with each status.
fn fixture() -> std::path::PathBuf {
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../fixtures/yocto/core-image-minimal-qemuarm64.rootfs.cve.json")
}
#[test]
fn the_report_lists_each_recipe_with_yoctos_verdicts() {
let check = read(&fixture()).unwrap();
let names: Vec<(&str, &str)> = check
.packages
.iter()
.map(|p| (p.name.as_str(), p.version.as_str()))
.collect();
assert_eq!(
names,
[
("glibc", "2.39+git"),
("busybox", "1.36.1"),
("zlib", "1.3.1")
]
);
let glibc = &check.packages[0];
let status = |id: &str| glibc.issues.iter().find(|i| i.id == id).unwrap();
assert_eq!(status("CVE-2024-2961").status, CheckStatus::Patched);
assert_eq!(
status("CVE-2024-2961").detail.as_deref(),
Some("cpe-stable-backport")
);
assert_eq!(status("CVE-2019-1010022").status, CheckStatus::Ignored);
assert_eq!(
status("CVE-2019-1010022").detail.as_deref(),
Some("disputed")
);
assert!(status("CVE-2019-1010022").description.is_some());
let unpatched: Vec<&str> = glibc
.issues
.iter()
.filter(|i| i.status == CheckStatus::Unpatched)
.map(|i| i.id.as_str())
.collect();
assert_eq!(
unpatched,
["CVE-2010-4756", "CVE-2026-5450", "CVE-2026-5928"]
);
assert_eq!(status("CVE-2026-5450").cvss(), Some(9.8));
// "0.0" is no score.
assert_eq!(status("CVE-2010-4756").cvss(), None);
}
#[test]
fn a_report_is_recognised_by_its_start() {
let head = std::fs::read(fixture()).unwrap();
assert!(is_cve_check(&head[..64.min(head.len())]));
assert!(!is_cve_check(&[0x28, 0xb5, 0x2f, 0xfd]));
assert!(!is_cve_check(b"[1, 2]"));
}
#[test]
fn something_else_is_refused() {
let dir = std::env::temp_dir().join(format!("cs-cvecheck-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("x.json");
std::fs::write(&path, br#"{"spdxVersion": "SPDX-2.2"}"#).unwrap();
assert!(matches!(read(&path), Err(CveCheckError::NotCveCheck(_))));
let _ = std::fs::remove_dir_all(&dir);
}
}
@@ -323,7 +323,7 @@ impl RecipeVersion {
/// The release part of a PV: what precedes a git or SCM suffix or a variable
/// the tree does not define (`1.0+git${SRCPV}` → `1.0`). `None` when nothing
/// is left (`git`, `+git`).
fn release_of(pv: &str) -> Option<String> {
pub(crate) fn release_of(pv: &str) -> Option<String> {
let end = ["${", "+git", "AUTOINC", "+svn", "+hg", "+cvs"]
.iter()
.filter_map(|marker| pv.find(marker))
@@ -820,7 +820,7 @@ pub fn nvd_queries(recipes: &[Recipe]) -> (Vec<NvdQuery>, Vec<String>) {
/// set aside (`upstream-wontfix`, `disputed`, `ignored`) `under_investigation`
/// with the reason as a note. `unpatched` and `vulnerable-investigation` make
/// none: the alert stays open for a person to assess.
fn status_statement(status: &str) -> Option<(VexStatus, Option<VexJustification>)> {
pub(crate) fn status_statement(status: &str) -> Option<(VexStatus, Option<VexJustification>)> {
match status {
"backported-patch" | "cpe-stable-backport" | "fixed-version" => {
Some((VexStatus::Fixed, None))
@@ -829,6 +829,8 @@ fn status_statement(status: &str) -> Option<(VexStatus, Option<VexJustification>
VexStatus::NotAffected,
Some(VexJustification::ComponentNotPresent),
)),
// The CVE was withdrawn by its CNA (Yocto's kernel CVE report).
"rejected" => Some((VexStatus::NotAffected, None)),
"not-applicable-platform" | "not-applicable-config" => Some((
VexStatus::NotAffected,
Some(VexJustification::VulnerableCodeNotPresent),
@@ -842,7 +844,7 @@ fn status_statement(status: &str) -> Option<(VexStatus, Option<VexJustification>
}
/// A statement the scan makes, saying where it comes from.
fn scan_statement(
pub(crate) fn scan_statement(
status: VexStatus,
justification: Option<VexJustification>,
because: String,
@@ -17,123 +17,20 @@ pub const RULE_EOL: &str = "yocto-release-eol";
/// The rule of a release whose end of life is near: within six months for an
/// LTS release, two for any other ([`soon_window`]).
pub const RULE_EOL_SOON: &str = "yocto-release-eol-soon";
/// Where the support periods come from.
pub const SOURCE_URL: &str = "https://wiki.yoctoproject.org/wiki/Releases";
/// When [`RELEASES`] was checked against its sources.
pub const CHECKED_ON: &str = "2026-10-09";
/// One Yocto Project release.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReleaseInfo {
/// The codename, lower case.
pub codename: &'static str,
/// The Yocto Project version.
pub version: &'static str,
/// A long term support release.
pub lts: bool,
/// Its release day.
pub released: NaiveDate,
/// The day its support ends (or ended).
pub end_of_life: NaiveDate,
}
/// A day of the table; every date in it is valid, a test checks them.
const fn day(y: i32, m: u32, d: u32) -> NaiveDate {
match NaiveDate::from_ymd_opt(y, m, d) {
Some(date) => date,
None => NaiveDate::MIN,
}
}
const fn release(
codename: &'static str,
version: &'static str,
lts: bool,
released: NaiveDate,
end_of_life: NaiveDate,
) -> ReleaseInfo {
ReleaseInfo {
codename,
version,
lts,
released,
end_of_life,
}
}
/// The bundled release table (`data/eol/yocto.json`): sources and check date
/// in the file, which the weekly CI check compares with endoflife.date.
pub use crate::pipeline::eol_tables::YoctoReleaseInfo as ReleaseInfo;
/// The Yocto Project releases, oldest first.
///
/// Source: the Yocto Project releases wiki, <https://wiki.yoctoproject.org/wiki/Releases>
/// (page last updated 2026-09-10), checked on 2026-10-09: codename, version,
/// LTS and support status. The wiki gives months only; the exact release and
/// end-of-life days are endoflife.date's (<https://endoflife.date/yocto>,
/// checked the same day), which agree with the wiki's months except
/// Walnascar (wiki: "EOL since November 2025", endoflife.date: 2025-12-07).
/// For Thud and older, which endoflife.date does not list, the end of life
/// is the last day of the month of the release's last point release (wiki),
/// and the release day the first of its month. Blacksail (6.1, due October
/// 2026) is not released yet and not listed: a newer branch reads as an
/// unknown release.
pub const RELEASES: &[ReleaseInfo] = &[
release("jethro", "2.0", false, day(2015, 11, 1), day(2017, 1, 31)),
release("krogoth", "2.1", false, day(2016, 4, 1), day(2017, 7, 31)),
release("morty", "2.2", false, day(2016, 11, 1), day(2018, 7, 31)),
release("pyro", "2.3", false, day(2017, 5, 1), day(2018, 7, 31)),
release("rocko", "2.4", false, day(2017, 10, 1), day(2018, 11, 30)),
release("sumo", "2.5", false, day(2018, 4, 1), day(2019, 4, 30)),
release("thud", "2.6", false, day(2018, 11, 1), day(2019, 10, 31)),
release("warrior", "2.7", false, day(2019, 5, 1), day(2020, 6, 1)),
release("zeus", "3.0", false, day(2019, 10, 22), day(2020, 8, 1)),
release("dunfell", "3.1", true, day(2020, 4, 21), day(2024, 4, 30)),
release(
"gatesgarth",
"3.2",
false,
day(2020, 11, 3),
day(2021, 5, 1),
),
release(
"hardknott",
"3.3",
false,
day(2021, 4, 19),
day(2022, 4, 20),
),
release("honister", "3.4", false, day(2021, 10, 25), day(2022, 5, 1)),
release("kirkstone", "4.0", true, day(2022, 4, 25), day(2026, 4, 27)),
release(
"langdale",
"4.1",
false,
day(2022, 10, 23),
day(2023, 5, 27),
),
release(
"mickledore",
"4.2",
false,
day(2023, 5, 3),
day(2023, 11, 5),
),
release("nanbield", "4.3", false, day(2023, 11, 9), day(2024, 6, 9)),
release("scarthgap", "5.0", true, day(2024, 4, 29), day(2028, 4, 30)),
release("styhead", "5.1", false, day(2024, 10, 16), day(2025, 5, 16)),
release("walnascar", "5.2", false, day(2025, 5, 7), day(2025, 12, 7)),
release(
"whinlatter",
"5.3",
false,
day(2025, 12, 15),
day(2026, 6, 15),
),
release("wrynose", "6.0", true, day(2026, 5, 13), day(2030, 4, 30)),
];
fn releases() -> &'static [ReleaseInfo] {
&crate::pipeline::eol_tables::yocto().releases
}
/// The repositories whose branch names the release, most telling first.
const RELEASE_REPOS: &[&str] = &["poky", "openembedded-core", "meta-openembedded"];
fn by_codename(codename: &str) -> Option<&'static ReleaseInfo> {
RELEASES.iter().find(|r| r.codename == codename)
releases().iter().find(|r| r.codename == codename)
}
/// The release a branch or tag names: a codename as one of its words
@@ -150,7 +47,7 @@ pub(crate) fn from_reference(reference: &str) -> Option<&'static ReleaseInfo> {
let version = lower.rsplit('/').next()?.strip_prefix("yocto-")?;
let mut parts = version.split('.');
let major_minor = format!("{}.{}", parts.next()?, parts.next()?);
RELEASES.iter().find(|r| r.version == major_minor)
releases().iter().find(|r| r.version == major_minor)
}
/// The newest of `codenames` the table knows.
@@ -195,8 +92,8 @@ fn conf_of(layer: &Layer) -> String {
/// `None` when none of them names a release the table knows.
pub(crate) fn derive(pins: &[LayerPin], layers: &[Layer]) -> Option<YoctoRelease> {
let make = |info: &ReleaseInfo, basis: ReleaseBasis, file: String| YoctoRelease {
codename: info.codename.to_string(),
version: info.version.to_string(),
codename: info.codename.clone(),
version: info.version.clone(),
lts: info.lts,
end_of_life: info.end_of_life,
basis,
@@ -236,7 +133,7 @@ pub(crate) fn derive(pins: &[LayerPin], layers: &[Layer]) -> Option<YoctoRelease
/// The newest LTS release on `today` whose end of life is not yet soon.
fn current_lts(today: NaiveDate) -> Option<&'static ReleaseInfo> {
let horizon = today.checked_add_months(soon_window(true))?;
RELEASES
releases()
.iter()
.filter(|r| r.lts && r.released <= today && r.end_of_life > horizon)
.max_by_key(|r| r.released)
@@ -280,7 +177,7 @@ pub(crate) fn finding(repo_id: &str, release: &YoctoRelease, today: NaiveDate) -
let eol = release.end_of_life;
let description = format!(
"The layers build Yocto {name} ({version}{lts}), read from {basis}. The Yocto Project \
{status} {eol} (source: {SOURCE_URL}, checked {CHECKED_ON}). After that, no security \
{status} {eol} (source: {source}, checked {checked}). After that, no security \
fixes are published for its recipes, so vulnerabilities in the image's components \
stay open unless every fix is backported by hand.\n\nCRA Annex I Part I (2)(c): \
vulnerabilities can be addressed through security updates; Annex I Part II (2): \
@@ -288,6 +185,8 @@ pub(crate) fn finding(repo_id: &str, release: &YoctoRelease, today: NaiveDate) -
the product's support period.",
version = release.version,
basis = basis_text(&release.basis, &release.file),
source = crate::pipeline::eol_tables::yocto().source,
checked = crate::pipeline::eol_tables::yocto().checked_on,
);
let remediation = match current_lts(today) {
Some(lts) if lts.codename != release.codename => format!(
@@ -296,7 +195,7 @@ pub(crate) fn finding(repo_id: &str, release: &YoctoRelease, today: NaiveDate) -
layers to its branch, and LAYERSERIES_COMPAT of your layers. Until then, \
backport the security fixes the product needs and record them (CVE_STATUS, \
patches).",
display_codename(lts.codename),
display_codename(&lts.codename),
lts.version,
lts.end_of_life
),
@@ -356,10 +255,8 @@ mod tests {
#[test]
fn the_table_is_ordered_and_names_the_required_releases() {
assert!(RELEASES.iter().all(|r| r.released != NaiveDate::MIN
&& r.end_of_life != NaiveDate::MIN
&& r.released < r.end_of_life));
assert!(RELEASES.windows(2).all(|w| w[0].released < w[1].released));
assert!(releases().iter().all(|r| r.released < r.end_of_life));
assert!(releases().windows(2).all(|w| w[0].released < w[1].released));
for codename in [
"dunfell",
"kirkstone",
@@ -373,12 +270,11 @@ mod tests {
] {
assert!(by_codename(codename).is_some(), "{codename}");
}
assert_eq!(date(2026, 10, 9).to_string(), CHECKED_ON);
}
#[test]
fn branches_and_tags_name_their_release() {
let codename = |r: &str| from_reference(r).map(|i| i.codename);
let codename = |r: &str| from_reference(r).map(|i| i.codename.as_str());
assert_eq!(codename("scarthgap"), Some("scarthgap"));
assert_eq!(codename("scarthgap-5.0.3"), Some("scarthgap"));
assert_eq!(codename("yocto-5.0.3"), Some("scarthgap"));
@@ -457,7 +353,7 @@ mod tests {
let info = by_codename(codename).expect("known");
YoctoRelease {
codename: codename.into(),
version: info.version.into(),
version: info.version.clone(),
lts: info.lts,
end_of_life: info.end_of_life,
basis: ReleaseBasis::Pin {
@@ -484,7 +380,9 @@ mod tests {
assert!(f
.description
.contains("\"dunfell\" that kas.yml pins poky to"));
assert!(f.description.contains(SOURCE_URL));
assert!(f
.description
.contains("https://wiki.yoctoproject.org/wiki/Releases"));
assert!(f.description.contains("Annex I Part I (2)(c)"));
assert!(f.description.contains("Part II"));
assert_eq!(f.file_path.as_deref(), Some("kas.yml"));
+650
View File
@@ -0,0 +1,650 @@
//! What a Yocto build put into an image, read from the build's own SPDX 2.2.
//!
//! Yocto's `create-spdx` class (the default since kirkstone; scarthgap writes
//! SPDX 2.2) archives one document per image, binary package, recipe and
//! runtime set into `<image>.spdx.tar.zst` next to the image. The image
//! document `CONTAINS` the packages that are installed, each package is
//! `GENERATED_FROM` its recipe, and the documents point at each other through
//! `externalDocumentRefs` by namespace. Unlike the recipe inventory
//! ([`crate::pipeline::yocto_inventory`]), which reads the recipes as written,
//! this is what the build resolved: overrides, PACKAGECONFIG and the machine
//! applied, only what is in the image.
//!
//! [`read_archive`] (or [`read_dir`] for an extracted archive) returns one
//! [`BuiltImage`] per image document: an SBOM component per recipe with
//! packages in the image (recipe version, declared licence, the CPEs NVD
//! knows it by), marked [`InImageBasis::Built`], and the CVEs the recipe's
//! patches fix (`sourceInfo: "CVEs fixed: …"`), which settle those CVEs as
//! fixed. References that cannot be resolved are listed, not guessed.
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::io::Read;
use std::path::Path;
use serde::Deserialize;
use compliance_core::models::{InImage, InImageBasis, SbomEntry, YOCTO_RECIPE_MANAGER};
use compliance_core::purl::encode;
/// Where a component read from the build's SPDX comes from, on its evidence.
pub const SOURCE: &str = "Yocto build SPDX";
/// The scan run's stage id for the build's image SPDX.
pub const STAGE: &str = "build_spdx";
/// Limits on an uploaded archive: it is untrusted input.
#[derive(Debug, Clone, Copy)]
pub struct ReadLimits {
/// Documents read at most.
pub max_documents: usize,
/// Bytes one document may have once decompressed.
pub max_document_bytes: u64,
/// Bytes all documents may have together once decompressed.
pub max_total_bytes: u64,
}
impl Default for ReadLimits {
fn default() -> Self {
// A core-image-minimal archive holds ~380 documents and ~11 MB; a
// large product image a few thousand.
Self {
max_documents: 20_000,
max_document_bytes: 64 * 1024 * 1024,
max_total_bytes: 1024 * 1024 * 1024,
}
}
}
/// Why the build's SPDX could not be read.
#[derive(Debug, thiserror::Error)]
pub enum YoctoSpdxError {
#[error("cannot read the SPDX archive: {0}")]
Io(#[from] std::io::Error),
#[error("the SPDX archive exceeds its limits: {0}")]
TooLarge(&'static str),
#[error("{file} is not an SPDX 2.2 JSON document: {reason}")]
NotSpdx { file: String, reason: String },
#[error("no image document (an SPDX package `SPDXRef-Image-…`) in the archive")]
NoImage,
}
/// One image as the build made it.
#[derive(Debug, Clone)]
pub struct BuiltImage {
/// The image recipe (`core-image-minimal`).
pub image: String,
/// The image document's package id, which carries the machine and build
/// time (`SPDXRef-Image-core-image-minimal-qemuarm64.rootfs-…`).
pub image_id: String,
/// One component per recipe with packages in the image, sorted by name.
pub entries: Vec<SbomEntry>,
/// The CVEs the recipes' patches fix, per component, sorted.
pub fixed: Vec<FixedCve>,
/// Packages the image contains whose documents are not in the archive,
/// or whose recipe is not (`missing-pkg`), sorted.
pub unresolved: Vec<String>,
/// The CVEs the build's SPDX states do not affect a component (SPDX 3.0
/// VEX), sorted; SPDX 2.2 states none.
pub not_affected: Vec<NotAffectedCve>,
}
/// A CVE the build's SPDX says does not affect a component, and why.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct NotAffectedCve {
pub component: String,
pub version: String,
pub cve: String,
/// The SPDX 3.0 justification (`vulnerableCodeNotPresent`, …).
pub justification: Option<String>,
/// The impact statement (`This issue has kernel fixes …`).
pub statement: Option<String>,
}
/// A CVE a recipe's patch fixes in the component built from it.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct FixedCve {
pub component: String,
pub version: String,
pub cve: String,
}
/// Read the images of a `<image>.spdx.tar.zst` archive.
///
/// # Errors
///
/// The archive cannot be read, exceeds `limits`, holds a document that is
/// not SPDX JSON, or holds no image document.
pub fn read_archive(
archive: &Path,
repo_id: &str,
limits: ReadLimits,
) -> Result<Vec<BuiltImage>, YoctoSpdxError> {
let file = std::fs::File::open(archive)?;
let decoder = zstd::stream::read::Decoder::new(file)?;
let mut tar = tar::Archive::new(decoder);
let mut documents = Vec::new();
let mut total = 0u64;
for entry in tar.entries()? {
let entry = entry?;
if !entry.header().entry_type().is_file() {
continue;
}
let name = entry.path()?.to_string_lossy().into_owned();
if !name.ends_with(".spdx.json") {
continue;
}
if documents.len() >= limits.max_documents {
return Err(YoctoSpdxError::TooLarge("too many documents"));
}
// `take` caps what is read whatever the header claims.
let mut bytes = Vec::new();
entry
.take(limits.max_document_bytes + 1)
.read_to_end(&mut bytes)?;
if bytes.len() as u64 > limits.max_document_bytes {
return Err(YoctoSpdxError::TooLarge("a document is too large"));
}
total += bytes.len() as u64;
if total > limits.max_total_bytes {
return Err(YoctoSpdxError::TooLarge(
"the documents are too large together",
));
}
documents.push((name, bytes));
}
images(&parse(documents)?, repo_id)
}
/// Read the images of an extracted archive: every `*.spdx.json` directly in
/// `dir`.
///
/// # Errors
///
/// As [`read_archive`].
pub fn read_dir(
dir: &Path,
repo_id: &str,
limits: ReadLimits,
) -> Result<Vec<BuiltImage>, YoctoSpdxError> {
let mut documents = Vec::new();
let mut total = 0u64;
let mut paths: Vec<_> = std::fs::read_dir(dir)?
.filter_map(Result::ok)
.map(|e| e.path())
.filter(|p| p.is_file() && p.to_string_lossy().ends_with(".spdx.json"))
.collect();
paths.sort();
if paths.len() > limits.max_documents {
return Err(YoctoSpdxError::TooLarge("too many documents"));
}
for path in paths {
let size = std::fs::metadata(&path)?.len();
if size > limits.max_document_bytes {
return Err(YoctoSpdxError::TooLarge("a document is too large"));
}
total += size;
if total > limits.max_total_bytes {
return Err(YoctoSpdxError::TooLarge(
"the documents are too large together",
));
}
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
documents.push((name, std::fs::read(&path)?));
}
images(&parse(documents)?, repo_id)
}
/// An SPDX 2.2 document, as far as it is read here.
#[derive(Debug, Deserialize)]
struct Document {
#[serde(rename = "documentNamespace")]
namespace: String,
#[serde(default)]
packages: Vec<Package>,
#[serde(default)]
relationships: Vec<Relationship>,
#[serde(default, rename = "externalDocumentRefs")]
external: Vec<ExternalRef>,
}
#[derive(Debug, Deserialize)]
struct Package {
#[serde(rename = "SPDXID")]
id: String,
name: String,
#[serde(default, rename = "versionInfo")]
version: Option<String>,
#[serde(default, rename = "licenseDeclared")]
license: Option<String>,
#[serde(default, rename = "externalRefs")]
refs: Vec<PackageRef>,
#[serde(default, rename = "sourceInfo")]
source_info: Option<String>,
#[serde(default)]
homepage: Option<String>,
}
#[derive(Debug, Deserialize)]
struct PackageRef {
#[serde(rename = "referenceType")]
kind: String,
#[serde(rename = "referenceLocator")]
locator: String,
}
#[derive(Debug, Deserialize)]
struct Relationship {
#[serde(rename = "spdxElementId")]
from: String,
#[serde(rename = "relationshipType")]
kind: String,
#[serde(rename = "relatedSpdxElement")]
to: String,
}
#[derive(Debug, Deserialize)]
struct ExternalRef {
#[serde(rename = "externalDocumentId")]
id: String,
#[serde(rename = "spdxDocument")]
namespace: String,
}
/// The documents by namespace.
fn parse(documents: Vec<(String, Vec<u8>)>) -> Result<HashMap<String, Document>, YoctoSpdxError> {
let mut by_namespace = HashMap::with_capacity(documents.len());
for (file, bytes) in documents {
let doc: Document =
serde_json::from_slice(&bytes).map_err(|e| YoctoSpdxError::NotSpdx {
file: file.clone(),
reason: e.to_string(),
})?;
by_namespace.insert(doc.namespace.clone(), doc);
}
Ok(by_namespace)
}
/// The package `local` of the document `doc` refers to as `reference`
/// (`DocumentRef-busybox:SPDXRef-Package-busybox`), with its document.
fn resolve<'a>(
docs: &'a HashMap<String, Document>,
doc: &Document,
reference: &str,
) -> Option<(&'a Document, &'a Package)> {
let (doc_ref, local) = reference.split_once(':')?;
let namespace = &doc.external.iter().find(|e| e.id == doc_ref)?.namespace;
let target = docs.get(namespace)?;
let package = target.packages.iter().find(|p| p.id == local)?;
Some((target, package))
}
/// Every image of `docs`.
fn images(
docs: &HashMap<String, Document>,
repo_id: &str,
) -> Result<Vec<BuiltImage>, YoctoSpdxError> {
let mut out = Vec::new();
for doc in docs.values() {
for image in doc
.packages
.iter()
.filter(|p| p.id.starts_with("SPDXRef-Image-"))
{
out.push(built_image(docs, doc, image, repo_id));
}
}
if out.is_empty() {
return Err(YoctoSpdxError::NoImage);
}
out.sort_by(|a, b| a.image_id.cmp(&b.image_id));
Ok(out)
}
/// A recipe with packages in the image, and those packages.
struct RecipeInImage<'a> {
recipe: &'a Package,
packages: BTreeSet<&'a str>,
}
/// The image `image` of the document `doc`.
fn built_image(
docs: &HashMap<String, Document>,
doc: &Document,
image: &Package,
repo_id: &str,
) -> BuiltImage {
let mut recipes: BTreeMap<(String, String), RecipeInImage<'_>> = BTreeMap::new();
let mut unresolved = BTreeSet::new();
let contained = doc
.relationships
.iter()
.filter(|r| r.from == image.id && r.kind == "CONTAINS");
for rel in contained {
let Some((package_doc, package)) = resolve(docs, doc, &rel.to) else {
unresolved.insert(package_name(&rel.to));
continue;
};
let recipe = package_doc
.relationships
.iter()
.filter(|r| r.from == package.id && r.kind == "GENERATED_FROM")
.find_map(|r| resolve(docs, package_doc, &r.to))
.map(|(_, recipe)| recipe)
.filter(|recipe| recipe.id.starts_with("SPDXRef-Recipe-"));
let Some(recipe) = recipe else {
unresolved.insert(package.name.clone());
continue;
};
let version = recipe
.version
.clone()
.or_else(|| package.version.clone())
.unwrap_or_default();
recipes
.entry((recipe.name.clone(), version))
.or_insert_with(|| RecipeInImage {
recipe,
packages: BTreeSet::new(),
})
.packages
.insert(package.name.as_str());
}
let mut entries = Vec::with_capacity(recipes.len());
let mut fixed = Vec::new();
for ((name, version), found) in &recipes {
let facts = ComponentFacts {
name,
version,
license: found.recipe.license.as_deref(),
cpe: cpes(found.recipe).into_iter().next(),
homepage: found.recipe.homepage.as_deref(),
packages: found.packages.iter().copied().collect(),
};
let label = image.id.trim_start_matches("SPDXRef-Image-");
entries.push(component(facts, &image.name, label, repo_id));
fixed.extend(fixed_cves(found.recipe).into_iter().map(|cve| FixedCve {
component: name.clone(),
version: version.clone(),
cve,
}));
}
fixed.sort();
BuiltImage {
image: image.name.clone(),
image_id: image.id.clone(),
entries,
fixed,
unresolved: unresolved.into_iter().collect(),
not_affected: Vec::new(),
}
}
/// What the build's SPDX (2.2 or 3.0) says about one recipe in the image.
pub(crate) struct ComponentFacts<'a> {
pub name: &'a str,
pub version: &'a str,
/// The declared licence as written (document prefixes are dropped here).
pub license: Option<&'a str>,
/// The first CPE 2.3 name it is known by.
pub cpe: Option<String>,
pub homepage: Option<&'a str>,
/// Its packages in the image, sorted.
pub packages: Vec<&'a str>,
}
/// The SBOM component of one recipe in the image `image`, whose SPDX the
/// evidence names as `label` (the image document's id).
pub(crate) fn component(
facts: ComponentFacts<'_>,
image: &str,
label: &str,
repo_id: &str,
) -> SbomEntry {
let (name, version) = (facts.name, facts.version);
let mut entry = SbomEntry::new(
repo_id.to_string(),
name.to_string(),
version.to_string(),
YOCTO_RECIPE_MANAGER.to_string(),
);
entry.purl = Some(if version.is_empty() {
format!("pkg:generic/{}", encode(name))
} else {
format!("pkg:generic/{}@{}", encode(name), encode(version))
});
entry.license = facts.license.and_then(license);
entry.cpe = facts.cpe;
entry.manufacturer_url = facts
.homepage
.filter(|h| h.starts_with("https://") || h.starts_with("http://"))
.map(str::to_string);
entry.evidence.push(format!(
"{SOURCE} ({label}): packages {}",
facts.packages.join(", ")
));
let in_image = InImage {
basis: InImageBasis::Built,
images: vec![image.to_string()],
};
entry.evidence.push(in_image.describe());
entry.in_image = Some(in_image);
entry
}
/// The package name of an unresolved reference
/// (`DocumentRef-x:SPDXRef-Package-busybox` → `busybox`).
fn package_name(reference: &str) -> String {
let local = reference.split_once(':').map_or(reference, |(_, l)| l);
local
.strip_prefix("SPDXRef-Package-")
.unwrap_or(local)
.to_string()
}
/// A declared licence as an SPDX expression, without the document prefix of
/// a licence defined in another document (`DocumentRef-recipe-busybox:
/// LicenseRef-bzip2-1.0.4` → `LicenseRef-bzip2-1.0.4`); `None` for
/// NOASSERTION, NONE or nothing.
pub(crate) fn license(declared: &str) -> Option<String> {
let cleaned: Vec<String> = declared
.split_whitespace()
.map(|token| {
let (open, rest) = token.split_at(token.len() - token.trim_start_matches('(').len());
let inner = rest.trim_end_matches(')');
let close = &rest[inner.len()..];
let inner = match inner.split_once(':') {
Some((doc, id)) if doc.starts_with("DocumentRef-") => id,
_ => inner,
};
format!("{open}{inner}{close}")
})
.collect();
let expression = cleaned.join(" ");
match expression.as_str() {
"" | "NOASSERTION" | "NONE" => None,
_ => Some(expression),
}
}
/// The CPE 2.3 names a recipe is known by (CVE_PRODUCT), in order.
fn cpes(recipe: &Package) -> Vec<String> {
recipe
.refs
.iter()
.filter(|r| r.kind.ends_with("cpe23Type"))
.map(|r| r.locator.clone())
.collect()
}
/// The CVEs a recipe's patches fix: create-spdx writes them into the
/// recipe's `sourceInfo` as `CVEs fixed: CVE-… CVE-…`.
fn fixed_cves(recipe: &Package) -> Vec<String> {
let Some(rest) = recipe
.source_info
.as_deref()
.and_then(|s| s.split_once("CVEs fixed:"))
.map(|(_, rest)| rest)
else {
return Vec::new();
};
let mut cves: Vec<String> = rest
.split(|c: char| c.is_whitespace() || c == ',')
.filter(|t| t.starts_with("CVE-") && t.len() > 4)
.map(str::to_string)
.collect();
cves.sort();
cves.dedup();
cves
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use std::path::PathBuf;
/// A trimmed copy of a real scarthgap (5.0.21) core-image-minimal for
/// qemuarm64: four recipes and one package whose document is missing.
fn fixtures() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixtures/yocto")
}
fn check(images: &[BuiltImage]) {
assert_eq!(images.len(), 1);
let image = &images[0];
assert_eq!(image.image, "core-image-minimal");
assert!(image.image_id.contains("qemuarm64"), "{}", image.image_id);
let names: Vec<(&str, &str)> = image
.entries
.iter()
.map(|e| (e.name.as_str(), e.version.as_str()))
.collect();
assert_eq!(
names,
[
("base-files", "3.0.14"),
("busybox", "1.36.1"),
("openssl", "3.5.9"),
("packagegroup-core-boot", "1.0"),
]
);
let busybox = &image.entries[1];
assert_eq!(busybox.package_manager, YOCTO_RECIPE_MANAGER);
assert_eq!(busybox.purl.as_deref(), Some("pkg:generic/busybox@1.36.1"));
assert_eq!(
busybox.license.as_deref(),
Some("GPL-2.0-only AND LicenseRef-bzip2-1.0.4")
);
assert_eq!(
busybox.cpe.as_deref(),
Some("cpe:2.3:*:*:busybox:1.36.1:*:*:*:*:*:*:*")
);
let in_image = busybox.in_image.as_ref().expect("in the image");
assert_eq!(in_image.basis, InImageBasis::Built);
assert_eq!(in_image.images, ["core-image-minimal"]);
// Its three packages are one component.
assert!(
busybox.evidence[0].ends_with("packages busybox, busybox-syslog, busybox-udhcpc"),
"{:?}",
busybox.evidence
);
let openssl = &image.entries[2];
assert_eq!(
openssl.cpe.as_deref(),
Some("cpe:2.3:*:openssl:openssl:3.5.9:*:*:*:*:*:*:*")
);
// A package group has no CPE: NVD knows nothing by that name.
assert_eq!(image.entries[3].cpe, None);
let busybox_fixed: Vec<&str> = image
.fixed
.iter()
.filter(|f| f.component == "busybox")
.map(|f| f.cve.as_str())
.collect();
assert_eq!(busybox_fixed.len(), 15);
assert!(busybox_fixed.contains(&"CVE-2022-48174"));
assert!(busybox_fixed.windows(2).all(|w| w[0] < w[1]), "sorted");
assert_eq!(image.unresolved, ["missing-pkg"]);
}
#[test]
fn an_extracted_archive_lists_what_the_build_installed() {
let images = read_dir(
&fixtures().join("spdx-scarthgap"),
"t",
ReadLimits::default(),
)
.unwrap();
check(&images);
}
#[test]
fn the_image_archive_reads_the_same() {
let images = read_archive(
&fixtures().join("core-image-minimal-qemuarm64.rootfs.spdx.tar.zst"),
"t",
ReadLimits::default(),
)
.unwrap();
check(&images);
}
#[test]
fn an_archive_past_its_limits_is_refused() {
let archive = fixtures().join("core-image-minimal-qemuarm64.rootfs.spdx.tar.zst");
let few = ReadLimits {
max_documents: 3,
..ReadLimits::default()
};
assert!(matches!(
read_archive(&archive, "t", few),
Err(YoctoSpdxError::TooLarge(_))
));
let small = ReadLimits {
max_document_bytes: 100,
..ReadLimits::default()
};
assert!(matches!(
read_archive(&archive, "t", small),
Err(YoctoSpdxError::TooLarge(_))
));
}
#[test]
fn documents_without_an_image_or_not_spdx_are_refused() {
let docs = vec![(
"recipe-x.spdx.json".to_string(),
br#"{"documentNamespace": "urn:x", "packages": [{"SPDXID": "SPDXRef-Recipe-x", "name": "x"}]}"#.to_vec(),
)];
assert!(matches!(
images(&parse(docs).unwrap(), "t"),
Err(YoctoSpdxError::NoImage)
));
let broken = vec![("a.spdx.json".to_string(), b"{".to_vec())];
assert!(matches!(parse(broken), Err(YoctoSpdxError::NotSpdx { .. })));
}
#[test]
fn licences_lose_the_document_prefix_and_noassertion_is_none() {
assert_eq!(
license("GPL-2.0-only AND DocumentRef-recipe-busybox:LicenseRef-bzip2-1.0.4")
.as_deref(),
Some("GPL-2.0-only AND LicenseRef-bzip2-1.0.4")
);
assert_eq!(
license("(MIT OR DocumentRef-r:LicenseRef-x)").as_deref(),
Some("(MIT OR LicenseRef-x)")
);
assert_eq!(license("NOASSERTION"), None);
assert_eq!(license(" "), None);
}
}
@@ -0,0 +1,395 @@
//! What a Yocto build put into an image, read from the build's own SPDX 3.0.
//!
//! With `create-spdx-3.0` (the default from Styhead 5.1 on, available in
//! Scarthgap) a build writes one JSON-LD document per image,
//! `<image>.rootfs.spdx.json`, holding the whole graph:
//!
//! - the image is a `software_Package` whose purpose is `archive`, output
//! (`hasOutput`) of the rootfs `build_Build`;
//! - the packages installed in it are that build's inputs (`hasInput`), each
//! a `software_Package` of purpose `install` with its version, CPE and
//! homepage, its licence through `hasConcludedLicense`;
//! - each package is output of its recipe's build,
//! `<recipe>:do_create_spdx:recipe`;
//! - the build's VEX: `security_Vulnerability` elements with their CVE id,
//! `fixedIn` and `doesNotAffect` assessments on the packages.
//!
//! [`read`] returns the same [`BuiltImage`] as the SPDX 2.2 reader
//! ([`crate::pipeline::yocto_spdx`]), with the not-affected statements too.
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::io::Read as _;
use std::path::Path;
use serde::{Deserialize, Deserializer};
use crate::pipeline::yocto_spdx::{
component, BuiltImage, ComponentFacts, FixedCve, NotAffectedCve, YoctoSpdxError,
};
/// Bytes an SPDX 3.0 image document may have (core-image-minimal's is
/// ~7 MB; a product image with sources listed can be far larger).
pub const MAX_BYTES: u64 = 512 * 1024 * 1024;
/// Whether the file starting with `head` is an SPDX 3 JSON-LD document.
pub fn is_spdx3(head: &[u8]) -> bool {
let text = String::from_utf8_lossy(head);
text.trim_start().starts_with('{')
&& text.contains("\"@context\"")
&& text.contains("spdx.org/rdf/3")
}
/// One element of the graph, as far as it is read here.
#[derive(Debug, Deserialize)]
struct Element {
#[serde(rename = "type", default)]
kind: String,
#[serde(rename = "spdxId", default)]
id: Option<String>,
#[serde(default)]
name: Option<String>,
#[serde(rename = "software_primaryPurpose", default)]
purpose: Option<String>,
#[serde(rename = "software_packageVersion", default)]
version: Option<String>,
#[serde(rename = "software_homePage", default)]
homepage: Option<String>,
#[serde(rename = "externalIdentifier", default)]
identifiers: Vec<Identifier>,
#[serde(default)]
from: Option<String>,
#[serde(default, deserialize_with = "one_or_many")]
to: Vec<String>,
#[serde(rename = "relationshipType", default)]
relationship: Option<String>,
#[serde(rename = "simplelicensing_licenseExpression", default)]
license_expression: Option<String>,
#[serde(rename = "security_impactStatement", default)]
impact: Option<String>,
#[serde(rename = "security_justificationType", default)]
justification: Option<String>,
}
#[derive(Debug, Deserialize)]
struct Identifier {
#[serde(rename = "externalIdentifierType")]
kind: String,
identifier: String,
}
/// `to` is a list, or one id.
fn one_or_many<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<String>, D::Error> {
#[derive(Deserialize)]
#[serde(untagged)]
enum OneOrMany {
One(String),
Many(Vec<String>),
}
Ok(match Option::<OneOrMany>::deserialize(deserializer)? {
Some(OneOrMany::One(id)) => vec![id],
Some(OneOrMany::Many(ids)) => ids,
None => Vec::new(),
})
}
#[derive(Debug, Deserialize)]
struct Document {
#[serde(rename = "@graph")]
graph: Vec<Element>,
}
/// Read the images of an SPDX 3.0 image document.
///
/// # Errors
///
/// The file cannot be read, is larger than [`MAX_BYTES`], is not an SPDX 3
/// JSON-LD document, or names no image.
pub fn read(path: &Path, repo_id: &str) -> Result<Vec<BuiltImage>, YoctoSpdxError> {
let mut bytes = Vec::new();
std::fs::File::open(path)?
.take(MAX_BYTES + 1)
.read_to_end(&mut bytes)?;
if bytes.len() as u64 > MAX_BYTES {
return Err(YoctoSpdxError::TooLarge(
"the SPDX 3.0 document is too large",
));
}
let file = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let doc: Document = serde_json::from_slice(&bytes).map_err(|e| YoctoSpdxError::NotSpdx {
file,
reason: e.to_string(),
})?;
images(&doc.graph, repo_id)
}
/// The graph's elements by id, and its relationships.
struct Graph<'a> {
by_id: HashMap<&'a str, &'a Element>,
relationships: Vec<&'a Element>,
}
impl<'a> Graph<'a> {
fn new(elements: &'a [Element]) -> Self {
let mut by_id = HashMap::with_capacity(elements.len());
let mut relationships = Vec::new();
for e in elements {
if let Some(id) = e.id.as_deref() {
by_id.insert(id, e);
}
if e.relationship.is_some() {
relationships.push(e);
}
}
Self {
by_id,
relationships,
}
}
/// The relationships of `kind`.
fn of(&self, kind: &'a str) -> impl Iterator<Item = &'a Element> + '_ {
self.relationships
.iter()
.copied()
.filter(move |r| r.relationship.as_deref() == Some(kind))
}
}
/// Every image of `elements`.
fn images(elements: &[Element], repo_id: &str) -> Result<Vec<BuiltImage>, YoctoSpdxError> {
let graph = Graph::new(elements);
let mut out: Vec<BuiltImage> = elements
.iter()
.filter(|e| e.kind == "software_Package" && e.purpose.as_deref() == Some("archive"))
.filter_map(|image| built_image(&graph, image, repo_id))
.collect();
if out.is_empty() {
return Err(YoctoSpdxError::NoImage);
}
out.sort_by(|a, b| a.image_id.cmp(&b.image_id));
Ok(out)
}
/// The image `image`, if a build outputs it.
fn built_image(graph: &Graph<'_>, image: &Element, repo_id: &str) -> Option<BuiltImage> {
let image_id = image.id.as_deref()?;
let image_name = image.name.clone().unwrap_or_default();
// The builds whose output the image is (the rootfs build).
let rootfs: BTreeSet<&str> = graph
.of("hasOutput")
.filter(|r| r.to.iter().any(|t| t == image_id))
.filter_map(|r| r.from.as_deref())
.collect();
let installed: BTreeSet<&str> = graph
.of("hasInput")
.filter(|r| r.from.as_deref().is_some_and(|f| rootfs.contains(f)))
.flat_map(|r| r.to.iter().map(String::as_str))
.collect();
if rootfs.is_empty() {
return None;
}
// Each package's recipe: the name of the recipe build that outputs it.
let mut recipe_of: HashMap<&str, &str> = HashMap::new();
for r in graph.of("hasOutput") {
let Some(build) = r.from.as_deref().and_then(|f| graph.by_id.get(f)) else {
continue;
};
let Some(recipe) = build
.name
.as_deref()
.and_then(|n| n.strip_suffix(":do_create_spdx:recipe"))
else {
continue;
};
for t in &r.to {
recipe_of.insert(t.as_str(), recipe);
}
}
let license_of: HashMap<&str, &str> = graph
.of("hasConcludedLicense")
.filter_map(|r| {
let expression =
r.to.iter()
.filter_map(|t| graph.by_id.get(t.as_str()))
.find_map(|e| e.license_expression.as_deref())?;
Some((r.from.as_deref()?, expression))
})
.collect();
/// A recipe with packages in the image.
struct Found<'a> {
package: &'a Element,
packages: BTreeSet<&'a str>,
ids: BTreeSet<&'a str>,
}
let mut recipes: BTreeMap<(&str, &str), Found<'_>> = BTreeMap::new();
let mut unresolved = BTreeSet::new();
for id in &installed {
let package = graph.by_id.get(id).copied();
let recipe = package.and_then(|_| recipe_of.get(id).copied());
let (Some(package), Some(recipe)) = (package, recipe) else {
unresolved.insert(package_name(id));
continue;
};
if package.purpose.as_deref() != Some("install") {
continue;
}
let version = package.version.as_deref().unwrap_or_default();
let found = recipes.entry((recipe, version)).or_insert_with(|| Found {
package,
packages: BTreeSet::new(),
ids: BTreeSet::new(),
});
found
.packages
.insert(package.name.as_deref().unwrap_or_default());
found.ids.insert(*id);
}
// The CVE ids of the vulnerabilities, and what the VEX says per package.
let cve_of = |id: &str| -> Option<&str> {
graph.by_id.get(id)?.identifiers.iter().find_map(|i| {
(i.kind == "cve" || i.identifier.starts_with("CVE-")).then_some(i.identifier.as_str())
})
};
let mut entries = Vec::with_capacity(recipes.len());
let mut fixed = BTreeSet::new();
let mut not_affected = BTreeSet::new();
for ((recipe, version), found) in &recipes {
let facts = ComponentFacts {
name: recipe,
version,
license: found.ids.iter().find_map(|id| license_of.get(id).copied()),
cpe: found
.package
.identifiers
.iter()
.find(|i| i.kind == "cpe23")
.map(|i| i.identifier.clone()),
homepage: found.package.homepage.as_deref(),
packages: found.packages.iter().copied().collect(),
};
let label = format!("{image_name}, SPDX 3.0");
entries.push(component(facts, &image_name, &label, repo_id));
for r in graph.of("fixedIn") {
if r.to.iter().any(|t| found.ids.contains(t.as_str())) {
if let Some(cve) = r.from.as_deref().and_then(cve_of) {
fixed.insert(FixedCve {
component: recipe.to_string(),
version: version.to_string(),
cve: cve.to_string(),
});
}
}
}
for r in graph.of("doesNotAffect") {
if r.to.iter().any(|t| found.ids.contains(t.as_str())) {
if let Some(cve) = r.from.as_deref().and_then(cve_of) {
not_affected.insert(NotAffectedCve {
component: recipe.to_string(),
version: version.to_string(),
cve: cve.to_string(),
justification: r.justification.clone(),
statement: r.impact.clone(),
});
}
}
}
}
Some(BuiltImage {
image: image_name,
image_id: image_id.to_string(),
entries,
fixed: fixed.into_iter().collect(),
unresolved: unresolved.into_iter().collect(),
not_affected: not_affected.into_iter().collect(),
})
}
/// The package name at the end of a package id (`…/package/busybox`).
fn package_name(id: &str) -> String {
id.rsplit('/').next().unwrap_or(id).to_string()
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use compliance_core::models::{InImageBasis, YOCTO_RECIPE_MANAGER};
/// A trimmed copy of a real Scarthgap (5.0.21) core-image-minimal for
/// qemuarm64 built with create-spdx-3.0: six recipes and one installed
/// package whose element is missing.
fn fixture() -> std::path::PathBuf {
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../fixtures/yocto/core-image-minimal-qemuarm64.rootfs.spdx3.json")
}
#[test]
fn the_spdx3_image_lists_what_the_build_installed() {
let images = read(&fixture(), "t").unwrap();
assert_eq!(images.len(), 1);
let image = &images[0];
assert_eq!(image.image, "core-image-minimal");
let names: Vec<(&str, &str)> = image
.entries
.iter()
.map(|e| (e.name.as_str(), e.version.as_str()))
.collect();
assert_eq!(
names,
[
("base-files", "3.0.14"),
("busybox", "1.36.1"),
("glibc", "2.39+git"),
("libxml2", "2.12.10"),
("openssl", "3.5.9"),
("packagegroup-core-boot", "1.0"),
]
);
let busybox = &image.entries[1];
assert_eq!(busybox.package_manager, YOCTO_RECIPE_MANAGER);
assert_eq!(
busybox.cpe.as_deref(),
Some("cpe:2.3:*:*:busybox:1.36.1:*:*:*:*:*:*:*")
);
assert!(busybox.license.is_some());
assert_eq!(
busybox.in_image.as_ref().map(|i| i.basis),
Some(InImageBasis::Built)
);
assert!(
busybox.evidence[0].ends_with("packages busybox, busybox-syslog, busybox-udhcpc"),
"{:?}",
busybox.evidence
);
// libc6 and ldconfig are one glibc component.
assert!(image.entries[2].evidence[0].ends_with("packages ldconfig, libc6"));
assert!(image
.fixed
.iter()
.any(|f| f.component == "busybox" && f.cve == "CVE-2022-48174"));
let glibc_not_affected: Vec<&NotAffectedCve> = image
.not_affected
.iter()
.filter(|n| n.component == "glibc")
.collect();
assert!(!glibc_not_affected.is_empty());
assert!(glibc_not_affected.iter().all(|n| n.cve.starts_with("CVE-")));
assert_eq!(image.unresolved, ["missing-pkg"]);
}
#[test]
fn an_spdx3_document_is_recognised_by_its_start() {
let head = std::fs::read(fixture()).unwrap();
assert!(is_spdx3(&head[..400.min(head.len())]));
assert!(!is_spdx3(br#"{"package": [], "version": "1"}"#));
assert!(!is_spdx3(&[0x28, 0xb5, 0x2f, 0xfd]));
}
}
+215 -4
View File
@@ -24,6 +24,14 @@ use compliance_core::AgentConfig;
/// How long an entitlement answer is trusted before it is re-fetched.
pub const ENTITLEMENT_TTL: Duration = Duration::from_secs(60);
/// The most API-key verdicts held at once. Callers choose the keys, so an
/// unbounded cache of invalid ones would grow without end.
const API_KEY_CACHE_MAX: usize = 10_000;
/// How long an API-key verdict is reused. A revoked key therefore keeps
/// working for up to this long; past it, an unreachable registry means `503`.
pub const API_KEY_TTL: Duration = Duration::from_secs(60);
/// Refresh the service token this long before it expires.
const TOKEN_MARGIN: Duration = Duration::from_secs(30);
/// Upper bound for one registry or Keycloak token request. Without it a hung
@@ -77,7 +85,7 @@ pub struct AuditEntry {
pub product: String,
/// What happened, e.g. `pruefwerk.support_access`.
pub action: String,
/// `user`, or `staff` for BreakPilot support.
/// `user`, `staff` for BreakPilot support, or `apikey`.
pub actor_type: String,
pub actor_id: String,
pub actor_name: String,
@@ -89,6 +97,17 @@ pub struct AuditEntry {
#[serde(skip_serializing_if = "String::is_empty")]
pub target_name: String,
pub metadata: serde_json::Value,
/// The caller's address, when the agent knows it; the registry otherwise
/// records the address of the agent itself.
#[serde(skip_serializing_if = "String::is_empty")]
pub source_ip: String,
}
/// The cache key for an API key: its SHA-256, hex. The key itself is never
/// held longer than the request.
fn key_digest(key: &str) -> String {
use sha2::{Digest, Sha256};
hex::encode(Sha256::digest(key.as_bytes()))
}
impl AuditEntry {
@@ -96,19 +115,33 @@ impl AuditEntry {
pub fn by(
ctx: &compliance_core::TenantContext,
action: &str,
metadata: serde_json::Value,
mut metadata: serde_json::Value,
) -> Self {
let actor_type = match (&ctx.staff, &ctx.api_key) {
(Some(_), _) => "staff",
(None, Some(key)) => {
// Who the caller says it acts for: informational only.
if let (Some(on_behalf_of), Some(map)) =
(&key.on_behalf_of, metadata.as_object_mut())
{
map.insert("on_behalf_of".to_string(), on_behalf_of.clone().into());
}
"apikey"
}
(None, None) => "user",
};
Self {
tenant_id: ctx.tenant_id.clone(),
product: "pruefwerk".to_string(),
action: action.to_string(),
actor_type: if ctx.staff.is_some() { "staff" } else { "user" }.to_string(),
actor_type: actor_type.to_string(),
actor_id: ctx.user_id.clone(),
actor_name: ctx.actor_label(),
target_type: String::new(),
target_id: String::new(),
target_name: String::new(),
metadata,
source_ip: String::new(),
}
}
@@ -122,6 +155,9 @@ impl AuditEntry {
}
}
/// The registry's answer for a portal-issued API key (tenant-registry ADR
/// 0001). Everything but `valid` defaults, so an older registry that sends
/// only `valid`, `tenant_id`, `product` and `scopes` still decodes.
#[derive(Debug, Clone, Deserialize)]
pub struct ApiKeyVerify {
pub valid: bool,
@@ -129,8 +165,26 @@ pub struct ApiKeyVerify {
pub tenant_id: String,
#[serde(default)]
pub product: String,
/// Already intersected with the tenant's entitlements; empty for a
/// halted or archived tenant.
#[serde(default)]
pub scopes: Vec<String>,
#[serde(default)]
pub key_id: String,
/// `personal` or `service`, as the registry labels it.
#[serde(default)]
pub kind: String,
/// Who the key was issued to, for the history and the audit log.
#[serde(default)]
pub holder: Option<String>,
#[serde(default)]
pub expires_at: Option<String>,
/// The tenant's ladder status (`active`, `restricted`, ...).
#[serde(default)]
pub tenant_status: String,
/// A key issued before scopes existed: it carries none.
#[serde(default)]
pub legacy: bool,
}
#[derive(Debug, Clone, Serialize)]
@@ -161,6 +215,9 @@ pub struct RegistryClient {
cache: DashMap<String, (Instant, EntitlementCheck)>,
/// Each tenant's projects, for [`ENTITLEMENT_TTL`].
projects: DashMap<String, (Instant, Vec<compliance_core::models::Project>)>,
/// API-key verdicts, valid and invalid, keyed by the key's SHA-256 (never
/// the key itself), for [`API_KEY_TTL`].
api_keys: DashMap<String, (Instant, ApiKeyVerify)>,
}
impl std::fmt::Debug for RegistryClient {
@@ -203,6 +260,7 @@ impl RegistryClient {
token: Mutex::new(None),
cache: DashMap::new(),
projects: DashMap::new(),
api_keys: DashMap::new(),
}))
}
@@ -270,6 +328,10 @@ impl RegistryClient {
if let Some(tok) = self.bearer().await? {
rb = rb.bearer_auth(tok);
}
// traceparent: the registry's spans join this request's trace.
for (name, value) in compliance_core::telemetry::trace_context_headers() {
rb = rb.header(name, value);
}
Ok(rb)
}
@@ -445,14 +507,48 @@ impl RegistryClient {
Ok(page.items)
}
/// Verify a portal-issued API key (`bp_…`).
/// Verify a portal-issued API key (`bp_…`), valid or not, reusing a
/// verdict younger than [`API_KEY_TTL`].
///
/// # Errors
///
/// The registry could not answer and no fresh verdict is cached. The
/// message never contains the key.
pub async fn verify_api_key(&self, key: &str) -> Result<ApiKeyVerify, String> {
let digest = key_digest(key);
if let Some(entry) = self.api_keys.get(&digest) {
if entry.0.elapsed() < API_KEY_TTL {
return Ok(entry.1.clone());
}
}
let verdict = self.fetch_api_key_verdict(key).await?;
self.cache_api_key_verdict(digest, &verdict);
Ok(verdict)
}
/// Keep `verdict` under `digest`. At [`API_KEY_CACHE_MAX`] the expired
/// verdicts go first; if none have, this one is not kept (the request
/// still gets it).
fn cache_api_key_verdict(&self, digest: String, verdict: &ApiKeyVerify) {
if self.api_keys.len() >= API_KEY_CACHE_MAX {
self.api_keys
.retain(|_, (at, _)| at.elapsed() < API_KEY_TTL);
if self.api_keys.len() >= API_KEY_CACHE_MAX {
return;
}
}
self.api_keys
.insert(digest, (Instant::now(), verdict.clone()));
}
async fn fetch_api_key_verdict(&self, key: &str) -> Result<ApiKeyVerify, String> {
let resp = self
.request(reqwest::Method::POST, "/v1/internal/api-keys/verify")
.await?
.json(&serde_json::json!({ "key": key }))
.send()
.await
// reqwest's error names the URL, never the body.
.map_err(|e| format!("api-key verify failed: {e}"))?;
if !resp.status().is_success() {
return Err(format!("api-key verify returned {}", resp.status()));
@@ -574,6 +670,7 @@ mod tests {
token: Mutex::new(None),
cache: DashMap::new(),
projects: DashMap::new(),
api_keys: DashMap::new(),
};
let started = Instant::now();
@@ -586,4 +683,118 @@ mod tests {
started.elapsed()
);
}
/// A registry whose verify endpoint counts its calls and can be taken
/// down (500). Every key is valid for tenant `t`.
async fn verify_registry() -> (
RegistryClient,
Arc<std::sync::atomic::AtomicUsize>,
Arc<std::sync::atomic::AtomicBool>,
) {
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
let calls = Arc::new(AtomicUsize::new(0));
let down = Arc::new(AtomicBool::new(false));
let (c, d) = (calls.clone(), down.clone());
let app = axum::Router::new().route(
"/v1/internal/api-keys/verify",
axum::routing::post(move |axum::Json(body): axum::Json<serde_json::Value>| {
let (c, d) = (c.clone(), d.clone());
async move {
c.fetch_add(1, Ordering::SeqCst);
if d.load(Ordering::SeqCst) {
return Err(axum::http::StatusCode::INTERNAL_SERVER_ERROR);
}
let valid = body["key"] != "bp_revoked";
Ok(axum::Json(serde_json::json!({
"valid": valid,
"tenant_id": "t",
"scopes": ["pruefwerk:findings.read"],
})))
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let client = RegistryClient {
base_url: format!("http://{addr}"),
product: "pruefwerk".into(),
http: reqwest::Client::new(),
token_url: None,
client_id: None,
client_secret: None,
token: Mutex::new(None),
cache: DashMap::new(),
projects: DashMap::new(),
api_keys: DashMap::new(),
};
(client, calls, down)
}
#[tokio::test]
async fn api_key_verdicts_are_reused_valid_or_not() {
use std::sync::atomic::Ordering;
let (client, calls, _) = verify_registry().await;
for _ in 0..3 {
assert!(client.verify_api_key("bp_good").await.unwrap().valid);
assert!(!client.verify_api_key("bp_revoked").await.unwrap().valid);
}
assert_eq!(calls.load(Ordering::SeqCst), 2);
}
#[tokio::test]
async fn an_unreachable_registry_is_bridged_only_by_a_fresh_verdict() {
use std::sync::atomic::Ordering;
let (client, _, down) = verify_registry().await;
client.verify_api_key("bp_good").await.unwrap();
down.store(true, Ordering::SeqCst);
// Warm: served from the cache.
assert!(client.verify_api_key("bp_good").await.unwrap().valid);
// Cold: nothing to fall back on.
assert!(client.verify_api_key("bp_other").await.is_err());
// Expired: as cold, so a revocation is never outlived by an outage.
for mut entry in client.api_keys.iter_mut() {
entry.0 = Instant::now()
.checked_sub(API_KEY_TTL + Duration::from_secs(1))
.unwrap();
}
let err = client.verify_api_key("bp_good").await.unwrap_err();
assert!(!err.contains("bp_good"), "{err}");
}
#[tokio::test]
async fn a_full_cache_drops_expired_verdicts_and_never_grows_past_its_cap() {
let (client, _, _) = verify_registry().await;
let verdict = client.verify_api_key("bp_good").await.unwrap();
let aged = Instant::now()
.checked_sub(API_KEY_TTL + Duration::from_secs(1))
.unwrap();
for i in 0..API_KEY_CACHE_MAX {
client
.api_keys
.insert(format!("old-{i}"), (aged, verdict.clone()));
}
client.verify_api_key("bp_new").await.unwrap();
assert!(client.api_keys.len() < 10, "{}", client.api_keys.len());
assert!(client.api_keys.contains_key(&key_digest("bp_new")));
// Full of fresh verdicts: the new one is answered but not kept.
for i in 0..API_KEY_CACHE_MAX {
client
.api_keys
.insert(format!("new-{i}"), (Instant::now(), verdict.clone()));
}
let before = client.api_keys.len();
assert!(client.verify_api_key("bp_newer").await.unwrap().valid);
assert_eq!(client.api_keys.len(), before);
}
#[tokio::test]
async fn the_cache_holds_a_digest_never_the_key() {
let (client, _, _) = verify_registry().await;
client.verify_api_key("bp_good").await.unwrap();
assert!(!client.api_keys.contains_key("bp_good"));
assert!(client.api_keys.contains_key(&key_digest("bp_good")));
assert!(client.api_keys.iter().all(|e| !e.key().contains("bp_")));
}
}
+25 -15
View File
@@ -31,9 +31,15 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError>
tenant_count = tenants.len(),
"Scheduled scan: tenants resolved"
);
for tenant_id in tenants {
scan_all_repos(&agent, &tenant_id).await;
}
// Every tenant and target at once: each scan waits for one of the
// `SCAN_CONCURRENCY` slots, so a slow repository holds one slot,
// not the whole tick (#61).
futures_util::future::join_all(
tenants
.iter()
.map(|tenant_id| scan_all_repos(&agent, tenant_id)),
)
.await;
})
})
.map_err(|e| AgentError::Scheduler(format!("Failed to create scan job: {e}")))?;
@@ -232,18 +238,22 @@ async fn scan_all_repos(agent: &ComplianceAgent, tenant_id: &str) {
let targets: Vec<_> = cursor.filter_map(|r| async { r.ok() }).collect().await;
for target in targets {
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
if let Err(e) = agent
.run_target_scan(tenant_id, &target_id, ScanTrigger::Scheduled)
.await
{
tracing::error!(
"Scheduled scan failed for {} (tenant '{tenant_id}'): {e}",
target.name
);
}
}
// Started together; the scan slots (`SCAN_CONCURRENCY`) decide how many
// run, and each scan's start jitter spreads them out.
futures_util::stream::iter(targets)
.for_each_concurrent(None, |target| async move {
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
if let Err(e) = agent
.run_target_scan(tenant_id, &target_id, ScanTrigger::Scheduled)
.await
{
tracing::error!(
"Scheduled scan failed for {} (tenant '{tenant_id}'): {e}",
target.name
);
}
})
.await;
}
async fn monitor_cves(agent: &ComplianceAgent, tenant_id: &str) {
+2
View File
@@ -101,6 +101,7 @@ pub fn uploaded_artifact(
ArtifactKind::FirmwareImage => Artifact::firmware_image(filename),
ArtifactKind::SourceArchive => Artifact::source_archive(filename),
ArtifactKind::MobilePackage => Artifact::mobile_package(filename),
ArtifactKind::BuildOutput => Artifact::build_output(filename),
_ => return None,
};
artifact.stored_path = Some(stored_path.to_string_lossy().to_string());
@@ -131,6 +132,7 @@ pub fn reference_artifact(
Artifact::plc_project(source_ref, plc_format.unwrap_or(PlcFormat::PlcopenXml))
}
ArtifactKind::PlaintextDescription => Artifact::plaintext(source_ref),
ArtifactKind::BuildOutput => Artifact::build_output(source_ref),
}
}
+260
View File
@@ -0,0 +1,260 @@
//! Portal-issued API keys on the customer API (tenant-registry ADR 0001):
//! the key middleware, the JWT middleware, the entitlement gate, the write
//! audit and the status ladder, in the server's order, against a fake tenant
//! registry and a live Mongo (for the agent itself); skips cleanly without
//! one. The route → scope table is covered in `role_gate`'s router tests.
#![allow(clippy::expect_used, clippy::unwrap_used)]
mod common;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use axum::body::Body;
use axum::extract::{Request, State};
use axum::http::StatusCode;
use axum::middleware::{from_fn, from_fn_with_state};
use axum::routing::{get, post};
use axum::{Extension, Json, Router};
use tower::ServiceExt;
use compliance_agent::agent::ComplianceAgent;
use compliance_agent::api::api_key_gate::require_api_key;
use compliance_agent::api::server::{audit_delegated_writes, require_entitlement};
use compliance_agent::database::DatabasePool;
use compliance_core::auth::{require_jwt_auth, require_tenant_status, JwksState};
use compliance_core::{TenantContext, SUPPORT_TENANT_HEADER};
use common::dev_config;
/// What the fake registry was asked: the path of every call, and the bodies
/// of audit entries.
#[derive(Default)]
struct Seen {
paths: Vec<String>,
audits: Vec<serde_json::Value>,
}
type Shared = Arc<Mutex<Seen>>;
const TENANT: &str = "11111111-1111-1111-1111-111111111111";
/// The registry's verify answer for `key`, or `None` to fail with 500.
fn verdict(key: &str) -> Option<serde_json::Value> {
let status = match key {
"bp_good" => "active",
"bp_restricted" => "restricted",
"bp_revoked" => return Some(serde_json::json!({ "valid": false })),
_ => return None,
};
Some(serde_json::json!({
"valid": true,
"tenant_id": TENANT,
"product": "pruefwerk",
"scopes": ["pruefwerk:findings.write"],
"key_id": "k-1",
"kind": "service",
"holder": "CI pipeline",
"tenant_status": status,
"legacy": false,
}))
}
async fn fake_registry(seen: Shared) -> String {
let app = Router::new()
.route(
"/v1/internal/api-keys/verify",
post(
|State(seen): State<Shared>, Json(body): Json<serde_json::Value>| async move {
seen.lock().unwrap().paths.push("verify".into());
verdict(body["key"].as_str().unwrap_or_default())
.map(Json)
.ok_or(StatusCode::INTERNAL_SERVER_ERROR)
},
),
)
.route(
"/v1/internal/entitlements/check",
post(|State(seen): State<Shared>| async move {
seen.lock().unwrap().paths.push("entitlement".into());
Json(serde_json::json!({ "allowed": true, "status": "active" }))
}),
)
.route(
"/v1/audit",
post(
|State(seen): State<Shared>, Json(body): Json<serde_json::Value>| async move {
seen.lock().unwrap().audits.push(body);
StatusCode::CREATED
},
),
)
.with_state(seen);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
format!("http://{addr}")
}
/// An agent whose registry is `registry`, or `None` without Mongo.
async fn agent(registry: &str) -> Option<Arc<ComplianceAgent>> {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db_name = format!("key_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
let Ok(pool) = DatabasePool::connect(&uri, &db_name).await else {
eprintln!("SKIP api_key_access: no MongoDB reachable at {uri}");
return None;
};
let mut config = dev_config(uri, db_name);
config.tenant_registry_url = Some(registry.to_string());
Some(Arc::new(ComplianceAgent::new(config, pool)))
}
/// `/r` answers the tenant the request runs in, for reads and writes.
fn app(agent: Arc<ComplianceAgent>) -> Router {
let tenant = |Extension(ctx): Extension<TenantContext>| async move { ctx.tenant_id };
// Same order as the server, without the role gate.
Router::new()
.route("/r", get(tenant).patch(tenant))
.layer(from_fn(require_tenant_status))
.layer(from_fn_with_state(agent.clone(), audit_delegated_writes))
.layer(from_fn_with_state(agent.clone(), require_entitlement))
.layer(from_fn(require_jwt_auth))
.layer(from_fn_with_state(agent, require_api_key))
// Never reached: no test presents a well-formed JWT.
.layer(Extension(JwksState::new(
"http://127.0.0.1:9/jwks".into(),
None,
None,
)))
}
async fn call(
agent: &Arc<ComplianceAgent>,
method: &str,
bearer: &str,
headers: &[(&str, &str)],
) -> (StatusCode, String) {
let mut req = Request::builder()
.method(method)
.uri("/r")
.header("authorization", format!("Bearer {bearer}"));
for (name, value) in headers {
req = req.header(*name, *value);
}
let resp = app(agent.clone())
.oneshot(req.body(Body::empty()).unwrap())
.await
.unwrap();
let status = resp.status();
let bytes = axum::body::to_bytes(resp.into_body(), 1 << 16)
.await
.unwrap();
(status, String::from_utf8_lossy(&bytes).into_owned())
}
#[tokio::test]
async fn a_key_works_in_its_own_tenant_only() {
let seen: Shared = Arc::default();
let base = fake_registry(seen.clone()).await;
let Some(agent) = agent(&base).await else {
return;
};
// The tenant comes from the registry; the support header names another.
let other = "22222222-2222-2222-2222-222222222222";
let (status, body) = call(&agent, "GET", "bp_good", &[(SUPPORT_TENANT_HEADER, other)]).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, TENANT);
// Within the TTL the registry is not asked again, and the entitlement
// check is never asked for a key.
let (status, _) = call(&agent, "GET", "bp_good", &[]).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(seen.lock().unwrap().paths, ["verify"]);
}
#[tokio::test]
async fn a_rejected_key_or_a_jwt_never_gets_a_key_context() {
let seen: Shared = Arc::default();
let base = fake_registry(seen.clone()).await;
let Some(agent) = agent(&base).await else {
return;
};
let (status, body) = call(&agent, "GET", "bp_revoked", &[]).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert!(body.contains("invalid_api_key"), "{body}");
// Not a key: the JWT middleware refuses it, and the registry's key
// verify is not asked.
let calls = seen.lock().unwrap().paths.len();
let (status, _) = call(&agent, "GET", "not-a-jwt", &[]).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(seen.lock().unwrap().paths.len(), calls);
}
#[tokio::test]
async fn a_cold_cache_and_an_unreachable_registry_mean_503() {
let seen: Shared = Arc::default();
let base = fake_registry(seen).await;
let Some(agent) = agent(&base).await else {
return;
};
let (status, body) = call(&agent, "GET", "bp_unreachable", &[]).await;
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
assert!(!body.contains("bp_unreachable"), "{body}");
}
#[tokio::test]
async fn a_restricted_tenant_reads_but_does_not_write() {
let seen: Shared = Arc::default();
let base = fake_registry(seen).await;
let Some(agent) = agent(&base).await else {
return;
};
assert_eq!(
call(&agent, "GET", "bp_restricted", &[]).await.0,
StatusCode::OK
);
assert_eq!(
call(&agent, "PATCH", "bp_restricted", &[]).await.0,
StatusCode::PAYMENT_REQUIRED
);
}
#[tokio::test]
async fn a_key_write_is_audited_as_the_key() {
let seen: Shared = Arc::default();
let base = fake_registry(seen.clone()).await;
let Some(agent) = agent(&base).await else {
return;
};
let (status, _) = call(
&agent,
"PATCH",
"bp_good",
&[("x-bp-actor", "jdoe"), ("x-bp-client-ip", "203.0.113.7")],
)
.await;
assert_eq!(status, StatusCode::OK);
// The audit is posted in the background.
let mut audit = None;
for _ in 0..50 {
audit = seen.lock().unwrap().audits.first().cloned();
if audit.is_some() {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
let audit = audit.expect("audit entry posted");
assert_eq!(audit["action"], "pruefwerk.api_key_write");
assert_eq!(audit["actor_type"], "apikey");
assert_eq!(audit["actor_id"], "apikey:k-1");
assert_eq!(audit["actor_name"], "CI pipeline");
assert_eq!(audit["metadata"]["on_behalf_of"], "jdoe");
assert_eq!(audit["tenant_id"], TENANT);
assert_eq!(audit["source_ip"], "203.0.113.7");
}
+8
View File
@@ -161,6 +161,14 @@ impl TestServer {
&self.db_name
}
/// The database the API reads and writes for the unauthenticated dev
/// tenant (`<db_name>_dev`, M7.2-D). Tests that seed data directly must
/// write here; `db_name()` alone is never opened by the agent.
#[allow(dead_code)] // not every test binary seeds data
pub fn tenant_db_name(&self) -> String {
format!("{}_dev", self.db_name)
}
/// Drop every per-tenant database belonging to this test run.
/// Post-M7.2-D the agent never opens a `db_name` directly —
/// data lives only in `<db_name>_<tenant>` per-tenant databases.
@@ -6,7 +6,7 @@ async fn insert_dast_target(server: &TestServer, repo_id: &str, name: &str) -> S
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let db = client.database(server.db_name());
let db = client.database(&server.tenant_db_name());
let result = db
.collection::<mongodb::bson::Document>("dast_targets")
@@ -30,7 +30,7 @@ async fn insert_pentest_session(server: &TestServer, target_id: &str, repo_id: &
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let db = client.database(server.db_name());
let db = client.database(&server.tenant_db_name());
let result = db
.collection::<mongodb::bson::Document>("pentest_sessions")
@@ -54,7 +54,7 @@ async fn insert_attack_node(server: &TestServer, session_id: &str) {
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let db = client.database(server.db_name());
let db = client.database(&server.tenant_db_name());
db.collection::<mongodb::bson::Document>("attack_chain_nodes")
.insert_one(mongodb::bson::doc! {
@@ -73,7 +73,7 @@ async fn insert_dast_finding(server: &TestServer, target_id: &str, session_id: &
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let db = client.database(server.db_name());
let db = client.database(&server.tenant_db_name());
db.collection::<mongodb::bson::Document>("dast_findings")
.insert_one(mongodb::bson::doc! {
@@ -99,7 +99,7 @@ async fn count_docs(server: &TestServer, collection: &str) -> u64 {
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let db = client.database(server.db_name());
let db = client.database(&server.tenant_db_name());
db.collection::<mongodb::bson::Document>(collection)
.count_documents(mongodb::bson::doc! {})
.await
@@ -175,7 +175,7 @@ async fn delete_repo_cascades_sast_findings_and_sbom() {
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let db = client.database(server.db_name());
let db = client.database(&server.tenant_db_name());
let now = mongodb::bson::DateTime::now();
db.collection::<mongodb::bson::Document>("findings")
@@ -18,7 +18,7 @@ async fn add_and_list_dast_targets() {
&json!({
"name": "test-app",
"base_url": "https://test-app.example.com",
"target_type": "webapp",
"target_type": "web_app",
}),
)
.await;
@@ -14,7 +14,7 @@ async fn insert_finding(server: &TestServer, repo_id: &str, title: &str, severit
// Get the DB name from the test server by parsing the health response
// For now, we use a direct insert approach
let db = client.database(server.db_name());
let db = client.database(&server.tenant_db_name());
let now = mongodb::bson::DateTime::now();
db.collection::<mongodb::bson::Document>("findings")
@@ -104,6 +104,35 @@ async fn update_finding_status() {
server.cleanup().await;
}
#[tokio::test]
async fn feedback_on_an_unknown_finding_is_404() {
let server = TestServer::start().await;
insert_finding(&server, "repo1", "Test Bug", "medium").await;
let resp = server.get("/api/v1/findings").await;
let body: serde_json::Value = resp.json().await.unwrap();
let finding_id = body["data"][0]["_id"]["$oid"].as_str().unwrap();
let feedback = json!({ "feedback": "reviewed" });
let resp = server
.patch(
&format!("/api/v1/findings/{finding_id}/feedback"),
&feedback,
)
.await;
assert_eq!(resp.status(), 200);
let resp = server
.patch(
"/api/v1/findings/000000000000000000000000/feedback",
&feedback,
)
.await;
assert_eq!(resp.status(), 404);
server.cleanup().await;
}
#[tokio::test]
async fn bulk_update_finding_status() {
let server = TestServer::start().await;
@@ -22,7 +22,7 @@ async fn stats_overview_returns_zeroes_on_empty_db() {
let body: serde_json::Value = resp.json().await.unwrap();
let data = &body["data"];
assert_eq!(data["repositories"], 0);
assert_eq!(data["total_repositories"], 0);
assert_eq!(data["total_findings"], 0);
server.cleanup().await;
@@ -235,7 +235,7 @@ async fn the_list_pages_with_a_total_after_the_project_filter() {
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let targets = client
.database(&format!("{}_dev", server.db_name()))
.database(&server.tenant_db_name())
.collection::<mongodb::bson::Document>("onboarded_targets");
for id in &ids[1..] {
let oid = mongodb::bson::oid::ObjectId::parse_str(id).unwrap();
@@ -39,7 +39,7 @@ async fn the_sbom_lists_components_in_the_image_first_and_filters_by_it() {
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
// The dev tenant's database, which the API reads.
let db = client.database(&format!("{}_dev", server.db_name()));
let db = client.database(&server.tenant_db_name());
let entries = [
recipe("aaa-tools", false),
recipe("busybox", true),
@@ -21,7 +21,7 @@ async fn stats_overview_reflects_inserted_data() {
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let db = client.database(server.db_name());
let db = client.database(&server.tenant_db_name());
let now = mongodb::bson::DateTime::now();
for (title, severity) in [
@@ -52,10 +52,10 @@ async fn stats_overview_reflects_inserted_data() {
let body: serde_json::Value = resp.json().await.unwrap();
let data = &body["data"];
assert_eq!(data["repositories"], 1);
assert_eq!(data["total_repositories"], 1);
assert_eq!(data["total_findings"], 4);
assert_eq!(data["critical"], 1);
assert_eq!(data["high"], 1);
assert_eq!(data["critical_findings"], 1);
assert_eq!(data["high_findings"], 1);
server.cleanup().await;
}
@@ -68,7 +68,7 @@ async fn stats_update_after_finding_status_change() {
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let db = client.database(server.db_name());
let db = client.database(&server.tenant_db_name());
let now = mongodb::bson::DateTime::now();
let result = db
@@ -102,11 +102,11 @@ async fn stats_update_after_finding_status_change() {
)
.await;
// The finding still exists (status changed, not deleted)
// The overview counts open findings only (open, triaged, needs_review):
// a resolved one drops out, though the finding itself is kept.
let resp = server.get("/api/v1/stats/overview").await;
let body: serde_json::Value = resp.json().await.unwrap();
// total_findings counts all findings regardless of status
assert_eq!(body["data"]["total_findings"], 1);
assert_eq!(body["data"]["total_findings"], 0);
server.cleanup().await;
}
+1
View File
@@ -35,6 +35,7 @@ fn tenant(id: &str, role: OrgRole) -> TenantCtx {
user_id: "u-1".to_string(),
user_name: None,
staff: None,
api_key: None,
})
}
+1
View File
@@ -64,6 +64,7 @@ fn member(user: &str) -> TenantContext {
user_id: user.into(),
user_name: None,
staff: None,
api_key: None,
}
}
+24 -1
View File
@@ -514,7 +514,7 @@ async fn collect(agent: &Agent, target_id: &str, run: &Value) -> Collected {
"{}:{}@{}{in_image}",
text(e, "package_manager"),
text(e, "name"),
text(e, "version")
blessed_version(&text(e, "package_manager"), &text(e, "version"))
));
for v in e["known_vulnerabilities"].as_array().into_iter().flatten() {
snapshot.cves.insert(text(v, "id"));
@@ -590,6 +590,20 @@ async fn wait_for_runs(
done
}
/// The version a snapshot keeps of a component. A GitHub Action is named by
/// a moving tag (`actions/deploy-pages@v5`), which the scan resolves to the
/// release it points to today (`v5.0.1`): the snapshot keeps the major
/// version, so an upstream patch release does not break the baseline (#573).
/// A commit SHA has no dot and stays whole.
fn blessed_version(package_manager: &str, version: &str) -> String {
if package_manager == "github" {
if let Some((major, _)) = version.split_once('.') {
return major.to_string();
}
}
version.to_string()
}
fn baseline_path(root: &Path, key: &str) -> PathBuf {
root.join("fixtures/nightly/baselines")
.join(format!("{key}.json"))
@@ -770,6 +784,15 @@ mod unit {
items.iter().map(|s| s.to_string()).collect()
}
#[test]
fn a_github_action_keeps_its_major_version_only() {
assert_eq!(blessed_version("github", "v5.0.1"), "v5");
assert_eq!(blessed_version("github", "v1"), "v1");
let sha = "38a6d9b276ed434454900130cacc87d058d3ac62";
assert_eq!(blessed_version("github", sha), sha);
assert_eq!(blessed_version("cargo", "1.0.15"), "1.0.15");
}
#[test]
fn exact_sets_report_both_directions_and_at_least_sets_only_losses() {
let blessed = Snapshot {
+87 -3
View File
@@ -69,6 +69,8 @@ async fn a_scan_closes_what_it_no_longer_finds_and_reopens_what_returns() {
finding("fp-kept", "semgrep", "src/a.c"),
finding("fp-fixed", "semgrep", "src/b.c"),
finding("fp-vendor", "semgrep", "Drivers/STM32F4xx_HAL_Driver/x.c"),
finding("fp-test-data", "semgrep", "fixtures/dotnet/Program.cs"),
finding("fp-excluded", "semgrep", "docs/samples/app.py"),
finding("fp-lint", "clippy", "src/lib.rs"),
decided,
other_target,
@@ -81,15 +83,18 @@ async fn a_scan_closes_what_it_no_longer_finds_and_reopens_what_returns() {
assert_eq!(idle.resolve_missing(&db, TARGET, &[]).await.unwrap(), 0);
// Act: semgrep completes and reports only fp-kept.
let mut run = RunFindings::new("run-2");
let mut run = RunFindings::new("run-2")
.with_test_data(vec!["fixtures".to_string()])
.with_excluded(vec!["docs/samples".to_string()]);
run.completed("semgrep");
let mut seen = vec![finding("fp-kept", "semgrep", "src/a.c")];
run.write_back(&db, &mut seen).await.unwrap();
let vendor = vec!["Drivers".to_string()];
let closed = run.resolve_missing(&db, TARGET, &vendor).await.unwrap();
// Assert: fixed and vendored closed, each with its reason; the rest kept.
assert_eq!(closed, 2);
// Assert: fixed, vendored, test data and excluded closed, each with its
// reason; the rest kept.
assert_eq!(closed, 4);
let fixed = row(&db, "fp-fixed").await;
assert_eq!(fixed.status, FindingStatus::Resolved);
assert_eq!(
@@ -102,6 +107,18 @@ async fn a_scan_closes_what_it_no_longer_finds_and_reopens_what_returns() {
last_scan_change(&vendored),
Some(ScanChangeKind::NowVendorCode)
);
let test_data = row(&db, "fp-test-data").await;
assert_eq!(test_data.status, FindingStatus::Resolved);
assert_eq!(
last_scan_change(&test_data),
Some(ScanChangeKind::NowTestData)
);
let excluded = row(&db, "fp-excluded").await;
assert_eq!(excluded.status, FindingStatus::Resolved);
assert_eq!(
last_scan_change(&excluded),
Some(ScanChangeKind::NowExcluded)
);
assert_eq!(row(&db, "fp-kept").await.status, FindingStatus::Open);
assert_eq!(
row(&db, "fp-false-positive").await.status,
@@ -144,3 +161,70 @@ async fn a_scan_closes_what_it_no_longer_finds_and_reopens_what_returns() {
pool.drop_tenant(TENANT).await.ok();
}
#[tokio::test]
async fn only_what_was_left_out_is_closed_for_a_stage_without_a_seen_set() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"leftout_{}",
&uuid::Uuid::new_v4().simple().to_string()[..10]
);
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP resolve_findings: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
// Arrange: PLC findings in an excluded path, in test data and elsewhere,
// and one of another scanner in the excluded path.
let mut decided = finding("fp-plc-decided", "plc-control-logic", "legacy/Old.st");
decided.status = FindingStatus::AcceptedRisk;
db.findings()
.insert_many([
finding("fp-plc-excluded", "plc-control-logic", "legacy/Old.st"),
finding("fp-plc-fixture", "plc-control-logic", "fixtures/Pump.xml"),
finding("fp-plc-kept", "plc-control-logic", "src/Main.st"),
finding("fp-other-scanner", "semgrep", "legacy/tool.py"),
decided,
])
.await
.unwrap();
// Act
let mut run = RunFindings::new("run-plc")
.with_excluded(vec!["legacy".to_string()])
.with_test_data(vec!["fixtures".to_string()]);
let closed = run
.resolve_left_out(&db, TARGET, "plc-control-logic")
.await
.unwrap();
// Assert: only the left-out PLC findings close, each with its reason;
// what the scan did not see otherwise is not closed as fixed.
assert_eq!(closed, 2);
assert_eq!(run.status_changed().len(), 2);
let excluded = row(&db, "fp-plc-excluded").await;
assert_eq!(excluded.status, FindingStatus::Resolved);
assert_eq!(
last_scan_change(&excluded),
Some(ScanChangeKind::NowExcluded)
);
let fixture = row(&db, "fp-plc-fixture").await;
assert_eq!(
last_scan_change(&fixture),
Some(ScanChangeKind::NowTestData)
);
assert_eq!(row(&db, "fp-plc-kept").await.status, FindingStatus::Open);
assert_eq!(
row(&db, "fp-other-scanner").await.status,
FindingStatus::Open
);
assert_eq!(
row(&db, "fp-plc-decided").await.status,
FindingStatus::AcceptedRisk,
"a person's decision stays"
);
pool.drop_tenant(TENANT).await.ok();
}
@@ -26,6 +26,7 @@ fn ctx(tenant_id: &str, slug: &str) -> TenantContext {
user_id: "u-1".to_string(),
user_name: None,
staff: None,
api_key: None,
}
}
@@ -29,6 +29,7 @@ fn ctx_with(status: TenantStatus) -> TenantContext {
user_id: "u-1".to_string(),
user_name: None,
staff: None,
api_key: None,
}
}
+3 -1
View File
@@ -54,7 +54,9 @@ mongodb = { workspace = true, optional = true }
opentelemetry = { version = "0.29", optional = true }
opentelemetry_sdk = { version = "0.29", features = ["rt-tokio"], optional = true }
opentelemetry-otlp = { version = "0.29", features = ["http", "reqwest-rustls"], optional = true }
opentelemetry-appender-tracing = { version = "0.29", optional = true }
# experimental_use_tracing_span_context: an OTLP log record carries the
# trace_id/span_id of the span it was logged in, so SigNoz links logs and traces.
opentelemetry-appender-tracing = { version = "0.29", optional = true, features = ["experimental_use_tracing_span_context"] }
tracing-opentelemetry = { version = "0.30", optional = true }
tracing-subscriber = { workspace = true, optional = true }
tracing = { workspace = true, optional = true }
+18 -3
View File
@@ -129,6 +129,12 @@ const PUBLIC_ENDPOINTS: &[&str] = &["/api/v1/health"];
/// would semantically conflict with these cross-tenant / machine operations.
const PUBLIC_PREFIXES: &[&str] = &["/api/v1/admin/", "/api/v1/werkbank/", "/api/v1/platform/"];
/// Whether `path` is outside the customer API: the health check, or a
/// sub-API with its own authentication ([`PUBLIC_PREFIXES`]).
pub fn bypasses_customer_auth(path: &str) -> bool {
PUBLIC_ENDPOINTS.contains(&path) || PUBLIC_PREFIXES.iter().any(|p| path.starts_with(p))
}
/// Middleware that validates Bearer JWT tokens against Keycloak's JWKS
/// and attaches a `TenantContext` extension on success.
///
@@ -137,9 +143,16 @@ const PUBLIC_PREFIXES: &[&str] = &["/api/v1/admin/", "/api/v1/werkbank/", "/api/
/// not configured), requests pass through and downstream code must
/// handle the missing context.
pub async fn require_jwt_auth(mut request: Request, next: Next) -> Response {
let path = request.uri().path();
if PUBLIC_ENDPOINTS.contains(&path) || PUBLIC_PREFIXES.iter().any(|p| path.starts_with(p)) {
if bypasses_customer_auth(request.uri().path()) {
return next.run(request).await;
}
// An API key the agent's key middleware (mounted outside this one, the
// only place that inserts a context this early) has already verified.
if request
.extensions()
.get::<TenantContext>()
.is_some_and(|c| c.api_key.is_some())
{
return next.run(request).await;
}
@@ -296,6 +309,7 @@ fn authenticate(c: Claims, requested_tenant: Option<&str>) -> Result<Authenticat
user_id: staff.user_id.clone(),
user_name: staff.user_name.clone(),
staff: Some(staff),
api_key: None,
}))
}
// Staff who also belong to a tenant work in it like anyone else.
@@ -431,6 +445,7 @@ fn claims_to_context(c: Claims) -> Result<TenantContext, String> {
user_id: c.sub,
user_name: c.name.or(c.preferred_username),
staff: None,
api_key: None,
})
}
+7 -2
View File
@@ -9,6 +9,10 @@ pub struct AgentConfig {
pub litellm_api_key: SecretString,
pub litellm_model: String,
pub litellm_embed_model: String,
/// Seconds one LLM call may take in total, waiting in the gateway's queue
/// included (`LLM_TIMEOUT_SECS`, default 600). Keep it at the gateway's own
/// request timeout: a call given up earlier keeps the model busy anyway.
pub llm_timeout_secs: u64,
pub github_token: Option<SecretString>,
pub github_webhook_secret: Option<SecretString>,
pub gitlab_url: Option<String>,
@@ -322,8 +326,9 @@ impl Default for AgentConfig {
mongodb_database: "compliance_scanner".to_string(),
litellm_url: "http://localhost:4000".to_string(),
litellm_api_key: SecretString::from(String::new()),
litellm_model: "gpt-4o".to_string(),
litellm_embed_model: "text-embedding-3-small".to_string(),
litellm_model: String::new(),
litellm_embed_model: String::new(),
llm_timeout_secs: 600,
github_token: None,
github_webhook_secret: None,
gitlab_url: None,
+1
View File
@@ -47,6 +47,7 @@ mod tests {
user_id: "u-1".to_string(),
user_name: None,
staff: None,
api_key: None,
}
}
+2 -1
View File
@@ -8,6 +8,7 @@ pub mod error;
pub mod exec_policy;
#[cfg(feature = "net")]
pub mod guarded_net;
pub mod license_notices;
pub mod models;
pub mod net_guard;
pub mod purl;
@@ -35,6 +36,6 @@ pub use error::CoreError;
pub use exec_policy::ExecPolicy;
pub use net_guard::{NetGuard, NetGuardError};
pub use tenant::{
OrgRole, ProductAccess, StaffAccess, TenantContext, TenantStatus, SUPPORT_ROLES,
ApiKeyAccess, OrgRole, ProductAccess, StaffAccess, TenantContext, TenantStatus, SUPPORT_ROLES,
SUPPORT_TENANT_HEADER,
};
+356
View File
@@ -0,0 +1,356 @@
//! Third-party notices: the file a product ships to name the components it
//! contains, their copyright and their licences (`THIRD-PARTY-NOTICES`).
//!
//! Built from a target's components with their confirmed licences attached
//! ([`crate::models::license::apply`]). Grouped by licence; for a licence
//! SPDX lists, the notice links its text on spdx.org instead of copying it;
//! for one of the workspace's own (`LicenseRef-`) it prints the text a
//! person stored. Components without a known licence are listed at the end,
//! so the gaps show. Build-only components are left out unless asked for.
use std::collections::BTreeMap;
use std::fmt::Write as _;
use serde::Deserialize;
use crate::models::license_policy::is_shipped;
use crate::models::SbomEntry;
use crate::spdx_license;
/// The formats a notice is written in.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NoticeFormat {
/// Plain text (`THIRD-PARTY-NOTICES.txt`).
#[default]
Text,
/// Markdown (`THIRD-PARTY-NOTICES.md`).
Markdown,
}
impl NoticeFormat {
/// The file name a download takes.
pub fn file_name(self) -> &'static str {
match self {
Self::Text => "THIRD-PARTY-NOTICES.txt",
Self::Markdown => "THIRD-PARTY-NOTICES.md",
}
}
/// The media type of a download.
pub fn content_type(self) -> &'static str {
match self {
Self::Text => "text/plain; charset=utf-8",
Self::Markdown => "text/markdown; charset=utf-8",
}
}
}
/// What a notice is made of.
#[derive(Debug, Clone)]
pub struct NoticeOptions<'a> {
/// The product's name for the heading (the target's name).
pub product: &'a str,
pub format: NoticeFormat,
/// Also list components only used to build.
pub include_build_only: bool,
}
/// The components of one licence.
#[derive(Default)]
struct Group<'a> {
/// The licence's URLs: spdx.org for listed ids, the stored one otherwise.
urls: Vec<String>,
/// Stored texts of licences SPDX does not list, once each.
texts: Vec<&'a str>,
/// `name version` with its copyright lines.
components: Vec<(String, Vec<&'a str>)>,
}
/// The heading of the components without a licence.
const UNKNOWN: &str = "Licence not determined";
/// The spdx.org page of each SPDX id in `expression`.
fn spdx_urls(expression: &str) -> Vec<String> {
let mut urls: Vec<String> = Vec::new();
for token in expression
.split(|c: char| c.is_whitespace() || c == '(' || c == ')')
.filter(|t| !t.is_empty())
{
if let Some(id) = spdx_license::canonical_id(token.trim_end_matches('+')) {
let url = format!("https://spdx.org/licenses/{id}.html");
if !urls.contains(&url) {
urls.push(url);
}
}
}
urls
}
/// The notice for `entries` (one target's components, confirmed licences
/// attached).
pub fn render(entries: &[SbomEntry], options: &NoticeOptions<'_>) -> String {
let mut groups: BTreeMap<String, Group<'_>> = BTreeMap::new();
let mut unknown: Vec<String> = Vec::new();
let mut listed = 0usize;
let mut seen: Vec<(&str, &str, &str)> = Vec::new();
for entry in entries {
let concluded = entry.concluded.as_ref();
if !options.include_build_only && !is_shipped(concluded) {
continue;
}
// One line per package and version, however many manifests name it.
let id = (
entry.package_manager.as_str(),
entry.name.as_str(),
entry.version.as_str(),
);
if seen.contains(&id) {
continue;
}
seen.push(id);
listed += 1;
let component = if entry.version.trim().is_empty() {
entry.name.clone()
} else {
format!("{} {}", entry.name, entry.version)
};
let Some(license) = entry.effective_license() else {
unknown.push(component);
continue;
};
let group = groups.entry(license.to_string()).or_default();
match concluded {
Some(c) => {
if let Some(url) = c.license_url.as_deref() {
if !group.urls.iter().any(|u| u == url) {
group.urls.push(url.to_string());
}
}
for url in spdx_urls(&c.license) {
if !group.urls.contains(&url) {
group.urls.push(url);
}
}
if let Some(text) = c.license_text.as_deref() {
if !group.texts.contains(&text) {
group.texts.push(text);
}
}
group
.components
.push((component, c.copyright.iter().map(String::as_str).collect()));
}
None => {
for url in spdx_urls(&spdx_license::normalise(license)) {
if !group.urls.contains(&url) {
group.urls.push(url);
}
}
group.components.push((component, Vec::new()));
}
}
}
for group in groups.values_mut() {
group.components.sort_by(|a, b| a.0.cmp(&b.0));
}
unknown.sort();
match options.format {
NoticeFormat::Text => text(options, &groups, &unknown, listed),
NoticeFormat::Markdown => markdown(options, &groups, &unknown, listed),
}
}
fn intro(options: &NoticeOptions<'_>, listed: usize) -> String {
format!(
"{} contains the following {listed} third-party components. Each is \
distributed under the licence named for it; the copyright belongs to \
its authors.",
options.product
)
}
fn text(
options: &NoticeOptions<'_>,
groups: &BTreeMap<String, Group<'_>>,
unknown: &[String],
listed: usize,
) -> String {
let rule = "=".repeat(72);
let mut out = String::new();
let _ = writeln!(out, "THIRD-PARTY NOTICES — {}\n", options.product);
let _ = writeln!(out, "{}\n", intro(options, listed));
for (license, group) in groups {
let _ = writeln!(out, "{rule}\n{license}\n{rule}");
for url in &group.urls {
let _ = writeln!(out, "Licence text: {url}");
}
out.push('\n');
for (component, copyright) in &group.components {
let _ = writeln!(out, " * {component}");
for line in copyright {
let _ = writeln!(out, " {line}");
}
}
for text in &group.texts {
let _ = writeln!(out, "\n{}\n", text.trim_end());
}
out.push('\n');
}
if !unknown.is_empty() {
let _ = writeln!(out, "{rule}\n{UNKNOWN}\n{rule}\n");
for component in unknown {
let _ = writeln!(out, " * {component}");
}
out.push('\n');
}
out
}
/// `text` with the characters markdown would read as formatting escaped.
fn md(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for c in text.chars() {
if matches!(
c,
'\\' | '`' | '*' | '_' | '[' | ']' | '<' | '>' | '#' | '|'
) {
out.push('\\');
}
out.push(c);
}
out
}
fn markdown(
options: &NoticeOptions<'_>,
groups: &BTreeMap<String, Group<'_>>,
unknown: &[String],
listed: usize,
) -> String {
let mut out = String::new();
let _ = writeln!(out, "# Third-party notices — {}\n", md(options.product));
let _ = writeln!(out, "{}\n", md(&intro(options, listed)));
for (license, group) in groups {
let _ = writeln!(out, "## {}\n", md(license));
for url in &group.urls {
let _ = writeln!(out, "Licence text: <{url}>\n");
}
for (component, copyright) in &group.components {
let _ = writeln!(out, "- {}", md(component));
for line in copyright {
let _ = writeln!(out, " - {}", md(line));
}
}
for text in &group.texts {
let _ = writeln!(
out,
"\n```text\n{}\n```",
text.trim_end().replace("```", "'''")
);
}
out.push('\n');
}
if !unknown.is_empty() {
let _ = writeln!(out, "## {UNKNOWN}\n");
for component in unknown {
let _ = writeln!(out, "- {}", md(component));
}
out.push('\n');
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::models::license::{conclusion_id, package_key};
use crate::models::{LicenseCategory, LicenseConclusion, LicenseUsage};
fn entry(name: &str, license: Option<&str>) -> SbomEntry {
let mut e = SbomEntry::new("r".into(), name.into(), "1.0".into(), "npm".into());
e.license = license.map(String::from);
e
}
fn concluded(name: &str, license: &str) -> LicenseConclusion {
let key = package_key(name, "npm", None);
LicenseConclusion {
id: conclusion_id(&key, None),
package_key: key,
name: name.into(),
package_manager: "npm".into(),
version: None,
license: license.into(),
license_name: Some("Pump EULA".into()),
category: LicenseCategory::Proprietary,
copyright: vec!["© 2024 Pump GmbH".into()],
license_text: Some("You may use it.".into()),
license_url: None,
evidence: None,
contract_ref: None,
valid_until: None,
usage: None,
note: None,
by: "u".into(),
by_name: None,
support: false,
at: chrono::Utc::now(),
review: None,
}
}
fn options(format: NoticeFormat) -> NoticeOptions<'static> {
NoticeOptions {
product: "Pump",
format,
include_build_only: false,
}
}
#[test]
fn groups_by_licence_links_spdx_and_prints_own_texts() {
let mut own = entry("pumplib", None);
own.concluded = Some(concluded("pumplib", "LicenseRef-Pump-EULA"));
let entries = vec![
entry("b", Some("MIT")),
entry("a", Some("MIT")),
entry("a", Some("MIT")),
own,
entry("mystery", None),
];
let out = render(&entries, &options(NoticeFormat::Text));
assert!(out.contains("following 4 third-party components"));
assert!(out.contains("https://spdx.org/licenses/MIT.html"));
let a = out.find(" * a 1.0").unwrap_or(usize::MAX);
let b = out.find(" * b 1.0").unwrap_or(0);
assert!(a < b, "sorted");
assert!(out.contains("Pump EULA"));
assert!(out.contains("© 2024 Pump GmbH"));
assert!(out.contains("You may use it."));
assert!(out.contains("Licence not determined"));
assert!(out.contains(" * mystery 1.0"));
}
#[test]
fn build_only_components_are_left_out_unless_asked() {
let mut tool = entry("jest", Some("MIT"));
let mut c = concluded("jest", "MIT");
c.usage = Some(LicenseUsage::BuildOnly);
tool.concluded = Some(c);
let entries = vec![tool];
assert!(!render(&entries, &options(NoticeFormat::Text)).contains("jest"));
let mut all = options(NoticeFormat::Text);
all.include_build_only = true;
assert!(render(&entries, &all).contains("jest"));
}
#[test]
fn markdown_escapes_names() {
let entries = vec![entry("*evil*", Some("MIT"))];
let out = render(&entries, &options(NoticeFormat::Markdown));
assert!(out.starts_with("# Third-party notices — Pump"));
assert!(out.contains("- \\*evil\\* 1.0"));
assert!(out.contains("<https://spdx.org/licenses/MIT.html>"));
}
}
+186
View File
@@ -0,0 +1,186 @@
//! Paths a target's owner leaves out of its scans (`scan_config.exclude_paths`).
//!
//! Each entry names a directory or a file relative to the root of the scanned
//! tree, such as `docs/samples` or `tools/legacy.py`. Everything under a
//! directory is left out of every stage: code findings, SBOM and CVE match.
//! There are no wildcards: a path is a prefix that ends at a `/`, the same
//! rule as for vendor code and test data. The scan applies them on top of
//! the test data it detects itself (`fixtures/`, `testdata/`).
/// How many paths one target may exclude.
pub const MAX_EXCLUDE_PATHS: usize = 50;
/// How long one excluded path may be, in bytes.
pub const MAX_EXCLUDE_PATH_LEN: usize = 256;
/// Why an excluded path was refused. Every variant names the entry as given.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ExcludePathError {
/// More than [`MAX_EXCLUDE_PATHS`] entries.
#[error("at most {MAX_EXCLUDE_PATHS} paths can be excluded")]
TooMany,
/// Longer than [`MAX_EXCLUDE_PATH_LEN`].
#[error("{0}: longer than {MAX_EXCLUDE_PATH_LEN} characters")]
TooLong(String),
/// Starts at the file system root (`/src`, `C:\src`).
#[error("{0}: give the path relative to the repository root, without a leading /")]
Absolute(String),
/// Names `.`, `..` or `.git` as a part, or is the root itself.
#[error("{0}: must name a directory or file inside the repository")]
OutsideTree(String),
/// Holds a wildcard (`*`, `?`, `[`).
#[error("{0}: wildcards are not supported; name the directory or file")]
Wildcard(String),
}
/// The excluded paths as stored: trimmed, `/`-separated, without a leading
/// `./` or a trailing `/`, blank lines dropped, duplicates removed, in the
/// order given.
///
/// # Arguments
///
/// * `paths` - the entries as a person typed them, one path each
///
/// # Returns
///
/// The normalised paths.
///
/// # Errors
///
/// The first entry that is not a path inside the tree
/// ([`ExcludePathError`]), or [`ExcludePathError::TooMany`].
///
/// # Examples
///
/// ```
/// use compliance_core::models::normalise_exclude_paths;
///
/// let paths = vec!["./docs/samples/".to_string(), "".to_string(), "tools\\old".to_string()];
/// assert_eq!(normalise_exclude_paths(&paths).unwrap(), ["docs/samples", "tools/old"]);
/// assert!(normalise_exclude_paths(&["../etc".to_string()]).is_err());
/// ```
pub fn normalise_exclude_paths(paths: &[String]) -> Result<Vec<String>, ExcludePathError> {
let mut out: Vec<String> = Vec::with_capacity(paths.len());
for raw in paths {
let Some(path) = normalise_one(raw)? else {
continue;
};
if !out.contains(&path) {
out.push(path);
}
}
if out.len() > MAX_EXCLUDE_PATHS {
return Err(ExcludePathError::TooMany);
}
Ok(out)
}
/// One entry normalised; `None` for a blank one.
fn normalise_one(raw: &str) -> Result<Option<String>, ExcludePathError> {
let given = raw.trim();
if given.is_empty() {
return Ok(None);
}
if given.len() > MAX_EXCLUDE_PATH_LEN {
return Err(ExcludePathError::TooLong(given.to_string()));
}
if given.contains(['*', '?', '[']) {
return Err(ExcludePathError::Wildcard(given.to_string()));
}
let slashed = given.replace('\\', "/");
// `/src`, and a Windows drive (`C:/src`).
let drive = slashed.as_bytes().get(1) == Some(&b':');
if slashed.starts_with('/') || drive {
return Err(ExcludePathError::Absolute(given.to_string()));
}
let parts: Vec<&str> = slashed
.trim_start_matches("./")
.split('/')
.filter(|part| !part.is_empty())
.collect();
let outside = parts.is_empty()
|| parts
.iter()
.any(|part| matches!(*part, "." | "..") || part.eq_ignore_ascii_case(".git"));
if outside {
return Err(ExcludePathError::OutsideTree(given.to_string()));
}
Ok(Some(parts.join("/")))
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
fn norm(paths: &[&str]) -> Result<Vec<String>, ExcludePathError> {
let owned: Vec<String> = paths.iter().map(|p| p.to_string()).collect();
normalise_exclude_paths(&owned)
}
#[test]
fn paths_are_stored_relative_and_slash_separated() {
assert_eq!(
norm(&[
" ./docs/samples/ ",
"",
"tools\\legacy.py",
"docs//samples",
"a/b"
])
.unwrap(),
["docs/samples", "tools/legacy.py", "a/b"]
);
assert!(norm(&[]).unwrap().is_empty());
}
#[test]
fn a_path_outside_the_tree_is_refused() {
for bad in [
"/etc",
"C:\\src",
"..",
"a/../b",
"./",
".",
".git",
"src/.git/hooks",
] {
let err = norm(&[bad]).unwrap_err();
assert!(
matches!(
err,
ExcludePathError::Absolute(_) | ExcludePathError::OutsideTree(_)
),
"{bad}: {err:?}"
);
}
}
#[test]
fn wildcards_length_and_count_are_limited() {
assert_eq!(
norm(&["src/*.c"]),
Err(ExcludePathError::Wildcard("src/*.c".into()))
);
let long = "a".repeat(MAX_EXCLUDE_PATH_LEN + 1);
assert!(matches!(
norm(&[long.as_str()]),
Err(ExcludePathError::TooLong(_))
));
let many: Vec<String> = (0..=MAX_EXCLUDE_PATHS).map(|n| format!("d{n}")).collect();
assert_eq!(
normalise_exclude_paths(&many),
Err(ExcludePathError::TooMany)
);
// Duplicates count once.
let same: Vec<String> = (0..=MAX_EXCLUDE_PATHS).map(|_| "d".to_string()).collect();
assert_eq!(normalise_exclude_paths(&same).unwrap(), ["d"]);
}
#[test]
fn the_error_names_the_entry() {
let err = norm(&["../x"]).unwrap_err();
assert!(err.to_string().starts_with("../x:"), "{err}");
}
}
+6
View File
@@ -131,6 +131,12 @@ pub enum ScanChangeKind {
NoLongerFound,
/// Its file now lies in vendor code, which is left out of the findings.
NowVendorCode,
/// Its file now lies in test data (`fixtures/`, `testdata/`), which is
/// left out of the scan.
NowTestData,
/// Its file now lies in a path the target's settings exclude from the
/// scan (`scan_config.exclude_paths`).
NowExcluded,
/// A finding marked resolved was reported again.
FoundAgain,
/// Its rule fired often enough in the repository that its occurrences
+484
View File
@@ -0,0 +1,484 @@
//! Licences a workspace has confirmed for its components: where a scan found
//! no licence (or a wrong one), a person states the licence, its category,
//! the copyright and where it is written down.
//!
//! A conclusion is kept apart from the scanned components, which every scan
//! rewrites, and is merged into them when they are read or exported
//! ([`apply`]). It belongs to a package: to one version of it, or to every
//! version. In the exports it is the concluded licence (CycloneDX
//! `acknowledgement: concluded`, SPDX `licenseConcluded`); the licence the
//! scan detected stays the declared one.
use chrono::{DateTime, NaiveDate, Utc};
use serde::{Deserialize, Serialize};
use super::SbomEntry;
use crate::purl::Purl;
use crate::spdx_license;
/// What a licence allows and asks for, roughly. A hint for reviewing
/// components, not legal advice.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LicenseCategory {
/// No rights reserved (CC0, Unlicense).
PublicDomain,
/// Use, change and ship freely; keep the notice (MIT, Apache-2.0, BSD).
Permissive,
/// Changes to the component itself stay open (LGPL, MPL, EPL).
WeakCopyleft,
/// Whatever is shipped with it stays open (GPL).
StrongCopyleft,
/// As strong copyleft, also when only offered over a network (AGPL).
NetworkCopyleft,
/// Bought or otherwise licensed under terms of its own.
Proprietary,
/// Written by the workspace's own company.
OwnCode,
/// Not known yet.
#[default]
Unclear,
}
impl LicenseCategory {
/// Every category, in the order a picker lists them.
pub const ALL: [Self; 8] = [
Self::Permissive,
Self::WeakCopyleft,
Self::StrongCopyleft,
Self::NetworkCopyleft,
Self::Proprietary,
Self::PublicDomain,
Self::OwnCode,
Self::Unclear,
];
/// The stored name (`weak_copyleft`).
pub fn as_str(self) -> &'static str {
match self {
Self::PublicDomain => "public_domain",
Self::Permissive => "permissive",
Self::WeakCopyleft => "weak_copyleft",
Self::StrongCopyleft => "strong_copyleft",
Self::NetworkCopyleft => "network_copyleft",
Self::Proprietary => "proprietary",
Self::OwnCode => "own_code",
Self::Unclear => "unclear",
}
}
/// The category of its stored name.
pub fn parse(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|c| c.as_str() == name)
}
/// Whether it asks for source code to be passed on (weak, strong or
/// network copyleft).
pub fn is_copyleft(self) -> bool {
matches!(
self,
Self::WeakCopyleft | Self::StrongCopyleft | Self::NetworkCopyleft
)
}
/// How much a licence of this category restricts, for combining the
/// terms of an expression: `OR` takes the least, `AND` the most.
pub(crate) fn restriction(self) -> u8 {
match self {
Self::PublicDomain => 0,
Self::Permissive | Self::OwnCode => 1,
Self::WeakCopyleft => 2,
Self::StrongCopyleft => 3,
Self::NetworkCopyleft => 4,
Self::Proprietary => 5,
Self::Unclear => 6,
}
}
}
/// Where a component is used: shipped in the product, or only to build or
/// develop it. Copyleft obligations mostly bind what is shipped.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LicenseUsage {
/// Part of what is delivered (an app, a firmware image, a library in it).
Shipped,
/// Only used to build, test or develop.
BuildOnly,
}
/// A licence a person confirmed for a package.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LicenseConclusion {
/// [`conclusion_id`]: the package key and the version, or `*` for all.
#[serde(rename = "_id")]
pub id: String,
/// [`package_key`] of the package.
pub package_key: String,
pub name: String,
pub package_manager: String,
/// The version it was confirmed for; `None` for every version.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
/// An SPDX licence expression (`MIT`, `MIT OR Apache-2.0`), or a
/// `LicenseRef-` id for a licence SPDX does not list.
pub license: String,
/// The name of a `LicenseRef-` licence (`Pump Controls EULA`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub license_name: Option<String>,
pub category: LicenseCategory,
/// Copyright lines (`© 2019 Example GmbH`).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub copyright: Vec<String>,
/// The licence text, where it is not an SPDX-listed licence.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub license_text: Option<String>,
/// Where the licence text is published.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub license_url: Option<String>,
/// Where the licence was found: a file in the repository, a contract,
/// a web page.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub evidence: Option<String>,
/// The contract or licence number of a bought licence.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub contract_ref: Option<String>,
/// When a bought licence ends.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub valid_until: Option<NaiveDate>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usage: Option<LicenseUsage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
/// Who confirmed it (Keycloak user id), with the name the workspace reads.
pub by: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub by_name: Option<String>,
/// BreakPilot support rather than one of the workspace's users.
#[serde(default)]
pub support: bool,
pub at: DateTime<Utc>,
/// The legal review of this licence, if one was made. Saving the
/// licence again drops it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub review: Option<super::license_policy::LegalReview>,
}
/// The most text a field takes; a licence text may be longer.
pub const MAX_FIELD_CHARS: usize = 2_000;
/// The most a licence text takes.
pub const MAX_TEXT_CHARS: usize = 200_000;
/// The most copyright lines.
pub const MAX_COPYRIGHT_LINES: usize = 20;
impl LicenseConclusion {
/// The licence as people read it: the name of a `LicenseRef-` licence,
/// otherwise the expression.
pub fn display(&self) -> &str {
match &self.license_name {
Some(name) if self.license.starts_with("LicenseRef-") => name,
_ => &self.license,
}
}
/// Whether it is a licence SPDX does not list (`LicenseRef-`).
pub fn is_custom(&self) -> bool {
self.license.starts_with("LicenseRef-")
}
/// Why it cannot be stored, in words; `Ok` when it can.
///
/// # Errors
///
/// The first problem found: no or an invalid licence, a custom licence
/// without a name, a field too long.
pub fn validate(&self) -> Result<(), String> {
let license = self.license.trim();
if license.is_empty() {
return Err("licence missing".into());
}
if self.is_custom() {
if !is_license_ref(license) {
return Err(format!("not a valid LicenseRef id: {license}"));
}
if self
.license_name
.as_deref()
.is_none_or(|n| n.trim().is_empty())
{
return Err("a licence SPDX does not list needs a name".into());
}
} else if !spdx_license::is_spdx_expression(license) {
return Err(format!("not an SPDX licence expression: {license}"));
}
if self.copyright.len() > MAX_COPYRIGHT_LINES {
return Err(format!("at most {MAX_COPYRIGHT_LINES} copyright lines"));
}
let short = [
("licence name", self.license_name.as_deref()),
("licence URL", self.license_url.as_deref()),
("evidence", self.evidence.as_deref()),
("contract", self.contract_ref.as_deref()),
("note", self.note.as_deref()),
];
for (field, value) in short {
if value.is_some_and(|v| v.chars().count() > MAX_FIELD_CHARS) {
return Err(format!("{field} longer than {MAX_FIELD_CHARS} characters"));
}
}
if self
.copyright
.iter()
.any(|c| c.chars().count() > MAX_FIELD_CHARS)
{
return Err(format!(
"copyright line longer than {MAX_FIELD_CHARS} characters"
));
}
if self
.license_text
.as_deref()
.is_some_and(|t| t.chars().count() > MAX_TEXT_CHARS)
{
return Err(format!(
"licence text longer than {MAX_TEXT_CHARS} characters"
));
}
if let Some(url) = self.license_url.as_deref() {
let lower = url.trim().to_ascii_lowercase();
if !(lower.starts_with("https://") || lower.starts_with("http://")) {
return Err("the licence URL must start with https:// or http://".into());
}
}
Ok(())
}
}
/// Whether `id` is a well-formed `LicenseRef-` id (letters, digits, `.`, `-`).
pub fn is_license_ref(id: &str) -> bool {
id.strip_prefix("LicenseRef-").is_some_and(|rest| {
!rest.is_empty()
&& rest
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-')
})
}
/// The `LicenseRef-` id of a licence SPDX does not list, made from its name:
/// `Pump Controls EULA` is `LicenseRef-Pump-Controls-EULA`.
pub fn license_ref(name: &str) -> String {
let mut id = String::from("LicenseRef-");
let mut dash = false;
for c in name.trim().chars() {
if c.is_ascii_alphanumeric() || c == '.' {
id.push(c);
dash = false;
} else if !dash && id.len() > "LicenseRef-".len() {
id.push('-');
dash = true;
}
}
// Only a dash after the name, never the one of `LicenseRef-`.
while id.len() > "LicenseRef-".len() && id.ends_with('-') {
id.pop();
}
if id.len() == "LicenseRef-".len() {
id.push_str("custom");
}
id
}
/// The key of a package across its versions: its purl without version,
/// qualifiers and subpath (`pkg:npm/%40scope/name`), or
/// `<package manager>:<name>` without a purl.
pub fn package_key(name: &str, package_manager: &str, purl: Option<&str>) -> String {
if let Some(p) = purl.and_then(Purl::parse) {
return match &p.namespace {
Some(ns) => format!("pkg:{}/{}/{}", p.ty, ns, p.name),
None => format!("pkg:{}/{}", p.ty, p.name),
};
}
format!("{}:{}", package_manager.trim(), name.trim())
}
/// The id of the conclusion for `key` at `version` (`*` for every version).
pub fn conclusion_id(key: &str, version: Option<&str>) -> String {
format!("{key}@{}", version.unwrap_or("*"))
}
/// The conclusion that applies to `entry`: the one for its version, else
/// the one for every version of its package.
pub fn find<'a>(
conclusions: &'a [LicenseConclusion],
entry: &SbomEntry,
) -> Option<&'a LicenseConclusion> {
find_for(
conclusions,
&entry.name,
&entry.package_manager,
&entry.version,
entry.purl.as_deref(),
)
}
/// [`find`] for a component given by its fields.
pub fn find_for<'a>(
conclusions: &'a [LicenseConclusion],
name: &str,
package_manager: &str,
version: &str,
purl: Option<&str>,
) -> Option<&'a LicenseConclusion> {
let key = package_key(name, package_manager, purl);
let mut all_versions = None;
for c in conclusions.iter().filter(|c| c.package_key == key) {
match c.version.as_deref() {
Some(v) if v == version => return Some(c),
None => all_versions = Some(c),
Some(_) => {}
}
}
all_versions
}
/// Attach to every entry the conclusion that applies to it.
pub fn apply(entries: &mut [SbomEntry], conclusions: &[LicenseConclusion]) {
if conclusions.is_empty() {
return;
}
for entry in entries.iter_mut() {
entry.concluded = find(conclusions, entry).cloned();
}
}
#[cfg(test)]
mod tests {
use super::*;
fn conclusion(key: &str, version: Option<&str>, license: &str) -> LicenseConclusion {
LicenseConclusion {
id: conclusion_id(key, version),
package_key: key.into(),
name: "x".into(),
package_manager: "npm".into(),
version: version.map(String::from),
license: license.into(),
license_name: None,
category: LicenseCategory::Permissive,
copyright: Vec::new(),
license_text: None,
license_url: None,
evidence: None,
contract_ref: None,
valid_until: None,
usage: None,
note: None,
by: "u1".into(),
by_name: None,
support: false,
at: Utc::now(),
review: None,
}
}
fn entry(name: &str, version: &str, purl: Option<&str>) -> SbomEntry {
let mut e = SbomEntry::new("t".into(), name.into(), version.into(), "npm".into());
e.purl = purl.map(String::from);
e
}
#[test]
fn a_package_is_keyed_without_its_version() {
assert_eq!(
package_key("core", "npm", Some("pkg:npm/%40angular/core@17.0.1?x=y")),
"pkg:npm/@angular/core"
);
// Encoded or not, the scope is the same package.
assert_eq!(
package_key("core", "npm", Some("pkg:npm/@angular/core@16.2.0")),
"pkg:npm/@angular/core"
);
assert_eq!(package_key("Foo", "nuget", None), "nuget:Foo");
assert_eq!(package_key("Foo", "nuget", Some("not a purl")), "nuget:Foo");
}
#[test]
fn the_version_conclusion_wins_over_the_package_one() {
let key = "pkg:npm/left-pad";
let all = conclusion(key, None, "MIT");
let one = conclusion(key, Some("1.3.0"), "ISC");
let list = vec![all, one];
let e = entry("left-pad", "1.3.0", Some("pkg:npm/left-pad@1.3.0"));
assert_eq!(find(&list, &e).map(|c| c.license.as_str()), Some("ISC"));
let other = entry("left-pad", "1.1.0", Some("pkg:npm/left-pad@1.1.0"));
assert_eq!(find(&list, &other).map(|c| c.license.as_str()), Some("MIT"));
let none = entry("right-pad", "1.0.0", Some("pkg:npm/right-pad@1.0.0"));
assert!(find(&list, &none).is_none());
}
#[test]
fn apply_attaches_and_leaves_others_alone() {
let list = vec![conclusion("pkg:npm/a", None, "MIT")];
let mut entries = vec![
entry("a", "1", Some("pkg:npm/a@1")),
entry("b", "1", Some("pkg:npm/b@1")),
];
apply(&mut entries, &list);
assert!(entries[0].concluded.is_some());
assert!(entries[1].concluded.is_none());
}
#[test]
fn custom_licences_get_a_license_ref() {
assert_eq!(
license_ref("Pump Controls EULA"),
"LicenseRef-Pump-Controls-EULA"
);
assert_eq!(license_ref(" ©© "), "LicenseRef-custom");
assert_eq!(license_ref("v1.2 / 2020"), "LicenseRef-v1.2-2020");
assert_eq!(license_ref("EULA!"), "LicenseRef-EULA");
assert!(is_license_ref("LicenseRef-a.b-1"));
assert!(!is_license_ref("LicenseRef-"));
assert!(!is_license_ref("LicenseRef-a b"));
assert!(!is_license_ref("MIT"));
}
#[test]
fn validation_names_the_problem() {
let ok = conclusion("k", None, "MIT OR Apache-2.0");
assert!(ok.validate().is_ok());
assert!(conclusion("k", None, "").validate().is_err());
assert!(conclusion("k", None, "Custom thing").validate().is_err());
let mut custom = conclusion("k", None, "LicenseRef-Pump");
assert!(custom.validate().is_err(), "a custom licence needs a name");
custom.license_name = Some("Pump EULA".into());
assert!(custom.validate().is_ok());
assert_eq!(custom.display(), "Pump EULA");
custom.license_url = Some("ftp://x".into());
assert!(custom.validate().is_err());
custom.license_url = Some("https://example.com/eula".into());
custom.copyright = vec!["c".into(); MAX_COPYRIGHT_LINES + 1];
assert!(custom.validate().is_err());
custom.copyright = vec!["x".repeat(MAX_FIELD_CHARS + 1)];
assert!(custom.validate().is_err());
custom.copyright.clear();
custom.note = Some("x".repeat(MAX_FIELD_CHARS + 1));
assert!(custom.validate().is_err());
custom.note = None;
custom.license_text = Some("x".repeat(MAX_TEXT_CHARS + 1));
assert!(custom.validate().is_err());
custom.license = "LicenseRef-a b".into();
custom.license_text = None;
assert!(custom.validate().is_err());
}
#[test]
fn categories_round_trip_their_names() {
for c in LicenseCategory::ALL {
assert_eq!(LicenseCategory::parse(c.as_str()), Some(c));
}
assert_eq!(LicenseCategory::parse("nope"), None);
assert!(LicenseCategory::WeakCopyleft.is_copyleft());
assert!(!LicenseCategory::Proprietary.is_copyleft());
}
}
@@ -0,0 +1,701 @@
//! A workspace's licence policy and what it says about each component.
//!
//! The policy names, per [`LicenseCategory`], what a licence of that category
//! needs when the component is shipped and when it is only used to build:
//! nothing ([`PolicyAction::Allow`]), a legal review ([`PolicyAction::Review`])
//! or that it may not be used ([`PolicyAction::Forbid`]). Single licences can
//! be ruled on their own (`GPL-3.0-only` forbidden, `LicenseRef-Pump-EULA`
//! allowed). A review is resolved by a person with the LEGAL role approving
//! the component's licence ([`LegalReview`]); a forbidden licence is not.
//!
//! The default forbids nothing: every copyleft, bought or unknown licence of
//! a shipped component asks for a review, so the workspace decides. A hint
//! for reviewing components, not legal advice.
use chrono::{DateTime, NaiveDate, Utc};
use serde::{Deserialize, Serialize};
use super::license::{LicenseCategory, LicenseConclusion, LicenseUsage};
use super::SbomEntry;
use crate::spdx_license;
/// The id of a workspace's one policy document.
pub const POLICY_ID: &str = "policy";
/// The most single-licence rules a policy holds.
pub const MAX_LICENSE_RULES: usize = 200;
/// The most days ahead a bought licence's end is announced.
pub const MAX_EXPIRY_WARNING_DAYS: u32 = 365;
/// What a licence needs before the component may be used.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PolicyAction {
/// May be used.
Allow,
/// May be used once a person with the LEGAL role approved it.
Review,
/// May not be used.
Forbid,
}
impl PolicyAction {
/// The stored name (`review`).
pub fn as_str(self) -> &'static str {
match self {
Self::Allow => "allow",
Self::Review => "review",
Self::Forbid => "forbid",
}
}
}
/// What a category of licence needs, shipped and build-only.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct CategoryRule {
pub category: LicenseCategory,
/// For a component in what is delivered.
pub shipped: PolicyAction,
/// For a component only used to build, test or develop.
pub build_only: PolicyAction,
}
/// What one licence needs, whatever its category says.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LicenseRule {
/// An SPDX licence id (`GPL-3.0-only`) or a `LicenseRef-` id.
pub license: String,
pub action: PolicyAction,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
}
/// A workspace's licence policy.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LicensePolicy {
/// Always [`POLICY_ID`]: one policy per workspace.
#[serde(rename = "_id", default = "policy_id")]
pub id: String,
/// One rule per category; a category missing here follows [`Self::default`].
pub categories: Vec<CategoryRule>,
/// Rules for single licences, before the categories.
#[serde(default)]
pub licenses: Vec<LicenseRule>,
/// How many days before a bought licence ends it is announced.
#[serde(default = "default_expiry_warning_days")]
pub expiry_warning_days: u32,
/// Who changed it last (Keycloak user id), with the name the workspace reads.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub updated_by: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub updated_by_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub updated_at: Option<DateTime<Utc>>,
}
fn policy_id() -> String {
POLICY_ID.to_string()
}
fn default_expiry_warning_days() -> u32 {
60
}
impl Default for LicensePolicy {
fn default() -> Self {
use LicenseCategory as C;
use PolicyAction::{Allow, Review};
let rule = |category, shipped, build_only| CategoryRule {
category,
shipped,
build_only,
};
Self {
id: policy_id(),
categories: vec![
rule(C::Permissive, Allow, Allow),
rule(C::PublicDomain, Allow, Allow),
rule(C::OwnCode, Allow, Allow),
rule(C::WeakCopyleft, Review, Allow),
rule(C::StrongCopyleft, Review, Allow),
rule(C::NetworkCopyleft, Review, Review),
rule(C::Proprietary, Review, Allow),
rule(C::Unclear, Review, Review),
],
licenses: Vec::new(),
expiry_warning_days: default_expiry_warning_days(),
updated_by: None,
updated_by_name: None,
updated_at: None,
}
}
}
impl LicensePolicy {
/// The rule of `category`: the policy's own, else the default one.
pub fn category_rule(&self, category: LicenseCategory) -> CategoryRule {
self.categories
.iter()
.find(|r| r.category == category)
.copied()
.or_else(|| {
Self::default()
.categories
.into_iter()
.find(|r| r.category == category)
})
.unwrap_or(CategoryRule {
category,
shipped: PolicyAction::Review,
build_only: PolicyAction::Review,
})
}
/// The rule for the licence `id`, if the policy has one.
pub fn license_rule(&self, id: &str) -> Option<&LicenseRule> {
self.licenses
.iter()
.find(|r| r.license.eq_ignore_ascii_case(id))
}
/// The policy with one rule for every category, in picker order, and the
/// licence rules trimmed and normalised to SPDX ids.
///
/// # Errors
///
/// Why it cannot be stored: a licence rule that is no SPDX id or
/// `LicenseRef-`, a licence ruled twice, too many rules, a warning period
/// beyond a year.
pub fn normalised(mut self) -> Result<Self, String> {
let mut categories = Vec::with_capacity(LicenseCategory::ALL.len());
for category in LicenseCategory::ALL {
categories.push(self.category_rule(category));
}
self.categories = categories;
if self.licenses.len() > MAX_LICENSE_RULES {
return Err(format!("at most {MAX_LICENSE_RULES} licence rules"));
}
let mut licenses: Vec<LicenseRule> = Vec::with_capacity(self.licenses.len());
for rule in self.licenses {
let raw = rule.license.trim();
let id = if super::license::is_license_ref(raw) {
raw.to_string()
} else {
match spdx_license::canonical_id(raw) {
Some(id) => id.to_string(),
None => return Err(format!("not an SPDX licence id or LicenseRef: {raw}")),
}
};
if licenses.iter().any(|r| r.license.eq_ignore_ascii_case(&id)) {
return Err(format!("{id} is ruled twice"));
}
let note = rule
.note
.map(|n| n.trim().to_string())
.filter(|n| !n.is_empty());
if note
.as_deref()
.is_some_and(|n| n.chars().count() > super::license::MAX_FIELD_CHARS)
{
return Err("rule note too long".into());
}
licenses.push(LicenseRule {
license: id,
action: rule.action,
note,
});
}
self.licenses = licenses;
if self.expiry_warning_days > MAX_EXPIRY_WARNING_DAYS {
return Err(format!(
"a bought licence is announced at most {MAX_EXPIRY_WARNING_DAYS} days ahead"
));
}
self.id = policy_id();
Ok(self)
}
}
/// A legal decision about a component's licence.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReviewDecision {
/// The licence may be used as confirmed.
Approved,
/// The licence may not be used as confirmed.
Rejected,
}
impl ReviewDecision {
/// The stored name (`approved`).
pub fn as_str(self) -> &'static str {
match self {
Self::Approved => "approved",
Self::Rejected => "rejected",
}
}
}
/// A legal review of a confirmed licence. Saving the licence again (a change)
/// drops it: the review was of what was confirmed before.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LegalReview {
pub decision: ReviewDecision,
/// Who decided (Keycloak user id), with the name the workspace reads.
pub by: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub by_name: Option<String>,
/// BreakPilot support rather than one of the workspace's users.
#[serde(default)]
pub support: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
pub at: DateTime<Utc>,
}
/// Why a component got its verdict.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum VerdictReason {
/// The rule of the licence's category.
Category {
category: LicenseCategory,
shipped: bool,
action: PolicyAction,
},
/// The policy's rule for one licence of it.
License {
license: String,
action: PolicyAction,
},
/// No licence is known for it.
Unknown,
/// The bought licence ended.
Expired { valid_until: NaiveDate },
/// The bought licence ends soon.
ExpiresSoon { valid_until: NaiveDate },
/// LEGAL approved it.
Approved,
/// LEGAL rejected it.
Rejected,
}
/// What the policy says about one component.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LicenseVerdict {
/// What it needs, after a legal review is taken into account.
pub action: PolicyAction,
/// What the policy alone asks for.
pub required: PolicyAction,
/// Shipped (the default) or only used to build.
pub shipped: bool,
pub reasons: Vec<VerdictReason>,
}
impl LicenseVerdict {
/// Whether it still needs a decision or may not be used.
pub fn is_open(&self) -> bool {
self.action != PolicyAction::Allow
}
}
/// Whether `entry` is shipped: unless a person said it is only used to build.
pub fn is_shipped(concluded: Option<&LicenseConclusion>) -> bool {
!matches!(
concluded.and_then(|c| c.usage),
Some(LicenseUsage::BuildOnly)
)
}
/// The terms of an SPDX expression (ids, without `WITH` exceptions) and
/// whether they are joined by `AND`; `None` for text that is no expression.
fn terms(expression: &str) -> Option<(Vec<String>, bool)> {
let normalised = spdx_license::normalise(expression);
let tokens: Vec<&str> = normalised
.split(|c: char| c.is_whitespace() || c == '(' || c == ')')
.filter(|t| !t.is_empty())
.collect();
// SPDX ids and `LicenseRef-`s, joined by operators.
let readable = !tokens.is_empty()
&& tokens.iter().all(|t| {
matches!(*t, "AND" | "OR" | "WITH")
|| super::license::is_license_ref(t)
|| spdx_license::canonical_id(t.trim_end_matches('+')).is_some()
});
if !readable {
return None;
}
let mut out = Vec::new();
let mut after_with = false;
let mut and = false;
for token in tokens {
match token {
"WITH" => after_with = true,
"AND" => {
and = true;
after_with = false;
}
"OR" => after_with = false,
id if !after_with => out.push(id.trim_end_matches('+').to_string()),
_ => {}
}
}
Some((out, and))
}
/// What `policy` says about `entry` on `today`, with its confirmed licence
/// attached ([`super::license::apply`]).
pub fn evaluate(entry: &SbomEntry, policy: &LicensePolicy, today: NaiveDate) -> LicenseVerdict {
let concluded = entry.concluded.as_ref();
let shipped = is_shipped(concluded);
let pick = |rule: CategoryRule| {
if shipped {
rule.shipped
} else {
rule.build_only
}
};
let mut reasons = Vec::new();
let expression = match concluded {
Some(c) => Some(c.license.as_str()),
None => entry
.license
.as_deref()
.map(str::trim)
.filter(|l| !l.is_empty()),
};
let mut required = match expression.and_then(terms) {
None => {
// No licence, or text SPDX cannot read: the category a person
// gave, else unclear.
let category = concluded.map_or(LicenseCategory::Unclear, |c| c.category);
if expression.is_none() {
reasons.push(VerdictReason::Unknown);
}
let action = pick(policy.category_rule(category));
reasons.push(VerdictReason::Category {
category,
shipped,
action,
});
action
}
Some((ids, and)) => {
let mut actions = Vec::with_capacity(ids.len());
for id in &ids {
if let Some(rule) = policy.license_rule(id) {
reasons.push(VerdictReason::License {
license: rule.license.clone(),
action: rule.action,
});
actions.push(rule.action);
continue;
}
// A licence SPDX does not list takes the category a person
// gave it; an SPDX one its own.
let category = match concluded {
Some(c) if id.starts_with("LicenseRef-") || ids.len() == 1 => {
if c.category == LicenseCategory::Unclear {
spdx_license::category(id)
} else {
c.category
}
}
_ => spdx_license::category(id),
};
let action = pick(policy.category_rule(category));
let reason = VerdictReason::Category {
category,
shipped,
action,
};
if !reasons.contains(&reason) {
reasons.push(reason);
}
actions.push(action);
}
// `AND`: every licence binds, the strictest counts. `OR`: the
// workspace may pick, the least strict counts.
let combined = if and {
actions.iter().copied().max()
} else {
actions.iter().copied().min()
};
combined.unwrap_or(PolicyAction::Review)
}
};
if let Some(until) = concluded.and_then(|c| c.valid_until) {
if until < today {
reasons.push(VerdictReason::Expired { valid_until: until });
required = PolicyAction::Forbid;
} else if (until - today).num_days() <= i64::from(policy.expiry_warning_days) {
reasons.push(VerdictReason::ExpiresSoon { valid_until: until });
}
}
let mut action = required;
match concluded
.and_then(|c| c.review.as_ref())
.map(|r| r.decision)
{
Some(ReviewDecision::Approved) => {
reasons.push(VerdictReason::Approved);
if action == PolicyAction::Review {
action = PolicyAction::Allow;
}
}
Some(ReviewDecision::Rejected) => {
reasons.push(VerdictReason::Rejected);
action = PolicyAction::Forbid;
}
None => {}
}
LicenseVerdict {
action,
required,
shipped,
reasons,
}
}
/// How many components need what, for a summary.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct VerdictCounts {
pub allowed: u64,
pub review: u64,
pub forbidden: u64,
/// Allowed because LEGAL approved them.
pub approved: u64,
/// Bought licences that end within the warning period.
pub expiring: u64,
}
impl VerdictCounts {
/// Count `verdict` in.
pub fn add(&mut self, verdict: &LicenseVerdict) {
match verdict.action {
PolicyAction::Allow => self.allowed += 1,
PolicyAction::Review => self.review += 1,
PolicyAction::Forbid => self.forbidden += 1,
}
if verdict.action == PolicyAction::Allow && verdict.required == PolicyAction::Review {
self.approved += 1;
}
if verdict
.reasons
.iter()
.any(|r| matches!(r, VerdictReason::ExpiresSoon { .. }))
{
self.expiring += 1;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::models::license::{conclusion_id, package_key};
fn today() -> NaiveDate {
NaiveDate::from_ymd_opt(2026, 10, 15).unwrap_or_default()
}
fn entry(license: Option<&str>) -> SbomEntry {
let mut e = SbomEntry::new("r".into(), "lib".into(), "1.0".into(), "npm".into());
e.license = license.map(String::from);
e
}
fn concluded(license: &str, category: LicenseCategory) -> LicenseConclusion {
let key = package_key("lib", "npm", None);
LicenseConclusion {
id: conclusion_id(&key, None),
package_key: key,
name: "lib".into(),
package_manager: "npm".into(),
version: None,
license: license.into(),
license_name: None,
category,
copyright: Vec::new(),
license_text: None,
license_url: None,
evidence: None,
contract_ref: None,
valid_until: None,
usage: None,
note: None,
by: "u".into(),
by_name: None,
support: false,
at: Utc::now(),
review: None,
}
}
fn review(decision: ReviewDecision) -> LegalReview {
LegalReview {
decision,
by: "legal".into(),
by_name: None,
support: false,
note: None,
at: Utc::now(),
}
}
#[test]
fn the_default_allows_permissive_and_reviews_copyleft_when_shipped() {
let p = LicensePolicy::default();
assert_eq!(
evaluate(&entry(Some("MIT")), &p, today()).action,
PolicyAction::Allow
);
assert_eq!(
evaluate(&entry(Some("GPL-3.0-only")), &p, today()).action,
PolicyAction::Review
);
let unknown = evaluate(&entry(None), &p, today());
assert_eq!(unknown.action, PolicyAction::Review);
assert!(unknown.reasons.contains(&VerdictReason::Unknown));
}
#[test]
fn build_only_follows_the_build_rule() {
let p = LicensePolicy::default();
let mut e = entry(Some("GPL-3.0-only"));
let mut c = concluded("GPL-3.0-only", LicenseCategory::StrongCopyleft);
c.usage = Some(LicenseUsage::BuildOnly);
e.concluded = Some(c);
let v = evaluate(&e, &p, today());
assert!(!v.shipped);
assert_eq!(v.action, PolicyAction::Allow);
}
#[test]
fn or_takes_the_least_and_and_the_most_strict() {
let mut p = LicensePolicy::default();
p.licenses.push(LicenseRule {
license: "GPL-3.0-only".into(),
action: PolicyAction::Forbid,
note: None,
});
assert_eq!(
evaluate(&entry(Some("MIT OR GPL-3.0-only")), &p, today()).action,
PolicyAction::Allow
);
assert_eq!(
evaluate(&entry(Some("MIT AND GPL-3.0-only")), &p, today()).action,
PolicyAction::Forbid
);
}
#[test]
fn a_licence_rule_beats_its_category() {
let mut p = LicensePolicy::default();
p.licenses.push(LicenseRule {
license: "LGPL-2.1-only".into(),
action: PolicyAction::Allow,
note: None,
});
let v = evaluate(&entry(Some("LGPL-2.1-only")), &p, today());
assert_eq!(v.action, PolicyAction::Allow);
assert!(matches!(v.reasons[0], VerdictReason::License { .. }));
}
#[test]
fn a_custom_licence_takes_the_category_a_person_gave() {
let p = LicensePolicy::default();
let mut e = entry(None);
e.concluded = Some(concluded("LicenseRef-Own", LicenseCategory::OwnCode));
assert_eq!(evaluate(&e, &p, today()).action, PolicyAction::Allow);
e.concluded = Some(concluded("LicenseRef-Eula", LicenseCategory::Proprietary));
assert_eq!(evaluate(&e, &p, today()).action, PolicyAction::Review);
}
#[test]
fn approval_resolves_a_review_but_not_a_ban() {
let mut p = LicensePolicy::default();
let mut e = entry(None);
let mut c = concluded("GPL-2.0-only", LicenseCategory::StrongCopyleft);
c.review = Some(review(ReviewDecision::Approved));
e.concluded = Some(c.clone());
let v = evaluate(&e, &p, today());
assert_eq!(
(v.required, v.action),
(PolicyAction::Review, PolicyAction::Allow)
);
let mut counts = VerdictCounts::default();
counts.add(&v);
assert_eq!((counts.allowed, counts.approved), (1, 1));
p.licenses.push(LicenseRule {
license: "GPL-2.0-only".into(),
action: PolicyAction::Forbid,
note: None,
});
assert_eq!(evaluate(&e, &p, today()).action, PolicyAction::Forbid);
c.review = Some(review(ReviewDecision::Rejected));
e.concluded = Some(c);
assert_eq!(
evaluate(&e, &LicensePolicy::default(), today()).action,
PolicyAction::Forbid
);
}
#[test]
fn an_ended_licence_is_forbidden_and_an_ending_one_announced() {
let p = LicensePolicy::default();
let mut e = entry(None);
let mut c = concluded("LicenseRef-Eula", LicenseCategory::Proprietary);
c.valid_until = NaiveDate::from_ymd_opt(2026, 10, 1);
c.review = Some(review(ReviewDecision::Approved));
e.concluded = Some(c.clone());
assert_eq!(evaluate(&e, &p, today()).action, PolicyAction::Forbid);
c.valid_until = NaiveDate::from_ymd_opt(2026, 11, 1);
e.concluded = Some(c);
let v = evaluate(&e, &p, today());
assert_eq!(v.action, PolicyAction::Allow);
assert!(v
.reasons
.iter()
.any(|r| matches!(r, VerdictReason::ExpiresSoon { .. })));
}
#[test]
fn normalising_fills_every_category_and_checks_licence_ids() {
let p = LicensePolicy {
categories: vec![CategoryRule {
category: LicenseCategory::Permissive,
shipped: PolicyAction::Review,
build_only: PolicyAction::Allow,
}],
licenses: vec![LicenseRule {
license: " gpl-3.0-only ".into(),
action: PolicyAction::Forbid,
note: Some(" ".into()),
}],
..LicensePolicy::default()
}
.normalised()
.unwrap_or_default();
assert_eq!(p.categories.len(), LicenseCategory::ALL.len());
assert_eq!(
p.category_rule(LicenseCategory::Permissive).shipped,
PolicyAction::Review
);
assert_eq!(p.licenses[0].license, "GPL-3.0-only");
assert_eq!(p.licenses[0].note, None);
let bad = LicensePolicy {
licenses: vec![LicenseRule {
license: "Some EULA".into(),
action: PolicyAction::Forbid,
note: None,
}],
..LicensePolicy::default()
};
assert!(bad.normalised().is_err());
}
}
+10
View File
@@ -4,10 +4,13 @@ pub mod credentials;
pub mod cve;
pub mod dast;
pub mod embedding;
pub mod exclude_paths;
pub mod finding;
pub mod git_source;
pub mod graph;
pub mod issue;
pub mod license;
pub mod license_policy;
pub mod mcp;
pub mod mcp_token;
pub mod notification;
@@ -37,6 +40,9 @@ pub use dast::{
DastTarget, DastTargetType, DastVulnType,
};
pub use embedding::{CodeEmbedding, EmbeddingBuildRun, EmbeddingBuildStatus};
pub use exclude_paths::{
normalise_exclude_paths, ExcludePathError, MAX_EXCLUDE_PATHS, MAX_EXCLUDE_PATH_LEN,
};
pub use finding::{
Finding, FindingStatus, Occurrence, ScanChangeKind, ScanStatusChange, Severity, StatusChange,
};
@@ -45,6 +51,10 @@ pub use graph::{
CodeEdge, CodeEdgeKind, CodeNode, CodeNodeKind, GraphBuildRun, GraphBuildStatus, ImpactAnalysis,
};
pub use issue::{IssueStatus, TrackerIssue, TrackerType};
pub use license::{LicenseCategory, LicenseConclusion, LicenseUsage};
pub use license_policy::{
LegalReview, LicensePolicy, LicenseVerdict, PolicyAction, ReviewDecision,
};
pub use mcp::{McpServerConfig, McpServerStatus, McpTransport};
pub use mcp_token::{McpToken, McpTokenView};
pub use notification::{CveNotification, NotificationSeverity, NotificationStatus};
+14
View File
@@ -84,6 +84,9 @@ pub enum ArtifactKind {
PlcProject,
/// Free-form plaintext describing the target (feeds classification only).
PlaintextDescription,
/// What a build wrote about its image: a Yocto image's SPDX archive
/// (`<image>.spdx.tar.zst`).
BuildOutput,
}
impl std::fmt::Display for ArtifactKind {
@@ -97,6 +100,7 @@ impl std::fmt::Display for ArtifactKind {
Self::LiveUrl => write!(f, "live_url"),
Self::PlcProject => write!(f, "plc_project"),
Self::PlaintextDescription => write!(f, "plaintext_description"),
Self::BuildOutput => write!(f, "build_output"),
}
}
}
@@ -328,6 +332,11 @@ impl Artifact {
Self::bare(ArtifactKind::MobilePackage, source_ref)
}
/// A build-output artifact (a Yocto image's SPDX archive) by file name.
pub fn build_output(source_ref: impl Into<String>) -> Self {
Self::bare(ArtifactKind::BuildOutput, source_ref)
}
/// A container-image artifact referenced by OCI ref.
pub fn container_image(source_ref: impl Into<String>) -> Self {
Self::bare(ArtifactKind::ContainerImage, source_ref)
@@ -417,6 +426,10 @@ pub struct TargetScanConfig {
pub pentest: Option<PentestConfig>,
/// Issue-tracker linkage.
pub issue_tracker: Option<IssueTrackerConfig>,
/// Directories and files left out of every scan stage, relative to the
/// tree's root, as [`super::normalise_exclude_paths`] stores them.
#[serde(default)]
pub exclude_paths: Vec<String>,
}
/// A sibling product in the company suite that may already hold authoritative
@@ -798,6 +811,7 @@ mod tests {
assert_eq!(TargetType::PlcSps.to_string(), "plc_sps");
assert_eq!(ArtifactKind::PlcProject.to_string(), "plc_project");
assert_eq!(ArtifactKind::MobilePackage.to_string(), "mobile_package");
assert_eq!(ArtifactKind::BuildOutput.to_string(), "build_output");
}
#[test]
+25
View File
@@ -41,6 +41,9 @@ pub enum InImageBasis {
/// read from the recipes without BitBake: what the image declares, not
/// what a build resolved.
Declared,
/// The build's own SPDX lists one of its packages in the image (Yocto's
/// create-spdx): what the build installed.
Built,
}
impl InImageBasis {
@@ -48,6 +51,7 @@ impl InImageBasis {
pub fn as_str(self) -> &'static str {
match self {
Self::Declared => "declared",
Self::Built => "built",
}
}
@@ -55,6 +59,7 @@ impl InImageBasis {
pub fn describe(self) -> &'static str {
match self {
Self::Declared => "In the image (declared in the recipes, not resolved by bitbake)",
Self::Built => "In the image (installed by the build, from its SPDX)",
}
}
}
@@ -119,6 +124,16 @@ pub struct SbomEntry {
/// stored before it was recorded.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub in_image: Option<InImage>,
/// The licence a person confirmed for the component
/// ([`super::license::LicenseConclusion`]). Never stored with it: a scan
/// rewrites the components, so it is attached when they are read.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub concluded: Option<super::license::LicenseConclusion>,
/// What the workspace's licence policy says about it
/// ([`super::license_policy::evaluate`]). Never stored: worked out when
/// the list is read.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub policy: Option<super::license_policy::LicenseVerdict>,
#[serde(with = "super::serde_helpers::bson_datetime")]
pub created_at: DateTime<Utc>,
#[serde(with = "super::serde_helpers::bson_datetime")]
@@ -135,6 +150,14 @@ pub struct ComponentHash {
}
impl SbomEntry {
/// The licence that counts: the confirmed one, else the detected one.
pub fn effective_license(&self) -> Option<&str> {
match &self.concluded {
Some(c) => Some(c.display()),
None => self.license.as_deref().filter(|l| !l.trim().is_empty()),
}
}
pub fn new(repo_id: String, name: String, version: String, package_manager: String) -> Self {
let now = Utc::now();
Self {
@@ -153,6 +176,8 @@ impl SbomEntry {
manufacturer_url: None,
cpe: None,
in_image: None,
concluded: None,
policy: None,
created_at: now,
updated_at: now,
}
+20 -1
View File
@@ -202,6 +202,15 @@ pub enum SkipCode {
/// Vendor and third-party directories left out of SAST; `subject` lists
/// them.
VendorCode,
/// Packages a build's image SPDX lists in the image without their
/// documents, so their recipes are not known; `subject` lists them.
BuildPackagesUnresolved,
/// Test-data directories (`fixtures/`, `testdata/`) left out of the whole
/// scan: code findings, SBOM and CVE match; `subject` lists them.
TestData,
/// Paths the target's settings exclude (`scan_config.exclude_paths`),
/// left out of the whole scan; `subject` lists those that were removed.
ExcludedPaths,
/// An analysis tool did not complete; `subject` names it.
ToolFailed,
/// A package manifest without a lockfile; `subject` is the manifest.
@@ -211,6 +220,10 @@ pub enum SkipCode {
NotAnalysedYet,
/// A PLC project archive that could not be read; `subject` is its name.
ArchiveUnreadable,
/// CODESYS projects in their native (binary) format, whose control logic
/// is not analysed until they are exported as PLCopen XML; `subject`
/// lists them.
NativePlcProject,
/// An uploaded or linked artifact that could not be read; `subject` is
/// its name.
ArtifactNotIngested,
@@ -266,13 +279,19 @@ impl SkipCode {
pub fn is_informational(self) -> bool {
// An exhaustive match, so a new code has to be classified here.
match self {
Self::VendorCode | Self::SuppressedInSource | Self::NotInTree => true,
Self::VendorCode
| Self::TestData
| Self::BuildPackagesUnresolved
| Self::ExcludedPaths
| Self::SuppressedInSource
| Self::NotInTree => true,
Self::FeatureDisabled
| Self::SubmodulesNotFetched
| Self::ToolFailed
| Self::DependenciesUnlocked
| Self::NotAnalysedYet
| Self::ArchiveUnreadable
| Self::NativePlcProject
| Self::ArtifactNotIngested
| Self::ArchivePasswordRequired
| Self::ArchivePasswordWrong
+267 -12
View File
@@ -9,7 +9,8 @@
//! the suppliers declare them.
use crate::models::{
advisory_source, is_cve, ComponentHash, SbomEntry, YOCTO_RECIPE_MANAGER, YOCTO_RECIPE_SOURCE,
advisory_source, is_cve, ComponentHash, LicenseConclusion, SbomEntry, YOCTO_RECIPE_MANAGER,
YOCTO_RECIPE_SOURCE,
};
use crate::purl::Purl;
use crate::spdx_license;
@@ -32,8 +33,8 @@ pub fn product_ref(subject: &str) -> String {
/// A license as CycloneDX writes it: an SPDX id, an SPDX expression
/// (`MIT OR Apache-2.0`), or a named license. A name or URL of a license
/// SPDX lists becomes its id ([`spdx_license::normalise`], BSI TR-03183-2).
/// It is the license the supplier declares (registry or lockfile metadata):
/// Prüfwerk has not concluded it.
/// It is the license the supplier declares (registry or lockfile metadata);
/// a license a person confirmed is written by [`concluded_choice`] instead.
fn license_choice(license: &str) -> serde_json::Value {
let license = spdx_license::normalise(license);
if spdx_license::canonical_id(&license) == Some(&*license) {
@@ -45,6 +46,87 @@ fn license_choice(license: &str) -> serde_json::Value {
}
}
/// The licence a person confirmed, as CycloneDX writes a concluded licence:
/// an SPDX id or expression, or a licence of its own by name with its text
/// and URL. CycloneDX takes either licences or one expression, never both,
/// so the declared licence is then kept as a property
/// ([`DECLARED_LICENSE_PROPERTY`]).
fn concluded_choice(c: &LicenseConclusion) -> serde_json::Value {
if c.is_custom() {
let mut license = serde_json::json!({
"name": c.display(),
"acknowledgement": "concluded",
});
if let Some(text) = &c.license_text {
license["text"] = serde_json::json!({ "contentType": "text/plain", "content": text });
}
if let Some(url) = &c.license_url {
license["url"] = serde_json::Value::String(url.clone());
}
serde_json::json!([{ "license": license }])
} else if spdx_license::canonical_id(&c.license) == Some(c.license.as_str()) {
serde_json::json!([{ "license": { "id": c.license, "acknowledgement": "concluded" } }])
} else {
serde_json::json!([{ "expression": c.license, "acknowledgement": "concluded" }])
}
}
/// The property holding the licence the scan detected, where a person
/// confirmed another one.
const DECLARED_LICENSE_PROPERTY: &str = "pruefwerk:license:declared";
/// The properties of a confirmed licence: its category, where the component
/// is used, a bought licence's contract and end, where it was found, and who
/// confirmed it when.
fn conclusion_properties(entry: &SbomEntry, c: &LicenseConclusion) -> Vec<serde_json::Value> {
let mut props = vec![serde_json::json!({
"name": "pruefwerk:license:category",
"value": c.category.as_str(),
})];
let mut push = |name: &str, value: Option<String>| {
if let Some(value) = value.filter(|v| !v.trim().is_empty()) {
props.push(serde_json::json!({ "name": name, "value": value }));
}
};
push(
DECLARED_LICENSE_PROPERTY,
entry.license.clone().filter(|l| l.trim() != c.license),
);
push(
"pruefwerk:license:usage",
c.usage.map(|u| match u {
crate::models::LicenseUsage::Shipped => "shipped".to_string(),
crate::models::LicenseUsage::BuildOnly => "build_only".to_string(),
}),
);
push("pruefwerk:license:contract", c.contract_ref.clone());
push(
"pruefwerk:license:valid_until",
c.valid_until.map(|d| d.to_string()),
);
push("pruefwerk:license:evidence", c.evidence.clone());
push(
"pruefwerk:license:concluded",
Some(format!(
"{} {}",
c.by_name.as_deref().unwrap_or(&c.by),
c.at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
)),
);
if let Some(review) = &c.review {
push(
"pruefwerk:license:review",
Some(format!(
"{} by {} {}",
review.decision.as_str(),
review.by_name.as_deref().unwrap_or(&review.by),
review.at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
)),
);
}
props
}
/// The file a registry package is distributed as (`log4j-core-2.14.1.jar`),
/// where its purl determines it. `None` for a package type whose file the
/// purl does not name (PyPI wheel or sdist, Go modules) and without a version.
@@ -182,8 +264,23 @@ pub fn cdx_components(entries: &[SbomEntry]) -> Vec<serde_json::Value> {
None => comp["properties"] = serde_json::Value::Array(provenance),
}
}
if let Some(license) = e.license.as_deref().filter(|l| !l.trim().is_empty()) {
comp["licenses"] = license_choice(license);
match &e.concluded {
Some(c) => {
comp["licenses"] = concluded_choice(c);
if !c.copyright.is_empty() {
comp["copyright"] = serde_json::Value::String(c.copyright.join("\n"));
}
let props = conclusion_properties(e, c);
match comp["properties"].as_array_mut() {
Some(properties) => properties.extend(props),
None => comp["properties"] = serde_json::Value::Array(props),
}
}
None => {
if let Some(license) = e.license.as_deref().filter(|l| !l.trim().is_empty()) {
comp["licenses"] = license_choice(license);
}
}
}
if let Some(url) = &e.manufacturer_url {
comp["manufacturer"] = serde_json::json!({ "url": [url] });
@@ -368,14 +465,34 @@ pub fn cyclonedx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
/// An SPDX 2.3 document for `entries`, named after `subject`.
pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
// A `LicenseRef-` a package concludes must be defined in the document.
let mut extracted: Vec<serde_json::Value> = Vec::new();
let mut defined = std::collections::HashSet::new();
for c in entries.iter().filter_map(|e| e.concluded.as_ref()) {
if c.is_custom() && defined.insert(c.license.clone()) {
let mut info = serde_json::json!({
"licenseId": c.license,
"name": c.display(),
// SPDX requires a text; without one, where to find it.
"extractedText": c.license_text.clone().unwrap_or_else(|| {
c.license_url.clone().unwrap_or_else(|| "NOASSERTION".to_string())
}),
});
if let Some(url) = &c.license_url {
info["seeAlsos"] = serde_json::json!([url]);
}
extracted.push(info);
}
}
let packages: Vec<serde_json::Value> = entries
.iter()
.enumerate()
.map(|(i, e)| {
// The license is what the supplier declares; nothing is
// concluded without a license review of our own. SPDX takes only
// an expression of listed ids; another license is NOASSERTION,
// its text kept as a comment.
// The declared license is what the supplier declares; a license
// is concluded only where a person of the workspace confirmed one
// (`concluded`). SPDX takes only an expression of listed ids; a
// declared license that is none is NOASSERTION, its text kept as
// a comment.
let raw = e
.license
.as_deref()
@@ -389,7 +506,8 @@ pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
"name": e.name,
"versionInfo": e.version,
"downloadLocation": "NOASSERTION",
"licenseConcluded": "NOASSERTION",
// Concluded only where a person confirmed the licence.
"licenseConcluded": e.concluded.as_ref().map_or("NOASSERTION", |c| c.license.as_str()),
"licenseDeclared": license.as_deref().unwrap_or("NOASSERTION"),
"externalRefs": e.purl.as_ref().map(|p| vec![serde_json::json!({
"referenceCategory": "PACKAGE-MANAGER",
@@ -400,6 +518,31 @@ pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
if let (Some(raw), None) = (raw, &license) {
package["licenseComments"] = serde_json::Value::String(format!("Declared: {raw}"));
}
if let Some(c) = &e.concluded {
if !c.copyright.is_empty() {
package["copyrightText"] = serde_json::Value::String(c.copyright.join("\n"));
}
let by = c.by_name.as_deref().unwrap_or(&c.by);
let mut note = format!(
"Concluded by {by} on {} ({})",
c.at.format("%Y-%m-%d"),
c.category.as_str()
);
if let Some(review) = &c.review {
note.push_str(&format!(
"; legal review: {} by {} on {}",
review.decision.as_str(),
review.by_name.as_deref().unwrap_or(&review.by),
review.at.format("%Y-%m-%d")
));
}
package["licenseComments"] = serde_json::Value::String(
match package["licenseComments"].as_str() {
Some(declared) => format!("{declared}. {note}"),
None => note,
},
);
}
if let (Some(cpe), Some(refs)) = (&e.cpe, package["externalRefs"].as_array_mut()) {
refs.push(serde_json::json!({
"referenceCategory": "SECURITY",
@@ -414,14 +557,18 @@ pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
})
.collect();
serde_json::json!({
let mut doc = serde_json::json!({
"spdxVersion": "SPDX-2.3",
"dataLicense": "CC0-1.0",
"SPDXID": "SPDXRef-DOCUMENT",
"name": format!("sbom-{subject}"),
"documentNamespace": format!("https://compliance-scanner/sbom/{subject}"),
"packages": packages,
})
});
if !extracted.is_empty() {
doc["hasExtractedLicensingInfos"] = serde_json::Value::Array(extracted);
}
doc
}
#[cfg(test)]
@@ -558,4 +705,112 @@ mod tests {
);
assert_eq!(spdx["packages"][1]["comment"], YOCTO_RECIPE_SOURCE);
}
fn concluded(license: &str, name: Option<&str>) -> LicenseConclusion {
use crate::models::license::{conclusion_id, package_key};
let key = package_key("pump-sdk", "nuget", None);
LicenseConclusion {
id: conclusion_id(&key, None),
package_key: key,
name: "pump-sdk".into(),
package_manager: "nuget".into(),
version: None,
license: license.into(),
license_name: name.map(String::from),
category: crate::models::LicenseCategory::Proprietary,
copyright: vec!["© 2019 Example GmbH".into()],
license_text: Some("All rights reserved.".into()),
license_url: None,
evidence: Some("contract 4711".into()),
contract_ref: Some("4711".into()),
valid_until: chrono::NaiveDate::from_ymd_opt(2027, 12, 31),
usage: Some(crate::models::LicenseUsage::Shipped),
note: None,
by: "u1".into(),
by_name: Some("Erika Muster".into()),
support: false,
at: chrono::Utc::now(),
review: None,
}
}
#[test]
fn a_confirmed_custom_licence_is_concluded_and_defined() {
let mut e = SbomEntry::new("t".into(), "pump-sdk".into(), "3.1".into(), "nuget".into());
e.license = Some("LicenseRef-file".into());
e.concluded = Some(concluded("LicenseRef-Pump-EULA", Some("Pump EULA")));
let cdx = cyclonedx(std::slice::from_ref(&e), "t");
let comp = &cdx["components"][0];
assert_eq!(comp["licenses"][0]["license"]["name"], "Pump EULA");
assert_eq!(
comp["licenses"][0]["license"]["acknowledgement"],
"concluded"
);
assert_eq!(
comp["licenses"][0]["license"]["text"]["content"],
"All rights reserved."
);
assert_eq!(comp["copyright"], "© 2019 Example GmbH");
let props = comp["properties"].as_array().unwrap();
let prop = |n: &str| {
props
.iter()
.find(|p| p["name"] == n)
.map(|p| p["value"].clone())
};
assert_eq!(
prop("pruefwerk:license:category"),
Some("proprietary".into())
);
assert_eq!(
prop(DECLARED_LICENSE_PROPERTY),
Some("LicenseRef-file".into())
);
assert_eq!(
prop("pruefwerk:license:valid_until"),
Some("2027-12-31".into())
);
assert_eq!(prop("pruefwerk:license:usage"), Some("shipped".into()));
let spdx = spdx(&[e], "t");
let package = &spdx["packages"][0];
assert_eq!(package["licenseConcluded"], "LicenseRef-Pump-EULA");
assert_eq!(package["copyrightText"], "© 2019 Example GmbH");
assert!(package["licenseComments"]
.as_str()
.unwrap()
.contains("Concluded by Erika Muster"));
let info = &spdx["hasExtractedLicensingInfos"][0];
assert_eq!(info["licenseId"], "LicenseRef-Pump-EULA");
assert_eq!(info["extractedText"], "All rights reserved.");
}
#[test]
fn a_confirmed_spdx_licence_replaces_the_declared_one() {
let mut one = SbomEntry::new("t".into(), "a".into(), "1".into(), "npm".into());
one.concluded = Some(concluded("MIT", None));
let mut two = SbomEntry::new("t".into(), "b".into(), "1".into(), "npm".into());
two.license = Some("MIT".into());
two.concluded = Some(concluded("MIT OR Apache-2.0", None));
let cdx = cyclonedx(&[one.clone(), two.clone()], "t");
assert_eq!(cdx["components"][0]["licenses"][0]["license"]["id"], "MIT");
assert_eq!(
cdx["components"][0]["licenses"][0]["license"]["acknowledgement"],
"concluded"
);
assert_eq!(
cdx["components"][1]["licenses"][0]["expression"],
"MIT OR Apache-2.0"
);
assert_eq!(
cdx["components"][1]["licenses"].as_array().unwrap().len(),
1
);
let spdx = spdx(&[one, two], "t");
assert_eq!(spdx["packages"][0]["licenseConcluded"], "MIT");
assert_eq!(spdx["packages"][0]["licenseDeclared"], "NOASSERTION");
assert_eq!(spdx["packages"][1]["licenseConcluded"], "MIT OR Apache-2.0");
assert_eq!(spdx["packages"][1]["licenseDeclared"], "MIT");
assert!(spdx.get("hasExtractedLicensingInfos").is_none());
}
}
Loaded 100 of 175 files, more files were not shown because too many files have changed in this diff. Show more