Compare commits

..
69 Commits
Author SHA1 Message Date
sharang 01a24f4556 test(nightly): a Yocto target with only its SPDX 3.0 image document (#150) (#860)
CI / Detect Changes (push) Successful in 4s
CI / Deploy Agent (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Agent integration (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Check (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 / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Successful in 1m7s
CI / Deploy Agent (push) Successful in 5m30s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
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 / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m9s
CI / Deploy Agent (push) Successful in 5m48s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
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 / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m8s
CI / Deploy Agent (push) Successful in 6m10s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
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 / Detect Changes (push) Successful in 5s
CI / Deploy Agent (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Check (push) Skipped
CI / Agent integration (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 / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m4s
CI / Deploy Agent (push) Successful in 8m27s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Deploy Dashboard (push) Successful in 6m16s
CI / Deploy MCP (push) Skipped
2026-11-04 23:18:50 +00:00
sharang c2fbffd2c6 feat(yocto): Yocto's own cve-check verdicts join the scan (#150) (#854)
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m29s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
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 / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 6m59s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 6s
CI / Deploy Dashboard (push) Successful in 4m57s
CI / Deploy MCP (push) Successful in 3m0s
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 / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 8m1s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
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 / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m12s
CI / Deploy Agent (push) Successful in 5m33s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
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 / Deploy Docs (push) Successful in 1m10s
CI / Deploy Agent (push) Successful in 6m30s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
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 / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Successful in 1m7s
CI / Deploy Agent (push) Successful in 5m24s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
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 / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m11s
CI / Deploy Agent (push) Successful in 8m56s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Deploy Dashboard (push) Successful in 6m46s
CI / Deploy MCP (push) Successful in 4m52s
2026-11-04 09:13:00 +00:00
sharang 533d5f35b5 fix(issues): a skipped scan still catches up the deferred issues (#826)
CI / Detect Changes (push) Successful in 7s
CI / Deploy Docs (push) Successful in 1m13s
CI / Deploy Agent (push) Successful in 6m45s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
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 / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Successful in 1m14s
CI / Deploy Agent (push) Successful in 10m50s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Deploy Dashboard (push) Successful in 7m56s
CI / Deploy MCP (push) Successful in 2m53s
2026-11-04 08:48:40 +00:00
sharang e01d2146e9 fix(nightly): no chat model, and GitHub Actions by major version (#573) (#821)
CI / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m23s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
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 / Deploy Agent (push) Canceled after 0s
CI / Deploy Docs (push) Successful in 1m16s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Deploy Dashboard (push) Successful in 6m46s
CI / Deploy MCP (push) Successful in 4m57s
2026-11-04 08:28:51 +00:00
sharang 5b0bf08478 fix(mobile): a manifest rule counts only on an AndroidManifest.xml (#824)
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 9m15s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
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 / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m54s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
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 / Detect Changes (push) Successful in 7s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Canceled after 0s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
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 / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 8m51s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
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 / Detect Changes (push) Successful in 4s
CI / Deploy Agent (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Check (push) Skipped
CI / Agent integration (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 / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 8m11s
CI / Check (push) Skipped
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 / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m9s
CI / Deploy Agent (push) Successful in 7m36s
CI / Check (push) Skipped
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 / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m34s
CI / Check (push) Skipped
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 / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 6m1s
CI / Check (push) Skipped
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 / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 6m15s
CI / Check (push) Skipped
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 / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m37s
CI / Deploy Agent (push) Successful in 12m9s
CI / Check (push) Skipped
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 / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 7m33s
CI / Check (push) Skipped
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 / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 6m0s
CI / Check (push) Skipped
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 / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 7m38s
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Dashboard (push) Successful in 5m41s
CI / Deploy MCP (push) Successful in 4m19s
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 / Detect Changes (push) Successful in 5s
CI / Deploy Agent (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Check (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 / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m25s
CI / Deploy Agent (push) Successful in 10m24s
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Successful in 11m57s
CI / Deploy MCP (push) Successful in 5m21s
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 / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 10m24s
CI / Check (push) Skipped
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 / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 12m40s
CI / Detect Changes (push) Successful in 3s
CI / Deploy Dashboard (push) Successful in 14m39s
CI / Check (push) Skipped
CI / Deploy MCP (push) Successful in 5m41s
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 / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 7m28s
CI / Detect Changes (push) Successful in 4s
CI / Deploy Dashboard (push) Successful in 5m29s
CI / Check (push) Skipped
CI / Deploy MCP (push) Skipped
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 / Detect Changes (push) Successful in 4s
CI / Deploy Dashboard (push) Successful in 6m22s
CI / Check (push) Skipped
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 / Deploy Docs (push) Successful in 1m16s
CI / Deploy Agent (push) Successful in 8m39s
CI / Detect Changes (push) Successful in 4s
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Successful in 6m40s
CI / Deploy MCP (push) Successful in 4m49s
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 / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Successful in 1m12s
CI / Deploy Agent (push) Successful in 5m25s
CI / Check (push) Skipped
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 / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m35s
CI / Check (push) Skipped
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 / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m6s
CI / Check (push) Skipped
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 / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m41s
CI / Check (push) Skipped
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 / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m23s
CI / Deploy Agent (push) Successful in 5m32s
CI / Check (push) Skipped
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 / Detect Changes (push) Successful in 3s
CI / Deploy Agent (push) Successful in 9m55s
CI / Check (push) Skipped
CI / Deploy MCP (push) Successful in 4m36s
CI / Deploy Dashboard (push) Successful in 10m29s
2026-10-13 22:07:02 +00:00
sharang 860d1a78bf fix(eol): end-of-life findings are high, soon is medium, and non-LTS Yocto releases warn two months ahead (#562)
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m14s
CI / Deploy Agent (push) Successful in 8m0s
CI / Deploy Dashboard (push) Successful in 6m17s
CI / Check (push) Skipped
CI / Deploy MCP (push) Successful in 4m30s
2026-10-09 19:28:49 +00:00
sharang a3735b12b7 chore(deps): remove dependencies nothing uses (#561)
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 8m35s
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Successful in 5m57s
CI / Deploy MCP (push) Successful in 3m17s
2026-10-09 18:58:27 +00:00
sharang db515486a4 feat(yocto): layer pins from kas, repo manifests and submodules, and a finding when the Yocto release is end of life (#559)
CI / Detect Changes (push) Successful in 5s
CI / Deploy Agent (push) Successful in 10m26s
CI / Deploy Docs (push) Successful in 1m20s
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Successful in 6m45s
CI / Deploy MCP (push) Successful in 3m57s
2026-10-09 18:40:00 +00:00
sharang d9f5ad85dc ci: the agent redeploys when werkbank-exec, control-map or docker/ change (#560)
CI / Detect Changes (push) Successful in 4s
CI / Deploy Agent (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-10-09 18:33:57 +00:00
sharang 64f5a810dd feat(scans): a scan run lists informational notes apart from skipped stages (#556)
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 6m59s
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Successful in 6m27s
CI / Deploy MCP (push) Successful in 3m20s
2026-10-09 18:21:28 +00:00
sharang 57b5aaeb97 feat(cve): the daily monitor re-checks NVD/CPE-only components incrementally (#558)
CI / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Successful in 1m19s
CI / Deploy Agent (push) Successful in 9m5s
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-10-09 18:19:19 +00:00
sharang ba499d14e4 feat(yocto): recipes an image recipe installs are marked as in the image (declared) (#557)
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Successful in 1m13s
CI / Deploy Agent (push) Successful in 10m7s
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Successful in 7m17s
CI / Deploy MCP (push) Successful in 3m21s
2026-10-09 17:58:38 +00:00
sharang 42b25719ec fix(cve): notifications and tracker issues respect VEX not_affected and fixed (#555)
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m15s
CI / Deploy Agent (push) Successful in 8m35s
CI / Check (push) Skipped
CI / Deploy MCP (push) Successful in 4m42s
CI / Deploy Dashboard (push) Successful in 6m30s
2026-10-09 17:07:37 +00:00
sharang 8d6be32c83 fix(yocto): recipe lint binds attack-surface findings to cra-ai-2 and counts suppressed findings (#554)
CI / Detect Changes (push) Successful in 5s
CI / Deploy Agent (push) Successful in 8m39s
CI / Deploy Docs (push) Successful in 1m13s
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Successful in 6m15s
CI / Deploy MCP (push) Successful in 3m26s
2026-10-09 16:49:27 +00:00
sharang ac50880b25 feat(yocto): the recipe inventory becomes SBOM components, CVE_STATUS and CVE patches become VEX (#551)
CI / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Successful in 1m13s
CI / Deploy Agent (push) Successful in 12m32s
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Successful in 7m53s
CI / Deploy MCP (push) Successful in 3m26s
2026-10-09 16:17:47 +00:00
sharang e382746cfb feat(issues): a catch-up files Gitea issues for open findings that never got one (off by default) (#553)
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m11s
CI / Deploy Agent (push) Successful in 8m58s
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Successful in 6m35s
CI / Deploy MCP (push) Successful in 2m54s
2026-10-09 16:08:23 +00:00
sharang 7e3856db31 feat(yocto): recipes are checked with oelint-adv and our own secure-by-default rules (#552)
CI / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Successful in 1m32s
CI / Deploy Agent (push) Successful in 13m11s
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Successful in 16m16s
CI / Deploy MCP (push) Successful in 5m11s
2026-10-09 15:48:31 +00:00
sharang 750f1d7308 feat(yocto): layer trees are detected as Embedded Linux / Yocto, and the scan matrix says what runs (#550)
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m15s
CI / Deploy Agent (push) Successful in 8m49s
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Successful in 6m40s
CI / Deploy MCP (push) Successful in 4m46s
2026-10-09 14:58:09 +00:00
sharang 528c9d4f7f feat(dashboard): Embedded Linux / Yocto is marked as a preview (#549)
CI / Deploy Docs (push) Successful in 1m15s
CI / Detect Changes (push) Successful in 4s
CI / Deploy Agent (push) Successful in 6m20s
CI / Deploy Dashboard (push) Successful in 4m9s
CI / Check (push) Skipped
CI / Deploy MCP (push) Skipped
2026-10-09 14:41:47 +00:00
sharang cc5b667870 fix(scheduler): scheduled scans are spread out and at most two clones run per git host (#547)
CI / Deploy Docs (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Agent (push) Successful in 6m28s
CI / Deploy Dashboard (push) Skipped
CI / Check (push) Skipped
CI / Deploy MCP (push) Skipped
2026-10-09 14:37:22 +00:00
sharang 11e3b98c99 fix(issues): Gitea issue sync lists once per scan and keeps at most two requests in flight per instance (#548)
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 8m50s
CI / Detect Changes (push) Successful in 4s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Check (push) Skipped
2026-10-09 14:25:29 +00:00
sharang dcf78b8e66 fix(git): clone and fetch retry three times on a 5xx or connection error (#546)
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 6m4s
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-10-09 14:22:34 +00:00
sharang 6f1172589e fix(sbom): SPDX licences are declared, and copyleft is found by SPDX id (#545)
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 6m53s
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Successful in 6m31s
CI / Deploy MCP (push) Successful in 4m48s
2026-10-09 13:57:47 +00:00
sharang 7f2b128efd feat(webhooks): the target page shows its last webhook deliveries, refused ones too (#544)
CI / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 9m6s
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Successful in 5m29s
CI / Deploy MCP (push) Successful in 3m28s
2026-10-09 13:51:47 +00:00
sharang 2c2fea6222 fix(sbom): known licence names are exported as SPDX ids (#543)
CI / Detect Changes (push) Successful in 5s
CI / Deploy Agent (push) Successful in 8m27s
CI / Deploy Docs (push) Skipped
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Successful in 5m51s
CI / Deploy MCP (push) Successful in 3m26s
2026-10-09 13:39:28 +00:00
sharang 44b2f38841 fix(vex): CVE is the primary vulnerability id in VEX, CSAF and CycloneDX, GHSA an alias (#542)
CI / Deploy Agent (push) Successful in 8m37s
CI / Deploy Docs (push) Successful in 1m15s
CI / Detect Changes (push) Successful in 5s
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Successful in 5m49s
CI / Deploy MCP (push) Successful in 3m33s
2026-10-09 13:22:05 +00:00
sharang 69a4c2084a feat(dashboard): the targets page pages server-side with page size and total (#541)
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 9m13s
CI / Check (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Successful in 6m11s
2026-10-09 13:18:20 +00:00
sharang 2ca73acabf fix(vex): the startup purl backfill always logs its count (#540)
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 7m15s
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-10-09 13:00:15 +00:00
sharang 2c5b2eb003 fix(malware): an unreachable or silent clamd is logged as an error (#539)
CI / Deploy Docs (push) Skipped
CI / Detect Changes (push) Successful in 6s
CI / Deploy Agent (push) Successful in 5m12s
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-10-09 13:00:12 +00:00
sharang e396141490 fix(webhooks): the managed Gitea webhook answers 202 and works in the background (#538)
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m24s
CI / Detect Changes (push) Successful in 2s
CI / Deploy Dashboard (push) Skipped
CI / Check (push) Skipped
CI / Deploy MCP (push) Skipped
2026-10-09 11:22:00 +00:00
270 changed files with 34446 additions and 2187 deletions

No files matched your search

+16 -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=
@@ -27,6 +31,9 @@ SEARXNG_URL=http://localhost:8888
# NVD
NVD_API_KEY=
# The CVE monitor re-checks components only NVD knows (Yocto recipes, embedded
# libraries, CODESYS runtime) by NVD's changed CVEs; on by default.
# NVD_MONITOR=off
# Agent
AGENT_PORT=3001
@@ -50,6 +57,14 @@ CVE_MONITOR_SCHEDULE=0 0 0 * * *
# FINDING_GROUP_THRESHOLD=5
# FINDING_GROUP_SCANNERS=mobsfscan=5,gitleaks=off
# FINDING_GROUP_SEVERITIES=low,info
# Issue catch-up (Gitea only): after a scan's own issues, open medium+ findings
# that never got an issue are linked to their existing issue or get a new one,
# at most 20 new per target and scan. off (default) | dry_run (log counts only) | on
# ISSUE_CATCHUP=off
# Closing CVE issues a VEX statement settles (not_affected or fixed), with a
# comment, at most 20 per target and scan; no new issue is opened for such a
# CVE either way. off (default) | dry_run (log counts per VEX status) | on
# ISSUE_AUTOCLOSE=off
GIT_CLONE_BASE_PATH=/tmp/compliance-scanner/repos
# NuGet licenses (#467): look up licenses the tree's .nuspec files do not give
# on api.nuget.org (package id and version only; never for ids a nuget.config
+112 -7
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.
@@ -176,9 +279,11 @@ jobs:
echo "Changed files:"
echo "$CHANGED"
# Agent: core libs, agent code, agent Dockerfile, and the docs and
# README the help assistant answers from (baked into the image)
if echo "$CHANGED" | grep -qE '^(compliance-core/|compliance-agent/|compliance-graph/|compliance-dast/|Dockerfile\.agent|Cargo\.(toml|lock)|docs/|README\.md)'; then
# Agent: core libs and the crates the agent links (werkbank-exec,
# control-map), agent code, agent Dockerfile and the helper scripts
# it copies from docker/, and the docs and README the help assistant
# answers from (baked into the image)
if echo "$CHANGED" | grep -qE '^(compliance-core/|compliance-agent/|compliance-graph/|compliance-dast/|werkbank-exec/|control-map/|docker/|Dockerfile\.agent|Cargo\.(toml|lock)|docs/|README\.md)'; then
echo "agent=true" >> "$GITHUB_OUTPUT"
else
echo "agent=false" >> "$GITHUB_OUTPUT"
@@ -236,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}" .
@@ -271,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"
@@ -302,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
@@ -334,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 }}
+3
View File
@@ -7,3 +7,6 @@
.playwright-mcp/
report-preview-full.png
compliance-dashboard/attack-chain-final.html
# Python bytecode (the agent image helpers)
__pycache__/
Generated
+513 -632
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"
+24 -3
View File
@@ -11,11 +11,15 @@ 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.
ARG MOBSFSCAN_VERSION=1.0.1
# Yocto recipe lint (BSD-2-Clause): only its security rules run.
ARG OELINT_ADV_VERSION=9.11.2
# The recipe inventory reads the recipes with the same oelint-parser.
ARG OELINT_PARSER_VERSION=8.13.2
# DevSkim (MIT) is published as a .NET tool on nuget.org, not as a release
# binary: the package is pinned by checksum and run on the .NET runtime (MIT).
ARG DEVSKIM_VERSION=1.0.100
@@ -63,6 +67,8 @@ ARG SBOMQS_SHA256
ARG SEMGREP_VERSION
ARG RUFF_VERSION
ARG MOBSFSCAN_VERSION
ARG OELINT_ADV_VERSION
ARG OELINT_PARSER_VERSION
ARG DEVSKIM_VERSION
ARG DEVSKIM_SHA256
ARG DOTNET_RUNTIME_VERSION
@@ -74,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
@@ -117,6 +127,16 @@ RUN pip3 install --break-system-packages --no-cache-dir --no-deps \
"tabulate==0.10.0" "xmltodict==1.0.4"
COPY docker/pruefwerk_mobsfscan.py /opt/pruefwerk/pruefwerk_mobsfscan.py
# Yocto recipe lint and recipe inventory; see
# compliance-agent/src/pipeline/recipe_lint/oelint.rs and yocto_inventory.rs.
# Its dependencies are pinned with it (oelint-parser reads the recipes;
# deprecated's wrapt is the 1.x semgrep's OpenTelemetry already installed).
RUN pip3 install --break-system-packages --no-cache-dir \
"oelint-adv==${OELINT_ADV_VERSION}" "oelint-parser==${OELINT_PARSER_VERSION}" "oelint-data==1.5.23" \
"anytree==2.13.0" "argcomplete==3.7.2" "urllib3==2.8.0" "regex==2026.9.29" \
"deprecated==1.3.1"
COPY docker/pruefwerk_yocto_recipes.py /opt/pruefwerk/pruefwerk_yocto_recipes.py
# .NET SAST without a build (#494): DevSkim on C#, VB.NET and .config files.
# The .NET runtime only (no SDK), with invariant globalisation so it needs no
# ICU; of DevSkim's bundled native libraries only the linux-x64 ones are kept.
@@ -139,10 +159,11 @@ RUN curl -sSfL -o /tmp/dotnet.tar.gz \
COPY --chmod=0755 docker/devskim.sh /usr/local/bin/devskim
RUN mkdir -p /opt/pruefwerk \
&& printf '{"rust":"%s","cargo-audit":"%s","syft":"%s","betterleaks":"%s","semgrep":"%s","ruff":"%s","cppcheck":"%s","mobsfscan":"%s","sbomqs":"%s","devskim":"%s","dotnet-runtime":"%s"}\n' \
&& printf '{"rust":"%s","cargo-audit":"%s","syft":"%s","betterleaks":"%s","semgrep":"%s","ruff":"%s","cppcheck":"%s","mobsfscan":"%s","oelint-adv":"%s","oelint-parser":"%s","sbomqs":"%s","devskim":"%s","dotnet-runtime":"%s"}\n' \
"${RUST_VERSION}" "${CARGO_AUDIT_VERSION}" "${SYFT_VERSION}" "${BETTERLEAKS_VERSION}" \
"${SEMGREP_VERSION}" "${RUFF_VERSION}" "$(cppcheck --version | cut -d' ' -f2)" \
"${MOBSFSCAN_VERSION}" "${SBOMQS_VERSION}" "${DEVSKIM_VERSION}" "${DOTNET_RUNTIME_VERSION}" \
"${MOBSFSCAN_VERSION}" "${OELINT_ADV_VERSION}" "${OELINT_PARSER_VERSION}" "${SBOMQS_VERSION}" "${DEVSKIM_VERSION}" \
"${DOTNET_RUNTIME_VERSION}" \
> /opt/pruefwerk/tool-versions.json
# The agent runs unprivileged. It writes only to its home (tool caches), the
+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
+4 -2
View File
@@ -55,15 +55,17 @@ walkdir = "2"
toml = "0.8"
# Read-only XML tree parsing for PLCopen project files (POU extraction).
roxmltree = "0.20"
# kas project files (Yocto layer pins); already in the tree through firmwerk-core.
yaml-rust2 = { version = "0.13", default-features = false }
base64 = "0.22"
urlencoding = "2"
futures-util = "0.3"
jsonwebtoken = "9"
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"] }
futures-core = "0.3"
dashmap = { workspace = true }
tokio-stream = { workspace = true }
rand = { 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"
}
]
}
+29 -7
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))
@@ -146,7 +156,8 @@ impl ComplianceAgent {
/// Scan a target, through the [`ScanGate`]: at most `SCAN_CONCURRENCY` scans
/// run at once, and a request for a target that is already being scanned is
/// coalesced — it becomes the one pending follow-up that this task runs next,
/// or it is dropped if a follow-up is already pending. Every trigger
/// or it is dropped if a follow-up is already pending. A scheduled scan
/// first waits a random [`crate::scan_gate::start_delay`]. Every trigger
/// (click, webhook, scheduler, demo seed) comes through here.
///
/// # Errors
@@ -158,6 +169,17 @@ impl ComplianceAgent {
target_id: &str,
trigger: compliance_core::models::ScanTrigger,
) -> Result<(), crate::error::AgentError> {
// Scheduled scans spread out before they take a slot or the target.
let delay = crate::scan_gate::start_delay(&trigger);
if !delay.is_zero() {
tracing::debug!(
tenant_id,
target_id,
delay_ms = delay.as_millis(),
"scheduled scan waits"
);
tokio::time::sleep(delay).await;
}
let key = ScanGate::key(tenant_id, target_id);
match self.scan_gate.admit(&key, trigger.clone()) {
Admission::Run => {}
+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)
);
}
}
+17
View File
@@ -226,6 +226,14 @@ pub struct SbomFilter {
pub has_vulns: Option<bool>,
#[serde(default)]
pub license: Option<String>,
/// Only components an image is known to contain (`true`), or only the
/// 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")]
@@ -263,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>,
}
@@ -655,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 ─────────────────────────────────
+12 -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,
})
}
@@ -95,6 +99,7 @@ fn state_counts(controls: &[crate::evidence::compliance::ControlStatus]) -> serd
"not_satisfied": count(ControlState::NotSatisfied),
"no_violation_found": count(ControlState::NoViolationFound),
"not_assessed": count(ControlState::NotAssessed),
"partial": count(ControlState::Partial),
"not_code_checkable": count(ControlState::NotCodeCheckable),
})
}
@@ -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" })))
}
+60 -3
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
@@ -99,7 +134,12 @@ pub async fn stats_overview(
.limit(10)
.await
{
Ok(cursor) => collect_cursor_async(cursor).await,
Ok(cursor) => {
let mut runs: Vec<ScanRun> = collect_cursor_async(cursor).await;
// Runs recorded before notes existed list them among their skips.
runs.iter_mut().for_each(ScanRun::split_notes);
runs
}
Err(e) => {
tracing::warn!("Failed to fetch recent scans: {e}");
Vec::new()
@@ -123,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;
+104 -52
View File
@@ -13,7 +13,7 @@ use serde::{Deserialize, Serialize};
use compliance_core::models::{
ArtifactKind, ComplianceProfile, Credentials, DetectedFact, Finding, OnboardedTarget,
PlcFormat, ScanRun, TargetType,
PlcFormat, ScanRun, TargetType, WebhookDelivery, DELIVERIES_SHOWN,
};
use compliance_core::scan_matrix::{applicable_scans, supports_pentest};
use compliance_core::tenant_ctx::TenantCtx;
@@ -96,6 +96,7 @@ pub async fn list_targets(
let targets = match db
.onboarded_targets()
.find(query)
.sort(TargetFilter::sort())
.skip(skip)
.limit(params.limit)
.await
@@ -169,6 +170,13 @@ impl TargetFilter {
None => doc! {},
}
}
/// The list's order: oldest first by id (creation order, what the list
/// showed before it paged). Ids are unique, so the order is total and a
/// page never repeats or skips a target.
pub fn sort() -> mongodb::bson::Document {
doc! { "_id": 1 }
}
}
/// The newest scan run of each target in `target_ids`, in one query.
@@ -192,7 +200,9 @@ pub(crate) async fn latest_scan_runs(
cursor
.filter_map(|row| async move {
let run = row.ok()?.get_document("run").ok()?.clone();
let run: ScanRun = mongodb::bson::from_document(run).ok()?;
let mut run: ScanRun = mongodb::bson::from_document(run).ok()?;
// Runs recorded before notes existed list them among their skips.
run.split_notes();
Some((run.repo_id.clone(), run))
})
.collect()
@@ -300,6 +310,42 @@ pub async fn get_target(
}))
}
/// GET /api/v1/targets/{id}/webhook-deliveries — the target's newest
/// webhook deliveries, refused and failed ones included; for a managed
/// target also those of its repository from before the target existed.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn list_webhook_deliveries(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
) -> Result<Json<ApiResponse<Vec<WebhookDelivery>>>, StatusCode> {
let oid = parse_oid(&id)?;
let db = tenant_db(&agent, &tenant).await?;
let target = db
.onboarded_targets()
.find_one(doc! { "_id": oid })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::NOT_FOUND)?;
let filter = crate::webhooks::deliveries::target_filter(&id, target.source_repo.as_ref());
let cursor = db
.webhook_deliveries()
.find(filter)
.sort(doc! { "received_at": -1 })
.limit(DELIVERIES_SHOWN)
.await
.map_err(|e| {
tracing::warn!("Failed to list webhook deliveries: {e}");
StatusCode::INTERNAL_SERVER_ERROR
})?;
let deliveries = collect_cursor_async(cursor).await;
Ok(Json(ApiResponse {
total: Some(deliveries.len() as u64),
data: deliveries,
page: None,
}))
}
/// PATCH /api/v1/targets/{id} — update mutable fields.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn update_target(
@@ -470,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()
@@ -509,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()
@@ -553,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(
@@ -1018,4 +1057,17 @@ mod filter_tests {
};
assert_eq!(blank.to_query(), doc! {});
}
#[test]
fn the_list_pages_in_a_total_order_with_the_filter_beside_it() {
// `?project=p1&page=2&limit=1` feeds both extractors of the handler.
let uri: axum::http::Uri = "/api/v1/targets?project=p1&page=2&limit=1"
.parse()
.expect("uri");
let Query(params) = Query::<PaginationParams>::try_from_uri(&uri).expect("params");
let Query(filter) = Query::<TargetFilter>::try_from_uri(&uri).expect("filter");
assert_eq!((params.page, params.limit, params.skip()), (2, 1, 1));
assert_eq!(filter.to_query(), doc! { "project_ids": "p1" });
assert_eq!(TargetFilter::sort(), doc! { "_id": 1 });
}
}
+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,
}
}
+240 -68
View File
@@ -16,25 +16,6 @@ pub(crate) const MAX_EXPORT_COMPONENTS: u64 = 100_000;
/// Package names listed per license in the summary; `count` stays exact.
const MAX_LICENSE_PACKAGES: i64 = 100;
const COPYLEFT_LICENSES: &[&str] = &[
"GPL-2.0",
"GPL-2.0-only",
"GPL-2.0-or-later",
"GPL-3.0",
"GPL-3.0-only",
"GPL-3.0-or-later",
"AGPL-3.0",
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"LGPL-2.1",
"LGPL-2.1-only",
"LGPL-2.1-or-later",
"LGPL-3.0",
"LGPL-3.0-only",
"LGPL-3.0-or-later",
"MPL-2.0",
];
#[tracing::instrument(skip_all)]
pub async fn sbom_filters(
Extension(agent): AgentExt,
@@ -103,18 +84,43 @@ pub async fn list_sbom(
if let Some(license) = &filter.license {
query.insert("license", license);
}
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(doc! { "name": 1 })
.sort(list_order())
.skip(skip)
.limit(filter.limit)
.await
@@ -125,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,
@@ -133,6 +142,62 @@ pub async fn list_sbom(
}))
}
/// The order of the SBOM list: the components an image contains first (a
/// missing `in_image` sorts as null, below any value), then by name.
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,
@@ -153,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
@@ -164,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)
@@ -255,56 +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()?;
let upper = row.license.to_uppercase();
Some(LicenseSummary {
is_copyleft: COPYLEFT_LICENSES
.iter()
.any(|c| upper.contains(&c.to_uppercase())),
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,
@@ -409,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);
}
}
+6 -1
View File
@@ -51,7 +51,12 @@ pub async fn list_scan_runs(
.limit(params.limit)
.await
{
Ok(cursor) => collect_cursor_async(cursor).await,
Ok(cursor) => {
let mut runs: Vec<ScanRun> = collect_cursor_async(cursor).await;
// Runs recorded before notes existed list them among their skips.
runs.iter_mut().for_each(ScanRun::split_notes);
runs
}
Err(e) => {
tracing::warn!("Failed to fetch scan runs: {e}");
Vec::new()
@@ -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}"
);
}
}
+23
View File
@@ -55,6 +55,10 @@ pub fn build_router() -> Router {
"/api/v1/targets/{id}/artifacts",
post(handlers::onboarding::add_artifact),
)
.route(
"/api/v1/targets/{id}/webhook-deliveries",
get(handlers::onboarding::list_webhook_deliveries),
)
.route(
"/api/v1/targets/{id}/artifacts/upload",
// The one route that takes large bodies — and it streams them to
@@ -141,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:?}");
}
}
+207 -1
View File
@@ -1,7 +1,7 @@
//! Heuristic target-type classification from artifact kinds and source markers.
//!
//! Complements the Firmwerk firmware detector: this handles web / backend /
//! mobile / desktop / PLC by sniffing manifest files and file extensions in the
//! mobile / desktop / PLC / Yocto by sniffing manifest files and file extensions in the
//! ingested code trees, plus strong priors from the artifact kinds themselves
//! (a PLC-project artifact is a PLC target; an `.ipa` is an iOS app).
@@ -40,6 +40,7 @@ const LOCATED_FILES: &[&str] = &[
"androidmanifest.xml",
"build.gradle",
"build.gradle.kts",
"layer.conf",
"projectversion.txt",
"pubspec.yaml",
"web.config",
@@ -280,6 +281,74 @@ fn package_json_is_frontend(root: &Path) -> bool {
.any(|f| c.contains(f))
}
/// The markers of a Yocto / OpenEmbedded layer tree.
#[derive(Default)]
struct YoctoShape {
/// The layers: directories holding a `conf/layer.conf` (`.` for the root).
layers: Vec<String>,
/// BitBake recipes, appends or includes (`.bb`, `.bbappend`, `.inc`
/// beside a `recipes-*` directory).
recipes: bool,
/// A kas project file (`kas*.yml`, or YAML beside a `kas/` directory).
kas: bool,
/// A build directory's `bblayers.conf` / `local.conf`, or poky's
/// `oe-init-build-env`.
build_setup: bool,
/// `meta-*` layer directories or distro configurations: common enough
/// elsewhere (`META-INF`) to only back up another signal.
corroborated: bool,
}
impl YoctoShape {
/// The confidence that the tree is a Yocto layer tree: a layer with its
/// recipes is as clear as an Android manifest; a kas file or a build
/// directory's configuration alone is weaker. `None` without any signal.
fn confidence(&self) -> Option<f32> {
let layer = !self.layers.is_empty();
let base = if layer && self.recipes {
return Some(0.8);
} else if layer || self.recipes {
0.65
} else if self.kas {
0.6
} else if self.build_setup {
0.5
} else {
return None;
};
Some(if self.corroborated { base + 0.05 } else { base })
}
}
/// What of a Yocto layer tree the markers show.
fn yocto_shape(m: &Markers) -> YoctoShape {
const LAYER_CONF: &str = "conf/layer.conf";
let is_yaml = |name: &str| name.ends_with(".yml") || name.ends_with(".yaml");
YoctoShape {
layers: m
.located_ending(LAYER_CONF)
.filter_map(|p| p.get(..p.len().saturating_sub(LAYER_CONF.len())))
.map(|dir| match dir.trim_end_matches('/') {
"" => ".".to_string(),
dir => dir.to_string(),
})
.collect(),
recipes: m.has_ext("bb")
|| m.has_ext("bbappend")
|| (m.has_ext("inc") && m.dirs.iter().any(|d| d.starts_with("recipes-"))),
kas: m.files.iter().any(|f| f.starts_with("kas") && is_yaml(f))
|| (m.dirs.contains("kas") && (m.has_ext("yml") || m.has_ext("yaml"))),
build_setup: ["bblayers.conf", "local.conf", "oe-init-build-env"]
.iter()
.any(|f| m.has_file(f)),
corroborated: m
.dirs
.iter()
.any(|d| d.starts_with("meta-") && d != "meta-inf")
|| (m.dirs.contains("distro") && m.has_ext("conf")),
}
}
/// The heuristic classifier: artifact-kind priors + source-tree markers.
pub struct HeuristicClassifier;
@@ -321,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![]))
}
@@ -519,6 +595,28 @@ impl HeuristicClassifier {
));
}
}
// Yocto / OpenEmbedded. The C sources a recipe carries in
// `files/` do not make it firmware: a layer with its recipes
// outranks Firmwerk's guess from loose sources (0.3).
let yocto = yocto_shape(&m);
if let Some(confidence) = yocto.confidence() {
let mut facts = facts_lang("bitbake");
facts.push(DetectedFact::new("build_system", "bitbake", "heuristic"));
// Each layer, for the stages that read the recipes.
facts.extend(
yocto
.layers
.iter()
.take(10)
.map(|layer| DetectedFact::new("yocto_layer", layer, "heuristic")),
);
out.push(verdict(
TargetType::EmbeddedLinuxYocto,
confidence,
"Yocto layer / BitBake recipes / kas project",
facts,
));
}
// Container-only.
if m.has_file("dockerfile") && out.is_empty() {
out.push(verdict(
@@ -902,6 +1000,114 @@ mod tests {
assert!(!v.iter().any(|x| x.target_type == TargetType::AndroidApp));
}
/// Assert the Yocto verdict's confidence (`None`: no Yocto verdict).
fn assert_yocto(verdicts: &[ClassifierVerdict], want: Option<f32>) {
let got = verdicts
.iter()
.find(|v| v.target_type == TargetType::EmbeddedLinuxYocto)
.map(|v| v.confidence);
match (got, want) {
(Some(got), Some(want)) => assert!((got - want).abs() < 1e-6, "{got} != {want}"),
_ => assert_eq!(got.is_some(), want.is_some(), "{got:?} != {want:?}"),
}
}
#[tokio::test]
async fn a_layer_with_recipes_is_confidently_yocto_and_names_its_layers() {
let v = classify_tree(|root| {
write_all(
root,
&[
(
"meta-pump/conf/layer.conf",
"BBFILE_COLLECTIONS += \"pump\"",
),
(
"meta-pump/recipes-app/pump/pump_1.0.bb",
"LICENSE = \"CLOSED\"",
),
(
"meta-pump/recipes-app/pump/files/pump.c",
"int main(void){}",
),
(
"meta-pump/recipes-app/pump/files/Makefile",
"all:\n\tcc pump.c",
),
("meta-pump/recipes-core/images/pump-image.bbappend", ""),
("conf/layer.conf", ""),
("recipes-x/x/x_1.0.bb", ""),
],
);
})
.await;
assert_eq!(top(&v), TargetType::EmbeddedLinuxYocto);
assert_yocto(&v, Some(0.8));
let facts = &v
.iter()
.find(|x| x.target_type == TargetType::EmbeddedLinuxYocto)
.expect("yocto verdict")
.facts;
let value = |key: &str| -> Vec<&str> {
facts
.iter()
.filter(|f| f.key == key)
.map(|f| f.value.as_str())
.collect()
};
assert_eq!(value("build_system"), ["bitbake"]);
assert_eq!(value("yocto_layer"), [".", "meta-pump"]);
}
#[tokio::test]
async fn weaker_yocto_signals_give_a_lower_confidence() {
let kas = classify_tree(|root| {
write_all(root, &[("kas-pump.yml", "header:\n version: 14\n")]);
})
.await;
assert_yocto(&kas, Some(0.6));
let kas_dir = classify_tree(|root| {
write_all(root, &[("kas/pump.yaml", "header:\n version: 14\n")]);
})
.await;
assert_yocto(&kas_dir, Some(0.6));
// A poky checkout: the build environment script and meta-* layers.
let poky = classify_tree(|root| {
write_all(
root,
&[("oe-init-build-env", "#!/bin/sh"), ("meta-poky/README", "")],
);
})
.await;
assert_yocto(&poky, Some(0.55));
let recipes_only = classify_tree(|root| {
write_all(root, &[("recipes-app/pump/pump_1.0.bb", "")]);
})
.await;
assert_yocto(&recipes_only, Some(0.65));
}
#[tokio::test]
async fn meta_inf_and_loose_conf_files_are_not_yocto() {
let v = classify_tree(|root| {
write_all(
root,
&[
("app/src/main/resources/META-INF/MANIFEST.MF", ""),
("pom.xml", "<project/>"),
("etc/distro/default.conf", ""),
("lib/defs.inc", ""),
],
);
})
.await;
assert_yocto(&v, None);
assert_eq!(top(&v), TargetType::BackendService);
}
#[tokio::test]
async fn structured_text_is_plc() {
let v = classify_tree(|root| {
+102
View File
@@ -260,6 +260,108 @@ mod tests {
assert_eq!(target.detected_type(&c), Some(TargetType::PlcSps));
}
/// What Firmwerk reports for loose C sources, or for a Makefile.
fn firmwerk_found(provider: &str, confidence: &str) -> MockFirmwareDetector {
MockFirmwareDetector {
detection: Some(FirmwareDetection {
provider: provider.to_string(),
confidence: confidence.to_string(),
build_system: provider.to_string(),
framework: Some("bare-metal".to_string()),
target: FirmwareTarget::default(),
gaps: vec![],
}),
}
}
/// Classify the tree `files` (relative path, content) as one source
/// archive, with `detector` standing in for Firmwerk.
async fn classify_files(
files: &[(&str, &str)],
detector: &MockFirmwareDetector,
) -> Classification {
let scratch = Scratch::new();
for (rel, content) in files {
let path = scratch.0.join(rel);
fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
fs::write(path, content).expect("write");
}
let artifact = Artifact::source_archive("upload.zip");
let mut wp = HashMap::new();
wp.insert(artifact.id.clone(), scratch.0.clone());
let mut target = OnboardedTarget::new("t".to_string(), TargetType::BackendService);
target.artifacts.push(artifact);
classify_target(&target, &wp, detector)
.await
.expect("classify")
}
#[tokio::test]
async fn the_nightly_yocto_fixture_is_typed_yocto() {
let fixture =
Path::new(env!("CARGO_MANIFEST_DIR")).join("../fixtures/nightly/firmware/yocto-layer");
let artifact = Artifact::source_archive("yocto-layer.zip");
let mut wp = HashMap::new();
wp.insert(artifact.id.clone(), fixture);
let mut target = OnboardedTarget::new("y".to_string(), TargetType::BackendService);
target.artifacts.push(artifact);
let c = classify_target(&target, &wp, &no_firmware())
.await
.expect("classify");
assert_eq!(c.suggested, TargetType::EmbeddedLinuxYocto);
assert!(c
.facts
.iter()
.any(|f| f.key == "build_system" && f.value == "bitbake"));
assert!(c
.facts
.iter()
.any(|f| f.key == "yocto_layer" && f.value == "."));
}
#[tokio::test]
async fn a_plain_c_firmware_repo_stays_bare_metal() {
let c = classify_files(
&[
("Makefile", "CC=arm-none-eabi-gcc\nCFLAGS=-mcpu=cortex-m4"),
("Core/Src/main.c", "int main(void){}"),
// A config file in `conf/` is not a layer.
("conf/board.conf", "BOARD=nucleo"),
],
&firmwerk_found("make", "medium"),
)
.await;
assert_eq!(c.suggested, TargetType::FirmwareBareMetal);
assert!(!c
.candidates
.iter()
.any(|x| x.target_type == TargetType::EmbeddedLinuxYocto));
}
#[tokio::test]
async fn a_layer_shipping_c_sources_is_yocto_not_bare_metal() {
// Firmwerk's source archaeology fires on the recipe's C sources.
let c = classify_files(
&[
("conf/layer.conf", "BBFILE_COLLECTIONS += \"pump\""),
(
"recipes-app/pump/pump_1.0.bb",
"SRC_URI = \"file://pump.c\"",
),
("recipes-app/pump/files/pump.c", "int main(void){}"),
("recipes-app/pump/files/pump.h", "#pragma once"),
],
&firmwerk_found("source-archaeology", "low"),
)
.await;
assert_eq!(c.suggested, TargetType::EmbeddedLinuxYocto);
// The firmware reading stays a lower candidate.
assert!(c
.candidates
.iter()
.any(|x| x.target_type == TargetType::FirmwareBareMetal));
}
#[tokio::test]
async fn no_signal_falls_back_to_declared_type() {
let scratch = Scratch::new();
+29 -4
View File
@@ -1,4 +1,6 @@
use compliance_core::config::{AppEnv, BreakpilotConfig, Features, PlcRuntimeConfig};
use compliance_core::config::{
AppEnv, BreakpilotConfig, Features, IssueAutoclose, IssueCatchup, PlcRuntimeConfig,
};
use compliance_core::AgentConfig;
use secrecy::SecretString;
@@ -47,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"),
@@ -127,6 +134,24 @@ fn build_config(app_env: AppEnv) -> Result<AgentConfig, AgentError> {
},
features: Features::parse(&env_var_opt("PW_FEATURES").unwrap_or_default()),
app_env,
issue_catchup: load_issue_catchup(),
issue_autoclose: load_issue_autoclose(),
})
}
/// `ISSUE_AUTOCLOSE`; an unknown value is logged and leaves closing off.
fn load_issue_autoclose() -> IssueAutoclose {
IssueAutoclose::parse(&env_var_opt("ISSUE_AUTOCLOSE").unwrap_or_default()).unwrap_or_else(|e| {
tracing::warn!("{e}; CVE issues settled by VEX stay open");
IssueAutoclose::Off
})
}
/// `ISSUE_CATCHUP`; an unknown value is logged and leaves the catch-up off.
fn load_issue_catchup() -> IssueCatchup {
IssueCatchup::parse(&env_var_opt("ISSUE_CATCHUP").unwrap_or_default()).unwrap_or_else(|e| {
tracing::warn!("{e}; the issue catch-up stays off");
IssueCatchup::Off
})
}
+118
View File
@@ -1,6 +1,7 @@
use std::sync::Arc;
use dashmap::DashMap;
use futures_util::StreamExt;
use mongodb::bson::doc;
use mongodb::options::IndexOptions;
use mongodb::{Client, Collection, IndexModel};
@@ -25,6 +26,22 @@ const HASH_HEX_LEN: usize = 32;
/// fits in the 63-byte cap: `prefix + "_" + 32 hex chars`.
const MAX_PREFIX_LEN: usize = MAX_DB_NAME_LEN - 1 - HASH_HEX_LEN;
/// The collection of [`Database::webhook_deliveries`].
const WEBHOOK_DELIVERIES: &str = "webhook_deliveries";
/// Deliveries kept per tenant: the target page shows the newest
/// [`DELIVERIES_SHOWN`] of a target, so this keeps them for 50 busy targets.
const WEBHOOK_DELIVERIES_MAX: u64 = 1_000;
/// The byte cap the capped collection needs as well; a delivery is well
/// under 1 KiB, so the document cap is the one that bites.
const WEBHOOK_DELIVERIES_BYTES: u64 = 2 * 1024 * 1024;
/// `create_collection` on a name that exists (Mongo error code 48).
fn is_namespace_exists(e: &mongodb::error::Error) -> bool {
matches!(&*e.kind, mongodb::error::ErrorKind::Command(c) if c.code == 48)
}
/// Per-tenant Mongo connection broker (M7.2 isolation model).
///
/// Holds one [`Client`] and hands out [`Database`] handles physically
@@ -151,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 {
@@ -317,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(
@@ -552,10 +592,71 @@ impl Database {
)
.await?;
// webhook_deliveries: capped, then the target page's two lookups
self.ensure_capped(
WEBHOOK_DELIVERIES,
WEBHOOK_DELIVERIES_BYTES,
WEBHOOK_DELIVERIES_MAX,
)
.await?;
self.webhook_deliveries()
.create_index(
IndexModel::builder()
.keys(doc! { "target_id": 1, "received_at": -1 })
.build(),
)
.await?;
self.webhook_deliveries()
.create_index(
IndexModel::builder()
.keys(doc! {
"source_repo.base_url": 1,
"source_repo.repo_id": 1,
"received_at": -1,
})
.build(),
)
.await?;
tracing::info!("Database indexes ensured");
Ok(())
}
/// Make `name` a capped collection of at most `bytes` and `max` documents,
/// so Mongo drops the oldest itself. An existing plain collection (written
/// before this ran) is converted; `convertToCapped` takes no document cap,
/// so that one is bounded by size only.
async fn ensure_capped(&self, name: &str, bytes: u64, max: u64) -> Result<(), AgentError> {
let created = self
.inner
.create_collection(name)
.capped(true)
.size(bytes)
.max(max)
.await;
match created {
Ok(()) => return Ok(()),
Err(e) if is_namespace_exists(&e) => {}
Err(e) => return Err(e.into()),
}
let mut specs = self
.inner
.list_collections()
.filter(doc! { "name": name })
.await?;
let capped = match specs.next().await {
Some(spec) => spec?.options.capped.unwrap_or(false),
None => false,
};
if !capped {
self.inner
.run_command(doc! { "convertToCapped": name, "size": bytes as i64 })
.await?;
tracing::info!(collection = name, "converted to a capped collection");
}
Ok(())
}
pub fn findings(&self) -> Collection<Finding> {
self.inner.collection("findings")
}
@@ -568,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")
}
@@ -661,6 +773,12 @@ impl Database {
self.inner.collection("pentest_messages")
}
/// The tenant's recent webhook deliveries: a capped collection (see
/// [`Self::ensure_capped`]), newest per target shown on the target page.
pub fn webhook_deliveries(&self) -> Collection<WebhookDelivery> {
self.inner.collection(WEBHOOK_DELIVERIES)
}
/// The Werkbank job queue (WB-02): declarative dynamic-execution jobs the
/// control plane enqueues and runners lease.
pub fn werkbank_jobs(&self) -> Collection<compliance_core::models::werkbank::JobRecord> {
+86 -3
View File
@@ -21,6 +21,9 @@ pub enum ControlState {
/// Checkable in code, but not by this scan: none completed yet, no tool
/// checks it, or none of its rules covers the scanned code's languages.
NotAssessed,
/// Assessed on part of what the control covers only: a Yocto target's
/// components come from its recipe inventory, not from the image's SBOM.
Partial,
/// A design property no code scan can decide (breakpilot-compliance).
NotCodeCheckable,
}
@@ -48,6 +51,11 @@ pub enum NotAssessedReason {
/// `manifests` declare could not be listed (no lockfile, or one no tool
/// reads), so the SBOM is incomplete.
DependenciesUnresolved { manifests: Vec<String> },
/// The control is checked on the target's components, and they are the
/// Yocto recipe inventory only, not the image's SBOM: every recipe in the
/// layer tree, not what the image contains (the reason of
/// [`ControlState::Partial`]).
RecipeInventoryOnly,
}
/// How far the target's SBOM speaks for its components.
@@ -59,10 +67,18 @@ pub enum SbomCoverage {
Empty,
/// The dependencies these manifests declare could not be listed.
Unresolved(Vec<String>),
/// The components are a Yocto recipe inventory; no image SBOM exists.
RecipeInventoryOnly,
}
/// The tools that check a target's components rather than its code.
const COMPONENT_TOOLS: [&str; 4] = ["syft", "osv", "dotnet-lifecycle", "build-lifecycle"];
const COMPONENT_TOOLS: [&str; 5] = [
"syft",
"osv",
"dotnet-lifecycle",
"build-lifecycle",
"yocto-release",
];
/// The tool a skipped stage of a scan run stands for, when that stage is one
/// a control's binding relies on.
@@ -72,6 +88,7 @@ pub fn tool_of_stage(stage: &str) -> Option<&'static str> {
"sast_c_cpp" => Some("cppcheck"),
"sast_mobile" => Some("mobsfscan"),
"sast_dotnet" => Some("devskim"),
"recipe_lint" => Some("oelint-adv"),
"cve_lookup" => Some("osv"),
"sbom" => Some("syft"),
_ => None,
@@ -96,7 +113,8 @@ pub struct ControlStatus {
pub state: ControlState,
/// Why a control is not code-checkable, from the map.
pub note: Option<String>,
/// Why a checkable control was not assessed; set only in that state.
/// Why a checkable control was not assessed, or assessed only in part;
/// set only in those states.
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<NotAssessedReason>,
/// How severe a violation is, as the catalog rates it.
@@ -163,7 +181,18 @@ pub fn control_statuses(
let (state, reason) = if !against.is_empty() {
(ControlState::NotSatisfied, None)
} else {
match (entry.status, scanned_languages) {
// A control otherwise outside static scans is assessed where
// one of its bindings checks the scanned code (cra-ai-2's
// recipe lint on a Yocto layer tree).
let status = match entry.status {
Coverage::NotCodeCheckable
if scanned_languages.is_some_and(|l| entry.checked_for(l)) =>
{
Coverage::Covered
}
status => status,
};
match (status, scanned_languages) {
(Coverage::NotCodeCheckable, _) => (ControlState::NotCodeCheckable, None),
(Coverage::NeedsTooling, _) => {
(ControlState::NotAssessed, Some(NotAssessedReason::NoTool))
@@ -200,6 +229,10 @@ pub fn control_statuses(
ControlState::NotAssessed,
Some(NotAssessedReason::NoComponents),
),
SbomCoverage::RecipeInventoryOnly => (
ControlState::Partial,
Some(NotAssessedReason::RecipeInventoryOnly),
),
SbomCoverage::Unresolved(manifests) => (
ControlState::NotAssessed,
Some(NotAssessedReason::DependenciesUnresolved {
@@ -278,6 +311,34 @@ mod tests {
status_of(statuses, control).state
}
#[test]
fn attack_surface_is_assessed_on_a_yocto_tree_only() {
let map = ControlMap::cra().expect("map");
let yocto = vec!["bitbake".to_string(), "c".to_string()];
let none = SbomCoverage::Complete;
let statuses = control_statuses(&map, &[], Some(&yocto), &[], &none);
assert_eq!(
state_of(&statuses, "cra-ai-2"),
ControlState::NoViolationFound
);
// Elsewhere it stays outside static scans.
for languages in [Some(python()), Some(c_only()), None] {
let statuses = control_statuses(&map, &[], languages.as_deref(), &[], &none);
assert_eq!(
state_of(&statuses, "cra-ai-2"),
ControlState::NotCodeCheckable
);
}
// oelint-adv did not complete: not assessed.
let statuses = control_statuses(&map, &[], Some(&yocto), &["oelint-adv"], &none);
assert_eq!(state_of(&statuses, "cra-ai-2"), ControlState::NotAssessed);
// A finding bound to it counts against it.
let mut network = finding("cra-ai-2", FindingStatus::Open);
network.scanner = "oelint-adv".into();
let statuses = control_statuses(&map, &[network], Some(&yocto), &[], &none);
assert_eq!(state_of(&statuses, "cra-ai-2"), ControlState::NotSatisfied);
}
#[test]
fn every_control_gets_exactly_one_state() {
let map = ControlMap::cra().expect("map");
@@ -411,6 +472,27 @@ mod tests {
assert_eq!(state_of(&with, "cra-ai-23"), ControlState::NoViolationFound);
}
#[test]
fn a_recipe_inventory_assesses_the_component_controls_only_in_part() {
let map = ControlMap::cra().expect("map");
let statuses = control_statuses(
&map,
&[],
Some(&c_only()),
&[],
&SbomCoverage::RecipeInventoryOnly,
);
for control in ["cra-ai-22", "cra-ai-23", "cra-ai-33"] {
let status = status_of(&statuses, control);
assert_eq!(status.state, ControlState::Partial, "{control}");
assert_eq!(status.reason, Some(NotAssessedReason::RecipeInventoryOnly));
}
assert_eq!(
state_of(&statuses, "cra-ai-20"),
ControlState::NoViolationFound
);
}
#[test]
fn unresolved_dependencies_claim_nothing_about_components() {
let map = ControlMap::cra().expect("map");
@@ -456,6 +538,7 @@ mod tests {
assert_eq!(tool_of_stage("cve_lookup"), Some("osv"));
assert_eq!(tool_of_stage("sast_mobile"), Some("mobsfscan"));
assert_eq!(tool_of_stage("sast_dotnet"), Some("devskim"));
assert_eq!(tool_of_stage("recipe_lint"), Some("oelint-adv"));
assert_eq!(tool_of_stage("sast_vendor_code"), None);
}
+145 -5
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) {
@@ -158,12 +205,16 @@ pub fn build_pack(
"type": inputs.target.target_type.to_string(),
}),
last_scan_run: inputs.last_run.as_ref().map(|run| {
// A run recorded before notes existed lists them among its skips.
let mut run = run.clone();
run.split_notes();
serde_json::json!({
"id": run.id.map(|id| id.to_hex()),
"status": run.status,
"started_at": run.started_at,
"completed_at": run.completed_at,
"skipped_stages": run.skipped_stages,
"notes": run.notes,
})
}),
tool_versions: std::fs::read(TOOL_VERSIONS_PATH)
@@ -215,12 +266,13 @@ pub fn scanned_languages(inputs: &EvidenceInputs) -> Option<&[String]> {
}
/// The tools that did not complete in the target's last scan (a skipped
/// stage a control relies on: semgrep, cppcheck, the CVE lookup).
/// stage a control relies on: semgrep, cppcheck, the CVE lookup). Notes never
/// count: the stage they inform about ran.
pub fn failed_tools(inputs: &EvidenceInputs) -> Vec<&'static str> {
inputs
.last_run
.iter()
.flat_map(|run| &run.skipped_stages)
.flat_map(ScanRun::skips)
.filter_map(|s| compliance::tool_of_stage(&s.stage))
.collect()
}
@@ -232,7 +284,7 @@ pub fn sbom_coverage(inputs: &EvidenceInputs) -> compliance::SbomCoverage {
let unresolved: Vec<String> = inputs
.last_run
.iter()
.flat_map(|run| &run.skipped_stages)
.flat_map(ScanRun::skips)
.filter(|s| s.code == Some(SkipCode::DependenciesUnlocked))
.filter_map(|s| s.subject.clone())
.collect();
@@ -240,6 +292,15 @@ pub fn sbom_coverage(inputs: &EvidenceInputs) -> compliance::SbomCoverage {
compliance::SbomCoverage::Unresolved(unresolved)
} else if inputs.sbom.is_empty() {
compliance::SbomCoverage::Empty
} else if inputs
.sbom
.iter()
.any(|e| e.package_manager == compliance_core::models::YOCTO_RECIPE_MANAGER)
{
// No image SBOM can be imported yet (Yocto tier 2), so a recipe
// inventory is all there is: it lists the layer tree's recipes, not
// what the image contains.
compliance::SbomCoverage::RecipeInventoryOnly
} else {
compliance::SbomCoverage::Complete
}
@@ -334,7 +395,7 @@ fn csv_cell(value: &str) -> String {
#[allow(clippy::expect_used)]
mod tests {
use super::*;
use compliance_core::models::{ScanType, Severity, TargetType};
use compliance_core::models::{ScanType, Severity, SkippedStage, TargetType};
use std::io::Read;
fn inputs() -> EvidenceInputs {
@@ -364,9 +425,26 @@ mod tests {
last_run: None,
catalog: Default::default(),
author: String::new(),
license_policy: Default::default(),
}
}
#[test]
fn a_recipe_inventory_is_not_a_complete_sbom() {
let mut with = inputs();
assert_eq!(sbom_coverage(&with), compliance::SbomCoverage::Complete);
with.sbom.push(SbomEntry::new(
"t1".into(),
"busybox".into(),
"1.35.0".into(),
compliance_core::models::YOCTO_RECIPE_MANAGER.into(),
));
assert_eq!(
sbom_coverage(&with),
compliance::SbomCoverage::RecipeInventoryOnly
);
}
#[test]
fn an_actively_exploited_vulnerability_adds_its_draft_notification() {
let mut with_kev = inputs();
@@ -391,21 +469,83 @@ mod tests {
assert!(listed.iter().all(|f| f.name != "enisa-drafts.json"));
}
/// The last run of `inputs()` with these skipped stages and notes, as a
/// completed run.
fn with_run(skipped: Vec<SkippedStage>, notes: Vec<SkippedStage>) -> EvidenceInputs {
let mut run = ScanRun::new("t1".into(), compliance_core::models::ScanTrigger::Manual);
run.completed_at = Some(Utc::now());
run.languages = vec!["c".into()];
run.skipped_stages = skipped;
run.notes = notes;
EvidenceInputs {
last_run: Some(run),
..inputs()
}
}
fn vendor_note() -> SkippedStage {
SkippedStage::new("sast_vendor_code", SkipCode::VendorCode, "vendor").about("Drivers")
}
#[test]
fn notes_leave_the_control_status_alone() {
let without = with_run(Vec::new(), Vec::new());
let noted = with_run(Vec::new(), vec![vendor_note()]);
// A run recorded before notes existed, the note among its skips.
let mut old_note = vendor_note();
old_note.status = SkippedStage::SKIPPED.to_string();
let old = with_run(vec![old_note], Vec::new());
assert!(failed_tools(&noted).is_empty());
assert!(failed_tools(&old).is_empty());
assert_eq!(compliance_of(&noted), compliance_of(&without));
assert_eq!(compliance_of(&old), compliance_of(&without));
}
#[test]
fn the_manifest_lists_the_last_runs_notes_apart_from_its_skips() {
let mut old_note = vendor_note();
old_note.status = SkippedStage::SKIPPED.to_string();
let semgrep = SkippedStage::new("sast", SkipCode::ToolFailed, "semgrep did not complete");
let pack = with_run(vec![old_note, semgrep], Vec::new());
assert_eq!(failed_tools(&pack), ["semgrep"]);
let (zip_bytes, _) = build_pack(&pack, Utc::now()).expect("pack");
let mut archive =
zip::ZipArchive::new(std::io::Cursor::new(zip_bytes)).expect("a valid zip");
let mut manifest = String::new();
archive
.by_name("manifest.json")
.expect("manifest")
.read_to_string(&mut manifest)
.expect("read");
let manifest: serde_json::Value = serde_json::from_str(&manifest).expect("json");
let run = &manifest["last_scan_run"];
assert_eq!(run["skipped_stages"].as_array().map(Vec::len), Some(1));
assert_eq!(run["skipped_stages"][0]["stage"], "sast");
assert_eq!(run["notes"][0]["stage"], "sast_vendor_code");
assert_eq!(run["notes"][0]["status"], "note");
}
#[test]
fn the_pack_holds_every_file_and_the_manifest_hashes_match() {
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",
+20
View File
@@ -16,6 +16,16 @@ pub enum SourceAction {
Ignore(&'static str),
}
impl SourceAction {
/// The repository the action is about; `None` for [`Self::Ignore`].
pub fn repo(&self) -> Option<&GiteaRepo> {
match self {
Self::Created(repo) | Self::Deleted(repo) | Self::Push(repo) => Some(repo),
Self::Ignore(_) => None,
}
}
}
/// A branch deletion pushes this as the new head.
const ZERO_SHA: &str = "0000000000000000000000000000000000000000";
@@ -73,6 +83,16 @@ mod tests {
})
}
#[test]
fn an_action_names_its_repository_unless_ignored() {
let p = json!({ "action": "created", "repository": repository("kunde") });
assert_eq!(
route_event("repository", &p, "kunde").repo().map(|r| r.id),
Some(42)
);
assert!(SourceAction::Ignore("x").repo().is_none());
}
#[test]
fn created_and_deleted() {
let p = json!({ "action": "created", "repository": repository("kunde") });
+5
View File
@@ -112,6 +112,11 @@ impl RepoLister for SourceClient {
self.base_url,
urlencoding::encode(org)
);
// One of the instance's two request slots, shared with the issue
// tracker, held until the page has been read.
let _permit = crate::trackers::gitea_limit::acquire(&self.base_url)
.await
.map_err(|e| AgentError::Other(format!("Gitea request slot: {e}")))?;
let resp = self
.http
.get(&url)
+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);
}
+2 -2
View File
@@ -45,9 +45,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Err(e) => tracing::error!("migrating stored findings failed: {e}"),
}
// Open CVE alerts stored before purls were recorded (#532) get their
// component's purl, before a scan can resolve them.
// component's purl, before a scan can resolve them. Logged with 0 too, so
// "ran, nothing to do" is told apart from "did not run".
match pipeline::vex_lifecycle::backfill_purls_everywhere(&agent.db_pool).await {
Ok(0) => {}
Ok(alerts) => tracing::info!(alerts, "CVE alerts got their component's purl"),
Err(e) => tracing::error!("backfilling CVE alert purls failed: {e}"),
}
@@ -381,6 +381,7 @@ mod tests {
severity: None,
url: None,
exploitation: None,
aliases: Vec::new(),
})
.collect();
entry
@@ -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::Medium,
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
}
@@ -270,7 +281,7 @@ fn check_xcode_project(root: &Path, file: &Path) -> Vec<Hit> {
remediation: "Migrate the code to Swift 5 or later (Xcode migrates Swift 4 \
code; older code through an Xcode release that still reads it) \
and set SWIFT_VERSION accordingly.",
severity: Severity::Medium,
severity: Severity::High,
cwe: "CWE-1104",
path,
line: Some(line),
@@ -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."
),
@@ -415,7 +432,7 @@ fn check_unity_project(root: &Path, project: &Path) -> Vec<Hit> {
relative(root, project)
),
remediation: "Upgrade the project to a supported Unity LTS release.",
severity: Severity::Medium,
severity: Severity::High,
cwe: "CWE-1104",
path,
line: Some(1),
@@ -466,8 +483,24 @@ mod tests {
Tree(dir)
}
/// The hits as `rule path:line`; every end-of-support hit is high, like
/// every other end-of-life finding, except the minimum OS an app still
/// installs on, which stays low until that severity is decided.
fn hits(t: &Tree) -> Vec<String> {
check_tree(&t.0)
let found = check_tree(&t.0);
for hit in found
.iter()
.filter(|h| h.rule_id.ends_with("-end-of-support"))
{
let expected = match hit.rule_id {
"ios-deployment-target-end-of-support" | "android-min-sdk-end-of-support" => {
Severity::Low
}
_ => Severity::High,
};
assert_eq!(hit.severity, expected, "{}", hit.rule_id);
}
found
.into_iter()
.map(|h| format!("{} {}:{}", h.rule_id, h.path, h.line.unwrap_or(0)))
.collect()
+22
View File
@@ -69,6 +69,18 @@ pub enum ClamavError {
Io(#[from] std::io::Error),
}
impl ClamavError {
/// True when the clamd service itself is down (unreachable or silent),
/// as opposed to a problem with one file or the tree. Logged as an error
/// so the "ERROR/FATAL logs" alert fires: nothing else restarts clamd.
pub fn service_down(&self) -> bool {
match self {
Self::Unreachable(..) | Self::Timeout => true,
Self::Refused(_) | Self::Io(_) => false,
}
}
}
/// A clamd service.
#[derive(Debug, Clone)]
pub struct Clamd {
@@ -397,6 +409,16 @@ fn finding(root: &Path, repo_id: &str, file: &Path, hash: &str, signature: &str)
mod tests {
use super::*;
#[test]
fn only_an_unreachable_or_silent_clamd_is_down() {
let refused = std::io::Error::from(std::io::ErrorKind::ConnectionRefused);
assert!(ClamavError::Unreachable("clamav:3310".into(), refused).service_down());
assert!(ClamavError::Timeout.service_down());
assert!(!ClamavError::Refused("INSTREAM size limit exceeded".into()).service_down());
let unreadable = std::io::Error::from(std::io::ErrorKind::PermissionDenied);
assert!(!ClamavError::Io(unreadable).service_down());
}
#[test]
fn clamd_answers_are_read() {
assert_eq!(
@@ -0,0 +1,141 @@
//! At most two clones or fetches against one git host at a time.
//!
//! Every target of a tenant usually lives on the same git host. When scans of
//! several of them start together (a git sync creating targets, scans resumed
//! after a restart), they would all clone from that host at once; a small
//! self-hosted Gitea answers that with an OOM kill and `502`s. The limit is
//! held only around the clone or fetch itself, not the rest of the scan, and
//! another host's clones go ahead meanwhile.
use std::collections::HashMap;
use std::sync::{Arc, Condvar, LazyLock, Mutex, PoisonError};
/// How many clones or fetches may run against one git host at once.
pub const CLONES_PER_HOST: usize = 2;
/// The limiter every clone and fetch of this process goes through.
pub static CLONE_SLOTS: LazyLock<HostLimiter> = LazyLock::new(|| HostLimiter::new(CLONES_PER_HOST));
/// A counting semaphore per git host, for blocking (non-async) callers.
#[derive(Debug)]
pub struct HostLimiter {
per_host: usize,
hosts: Mutex<HashMap<String, Arc<HostSlots>>>,
}
/// The slots of one host: how many are taken, and a wake-up for waiters.
#[derive(Debug, Default)]
struct HostSlots {
taken: Mutex<usize>,
freed: Condvar,
}
/// One taken slot of a host; dropping it frees the slot.
#[derive(Debug)]
pub struct HostPermit {
slots: Arc<HostSlots>,
}
impl HostLimiter {
/// A limiter allowing `per_host` operations per host at once (at least one).
pub fn new(per_host: usize) -> Self {
Self {
per_host: per_host.max(1),
hosts: Mutex::new(HashMap::new()),
}
}
/// Wait until `host` has a free slot and take it.
///
/// Blocks the calling thread. On the async runtime's worker threads it
/// hands the worker's other tasks to another worker first.
pub fn acquire(&self, host: &str) -> HostPermit {
// The map lock is held only for the lookup, never while waiting.
let slots = {
let mut hosts = self.hosts.lock().unwrap_or_else(PoisonError::into_inner);
Arc::clone(hosts.entry(host.to_ascii_lowercase()).or_default())
};
let taken = slots.taken.lock().unwrap_or_else(PoisonError::into_inner);
let mut taken = if *taken < self.per_host {
taken
} else {
tracing::info!(host, "waiting for a free clone slot on this git host");
off_the_runtime(|| {
slots
.freed
.wait_while(taken, |taken| *taken >= self.per_host)
.unwrap_or_else(PoisonError::into_inner)
})
};
*taken += 1;
drop(taken);
HostPermit { slots }
}
}
impl Drop for HostPermit {
fn drop(&mut self) {
let mut taken = self
.slots
.taken
.lock()
.unwrap_or_else(PoisonError::into_inner);
*taken = taken.saturating_sub(1);
self.slots.freed.notify_one();
}
}
/// Run blocking `work` without stalling the async runtime: on a multi-thread
/// runtime's worker, `block_in_place` moves the worker's other tasks first.
pub(crate) fn off_the_runtime<R>(work: impl FnOnce() -> R) -> R {
let on_multi_thread_runtime = tokio::runtime::Handle::try_current()
.is_ok_and(|h| h.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread);
if on_multi_thread_runtime {
tokio::task::block_in_place(work)
} else {
work()
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::HostLimiter;
use std::sync::{mpsc, Arc};
use std::time::Duration;
#[test]
fn a_host_runs_at_most_two_while_another_host_proceeds() {
let limiter = Arc::new(HostLimiter::new(2));
let first = limiter.acquire("git.example.com");
let _second = limiter.acquire("git.example.com");
// A third clone from the same host waits.
let (sent, received) = mpsc::channel();
let waiting = Arc::clone(&limiter);
let third = std::thread::spawn(move || {
let permit = waiting.acquire("GIT.example.com");
sent.send(()).expect("send");
drop(permit);
});
assert!(received.recv_timeout(Duration::from_millis(100)).is_err());
// Another host is not held up by the full one.
let _other = limiter.acquire("gitlab.example.org");
// A freed slot lets the waiting clone go ahead.
drop(first);
received
.recv_timeout(Duration::from_secs(5))
.expect("the third clone runs once a slot is free");
third.join().expect("join");
}
#[test]
fn a_dropped_permit_frees_its_slot() {
let limiter = HostLimiter::new(1);
drop(limiter.acquire("git.example.com"));
// Would block forever if the slot had not been freed.
let _again = limiter.acquire("git.example.com");
}
}
@@ -192,6 +192,7 @@ pub(crate) fn apply(
severity: hit.vulnerability.severity.clone(),
url: hit.advisory.url.clone(),
exploitation: None,
aliases: Vec::new(),
});
}
let fixed = hit.advisory.fixed_versions(hit.vulnerability, &entry.name);
@@ -333,6 +334,7 @@ mod tests {
severity: None,
url: None,
exploitation: None,
aliases: Vec::new(),
});
let mut nvd = CveAlert::new(
"CVE-2026-90001".into(),
+116 -8
View File
@@ -1,18 +1,19 @@
use std::collections::{BTreeSet, HashMap};
use compliance_core::models::{CveAlert, CveSource, SbomEntry, VulnRef};
use compliance_core::models::{CveAlert, CveSource, SbomEntry, VulnRef, YOCTO_RECIPE_MANAGER};
use compliance_core::net_guard::NetGuard;
use compliance_core::CoreError;
use crate::pipeline::embedded_versions::{self, EMBEDDED_MANAGER};
use crate::pipeline::nvd_cpe::{self, NvdCve, NvdProduct};
use crate::pipeline::public_http::{read_body, read_json, PublicHttp};
use crate::pipeline::yocto_inventory::NvdQuery;
/// OSV's API.
const OSV_API: &str = "https://api.osv.dev";
/// Every CODESYS product: advisories key off the runtime's version.
const CODESYS: NvdProduct = NvdProduct {
pub(crate) const CODESYS: NvdProduct = NvdProduct {
match_string: "cpe:2.3:a:codesys",
marker: ":codesys:",
};
@@ -79,6 +80,7 @@ impl CveScanner {
severity: vuln.severity,
url: Some(format!("https://osv.dev/vulnerability/{}", vuln.id)),
exploitation: None,
aliases: Vec::new(),
});
let mut alert = CveAlert::new(
vuln.id,
@@ -116,6 +118,7 @@ impl CveScanner {
for vuln in &mut entry.known_vulnerabilities {
if let Some(detail) = details.get(&vuln.id) {
vuln.severity = detail.severity.clone().or(vuln.severity.take());
vuln.aliases.clone_from(&detail.aliases);
}
}
}
@@ -155,10 +158,13 @@ impl CveScanner {
let mut refused = Vec::new();
// Each query keeps the index of its entry: an entry without a purl is
// not asked about, and must not shift the answers onto its neighbours.
// Yocto recipes are matched by CPE in NVD instead ([`Self::scan_yocto`]).
let queries: Vec<(usize, &str)> = entries
.iter()
.enumerate()
.filter(|(_, e)| !without_osv_advisories(e))
.filter(|(_, e)| {
!without_osv_advisories(e) && e.package_manager != YOCTO_RECIPE_MANAGER
})
.filter_map(|(i, e)| e.purl.as_deref().map(|purl| (i, purl)))
.collect();
@@ -349,6 +355,82 @@ impl CveScanner {
}
}
impl CveScanner {
/// Match the components of a Yocto recipe inventory against NVD by CPE
/// (`queries`, see [`crate::pipeline::yocto_inventory::nvd_queries`]),
/// one product after the other, within `budget`. A recipe whose lookup
/// fails, or that the budget leaves unasked, is reported in
/// [`CveLookup::unchecked`]; the others are still matched.
///
/// NVD answers about 5 requests per 30 seconds without an API key and 50
/// with one (`NVD_API_KEY`, sent as the `apiKey` header): the requests are
/// paced to that ([`nvd_cpe::request_interval`]), a cached answer costs
/// none, and a layer tree can name hundreds of products: the budget keeps
/// the scan bounded, and the 6-hour cache lets the next scan of the same
/// products go further.
pub async fn scan_yocto(
&self,
repo_id: &str,
entries: &mut [SbomEntry],
queries: &[NvdQuery],
budget: std::time::Duration,
) -> CveLookup {
let deadline = tokio::time::Instant::now() + budget;
let interval = nvd_cpe::request_interval(self.nvd_api_key.is_some());
let mut next_request = tokio::time::Instant::now();
let mut lookup = CveLookup::default();
for query in queries {
let mut found: Vec<NvdCve> = Vec::new();
let mut checked = true;
for product in &query.products {
let (match_string, marker) = (product.match_string(), product.marker());
if !nvd_cpe::is_cached(&match_string) {
if next_request >= deadline {
checked = false;
continue;
}
tokio::time::sleep_until(next_request).await;
next_request = tokio::time::Instant::now() + interval;
}
let lookup = nvd_cpe::match_cves(
&self.http,
self.nvd_api_key.as_deref(),
&match_string,
&marker,
&query.cve_version,
);
match tokio::time::timeout_at(deadline, lookup).await {
Ok(Ok(cves)) => {
for cve in cves {
if !found.iter().any(|f| f.id == cve.id) {
found.push(cve);
}
}
}
Ok(Err(e)) => {
tracing::warn!(recipe = %query.name, "NVD lookup failed: {e}");
checked = false;
}
Err(_) => checked = false,
}
}
if !checked {
lookup
.unchecked
.push(format!("{} {}", query.name, query.version));
}
lookup.alerts.extend(record_nvd(
repo_id,
entries,
&query.name,
&query.version,
found,
));
}
lookup
}
}
/// What a CVE lookup found, and what it could not check.
#[derive(Debug, Default)]
pub struct CveLookup {
@@ -359,9 +441,10 @@ pub struct CveLookup {
pub unchecked: Vec<String>,
}
/// Attach NVD `cves` to the SBOM entry `name@version` and make an alert for
/// each.
fn record_nvd(
/// Attach NVD `cves` to the SBOM entry `name@version` (once per CVE: an
/// entry read back from the database may carry it already) and make an alert
/// for each.
pub(crate) fn record_nvd(
repo_id: &str,
entries: &mut [SbomEntry],
name: &str,
@@ -374,13 +457,17 @@ fn record_nvd(
let purl = entry.as_ref().and_then(|e| e.purl.clone());
cves.into_iter()
.map(|cve| {
if let Some(e) = entry.as_deref_mut() {
if let Some(e) = entry
.as_deref_mut()
.filter(|e| !e.known_vulnerabilities.iter().any(|v| v.id == cve.id))
{
e.known_vulnerabilities.push(VulnRef {
id: cve.id.clone(),
source: "nvd".to_string(),
severity: None,
url: Some(format!("https://nvd.nist.gov/vuln/detail/{}", cve.id)),
exploitation: None,
aliases: Vec::new(),
});
}
let mut alert = CveAlert::new(
@@ -487,7 +574,7 @@ fn without_osv_advisories(entry: &SbomEntry) -> bool {
/// The CODESYS runtime component (name + version) from an SBOM, if present. The
/// runtime carries the version CODESYS advisories key off; the internal library
/// components do not.
fn codesys_runtime(entries: &[SbomEntry]) -> Option<(String, String)> {
pub(crate) fn codesys_runtime(entries: &[SbomEntry]) -> Option<(String, String)> {
entries
.iter()
.find(|e| e.package_manager == "codesys" && e.name.starts_with("CODESYS Control"))
@@ -600,6 +687,23 @@ mod tests {
);
}
#[tokio::test]
async fn yocto_recipes_are_left_to_nvd_not_asked_of_osv() {
let (url, hits) = fake_osv().await;
let scanner = CveScanner::new(NetGuard::allow_private(), None)
.unwrap()
.with_osv_api(url);
let mut recipe = with_purl("busybox", "pkg:generic/busybox@1.35.0");
recipe.package_manager = YOCTO_RECIPE_MANAGER.into();
let mut entries = vec![recipe];
let lookup = scanner.scan_dependencies("t", &mut entries).await.unwrap();
assert_eq!(hits.load(Ordering::SeqCst), 0, "OSV was asked");
assert!(lookup.alerts.is_empty());
assert!(lookup.unchecked.is_empty(), "NVD checks it, not OSV");
}
#[test]
fn an_nvd_alert_keeps_the_purl_of_its_component() {
let mut entries = vec![
@@ -615,6 +719,10 @@ mod tests {
let without = record_nvd("t", &mut entries, "FreeRTOS", "1.0.0", vec![cve("CVE-2")]);
assert_eq!(with[0].purl.as_deref(), Some("pkg:generic/lwip@1.0.0"));
assert_eq!(without[0].purl, None);
// Recorded again (the monitor re-reads stored entries), the
// component lists the CVE once.
record_nvd("t", &mut entries, "lwIP", "1.0.0", vec![cve("CVE-1")]);
assert_eq!(entries[0].known_vulnerabilities.len(), 1);
}
fn entry(name: &str, ver: &str, pm: &str) -> SbomEntry {
@@ -28,7 +28,7 @@ use std::collections::{BTreeSet, HashMap};
use std::sync::Arc;
use std::time::Duration;
use compliance_core::models::{CveAlert, EpssScore, Exploitation, KevEntry, SbomEntry};
use compliance_core::models::{is_cve, CveAlert, EpssScore, Exploitation, KevEntry, SbomEntry};
use compliance_core::net_guard::NetGuard;
use compliance_core::CoreError;
use futures_util::future::BoxFuture;
@@ -194,7 +194,7 @@ impl CveEnricher {
let cves: BTreeSet<String> = alerts
.iter()
.map(|a| a.cve().to_string())
.filter(|id| is_cve_id(id))
.filter(|id| is_cve(id))
.collect();
let mut counts = EnrichCounts {
cves: cves.len(),
@@ -446,22 +446,10 @@ impl CveEnricher {
}
}
/// Whether `id` is a CVE id (`CVE-2021-44228`).
fn is_cve_id(id: &str) -> bool {
let mut parts = id.splitn(3, '-');
parts.next() == Some("CVE")
&& parts
.next()
.is_some_and(|y| y.len() == 4 && y.bytes().all(|b| b.is_ascii_digit()))
&& parts
.next()
.is_some_and(|n| n.len() >= 4 && n.bytes().all(|b| b.is_ascii_digit()))
}
/// Where Vulnrichment keeps the record of `cve`: `<year>/<thousands>xxx/<cve>.json`
/// (`CVE-2021-44228` → `2021/44xxx/CVE-2021-44228.json`).
fn vulnrichment_path(cve: &str) -> Option<String> {
if !is_cve_id(cve) {
if !is_cve(cve) {
return None;
}
let mut parts = cve.splitn(3, '-').skip(1);
@@ -930,6 +918,7 @@ mod tests {
severity: None,
url: None,
exploitation: None,
aliases: Vec::new(),
});
e
}
@@ -977,7 +966,7 @@ mod tests {
"CVE-2021-../x",
"RUSTSEC-2021-0001",
] {
assert!(!is_cve_id(id), "{id}");
assert!(!is_cve(id), "{id}");
assert_eq!(vulnrichment_path(id), None);
}
}
+452 -12
View File
@@ -7,6 +7,13 @@
//! updated or removed), the issue is closed with a comment; when it comes back,
//! it is reopened.
//!
//! A CVE a VEX statement settles (`not_affected` or `fixed`, by a person, the
//! scan or an imported VEX document) gets no issue. Its open issue is closed
//! with a comment naming the status and the reason when `ISSUE_AUTOCLOSE` is
//! `on` (at most [`AUTOCLOSE_PER_SCAN`] per target and scan), only counted
//! with `dry_run`, and left open with `off`, the default. When the statement
//! is withdrawn, the issue is reopened (or opened) as for a CVE found again.
//!
//! What is known about a CVE's exploitation (#493) moves the threshold: a CVE
//! in CISA's KEV catalog always gets an issue, rated at least high, and one
//! whose EPSS percentile reaches [`epss_percentile`] is rated one step higher
@@ -16,8 +23,9 @@ use std::collections::{BTreeMap, HashMap};
use mongodb::bson::doc;
use compliance_core::config::IssueAutoclose;
use compliance_core::models::notification::{parse_severity, NotificationSeverity};
use compliance_core::models::{CveAlert, IssueStatus, TrackerIssue};
use compliance_core::models::{CveAlert, IssueStatus, TrackerIssue, VexAssessment, VexStatus};
use crate::database::Database;
use crate::error::AgentError;
@@ -30,6 +38,8 @@ const CVE_CONTROLS: [&str; 2] = ["cra-ai-22", "cra-ai-33"];
/// Where the issues of one target go.
pub(crate) struct CveIssueTarget<'a> {
pub db: &'a Database,
/// The tenant, for the log lines.
pub tenant_id: &'a str,
pub tracker: &'a TrackerDispatch,
pub owner: &'a str,
pub repo: &'a str,
@@ -40,6 +50,9 @@ pub(crate) struct CveIssueTarget<'a> {
/// From this EPSS percentile (0 to 1) on a CVE is rated one step higher;
/// `None` leaves EPSS out (see [`epss_percentile`]).
pub epss_percentile: Option<f64>,
/// Whether open issues a VEX statement settles are closed
/// (`ISSUE_AUTOCLOSE`).
pub autoclose: IssueAutoclose,
}
/// The EPSS percentile from which a CVE is rated one step higher.
@@ -136,7 +149,9 @@ fn issue_worthy(alert: &CveAlert, epss_percentile: Option<f64>) -> bool {
/// # Arguments
///
/// * `target` - where the issues go
/// * `alerts` - every CVE the scan found in the target's components
/// * `alerts` - every CVE the scan found in the target's components, with
/// its stored VEX statement
/// ([`crate::pipeline::vex_lifecycle::attach_stored_vex`])
/// * `complete` - whether every component was matched; only then is a CVE
/// that is missing from `alerts` known to be gone, and its issue closed
///
@@ -171,7 +186,7 @@ pub(crate) async fn sync_cve_issues(
for (key, alert) in present
.iter()
.filter(|(_, a)| issue_worthy(a, target.epss_percentile))
.filter(|(_, a)| !a.is_resolved_by_vex() && issue_worthy(a, target.epss_percentile))
{
match existing.get(key) {
Some(issue) if is_closed(&issue.status) => {
@@ -190,6 +205,17 @@ pub(crate) async fn sync_cve_issues(
}
}
// A VEX statement settles the CVE whether or not the scan was complete.
let settled: Vec<(&TrackerIssue, &VexAssessment)> = present
.iter()
.filter_map(|(key, alert)| {
let vex = alert.vex.as_ref().filter(|_| alert.is_resolved_by_vex())?;
let issue = existing.get(key).filter(|i| !is_closed(&i.status))?;
Some((issue, vex))
})
.collect();
counts.closed += autoclose(target, &settled).await?;
if complete {
for (key, issue) in &existing {
if present.contains_key(key) || is_closed(&issue.status) {
@@ -205,6 +231,86 @@ pub(crate) async fn sync_cve_issues(
Ok(counts)
}
/// Open issues closed per target and scan because a VEX statement settles
/// their CVE; the rest follow in the next scans.
const AUTOCLOSE_PER_SCAN: usize = 20;
/// Close the open issues in `settled` (each with the VEX statement that
/// settles its CVE) as `ISSUE_AUTOCLOSE` says: not at all, only counted, or
/// at most [`AUTOCLOSE_PER_SCAN`] with a comment. Every Gitea request waits
/// for its instance's slot ([`crate::trackers::gitea_limit`]). Unless off,
/// logs one line per target and scan with counts only, also when there is
/// nothing to close, so "ran, nothing to close" shows in the log.
///
/// # Returns
///
/// How many issues were closed.
///
/// # Errors
///
/// A database error.
async fn autoclose(
target: &CveIssueTarget<'_>,
settled: &[(&TrackerIssue, &VexAssessment)],
) -> Result<u32, AgentError> {
let tenant_id = target.tenant_id;
let target_id = target.target_id;
match target.autoclose {
IssueAutoclose::Off => Ok(0),
IssueAutoclose::DryRun => {
let not_affected = settled
.iter()
.filter(|(_, vex)| vex.status == VexStatus::NotAffected)
.count();
tracing::info!(
tenant_id,
target_id,
would_close = settled.len(),
not_affected,
fixed = settled.len() - not_affected,
"CVE issues settled by VEX (dry run, nothing changed)"
);
Ok(0)
}
IssueAutoclose::On => {
let (mut closed, mut failed) = (0u32, 0u32);
for (issue, vex) in settled.iter().take(AUTOCLOSE_PER_SCAN) {
if set_state(target, issue, &vex_comment(vex), "closed").await {
record(target.db, issue, IssueStatus::Closed).await?;
closed += 1;
} else {
failed += 1;
}
}
tracing::info!(
tenant_id,
target_id,
closed,
deferred = settled.len().saturating_sub(AUTOCLOSE_PER_SCAN),
failed,
"CVE issues settled by VEX closed"
);
Ok(closed)
}
}
}
/// The comment an issue is closed with when a VEX statement settles its CVE:
/// the status and the justification, or the reason in words.
fn vex_comment(vex: &VexAssessment) -> String {
let reason = match (vex.justification, vex.impact_statement.as_deref()) {
(Some(justification), _) => format!(" ({})", justification.as_str()),
(None, Some(statement)) if !statement.trim().is_empty() => {
format!(": {}", statement.trim())
}
(None, _) => String::new(),
};
let status = vex.status.as_str();
format!(
"**Prüfwerk:** VEX-Status `{status}`{reason}. Geschlossen, solange diese Aussage gilt.\n\nVEX status `{status}`{reason}. Closed while this statement stands."
)
}
/// Whether an issue is closed.
fn is_closed(status: &IssueStatus) -> bool {
matches!(status, IssueStatus::Closed | IssueStatus::Resolved)
@@ -411,7 +517,7 @@ mod tests {
use axum::extract::{Path, State};
use axum::routing::{get, patch, post};
use axum::{Json, Router};
use compliance_core::models::CveSource;
use compliance_core::models::{CveSource, VexJustification, VexStatus};
use compliance_core::NetGuard;
use secrecy::SecretString;
@@ -420,14 +526,22 @@ mod tests {
/// The calls a fake Gitea received.
type Calls = Arc<Mutex<Vec<String>>>;
async fn fake_gitea(calls: Calls) -> String {
async fn labels() -> Json<serde_json::Value> {
Json(serde_json::json!(pruefwerk_labels()
.iter()
.enumerate()
.map(|(i, l)| serde_json::json!({ "id": i as i64 + 1, "name": l.name, "color": "fff" }))
.collect::<Vec<_>>()))
/// The Prüfwerk labels, all present.
async fn labels(
axum::extract::Query(page): axum::extract::Query<std::collections::HashMap<String, String>>,
) -> Json<serde_json::Value> {
// One page of labels: a later page is empty, as Gitea ends a list.
if page.get("page").map(String::as_str) != Some("1") {
return Json(serde_json::json!([]));
}
Json(serde_json::json!(pruefwerk_labels()
.iter()
.enumerate()
.map(|(i, l)| serde_json::json!({ "id": i as i64 + 1, "name": l.name, "color": "fff" }))
.collect::<Vec<_>>()))
}
async fn fake_gitea(calls: Calls) -> String {
async fn create(
State(calls): State<Calls>,
Json(body): Json<serde_json::Value>,
@@ -453,8 +567,12 @@ mod tests {
async fn comment(
State(calls): State<Calls>,
Path((_o, _r, n)): Path<(String, String, String)>,
Json(body): Json<serde_json::Value>,
) -> axum::http::StatusCode {
calls.lock().unwrap().push(format!("comment {n}"));
calls.lock().unwrap().push(format!(
"comment {n}: {}",
body["body"].as_str().unwrap_or_default()
));
axum::http::StatusCode::CREATED
}
async fn state(
@@ -480,6 +598,27 @@ mod tests {
format!("http://{addr}")
}
/// A Gitea that lists its labels and refuses (and records) every other
/// call: a dry run must not write.
async fn read_only_gitea(calls: Calls) -> String {
async fn refuse(
State(calls): State<Calls>,
method: axum::http::Method,
uri: axum::http::Uri,
) -> axum::http::StatusCode {
calls.lock().unwrap().push(format!("{method} {uri}"));
axum::http::StatusCode::INTERNAL_SERVER_ERROR
}
let app = Router::new()
.route("/api/v1/repos/{o}/{r}/labels", get(labels))
.fallback(refuse)
.with_state(calls);
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}")
}
fn exploited(kev: bool, percentile: Option<f64>) -> compliance_core::models::Exploitation {
compliance_core::models::Exploitation {
kev: kev.then(|| compliance_core::models::KevEntry {
@@ -585,12 +724,14 @@ mod tests {
let tracker = TrackerDispatch::Gitea(gitea);
let target = CveIssueTarget {
db: &db,
tenant_id: "cve-issues",
tracker: &tracker,
owner: "kunde",
repo: "app",
target_id: "target-1",
dashboard: "https://pruefwerk.example",
epss_percentile: Some(0.95),
autoclose: IssueAutoclose::Off,
};
let okhttp = alert("okhttp", "3.12.0", "GHSA-3cqm-mf7h-prrj", "HIGH");
let minor = alert("gson", "2.8.8", "GHSA-4jrv-ppp4-jm57", "MODERATE");
@@ -653,4 +794,303 @@ mod tests {
pool.drop_tenant("cve-issues").await.ok();
}
fn vex(status: VexStatus) -> VexAssessment {
VexAssessment {
status,
justification: (status == VexStatus::NotAffected)
.then_some(VexJustification::VulnerableCodeNotInExecutePath),
impact_statement: None,
action_statement: None,
by: "u1".into(),
by_name: None,
at: chrono::Utc::now(),
by_scan: false,
}
}
#[test]
fn the_vex_comment_names_the_status_and_the_reason() {
let comment = vex_comment(&vex(VexStatus::NotAffected));
assert!(
comment.contains("VEX status `not_affected` (vulnerable_code_not_in_execute_path)."),
"{comment}"
);
let mut stated = vex(VexStatus::NotAffected);
stated.justification = None;
stated.impact_statement = Some(" The parser is not built. ".into());
assert!(vex_comment(&stated).contains("`not_affected`: The parser is not built."));
assert!(vex_comment(&vex(VexStatus::Fixed)).contains("VEX status `fixed`. Closed"));
}
/// A tenant database for one test, or `None` (the test skips) without
/// MongoDB.
async fn test_db(tenant: &str) -> Option<(crate::database::DatabasePool, Database)> {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"cvevex_{}",
&uuid::Uuid::new_v4().simple().to_string()[..10]
);
let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP cve_issues: no MongoDB reachable at {uri}");
return None;
};
let db = pool.for_tenant_id(tenant).await.unwrap();
Some((pool, db))
}
fn tracker_at(base: String) -> TrackerDispatch {
TrackerDispatch::Gitea(
GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap(),
)
}
fn vex_target<'a>(
db: &'a Database,
tracker: &'a TrackerDispatch,
autoclose: IssueAutoclose,
) -> CveIssueTarget<'a> {
CveIssueTarget {
db,
tenant_id: "cve-issues-vex",
tracker,
owner: "kunde",
repo: "app",
target_id: "target-1",
dashboard: "",
epss_percentile: None,
autoclose,
}
}
fn closed(n: u32) -> CveIssueCounts {
CveIssueCounts {
closed: n,
..Default::default()
}
}
#[tokio::test]
async fn a_vex_not_affected_or_fixed_closes_the_issue_until_it_is_withdrawn() {
let Some((pool, db)) = test_db("cve-issues-vex").await else {
return;
};
let calls: Calls = Arc::default();
let tracker = tracker_at(fake_gitea(calls.clone()).await);
let target = vex_target(&db, &tracker, IssueAutoclose::On);
let mut okhttp = alert("okhttp", "3.12.0", "GHSA-3cqm-mf7h-prrj", "HIGH");
let mut settled = alert("log4j-core", "2.14.1", "GHSA-jfh8-c2jp-5v3q", "CRITICAL");
settled.aliases = vec!["CVE-2021-44228".into()];
settled.vex = Some(vex(VexStatus::Fixed));
// A settled CVE opens no issue; the unsettled one opens one.
let counts = sync_cve_issues(&target, &[okhttp.clone(), settled.clone()], true)
.await
.unwrap();
assert_eq!(
counts,
CveIssueCounts {
created: 1,
..Default::default()
}
);
assert!(calls.lock().unwrap()[0].contains("okhttp@3.12.0"));
// Stated not_affected: closed with the status and the reason, even
// after an incomplete scan, and only once.
okhttp.vex = Some(vex(VexStatus::NotAffected));
let both = [okhttp.clone(), settled.clone()];
assert_eq!(
sync_cve_issues(&target, &both, false).await.unwrap(),
closed(1)
);
{
let calls = calls.lock().unwrap();
let comment = &calls[calls.len() - 2];
assert!(comment.starts_with("comment 100: "), "{comment}");
assert!(
comment.contains("`not_affected` (vulnerable_code_not_in_execute_path)"),
"{comment}"
);
assert_eq!(calls.last().unwrap(), "state 100: \"closed\"");
}
assert_eq!(
sync_cve_issues(&target, &both, true).await.unwrap(),
CveIssueCounts::default()
);
// Withdrawn (back under investigation): the same issue is reopened,
// not opened twice.
okhttp.vex = Some(vex(VexStatus::UnderInvestigation));
assert_eq!(
sync_cve_issues(&target, &[okhttp.clone(), settled], true)
.await
.unwrap(),
CveIssueCounts {
reopened: 1,
..Default::default()
}
);
assert_eq!(calls.lock().unwrap().last().unwrap(), "state 100: \"open\"");
assert_eq!(
db.tracker_issues().count_documents(doc! {}).await.unwrap(),
1
);
pool.drop_tenant("cve-issues-vex").await.ok();
}
/// Log lines written while the returned guard lives (on this thread; a
/// `#[tokio::test]` runs on one).
fn capture_logs() -> (Arc<Mutex<Vec<u8>>>, tracing::subscriber::DefaultGuard) {
let buffer: Arc<Mutex<Vec<u8>>> = Arc::default();
let writer = buffer.clone();
let subscriber = tracing_subscriber::fmt()
.with_ansi(false)
.with_max_level(tracing::Level::INFO)
.with_writer(move || LogWriter(writer.clone()))
.finish();
(buffer, tracing::subscriber::set_default(subscriber))
}
struct LogWriter(Arc<Mutex<Vec<u8>>>);
impl std::io::Write for LogWriter {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
/// The autoclose summary lines logged into `logs`.
fn summaries(logs: &Mutex<Vec<u8>>) -> Vec<String> {
String::from_utf8_lossy(&logs.lock().unwrap())
.lines()
.filter(|l| l.contains("CVE issues settled by VEX"))
.map(str::to_owned)
.collect()
}
#[tokio::test]
async fn autoclose_off_and_dry_run_leave_the_issue_open() {
let Some((pool, db)) = test_db("cve-issues-vex-off").await else {
return;
};
let (logs, _guard) = capture_logs();
let calls: Calls = Arc::default();
let tracker = tracker_at(fake_gitea(calls.clone()).await);
let mut okhttp = alert("okhttp", "3.12.0", "GHSA-3cqm-mf7h-prrj", "HIGH");
let open = vex_target(&db, &tracker, IssueAutoclose::Off);
assert_eq!(
sync_cve_issues(&open, std::slice::from_ref(&okhttp), true)
.await
.unwrap()
.created,
1
);
let before = calls.lock().unwrap().len();
// Off: the settled CVE's issue stays open, nothing is called.
okhttp.vex = Some(vex(VexStatus::Fixed));
let found = std::slice::from_ref(&okhttp);
assert_eq!(
sync_cve_issues(&open, found, true).await.unwrap(),
CveIssueCounts::default()
);
assert_eq!(calls.lock().unwrap().len(), before);
// Off logs no summary.
assert!(summaries(&logs).is_empty());
// Dry run, against a Gitea that refuses every write: only counted,
// and a target with nothing to close says so too.
let writes: Calls = Arc::default();
let read_only = tracker_at(read_only_gitea(writes.clone()).await);
let dry = vex_target(&db, &read_only, IssueAutoclose::DryRun);
assert_eq!(
sync_cve_issues(&dry, found, true).await.unwrap(),
CveIssueCounts::default()
);
assert!(writes.lock().unwrap().is_empty(), "{:?}", writes.lock());
let other = CveIssueTarget {
target_id: "target-2",
..vex_target(&db, &read_only, IssueAutoclose::DryRun)
};
sync_cve_issues(&other, &[], true).await.unwrap();
let lines = summaries(&logs);
assert_eq!(lines.len(), 2, "{lines:?}");
assert!(
lines[0].contains("tenant_id=\"cve-issues-vex\"")
&& lines[0].contains("target_id=\"target-1\"")
&& lines[0].contains("would_close=1 not_affected=0 fixed=1"),
"{}",
lines[0]
);
assert!(
lines[1].contains("target_id=\"target-2\"") && lines[1].contains("would_close=0"),
"{}",
lines[1]
);
// No title or path in the line.
assert!(!lines[0].contains("okhttp"), "{}", lines[0]);
assert_eq!(
db.tracker_issues()
.count_documents(doc! { "status": "open" })
.await
.unwrap(),
1
);
pool.drop_tenant("cve-issues-vex-off").await.ok();
}
#[tokio::test]
async fn autoclose_closes_at_most_twenty_per_scan() {
let Some((pool, db)) = test_db("cve-issues-vex-many").await else {
return;
};
let calls: Calls = Arc::default();
let tracker = tracker_at(fake_gitea(calls.clone()).await);
let target = vex_target(&db, &tracker, IssueAutoclose::On);
let mut alerts: Vec<CveAlert> = (0..22)
.map(|i| {
let mut a = alert(
&format!("lib{i:02}"),
"1.0",
&format!("CVE-2026-{i:04}"),
"HIGH",
);
a.aliases.clear();
a
})
.collect();
assert_eq!(
sync_cve_issues(&target, &alerts, true)
.await
.unwrap()
.created,
22
);
for a in &mut alerts {
a.vex = Some(vex(VexStatus::NotAffected));
}
assert_eq!(
sync_cve_issues(&target, &alerts, true).await.unwrap(),
closed(20)
);
assert_eq!(
sync_cve_issues(&target, &alerts, true).await.unwrap(),
closed(2)
);
assert_eq!(
sync_cve_issues(&target, &alerts, true).await.unwrap(),
CveIssueCounts::default()
);
pool.drop_tenant("cve-issues-vex-many").await.ok();
}
}
@@ -0,0 +1,78 @@
//! A notification for every CVE a target's components newly carry, shared by
//! the scans (every SBOM source: source, firmware, CODESYS libraries and
//! runtime) and the hourly CVE monitor.
//!
//! One notification per CVE, target, package and version. An alert a VEX
//! statement settles (`not_affected` or `fixed`, see
//! [`CveAlert::is_resolved_by_vex`]) raises none; once the statement is
//! withdrawn, the next scan or monitor run raises it as for any new CVE.
use mongodb::bson::doc;
use compliance_core::models::notification::{parse_severity, CveNotification};
use compliance_core::models::CveAlert;
use crate::database::Database;
/// Create the notifications `alerts` of the target `repo_id` (named
/// `repo_name`) do not have yet. The alerts carry their stored VEX statement
/// ([`crate::pipeline::vex_lifecycle::attach_stored_vex`]).
///
/// # Returns
///
/// How many notifications were created. A notification that cannot be stored
/// is logged and skipped.
pub async fn notify_new_cves(
db: &Database,
repo_id: &str,
repo_name: &str,
alerts: &[CveAlert],
) -> u32 {
let mut created = 0;
for alert in alerts.iter().filter(|a| !a.is_resolved_by_vex()) {
let filter = doc! {
"cve_id": &alert.cve_id,
"repo_id": &alert.repo_id,
"package_name": &alert.affected_package,
"package_version": &alert.affected_version,
};
let severity = parse_severity(alert.severity.as_deref(), alert.cvss_score);
let mut notification = CveNotification::new(
alert.cve_id.clone(),
repo_id.to_string(),
repo_name.to_string(),
alert.affected_package.clone(),
alert.affected_version.clone(),
severity,
);
notification.cvss_score = alert.cvss_score;
notification.summary = alert.summary.clone();
notification.url = Some(format!("https://osv.dev/vulnerability/{}", alert.cve_id));
let notification = match mongodb::bson::to_bson(&notification) {
Ok(n) => n,
Err(e) => {
tracing::warn!(
cve = alert.cve_id,
"could not encode the CVE notification: {e}"
);
continue;
}
};
// Inserted only when missing (`$setOnInsert`), so a notification
// that was read or dismissed stays as it is.
match db
.cve_notifications()
.update_one(filter, doc! { "$setOnInsert": notification })
.upsert(true)
.await
{
Ok(result) if result.upserted_id.is_some() => created += 1,
Ok(_) => {}
Err(e) => tracing::warn!(
cve = alert.cve_id,
"could not store the CVE notification: {e}"
),
}
}
created
}
@@ -494,7 +494,7 @@ fn check_frameworks(root: &Path, today: chrono::NaiveDate) -> Vec<Hit> {
),
remediation: "Retarget the project to a supported version (.NET Framework \
4.8/4.8.1, or a supported .NET release) and test it there.",
severity: Severity::Medium,
severity: Severity::High,
cwe: "CWE-1104",
path: project.path.clone(),
line: Some(tf.line),
@@ -677,6 +677,8 @@ mod tests {
["dotnet-framework-end-of-support Legacy/Legacy.csproj:3"]
);
assert_eq!(hits[0].cwe, "CWE-1104");
// End of life is high, like every other end-of-life finding.
assert_eq!(hits[0].severity, Severity::High);
assert!(
hits[0].title.contains(".NET Framework 4.5"),
"{}",
+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.
+71 -3
View File
@@ -5,6 +5,7 @@ use git2::{Cred, FetchOptions, RemoteCallbacks, RemoteRedirect, Repository};
use compliance_core::NetGuard;
use crate::error::AgentError;
use crate::pipeline::git_retry::Backoff;
use crate::tenant_path::{name_segment, tenant_segment};
/// The directory a tenant's checkout of `repo_name` lives in.
@@ -173,6 +174,8 @@ pub struct GitOps {
net_guard: NetGuard,
/// How long and how large a clone or fetch may be.
limits: CloneLimits,
/// When a clone or fetch the host failed briefly is tried again.
backoff: Backoff,
}
impl GitOps {
@@ -188,6 +191,7 @@ impl GitOps {
credentials,
net_guard,
limits: CloneLimits::from_env(),
backoff: Backoff::default(),
}
}
@@ -198,6 +202,18 @@ impl GitOps {
self
}
/// The same operations with another retry schedule (tests).
#[cfg(test)]
fn with_backoff(mut self, backoff: Backoff) -> Self {
self.backoff = backoff;
self
}
/// When this instance tries a failed clone or fetch again.
pub(crate) fn backoff(&self) -> &Backoff {
&self.backoff
}
/// Fetch options for one bounded transfer: the credentials, no
/// redirects, and a progress check that stops the transfer once it
/// exceeds [`CloneLimits`], leaving the reason in `stopped`.
@@ -282,6 +298,11 @@ impl GitOps {
#[tracing::instrument(skip_all, fields(tenant = %self.tenant_id, repo_name = %repo_name))]
pub fn clone_or_fetch(&self, git_url: &str, repo_name: &str) -> Result<PathBuf, AgentError> {
reject_ssh_url(git_url)?;
// At most two clones or fetches per git host, held to the end of this
// one; a refused remote has no host and fails below anyway.
let _host_slot = self
.remote_host(git_url)
.map(|host| crate::pipeline::clone_limit::CLONE_SLOTS.acquire(&host));
// Per tenant: two tenants with the same target name get two checkouts.
let repo_path = self.clone_path(repo_name);
@@ -290,7 +311,8 @@ impl GitOps {
// every scan after it (#486).
if repo_path.exists() && prepare_entry(&repo_path) {
tracing::info!("fetching updates for existing repo");
match self.fetch(&repo_path) {
// A 502 is retried before it can be taken for a broken entry.
match self.backoff.retry("fetch", || self.fetch(&repo_path)) {
Ok(()) => return Ok(repo_path),
Err(AgentError::Git(e)) if is_corruption(&e) => {
tracing::warn!(
@@ -315,7 +337,8 @@ impl GitOps {
// Before creating anything: a refused remote must not leave an entry
// behind for the next run to try to fetch.
self.check_remote(git_url)?;
self.clone_atomically(git_url, &repo_path)?;
self.backoff
.retry("clone", || self.clone_atomically(git_url, &repo_path))?;
tracing::info!("Cloned {git_url} to {}", repo_path.display());
Ok(repo_path)
}
@@ -376,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(())
@@ -833,6 +863,44 @@ mod tests {
);
}
#[test]
fn a_clone_the_host_answers_with_502_is_tried_four_times() {
// A git host that answers every request with 502, counting them.
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
let port = listener.local_addr().expect("addr").port();
let requests = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let counted = std::sync::Arc::clone(&requests);
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(mut stream) = stream else { break };
counted.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let mut buf = [0u8; 4096];
let _ = std::io::Read::read(&mut stream, &mut buf);
let _ = std::io::Write::write_all(
&mut stream,
b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
);
}
});
let scratch =
Scratch(std::env::temp_dir().join(format!("cs-git-{}", uuid::Uuid::new_v4())));
let ops = GitOps::new(
&scratch.0.to_string_lossy(),
"tenant-a",
RepoCredentials::default(),
NetGuard::allow_private(),
)
.with_backoff(crate::pipeline::git_retry::Backoff::immediate());
let err = ops
.clone_or_fetch(&format!("http://127.0.0.1:{port}/org/repo.git"), "flaky")
.expect_err("the host never recovers");
assert!(err.to_string().contains("502"), "{err}");
assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 4);
assert!(!ops.clone_path("flaky").exists());
}
#[test]
fn a_fetch_rechecks_the_stored_remote() {
// An existing checkout whose `origin` now points somewhere private (a
+238
View File
@@ -0,0 +1,238 @@
//! Retrying a clone or fetch the git host failed for a passing reason.
//!
//! A git host that restarts (an OOM kill, a redeploy) answers `502` or
//! refuses connections for a few seconds; every scan that clones in that
//! window would fail. A clone or fetch that fails with a 5xx status or a
//! network error is tried again after 5, 15 and 30 seconds. One that fails
//! for a reason another try cannot change (authentication, 403, 404, a
//! missing reference, a download limit) fails at once.
use std::time::Duration;
use git2::{ErrorClass, ErrorCode};
use crate::error::AgentError;
/// The waits between the tries of one clone or fetch: one retry per entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Backoff {
schedule: [Duration; 3],
}
impl Default for Backoff {
/// Three retries, after 5, 15 and 30 seconds.
fn default() -> Self {
Self {
schedule: [5, 15, 30].map(Duration::from_secs),
}
}
}
impl Backoff {
/// The same number of retries without waiting (tests).
#[cfg(test)]
pub(crate) fn immediate() -> Self {
Self {
schedule: [Duration::ZERO; 3],
}
}
/// Run `op`, and run it again after each wait of the schedule while it
/// fails with a [transient](is_transient) error.
///
/// # Arguments
///
/// * `what` - What `op` does, for the log (`"clone"`, `"fetch"`).
/// * `op` - The clone or fetch; it must be safe to run again after it failed.
///
/// # Errors
///
/// The first error that is not transient, or the last one once the
/// schedule is used up.
pub fn retry<T>(
&self,
what: &str,
mut op: impl FnMut() -> Result<T, AgentError>,
) -> Result<T, AgentError> {
// `iter()` yields `&Duration`, one wait per retry, in order.
let mut waits = self.schedule.iter();
let mut attempt = 1;
loop {
match op() {
Ok(value) => return Ok(value),
Err(error) => {
let Some(wait) = waits.next().filter(|_| is_retryable(&error)) else {
return Err(error);
};
tracing::warn!(
attempt,
wait_secs = wait.as_secs(),
error = %error,
"git {what} failed for a passing reason; trying again"
);
sleep(*wait);
attempt += 1;
}
}
}
}
}
/// Whether `error` is a git error another try may not see.
fn is_retryable(error: &AgentError) -> bool {
matches!(error, AgentError::Git(e) if is_transient(e))
}
/// Whether a git error comes from the host or the network being briefly
/// unavailable: a 5xx status, a timeout, or a connection that failed.
pub fn is_transient(error: &git2::Error) -> bool {
if error.code() == ErrorCode::Auth {
return false;
}
if error.code() == ErrorCode::Timeout {
return true;
}
match error.class() {
// libgit2: "unexpected http status code: 502".
ErrorClass::Http => error
.message()
.strip_prefix("unexpected http status code: ")
.and_then(|status| status.trim().parse::<u16>().ok())
.is_some_and(|status| (500..=599).contains(&status)),
// Every network error libgit2 raises is a failed connection, read or
// write, except these three about the URL itself.
ErrorClass::Net => !["invalid url", "invalid scp-style path", "cannot redirect"]
.iter()
.any(|prefix| error.message().starts_with(prefix)),
_ => false,
}
}
/// Wait `duration` on this thread, without stalling the async runtime's
/// other tasks (clones run on its worker threads).
fn sleep(duration: Duration) {
if !duration.is_zero() {
crate::pipeline::clone_limit::off_the_runtime(|| std::thread::sleep(duration));
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::{is_transient, Backoff};
use crate::error::AgentError;
use git2::{ErrorClass, ErrorCode};
fn git_error(code: ErrorCode, class: ErrorClass, message: &str) -> git2::Error {
git2::Error::new(code, class, message)
}
fn http_status(status: u16) -> git2::Error {
git_error(
ErrorCode::GenericError,
ErrorClass::Http,
&format!("unexpected http status code: {status}"),
)
}
#[test]
fn a_5xx_status_is_transient() {
assert!(is_transient(&http_status(502)));
assert!(is_transient(&http_status(503)));
assert!(is_transient(&http_status(500)));
}
#[test]
fn a_failed_connection_or_timeout_is_transient() {
let refused = git_error(
ErrorCode::GenericError,
ErrorClass::Net,
"failed to connect to git.example.com: Connection refused",
);
let timeout = git_error(
ErrorCode::Timeout,
ErrorClass::Net,
"could not read from socket: timed out",
);
let unresolved = git_error(
ErrorCode::GenericError,
ErrorClass::Net,
"failed to resolve address for git.example.com: Name or service not known",
);
assert!(is_transient(&refused));
assert!(is_transient(&timeout));
assert!(is_transient(&unresolved));
}
#[test]
fn auth_not_found_and_bad_refs_are_not_transient() {
let unauthorized = git_error(
ErrorCode::Auth,
ErrorClass::Http,
"unexpected authentication failure",
);
let missing_ref = git_error(
ErrorCode::NotFound,
ErrorClass::Reference,
"reference 'refs/heads/nope' not found",
);
let bad_url = git_error(ErrorCode::GenericError, ErrorClass::Net, "invalid url: x");
let redirect = git_error(
ErrorCode::GenericError,
ErrorClass::Net,
"cannot redirect from 'a' to 'b'",
);
assert!(!is_transient(&unauthorized));
assert!(!is_transient(&http_status(401)));
assert!(!is_transient(&http_status(403)));
assert!(!is_transient(&http_status(404)));
assert!(!is_transient(&missing_ref));
assert!(!is_transient(&bad_url));
assert!(!is_transient(&redirect));
}
/// An operation that fails with `error` its first `failures` runs, and
/// how often it ran.
fn run_failing(failures: usize, error: fn() -> AgentError) -> (Result<u8, AgentError>, usize) {
let mut runs = 0;
let result = Backoff::immediate().retry("fetch", || {
runs += 1;
if runs <= failures {
Err(error())
} else {
Ok(7)
}
});
(result, runs)
}
#[test]
fn two_502s_then_success_succeeds_on_the_third_try() {
let (result, runs) = run_failing(2, || AgentError::Git(http_status(502)));
assert_eq!(result.unwrap(), 7);
assert_eq!(runs, 3);
}
#[test]
fn four_502s_fail_after_three_retries() {
let (result, runs) = run_failing(4, || AgentError::Git(http_status(502)));
assert!(matches!(result, Err(AgentError::Git(e)) if e.message().contains("502")));
assert_eq!(runs, 4);
}
#[test]
fn a_permanent_error_is_not_retried() {
let (result, runs) = run_failing(4, || AgentError::Git(http_status(404)));
assert!(result.is_err());
assert_eq!(runs, 1);
let (limit, runs) = run_failing(4, || AgentError::Other("download limit".to_string()));
assert!(limit.is_err());
assert_eq!(runs, 1);
}
#[test]
fn the_default_schedule_waits_5_15_and_30_seconds() {
let secs = Backoff::default().schedule.map(|d| d.as_secs());
assert_eq!(secs, [5, 15, 30]);
}
}
@@ -91,10 +91,12 @@ impl GitOps {
} else {
&anonymous
};
let mut options = SubmoduleUpdateOptions::new();
options.fetch(credentials.fetch_options());
submodule.update(true, Some(&mut options))?;
Ok(())
self.backoff().retry("submodule fetch", || {
let mut options = SubmoduleUpdateOptions::new();
options.fetch(credentials.fetch_options());
submodule.update(true, Some(&mut options))?;
Ok(())
})
}
}
@@ -0,0 +1,595 @@
//! The issue catch-up (`ISSUE_CATCHUP`).
//!
//! A scan opens issues only for the findings it stores new, so a finding
//! whose issue could not be opened (a failed listing, a refused create)
//! never got one later. After a scan's own issues, the catch-up goes through
//! the target's open medium+ findings without an issue: one that has an issue
//! already (by fingerprint marker, then title, as in
//! [`super::issue_creation`]) is linked to it, the others get a new one, at
//! 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};
use compliance_core::config::IssueCatchup;
use compliance_core::models::{Finding, Severity};
use futures_util::TryStreamExt;
use mongodb::bson::doc;
use super::issue_creation::{
issue_title, wants_issue, ExistingIssues, IssueSink, KnownIssue, ISSUE_SEVERITIES,
ISSUE_STATUSES,
};
use crate::error::AgentError;
/// New issues the catch-up opens per target and scan; links are not counted.
pub(super) const MAX_NEW_ISSUES: usize = 20;
/// A count per severity, highest first when shown.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub(super) struct SeverityCounts(BTreeMap<Severity, u32>);
impl SeverityCounts {
/// Count one finding of `severity`.
fn add(&mut self, severity: &Severity) {
*self.0.entry(severity.clone()).or_default() += 1;
}
/// All counted.
pub(super) fn total(&self) -> u32 {
self.0.values().sum()
}
}
impl std::fmt::Display for SeverityCounts {
/// `critical=1 high=3`, or `-` when nothing was counted.
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.0.is_empty() {
return f.write_str("-");
}
let parts: Vec<String> = self
.0
.iter()
.rev()
.map(|(severity, n)| format!("{severity}={n}"))
.collect();
f.write_str(&parts.join(" "))
}
}
/// What a catch-up does, decided before any request.
#[derive(Debug, Default)]
struct CatchupPlan<'a> {
/// Findings whose issue exists, with it.
link: Vec<(&'a Finding, &'a KnownIssue)>,
/// Findings that get a new issue, at most the cap.
create: Vec<&'a Finding>,
/// Findings past the cap: their issues wait for the next scans.
deferred: SeverityCounts,
}
/// What a catch-up did on one target (in a dry run: would do).
#[derive(Debug, Default, PartialEq, Eq)]
pub(super) struct CatchupSummary {
pub(super) mode: IssueCatchup,
pub(super) created: SeverityCounts,
pub(super) linked: SeverityCounts,
pub(super) deferred: SeverityCounts,
/// Issues the tracker refused.
pub(super) failed: u32,
}
impl CatchupSummary {
/// Log the one line per target: counts and severities, never a title or
/// a path.
pub(super) fn log(&self, tenant_id: &str, target_id: &str) {
let what = match self.mode {
IssueCatchup::DryRun => "issue catch-up (dry run, nothing changed)",
IssueCatchup::Off | IssueCatchup::On => "issue catch-up",
};
tracing::info!(
tenant_id,
target_id,
mode = self.mode.as_str(),
created = self.created.total(),
created_severities = %self.created,
linked = self.linked.total(),
linked_severities = %self.linked,
deferred = self.deferred.total(),
deferred_severities = %self.deferred,
failed = self.failed,
"{what}"
);
}
}
/// Run the catch-up for the target of `sink` against `index`, the listing
/// of its repository's issues (with the scan's new issues added).
///
/// # Errors
///
/// The target's findings cannot be read.
pub(super) async fn catch_up(
sink: &IssueSink<'_>,
index: &ExistingIssues,
mode: IssueCatchup,
) -> Result<CatchupSummary, AgentError> {
let candidates = select(load_candidates(sink).await?);
Ok(run(sink, &candidates, index, mode).await)
}
/// 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(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> {
let mut candidates: Vec<Finding> = findings
.into_iter()
.filter(|f| wants_issue(f) && f.tracker_issue_url.is_none())
.collect();
candidates.sort_by(|a, b| {
b.severity
.cmp(&a.severity)
.then(a.created_at.cmp(&b.created_at))
});
candidates
}
/// Decide for each of `candidates` (in order): link it to its issue in
/// `index`, give it a new one while fewer than `cap` are planned, or defer
/// it. A single finding with the title of an issue planned here is left for
/// the next scan, which links it to that issue (as the scan's own issue
/// creation never opens two issues of one title).
fn plan<'a>(candidates: &'a [Finding], index: &'a ExistingIssues, cap: usize) -> CatchupPlan<'a> {
let mut plan = CatchupPlan::default();
let mut planned_titles = HashSet::new();
for finding in candidates {
let title = issue_title(finding);
if let Some(known) = index.find(finding, &title) {
plan.link.push((finding, known));
} else if finding.occurrences.is_empty() && planned_titles.contains(&title) {
continue;
} else if plan.create.len() < cap {
planned_titles.insert(title);
plan.create.push(finding);
} else {
plan.deferred.add(&finding.severity);
}
}
plan
}
/// Plan the catch-up of `candidates` and, when `mode` is on, carry it out.
async fn run(
sink: &IssueSink<'_>,
candidates: &[Finding],
index: &ExistingIssues,
mode: IssueCatchup,
) -> CatchupSummary {
let plan = plan(candidates, index, MAX_NEW_ISSUES);
let mut summary = CatchupSummary {
mode,
deferred: plan.deferred,
..CatchupSummary::default()
};
match mode {
IssueCatchup::Off => {}
IssueCatchup::DryRun => {
plan.link
.iter()
.for_each(|(f, _)| summary.linked.add(&f.severity));
plan.create
.iter()
.for_each(|f| summary.created.add(&f.severity));
}
IssueCatchup::On => {
for (finding, known) in plan.link {
sink.link(finding, &issue_title(finding), known).await;
summary.linked.add(&finding.severity);
}
for finding in plan.create {
match sink.open(finding, &issue_title(finding)).await {
Ok(_) => summary.created.add(&finding.severity),
Err(e) => {
summary.failed += 1;
tracing::warn!(
"[{}] Catch-up issue for {} not created: {e}",
sink.repo_id,
finding.fingerprint
);
}
}
}
}
}
summary
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use std::sync::{Arc, Mutex};
use axum::extract::State;
use axum::routing::get;
use axum::{Json, Router};
use chrono::{Duration, Utc};
use compliance_core::models::{FindingStatus, ScanType, TrackerIssue};
use compliance_core::NetGuard;
use secrecy::SecretString;
use super::*;
use crate::database::Database;
use crate::pipeline::issue_creation::format_issue_body;
use crate::pipeline::tracker_dispatch::TrackerDispatch;
use crate::trackers::gitea::{GiteaIssue, GiteaTracker};
/// A finding of `severity`, `age_days` old.
fn finding(fingerprint: &str, severity: Severity, age_days: i64) -> Finding {
let mut f = Finding::new(
"target-1".into(),
fingerprint.into(),
"semgrep".into(),
ScanType::Sast,
format!("rule {fingerprint}"),
"desc".into(),
severity,
);
f.created_at = Utc::now() - Duration::days(age_days);
f
}
fn fingerprints(findings: &[&Finding]) -> Vec<String> {
findings.iter().map(|f| f.fingerprint.clone()).collect()
}
/// A listed issue whose body carries `finding`'s fingerprint marker.
fn issue_of(number: i64, finding: &Finding) -> GiteaIssue {
GiteaIssue {
number,
title: "renamed since".into(),
body: Some(format_issue_body(finding)),
html_url: format!("https://gitea.invalid/o/r/issues/{number}"),
state: "open".into(),
}
}
#[test]
fn only_undecided_medium_and_above_without_an_issue_are_caught_up() {
let mut linked = finding("linked", Severity::High, 1);
linked.tracker_issue_url = Some("https://gitea.invalid/o/r/issues/1".into());
let mut decided = finding("decided", Severity::Critical, 1);
decided.status = FindingStatus::AcceptedRisk;
let mut triaged = finding("triaged", Severity::Medium, 1);
triaged.status = FindingStatus::Triaged;
let selected = select(vec![
finding("low", Severity::Low, 1),
finding("info", Severity::Info, 1),
linked,
decided,
triaged,
finding("open", Severity::High, 1),
]);
let names: Vec<&str> = selected.iter().map(|f| f.fingerprint.as_str()).collect();
assert_eq!(names, ["open", "triaged"]);
}
#[test]
fn highest_severity_first_then_oldest() {
let selected = select(vec![
finding("medium-old", Severity::Medium, 30),
finding("high-new", Severity::High, 1),
finding("critical-new", Severity::Critical, 1),
finding("high-old", Severity::High, 10),
finding("critical-old", Severity::Critical, 5),
]);
let names: Vec<&str> = selected.iter().map(|f| f.fingerprint.as_str()).collect();
assert_eq!(
names,
[
"critical-old",
"critical-new",
"high-old",
"high-new",
"medium-old"
]
);
}
#[test]
fn at_most_twenty_new_issues_and_the_rest_are_deferred() {
let mut all: Vec<Finding> = (0..22)
.map(|i| finding(&format!("high-{i}"), Severity::High, 100 - i))
.collect();
all.extend((0..3).map(|i| finding(&format!("medium-{i}"), Severity::Medium, 1)));
let candidates = select(all);
let index = ExistingIssues::default();
let plan = plan(&candidates, &index, MAX_NEW_ISSUES);
assert_eq!(plan.create.len(), 20);
assert!(plan.link.is_empty());
// The oldest highs first; two highs and the mediums wait.
assert_eq!(plan.create[0].fingerprint, "high-0");
assert_eq!(plan.create[19].fingerprint, "high-19");
assert_eq!(plan.deferred.total(), 5);
assert_eq!(plan.deferred.to_string(), "high=2 medium=3");
}
#[test]
fn a_finding_with_an_issue_is_linked_and_not_counted() {
let candidates = select(
(0..21)
.map(|i| finding(&format!("fp-{i}"), Severity::High, 50 - i))
.collect(),
);
// fp-0 has its issue (found by its marker, under another title).
let index = ExistingIssues::new(&[issue_of(7, &candidates[0])]);
let plan = plan(&candidates, &index, MAX_NEW_ISSUES);
assert_eq!(plan.link.len(), 1);
assert_eq!(plan.link[0].0.fingerprint, "fp-0");
assert_eq!(plan.link[0].1.url, "https://gitea.invalid/o/r/issues/7");
assert_eq!(plan.create.len(), 20, "the link does not use the cap");
assert!(!fingerprints(&plan.create).contains(&"fp-0".to_string()));
assert_eq!(plan.deferred.total(), 0);
}
#[test]
fn one_new_issue_per_title() {
let first = finding("fp-a", Severity::High, 2);
let mut second = finding("fp-b", Severity::High, 1);
second.title = first.title.clone();
let candidates = select(vec![first, second]);
let index = ExistingIssues::default();
let plan = plan(&candidates, &index, MAX_NEW_ISSUES);
assert_eq!(fingerprints(&plan.create), ["fp-a"]);
assert_eq!(plan.deferred.total(), 0);
}
/// Requests a fake Gitea saw, as `METHOD path`.
type Seen = Arc<Mutex<Vec<String>>>;
/// A fake Gitea whose repository has `issues`; a created issue gets
/// number 100 and up.
async fn fake_gitea(issues: Vec<GiteaIssue>, seen: Seen) -> String {
async fn list(
State((issues, seen)): State<(Arc<Vec<serde_json::Value>>, Seen)>,
axum::extract::Query(params): axum::extract::Query<
std::collections::HashMap<String, String>,
>,
) -> Json<serde_json::Value> {
seen.lock().unwrap().push("GET issues".into());
if params.get("page").map(String::as_str) != Some("1") {
return Json(serde_json::json!([]));
}
Json(serde_json::json!(*issues))
}
async fn create(
State((_, seen)): State<(Arc<Vec<serde_json::Value>>, Seen)>,
) -> (axum::http::StatusCode, Json<serde_json::Value>) {
let mut seen = seen.lock().unwrap();
seen.push("POST issues".into());
let number = 99 + seen.iter().filter(|s| s.starts_with("POST")).count();
(
axum::http::StatusCode::CREATED,
Json(serde_json::json!({
"number": number,
"html_url": format!("https://gitea.invalid/o/r/issues/{number}"),
})),
)
}
let issues: Vec<serde_json::Value> = issues
.iter()
.map(|i| {
serde_json::json!({
"number": i.number,
"title": i.title,
"body": i.body,
"html_url": i.html_url,
"state": i.state,
})
})
.collect();
let app = Router::new()
.route("/api/v1/repos/{o}/{r}/issues", get(list).post(create))
.with_state((Arc::new(issues), 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}")
}
fn sink<'a>(db: &'a Database, tracker: &'a TrackerDispatch, repo_id: &'a str) -> IssueSink<'a> {
IssueSink {
db,
tracker,
owner: "kunde",
repo: "fw",
repo_id,
managed: false,
dashboard: String::new(),
labels: tokio::sync::OnceCell::new(),
}
}
fn posts(seen: &Seen) -> usize {
seen.lock()
.unwrap()
.iter()
.filter(|s| s.starts_with("POST"))
.count()
}
#[tokio::test]
async fn a_dry_run_counts_but_creates_and_links_nothing() {
let seen: Seen = Arc::default();
let with_issue = finding("fp-old", Severity::High, 9);
let index = ExistingIssues::new(&[issue_of(7, &with_issue)]);
let base = fake_gitea(Vec::new(), seen.clone()).await;
let tracker = TrackerDispatch::Gitea(
GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap(),
);
// Never reached: a dry run writes nothing (the client connects lazily).
let client =
mongodb::Client::with_uri_str("mongodb://127.0.0.1:1/?serverSelectionTimeoutMS=100")
.await
.unwrap();
let db = Database::from_database(client.database("unused"));
let sink = sink(&db, &tracker, "target-1");
let candidates = select(vec![
with_issue,
finding("fp-new", Severity::Critical, 1),
finding("fp-medium", Severity::Medium, 1),
]);
let summary = run(&sink, &candidates, &index, IssueCatchup::DryRun).await;
assert_eq!(summary.created.to_string(), "critical=1 medium=1");
assert_eq!(summary.linked.to_string(), "high=1");
assert_eq!(summary.deferred.total(), 0);
assert!(seen.lock().unwrap().is_empty(), "no request to Gitea");
}
#[tokio::test]
async fn on_links_by_marker_and_opens_the_others() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"catchup_{}",
&uuid::Uuid::new_v4().simple().to_string()[..10]
);
let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP issue_catchup: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id("issue-catchup").await.unwrap();
// Arrange: one finding whose issue exists (#7, matched by its
// marker), one without, one already linked, and a low one.
let old = finding("fp-old", Severity::High, 9);
let fresh = finding("fp-new", Severity::Critical, 1);
let mut linked = finding("fp-linked", Severity::High, 3);
linked.tracker_issue_url = Some("https://gitea.invalid/o/r/issues/2".into());
let low = finding("fp-low", Severity::Low, 3);
let seen: Seen = Arc::default();
let base = fake_gitea(vec![issue_of(7, &old)], seen.clone()).await;
let gitea =
GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap();
db.findings()
.insert_many([&old, &fresh, &linked, &low])
.await
.unwrap();
let index = ExistingIssues::new(&gitea.list_issues("kunde", "fw").await.unwrap());
let tracker = TrackerDispatch::Gitea(gitea);
let sink = sink(&db, &tracker, "target-1");
let url_of = |fp: &'static str| {
let db = db.clone();
async move {
db.findings()
.find_one(doc! { "fingerprint": fp })
.await
.unwrap()
.unwrap()
.tracker_issue_url
}
};
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));
assert_eq!(posts(&seen), 0);
assert_eq!(url_of("fp-old").await, None);
// On: the old finding is linked to #7 without a request, the new
// one gets an issue, the others are left alone.
let done = catch_up(&sink, &index, IssueCatchup::On).await.unwrap();
assert_eq!(done.linked.to_string(), "high=1");
assert_eq!(done.created.to_string(), "critical=1");
assert_eq!(done.failed, 0);
assert_eq!(posts(&seen), 1, "one create, for the new finding only");
assert_eq!(
url_of("fp-old").await.as_deref(),
Some("https://gitea.invalid/o/r/issues/7")
);
assert_eq!(
url_of("fp-new").await.as_deref(),
Some("https://gitea.invalid/o/r/issues/100")
);
assert_eq!(url_of("fp-low").await, None);
let old_id = db
.findings()
.find_one(doc! { "fingerprint": "fp-old" })
.await
.unwrap()
.unwrap()
.id
.unwrap();
let record: TrackerIssue = db
.tracker_issues()
.find_one(doc! { "finding_id": old_id.to_hex() })
.await
.unwrap()
.expect("the link is recorded for the status sync");
assert_eq!(record.external_id, "7");
// 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();
}
}
+527 -155
View File
@@ -1,6 +1,12 @@
use std::collections::HashMap;
use mongodb::bson::doc;
use crate::database::Database;
use crate::pipeline::repo_view::RepoView;
use crate::trackers::gitea::GiteaIssue;
use compliance_core::config::IssueCatchup;
use compliance_core::error::CoreError;
use compliance_core::models::*;
use super::orchestrator::{extract_base_url, PipelineOrchestrator};
@@ -24,41 +30,20 @@ impl PipelineOrchestrator {
alerts: &[CveAlert],
complete: bool,
) -> Result<(), AgentError> {
if !repo.managed {
return Ok(());
}
let (Some(tracker), Some(owner), Some(name)) = (
self.build_tracker(repo),
repo.tracker_owner.as_deref(),
repo.tracker_repo.as_deref(),
) else {
return Ok(());
};
let dashboard = std::env::var("DASHBOARD_PUBLIC_URL").unwrap_or_default();
let target = crate::pipeline::cve_issues::CveIssueTarget {
let sync = CveIssueSync {
config: &self.config,
net_guard: self.net_guard,
db: &self.db,
tracker: &tracker,
owner,
repo: name,
target_id: repo_id,
dashboard: &dashboard,
epss_percentile: crate::pipeline::cve_issues::epss_percentile(
std::env::var("CVE_ISSUE_EPSS_PERCENTILE").ok().as_deref(),
),
tenant_id: &self.tenant_id,
};
let counts =
crate::pipeline::cve_issues::sync_cve_issues(&target, alerts, complete).await?;
tracing::info!(
"[{repo_id}] CVE issues: {} opened, {} reopened, {} closed",
counts.created,
counts.reopened,
counts.closed
);
Ok(())
sync.sync(repo, repo_id, alerts, complete).await
}
/// Create tracker issues for new findings (severity >= Medium).
/// Checks for duplicates via fingerprint search before creating.
/// Skips a finding whose issue exists (by fingerprint, then title): on
/// Gitea matched against one listing of the repository's issues, on other
/// trackers by a search per finding. On Gitea the issue catch-up
/// ([`crate::pipeline::issue_catchup`]) follows, on the same listing.
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
pub(super) async fn create_tracker_issues(
&self,
@@ -89,144 +74,72 @@ impl PipelineOrchestrator {
}
};
// Only create issues for medium+ severity findings nobody has decided
// about (a group can take over its places' decision, #483).
let actionable: Vec<&Finding> = new_findings
.iter()
.filter(|f| {
matches!(
f.severity,
Severity::Medium | Severity::High | Severity::Critical
) && matches!(
f.status,
FindingStatus::Open | FindingStatus::Triaged | FindingStatus::NeedsReview
)
})
.collect();
let actionable: Vec<&Finding> = new_findings.iter().filter(|f| wants_issue(f)).collect();
// Only Gitea has the listing the catch-up matches against.
let catchup = match &tracker {
TrackerDispatch::Gitea(_) => self.config.issue_catchup,
_ => IssueCatchup::Off,
};
if actionable.is_empty() {
if actionable.is_empty() && catchup == IssueCatchup::Off {
tracing::info!("[{repo_id}] No medium+ findings, skipping issue creation");
return Ok(());
}
tracing::info!(
"[{repo_id}] Creating issues for {} findings via {}",
actionable.len(),
tracker.name()
);
// A managed repository (#439) gets its labels created once per run
// and attached by id. If that fails (no permission), the issues are
// still opened, with the label names in the body as before.
let managed_labels = match (&tracker, repo.managed) {
(TrackerDispatch::Gitea(gitea), true) => match gitea
.ensure_labels(
owner,
tracker_repo_name,
&trackers::gitea::pruefwerk_labels(),
)
.await
{
Ok(ids) => Some(ids),
Err(e) => {
tracing::warn!("[{repo_id}] Could not ensure the Prüfwerk labels: {e}");
None
}
},
// A Gitea lists its issues once and the findings are matched here, not
// searched one by one (a burst of searches took a small instance
// down). A listing that fails stops the sync for this repository,
// the catch-up included; the next scan tries again.
let mut existing = match &tracker {
TrackerDispatch::Gitea(gitea) => {
let issues = gitea.list_issues(owner, tracker_repo_name).await?;
Some(ExistingIssues::new(&issues))
}
_ => None,
};
let dashboard = std::env::var("DASHBOARD_PUBLIC_URL").unwrap_or_default();
let sink = IssueSink {
db: &self.db,
tracker: &tracker,
owner,
repo: tracker_repo_name,
repo_id,
managed: repo.managed,
dashboard: std::env::var("DASHBOARD_PUBLIC_URL").unwrap_or_default(),
labels: tokio::sync::OnceCell::new(),
};
if !actionable.is_empty() {
tracing::info!(
"[{repo_id}] Creating issues for {} findings via {}",
actionable.len(),
tracker.name()
);
}
let mut created = 0u32;
for finding in actionable {
let title = issue_title(finding);
// Check if an issue already exists by fingerprint first, then by title
let mut found_existing = false;
for search_term in issue_search_terms(finding, &title) {
match tracker
.find_existing_issue(owner, tracker_repo_name, search_term)
let found_existing = match &existing {
Some(index) => index.find(finding, &title).map(|known| known.url.clone()),
None => search_existing(&tracker, owner, tracker_repo_name, finding, &title)
.await
{
Ok(Some(existing)) => {
tracing::debug!(
"[{repo_id}] Issue already exists for '{}': {}",
search_term,
existing.external_url
);
found_existing = true;
break;
}
Ok(None) => {}
Err(e) => {
tracing::warn!("[{repo_id}] Failed to search for existing issue: {e}");
}
}
}
if found_existing {
.map(|issue| issue.external_url),
};
if let Some(url) = found_existing {
tracing::debug!(
"[{repo_id}] Issue already exists for '{}': {url}",
finding.fingerprint
);
continue;
}
let mut body = format_issue_body(finding);
if repo.managed {
if let Some(link) = finding_link(&dashboard, repo_id) {
body.push_str(&format!(
"\n[Open in Prüfwerk / In Prüfwerk öffnen]({link})"
));
}
}
let labels = vec![
format!("severity:{}", finding.severity),
format!("scanner:{}", finding.scanner),
"compliance-scanner".to_string(),
];
let result = match (&tracker, &managed_labels) {
(TrackerDispatch::Gitea(gitea), Some(ids)) => {
let label_ids = label_ids(
ids,
&trackers::gitea::issue_label_names(&finding.severity.to_string()),
);
gitea
.create_issue_with_label_ids(
owner,
tracker_repo_name,
&title,
&body,
&label_ids,
)
.await
}
_ => {
tracker
.create_issue(owner, tracker_repo_name, &title, &body, &labels)
.await
}
};
match result {
Ok(mut issue) => {
issue.finding_id = finding
.id
.as_ref()
.map(|id| id.to_hex())
.unwrap_or_default();
// Update the finding with the issue URL
if let Some(finding_id) = &finding.id {
let _ = self
.db
.findings()
.update_one(
doc! { "_id": finding_id },
doc! { "$set": { "tracker_issue_url": &issue.external_url } },
)
.await;
match sink.open(finding, &title).await {
Ok(issue) => {
// Later findings of this run with the same title find it.
if let Some(index) = existing.as_mut() {
index.insert(&finding.fingerprint, &title, &issue);
}
// Store the tracker issue record
if let Err(e) = self.db.tracker_issues().insert_one(&issue).await {
tracing::warn!("[{repo_id}] Failed to store tracker issue: {e}");
}
created += 1;
}
Err(e) => {
@@ -237,8 +150,104 @@ impl PipelineOrchestrator {
}
}
}
tracing::info!("[{repo_id}] Created {created} tracker issues");
if let (Some(index), IssueCatchup::DryRun | IssueCatchup::On) = (&existing, catchup) {
let summary = crate::pipeline::issue_catchup::catch_up(&sink, index, catchup).await?;
summary.log(&self.tenant_id, repo_id);
}
Ok(())
}
}
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.
pub(crate) struct CveIssueSync<'a> {
pub config: &'a compliance_core::AgentConfig,
pub net_guard: compliance_core::NetGuard,
pub db: &'a Database,
/// The tenant, for the log lines.
pub tenant_id: &'a str,
}
impl CveIssueSync<'_> {
/// Open, reopen and close the CVE issues of the managed repository
/// `repo` (target `repo_id`) to match `alerts` (see
/// [`crate::pipeline::cve_issues::sync_cve_issues`] for `complete`);
/// other targets, and one without a tracker, get none.
///
/// # Errors
///
/// A database error.
pub(crate) async fn sync(
&self,
repo: &RepoView,
repo_id: &str,
alerts: &[CveAlert],
complete: bool,
) -> Result<(), AgentError> {
if !repo.managed {
return Ok(());
}
let (Some(tracker), Some(owner), Some(name)) = (
build_tracker(self.config, self.net_guard, repo),
repo.tracker_owner.as_deref(),
repo.tracker_repo.as_deref(),
) else {
return Ok(());
};
let dashboard = std::env::var("DASHBOARD_PUBLIC_URL").unwrap_or_default();
let target = crate::pipeline::cve_issues::CveIssueTarget {
db: self.db,
tenant_id: self.tenant_id,
tracker: &tracker,
owner,
repo: name,
target_id: repo_id,
dashboard: &dashboard,
epss_percentile: crate::pipeline::cve_issues::epss_percentile(
std::env::var("CVE_ISSUE_EPSS_PERCENTILE").ok().as_deref(),
),
autoclose: self.config.issue_autoclose,
};
let counts =
crate::pipeline::cve_issues::sync_cve_issues(&target, alerts, complete).await?;
tracing::info!(
"[{repo_id}] CVE issues: {} opened, {} reopened, {} closed",
counts.created,
counts.reopened,
counts.closed
);
Ok(())
}
}
@@ -324,6 +333,272 @@ pub(crate) fn build_tracker(
}
}
/// Search the tracker for a finding's issue, one search per term of
/// [`issue_search_terms`] (trackers other than Gitea). A failed search is
/// logged and counts as not found.
async fn search_existing(
tracker: &TrackerDispatch,
owner: &str,
repo: &str,
finding: &Finding,
title: &str,
) -> Option<TrackerIssue> {
for search_term in issue_search_terms(finding, title) {
match tracker.find_existing_issue(owner, repo, search_term).await {
Ok(Some(existing)) => return Some(existing),
Ok(None) => {}
Err(e) => tracing::warn!("Failed to search for existing issue: {e}"),
}
}
None
}
/// The marker a finding issue's body carries its fingerprint in, right
/// before the fingerprint and its closing backtick.
const FINGERPRINT_MARKER: &str = "*Fingerprint:* `";
/// The fingerprint in an issue body written by [`format_issue_body`].
fn body_fingerprint(body: &str) -> Option<&str> {
let start = body.find(FINGERPRINT_MARKER)? + FINGERPRINT_MARKER.len();
let rest = &body[start..];
rest.find('`')
.map(|end| &rest[..end])
.filter(|fp| !fp.is_empty())
}
/// An issue of the repository: what a finding linked to it records.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct KnownIssue {
/// The issue number.
pub(super) external_id: String,
pub(super) url: String,
/// Closed on the tracker.
pub(super) closed: bool,
}
/// The issues a repository already has, by fingerprint and by title, built
/// from one listing so each finding is matched without a request.
#[derive(Debug, Default)]
pub(super) struct ExistingIssues {
/// Fingerprint (from the body's marker) to issue.
by_fingerprint: HashMap<String, KnownIssue>,
/// Exact title to issue.
by_title: HashMap<String, KnownIssue>,
}
impl ExistingIssues {
/// Index `issues`; where two share a fingerprint or title, the first
/// listed (Gitea lists the newest first) wins.
pub(super) fn new(issues: &[GiteaIssue]) -> Self {
let mut index = Self::default();
for issue in issues {
let known = KnownIssue {
external_id: issue.number.to_string(),
url: issue.html_url.clone(),
closed: issue.state == "closed",
};
if let Some(fp) = issue.body.as_deref().and_then(body_fingerprint) {
index
.by_fingerprint
.entry(fp.to_string())
.or_insert_with(|| known.clone());
}
index.by_title.entry(issue.title.clone()).or_insert(known);
}
index
}
/// `finding`'s issue: by fingerprint, then by `title` (not for a group,
/// see [`issue_search_terms`]).
pub(super) fn find(&self, finding: &Finding, title: &str) -> Option<&KnownIssue> {
self.by_fingerprint.get(&finding.fingerprint).or_else(|| {
finding
.occurrences
.is_empty()
.then(|| self.by_title.get(title))
.flatten()
})
}
/// Add an issue opened during this run.
fn insert(&mut self, fingerprint: &str, title: &str, issue: &TrackerIssue) {
let known = KnownIssue {
external_id: issue.external_id.clone(),
url: issue.external_url.clone(),
closed: false,
};
self.by_fingerprint
.entry(fingerprint.to_string())
.or_insert_with(|| known.clone());
self.by_title.entry(title.to_string()).or_insert(known);
}
}
/// The severities a finding gets an issue at.
pub(super) const ISSUE_SEVERITIES: [Severity; 3] =
[Severity::Medium, Severity::High, Severity::Critical];
/// The statuses of findings nobody has decided about (a group can take over
/// its places' decision, #483): only those get an issue.
pub(super) const ISSUE_STATUSES: [FindingStatus; 3] = [
FindingStatus::Open,
FindingStatus::Triaged,
FindingStatus::NeedsReview,
];
/// Whether `finding` should have an issue: medium or above and undecided.
pub(super) fn wants_issue(finding: &Finding) -> bool {
ISSUE_SEVERITIES.contains(&finding.severity) && ISSUE_STATUSES.contains(&finding.status)
}
/// Where a target's finding issues are opened, and what each one gets.
pub(super) struct IssueSink<'a> {
pub(super) db: &'a Database,
pub(super) tracker: &'a TrackerDispatch,
pub(super) owner: &'a str,
pub(super) repo: &'a str,
/// The target the findings belong to.
pub(super) repo_id: &'a str,
/// From a managed git source (#439): its issues get the Prüfwerk labels
/// and a link into Prüfwerk.
pub(super) managed: bool,
/// The dashboard's public origin (`DASHBOARD_PUBLIC_URL`).
pub(super) dashboard: String,
/// The ids of the Prüfwerk labels, ensured once, when the first issue
/// is opened (`None` inside: they could not be ensured). A `OnceCell`
/// runs its async initialiser at most once, like a cached property.
pub(super) labels: tokio::sync::OnceCell<Option<HashMap<String, i64>>>,
}
impl IssueSink<'_> {
/// The label ids of a managed Gitea repository, ensured on first use.
/// If that fails (no permission), issues are still opened, with the
/// label names in the body as before.
async fn label_ids(&self) -> Option<&HashMap<String, i64>> {
let TrackerDispatch::Gitea(gitea) = self.tracker else {
return None;
};
if !self.managed {
return None;
}
self.labels
.get_or_init(|| async {
match gitea
.ensure_labels(self.owner, self.repo, &trackers::gitea::pruefwerk_labels())
.await
{
Ok(ids) => Some(ids),
Err(e) => {
tracing::warn!(
"[{}] Could not ensure the Prüfwerk labels: {e}",
self.repo_id
);
None
}
}
})
.await
.as_ref()
}
/// Open the issue of `finding`, titled `title`, and record it.
///
/// # Errors
///
/// The tracker refused the issue; nothing is recorded then.
pub(super) async fn open(
&self,
finding: &Finding,
title: &str,
) -> Result<TrackerIssue, CoreError> {
let mut body = format_issue_body(finding);
if self.managed {
if let Some(link) = finding_link(&self.dashboard, self.repo_id) {
body.push_str(&format!(
"\n[Open in Prüfwerk / In Prüfwerk öffnen]({link})"
));
}
}
let mut issue = match (self.tracker, self.label_ids().await) {
(TrackerDispatch::Gitea(gitea), Some(ids)) => {
let label_ids = label_ids(
ids,
&trackers::gitea::issue_label_names(&finding.severity.to_string()),
);
gitea
.create_issue_with_label_ids(self.owner, self.repo, title, &body, &label_ids)
.await?
}
_ => {
let labels = [
format!("severity:{}", finding.severity),
format!("scanner:{}", finding.scanner),
"compliance-scanner".to_string(),
];
self.tracker
.create_issue(self.owner, self.repo, title, &body, &labels)
.await?
}
};
issue.finding_id = finding
.id
.as_ref()
.map(|id| id.to_hex())
.unwrap_or_default();
self.record(finding, &issue).await;
Ok(issue)
}
/// Link `finding` to its Gitea issue `known`, which exists already.
pub(super) async fn link(&self, finding: &Finding, title: &str, known: &KnownIssue) {
let mut issue = TrackerIssue::new(
finding
.id
.as_ref()
.map(|id| id.to_hex())
.unwrap_or_default(),
TrackerType::Gitea,
known.external_id.clone(),
known.url.clone(),
title.to_string(),
);
if known.closed {
issue.status = IssueStatus::Closed;
}
self.record(finding, &issue).await;
}
/// Put the issue's URL on the finding and store the issue record (one
/// per finding, replacing an older one), which the status sync
/// ([`crate::pipeline::issue_sync`]) finds the issue by. A failed write
/// is logged: the issue exists either way.
async fn record(&self, finding: &Finding, issue: &TrackerIssue) {
let Some(finding_id) = &finding.id else {
return;
};
if let Err(e) = self
.db
.findings()
.update_one(
doc! { "_id": finding_id },
doc! { "$set": { "tracker_issue_url": &issue.external_url } },
)
.await
{
tracing::warn!("[{}] Failed to link the issue: {e}", self.repo_id);
}
if let Err(e) = self
.db
.tracker_issues()
.replace_one(doc! { "finding_id": &issue.finding_id }, issue)
.upsert(true)
.await
{
tracing::warn!("[{}] Failed to store tracker issue: {e}", self.repo_id);
}
}
}
/// What to search the tracker for to find a finding's issue: its
/// fingerprint, then its title. A group (#464) only by fingerprint: it has
/// the title of its rule's single findings, whose issues are being closed as
@@ -339,7 +614,7 @@ fn issue_search_terms<'a>(finding: &'a Finding, title: &'a str) -> Vec<&'a str>
/// A finding's issue title: severity, scanner, the app variant when there
/// are several (the same flaw in the phone and the tablet app is two
/// issues, and the title is what an issue is found by), and its title.
fn issue_title(finding: &Finding) -> String {
pub(super) fn issue_title(finding: &Finding) -> String {
match &finding.variant {
Some(variant) => format!(
"[{}] {} ({variant}): {}",
@@ -403,7 +678,7 @@ pub(super) fn format_issue_body(finding: &Finding) -> String {
}
body.push_str(&format!(
"\n---\n*Fingerprint:* `{}`\n*Generated by compliance-scanner*",
"\n---\n{FINGERPRINT_MARKER}{}`\n*Generated by compliance-scanner*",
finding.fingerprint
));
@@ -442,7 +717,7 @@ fn finding_link(dashboard: &str, target_id: &str) -> Option<String> {
/// The ids of `names` among the ensured labels; a name without an id is left
/// out.
fn label_ids(ids: &std::collections::HashMap<String, i64>, names: &[String]) -> Vec<i64> {
fn label_ids(ids: &HashMap<String, i64>, names: &[String]) -> Vec<i64> {
names.iter().filter_map(|n| ids.get(n).copied()).collect()
}
@@ -531,6 +806,103 @@ mod tests {
);
}
fn listed(number: i64, title: &str, body: Option<&str>) -> GiteaIssue {
GiteaIssue {
number,
title: title.into(),
body: body.map(str::to_string),
html_url: format!("https://gitea.invalid/o/r/issues/{number}"),
state: "open".into(),
}
}
/// The URL of `finding`'s issue in `index`.
fn url<'a>(index: &'a ExistingIssues, finding: &Finding, title: &str) -> Option<&'a str> {
index.find(finding, title).map(|known| known.url.as_str())
}
fn high(fingerprint: &str, title: &str) -> Finding {
Finding::new(
"r".into(),
fingerprint.into(),
"semgrep".into(),
ScanType::Sast,
title.into(),
"desc".into(),
Severity::High,
)
}
#[test]
fn the_fingerprint_is_read_back_from_the_body() {
let body = format_issue_body(&high("fp-abc", "SQL injection"));
assert_eq!(body_fingerprint(&body), Some("fp-abc"));
assert_eq!(body_fingerprint("no marker"), None);
assert_eq!(body_fingerprint("*Fingerprint:* `"), None);
}
#[test]
fn an_issue_is_matched_by_its_fingerprint_marker() {
let finding = high("fp-1", "SQL injection");
let body = format_issue_body(&finding);
// Another title: the scanner renamed the rule since.
let index = ExistingIssues::new(&[
listed(3, "something else", Some("text")),
listed(7, "[high] semgrep: old name", Some(&body)),
]);
assert_eq!(
url(&index, &finding, &issue_title(&finding)),
Some("https://gitea.invalid/o/r/issues/7")
);
}
#[test]
fn an_issue_without_the_marker_is_matched_by_title_unless_grouped() {
let finding = high("fp-2", "SQL injection");
let title = issue_title(&finding);
let index = ExistingIssues::new(&[listed(4, &title, None)]);
assert_eq!(
url(&index, &finding, &title),
Some("https://gitea.invalid/o/r/issues/4")
);
// A group is found by its fingerprint only.
let mut group = finding.clone();
group.occurrences = (1..=2)
.map(|line| Occurrence {
file: "a.rs".into(),
line: Some(line),
variant: None,
decision: None,
})
.collect();
assert_eq!(url(&index, &group, &title), None);
}
#[test]
fn no_match_means_a_new_issue_and_it_is_found_afterwards() {
let first = high("fp-3", "Hardcoded key");
let title = issue_title(&first);
let mut index = ExistingIssues::new(&[listed(1, "[high] semgrep: other", Some("x"))]);
assert_eq!(url(&index, &first, &title), None);
// Opened during this run: the next finding with that title (or the
// same fingerprint) is not opened twice.
let opened = TrackerIssue::new(
String::new(),
TrackerType::Gitea,
"9".into(),
"https://gitea.invalid/o/r/issues/9".into(),
title.clone(),
);
index.insert(&first.fingerprint, &title, &opened);
let same_title = high("fp-4", "Hardcoded key");
assert_eq!(
url(&index, &same_title, &title),
Some("https://gitea.invalid/o/r/issues/9")
);
assert!(index.find(&first, "another title").is_some());
}
#[test]
fn a_variant_is_in_the_title_and_the_body() {
let mut finding = Finding::new(
+98 -14
View File
@@ -7,6 +7,9 @@
//! reopens its issue. The sync reads each finding's status when it runs, so a
//! change made in between is the one carried over.
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use mongodb::bson::{doc, oid::ObjectId};
use compliance_core::models::{
@@ -78,8 +81,9 @@ impl IssueSync {
return;
}
tokio::spawn(async move {
let mut risk_labels = RiskLabels::new();
for id in ids {
if let Err(e) = self.sync_one(id).await {
if let Err(e) = self.sync_one(id, &mut risk_labels).await {
tracing::warn!(finding = %id, error = %e, "issue status not synced");
}
}
@@ -87,7 +91,10 @@ impl IssueSync {
}
/// Carry the status of finding `id` over to its issue, if it has one.
async fn sync_one(&self, id: ObjectId) -> Result<(), String> {
/// `risk_labels` keeps the `risk:accepted` label id of each target this
/// run has resolved, so the labels are listed once per target, not once
/// per issue.
async fn sync_one(&self, id: ObjectId, risk_labels: &mut RiskLabels) -> Result<(), String> {
let Some(issue) = self
.db
.tracker_issues()
@@ -138,7 +145,14 @@ impl IssueSync {
accepted_risk: true,
} = action
{
label_accepted_risk(&tracker, owner, name, number).await;
label_accepted_risk(
&tracker,
owner,
name,
number,
risk_labels.entry(finding.repo_id.clone()),
)
.await;
}
let (state, status) = match action {
IssueAction::Close { .. } => ("closed", IssueStatus::Closed),
@@ -169,17 +183,34 @@ impl IssueSync {
}
}
/// The `risk:accepted` label id per target (`Finding::repo_id`), once
/// resolved; `None` for a target whose repository has no such label.
type RiskLabels = HashMap<String, Option<i64>>;
/// Put the `risk:accepted` label on a Gitea issue. Other trackers keep only
/// the comment; a label that cannot be set does not stop the close.
async fn label_accepted_risk(tracker: &TrackerDispatch, owner: &str, repo: &str, number: &str) {
/// the comment; a label that cannot be set does not stop the close. The
/// label id is resolved once per target and kept in `cached`.
async fn label_accepted_risk(
tracker: &TrackerDispatch,
owner: &str,
repo: &str,
number: &str,
cached: Entry<'_, String, Option<i64>>,
) {
let TrackerDispatch::Gitea(gitea) = tracker else {
return;
};
let labelled = async {
let ids = gitea
.ensure_labels(owner, repo, &pruefwerk_labels())
.await?;
let label: Vec<i64> = ids.get(LABEL_ACCEPTED_RISK).copied().into_iter().collect();
let label = match cached {
Entry::Occupied(known) => *known.get(),
Entry::Vacant(slot) => {
let ids = gitea
.ensure_labels(owner, repo, &pruefwerk_labels())
.await?;
*slot.insert(ids.get(LABEL_ACCEPTED_RISK).copied())
}
};
let label: Vec<i64> = label.into_iter().collect();
gitea.add_labels(owner, repo, number, &label).await
};
if let Err(e) = labelled.await {
@@ -204,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.",
@@ -261,7 +300,17 @@ mod tests {
type Calls = Arc<Mutex<Vec<String>>>;
async fn fake_gitea(calls: Calls) -> String {
async fn labels() -> Json<serde_json::Value> {
async fn labels(
State(calls): State<Calls>,
axum::extract::Query(page): axum::extract::Query<
std::collections::HashMap<String, String>,
>,
) -> Json<serde_json::Value> {
// One page of labels: a later page is empty, as Gitea ends a list.
if page.get("page").map(String::as_str) != Some("1") {
return Json(serde_json::json!([]));
}
calls.lock().unwrap().push("list labels".into());
// Every Prüfwerk label exists already; risk:accepted is id 42.
Json(serde_json::json!(pruefwerk_labels()
.iter()
@@ -395,7 +444,9 @@ mod tests {
};
// Act + assert: the scan closed it, so the issue closes with a comment.
sync.sync_one(finding_id).await.unwrap();
sync.sync_one(finding_id, &mut RiskLabels::new())
.await
.unwrap();
assert_eq!(issue_status().await, IssueStatus::Closed);
{
let calls = calls.lock().unwrap();
@@ -405,7 +456,9 @@ mod tests {
}
// Synced again with no change: nothing more is sent.
sync.sync_one(finding_id).await.unwrap();
sync.sync_one(finding_id, &mut RiskLabels::new())
.await
.unwrap();
assert_eq!(calls.lock().unwrap().len(), 2);
// It comes back: the issue reopens.
@@ -416,7 +469,9 @@ mod tests {
)
.await
.unwrap();
sync.sync_one(finding_id).await.unwrap();
sync.sync_one(finding_id, &mut RiskLabels::new())
.await
.unwrap();
assert_eq!(issue_status().await, IssueStatus::Open);
assert_eq!(calls.lock().unwrap().last().unwrap(), "state 12: \"open\"");
@@ -428,7 +483,9 @@ mod tests {
)
.await
.unwrap();
sync.sync_one(finding_id).await.unwrap();
sync.sync_one(finding_id, &mut RiskLabels::new())
.await
.unwrap();
{
let calls = calls.lock().unwrap();
let tail: Vec<&str> = calls.iter().rev().take(2).map(String::as_str).collect();
@@ -438,6 +495,33 @@ mod tests {
pool.drop_tenant("issue-sync").await.ok();
}
#[tokio::test]
async fn the_risk_label_is_resolved_once_per_target() {
let calls: Calls = Arc::default();
let base = fake_gitea(calls.clone()).await;
let tracker = TrackerDispatch::Gitea(
crate::trackers::gitea::GiteaTracker::new(
base,
secrecy::SecretString::from("t"),
NetGuard::allow_private(),
)
.unwrap(),
);
let mut cache = RiskLabels::new();
for number in ["5", "6"] {
label_accepted_risk(&tracker, "kunde", "fw", number, cache.entry("t1".into())).await;
}
let calls = calls.lock().unwrap();
assert_eq!(
*calls,
["list labels", "labels 5: [42]", "labels 6: [42]"],
"the labels are listed once"
);
assert_eq!(cache["t1"], Some(42));
}
fn by_scan(status: FindingStatus, kind: ScanChangeKind) -> StatusChange {
StatusChange::by_scan(status, kind, "run-1")
}
+11 -2
View File
@@ -30,6 +30,8 @@ fn language_of(extension: &str) -> Option<&'static str> {
// Objective-C; `.m` is also MATLAB's extension, which only means
// mobsfscan looks at a tree it finds nothing in.
"m" | "mm" => "objc",
// Yocto / OpenEmbedded recipes, appends and classes.
"bb" | "bbappend" | "bbclass" => "bitbake",
_ => return None,
})
}
@@ -64,6 +66,10 @@ mod tests {
("tools/flash.py", "print('flash')"),
("Middlewares/Third_Party/lib/x.cpp", "int x;"),
("README.md", "# readme"),
(
"meta-pump/recipes-app/pump/pump_1.0.bb",
"LICENSE = \"CLOSED\"",
),
] {
let file = root.join(path);
std::fs::create_dir_all(file.parent().expect("parent")).expect("mkdir");
@@ -72,8 +78,11 @@ mod tests {
let vendor = vec!["Middlewares/Third_Party".to_string()];
assert_eq!(source_languages(root, &vendor), ["c", "python"]);
assert_eq!(source_languages(root, &[]), ["c", "cpp", "python"]);
assert_eq!(source_languages(root, &vendor), ["bitbake", "c", "python"]);
assert_eq!(
source_languages(root, &[]),
["bitbake", "c", "cpp", "python"]
);
let _ = std::fs::remove_dir_all(&dir);
}
}
@@ -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!(
+16 -1
View File
@@ -3,6 +3,7 @@ pub mod binary_depth;
pub mod build_lifecycle;
pub mod change;
pub mod clamav;
pub mod clone_limit;
pub mod code_review;
pub mod cppcheck;
pub(crate) mod csaf_feed;
@@ -10,38 +11,52 @@ pub(crate) mod csaf_match;
pub mod cve;
pub(crate) mod cve_enrichment;
pub(crate) mod cve_issues;
pub mod cve_notify;
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;
pub mod git_retry;
pub mod git_submodules;
pub mod gitleaks;
mod graph_build;
pub mod grouping;
pub mod ios_config;
mod issue_creation;
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;
pub(crate) mod nvd_monitor;
pub mod orchestrator;
pub mod patterns;
pub mod plan;
pub mod plc;
mod pr_review;
mod public_http;
pub mod recipe_lint;
pub mod repo_view;
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;
+138 -54
View File
@@ -40,7 +40,7 @@ pub(crate) const NVD_CVES_URL: &str = "https://services.nvd.nist.gov/rest/json/c
/// Waits before each retry of a failed NVD request. NVD asks for about six
/// seconds between requests, and answers 403/429 when a key's budget is
/// spent; three retries ride out a short limit without stalling a scan.
const RETRY_DELAYS: [Duration; 3] = [
pub(crate) const RETRY_DELAYS: [Duration; 3] = [
Duration::from_secs(6),
Duration::from_secs(12),
Duration::from_secs(24),
@@ -80,15 +80,25 @@ pub(crate) async fn product_cves(
product: NvdProduct,
version: &str,
) -> Result<Vec<NvdCve>, String> {
let body = product_body(
http,
NVD_CVES_URL,
api_key,
product.match_string,
&RETRY_DELAYS,
)
.await?;
Ok(parse(&body, product.marker, version))
match_cves(http, api_key, product.match_string, product.marker, version).await
}
/// [`product_cves`] for a product named at run time (a Yocto recipe's
/// CVE_PRODUCT): the CVEs NVD lists for `match_string` whose vulnerable CPE
/// contains `marker` and whose range covers `version`.
///
/// # Errors
///
/// Why NVD could not be asked, as for [`product_cves`].
pub(crate) async fn match_cves(
http: &PublicHttp,
api_key: Option<&str>,
match_string: &str,
marker: &str,
version: &str,
) -> Result<Vec<NvdCve>, String> {
let body = product_body(http, NVD_CVES_URL, api_key, match_string, &RETRY_DELAYS).await?;
Ok(parse(&body, marker, version))
}
/// NVD's answer for `match_string`: cached, or fetched from `base_url` with
@@ -103,36 +113,48 @@ async fn product_body(
if let Some(body) = cached(match_string) {
return Ok(body);
}
let query = [("virtualMatchString", match_string.to_string())];
let body = Arc::new(fetch(http, base_url, api_key, &query, delays).await?);
if let Ok(mut c) = cache().lock() {
c.insert(
match_string.to_string(),
(Instant::now(), Arc::clone(&body)),
);
}
Ok(body)
}
/// NVD's answer to `query` at `base_url`, asked again after each of `delays`
/// while NVD's answer is transient ([`is_transient`]) or the request fails.
///
/// # Errors
///
/// Why NVD could not be asked (net guard, network, status, body) after the
/// retries; a status NVD gives for good (404 for a query it refuses) and a
/// URL the net guard refuses are not retried.
pub(crate) async fn fetch(
http: &PublicHttp,
base_url: &str,
api_key: Option<&str>,
query: &[(&str, String)],
delays: &[Duration],
) -> Result<serde_json::Value, String> {
let mut last_error = String::new();
for attempt in 0..=delays.len() {
if let Some(wait) = attempt.checked_sub(1).and_then(|i| delays.get(i)) {
tracing::info!(
match_string,
attempt,
"retrying NVD after {wait:?}: {last_error}"
);
tracing::info!(attempt, "retrying NVD after {wait:?}: {last_error}");
tokio::time::sleep(*wait).await;
}
// A URL the net guard refuses is refused for good: not retried.
let mut req = http
.get(base_url)?
.query(&[("virtualMatchString", match_string)])
.query(query)
.timeout(NVD_REQUEST_TIMEOUT);
if let Some(key) = api_key {
req = req.header("apiKey", key);
}
match req.send().await {
Ok(resp) if resp.status().is_success() => {
let body: serde_json::Value = read_json(resp).await?;
let body = Arc::new(body);
if let Ok(mut c) = cache().lock() {
c.insert(
match_string.to_string(),
(Instant::now(), Arc::clone(&body)),
);
}
return Ok(body);
}
Ok(resp) if resp.status().is_success() => return read_json(resp).await,
Ok(resp) if is_transient(resp.status()) => {
last_error = format!("NVD returned {}", resp.status());
}
@@ -143,6 +165,22 @@ async fn product_body(
Err(last_error)
}
/// Whether a fresh answer for `match_string` is cached, so asking costs no
/// request against NVD's rate limit.
pub(crate) fn is_cached(match_string: &str) -> bool {
cached(match_string).is_some()
}
/// The pause between two requests that keeps within NVD's rate limit: 50
/// requests per 30 seconds with an API key, 5 without.
pub(crate) fn request_interval(with_key: bool) -> Duration {
if with_key {
Duration::from_millis(600)
} else {
Duration::from_secs(6)
}
}
/// A fresh cached answer for `match_string`, if there is one.
fn cached(match_string: &str) -> Option<Arc<serde_json::Value>> {
let cache = cache().lock().ok()?;
@@ -164,36 +202,59 @@ pub fn parse(body: &serde_json::Value, marker: &str, version: &str) -> Vec<NvdCv
};
vulns
.iter()
.filter_map(|v| {
let cve = &v["cve"];
let id = cve["id"].as_str()?;
let covered = cve["configurations"]
.as_array()
.into_iter()
.flatten()
.flat_map(|c| c["nodes"].as_array().into_iter().flatten())
.flat_map(|n| n["cpeMatch"].as_array().into_iter().flatten())
.any(|cm| {
cm["vulnerable"].as_bool() == Some(true)
&& cm["criteria"].as_str().is_some_and(|c| c.contains(marker))
&& version_matches(version, &cpe_range(cm))
});
covered.then(|| NvdCve {
id: id.to_string(),
summary: cve["descriptions"]
.as_array()
.and_then(|d| d.iter().find(|x| x["lang"].as_str() == Some("en")))
.and_then(|x| x["value"].as_str())
.map(String::from),
cvss: cve["metrics"]["cvssMetricV31"]
.as_array()
.and_then(|m| m.first())
.and_then(|m| m["cvssData"]["baseScore"].as_f64()),
})
})
.filter_map(|v| parse_cve(v, marker, version))
.collect()
}
/// One entry of an NVD response's `vulnerabilities`, when a vulnerable CPE
/// of it contains `marker` and its range covers `version`.
pub(crate) fn parse_cve(v: &serde_json::Value, marker: &str, version: &str) -> Option<NvdCve> {
let cve = &v["cve"];
let id = cve["id"].as_str()?;
let covered = cpe_matches(v).any(|cm| {
cm["vulnerable"].as_bool() == Some(true)
&& cm["criteria"].as_str().is_some_and(|c| c.contains(marker))
&& version_matches(version, &cpe_range(cm))
});
covered.then(|| NvdCve {
id: id.to_string(),
summary: cve["descriptions"]
.as_array()
.and_then(|d| d.iter().find(|x| x["lang"].as_str() == Some("en")))
.and_then(|x| x["value"].as_str())
.map(String::from),
cvss: cve["metrics"]["cvssMetricV31"]
.as_array()
.and_then(|m| m.first())
.and_then(|m| m["cvssData"]["baseScore"].as_f64()),
})
}
/// Every `cpeMatch` object of one entry of an NVD response's
/// `vulnerabilities`.
pub(crate) fn cpe_matches(v: &serde_json::Value) -> impl Iterator<Item = &serde_json::Value> {
v["cve"]["configurations"]
.as_array()
.into_iter()
.flatten()
.flat_map(|c| c["nodes"].as_array().into_iter().flatten())
.flat_map(|n| n["cpeMatch"].as_array().into_iter().flatten())
}
/// Whether the CPE `criteria` is one NVD returns for the match string
/// `match_string` (`virtualMatchString`): each component the match string
/// names (part, vendor, product, ...) is `*` there or equal in `criteria`.
/// `cpe:2.3:a:codesys` matches every CODESYS application CPE,
/// `cpe:2.3:*:amazon:freertos` FreeRTOS as application and operating system.
pub(crate) fn matches_virtual(match_string: &str, criteria: &str) -> bool {
let mut wanted = match_string.split(':');
let mut have = criteria.split(':');
wanted.all(|w| {
have.next()
.is_some_and(|h| w == "*" || w.eq_ignore_ascii_case(h))
})
}
/// Version constraints from an NVD `cpeMatch` node.
#[derive(Default)]
struct CpeRange {
@@ -249,6 +310,12 @@ fn version_matches(v: &str, r: &CpeRange) -> bool {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_api_key_allows_ten_times_the_requests() {
assert_eq!(request_interval(false), Duration::from_secs(6));
assert_eq!(request_interval(true) * 10, request_interval(false));
}
use std::cmp::Ordering::{Equal, Greater, Less};
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -359,6 +426,23 @@ mod tests {
assert_eq!(hits.load(Ordering::SeqCst), 0);
}
#[test]
fn a_match_string_matches_cpes_as_nvd_lists_them() {
let criteria = "cpe:2.3:o:amazon:freertos:*:*:*:*:*:*:*:*";
assert!(matches_virtual("cpe:2.3:*:amazon:freertos", criteria));
assert!(matches_virtual("cpe:2.3:*:*:freertos", criteria));
assert!(!matches_virtual("cpe:2.3:a:amazon:freertos", criteria));
assert!(!matches_virtual(
"cpe:2.3:*:amazon:freertos-plus-tcp",
criteria
));
assert!(matches_virtual(
"cpe:2.3:a:codesys",
"cpe:2.3:a:codesys:control_for_linux_sl:*:*:*:*:*:*:*:*"
));
assert!(!matches_virtual("cpe:2.3:a:codesys", "cpe:2.3:a"));
}
#[test]
fn fatfs_revisions_match_nvds_ranges() {
// The shape of CVE-2026-6682: FatFs R0.16 and earlier.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+23 -2
View File
@@ -124,8 +124,8 @@ fn resolve_artifact(target: &OnboardedTarget, required: Option<ArtifactKind>) ->
/// The pipeline phase reported while a given scan runs.
fn phase_for(scan: ScanType) -> ScanPhase {
match scan {
ScanType::Sast => ScanPhase::Sast,
ScanType::Sbom => ScanPhase::SbomGeneration,
ScanType::Sast | ScanType::RecipeLint => ScanPhase::Sast,
ScanType::Sbom | ScanType::RecipeInventory => ScanPhase::SbomGeneration,
ScanType::Cve => ScanPhase::CveScanning,
ScanType::Gdpr | ScanType::OAuth => ScanPhase::PatternScanning,
ScanType::SecretDetection => ScanPhase::SecretDetection,
@@ -175,6 +175,27 @@ mod tests {
assert_eq!(dast.artifact_id, url_id);
}
#[test]
fn a_yocto_layer_tree_runs_its_source_scans_recipe_inventory_and_lint() {
let t = target(
TargetType::EmbeddedLinuxYocto,
vec![Artifact::source_archive("meta-pump.zip")],
);
let plan = build_scan_plan(&t);
assert!(plan.has(ScanType::Sast) && plan.has(ScanType::Sbom));
assert!(plan.has(ScanType::RecipeLint));
assert_eq!(
step_for(&plan, ScanType::RecipeLint).map(|s| &s.phase),
Some(&ScanPhase::Sast)
);
assert!(plan.has(ScanType::RecipeInventory));
assert!(!plan.has(ScanType::Dast));
assert!(
plan.unavailable.is_empty(),
"nothing is recorded as not run: no image is attached"
);
}
#[test]
fn webapp_without_url_omits_dast() {
let t = target(TargetType::WebApp, vec![Artifact::git_repo("u", "main")]);
+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(
+11 -2
View File
@@ -61,18 +61,27 @@ impl PublicHttp {
}
}
/// How the error of a body over [`MAX_BODY_BYTES`] begins.
const TOO_LARGE: &str = "response larger than";
/// Whether `error` (from [`read_body`] or [`read_json`]) says the body
/// exceeded [`MAX_BODY_BYTES`], so a smaller page could still be read.
pub(crate) fn is_too_large(error: &str) -> bool {
error.starts_with(TOO_LARGE)
}
/// The body of `resp`, refused once it exceeds [`MAX_BODY_BYTES`].
pub(crate) async fn read_body(mut resp: reqwest::Response) -> Result<Vec<u8>, String> {
if resp
.content_length()
.is_some_and(|n| n > MAX_BODY_BYTES as u64)
{
return Err(format!("response larger than {MAX_BODY_BYTES} bytes"));
return Err(format!("{TOO_LARGE} {MAX_BODY_BYTES} bytes"));
}
let mut body = Vec::new();
while let Some(chunk) = resp.chunk().await.map_err(|e| e.to_string())? {
if body.len() + chunk.len() > MAX_BODY_BYTES {
return Err(format!("response larger than {MAX_BODY_BYTES} bytes"));
return Err(format!("{TOO_LARGE} {MAX_BODY_BYTES} bytes"));
}
body.extend_from_slice(&chunk);
}
@@ -0,0 +1,544 @@
//! Recipe lint of a Yocto / OpenEmbedded layer tree (tier 1, no build).
//!
//! Two scanners read the layers' recipes and configuration:
//!
//! - **oelint-adv** (BSD-2-Clause, [`oelint`]) with only its security rules:
//! debug and empty-password image features, missing checksums, `AUTOREV`,
//! `tag=` fetches, network access in tasks and skipped QA checks;
//! - **our own rules** (`yocto-config`, [`rules`]): password hashes in
//! `EXTRA_USERS_PARAMS`, `http://` fetches, a shipped `sshd_config` that
//! allows root or password logins, certificates shipped with a recipe, and a
//! distro without `security_flags.inc`.
//!
//! Upstream layers (Poky, OpenEmbedded, the BSP vendors' layers) are not the
//! customer's to fix, so neither scanner reads them; the run names them, as it
//! names vendor code.
pub mod oelint;
pub mod rules;
use std::collections::BTreeMap;
use std::path::Path;
use compliance_core::models::{Finding, ScanType, Severity};
use crate::pipeline::dedup;
use crate::pipeline::source_text::{read_lines, read_text};
/// The stage id a failed oelint-adv run is recorded under.
pub const STAGE: &str = "recipe_lint";
/// The stage id the upstream layers left out are recorded under.
pub const UPSTREAM_STAGE: &str = "recipe_lint_upstream";
/// The stage id the findings suppressed by `# nooelint` comments are
/// recorded under.
pub const SUPPRESSED_STAGE: &str = "recipe_lint_suppressed";
/// Directories never walked: version control and a build directory's output.
const SKIPPED_DIRS: &[&str] = &[".git", "build", "downloads", "sstate-cache"];
/// `BBFILE_COLLECTIONS` of upstream layers: OpenEmbedded-Core and Poky, the
/// meta-openembedded layers, and widely used security, virtualisation and
/// BSP layers. Their findings are upstream's, like vendor SDK code.
const UPSTREAM_COLLECTIONS: &[&str] = &[
"core",
"yocto",
"yoctobsp",
"selftest",
"skeleton",
"openembedded-layer",
"meta-python",
"networking-layer",
"multimedia-layer",
"filesystems-layer",
"webserver",
"gnome-layer",
"xfce-layer",
"perl-layer",
"meta-initramfs",
"security",
"virtualization-layer",
"arm",
"arm-bsp",
"arm-toolchain",
"intel",
"freescale-layer",
"raspberrypi",
"clang-layer",
"qt6-layer",
];
/// The Yocto releases oelint-adv 9.11 knows, oldest first (its `--release`
/// choices, without `latest`).
const RELEASES: &[&str] = &[
"inky",
"clyde",
"blinky",
"pinky",
"purple",
"green",
"laverne",
"bernard",
"edison",
"denzil",
"danny",
"dylan",
"dora",
"daisy",
"dizzy",
"fido",
"jethro",
"krogoth",
"morty",
"pyro",
"rocko",
"sumo",
"thud",
"warrior",
"zeus",
"dunfell",
"gatesgarth",
"hardknott",
"honister",
"kirkstone",
"langdale",
"mickledore",
"nanbield",
"scarthgap",
"styhead",
"walnascar",
"whinlatter",
"wrynose",
"blacksail",
];
/// The CRA Annex I requirement a rule's finding is about. The control it is
/// evidence for comes from the control map, by rule id.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Cra {
/// Part I (2)(b): made available with a secure by default configuration.
SecureByDefault,
/// Part I (2)(j): designed to limit attack surfaces.
AttackSurface,
/// Part I (2)(f): the integrity of the software, here of what the image
/// is built from.
Integrity,
/// Informational, not a requirement on its own.
None,
}
impl Cra {
/// The requirement in words, for the finding's description.
fn text(self) -> Option<&'static str> {
match self {
Self::SecureByDefault => Some(
"CRA Annex I Part I (2)(b): products are made available with a secure by \
default configuration.",
),
Self::AttackSurface => {
Some("CRA Annex I Part I (2)(j): products are designed to limit attack surfaces.")
}
Self::Integrity => Some(
"CRA Annex I Part I (2)(f): the integrity of the software is protected; an \
image built from unverified or moving sources cannot be traced to them.",
),
Self::None => None,
}
}
}
/// What a rule reports: its scanner and id, title, severity, CWE, the CRA
/// requirement and the fix.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuleInfo {
/// The scanner name findings carry.
pub scanner: &'static str,
/// The rule id findings carry.
pub id: &'static str,
/// The finding's title.
pub title: &'static str,
/// The finding's severity.
pub severity: Severity,
/// The weakness, as `CWE-<n>`.
pub cwe: Option<&'static str>,
/// The CRA requirement.
pub cra: Cra,
/// How to fix it.
pub remediation: &'static str,
}
/// A rule matching at a place, before it becomes a [`Finding`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Hit {
pub rule: &'static RuleInfo,
/// The file, relative to the tree.
pub path: String,
/// The line, 1-based.
pub line: u32,
/// What the rule saw there, for the description; may be empty.
pub detail: String,
/// The snippet to show instead of the line (with a secret hidden).
pub snippet: Option<String>,
}
impl Hit {
fn new(rule: &'static RuleInfo, path: &str, line: u32, detail: String) -> Self {
Self {
rule,
path: path.to_string(),
line,
detail,
snippet: None,
}
}
/// The finding of `repo_id` for this hit in the tree under `root`.
fn into_finding(self, root: &Path, repo_id: &str) -> Finding {
let rule = self.rule;
let line = self.line.to_string();
let fingerprint =
dedup::compute_fingerprint(&[repo_id, rule.scanner, rule.id, &self.path, &line]);
let description = [Some(self.detail.as_str()), rule.cra.text()]
.into_iter()
.flatten()
.filter(|part| !part.is_empty())
.collect::<Vec<_>>()
.join("\n\n");
let mut finding = Finding::new(
repo_id.to_string(),
fingerprint,
rule.scanner.to_string(),
ScanType::RecipeLint,
rule.title.to_string(),
description,
rule.severity.clone(),
);
finding.rule_id = Some(rule.id.to_string());
finding.cwe = rule.cwe.map(str::to_string);
finding.remediation = Some(rule.remediation.to_string());
finding.code_snippet = self
.snippet
.or_else(|| read_lines(root, &self.path, self.line, self.line));
finding.line_number = Some(self.line);
finding.file_path = Some(self.path);
finding
}
}
/// One layer of the tree and the files the recipe lint reads in it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Layer {
/// The layer's directory relative to the tree, `.` for the root.
pub dir: String,
/// The oldest release its `LAYERSERIES_COMPAT` names: the recipes are
/// read with that release's syntax and rules.
pub release: Option<&'static str>,
/// An upstream layer, which is not linted.
pub upstream: bool,
/// The collections its `layer.conf` declares (`BBFILE_COLLECTIONS`).
pub collections: Vec<String>,
/// Every release its `LAYERSERIES_COMPAT_*` names, as written.
pub compat: Vec<String>,
/// Its files relative to the tree; a nested layer's files are its own.
pub files: Vec<String>,
}
impl Layer {
/// `file` (relative to the tree) relative to the layer.
fn inner<'a>(&self, file: &'a str) -> &'a str {
if self.dir == "." {
file
} else {
file.get(self.dir.len() + 1..).unwrap_or(file)
}
}
}
/// The recipe lint of one tree.
#[derive(Debug, Clone)]
pub struct RecipeLint {
layers: Vec<Layer>,
}
impl RecipeLint {
/// The recipe lint for a tree whose source `languages` include BitBake,
/// skipping the `excluded` vendor directories; `None` otherwise.
///
/// # Arguments
///
/// * `root` - the tree
/// * `languages` - the source languages found outside vendor code
/// * `excluded` - vendor directories relative to the tree
pub fn for_tree(root: &Path, languages: &[String], excluded: &[String]) -> Option<Self> {
languages.iter().any(|l| l == "bitbake").then(|| Self {
layers: layers(root, excluded),
})
}
/// The upstream layers left out, relative to the tree.
pub fn upstream_layers(&self) -> Vec<&str> {
self.layers
.iter()
.filter(|l| l.upstream)
.map(|l| l.dir.as_str())
.collect()
}
/// What our own rules ([`rules`]) find in the customer's layers under
/// `root`. They read files only, so they always complete.
pub fn config_findings(&self, root: &Path, repo_id: &str) -> Vec<Finding> {
self.config_hits(root)
.into_iter()
.map(|hit| hit.into_finding(root, repo_id))
.collect()
}
/// The customer's layers: those the lint reads.
fn own_layers(&self) -> impl Iterator<Item = &Layer> {
self.layers.iter().filter(|l| !l.upstream)
}
}
/// Whether the recipe lint reads `inner` (a path relative to its layer):
/// recipes, appends, includes, classes, the layer's configuration, and what
/// recipes ship in their `files/` (sshd configurations, certificates).
fn is_read(inner: &str) -> bool {
let name = inner.rsplit('/').next().unwrap_or(inner);
let ext = name.rsplit_once('.').map_or("", |(_, ext)| ext);
match ext {
"bb" | "bbappend" | "bbclass" | "inc" => true,
"conf" => inner.starts_with("conf/"),
"sample" => name == "local.conf.sample",
_ => rules::is_shipped_file(inner, name),
}
}
/// The layers of the tree under `root`, outside the `excluded` directories:
/// each directory holding a `conf/layer.conf`. A tree without one (loose
/// recipes) is read as a single layer.
pub(crate) fn layers(root: &Path, excluded: &[String]) -> Vec<Layer> {
let files: Vec<String> = walkdir::WalkDir::new(root)
.min_depth(1)
.into_iter()
.filter_entry(|e| {
let rel = rel_path(root, e.path());
!(e.file_type().is_dir()
&& (SKIPPED_DIRS.contains(&e.file_name().to_string_lossy().as_ref())
|| excluded.contains(&rel)))
})
.filter_map(Result::ok)
.filter(|e| e.file_type().is_file())
.map(|e| rel_path(root, e.path()))
.collect();
let mut dirs: Vec<String> = files
.iter()
.filter_map(|f| match f.strip_suffix("conf/layer.conf") {
Some("") => Some(".".to_string()),
Some(dir) => dir.strip_suffix('/').map(str::to_string),
None => None,
})
.collect();
if dirs.is_empty() {
dirs.push(".".to_string());
}
// Deepest first, so a file belongs to the innermost layer holding it.
dirs.sort_by_key(|d| std::cmp::Reverse(d.len()));
let mut by_dir: BTreeMap<String, Vec<String>> = BTreeMap::new();
for file in files {
let owner = dirs
.iter()
.find(|d| d.as_str() == "." || file.starts_with(&format!("{d}/")));
if let Some(owner) = owner {
by_dir.entry(owner.clone()).or_default().push(file);
}
}
dirs.sort();
dirs.into_iter()
.map(|dir| {
let conf = if dir == "." {
"conf/layer.conf".to_string()
} else {
format!("{dir}/conf/layer.conf")
};
let (collections, compat) = read_text(root, &conf)
.map(|text| layer_conf(&text))
.unwrap_or_default();
let mut layer = Layer {
upstream: collections
.iter()
.any(|c| UPSTREAM_COLLECTIONS.contains(&c.as_str())),
release: oldest_release(&compat),
files: Vec::new(),
dir,
collections,
compat,
};
let mut files = by_dir.remove(&layer.dir).unwrap_or_default();
files.retain(|f| is_read(layer.inner(f)));
files.sort();
layer.files = files;
layer
})
.collect()
}
/// `path` relative to `root`, `/`-separated.
pub(crate) fn rel_path(root: &Path, path: &Path) -> String {
path.strip_prefix(root)
.unwrap_or(path)
.to_string_lossy()
.replace('\\', "/")
}
/// The collections a `layer.conf` declares and the releases it is compatible
/// with (`BBFILE_COLLECTIONS`, `LAYERSERIES_COMPAT_*`).
fn layer_conf(text: &str) -> (Vec<String>, Vec<String>) {
let mut collections = Vec::new();
let mut compat = Vec::new();
for assignment in rules::assignments(text) {
let words = assignment
.value
.split_whitespace()
.map(str::to_string)
.collect::<Vec<_>>();
if assignment.var == "BBFILE_COLLECTIONS" {
collections.extend(words);
} else if assignment.var.starts_with("LAYERSERIES_COMPAT_") {
compat.extend(words);
}
}
(collections, compat)
}
/// The oldest of `releases` oelint-adv knows.
fn oldest_release(releases: &[String]) -> Option<&'static str> {
RELEASES
.iter()
.find(|known| releases.iter().any(|r| r == *known))
.copied()
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
pub(crate) mod tests {
use super::*;
use std::path::PathBuf;
/// A scratch tree holding `files`, removed on drop.
pub(crate) struct Tree(pub PathBuf);
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
pub(crate) fn tree(files: &[(&str, &str)]) -> Tree {
let dir = std::env::temp_dir().join(format!("cs-recipe-lint-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).expect("mkdir");
for (path, content) in files {
let full = dir.join(path);
std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir");
std::fs::write(full, content).expect("write");
}
Tree(dir)
}
const POKY_META: &str =
"BBFILE_COLLECTIONS += \"core\"\nLAYERSERIES_COMPAT_core = \"scarthgap\"\n";
const OWN: &str =
"BBFILE_COLLECTIONS += \"pump\"\nLAYERSERIES_COMPAT_pump = \"scarthgap kirkstone\"\n";
#[test]
fn layers_are_found_with_their_release_and_upstream_ones_marked() {
let t = tree(&[
("poky/meta/conf/layer.conf", POKY_META),
("poky/meta/recipes-core/busybox/busybox_1.36.bb", ""),
("meta-pump/conf/layer.conf", OWN),
("meta-pump/conf/distro/pump.conf", ""),
("meta-pump/recipes-app/pump/pump_1.0.bb", ""),
("meta-pump/recipes-app/pump/files/pump.c", ""),
("meta-pump/recipes-app/pump/files/server.pem", ""),
("meta-pump/README.md", ""),
("build/conf/local.conf", ""),
]);
let lint = RecipeLint::for_tree(&t.0, &["bitbake".to_string()], &[]).expect("bitbake");
assert_eq!(lint.upstream_layers(), ["poky/meta"]);
let own: Vec<&Layer> = lint.own_layers().collect();
assert_eq!(own.len(), 1);
assert_eq!(own[0].dir, "meta-pump");
// The oldest compatible release.
assert_eq!(own[0].release, Some("kirkstone"));
assert_eq!(
own[0].files,
[
"meta-pump/conf/distro/pump.conf",
"meta-pump/conf/layer.conf",
"meta-pump/recipes-app/pump/files/server.pem",
"meta-pump/recipes-app/pump/pump_1.0.bb",
]
);
}
#[test]
fn loose_recipes_are_one_layer_and_other_trees_are_not_linted() {
let t = tree(&[("recipes-app/pump/pump_1.0.bb", "")]);
let lint = RecipeLint::for_tree(&t.0, &["bitbake".to_string()], &[]).expect("bitbake");
let own: Vec<&Layer> = lint.own_layers().collect();
assert_eq!(own[0].dir, ".");
assert_eq!(own[0].release, None);
assert!(RecipeLint::for_tree(&t.0, &["c".to_string()], &[]).is_none());
}
#[test]
fn vendor_directories_are_not_read() {
let t = tree(&[
("conf/layer.conf", OWN),
("vendor/recipes-x/x/x_1.0.bb", ""),
("recipes-app/pump/pump_1.0.bb", ""),
]);
let lint = RecipeLint::for_tree(&t.0, &["bitbake".to_string()], &["vendor".to_string()])
.expect("bitbake");
assert_eq!(
lint.layers[0].files,
["conf/layer.conf", "recipes-app/pump/pump_1.0.bb"]
);
}
#[test]
fn every_rule_with_a_cra_requirement_is_bound_in_the_control_map() {
let map = control_map::ControlMap::cra().expect("map");
let all = oelint::RULES.iter().chain(rules::RULES.iter().copied());
for rule in all {
let bound = !map
.controls_for_finding(rule.scanner, None, Some(rule.id))
.is_empty();
assert_eq!(bound, rule.cra != Cra::None, "{}", rule.id);
}
}
#[test]
fn a_hit_becomes_a_recipe_lint_finding_with_its_cra_requirement() {
let t = tree(&[("recipes-app/x/x.bb", "SRC_URI = \"http://x/y.tgz\"\n")]);
let rule = &rules::RULES[1];
let finding = Hit::new(rule, "recipes-app/x/x.bb", 1, "Fetched without TLS".into())
.into_finding(&t.0, "t");
assert_eq!(finding.scanner, "yocto-config");
assert_eq!(finding.scan_type, ScanType::RecipeLint);
assert_eq!(finding.rule_id.as_deref(), Some("yocto-src-uri-http"));
assert!(finding
.description
.starts_with("Fetched without TLS\n\nCRA Annex I"));
assert_eq!(
finding.code_snippet.as_deref(),
Some("SRC_URI = \"http://x/y.tgz\"")
);
}
#[test]
fn unknown_releases_are_ignored() {
assert_eq!(oldest_release(&["future".to_string()]), None);
assert_eq!(
oldest_release(&["wrynose".to_string(), "dunfell".to_string()]),
Some("dunfell")
);
}
}
@@ -0,0 +1,617 @@
//! oelint-adv (BSD-2-Clause, used unchanged) with only its security rules.
//!
//! oelint-adv is mostly a style linter for the OpenEmbedded style guide; the
//! rule file passed with `--rulefile` loads only the rules in [`RULES`], so
//! none of the style rules run. Two of its defaults are not safe for a
//! customer's tree:
//!
//! - it reads a `.oelint.cfg` from the working directory, which would let the
//! repository switch rules off: `OELINT_SKIP_CONFIG` turns that off;
//! - it caches results under the home directory only with `--cached`, which
//! is never passed.
//!
//! Each layer is read with the oldest release its `LAYERSERIES_COMPAT` names
//! (`--release`): the syntax (`_append` before Kirkstone) and which rules
//! apply depend on it. `oelint.vars.srcurigittag`, for one, only applies up
//! to Walnascar; later BitBake checks the tag itself.
//!
//! A `# nooelint: <rule>` comment in a recipe suppresses a finding there, as
//! oelint-adv intends. oelint-adv drops suppressed findings without a trace,
//! so they are counted: the suppressions of our rules in the recipes, less
//! those oelint-adv reports as not needed (`oelint.file.inlinesuppress_na`).
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::time::Duration;
use compliance_core::models::{Finding, Severity};
use compliance_core::CoreError;
use super::{Cra, Hit, RecipeLint, RuleInfo};
/// The scanner name of oelint-adv's findings.
pub const SCANNER: &str = "oelint-adv";
/// oelint-adv's report of a `# nooelint` comment that suppressed nothing.
const UNUSED_SUPPRESSION: &str = "oelint.file.inlinesuppress_na";
/// The id of every image-feature rule at once, as a suppression may name it.
const IMAGE_FEATURES: &str = "oelint.var.badimagefeature";
/// How long one run may take before it is stopped and recorded as failed.
const TIMEOUT: Duration = Duration::from_secs(600);
/// Files per run, so a tree with many recipes stays under the argument
/// limit. A recipe and its appends are in the same layer, and a layer's files
/// are sorted, so they mostly stay in one run.
const FILES_PER_RUN: usize = 1000;
/// A security rule of oelint-adv and what it means.
const fn rule(
id: &'static str,
title: &'static str,
severity: Severity,
cwe: Option<&'static str>,
cra: Cra,
remediation: &'static str,
) -> RuleInfo {
RuleInfo {
scanner: SCANNER,
id,
title,
severity,
cwe,
cra,
remediation,
}
}
/// Removing a debug or development image feature.
const DROP_FEATURE: &str = "Remove the feature from IMAGE_FEATURES / EXTRA_IMAGE_FEATURES of \
the product image; keep it in a separate development image.";
/// The rules that run, by their id in oelint-adv 9.11.
pub static RULES: [RuleInfo; 13] = [
rule(
"oelint.var.badimagefeature.debug-tweaks",
"Image feature debug-tweaks (empty root password, root login)",
Severity::High,
Some("CWE-258"),
Cra::SecureByDefault,
DROP_FEATURE,
),
rule(
"oelint.var.badimagefeature.allow-empty-password",
"Image feature allow-empty-password",
Severity::High,
Some("CWE-258"),
Cra::SecureByDefault,
DROP_FEATURE,
),
rule(
"oelint.var.badimagefeature.empty-root-password",
"Image feature empty-root-password",
Severity::High,
Some("CWE-258"),
Cra::SecureByDefault,
DROP_FEATURE,
),
rule(
"oelint.var.badimagefeature.serial-autologin-root",
"Image feature serial-autologin-root",
Severity::High,
Some("CWE-306"),
Cra::SecureByDefault,
DROP_FEATURE,
),
rule(
"oelint.var.badimagefeature.allow-root-login",
"Image feature allow-root-login",
Severity::Medium,
Some("CWE-1188"),
Cra::SecureByDefault,
DROP_FEATURE,
),
rule(
"oelint.var.badimagefeature.tools-debug",
"Image feature tools-debug (debugging tools on the device)",
Severity::Low,
Some("CWE-489"),
Cra::SecureByDefault,
DROP_FEATURE,
),
rule(
"oelint.var.badimagefeature.dbg-pkgs",
"Image feature dbg-pkgs (debug symbols on the device)",
Severity::Low,
Some("CWE-489"),
Cra::SecureByDefault,
DROP_FEATURE,
),
rule(
"oelint.var.badimagefeature.dev-pkgs",
"Image feature dev-pkgs (development files on the device)",
Severity::Low,
Some("CWE-489"),
Cra::SecureByDefault,
DROP_FEATURE,
),
rule(
"oelint.vars.srcurichecksum",
"Fetched source without a checksum",
Severity::Medium,
Some("CWE-494"),
Cra::Integrity,
"Add SRC_URI[sha256sum] for every downloaded file, so a changed or swapped download \
fails the build.",
),
rule(
"oelint.vars.autorev",
"SRCREV follows the branch head (AUTOREV)",
Severity::Medium,
Some("CWE-494"),
Cra::Integrity,
"Pin SRCREV to a commit: with AUTOREV every build takes whatever the branch holds, \
and the image cannot be rebuilt or traced to its sources.",
),
rule(
"oelint.vars.srcurigittag",
"Git source pinned by a tag instead of a commit",
Severity::Low,
Some("CWE-494"),
Cra::Integrity,
"Pin SRCREV to a commit: a tag can be moved.",
),
rule(
"oelint.task.network",
"Task with network access",
Severity::Medium,
Some("CWE-494"),
Cra::AttackSurface,
"Fetch in do_fetch through SRC_URI, with checksums, instead of giving a build task \
network access.",
),
rule(
"oelint.vars.insaneskip",
"QA checks skipped (INSANE_SKIP)",
Severity::Low,
None,
Cra::None,
"Fix what the QA check reports instead of skipping it; some (ldflags, \
already-stripped, textrel) guard the binaries' hardening.",
),
];
/// The rule file passed with `--rulefile`: only [`RULES`] are loaded, and
/// the report of suppressions that suppressed nothing. An empty severity keeps
/// oelint-adv's own; ours come from [`RULES`].
fn rulefile() -> String {
let entries: serde_json::Map<String, serde_json::Value> = RULES
.iter()
.map(|r| r.id)
.chain([UNUSED_SUPPRESSION])
.map(|id| (id.to_string(), serde_json::Value::String(String::new())))
.collect();
serde_json::Value::Object(entries).to_string()
}
/// One issue of oelint-adv's `gitlab-codequality` report.
#[derive(Debug, serde::Deserialize)]
struct Issue {
check_name: String,
description: String,
location: Location,
}
#[derive(Debug, serde::Deserialize)]
struct Location {
path: String,
lines: Lines,
}
#[derive(Debug, serde::Deserialize)]
struct Lines {
begin: u32,
}
/// What one oelint-adv run reported.
#[derive(Debug, Default)]
struct Report {
hits: Vec<Hit>,
/// `# nooelint` suppressions of our rules that suppressed nothing.
unused_suppressions: usize,
}
/// The hits in a `gitlab-codequality` `report`. An issue is reported once per
/// place, though oelint-adv repeats it for each configuration it tries; a
/// rule we did not ask for is dropped.
///
/// # Errors
///
/// Returns the parse error when `report` is not that format.
fn parse_report(report: &str) -> Result<Report, serde_json::Error> {
let issues: Vec<Issue> = serde_json::from_str(report)?;
let mut seen = BTreeSet::new();
let mut unused = BTreeSet::new();
let mut hits = Vec::new();
for issue in issues {
let path = issue
.location
.path
.strip_prefix("./")
.unwrap_or(&issue.location.path)
.to_string();
let line = issue.location.lines.begin.max(1);
if issue.check_name == UNUSED_SUPPRESSION {
// "Inline suppression for '<id>' is not needed"
if let Some(id) = issue.description.split('\'').nth(1) {
if is_ours(id) {
unused.insert((path, line, id.to_string()));
}
}
continue;
}
let Some(rule) = RULES.iter().find(|r| r.id == issue.check_name) else {
continue;
};
if !seen.insert((rule.id, path.clone(), line)) {
continue;
}
// `[branch:true]` names the configuration oelint-adv tried.
let detail = match issue.description.rsplit_once(" [") {
Some((text, matrix)) if matrix.ends_with(']') => text,
_ => issue.description.as_str(),
};
hits.push(Hit::new(rule, &path, line, detail.to_string()));
}
Ok(Report {
hits,
unused_suppressions: unused.len(),
})
}
/// Whether a suppression naming `id` can suppress one of our rules.
fn is_ours(id: &str) -> bool {
id == IMAGE_FEATURES || RULES.iter().any(|r| r.id == id)
}
/// How many suppressions of our rules the `# nooelint:` comments in `text`
/// name, read as oelint-adv reads them.
fn suppressions(text: &str) -> usize {
text.lines()
.filter_map(|line| {
let rest = line.trim_start().strip_prefix('#')?;
// `#\s+nooelint:\s+<ids>`, as oelint-adv matches it.
let ids = rest.trim_start().strip_prefix("nooelint:").filter(|ids| {
rest.starts_with(char::is_whitespace) && ids.starts_with(char::is_whitespace)
})?;
Some(
ids.split(|c: char| c == ',' || c.is_whitespace())
.filter(|id| is_ours(id))
.count(),
)
})
.sum()
}
/// oelint-adv's findings, and how many it did not report because a
/// `# nooelint` comment suppressed them.
#[derive(Debug, Default)]
pub struct OelintOutput {
/// The findings.
pub findings: Vec<Finding>,
/// Suppressions of our rules in the recipes that took effect.
pub suppressed: usize,
}
/// A scanner error with `source` as its cause.
fn failed(source: Box<dyn std::error::Error + Send + Sync>) -> CoreError {
CoreError::Scanner {
scanner: SCANNER.to_string(),
source,
}
}
impl RecipeLint {
/// oelint-adv's findings in the customer's layers under `root`, and the
/// findings suppressed by comments there.
///
/// # Errors
///
/// Returns `CoreError::Scanner` when oelint-adv cannot start, times out,
/// exits with an error, or writes a report that cannot be read.
pub async fn oelint_findings(
&self,
root: &Path,
repo_id: &str,
) -> Result<OelintOutput, CoreError> {
let work = WorkDir::new().map_err(|e| failed(Box::new(e)))?;
let mut hits = Vec::new();
let mut unused = 0;
let mut named = 0;
for layer in self.own_layers() {
// Includes are read through the recipes, so their comments count.
named += layer
.files
.iter()
.filter(|f| {
let inner = layer.inner(f);
is_bitbake(inner) || inner.ends_with(".inc")
})
.filter_map(|f| super::read_text(root, f))
.map(|text| suppressions(&text))
.sum::<usize>();
let files: Vec<&String> = layer
.files
.iter()
.filter(|f| is_bitbake(layer.inner(f)))
.collect();
for chunk in files.chunks(FILES_PER_RUN) {
let report = parse_report(&run(root, layer.release, chunk, &work).await?)?;
hits.extend(report.hits);
unused += report.unused_suppressions;
}
}
Ok(OelintOutput {
findings: hits
.into_iter()
.map(|hit| hit.into_finding(root, repo_id))
.collect(),
suppressed: named.saturating_sub(unused),
})
}
}
/// Whether oelint-adv reads `inner` (relative to its layer): recipes,
/// appends, classes and the layer's configuration. Includes are read through
/// the recipes that require them.
fn is_bitbake(inner: &str) -> bool {
let ext = inner.rsplit_once('.').map_or("", |(_, ext)| ext);
matches!(ext, "bb" | "bbappend" | "bbclass") || (ext == "conf" && inner.starts_with("conf/"))
}
/// One oelint-adv run over `files` (relative to `root`) read as `release`.
async fn run(
root: &Path,
release: Option<&str>,
files: &[&String],
work: &WorkDir,
) -> Result<String, CoreError> {
let mut cmd = crate::pipeline::tool_cmd::tool_in(SCANNER, root, &[]);
cmd.env("OELINT_SKIP_CONFIG", "1")
.args(["--quiet", "--exit-zero", "--relpaths", "--jobs", "2"])
.args([
"--outputformat",
"gitlab-codequality",
"--messageformat",
"{msg}",
])
.arg("--rulefile")
.arg(work.rulefile())
.arg("--output")
.arg(work.report());
if let Some(release) = release {
cmd.args(["--release", release]);
}
cmd.args(files.iter().map(|f| f.as_str()));
let output = crate::pipeline::tool_cmd::run_bounded_for(&mut cmd, SCANNER, TIMEOUT)
.await
.map_err(|e| failed(Box::new(e)))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let tail: String = stderr.lines().rev().take(3).collect::<Vec<_>>().join(" / ");
return Err(failed(
format!("exited with {}: {tail}", output.status).into(),
));
}
let report = std::fs::read_to_string(work.report()).map_err(|e| failed(Box::new(e)))?;
// The report is rewritten by every run.
let _ = std::fs::remove_file(work.report());
Ok(report)
}
/// The rule file and report of the runs, in a temporary directory removed on
/// drop.
struct WorkDir(PathBuf);
impl WorkDir {
fn new() -> std::io::Result<Self> {
let dir = std::env::temp_dir().join(format!("cs-oelint-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir)?;
let work = Self(dir);
std::fs::write(work.rulefile(), rulefile())?;
Ok(work)
}
fn rulefile(&self) -> PathBuf {
self.0.join("rules.json")
}
fn report(&self) -> PathBuf {
self.0.join("report.json")
}
}
impl Drop for WorkDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
const REPORT: &str = r#"[
{"description": "EXTRA_IMAGE_FEATURES contains 'debug-tweaks', that is a security risk. Allows limitless access without authentication [branch:true]",
"check_name": "oelint.var.badimagefeature.debug-tweaks",
"fingerprint": "a", "location": {"path": "recipes-core/images/pump-image.bb", "lines": {"begin": 8}},
"severity": "minor"},
{"description": "EXTRA_IMAGE_FEATURES contains 'debug-tweaks', that is a security risk. Allows limitless access without authentication [branch:false]",
"check_name": "oelint.var.badimagefeature.debug-tweaks",
"fingerprint": "b", "location": {"path": "recipes-core/images/pump-image.bb", "lines": {"begin": 8}},
"severity": "minor"},
{"description": "Variable 'HOMEPAGE' should be set [branch:true]",
"check_name": "oelint.var.mandatoryvar.HOMEPAGE",
"fingerprint": "c", "location": {"path": "recipes-app/x/x.bb", "lines": {"begin": 1}},
"severity": "critical"},
{"description": "SRC_URI[sha256sum] is needed",
"check_name": "oelint.vars.srcurichecksum",
"fingerprint": "d", "location": {"path": "./recipes-app/web/web_2.1.bb", "lines": {"begin": 0}},
"severity": "critical"},
{"description": "Inline suppression for 'oelint.vars.autorev' is not needed",
"check_name": "oelint.file.inlinesuppress_na",
"fingerprint": "e", "location": {"path": "recipes-app/web/web_2.1.bb", "lines": {"begin": 9}},
"severity": "info"},
{"description": "Inline suppression for 'oelint.vars.autorev' is not needed",
"check_name": "oelint.file.inlinesuppress_na",
"fingerprint": "f", "location": {"path": "recipes-app/web/web_2.1.bb", "lines": {"begin": 9}},
"severity": "info"},
{"description": "Inline suppression for 'oelint.var.order.PV' is not needed",
"check_name": "oelint.file.inlinesuppress_na",
"fingerprint": "g", "location": {"path": "recipes-app/web/web_2.1.bb", "lines": {"begin": 3}},
"severity": "info"}
]"#;
#[test]
fn the_report_becomes_one_hit_per_rule_and_place() {
let report = parse_report(REPORT).expect("report");
assert_eq!(report.unused_suppressions, 1);
let hits = report.hits;
let got: Vec<(&str, &str, u32, Severity)> = hits
.iter()
.map(|h| (h.rule.id, h.path.as_str(), h.line, h.rule.severity.clone()))
.collect();
assert_eq!(
got,
[
(
"oelint.var.badimagefeature.debug-tweaks",
"recipes-core/images/pump-image.bb",
8,
Severity::High
),
(
"oelint.vars.srcurichecksum",
"recipes-app/web/web_2.1.bb",
1,
Severity::Medium
),
]
);
assert_eq!(
hits[0].detail,
"EXTRA_IMAGE_FEATURES contains 'debug-tweaks', that is a security risk. Allows \
limitless access without authentication"
);
assert!(parse_report("not json").is_err());
assert!(parse_report("[]").expect("empty").hits.is_empty());
}
#[test]
fn the_rule_file_lists_only_the_security_rules() {
let file: serde_json::Map<String, serde_json::Value> =
serde_json::from_str(&rulefile()).expect("json");
assert_eq!(file.len(), RULES.len() + 1);
assert!(file.contains_key(UNUSED_SUPPRESSION));
assert!(file.keys().all(|id| id.starts_with("oelint.")));
assert!(!file.contains_key("oelint.var.badimagefeature"));
}
#[test]
fn suppressions_of_our_rules_are_counted_as_oelint_adv_reads_them() {
let text = "# nooelint: oelint.vars.autorev, oelint.var.order.PV\n\
SRCREV = \"${AUTOREV}\"\n\
# nooelint: oelint.var.badimagefeature oelint.task.network\n\
#nooelint: oelint.vars.insaneskip\n\
# nooelint:oelint.vars.insaneskip\n\
# a note about nooelint: oelint.vars.autorev\n";
// One of the two on the first comment and both on the second; the
// third lacks the space oelint-adv requires, the last is prose.
assert_eq!(suppressions(text), 3);
assert_eq!(suppressions("SRC_URI = \"x\"\n"), 0);
}
/// The fixture with `# nooelint` comments: one that suppresses a
/// finding and one in the wrong place.
#[tokio::test]
async fn suppressed_findings_are_counted() {
if !installed() {
return;
}
let fixture =
Path::new(env!("CARGO_MANIFEST_DIR")).join("../fixtures/nightly/firmware/yocto-layer");
let read = |rel: &str| std::fs::read_to_string(fixture.join(rel)).expect("fixture");
let fw = read("recipes-app/pump-fw/pump-fw_git.bb")
.replace("SRCREV = ", "# nooelint: oelint.vars.autorev\nSRCREV = ");
let web = read("recipes-app/pump-web/pump-web_2.1.bb").replace(
"do_compile() {",
"# nooelint: oelint.task.network\ndo_compile() {",
);
let t = super::super::tests::tree(&[
("conf/layer.conf", &read("conf/layer.conf")),
("recipes-app/pump-fw/pump-fw_git.bb", &fw),
("recipes-app/pump-web/pump-web_2.1.bb", &web),
]);
let lint = RecipeLint::for_tree(&t.0, &["bitbake".to_string()], &[]).expect("lint");
let out = lint.oelint_findings(&t.0, "t").await.expect("oelint-adv");
let rules: Vec<&str> = out
.findings
.iter()
.filter_map(|f| f.rule_id.as_deref())
.collect();
assert!(!rules.contains(&"oelint.vars.autorev"));
assert!(rules.contains(&"oelint.task.network"));
assert_eq!(out.suppressed, 1);
}
/// Whether oelint-adv is on the PATH (the agent image has it).
fn installed() -> bool {
let found = std::process::Command::new(SCANNER)
.arg("--version")
.output()
.is_ok_and(|o| o.status.success());
if !found {
eprintln!("oelint-adv is not installed; skipping");
}
found
}
/// Runs the real oelint-adv over the nightly fixture when it is on the
/// PATH (the agent image has it); passes without it.
#[tokio::test]
async fn the_fixture_layer_yields_the_security_findings() {
if !installed() {
return;
}
let root =
Path::new(env!("CARGO_MANIFEST_DIR")).join("../fixtures/nightly/firmware/yocto-layer");
let lint = RecipeLint::for_tree(&root, &["bitbake".to_string()], &[]).expect("lint");
let out = lint.oelint_findings(&root, "t").await.expect("oelint-adv");
assert_eq!(out.suppressed, 0);
let mut got: Vec<String> = out
.findings
.iter()
.map(|f| {
format!(
"{} {}:{}",
f.rule_id.as_deref().unwrap_or_default(),
f.file_path.as_deref().unwrap_or_default(),
f.line_number.unwrap_or(0)
)
})
.collect();
got.sort();
assert_eq!(
got,
[
"oelint.task.network recipes-app/pump-web/pump-web_2.1.bb:8",
"oelint.var.badimagefeature.allow-empty-password recipes-core/images/pump-image.bb:7",
"oelint.var.badimagefeature.debug-tweaks recipes-core/images/pump-image.bb:8",
"oelint.vars.autorev recipes-app/pump-fw/pump-fw_git.bb:6",
"oelint.vars.srcurichecksum recipes-app/pump-web/pump-web_2.1.bb:6",
]
);
}
}
@@ -0,0 +1,620 @@
//! Our own secure-by-default rules for Yocto layers (`yocto-config`).
//!
//! What oelint-adv does not check, read from the layer files without running
//! BitBake:
//!
//! - a password (hash or clear text) in `EXTRA_USERS_PARAMS`: every device
//! gets the same one;
//! - an `http://` fetch in `SRC_URI`;
//! - a shipped `sshd_config` with `PermitRootLogin yes` or
//! `PasswordAuthentication yes`;
//! - a certificate shipped with a recipe (informational: which trust anchors
//! the image carries). Private keys are the secret scanner's (gitleaks
//! reports PEM keys anywhere in the tree), so they are not reported twice;
//! - a distro configuration, or a `local.conf.sample` without a distro, that
//! does not pull in `security_flags.inc` (stack protector, FORTIFY_SOURCE,
//! PIE, RELRO).
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use std::sync::LazyLock;
use compliance_core::models::Severity;
use regex::Regex;
use super::{Cra, Hit, Layer, RecipeLint, RuleInfo};
use crate::pipeline::source_text::read_text;
/// The scanner name of these rules' findings.
pub const SCANNER: &str = "yocto-config";
/// Extensions of certificate files a recipe may ship.
const CERTIFICATE_EXTENSIONS: &[&str] = &["pem", "crt", "cer", "cert"];
/// Values of `-p` that lock an account instead of setting a password.
const LOCKED: &[&str] = &["*", "!", "!!", "!*", "x"];
const EXTRAUSERS_PASSWORD: RuleInfo = RuleInfo {
scanner: SCANNER,
id: "yocto-extrausers-password",
title: "Password set in EXTRA_USERS_PARAMS",
severity: Severity::High,
cwe: Some("CWE-798"),
cra: Cra::SecureByDefault,
remediation: "Do not bake a password or password hash into the image: every device \
ships with the same credential. Lock the account (usermod -p '*'), use key \
authentication, or set a per-device password at provisioning.",
};
const SRC_URI_HTTP: RuleInfo = RuleInfo {
scanner: SCANNER,
id: "yocto-src-uri-http",
title: "Source fetched over unencrypted http",
severity: Severity::Medium,
cwe: Some("CWE-319"),
cra: Cra::AttackSurface,
remediation: "Fetch over https (or git with protocol=https) and keep the checksum or \
SRCREV pinned.",
};
const SSHD_ROOT_LOGIN: RuleInfo = RuleInfo {
scanner: SCANNER,
id: "yocto-sshd-root-login",
title: "Shipped sshd_config allows root login",
severity: Severity::High,
cwe: Some("CWE-1188"),
cra: Cra::SecureByDefault,
remediation: "Set PermitRootLogin no (or prohibit-password with key authentication) in \
the sshd_config the image ships.",
};
const SSHD_PASSWORD_AUTH: RuleInfo = RuleInfo {
scanner: SCANNER,
id: "yocto-sshd-password-auth",
title: "Shipped sshd_config allows password logins",
severity: Severity::Medium,
cwe: Some("CWE-1188"),
cra: Cra::SecureByDefault,
remediation: "Set PasswordAuthentication no and use key authentication.",
};
const SHIPPED_CERTIFICATE: RuleInfo = RuleInfo {
scanner: SCANNER,
id: "yocto-files-certificate",
title: "Certificate shipped with a recipe",
severity: Severity::Info,
cwe: None,
cra: Cra::None,
remediation: "Check that the certificate is meant to be on every device (a trust anchor, \
not a device identity) and that it is renewed before it expires.",
};
const DISTRO_NO_SECURITY_FLAGS: RuleInfo = RuleInfo {
scanner: SCANNER,
id: "yocto-distro-no-security-flags",
title: "Distro does not include security_flags.inc",
severity: Severity::Medium,
cwe: Some("CWE-693"),
cra: Cra::SecureByDefault,
remediation: "Add require conf/distro/include/security_flags.inc to the distro \
configuration, so every package is built with the stack protector, \
FORTIFY_SOURCE, PIE and full RELRO.",
};
const LOCAL_CONF_NO_SECURITY_FLAGS: RuleInfo = RuleInfo {
scanner: SCANNER,
id: "yocto-local-conf-no-security-flags",
title: "local.conf.sample builds without a distro or security_flags.inc",
severity: Severity::Info,
cwe: Some("CWE-693"),
cra: Cra::SecureByDefault,
remediation: "Set DISTRO to a distro that includes security_flags.inc, or require it in \
the template.",
};
/// Every rule of this scanner.
pub const RULES: [&RuleInfo; 7] = [
&EXTRAUSERS_PASSWORD,
&SRC_URI_HTTP,
&SSHD_ROOT_LOGIN,
&SSHD_PASSWORD_AUTH,
&SHIPPED_CERTIFICATE,
&DISTRO_NO_SECURITY_FLAGS,
&LOCAL_CONF_NO_SECURITY_FLAGS,
];
/// The start of a BitBake assignment: the variable (with its overrides), the
/// operator and the opening quote.
static ASSIGNMENT: LazyLock<Option<Regex>> = LazyLock::new(|| {
Regex::new(
r#"^\s*(?:export\s+)?([A-Za-z0-9_${}.+/-]+(?::[A-Za-z0-9_${}.+/-]+)*)\s*(?:\?\?=|\?=|:=|\+=|=\+|\.=|=\.|=)\s*(["'])"#,
)
.ok()
});
/// A password option of `useradd` / `usermod` and its value.
static PASSWORD_OPTION: LazyLock<Option<Regex>> = LazyLock::new(|| {
Regex::new(
r#"\b(?:useradd|usermod)\b[^;]*?\s(?:-p|-P|--password)\s+('[^']*'|\\?"[^"]*\\?"|[^\s;]+)"#,
)
.ok()
});
/// A `require` or `include` and the file it names.
static INCLUDE: LazyLock<Option<Regex>> =
LazyLock::new(|| Regex::new(r"^\s*(?:require|include)\s+(\S+)").ok());
/// One assignment in a BitBake file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Assignment {
/// The variable without its overrides (`SRC_URI` for `SRC_URI:append`).
pub var: String,
/// The value between the quotes; continued lines are joined by `\n`.
pub value: String,
/// The line the assignment starts on, 1-based.
pub line: u32,
}
impl Assignment {
/// The line of byte `offset` in the value.
fn line_at(&self, offset: usize) -> u32 {
let newlines = self.value.get(..offset).unwrap_or("").matches('\n').count();
self.line + u32::try_from(newlines).unwrap_or(0)
}
}
/// The assignments in BitBake `text`, in order. Flags (`SRC_URI[sha256sum]`)
/// and comments are not assignments.
pub(crate) fn assignments(text: &str) -> Vec<Assignment> {
let Some(start) = ASSIGNMENT.as_ref() else {
return Vec::new();
};
let mut out = Vec::new();
let mut lines = text.lines().enumerate();
while let Some((index, line)) = lines.next() {
let Some(caps) = start.captures(line) else {
continue;
};
let (Some(name), Some(quote), Some(all)) = (caps.get(1), caps.get(2), caps.get(0)) else {
continue;
};
let quote = quote.as_str();
let mut value = String::new();
let mut rest = &line[all.end()..];
loop {
if let Some(end) = rest.find(quote) {
value.push_str(&rest[..end]);
break;
}
match rest.trim_end().strip_suffix('\\') {
Some(continued) => {
value.push_str(continued);
value.push('\n');
match lines.next() {
Some((_, next)) => rest = next,
None => break,
}
}
None => {
value.push_str(rest);
break;
}
}
}
out.push(Assignment {
var: name
.as_str()
.split(':')
.next()
.unwrap_or_default()
.to_string(),
value,
line: u32::try_from(index + 1).unwrap_or(u32::MAX),
});
}
out
}
/// Whether `inner` (relative to its layer, file `name`) is a file a recipe
/// ships that these rules read: an sshd configuration or a certificate in a
/// `recipes-*` directory.
pub(crate) fn is_shipped_file(inner: &str, name: &str) -> bool {
if !inner.starts_with("recipes-") {
return false;
}
let ext = name.rsplit_once('.').map_or("", |(_, ext)| ext);
name.starts_with("sshd_config") || CERTIFICATE_EXTENSIONS.contains(&ext)
}
impl RecipeLint {
/// What our own rules find in the customer's layers under `root`.
pub(crate) fn config_hits(&self, root: &Path) -> Vec<Hit> {
let index = ConfIndex::new(root, &self.layers);
let mut hits = Vec::new();
for layer in self.own_layers() {
for file in &layer.files {
let Some(text) = read_text(root, file) else {
continue;
};
let inner = layer.inner(file);
let name = inner.rsplit('/').next().unwrap_or(inner);
if name.starts_with("sshd_config") {
hits.extend(sshd_hits(file, &text));
} else if is_shipped_file(inner, name) {
hits.extend(certificate_hit(file, &text));
} else {
let found = assignments(&text);
hits.extend(extrausers_hits(file, &found));
hits.extend(http_hits(file, &found));
if is_distro_conf(inner) && !index.hardened(file, &text) {
hits.push(Hit::new(&DISTRO_NO_SECURITY_FLAGS, file, 1, String::new()));
} else if name == "local.conf.sample"
&& without_distro(&found)
&& !index.hardened(file, &text)
{
hits.push(Hit::new(
&LOCAL_CONF_NO_SECURITY_FLAGS,
file,
1,
String::new(),
));
}
}
}
}
hits
}
}
/// Passwords set by `useradd` / `usermod` in `EXTRA_USERS_PARAMS`. The
/// snippet hides the value.
fn extrausers_hits(file: &str, found: &[Assignment]) -> Vec<Hit> {
let Some(option) = PASSWORD_OPTION.as_ref() else {
return Vec::new();
};
found
.iter()
.filter(|a| a.var == "EXTRA_USERS_PARAMS")
.flat_map(|a| {
option.captures_iter(&a.value).filter_map(|caps| {
let value = caps.get(1)?;
let bare = value
.as_str()
.trim_matches(|c| matches!(c, '\'' | '"' | '\\'));
let reference = bare.starts_with("${") && bare.ends_with('}');
if LOCKED.contains(&bare) || reference {
return None;
}
let whole = caps.get(0)?;
let command = a
.value
.get(whole.start()..value.start())
.unwrap_or_default();
let shown = format!("{}<hidden>", command.trim_start());
let mut hit = Hit::new(
&EXTRAUSERS_PASSWORD,
file,
a.line_at(value.start()),
if bare.is_empty() {
"The account is given an empty password.".to_string()
} else {
"The image sets a fixed password for the account.".to_string()
},
);
hit.snippet = Some(shown);
Some(hit)
})
})
.collect()
}
/// `http://` fetches and `protocol=http` in `SRC_URI`.
fn http_hits(file: &str, found: &[Assignment]) -> Vec<Hit> {
found
.iter()
.filter(|a| a.var == "SRC_URI")
.flat_map(|a| {
a.value
.split_whitespace()
.filter(|uri| {
uri.starts_with("http://")
|| uri.split(';').skip(1).any(|o| o == "protocol=http")
})
.filter_map(|uri| {
let offset = a.value.find(uri)?;
Some(Hit::new(
&SRC_URI_HTTP,
file,
a.line_at(offset),
format!("Fetched without TLS: {uri}"),
))
})
.collect::<Vec<_>>()
})
.collect()
}
/// `PermitRootLogin yes` and `PasswordAuthentication yes` in an sshd
/// configuration; comments are the stock template's defaults, not settings.
fn sshd_hits(file: &str, text: &str) -> Vec<Hit> {
text.lines()
.enumerate()
.filter_map(|(index, line)| {
let mut words = line.split_whitespace();
let key = words.next()?.to_ascii_lowercase();
let value = words.next()?.to_ascii_lowercase();
let rule = match (key.as_str(), value.as_str()) {
("permitrootlogin", "yes") => &SSHD_ROOT_LOGIN,
("passwordauthentication", "yes") => &SSHD_PASSWORD_AUTH,
_ => return None,
};
let line_number = u32::try_from(index + 1).ok()?;
Some(Hit::new(rule, file, line_number, String::new()))
})
.collect()
}
/// The first certificate in a shipped file.
fn certificate_hit(file: &str, text: &str) -> Option<Hit> {
let index = text
.lines()
.position(|l| l.contains("-----BEGIN CERTIFICATE-----"))?;
let line = u32::try_from(index + 1).ok()?;
Some(Hit::new(&SHIPPED_CERTIFICATE, file, line, String::new()))
}
/// Whether `inner` is a distro configuration (`conf/distro/<name>.conf`).
fn is_distro_conf(inner: &str) -> bool {
inner
.strip_prefix("conf/distro/")
.is_some_and(|name| !name.contains('/') && name.ends_with(".conf"))
}
/// Whether a `local.conf.sample` builds without a distro (`DISTRO` unset or
/// `nodistro`), which OpenEmbedded-Core builds without the security flags. A
/// named distro is checked on its own when it is in the tree, and is not
/// known otherwise.
fn without_distro(found: &[Assignment]) -> bool {
found
.iter()
.rev()
.find(|a| a.var == "DISTRO")
.is_none_or(|a| a.value.trim() == "nodistro")
}
/// The configuration files of every layer (upstream included), by their path
/// inside the layer, to follow `require` and `include`.
struct ConfIndex<'a> {
root: &'a Path,
by_inner: BTreeMap<&'a str, &'a str>,
}
impl<'a> ConfIndex<'a> {
fn new(root: &'a Path, layers: &'a [Layer]) -> Self {
let by_inner = layers
.iter()
.flat_map(|l| l.files.iter().map(move |f| (l.inner(f), f.as_str())))
.filter(|(inner, _)| inner.starts_with("conf/"))
.collect();
Self { root, by_inner }
}
/// Whether the configuration `text` of `file` may pull in
/// `security_flags.inc`, itself or through what it requires. An include
/// that is not in the tree (Poky's distros, a BSP layer kas fetches) or
/// goes through a variable cannot be followed and counts as hardened, so
/// nothing is claimed that is not known.
fn hardened(&self, file: &str, text: &str) -> bool {
let mut seen = BTreeSet::from([file.to_string()]);
self.follows(text, &mut seen)
}
fn follows(&self, text: &str, seen: &mut BTreeSet<String>) -> bool {
let Some(include) = INCLUDE.as_ref() else {
return true;
};
text.lines()
.filter_map(|line| include.captures(line)?.get(1))
.map(|target| target.as_str())
.any(|target| {
let name = target.rsplit('/').next().unwrap_or(target);
if name == "security_flags.inc" || target.contains("${") {
return true;
}
let Some(file) = self.by_inner.get(target) else {
return true;
};
if !seen.insert((*file).to_string()) {
return false;
}
read_text(self.root, file).is_some_and(|text| self.follows(&text, seen))
})
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::super::tests::tree;
use super::*;
fn rule_lines(lint_root: &Path) -> Vec<String> {
let lint = RecipeLint::for_tree(lint_root, &["bitbake".to_string()], &[]).expect("lint");
let mut out: Vec<String> = lint
.config_hits(lint_root)
.into_iter()
.map(|h| format!("{} {}:{}", h.rule.id, h.path, h.line))
.collect();
out.sort();
out
}
const LAYER: &str = "BBFILE_COLLECTIONS += \"pump\"\nLAYERSERIES_COMPAT_pump = \"scarthgap\"\n";
#[test]
fn assignments_join_continued_lines_and_skip_flags() {
let text = "SRC_URI = \"git://x;protocol=https \\\n file://a.patch \\\n\"\n\
SRC_URI[sha256sum] = \"abc\"\n# SRC_URI = \"http://commented\"\n\
SRC_URI:append:arm = \" http://y/z.tgz\"\n";
let found = assignments(text);
assert_eq!(found.len(), 2);
assert_eq!(found[0].var, "SRC_URI");
assert_eq!(found[0].line, 1);
assert!(found[0].value.contains("file://a.patch"));
assert_eq!(found[1].var, "SRC_URI");
assert_eq!(found[1].line, 6);
}
#[test]
fn a_password_in_extra_users_params_is_reported_with_its_value_hidden() {
let text = "EXTRA_USERS_PARAMS = \"\\\n useradd -m -p '$6$salt$hash' pump; \\\n \
usermod -p '*' root; \\\n usermod -P secret operator; \\\n \
usermod -p '${ROOT_HASH}' service; \\\n\"\n";
let hits = extrausers_hits("image.bb", &assignments(text));
let lines: Vec<u32> = hits.iter().map(|h| h.line).collect();
// The locked root account and the hash from a variable are not.
assert_eq!(lines, [2, 4]);
let snippet = hits[0].snippet.as_deref().expect("snippet");
assert!(snippet.starts_with("useradd -m -p"));
assert!(snippet.ends_with("<hidden>"));
assert!(!hits.iter().any(|h| h
.snippet
.as_deref()
.is_some_and(|s| s.contains("secret") || s.contains("$6$"))));
}
#[test]
fn plain_http_fetches_are_reported_and_https_ones_are_not() {
let text = "SRC_URI = \"http://a/b.tgz \\\n https://c/d.tgz \\\n \
git://e/f.git;protocol=http;branch=main \\\n \
git://g/h.git;protocol=https;branch=main\"\n";
let hits = http_hits("x.bb", &assignments(text));
let lines: Vec<u32> = hits.iter().map(|h| h.line).collect();
assert_eq!(lines, [1, 3]);
}
#[test]
fn sshd_settings_count_only_when_set() {
let text = "#PermitRootLogin yes\nPermitRootLogin yes\nPasswordAuthentication no\n\
passwordauthentication YES\nPermitRootLogin prohibit-password\n";
let lines: Vec<(&str, u32)> = sshd_hits("sshd_config", text)
.iter()
.map(|h| (h.rule.id, h.line))
.collect();
assert_eq!(
lines,
[
("yocto-sshd-root-login", 2),
("yocto-sshd-password-auth", 4)
]
);
}
#[test]
fn a_tree_reports_each_rule_once_where_it_applies() {
let t = tree(&[
("conf/layer.conf", LAYER),
// Requires a distro that includes the flags: hardened.
(
"conf/distro/pump.conf",
"require conf/distro/include/pump-base.inc\nDISTRO = \"pump\"\n",
),
(
"conf/distro/include/pump-base.inc",
"require conf/distro/include/security_flags.inc\n",
),
// Poky's distro, or a BSP include kas fetches: not in the tree,
// so not known.
(
"conf/distro/pump-poky.conf",
"require conf/distro/poky.conf\n",
),
(
"conf/distro/pump-imx.conf",
"require conf/distro/include/fsl-imx-base.inc\n",
),
// An include in the tree without the flags is followed.
(
"conf/distro/pump-lite.conf",
"include conf/distro/include/pump-lite.inc\n",
),
(
"conf/distro/include/pump-lite.inc",
"DISTRO_FEATURES = \"\"\n",
),
("conf/distro/bare.conf", "DISTRO = \"bare\"\n"),
(
"conf/templates/default/local.conf.sample",
"MACHINE ?= \"qemux86-64\"\n",
),
(
"recipes-connectivity/openssh/files/sshd_config",
"PermitRootLogin yes\n",
),
// Not shipped with a recipe: not read.
("docs/sshd_config", "PermitRootLogin yes\n"),
(
"recipes-core/ca/files/ca.pem",
"# root CA\n-----BEGIN CERTIFICATE-----\nMII\n-----END CERTIFICATE-----\n",
),
(
"recipes-core/ca/files/notes.pem",
"-----BEGIN PUBLIC KEY-----\n",
),
]);
assert_eq!(
rule_lines(&t.0),
[
"yocto-distro-no-security-flags conf/distro/bare.conf:1",
"yocto-distro-no-security-flags conf/distro/pump-lite.conf:1",
"yocto-files-certificate recipes-core/ca/files/ca.pem:2",
"yocto-local-conf-no-security-flags conf/templates/default/local.conf.sample:1",
"yocto-sshd-root-login recipes-connectivity/openssh/files/sshd_config:1",
]
);
}
#[test]
fn a_local_conf_with_a_distro_or_flags_is_not_reported() {
let t = tree(&[
("conf/layer.conf", LAYER),
("conf/local.conf.sample", "DISTRO ?= \"poky\"\n"),
(
"conf/templates/hardened/local.conf.sample",
"require conf/distro/include/security_flags.inc\n",
),
]);
assert!(rule_lines(&t.0).is_empty());
}
#[test]
fn the_fixture_layer_yields_the_nightly_baseline() {
let root =
Path::new(env!("CARGO_MANIFEST_DIR")).join("../fixtures/nightly/firmware/yocto-layer");
assert_eq!(
rule_lines(&root),
[
"yocto-distro-no-security-flags conf/distro/pump-distro.conf:1",
"yocto-extrausers-password recipes-core/images/pump-image.bb:13",
"yocto-src-uri-http recipes-app/pump-web/pump-web_2.1.bb:6",
"yocto-sshd-root-login recipes-connectivity/openssh/files/sshd_config:3",
]
);
}
#[test]
fn upstream_layers_are_not_checked() {
let t = tree(&[
(
"poky/meta/conf/layer.conf",
"BBFILE_COLLECTIONS += \"core\"\n",
),
("poky/meta/conf/distro/defaultsetup.conf", "DISTRO = \"\"\n"),
(
"poky/meta/recipes-x/x/x.bb",
"SRC_URI = \"http://x/y.tgz\"\n",
),
]);
assert!(rule_lines(&t.0).is_empty());
}
}
@@ -45,6 +45,16 @@ pub struct RepoView {
/// Whether the target's uploaded files let a scheduled scan without new
/// commits be skipped ([`crate::pipeline::change::uploads_allow_git_skip`]).
pub uploads_allow_skip: bool,
/// Whether the tree is read as Yocto layers (its recipe inventory): it
/// was classified as one, or the target is a Yocto target. Set by the
/// caller after classification; `false` from [`Self::from_target`].
pub yocto_layers: bool,
/// Directories and files the target's settings leave out of every scan
/// stage (`scan_config.exclude_paths`).
pub exclude_paths: Vec<String>,
/// The target's uploaded build outputs (Yocto image SPDX archives), as
/// ingested. Set by the caller; empty from [`Self::from_target`].
pub build_outputs: Vec<std::path::PathBuf>,
}
impl RepoView {
@@ -74,6 +84,9 @@ impl RepoView {
findings_count: target.findings_count,
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();
@@ -488,6 +488,7 @@ fn merge_audit_vulns(entries: &mut [SbomEntry], vulns: Vec<cargo_audit::AuditVul
severity: None,
url: Some(vuln.url),
exploitation: None,
aliases: Vec::new(),
});
}
}
@@ -475,54 +475,12 @@ pub(super) fn license_from_url(url: &str) -> Option<String> {
{
return Some(expression);
}
let page = bare
.trim_end_matches(".php")
.trim_end_matches(".html")
.trim_end_matches(".txt")
.trim_end_matches(".md");
let known = WELL_KNOWN_URLS
.iter()
.find(|(prefix, _)| page == *prefix)
.map(|(_, spdx)| (*spdx).to_string());
Some(known.unwrap_or_else(|| url.to_string()))
Some(
compliance_core::spdx_license::spdx_of_url(url)
.map_or_else(|| url.to_string(), str::to_string),
)
}
/// License pages (lowercase, without scheme, `www.`, trailing slash and
/// `.html`/`.php`/`.txt`) and the SPDX id they stand for.
const WELL_KNOWN_URLS: &[(&str, &str)] = &[
("opensource.org/licenses/mit", "MIT"),
("opensource.org/licenses/mit-license", "MIT"),
("opensource.org/license/mit", "MIT"),
("choosealicense.com/licenses/mit", "MIT"),
("opensource.org/licenses/apache-2.0", "Apache-2.0"),
("opensource.org/license/apache-2-0", "Apache-2.0"),
("apache.org/licenses/license-2.0", "Apache-2.0"),
("choosealicense.com/licenses/apache-2.0", "Apache-2.0"),
("opensource.org/licenses/bsd-license", "BSD-3-Clause"),
("opensource.org/licenses/bsd-3-clause", "BSD-3-Clause"),
("opensource.org/licenses/bsd-2-clause", "BSD-2-Clause"),
("opensource.org/licenses/ms-pl", "MS-PL"),
("opensource.org/licenses/ms-rl", "MS-RL"),
("microsoft.com/opensource/licenses.mspx#ms-pl", "MS-PL"),
("opensource.org/licenses/mpl-2.0", "MPL-2.0"),
("mozilla.org/mpl/2.0", "MPL-2.0"),
("opensource.org/licenses/isc", "ISC"),
("opensource.org/licenses/zlib", "Zlib"),
("opensource.org/licenses/lgpl-2.1", "LGPL-2.1-only"),
("opensource.org/licenses/lgpl-3.0", "LGPL-3.0-only"),
("gnu.org/licenses/lgpl-2.1", "LGPL-2.1-only"),
("gnu.org/licenses/old-licenses/lgpl-2.1", "LGPL-2.1-only"),
("gnu.org/licenses/lgpl-3.0", "LGPL-3.0-only"),
("gnu.org/licenses/lgpl", "LGPL-3.0-or-later"),
("gnu.org/licenses/gpl-2.0", "GPL-2.0-only"),
("gnu.org/licenses/old-licenses/gpl-2.0", "GPL-2.0-only"),
("gnu.org/licenses/gpl-3.0", "GPL-3.0-only"),
("gnu.org/licenses/gpl", "GPL-3.0-or-later"),
("gnu.org/licenses/agpl-3.0", "AGPL-3.0-only"),
("gnu.org/licenses/agpl", "AGPL-3.0-or-later"),
("unlicense.org", "Unlicense"),
];
/// `%XX` escapes decoded (the expressions nuget.org puts in a URL path).
fn percent_decode(s: &str) -> String {
let bytes = s.as_bytes();
@@ -762,7 +762,8 @@ fn pom_license(text: &str) -> PomLicense {
let name = child(license, "name");
let url = child(license, "url");
name.as_deref()
.and_then(spdx_of_name)
.and_then(compliance_core::spdx_license::spdx_of_name)
.map(str::to_string)
.or_else(|| {
url.as_deref()
.and_then(license_from_url)
@@ -790,31 +791,6 @@ fn pom_license(text: &str) -> PomLicense {
}
}
/// The SPDX id of a license as POMs commonly name it.
fn spdx_of_name(name: &str) -> Option<String> {
let n = name.to_ascii_lowercase();
let id = if n.contains("apache") && n.contains("2") {
"Apache-2.0"
} else if n == "mit" || n.contains("mit license") {
"MIT"
} else if n.contains("bsd") && (n.contains("3") || n.contains("new") || n.contains("revised")) {
"BSD-3-Clause"
} else if n.contains("bsd") && (n.contains("2") || n.contains("simplified")) {
"BSD-2-Clause"
} else if n.contains("eclipse public license") && n.contains("2") {
"EPL-2.0"
} else if n.contains("eclipse public license") && n.contains("1") {
"EPL-1.0"
} else if n.contains("eclipse distribution license") {
"BSD-3-Clause"
} else if n.contains("mozilla public license") && n.contains("2") {
"MPL-2.0"
} else {
return None;
};
Some(id.to_string())
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
@@ -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());
}
}
+142 -5
View File
@@ -5,7 +5,10 @@
//! complete lookup no longer reports it (the component removed or updated
//! past the fix), it is marked resolved, and one nobody assessed, or
//! assessed as affected, gets the VEX status `fixed` from the scan. A
//! person's `not_affected` or `fixed` is never changed by a scan. The first
//! person's `not_affected` or `fixed` is never changed by a scan. What a
//! scan states from the target's own data (a Yocto recipe's CVE_STATUS or
//! `CVE:` patch) is stated again on every scan, and likewise never replaces
//! a person's statement. The first
//! scan that finds it actively exploited records when (`exploited_seen_at`),
//! the start of the CRA's reporting deadlines.
//!
@@ -148,15 +151,149 @@ pub async fn upsert_reported(db: &Database, alert: &CveAlert) -> Result<(), Agen
)
.await?;
}
let mut scan_fixed = filter;
scan_fixed.insert("vex.by_scan", true);
scan_fixed.insert("vex.status", "fixed");
// Reported again, the scan's own statement is withdrawn: a `fixed`
// because the component was gone, or what a recipe said last time
// ([`apply_scan_statements`] states it again if it still does).
let mut by_scan = filter;
by_scan.insert("vex.by_scan", true);
db.cve_alerts()
.update_one(scan_fixed, doc! { "$unset": { "vex": "" } })
.update_one(by_scan, doc! { "$unset": { "vex": "" } })
.await?;
Ok(())
}
/// Store `alert` as found by the CVE monitor between scans: inserted when
/// the target has no alert for the CVE yet (the scan's key, CVE and target),
/// otherwise only its exploitation is refreshed and, when it has none, given
/// the component's purl (same package and version). Unlike
/// [`upsert_reported`] it leaves the rest alone: the VEX statements a scan
/// made from the target's own data (a recipe's `CVE_STATUS`) and whether the
/// alert is resolved are the scan's to change.
///
/// # Returns
///
/// Whether the alert was new.
///
/// # Errors
///
/// A database or encoding error.
pub async fn store_monitored(db: &Database, alert: &CveAlert) -> Result<bool, AgentError> {
let filter = doc! { "cve_id": &alert.cve_id, "repo_id": &alert.repo_id };
let mut insert = mongodb::bson::to_document(alert)
.map_err(|e| AgentError::Other(format!("encode CVE alert: {e}")))?;
let exploitation = insert.remove("exploitation");
let mut update = doc! { "$setOnInsert": insert };
if let Some(exploitation) = exploitation {
update.insert("$set", doc! { "exploitation": exploitation });
}
let inserted = db
.cve_alerts()
.update_one(filter.clone(), update)
.upsert(true)
.await?
.upserted_id
.is_some();
// An alert stored before purls were recorded gets its component's purl
// (only for the same package and version).
if let Some(purl) = &alert.purl {
let mut without_purl = filter;
without_purl.insert("affected_package", &alert.affected_package);
without_purl.insert("affected_version", &alert.affected_version);
without_purl.insert("purl", doc! { "$exists": false });
db.cve_alerts()
.update_one(without_purl, doc! { "$set": { "purl": purl } })
.await?;
}
Ok(inserted)
}
/// Set the VEX statements this scan makes on `repo_id`'s alerts (a Yocto
/// recipe's CVE_STATUS or `CVE:` patch, see
/// [`crate::pipeline::yocto_inventory::vex_statements`]), each as
/// `(cve_id, statement)`. Only an alert nobody assessed, or one whose
/// statement a scan made, gets it: a person's statement is never replaced.
/// Run after [`upsert_reported`], which withdraws the scan's last statements.
///
/// # Returns
///
/// How many alerts got a statement.
///
/// # Errors
///
/// A database error.
pub async fn apply_scan_statements(
db: &Database,
repo_id: &str,
statements: &[(String, VexAssessment)],
) -> Result<u64, AgentError> {
let mut set = 0;
for (cve_id, statement) in statements {
let vex = mongodb::bson::to_bson(statement)
.map_err(|e| AgentError::Other(format!("encode VEX: {e}")))?;
let result = db
.cve_alerts()
.update_one(
scan_may_state(repo_id, cve_id),
doc! { "$set": { "vex": vex } },
)
.await?;
set += result.modified_count;
}
Ok(set)
}
/// The alert `cve_id` of `repo_id`, while no person has assessed it.
fn scan_may_state(repo_id: &str, cve_id: &str) -> mongodb::bson::Document {
doc! {
"repo_id": repo_id,
"cve_id": cve_id,
"$or": [
{ "vex": { "$exists": false } },
{ "vex.by_scan": true },
],
}
}
/// Give the alerts a scan found (which carry no VEX statement) the statement
/// stored on `repo_id`'s alert of the same CVE, or none, so that
/// [`CveAlert::is_resolved_by_vex`] tells whether they notify and keep an
/// issue. Run after the alerts were stored and the scan's own statements set
/// ([`upsert_reported`], [`apply_scan_statements`]).
///
/// # Errors
///
/// A database error.
pub async fn attach_stored_vex(
db: &Database,
repo_id: &str,
alerts: &mut [CveAlert],
) -> Result<(), AgentError> {
if alerts.is_empty() {
return Ok(());
}
let ids: Vec<&str> = alerts.iter().map(|a| a.cve_id.as_str()).collect();
let stored: Vec<CveAlert> = db
.cve_alerts()
.find(doc! {
"repo_id": repo_id,
"cve_id": { "$in": ids },
"vex": { "$exists": true },
})
.await?
.try_collect()
.await?;
let statements: std::collections::HashMap<String, VexAssessment> = stored
.into_iter()
.filter_map(|alert| Some((alert.cve_id, alert.vex?)))
.collect();
for alert in alerts {
// Cloned, not taken: one CVE can be listed for two versions of a
// package.
alert.vex = statements.get(&alert.cve_id).cloned();
}
Ok(())
}
/// Mark resolved the stored alerts of `repo_id` a complete lookup
/// (`complete`) no longer reports in `current`.
///
@@ -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);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,177 @@
//! Git submodules as layer pins: `.gitmodules` names each submodule's path,
//! URL and branch, and the tree's HEAD commit records the commit each
//! submodule is pinned to (its gitlink). An uploaded archive has no `.git`,
//! so its submodules have no commit.
use std::path::Path;
use compliance_core::models::{LayerPin, PinSource};
use git2::Repository;
use super::{clean_ref, read_small};
/// The file submodules are declared in.
pub(crate) const GITMODULES: &str = ".gitmodules";
/// The git file mode of a gitlink: a commit of another repository.
const GITLINK_MODE: i32 = 0o160000;
/// One `[submodule "<name>"]` section.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct Submodule {
pub name: String,
pub path: Option<String>,
pub url: Option<String>,
pub branch: Option<String>,
}
/// The submodules a `.gitmodules` text declares, in order.
pub(crate) fn parse(text: &str) -> Vec<Submodule> {
let mut out: Vec<Submodule> = Vec::new();
// Only keys inside a `[submodule "…"]` section count.
let mut in_submodule = false;
for line in text.lines().map(str::trim) {
if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
continue;
}
if let Some(section) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
let name = section
.trim()
.strip_prefix("submodule")
.map(|rest| rest.trim().trim_matches('"').to_string());
in_submodule = name.is_some();
if let Some(name) = name {
out.push(Submodule {
name,
..Submodule::default()
});
}
continue;
}
let (Some(current), true) = (out.last_mut(), in_submodule) else {
continue;
};
let Some((key, value)) = line.split_once('=') else {
continue;
};
let value = value.trim().trim_matches('"').to_string();
match key.trim().to_ascii_lowercase().as_str() {
"path" => current.path = Some(value),
"url" => current.url = Some(value),
"branch" => current.branch = Some(value),
_ => {}
}
}
out
}
/// The commit the HEAD tree of the repository at `root` records at `path`,
/// when `root` is a git checkout and `path` a gitlink there.
fn gitlink(repo: &Repository, path: &str) -> Option<String> {
let tree = repo.head().ok()?.peel_to_tree().ok()?;
let entry = tree.get_path(Path::new(path)).ok()?;
(entry.filemode() == GITLINK_MODE).then(|| entry.id().to_string())
}
/// The submodules of the tree under `root` as pins, and their paths (whose
/// own kas files and manifests are another repository's, not the tree's).
pub(crate) fn pins(root: &Path) -> (Vec<LayerPin>, Vec<String>) {
let Some(text) = read_small(&root.join(GITMODULES)) else {
return (Vec::new(), Vec::new());
};
// `open`, not `discover`: only a checkout rooted at the tree counts.
let repo = Repository::open(root).ok();
let submodules = parse(&text);
let paths = submodules.iter().filter_map(|s| s.path.clone()).collect();
let pins = submodules
.into_iter()
.map(|s| LayerPin {
commit: repo
.as_ref()
.zip(s.path.as_deref())
.and_then(|(repo, path)| gitlink(repo, path)),
branch: s.branch.as_deref().and_then(clean_ref),
url: s.url,
name: s.name,
source: PinSource::GitSubmodule,
file: GITMODULES.to_string(),
})
.collect();
(pins, paths)
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use crate::pipeline::recipe_lint::tests::tree;
const GITMODULES_TEXT: &str = "# layers\n[submodule \"poky\"]\n\tpath = layers/poky\n\t\
url = https://git.yoctoproject.org/poky\n\tbranch = kirkstone\n\
[core]\n\tpath = not-a-submodule\n\
[submodule \"meta-oe\"]\n\tpath = layers/meta-openembedded\n\t\
url = \"https://github.com/openembedded/meta-openembedded.git\"\n";
#[test]
fn gitmodules_sections_are_read() {
let found = parse(GITMODULES_TEXT);
assert_eq!(found.len(), 2);
assert_eq!(found[0].name, "poky");
assert_eq!(found[0].path.as_deref(), Some("layers/poky"));
assert_eq!(found[0].branch.as_deref(), Some("kirkstone"));
assert_eq!(found[1].name, "meta-oe");
assert_eq!(
found[1].url.as_deref(),
Some("https://github.com/openembedded/meta-openembedded.git")
);
assert_eq!(found[1].branch, None);
}
#[test]
fn an_archive_has_submodules_without_commits() {
let t = tree(&[(GITMODULES, GITMODULES_TEXT)]);
let (pins, paths) = pins(&t.0);
assert_eq!(paths, ["layers/poky", "layers/meta-openembedded"]);
assert_eq!(pins[0].source, PinSource::GitSubmodule);
assert_eq!(pins[0].file, ".gitmodules");
assert_eq!(pins[0].commit, None);
}
#[test]
fn a_checkout_pins_each_submodule_to_its_gitlink_commit() {
let t = tree(&[(GITMODULES, GITMODULES_TEXT), ("README", "x")]);
let repo = Repository::init(&t.0).expect("init");
let sig = git2::Signature::now("t", "t@example.com").expect("sig");
// A commit of the layer repository the gitlink points at.
let pinned = git2::Oid::from_str("0123456789abcdef0123456789abcdef01234567").expect("oid");
let mut index = repo.index().expect("index");
index.add_path(Path::new(GITMODULES)).expect("add");
index.add_path(Path::new("README")).expect("add");
index
.add(&git2::IndexEntry {
ctime: git2::IndexTime::new(0, 0),
mtime: git2::IndexTime::new(0, 0),
dev: 0,
ino: 0,
mode: 0o160000,
uid: 0,
gid: 0,
file_size: 0,
id: pinned,
flags: 0,
flags_extended: 0,
path: b"layers/poky".to_vec(),
})
.expect("gitlink");
let tree_id = index.write_tree().expect("tree");
let commit_tree = repo.find_tree(tree_id).expect("tree");
repo.commit(Some("HEAD"), &sig, &sig, "layers", &commit_tree, &[])
.expect("commit");
let (pins, _) = pins(&t.0);
assert_eq!(pins[0].commit.as_deref(), Some(pinned.to_string().as_str()));
assert_eq!(pins[0].branch.as_deref(), Some("kirkstone"));
// meta-oe has no gitlink in HEAD.
assert_eq!(pins[1].commit, None);
}
}
@@ -0,0 +1,493 @@
//! kas project files as layer pins.
//!
//! A kas file (`kas*.yml`, `kas/*.yml`) lists the repositories a build
//! fetches under `repos:`, each with its `url`, `branch`, `tag`, `commit` or
//! the older `refspec`. `header.includes` merges other kas files in before the
//! file's own settings; only local includes are read: an include from another
//! repository (`repo:` / `file:`) or a URL is named, never fetched. A lock
//! file beside a kas file (`kas.lock.yml`) pins commits under
//! `overrides.repos`.
use std::collections::{BTreeSet, HashMap};
use std::path::Path;
use compliance_core::models::{LayerPin, PinSource};
use yaml_rust2::parser::{Event, Parser};
use yaml_rust2::{Yaml, YamlLoader};
use super::{clean_ref, is_commit, local_include, read_small};
/// Most YAML nodes a kas file may expand to, aliases included: a file of
/// nested aliases ("billion laughs") is refused instead of expanded.
const MAX_NODES: usize = 100_000;
/// Whether `rel` (relative to the tree) names a kas project file: `kas*.yml`
/// anywhere, or any YAML file in a `kas/` directory. Lock files are read with
/// the file they lock, not on their own.
pub(crate) fn is_kas_file(rel: &str) -> bool {
let name = rel.rsplit('/').next().unwrap_or(rel);
let yaml = name.ends_with(".yml") || name.ends_with(".yaml");
let in_kas_dir = rel.split('/').rev().nth(1) == Some("kas");
yaml && !is_lock_file(name) && (name.starts_with("kas") || in_kas_dir)
}
fn is_lock_file(name: &str) -> bool {
name.ends_with(".lock.yml") || name.ends_with(".lock.yaml")
}
/// The lock file kas reads beside `rel` (`x.yml` -> `x.lock.yml`).
fn lock_file(rel: &str) -> Option<String> {
let (stem, ext) = rel.rsplit_once('.')?;
Some(format!("{stem}.lock.{ext}"))
}
/// How many nodes the YAML `text` expands to with its aliases resolved;
/// `None` past [`MAX_NODES`] or when it does not parse.
fn expanded_nodes(text: &str) -> Option<usize> {
let mut parser = Parser::new_from_str(text);
// Open collections: (anchor id, nodes so far).
let mut open: Vec<(usize, usize)> = Vec::new();
let mut anchors: HashMap<usize, usize> = HashMap::new();
let mut total = 0usize;
loop {
let (event, _) = parser.next_token().ok()?;
let done = match event {
Event::StreamEnd => break,
Event::SequenceStart(anchor, _) | Event::MappingStart(anchor, _) => {
open.push((anchor, 1));
None
}
Event::SequenceEnd | Event::MappingEnd => {
let (anchor, nodes) = open.pop()?;
if anchor > 0 {
anchors.insert(anchor, nodes);
}
Some(nodes)
}
Event::Scalar(_, _, anchor, _) => {
if anchor > 0 {
anchors.insert(anchor, 1);
}
Some(1)
}
Event::Alias(anchor) => Some(anchors.get(&anchor).copied().unwrap_or(1)),
_ => None,
};
if let Some(nodes) = done {
match open.last_mut() {
Some((_, parent)) => *parent = parent.saturating_add(nodes),
None => total = total.saturating_add(nodes),
}
let pending: usize = open.iter().map(|(_, n)| *n).sum();
if total.saturating_add(pending) > MAX_NODES {
return None;
}
}
}
Some(total)
}
/// The kas file `rel` under `root` as YAML: `None` when it is missing, too
/// large, not YAML, expands too far, or has no `header` (not a kas file).
fn load(root: &Path, rel: &str) -> Option<Yaml> {
let text = read_small(&root.join(rel))?;
expanded_nodes(&text)?;
let doc = YamlLoader::load_from_str(&text).ok()?.into_iter().next()?;
(!doc["header"].is_badvalue()).then_some(doc)
}
/// A repository entry as the merged kas files describe it.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct Repo {
url: Option<String>,
branch: Option<String>,
tag: Option<String>,
refspec: Option<String>,
commit: Option<String>,
/// The last file that set any of it.
file: String,
}
/// The repositories of one kas configuration, in the order they first
/// appear, and the default branch.
#[derive(Debug, Default)]
struct Merged {
repos: Vec<(String, Repo)>,
default_branch: Option<String>,
}
impl Merged {
fn repo(&mut self, name: &str) -> &mut Repo {
let index = match self.repos.iter().position(|(n, _)| n == name) {
Some(index) => index,
None => {
self.repos.push((name.to_string(), Repo::default()));
self.repos.len() - 1
}
};
&mut self.repos[index].1
}
/// Lay `doc` (the kas file `file`) over what is merged so far: its
/// settings override the included files'.
fn apply(&mut self, doc: &Yaml, file: &str) {
let text = |y: &Yaml| match y {
Yaml::String(s) => Some(s.clone()),
Yaml::Integer(i) => Some(i.to_string()),
Yaml::Real(r) => Some(r.clone()),
_ => None,
};
let defaults = &doc["defaults"]["repos"];
if let Some(branch) = text(&defaults["branch"]).or_else(|| text(&defaults["refspec"])) {
self.default_branch = Some(branch);
}
if let Some(repos) = doc["repos"].as_hash() {
for (key, value) in repos {
let Some(name) = text(key) else { continue };
let repo = self.repo(&name);
repo.file = file.to_string();
for (field, slot) in [
("url", &mut repo.url),
("branch", &mut repo.branch),
("tag", &mut repo.tag),
("refspec", &mut repo.refspec),
("commit", &mut repo.commit),
] {
if let Some(v) = text(&value[field]) {
*slot = Some(v);
}
}
}
}
if let Some(overrides) = doc["overrides"]["repos"].as_hash() {
for (key, value) in overrides {
let (Some(name), Some(commit)) = (text(key), text(&value["commit"])) else {
continue;
};
let repo = self.repo(&name);
repo.commit = Some(commit);
repo.file = file.to_string();
}
}
}
/// The pins of the repositories fetched from elsewhere (with a `url`).
fn pins(self) -> Vec<LayerPin> {
let default_branch = self.default_branch;
self.repos
.into_iter()
.filter_map(|(name, repo)| {
let url = repo.url?;
// A refspec may be a commit (old kas files) or a branch.
let refspec_commit = repo.refspec.clone().filter(|r| is_commit(r));
let named = repo
.branch
.or(repo.tag)
.or(repo.refspec.filter(|r| !is_commit(r)))
.or(default_branch.clone());
Some(LayerPin {
name,
source: PinSource::Kas,
file: repo.file,
url: Some(url),
branch: named.as_deref().and_then(clean_ref),
commit: repo.commit.or(refspec_commit),
})
})
.collect()
}
}
/// What the kas files of a tree pin.
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct KasPins {
pub pins: Vec<LayerPin>,
/// Includes that were not read (remote ones, missing ones), as written.
pub unread_includes: BTreeSet<String>,
}
/// Reads kas files and their includes, each file once.
struct Reader<'a> {
root: &'a Path,
docs: HashMap<String, Option<Yaml>>,
unread: BTreeSet<String>,
/// Every file merged into a configuration so far.
visited: BTreeSet<String>,
}
impl Reader<'_> {
fn doc(&mut self, rel: &str) -> Option<Yaml> {
let root = self.root;
self.docs
.entry(rel.to_string())
.or_insert_with(|| load(root, rel))
.clone()
}
/// The local files `doc` (the kas file `rel`) includes, in order; remote
/// and unresolvable ones are recorded as unread.
fn includes(&mut self, rel: &str, doc: &Yaml) -> Vec<String> {
let Some(list) = doc["header"]["includes"].as_vec() else {
return Vec::new();
};
let mut out = Vec::new();
for include in list {
match include {
Yaml::String(path) if path.contains("://") => {
self.unread.insert(path.clone());
}
Yaml::String(path) => match local_include(self.root, rel, path) {
Some(found) => out.push(found),
None => {
self.unread.insert(path.clone());
}
},
// `repo:` + `file:`: a file in another repository.
Yaml::Hash(_) => {
let repo = include["repo"].as_str().unwrap_or("?");
let file = include["file"].as_str().unwrap_or("?");
self.unread.insert(format!("{repo}:{file}"));
}
_ => {}
}
}
out
}
/// Merge `rel` with everything it includes into `merged`; `stack` holds
/// the files being read, so an include cycle ends.
fn merge(&mut self, rel: &str, merged: &mut Merged, stack: &mut Vec<String>) {
if stack.iter().any(|s| s == rel) {
return;
}
let Some(doc) = self.doc(rel) else {
return;
};
stack.push(rel.to_string());
self.visited.insert(rel.to_string());
for include in self.includes(rel, &doc) {
if self.doc(&include).is_some() {
self.merge(&include, merged, stack);
} else if !stack.contains(&include) {
self.unread.insert(include);
}
}
merged.apply(&doc, rel);
stack.pop();
}
}
/// The pins of the kas files `files` (relative to `root`). Each file no other
/// one includes is a configuration of its own; a pin several of them share
/// is listed once.
pub(crate) fn read(root: &Path, files: &[String]) -> KasPins {
let mut reader = Reader {
root,
docs: HashMap::new(),
unread: BTreeSet::new(),
visited: BTreeSet::new(),
};
let mut included: BTreeSet<String> = BTreeSet::new();
for file in files {
if let Some(doc) = reader.doc(file) {
included.extend(reader.includes(file, &doc));
}
}
let mut pins: Vec<LayerPin> = Vec::new();
// The files no other one includes first; then any left unread, which only
// an include cycle leaves.
let order = files
.iter()
.filter(|f| !included.contains(*f))
.chain(files.iter().filter(|f| included.contains(*f)));
for file in order {
if reader.visited.contains(file) || reader.doc(file).is_none() {
continue;
}
let mut merged = Merged::default();
reader.merge(file, &mut merged, &mut Vec::new());
if let Some(lock) = lock_file(file).filter(|l| root.join(l).is_file()) {
if let Some(doc) = load(root, &lock) {
merged.apply(&doc, &lock);
}
}
for pin in merged.pins() {
if !pins.contains(&pin) {
pins.push(pin);
}
}
}
KasPins {
pins,
unread_includes: reader.unread,
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use crate::pipeline::recipe_lint::tests::tree;
const SHA: &str = "4a2d3b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a";
#[test]
fn kas_files_are_recognised_by_name_and_directory() {
assert!(is_kas_file("kas.yml"));
assert!(is_kas_file("kas-pump.yaml"));
assert!(is_kas_file("ci/kas/machine.yml"));
assert!(!is_kas_file("kas.lock.yml"));
assert!(!is_kas_file("docker-compose.yml"));
assert!(!is_kas_file("kas/readme.md"));
}
#[test]
fn includes_are_merged_and_the_including_file_wins() {
let t = tree(&[
(
"kas.yml",
&format!(
"header:\n version: 14\n includes:\n - kas/common.yml\n \
- repo: meta-vendor\n file: kas/vendor.yml\n \
- https://example.com/remote.yml\n - kas/missing.yml\n\
repos:\n poky:\n commit: {SHA}\n meta-pump:\n"
),
),
(
"kas/common.yml",
"header:\n version: 14\ndefaults:\n repos:\n branch: kirkstone\n\
repos:\n poky:\n url: https://git.yoctoproject.org/poky\n \
branch: dunfell\n meta-openembedded:\n \
url: https://github.com/openembedded/meta-openembedded\n",
),
]);
let files = vec!["kas.yml".to_string(), "kas/common.yml".to_string()];
let read = read(&t.0, &files);
assert_eq!(read.pins.len(), 2, "{:?}", read.pins);
let poky = &read.pins[0];
assert_eq!(poky.name, "poky");
assert_eq!(
poky.url.as_deref(),
Some("https://git.yoctoproject.org/poky")
);
assert_eq!(poky.branch.as_deref(), Some("dunfell"));
assert_eq!(poky.commit.as_deref(), Some(SHA));
assert_eq!(poky.file, "kas.yml");
// The default branch fills in, and the tree's own layer (no url) is
// not a pin.
assert_eq!(read.pins[1].branch.as_deref(), Some("kirkstone"));
assert_eq!(read.pins[1].file, "kas/common.yml");
assert_eq!(
read.unread_includes.iter().collect::<Vec<_>>(),
[
"https://example.com/remote.yml",
"kas/missing.yml",
"meta-vendor:kas/vendor.yml"
]
);
}
#[test]
fn an_include_cycle_ends() {
let t = tree(&[
(
"kas/a.yml",
"header:\n version: 14\n includes:\n - kas/b.yml\n\
repos:\n poky:\n url: https://git.yoctoproject.org/poky\n",
),
(
"kas/b.yml",
"header:\n version: 14\n includes:\n - kas/a.yml\n\
repos:\n poky:\n branch: scarthgap\n",
),
(
"kas-top.yml",
"header:\n version: 14\n includes:\n - kas/a.yml\n",
),
]);
let files: Vec<String> = ["kas-top.yml", "kas/a.yml", "kas/b.yml"]
.map(String::from)
.to_vec();
let read = read(&t.0, &files);
assert_eq!(read.pins.len(), 1);
assert_eq!(read.pins[0].branch.as_deref(), Some("scarthgap"));
assert!(read.unread_includes.is_empty());
}
#[test]
fn files_that_only_include_each_other_are_still_read_once() {
let t = tree(&[
(
"kas/a.yml",
"header:\n version: 14\n includes:\n - kas/b.yml\n\
repos:\n poky:\n url: https://git.yoctoproject.org/poky\n",
),
(
"kas/b.yml",
"header:\n version: 14\n includes:\n - kas/a.yml\n",
),
]);
let files: Vec<String> = ["kas/a.yml", "kas/b.yml"].map(String::from).to_vec();
assert_eq!(read(&t.0, &files).pins.len(), 1);
}
#[test]
fn an_include_leaving_the_tree_is_not_read() {
let t = tree(&[(
"kas.yml",
"header:\n version: 14\n includes:\n - ../../etc/kas.yml\n",
)]);
let read = read(&t.0, &["kas.yml".to_string()]);
assert!(read.pins.is_empty());
assert!(read.unread_includes.contains("../../etc/kas.yml"));
}
#[test]
fn a_lock_file_pins_the_commits_and_a_refspec_may_be_one() {
let t = tree(&[
(
"kas.yml",
&format!(
"header:\n version: 8\nrepos:\n poky:\n \
url: https://git.yoctoproject.org/poky\n refspec: refs/heads/kirkstone\n \
meta-oe:\n url: https://github.com/openembedded/meta-openembedded\n \
refspec: {SHA}\n"
),
),
(
"kas.lock.yml",
&format!("header:\n version: 14\noverrides:\n repos:\n poky:\n commit: {SHA}\n"),
),
]);
let read = read(&t.0, &["kas.yml".to_string()]);
assert_eq!(read.pins[0].branch.as_deref(), Some("kirkstone"));
assert_eq!(read.pins[0].commit.as_deref(), Some(SHA));
assert_eq!(read.pins[0].file, "kas.lock.yml");
assert_eq!(read.pins[1].branch, None);
assert_eq!(read.pins[1].commit.as_deref(), Some(SHA));
}
#[test]
fn yaml_without_a_header_or_with_an_alias_bomb_is_not_read() {
let mut bomb =
String::from("header:\n version: 14\na: &a [x, x, x, x, x, x, x, x, x, x]\n");
let mut previous = 'a';
for name in ['b', 'c', 'd', 'e', 'f', 'g'] {
bomb.push_str(&format!(
"{name}: &{name} [*{previous}, *{previous}, *{previous}, *{previous}, \
*{previous}, *{previous}, *{previous}, *{previous}, *{previous}, *{previous}]\n"
));
previous = name;
}
let t = tree(&[
("kas.yml", bomb.as_str()),
(
"kas-plain.yml",
"repos:\n poky:\n url: https://x/poky\n",
),
]);
assert!(load(&t.0, "kas.yml").is_none());
assert!(load(&t.0, "kas-plain.yml").is_none());
assert_eq!(expanded_nodes("a: &a [1, 2]\nb: *a\n"), Some(9));
}
}
@@ -0,0 +1,298 @@
//! `repo` tool manifests as layer pins.
//!
//! A manifest (`default.xml` and the files it includes) names remotes
//! (`<remote name fetch revision>`), a default (`<default remote revision>`)
//! and the projects to check out (`<project name path remote revision
//! upstream>`). A project's URL is its remote's `fetch` and its name; its
//! revision is its own, else the remote's, else the default's. A revision may
//! be a commit, then `upstream` (or `dest-branch`) names the branch.
//! `<include name>` is read from the manifest's own directory, never fetched.
use std::collections::BTreeSet;
use std::path::Path;
use compliance_core::models::{LayerPin, PinSource};
use super::{clean_ref, is_commit, local_include, read_small};
/// Most manifest files one configuration may include.
const MAX_FILES: usize = 32;
/// Whether `text` is a `repo` manifest: a `<manifest>` root with projects or
/// includes (an Android app manifest is a `<manifest>` without either).
fn is_manifest(doc: &roxmltree::Document<'_>) -> bool {
let root = doc.root_element();
root.has_tag_name("manifest")
&& root
.children()
.any(|c| c.has_tag_name("project") || c.has_tag_name("include"))
}
/// One `<project>`, with what it inherits not yet filled in.
#[derive(Debug, Clone)]
struct Project {
name: String,
remote: Option<String>,
revision: Option<String>,
upstream: Option<String>,
file: String,
}
/// Everything one manifest configuration declares, includes merged in
/// document order.
#[derive(Debug, Default)]
struct Declared {
/// name -> (fetch, revision)
remotes: Vec<(String, String, Option<String>)>,
default_remote: Option<String>,
default_revision: Option<String>,
projects: Vec<Project>,
/// The files read, includes too.
files: Vec<String>,
}
/// Read the manifest `rel` under `root` and the files it includes into
/// `declared`; `stack` ends include cycles, `unread` collects includes that
/// could not be read.
fn declare(
root: &Path,
rel: &str,
declared: &mut Declared,
stack: &mut Vec<String>,
unread: &mut BTreeSet<String>,
) {
if stack.iter().any(|s| s == rel) || declared.files.len() >= MAX_FILES {
return;
}
let Some(text) = read_small(&root.join(rel)) else {
unread.insert(rel.to_string());
return;
};
// roxmltree refuses a DTD by default, so no entity can expand.
let Ok(doc) = roxmltree::Document::parse(&text) else {
unread.insert(rel.to_string());
return;
};
declared.files.push(rel.to_string());
stack.push(rel.to_string());
let attr = |n: &roxmltree::Node<'_, '_>, a: &str| n.attribute(a).map(str::to_string);
for node in doc.root_element().children().filter(|n| n.is_element()) {
match node.tag_name().name() {
"remote" => {
if let (Some(name), Some(fetch)) = (attr(&node, "name"), attr(&node, "fetch")) {
declared
.remotes
.push((name, fetch, attr(&node, "revision")));
}
}
"default" => {
declared.default_remote = attr(&node, "remote").or(declared.default_remote.take());
declared.default_revision =
attr(&node, "revision").or(declared.default_revision.take());
}
"project" => {
if let Some(name) = attr(&node, "name") {
declared.projects.push(Project {
name,
remote: attr(&node, "remote"),
revision: attr(&node, "revision"),
upstream: attr(&node, "upstream").or_else(|| attr(&node, "dest-branch")),
file: rel.to_string(),
});
}
}
"extend-project" => {
let name = attr(&node, "name");
for project in declared
.projects
.iter_mut()
.filter(|p| Some(&p.name) == name.as_ref())
{
if let Some(revision) = attr(&node, "revision") {
project.revision = Some(revision);
project.file = rel.to_string();
}
if let Some(remote) = attr(&node, "remote") {
project.remote = Some(remote);
}
}
}
"remove-project" => {
let name = attr(&node, "name");
declared.projects.retain(|p| Some(&p.name) != name.as_ref());
}
"include" => {
let Some(name) = attr(&node, "name") else {
continue;
};
match local_include(root, rel, &name) {
Some(found) => declare(root, &found, declared, stack, unread),
None => {
unread.insert(name);
}
}
}
_ => {}
}
}
stack.pop();
}
impl Declared {
fn pins(self) -> Vec<LayerPin> {
let remote = |name: Option<&String>| {
name.and_then(|n| self.remotes.iter().rev().find(|(r, _, _)| r == n))
};
self.projects
.iter()
.map(|p| {
let remote = remote(p.remote.as_ref().or(self.default_remote.as_ref()));
let revision = p
.revision
.clone()
.or_else(|| remote.and_then(|(_, _, r)| r.clone()))
.or_else(|| self.default_revision.clone());
let (branch, commit) = match revision {
Some(r) if is_commit(&r) => (p.upstream.clone(), Some(r)),
other => (other, None),
};
LayerPin {
name: p.name.clone(),
source: PinSource::RepoManifest,
file: p.file.clone(),
url: remote
.map(|(_, fetch, _)| format!("{}/{}", fetch.trim_end_matches('/'), p.name)),
branch: branch.as_deref().and_then(clean_ref),
commit,
}
})
.collect()
}
}
/// What the manifests among `files` (XML files relative to `root`) pin, and
/// the includes that were not read. A manifest another one includes is read
/// with it, not on its own.
pub(crate) fn read(root: &Path, files: &[String]) -> (Vec<LayerPin>, BTreeSet<String>) {
let mut manifests: Vec<String> = Vec::new();
let mut included: BTreeSet<String> = BTreeSet::new();
for file in files {
let Some(text) = read_small(&root.join(file)) else {
continue;
};
let Ok(doc) = roxmltree::Document::parse(&text) else {
continue;
};
if !is_manifest(&doc) {
continue;
}
manifests.push(file.clone());
included.extend(
doc.root_element()
.children()
.filter(|n| n.has_tag_name("include"))
.filter_map(|n| n.attribute("name"))
.filter_map(|name| local_include(root, file, name)),
);
}
let mut pins: Vec<LayerPin> = Vec::new();
let mut unread = BTreeSet::new();
let mut visited: BTreeSet<String> = BTreeSet::new();
// The manifests no other one includes first; then any left unread,
// which only an include cycle leaves.
let order = manifests
.iter()
.filter(|m| !included.contains(*m))
.chain(manifests.iter().filter(|m| included.contains(*m)));
for manifest in order {
if visited.contains(manifest) {
continue;
}
let mut declared = Declared::default();
declare(root, manifest, &mut declared, &mut Vec::new(), &mut unread);
visited.extend(declared.files.iter().cloned());
for pin in declared.pins() {
if !pins.contains(&pin) {
pins.push(pin);
}
}
}
(pins, unread)
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use crate::pipeline::recipe_lint::tests::tree;
const SHA: &str = "4a2d3b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a";
#[test]
fn projects_inherit_remote_and_revision_and_includes_are_read() {
let t = tree(&[
(
"manifests/default.xml",
&format!(
"<?xml version=\"1.0\"?>\n<manifest>\n\
<remote name=\"yocto\" fetch=\"https://git.yoctoproject.org/\"/>\n\
<remote name=\"oe\" fetch=\"https://github.com/openembedded\" \
revision=\"refs/heads/scarthgap\"/>\n\
<default remote=\"yocto\" revision=\"kirkstone\"/>\n\
<project name=\"poky\" path=\"layers/poky\" revision=\"{SHA}\" \
upstream=\"refs/heads/kirkstone\"/>\n\
<project name=\"meta-openembedded\" remote=\"oe\"/>\n\
<project name=\"meta-old\"/>\n\
<remove-project name=\"meta-old\"/>\n\
<include name=\"bsp.xml\"/>\n\
<include name=\"missing.xml\"/>\n</manifest>\n"
),
),
(
"manifests/bsp.xml",
"<manifest>\n<project name=\"meta-arm\" revision=\"refs/tags/yocto-4.0.3\"/>\n\
<include name=\"default.xml\"/>\n</manifest>\n",
),
(
"app/AndroidManifest.xml",
"<manifest package=\"x\"><application/></manifest>",
),
]);
let files: Vec<String> = [
"manifests/default.xml",
"manifests/bsp.xml",
"app/AndroidManifest.xml",
]
.map(String::from)
.to_vec();
let (pins, unread) = read(&t.0, &files);
let names: Vec<&str> = pins.iter().map(|p| p.name.as_str()).collect();
assert_eq!(names, ["poky", "meta-openembedded", "meta-arm"]);
assert_eq!(
pins[0].url.as_deref(),
Some("https://git.yoctoproject.org/poky")
);
assert_eq!(pins[0].commit.as_deref(), Some(SHA));
assert_eq!(pins[0].branch.as_deref(), Some("kirkstone"));
assert_eq!(pins[0].source, PinSource::RepoManifest);
assert_eq!(
pins[1].url.as_deref(),
Some("https://github.com/openembedded/meta-openembedded")
);
assert_eq!(pins[1].branch.as_deref(), Some("scarthgap"));
assert_eq!(pins[2].branch.as_deref(), Some("yocto-4.0.3"));
assert_eq!(pins[2].file, "manifests/bsp.xml");
assert_eq!(unread.into_iter().collect::<Vec<_>>(), ["missing.xml"]);
}
#[test]
fn a_manifest_with_a_dtd_is_not_read() {
let t = tree(&[(
"default.xml",
"<?xml version=\"1.0\"?>\n<!DOCTYPE manifest [<!ENTITY a \"aaaa\">]>\n\
<manifest><project name=\"&a;\"/></manifest>\n",
)]);
let (pins, _) = read(&t.0, &["default.xml".to_string()]);
assert!(pins.is_empty());
}
}
@@ -0,0 +1,281 @@
//! Layer pins of a Yocto / OpenEmbedded layer tree and the release they make
//! up (tier 1: nothing is fetched, nothing is built).
//!
//! The layers a build uses are pinned in one of three ways, all read here:
//!
//! - **kas** project files ([`kas`]), with their local includes;
//! - **`repo` manifests** ([`manifest`]), with their local includes;
//! - **git submodules** ([`gitmodules`]), with the commit the tree records.
//!
//! From the pins, or else from `LAYERSERIES_COMPAT`, [`release`] reads the
//! Yocto release and reports when its support has ended or ends soon. The
//! pins are stored on the target, where tier 2 (fetching the upstream layers
//! at their pins, importing the build's SPDX) will start from.
pub mod gitmodules;
pub mod kas;
pub mod manifest;
pub mod release;
use std::collections::BTreeSet;
use std::path::{Component, Path, PathBuf};
use compliance_core::models::LayerPins;
use crate::pipeline::recipe_lint;
/// The stage id an unknown release is recorded under.
pub const STAGE: &str = "yocto_release";
/// The largest kas file, manifest or `.gitmodules` that is read.
const MAX_FILE_BYTES: u64 = 1 << 20;
/// How deep kas files and manifests are looked for.
const MAX_DEPTH: usize = 4;
/// Directories never searched: version control, build output, downloads.
const SKIPPED_DIRS: &[&str] = &[".git", "build", "downloads", "sstate-cache", "node_modules"];
/// The text of the regular file at `path` (not a symlink), when it is at
/// most [`MAX_FILE_BYTES`].
pub(crate) fn read_small(path: &Path) -> Option<String> {
let meta = std::fs::symlink_metadata(path).ok()?;
if !meta.is_file() || meta.len() > MAX_FILE_BYTES {
return None;
}
std::fs::read_to_string(path).ok()
}
/// Whether `value` is a full git commit id (SHA-1 or SHA-256).
pub(crate) fn is_commit(value: &str) -> bool {
matches!(value.len(), 40 | 64) && value.bytes().all(|b| b.is_ascii_hexdigit())
}
/// A branch or tag as shown: `refs/heads/` and `refs/tags/` dropped, `None`
/// when empty.
pub(crate) fn clean_ref(reference: &str) -> Option<String> {
let trimmed = reference.trim();
let name = trimmed
.strip_prefix("refs/heads/")
.or_else(|| trimmed.strip_prefix("refs/tags/"))
.unwrap_or(trimmed);
(!name.is_empty()).then(|| name.to_string())
}
/// `path` joined to `base` (relative to the tree) without leaving it;
/// `None` when a `..` climbs out.
fn inside(base: &Path, path: &str) -> Option<PathBuf> {
let mut out = PathBuf::new();
for part in base.join(path).components() {
match part {
Component::Normal(p) => out.push(p),
Component::CurDir => {}
Component::ParentDir => {
if !out.pop() {
return None;
}
}
Component::RootDir | Component::Prefix(_) => return None,
}
}
Some(out)
}
/// The local file an include `path` in `including` (both relative to the
/// tree under `root`) names: relative to the including file's directory,
/// else to the tree. `None` for a URL, a path leaving the tree, a symlink or
/// a missing file.
pub(crate) fn local_include(root: &Path, including: &str, path: &str) -> Option<String> {
if path.contains("://") || path.is_empty() {
return None;
}
let dir = Path::new(including).parent().unwrap_or(Path::new(""));
[dir, Path::new("")]
.into_iter()
.filter_map(|base| inside(base, path))
.find(|rel| std::fs::symlink_metadata(root.join(rel)).is_ok_and(|m| m.is_file()))
.map(|rel| rel.to_string_lossy().replace('\\', "/"))
}
/// The layer pins of the tree under `root` and the release they make up,
/// outside the `excluded` vendor directories. A submodule's own kas files
/// and manifests are its repository's, not the tree's, and are not read.
pub fn read(root: &Path, excluded: &[String]) -> LayerPins {
let (submodule_pins, submodule_paths) = gitmodules::pins(root);
let mut kas_files = Vec::new();
let mut xml_files = Vec::new();
let walk = walkdir::WalkDir::new(root)
.min_depth(1)
.max_depth(MAX_DEPTH)
.sort_by_file_name()
.into_iter()
.filter_entry(|e| {
let rel = recipe_lint::rel_path(root, e.path());
!(e.file_type().is_dir()
&& (SKIPPED_DIRS.contains(&e.file_name().to_string_lossy().as_ref())
|| excluded.contains(&rel)
|| submodule_paths.contains(&rel)))
})
.filter_map(Result::ok)
.filter(|e| e.file_type().is_file());
for entry in walk {
let rel = recipe_lint::rel_path(root, entry.path());
if kas::is_kas_file(&rel) {
kas_files.push(rel);
} else if rel.ends_with(".xml") {
xml_files.push(rel);
}
}
let kas = kas::read(root, &kas_files);
let (manifest_pins, manifest_unread) = manifest::read(root, &xml_files);
let pins: Vec<_> = kas
.pins
.into_iter()
.chain(manifest_pins)
.chain(submodule_pins)
.collect();
let layers = recipe_lint::layers(root, excluded);
let unread: BTreeSet<String> = kas
.unread_includes
.into_iter()
.chain(manifest_unread)
.collect();
LayerPins {
release: release::derive(&pins, &layers),
pins,
unread_includes: unread.into_iter().collect(),
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use crate::pipeline::recipe_lint::tests::tree;
use compliance_core::models::{PinSource, ReleaseBasis};
#[test]
fn refs_and_commits_are_recognised() {
assert_eq!(
clean_ref("refs/heads/kirkstone").as_deref(),
Some("kirkstone")
);
assert_eq!(
clean_ref("refs/tags/yocto-5.0.3").as_deref(),
Some("yocto-5.0.3")
);
assert_eq!(clean_ref(" "), None);
assert!(is_commit("4a2d3b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a"));
assert!(!is_commit("kirkstone"));
assert!(!is_commit("4a2d3b5"));
}
#[test]
fn includes_resolve_beside_the_file_then_from_the_root_and_never_outside() {
let t = tree(&[("kas/a.yml", ""), ("kas/b.yml", ""), ("common.yml", "")]);
assert_eq!(
local_include(&t.0, "kas/a.yml", "b.yml").as_deref(),
Some("kas/b.yml")
);
assert_eq!(
local_include(&t.0, "kas/a.yml", "kas/b.yml").as_deref(),
Some("kas/b.yml")
);
assert_eq!(
local_include(&t.0, "kas/a.yml", "../common.yml").as_deref(),
Some("common.yml")
);
assert_eq!(local_include(&t.0, "kas/a.yml", "../../x.yml"), None);
assert_eq!(local_include(&t.0, "kas/a.yml", "/etc/passwd"), None);
assert_eq!(local_include(&t.0, "kas/a.yml", "https://x/y.yml"), None);
assert_eq!(local_include(&t.0, "kas/a.yml", "missing.yml"), None);
}
#[test]
fn a_tree_pins_its_layers_and_the_pins_name_the_release() {
let t = tree(&[
(
"kas.yml",
"header:\n version: 14\nrepos:\n poky:\n \
url: https://git.yoctoproject.org/poky\n branch: dunfell\n \
commit: 4a2d3b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a\n",
),
(
".gitmodules",
"[submodule \"meta-vendor\"]\n\tpath = layers/meta-vendor\n\t\
url = https://git.example.com/meta-vendor.git\n",
),
// A submodule's own kas files are not the tree's.
(
"layers/meta-vendor/kas.yml",
"header:\n version: 14\nrepos:\n x:\n url: https://x/x\n",
),
(
"conf/layer.conf",
"BBFILE_COLLECTIONS += \"pump\"\nLAYERSERIES_COMPAT_pump = \"scarthgap\"\n",
),
("recipes-app/pump/pump_1.0.bb", ""),
]);
let read = read(&t.0, &[]);
let names: Vec<(&str, PinSource)> = read
.pins
.iter()
.map(|p| (p.name.as_str(), p.source))
.collect();
assert_eq!(
names,
[
("poky", PinSource::Kas),
("meta-vendor", PinSource::GitSubmodule)
]
);
let release = read.release.expect("release");
// The pin wins over the layer's LAYERSERIES_COMPAT.
assert_eq!(release.codename, "dunfell");
assert!(matches!(release.basis, ReleaseBasis::Pin { .. }));
}
#[test]
fn the_nightly_fixture_pins_dunfell_and_is_end_of_life() {
let root =
Path::new(env!("CARGO_MANIFEST_DIR")).join("../fixtures/nightly/firmware/yocto-layer");
let read = read(&root, &[]);
let pins: Vec<String> = read
.pins
.iter()
.map(|p| {
format!(
"{:?} {} {}@{}",
p.source,
p.name,
p.branch.as_deref().unwrap_or("-"),
p.commit.as_deref().unwrap_or("-")
)
})
.collect();
assert_eq!(
pins,
[
// Included files' repositories come first, as kas merges them.
"Kas meta-openembedded dunfell@-",
"Kas poky dunfell@0b1f2c3d4e5f60718293a4b5c6d7e8f901234567",
"GitSubmodule meta-security dunfell@-",
]
);
assert_eq!(read.unread_includes, ["meta-vendor:kas/vendor.yml"]);
let release = read.release.expect("release");
assert_eq!(release.codename, "dunfell");
let today = chrono::NaiveDate::from_ymd_opt(2026, 10, 9).expect("date");
let finding = release::finding("t", &release, today).expect("finding");
assert_eq!(finding.rule_id.as_deref(), Some(release::RULE_EOL));
assert_eq!(finding.file_path.as_deref(), Some("kas.yml"));
}
#[test]
fn a_tree_without_pins_or_compat_has_no_release() {
let t = tree(&[("recipes-app/pump/pump_1.0.bb", "")]);
let read = read(&t.0, &[]);
assert!(read.pins.is_empty());
assert_eq!(read.release, None);
}
}
@@ -0,0 +1,445 @@
//! The Yocto release a layer tree builds, its support period, and a finding
//! when that period is over or ends soon.
use chrono::NaiveDate;
use compliance_core::models::{
display_codename, soon_window, Finding, LayerPin, ReleaseBasis, ScanType, Severity, Support,
YoctoRelease,
};
use crate::pipeline::dedup;
use crate::pipeline::recipe_lint::Layer;
/// The scanner name of the support-status findings.
pub const SCANNER: &str = "yocto-release";
/// The rule of a release past its end of life.
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";
/// 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.
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)
}
/// The release a branch or tag names: a codename as one of its words
/// (`scarthgap`, `scarthgap-5.0.3`, `kirkstone-4.0.15`, `dunfell-23.0.10`),
/// or a `yocto-<version>` tag (`yocto-5.0.3`). `master` names none.
pub(crate) fn from_reference(reference: &str) -> Option<&'static ReleaseInfo> {
let lower = reference.to_ascii_lowercase();
if let Some(found) = lower
.split(|c: char| !c.is_ascii_alphanumeric())
.find_map(by_codename)
{
return Some(found);
}
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)
}
/// The newest of `codenames` the table knows.
fn newest<'a>(codenames: impl IntoIterator<Item = &'a String>) -> Option<&'static ReleaseInfo> {
codenames
.into_iter()
.filter_map(|c| by_codename(c))
.max_by_key(|r| r.released)
}
/// Whether `pin` is the repository `repo` (by its URL's last segment, else
/// its name).
fn pin_is(pin: &LayerPin, repo: &str) -> bool {
let tail = pin.url.as_deref().and_then(|url| {
url.trim_end_matches('/')
.rsplit(['/', ':'])
.next()
.map(|t| t.trim_end_matches(".git"))
});
tail.unwrap_or(&pin.name) == repo || pin.name == repo
}
/// The configuration file of `layer`, relative to the tree.
fn conf_of(layer: &Layer) -> String {
if layer.dir == "." {
"conf/layer.conf".to_string()
} else {
format!("{}/conf/layer.conf", layer.dir)
}
}
/// The release the tree builds, from the first of:
///
/// 1. the branch or tag of a Poky, OpenEmbedded-Core or meta-openembedded pin
/// (in that order): what the build fetches;
/// 2. `LAYERSERIES_COMPAT_core` of an OpenEmbedded-Core layer in the tree;
/// 3. the newest release every customer layer declares compatible in
/// `LAYERSERIES_COMPAT_*`: the build can use no newer one, and a layer
/// that also names older releases is not built on those for it (the
/// recipe lint reads the oldest instead, for the syntax it must accept).
///
/// `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.clone(),
version: info.version.clone(),
lts: info.lts,
end_of_life: info.end_of_life,
basis,
file,
};
for repo in RELEASE_REPOS {
for pin in pins.iter().filter(|p| pin_is(p, repo)) {
let Some(branch) = &pin.branch else { continue };
if let Some(info) = from_reference(branch) {
let basis = ReleaseBasis::Pin {
name: pin.name.clone(),
branch: branch.clone(),
};
return Some(make(info, basis, pin.file.clone()));
}
}
}
let core = layers
.iter()
.filter(|l| l.collections.iter().any(|c| c == "core"))
.find_map(|l| newest(&l.compat).map(|info| (info, conf_of(l))));
if let Some((info, file)) = core {
return Some(make(info, ReleaseBasis::CoreLayer, file));
}
let own: Vec<&Layer> = layers
.iter()
.filter(|l| !l.upstream && !l.compat.is_empty())
.collect();
let first = own.first()?;
let common = first
.compat
.iter()
.filter(|c| own.iter().all(|l| l.compat.contains(c)));
newest(common).map(|info| make(info, ReleaseBasis::LayerCompat, conf_of(first)))
}
/// 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()
.iter()
.filter(|r| r.lts && r.released <= today && r.end_of_life > horizon)
.max_by_key(|r| r.released)
}
/// What `basis` (in `file`) is, in words.
fn basis_text(basis: &ReleaseBasis, file: &str) -> String {
match basis {
ReleaseBasis::Pin { name, branch } => {
format!("the branch or tag \"{branch}\" that {file} pins {name} to")
}
ReleaseBasis::CoreLayer => {
format!("LAYERSERIES_COMPAT_core of the OpenEmbedded-Core layer ({file})")
}
ReleaseBasis::LayerCompat => format!(
"LAYERSERIES_COMPAT of your layers ({file}): the newest release they all declare"
),
}
}
/// The support-status finding of `repo_id` for `release` on `today`;
/// `None` while its end of life is not yet soon ([`soon_window`]).
pub(crate) fn finding(repo_id: &str, release: &YoctoRelease, today: NaiveDate) -> Option<Finding> {
let (rule, severity, title, status) = match release.support(today) {
Support::Supported => return None,
Support::Ended => (
RULE_EOL,
Severity::High,
"is end of life since",
"ended its support on",
),
Support::EndsSoon => (
RULE_EOL_SOON,
Severity::Medium,
"reaches end of life on",
"ends its support on",
),
};
let name = display_codename(&release.codename);
let lts = if release.lts { " LTS" } else { "" };
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}, 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): \
vulnerabilities are remediated without delay, including by security updates, over \
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!(
"Move the layers to the current long term support release, Yocto {} ({}), \
supported until {}: update the pins of Poky / OpenEmbedded-Core and the other \
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),
lts.version,
lts.end_of_life
),
_ => "Move the layers to a Yocto release that is supported for the product's support \
period, and backport security fixes until then."
.to_string(),
};
let fingerprint =
dedup::compute_fingerprint(&[repo_id, SCANNER, rule, &release.file, &release.codename]);
let mut finding = Finding::new(
repo_id.to_string(),
fingerprint,
SCANNER.to_string(),
ScanType::Sbom,
format!("Yocto {name} ({}) {title} {eol}", release.version),
description,
severity,
);
finding.rule_id = Some(rule.to_string());
finding.cwe = Some("CWE-1104".to_string());
finding.remediation = Some(remediation);
finding.file_path = Some(release.file.clone());
Some(finding)
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use compliance_core::models::PinSource;
fn date(y: i32, m: u32, d: u32) -> NaiveDate {
NaiveDate::from_ymd_opt(y, m, d).expect("date")
}
fn pin(name: &str, url: &str, branch: Option<&str>) -> LayerPin {
LayerPin {
name: name.into(),
source: PinSource::Kas,
file: "kas.yml".into(),
url: Some(url.into()),
branch: branch.map(str::to_string),
commit: None,
}
}
fn layer(dir: &str, collections: &[&str], compat: &[&str], upstream: bool) -> Layer {
Layer {
dir: dir.into(),
release: None,
upstream,
collections: collections.iter().map(|c| c.to_string()).collect(),
compat: compat.iter().map(|c| c.to_string()).collect(),
files: Vec::new(),
}
}
#[test]
fn the_table_is_ordered_and_names_the_required_releases() {
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",
"mickledore",
"nanbield",
"scarthgap",
"styhead",
"walnascar",
"whinlatter",
"wrynose",
] {
assert!(by_codename(codename).is_some(), "{codename}");
}
}
#[test]
fn branches_and_tags_name_their_release() {
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"));
assert_eq!(codename("refs/tags/yocto-4.0.15"), Some("kirkstone"));
assert_eq!(codename("kirkstone-4.0.15"), Some("kirkstone"));
assert_eq!(codename("dunfell-23.0.10"), Some("dunfell"));
assert_eq!(codename("Mickledore"), Some("mickledore"));
assert_eq!(codename("master"), None);
assert_eq!(codename("main"), None);
assert_eq!(codename("yocto-9.9"), None);
assert_eq!(codename("blacksail"), None);
}
#[test]
fn poky_pins_win_over_meta_openembedded_and_layer_compat() {
let pins = [
pin(
"meta-oe",
"https://github.com/openembedded/meta-openembedded.git",
Some("scarthgap"),
),
pin("poky", "https://git.yoctoproject.org/poky", Some("dunfell")),
];
let layers = [layer(".", &["pump"], &["scarthgap"], false)];
let release = derive(&pins, &layers).expect("release");
assert_eq!(release.codename, "dunfell");
assert_eq!(
release.basis,
ReleaseBasis::Pin {
name: "poky".into(),
branch: "dunfell".into()
}
);
assert_eq!(release.file, "kas.yml");
// meta-openembedded speaks when poky names no release.
let pins = [
pin("poky", "https://git.yoctoproject.org/poky", None),
pin(
"meta-oe",
"git@github.com:openembedded/meta-openembedded.git",
Some("kirkstone"),
),
];
assert_eq!(
derive(&pins, &layers).expect("release").codename,
"kirkstone"
);
}
#[test]
fn without_pins_the_core_layer_then_the_customer_layers_decide() {
let core = layer("poky/meta", &["core"], &["nanbield"], true);
let own = layer("meta-pump", &["pump"], &["kirkstone", "scarthgap"], false);
let release = derive(&[], &[core, own.clone()]).expect("release");
assert_eq!(release.codename, "nanbield");
assert_eq!(release.basis, ReleaseBasis::CoreLayer);
assert_eq!(release.file, "poky/meta/conf/layer.conf");
// The newest release every own layer declares.
let other = layer(
"meta-ui",
&["ui"],
&["kirkstone", "scarthgap", "wrynose"],
false,
);
let release = derive(&[], &[own.clone(), other]).expect("release");
assert_eq!(release.codename, "scarthgap");
assert_eq!(release.basis, ReleaseBasis::LayerCompat);
assert_eq!(release.file, "meta-pump/conf/layer.conf");
// Layers with nothing in common, or no compat at all: unknown.
let apart = layer("meta-ui", &["ui"], &["wrynose"], false);
assert_eq!(derive(&[], &[own, apart]), None);
assert_eq!(derive(&[], &[layer(".", &["x"], &[], false)]), None);
}
fn release_of(codename: &str) -> YoctoRelease {
let info = by_codename(codename).expect("known");
YoctoRelease {
codename: codename.into(),
version: info.version.clone(),
lts: info.lts,
end_of_life: info.end_of_life,
basis: ReleaseBasis::Pin {
name: "poky".into(),
branch: codename.into(),
},
file: "kas.yml".into(),
}
}
#[test]
fn an_ended_release_is_a_high_finding_naming_the_date_source_and_current_lts() {
let today = date(2026, 10, 9);
let f = finding("t1", &release_of("dunfell"), today).expect("finding");
assert_eq!(f.scanner, SCANNER);
assert_eq!(f.rule_id.as_deref(), Some(RULE_EOL));
assert_eq!(f.severity, Severity::High);
assert_eq!(f.scan_type, ScanType::Sbom);
assert_eq!(
f.title,
"Yocto Dunfell (3.1) is end of life since 2024-04-30"
);
assert!(f.description.contains("Yocto Dunfell (3.1 LTS)"));
assert!(f
.description
.contains("\"dunfell\" that kas.yml pins poky to"));
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"));
assert_eq!(f.cwe.as_deref(), Some("CWE-1104"));
// Wrynose is the newest LTS released by then.
assert!(f
.remediation
.as_deref()
.expect("remediation")
.contains("Yocto Wrynose (6.0), supported until 2030-04-30"));
}
#[test]
fn a_release_ending_soon_is_medium_and_a_supported_one_none() {
let today = date(2026, 3, 1);
let f = finding("t1", &release_of("kirkstone"), today).expect("finding");
assert_eq!(f.rule_id.as_deref(), Some(RULE_EOL_SOON));
assert_eq!(f.severity, Severity::Medium);
assert_eq!(
f.title,
"Yocto Kirkstone (4.0) reaches end of life on 2026-04-27"
);
// Wrynose is not out yet: Scarthgap is the current LTS.
assert!(f
.remediation
.as_deref()
.expect("r")
.contains("Yocto Scarthgap (5.0)"));
assert!(finding("t1", &release_of("scarthgap"), today).is_none());
// A different release is a different finding.
let other = finding("t1", &release_of("mickledore"), today).expect("finding");
assert_ne!(other.fingerprint, f.fingerprint);
}
#[test]
fn a_release_without_lts_warns_two_months_ahead() {
// Whinlatter (5.3) ends on 2026-06-15.
let whinlatter = release_of("whinlatter");
assert!(finding("t1", &whinlatter, date(2026, 4, 14)).is_none());
let soon = finding("t1", &whinlatter, date(2026, 4, 15)).expect("finding");
assert_eq!(soon.rule_id.as_deref(), Some(RULE_EOL_SOON));
assert_eq!(soon.severity, Severity::Medium);
let ended = finding("t1", &whinlatter, date(2026, 6, 16)).expect("finding");
assert_eq!(ended.rule_id.as_deref(), Some(RULE_EOL));
assert_eq!(ended.severity, Severity::High);
}
#[test]
fn the_rules_are_bound_in_the_control_map() {
let map = control_map::ControlMap::cra().expect("map");
for rule in [RULE_EOL, RULE_EOL_SOON] {
let controls: Vec<String> = map
.controls_for_finding(SCANNER, Some("CWE-1104"), Some(rule))
.into_iter()
.map(|c| c.control.clone())
.collect();
assert_eq!(controls, ["cra-ai-22"], "{rule}");
}
}
}
+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);
}
}
Loaded 100 of 270 files, more files were not shown because too many files have changed in this diff. Show more