Compare commits

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 23:09:51 +01:00
sharang 168cbe98f8 ci: build the dashboard tests one rustc at a time (#933)
CI / Check (push) Skipped
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
2026-11-06 21:05:29 +00:00
sharang 9f2e78c6c4 feat(metering): new content starts a change-driven scan (t72) (#930)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Successful in 1m28s
CI / Deploy Agent (push) Successful in 9m6s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 3m13s
CI / Deploy Dashboard (push) Successful in 6m53s
2026-11-06 16:14:26 +00:00
sharang 9ce3b868bb feat(metering): send the month's peak of extra targets (t72) (#929)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m57s
CI / Agent integration (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-06 15:55:44 +00:00
sharang a7355ffdc8 feat(metering): the quota, Prüftage, the daily limit and the cap (t72) (#928)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Failing after 7m45s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 4m52s
CI / Deploy Dashboard (push) Failing after 5m54s
2026-11-06 14:48:07 +00:00
sharangandSharang Parnerkar ce786b716b feat(metering): included and extra targets, and why each scan ran (t72) (#927)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 9m4s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 5m4s
CI / Deploy Dashboard (push) Successful in 6m57s
First part of t72, Prüfwerk metering (LB §2 Abs. 4–5, §7). This PR records what a scan is metered by. Nothing is counted or enforced yet; counters, the 6-per-day limit and the Prüftag cap come in the next PR.

## What changes

- **Included vs extra targets.** Each target stores `billing: included | extra`.
  - The oldest active targets by `created_at` are included, up to the plan's `limits.included_targets` from the registry entitlement. The rest are extra.
  - The split is refreshed before each scan and when a target is created. Archiving an included target moves the oldest extra one up.
  - A plan without that key includes every target, which is every plan until the registry sends the limits. So this PR changes nothing for existing tenants.
- **Run attribution.** Each run records an `attribution`:
  - `request`: the customer started it (dashboard or API).
  - `support`: staff started it.
  - `change`: something the customer changed, i.e. new commits, other uploads, or a live URL.
  - `rescan`: only the Prüfwerk build changed.

  For scheduled and webhook scans it's set where change detection decides, so our rescan after an update is no longer counted as a customer change. `uploads_changed` / `content_changed` don't depend on `UPLOAD_CHANGE_SKIP`.
- **`chargeable`.** Says whether the run counts once it completes:
  - a request always counts;
  - a change counts only on an extra target;
  - rescans and support scans never count.

  `scan.completed` now carries `attribution` and `counted` as properties.
- **Dashboard.** The targets list shows a "Zusätzliches Prüfobjekt" badge on an extra target.

## Tests

- **Core:** the included/extra split, attribution, and the contract table of what counts.
- **Agent:** `content_changed`/`uploads_changed`, the `included_targets` limit, reading a stored target's billing, and a Mongo integration test (`tests/target_billing.rs`): the oldest are included, and an extra target moves up on archive.

Not built locally, per the CI-only rule; CI is the compiler here.

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

---------

Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Reviewed-on: #927
2026-11-06 14:30:07 +00:00
sharang c28f9e186b fix(mcp): rmcp 3.9, with the Host check of the Streamable HTTP server (#909)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 8m54s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 5m8s
CI / Deploy Dashboard (push) Successful in 6m43s
2026-11-05 19:31:06 +00:00
sharang 4480e8b509 fix(scan): Prüfwerk's own code no longer flags its test literals (#908)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 8s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m37s
CI / Agent integration (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-05 19:12:37 +00:00
sharang aa1c9b5d2b fix(docs): update the docs site's dependencies within their ranges (#907)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 10s
CI / Deploy Agent (push) Canceled after 0s
CI / Deploy Docs (push) Successful in 1m21s
CI / Agent integration (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-05 19:12:16 +00:00
sharang b2b9fd2a02 fix(scan): a Semgrep rule pack with its samples is test data (#905)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 11s
CI / Deploy Agent (push) Canceled after 0s
CI / Deploy Docs (push) Successful in 1m13s
CI / Agent integration (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-05 19:11:56 +00:00
sharang 8d839ed5ad fix(deps): openssl 0.10.82 and mongodb 3.10 (hickory 0.26) (#906)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 7s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 7m20s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 3m51s
CI / Deploy Dashboard (push) Successful in 4m25s
2026-11-05 19:11:42 +00:00
sharang b079cf9267 fix(scan): findings in test data and excluded paths close, whichever scanner stored them (#904)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 6m47s
CI / Agent integration (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-05 17:56:00 +00:00
sharang 2157ae2d42 fix(telemetry): service.version reports the release, not the crate version (#883)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 8m36s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 4m40s
CI / Deploy Dashboard (push) Successful in 6m12s
2026-11-05 17:32:27 +00:00
sharang 13d09dc830 fix(sbom): a component the build installed is badged "Im Image (gebaut)" (#881)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m11s
CI / Deploy Agent (push) Successful in 8m28s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Successful in 5m14s
2026-11-05 08:30:19 +00:00
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 / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-05 01:06:34 +00:00
sharang 3d7deee4a8 feat(yocto): read the build's SPDX 3.0 image document (#150) (#859)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Successful in 1m7s
CI / Deploy Agent (push) Successful in 5m30s
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 / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m9s
CI / Deploy Agent (push) Successful in 5m48s
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 / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m8s
CI / Deploy Agent (push) Successful in 6m10s
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 / Check (push) Skipped
CI / Detect Changes (push) Successful in 5s
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
2026-11-04 23:35:36 +00:00
sharang 7f5ddf69fc feat(yocto): build output in the wizard and the guide (#150) (#855)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m4s
CI / Deploy Agent (push) Successful in 8m27s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Successful in 6m16s
2026-11-04 23:18:50 +00:00
sharang c2fbffd2c6 feat(yocto): Yocto's own cve-check verdicts join the scan (#150) (#854)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m29s
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 / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 6m59s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 3m0s
CI / Deploy Dashboard (push) Successful in 4m57s
2026-11-04 22:42:48 +00:00
sharang 2ca87d1920 feat(yocto): read what a build installed from its SPDX 2.2 (#150) (#852)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 8m1s
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 / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m12s
CI / Deploy Agent (push) Successful in 5m33s
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 / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Successful in 1m10s
CI / Deploy Agent (push) Successful in 6m30s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-04 11:10:09 +00:00
sharang c16e91f981 fix(plc): test data and excluded paths leave the PLC analysis too (#828)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Successful in 1m7s
CI / Deploy Agent (push) Successful in 5m24s
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 / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m11s
CI / Deploy Agent (push) Successful in 8m56s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 4m52s
CI / Deploy Dashboard (push) Successful in 6m46s
2026-11-04 09:13:00 +00:00
sharang 533d5f35b5 fix(issues): a skipped scan still catches up the deferred issues (#826)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 7s
CI / Deploy Docs (push) Successful in 1m13s
CI / Deploy Agent (push) Successful in 6m45s
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 / Check (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Successful in 1m14s
CI / Deploy Agent (push) Successful in 10m50s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 2m53s
CI / Deploy Dashboard (push) Successful in 7m56s
2026-11-04 08:48:40 +00:00
sharang e01d2146e9 fix(nightly): no chat model, and GitHub Actions by major version (#573) (#821)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m23s
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 / Check (push) Skipped
CI / Deploy Agent (push) Canceled after 0s
CI / Deploy Docs (push) Successful in 1m16s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 4m57s
CI / Deploy Dashboard (push) Successful in 6m46s
2026-11-04 08:28:51 +00:00
sharang 5b0bf08478 fix(mobile): a manifest rule counts only on an AndroidManifest.xml (#824)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 9m15s
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 / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m54s
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 / Check (push) Skipped
CI / Detect Changes (push) Successful in 7s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Canceled after 0s
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 / Check (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 8m51s
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 / Check (push) Skipped
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
2026-11-02 21:27:12 +00:00
sharang 70be25650b fix(deps): pulldown-cmark 0.13.6 (RUSTSEC-2026-0433) (#587)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 8m11s
CI / Deploy Dashboard (push) Successful in 3m51s
CI / Deploy MCP (push) Successful in 4m23s
2026-11-02 21:08:01 +00:00
sharang 34243b208d fix(i18n): CRA status names mapped findings, not verdicts (#585)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m9s
CI / Deploy Agent (push) Successful in 7m36s
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Successful in 5m26s
2026-10-31 23:55:08 +00:00
sharang 9d4e46c34f fix(agent): cascade delete reads ids raw; integration tests fixed (#584)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m34s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-10-30 08:28:13 +00:00
sharang 0cbabb73fd fix(deps): zip 9 and tantivy 0.27 (zstd 0.14), drop seven audit ignores (#583)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 6m1s
CI / Deploy MCP (push) Successful in 3m23s
CI / Deploy Dashboard (push) Successful in 3m56s
2026-10-30 07:23:58 +00:00
sharang 1135b65b9e fix(llm): embedding requests within the model's token budget (#582)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 6m15s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-10-30 07:22:30 +00:00
sharangandSharang Parnerkar 330d492578 fix(docker): Upgrade Alpine packages in the docs image (#581)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m37s
CI / Deploy Agent (push) Successful in 12m9s
CI / Deploy MCP (push) Successful in 6m3s
CI / Deploy Dashboard (push) Successful in 14m17s
vuln-watch flags CVE-2026-111497 (critical, brotli decoder out-of-bounds write) in compliance-docs. nginx:alpine (3.24) still ships brotli-libs 1.2.0-r1; Alpine already has 1.2.1-r0. Dockerfile.docs now runs `apk upgrade --no-cache` in the nginx stage (CI already builds it with `--pull`).

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

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

---------

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

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

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Reviewed-on: #580
2026-10-29 14:31:09 +00:00
sharang 24001850ec fix(telemetry): console logs to WARN+ while logs go out over OTLP (#579)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 6m0s
CI / Deploy MCP (push) Successful in 3m28s
CI / Deploy Dashboard (push) Successful in 4m17s
2026-10-29 11:58:25 +00:00
sharang fad23c20a9 feat(telemetry): W3C propagation, route-named spans, trace-linked logs (#577)
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 7m38s
CI / Check (push) Skipped
CI / Deploy MCP (push) Successful in 4m19s
CI / Deploy Dashboard (push) Successful in 5m41s
2026-10-29 10:13:33 +00:00
sharang c739f1b7e5 ci: two cargo jobs and line-tables-only debug info on the runners (#578)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Agent (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-10-29 09:58:03 +00:00
sharang b247c5b359 fix(llm): nightly uses the gateway's models; no OpenAI defaults (#575)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m25s
CI / Deploy Agent (push) Successful in 10m24s
CI / Deploy MCP (push) Successful in 5m21s
CI / Deploy Dashboard (push) Successful in 11m57s
2026-10-29 07:43:21 +00:00
sharang 4ded72ce32 fix(deps): pulldown-cmark 0.13.5; zstd advisories until zip 9.x (#576)
CI / Detect Changes (push) Successful in 4s
CI / Check (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 10m24s
CI / Deploy MCP (push) Successful in 5m18s
CI / Deploy Dashboard (push) Successful in 6m40s
2026-10-28 22:11:42 +00:00
149 changed files with 12782 additions and 1575 deletions

No files matched your search

+5 -30
View File
@@ -1,34 +1,9 @@
[advisories]
ignore = [
# zip 2.4.2 — RUSTSEC-2026-0367/0368/0369 (published 2026-10): SUID/SGID
# bits, symlink targets and permissions applied through symlinks, all in
# ZipArchive::extract() / ZipStreamReader::extract(). We never call
# those: ingest/archive.rs walks the entries itself, skips any path that
# enclosed_name() rejects, and writes file contents only — no symlinks,
# no Unix modes. The fix is zip >= 9.0.0, a major jump from our "2".
# FOLLOW-UP: bump zip to 9.x in its own PR (backlog), then drop these.
"RUSTSEC-2026-0367",
"RUSTSEC-2026-0368",
"RUSTSEC-2026-0369",
# hickory-proto 0.25.x pulled in transitively via mongodb → hickory-resolver.
# MongoDB 3.x has not yet released with hickory-resolver 0.26.x, so we cannot
# upgrade past this without a mongodb release. Both are DNS-layer DoS vectors
# requiring a MITM/controlled DNS server against MongoDB's hostname resolution —
# not a realistic attack surface here. Revisit when mongodb bumps hickory.
# hickory-proto, pulled in transitively via mongodb → hickory-resolver
# (0.26.3 since mongodb 3.10, which fixed RUSTSEC-2026-0119). The NSEC3 loop
# is in DNSSEC validation, which the driver does not use, and needs a
# MITM/controlled DNS server against MongoDB's hostname resolution — not a
# realistic attack surface here. Revisit when hickory ships a fix.
"RUSTSEC-2026-0118", # NSEC3 loop, no fix available upstream
"RUSTSEC-2026-0119", # O(n²) name compression, fixed in hickory-proto >=0.26.1
# rmcp 0.16.0 — DNS rebinding in Streamable HTTP server transport (missing
# Host header validation). Patched in rmcp >= 1.4.0, which is a major API
# version jump from our pin; rmcp shipped 0.x → 1.x → 2.x in three months
# and the migration touches every tool handler + the auth middleware we
# just landed in #92. Threat model in our deployment: the MCP server is
# exposed at a public hostname (comp-mcp-dev.breakpilot.com) behind orca's
# TLS-terminating ingress with per-tenant bearer auth — the attack model
# (browser DNS-rebinding into localhost MCP server) doesn't directly apply.
# Defense-in-depth Host-header check is still a worthwhile follow-up.
# FOLLOW-UP: bump rmcp to 2.x in a dedicated PR (M7.3 follow-up, sized
# multi-hour due to API surface change).
"RUSTSEC-2026-0189",
]
+10 -1
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=
@@ -142,6 +146,11 @@ DASHBOARD_SESSION_KEY=
# MCP Server
MCP_ENDPOINT_URL=http://localhost:8090
# The hostnames (or host:port) clients reach the MCP server at, comma-separated:
# the public hostname behind the ingress and the in-network name the dashboard
# uses. Requests with another Host header are refused (DNS rebinding
# protection). Unset, the Host header is not checked and a warning is logged.
# MCP_ALLOWED_HOSTS=pruefwerk-stage.breakpilot.com,compliance-mcp:8090
# Absolute health URL for the default MCP server card. Set it where an ingress
# routes /mcp/* to a server that serves /health at its own root (staging:
# https://pruefwerk-stage.breakpilot.com/mcp/health). Derived from
+121 -4
View File
@@ -16,6 +16,12 @@ env:
COSIGN_PASSWORD: ${{ secrets.COSIGN_PASSWORD }}
CARGO_TERM_COLOR: always
RUSTFLAGS: "-D warnings"
# Job containers on the OVH runners get --cpus=2 --memory=3g, but cargo sees
# the host's 8 cores and ran up to 8 rustc with full debug info: the dashboard
# build was OOM-killed (signal 9). Two jobs to match the CPUs, and line tables
# only (backtraces keep file:line, no full variable info).
CARGO_BUILD_JOBS: "2"
CARGO_PROFILE_DEV_DEBUG: line-tables-only
# Compile cache: sccache -> Hetzner S3 (breakpilot-sccache), runner-independent
# and persistent across CI runs (own key prefix). Reuses the shared cluster S3
# creds (same bucket as werkpilot). Requires repo secrets HETZNER_S3_ACCESS_KEY
@@ -107,6 +113,15 @@ jobs:
env:
RUSTC_WRAPPER: ""
# The repository's Python scripts (the EOL table check, the CODESYS
# export script customers download) have offline tests.
- name: Script tests
run: |
command -v python3 >/dev/null || { apt-get update -qq && apt-get install -y -qq --no-install-recommends python3; }
python3 -B -I -m unittest discover -s scripts -p "test_*.py"
env:
RUSTC_WRAPPER: ""
# Clippy (compiles once, sccache reuses across feature sets). --all-targets
# lints test code too; tests may unwrap (clippy.toml), production may not.
- name: Clippy (core)
@@ -136,15 +151,110 @@ jobs:
# compliance-core's integration tests need no services.
- name: Tests (core integration)
run: cargo test -p compliance-core --tests
# The dashboard crate compiles as the library and as its test harness at
# once, each rustc at about 1.65 GB: two of them exceed the job's 3 GiB
# and get OOM-killed (signal 9). One at a time for these two steps.
- name: Tests (dashboard server)
env:
CARGO_BUILD_JOBS: "1"
run: cargo test -p compliance-dashboard --features server --no-default-features
- name: Tests (dashboard web)
env:
CARGO_BUILD_JOBS: "1"
run: cargo test -p compliance-dashboard --features web --no-default-features
- name: Show sccache stats
run: sccache --show-stats
if: always()
# compliance-agent's integration tests (compliance-agent/tests) need MongoDB.
# Every test opens its own database, so WiredTiger keeps a file open per
# collection and index: with the containers' default of 1024 open files
# mongod aborts mid-run ("Too many open files"), which is what took the
# mongo service down in #584. mongod runs as a process in this job
# container with a raised limit, and its log is printed when a test fails.
agent-integration:
name: Agent integration
if: github.event_name == 'pull_request'
runs-on: docker
container:
image: rust:1.94-bookworm
env:
MONGODB_VERSION: "7.0.45"
MONGODB_SHA256: e97e79211a7106a065d9119039ead401f32cfbbfa1681977fdeba4b4a4bf1f63
steps:
- name: Checkout
run: |
git init
git remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git"
git fetch --depth=1 origin "${GITHUB_SHA}"
git checkout FETCH_HEAD
- name: Use Kellnr crates.io mirror
run: |
: "${CARGO_HOME:=/usr/local/cargo}"
mkdir -p "$CARGO_HOME"
{
echo '[source.crates-io]'
echo 'replace-with = "kellnr"'
echo '[registries.kellnr]'
echo 'index = "sparse+https://crates.breakpilot.com/api/v1/cratesio/"'
} >> "$CARGO_HOME/config.toml"
env:
RUSTC_WRAPPER: ""
- name: Install sccache
run: |
curl -fsSL https://github.com/mozilla/sccache/releases/download/v0.10.0/sccache-v0.10.0-x86_64-unknown-linux-musl.tar.gz \
| tar xz --strip-components=1 -C /usr/local/bin/ sccache-v0.10.0-x86_64-unknown-linux-musl/sccache
chmod +x /usr/local/bin/sccache
env:
RUSTC_WRAPPER: ""
- name: Configure git auth for the private firmwerk dependency
run: |
git config --global \
url."https://platform-ci:${{ secrets.PLATFORM_CI_TOKEN }}@git.breakpilot.com/".insteadOf \
"ssh://git@git.breakpilot.com:22222/"
env:
RUSTC_WRAPPER: ""
# Build first, so compiling and mongod never share the job's 3 GB.
- name: Build the agent integration tests
run: cargo test -p compliance-agent --test '*' --no-run
# The official Debian 12 build, checked against its sha256; a small
# WiredTiger cache, no auth (the job container is its only client).
- name: Start MongoDB
run: |
T="mongodb-linux-x86_64-debian12-${MONGODB_VERSION}"
curl -fsSL "https://fastdl.mongodb.org/linux/${T}.tgz" -o /tmp/mongodb.tgz
echo "${MONGODB_SHA256} /tmp/mongodb.tgz" | sha256sum -c -
tar -xzf /tmp/mongodb.tgz -C /opt
mkdir -p /tmp/mongo-db
ulimit -n 64000 2>/dev/null || ulimit -n "$(ulimit -Hn)"
echo "open files: soft $(ulimit -Sn), hard $(ulimit -Hn)"
"/opt/${T}/bin/mongod" --dbpath /tmp/mongo-db --bind_ip 127.0.0.1 --port 27017 \
--wiredTigerCacheSizeGB 0.25 --fork --logpath /tmp/mongod.log
for i in $(seq 1 30); do
if (exec 3<>/dev/tcp/127.0.0.1/27017) 2>/dev/null; then echo "mongod is up"; exit 0; fi
sleep 1
done
echo "mongod did not start"; tail -50 /tmp/mongod.log; exit 1
shell: bash
env:
RUSTC_WRAPPER: ""
- name: Tests (agent integration)
run: cargo test -p compliance-agent --test '*'
env:
TEST_MONGODB_URI: mongodb://127.0.0.1:27017/
- name: MongoDB log
if: failure()
run: |
pgrep -a mongod || echo "mongod is not running"
tail -100 /tmp/mongod.log || true
env:
RUSTC_WRAPPER: ""
# ---------------------------------------------------------------------------
# Stage 2: Deploy (only on main, after checks pass)
# Each service only deploys when its relevant files changed.
@@ -238,7 +348,7 @@ jobs:
echo "version: ${PRUEFWERK_VERSION:-crate} commit: ${GITHUB_SHA}"
IMAGE=repo.breakpilot.com/pruefwerk/compliance-agent
echo "$REGISTRY_PASSWORD" | docker login repo.breakpilot.com -u "$REGISTRY_USERNAME" --password-stdin
DOCKER_BUILDKIT=1 docker build --secret id=git_token,env=PLATFORM_CI_TOKEN \
DOCKER_BUILDKIT=1 docker build --pull --secret id=git_token,env=PLATFORM_CI_TOKEN \
--build-arg PRUEFWERK_VERSION="${PRUEFWERK_VERSION}" \
--build-arg PRUEFWERK_COMMIT="${GITHUB_SHA}" \
-f Dockerfile.agent -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
@@ -271,9 +381,16 @@ jobs:
apk add --no-cache git curl openssl
git init && git remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git"
git fetch --depth=1 origin "${GITHUB_SHA}" && git checkout FETCH_HEAD
# service.version in telemetry: the latest release tag without its v,
# as for the agent. No tag → empty, and the crate version is used.
git fetch --quiet --unshallow --tags origin || true
TAG=$(git describe --tags --abbrev=0 --match 'v[0-9]*' 2>/dev/null || true)
PRUEFWERK_VERSION="${TAG#v}"
echo "version: ${PRUEFWERK_VERSION:-crate}"
IMAGE=repo.breakpilot.com/pruefwerk/compliance-dashboard
echo "$REGISTRY_PASSWORD" | docker login repo.breakpilot.com -u "$REGISTRY_USERNAME" --password-stdin
DOCKER_BUILDKIT=1 docker build --secret id=git_token,env=PLATFORM_CI_TOKEN \
DOCKER_BUILDKIT=1 docker build --pull --secret id=git_token,env=PLATFORM_CI_TOKEN \
--build-arg PRUEFWERK_VERSION="${PRUEFWERK_VERSION}" \
-f Dockerfile.dashboard -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
docker push "$IMAGE:latest" && docker push "$IMAGE:${GITHUB_SHA}"
{ command -v cosign >/dev/null 2>&1 || curl -sSfLo /usr/local/bin/cosign https://github.com/sigstore/cosign/releases/download/v2.4.3/cosign-linux-amd64 || wget -qO /usr/local/bin/cosign https://github.com/sigstore/cosign/releases/download/v2.4.3/cosign-linux-amd64; } || echo "::warning::cosign fetch failed"
@@ -304,7 +421,7 @@ jobs:
git fetch --depth=1 origin "${GITHUB_SHA}" && git checkout FETCH_HEAD
IMAGE=repo.breakpilot.com/pruefwerk/compliance-docs
echo "$REGISTRY_PASSWORD" | docker login repo.breakpilot.com -u "$REGISTRY_USERNAME" --password-stdin
docker build -f Dockerfile.docs -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
docker build --pull -f Dockerfile.docs -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
docker push "$IMAGE:latest" && docker push "$IMAGE:${GITHUB_SHA}"
{ command -v cosign >/dev/null 2>&1 || curl -sSfLo /usr/local/bin/cosign https://github.com/sigstore/cosign/releases/download/v2.4.3/cosign-linux-amd64 || wget -qO /usr/local/bin/cosign https://github.com/sigstore/cosign/releases/download/v2.4.3/cosign-linux-amd64; } || echo "::warning::cosign fetch failed"
chmod +x /usr/local/bin/cosign 2>/dev/null || true
@@ -336,7 +453,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"
+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 }}
+11
View File
@@ -0,0 +1,11 @@
# Made-up secrets in Prüfwerk's own tests, found by the secret scanner in the
# git history (commit:file:rule:line, as gitleaks fingerprints them). Neither is
# a real credential; the history keeps them, so they are listed here.
#
# A Firebase-shaped key in the test that the real scanner still finds Firebase
# keys (compliance-agent/src/pipeline/gitleaks.rs).
6c9756bebf599eb16112d693c769cd752292d6a9:compliance-agent/src/pipeline/gitleaks.rs:gcp-api-key:278
d42b429273668bd285440596fd78e564d34b01ef:compliance-agent/src/pipeline/gitleaks.rs:gcp-api-key:278
# The throwaway MongoDB root password of a CI test container.
3ef5c28a97f169ed03009f70a9a20a7c9095f0b2:.gitea/workflows/ci.yml:generic-password:170
5424074d26552882c6529c2dd9d309b9cc37376a:.gitea/workflows/ci.yml:generic-password:72
Generated
+678 -371
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"
+1 -1
View File
@@ -11,7 +11,7 @@ ARG BETTERLEAKS_SHA256=f8b185a39ffcece2a1ca82bf3a4e7435cd81963ffd16b7a9128daf75f
# in the release's checksums.txt.
ARG SBOMQS_VERSION=2.1.2
ARG SBOMQS_SHA256=451c800019c81059f86eac2c1344c57572b3436e7e0ffeaa076459d195a39ab8
ARG SEMGREP_VERSION=1.177.0
ARG SEMGREP_VERSION=1.179.0
ARG RUFF_VERSION=0.16.8
# mobsfscan pins an older semgrep; it is installed without its dependencies so
# it runs on the semgrep above, and its other dependencies are pinned here.
+3
View File
@@ -5,6 +5,9 @@ RUN cargo install dioxus-cli --version 0.7.3 --locked
# Legal pages linked from the sidebar; the defaults are breakpilot.com's.
ARG IMPRINT_URL=https://breakpilot.com/impressum
ARG PRIVACY_URL=https://breakpilot.com/datenschutz
# The release telemetry reports as service.version (CI passes the latest
# release tag); empty falls back to the crate version.
ARG PRUEFWERK_VERSION=
WORKDIR /app
COPY . .
+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
@@ -33,6 +33,8 @@ tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
chrono = { workspace = true }
# Calendar days and months of metering in Europe/Berlin (t72).
chrono-tz = "0.10"
mongodb = { workspace = true }
reqwest = { workspace = true }
thiserror = { workspace = true }
@@ -62,6 +64,8 @@ urlencoding = "2"
futures-util = "0.3"
zip = { workspace = true }
tar = { workspace = true }
# Yocto image SPDX archives (`*.spdx.tar.zst`); already in the tree via zip.
zstd = "0.14"
flate2 = { workspace = true }
tokio-tungstenite = { version = "0.26", features = ["rustls-tls-webpki-roots"] }
dashmap = { workspace = true }
+150 -11
View File
@@ -13,6 +13,12 @@ use crate::registry::RegistryClient;
use crate::scan_gate::{Admission, HeldTarget, ScanGate};
use crate::secrets::SecretBox;
/// A target whose billing changed, with its new billing (t72).
pub type BillingChange = (
mongodb::bson::oid::ObjectId,
compliance_core::models::TargetBilling,
);
/// Default maximum concurrent pentest sessions.
const DEFAULT_MAX_CONCURRENT_SESSIONS: usize = 5;
@@ -56,12 +62,22 @@ pub struct ComplianceAgent {
impl ComplianceAgent {
pub fn new(config: AgentConfig, db_pool: DatabasePool) -> Self {
let llm = Arc::new(LlmClient::new(
config.litellm_url.clone(),
config.litellm_api_key.clone(),
config.litellm_model.clone(),
config.litellm_embed_model.clone(),
));
if config.litellm_model.is_empty() || config.litellm_embed_model.is_empty() {
tracing::warn!(
chat = !config.litellm_model.is_empty(),
embeddings = !config.litellm_embed_model.is_empty(),
"LITELLM_MODEL / LITELLM_EMBED_MODEL not set: those LLM parts are off"
);
}
let llm = Arc::new(
LlmClient::new(
config.litellm_url.clone(),
config.litellm_api_key.clone(),
config.litellm_model.clone(),
config.litellm_embed_model.clone(),
)
.with_timeout(std::time::Duration::from_secs(config.llm_timeout_secs)),
);
let http = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(30))
.connect_timeout(std::time::Duration::from_secs(10))
@@ -123,6 +139,19 @@ impl ComplianceAgent {
metric: &str,
key: String,
properties: serde_json::Value,
) {
self.emit_usage_quantity(tenant_id, metric, key, 1.0, properties);
}
/// [`Self::emit_usage`] with a `quantity` other than one, such as the
/// month's peak of extra targets (t72).
pub fn emit_usage_quantity(
&self,
tenant_id: &str,
metric: &str,
key: String,
quantity: f64,
properties: serde_json::Value,
) {
let Some(registry) = self.registry.clone() else {
return;
@@ -132,7 +161,7 @@ impl ComplianceAgent {
tenant_id: tenant_id.to_string(),
product: registry.product().to_string(),
metric: metric.to_string(),
quantity: 1.0,
quantity,
occurred_at: chrono::Utc::now().to_rfc3339(),
properties: Some(properties),
};
@@ -143,6 +172,95 @@ impl ComplianceAgent {
});
}
/// Store which of the tenant's targets are the plan's included ones and
/// which are extra (t72), from the plan's `included_targets`. Without a
/// registry every target is included. Best-effort: when the plan cannot
/// be read or the targets not updated, the stored split stays.
///
/// # Returns
///
/// The targets whose billing changed, with their new billing.
pub async fn refresh_billing(
&self,
tenant_id: &str,
db: &crate::database::Database,
) -> Vec<BillingChange> {
match self.plan(tenant_id).await {
Some(plan) => {
self.assign_billing(tenant_id, db, plan.included_targets)
.await
}
None => Vec::new(),
}
}
/// The tenant's plan for metering (t72), from its entitlement; without
/// a registry, no limits at all. `None` when the registry did not
/// answer: then the stored billing stays, and counted Prüfungen are
/// neither checked nor charged.
pub async fn plan(&self, tenant_id: &str) -> Option<crate::metering::Plan> {
let Some(registry) = &self.registry else {
return Some(crate::metering::Plan::default());
};
match registry.check_entitlement(tenant_id, None, None).await {
Ok(check) => Some(crate::metering::Plan {
included_targets: check.included_targets(),
limits: check.plan_limits(),
}),
Err(e) => {
tracing::warn!(tenant_id, "plan not read, metering waits: {e}");
None
}
}
}
/// Store the billing of the tenant's targets for a plan that includes
/// `included` targets; best-effort.
async fn assign_billing(
&self,
tenant_id: &str,
db: &crate::database::Database,
included: Option<u32>,
) -> Vec<BillingChange> {
let changes = match crate::metering::assign_billing(db, included).await {
Ok(changes) => {
if !changes.is_empty() {
tracing::info!(tenant_id, changed = changes.len(), "target billing updated");
}
changes
}
Err(e) => {
tracing::warn!(tenant_id, "target billing not updated: {e}");
return Vec::new();
}
};
self.report_extra_peak(tenant_id, db).await;
changes
}
/// Send the month's peak of extra targets as `target.extra` when it
/// rose, and once a day besides (t72). The key carries the peak, so the
/// registry keeps every rise and drops the daily re-send as a duplicate;
/// billing takes the highest quantity per tenant-month. Count only: no
/// target names leave Prüfwerk. Best-effort.
async fn report_extra_peak(&self, tenant_id: &str, db: &crate::database::Database) {
let now = chrono::Utc::now();
match crate::metering::record_extra_peak(db, now).await {
Ok(Some(peak)) => {
let (month, _) = crate::metering::berlin_period(now);
self.emit_usage_quantity(
tenant_id,
"target.extra",
format!("target-extra:{tenant_id}:{month}:{peak}"),
f64::from(peak),
serde_json::json!({ "month": month }),
);
}
Ok(None) => {}
Err(e) => tracing::warn!(tenant_id, "extra targets not recorded: {e}"),
}
}
/// Scan a target, through the [`ScanGate`]: at most `SCAN_CONCURRENCY` scans
/// run at once, and a request for a target that is already being scanned is
/// coalesced — it becomes the one pending follow-up that this task runs next,
@@ -223,21 +341,42 @@ impl ComplianceAgent {
trigger: compliance_core::models::ScanTrigger,
) -> Result<(), crate::error::AgentError> {
let db = self.db_pool.for_tenant_id(tenant_id).await?;
// Whether this target is included or extra decides whether its scan
// counts, and the plan's limits whether a counted one may run (t72).
let plan = self.plan(tenant_id).await;
if let Some(plan) = &plan {
self.assign_billing(tenant_id, &db, plan.included_targets)
.await;
}
let orchestrator =
PipelineOrchestrator::new(self.config.clone(), tenant_id, db.clone(), self.llm.clone())
.with_nuget_license_cache(self.nuget_license_cache.clone())
.with_exploit_cache(self.exploit_cache.clone())
.with_advisory_index(self.advisory_index.clone());
.with_advisory_index(self.advisory_index.clone())
.with_plan_limits(plan.map(|p| p.limits));
let started = chrono::Utc::now();
let scanned = orchestrator.run_target(target_id, trigger.clone()).await?;
let outcome = orchestrator.run_target(target_id, trigger.clone()).await?;
// Support's scans are ours, not the customer's usage; a scheduled scan
// skipped because nothing changed scanned nothing (#465).
if scanned && trigger != compliance_core::models::ScanTrigger::Support {
if outcome.scanned && trigger != compliance_core::models::ScanTrigger::Support {
self.emit_usage(
tenant_id,
"scan.completed",
format!("scan:{tenant_id}:{target_id}:{}", started.timestamp()),
serde_json::json!({ "target_id": target_id, "trigger": format!("{trigger:?}") }),
serde_json::json!({
"target_id": target_id,
"trigger": format!("{trigger:?}"),
"attribution": outcome.attribution,
"counted": outcome.chargeable,
}),
);
}
if let Some(day) = &outcome.booked_prueftag {
self.emit_usage(
tenant_id,
"prueftag.booked",
format!("prueftag:{tenant_id}:{target_id}:{day}"),
serde_json::json!({ "target_id": target_id, "day": day }),
);
}
self.notify_new_findings(tenant_id, target_id, &db, started);
+54 -2
View File
@@ -13,9 +13,44 @@ pub async fn access() -> Json<serde_json::Value> {
Json(serde_json::json!({ "access": true }))
}
/// How long the health check waits for MongoDB before it reports it down.
const DB_PING_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
/// `GET /api/v1/health`: 200 `{"status":"ok"}` when MongoDB answers a ping,
/// 503 `{"status":"degraded","mongo":"unreachable"}` when it does not, so a
/// load balancer and the container health check stop sending traffic to an
/// instance that cannot serve it (#60). Public, untraced, no tenant.
#[tracing::instrument(skip_all)]
pub async fn health() -> Json<serde_json::Value> {
Json(serde_json::json!({ "status": "ok" }))
pub async fn health(
axum::extract::Extension(agent): AgentExt,
) -> (axum::http::StatusCode, Json<serde_json::Value>) {
let reachable = match tokio::time::timeout(DB_PING_TIMEOUT, agent.db_pool.ping()).await {
Ok(Ok(())) => true,
Ok(Err(e)) => {
tracing::warn!(error = %e, "health: MongoDB ping failed");
false
}
Err(_) => {
tracing::warn!("health: MongoDB ping timed out");
false
}
};
health_answer(reachable)
}
/// The health answer for whether MongoDB answered.
fn health_answer(mongo_reachable: bool) -> (axum::http::StatusCode, Json<serde_json::Value>) {
if mongo_reachable {
(
axum::http::StatusCode::OK,
Json(serde_json::json!({ "status": "ok" })),
)
} else {
(
axum::http::StatusCode::SERVICE_UNAVAILABLE,
Json(serde_json::json!({ "status": "degraded", "mongo": "unreachable" })),
)
}
}
/// Findings that still need someone's attention: not resolved, not a false
@@ -128,3 +163,20 @@ pub async fn stats_overview(
page: None,
}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_health_answer_follows_the_database() {
let (status, Json(body)) = health_answer(true);
assert_eq!(status, axum::http::StatusCode::OK);
assert_eq!(body, serde_json::json!({ "status": "ok" }));
let (status, Json(body)) = health_answer(false);
assert_eq!(status, axum::http::StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(body["status"], "degraded");
assert_eq!(body["mongo"], "unreachable");
}
}
+85 -56
View File
@@ -516,36 +516,13 @@ pub async fn delete_target(
.await;
// DAST targets linked to this target, and all their downstream data.
if let Ok(mut cursor) = db.dast_targets().find(doc! { "repo_id": &id }).await {
use futures_util::StreamExt;
while let Some(Ok(dt)) = cursor.next().await {
let dast_target_id = dt.id.map(|oid| oid.to_hex()).unwrap_or_default();
if !dast_target_id.is_empty() {
cascade_delete_dast_target(db, &dast_target_id).await;
}
}
for dast_target_id in ids_of(db.dast_targets(), doc! { "repo_id": &id }).await {
cascade_delete_dast_target(db, &dast_target_id).await;
}
// Pentest sessions linked directly to this target (not via a DAST target).
if let Ok(mut cursor) = db.pentest_sessions().find(doc! { "repo_id": &id }).await {
use futures_util::StreamExt;
while let Some(Ok(session)) = cursor.next().await {
let session_id = session.id.map(|oid| oid.to_hex()).unwrap_or_default();
if !session_id.is_empty() {
let _ = db
.attack_chain_nodes()
.delete_many(doc! { "session_id": &session_id })
.await;
let _ = db
.pentest_messages()
.delete_many(doc! { "session_id": &session_id })
.await;
let _ = db
.dast_findings()
.delete_many(doc! { "session_id": &session_id })
.await;
}
}
for session_id in ids_of(db.pentest_sessions(), doc! { "repo_id": &id }).await {
delete_session_data(db, &session_id).await;
}
let _ = db
.pentest_sessions()
@@ -555,32 +532,32 @@ pub async fn delete_target(
Ok(Json(serde_json::json!({ "status": "deleted" })))
}
/// The `_id`s (hex) of the documents in `coll` that match `filter`, read raw
/// with only `_id` projected: a document stored in another shape (an older
/// version, a manual insert) is still found, so a cascade never stops at it
/// and leaves its downstream data behind.
async fn ids_of<T: Send + Sync>(
coll: mongodb::Collection<T>,
filter: mongodb::bson::Document,
) -> Vec<String> {
use futures_util::StreamExt;
let raw = coll.clone_with_type::<mongodb::bson::Document>();
let mut out = Vec::new();
if let Ok(mut cursor) = raw.find(filter).projection(doc! { "_id": 1 }).await {
while let Some(next) = cursor.next().await {
if let Ok(Ok(oid)) = next.as_ref().map(|d| d.get_object_id("_id")) {
out.push(oid.to_hex());
}
}
}
out
}
/// Delete a DAST target and everything downstream of it (pentest sessions +
/// their attack chains / messages / findings, DAST scan runs + findings).
async fn cascade_delete_dast_target(db: &crate::database::Database, target_id: &str) {
use futures_util::StreamExt;
if let Ok(mut cursor) = db
.pentest_sessions()
.find(doc! { "target_id": target_id })
.await
{
while let Some(Ok(session)) = cursor.next().await {
let session_id = session.id.map(|oid| oid.to_hex()).unwrap_or_default();
if !session_id.is_empty() {
let _ = db
.attack_chain_nodes()
.delete_many(doc! { "session_id": &session_id })
.await;
let _ = db
.pentest_messages()
.delete_many(doc! { "session_id": &session_id })
.await;
let _ = db
.dast_findings()
.delete_many(doc! { "session_id": &session_id })
.await;
}
}
for session_id in ids_of(db.pentest_sessions(), doc! { "target_id": target_id }).await {
delete_session_data(db, &session_id).await;
}
let _ = db
.pentest_sessions()
@@ -599,6 +576,22 @@ async fn cascade_delete_dast_target(db: &crate::database::Database, target_id: &
}
}
/// The attack chain, messages and findings of one pentest session.
async fn delete_session_data(db: &crate::database::Database, session_id: &str) {
let _ = db
.attack_chain_nodes()
.delete_many(doc! { "session_id": session_id })
.await;
let _ = db
.pentest_messages()
.delete_many(doc! { "session_id": session_id })
.await;
let _ = db
.dast_findings()
.delete_many(doc! { "session_id": session_id })
.await;
}
/// POST /api/v1/targets/{id}/artifacts — attach an artifact (by reference).
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn add_artifact(
@@ -1006,6 +999,30 @@ pub async fn detect_target(
}))
}
/// Why a scan is asked for (`POST /api/v1/targets/{id}/scan?reason=…`).
#[derive(Debug, Default, serde::Deserialize)]
pub struct ScanReason {
/// `new_content` after the customer created the target or uploaded
/// files (t72): it runs only when something changed, as a change-driven
/// Prüfung. Absent: the customer asks for a Prüfung, which always runs
/// and counts.
#[serde(default)]
pub reason: Option<String>,
}
/// The trigger of a scan the customer (`staff: false`) or support asked
/// for, for `reason`. Support's scans are never the customer's usage.
fn requested_trigger(staff: bool, reason: Option<&str>) -> compliance_core::models::ScanTrigger {
use compliance_core::models::ScanTrigger;
if staff {
ScanTrigger::Support
} else if reason == Some("new_content") {
ScanTrigger::NewContent
} else {
ScanTrigger::Manual
}
}
/// POST /api/v1/targets/{id}/scan — trigger a scan for the target.
///
/// Dispatches to the unified pipeline when `UNIFIED_PIPELINE` is set (else the
@@ -1015,6 +1032,7 @@ pub async fn trigger_target_scan(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
Query(reason): Query<ScanReason>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let oid = parse_oid(&id)?;
let db = tenant_db(&agent, &tenant).await?;
@@ -1031,12 +1049,7 @@ pub async fn trigger_target_scan(
let agent_clone = (*agent).clone();
let tenant_id = tenant.0.tenant_id.clone();
// A scan support starts is not the customer's usage.
let trigger = if tenant.0.staff.is_some() {
compliance_core::models::ScanTrigger::Support
} else {
compliance_core::models::ScanTrigger::Manual
};
let trigger = requested_trigger(tenant.0.staff.is_some(), reason.reason.as_deref());
tokio::spawn(async move {
// Always the unified target pipeline — this endpoint is about an
// onboarded target by construction, independent of the global
@@ -1052,6 +1065,22 @@ pub async fn trigger_target_scan(
mod filter_tests {
use super::*;
#[test]
fn a_scan_asked_for_new_content_is_change_driven() {
use compliance_core::models::ScanTrigger;
assert_eq!(requested_trigger(false, None), ScanTrigger::Manual);
assert_eq!(
requested_trigger(false, Some("new_content")),
ScanTrigger::NewContent
);
assert_eq!(requested_trigger(false, Some("other")), ScanTrigger::Manual);
assert_eq!(
requested_trigger(true, Some("new_content")),
ScanTrigger::Support,
"support's scans are never the customer's usage"
);
}
#[test]
fn a_project_filter_matches_its_targets() {
let filter = TargetFilter {
+2 -31
View File
@@ -18,6 +18,8 @@ use mongodb::bson::{doc, Document};
use serde::{Deserialize, Serialize};
use compliance_core::auth::{validate_service_token, JwksState};
// Re-exported: the VEX, evidence and change-detection code import them from here.
pub use compliance_core::build_info::{BUILD_COMMIT, BUILD_VERSION};
use crate::agent::ComplianceAgent;
@@ -432,23 +434,6 @@ pub async fn usage(
}))
}
/// The build version: `PRUEFWERK_VERSION` at compile time (CI: the latest
/// release tag without its `v`), else the crate version.
pub const BUILD_VERSION: &str =
non_empty_or(option_env!("PRUEFWERK_VERSION"), env!("CARGO_PKG_VERSION"));
/// The commit the build is from: `PRUEFWERK_COMMIT` at compile time (CI:
/// the full SHA), else "unknown". The portal's version line shows 8 characters.
pub const BUILD_COMMIT: &str = non_empty_or(option_env!("PRUEFWERK_COMMIT"), "unknown");
/// A Docker build arg left empty is an empty env var, not an unset one.
const fn non_empty_or(value: Option<&'static str>, fallback: &'static str) -> &'static str {
match value {
Some(v) if !v.is_empty() => v,
_ => fallback,
}
}
/// `GET /api/v1/platform/version` — contract handshake (§4.1 /version).
pub async fn version(State(st): State<PlatformState>) -> Json<serde_json::Value> {
Json(serde_json::json!({
@@ -807,20 +792,6 @@ pub async fn delete_git_source(
})))
}
#[cfg(test)]
mod build_info_tests {
use super::*;
#[test]
fn an_unset_or_empty_build_value_falls_back() {
assert_eq!(non_empty_or(None, "0.4.4"), "0.4.4");
assert_eq!(non_empty_or(Some(""), "unknown"), "unknown");
assert_eq!(non_empty_or(Some("0.4.5"), "0.4.4"), "0.4.5");
assert!(!BUILD_VERSION.is_empty());
assert!(!BUILD_COMMIT.is_empty());
}
}
#[cfg(test)]
mod target_count_tests {
use super::*;
@@ -7,11 +7,11 @@
//! its token and its uploaded file, and a scan config keeps every field the
//! request does not name (#304).
use serde::Deserialize;
use serde::{Deserialize, Deserializer};
use compliance_core::models::{
Artifact, ArtifactAuth, ArtifactKind, Environment, IssueTrackerConfig, PentestConfig,
PentestStrategy, PlcFormat, ScanType, TargetScanConfig,
normalise_exclude_paths, Artifact, ArtifactAuth, ArtifactKind, Environment, IssueTrackerConfig,
PentestConfig, PentestStrategy, PlcFormat, ScanType, TargetScanConfig,
};
use crate::secrets::{SecretBox, SecretError};
@@ -138,6 +138,22 @@ pub struct ScanConfigUpdate {
pub strategy: Option<PentestStrategy>,
pub pentest: Option<PentestConfig>,
pub issue_tracker: Option<IssueTrackerConfig>,
/// Paths left out of every scan; replaces the stored list. Normalised
/// while the request is read, so an invalid path is refused with its
/// reason (axum answers 422 with the message).
#[serde(default, deserialize_with = "exclude_paths")]
pub exclude_paths: Option<Vec<String>>,
}
/// `exclude_paths` as [`normalise_exclude_paths`] stores them; an invalid
/// entry fails the request with the reason naming it.
fn exclude_paths<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
where
D: Deserializer<'de>,
{
Option::<Vec<String>>::deserialize(deserializer)?
.map(|paths| normalise_exclude_paths(&paths).map_err(serde::de::Error::custom))
.transpose()
}
impl ScanConfigUpdate {
@@ -169,6 +185,9 @@ impl ScanConfigUpdate {
if let Some(v) = self.strategy {
merged.strategy = Some(v);
}
if let Some(v) = self.exclude_paths {
merged.exclude_paths = v;
}
if let Some(mut tracker) = self.issue_tracker {
let kept = stored.issue_tracker.as_ref().and_then(|t| t.token.as_ref());
secrets.take_update(&mut tracker.token, kept)?;
@@ -275,6 +294,32 @@ mod tests {
assert!(cleared.auth.is_none());
}
#[test]
fn excluded_paths_are_normalised_or_refused_with_the_reason() {
let update: ScanConfigUpdate =
serde_json::from_str(r#"{"exclude_paths": ["./docs/samples/", "", "tools\\old"]}"#)
.unwrap();
assert_eq!(
update.exclude_paths.as_deref(),
Some(&["docs/samples".to_string(), "tools/old".to_string()][..])
);
let stored = TargetScanConfig {
exclude_paths: vec!["old".into()],
..Default::default()
};
let merged = update.apply(&secrets(), &stored).unwrap();
assert_eq!(merged.exclude_paths, ["docs/samples", "tools/old"]);
// Left out: the stored list stays.
let untouched: ScanConfigUpdate = serde_json::from_str("{}").unwrap();
let kept = untouched.apply(&secrets(), &stored).unwrap();
assert_eq!(kept.exclude_paths, ["old"]);
let err = serde_json::from_str::<ScanConfigUpdate>(r#"{"exclude_paths": ["../etc"]}"#)
.unwrap_err();
assert!(err.to_string().contains("../etc"), "{err}");
}
#[test]
fn enabling_a_scan_keeps_the_tracker_and_its_token() {
let s = secrets();
+1
View File
@@ -3,5 +3,6 @@ pub mod handlers;
pub mod role_gate;
pub mod routes;
pub mod server;
pub mod trace;
pub use server::start_api_server;
+5 -1
View File
@@ -444,7 +444,11 @@ pub async fn start_api_server(
&agent.config.cors_allowed_origins,
agent.config.app_env,
))
.layer(TraceLayer::new_for_http())
.layer(
TraceLayer::new_for_http()
.make_span_with(crate::api::trace::make_span)
.on_response(crate::api::trace::on_response),
)
// Security headers (defense-in-depth, primary enforcement via Traefik)
.layer(SetResponseHeaderLayer::overriding(
axum::http::header::STRICT_TRANSPORT_SECURITY,
+146
View File
@@ -0,0 +1,146 @@
//! One server span per HTTP request, for `TraceLayer` (instrumentation plan,
//! research/observability/2026-10-28-instrumentation-portal-registry-db.md).
//!
//! The default `TraceLayer` span is DEBUG (so the INFO filter drops it) and
//! records the full URI. This one is INFO, named after the route template
//! (`GET /api/v1/targets/{id}`), continues an incoming `traceparent` (portal,
//! registry) and records no path, query or client address.
use std::time::Duration;
use axum::extract::{MatchedPath, Request};
use axum::response::Response;
use tracing::Span;
/// The health route is polled every few seconds and gets no span.
const UNTRACED: &[&str] = &["/api/v1/health"];
pub fn make_span(req: &Request) -> Span {
let route = req
.extensions()
.get::<MatchedPath>()
.map(MatchedPath::as_str);
if route.is_some_and(|r| UNTRACED.contains(&r)) {
return Span::none();
}
let method = req.method().as_str();
let span = tracing::info_span!(
"http",
otel.name = %format!("{method} {}", route.unwrap_or("unmatched")),
otel.kind = "server",
otel.status_code = tracing::field::Empty,
http.request.method = %method,
http.route = route.unwrap_or(""),
http.response.status_code = tracing::field::Empty,
);
let header = |name: &str| req.headers().get(name).and_then(|v| v.to_str().ok());
compliance_core::telemetry::continue_trace(&span, header("traceparent"), header("tracestate"));
span
}
pub fn on_response(res: &Response, _latency: Duration, span: &Span) {
span.record("http.response.status_code", res.status().as_u16());
if res.status().is_server_error() {
span.record("otel.status_code", "ERROR");
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use axum::body::Body;
use axum::routing::get;
use axum::Router;
use std::sync::{Arc, Mutex};
use tower::ServiceExt as _;
use tower_http::trace::TraceLayer;
use tracing::field::{Field, Visit};
use tracing::span::{Attributes, Id, Record};
use tracing_subscriber::layer::{Context, SubscriberExt as _};
use tracing_subscriber::Layer;
/// Every field recorded on any span, as "name=value".
#[derive(Clone, Default)]
struct Fields(Arc<Mutex<Vec<String>>>);
struct Collect<'a>(&'a Mutex<Vec<String>>);
impl Visit for Collect<'_> {
fn record_debug(&mut self, f: &Field, v: &dyn std::fmt::Debug) {
self.0.lock().unwrap().push(format!("{}={v:?}", f.name()));
}
fn record_str(&mut self, f: &Field, v: &str) {
self.0.lock().unwrap().push(format!("{}={v}", f.name()));
}
}
impl<S: tracing::Subscriber> Layer<S> for Fields {
fn on_new_span(&self, a: &Attributes<'_>, _: &Id, _: Context<'_, S>) {
a.record(&mut Collect(&self.0));
}
fn on_record(&self, _: &Id, r: &Record<'_>, _: Context<'_, S>) {
r.record(&mut Collect(&self.0));
}
}
async fn call(path: &str, status: u16) -> Vec<String> {
let fields = Fields::default();
let sub = tracing_subscriber::registry().with(fields.clone());
let _guard = tracing::subscriber::set_default(sub);
let app = Router::new()
.route("/api/v1/health", get(|| async { "ok" }))
.route(
"/api/v1/targets/{id}",
get(move || async move { axum::http::StatusCode::from_u16(status).unwrap() }),
)
.layer(
TraceLayer::new_for_http()
.make_span_with(make_span)
.on_response(on_response),
);
let req = Request::builder().uri(path).body(Body::empty()).unwrap();
app.oneshot(req).await.unwrap();
let out = fields.0.lock().unwrap().clone();
out
}
#[tokio::test]
async fn names_the_span_after_the_route_and_keeps_the_path_out() {
let f = call("/api/v1/targets/acme-firmware?token=x", 200).await;
assert!(
f.contains(&"otel.name=GET /api/v1/targets/{id}".to_string()),
"{f:?}"
);
assert!(
f.contains(&"http.route=/api/v1/targets/{id}".to_string()),
"{f:?}"
);
assert!(
f.contains(&"http.response.status_code=200".to_string()),
"{f:?}"
);
assert!(
f.iter()
.all(|x| !x.contains("acme") && !x.contains("token")),
"{f:?}"
);
assert!(
!f.iter().any(|x| x.starts_with("otel.status_code")),
"{f:?}"
);
}
#[tokio::test]
async fn a_server_error_marks_the_span() {
let f = call("/api/v1/targets/1", 503).await;
assert!(f.contains(&"otel.status_code=ERROR".to_string()), "{f:?}");
}
#[tokio::test]
async fn health_and_unmatched() {
assert!(
call("/api/v1/health", 200).await.is_empty(),
"health gets no span"
);
let f = call("/nope/acme", 200).await;
assert!(f.contains(&"otel.name=GET unmatched".to_string()), "{f:?}");
}
}
@@ -390,6 +390,13 @@ impl HeuristicClassifier {
ArtifactKind::SourceArchive if lower.ends_with(".projectarchive") => out.push(
verdict(TargetType::PlcSps, 0.85, "CODESYS project archive", vec![]),
),
// A Yocto image's SPDX archive is Yocto by itself.
ArtifactKind::BuildOutput if lower.ends_with(".spdx.tar.zst") => out.push(verdict(
TargetType::EmbeddedLinuxYocto,
0.7,
"Yocto image SPDX archive",
vec![],
)),
ArtifactKind::LiveUrl if input.artifacts.len() == 1 => {
out.push(verdict(TargetType::WebApp, 0.3, "live URL only", vec![]))
}
+8 -3
View File
@@ -49,9 +49,14 @@ fn build_config(app_env: AppEnv) -> Result<AgentConfig, AgentError> {
litellm_url: env_var_opt("LITELLM_URL")
.unwrap_or_else(|| "http://localhost:4000".to_string()),
litellm_api_key: SecretString::from(env_var_opt("LITELLM_API_KEY").unwrap_or_default()),
litellm_model: env_var_opt("LITELLM_MODEL").unwrap_or_else(|| "gpt-4o".to_string()),
litellm_embed_model: env_var_opt("LITELLM_EMBED_MODEL")
.unwrap_or_else(|| "text-embedding-3-small".to_string()),
// No default model: our gateway serves none of the OpenAI names, so an
// unset model means the LLM parts are off (LlmClient refuses to call).
litellm_model: env_var_opt("LITELLM_MODEL").unwrap_or_default(),
litellm_embed_model: env_var_opt("LITELLM_EMBED_MODEL").unwrap_or_default(),
llm_timeout_secs: env_var_opt("LLM_TIMEOUT_SECS")
.and_then(|v| v.parse::<u64>().ok())
.filter(|n| *n > 0)
.unwrap_or(600),
github_token: env_secret_opt("GITHUB_TOKEN"),
github_webhook_secret: env_secret_opt("GITHUB_WEBHOOK_SECRET"),
gitlab_url: env_var_opt("GITLAB_URL"),
+14
View File
@@ -168,6 +168,20 @@ impl DatabasePool {
}
}
/// Ask MongoDB whether it answers (`ping` on the `admin` database), for
/// the health check.
///
/// # Errors
///
/// The driver's error when the server cannot be reached or refuses.
pub async fn ping(&self) -> Result<(), mongodb::error::Error> {
self.client
.database("admin")
.run_command(doc! { "ping": 1 })
.await
.map(|_| ())
}
/// Raw client handle. Reserved for cross-tenant admin flows that
/// must opt in explicitly (tenant listing, drop-on-offboard).
pub fn client(&self) -> &Client {
+6
View File
@@ -42,6 +42,11 @@ pub enum AgentError {
#[error("the archive password set on the target does not open it")]
ArchivePasswordWrong,
/// A counted Prüfung the plan does not allow now (t72): not an error of
/// the scan, which ends without scanning.
#[error("not run: {0:?}")]
NotAdmitted(compliance_core::models::Refusal),
#[error("{0}")]
Other(String),
}
@@ -73,6 +78,7 @@ impl AgentError {
| Self::Config(_)
| Self::Secret(_)
| Self::Exec(_)
| Self::NotAdmitted(_)
| Self::Other(_) => (
RunErrorCode::Internal,
"the scan stopped because of an internal error",
+4 -1
View File
@@ -531,7 +531,10 @@ mod tests {
let (zip_bytes, listed) = build_pack(&inputs(), Utc::now()).expect("pack");
let mut archive =
zip::ZipArchive::new(std::io::Cursor::new(zip_bytes)).expect("a valid zip");
let mut names: Vec<String> = archive.file_names().map(String::from).collect();
let mut names: Vec<String> = archive
.file_names()
.map(|n| n.expect("a UTF-8 entry name").into_owned())
.collect();
names.sort();
assert_eq!(
names,
+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
@@ -17,6 +17,7 @@ pub mod ingest;
pub mod license_conclusions;
pub mod lifecycle;
pub mod llm;
pub mod metering;
pub mod pentest;
pub mod pipeline;
pub mod rag;
+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);
}
+383
View File
@@ -0,0 +1,383 @@
//! Metering of a tenant's Prüfungen (t72).
//!
//! **Included and extra targets.** The oldest active targets are included,
//! up to the plan's `included_targets`; every other active target is extra.
//! The split is stored on each target ([`OnboardedTarget::billing`]) and
//! brought up to date before each scan and when a target is created, so
//! archiving an included target moves the oldest extra one up.
//!
//! **Counters.** A counted Prüfung is checked against the plan when it
//! starts ([`usage`] and [`compliance_core::models::admit`]) and charged
//! when it completes ([`charge`]): to the month's quota, else to the
//! target's Prüftag for the day, booking one if none is. Months and days
//! are calendar ones in Europe/Berlin. A run that fails because of us is
//! never charged, so nothing is refunded.
//!
//! [`OnboardedTarget::billing`]: compliance_core::models::OnboardedTarget::billing
use chrono::{DateTime, Utc};
use futures_util::TryStreamExt;
use mongodb::bson::{doc, oid::ObjectId, Document};
use compliance_core::models::{
split_included, BillableTarget, DayUsage, MonthUsage, PlanLimits, RunCharge, TargetBilling,
};
use crate::database::Database;
use crate::error::AgentError;
/// Store the billing of the tenant's active targets for a plan that
/// includes `included` targets.
///
/// # Arguments
///
/// * `db` - The tenant's database.
/// * `included` - How many targets the plan includes; `None` is unlimited.
///
/// # Returns
///
/// The targets whose billing changed, with their new billing.
///
/// # Errors
///
/// Returns an error if the targets cannot be read or updated.
pub async fn assign_billing(
db: &Database,
included: Option<u32>,
) -> Result<Vec<(ObjectId, TargetBilling)>, AgentError> {
// Only the three fields the split needs: a whole target holds its
// artifacts, and older documents may lack fields the model requires.
let docs: Vec<Document> = db
.raw_collection("onboarded_targets")
.find(doc! { "archived_at": null })
.projection(doc! { "_id": 1, "created_at": 1, "billing": 1 })
.await?
.try_collect()
.await?;
let targets: Vec<BillableTarget<ObjectId>> = docs.iter().filter_map(billable).collect();
let changes = split_included(&targets, included);
for wanted in [TargetBilling::Included, TargetBilling::Extra] {
let ids: Vec<ObjectId> = changes
.iter()
.filter(|(_, billing)| *billing == wanted)
.map(|(id, _)| *id)
.collect();
if ids.is_empty() {
continue;
}
let value =
mongodb::bson::to_bson(&wanted).map_err(|e| AgentError::Other(e.to_string()))?;
db.onboarded_targets()
.update_many(
doc! { "_id": { "$in": ids } },
doc! { "$set": { "billing": value } },
)
.await?;
}
Ok(changes)
}
/// A stored target as the split sees it; `None` without an id. A target
/// without a creation time counts as the oldest, one without a billing as
/// included (stored before metering).
fn billable(target: &Document) -> Option<BillableTarget<ObjectId>> {
Some(BillableTarget {
id: target.get_object_id("_id").ok()?,
created_at: target
.get_datetime("created_at")
.map_or(DateTime::<Utc>::MIN_UTC, |at| at.to_chrono()),
billing: target
.get("billing")
.and_then(|b| mongodb::bson::from_bson(b.clone()).ok())
.unwrap_or_default(),
})
}
/// The tenant's plan as metering reads it from the registry.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Plan {
/// How many targets the plan includes; `None` is unlimited.
pub included_targets: Option<u32>,
/// The quota and the customer's Prüftag cap.
pub limits: PlanLimits,
}
/// The tenant's counted Prüfungen and booked Prüftage per month.
const MONTHS: &str = "metering_months";
/// Each target's Prüftag per day, once the quota was used up.
const DAYS: &str = "metering_days";
/// The calendar month and day of `at` in Europe/Berlin, as `YYYY-MM` and
/// `YYYY-MM-DD`: the periods the contract counts in.
pub fn berlin_period(at: DateTime<Utc>) -> (String, String) {
let local = at.with_timezone(&chrono_tz::Europe::Berlin);
(
local.format("%Y-%m").to_string(),
local.format("%Y-%m-%d").to_string(),
)
}
/// The id of a target's counter for one day.
fn day_id(target_id: &str, day: &str) -> String {
format!("{target_id}:{day}")
}
/// A stored counter as a `u32`; missing or negative reads as 0.
fn count(document: Option<&Document>, field: &str) -> u32 {
document
.and_then(|d| d.get(field))
.and_then(mongodb::bson::Bson::as_i64)
.or_else(|| document.and_then(|d| d.get_i32(field).ok()).map(i64::from))
.and_then(|n| u32::try_from(n).ok())
.unwrap_or(0)
}
/// What the tenant used this month and `target_id` today, at `at`.
///
/// # Errors
///
/// Returns an error if the counters cannot be read.
pub async fn usage(
db: &Database,
target_id: &str,
at: DateTime<Utc>,
) -> Result<(MonthUsage, DayUsage), AgentError> {
let (month, day) = berlin_period(at);
let month_doc = db
.raw_collection(MONTHS)
.find_one(doc! { "_id": &month })
.await?;
let day_doc = db
.raw_collection(DAYS)
.find_one(doc! { "_id": day_id(target_id, &day) })
.await?;
Ok((
MonthUsage {
pruefungen: count(month_doc.as_ref(), "pruefungen"),
prueftage: count(month_doc.as_ref(), "prueftage"),
},
DayUsage {
prueftag_booked: day_doc
.as_ref()
.and_then(|d| d.get_bool("prueftag_booked").ok())
.unwrap_or(false),
prueftag_pruefungen: count(day_doc.as_ref(), "prueftag_pruefungen"),
},
))
}
/// What [`charge`] charged a completed Prüfung to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Charged {
/// The quota or the target's Prüftag.
pub charge: RunCharge,
/// The Berlin day (`YYYY-MM-DD`) of a Prüftag this Prüfung booked; it
/// goes to the registry as `prueftag.booked`.
pub booked_prueftag: Option<String>,
}
/// Charge one completed, counted Prüfung on `target_id` at `at`: to the
/// month's quota while it lasts, else to the target's Prüftag that day,
/// booking it if none is. The start of the run checked the limits, so this
/// never refuses; scans of several targets finishing at once can take the
/// quota or a Prüftag over by the ones that raced.
///
/// # Errors
///
/// Returns an error if the counters cannot be written.
pub async fn charge(
db: &Database,
target_id: &str,
limits: PlanLimits,
at: DateTime<Utc>,
) -> Result<Charged, AgentError> {
let (month, day) = berlin_period(at);
let months = db.raw_collection(MONTHS);
months
.update_one(
doc! { "_id": &month },
doc! { "$setOnInsert": { "pruefungen": 0_i64, "prueftage": 0_i64 } },
)
.upsert(true)
.await?;
let quota_filter = match limits.monthly_pruefungen {
// `$not $gte` also matches a month document without the counter.
Some(quota) => doc! {
"_id": &month,
"pruefungen": { "$not": { "$gte": i64::from(quota) } },
},
None => doc! { "_id": &month },
};
let in_quota = months
.update_one(quota_filter, doc! { "$inc": { "pruefungen": 1_i64 } })
.await?;
if in_quota.matched_count == 1 {
return Ok(Charged {
charge: RunCharge::Quota,
booked_prueftag: None,
});
}
let days = db.raw_collection(DAYS);
let id = day_id(target_id, &day);
days.update_one(
doc! { "_id": &id },
doc! { "$setOnInsert": {
"target_id": target_id,
"day": &day,
"month": &month,
"prueftag_booked": false,
"prueftag_pruefungen": 0_i64,
} },
)
.upsert(true)
.await?;
let booked = days
.update_one(
doc! { "_id": &id, "prueftag_booked": false },
doc! { "$set": { "prueftag_booked": true, "prueftag_pruefungen": 1_i64 } },
)
.await?;
if booked.matched_count == 1 {
months
.update_one(
doc! { "_id": &month },
doc! { "$inc": { "prueftage": 1_i64 } },
)
.await?;
return Ok(Charged {
charge: RunCharge::Prueftag,
booked_prueftag: Some(day),
});
}
days.update_one(
doc! { "_id": &id },
doc! { "$inc": { "prueftag_pruefungen": 1_i64 } },
)
.await?;
Ok(Charged {
charge: RunCharge::Prueftag,
booked_prueftag: None,
})
}
/// Record how many of the tenant's active targets are extra at `at`, as
/// the month's peak (t72): the 5,99 € line bills the highest number of
/// extra targets at once in the calendar month (Europe/Berlin).
///
/// # Returns
///
/// The month's peak when it goes to the registry as `target.extra`: when it
/// rose, and once a day besides (a re-send the registry drops as a
/// duplicate of its key). `None` otherwise, and while no target was extra.
///
/// # Errors
///
/// Returns an error if the targets or the month's counters cannot be read
/// or written.
pub async fn record_extra_peak(
db: &Database,
at: DateTime<Utc>,
) -> Result<Option<u32>, AgentError> {
let extra = mongodb::bson::to_bson(&TargetBilling::Extra)
.map_err(|e| AgentError::Other(e.to_string()))?;
let now = db
.onboarded_targets()
.count_documents(doc! { "archived_at": null, "billing": extra })
.await?;
let now = u32::try_from(now).unwrap_or(u32::MAX);
let (month, day) = berlin_period(at);
let months = db.raw_collection(MONTHS);
// The document before the update: the peak and the day it was last sent.
let before = months
.find_one_and_update(
doc! { "_id": &month },
doc! {
"$max": { "extra_peak": i64::from(now) },
"$setOnInsert": { "pruefungen": 0_i64, "prueftage": 0_i64 },
},
)
.upsert(true)
.await?;
let previous = count(before.as_ref(), "extra_peak");
let sent_on = before
.as_ref()
.and_then(|d| d.get_str("extra_sent_on").ok());
let peak = previous.max(now);
if peak == 0 || (peak == previous && sent_on == Some(day.as_str())) {
return Ok(None);
}
months
.update_one(
doc! { "_id": &month },
doc! { "$set": { "extra_sent_on": &day } },
)
.await?;
Ok(Some(peak))
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::TimeZone;
#[test]
fn periods_are_calendar_ones_in_berlin() {
let at = |y, m, d, h, min| {
Utc.with_ymd_and_hms(y, m, d, h, min, 0)
.single()
.expect("valid")
};
// 23:30 UTC on 31 Oct is already 1 Nov in Berlin (CET, UTC+1).
assert_eq!(
berlin_period(at(2026, 10, 31, 23, 30)),
("2026-11".to_string(), "2026-11-01".to_string())
);
// In summer (CEST, UTC+2) the day turns at 22:00 UTC.
assert_eq!(berlin_period(at(2026, 7, 14, 21, 59)).1, "2026-07-14");
assert_eq!(berlin_period(at(2026, 7, 14, 22, 0)).1, "2026-07-15");
}
#[test]
fn a_counter_reads_as_zero_when_missing() {
let stored = doc! { "pruefungen": 7_i64, "small": 3_i32, "negative": -1_i64 };
assert_eq!(count(Some(&stored), "pruefungen"), 7);
assert_eq!(count(Some(&stored), "small"), 3);
assert_eq!(count(Some(&stored), "negative"), 0);
assert_eq!(count(Some(&stored), "absent"), 0);
assert_eq!(count(None, "pruefungen"), 0);
}
#[test]
fn a_stored_target_reads_with_defaults_for_what_it_lacks() {
// Arrange
let id = ObjectId::new();
let at = mongodb::bson::DateTime::from_millis(1_700_000_000_000);
let extra = doc! { "_id": id, "created_at": at, "billing": "extra" };
let old = doc! { "_id": id };
// Act
let extra = billable(&extra);
let old = billable(&old);
// Assert
assert_eq!(
extra,
Some(BillableTarget {
id,
created_at: at.to_chrono(),
billing: TargetBilling::Extra,
})
);
assert_eq!(
old,
Some(BillableTarget {
id,
created_at: DateTime::<Utc>::MIN_UTC,
billing: TargetBilling::Included,
})
);
assert_eq!(billable(&doc! { "name": "no id" }), None);
}
}
+43
View File
@@ -70,6 +70,22 @@ pub fn uploads_allow_git_skip(target: &OnboardedTarget) -> bool {
upload_skip_enabled() && uploads_match(target)
}
/// Whether a file uploaded to `target` changed since its last completed
/// scan: it has uploads, and they are not the ones that scan read. For
/// metering (t72), independent of [`upload_skip_enabled`].
pub fn uploads_changed(target: &OnboardedTarget) -> bool {
target.artifacts.iter().any(is_upload) && !uploads_match(target)
}
/// Whether the customer changed what `target`, which has no git repository,
/// gives a scan to read since its last completed one: it was never scanned,
/// its uploads changed, or it has a live URL (the service changes on its
/// own). A scheduled scan that runs without such a change is our own rescan
/// (t72).
pub fn content_changed(target: &OnboardedTarget) -> bool {
target.live_url().is_some() || target.last_scan.is_none() || uploads_changed(target)
}
/// Whether the uploads of `target` are the ones its last completed scan read.
fn uploads_match(target: &OnboardedTarget) -> bool {
target
@@ -219,4 +235,31 @@ mod tests {
let unhashed = target(vec![upload("a", None)]);
assert_eq!(upload_inputs(&unhashed), None);
}
#[test]
fn only_a_change_the_customer_made_is_a_content_change() {
// Arrange: a target scanned once, by an older build.
let mut t = target(vec![upload("a", Some("h1"))]);
assert!(content_changed(&t), "never scanned");
t.last_scan = Some(LastScan {
build: "0.0.1+old".into(),
inputs: upload_inputs(&t),
});
// Act / Assert: a new build alone is no change of the customer's.
assert!(!content_changed(&t));
assert!(!uploads_changed(&t));
t.artifacts[0].content_hash = Some("h2".into());
assert!(content_changed(&t), "another upload");
assert!(uploads_changed(&t));
let mut live = target(vec![Artifact::live_url("https://pump.example.com")]);
live.last_scan = Some(LastScan {
build: build_id(),
inputs: None,
});
assert!(content_changed(&live), "a live service changes on its own");
assert!(!uploads_changed(&live), "nothing uploaded");
}
}
+132 -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,94 @@ impl RunFindings {
Ok(closed)
}
/// Close the undecided findings on target `target_id` whose file lies in
/// the excluded paths or the test data this run left out
/// ([`Self::with_excluded`], [`Self::with_test_data`]), each with its
/// reason. Nothing is closed as fixed; only what was left out.
///
/// [`Self::resolve_missing`] only closes what a scanner that completed no
/// longer reports. A scanner that did not run cannot close its findings in
/// a left-out path, although nothing can see them any more: cppcheck runs
/// only on a tree with C, so once a fixture held the tree's only C, its
/// findings would stay open for good. This closes them, whichever scanner
/// stored them. A finding this run reported again is kept.
///
/// # Arguments
///
/// * `db` - the tenant database
/// * `target_id` - the scanned target (`Finding::repo_id`)
/// * `scanner` - only this scanner's findings (a stage that stores its
/// findings without this object, the PLC analysis), or `None` for all
///
/// # Returns
///
/// How many findings were closed.
///
/// # Errors
///
/// A database error.
pub async fn resolve_left_out(
&mut self,
db: &Database,
target_id: &str,
scanner: Option<&str>,
) -> Result<u32, AgentError> {
if self.excluded.is_empty() && self.test_data.is_empty() {
return Ok(0);
}
let mut filter = doc! {
"repo_id": target_id,
"status": { "$in": UNDECIDED.to_vec() },
};
if let Some(scanner) = scanner {
filter.insert("scanner", scanner);
}
let rows: Vec<Document> = db
.findings()
.clone_with_type::<Document>()
.find(filter)
.projection(doc! { "fingerprint": 1, "file_path": 1 })
.await?
.try_collect()
.await?;
let (mut excluded, mut test_data) = (Vec::new(), Vec::new());
for row in &rows {
let (Ok(id), Ok(file)) = (row.get_object_id("_id"), row.get_str("file_path")) else {
continue;
};
// Something in this run still reports it, so it is not left out:
// closing it would only see it reopened by the next run.
let reported = row
.get_str("fingerprint")
.is_ok_and(|fp| self.inserted.contains_key(fp) || self.earlier.contains(fp));
if reported {
continue;
}
if crate::pipeline::vendor::in_vendor_dir(file, &self.excluded) {
excluded.push(id);
} else if crate::pipeline::vendor::in_vendor_dir(file, &self.test_data) {
test_data.push(id);
}
}
self.set_status(
db,
&excluded,
&UNDECIDED,
FindingStatus::Resolved,
ScanChangeKind::NowExcluded,
)
.await?;
self.set_status(
db,
&test_data,
&UNDECIDED,
FindingStatus::Resolved,
ScanChangeKind::NowTestData,
)
.await?;
Ok(u32::try_from(excluded.len() + test_data.len()).unwrap_or(u32::MAX))
}
/// Move the findings `ids` whose status is still one of `from` to `to`,
/// with a history entry saying this run did it and why. The `from` guard
/// leaves alone a finding a person changed in the meantime.
+8 -1
View File
@@ -399,7 +399,14 @@ impl GitOps {
let head_name = head_ref.name().unwrap_or("HEAD");
repo.reference(head_name, fetch_commit.id(), true, "fast-forward")?;
repo.checkout_head(Some(git2::build::CheckoutBuilder::default().force()))?;
// `recreate_missing`: a scan takes the test data out of its working
// copy (`pipeline::test_data`); every fetch puts it back, so what is
// left out always follows the current rules.
repo.checkout_head(Some(
git2::build::CheckoutBuilder::default()
.force()
.recreate_missing(true),
))?;
tracing::info!("Fetched and fast-forwarded {}", repo_path.display());
Ok(())
+41 -9
View File
@@ -9,6 +9,10 @@
//! most [`MAX_NEW_ISSUES`] per scan, highest severity and oldest first. The
//! rest wait for the next scans. Gitea only: it matches against the listing
//! the scan made anyway; the other trackers would need a search per finding.
//!
//! A scheduled scan that change detection skips (no new commits) still runs
//! the catch-up when findings are [`waiting`] for an issue, so a backlog
//! does not wait for the next push.
use std::collections::{BTreeMap, HashSet};
@@ -119,26 +123,50 @@ pub(super) async fn catch_up(
Ok(run(sink, &candidates, index, mode).await)
}
/// The target's open medium+ findings without an issue, as stored.
async fn load_candidates(sink: &IssueSink<'_>) -> Result<Vec<Finding>, AgentError> {
/// The target's open medium+ findings without an issue, as a query.
fn candidate_filter(repo_id: &str) -> mongodb::bson::Document {
let severities: Vec<String> = ISSUE_SEVERITIES.iter().map(Severity::to_string).collect();
let statuses: Vec<String> = ISSUE_STATUSES.iter().map(ToString::to_string).collect();
// `tracker_issue_url: null` matches a missing field too.
doc! {
"repo_id": repo_id,
"tracker_issue_url": null,
"severity": { "$in": severities },
"status": { "$in": statuses },
}
}
/// The target's open medium+ findings without an issue, as stored.
async fn load_candidates(sink: &IssueSink<'_>) -> Result<Vec<Finding>, AgentError> {
let findings = sink
.db
.findings()
.find(doc! {
"repo_id": sink.repo_id,
"tracker_issue_url": null,
"severity": { "$in": severities },
"status": { "$in": statuses },
})
.find(candidate_filter(sink.repo_id))
.await?
.try_collect()
.await?;
Ok(findings)
}
/// Whether target `repo_id` has findings waiting for an issue: one query,
/// so a skipped scan with nothing to catch up never lists the tracker.
///
/// # Errors
///
/// The findings cannot be read.
pub(super) async fn waiting(
db: &crate::database::Database,
repo_id: &str,
) -> Result<bool, AgentError> {
let one = db
.findings()
.clone_with_type::<mongodb::bson::Document>()
.find_one(candidate_filter(repo_id))
.projection(doc! { "_id": 1 })
.await?;
Ok(one.is_some())
}
/// The findings that want an issue and have none, highest severity first,
/// then oldest first.
fn select(findings: Vec<Finding>) -> Vec<Finding> {
@@ -515,6 +543,8 @@ mod tests {
}
};
assert!(waiting(&db, "target-1").await.unwrap());
// A dry run changes nothing.
let dry = catch_up(&sink, &index, IssueCatchup::DryRun).await.unwrap();
assert_eq!((dry.created.total(), dry.linked.total()), (1, 1));
@@ -554,10 +584,12 @@ mod tests {
.expect("the link is recorded for the status sync");
assert_eq!(record.external_id, "7");
// The next scan finds nothing left to do.
// The next scan finds nothing left to do, and a skipped one would
// not even list the tracker.
let again = catch_up(&sink, &index, IssueCatchup::On).await.unwrap();
assert_eq!((again.created.total(), again.linked.total()), (0, 0));
assert_eq!(posts(&seen), 1);
assert!(!waiting(&db, "target-1").await.unwrap());
pool.drop_tenant("issue-catchup").await.ok();
}
}
@@ -160,6 +160,35 @@ impl PipelineOrchestrator {
}
}
impl PipelineOrchestrator {
/// The issue catch-up for a scan that change detection skipped: without
/// it, findings deferred by [`crate::pipeline::issue_catchup::MAX_NEW_ISSUES`]
/// wait for the next push. Runs only with the catch-up on (or in dry
/// run), on a Gitea tracker, and when findings are waiting for an issue,
/// so an idle repository costs one query and no tracker request. A
/// failure is logged; the skipped scan stays skipped.
pub(super) async fn catch_up_unchanged(&self, repo: &RepoView, repo_id: &str) {
if self.config.issue_catchup == IssueCatchup::Off {
return;
}
let Some(TrackerDispatch::Gitea(_)) = self.build_tracker(repo) else {
return;
};
match crate::pipeline::issue_catchup::waiting(&self.db, repo_id).await {
Ok(true) => {}
Ok(false) => return,
Err(e) => {
tracing::warn!("[{repo_id}] Issue catch-up check failed: {e}");
return;
}
}
tracing::info!("[{repo_id}] Unchanged repository: issue catch-up only");
if let Err(e) = self.create_tracker_issues(repo, repo_id, &[]).await {
tracing::warn!("[{repo_id}] Issue catch-up failed: {e}");
}
}
}
/// What opening, reopening and closing a target's CVE issues needs: the
/// tracker configuration, where tracker calls may connect, and the tenant's
/// database. Shared by the scans and the CVE monitor.
@@ -235,6 +235,14 @@ fn comment(status: &FindingStatus, change: Option<&StatusChange>) -> String {
"Die Datei gilt jetzt als Herstellercode und ist von den Befunden ausgenommen.",
"The file now counts as vendor code, which is left out of the findings.",
),
(FindingStatus::Resolved, Some(ScanChangeKind::NowTestData)) => (
"Die Datei liegt in Testdaten (z. B. fixtures/ oder testdata/), die von der Prüfung ausgenommen sind.",
"The file lies in test data (such as fixtures/ or testdata/), which is left out of the scan.",
),
(FindingStatus::Resolved, Some(ScanChangeKind::NowExcluded)) => (
"Die Datei liegt in einem Pfad, den die Einstellungen des Prüfobjekts von der Prüfung ausnehmen.",
"The file lies in a path the target's settings leave out of the scan.",
),
(FindingStatus::Resolved, _) => (
"In Prüfwerk als behoben markiert.",
"Marked resolved in Prüfwerk.",
+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!(
+5
View File
@@ -47,11 +47,16 @@ pub mod sbom;
pub mod sbom_quality;
pub mod semgrep;
pub mod source_text;
pub mod test_data;
pub mod tool_cmd;
mod tracker_dispatch;
pub(crate) mod unity_settings;
pub mod variants;
pub mod vendor;
pub mod vex_lifecycle;
pub mod yocto_build;
pub mod yocto_cve_check;
pub mod yocto_inventory;
pub mod yocto_pins;
pub mod yocto_spdx;
pub mod yocto_spdx3;
+670 -39
View File
@@ -37,6 +37,30 @@ pub struct GraphContext {
pub impacts: Vec<compliance_core::models::graph::ImpactAnalysis>,
}
/// How a scan of an onboarded target went, for its usage events (t72).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TargetScanOutcome {
/// `false` when it was skipped because nothing changed (#465), or the
/// plan did not allow it now.
pub scanned: bool,
/// Why it ran; `None` when it was skipped.
pub attribution: Option<ScanAttribution>,
/// Whether it counts toward the customer's usage.
pub chargeable: bool,
/// The Berlin day (`YYYY-MM-DD`) of a Prüftag this scan booked.
pub booked_prueftag: Option<String>,
}
/// What a scan left out of its working copy before the first stage, as
/// paths relative to the tree.
#[derive(Debug, Default)]
struct LeftOut {
/// Removed because the target's settings exclude them.
excluded: Vec<String>,
/// Detected test data ([`crate::pipeline::test_data`]).
test_data: Vec<String>,
}
pub struct PipelineOrchestrator {
pub(super) config: AgentConfig,
/// The tenant this run belongs to. Carried explicitly because the on-disk
@@ -55,6 +79,9 @@ pub struct PipelineOrchestrator {
pub(super) exploit_cache: Option<Arc<dyn ExploitCache>>,
/// The vendor CSAF advisories (#515); none in tests.
pub(super) advisory_index: Option<Arc<dyn crate::pipeline::csaf_match::AdvisoryIndex>>,
/// The tenant's plan limits for metering (t72); `None` when not known,
/// and then counted Prüfungen are neither checked nor charged.
pub(super) plan_limits: Option<PlanLimits>,
}
impl PipelineOrchestrator {
@@ -71,9 +98,16 @@ impl PipelineOrchestrator {
nuget_license_cache: None,
exploit_cache: None,
advisory_index: None,
plan_limits: None,
}
}
/// Check and charge counted Prüfungen against `limits` (t72).
pub(crate) fn with_plan_limits(mut self, limits: Option<PlanLimits>) -> Self {
self.plan_limits = limits;
self
}
/// Cache the NuGet licenses looked up on nuget.org in `cache` (#467).
pub(crate) fn with_nuget_license_cache(mut self, cache: Arc<dyn LicenseCache>) -> Self {
self.nuget_license_cache = Some(cache);
@@ -164,23 +198,35 @@ impl PipelineOrchestrator {
// new to find; one a person started always runs (after a changed
// setting it can find something else), a new Prüfwerk build scans
// once (#465), and so does a file uploaded to the target since.
if !trigger.started_by_person()
&& repo.uploads_allow_skip
&& repo.last_scanned_build.as_deref()
== Some(crate::pipeline::change::build_id().as_str())
&& !GitOps::has_new_commits(&repo_path, repo.last_scanned_commit.as_deref())?
{
tracing::info!("[{repo_id}] No new commits, skipping scan");
self.skip_stage(
if !trigger.started_by_person() {
let new_commits =
GitOps::has_new_commits(&repo_path, repo.last_scanned_commit.as_deref())?;
if !new_commits
&& repo.uploads_allow_skip
&& repo.last_scanned_build.as_deref()
== Some(crate::pipeline::change::build_id().as_str())
{
tracing::info!("[{repo_id}] No new commits, skipping scan");
self.skip_stage(
scan_run_id,
SkippedStage::new(
"change_detection",
SkipCode::NoNewCommits,
"no new commits since the last scan",
),
)
.await;
// Findings deferred by the catch-up's cap still get their issues.
self.catch_up_unchanged(repo, &repo_id).await;
return Ok(0);
}
self.attribute_run(
scan_run_id,
SkippedStage::new(
"change_detection",
SkipCode::NoNewCommits,
"no new commits since the last scan",
),
&repo_id,
ScanAttribution::detected(trigger, new_commits || repo.changed_besides_commits),
repo.billing,
)
.await;
return Ok(0);
.await?;
}
// Submodules are part of what the product ships (a HAL, an RTOS).
@@ -225,6 +271,14 @@ impl PipelineOrchestrator {
let repo_id = repo.id.as_ref().map(|id| id.to_hex()).unwrap_or_default();
let repo_path = tree.to_path_buf();
// What the target's settings exclude, and test data (`fixtures/`,
// `testdata/`), which is not what the product ships, leave the working
// copy before any stage reads it, so no stage reports them — no code
// findings, no SBOM components, no CVEs.
let left_out = self
.prune_left_out(&repo_path, &repo.exclude_paths, scan_run_id)
.await;
let mut all_findings: Vec<Finding> = Vec::new();
// Each scanner stage saves its new findings at once, so they show while
// the scan runs (#372); triage updates them at the end.
@@ -235,9 +289,19 @@ impl PipelineOrchestrator {
tokio::task::spawn_blocking(move || crate::pipeline::variants::app_variants(&tree))
.await
.unwrap_or_default();
// Left out of the tree, but a scanner that walks the git history
// (gitleaks) still sees what was committed there.
let left_out_dirs: Vec<String> = left_out
.excluded
.iter()
.chain(&left_out.test_data)
.cloned()
.collect();
let mut run_findings = crate::pipeline::finding_store::RunFindings::new(scan_run_id)
.with_variants(variants)
.with_tree(repo_path.clone());
.with_tree(repo_path.clone())
.with_excluded(left_out.excluded)
.with_test_data(left_out.test_data);
// Stage 1: SAST. Vendor SDK code (HAL, CMSIS, third-party middleware) is
// not the customer's to fix, so both analysers skip it and the run says
@@ -271,12 +335,14 @@ impl PipelineOrchestrator {
.await;
}
// The same vendor code is left out of every code scanner's findings:
// the pattern, secret and lint scanners walk the whole tree.
// the pattern, secret and lint scanners walk the whole tree. So are the
// left-out paths, for the secret scanner, which reads the history.
let outside_vendor = |findings: &mut Vec<Finding>| {
findings.retain(|f| {
!f.file_path
.as_deref()
.is_some_and(|p| crate::pipeline::vendor::in_vendor_dir(p, &vendor))
!f.file_path.as_deref().is_some_and(|p| {
crate::pipeline::vendor::in_vendor_dir(p, &vendor)
|| crate::pipeline::vendor::in_vendor_dir(p, &left_out_dirs)
})
})
};
match SemgrepScanner::new(vendor.clone())
@@ -535,7 +601,15 @@ impl PipelineOrchestrator {
)
.await;
}
let yocto_entries = yocto_inventory::entries(&yocto.recipes, &declarations, &repo_id);
// What the build installed, from its image SPDX: joined with the
// inventory by recipe name, the build's version and image marking win.
let (built_images, cve_checks) = self.read_build_outputs(repo, &repo_id, scan_run_id).await;
let built = crate::pipeline::yocto_build::Built::new(&built_images, &cve_checks);
let yocto_entries = built.merge(yocto_inventory::entries(
&yocto.recipes,
&declarations,
&repo_id,
));
let yocto_recipes = yocto.recipes;
for entry in embedded.into_iter().chain(codesys).chain(yocto_entries) {
let known = sbom_entries
@@ -666,8 +740,10 @@ impl PipelineOrchestrator {
// A Yocto recipe inventory's components: NVD by CPE, within a budget
// of their own (a layer tree can name hundreds of products).
if !yocto_recipes.is_empty() {
let (queries, unversioned) = yocto_inventory::nvd_queries(&yocto_recipes);
if !yocto_recipes.is_empty() || !built.is_empty() {
let (inventory_queries, mut unversioned) = yocto_inventory::nvd_queries(&yocto_recipes);
let (queries, built_unversioned) = built.nvd_queries(inventory_queries);
unversioned.extend(built_unversioned);
let lookup = cve_scanner
.scan_yocto(
&repo_id,
@@ -689,6 +765,22 @@ impl PipelineOrchestrator {
.await;
}
}
// What the build's cve-check found unpatched and the match above did
// not (another version range, a CPE NVD's API matches differently).
let missing = built.unpatched_missing(&cve_alerts, |name| {
sbom_entries
.iter()
.any(|e| e.package_manager == YOCTO_RECIPE_MANAGER && e.name == name)
});
for (name, version, cves) in missing {
cve_alerts.extend(crate::pipeline::cve::record_nvd(
&repo_id,
&mut sbom_entries,
&name,
&version,
cves,
));
}
self.match_advisories(&repo_id, &mut sbom_entries, &mut cve_alerts)
.await;
@@ -949,6 +1041,11 @@ impl PipelineOrchestrator {
run_findings
.resolve_missing(&self.db, &repo_id, &vendor)
.await?;
// And what an earlier scan stored in a left-out path, also of a scanner
// that did not run this time.
run_findings
.resolve_left_out(&self.db, &repo_id, None)
.await?;
// Their issues follow: closed with a comment, or reopened.
crate::pipeline::issue_sync::IssueSync {
db: self.db.clone(),
@@ -999,7 +1096,7 @@ impl PipelineOrchestrator {
// stated again after the alerts were stored, never over a person's,
// and before the notifications, which a `not_affected` or `fixed`
// suppresses.
let statements = yocto_inventory::vex_statements(&yocto_recipes, &cve_alerts);
let statements = built.statements(&yocto_recipes, &cve_alerts);
if !statements.is_empty() {
match crate::pipeline::vex_lifecycle::apply_scan_statements(
&self.db,
@@ -1062,8 +1159,9 @@ impl PipelineOrchestrator {
///
/// # Returns
///
/// Whether it scanned: `false` when it was skipped because nothing changed
/// since the last completed scan (a scheduled or webhook scan, #465).
/// Whether it scanned (`false` when it was skipped because nothing changed
/// since the last completed scan, a scheduled or webhook scan, #465), and
/// how it is metered (t72).
///
/// # Errors
///
@@ -1072,7 +1170,7 @@ impl PipelineOrchestrator {
&self,
target_id: &str,
trigger: ScanTrigger,
) -> Result<bool, AgentError> {
) -> Result<TargetScanOutcome, AgentError> {
let oid = mongodb::bson::oid::ObjectId::parse_str(target_id)
.map_err(|e| AgentError::Other(e.to_string()))?;
let target = self
@@ -1082,7 +1180,13 @@ impl PipelineOrchestrator {
.await?
.ok_or_else(|| AgentError::Other(format!("Onboarded target {target_id} not found")))?;
let scan_run = ScanRun::new(target_id.to_string(), trigger.clone());
let mut scan_run = ScanRun::new(target_id.to_string(), trigger.clone());
// A scan a person started is attributed from the start; change
// detection attributes the others (t72).
if let Some(attribution) = ScanAttribution::of_person(&trigger) {
scan_run.attribution = Some(attribution);
scan_run.chargeable = attribution.chargeable(target.billing);
}
let insert = self.db.scan_runs().insert_one(&scan_run).await?;
let scan_run_id = insert
.inserted_id
@@ -1090,9 +1194,20 @@ impl PipelineOrchestrator {
.map(|id| id.to_hex())
.unwrap_or_default();
let result = self
.run_target_pipeline(&target, &scan_run_id, &trigger)
.await;
// A counted Prüfung a person started is checked against the plan
// before anything runs (t72).
let admitted = if scan_run.chargeable {
self.admit_run(&scan_run_id, target_id).await
} else {
Ok(())
};
let result = match admitted {
Ok(()) => {
self.run_target_pipeline(&target, &scan_run_id, &trigger)
.await
}
Err(e) => Err(e),
};
match &result {
Ok(count) => {
let mut completed = doc! {
@@ -1143,6 +1258,23 @@ impl PipelineOrchestrator {
)
.await?;
}
// The plan does not allow it now: the run ends without scanning,
// and the target keeps what its last scan read, so the change is
// scanned once it may be.
Err(AgentError::NotAdmitted(refusal)) => {
tracing::info!(target_id, ?refusal, "counted Prüfung not run");
self.db
.scan_runs()
.update_one(
doc! { "_id": &insert.inserted_id },
doc! { "$set": {
"status": "completed",
"current_phase": "completed",
"completed_at": mongodb::bson::DateTime::now(),
} },
)
.await?;
}
Err(e) => {
tracing::error!(target_id, error = %e, "Unified scan pipeline failed");
let (code, message) = e.run_failure();
@@ -1160,16 +1292,171 @@ impl PipelineOrchestrator {
.await?;
}
}
result?;
let skipped = self
let refused = matches!(result, Err(AgentError::NotAdmitted(_)));
let invalid_input = matches!(
result,
Err(AgentError::ArchivePasswordRequired | AgentError::ArchivePasswordWrong)
);
// Read back without hiding the scan's own error behind a failed read.
let run = self
.db
.scan_runs()
.count_documents(doc! {
"_id": &insert.inserted_id,
"skipped_stages.stage": "change_detection",
})
.await?;
Ok(skipped == 0)
.find_one(doc! { "_id": &insert.inserted_id })
.await
.ok()
.flatten();
let unchanged = run.as_ref().is_some_and(|r| {
r.skipped_stages
.iter()
.any(|s| s.stage == "change_detection")
});
let chargeable = run.as_ref().is_some_and(|r| r.chargeable);
let attribution = run.and_then(|r| r.attribution);
// A counted Prüfung is charged when it completed, or when it failed on
// the customer's input; a failure of ours never is (t72).
let charged = if chargeable && ((result.is_ok() && !unchanged) || invalid_input) {
self.charge_run(&insert.inserted_id, target_id).await
} else {
None
};
if !refused {
result?;
}
Ok(TargetScanOutcome {
scanned: !refused && !unchanged,
attribution,
chargeable,
booked_prueftag: charged.and_then(|c| c.booked_prueftag),
})
}
/// Check a counted Prüfung against the plan before it scans (t72):
/// the quota, today's Prüftag on the target, the customer's cap. It runs
/// when the plan's limits or the usage are not known.
///
/// # Errors
///
/// [`AgentError::NotAdmitted`] when the plan does not allow it now; why
/// is recorded on the run.
async fn admit_run(&self, scan_run_id: &str, target_id: &str) -> Result<(), AgentError> {
let Some(limits) = self.plan_limits else {
return Ok(());
};
let (month, day) =
match crate::metering::usage(&self.db, target_id, chrono::Utc::now()).await {
Ok(usage) => usage,
Err(e) => {
tracing::warn!(target_id, "usage not read, the Prüfung runs: {e}");
return Ok(());
}
};
let Admission::Refused(refusal) = admit(limits, month, day) else {
return Ok(());
};
let (code, reason) = match refusal {
Refusal::DailyLimit => (
SkipCode::PrueftagLimitReached,
"the quota is used up and today's Prüftag on the target has had its Prüfungen",
),
Refusal::PrueftagCap => (
SkipCode::PrueftagCapReached,
"the quota is used up and the customer's Prüftag limit is reached",
),
};
self.skip_stage(scan_run_id, SkippedStage::new("metering", code, reason))
.await;
Err(AgentError::NotAdmitted(refusal))
}
/// Charge the completed, counted run `run_id` on `target_id` and record
/// what it was charged to (t72). Nothing is charged when the plan's
/// limits are not known. Best-effort: a counter that cannot be written is
/// logged.
async fn charge_run(
&self,
run_id: &mongodb::bson::Bson,
target_id: &str,
) -> Option<crate::metering::Charged> {
let limits = self.plan_limits?;
match crate::metering::charge(&self.db, target_id, limits, chrono::Utc::now()).await {
Ok(charged) => {
if let Ok(value) = mongodb::bson::to_bson(&charged.charge) {
if let Err(e) = self
.db
.scan_runs()
.update_one(
doc! { "_id": run_id.clone() },
doc! { "$set": { "charge": value } },
)
.await
{
tracing::warn!(target_id, "charge not recorded on the run: {e}");
}
}
Some(charged)
}
Err(e) => {
tracing::warn!(target_id, "Prüfung not charged: {e}");
None
}
}
}
/// Record why the run `scan_run_id` on `target_id` runs and whether it
/// counts, on a target billed as `billing`, and check a counted one
/// against the plan (t72). A run with several code artifacts is
/// attributed once per artifact; a change found in any of them wins over
/// our rescan. The record is best-effort, like [`Self::skip_stage`].
///
/// # Errors
///
/// [`AgentError::NotAdmitted`] when the plan does not allow a counted
/// Prüfung now.
async fn attribute_run(
&self,
scan_run_id: &str,
target_id: &str,
attribution: ScanAttribution,
billing: TargetBilling,
) -> Result<(), AgentError> {
let chargeable = attribution.chargeable(billing);
self.record_attribution(scan_run_id, attribution, chargeable)
.await;
if chargeable {
self.admit_run(scan_run_id, target_id).await?;
}
Ok(())
}
/// Store `attribution` and `chargeable` on the run, unless it already
/// reads as a change.
async fn record_attribution(
&self,
scan_run_id: &str,
attribution: ScanAttribution,
chargeable: bool,
) {
let Ok(oid) = mongodb::bson::oid::ObjectId::parse_str(scan_run_id) else {
return;
};
let Ok(value) = mongodb::bson::to_bson(&attribution) else {
return;
};
let change = mongodb::bson::to_bson(&ScanAttribution::Change).unwrap_or_default();
if let Err(e) = self
.db
.scan_runs()
.update_one(
doc! { "_id": oid, "attribution": { "$ne": change } },
doc! { "$set": {
"attribution": value,
"chargeable": chargeable,
} },
)
.await
{
tracing::warn!(scan_run_id, "scan run not attributed: {e}");
}
}
/// Run the applicable scans for a target. For a code target this reuses the
@@ -1214,6 +1501,19 @@ impl PipelineOrchestrator {
.await;
return Ok(0);
}
// A git target is attributed where its commits are compared.
if !trigger.started_by_person() && !has_git {
self.attribute_run(
scan_run_id,
&target_id,
ScanAttribution::detected(
trigger,
crate::pipeline::change::content_changed(target),
),
target.billing,
)
.await?;
}
let plan = build_scan_plan(target);
// An attached artifact nothing analyses is recorded, never passed over:
// a completed run must not read as "we looked and found nothing".
@@ -1323,6 +1623,7 @@ impl PipelineOrchestrator {
}
let mut repo = RepoView::from_target(target, code, &self.secrets);
repo.yocto_layers = yocto_layers;
repo.build_outputs = build_output_paths(target, &working_paths);
let n = self.run_pipeline(&repo, scan_run_id, trigger).await?;
self.finalize_target(target, &repo, n).await?;
new_count += n;
@@ -1338,6 +1639,7 @@ impl PipelineOrchestrator {
Some(tree) => {
let mut repo = RepoView::from_target(target, code, &self.secrets);
repo.yocto_layers = yocto_layers;
repo.build_outputs = build_output_paths(target, &working_paths);
let upload = crate::pipeline::plc::sbom::uploaded_archive(code);
let n = self.scan_tree(tree, upload, &repo, scan_run_id).await?;
self.finalize_target(target, &repo, n).await?;
@@ -1356,6 +1658,14 @@ impl PipelineOrchestrator {
}
}
}
// Only what a build wrote about its image (an image SPDX archive,
// a cve-check report): the same stages run over an empty tree, so
// the SBOM, CVEs and VEX come from the build output alone.
None if target.has(ArtifactKind::BuildOutput) => {
new_count += self
.scan_build_output_only(target, &target_id, &working_paths, scan_run_id)
.await?;
}
None => {
// No code to scan. DAST is attempted for a target the matrix
// plans it for, and for a migrated DAST target, which carries no
@@ -1415,10 +1725,22 @@ impl PipelineOrchestrator {
let mut analysed = Vec::with_capacity(sources.len());
let mut all_sbom: Vec<SbomEntry> = Vec::new();
let mut sbom_seen = std::collections::BTreeSet::new();
// CODESYS projects in their native format: their control logic is not
// read, and the run says so (#165).
let mut native = std::collections::BTreeSet::new();
// What the target's settings exclude and the test data leave each tree
// first, as in a code scan (#820, #825).
let mut left_out = LeftOut::default();
for a in &sources {
let Some(path) = ingest_set.get(&a.id).and_then(|ia| ia.working_path.clone()) else {
continue;
};
let pruned = self
.prune_left_out(&path, &target.scan_config.exclude_paths, scan_run_id)
.await;
left_out.excluded.extend(pruned.excluded);
left_out.test_data.extend(pruned.test_data);
native.extend(crate::pipeline::plc::native_projects(&path));
analysed.push((
path.clone(),
crate::pipeline::plc::analyze_tree(&path, target_id),
@@ -1459,6 +1781,23 @@ impl PipelineOrchestrator {
}
}
}
if !native.is_empty() {
let list = native.into_iter().collect::<Vec<_>>().join(", ");
self.skip_stage(
scan_run_id,
SkippedStage::new(
"plc_native_project",
SkipCode::NativePlcProject,
format!(
"CODESYS projects in their native format are not analysed for control \
logic: {list}; export the POUs as PLCopen XML (Project > Export \
PLCopenXML) and add the export to the target"
),
)
.about(list),
)
.await;
}
let all_findings = self.map_plc_findings(scan_run_id, analysed).await;
tracing::info!(
target_id,
@@ -1501,6 +1840,24 @@ impl PipelineOrchestrator {
"Refreshed control_refs on {refreshed_count} existing PLC findings"
);
}
// Findings an earlier scan stored in what is now left out close with
// that reason, and their issues follow.
let mut left_out_run = crate::pipeline::finding_store::RunFindings::new(scan_run_id)
.with_excluded(left_out.excluded)
.with_test_data(left_out.test_data);
let closed = left_out_run
.resolve_left_out(&self.db, target_id, Some("plc-control-logic"))
.await?;
if closed > 0 {
tracing::info!(target_id, closed, "PLC findings in left-out paths resolved");
crate::pipeline::issue_sync::IssueSync {
db: self.db.clone(),
config: self.config.clone(),
secrets: self.secrets.clone(),
net_guard: self.net_guard,
}
.spawn(left_out_run.status_changed().to_vec());
}
if !all_sbom.is_empty() {
if let Err(e) = self
@@ -2275,6 +2632,100 @@ impl PipelineOrchestrator {
.await;
}
/// Take what the target's settings exclude (`excluded`, relative paths)
/// and the test data ([`crate::pipeline::test_data`]) out of the working
/// copy at `tree`, and note on the run what was left out. Only a working
/// copy under the clone or artifact directories is touched; the git
/// fetch and the archive unpack restore it next scan.
///
/// # Returns
///
/// The paths removed, relative to `tree`; empty when there were none or
/// the tree is not the agent's own.
async fn prune_left_out(
&self,
tree: &std::path::Path,
excluded: &[String],
scan_run_id: &str,
) -> LeftOut {
let root = tree.to_path_buf();
let configured = excluded.to_vec();
let clones = std::path::PathBuf::from(&self.config.git_clone_base_path);
let artifacts = std::path::PathBuf::from(&self.config.artifact_store_base_path);
let pruned = tokio::task::spawn_blocking(move || {
use crate::pipeline::test_data::{prune, test_data_dirs};
let owned = [clones.as_path(), artifacts.as_path()];
// Nothing to remove needs no ownership check (and no warning for
// a tree outside the agent's directories).
let prune_some = |paths: &[String]| {
if paths.is_empty() {
Ok(Vec::new())
} else {
prune(&root, paths, &owned)
}
};
// The configured paths first: test data inside them is gone with
// them and not listed twice.
let excluded = prune_some(&configured)?;
let missing: Vec<String> = configured
.into_iter()
.filter(|p| !excluded.contains(p))
.collect();
let test_data = prune_some(&test_data_dirs(&root))?;
Ok::<_, crate::pipeline::test_data::PruneError>((
LeftOut {
excluded,
test_data,
},
missing,
))
})
.await;
let (left_out, missing) = match pruned {
Ok(Ok(done)) => done,
Ok(Err(e)) => {
tracing::warn!(scan_run_id, error = %e, "nothing taken out of the scan");
return LeftOut::default();
}
Err(e) => {
tracing::warn!(scan_run_id, error = %e, "left-out walk failed");
return LeftOut::default();
}
};
if !left_out.excluded.is_empty() || !missing.is_empty() {
let list = left_out.excluded.join(", ");
let mut reason = format!(
"excluded in the target's settings, left out of the whole scan (code findings, \
SBOM, CVE match): {list}"
);
if !missing.is_empty() {
reason.push_str(&format!("; not in the tree: {}", missing.join(", ")));
}
self.skip_stage(
scan_run_id,
SkippedStage::new("excluded_paths", SkipCode::ExcludedPaths, reason).about(list),
)
.await;
}
if !left_out.test_data.is_empty() {
let list = left_out.test_data.join(", ");
self.skip_stage(
scan_run_id,
SkippedStage::new(
"test_data",
SkipCode::TestData,
format!(
"test data is left out of the whole scan (code findings, SBOM, CVE \
match): {list}"
),
)
.about(list),
)
.await;
}
left_out
}
/// The recipe lint of a tree whose `languages` include BitBake, outside
/// the `vendor` directories: the findings, and the scanners that
/// completed. Upstream layers left out and findings suppressed in the
@@ -2454,6 +2905,167 @@ impl PipelineOrchestrator {
/// The recipes, images and package groups of a Yocto layer tree. A parser
/// that failed, a tree with no layer, or recipes the parser could not read
/// are recorded on the run.
/// Scan a target whose only code-like input is its build output: the
/// stages run over an empty working directory (nothing to find there),
/// with the build outputs read as for a layer tree. The run says that
/// there was no source code.
///
/// # Returns
///
/// How many findings were new.
///
/// # Errors
///
/// The working directory cannot be made, or a stage fails as in
/// [`Self::scan_tree`].
async fn scan_build_output_only(
&self,
target: &OnboardedTarget,
target_id: &str,
working_paths: &std::collections::HashMap<String, std::path::PathBuf>,
scan_run_id: &str,
) -> Result<u32, AgentError> {
let Some(first) = target
.artifacts
.iter()
.find(|a| a.kind == ArtifactKind::BuildOutput)
else {
return Ok(0);
};
self.skip_stage(
scan_run_id,
SkippedStage::new(
"source_code",
SkipCode::NotAnalysedYet,
"the target has no source code (a git repository or a source archive): only \
its build output is read; code analysis, the recipe inventory and the recipe \
lint need the layer tree",
),
)
.await;
// Under the agent's own work directory, so it is never a tree the
// scan may not touch, and empty on every run.
let tree = crate::ingest::blob::work_dir(
std::path::Path::new(&self.config.artifact_store_base_path),
target_id,
"build-output-only",
);
let _ = std::fs::remove_dir_all(&tree);
std::fs::create_dir_all(&tree)
.map_err(|e| AgentError::Other(format!("build-output work directory: {e}")))?;
let mut repo = RepoView::from_target(target, first, &self.secrets);
repo.build_outputs = build_output_paths(target, working_paths);
let scanned = self.scan_tree(&tree, None, &repo, scan_run_id).await;
let _ = std::fs::remove_dir_all(&tree);
let n = scanned?;
self.finalize_target(target, &repo, n).await?;
Ok(n)
}
/// What the target's build outputs say: the images their SPDX archives
/// describe ([`crate::pipeline::yocto_spdx`]) and their cve-check reports
/// ([`crate::pipeline::yocto_cve_check`]), told apart by content. One
/// that cannot be read is noted on the run (and skipped), and so are
/// packages an archive lists in an image without their documents.
async fn read_build_outputs(
&self,
repo: &RepoView,
repo_id: &str,
scan_run_id: &str,
) -> (
Vec<crate::pipeline::yocto_spdx::BuiltImage>,
Vec<crate::pipeline::yocto_cve_check::CveCheck>,
) {
/// One build output, read as what it is.
enum Read {
Images(Vec<crate::pipeline::yocto_spdx::BuiltImage>),
Check(crate::pipeline::yocto_cve_check::CveCheck),
}
let mut images = Vec::new();
let mut checks = Vec::new();
for path in &repo.build_outputs {
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let file = path.clone();
let id = repo_id.to_string();
let read = tokio::task::spawn_blocking(move || -> Result<Read, String> {
let mut head = [0u8; 512];
let n = {
use std::io::Read as _;
std::fs::File::open(&file)
.and_then(|mut f| f.read(&mut head))
.map_err(|e| e.to_string())?
};
// An SPDX 3.0 image document is JSON too: recognised first.
if crate::pipeline::yocto_spdx3::is_spdx3(&head[..n]) {
return crate::pipeline::yocto_spdx3::read(&file, &id)
.map(Read::Images)
.map_err(|e| e.to_string());
}
if crate::pipeline::yocto_cve_check::is_cve_check(&head[..n]) {
return crate::pipeline::yocto_cve_check::read(&file)
.map(Read::Check)
.map_err(|e| e.to_string());
}
crate::pipeline::yocto_spdx::read_archive(
&file,
&id,
crate::pipeline::yocto_spdx::ReadLimits::default(),
)
.map(Read::Images)
.map_err(|e| e.to_string())
})
.await;
match read {
Ok(Ok(Read::Images(read))) => images.extend(read),
Ok(Ok(Read::Check(check))) => checks.push(check),
Ok(Err(e)) => {
tracing::warn!(scan_run_id, file = %name, error = %e, "build output not read");
self.skip_stage(
scan_run_id,
SkippedStage::new(
crate::pipeline::yocto_spdx::STAGE,
SkipCode::ArtifactNotIngested,
format!(
"{name} was not read as a Yocto image SPDX archive \
(<image>.spdx.tar.zst), SPDX 3.0 image document \
(<image>.spdx.json) or cve-check report (<image>.json): {e}"
),
)
.about(name),
)
.await;
}
Err(e) => tracing::warn!(scan_run_id, error = %e, "build output read failed"),
}
}
let unresolved: Vec<String> = images
.iter()
.flat_map(|i| i.unresolved.iter().cloned())
.collect::<std::collections::BTreeSet<_>>()
.into_iter()
.collect();
if !unresolved.is_empty() {
let list = component_list(&unresolved);
self.skip_stage(
scan_run_id,
SkippedStage::new(
crate::pipeline::yocto_spdx::STAGE,
SkipCode::BuildPackagesUnresolved,
format!(
"the image SPDX lists these packages in the image without their \
documents, so their recipes are not known: {list}"
),
)
.about(list),
)
.await;
}
(images, checks)
}
async fn yocto_recipes(&self, tree: &std::path::Path, scan_run_id: &str) -> Inventory {
match yocto_inventory::read(tree).await {
Ok(inventory) if inventory.recipes.is_empty() && inventory.errors.is_empty() => {
@@ -2733,6 +3345,25 @@ pub(super) fn extract_base_url(git_url: &str) -> Option<String> {
}
}
/// The ingested files of `target`'s build outputs (Yocto image SPDX
/// archives), or the stored upload where ingest recorded no working path.
fn build_output_paths(
target: &OnboardedTarget,
working_paths: &std::collections::HashMap<String, std::path::PathBuf>,
) -> Vec<std::path::PathBuf> {
target
.artifacts
.iter()
.filter(|a| a.kind == ArtifactKind::BuildOutput)
.filter_map(|a| {
working_paths
.get(&a.id)
.cloned()
.or_else(|| a.stored_path.as_deref().map(std::path::PathBuf::from))
})
.collect()
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
+6 -2
View File
@@ -386,8 +386,12 @@ mod tests {
fn oauth_token_url_matches() {
let scanner = OAuthPatternScanner::new();
let pattern = &scanner.patterns[3]; // oauth-token-url
assert!(pattern.pattern.is_match("access_token = build_url(query)"));
assert!(pattern.pattern.is_match("bearer = url.param"));
// Split, so this file's own line does not match the rule it tests
// when Prüfwerk scans its own repository.
assert!(pattern
.pattern
.is_match(concat!("access_", "token = build_url(query)")));
assert!(pattern.pattern.is_match(concat!("bear", "er = url.param")));
}
// --- Pattern rule file extension filtering ---
+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(
@@ -45,10 +45,21 @@ pub struct RepoView {
/// Whether the target's uploaded files let a scheduled scan without new
/// commits be skipped ([`crate::pipeline::change::uploads_allow_git_skip`]).
pub uploads_allow_skip: bool,
/// Whether the customer changed something besides the commits since the
/// last completed scan: an uploaded file, or a live URL to probe (t72).
pub changed_besides_commits: bool,
/// How the target is billed, for whether its scan counts (t72).
pub billing: compliance_core::models::TargetBilling,
/// Whether the tree is read as Yocto layers (its recipe inventory): it
/// was classified as one, or the target is a Yocto target. Set by the
/// caller after classification; `false` from [`Self::from_target`].
pub yocto_layers: bool,
/// Directories and files the target's settings leave out of every scan
/// stage (`scan_config.exclude_paths`).
pub exclude_paths: Vec<String>,
/// The target's uploaded build outputs (Yocto image SPDX archives), as
/// ingested. Set by the caller; empty from [`Self::from_target`].
pub build_outputs: Vec<std::path::PathBuf>,
}
impl RepoView {
@@ -78,7 +89,12 @@ impl RepoView {
findings_count: target.findings_count,
managed: target.source_repo.is_some(),
uploads_allow_skip: crate::pipeline::change::uploads_allow_git_skip(target),
changed_besides_commits: target.live_url().is_some()
|| crate::pipeline::change::uploads_changed(target),
billing: target.billing,
yocto_layers: false,
exclude_paths: target.scan_config.exclude_paths.clone(),
build_outputs: Vec::new(),
};
if let Some(git) = &code.git {
view.default_branch = git.default_branch.clone();
+509
View File
@@ -0,0 +1,509 @@
//! Test data inside a scanned tree: fixtures, sample projects, golden files.
//!
//! A repository's test data is not what it ships. Its sample lockfiles name
//! old, vulnerable dependencies on purpose, its sample code holds the flaws a
//! test expects to find, and none of it is the product's to fix. Scanned as
//! product code, it buries the real findings: the CVE issues of a test
//! fixture's `struts2 2.3.30` read exactly like those of a dependency the
//! product uses.
//!
//! So the directories that hold test data by a common convention are taken
//! out of the scan's working copy before the first stage runs, and every
//! stage — code findings, SBOM, CVE match — sees the tree without them. The
//! working copy is a git clone, restored on every fetch, or an unpacked
//! upload, unpacked again on every scan, so nothing is lost.
//!
//! Matching is by directory name, and narrow: `tests/` and `spec/` hold test
//! code that can leak a real secret, and `examples/` or `demo/` are often the
//! product's own code, so neither is matched.
//!
//! One more kind is found by its content: a Semgrep rule pack. Semgrep's own
//! test convention puts each rule `X.yaml` next to the sample it is tested
//! on, `X.py` or `X.cs`, and the samples hold the flaws the rules must find.
//! A directory with such a pair is test data with everything below it (a
//! vendored pack's manifests too), unless it is the tree itself.
use std::collections::{HashMap, HashSet};
use std::ffi::OsString;
use std::path::{Path, PathBuf};
/// Directory names that hold test data by convention, compared
/// case-insensitively: `fixtures` (Rails, pytest, Jest's `__fixtures__`),
/// Go's `testdata`, and their spellings.
const TEST_DATA_DIR_NAMES: &[&str] = &[
"fixtures",
"__fixtures__",
"testdata",
"test_data",
"test-data",
"test-fixtures",
"test_fixtures",
];
/// A rule file larger than this is not read: Semgrep rule files are a few
/// kilobytes, and a large YAML file is data, not a rule pack.
const MAX_RULE_FILE_BYTES: u64 = 1024 * 1024;
/// The top-most test-data directories under `root`, relative to it with `/`
/// separators, sorted: those named like test data, and Semgrep rule packs
/// with their samples. A directory inside one that already matched is not
/// listed again, `root` itself is never listed, and a symbolic link is never
/// followed or listed.
///
/// # Arguments
///
/// * `root` - the scanned tree
///
/// # Returns
///
/// The directories to leave out of the scan, e.g. `["fixtures",
/// "pkg/parser/testdata"]`.
pub fn test_data_dirs(root: &Path) -> Vec<String> {
let mut found = Vec::new();
// YAML files outside the test data found so far: rule pack candidates,
// checked once the walk is done.
let mut yaml_files = Vec::new();
let mut walker = walkdir::WalkDir::new(root).min_depth(1).into_iter();
while let Some(entry) = walker.next() {
let Ok(entry) = entry else {
continue;
};
// `file_type()` does not follow links: a link to a directory is a
// link here, never a directory.
if entry.file_type().is_file() {
if is_yaml(entry.path()) {
yaml_files.push(entry.into_path());
}
continue;
}
if !entry.file_type().is_dir() {
continue;
}
let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
if name == ".git" {
walker.skip_current_dir();
continue;
}
if TEST_DATA_DIR_NAMES.contains(&name.as_str()) {
if let Ok(rel) = entry.path().strip_prefix(root) {
found.push(rel.to_string_lossy().replace('\\', "/"));
}
walker.skip_current_dir();
}
}
found.extend(rule_pack_dirs(root, &yaml_files));
top_most(found)
}
/// The directories, relative to `root`, of the `yaml_files` that are Semgrep
/// rules with a sample of the same name next to them. Each directory is read
/// once, and a rule file only when such a sample exists.
fn rule_pack_dirs(root: &Path, yaml_files: &[PathBuf]) -> Vec<String> {
// Per directory: the names (without extension) of its files that are not
// YAML, the possible samples.
let mut samples: HashMap<&Path, HashSet<OsString>> = HashMap::new();
let mut packs: HashSet<&Path> = HashSet::new();
for rule in yaml_files {
let (Some(dir), Some(stem)) = (rule.parent(), rule.file_stem()) else {
continue;
};
if dir == root || packs.contains(dir) {
continue;
}
let names = samples.entry(dir).or_insert_with(|| sample_stems(dir));
if names.contains(stem) && is_semgrep_rule_file(rule) {
packs.insert(dir);
}
}
packs
.into_iter()
.filter_map(|dir| dir.strip_prefix(root).ok())
.map(|rel| rel.to_string_lossy().replace('\\', "/"))
.collect()
}
/// The names without extension of the regular files in `dir` that are not
/// YAML.
fn sample_stems(dir: &Path) -> HashSet<OsString> {
let Ok(entries) = std::fs::read_dir(dir) else {
return HashSet::new();
};
entries
.flatten()
.filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
.map(|e| e.path())
.filter(|p| !is_yaml(p))
.filter_map(|p| p.file_stem().map(OsString::from))
.collect()
}
/// Whether `path` ends in `.yaml` or `.yml`.
fn is_yaml(path: &Path) -> bool {
path.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("yaml") || ext.eq_ignore_ascii_case("yml"))
}
/// Whether the file at `path` is a Semgrep rule file: a `rules` list with at
/// least one rule naming its `id`, `languages` and `message`, which Semgrep
/// requires of every rule.
fn is_semgrep_rule_file(path: &Path) -> bool {
if !std::fs::metadata(path).is_ok_and(|m| m.len() <= MAX_RULE_FILE_BYTES) {
return false;
}
let Ok(text) = std::fs::read_to_string(path) else {
return false;
};
let Ok(docs) = yaml_rust2::YamlLoader::load_from_str(&text) else {
return false;
};
docs.first()
.and_then(|doc| doc["rules"].as_vec())
.is_some_and(|rules| {
rules.iter().any(|rule| {
rule["id"].as_str().is_some()
&& !rule["languages"].is_badvalue()
&& !rule["message"].is_badvalue()
})
})
}
/// `dirs` sorted, without those inside another one listed.
fn top_most(mut dirs: Vec<String>) -> Vec<String> {
dirs.sort();
dirs.dedup();
let mut kept: Vec<String> = Vec::with_capacity(dirs.len());
for dir in dirs {
let inside = kept.iter().any(|outer| {
dir.strip_prefix(outer.as_str())
.is_some_and(|rest| rest.starts_with('/'))
});
if !inside {
kept.push(dir);
}
}
kept
}
/// Remove the `paths` (the [`test_data_dirs`], or the directories and files
/// a target's settings exclude) from the working copy at `root`.
///
/// Only a working copy the agent made may lose files: `root` must lie under
/// one of `owned_bases` (the clone base and the artifact store). Anything
/// else is refused, so the call can never delete a directory it was pointed
/// at by mistake. A path is only removed when it lies inside `root` without
/// passing a symbolic link: `src/link/x` with `src/link` pointing elsewhere
/// is left alone, and so is a link itself.
///
/// # Arguments
///
/// * `root` - the scan's working copy
/// * `paths` - directories or files relative to `root`, `/`-separated
/// * `owned_bases` - the directories the agent's working copies live under
///
/// # Returns
///
/// The paths that were removed; one that is not in the tree is left out, and
/// one that could not be removed is logged and left out.
///
/// # Errors
///
/// [`PruneError::NotOwned`] when `root` lies under none of `owned_bases`;
/// nothing is removed then.
pub fn prune(
root: &Path,
paths: &[String],
owned_bases: &[&Path],
) -> Result<Vec<String>, PruneError> {
let owned = owned_bases
.iter()
.any(|base| !base.as_os_str().is_empty() && root.starts_with(base) && root != *base);
if !owned {
return Err(PruneError::NotOwned);
}
let mut removed = Vec::with_capacity(paths.len());
for rel in paths {
let Some(path) = inside_without_links(root, rel) else {
continue;
};
let Ok(meta) = std::fs::symlink_metadata(&path) else {
continue;
};
let outcome = if meta.is_dir() {
std::fs::remove_dir_all(&path)
} else if meta.is_file() {
std::fs::remove_file(&path)
} else {
continue;
};
match outcome {
Ok(()) => removed.push(rel.clone()),
Err(e) => tracing::warn!(path = %rel, error = %e, "left-out path not removed"),
}
}
Ok(removed)
}
/// `root` joined with `rel` when every component of `rel` is a plain name
/// and none of the directories on the way is a symbolic link; `None`
/// otherwise (also when a part does not exist).
fn inside_without_links(root: &Path, rel: &str) -> Option<std::path::PathBuf> {
let rel_path = Path::new(rel);
if rel_path.is_absolute() {
return None;
}
let mut path = root.to_path_buf();
for component in rel_path.components() {
let std::path::Component::Normal(name) = component else {
tracing::warn!(path = %rel, "left-out path outside the tree; not removed");
return None;
};
path.push(name);
let meta = std::fs::symlink_metadata(&path).ok()?;
if meta.file_type().is_symlink() {
return None;
}
}
(path != root).then_some(path)
}
/// Why [`prune`] removed nothing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum PruneError {
/// The tree is not a working copy the agent made.
#[error("the tree is not under the agent's clone or artifact directories")]
NotOwned,
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
fn write(root: &Path, rel: &str) {
let path = root.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "x").unwrap();
}
/// A scratch directory, removed on drop.
struct Scratch(std::path::PathBuf);
impl Scratch {
fn new() -> Self {
let dir = std::env::temp_dir().join(format!("cs-testdata-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
Self(dir)
}
fn path(&self) -> &Path {
&self.0
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// A working copy under a fake clone base: `(base, tree)`.
fn tree() -> (Scratch, std::path::PathBuf) {
let base = Scratch::new();
let root = base.path().join("tenant").join("repo");
for file in [
"src/main.rs",
"src/fixtures_helper.rs",
"src/fixtures.rs",
"fixtures/nightly/eco/maven/pom.xml",
"fixtures/nightly/eco/maven/fixtures/inner.txt",
"pkg/parser/testdata/input.json",
"web/__fixtures__/user.json",
"Tests/Test-Data/sample.csv",
"tests/integration.rs",
"examples/demo.rs",
".git/fixtures/HEAD",
] {
write(&root, file);
}
(base, root)
}
#[test]
fn test_data_is_found_by_name_and_reported_once() {
let (_base, root) = tree();
assert_eq!(
test_data_dirs(&root),
[
"Tests/Test-Data",
"fixtures",
"pkg/parser/testdata",
"web/__fixtures__",
]
);
}
/// A Semgrep rule file with one rule.
const RULE: &str = "rules:\n - id: no-exec\n languages: [python]\n \
message: exec runs code\n severity: ERROR\n pattern: exec(...)\n";
fn write_text(root: &Path, rel: &str, text: &str) {
let path = root.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
#[test]
fn a_semgrep_rule_pack_with_its_samples_is_test_data() {
let (_base, root) = tree();
// A pack: a rule and its sample, with a vendored pack below it.
write_text(&root, "agent/rules/cra.yaml", RULE);
write(&root, "agent/rules/cra.py");
write(&root, "agent/rules/vendor/gitlab/java/pom.xml");
write_text(
&root,
"agent/rules/vendor/gitlab/java/inject/ognl.yml",
RULE,
);
write(&root, "agent/rules/vendor/gitlab/java/inject/ognl.java");
// Not packs: a configuration next to the code it configures, a rule
// without a sample, and a rule pack that is the tree itself.
write_text(&root, "app/settings.yaml", "debug: true\n");
write(&root, "app/settings.py");
write_text(&root, "ci/.semgrep.yml", RULE);
write(&root, "ci/build.sh");
write_text(&root, "local.yaml", RULE);
write(&root, "local.py");
let dirs = test_data_dirs(&root);
assert!(dirs.contains(&"agent/rules".to_string()));
assert!(
!dirs.iter().any(|d| d.starts_with("agent/rules/")),
"a pack inside the pack is not listed again: {dirs:?}"
);
for not_test_data in ["app", "ci", ""] {
assert!(
!dirs.contains(&not_test_data.to_string()),
"{not_test_data}"
);
}
}
#[test]
fn a_large_or_unreadable_yaml_file_is_not_a_rule_file() {
let base = Scratch::new();
write_text(base.path(), "big.yaml", &"x: 1\n".repeat(300_000));
write_text(base.path(), "broken.yaml", "rules: [\n");
write_text(base.path(), "rule.yaml", RULE);
assert!(!is_semgrep_rule_file(&base.path().join("big.yaml")));
assert!(!is_semgrep_rule_file(&base.path().join("broken.yaml")));
assert!(is_semgrep_rule_file(&base.path().join("rule.yaml")));
}
#[test]
fn only_the_top_most_directories_are_kept() {
let dirs = ["a/b", "a", "a-x", "a/b/c", "b"].map(String::from).to_vec();
assert_eq!(top_most(dirs), ["a", "a-x", "b"]);
}
#[test]
fn the_tree_itself_is_never_test_data() {
let base = Scratch::new();
let root = base.path().join("fixtures");
write(&root, "package-lock.json");
assert!(test_data_dirs(&root).is_empty());
}
#[test]
fn pruning_removes_the_test_data_and_keeps_the_rest() {
let (base, root) = tree();
let dirs = test_data_dirs(&root);
let removed = prune(&root, &dirs, &[base.path()]).unwrap();
assert_eq!(removed, dirs);
assert!(!root.join("fixtures").exists());
assert!(!root.join("pkg/parser/testdata").exists());
assert!(root.join("pkg/parser").is_dir());
for kept in [
"src/main.rs",
"src/fixtures_helper.rs",
"src/fixtures.rs",
"tests/integration.rs",
"examples/demo.rs",
".git/fixtures/HEAD",
] {
assert!(root.join(kept).is_file(), "{kept} must stay");
}
}
#[test]
fn a_tree_the_agent_did_not_make_is_never_pruned() {
let (_base, root) = tree();
let elsewhere = Scratch::new();
let dirs = test_data_dirs(&root);
assert_eq!(
prune(&root, &dirs, &[elsewhere.path()]),
Err(PruneError::NotOwned)
);
// The base itself is not a working copy, and an empty base owns nothing.
assert_eq!(
prune(&root, &dirs, &[root.as_path(), Path::new("")]),
Err(PruneError::NotOwned)
);
assert!(root.join("fixtures").is_dir());
}
#[test]
fn a_configured_file_or_directory_is_removed_and_a_missing_one_skipped() {
let (base, root) = tree();
let removed = prune(
&root,
&[
"src/main.rs".to_string(),
"examples".to_string(),
"not/there".to_string(),
],
&[base.path()],
)
.unwrap();
assert_eq!(removed, ["src/main.rs", "examples"]);
assert!(!root.join("src/main.rs").exists());
assert!(root.join("src/fixtures.rs").is_file());
assert!(!root.join("examples").exists());
}
#[cfg(unix)]
#[test]
fn a_path_through_a_link_is_never_followed() {
let (base, root) = tree();
let outside = base.path().join("outside");
write(&outside, "keep/me.txt");
std::os::unix::fs::symlink(&outside, root.join("src/link")).unwrap();
let removed = prune(&root, &["src/link/keep".to_string()], &[base.path()]).unwrap();
assert!(removed.is_empty());
assert!(outside.join("keep/me.txt").is_file());
}
#[test]
fn a_path_outside_the_tree_is_never_removed() {
let (base, root) = tree();
let removed = prune(
&root,
&["../repo/src".to_string(), "/etc".to_string()],
&[base.path()],
)
.unwrap();
assert!(removed.is_empty());
assert!(root.join("src/main.rs").is_file());
}
#[cfg(unix)]
#[test]
fn a_link_named_like_test_data_is_left_alone() {
let (base, root) = tree();
let target = base.path().join("outside");
write(&target, "keep.txt");
std::os::unix::fs::symlink(&target, root.join("src/testdata")).unwrap();
let dirs = test_data_dirs(&root);
assert!(!dirs.contains(&"src/testdata".to_string()));
prune(&root, &["src/testdata".to_string()], &[base.path()]).unwrap();
assert!(target.join("keep.txt").is_file());
assert!(root.join("src/testdata").exists());
}
}
@@ -0,0 +1,715 @@
//! A Yocto build's own evidence (its image SPDX, [`crate::pipeline::yocto_spdx`])
//! combined with the recipe inventory of the layer tree
//! ([`crate::pipeline::yocto_inventory`]).
//!
//! The two name the same recipes differently: the inventory reads PV as
//! written (`linux-yocto 6.6`), the build records what it built
//! (`6.6.151+git`). So they are joined by recipe name, and for a recipe in
//! both the build wins: its version, CPE and licence, and its image marking
//! ([`InImageBasis::Built`]). An image the build's SPDX covers is
//! authoritative: a recipe the inventory declares in it but the build did not
//! install loses that marking; images the SPDX does not cover keep theirs.
//!
//! The build also says which CVEs its patches fixed; those become `fixed`
//! VEX statements on the matching alerts, ahead of what the recipes state.
//! Its cve-check report ([`crate::pipeline::yocto_cve_check`]), when it was
//! uploaded too, goes first: Yocto's verdict on every CVE it looked at, and
//! the CVEs it found unpatched that NVD's match here did not.
use std::collections::{BTreeMap, BTreeSet, HashMap};
use compliance_core::models::{
CveAlert, InImage, InImageBasis, SbomEntry, VexAssessment, VexJustification, VexStatus,
YOCTO_RECIPE_MANAGER,
};
use crate::pipeline::nvd_cpe::NvdCve;
use crate::pipeline::yocto_cve_check::{CheckStatus, CheckedIssue, CveCheck};
use crate::pipeline::yocto_inventory::{self, CpeProduct, NvdQuery, Recipe};
use crate::pipeline::yocto_spdx::{BuiltImage, NotAffectedCve};
/// What the build installed, across its images, by recipe name.
#[derive(Debug, Default)]
pub struct Built<'a> {
/// One component per recipe (the first image's, with every image named).
components: BTreeMap<String, SbomEntry>,
/// The images the SPDX covers (`core-image-minimal`).
images: BTreeSet<String>,
/// The CVEs fixed per recipe name.
fixed: HashMap<String, BTreeSet<&'a str>>,
/// What the build's SPDX 3.0 VEX says does not affect each recipe, by CVE.
not_affected: HashMap<&'a str, HashMap<&'a str, &'a NotAffectedCve>>,
/// Yocto's cve-check verdicts per recipe name, by CVE.
checked: HashMap<&'a str, HashMap<&'a str, &'a CheckedIssue>>,
/// The version cve-check names each recipe at.
checked_versions: BTreeMap<&'a str, &'a str>,
}
impl<'a> Built<'a> {
/// Gather `images` (from one or more build-output archives) and the
/// cve-check reports `checks`.
pub fn new(images: &'a [BuiltImage], checks: &'a [CveCheck]) -> Self {
let mut built = Self::default();
for package in checks.iter().flat_map(|c| &c.packages) {
built
.checked_versions
.insert(package.name.as_str(), package.version.as_str());
let issues = built.checked.entry(package.name.as_str()).or_default();
for issue in &package.issues {
issues.insert(issue.id.as_str(), issue);
}
}
for image in images {
built.images.insert(image.image.clone());
for entry in &image.entries {
match built.components.get_mut(&entry.name) {
Some(known) => add_image(known, &image.image),
None => {
built.components.insert(entry.name.clone(), entry.clone());
}
}
}
for fixed in &image.fixed {
built
.fixed
.entry(fixed.component.clone())
.or_default()
.insert(fixed.cve.as_str());
}
for na in &image.not_affected {
built
.not_affected
.entry(na.component.as_str())
.or_default()
.insert(na.cve.as_str(), na);
}
}
built
}
/// Whether the build listed nothing.
pub fn is_empty(&self) -> bool {
self.components.is_empty() && self.checked.is_empty()
}
/// The CVEs cve-check found unpatched that `alerts` do not have, per
/// recipe and version (the built one where the build lists the recipe),
/// for recipes `known` (components of the scan) only.
pub fn unpatched_missing(
&self,
alerts: &[CveAlert],
known: impl Fn(&str) -> bool,
) -> Vec<(String, String, Vec<NvdCve>)> {
let mut out = Vec::new();
for (name, issues) in &self.checked {
if !known(name) {
continue;
}
let version = self
.components
.get(*name)
.map(|c| c.version.as_str())
.or_else(|| self.checked_versions.get(name).copied())
.unwrap_or_default();
let mut missing: Vec<NvdCve> = issues
.values()
.filter(|i| i.status == CheckStatus::Unpatched)
.filter(|i| {
!alerts
.iter()
.any(|a| a.affected_package == *name && a.cve_id == i.id)
})
.map(|i| NvdCve {
id: i.id.clone(),
summary: i.summary.clone(),
cvss: i.cvss(),
})
.collect();
if missing.is_empty() {
continue;
}
missing.sort_by(|a, b| a.id.cmp(&b.id));
out.push((name.to_string(), version.to_string(), missing));
}
out.sort_by(|a, b| a.0.cmp(&b.0));
out
}
/// Yocto's cve-check verdict on `cve` of `package`, as a statement:
/// Patched is fixed, Ignored as its CVE_STATUS reason says, Unpatched
/// none.
fn checked_statement(&self, package: &str, cve: &str) -> Option<VexAssessment> {
let issue = self.checked.get(package)?.get(cve)?;
let (status, justification) = match issue.status {
CheckStatus::Unpatched => return None,
// Yocto's kernel CVE report (improve_kernel_cve_report.py) says
// Patched when the version is outside the affected range: not
// affected rather than fixed.
CheckStatus::Patched if issue.detail.as_deref() == Some("version-not-in-range") => (
VexStatus::NotAffected,
Some(VexJustification::VulnerableCodeNotPresent),
),
CheckStatus::Patched => (VexStatus::Fixed, None),
CheckStatus::Ignored => {
yocto_inventory::status_statement(issue.detail.as_deref().unwrap_or("ignored"))?
}
};
let verdict = match issue.status {
CheckStatus::Patched => "Patched",
CheckStatus::Ignored => "Ignored",
CheckStatus::Unpatched => "Unpatched",
};
let mut because = format!("Yocto cve-check: {verdict}");
if let Some(detail) = issue.detail.as_deref() {
because.push_str(&format!(" ({detail})"));
}
if let Some(note) = issue.description.as_deref().filter(|n| !n.is_empty()) {
because.push_str(&format!(": {note}"));
}
Some(yocto_inventory::scan_statement(
status,
justification,
because,
))
}
/// The SBOM components: `inventory` (the recipe inventory's) joined with
/// what the build installed, by recipe name. See the module docs.
pub fn merge(&self, inventory: Vec<SbomEntry>) -> Vec<SbomEntry> {
let mut out = Vec::with_capacity(inventory.len() + self.components.len());
let mut joined = BTreeSet::new();
for mut entry in inventory {
if entry.package_manager != YOCTO_RECIPE_MANAGER {
out.push(entry);
continue;
}
match self.components.get(&entry.name) {
Some(built) => {
joined.insert(entry.name.clone());
out.push(self.joined(entry, built));
}
None => {
self.uncover(&mut entry);
out.push(entry);
}
}
}
out.extend(
self.components
.values()
.filter(|c| !joined.contains(&c.name))
.cloned(),
);
out
}
/// `inventory`'s component with what the build says about it.
fn joined(&self, inventory: SbomEntry, built: &SbomEntry) -> SbomEntry {
let mut entry = built.clone();
// The inventory knows where the recipe is and what it fetches.
entry.download_url = built.download_url.clone().or(inventory.download_url);
entry.license = built.license.clone().or(inventory.license);
entry.cpe = built.cpe.clone().or(inventory.cpe);
let declared_elsewhere: Vec<String> = inventory
.in_image
.as_ref()
.filter(|i| i.basis == InImageBasis::Declared)
.map(|i| {
i.images
.iter()
.filter(|image| !self.images.contains(*image))
.cloned()
.collect()
})
.unwrap_or_default();
let mut evidence: Vec<String> = inventory
.evidence
.into_iter()
.filter(|line| !line.starts_with(InImageBasis::Declared.describe()))
.collect();
if !declared_elsewhere.is_empty() {
evidence.push(
InImage {
basis: InImageBasis::Declared,
images: declared_elsewhere,
}
.describe(),
);
}
for line in built.evidence.iter() {
if !evidence.contains(line) {
evidence.push(line.clone());
}
}
entry.evidence = evidence;
entry
}
/// Take the images the build covers out of `entry`'s declared marking:
/// the build installed it there, or it is not there.
fn uncover(&self, entry: &mut SbomEntry) {
let Some(in_image) = entry
.in_image
.as_mut()
.filter(|i| i.basis == InImageBasis::Declared)
else {
return;
};
let before = in_image.describe();
in_image.images.retain(|image| !self.images.contains(image));
let after = (!in_image.images.is_empty()).then(|| in_image.describe());
if after.is_none() {
entry.in_image = None;
}
entry.evidence.retain(|line| *line != before);
entry.evidence.extend(after);
}
/// What to ask NVD: the inventory's `queries`, with the build's version
/// and CPE for a recipe the build installed, and a query for each built
/// recipe the inventory does not have. Returns the queries and the
/// components that cannot be asked about (no release version).
pub fn nvd_queries(&self, queries: Vec<NvdQuery>) -> (Vec<NvdQuery>, Vec<String>) {
let mut out: Vec<NvdQuery> = queries
.into_iter()
.filter(|q| !self.components.contains_key(&q.name))
.collect();
let mut unversioned = Vec::new();
for component in self.components.values() {
let products: Vec<CpeProduct> =
component.cpe.iter().filter_map(|c| product(c)).collect();
if products.is_empty() {
continue;
}
match yocto_inventory::release_of(&component.version) {
Some(cve_version) => out.push(NvdQuery {
name: component.name.clone(),
version: component.version.clone(),
cve_version,
products,
}),
None => unversioned.push(format!("{} (no release version)", component.name)),
}
}
(out, unversioned)
}
/// The VEX statements on `alerts`: `fixed` for a CVE the build's patches
/// fixed in the component, else what its recipe in the tree states
/// (joined by name, whatever version either side names), else what
/// [`yocto_inventory::vex_statements`] finds.
pub fn statements(
&self,
recipes: &[Recipe],
alerts: &[CveAlert],
) -> Vec<(String, VexAssessment)> {
let (built_alerts, other): (Vec<&CveAlert>, Vec<&CveAlert>) =
alerts.iter().partition(|a| {
self.components.contains_key(&a.affected_package)
|| self.checked.contains_key(a.affected_package.as_str())
});
let mut out: Vec<(String, VexAssessment)> = built_alerts
.iter()
.filter_map(|alert| {
if let Some(checked) =
self.checked_statement(&alert.affected_package, &alert.cve_id)
{
return Some((alert.cve_id.clone(), checked));
}
if let Some(na) = self
.not_affected
.get(alert.affected_package.as_str())
.and_then(|cves| cves.get(alert.cve_id.as_str()))
{
return Some((alert.cve_id.clone(), not_affected_statement(na)));
}
let fixed = self
.fixed
.get(&alert.affected_package)
.is_some_and(|cves| cves.contains(alert.cve_id.as_str()));
let statement = if fixed {
Some(yocto_inventory::scan_statement(
VexStatus::Fixed,
None,
format!(
"Fixed by a patch the build applied to {} (Yocto create-spdx: CVEs \
fixed)",
alert.affected_package
),
))
} else {
recipes
.iter()
.find(|r| r.bpn == alert.affected_package)
.and_then(|r| yocto_inventory::recipe_statement(r, &alert.cve_id))
};
statement.map(|vex| (alert.cve_id.clone(), vex))
})
.collect();
let rest: Vec<CveAlert> = other.into_iter().cloned().collect();
out.extend(yocto_inventory::vex_statements(recipes, &rest));
out
}
}
/// The statement the build's SPDX 3.0 makes that `na` does not affect its
/// component, with its justification and impact statement.
fn not_affected_statement(na: &NotAffectedCve) -> VexAssessment {
let justification = match na.justification.as_deref() {
Some("componentNotPresent") => Some(VexJustification::ComponentNotPresent),
Some("vulnerableCodeNotPresent") => Some(VexJustification::VulnerableCodeNotPresent),
Some("vulnerableCodeNotInExecutePath") => {
Some(VexJustification::VulnerableCodeNotInExecutePath)
}
Some("vulnerableCodeCannotBeControlledByAdversary") => {
Some(VexJustification::VulnerableCodeCannotBeControlledByAdversary)
}
Some("inlineMitigationsAlreadyExist") => {
Some(VexJustification::InlineMitigationsAlreadyExist)
}
_ => None,
};
let mut because = "Yocto SPDX 3.0 VEX: not affected".to_string();
if let Some(statement) = na.statement.as_deref().filter(|s| !s.is_empty()) {
because.push_str(&format!(": {statement}"));
}
yocto_inventory::scan_statement(VexStatus::NotAffected, justification, because)
}
/// Add `image` to `entry`'s built marking and its evidence line.
fn add_image(entry: &mut SbomEntry, image: &str) {
let Some(in_image) = entry.in_image.as_mut() else {
return;
};
if in_image.images.iter().any(|i| i == image) {
return;
}
let before = in_image.describe();
in_image.images.push(image.to_string());
let after = in_image.describe();
for line in entry.evidence.iter_mut() {
if *line == before {
line.clone_from(&after);
}
}
}
/// The product a CPE 2.3 name names (`cpe:2.3:*:openssl:openssl:3.5.9:…` →
/// vendor `openssl`, product `openssl`; a `*` vendor is any vendor).
fn product(cpe: &str) -> Option<CpeProduct> {
let mut parts = cpe.split(':');
if parts.next()? != "cpe" || parts.next()? != "2.3" {
return None;
}
let _part = parts.next()?;
let vendor = parts.next()?;
let product = parts.next()?;
if product.is_empty() || product == "*" {
return None;
}
Some(CpeProduct {
vendor: (vendor != "*" && !vendor.is_empty()).then(|| vendor.replace('\\', "")),
product: product.replace('\\', ""),
})
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use crate::pipeline::yocto_spdx::{read_dir, ReadLimits};
fn built_images() -> Vec<BuiltImage> {
let dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../fixtures/yocto/spdx-scarthgap");
read_dir(&dir, "t", ReadLimits::default()).unwrap()
}
/// An inventory component as the recipe inventory makes it.
fn inventory(name: &str, version: &str, declared: &[&str]) -> SbomEntry {
let mut e = SbomEntry::new(
"t".into(),
name.into(),
version.into(),
YOCTO_RECIPE_MANAGER.into(),
);
e.evidence.push(format!(
"Yocto recipe inventory: recipes-core/{name}/{name}.bb"
));
if !declared.is_empty() {
let in_image = InImage {
basis: InImageBasis::Declared,
images: declared.iter().map(|s| s.to_string()).collect(),
};
e.evidence.push(in_image.describe());
e.in_image = Some(in_image);
}
e
}
#[test]
fn the_build_wins_by_recipe_name_whatever_version_the_tree_names() {
let images = built_images();
let built = Built::new(&images, &[]);
let merged = built.merge(vec![
// PV in the tree differs from what the build recorded.
inventory("busybox", "1.36", &["core-image-minimal", "rescue-image"]),
inventory("dropbear", "2024.85", &["core-image-minimal"]),
inventory("tool", "1.0", &["rescue-image"]),
SbomEntry::new("t".into(), "serde".into(), "1.0".into(), "cargo".into()),
]);
let by_name = |n: &str| merged.iter().find(|e| e.name == n).unwrap();
let busybox = by_name("busybox");
assert_eq!(busybox.version, "1.36.1");
assert_eq!(
busybox.in_image.as_ref().map(|i| i.basis),
Some(InImageBasis::Built)
);
assert!(busybox.evidence[0].starts_with("Yocto recipe inventory"));
// The image the SPDX does not cover keeps its declaration as evidence.
assert!(busybox.evidence.iter().any(
|l| l.starts_with(InImageBasis::Declared.describe()) && l.ends_with("rescue-image")
));
// The built image's declaration is gone: the build says where it is.
assert!(!busybox
.evidence
.iter()
.any(|l| l.starts_with(InImageBasis::Declared.describe())
&& l.contains("core-image-minimal")));
// Declared in the built image but not installed by the build: unmarked.
assert!(by_name("dropbear").in_image.is_none());
assert_eq!(by_name("dropbear").evidence.len(), 1);
// Another image's declaration is left alone.
assert_eq!(
by_name("tool").in_image.as_ref().map(|i| i.images.clone()),
Some(vec!["rescue-image".to_string()])
);
// Built only: added. Not a recipe component: untouched.
assert!(merged
.iter()
.any(|e| e.name == "openssl" && e.version == "3.5.9"));
assert_eq!(by_name("serde").package_manager, "cargo");
assert_eq!(merged.iter().filter(|e| e.name == "busybox").count(), 1);
}
#[test]
fn nvd_is_asked_with_the_built_version_and_cpe() {
let images = built_images();
let built = Built::new(&images, &[]);
let stale = NvdQuery {
name: "busybox".into(),
version: "1.36".into(),
cve_version: "1.36".into(),
products: vec![],
};
let other = NvdQuery {
name: "zlib".into(),
version: "1.3".into(),
cve_version: "1.3".into(),
products: vec![],
};
let (queries, unversioned) = built.nvd_queries(vec![stale, other]);
let names: Vec<(&str, &str)> = queries
.iter()
.map(|q| (q.name.as_str(), q.version.as_str()))
.collect();
assert!(names.contains(&("zlib", "1.3")), "{names:?}");
assert!(names.contains(&("busybox", "1.36.1")), "{names:?}");
assert!(!names.contains(&("busybox", "1.36")));
let openssl = queries.iter().find(|q| q.name == "openssl").unwrap();
assert_eq!(
openssl.products,
[CpeProduct {
vendor: Some("openssl".into()),
product: "openssl".into()
}]
);
// The package group has no CPE: nothing to ask, nothing missing.
assert!(!queries.iter().any(|q| q.name == "packagegroup-core-boot"));
assert!(unversioned.is_empty());
}
#[test]
fn a_cve_the_build_patched_is_stated_fixed() {
let images = built_images();
let built = Built::new(&images, &[]);
let alert = |package: &str, cve: &str| {
CveAlert::new(
cve.into(),
"t".into(),
package.into(),
"1.36.1".into(),
compliance_core::models::CveSource::Nvd,
)
};
let statements = built.statements(
&[],
&[
alert("busybox", "CVE-2022-48174"),
alert("busybox", "CVE-2099-0001"),
],
);
assert_eq!(statements.len(), 1);
assert_eq!(statements[0].0, "CVE-2022-48174");
assert_eq!(statements[0].1.status, VexStatus::Fixed);
assert!(statements[0].1.by_scan);
}
#[test]
fn cpe_products_are_read_from_cpe_names() {
assert_eq!(
product("cpe:2.3:*:*:busybox:1.36.1:*:*:*:*:*:*:*"),
Some(CpeProduct {
vendor: None,
product: "busybox".into()
})
);
assert_eq!(product("cpe:2.3:a:*:*:1:*"), None);
assert_eq!(product("cpe:/a:x:y"), None);
}
fn checks() -> Vec<CveCheck> {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../fixtures/yocto/core-image-minimal-qemuarm64.rootfs.cve.json");
vec![crate::pipeline::yocto_cve_check::read(&path).unwrap()]
}
fn alert(package: &str, version: &str, cve: &str) -> CveAlert {
CveAlert::new(
cve.into(),
"t".into(),
package.into(),
version.into(),
compliance_core::models::CveSource::Nvd,
)
}
#[test]
fn yoctos_own_verdict_comes_first() {
let images = built_images();
let checks = checks();
let built = Built::new(&images, &checks);
let statements = built.statements(
&[],
&[
// Patched, with the reason.
alert("glibc", "2.39+git", "CVE-2024-2961"),
// Ignored as disputed: still to be assessed, with the note.
alert("glibc", "2.39+git", "CVE-2019-1010022"),
// Ignored as not applicable to the configuration.
alert("zlib", "1.3.1", "CVE-2026-22184"),
// Unpatched: no statement.
alert("glibc", "2.39+git", "CVE-2026-5450"),
],
);
let by_cve = |cve: &str| statements.iter().find(|(c, _)| c == cve).map(|(_, v)| v);
let patched = by_cve("CVE-2024-2961").unwrap();
assert_eq!(patched.status, VexStatus::Fixed);
assert!(patched
.impact_statement
.as_deref()
.unwrap()
.starts_with("Yocto cve-check: Patched (cpe-stable-backport)"));
assert_eq!(
by_cve("CVE-2019-1010022").unwrap().status,
VexStatus::UnderInvestigation
);
assert_eq!(
by_cve("CVE-2026-22184").unwrap().status,
VexStatus::NotAffected
);
assert!(by_cve("CVE-2026-5450").is_none());
}
#[test]
fn unpatched_cves_the_match_missed_are_added() {
let images = built_images();
let checks = checks();
let built = Built::new(&images, &checks);
let have = [alert("glibc", "2.39+git", "CVE-2026-5450")];
let missing = built.unpatched_missing(&have, |name| name != "zlib");
assert_eq!(missing.len(), 1);
let (name, version, cves) = &missing[0];
assert_eq!((name.as_str(), version.as_str()), ("glibc", "2.39+git"));
let ids: Vec<&str> = cves.iter().map(|c| c.id.as_str()).collect();
assert_eq!(ids, ["CVE-2010-4756", "CVE-2026-5928"]);
assert_eq!(cves[1].cvss, Some(7.5));
// A recipe that is not a component of the scan gets nothing.
assert!(built.unpatched_missing(&have, |_| false).is_empty());
}
#[test]
fn the_kernel_report_filtered_by_compiled_files_settles_kernel_cves() {
// Yocto's improve_kernel_cve_report.py over a real scarthgap kernel
// (linux-yocto 6.6.151) with its compiled sources and the kernel
// CNA's data, trimmed to two CVEs of each verdict.
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../fixtures/yocto/linux-yocto.improved-cve-report.json");
let checks = vec![crate::pipeline::yocto_cve_check::read(&path).unwrap()];
let built = Built::new(&[], &checks);
let version = "6.6.151+git";
let status = |cve: &str| {
built
.statements(&[], &[alert("linux-yocto", version, cve)])
.first()
.map(|(_, v)| (v.status, v.justification))
};
// Its files are not compiled into this kernel.
assert_eq!(
status("CVE-2023-52586"),
Some((
VexStatus::NotAffected,
Some(VexJustification::VulnerableCodeNotPresent)
))
);
// Withdrawn by the kernel's CNA.
assert_eq!(
status("CVE-2021-46907").map(|s| s.0),
Some(VexStatus::NotAffected)
);
// Outside the affected versions: not affected, not "fixed".
assert_eq!(
status("CVE-2024-0053"),
Some((
VexStatus::NotAffected,
Some(VexJustification::VulnerableCodeNotPresent)
))
);
assert_eq!(
status("CVE-2019-25160").map(|s| s.0),
Some(VexStatus::Fixed)
);
assert_eq!(
status("CVE-2022-48669").map(|s| s.0),
Some(VexStatus::Fixed)
);
// In range and not patched: open.
assert_eq!(status("CVE-2024-42067"), None);
}
#[test]
fn the_spdx3_vex_settles_what_it_says_does_not_affect() {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../fixtures/yocto/core-image-minimal-qemuarm64.rootfs.spdx3.json");
let images = crate::pipeline::yocto_spdx3::read(&path, "t").unwrap();
let built = Built::new(&images, &[]);
let statements = built.statements(
&[],
&[
alert("glibc", "2.39+git", "CVE-2019-1010022"),
alert("busybox", "1.36.1", "CVE-2022-48174"),
],
);
let by_cve = |cve: &str| statements.iter().find(|(c, _)| c == cve).map(|(_, v)| v);
let glibc = by_cve("CVE-2019-1010022").unwrap();
assert_eq!(glibc.status, VexStatus::NotAffected);
assert!(glibc
.impact_statement
.as_deref()
.unwrap()
.starts_with("Yocto SPDX 3.0 VEX: not affected"));
assert_eq!(by_cve("CVE-2022-48174").unwrap().status, VexStatus::Fixed);
}
}
@@ -0,0 +1,184 @@
//! What Yocto's own CVE check says about an image: its `cve-check` JSON.
//!
//! With `INHERIT += "cve-check"` a build matches every recipe against NVD
//! and writes, next to the image, `<image>.json`: per recipe (`package`)
//! its version and the CVEs NVD records for its products, each `Patched`
//! (a patch or the version fixes it), `Ignored` (a CVE_STATUS sets it aside,
//! with the reason as `detail`) or `Unpatched`. Unlike the SPDX's
//! "CVEs fixed", this covers every CVE the build looked at, with Yocto's
//! reason.
//!
//! [`read`] parses the file; [`is_cve_check`] recognises one among a target's
//! build outputs.
use std::io::Read;
use std::path::Path;
use serde::Deserialize;
/// Bytes a cve-check JSON may have (a large product image's is ~50 MB).
pub const MAX_BYTES: u64 = 256 * 1024 * 1024;
/// Yocto's verdict on one CVE of one recipe.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
pub enum CheckStatus {
Patched,
Unpatched,
Ignored,
}
/// One CVE of one recipe, as cve-check reports it.
#[derive(Debug, Clone, Deserialize)]
pub struct CheckedIssue {
pub id: String,
pub status: CheckStatus,
/// The CVE_STATUS reason (`fixed-version`, `cpe-stable-backport`,
/// `not-applicable-config`, `disputed`, …), where one applies.
#[serde(default)]
pub detail: Option<String>,
/// The CVE_STATUS note the recipe gives with it.
#[serde(default)]
pub description: Option<String>,
/// NVD's description.
#[serde(default)]
pub summary: Option<String>,
/// CVSS v3 base score as text (`"9.8"`, `"0.0"` for none).
#[serde(default)]
pub scorev3: Option<String>,
}
impl CheckedIssue {
/// The CVSS v3 base score, `None` when NVD gives none.
pub fn cvss(&self) -> Option<f64> {
self.scorev3
.as_deref()
.and_then(|s| s.parse::<f64>().ok())
.filter(|s| *s > 0.0)
}
}
/// One recipe of the image.
#[derive(Debug, Clone, Deserialize)]
pub struct CheckedPackage {
pub name: String,
pub version: String,
#[serde(default, rename = "issue")]
pub issues: Vec<CheckedIssue>,
}
/// A cve-check report.
#[derive(Debug, Clone, Deserialize)]
pub struct CveCheck {
#[serde(rename = "package")]
pub packages: Vec<CheckedPackage>,
}
/// Why a cve-check JSON could not be read.
#[derive(Debug, thiserror::Error)]
pub enum CveCheckError {
#[error("cannot read the cve-check report: {0}")]
Io(#[from] std::io::Error),
#[error("the cve-check report is larger than {MAX_BYTES} bytes")]
TooLarge,
#[error("not a Yocto cve-check JSON report: {0}")]
NotCveCheck(String),
}
/// Whether the file starting with `head` is a cve-check report: a JSON
/// object whose first keys include `package` or `version`.
pub fn is_cve_check(head: &[u8]) -> bool {
let text = String::from_utf8_lossy(head);
let text = text.trim_start();
text.starts_with('{') && (text.contains("\"package\"") || text.contains("\"version\""))
}
/// Read the cve-check report at `path`.
///
/// # Errors
///
/// The file cannot be read, is larger than [`MAX_BYTES`], or is not a
/// cve-check report.
pub fn read(path: &Path) -> Result<CveCheck, CveCheckError> {
let file = std::fs::File::open(path)?;
let mut bytes = Vec::new();
file.take(MAX_BYTES + 1).read_to_end(&mut bytes)?;
if bytes.len() as u64 > MAX_BYTES {
return Err(CveCheckError::TooLarge);
}
serde_json::from_slice(&bytes).map_err(|e| CveCheckError::NotCveCheck(e.to_string()))
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
/// A trimmed copy of a real scarthgap (5.0.21) core-image-minimal's
/// cve-check report: glibc, busybox and zlib with each status.
fn fixture() -> std::path::PathBuf {
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../fixtures/yocto/core-image-minimal-qemuarm64.rootfs.cve.json")
}
#[test]
fn the_report_lists_each_recipe_with_yoctos_verdicts() {
let check = read(&fixture()).unwrap();
let names: Vec<(&str, &str)> = check
.packages
.iter()
.map(|p| (p.name.as_str(), p.version.as_str()))
.collect();
assert_eq!(
names,
[
("glibc", "2.39+git"),
("busybox", "1.36.1"),
("zlib", "1.3.1")
]
);
let glibc = &check.packages[0];
let status = |id: &str| glibc.issues.iter().find(|i| i.id == id).unwrap();
assert_eq!(status("CVE-2024-2961").status, CheckStatus::Patched);
assert_eq!(
status("CVE-2024-2961").detail.as_deref(),
Some("cpe-stable-backport")
);
assert_eq!(status("CVE-2019-1010022").status, CheckStatus::Ignored);
assert_eq!(
status("CVE-2019-1010022").detail.as_deref(),
Some("disputed")
);
assert!(status("CVE-2019-1010022").description.is_some());
let unpatched: Vec<&str> = glibc
.issues
.iter()
.filter(|i| i.status == CheckStatus::Unpatched)
.map(|i| i.id.as_str())
.collect();
assert_eq!(
unpatched,
["CVE-2010-4756", "CVE-2026-5450", "CVE-2026-5928"]
);
assert_eq!(status("CVE-2026-5450").cvss(), Some(9.8));
// "0.0" is no score.
assert_eq!(status("CVE-2010-4756").cvss(), None);
}
#[test]
fn a_report_is_recognised_by_its_start() {
let head = std::fs::read(fixture()).unwrap();
assert!(is_cve_check(&head[..64.min(head.len())]));
assert!(!is_cve_check(&[0x28, 0xb5, 0x2f, 0xfd]));
assert!(!is_cve_check(b"[1, 2]"));
}
#[test]
fn something_else_is_refused() {
let dir = std::env::temp_dir().join(format!("cs-cvecheck-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("x.json");
std::fs::write(&path, br#"{"spdxVersion": "SPDX-2.2"}"#).unwrap();
assert!(matches!(read(&path), Err(CveCheckError::NotCveCheck(_))));
let _ = std::fs::remove_dir_all(&dir);
}
}
@@ -323,7 +323,7 @@ impl RecipeVersion {
/// The release part of a PV: what precedes a git or SCM suffix or a variable
/// the tree does not define (`1.0+git${SRCPV}` → `1.0`). `None` when nothing
/// is left (`git`, `+git`).
fn release_of(pv: &str) -> Option<String> {
pub(crate) fn release_of(pv: &str) -> Option<String> {
let end = ["${", "+git", "AUTOINC", "+svn", "+hg", "+cvs"]
.iter()
.filter_map(|marker| pv.find(marker))
@@ -820,7 +820,7 @@ pub fn nvd_queries(recipes: &[Recipe]) -> (Vec<NvdQuery>, Vec<String>) {
/// set aside (`upstream-wontfix`, `disputed`, `ignored`) `under_investigation`
/// with the reason as a note. `unpatched` and `vulnerable-investigation` make
/// none: the alert stays open for a person to assess.
fn status_statement(status: &str) -> Option<(VexStatus, Option<VexJustification>)> {
pub(crate) fn status_statement(status: &str) -> Option<(VexStatus, Option<VexJustification>)> {
match status {
"backported-patch" | "cpe-stable-backport" | "fixed-version" => {
Some((VexStatus::Fixed, None))
@@ -829,6 +829,8 @@ fn status_statement(status: &str) -> Option<(VexStatus, Option<VexJustification>
VexStatus::NotAffected,
Some(VexJustification::ComponentNotPresent),
)),
// The CVE was withdrawn by its CNA (Yocto's kernel CVE report).
"rejected" => Some((VexStatus::NotAffected, None)),
"not-applicable-platform" | "not-applicable-config" => Some((
VexStatus::NotAffected,
Some(VexJustification::VulnerableCodeNotPresent),
@@ -842,7 +844,7 @@ fn status_statement(status: &str) -> Option<(VexStatus, Option<VexJustification>
}
/// A statement the scan makes, saying where it comes from.
fn scan_statement(
pub(crate) fn scan_statement(
status: VexStatus,
justification: Option<VexJustification>,
because: String,
+650
View File
@@ -0,0 +1,650 @@
//! What a Yocto build put into an image, read from the build's own SPDX 2.2.
//!
//! Yocto's `create-spdx` class (the default since kirkstone; scarthgap writes
//! SPDX 2.2) archives one document per image, binary package, recipe and
//! runtime set into `<image>.spdx.tar.zst` next to the image. The image
//! document `CONTAINS` the packages that are installed, each package is
//! `GENERATED_FROM` its recipe, and the documents point at each other through
//! `externalDocumentRefs` by namespace. Unlike the recipe inventory
//! ([`crate::pipeline::yocto_inventory`]), which reads the recipes as written,
//! this is what the build resolved: overrides, PACKAGECONFIG and the machine
//! applied, only what is in the image.
//!
//! [`read_archive`] (or [`read_dir`] for an extracted archive) returns one
//! [`BuiltImage`] per image document: an SBOM component per recipe with
//! packages in the image (recipe version, declared licence, the CPEs NVD
//! knows it by), marked [`InImageBasis::Built`], and the CVEs the recipe's
//! patches fix (`sourceInfo: "CVEs fixed: …"`), which settle those CVEs as
//! fixed. References that cannot be resolved are listed, not guessed.
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::io::Read;
use std::path::Path;
use serde::Deserialize;
use compliance_core::models::{InImage, InImageBasis, SbomEntry, YOCTO_RECIPE_MANAGER};
use compliance_core::purl::encode;
/// Where a component read from the build's SPDX comes from, on its evidence.
pub const SOURCE: &str = "Yocto build SPDX";
/// The scan run's stage id for the build's image SPDX.
pub const STAGE: &str = "build_spdx";
/// Limits on an uploaded archive: it is untrusted input.
#[derive(Debug, Clone, Copy)]
pub struct ReadLimits {
/// Documents read at most.
pub max_documents: usize,
/// Bytes one document may have once decompressed.
pub max_document_bytes: u64,
/// Bytes all documents may have together once decompressed.
pub max_total_bytes: u64,
}
impl Default for ReadLimits {
fn default() -> Self {
// A core-image-minimal archive holds ~380 documents and ~11 MB; a
// large product image a few thousand.
Self {
max_documents: 20_000,
max_document_bytes: 64 * 1024 * 1024,
max_total_bytes: 1024 * 1024 * 1024,
}
}
}
/// Why the build's SPDX could not be read.
#[derive(Debug, thiserror::Error)]
pub enum YoctoSpdxError {
#[error("cannot read the SPDX archive: {0}")]
Io(#[from] std::io::Error),
#[error("the SPDX archive exceeds its limits: {0}")]
TooLarge(&'static str),
#[error("{file} is not an SPDX 2.2 JSON document: {reason}")]
NotSpdx { file: String, reason: String },
#[error("no image document (an SPDX package `SPDXRef-Image-…`) in the archive")]
NoImage,
}
/// One image as the build made it.
#[derive(Debug, Clone)]
pub struct BuiltImage {
/// The image recipe (`core-image-minimal`).
pub image: String,
/// The image document's package id, which carries the machine and build
/// time (`SPDXRef-Image-core-image-minimal-qemuarm64.rootfs-…`).
pub image_id: String,
/// One component per recipe with packages in the image, sorted by name.
pub entries: Vec<SbomEntry>,
/// The CVEs the recipes' patches fix, per component, sorted.
pub fixed: Vec<FixedCve>,
/// Packages the image contains whose documents are not in the archive,
/// or whose recipe is not (`missing-pkg`), sorted.
pub unresolved: Vec<String>,
/// The CVEs the build's SPDX states do not affect a component (SPDX 3.0
/// VEX), sorted; SPDX 2.2 states none.
pub not_affected: Vec<NotAffectedCve>,
}
/// A CVE the build's SPDX says does not affect a component, and why.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct NotAffectedCve {
pub component: String,
pub version: String,
pub cve: String,
/// The SPDX 3.0 justification (`vulnerableCodeNotPresent`, …).
pub justification: Option<String>,
/// The impact statement (`This issue has kernel fixes …`).
pub statement: Option<String>,
}
/// A CVE a recipe's patch fixes in the component built from it.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct FixedCve {
pub component: String,
pub version: String,
pub cve: String,
}
/// Read the images of a `<image>.spdx.tar.zst` archive.
///
/// # Errors
///
/// The archive cannot be read, exceeds `limits`, holds a document that is
/// not SPDX JSON, or holds no image document.
pub fn read_archive(
archive: &Path,
repo_id: &str,
limits: ReadLimits,
) -> Result<Vec<BuiltImage>, YoctoSpdxError> {
let file = std::fs::File::open(archive)?;
let decoder = zstd::stream::read::Decoder::new(file)?;
let mut tar = tar::Archive::new(decoder);
let mut documents = Vec::new();
let mut total = 0u64;
for entry in tar.entries()? {
let entry = entry?;
if !entry.header().entry_type().is_file() {
continue;
}
let name = entry.path()?.to_string_lossy().into_owned();
if !name.ends_with(".spdx.json") {
continue;
}
if documents.len() >= limits.max_documents {
return Err(YoctoSpdxError::TooLarge("too many documents"));
}
// `take` caps what is read whatever the header claims.
let mut bytes = Vec::new();
entry
.take(limits.max_document_bytes + 1)
.read_to_end(&mut bytes)?;
if bytes.len() as u64 > limits.max_document_bytes {
return Err(YoctoSpdxError::TooLarge("a document is too large"));
}
total += bytes.len() as u64;
if total > limits.max_total_bytes {
return Err(YoctoSpdxError::TooLarge(
"the documents are too large together",
));
}
documents.push((name, bytes));
}
images(&parse(documents)?, repo_id)
}
/// Read the images of an extracted archive: every `*.spdx.json` directly in
/// `dir`.
///
/// # Errors
///
/// As [`read_archive`].
pub fn read_dir(
dir: &Path,
repo_id: &str,
limits: ReadLimits,
) -> Result<Vec<BuiltImage>, YoctoSpdxError> {
let mut documents = Vec::new();
let mut total = 0u64;
let mut paths: Vec<_> = std::fs::read_dir(dir)?
.filter_map(Result::ok)
.map(|e| e.path())
.filter(|p| p.is_file() && p.to_string_lossy().ends_with(".spdx.json"))
.collect();
paths.sort();
if paths.len() > limits.max_documents {
return Err(YoctoSpdxError::TooLarge("too many documents"));
}
for path in paths {
let size = std::fs::metadata(&path)?.len();
if size > limits.max_document_bytes {
return Err(YoctoSpdxError::TooLarge("a document is too large"));
}
total += size;
if total > limits.max_total_bytes {
return Err(YoctoSpdxError::TooLarge(
"the documents are too large together",
));
}
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
documents.push((name, std::fs::read(&path)?));
}
images(&parse(documents)?, repo_id)
}
/// An SPDX 2.2 document, as far as it is read here.
#[derive(Debug, Deserialize)]
struct Document {
#[serde(rename = "documentNamespace")]
namespace: String,
#[serde(default)]
packages: Vec<Package>,
#[serde(default)]
relationships: Vec<Relationship>,
#[serde(default, rename = "externalDocumentRefs")]
external: Vec<ExternalRef>,
}
#[derive(Debug, Deserialize)]
struct Package {
#[serde(rename = "SPDXID")]
id: String,
name: String,
#[serde(default, rename = "versionInfo")]
version: Option<String>,
#[serde(default, rename = "licenseDeclared")]
license: Option<String>,
#[serde(default, rename = "externalRefs")]
refs: Vec<PackageRef>,
#[serde(default, rename = "sourceInfo")]
source_info: Option<String>,
#[serde(default)]
homepage: Option<String>,
}
#[derive(Debug, Deserialize)]
struct PackageRef {
#[serde(rename = "referenceType")]
kind: String,
#[serde(rename = "referenceLocator")]
locator: String,
}
#[derive(Debug, Deserialize)]
struct Relationship {
#[serde(rename = "spdxElementId")]
from: String,
#[serde(rename = "relationshipType")]
kind: String,
#[serde(rename = "relatedSpdxElement")]
to: String,
}
#[derive(Debug, Deserialize)]
struct ExternalRef {
#[serde(rename = "externalDocumentId")]
id: String,
#[serde(rename = "spdxDocument")]
namespace: String,
}
/// The documents by namespace.
fn parse(documents: Vec<(String, Vec<u8>)>) -> Result<HashMap<String, Document>, YoctoSpdxError> {
let mut by_namespace = HashMap::with_capacity(documents.len());
for (file, bytes) in documents {
let doc: Document =
serde_json::from_slice(&bytes).map_err(|e| YoctoSpdxError::NotSpdx {
file: file.clone(),
reason: e.to_string(),
})?;
by_namespace.insert(doc.namespace.clone(), doc);
}
Ok(by_namespace)
}
/// The package `local` of the document `doc` refers to as `reference`
/// (`DocumentRef-busybox:SPDXRef-Package-busybox`), with its document.
fn resolve<'a>(
docs: &'a HashMap<String, Document>,
doc: &Document,
reference: &str,
) -> Option<(&'a Document, &'a Package)> {
let (doc_ref, local) = reference.split_once(':')?;
let namespace = &doc.external.iter().find(|e| e.id == doc_ref)?.namespace;
let target = docs.get(namespace)?;
let package = target.packages.iter().find(|p| p.id == local)?;
Some((target, package))
}
/// Every image of `docs`.
fn images(
docs: &HashMap<String, Document>,
repo_id: &str,
) -> Result<Vec<BuiltImage>, YoctoSpdxError> {
let mut out = Vec::new();
for doc in docs.values() {
for image in doc
.packages
.iter()
.filter(|p| p.id.starts_with("SPDXRef-Image-"))
{
out.push(built_image(docs, doc, image, repo_id));
}
}
if out.is_empty() {
return Err(YoctoSpdxError::NoImage);
}
out.sort_by(|a, b| a.image_id.cmp(&b.image_id));
Ok(out)
}
/// A recipe with packages in the image, and those packages.
struct RecipeInImage<'a> {
recipe: &'a Package,
packages: BTreeSet<&'a str>,
}
/// The image `image` of the document `doc`.
fn built_image(
docs: &HashMap<String, Document>,
doc: &Document,
image: &Package,
repo_id: &str,
) -> BuiltImage {
let mut recipes: BTreeMap<(String, String), RecipeInImage<'_>> = BTreeMap::new();
let mut unresolved = BTreeSet::new();
let contained = doc
.relationships
.iter()
.filter(|r| r.from == image.id && r.kind == "CONTAINS");
for rel in contained {
let Some((package_doc, package)) = resolve(docs, doc, &rel.to) else {
unresolved.insert(package_name(&rel.to));
continue;
};
let recipe = package_doc
.relationships
.iter()
.filter(|r| r.from == package.id && r.kind == "GENERATED_FROM")
.find_map(|r| resolve(docs, package_doc, &r.to))
.map(|(_, recipe)| recipe)
.filter(|recipe| recipe.id.starts_with("SPDXRef-Recipe-"));
let Some(recipe) = recipe else {
unresolved.insert(package.name.clone());
continue;
};
let version = recipe
.version
.clone()
.or_else(|| package.version.clone())
.unwrap_or_default();
recipes
.entry((recipe.name.clone(), version))
.or_insert_with(|| RecipeInImage {
recipe,
packages: BTreeSet::new(),
})
.packages
.insert(package.name.as_str());
}
let mut entries = Vec::with_capacity(recipes.len());
let mut fixed = Vec::new();
for ((name, version), found) in &recipes {
let facts = ComponentFacts {
name,
version,
license: found.recipe.license.as_deref(),
cpe: cpes(found.recipe).into_iter().next(),
homepage: found.recipe.homepage.as_deref(),
packages: found.packages.iter().copied().collect(),
};
let label = image.id.trim_start_matches("SPDXRef-Image-");
entries.push(component(facts, &image.name, label, repo_id));
fixed.extend(fixed_cves(found.recipe).into_iter().map(|cve| FixedCve {
component: name.clone(),
version: version.clone(),
cve,
}));
}
fixed.sort();
BuiltImage {
image: image.name.clone(),
image_id: image.id.clone(),
entries,
fixed,
unresolved: unresolved.into_iter().collect(),
not_affected: Vec::new(),
}
}
/// What the build's SPDX (2.2 or 3.0) says about one recipe in the image.
pub(crate) struct ComponentFacts<'a> {
pub name: &'a str,
pub version: &'a str,
/// The declared licence as written (document prefixes are dropped here).
pub license: Option<&'a str>,
/// The first CPE 2.3 name it is known by.
pub cpe: Option<String>,
pub homepage: Option<&'a str>,
/// Its packages in the image, sorted.
pub packages: Vec<&'a str>,
}
/// The SBOM component of one recipe in the image `image`, whose SPDX the
/// evidence names as `label` (the image document's id).
pub(crate) fn component(
facts: ComponentFacts<'_>,
image: &str,
label: &str,
repo_id: &str,
) -> SbomEntry {
let (name, version) = (facts.name, facts.version);
let mut entry = SbomEntry::new(
repo_id.to_string(),
name.to_string(),
version.to_string(),
YOCTO_RECIPE_MANAGER.to_string(),
);
entry.purl = Some(if version.is_empty() {
format!("pkg:generic/{}", encode(name))
} else {
format!("pkg:generic/{}@{}", encode(name), encode(version))
});
entry.license = facts.license.and_then(license);
entry.cpe = facts.cpe;
entry.manufacturer_url = facts
.homepage
.filter(|h| h.starts_with("https://") || h.starts_with("http://"))
.map(str::to_string);
entry.evidence.push(format!(
"{SOURCE} ({label}): packages {}",
facts.packages.join(", ")
));
let in_image = InImage {
basis: InImageBasis::Built,
images: vec![image.to_string()],
};
entry.evidence.push(in_image.describe());
entry.in_image = Some(in_image);
entry
}
/// The package name of an unresolved reference
/// (`DocumentRef-x:SPDXRef-Package-busybox` → `busybox`).
fn package_name(reference: &str) -> String {
let local = reference.split_once(':').map_or(reference, |(_, l)| l);
local
.strip_prefix("SPDXRef-Package-")
.unwrap_or(local)
.to_string()
}
/// A declared licence as an SPDX expression, without the document prefix of
/// a licence defined in another document (`DocumentRef-recipe-busybox:
/// LicenseRef-bzip2-1.0.4` → `LicenseRef-bzip2-1.0.4`); `None` for
/// NOASSERTION, NONE or nothing.
pub(crate) fn license(declared: &str) -> Option<String> {
let cleaned: Vec<String> = declared
.split_whitespace()
.map(|token| {
let (open, rest) = token.split_at(token.len() - token.trim_start_matches('(').len());
let inner = rest.trim_end_matches(')');
let close = &rest[inner.len()..];
let inner = match inner.split_once(':') {
Some((doc, id)) if doc.starts_with("DocumentRef-") => id,
_ => inner,
};
format!("{open}{inner}{close}")
})
.collect();
let expression = cleaned.join(" ");
match expression.as_str() {
"" | "NOASSERTION" | "NONE" => None,
_ => Some(expression),
}
}
/// The CPE 2.3 names a recipe is known by (CVE_PRODUCT), in order.
fn cpes(recipe: &Package) -> Vec<String> {
recipe
.refs
.iter()
.filter(|r| r.kind.ends_with("cpe23Type"))
.map(|r| r.locator.clone())
.collect()
}
/// The CVEs a recipe's patches fix: create-spdx writes them into the
/// recipe's `sourceInfo` as `CVEs fixed: CVE-… CVE-…`.
fn fixed_cves(recipe: &Package) -> Vec<String> {
let Some(rest) = recipe
.source_info
.as_deref()
.and_then(|s| s.split_once("CVEs fixed:"))
.map(|(_, rest)| rest)
else {
return Vec::new();
};
let mut cves: Vec<String> = rest
.split(|c: char| c.is_whitespace() || c == ',')
.filter(|t| t.starts_with("CVE-") && t.len() > 4)
.map(str::to_string)
.collect();
cves.sort();
cves.dedup();
cves
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use std::path::PathBuf;
/// A trimmed copy of a real scarthgap (5.0.21) core-image-minimal for
/// qemuarm64: four recipes and one package whose document is missing.
fn fixtures() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixtures/yocto")
}
fn check(images: &[BuiltImage]) {
assert_eq!(images.len(), 1);
let image = &images[0];
assert_eq!(image.image, "core-image-minimal");
assert!(image.image_id.contains("qemuarm64"), "{}", image.image_id);
let names: Vec<(&str, &str)> = image
.entries
.iter()
.map(|e| (e.name.as_str(), e.version.as_str()))
.collect();
assert_eq!(
names,
[
("base-files", "3.0.14"),
("busybox", "1.36.1"),
("openssl", "3.5.9"),
("packagegroup-core-boot", "1.0"),
]
);
let busybox = &image.entries[1];
assert_eq!(busybox.package_manager, YOCTO_RECIPE_MANAGER);
assert_eq!(busybox.purl.as_deref(), Some("pkg:generic/busybox@1.36.1"));
assert_eq!(
busybox.license.as_deref(),
Some("GPL-2.0-only AND LicenseRef-bzip2-1.0.4")
);
assert_eq!(
busybox.cpe.as_deref(),
Some("cpe:2.3:*:*:busybox:1.36.1:*:*:*:*:*:*:*")
);
let in_image = busybox.in_image.as_ref().expect("in the image");
assert_eq!(in_image.basis, InImageBasis::Built);
assert_eq!(in_image.images, ["core-image-minimal"]);
// Its three packages are one component.
assert!(
busybox.evidence[0].ends_with("packages busybox, busybox-syslog, busybox-udhcpc"),
"{:?}",
busybox.evidence
);
let openssl = &image.entries[2];
assert_eq!(
openssl.cpe.as_deref(),
Some("cpe:2.3:*:openssl:openssl:3.5.9:*:*:*:*:*:*:*")
);
// A package group has no CPE: NVD knows nothing by that name.
assert_eq!(image.entries[3].cpe, None);
let busybox_fixed: Vec<&str> = image
.fixed
.iter()
.filter(|f| f.component == "busybox")
.map(|f| f.cve.as_str())
.collect();
assert_eq!(busybox_fixed.len(), 15);
assert!(busybox_fixed.contains(&"CVE-2022-48174"));
assert!(busybox_fixed.windows(2).all(|w| w[0] < w[1]), "sorted");
assert_eq!(image.unresolved, ["missing-pkg"]);
}
#[test]
fn an_extracted_archive_lists_what_the_build_installed() {
let images = read_dir(
&fixtures().join("spdx-scarthgap"),
"t",
ReadLimits::default(),
)
.unwrap();
check(&images);
}
#[test]
fn the_image_archive_reads_the_same() {
let images = read_archive(
&fixtures().join("core-image-minimal-qemuarm64.rootfs.spdx.tar.zst"),
"t",
ReadLimits::default(),
)
.unwrap();
check(&images);
}
#[test]
fn an_archive_past_its_limits_is_refused() {
let archive = fixtures().join("core-image-minimal-qemuarm64.rootfs.spdx.tar.zst");
let few = ReadLimits {
max_documents: 3,
..ReadLimits::default()
};
assert!(matches!(
read_archive(&archive, "t", few),
Err(YoctoSpdxError::TooLarge(_))
));
let small = ReadLimits {
max_document_bytes: 100,
..ReadLimits::default()
};
assert!(matches!(
read_archive(&archive, "t", small),
Err(YoctoSpdxError::TooLarge(_))
));
}
#[test]
fn documents_without_an_image_or_not_spdx_are_refused() {
let docs = vec![(
"recipe-x.spdx.json".to_string(),
br#"{"documentNamespace": "urn:x", "packages": [{"SPDXID": "SPDXRef-Recipe-x", "name": "x"}]}"#.to_vec(),
)];
assert!(matches!(
images(&parse(docs).unwrap(), "t"),
Err(YoctoSpdxError::NoImage)
));
let broken = vec![("a.spdx.json".to_string(), b"{".to_vec())];
assert!(matches!(parse(broken), Err(YoctoSpdxError::NotSpdx { .. })));
}
#[test]
fn licences_lose_the_document_prefix_and_noassertion_is_none() {
assert_eq!(
license("GPL-2.0-only AND DocumentRef-recipe-busybox:LicenseRef-bzip2-1.0.4")
.as_deref(),
Some("GPL-2.0-only AND LicenseRef-bzip2-1.0.4")
);
assert_eq!(
license("(MIT OR DocumentRef-r:LicenseRef-x)").as_deref(),
Some("(MIT OR LicenseRef-x)")
);
assert_eq!(license("NOASSERTION"), None);
assert_eq!(license(" "), None);
}
}
@@ -0,0 +1,395 @@
//! What a Yocto build put into an image, read from the build's own SPDX 3.0.
//!
//! With `create-spdx-3.0` (the default from Styhead 5.1 on, available in
//! Scarthgap) a build writes one JSON-LD document per image,
//! `<image>.rootfs.spdx.json`, holding the whole graph:
//!
//! - the image is a `software_Package` whose purpose is `archive`, output
//! (`hasOutput`) of the rootfs `build_Build`;
//! - the packages installed in it are that build's inputs (`hasInput`), each
//! a `software_Package` of purpose `install` with its version, CPE and
//! homepage, its licence through `hasConcludedLicense`;
//! - each package is output of its recipe's build,
//! `<recipe>:do_create_spdx:recipe`;
//! - the build's VEX: `security_Vulnerability` elements with their CVE id,
//! `fixedIn` and `doesNotAffect` assessments on the packages.
//!
//! [`read`] returns the same [`BuiltImage`] as the SPDX 2.2 reader
//! ([`crate::pipeline::yocto_spdx`]), with the not-affected statements too.
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::io::Read as _;
use std::path::Path;
use serde::{Deserialize, Deserializer};
use crate::pipeline::yocto_spdx::{
component, BuiltImage, ComponentFacts, FixedCve, NotAffectedCve, YoctoSpdxError,
};
/// Bytes an SPDX 3.0 image document may have (core-image-minimal's is
/// ~7 MB; a product image with sources listed can be far larger).
pub const MAX_BYTES: u64 = 512 * 1024 * 1024;
/// Whether the file starting with `head` is an SPDX 3 JSON-LD document.
pub fn is_spdx3(head: &[u8]) -> bool {
let text = String::from_utf8_lossy(head);
text.trim_start().starts_with('{')
&& text.contains("\"@context\"")
&& text.contains("spdx.org/rdf/3")
}
/// One element of the graph, as far as it is read here.
#[derive(Debug, Deserialize)]
struct Element {
#[serde(rename = "type", default)]
kind: String,
#[serde(rename = "spdxId", default)]
id: Option<String>,
#[serde(default)]
name: Option<String>,
#[serde(rename = "software_primaryPurpose", default)]
purpose: Option<String>,
#[serde(rename = "software_packageVersion", default)]
version: Option<String>,
#[serde(rename = "software_homePage", default)]
homepage: Option<String>,
#[serde(rename = "externalIdentifier", default)]
identifiers: Vec<Identifier>,
#[serde(default)]
from: Option<String>,
#[serde(default, deserialize_with = "one_or_many")]
to: Vec<String>,
#[serde(rename = "relationshipType", default)]
relationship: Option<String>,
#[serde(rename = "simplelicensing_licenseExpression", default)]
license_expression: Option<String>,
#[serde(rename = "security_impactStatement", default)]
impact: Option<String>,
#[serde(rename = "security_justificationType", default)]
justification: Option<String>,
}
#[derive(Debug, Deserialize)]
struct Identifier {
#[serde(rename = "externalIdentifierType")]
kind: String,
identifier: String,
}
/// `to` is a list, or one id.
fn one_or_many<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<String>, D::Error> {
#[derive(Deserialize)]
#[serde(untagged)]
enum OneOrMany {
One(String),
Many(Vec<String>),
}
Ok(match Option::<OneOrMany>::deserialize(deserializer)? {
Some(OneOrMany::One(id)) => vec![id],
Some(OneOrMany::Many(ids)) => ids,
None => Vec::new(),
})
}
#[derive(Debug, Deserialize)]
struct Document {
#[serde(rename = "@graph")]
graph: Vec<Element>,
}
/// Read the images of an SPDX 3.0 image document.
///
/// # Errors
///
/// The file cannot be read, is larger than [`MAX_BYTES`], is not an SPDX 3
/// JSON-LD document, or names no image.
pub fn read(path: &Path, repo_id: &str) -> Result<Vec<BuiltImage>, YoctoSpdxError> {
let mut bytes = Vec::new();
std::fs::File::open(path)?
.take(MAX_BYTES + 1)
.read_to_end(&mut bytes)?;
if bytes.len() as u64 > MAX_BYTES {
return Err(YoctoSpdxError::TooLarge(
"the SPDX 3.0 document is too large",
));
}
let file = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let doc: Document = serde_json::from_slice(&bytes).map_err(|e| YoctoSpdxError::NotSpdx {
file,
reason: e.to_string(),
})?;
images(&doc.graph, repo_id)
}
/// The graph's elements by id, and its relationships.
struct Graph<'a> {
by_id: HashMap<&'a str, &'a Element>,
relationships: Vec<&'a Element>,
}
impl<'a> Graph<'a> {
fn new(elements: &'a [Element]) -> Self {
let mut by_id = HashMap::with_capacity(elements.len());
let mut relationships = Vec::new();
for e in elements {
if let Some(id) = e.id.as_deref() {
by_id.insert(id, e);
}
if e.relationship.is_some() {
relationships.push(e);
}
}
Self {
by_id,
relationships,
}
}
/// The relationships of `kind`.
fn of(&self, kind: &'a str) -> impl Iterator<Item = &'a Element> + '_ {
self.relationships
.iter()
.copied()
.filter(move |r| r.relationship.as_deref() == Some(kind))
}
}
/// Every image of `elements`.
fn images(elements: &[Element], repo_id: &str) -> Result<Vec<BuiltImage>, YoctoSpdxError> {
let graph = Graph::new(elements);
let mut out: Vec<BuiltImage> = elements
.iter()
.filter(|e| e.kind == "software_Package" && e.purpose.as_deref() == Some("archive"))
.filter_map(|image| built_image(&graph, image, repo_id))
.collect();
if out.is_empty() {
return Err(YoctoSpdxError::NoImage);
}
out.sort_by(|a, b| a.image_id.cmp(&b.image_id));
Ok(out)
}
/// The image `image`, if a build outputs it.
fn built_image(graph: &Graph<'_>, image: &Element, repo_id: &str) -> Option<BuiltImage> {
let image_id = image.id.as_deref()?;
let image_name = image.name.clone().unwrap_or_default();
// The builds whose output the image is (the rootfs build).
let rootfs: BTreeSet<&str> = graph
.of("hasOutput")
.filter(|r| r.to.iter().any(|t| t == image_id))
.filter_map(|r| r.from.as_deref())
.collect();
let installed: BTreeSet<&str> = graph
.of("hasInput")
.filter(|r| r.from.as_deref().is_some_and(|f| rootfs.contains(f)))
.flat_map(|r| r.to.iter().map(String::as_str))
.collect();
if rootfs.is_empty() {
return None;
}
// Each package's recipe: the name of the recipe build that outputs it.
let mut recipe_of: HashMap<&str, &str> = HashMap::new();
for r in graph.of("hasOutput") {
let Some(build) = r.from.as_deref().and_then(|f| graph.by_id.get(f)) else {
continue;
};
let Some(recipe) = build
.name
.as_deref()
.and_then(|n| n.strip_suffix(":do_create_spdx:recipe"))
else {
continue;
};
for t in &r.to {
recipe_of.insert(t.as_str(), recipe);
}
}
let license_of: HashMap<&str, &str> = graph
.of("hasConcludedLicense")
.filter_map(|r| {
let expression =
r.to.iter()
.filter_map(|t| graph.by_id.get(t.as_str()))
.find_map(|e| e.license_expression.as_deref())?;
Some((r.from.as_deref()?, expression))
})
.collect();
/// A recipe with packages in the image.
struct Found<'a> {
package: &'a Element,
packages: BTreeSet<&'a str>,
ids: BTreeSet<&'a str>,
}
let mut recipes: BTreeMap<(&str, &str), Found<'_>> = BTreeMap::new();
let mut unresolved = BTreeSet::new();
for id in &installed {
let package = graph.by_id.get(id).copied();
let recipe = package.and_then(|_| recipe_of.get(id).copied());
let (Some(package), Some(recipe)) = (package, recipe) else {
unresolved.insert(package_name(id));
continue;
};
if package.purpose.as_deref() != Some("install") {
continue;
}
let version = package.version.as_deref().unwrap_or_default();
let found = recipes.entry((recipe, version)).or_insert_with(|| Found {
package,
packages: BTreeSet::new(),
ids: BTreeSet::new(),
});
found
.packages
.insert(package.name.as_deref().unwrap_or_default());
found.ids.insert(*id);
}
// The CVE ids of the vulnerabilities, and what the VEX says per package.
let cve_of = |id: &str| -> Option<&str> {
graph.by_id.get(id)?.identifiers.iter().find_map(|i| {
(i.kind == "cve" || i.identifier.starts_with("CVE-")).then_some(i.identifier.as_str())
})
};
let mut entries = Vec::with_capacity(recipes.len());
let mut fixed = BTreeSet::new();
let mut not_affected = BTreeSet::new();
for ((recipe, version), found) in &recipes {
let facts = ComponentFacts {
name: recipe,
version,
license: found.ids.iter().find_map(|id| license_of.get(id).copied()),
cpe: found
.package
.identifiers
.iter()
.find(|i| i.kind == "cpe23")
.map(|i| i.identifier.clone()),
homepage: found.package.homepage.as_deref(),
packages: found.packages.iter().copied().collect(),
};
let label = format!("{image_name}, SPDX 3.0");
entries.push(component(facts, &image_name, &label, repo_id));
for r in graph.of("fixedIn") {
if r.to.iter().any(|t| found.ids.contains(t.as_str())) {
if let Some(cve) = r.from.as_deref().and_then(cve_of) {
fixed.insert(FixedCve {
component: recipe.to_string(),
version: version.to_string(),
cve: cve.to_string(),
});
}
}
}
for r in graph.of("doesNotAffect") {
if r.to.iter().any(|t| found.ids.contains(t.as_str())) {
if let Some(cve) = r.from.as_deref().and_then(cve_of) {
not_affected.insert(NotAffectedCve {
component: recipe.to_string(),
version: version.to_string(),
cve: cve.to_string(),
justification: r.justification.clone(),
statement: r.impact.clone(),
});
}
}
}
}
Some(BuiltImage {
image: image_name,
image_id: image_id.to_string(),
entries,
fixed: fixed.into_iter().collect(),
unresolved: unresolved.into_iter().collect(),
not_affected: not_affected.into_iter().collect(),
})
}
/// The package name at the end of a package id (`…/package/busybox`).
fn package_name(id: &str) -> String {
id.rsplit('/').next().unwrap_or(id).to_string()
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use compliance_core::models::{InImageBasis, YOCTO_RECIPE_MANAGER};
/// A trimmed copy of a real Scarthgap (5.0.21) core-image-minimal for
/// qemuarm64 built with create-spdx-3.0: six recipes and one installed
/// package whose element is missing.
fn fixture() -> std::path::PathBuf {
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../fixtures/yocto/core-image-minimal-qemuarm64.rootfs.spdx3.json")
}
#[test]
fn the_spdx3_image_lists_what_the_build_installed() {
let images = read(&fixture(), "t").unwrap();
assert_eq!(images.len(), 1);
let image = &images[0];
assert_eq!(image.image, "core-image-minimal");
let names: Vec<(&str, &str)> = image
.entries
.iter()
.map(|e| (e.name.as_str(), e.version.as_str()))
.collect();
assert_eq!(
names,
[
("base-files", "3.0.14"),
("busybox", "1.36.1"),
("glibc", "2.39+git"),
("libxml2", "2.12.10"),
("openssl", "3.5.9"),
("packagegroup-core-boot", "1.0"),
]
);
let busybox = &image.entries[1];
assert_eq!(busybox.package_manager, YOCTO_RECIPE_MANAGER);
assert_eq!(
busybox.cpe.as_deref(),
Some("cpe:2.3:*:*:busybox:1.36.1:*:*:*:*:*:*:*")
);
assert!(busybox.license.is_some());
assert_eq!(
busybox.in_image.as_ref().map(|i| i.basis),
Some(InImageBasis::Built)
);
assert!(
busybox.evidence[0].ends_with("packages busybox, busybox-syslog, busybox-udhcpc"),
"{:?}",
busybox.evidence
);
// libc6 and ldconfig are one glibc component.
assert!(image.entries[2].evidence[0].ends_with("packages ldconfig, libc6"));
assert!(image
.fixed
.iter()
.any(|f| f.component == "busybox" && f.cve == "CVE-2022-48174"));
let glibc_not_affected: Vec<&NotAffectedCve> = image
.not_affected
.iter()
.filter(|n| n.component == "glibc")
.collect();
assert!(!glibc_not_affected.is_empty());
assert!(glibc_not_affected.iter().all(|n| n.cve.starts_with("CVE-")));
assert_eq!(image.unresolved, ["missing-pkg"]);
}
#[test]
fn an_spdx3_document_is_recognised_by_its_start() {
let head = std::fs::read(fixture()).unwrap();
assert!(is_spdx3(&head[..400.min(head.len())]));
assert!(!is_spdx3(br#"{"package": [], "version": "1"}"#));
assert!(!is_spdx3(&[0x28, 0xb5, 0x2f, 0xfd]));
}
}
+68
View File
@@ -63,6 +63,30 @@ impl EntitlementCheck {
pub fn member_blocked(&self) -> bool {
!self.allowed && self.reason.as_deref() == Some(MEMBER_BLOCKED)
}
/// How many targets the tenant's plan includes (t72):
/// `limits.included_targets`. `None` when the plan sets no limit (no
/// limits, the key missing or null), so every target is included.
pub fn included_targets(&self) -> Option<u32> {
self.limit("included_targets")
}
/// The plan's monthly quota and the customer's Prüftag cap (t72), from
/// `limits.monthly_pruefungen` and `limits.prueftag_cap`; a missing or
/// null key is no limit.
pub fn plan_limits(&self) -> compliance_core::models::PlanLimits {
compliance_core::models::PlanLimits {
monthly_pruefungen: self.limit("monthly_pruefungen"),
prueftag_cap: self.limit("prueftag_cap"),
}
}
/// The whole-number limit `key`; `None` when absent or null.
fn limit(&self, key: &str) -> Option<u32> {
let n = self.limits.as_ref()?.get(key)?.as_u64()?;
// A count beyond u32 is no limit in practice.
Some(u32::try_from(n).unwrap_or(u32::MAX))
}
}
#[derive(Debug, Clone, Deserialize)]
@@ -328,6 +352,10 @@ impl RegistryClient {
if let Some(tok) = self.bearer().await? {
rb = rb.bearer_auth(tok);
}
// traceparent: the registry's spans join this request's trace.
for (name, value) in compliance_core::telemetry::trace_context_headers() {
rb = rb.header(name, value);
}
Ok(rb)
}
@@ -630,6 +658,46 @@ pub fn scheduler_runs_for(status: &str) -> bool {
mod tests {
use super::*;
#[test]
fn the_plan_sets_how_many_targets_are_included() {
let check = |limits: serde_json::Value| -> EntitlementCheck {
serde_json::from_value(serde_json::json!({ "allowed": true, "limits": limits }))
.expect("an entitlement answer")
};
assert_eq!(
check(serde_json::json!({ "included_targets": 5 })).included_targets(),
Some(5)
);
assert_eq!(
check(serde_json::json!({ "included_targets": null })).included_targets(),
None
);
assert_eq!(check(serde_json::json!({})).included_targets(), None);
assert_eq!(check(serde_json::Value::Null).included_targets(), None);
}
#[test]
fn the_plan_sets_the_quota_and_the_cap() {
let check: EntitlementCheck = serde_json::from_value(serde_json::json!({
"allowed": true,
"limits": { "included_targets": 5, "monthly_pruefungen": 100, "prueftag_cap": 0 },
}))
.expect("an entitlement answer");
assert_eq!(
check.plan_limits(),
compliance_core::models::PlanLimits {
monthly_pruefungen: Some(100),
prueftag_cap: Some(0),
}
);
assert_eq!(
EntitlementCheck::default().plan_limits(),
compliance_core::models::PlanLimits::default(),
"Enterprise: no limits"
);
}
#[test]
fn ladder_filter() {
for s in ["active", "trial", "demo", "warning", ""] {
+6 -2
View File
@@ -38,7 +38,10 @@ pub const SCHEDULED_SCAN_JITTER: Duration = Duration::from_secs(30);
pub fn start_delay(trigger: &ScanTrigger) -> Duration {
match trigger {
ScanTrigger::Scheduled => rand::rng().random_range(Duration::ZERO..=SCHEDULED_SCAN_JITTER),
ScanTrigger::Webhook | ScanTrigger::Manual | ScanTrigger::Support => Duration::ZERO,
ScanTrigger::Webhook
| ScanTrigger::Manual
| ScanTrigger::Support
| ScanTrigger::NewContent => Duration::ZERO,
}
}
@@ -187,11 +190,12 @@ mod tests {
}
#[test]
fn webhook_manual_and_support_scans_start_at_once() {
fn webhook_manual_support_and_new_content_scans_start_at_once() {
for trigger in [
ScanTrigger::Webhook,
ScanTrigger::Manual,
ScanTrigger::Support,
ScanTrigger::NewContent,
] {
assert_eq!(start_delay(&trigger), Duration::ZERO);
}
+25 -15
View File
@@ -31,9 +31,15 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError>
tenant_count = tenants.len(),
"Scheduled scan: tenants resolved"
);
for tenant_id in tenants {
scan_all_repos(&agent, &tenant_id).await;
}
// Every tenant and target at once: each scan waits for one of the
// `SCAN_CONCURRENCY` slots, so a slow repository holds one slot,
// not the whole tick (#61).
futures_util::future::join_all(
tenants
.iter()
.map(|tenant_id| scan_all_repos(&agent, tenant_id)),
)
.await;
})
})
.map_err(|e| AgentError::Scheduler(format!("Failed to create scan job: {e}")))?;
@@ -232,18 +238,22 @@ async fn scan_all_repos(agent: &ComplianceAgent, tenant_id: &str) {
let targets: Vec<_> = cursor.filter_map(|r| async { r.ok() }).collect().await;
for target in targets {
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
if let Err(e) = agent
.run_target_scan(tenant_id, &target_id, ScanTrigger::Scheduled)
.await
{
tracing::error!(
"Scheduled scan failed for {} (tenant '{tenant_id}'): {e}",
target.name
);
}
}
// Started together; the scan slots (`SCAN_CONCURRENCY`) decide how many
// run, and each scan's start jitter spreads them out.
futures_util::stream::iter(targets)
.for_each_concurrent(None, |target| async move {
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
if let Err(e) = agent
.run_target_scan(tenant_id, &target_id, ScanTrigger::Scheduled)
.await
{
tracing::error!(
"Scheduled scan failed for {} (tenant '{tenant_id}'): {e}",
target.name
);
}
})
.await;
}
async fn monitor_cves(agent: &ComplianceAgent, tenant_id: &str) {
+11
View File
@@ -26,6 +26,15 @@ pub async fn create_target(
) -> Result<OnboardedTarget, AgentError> {
let res = db.onboarded_targets().insert_one(&target).await?;
target.id = res.inserted_id.as_object_id();
// A target beyond the plan's included ones is extra from the start (t72).
if let Some((_, billing)) = agent
.refresh_billing(tenant_id, db)
.await
.into_iter()
.find(|(id, _)| Some(*id) == target.id)
{
target.billing = billing;
}
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
agent.emit_usage(
tenant_id,
@@ -101,6 +110,7 @@ pub fn uploaded_artifact(
ArtifactKind::FirmwareImage => Artifact::firmware_image(filename),
ArtifactKind::SourceArchive => Artifact::source_archive(filename),
ArtifactKind::MobilePackage => Artifact::mobile_package(filename),
ArtifactKind::BuildOutput => Artifact::build_output(filename),
_ => return None,
};
artifact.stored_path = Some(stored_path.to_string_lossy().to_string());
@@ -131,6 +141,7 @@ pub fn reference_artifact(
Artifact::plc_project(source_ref, plc_format.unwrap_or(PlcFormat::PlcopenXml))
}
ArtifactKind::PlaintextDescription => Artifact::plaintext(source_ref),
ArtifactKind::BuildOutput => Artifact::build_output(source_ref),
}
}
+8
View File
@@ -161,6 +161,14 @@ impl TestServer {
&self.db_name
}
/// The database the API reads and writes for the unauthenticated dev
/// tenant (`<db_name>_dev`, M7.2-D). Tests that seed data directly must
/// write here; `db_name()` alone is never opened by the agent.
#[allow(dead_code)] // not every test binary seeds data
pub fn tenant_db_name(&self) -> String {
format!("{}_dev", self.db_name)
}
/// Drop every per-tenant database belonging to this test run.
/// Post-M7.2-D the agent never opens a `db_name` directly —
/// data lives only in `<db_name>_<tenant>` per-tenant databases.
+80
View File
@@ -0,0 +1,80 @@
//! The month's peak of extra targets goes to the registry when it rises and
//! once a day besides; a new month starts again (t72). Runs against a live
//! Mongo (`TEST_MONGODB_URI`) and skips cleanly without one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
use chrono::{Duration, TimeZone, Utc};
use compliance_agent::database::DatabasePool;
use compliance_agent::metering::{assign_billing, charge, record_extra_peak};
use compliance_core::models::{OnboardedTarget, PlanLimits, RunCharge, TargetType};
use mongodb::bson::doc;
const TENANT: &str = "extra-peak";
#[tokio::test]
async fn the_peak_is_sent_when_it_rises_and_once_a_day() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"extrapeak_{}",
&uuid::Uuid::new_v4().simple().to_string()[..10]
);
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP extra_peak: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
// Arrange: three targets on a plan that includes one, on 6 Nov.
let mut ids = Vec::new();
for days in [3, 2, 1] {
let mut target = OnboardedTarget::new(format!("t{days}"), TargetType::FirmwareRtos);
target.created_at = Utc::now() - Duration::days(days);
let res = db.onboarded_targets().insert_one(&target).await.unwrap();
ids.push(res.inserted_id.as_object_id().unwrap());
}
assign_billing(&db, Some(1)).await.unwrap();
let nov6 = Utc.with_ymd_and_hms(2026, 11, 6, 9, 0, 0).single().unwrap();
// Act / Assert: two extra targets, sent once that day.
assert_eq!(record_extra_peak(&db, nov6).await.unwrap(), Some(2));
assert_eq!(record_extra_peak(&db, nov6).await.unwrap(), None);
// One extra target is archived: the month's peak stays two.
db.onboarded_targets()
.update_one(
doc! { "_id": ids[2] },
doc! { "$set": { "archived_at": mongodb::bson::DateTime::now() } },
)
.await
.unwrap();
assign_billing(&db, Some(1)).await.unwrap();
assert_eq!(record_extra_peak(&db, nov6).await.unwrap(), None);
assert_eq!(
record_extra_peak(&db, nov6 + Duration::days(1))
.await
.unwrap(),
Some(2),
"re-sent once the next day"
);
// A new month starts from the targets extra now.
let dec1 = Utc.with_ymd_and_hms(2026, 12, 1, 9, 0, 0).single().unwrap();
assert_eq!(record_extra_peak(&db, dec1).await.unwrap(), Some(1));
// The month document the peak created still counts the quota.
let plan = PlanLimits {
monthly_pruefungen: Some(1),
prueftag_cap: None,
};
assert_eq!(
charge(&db, "t", plan, dec1).await.unwrap().charge,
RunCharge::Quota
);
assert_eq!(
charge(&db, "t", plan, dec1).await.unwrap().charge,
RunCharge::Prueftag
);
pool.drop_tenant(TENANT).await.ok();
}
@@ -6,7 +6,7 @@ async fn insert_dast_target(server: &TestServer, repo_id: &str, name: &str) -> S
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let db = client.database(server.db_name());
let db = client.database(&server.tenant_db_name());
let result = db
.collection::<mongodb::bson::Document>("dast_targets")
@@ -30,7 +30,7 @@ async fn insert_pentest_session(server: &TestServer, target_id: &str, repo_id: &
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let db = client.database(server.db_name());
let db = client.database(&server.tenant_db_name());
let result = db
.collection::<mongodb::bson::Document>("pentest_sessions")
@@ -54,7 +54,7 @@ async fn insert_attack_node(server: &TestServer, session_id: &str) {
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let db = client.database(server.db_name());
let db = client.database(&server.tenant_db_name());
db.collection::<mongodb::bson::Document>("attack_chain_nodes")
.insert_one(mongodb::bson::doc! {
@@ -73,7 +73,7 @@ async fn insert_dast_finding(server: &TestServer, target_id: &str, session_id: &
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let db = client.database(server.db_name());
let db = client.database(&server.tenant_db_name());
db.collection::<mongodb::bson::Document>("dast_findings")
.insert_one(mongodb::bson::doc! {
@@ -99,7 +99,7 @@ async fn count_docs(server: &TestServer, collection: &str) -> u64 {
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let db = client.database(server.db_name());
let db = client.database(&server.tenant_db_name());
db.collection::<mongodb::bson::Document>(collection)
.count_documents(mongodb::bson::doc! {})
.await
@@ -175,7 +175,7 @@ async fn delete_repo_cascades_sast_findings_and_sbom() {
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let db = client.database(server.db_name());
let db = client.database(&server.tenant_db_name());
let now = mongodb::bson::DateTime::now();
db.collection::<mongodb::bson::Document>("findings")
@@ -18,7 +18,7 @@ async fn add_and_list_dast_targets() {
&json!({
"name": "test-app",
"base_url": "https://test-app.example.com",
"target_type": "webapp",
"target_type": "web_app",
}),
)
.await;
@@ -14,7 +14,7 @@ async fn insert_finding(server: &TestServer, repo_id: &str, title: &str, severit
// Get the DB name from the test server by parsing the health response
// For now, we use a direct insert approach
let db = client.database(server.db_name());
let db = client.database(&server.tenant_db_name());
let now = mongodb::bson::DateTime::now();
db.collection::<mongodb::bson::Document>("findings")
@@ -22,7 +22,7 @@ async fn stats_overview_returns_zeroes_on_empty_db() {
let body: serde_json::Value = resp.json().await.unwrap();
let data = &body["data"];
assert_eq!(data["repositories"], 0);
assert_eq!(data["total_repositories"], 0);
assert_eq!(data["total_findings"], 0);
server.cleanup().await;
@@ -235,7 +235,7 @@ async fn the_list_pages_with_a_total_after_the_project_filter() {
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let targets = client
.database(&format!("{}_dev", server.db_name()))
.database(&server.tenant_db_name())
.collection::<mongodb::bson::Document>("onboarded_targets");
for id in &ids[1..] {
let oid = mongodb::bson::oid::ObjectId::parse_str(id).unwrap();
@@ -39,7 +39,7 @@ async fn the_sbom_lists_components_in_the_image_first_and_filters_by_it() {
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
// The dev tenant's database, which the API reads.
let db = client.database(&format!("{}_dev", server.db_name()));
let db = client.database(&server.tenant_db_name());
let entries = [
recipe("aaa-tools", false),
recipe("busybox", true),
@@ -21,7 +21,7 @@ async fn stats_overview_reflects_inserted_data() {
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let db = client.database(server.db_name());
let db = client.database(&server.tenant_db_name());
let now = mongodb::bson::DateTime::now();
for (title, severity) in [
@@ -52,10 +52,10 @@ async fn stats_overview_reflects_inserted_data() {
let body: serde_json::Value = resp.json().await.unwrap();
let data = &body["data"];
assert_eq!(data["repositories"], 1);
assert_eq!(data["total_repositories"], 1);
assert_eq!(data["total_findings"], 4);
assert_eq!(data["critical"], 1);
assert_eq!(data["high"], 1);
assert_eq!(data["critical_findings"], 1);
assert_eq!(data["high_findings"], 1);
server.cleanup().await;
}
@@ -68,7 +68,7 @@ async fn stats_update_after_finding_status_change() {
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let db = client.database(server.db_name());
let db = client.database(&server.tenant_db_name());
let now = mongodb::bson::DateTime::now();
let result = db
@@ -102,11 +102,11 @@ async fn stats_update_after_finding_status_change() {
)
.await;
// The finding still exists (status changed, not deleted)
// The overview counts open findings only (open, triaged, needs_review):
// a resolved one drops out, though the finding itself is kept.
let resp = server.get("/api/v1/stats/overview").await;
let body: serde_json::Value = resp.json().await.unwrap();
// total_findings counts all findings regardless of status
assert_eq!(body["data"]["total_findings"], 1);
assert_eq!(body["data"]["total_findings"], 0);
server.cleanup().await;
}
@@ -0,0 +1,83 @@
//! Counted Prüfungen go to the month's quota first; once it is used up, the
//! first one on a target that day books a Prüftag that allows six (t72).
//! Runs against a live Mongo (`TEST_MONGODB_URI`) and skips cleanly without
//! one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
use chrono::{TimeZone, Utc};
use compliance_agent::database::DatabasePool;
use compliance_agent::metering::{charge, usage};
use compliance_core::models::{
admit, Admission, PlanLimits, Refusal, RunCharge, PRUEFUNGEN_PER_PRUEFTAG,
};
const TENANT: &str = "metering-counters";
#[tokio::test]
async fn the_quota_then_a_prueftag_of_six_then_nothing() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"metering_{}",
&uuid::Uuid::new_v4().simple().to_string()[..10]
);
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP metering_counters: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
// Arrange: a quota of two and a cap of one Prüftag, on 6 Nov in Berlin.
let plan = PlanLimits {
monthly_pruefungen: Some(2),
prueftag_cap: Some(1),
};
let at = Utc.with_ymd_and_hms(2026, 11, 6, 9, 0, 0).single().unwrap();
let admitted = |target: &'static str| {
let db = db.clone();
async move {
let (month, day) = usage(&db, target, at).await.unwrap();
admit(plan, month, day)
}
};
// Act / Assert: the quota first.
for _ in 0..2 {
assert_eq!(admitted("a").await, Admission::Quota);
let charged = charge(&db, "a", plan, at).await.unwrap();
assert_eq!(charged.charge, RunCharge::Quota);
assert_eq!(charged.booked_prueftag, None);
}
// The quota is used up: the next one books target a's Prüftag.
assert_eq!(admitted("a").await, Admission::BookPrueftag);
let booked = charge(&db, "a", plan, at).await.unwrap();
assert_eq!(booked.charge, RunCharge::Prueftag);
assert_eq!(booked.booked_prueftag.as_deref(), Some("2026-11-06"));
// It allows six in all; the seventh that day does not run.
for _ in 1..PRUEFUNGEN_PER_PRUEFTAG {
assert_eq!(admitted("a").await, Admission::Prueftag);
let charged = charge(&db, "a", plan, at).await.unwrap();
assert_eq!(charged.booked_prueftag, None, "no second booking");
}
assert_eq!(admitted("a").await, Admission::Refused(Refusal::DailyLimit));
// Another target would need a second Prüftag, over the cap of one.
assert_eq!(
admitted("b").await,
Admission::Refused(Refusal::PrueftagCap)
);
// The next calendar day in Berlin is a new day for target a.
let tomorrow = Utc
.with_ymd_and_hms(2026, 11, 6, 23, 30, 0)
.single()
.unwrap();
let (month, day) = usage(&db, "a", tomorrow).await.unwrap();
assert!(!day.prueftag_booked, "7 Nov in Berlin");
assert_eq!(month.prueftage, 1);
assert_eq!(month.pruefungen, 2);
pool.drop_tenant(TENANT).await.ok();
}
+24 -1
View File
@@ -514,7 +514,7 @@ async fn collect(agent: &Agent, target_id: &str, run: &Value) -> Collected {
"{}:{}@{}{in_image}",
text(e, "package_manager"),
text(e, "name"),
text(e, "version")
blessed_version(&text(e, "package_manager"), &text(e, "version"))
));
for v in e["known_vulnerabilities"].as_array().into_iter().flatten() {
snapshot.cves.insert(text(v, "id"));
@@ -590,6 +590,20 @@ async fn wait_for_runs(
done
}
/// The version a snapshot keeps of a component. A GitHub Action is named by
/// a moving tag (`actions/deploy-pages@v5`), which the scan resolves to the
/// release it points to today (`v5.0.1`): the snapshot keeps the major
/// version, so an upstream patch release does not break the baseline (#573).
/// A commit SHA has no dot and stays whole.
fn blessed_version(package_manager: &str, version: &str) -> String {
if package_manager == "github" {
if let Some((major, _)) = version.split_once('.') {
return major.to_string();
}
}
version.to_string()
}
fn baseline_path(root: &Path, key: &str) -> PathBuf {
root.join("fixtures/nightly/baselines")
.join(format!("{key}.json"))
@@ -770,6 +784,15 @@ mod unit {
items.iter().map(|s| s.to_string()).collect()
}
#[test]
fn a_github_action_keeps_its_major_version_only() {
assert_eq!(blessed_version("github", "v5.0.1"), "v5");
assert_eq!(blessed_version("github", "v1"), "v1");
let sha = "38a6d9b276ed434454900130cacc87d058d3ac62";
assert_eq!(blessed_version("github", sha), sha);
assert_eq!(blessed_version("cargo", "1.0.15"), "1.0.15");
}
#[test]
fn exact_sets_report_both_directions_and_at_least_sets_only_losses() {
let blessed = Snapshot {
+150 -3
View File
@@ -69,6 +69,8 @@ async fn a_scan_closes_what_it_no_longer_finds_and_reopens_what_returns() {
finding("fp-kept", "semgrep", "src/a.c"),
finding("fp-fixed", "semgrep", "src/b.c"),
finding("fp-vendor", "semgrep", "Drivers/STM32F4xx_HAL_Driver/x.c"),
finding("fp-test-data", "semgrep", "fixtures/dotnet/Program.cs"),
finding("fp-excluded", "semgrep", "docs/samples/app.py"),
finding("fp-lint", "clippy", "src/lib.rs"),
decided,
other_target,
@@ -81,15 +83,18 @@ async fn a_scan_closes_what_it_no_longer_finds_and_reopens_what_returns() {
assert_eq!(idle.resolve_missing(&db, TARGET, &[]).await.unwrap(), 0);
// Act: semgrep completes and reports only fp-kept.
let mut run = RunFindings::new("run-2");
let mut run = RunFindings::new("run-2")
.with_test_data(vec!["fixtures".to_string()])
.with_excluded(vec!["docs/samples".to_string()]);
run.completed("semgrep");
let mut seen = vec![finding("fp-kept", "semgrep", "src/a.c")];
run.write_back(&db, &mut seen).await.unwrap();
let vendor = vec!["Drivers".to_string()];
let closed = run.resolve_missing(&db, TARGET, &vendor).await.unwrap();
// Assert: fixed and vendored closed, each with its reason; the rest kept.
assert_eq!(closed, 2);
// Assert: fixed, vendored, test data and excluded closed, each with its
// reason; the rest kept.
assert_eq!(closed, 4);
let fixed = row(&db, "fp-fixed").await;
assert_eq!(fixed.status, FindingStatus::Resolved);
assert_eq!(
@@ -102,6 +107,18 @@ async fn a_scan_closes_what_it_no_longer_finds_and_reopens_what_returns() {
last_scan_change(&vendored),
Some(ScanChangeKind::NowVendorCode)
);
let test_data = row(&db, "fp-test-data").await;
assert_eq!(test_data.status, FindingStatus::Resolved);
assert_eq!(
last_scan_change(&test_data),
Some(ScanChangeKind::NowTestData)
);
let excluded = row(&db, "fp-excluded").await;
assert_eq!(excluded.status, FindingStatus::Resolved);
assert_eq!(
last_scan_change(&excluded),
Some(ScanChangeKind::NowExcluded)
);
assert_eq!(row(&db, "fp-kept").await.status, FindingStatus::Open);
assert_eq!(
row(&db, "fp-false-positive").await.status,
@@ -144,3 +161,133 @@ async fn a_scan_closes_what_it_no_longer_finds_and_reopens_what_returns() {
pool.drop_tenant(TENANT).await.ok();
}
#[tokio::test]
async fn only_what_was_left_out_is_closed_for_a_stage_without_a_seen_set() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"leftout_{}",
&uuid::Uuid::new_v4().simple().to_string()[..10]
);
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP resolve_findings: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
// Arrange: PLC findings in an excluded path, in test data and elsewhere,
// and one of another scanner in the excluded path.
let mut decided = finding("fp-plc-decided", "plc-control-logic", "legacy/Old.st");
decided.status = FindingStatus::AcceptedRisk;
db.findings()
.insert_many([
finding("fp-plc-excluded", "plc-control-logic", "legacy/Old.st"),
finding("fp-plc-fixture", "plc-control-logic", "fixtures/Pump.xml"),
finding("fp-plc-kept", "plc-control-logic", "src/Main.st"),
finding("fp-other-scanner", "semgrep", "legacy/tool.py"),
decided,
])
.await
.unwrap();
// Act
let mut run = RunFindings::new("run-plc")
.with_excluded(vec!["legacy".to_string()])
.with_test_data(vec!["fixtures".to_string()]);
let closed = run
.resolve_left_out(&db, TARGET, Some("plc-control-logic"))
.await
.unwrap();
// Assert: only the left-out PLC findings close, each with its reason;
// what the scan did not see otherwise is not closed as fixed.
assert_eq!(closed, 2);
assert_eq!(run.status_changed().len(), 2);
let excluded = row(&db, "fp-plc-excluded").await;
assert_eq!(excluded.status, FindingStatus::Resolved);
assert_eq!(
last_scan_change(&excluded),
Some(ScanChangeKind::NowExcluded)
);
let fixture = row(&db, "fp-plc-fixture").await;
assert_eq!(
last_scan_change(&fixture),
Some(ScanChangeKind::NowTestData)
);
assert_eq!(row(&db, "fp-plc-kept").await.status, FindingStatus::Open);
assert_eq!(
row(&db, "fp-other-scanner").await.status,
FindingStatus::Open
);
assert_eq!(
row(&db, "fp-plc-decided").await.status,
FindingStatus::AcceptedRisk,
"a person's decision stays"
);
pool.drop_tenant(TENANT).await.ok();
}
#[tokio::test]
async fn left_out_findings_close_whichever_scanner_stored_them() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"leftoutall_{}",
&uuid::Uuid::new_v4().simple().to_string()[..10]
);
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP resolve_findings: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
// Arrange: an earlier scan stored findings of scanners that do not run
// now (no C, no BitBake left in the tree), one in the test data that this
// run still reports, and one outside the left-out paths.
db.findings()
.insert_many([
finding("fp-cppcheck", "cppcheck", "fixtures/firmware/sensors.c"),
finding("fp-recipe", "yocto-config", "legacy/image.bb"),
finding("fp-reported", "gitleaks", "fixtures/app/.env.local"),
finding("fp-kept", "cppcheck", "src/main.c"),
])
.await
.unwrap();
// Act: only gitleaks completes, and it reports fp-reported again.
let mut run = RunFindings::new("run-all")
.with_excluded(vec!["legacy".to_string()])
.with_test_data(vec!["fixtures".to_string()]);
run.completed("gitleaks");
let mut seen = vec![finding(
"fp-reported",
"gitleaks",
"fixtures/app/.env.local",
)];
run.write_back(&db, &mut seen).await.unwrap();
run.resolve_missing(&db, TARGET, &[]).await.unwrap();
let closed = run.resolve_left_out(&db, TARGET, None).await.unwrap();
// Assert: the left-out findings close with their reason, although their
// scanner did not run; one this run reported, and one outside, stay.
assert_eq!(closed, 2);
let cppcheck = row(&db, "fp-cppcheck").await;
assert_eq!(cppcheck.status, FindingStatus::Resolved);
assert_eq!(
last_scan_change(&cppcheck),
Some(ScanChangeKind::NowTestData)
);
let recipe = row(&db, "fp-recipe").await;
assert_eq!(recipe.status, FindingStatus::Resolved);
assert_eq!(last_scan_change(&recipe), Some(ScanChangeKind::NowExcluded));
assert_eq!(
row(&db, "fp-reported").await.status,
FindingStatus::Open,
"a finding this run reported is not closed"
);
assert_eq!(row(&db, "fp-kept").await.status, FindingStatus::Open);
pool.drop_tenant(TENANT).await.ok();
}
+82
View File
@@ -0,0 +1,82 @@
//! The oldest active targets are the plan's included ones; the rest are
//! extra, and an extra one moves up when an included one is archived (t72).
//! Runs against a live Mongo (`TEST_MONGODB_URI`) and skips cleanly without
//! one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
use chrono::{Duration, Utc};
use compliance_agent::database::{Database, DatabasePool};
use compliance_agent::metering::assign_billing;
use compliance_core::models::{OnboardedTarget, TargetBilling, TargetType};
use mongodb::bson::{doc, oid::ObjectId};
const TENANT: &str = "target-billing";
async fn billing(db: &Database, id: ObjectId) -> TargetBilling {
db.onboarded_targets()
.find_one(doc! { "_id": id })
.await
.unwrap()
.unwrap()
.billing
}
#[tokio::test]
async fn the_oldest_targets_are_included_and_an_extra_one_moves_up() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"billing_{}",
&uuid::Uuid::new_v4().simple().to_string()[..10]
);
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP target_billing: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
// Arrange: three targets, created a day apart.
let mut ids = Vec::new();
for days in [3, 2, 1] {
let mut target = OnboardedTarget::new(format!("t{days}"), TargetType::FirmwareRtos);
target.created_at = Utc::now() - Duration::days(days);
let res = db.onboarded_targets().insert_one(&target).await.unwrap();
ids.push(res.inserted_id.as_object_id().unwrap());
}
let (oldest, middle, newest) = (ids[0], ids[1], ids[2]);
// Act: a plan with two included targets.
let changes = assign_billing(&db, Some(2)).await.unwrap();
// Assert: only the newest is extra, and it is the one change.
assert_eq!(changes, vec![(newest, TargetBilling::Extra)]);
assert_eq!(billing(&db, oldest).await, TargetBilling::Included);
assert_eq!(billing(&db, middle).await, TargetBilling::Included);
assert_eq!(billing(&db, newest).await, TargetBilling::Extra);
assert!(
assign_billing(&db, Some(2)).await.unwrap().is_empty(),
"nothing changes a second time"
);
// Act: the oldest is archived.
db.onboarded_targets()
.update_one(
doc! { "_id": oldest },
doc! { "$set": { "archived_at": mongodb::bson::DateTime::now() } },
)
.await
.unwrap();
assign_billing(&db, Some(2)).await.unwrap();
// Assert: the extra one moved up.
assert_eq!(billing(&db, newest).await, TargetBilling::Included);
// Act / Assert: a plan without a limit includes every target.
assign_billing(&db, Some(0)).await.unwrap();
assert_eq!(billing(&db, middle).await, TargetBilling::Extra);
assign_billing(&db, None).await.unwrap();
assert_eq!(billing(&db, middle).await, TargetBilling::Included);
pool.drop_tenant(TENANT).await.ok();
}
+3 -1
View File
@@ -54,7 +54,9 @@ mongodb = { workspace = true, optional = true }
opentelemetry = { version = "0.29", optional = true }
opentelemetry_sdk = { version = "0.29", features = ["rt-tokio"], optional = true }
opentelemetry-otlp = { version = "0.29", features = ["http", "reqwest-rustls"], optional = true }
opentelemetry-appender-tracing = { version = "0.29", optional = true }
# experimental_use_tracing_span_context: an OTLP log record carries the
# trace_id/span_id of the span it was logged in, so SigNoz links logs and traces.
opentelemetry-appender-tracing = { version = "0.29", optional = true, features = ["experimental_use_tracing_span_context"] }
tracing-opentelemetry = { version = "0.30", optional = true }
tracing-subscriber = { workspace = true, optional = true }
tracing = { workspace = true, optional = true }
+38
View File
@@ -0,0 +1,38 @@
//! The release a binary was built as, read at compile time.
//!
//! CI passes the latest release tag (without its `v`) as `PRUEFWERK_VERSION`
//! and the commit as `PRUEFWERK_COMMIT` to the image build. The crate version
//! is only the fallback for a local build: it is not bumped per release, so
//! anything that names the running version (the agent's `/version` handshake,
//! telemetry's `service.version`, evidence tooling) uses these constants.
/// The build version: `PRUEFWERK_VERSION` at compile time, else the crate
/// version.
pub const BUILD_VERSION: &str =
non_empty_or(option_env!("PRUEFWERK_VERSION"), env!("CARGO_PKG_VERSION"));
/// The commit the build is from: `PRUEFWERK_COMMIT` at compile time (CI: the
/// full SHA), else "unknown". The portal's version line shows 8 characters.
pub const BUILD_COMMIT: &str = non_empty_or(option_env!("PRUEFWERK_COMMIT"), "unknown");
/// A Docker build arg left empty is an empty env var, not an unset one.
const fn non_empty_or(value: Option<&'static str>, fallback: &'static str) -> &'static str {
match value {
Some(v) if !v.is_empty() => v,
_ => fallback,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_unset_or_empty_build_value_falls_back() {
assert_eq!(non_empty_or(None, "0.4.4"), "0.4.4");
assert_eq!(non_empty_or(Some(""), "unknown"), "unknown");
assert_eq!(non_empty_or(Some("0.4.5"), "0.4.4"), "0.4.5");
assert!(!BUILD_VERSION.is_empty());
assert!(!BUILD_COMMIT.is_empty());
}
}
+7 -2
View File
@@ -9,6 +9,10 @@ pub struct AgentConfig {
pub litellm_api_key: SecretString,
pub litellm_model: String,
pub litellm_embed_model: String,
/// Seconds one LLM call may take in total, waiting in the gateway's queue
/// included (`LLM_TIMEOUT_SECS`, default 600). Keep it at the gateway's own
/// request timeout: a call given up earlier keeps the model busy anyway.
pub llm_timeout_secs: u64,
pub github_token: Option<SecretString>,
pub github_webhook_secret: Option<SecretString>,
pub gitlab_url: Option<String>,
@@ -322,8 +326,9 @@ impl Default for AgentConfig {
mongodb_database: "compliance_scanner".to_string(),
litellm_url: "http://localhost:4000".to_string(),
litellm_api_key: SecretString::from(String::new()),
litellm_model: "gpt-4o".to_string(),
litellm_embed_model: "text-embedding-3-small".to_string(),
litellm_model: String::new(),
litellm_embed_model: String::new(),
llm_timeout_secs: 600,
github_token: None,
github_webhook_secret: None,
gitlab_url: None,
+1
View File
@@ -1,3 +1,4 @@
pub mod build_info;
pub mod config;
pub mod control_check;
pub mod csaf_docs;
+186
View File
@@ -0,0 +1,186 @@
//! Paths a target's owner leaves out of its scans (`scan_config.exclude_paths`).
//!
//! Each entry names a directory or a file relative to the root of the scanned
//! tree, such as `docs/samples` or `tools/legacy.py`. Everything under a
//! directory is left out of every stage: code findings, SBOM and CVE match.
//! There are no wildcards: a path is a prefix that ends at a `/`, the same
//! rule as for vendor code and test data. The scan applies them on top of
//! the test data it detects itself (`fixtures/`, `testdata/`).
/// How many paths one target may exclude.
pub const MAX_EXCLUDE_PATHS: usize = 50;
/// How long one excluded path may be, in bytes.
pub const MAX_EXCLUDE_PATH_LEN: usize = 256;
/// Why an excluded path was refused. Every variant names the entry as given.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ExcludePathError {
/// More than [`MAX_EXCLUDE_PATHS`] entries.
#[error("at most {MAX_EXCLUDE_PATHS} paths can be excluded")]
TooMany,
/// Longer than [`MAX_EXCLUDE_PATH_LEN`].
#[error("{0}: longer than {MAX_EXCLUDE_PATH_LEN} characters")]
TooLong(String),
/// Starts at the file system root (`/src`, `C:\src`).
#[error("{0}: give the path relative to the repository root, without a leading /")]
Absolute(String),
/// Names `.`, `..` or `.git` as a part, or is the root itself.
#[error("{0}: must name a directory or file inside the repository")]
OutsideTree(String),
/// Holds a wildcard (`*`, `?`, `[`).
#[error("{0}: wildcards are not supported; name the directory or file")]
Wildcard(String),
}
/// The excluded paths as stored: trimmed, `/`-separated, without a leading
/// `./` or a trailing `/`, blank lines dropped, duplicates removed, in the
/// order given.
///
/// # Arguments
///
/// * `paths` - the entries as a person typed them, one path each
///
/// # Returns
///
/// The normalised paths.
///
/// # Errors
///
/// The first entry that is not a path inside the tree
/// ([`ExcludePathError`]), or [`ExcludePathError::TooMany`].
///
/// # Examples
///
/// ```
/// use compliance_core::models::normalise_exclude_paths;
///
/// let paths = vec!["./docs/samples/".to_string(), "".to_string(), "tools\\old".to_string()];
/// assert_eq!(normalise_exclude_paths(&paths).unwrap(), ["docs/samples", "tools/old"]);
/// assert!(normalise_exclude_paths(&["../etc".to_string()]).is_err());
/// ```
pub fn normalise_exclude_paths(paths: &[String]) -> Result<Vec<String>, ExcludePathError> {
let mut out: Vec<String> = Vec::with_capacity(paths.len());
for raw in paths {
let Some(path) = normalise_one(raw)? else {
continue;
};
if !out.contains(&path) {
out.push(path);
}
}
if out.len() > MAX_EXCLUDE_PATHS {
return Err(ExcludePathError::TooMany);
}
Ok(out)
}
/// One entry normalised; `None` for a blank one.
fn normalise_one(raw: &str) -> Result<Option<String>, ExcludePathError> {
let given = raw.trim();
if given.is_empty() {
return Ok(None);
}
if given.len() > MAX_EXCLUDE_PATH_LEN {
return Err(ExcludePathError::TooLong(given.to_string()));
}
if given.contains(['*', '?', '[']) {
return Err(ExcludePathError::Wildcard(given.to_string()));
}
let slashed = given.replace('\\', "/");
// `/src`, and a Windows drive (`C:/src`).
let drive = slashed.as_bytes().get(1) == Some(&b':');
if slashed.starts_with('/') || drive {
return Err(ExcludePathError::Absolute(given.to_string()));
}
let parts: Vec<&str> = slashed
.trim_start_matches("./")
.split('/')
.filter(|part| !part.is_empty())
.collect();
let outside = parts.is_empty()
|| parts
.iter()
.any(|part| matches!(*part, "." | "..") || part.eq_ignore_ascii_case(".git"));
if outside {
return Err(ExcludePathError::OutsideTree(given.to_string()));
}
Ok(Some(parts.join("/")))
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
fn norm(paths: &[&str]) -> Result<Vec<String>, ExcludePathError> {
let owned: Vec<String> = paths.iter().map(|p| p.to_string()).collect();
normalise_exclude_paths(&owned)
}
#[test]
fn paths_are_stored_relative_and_slash_separated() {
assert_eq!(
norm(&[
" ./docs/samples/ ",
"",
"tools\\legacy.py",
"docs//samples",
"a/b"
])
.unwrap(),
["docs/samples", "tools/legacy.py", "a/b"]
);
assert!(norm(&[]).unwrap().is_empty());
}
#[test]
fn a_path_outside_the_tree_is_refused() {
for bad in [
"/etc",
"C:\\src",
"..",
"a/../b",
"./",
".",
".git",
"src/.git/hooks",
] {
let err = norm(&[bad]).unwrap_err();
assert!(
matches!(
err,
ExcludePathError::Absolute(_) | ExcludePathError::OutsideTree(_)
),
"{bad}: {err:?}"
);
}
}
#[test]
fn wildcards_length_and_count_are_limited() {
assert_eq!(
norm(&["src/*.c"]),
Err(ExcludePathError::Wildcard("src/*.c".into()))
);
let long = "a".repeat(MAX_EXCLUDE_PATH_LEN + 1);
assert!(matches!(
norm(&[long.as_str()]),
Err(ExcludePathError::TooLong(_))
));
let many: Vec<String> = (0..=MAX_EXCLUDE_PATHS).map(|n| format!("d{n}")).collect();
assert_eq!(
normalise_exclude_paths(&many),
Err(ExcludePathError::TooMany)
);
// Duplicates count once.
let same: Vec<String> = (0..=MAX_EXCLUDE_PATHS).map(|_| "d".to_string()).collect();
assert_eq!(normalise_exclude_paths(&same).unwrap(), ["d"]);
}
#[test]
fn the_error_names_the_entry() {
let err = norm(&["../x"]).unwrap_err();
assert!(err.to_string().starts_with("../x:"), "{err}");
}
}
+6
View File
@@ -131,6 +131,12 @@ pub enum ScanChangeKind {
NoLongerFound,
/// Its file now lies in vendor code, which is left out of the findings.
NowVendorCode,
/// Its file now lies in test data (`fixtures/`, `testdata/`), which is
/// left out of the scan.
NowTestData,
/// Its file now lies in a path the target's settings exclude from the
/// scan (`scan_config.exclude_paths`).
NowExcluded,
/// A finding marked resolved was reported again.
FoundAgain,
/// Its rule fired often enough in the repository that its occurrences
+440
View File
@@ -0,0 +1,440 @@
//! Metering (t72): whether a target is one of the plan's included targets,
//! why a scan ran, and whether that scan counts toward the customer's usage.
//!
//! The contract (Leistungsbeschreibung Prüfwerk §2 Abs. 4–5, §7): change-driven
//! scans of an included target are not counted; Prüfungen the customer
//! requests are, and so is every scan of an extra target. Our own rescans and
//! support's scans never are.
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use super::repository::ScanTrigger;
/// Whether a target is one of the plan's included targets or an extra one
/// (billed per month on top).
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum TargetBilling {
/// One of the plan's included targets. Targets stored before metering
/// existed read as included.
#[default]
Included,
/// A target beyond the plan's included ones.
Extra,
}
/// Why a scan ran, as far as metering is concerned.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ScanAttribution {
/// Started because something changed: new commits, other uploaded
/// files, or a live URL (scanned on every schedule).
Change,
/// The customer asked for it (dashboard or API).
Request,
/// Our own: a scheduled scan where nothing the customer changed, only
/// the Prüfwerk build. Never counted.
Rescan,
/// Started by Breakpilot support in the customer's tenant. Never counted.
Support,
}
impl ScanAttribution {
/// The attribution a scan started by a person has from the start, before
/// any change detection; `None` for a scheduled or webhook scan, which
/// change detection attributes.
pub fn of_person(trigger: &ScanTrigger) -> Option<Self> {
match trigger {
ScanTrigger::Manual => Some(Self::Request),
ScanTrigger::Support => Some(Self::Support),
ScanTrigger::Scheduled | ScanTrigger::Webhook | ScanTrigger::NewContent => None,
}
}
/// The attribution of a scan that runs, from its trigger and whether
/// change detection found a change the customer made.
///
/// # Arguments
///
/// * `trigger` - What started the scan.
/// * `content_changed` - New commits, other uploaded files, or a live
/// URL. Ignored for a scan a person started.
pub fn detected(trigger: &ScanTrigger, content_changed: bool) -> Self {
match Self::of_person(trigger) {
Some(person) => person,
None if content_changed => Self::Change,
None => Self::Rescan,
}
}
/// Whether a scan with this attribution, on a target billed as
/// `billing`, counts toward the customer's usage once it completes.
///
/// # Examples
///
/// ```
/// use compliance_core::models::{ScanAttribution, TargetBilling};
///
/// assert!(!ScanAttribution::Change.chargeable(TargetBilling::Included));
/// assert!(ScanAttribution::Change.chargeable(TargetBilling::Extra));
/// assert!(ScanAttribution::Request.chargeable(TargetBilling::Included));
/// assert!(!ScanAttribution::Rescan.chargeable(TargetBilling::Extra));
/// ```
pub fn chargeable(self, billing: TargetBilling) -> bool {
match self {
Self::Request => true,
Self::Change => billing == TargetBilling::Extra,
Self::Rescan | Self::Support => false,
}
}
}
/// How many counted Prüfungen one Prüftag allows on its target that day.
pub const PRUEFUNGEN_PER_PRUEFTAG: u32 = 6;
/// What the tenant's plan allows per calendar month (Europe/Berlin).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PlanLimits {
/// Counted Prüfungen in the quota; `None` is unlimited (no Prüftage).
pub monthly_pruefungen: Option<u32>,
/// Prüftage the customer allows; `None` is no cap, `Some(0)` none.
pub prueftag_cap: Option<u32>,
}
/// What the tenant used so far this month.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct MonthUsage {
/// Counted Prüfungen charged to the quota.
pub pruefungen: u32,
/// Prüftage booked.
pub prueftage: u32,
}
/// What one target used today, once the quota was used up.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DayUsage {
/// Whether a Prüftag is booked for the target today.
pub prueftag_booked: bool,
/// Counted Prüfungen charged to that Prüftag.
pub prueftag_pruefungen: u32,
}
/// What a counted Prüfung was charged to.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum RunCharge {
/// The month's quota.
Quota,
/// The target's Prüftag for that day.
Prueftag,
}
/// Whether a counted Prüfung may run, and what it is charged to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Admission {
/// Within the month's quota.
Quota,
/// On the target's Prüftag already booked today.
Prueftag,
/// The quota is used up: this Prüfung books today's Prüftag.
BookPrueftag,
/// It does not run.
Refused(Refusal),
}
/// Why a counted Prüfung does not run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Refusal {
/// Today's Prüftag on the target is used up; there is no second one.
DailyLimit,
/// The quota is used up and the customer's Prüftag cap is reached.
PrueftagCap,
}
/// Whether one more counted Prüfung on a target may run, by the contract
/// (LB Prüfwerk §2 Abs. 5): the quota first; once it is used up, the first
/// counted Prüfung on a target that day books a Prüftag (unless the cap is
/// reached), which allows [`PRUEFUNGEN_PER_PRUEFTAG`] from then on.
///
/// # Examples
///
/// ```
/// use compliance_core::models::{admit, Admission, DayUsage, MonthUsage, PlanLimits};
///
/// let plan = PlanLimits { monthly_pruefungen: Some(100), prueftag_cap: None };
/// let used_up = MonthUsage { pruefungen: 100, prueftage: 0 };
/// assert_eq!(admit(plan, used_up, DayUsage::default()), Admission::BookPrueftag);
/// ```
pub fn admit(limits: PlanLimits, month: MonthUsage, day: DayUsage) -> Admission {
let Some(quota) = limits.monthly_pruefungen else {
return Admission::Quota;
};
if month.pruefungen < quota {
return Admission::Quota;
}
if day.prueftag_booked {
return if day.prueftag_pruefungen < PRUEFUNGEN_PER_PRUEFTAG {
Admission::Prueftag
} else {
Admission::Refused(Refusal::DailyLimit)
};
}
match limits.prueftag_cap {
Some(cap) if month.prueftage >= cap => Admission::Refused(Refusal::PrueftagCap),
_ => Admission::BookPrueftag,
}
}
/// One active target as [`split_included`] sees it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BillableTarget<Id> {
/// The target's id.
pub id: Id,
/// When it was created: the oldest targets are the included ones.
pub created_at: DateTime<Utc>,
/// How it is billed now.
pub billing: TargetBilling,
}
/// The targets whose billing has to change so that the `included` oldest
/// active targets are included and the rest are extra.
///
/// # Arguments
///
/// * `targets` - The tenant's active (not archived) targets, in any order.
/// Ties on `created_at` are broken by id, so the split is stable.
/// * `included` - How many targets the plan includes; `None` is unlimited.
///
/// # Returns
///
/// Each target whose billing differs from what it should be, with the
/// billing it should have. Empty when nothing changes.
pub fn split_included<Id: Ord + Clone>(
targets: &[BillableTarget<Id>],
included: Option<u32>,
) -> Vec<(Id, TargetBilling)> {
let mut ordered: Vec<&BillableTarget<Id>> = targets.iter().collect();
ordered.sort_unstable_by(|a, b| a.created_at.cmp(&b.created_at).then(a.id.cmp(&b.id)));
// `usize::MAX` stands for "no limit"; a u32 always fits a usize here.
let limit = included.map_or(usize::MAX, |n| n as usize);
ordered
.into_iter()
.enumerate()
.filter_map(|(rank, target)| {
let wanted = if rank < limit {
TargetBilling::Included
} else {
TargetBilling::Extra
};
(target.billing != wanted).then(|| (target.id.clone(), wanted))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::TimeZone;
fn target(id: u32, day: u32, billing: TargetBilling) -> BillableTarget<u32> {
BillableTarget {
id,
created_at: Utc
.with_ymd_and_hms(2026, 11, day, 0, 0, 0)
.single()
.expect("valid date"),
billing,
}
}
#[test]
fn the_oldest_targets_are_included_and_the_rest_extra() {
// Arrange: three included targets, created on days 3, 1 and 2.
let targets = [
target(1, 3, TargetBilling::Included),
target(2, 1, TargetBilling::Included),
target(3, 2, TargetBilling::Included),
];
// Act
let changes = split_included(&targets, Some(2));
// Assert: only the newest one moves to extra.
assert_eq!(changes, vec![(1, TargetBilling::Extra)]);
}
#[test]
fn an_extra_target_moves_up_when_an_included_one_leaves() {
let targets = [
target(2, 2, TargetBilling::Included),
target(3, 3, TargetBilling::Extra),
];
assert_eq!(
split_included(&targets, Some(2)),
vec![(3, TargetBilling::Included)]
);
}
#[test]
fn without_a_limit_every_target_is_included() {
let targets = [
target(1, 1, TargetBilling::Extra),
target(2, 2, TargetBilling::Included),
];
assert_eq!(
split_included(&targets, None),
vec![(1, TargetBilling::Included)]
);
}
#[test]
fn equal_creation_times_split_by_id() {
let targets = [
target(9, 1, TargetBilling::Included),
target(4, 1, TargetBilling::Included),
];
assert_eq!(
split_included(&targets, Some(1)),
vec![(9, TargetBilling::Extra)]
);
}
#[test]
fn a_scan_a_person_started_keeps_its_attribution() {
assert_eq!(
ScanAttribution::detected(&ScanTrigger::Manual, false),
ScanAttribution::Request
);
assert_eq!(
ScanAttribution::detected(&ScanTrigger::Support, true),
ScanAttribution::Support
);
}
#[test]
fn a_scheduled_scan_is_a_change_or_our_rescan() {
assert_eq!(
ScanAttribution::detected(&ScanTrigger::Scheduled, true),
ScanAttribution::Change
);
assert_eq!(
ScanAttribution::detected(&ScanTrigger::Webhook, false),
ScanAttribution::Rescan
);
assert_eq!(
ScanAttribution::detected(&ScanTrigger::NewContent, true),
ScanAttribution::Change,
"an upload is the customer's change"
);
}
#[test]
fn what_counts_follows_the_contract() {
use ScanAttribution::{Change, Request, Rescan, Support};
use TargetBilling::{Extra, Included};
let counted: Vec<(ScanAttribution, TargetBilling)> = [Change, Request, Rescan, Support]
.into_iter()
.flat_map(|a| [(a, Included), (a, Extra)])
.filter(|(a, b)| a.chargeable(*b))
.collect();
assert_eq!(
counted,
vec![(Change, Extra), (Request, Included), (Request, Extra)]
);
}
const PLAN: PlanLimits = PlanLimits {
monthly_pruefungen: Some(100),
prueftag_cap: Some(2),
};
#[test]
fn the_quota_comes_first() {
let month = MonthUsage {
pruefungen: 99,
prueftage: 0,
};
assert_eq!(admit(PLAN, month, DayUsage::default()), Admission::Quota);
}
#[test]
fn a_used_up_quota_books_a_prueftag_that_allows_six() {
let month = MonthUsage {
pruefungen: 100,
prueftage: 1,
};
assert_eq!(
admit(PLAN, month, DayUsage::default()),
Admission::BookPrueftag
);
let booked = |used| DayUsage {
prueftag_booked: true,
prueftag_pruefungen: used,
};
assert_eq!(admit(PLAN, month, booked(5)), Admission::Prueftag);
assert_eq!(
admit(PLAN, month, booked(PRUEFUNGEN_PER_PRUEFTAG)),
Admission::Refused(Refusal::DailyLimit)
);
}
#[test]
fn the_cap_stops_new_prueftage_but_not_a_booked_one() {
let month = MonthUsage {
pruefungen: 100,
prueftage: 2,
};
assert_eq!(
admit(PLAN, month, DayUsage::default()),
Admission::Refused(Refusal::PrueftagCap)
);
let booked = DayUsage {
prueftag_booked: true,
prueftag_pruefungen: 1,
};
assert_eq!(admit(PLAN, month, booked), Admission::Prueftag);
let none_allowed = PlanLimits {
prueftag_cap: Some(0),
..PLAN
};
let nothing_booked = MonthUsage {
pruefungen: 100,
prueftage: 0,
};
assert_eq!(
admit(none_allowed, nothing_booked, DayUsage::default()),
Admission::Refused(Refusal::PrueftagCap)
);
}
#[test]
fn without_a_quota_everything_runs() {
let unlimited = PlanLimits::default();
let month = MonthUsage {
pruefungen: 10_000,
prueftage: 0,
};
assert_eq!(
admit(unlimited, month, DayUsage::default()),
Admission::Quota
);
}
#[test]
fn stored_names_are_snake_case() {
assert_eq!(
serde_json::to_value(TargetBilling::Extra).expect("serializes"),
"extra"
);
assert_eq!(
serde_json::to_value(ScanAttribution::Rescan).expect("serializes"),
"rescan"
);
}
}
+9
View File
@@ -4,6 +4,7 @@ pub mod credentials;
pub mod cve;
pub mod dast;
pub mod embedding;
pub mod exclude_paths;
pub mod finding;
pub mod git_source;
pub mod graph;
@@ -12,6 +13,7 @@ pub mod license;
pub mod license_policy;
pub mod mcp;
pub mod mcp_token;
pub mod metering;
pub mod notification;
pub mod onboarding;
pub mod oscal;
@@ -39,6 +41,9 @@ pub use dast::{
DastTarget, DastTargetType, DastVulnType,
};
pub use embedding::{CodeEmbedding, EmbeddingBuildRun, EmbeddingBuildStatus};
pub use exclude_paths::{
normalise_exclude_paths, ExcludePathError, MAX_EXCLUDE_PATHS, MAX_EXCLUDE_PATH_LEN,
};
pub use finding::{
Finding, FindingStatus, Occurrence, ScanChangeKind, ScanStatusChange, Severity, StatusChange,
};
@@ -53,6 +58,10 @@ pub use license_policy::{
};
pub use mcp::{McpServerConfig, McpServerStatus, McpTransport};
pub use mcp_token::{McpToken, McpTokenView};
pub use metering::{
admit, split_included, Admission, BillableTarget, DayUsage, MonthUsage, PlanLimits, Refusal,
RunCharge, ScanAttribution, TargetBilling, PRUEFUNGEN_PER_PRUEFTAG,
};
pub use notification::{CveNotification, NotificationSeverity, NotificationStatus};
pub use onboarding::{
default_compliance_profile, Artifact, ArtifactAuth, ArtifactKind, Classification,
+20
View File
@@ -84,6 +84,9 @@ pub enum ArtifactKind {
PlcProject,
/// Free-form plaintext describing the target (feeds classification only).
PlaintextDescription,
/// What a build wrote about its image: a Yocto image's SPDX archive
/// (`<image>.spdx.tar.zst`).
BuildOutput,
}
impl std::fmt::Display for ArtifactKind {
@@ -97,6 +100,7 @@ impl std::fmt::Display for ArtifactKind {
Self::LiveUrl => write!(f, "live_url"),
Self::PlcProject => write!(f, "plc_project"),
Self::PlaintextDescription => write!(f, "plaintext_description"),
Self::BuildOutput => write!(f, "build_output"),
}
}
}
@@ -328,6 +332,11 @@ impl Artifact {
Self::bare(ArtifactKind::MobilePackage, source_ref)
}
/// A build-output artifact (a Yocto image's SPDX archive) by file name.
pub fn build_output(source_ref: impl Into<String>) -> Self {
Self::bare(ArtifactKind::BuildOutput, source_ref)
}
/// A container-image artifact referenced by OCI ref.
pub fn container_image(source_ref: impl Into<String>) -> Self {
Self::bare(ArtifactKind::ContainerImage, source_ref)
@@ -417,6 +426,10 @@ pub struct TargetScanConfig {
pub pentest: Option<PentestConfig>,
/// Issue-tracker linkage.
pub issue_tracker: Option<IssueTrackerConfig>,
/// Directories and files left out of every scan stage, relative to the
/// tree's root, as [`super::normalise_exclude_paths`] stores them.
#[serde(default)]
pub exclude_paths: Vec<String>,
}
/// A sibling product in the company suite that may already hold authoritative
@@ -647,6 +660,11 @@ pub struct OnboardedTarget {
/// its last scan; `None` for every other target.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub layer_pins: Option<super::yocto::LayerPins>,
/// Whether the target is one of the plan's included targets or an extra
/// one (t72). The agent sets it from the plan; stored, so it never flips
/// unseen.
#[serde(default)]
pub billing: super::metering::TargetBilling,
/// Creation timestamp.
#[serde(
default = "chrono::Utc::now",
@@ -687,6 +705,7 @@ impl OnboardedTarget {
archived_at: None,
last_scan: None,
layer_pins: None,
billing: super::metering::TargetBilling::default(),
created_at: now,
updated_at: now,
}
@@ -798,6 +817,7 @@ mod tests {
assert_eq!(TargetType::PlcSps.to_string(), "plc_sps");
assert_eq!(ArtifactKind::PlcProject.to_string(), "plc_project");
assert_eq!(ArtifactKind::MobilePackage.to_string(), "mobile_package");
assert_eq!(ArtifactKind::BuildOutput.to_string(), "build_output");
}
#[test]
+5 -1
View File
@@ -10,6 +10,10 @@ pub enum ScanTrigger {
/// Started by BreakPilot support in the customer's tenant; not counted
/// as the customer's usage.
Support,
/// Started after the customer gave the target new content: created it,
/// or uploaded files (t72). Like a scheduled scan, it runs only when
/// something changed, and then it is a change-driven Prüfung.
NewContent,
}
impl ScanTrigger {
@@ -18,7 +22,7 @@ impl ScanTrigger {
pub fn started_by_person(&self) -> bool {
match self {
Self::Manual | Self::Support => true,
Self::Scheduled | Self::Webhook => false,
Self::Scheduled | Self::Webhook | Self::NewContent => false,
}
}
}
+5
View File
@@ -41,6 +41,9 @@ pub enum InImageBasis {
/// read from the recipes without BitBake: what the image declares, not
/// what a build resolved.
Declared,
/// The build's own SPDX lists one of its packages in the image (Yocto's
/// create-spdx): what the build installed.
Built,
}
impl InImageBasis {
@@ -48,6 +51,7 @@ impl InImageBasis {
pub fn as_str(self) -> &'static str {
match self {
Self::Declared => "declared",
Self::Built => "built",
}
}
@@ -55,6 +59,7 @@ impl InImageBasis {
pub fn describe(self) -> &'static str {
match self {
Self::Declared => "In the image (declared in the recipes, not resolved by bitbake)",
Self::Built => "In the image (installed by the build, from its SPDX)",
}
}
}
+48 -2
View File
@@ -184,6 +184,20 @@ pub struct ScanRun {
/// at the end of this run (sbomqs, #496); `None` when it was not scored.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sbom_quality: Option<super::sbom::SbomQuality>,
/// Why the run ran, for metering (t72): set when it starts for a scan a
/// person started, and by change detection otherwise. `None` for a run
/// skipped because nothing changed, and in runs from before metering.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attribution: Option<super::metering::ScanAttribution>,
/// Whether the run counts toward the customer's usage once it completes
/// ([`super::metering::ScanAttribution::chargeable`] for the target's
/// billing when it was attributed).
#[serde(default)]
pub chargeable: bool,
/// What the run was charged to once it counted; `None` while it runs,
/// and for a run that did not count.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub charge: Option<super::metering::RunCharge>,
}
/// Why a stage was skipped, or what a run note is about
@@ -202,6 +216,15 @@ pub enum SkipCode {
/// Vendor and third-party directories left out of SAST; `subject` lists
/// them.
VendorCode,
/// Packages a build's image SPDX lists in the image without their
/// documents, so their recipes are not known; `subject` lists them.
BuildPackagesUnresolved,
/// Test-data directories (`fixtures/`, `testdata/`) left out of the whole
/// scan: code findings, SBOM and CVE match; `subject` lists them.
TestData,
/// Paths the target's settings exclude (`scan_config.exclude_paths`),
/// left out of the whole scan; `subject` lists those that were removed.
ExcludedPaths,
/// An analysis tool did not complete; `subject` names it.
ToolFailed,
/// A package manifest without a lockfile; `subject` is the manifest.
@@ -211,6 +234,10 @@ pub enum SkipCode {
NotAnalysedYet,
/// A PLC project archive that could not be read; `subject` is its name.
ArchiveUnreadable,
/// CODESYS projects in their native (binary) format, whose control logic
/// is not analysed until they are exported as PLCopen XML; `subject`
/// lists them.
NativePlcProject,
/// An uploaded or linked artifact that could not be read; `subject` is
/// its name.
ArtifactNotIngested,
@@ -257,6 +284,12 @@ pub enum SkipCode {
/// layer pins or `LAYERSERIES_COMPAT`, so its support period was not
/// checked.
ReleaseUnknown,
/// The month's quota is used up and today's Prüftag on the target has
/// had its Prüfungen, so this counted Prüfung did not run (t72).
PrueftagLimitReached,
/// The month's quota is used up and the Prüftag limit the customer set
/// is reached, so this counted Prüfung did not run (t72).
PrueftagCapReached,
}
impl SkipCode {
@@ -266,13 +299,19 @@ impl SkipCode {
pub fn is_informational(self) -> bool {
// An exhaustive match, so a new code has to be classified here.
match self {
Self::VendorCode | Self::SuppressedInSource | Self::NotInTree => true,
Self::VendorCode
| Self::TestData
| Self::BuildPackagesUnresolved
| Self::ExcludedPaths
| Self::SuppressedInSource
| Self::NotInTree => true,
Self::FeatureDisabled
| Self::SubmodulesNotFetched
| Self::ToolFailed
| Self::DependenciesUnlocked
| Self::NotAnalysedYet
| Self::ArchiveUnreadable
| Self::NativePlcProject
| Self::ArtifactNotIngested
| Self::ArchivePasswordRequired
| Self::ArchivePasswordWrong
@@ -285,7 +324,9 @@ impl SkipCode {
| Self::PlatformProjectGenerated
| Self::UploadUnchanged
| Self::TooLargeToScan
| Self::ReleaseUnknown => false,
| Self::ReleaseUnknown
| Self::PrueftagLimitReached
| Self::PrueftagCapReached => false,
}
}
}
@@ -391,6 +432,9 @@ impl ScanRun {
languages: Vec::new(),
planned_phases: Vec::new(),
sbom_quality: None,
attribution: None,
chargeable: false,
charge: None,
}
}
}
@@ -455,6 +499,8 @@ mod skipped_stage_tests {
SkipCode::PlatformProjectGenerated,
SkipCode::UploadUnchanged,
SkipCode::TooLargeToScan,
SkipCode::PrueftagLimitReached,
SkipCode::PrueftagCapReached,
];
assert!(notes.iter().all(|c| c.is_informational()));
assert!(skips.iter().all(|c| !c.is_informational()));
+43 -28
View File
@@ -29,9 +29,6 @@ const CONTAINER_IMAGES: &str =
"container images are not scanned yet: only the sources that build them are";
/// Why a Yocto image has no SBOM or CVE match yet: that needs the build's
/// artefacts (tier 2), not the layer tree.
const YOCTO_IMAGE_SBOM: &str = "a Yocto image SBOM needs build artefacts (SPDX/manifest), planned";
const YOCTO_IMAGE_CVE: &str =
"CVE matching for a Yocto image needs build artefacts (SPDX/manifest), planned";
/// Why the firmware SBOM stage passes over a Yocto layer tree: Firmwerk forms
/// no build plan from BitBake recipes. The agent records it with this text.
pub const YOCTO_BUILD_PLANNED: &str =
@@ -62,6 +59,9 @@ pub enum ArtifactRequirement {
Mobile,
/// A container image.
Container,
/// What a build wrote about its image: a Yocto image SPDX archive or its
/// cve-check report.
BuildOutput,
/// No specific artifact required.
Any,
}
@@ -231,7 +231,7 @@ pub fn rules_for(target_type: TargetType) -> Vec<ScanRule> {
/// The rules specific to a target type (see [`rules_for`], which adds the rules
/// that apply to every target).
fn target_rules(target_type: TargetType) -> Vec<ScanRule> {
use ArtifactRequirement::{Code, Firmware, HttpUrl, Mobile, Plc, RunningUrl};
use ArtifactRequirement::{BuildOutput, Code, Firmware, HttpUrl, Mobile, Plc, RunningUrl};
match target_type {
TargetType::WebApp | TargetType::BackendService => {
let mut r = sast_umbrella();
@@ -304,17 +304,18 @@ fn target_rules(target_type: TargetType) -> Vec<ScanRule> {
Firmware,
UNPACKING_IMAGES,
));
r.push(ScanRule::unavailable(
// Tier 2: what the build wrote about its image (#150).
r.push(ScanRule::new(
ScanType::Sbom,
"SBOM from the image's build artefacts",
Firmware,
YOCTO_IMAGE_SBOM,
true,
"SBOM of the image from the build's own SPDX (create-spdx)",
BuildOutput,
));
r.push(ScanRule::unavailable(
r.push(ScanRule::new(
ScanType::Cve,
"Match image components against known CVEs",
Firmware,
YOCTO_IMAGE_CVE,
true,
"Image components against known CVEs, with Yocto's cve-check verdicts",
BuildOutput,
));
r.push(ScanRule::new(
ScanType::Dast,
@@ -409,6 +410,7 @@ fn representative_kind(req: ArtifactRequirement) -> Option<ArtifactKind> {
ArtifactRequirement::Plc => Some(ArtifactKind::PlcProject),
ArtifactRequirement::Mobile => Some(ArtifactKind::MobilePackage),
ArtifactRequirement::Container => Some(ArtifactKind::ContainerImage),
ArtifactRequirement::BuildOutput => Some(ArtifactKind::BuildOutput),
ArtifactRequirement::Any => None,
}
}
@@ -438,6 +440,7 @@ fn requirement_satisfied(req: ArtifactRequirement, target: &OnboardedTarget) ->
}
ArtifactRequirement::Mobile => target.has(ArtifactKind::MobilePackage),
ArtifactRequirement::Container => target.has(ArtifactKind::ContainerImage),
ArtifactRequirement::BuildOutput => target.has(ArtifactKind::BuildOutput),
ArtifactRequirement::Any => true,
}
}
@@ -734,34 +737,46 @@ mod tests {
}
#[test]
fn a_yocto_image_has_no_sbom_until_build_artefacts_can_be_imported() {
let t = target_with(
fn a_yocto_image_sbom_comes_from_the_build_output() {
let without = target_with(
TargetType::EmbeddedLinuxYocto,
vec![
Artifact::firmware_image("core-image.wic"),
Artifact::live_url("https://device.local"),
],
);
let opts = applicable_scans(&t);
let image_option = |scan: ScanType| {
opts.iter().find(|o| {
o.scan == scan && o.required_artifact == Some(ArtifactKind::FirmwareImage)
})
// The image rules, apart from the source SBOM/CVE of the SAST umbrella.
let image_option = |opts: &[ScanOption], scan: ScanType| {
opts.iter()
.find(|o| o.scan == scan && o.required_artifact == Some(ArtifactKind::BuildOutput))
.cloned()
};
for (scan, reason) in [
(ScanType::Sbom, YOCTO_IMAGE_SBOM),
(ScanType::Cve, YOCTO_IMAGE_CVE),
] {
let opt = image_option(scan).expect("image rule listed");
assert!(!opt.default_on);
assert_eq!(opt.unavailable_with_artifact(), Some(reason));
assert!(reason.contains("build artefacts (SPDX/manifest), planned"));
let opts = applicable_scans(&without);
for scan in [ScanType::Sbom, ScanType::Cve] {
let opt = image_option(&opts, scan).expect("image rule listed");
assert_eq!(
opt.blocked_reason.as_deref(),
Some("no build_output artifact provided")
);
}
// With a web address DAST is unblocked but still opt-in; no pentest
// until an image boots in an emulation sandbox.
let dast = option(&opts, ScanType::Dast).expect("dast listed");
assert!(dast.blocked_reason.is_none() && !dast.default_on);
assert!(!supports_pentest(t.target_type));
assert!(!supports_pentest(without.target_type));
// The image's SPDX archive, without a layer tree, turns both on.
let with = target_with(
TargetType::EmbeddedLinuxYocto,
vec![Artifact::build_output(
"core-image-minimal.rootfs.spdx.tar.zst",
)],
);
let opts = applicable_scans(&with);
for scan in [ScanType::Sbom, ScanType::Cve] {
let opt = image_option(&opts, scan).expect("image rule listed");
assert!(opt.default_on && opt.blocked_reason.is_none(), "{scan:?}");
}
}
#[test]
+121 -4
View File
@@ -13,14 +13,18 @@
//! | `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP collector endpoint (e.g. `https://otel.example.com`) | *(disabled)* |
//! | `OTEL_SERVICE_NAME` | Service name for resource | `service_name` param |
//! | `RUST_LOG` / standard `EnvFilter` | Log level filter | `info` |
//! | `LOG_CONSOLE` | Console (stdout) filter while OTLP export is on; the logs reach SigNoz via OTLP, so the console copy is only a fallback | `warn` |
use opentelemetry::global;
use opentelemetry::trace::TracerProvider as _;
use opentelemetry::KeyValue;
use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge;
use opentelemetry_otlp::{LogExporter, SpanExporter, WithExportConfig};
use opentelemetry_sdk::{logs::SdkLoggerProvider, trace::SdkTracerProvider, Resource};
use tracing_opentelemetry::OpenTelemetryLayer;
use opentelemetry_sdk::{
logs::SdkLoggerProvider, propagation::TraceContextPropagator, trace::SdkTracerProvider,
Resource,
};
use tracing_opentelemetry::{OpenTelemetryLayer, OpenTelemetrySpanExt as _};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Layer as _};
/// Guard that shuts down OTel providers on drop.
@@ -51,7 +55,10 @@ fn build_resource(service_name: &str) -> Resource {
let name = std::env::var("OTEL_SERVICE_NAME").unwrap_or_else(|_| service_name.to_string());
Resource::builder()
.with_service_name(name)
.with_attributes([KeyValue::new("service.version", env!("CARGO_PKG_VERSION"))])
.with_attributes([KeyValue::new(
"service.version",
crate::build_info::BUILD_VERSION,
)])
.build()
}
@@ -68,6 +75,9 @@ fn build_resource(service_name: &str) -> Resource {
/// Panics if the tracing subscriber cannot be initialized (e.g. called twice).
pub fn init_telemetry(service_name: &str) -> TelemetryGuard {
let otel_endpoint = std::env::var("OTEL_EXPORTER_OTLP_ENDPOINT").ok();
// W3C trace context in and out (traceparent), so a call from the portal or
// the registry and Prüfwerk's own calls to the registry stay one trace.
global::set_text_map_propagator(TraceContextPropagator::new());
let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
let fmt_layer = tracing_subscriber::fmt::layer();
@@ -117,9 +127,16 @@ pub fn init_telemetry(service_name: &str) -> TelemetryGuard {
.add_directive("h2=off".parse().unwrap_or_default())
.add_directive("reqwest=off".parse().unwrap_or_default());
// The OTLP log records are the copy SigNoz uses (structured, with
// severity and trace context). The node agent also ships stdout, so
// a full console copy would store every line twice; keep it to
// warnings and errors unless LOG_CONSOLE says otherwise.
let console_filter =
EnvFilter::try_from_env("LOG_CONSOLE").unwrap_or_else(|_| EnvFilter::new("warn"));
tracing_subscriber::registry()
.with(env_filter)
.with(fmt_layer)
.with(fmt_layer.with_filter(console_filter))
.with(otel_trace_layer)
.with(otel_log_layer.with_filter(otel_filter))
.init();
@@ -150,3 +167,103 @@ pub fn init_telemetry(service_name: &str) -> TelemetryGuard {
}
}
}
/// The W3C headers (`traceparent`, `tracestate`) for an outbound request made
/// inside the current span; empty outside a trace or with telemetry off.
pub fn trace_context_headers() -> Vec<(String, String)> {
struct Headers(Vec<(String, String)>);
impl opentelemetry::propagation::Injector for Headers {
fn set(&mut self, key: &str, value: String) {
self.0.push((key.to_string(), value));
}
}
let cx = tracing::Span::current().context();
let mut headers = Headers(Vec::new());
global::get_text_map_propagator(|p| p.inject_context(&cx, &mut headers));
headers.0
}
/// Makes `span` a child of the caller's trace when the request carried a
/// `traceparent` (and optionally `tracestate`); without one it stays a root.
pub fn continue_trace(span: &tracing::Span, traceparent: Option<&str>, tracestate: Option<&str>) {
let Some(traceparent) = traceparent else {
return;
};
struct Carrier<'a>(&'a str, Option<&'a str>);
impl opentelemetry::propagation::Extractor for Carrier<'_> {
fn get(&self, key: &str) -> Option<&str> {
match key {
"traceparent" => Some(self.0),
"tracestate" => self.1,
_ => None,
}
}
fn keys(&self) -> Vec<&str> {
vec!["traceparent", "tracestate"]
}
}
let parent = global::get_text_map_propagator(|p| p.extract(&Carrier(traceparent, tracestate)));
span.set_parent(parent);
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod propagation_tests {
use super::*;
use opentelemetry::trace::TraceContextExt as _;
const PARENT: &str = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01";
fn subscriber() -> impl tracing::Subscriber {
let tracer = SdkTracerProvider::builder().build().tracer("test");
tracing_subscriber::registry().with(OpenTelemetryLayer::new(tracer))
}
#[test]
fn a_traceparent_is_continued_and_passed_on() {
global::set_text_map_propagator(TraceContextPropagator::new());
tracing::subscriber::with_default(subscriber(), || {
let span = tracing::info_span!("request");
continue_trace(&span, Some(PARENT), None);
let trace_id = span.context().span().span_context().trace_id().to_string();
assert_eq!(trace_id, "0af7651916cd43dd8448eb211c80319c");
let _entered = span.enter();
let headers = trace_context_headers();
let (_, value) = headers
.iter()
.find(|(k, _)| k == "traceparent")
.expect("traceparent");
assert!(
value.starts_with("00-0af7651916cd43dd8448eb211c80319c-"),
"{value}"
);
assert!(
!value.contains("b7ad6b7169203331"),
"the child passes its own span id"
);
});
}
#[test]
fn without_a_traceparent_the_span_stays_a_root() {
global::set_text_map_propagator(TraceContextPropagator::new());
tracing::subscriber::with_default(subscriber(), || {
let span = tracing::info_span!("request");
continue_trace(&span, None, None);
let ctx = span.context();
let sc = ctx.span().span_context().clone();
assert!(sc.is_valid(), "a root span of its own");
assert_ne!(
sc.trace_id().to_string(),
"0af7651916cd43dd8448eb211c80319c"
);
});
}
#[test]
fn outside_a_trace_no_headers_are_sent() {
global::set_text_map_propagator(TraceContextPropagator::new());
assert!(trace_context_headers().is_empty());
}
}
+4
View File
@@ -4793,6 +4793,10 @@ tbody tr:last-child td {
margin-bottom: 2px;
}
.targets-extra {
margin-top: 4px;
}
.targets-cra {
min-width: 220px;
}
@@ -6,8 +6,8 @@ use dioxus::prelude::*;
use crate::i18n::texts::{common, kinds, onboarding as otx, targets as tx};
use crate::i18n::use_lang;
use crate::infrastructure::onboarding::{
is_file_kind, plc_format_for, set_archive_password, upload_target_artifact, ArchivePassword,
PasswordOutcome, UNSUPPORTED_ARCHIVE,
is_file_kind, plc_format_for, set_archive_password, trigger_new_content_scan,
upload_target_artifact, ArchivePassword, PasswordOutcome, UNSUPPORTED_ARCHIVE,
};
/// The upload row for target `target_id`; `on_uploaded` runs once the file
@@ -64,13 +64,16 @@ pub fn ArtifactUpload(target_id: String, on_uploaded: EventHandler<()>) -> Eleme
}
}
}
div { class: "form-group",
label { {common::ARCHIVE_PASSWORD.get(lang)} }
input {
r#type: "password",
autocomplete: "off",
value: "{password}",
oninput: move |e| password.set(e.value()),
// Firmware images and build outputs are never unpacked.
if kind() != "firmware_image" && kind() != "build_output" {
div { class: "form-group",
label { {common::ARCHIVE_PASSWORD.get(lang)} }
input {
r#type: "password",
autocomplete: "off",
value: "{password}",
oninput: move |e| password.set(e.value()),
}
}
}
button {
@@ -79,6 +82,7 @@ pub fn ArtifactUpload(target_id: String, on_uploaded: EventHandler<()>) -> Eleme
onclick: move |_| {
let Some(picked) = file() else { return; };
let (id, kind, pw) = (target_id.clone(), kind(), password());
let scan_id = id.clone();
let format = (kind == "plc_project").then(|| plc_format.read().clone());
busy.set(true);
spawn(async move {
@@ -112,10 +116,21 @@ pub fn ArtifactUpload(target_id: String, on_uploaded: EventHandler<()>) -> Eleme
}
}
};
// New content starts its change-driven scan (t72); a
// failed start leaves the file for the next scan.
let scanning = match &result {
Ok(()) => trigger_new_content_scan(scan_id).await.is_ok(),
Err(_) => false,
};
busy.set(false);
match result {
Ok(()) => {
note.set(Some((true, tx::UPLOADED.get(lang).to_string())));
let uploaded = if scanning {
tx::UPLOADED
} else {
tx::UPLOADED_NOT_SCANNED
};
note.set(Some((true, uploaded.get(lang).to_string())));
file.set(None);
password.set(String::new());
on_uploaded.call(());
+191 -35
View File
@@ -475,10 +475,26 @@ pub mod scans {
de: "Git-LFS-Dateien",
en: "Git LFS files",
},
"plc_native_project" => Text {
de: "SPS-Projekt (natives Format)",
en: "PLC project (native format)",
},
"sast_vendor_code" => Text {
de: "Herstellercode (HAL, CMSIS, Drittanbieter)",
en: "Vendor code (HAL, CMSIS, third party)",
},
"excluded_paths" => Text {
de: "Ausgenommene Pfade",
en: "Excluded paths",
},
"build_spdx" => Text {
de: "Build-SPDX (Yocto-Image)",
en: "Build SPDX (Yocto image)",
},
"test_data" => Text {
de: "Testdaten (fixtures, testdata)",
en: "Test data (fixtures, testdata)",
},
"sbom" => Text {
de: "Stückliste (Syft)",
en: "SBOM (Syft)",
@@ -588,6 +604,30 @@ pub mod scans {
(SkipCode::VendorCode, Lang::En) => format!(
"Vendor and third-party code, left out of code analysis but in the SBOM: {subject}"
),
(SkipCode::BuildPackagesUnresolved, Lang::De) => format!(
"Im Image-SPDX des Builds ohne eigenes Dokument, Rezept daher unbekannt: {subject}"
),
(SkipCode::BuildPackagesUnresolved, Lang::En) => format!(
"In the build's image SPDX without their own document, so their recipe is not known: {subject}"
),
(SkipCode::TestData, Lang::De) => format!(
"Testdaten, von der ganzen Prüfung ausgenommen (Codeanalyse, Stückliste, CVEs): {subject}"
),
(SkipCode::TestData, Lang::En) => format!(
"Test data, left out of the whole scan (code analysis, SBOM, CVEs): {subject}"
),
(SkipCode::ExcludedPaths, Lang::De) => format!(
"In den Einstellungen des Prüfobjekts ausgenommen, von der ganzen Prüfung ausgenommen (Codeanalyse, Stückliste, CVEs): {subject}"
),
(SkipCode::ExcludedPaths, Lang::En) => format!(
"Excluded in the target's settings, left out of the whole scan (code analysis, SBOM, CVEs): {subject}"
),
(SkipCode::NativePlcProject, Lang::De) => format!(
"CODESYS-Projekt im nativen Format, Steuerungslogik nicht geprüft: {subject}. Die POUs als PLCopen XML exportieren (Projekt → PLCopenXML exportieren) und den Export zum Prüfobjekt hinzufügen."
),
(SkipCode::NativePlcProject, Lang::En) => format!(
"CODESYS project in its native format, control logic not analysed: {subject}. Export the POUs as PLCopen XML (Project → Export PLCopenXML) and add the export to the target."
),
(SkipCode::ToolFailed, Lang::De) => format!(
"{subject} wurde nicht fertig; was es prüft, gilt als nicht bewertet."
),
@@ -673,6 +713,28 @@ pub mod scans {
so it was not scanned again. \"Run scan\" always scans in full."
.into()
}
(SkipCode::PrueftagLimitReached, Lang::De) => {
"Nicht geprüft: Das Monatskontingent ist aufgebraucht, und der heutige Prüftag \
für dieses Prüfobjekt hat seine Prüfungen bereits erreicht. Morgen ist wieder \
eine Prüfung möglich."
.into()
}
(SkipCode::PrueftagLimitReached, Lang::En) => {
"Not scanned: the monthly quota is used up and today's Prüftag for this target \
has had all its scans. It can be scanned again tomorrow."
.into()
}
(SkipCode::PrueftagCapReached, Lang::De) => {
"Nicht geprüft: Das Monatskontingent ist aufgebraucht, und Ihr Limit für \
Prüftage ist erreicht. Gezählte Prüfungen laufen wieder ab dem nächsten Monat \
oder nach einer Erhöhung des Limits im Portal."
.into()
}
(SkipCode::PrueftagCapReached, Lang::En) => {
"Not scanned: the monthly quota is used up and your Prüftag limit is reached. \
Counted scans run again next month, or once you raise the limit in the portal."
.into()
}
(SkipCode::TooLargeToScan, Lang::De) => {
format!("Zu groß für die Suche nach Schadsoftware, nicht geprüft: {subject}")
}
@@ -803,6 +865,17 @@ pub mod targets {
de: "+ Prüfobjekt anlegen",
en: "+ Add a target",
};
/// Badge of a target beyond the plan's included ones (t72).
pub const EXTRA: Text = Text {
de: "Zusätzliches Prüfobjekt",
en: "Extra target",
};
pub const EXTRA_HINT: Text = Text {
de: "Über die in Ihrem Tarif enthaltenen Prüfobjekte hinaus: wird monatlich \
zusätzlich berechnet, und jede seiner Prüfungen zählt zu Ihrem Kontingent.",
en: "Beyond the targets your plan includes: billed monthly on top, and each of \
its scans counts toward your quota.",
};
pub const COL_NAME: Text = Text {
de: "Name",
en: "Name",
@@ -972,9 +1045,9 @@ pub mod targets {
en: "Download evidence pack",
};
pub const EVIDENCE_HINT: Text = Text {
de: "ZIP mit OSCAL-Bewertung (CRA Anhang I), SBOM (CycloneDX, SPDX), Befunden \
de: "ZIP mit OSCAL-Prüfergebnissen (CRA Anhang I), SBOM (CycloneDX, SPDX), Befunden \
(JSON, CSV), CVE-Warnungen und einem Manifest mit SHA-256-Prüfsummen.",
en: "ZIP with the OSCAL assessment (CRA Annex I), SBOM (CycloneDX, SPDX), \
en: "ZIP with the OSCAL assessment results (CRA Annex I), SBOM (CycloneDX, SPDX), \
findings (JSON, CSV), CVE alerts and a manifest with SHA-256 checksums.",
};
pub const BACK: Text = Text {
@@ -1045,17 +1118,69 @@ pub mod targets {
};
pub const UPLOAD_HINT: Text = Text {
de: "Ein Archiv (zip, tar, tar.gz), ein SPS-Projekt oder ein Firmware-Image. Die Datei \
wird sofort hochgeladen und bei der nächsten Prüfung geprüft.",
wird sofort hochgeladen und gleich danach geprüft.",
en: "An archive (zip, tar, tar.gz), a PLC project or a firmware image. It is uploaded \
at once and checked by the next scan.",
at once and scanned right after.",
};
pub const UPLOAD: Text = Text {
de: "Hochladen",
en: "Upload",
};
pub const EXCLUDE_TITLE: Text = Text {
de: "Von der Prüfung ausgenommen",
en: "Left out of the scan",
};
pub const EXCLUDE_HINT: Text = Text {
de: "Ein Verzeichnis oder eine Datei je Zeile, relativ zum Wurzelverzeichnis \
(z. B. docs/beispiele), ohne Platzhalter. Ausgenommenes erzeugt keine Befunde, \
keine Stücklisten-Einträge und keine CVEs. Testdaten (fixtures, testdata) nimmt \
die Prüfung von selbst aus.",
en: "One directory or file per line, relative to the root (e.g. docs/samples), \
without wildcards. What is left out produces no findings, no SBOM components and \
no CVEs. Test data (fixtures, testdata) is left out automatically.",
};
/// Why an excluded path was refused, naming the entry.
pub fn exclude_error(
error: &compliance_core::models::ExcludePathError,
lang: super::super::Lang,
) -> String {
use super::super::Lang;
use compliance_core::models::{ExcludePathError as E, MAX_EXCLUDE_PATHS};
match (error, lang) {
(E::TooMany, Lang::De) => {
format!("Höchstens {MAX_EXCLUDE_PATHS} Pfade können ausgenommen werden.")
}
(E::TooMany, Lang::En) => format!("At most {MAX_EXCLUDE_PATHS} paths can be excluded."),
(E::TooLong(p), Lang::De) => format!("{p}: zu lang."),
(E::TooLong(p), Lang::En) => format!("{p}: too long."),
(E::Absolute(p), Lang::De) => {
format!("{p}: relativ zum Wurzelverzeichnis angeben, ohne führenden /.")
}
(E::Absolute(p), Lang::En) => {
format!("{p}: give it relative to the root, without a leading /.")
}
(E::OutsideTree(p), Lang::De) => {
format!("{p}: muss ein Verzeichnis oder eine Datei im Repository sein.")
}
(E::OutsideTree(p), Lang::En) => {
format!("{p}: must be a directory or file inside the repository.")
}
(E::Wildcard(p), Lang::De) => {
format!("{p}: keine Platzhalter; Verzeichnis oder Datei angeben.")
}
(E::Wildcard(p), Lang::En) => format!("{p}: no wildcards; name the directory or file."),
}
}
pub const UPLOADED: Text = Text {
de: "Hochgeladen. Starten Sie die Prüfung, um die Datei zu prüfen.",
en: "Uploaded. Start a scan to check the file.",
de: "Hochgeladen. Die Prüfung der neuen Datei startet.",
en: "Uploaded. The scan of the new file is starting.",
};
pub const UPLOADED_NOT_SCANNED: Text = Text {
de: "Hochgeladen. Die Prüfung konnte nicht gestartet werden; die nächste \
geplante Prüfung liest die Datei.",
en: "Uploaded. The scan could not be started; the next scheduled scan reads \
the file.",
};
pub const EVIDENCE_BUILDING: Text = Text {
de: "Wird erstellt …",
@@ -1229,7 +1354,7 @@ pub mod kinds {
pub const MACHINE_TYPES: usize = 4;
/// The artifact kinds, in the order the forms offer them.
pub const ARTIFACT_KINDS: [(&str, Text); 8] = [
pub const ARTIFACT_KINDS: [(&str, Text); 9] = [
(
"git_repo",
Text {
@@ -1251,6 +1376,13 @@ pub mod kinds {
en: "Firmware image",
},
),
(
"build_output",
Text {
de: "Build-Ergebnisse (Yocto: Image-SPDX .spdx.tar.zst, cve-check .json)",
en: "Build output (Yocto: image SPDX .spdx.tar.zst, cve-check .json)",
},
),
(
"mobile_package",
Text {
@@ -1934,10 +2066,10 @@ pub mod findings {
/// Every status, in the order the forms offer them.
pub const WRONG_MAPPING_HINT: Text = Text {
de: "Warum verletzt der Befund die zugeordnete CRA-Anforderung nicht (z. B. der Code \
de: "Warum gehört der Befund nicht zur zugeordneten CRA-Anforderung (z. B. der Code \
ist in Ordnung, oder die Anforderung betrifft etwas anderes)? Die Begründung hilft, \
künftige Zuordnungen zu verbessern.",
en: "Why does the finding not violate the CRA requirement it was mapped to (e.g. the \
en: "Why does the finding not belong to the CRA requirement it was mapped to (e.g. the \
code is fine, or the requirement is about something else)? The reason helps \
improve future mappings.",
};
@@ -1977,6 +2109,14 @@ pub mod findings {
de: "Liegt jetzt in Herstellercode, der von den Befunden ausgenommen ist.",
en: "Now lies in vendor code, which is left out of the findings.",
},
ScanChangeKind::NowTestData => Text {
de: "Liegt jetzt in Testdaten, die von der Prüfung ausgenommen sind.",
en: "Now lies in test data, which is left out of the scan.",
},
ScanChangeKind::NowExcluded => Text {
de: "Liegt jetzt in einem Pfad, den die Einstellungen des Prüfobjekts von der Prüfung ausnehmen.",
en: "Now lies in a path the target's settings leave out of the scan.",
},
ScanChangeKind::FoundAgain => Text {
de: "Bei der Prüfung erneut gefunden.",
en: "Found again by the scan.",
@@ -2195,16 +2335,36 @@ pub mod sbom {
de: "Yocto-Rezeptinventar (nicht die SBOM des Images): aus den Rezepten im Layer-Baum gelesen, ohne Build. Layer-Overrides und PACKAGECONFIG sind nicht aufgelöst; es listet daher mehr, als das Image enthält. Was ein Image-Rezept installiert, ist mit „Im Image (deklariert)“ markiert.",
en: "Yocto recipe inventory (not the image SBOM): read from the recipes in the layer tree, without a build. Layer overrides and PACKAGECONFIG are not resolved, so it lists more than the image contains. What an image recipe installs is marked \"In the image (declared)\".",
};
/// A component an image recipe installs (its badge and filter).
/// The badge of a component an image recipe installs.
pub const IN_IMAGE: Text = Text {
de: "Im Image (deklariert)",
en: "In the image (declared)",
};
/// The badge's and the filter's tooltip; the badge adds the images.
/// The badge of a component the build installed (its image SPDX).
pub const IN_IMAGE_BUILT: Text = Text {
de: "Im Image (gebaut)",
en: "In the image (built)",
};
/// The in-image filter's choice: declared or built alike.
pub const IN_IMAGE_ANY: Text = Text {
de: "Im Image",
en: "In the image",
};
/// The in-image filter's tooltip.
pub const IN_IMAGE_FILTER_HINT: Text = Text {
de: "Vom Build installiert (Image-SPDX) oder von den Image-Rezepten deklariert.",
en: "Installed by the build (image SPDX) or declared by the image recipes.",
};
/// The declared badge's tooltip; the badge adds the images.
pub const IN_IMAGE_HINT: Text = Text {
de: "Aus den Rezepten gelesen (IMAGE_INSTALL, Paketgruppen eine Ebene tief, IMAGE_FEATURES), nicht von BitBake aufgelöst: Overrides, PACKAGECONFIG und von DISTRO_FEATURES abhängige Pakete sind nicht berücksichtigt.",
en: "Read from the recipes (IMAGE_INSTALL, package groups one level deep, IMAGE_FEATURES), not resolved by bitbake: overrides, PACKAGECONFIG and packages that depend on DISTRO_FEATURES are not taken into account.",
};
/// The in-image badge's tooltip for a component the build installed.
pub const IN_IMAGE_BUILT_HINT: Text = Text {
de: "Vom Build installiert, laut dessen Image-SPDX (Yocto create-spdx): Overrides, PACKAGECONFIG und Maschine sind berücksichtigt.",
en: "Installed by the build, according to its image SPDX (Yocto create-spdx): overrides, PACKAGECONFIG and the machine are taken into account.",
};
/// The in-image filter's other choice.
pub const ALL_COMPONENTS: Text = Text {
de: "Alle Komponenten",
@@ -2737,34 +2897,34 @@ pub mod compliance {
en: "CRA status",
};
pub const SUBTITLE: Text = Text {
de: "Stand gegen die grundlegenden Anforderungen des Cyber Resilience Act (Anhang I)",
en: "Standing against the Cyber Resilience Act's essential requirements (Annex I)",
de: "Befunde aus der Prüfung, zugeordnet zu den grundlegenden Anforderungen des Cyber Resilience Act (Anhang I)",
en: "Scan findings mapped to the Cyber Resilience Act's essential requirements (Annex I)",
};
pub const OPEN: Text = Text {
de: "CRA-Status anzeigen",
en: "Show CRA status",
};
pub const NOT_SATISFIED: Text = Text {
de: "Nicht erfüllt",
en: "Not satisfied",
de: "Befunde zugeordnet",
en: "Findings mapped",
};
pub const NO_VIOLATION: Text = Text {
de: "Kein Verstoß gefunden",
en: "No violation found",
de: "Geprüft, keine Befunde",
en: "Checked, no findings",
};
pub const VIOLATED_COUNT: Text = Text {
de: "nicht erfüllt",
en: "violated",
de: "mit Befunden",
en: "with findings",
};
pub const NOT_ASSESSED: Text = Text {
de: "Nicht bewertet",
en: "Not assessed",
de: "Nicht geprüft",
en: "Not checked",
};
/// A control assessed on part of what it covers (a Yocto recipe
/// A control checked on part of what it covers (a Yocto recipe
/// inventory instead of the image's SBOM).
pub const PARTIAL: Text = Text {
de: "Teilweise bewertet",
en: "Partly assessed",
de: "Teilweise geprüft",
en: "Partly checked",
};
pub const RECIPE_INVENTORY_ONLY: Text = Text {
de: "Nur das Yocto-Rezeptinventar, nicht die SBOM des Images: geprüft sind die Rezepte im Layer-Baum, nicht was das Image enthält. Vollständig erst mit der SBOM aus dem Build.",
@@ -3471,9 +3631,9 @@ pub mod coverage {
de: "App-Pakete werden noch nicht analysiert",
en: "app packages are not analysed yet",
};
pub const YOCTO_BUILD_ARTEFACTS: Text = Text {
de: "braucht die Build-Artefakte des Images (SPDX/Manifest), geplant",
en: "needs the image's build artefacts (SPDX/manifest), planned",
pub const NEEDS_BUILD_OUTPUT: Text = Text {
de: "braucht die Build-Ergebnisse des Images (Image-SPDX, cve-check)",
en: "needs the image's build output (image SPDX, cve-check)",
};
pub const YOCTO_BUILD_PLANNED: Text = Text {
de: "Die Analyse von Yocto-Builds ist geplant (Stufe 2); ein Layer-Baum ist kein \
@@ -3503,8 +3663,8 @@ pub mod coverage {
// Yocto first: its image reasons also name firmware images.
let text = if r.contains("yocto build analysis") {
YOCTO_BUILD_PLANNED
} else if r.contains("build artefacts") {
YOCTO_BUILD_ARTEFACTS
} else if r.contains("build_output") {
NEEDS_BUILD_OUTPUT
} else if r.contains("recipe inventory") {
RECIPE_INVENTORY_PLANNED
} else if r.contains("recipe lint") {
@@ -3581,12 +3741,8 @@ mod coverage_tests {
coverage::MOBILE_NOT_ANALYSED,
),
(
"a Yocto image SBOM needs build artefacts (SPDX/manifest), planned",
coverage::YOCTO_BUILD_ARTEFACTS,
),
(
"CVE matching for a Yocto image needs build artefacts (SPDX/manifest), planned",
coverage::YOCTO_BUILD_ARTEFACTS,
"no build_output artifact provided",
coverage::NEEDS_BUILD_OUTPUT,
),
(
"Yocto build analysis is planned (tier 2): a layer tree is not a firmware build",
@@ -229,7 +229,7 @@ pub fn demo_seed_default_selection(targets: &[DemoSeedTarget], source_only: bool
pub fn is_file_kind(kind: &str) -> bool {
matches!(
kind,
"plc_project" | "firmware_image" | "source_archive" | "mobile_package"
"plc_project" | "firmware_image" | "source_archive" | "mobile_package" | "build_output"
)
}
@@ -299,7 +299,7 @@ pub fn validate_artifact_ref(kind: &str, source_ref: &str) -> Option<String> {
"container_image" => {
(!no_space).then(|| "Enter an image ref, e.g. registry/name:tag".to_string())
}
"source_archive" | "firmware_image" | "mobile_package" | "plc_project" => {
"source_archive" | "firmware_image" | "mobile_package" | "plc_project" | "build_output" => {
(!no_space).then(|| "Enter a path or URL (no spaces)".to_string())
}
// plaintext_description (and anything unknown): accept free-form text.
@@ -472,13 +472,16 @@ pub async fn upload_target_artifact(
super::agent_client::json_or_error(resp).await
}
/// Update a target's name / type / artifacts (dashboard editor).
/// Update a target's name / type / artifacts / excluded paths (dashboard
/// editor). `exclude_paths` replaces the stored list; the agent normalises
/// and checks it (`normalise_exclude_paths`).
#[server]
pub async fn update_target(
id: String,
name: Option<String>,
target_type: Option<String>,
artifacts: Option<Vec<ArtifactInputDto>>,
exclude_paths: Option<Vec<String>>,
) -> Result<TargetResponse, ServerFnError> {
let mut body = serde_json::Map::new();
if let Some(n) = name {
@@ -493,6 +496,12 @@ pub async fn update_target(
serde_json::to_value(a).map_err(|e| ServerFnError::new(e.to_string()))?,
);
}
if let Some(paths) = exclude_paths {
body.insert(
"scan_config".to_string(),
serde_json::json!({ "exclude_paths": paths }),
);
}
let resp = super::agent_client::agent_request(
reqwest::Method::PATCH,
&format!("/api/v1/targets/{id}"),
@@ -597,7 +606,24 @@ pub async fn delete_target(id: String) -> Result<serde_json::Value, ServerFnErro
super::agent_client::json_or_error(resp).await
}
/// Trigger a scan for a target.
/// Start the scan of a target that just got new content: it was created,
/// or files were uploaded to it (t72). It runs only when something changed,
/// as a change-driven Prüfung that does not count on an included target.
#[server]
pub async fn trigger_new_content_scan(id: String) -> Result<serde_json::Value, ServerFnError> {
let resp = super::agent_client::agent_request(
reqwest::Method::POST,
&format!("/api/v1/targets/{id}/scan?reason=new_content"),
)
.await?
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
super::agent_client::json_or_error(resp).await
}
/// Trigger a scan for a target: the customer asks for a Prüfung, which
/// always runs and counts (t72).
#[server]
pub async fn trigger_target_scan(id: String) -> Result<serde_json::Value, ServerFnError> {
let resp = super::agent_client::agent_request(
@@ -624,6 +650,7 @@ mod tests {
assert_eq!(plc_format_for("pump_station.st"), Some("structured_text"));
assert_eq!(plc_format_for("firmware.bin"), None);
assert!(is_file_kind("source_archive") && !is_file_kind("git_repo"));
assert!(is_file_kind("build_output"));
}
#[test]
+6 -5
View File
@@ -17,7 +17,7 @@ use crate::i18n::texts::{common, kinds, onboarding as tx};
use crate::i18n::{format_bytes, use_lang};
use crate::infrastructure::onboarding::{
create_target, detect_target, enable_target_scans, fetch_applicable_scans, is_file_kind,
plc_format_for, set_archive_password, trigger_target_scan, upload_target_artifact,
plc_format_for, set_archive_password, trigger_new_content_scan, upload_target_artifact,
validate_artifact_ref, validate_target_name, ArchivePassword, ArtifactInputDto,
PasswordOutcome, UNSUPPORTED_ARCHIVE,
};
@@ -405,8 +405,9 @@ pub fn OnboardingPage() -> Element {
span { style: "opacity: 0.7;", "{kind_label(&pf.kind)} ({tx::FILE_SUFFIX.get(lang)}): " }
"{pf.filename} ({format_bytes(pf.file.size(), lang)})"
}
// Firmware images are never unpacked; archives may be locked.
if pf.kind != "firmware_image" {
// Firmware images and build outputs are never unpacked;
// archives may be locked.
if pf.kind != "firmware_image" && pf.kind != "build_output" {
input {
r#type: "password",
autocomplete: "off",
@@ -590,7 +591,7 @@ pub fn OnboardingPage() -> Element {
return;
}
}
first_scan.set(match trigger_target_scan(id).await {
first_scan.set(match trigger_new_content_scan(id).await {
Ok(_) => FirstScan::Started,
Err(e) => FirstScan::Failed(e.to_string()),
});
@@ -749,7 +750,7 @@ pub fn OnboardingPage() -> Element {
let offers_optin = !source_only && !optin_scans(&applicable).is_empty();
scans.set(applicable);
if upload_errors.read().is_empty() && !offers_optin {
first_scan.set(match trigger_target_scan(id).await {
first_scan.set(match trigger_new_content_scan(id).await {
Ok(_) => FirstScan::Started,
Err(e) => FirstScan::Failed(e.to_string()),
});
+12 -7
View File
@@ -206,13 +206,13 @@ pub fn SbomPage(target: String) -> Element {
}
select {
class: "sbom-filter-select",
title: tx::IN_IMAGE_HINT.get(lang),
title: tx::IN_IMAGE_FILTER_HINT.get(lang),
onchange: move |e| {
in_image_filter.set((e.value() == "true").then_some(true));
page.set(1);
},
option { value: "", {tx::ALL_COMPONENTS.get(lang)} }
option { value: "true", {tx::IN_IMAGE.get(lang)} }
option { value: "true", {tx::IN_IMAGE_ANY.get(lang)} }
}
select {
class: "sbom-filter-select",
@@ -354,9 +354,14 @@ pub fn SbomPage(target: String) -> Element {
let edit_target = target.clone();
let edit_existing = entry.concluded.clone();
let row_key_click = row_key.clone();
// Which images declare it, on the badge's tooltip.
let in_image_title = entry.in_image.as_ref().map(|i| {
format!("{} (Images: {})", tx::IN_IMAGE_HINT.get(lang), i.images.join(", "))
// How it is known to be in the image names the badge; the
// tooltip adds which images hold it.
let in_image_badge = entry.in_image.as_ref().map(|i| {
let (label, hint) = match i.basis {
compliance_core::models::InImageBasis::Declared => (tx::IN_IMAGE, tx::IN_IMAGE_HINT),
compliance_core::models::InImageBasis::Built => (tx::IN_IMAGE_BUILT, tx::IN_IMAGE_BUILT_HINT),
};
(label.get(lang), format!("{} (Images: {})", hint.get(lang), i.images.join(", ")))
});
rsx! {
tr {
@@ -381,12 +386,12 @@ pub fn SbomPage(target: String) -> Element {
td {
style: "font-weight: 500;",
"{entry.name}"
if let Some(title) = in_image_title {
if let Some((label, title)) = in_image_badge {
" "
span {
class: "badge badge-success",
title: "{title}",
{tx::IN_IMAGE.get(lang)}
{label}
}
}
}
+41 -2
View File
@@ -39,6 +39,21 @@ fn str_at<'a>(v: &'a serde_json::Value, key: &str) -> &'a str {
v.get(key).and_then(|x| x.as_str()).unwrap_or("")
}
/// The target's excluded paths (`scan_config.exclude_paths`), one per line
/// as the editor shows them.
fn exclude_paths_of(target: &serde_json::Value) -> String {
target["scan_config"]["exclude_paths"]
.as_array()
.map(|paths| {
paths
.iter()
.filter_map(serde_json::Value::as_str)
.collect::<Vec<_>>()
.join("\n")
})
.unwrap_or_default()
}
/// The target's artifacts as the editor edits them. Credentials never come
/// back from the agent; only whether one is set.
fn editable_artifacts(target: &serde_json::Value) -> Vec<ArtifactInputDto> {
@@ -463,6 +478,7 @@ fn TargetEditor(
let mut edit_type = use_signal(|| str_at(&target, "target_type").to_string());
let mut edit_arts = use_signal(|| editable_artifacts(&target));
let mut edit_saving = use_signal(|| false);
let mut edit_excludes = use_signal(|| exclude_paths_of(&target));
// Projects are saved apart from the rest, and only when they changed.
let stored_projects = project_ids_of(&target);
let edit_projects = use_signal(|| stored_projects.clone());
@@ -475,6 +491,11 @@ fn TargetEditor(
{
let name_err = validate_target_name(&edit_name());
// Checked as the agent checks it, so a bad path shows before Save.
let exclude_lines: Vec<String> = edit_excludes().lines().map(String::from).collect();
let excludes = compliance_core::models::normalise_exclude_paths(&exclude_lines);
let exclude_err = excludes.as_ref().err().map(|e| tx::exclude_error(e, lang));
let exclude_paths = excludes.clone().unwrap_or_default();
let e_source_err = if e_source().is_empty() {
None
} else {
@@ -643,6 +664,23 @@ fn TargetEditor(
on_saved.call(());
},
}
div { class: "form-group",
label { {tx::EXCLUDE_TITLE.get(lang)} }
textarea {
rows: "3",
spellcheck: "false",
placeholder: "docs/samples",
style: "font-family: monospace;",
value: "{edit_excludes}",
oninput: move |e| edit_excludes.set(e.value()),
}
div { style: "font-size: 0.85em; color: var(--text-secondary); margin-top: 4px;",
{tx::EXCLUDE_HINT.get(lang)}
}
if let Some(err) = exclude_err.clone() {
div { style: "color: var(--danger, #d33); font-size: 0.85em;", "{err}" }
}
}
match projects.read().clone() {
Some(Ok(list)) => rsx! { ProjectPicker { projects: list, selected: edit_projects } },
Some(Err(e)) => rsx! {
@@ -658,17 +696,18 @@ fn TargetEditor(
}
button {
class: "btn btn-primary",
disabled: edit_saving() || name_err.is_some(),
disabled: edit_saving() || name_err.is_some() || exclude_err.is_some(),
onclick: move |_| {
let id = eid.clone();
let nm = edit_name();
let tt = edit_type();
let arts = edit_arts();
let excluded = exclude_paths.clone();
let chosen = edit_projects();
let projects_changed = chosen != stored_projects;
edit_saving.set(true);
spawn(async move {
let saved = match update_target(id.clone(), Some(nm), Some(tt), Some(arts)).await {
let saved = match update_target(id.clone(), Some(nm), Some(tt), Some(arts), Some(excluded)).await {
Ok(_) if projects_changed => set_target_projects(id, chosen).await,
Ok(_) => Ok(()),
Err(e) => Err(e),
@@ -233,6 +233,13 @@ pub fn TargetsPage() -> Element {
"{name}"
}
span { class: "targets-type", "{ttype}" }
if str_at(t, "billing") == "extra" {
span {
class: "badge badge-neutral targets-extra",
title: tx::EXTRA_HINT.get(lang),
{tx::EXTRA.get(lang)}
}
}
if let Some(Ok(all)) = projects.read().clone() {
ProjectChips { ids: project_ids_of(t), projects: all }
}
+1 -1
View File
@@ -25,7 +25,7 @@ tree-sitter-typescript = "0.23"
petgraph = "0.7"
# Text search
tantivy = "0.25"
tantivy = "0.27"
# Serialization
bson = { version = "2", features = ["chrono-0_4"] }
+1 -1
View File
@@ -99,7 +99,7 @@ impl SymbolIndex {
.map_err(|e| CoreError::Graph(format!("Failed to parse query: {e}")))?;
let top_docs = searcher
.search(&query, &TopDocs::with_limit(limit))
.search(&query, &TopDocs::with_limit(limit).order_by_score())
.map_err(|e| CoreError::Graph(format!("Search failed: {e}")))?;
let mut results = Vec::new();
+1 -1
View File
@@ -5,7 +5,7 @@ edition = "2021"
[dependencies]
compliance-core = { workspace = true, features = ["mongodb", "axum"] }
rmcp = { version = "0.16", features = ["server", "macros", "transport-io", "transport-streamable-http-server"] }
rmcp = { version = "3.9", features = ["server", "macros", "transport-io", "transport-streamable-http-server"] }
tokio = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
+55 -1
View File
@@ -60,7 +60,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
))
},
Arc::new(LocalSessionManager::default()),
StreamableHttpServerConfig::default(),
http_config(std::env::var("MCP_ALLOWED_HOSTS").ok().as_deref()),
);
let router = axum::Router::new()
@@ -112,3 +112,57 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
/// The Streamable HTTP configuration, with the `Host` values the server
/// answers to (DNS rebinding protection).
///
/// # Arguments
///
/// * `allowed_hosts` - `MCP_ALLOWED_HOSTS`: the hostnames or `host:port`
/// authorities clients reach the server at, comma-separated (the public
/// hostname behind the ingress, and the in-network name the dashboard
/// uses). Unset or empty, `Host` is not checked: the server sits behind the
/// ingress and per-tenant bearer tokens, as before rmcp checked it, and a
/// warning says so.
///
/// # Returns
///
/// rmcp's defaults with the host check set from `allowed_hosts`.
fn http_config(allowed_hosts: Option<&str>) -> StreamableHttpServerConfig {
let hosts: Vec<&str> = allowed_hosts
.unwrap_or_default()
.split(',')
.map(str::trim)
.filter(|h| !h.is_empty())
.collect();
let config = StreamableHttpServerConfig::default();
if hosts.is_empty() {
tracing::warn!("MCP_ALLOWED_HOSTS is not set; the Host header is not checked");
config.disable_allowed_hosts()
} else {
tracing::info!(?hosts, "MCP server answers to these hosts");
config.with_allowed_hosts(hosts)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn allowed_hosts_are_read_from_a_comma_separated_list() {
let config = http_config(Some(
" pruefwerk-stage.breakpilot.com, compliance-mcp:8090 ,",
));
assert_eq!(
config.allowed_hosts,
["pruefwerk-stage.breakpilot.com", "compliance-mcp:8090"]
);
}
#[test]
fn without_allowed_hosts_the_host_is_not_checked() {
assert!(http_config(None).allowed_hosts.is_empty());
assert!(http_config(Some(" , ")).allowed_hosts.is_empty());
}
}
+7 -12
View File
@@ -256,17 +256,12 @@ impl ComplianceMcpServer {
#[tool_handler]
impl ServerHandler for ComplianceMcpServer {
fn get_info(&self) -> ServerInfo {
ServerInfo {
protocol_version: ProtocolVersion::V_2024_11_05,
capabilities: ServerCapabilities::builder()
.enable_tools()
.build(),
server_info: Implementation::from_build_env(),
instructions: Some(
"Prüfwerk MCP server. Start with list_targets; each target's id is the repo_id/target_id the other tools take. Query findings, the CRA control mapping (OSCAL), SBOMs (CycloneDX, SPDX), CVE alerts, scan runs, DAST results and pentest sessions of your tenant."
.to_string(),
),
}
fn get_info(&self) -> ServerConfig {
ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
.with_protocol_version(ProtocolVersion::V_2024_11_05)
.with_server_info(Implementation::from_build_env())
.with_instructions(
"Prüfwerk MCP server. Start with list_targets; each target's id is the repo_id/target_id the other tools take. Query findings, the CRA control mapping (OSCAL), SBOMs (CycloneDX, SPDX), CVE alerts, scan runs, DAST results and pentest sessions of your tenant.",
)
}
}
+2 -2
View File
@@ -134,7 +134,7 @@ pub async fn list_dast_findings(
let json = serde_json::to_string_pretty(&results)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
#[derive(Debug, Deserialize, JsonSchema)]
@@ -210,5 +210,5 @@ pub async fn dast_scan_summary(
let json = serde_json::to_string_pretty(&summary)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
+3 -3
View File
@@ -153,7 +153,7 @@ pub async fn list_findings(
let json = serde_json::to_string_pretty(&results)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
#[derive(Debug, Deserialize, JsonSchema)]
@@ -179,7 +179,7 @@ pub async fn get_finding(
let json = serde_json::to_string_pretty(&finding)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
#[derive(Debug, Deserialize, JsonSchema)]
@@ -252,5 +252,5 @@ pub async fn findings_summary(
let json = serde_json::to_string_pretty(&summary)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
+1 -1
View File
@@ -39,7 +39,7 @@ where
pub fn json_result<T: serde::Serialize>(value: &T) -> Result<CallToolResult, McpError> {
let json = serde_json::to_string_pretty(value)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
/// A database error as an internal MCP error.
+1 -1
View File
@@ -47,5 +47,5 @@ pub async fn oscal_assessment(
let document = assess(&findings, chrono::Utc::now());
let json = serde_json::to_string_pretty(&document)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
+5 -5
View File
@@ -152,7 +152,7 @@ pub async fn list_pentest_sessions(
let json = serde_json::to_string_pretty(&results)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
// ── Get Pentest Session ────────────────────────────────────────
@@ -181,7 +181,7 @@ pub async fn get_pentest_session(
let json = serde_json::to_string_pretty(&session)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
// ── Get Attack Chain ───────────────────────────────────────────
@@ -223,7 +223,7 @@ pub async fn get_attack_chain(
let json = serde_json::to_string_pretty(&results)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
// ── Get Pentest Messages ───────────────────────────────────────
@@ -265,7 +265,7 @@ pub async fn get_pentest_messages(
let json = serde_json::to_string_pretty(&results)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
// ── Pentest Stats ──────────────────────────────────────────────
@@ -344,5 +344,5 @@ pub async fn pentest_stats(
let json = serde_json::to_string_pretty(&summary)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
+3 -3
View File
@@ -134,7 +134,7 @@ pub async fn list_sbom_packages(
let json = serde_json::to_string_pretty(&results)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
#[derive(Debug, Deserialize, JsonSchema)]
@@ -190,7 +190,7 @@ pub async fn sbom_vuln_report(
let json = serde_json::to_string_pretty(&report)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
/// The SBOM exchange formats `get_sbom` writes.
@@ -405,5 +405,5 @@ pub async fn third_party_notices(
include_build_only: params.include_build_only,
},
);
Ok(CallToolResult::success(vec![Content::text(text)]))
Ok(CallToolResult::success(vec![ContentBlock::text(text)]))
}
@@ -7,9 +7,9 @@ import { withBase } from 'vitepress'
/** The CRA status strip of the example view: 40 Annex I requirements. */
const craStates = [
{ key: 'violated', label: 'Nicht erfüllt', count: 3 },
{ key: 'unassessed', label: 'Nicht bewertet', count: 5 },
{ key: 'clean', label: 'Kein Verstoß gefunden', count: 13 },
{ key: 'violated', label: 'Befunde zugeordnet', count: 3 },
{ key: 'unassessed', label: 'Nicht geprüft', count: 5 },
{ key: 'clean', label: 'Geprüft, keine Befunde', count: 13 },
{ key: 'process', label: 'Nicht im Code prüfbar', count: 19 },
]
const craTotal = craStates.reduce((sum, s) => sum + s.count, 0)
@@ -106,7 +106,7 @@ const packFiles = [
<div class="bp-link-row">
<span class="bp-link-label">Befund ↔ Anforderung</span>
<span class="bp-req">CRA Anhang I, Teil I, Nr. 2</span>
<span class="bp-state bp-state-violated">Nicht erfüllt</span>
<span class="bp-state bp-state-violated">Befunde zugeordnet</span>
</div>
</article>
@@ -186,7 +186,7 @@ const packFiles = [
<section class="bp-section bp-wrap bp-note">
<p>
Prüfwerk liefert Nachweise für die CRA-Bewertung. Es zeigt, welche Anforderungen
im Code geprüft sind, und sagt offen, was nicht bewertet wurde und warum.
im Code geprüft sind, und sagt offen, was nicht geprüft wurde und warum.
Prozess- und Designanforderungen belegen Sie im BreakPilot-Compliance-Prozess.
</p>
<dl class="bp-dates">
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff. Show more