Compare commits

...
45 Commits
Author SHA1 Message Date
sharangandClaude Opus 5.5 f5697ff21d feat(scan): record which components each scan added, updated or removed (#974) (#975)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m29s
CI / Deploy Agent (push) Successful in 8m13s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 58s
CI / Deploy Dashboard (push) Successful in 6m12s
Before a stage replaces its part of a target's SBOM (the code SBOM, the
CODESYS libraries, the firmware components), the entries it replaces are
compared with the new ones and the changes are added to the scan run
(`component_changes`, at most 5000; `None` on runs from before). A
component is its package manager and name; one version before and one
after is an update, otherwise each new version an addition and each gone
one a removal.

The Verlauf API joins them with the scan's CVEs: a new CVE goes with the
component now at its version, a gone one with the component that was at
its version, and what no change explains is an advisory row. The scan's
drill-down shows the mockup's table (neu / aktualisiert / entfernt / neue
Advisory, version before → after, CVEs +n −m) above the CVE list; scans
from before say the components were not recorded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 10:18:01 +00:00
sharangandClaude Opus 5.5 31886d226c feat(dashboard): CRA Annex I tiles and the scan history chart (#957) (#973)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Successful in 1m7s
CI / Deploy Agent (push) Successful in 5m53s
CI / Deploy Dashboard (push) Successful in 3m34s
CI / Deploy MCP (push) Successful in 4m7s
The two views the repo tabs still showed as placeholders, as in the mockup:

- CRA Annex I: the 40 requirements as tiles, ten to a row, coloured by state
  and marked with a sign (! ? ~ OK –) so the state is never told by colour
  alone, with a legend and counts. A tile opens the requirement (in the
  URL, ?control=cra-ai-3) with its state, findings and reason, reusing the
  CRA page's row.
- Verlauf: per scan the CVE alerts found new above the line and those found
  gone below it, with the run's status, and a table view. A scan opens what
  it changed (?scan=<run id>): each CVE with component, version and
  severity. New: GET /api/v1/targets/{id}/scan-changes and
  compliance_core::scan_changes. A completed scan's window runs from the end
  of the completed scan before it; the first is the baseline; scans that did
  not complete change nothing. Which components a scan added, updated or
  removed is not stored, and the view says so.

Docs: the target's page and its views in the targets guide; the overview's
repo cards with their Heute buckets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 21:31:03 +00:00
sharangandClaude Opus 5.5 692840df59 feat(issues): poll Gitea for issues a person closed or reopened (#953) (#972)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m14s
CI / Deploy Agent (push) Successful in 6m58s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
The back-sync of #960 only listened to the managed git source's
organisation webhook, which most targets do not have: repositories with a
Gitea issue tracker get no webhook at all. Every GIT_SOURCE_SYNC_MINUTES
(30 by default) the agent now lists the issues of each target that has
Prüfwerk issues, one listing per repository, and compares their state with
its records. For an issue whose state differs it reads the timeline to see
who closed or reopened it; a person's change is carried back exactly as a
webhook delivery is (same rules: an undecided finding is resolved as
"closed in the ticket", a decision already made stays, a CVE issue only
records the close). Changes by the bot user that opened the issue are left
alone. Targets are polled one after the other, so a small Gitea sees one
listing at a time; tenants go through the same entitlement check as the
webhook. Where the webhook delivered a change already, the records match
and the poll does nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 21:31:02 +00:00
sharangandClaude Opus 5.5 f5ed826b99 feat(dashboard): repo views as tabs, Heute per repo, bucket counts on repo cards (#957) (#971)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 7m8s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 3m18s
CI / Deploy Dashboard (push) Successful in 5m18s
Checked against the mockup in a local run: the tab strip scrolls on its
own on a narrow screen instead of widening the page and no longer shows a
stray scrollbar; the CRA tab counts the requirements checked without a
finding (not those outside the code); the licence tab says why it is empty;
the repo cards' bucket labels wrap as in the mockup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 20:17:31 +00:00
sharangandClaude Opus 5.5 5017c6286e fix(inbox): resubmissions return to their bucket, new CVEs end a snooze, secrets stay for today (#950) (#970)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 10m5s
CI / Deploy MCP (push) Successful in 4m57s
CI / Deploy Dashboard (push) Successful in 7m29s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 20:17:17 +00:00
sharangandClaude Opus 5.5 ad0fde9106 feat(dashboard): licences by group as a clickable chart (#957) (#967)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 10m8s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 5m10s
CI / Deploy Dashboard (push) Successful in 7m57s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 17:45:09 +00:00
sharangandClaude Opus 5.5 d6986d23b1 feat(dashboard): Heute inbox with urgency buckets and dated resubmission (#950) (#965)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 9m56s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 2m35s
CI / Deploy Dashboard (push) Successful in 7m58s
A new landing page "Heute" (the overview moves to /overview and stays in
the sidebar): the Erstbewertung, target chips, the four bucket tiles and
the cards of the chosen bucket with their decisions, "Später" with one
week, one month or a date, "Details", an undo strip after each decision,
and the keys j/k/f/a/s on this page only. The sidebar's "Heute" entry
shows the workspace's "Heute handeln" count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 17:22:59 +00:00
sharangandClaude Opus 5.5 7b7731f46d feat(dashboard): CVE trend charts on the overview and per repo, repos grouped by project (#952) (#963)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Successful in 1m5s
CI / Deploy Agent (push) Successful in 9m45s
CI / Deploy MCP (push) Successful in 2m39s
CI / Deploy Dashboard (push) Successful in 7m51s
Describe the new overview figures, the 30-day chart, the targets by
project and the target page's "Wo handeln" table in the guide. Key the
overview's project groups by the project's id, so two projects with the
same name stay apart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 17:00:51 +00:00
sharangandClaude Opus 5.5 03dd8f8df4 feat(dashboard): search and filter tickets, link each to its finding (#946) (#956)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m8s
CI / Deploy Agent (push) Successful in 8m53s
CI / Deploy MCP (push) Successful in 4m49s
CI / Deploy Dashboard (push) Successful in 6m57s
The Tickets page was a paged table only. GET /api/v1/issues now takes
q (title word or ticket number: 913, #913, PROJ-913), status (open
takes in_progress, closed takes resolved) and repo_id, tenant-scoped as
before. A ticket stores no target: the target filter takes the ids of
the target's findings with a ticket plus its CVE tickets
(finding_id cve:{target}:...).

Each row links to its finding, or for a CVE ticket to the target's
components and CVEs (SBOM page), next to the tracker link. Texts are
German and English, the status is a readable badge. The CVE key prefix
and the closed check move to compliance-core so the agent and the
dashboard read them the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:41:38 +00:00
sharangandClaude Opus 5.5 f1123e1adb feat(issues): closing or reopening a Prüfwerk issue in Gitea updates the finding (#953) (#960)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Successful in 1m8s
CI / Deploy Agent (push) Successful in 8m53s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 4m56s
CI / Deploy Dashboard (push) Successful in 6m54s
The managed Git source's org webhook now handles `issues` events. A
person closing an issue Prüfwerk opened resolves the undecided finding,
recorded as "closed in the ticket" with the Gitea login; reopening it
makes the finding open again. A decision already made in Prüfwerk is
kept. Events whose sender is the issue's author (Prüfwerk's bot user,
which opened it) are ignored, and the back-sync never calls Gitea, so
nothing loops; the issue record is updated first, so the outbound sync
has nothing left to comment or close.

CVE issues closed in Gitea only record the close and who did it, no VEX
status. The scan leaves such an issue closed while the CVE is still
found, and forgets the close once a complete scan no longer finds it, so
a CVE that comes back reopens the issue as before.

The platform API names the events the webhook needs (`webhook_events`);
Prüfwerk cannot change the webhook itself, so existing webhooks need
the Issues event added in Gitea. The finding history shows
"Im Ticket geschlossen von <login>".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:22:29 +00:00
sharangandClaude Opus 5.5 6e97a0bf4c feat(findings): group findings by rule and file, decide a group at once (#951) (#961)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 9m58s
CI / Deploy MCP (push) Successful in 5m35s
CI / Deploy Dashboard (push) Successful in 7m38s
Undecided findings are grouped on read, by target, tool, rule and file,
and by directory when a rule fires in three or more files of one
directory. A stored #464 group stays a group of its own. Nothing about
groups is stored.

- compliance-core: models::finding_group with the pure group_findings
  and members_of, for the findings list and later the Heute inbox.
- GET /api/v1/finding-groups[?target=] lists the groups;
  POST /api/v1/finding-groups/decide gives every undecided member the
  same status through the bulk path (status history, issue sync), so
  VEX and the evidence pack see ordinary per-finding changes.
- Findings list: Gruppiert / Einzeln toggle (default grouped) with group
  cards, the AI's reason, the places, and Fehlalarm / Risiko akzeptiert
  for all places of a group.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:01:15 +00:00
sharangandClaude Opus 5.5 cd90a26558 feat(dashboard): open findings by type and folder as clickable charts (#957) (#964)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 9m43s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 3m18s
CI / Deploy Dashboard (push) Successful in 7m22s
The findings page of one target (/findings?target=...) now opens with two
charts of its open findings: a bar per finding type stacked by severity
(one red scale, every segment a button), and a tree map of the folders
they are in (area = open findings, colour = the most severe). A click
opens the list narrowed to that type and severity, or to that folder; the
filter goes into the URL, a breadcrumb names it and leads back to the
charts. A "Tabelle" toggle shows the same numbers as tables.

- core: finding_breakdown (the shared DTO and the pure counting function;
  open = Open, Triaged, NeedsReview as for tracker issues)
- agent: GET /api/v1/targets/{id}/finding-breakdown; the findings list
  takes an anchored literal `path` folder filter and `status=undecided`
- dashboard: FindingsPage takes scan_type, severity and path from the
  query (Route::findings(target) builds the plain list link)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 15:40:05 +00:00
sharangandClaude Opus 5.5 32cd11bb2f feat(dashboard): CVEs by severity and VEX status as a clickable grid (#957) (#962)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Successful in 1m11s
CI / Deploy Agent (push) Successful in 8m59s
CI / Deploy MCP (push) Successful in 5m4s
CI / Deploy Dashboard (push) Successful in 6m44s
The target's "Schwachstellen und VEX" card now opens with a grid of
severity rows against VEX-status columns (offen, in Pruefung, betroffen,
nicht betroffen, behoben), each count shaded on one blue scale and a
button into the CVE list narrowed to that cell. The choice sits in the
URL (?cve_severity=high&cve_vex=open), with a breadcrumb and a way back;
a table toggle shows the same numbers, and a tile counts the CVEs nobody
has assessed yet.

The agent counts the still-reported alerts in
GET /api/v1/targets/{id}/cve-matrix; the bucketing lives in
compliance-core so the dashboard narrows the list the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 15:16:06 +00:00
sharangandClaude Opus 5.5 88682c6c6a feat(dashboard): components by update impact and ecosystem as clickable charts (#957) (#966)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Successful in 1m19s
CI / Deploy Agent (push) Successful in 9m12s
CI / Deploy MCP (push) Successful in 5m2s
CI / Deploy Dashboard (push) Successful in 6m50s
The SBOM page's component tab opens, for one target, with two bar charts
(one hue, no legend; "Tabelle" shows the same numbers as tables):

- "Welches Update entfernt die meisten CVEs": per CVE group of #949 with
  a fix, "openssl 3.0.11 -> 3.0.15" and "-3 CVEs", ranked by the CVEs the
  update fixes, then by the worst severity; top 10, then "Alle anzeigen".
  A bar opens that component's group card in place (breadcrumb
  "Komponenten > openssl 3.0.11", "Zurueck zum Diagramm"). The card is
  #949's own; only its visibility changes.
- "Komponenten nach Oekosystem": per package manager the components and
  how many have a known vulnerability. A bar filters the component table
  below to it and puts it in the URL: the new additive route
  /sbom/ecosystem/:ecosystem?target=<id> renders the same page. The
  package-manager select now shows the active filter.

Agent: GET /api/v1/targets/{id}/sbom-ecosystems counts the target's SBOM
components per package manager in one aggregation (tenant database, org
role gate as every route). The ranking and the filterable managers live
in compliance-core (sbom_ecosystems), shared with /sbom/filters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 14:52:22 +00:00
sharangandClaude Opus 5.5 f57a1020db feat(cve): group CVEs by package with one VEX decision per group (#949) (#959)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Successful in 1m11s
CI / Deploy Agent (push) Successful in 8m35s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 4m55s
CI / Deploy Dashboard (push) Successful in 6m34s
The target's open CVE alerts are grouped by component (package, version,
purl) in compliance-core: the highest fixed version the advisories name
above the component's own, how many CVEs that update fixes, the CVEs per
severity (a CVE in several alerts counts once), KEV and the highest EPSS.

Agent:
- GET /api/v1/targets/{id}/cve-groups lists the groups, most severe first.
- PATCH /api/v1/targets/{id}/cve-groups/vex states one VEX status on every
  open alert of a component: one statement per alert with the validation,
  author and time of PATCH /api/v1/cves/{id}/vex, so the exports and the
  CVE issue auto-close treat them as single decisions. Settled alerts keep
  their statements; 404 when the component has no open alert.

Dashboard: the target's VEX section opens grouped ("Gruppiert") with one
card per component ("vite 5.4.21 -> 8.3.3 behebt 9 CVEs (1 hoch, ...)"),
"Nicht betroffen (alle N)" opening the same statement editor as
"Bewerten", and the rows on demand; "Einzeln" keeps the full list. The
severity badge of a row now uses the same rating as the group counts
(GitHub's MODERATE reads as medium, a CVSS-only alert gets its badge).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 14:31:33 +00:00
sharangandClaude Opus 5.5 29e38c8b80 feat(dashboard): MCP-Tokens in the sidebar, also in source-only deployments (#969)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Successful in 1m11s
CI / Deploy Agent (push) Successful in 9m19s
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Successful in 7m0s
The only link to the MCP tokens was the overview's MCP-Server card, which a
source-only deployment (prod) hides with the runtime sections. The MCP
endpoint serves such a deployment all the same, so there a token could only
be created by typing /mcp-tokens. The sidebar now has an MCP-Tokens entry
that source-only mode leaves enabled; the overview card is unchanged.

The docs name the entry instead of the bare URL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 14:10:25 +00:00
sharangandClaude Opus 5.5 ef9c578948 feat(findings): say why a finding needs review — AI false alarm or AI unsure (#954) (#958)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 6m19s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 4m6s
CI / Deploy Dashboard (push) Successful in 5m38s
"Zu prüfen" now says which of the two cases put it there: the LLM triage
dismissed the finding as a likely false alarm ("KI: wohl Fehlalarm"), or it
confirmed it with too little confidence ("KI: unsicher"). The reason is read
from the verdict already stored on the finding (triage_action, confidence),
so findings from before this change get it too; the wire status stays
needs_review.

- core: ReviewReason, ReviewReason::of_verdict and Finding::review_reason;
  the triage's confidence threshold and its action markers move to core.
- agent: apply_action decides through ReviewReason::of_verdict, so the
  triage and the label cannot drift apart.
- dashboard: the list and the finding page show the reason instead of the
  bare status, the list with the AI's rationale on hover; the finding page
  confirms ("Fehlalarm bestätigen", false positive with the rationale as
  reason) or rejects ("Doch prüfen", triaged) the AI's guess in one click,
  for roles that may change a status.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 13:49:33 +00:00
sharangandClaude Opus 5.5 589c3b440b docs(mcp): how to get an MCP token and connect a client (#968)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Agent (push) Canceled after 0s
CI / Deploy Docs (push) Successful in 1m14s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
The MCP endpoint accepts only MCP tokens (mcpt_…) from the MCP-Tokens page,
which a signed-in person creates; the docs said to use the MCP server
entry's access token, which the endpoint refuses, and gave a wrong URL.
Portal API keys neither work at the endpoint nor can create MCP tokens.

- Step by step: create the token at /mcp-tokens (also reachable in
  source-only deployments, where the overview card is hidden), add the
  server with the real endpoint (/mcp/mcp) to Claude Code or a JSON-configured
  client, check /mcp/health, and read the three 401 answers.
- API-Schlüssel: a note that keys are not for MCP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 13:48:58 +00:00
sharangandClaude Opus 5.5 b9acabb6ba feat(issues): link a finding's issue to the finding itself (#947) (#948)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m55s
CI / Agent integration (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
The "Open in Prüfwerk" link in a finding's issue went to the target's
whole finding list. It now opens the finding's own page
(/findings/{id}), where its status is set; a group (#464) links to its
own page. The link stays https-only and is left out for a finding
without an id. CVE issues and the new-findings notification keep their
links.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 13:48:43 +00:00
sharangandClaude Opus 5.5 d274c68ecb test(nightly): a queued scan run is not finished yet (t84) (#945)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m38s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 12:53:02 +00:00
sharangandClaude Opus 5.5 29d3c91f5a feat(graph): Razor and Web Forms code in the code graph (t84) (#944)
CI / Agent integration (push) Skipped
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 6m14s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 12:10:23 +00:00
sharangandClaude Opus 5.5 5a11a3b602 feat(graph): Visual Basic .NET in the code graph (t84) (#943)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 6m21s
CI / Deploy MCP (push) Successful in 3m30s
CI / Deploy Dashboard (push) Successful in 4m8s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 11:49:59 +00:00
sharangandClaude Opus 5.5 ca66b9a7b1 fix(scan): read UTF-16 and Windows-1252 files in the remaining readers (t84) (#942)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 7m21s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 51s
CI / Deploy Dashboard (push) Successful in 5m8s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 09:58:55 +00:00
sharangandClaude Opus 5.5 b420b28ea8 fix(graph): read UTF-16 and Windows-1252 source files into the code graph (t84) (#941)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 8m33s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 4m48s
CI / Deploy Dashboard (push) Successful in 6m18s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 08:13:46 +00:00
sharangandClaude Opus 5.5 d3c8eee393 fix(scan): a person's scan gets the next slot and shows as queued (t84) (#940)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 8m15s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 4m47s
CI / Deploy Dashboard (push) Successful in 6m1s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 07:52:24 +00:00
sharang c8deabd4d9 feat(dashboard): show the code graph, from its card and from a finding (t82) (#939)
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 MCP (push) Skipped
CI / Deploy Dashboard (push) Successful in 3m27s
2026-11-07 10:43:02 +00:00
sharang c1a70b025c feat(dashboard): the code graph's card on the target page (t82) (#937)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 8m31s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 4m50s
CI / Deploy Dashboard (push) Successful in 6m20s
2026-11-07 10:24:13 +00:00
sharang 37888af374 feat(graph): PLC programs, function blocks and functions in the code graph (t82) (#936)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 6m46s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-07 10:05:15 +00:00
sharang 1569100721 feat(graph): C and C# in the code graph (t82) (#935)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 10m49s
CI / Deploy MCP (push) Successful in 5m58s
CI / Deploy Dashboard (push) Successful in 7m28s
2026-11-07 09:44:21 +00:00
sharang d9fcc75792 fix(nightly): start the agent in a step, not as a service (#938)
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-07 09:44:11 +00:00
sharang a2699a3ec3 feat(metering): swap an extra target with an included one (t72) (#932)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 8m36s
CI / Agent integration (push) Skipped
CI / Deploy MCP (push) Successful in 4m54s
CI / Deploy Dashboard (push) Successful in 6m27s
2026-11-07 03:11:29 +00:00
sharang 3bdaf28737 feat(metering): this month's usage on the targets page (t72) (#931)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 8m43s
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Successful in 6m24s
2026-11-07 02:50:56 +00:00
sharang 168cbe98f8 ci: build the dashboard tests one rustc at a time (#933)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Agent (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-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 / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 8s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m37s
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 / Agent integration (push) Skipped
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 7s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 7m20s
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 / Agent integration (push) Skipped
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 8m36s
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 / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m11s
CI / Deploy Agent (push) Successful in 8m28s
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Successful in 5m14s
2026-11-05 08:30:19 +00:00
196 changed files with 31720 additions and 3260 deletions

No files matched your search

+5 -19
View File
@@ -1,23 +1,9 @@
[advisories]
ignore = [
# hickory-proto 0.25.x pulled in transitively via mongodb → hickory-resolver.
# MongoDB 3.x has not yet released with hickory-resolver 0.26.x, so we cannot
# upgrade past this without a mongodb release. Both are DNS-layer DoS vectors
# requiring a MITM/controlled DNS server against MongoDB's hostname resolution —
# not a realistic attack surface here. Revisit when mongodb bumps hickory.
# hickory-proto, pulled in transitively via mongodb → hickory-resolver
# (0.26.3 since mongodb 3.10, which fixed RUSTSEC-2026-0119). The NSEC3 loop
# is in DNSSEC validation, which the driver does not use, and needs a
# MITM/controlled DNS server against MongoDB's hostname resolution — not a
# realistic attack surface here. Revisit when hickory ships a fix.
"RUSTSEC-2026-0118", # NSEC3 loop, no fix available upstream
"RUSTSEC-2026-0119", # O(n²) name compression, fixed in hickory-proto >=0.26.1
# rmcp 0.16.0 — DNS rebinding in Streamable HTTP server transport (missing
# Host header validation). Patched in rmcp >= 1.4.0, which is a major API
# version jump from our pin; rmcp shipped 0.x → 1.x → 2.x in three months
# and the migration touches every tool handler + the auth middleware we
# just landed in #92. Threat model in our deployment: the MCP server is
# exposed at a public hostname (comp-mcp-dev.breakpilot.com) behind orca's
# TLS-terminating ingress with per-tenant bearer auth — the attack model
# (browser DNS-rebinding into localhost MCP server) doesn't directly apply.
# Defense-in-depth Host-header check is still a worthwhile follow-up.
# FOLLOW-UP: bump rmcp to 2.x in a dedicated PR (M7.3 follow-up, sized
# multi-hour due to API surface change).
"RUSTSEC-2026-0189",
]
+5
View File
@@ -146,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
+18 -2
View File
@@ -138,6 +138,8 @@ jobs:
run: cargo clippy -p werkbank-exec --all-targets -- -D warnings
- name: Clippy (control-map)
run: cargo clippy -p control-map --all-targets -- -D warnings
- name: Clippy (graph)
run: cargo clippy -p compliance-graph --all-targets -- -D warnings
# Security audit
- name: Security Audit
@@ -146,14 +148,21 @@ jobs:
RUSTC_WRAPPER: ""
# Tests (reuses compilation artifacts from clippy)
- name: Tests (core + agent + werkbank-exec + control-map)
run: cargo test -p compliance-core -p compliance-agent -p werkbank-exec -p control-map --lib
- name: Tests (core + agent + graph + werkbank-exec + control-map)
run: cargo test -p compliance-core -p compliance-agent -p compliance-graph -p werkbank-exec -p control-map --lib
# compliance-core's integration tests need no services.
- name: Tests (core integration)
run: cargo test -p compliance-core --tests
# The dashboard crate compiles as the library and as its test harness at
# once, each rustc at about 1.65 GB: two of them exceed the job's 3 GiB
# and get OOM-killed (signal 9). One at a time for these two steps.
- name: Tests (dashboard server)
env:
CARGO_BUILD_JOBS: "1"
run: cargo test -p compliance-dashboard --features server --no-default-features
- name: Tests (dashboard web)
env:
CARGO_BUILD_JOBS: "1"
run: cargo test -p compliance-dashboard --features web --no-default-features
- name: Show sccache stats
@@ -374,9 +383,16 @@ jobs:
apk add --no-cache git curl openssl
git init && git remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git"
git fetch --depth=1 origin "${GITHUB_SHA}" && git checkout FETCH_HEAD
# service.version in telemetry: the latest release tag without its v,
# as for the agent. No tag → empty, and the crate version is used.
git fetch --quiet --unshallow --tags origin || true
TAG=$(git describe --tags --abbrev=0 --match 'v[0-9]*' 2>/dev/null || true)
PRUEFWERK_VERSION="${TAG#v}"
echo "version: ${PRUEFWERK_VERSION:-crate}"
IMAGE=repo.breakpilot.com/pruefwerk/compliance-dashboard
echo "$REGISTRY_PASSWORD" | docker login repo.breakpilot.com -u "$REGISTRY_USERNAME" --password-stdin
DOCKER_BUILDKIT=1 docker build --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"
+58 -26
View File
@@ -51,30 +51,6 @@ jobs:
env:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: example
# The image main deployed. Dev mode (no Keycloak): the harness talks to
# the unauthenticated dev tenant; source_only matches staging.
agent:
image: repo.breakpilot.com/pruefwerk/compliance-agent:latest
credentials:
username: ${{ secrets.REGISTRY_USERNAME }}
password: ${{ secrets.REGISTRY_PASSWORD }}
env:
APP_ENV: dev
MONGODB_URI: mongodb://root:example@mongo:27017/?authSource=admin
MONGODB_DATABASE: nightly
PW_FEATURES: source_only
# 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 }}
steps:
- name: Checkout
run: |
@@ -149,10 +125,59 @@ jobs:
env:
RUSTC_WRAPPER: ""
# The image main deployed, started here rather than as a service:
# act_runner 0.6.1 hands a service's registry credentials to the job
# container's own pull (map order decides which service wins), so the
# Harbor login reached docker.io about every other night. mongo, the
# only service left, has no credentials. The agent shares this
# container's network: it reaches mongo by name and listens on
# localhost here. The login lands in this container's ~/.docker, which
# goes with it.
# Dev mode (no Keycloak): the harness talks to the unauthenticated dev
# tenant; source_only matches staging.
- name: Start the agent
run: |
curl -fsSL -o /tmp/docker.tgz \
https://download.docker.com/linux/static/stable/x86_64/docker-27.5.1.tgz
echo "4f798b3ee1e0140eab5bf30b0edc4e84f4cdb53255a429dc3bbae9524845d640 /tmp/docker.tgz" \
| sha256sum -c -
tar xzf /tmp/docker.tgz --strip-components=1 -C /usr/local/bin docker/docker
echo "$REGISTRY_PASSWORD" | docker login repo.breakpilot.com -u "$REGISTRY_USERNAME" --password-stdin
# -e NAME without a value passes this step's variable, so no secret
# appears on the command line. The container runs on the runner's
# daemon, outside the job's own limits, so it has its own; the label
# finds one a cancelled job left behind.
docker run -d --pull always --name "nightly-agent-${GITHUB_RUN_ID}" \
--label pruefwerk-nightly --memory 4g --cpus 2 \
--network "container:$(hostname)" \
-e APP_ENV=dev \
-e MONGODB_URI=mongodb://root:example@mongo:27017/?authSource=admin \
-e MONGODB_DATABASE=nightly \
-e PW_FEATURES=source_only \
-e LITELLM_URL -e LITELLM_API_KEY \
-e LITELLM_EMBED_MODEL=bge-multilingual-gemma2 \
-e NVD_API_KEY \
repo.breakpilot.com/pruefwerk/compliance-agent:latest
env:
RUSTC_WRAPPER: ""
REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }}
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
# No chat model: LLM triage, code review and the control judge are
# off (LlmClient sends nothing without LITELLM_MODEL, #575). Their
# output never gates the run, and with the model on, ~600 calls of
# 11 s on average (p99 147 s) on the gateway prod also uses kept
# every scan past NIGHTLY_TIMEOUT_SECS from 2026-10-30 on (#573).
# Embeddings stay on: the gateway's embedding model.
LITELLM_URL: ${{ secrets.NIGHTLY_LITELLM_URL }}
LITELLM_API_KEY: ${{ secrets.NIGHTLY_LITELLM_API_KEY }}
# Optional. The CODESYS CVE match queries NVD, which rate-limits
# unauthenticated clients; a key keeps those CVEs from going missing.
NVD_API_KEY: ${{ secrets.NIGHTLY_NVD_API_KEY }}
- name: Wait for the agent
run: |
for i in $(seq 1 90); do
curl -fsS http://agent:3001/api/v1/health && exit 0
curl -fsS http://localhost:3001/api/v1/health && exit 0
sleep 2
done
echo "agent did not become healthy" >&2
@@ -163,13 +188,20 @@ jobs:
- name: Scan the corpus and compare with the baselines
run: cargo test -p compliance-agent --test nightly -- --nocapture
env:
NIGHTLY_AGENT_URL: http://agent:3001
NIGHTLY_AGENT_URL: http://localhost:3001
NIGHTLY_CODESYS_SAMPLE: /tmp/csv-blackbox.projectarchive
NIGHTLY_ZEPHYR_EXAMPLE: /tmp/zephyr-example.zip
NIGHTLY_IOS_SAMPLE: /tmp/ios-sample.zip
NIGHTLY_ANDROID_SAMPLE: /tmp/android-sample.zip
NIGHTLY_BLESS: ${{ inputs.bless && '1' || '0' }}
# The agent is not a service, so the runner does not remove it.
- name: Stop the agent
if: always()
run: docker rm -f "nightly-agent-${GITHUB_RUN_ID}" || true
env:
RUSTC_WRAPPER: ""
# upload-artifact is a Node action and the Rust image has no node.
- name: Install node for the artifact upload
if: always()
+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
+261 -79
View File
@@ -526,6 +526,16 @@ dependencies = [
"windows-link",
]
[[package]]
name = "chrono-tz"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3"
dependencies = [
"chrono",
"phf 0.12.1",
]
[[package]]
name = "ciborium"
version = "0.2.2"
@@ -596,6 +606,7 @@ dependencies = [
"axum",
"base64 0.22.1",
"chrono",
"chrono-tz",
"compliance-core",
"compliance-dast",
"compliance-graph",
@@ -651,6 +662,7 @@ dependencies = [
"base64 0.22.1",
"bson",
"chrono",
"encoding_rs",
"hex",
"jsonschema",
"jsonwebtoken",
@@ -743,13 +755,17 @@ dependencies = [
"petgraph",
"serde",
"tantivy",
"thiserror 2.0.18",
"tokio",
"tracing",
"tree-sitter",
"tree-sitter-c",
"tree-sitter-c-sharp",
"tree-sitter-javascript",
"tree-sitter-python",
"tree-sitter-rust",
"tree-sitter-typescript",
"tree-sitter-vb-dotnet",
]
[[package]]
@@ -1114,7 +1130,7 @@ dependencies = [
"cssparser-macros",
"dtoa-short",
"itoa",
"phf",
"phf 0.13.1",
"smallvec",
]
@@ -1166,6 +1182,16 @@ dependencies = [
"darling_macro 0.23.0",
]
[[package]]
name = "darling"
version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"
dependencies = [
"darling_core 0.24.1",
"darling_macro 0.24.1",
]
[[package]]
name = "darling_core"
version = "0.21.3"
@@ -1193,6 +1219,19 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "darling_core"
version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"
dependencies = [
"ident_case",
"proc-macro2",
"quote",
"strsim",
"syn 3.0.9",
]
[[package]]
name = "darling_macro"
version = "0.21.3"
@@ -1215,6 +1254,17 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "darling_macro"
version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"
dependencies = [
"darling_core 0.24.1",
"quote",
"syn 3.0.9",
]
[[package]]
name = "dashmap"
version = "6.1.0"
@@ -1368,7 +1418,7 @@ dependencies = [
"dioxus-cli-config 0.7.3",
"http",
"infer",
"jni",
"jni 0.21.1",
"js-sys",
"ndk",
"ndk-context",
@@ -2037,18 +2087,6 @@ dependencies = [
"cfg-if",
]
[[package]]
name = "enum-as-inner"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "enumset"
version = "1.1.10"
@@ -2647,23 +2685,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hickory-proto"
version = "0.25.2"
name = "hickory-net"
version = "0.26.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8a6fe56c0038198998a6f217ca4e7ef3a5e51f46163bd6dd60b5c71ca6c6502"
checksum = "c480823ed7c2c5d0f09c41020cb6b7c28029ce60ec42dc942158dcf22f8e0a4d"
dependencies = [
"async-trait",
"cfg-if",
"data-encoding",
"enum-as-inner",
"futures-channel",
"futures-io",
"futures-util",
"hickory-proto",
"idna",
"ipnet",
"once_cell",
"rand 0.9.2",
"ring",
"jni 0.22.4",
"rand 0.10.3",
"thiserror 2.0.18",
"tinyvec",
"tokio",
@@ -2672,21 +2709,46 @@ dependencies = [
]
[[package]]
name = "hickory-resolver"
version = "0.25.2"
name = "hickory-proto"
version = "0.26.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc62a9a99b0bfb44d2ab95a7208ac952d31060efc16241c87eaf36406fecf87a"
checksum = "12b92608f679a6fa515dd1d15c1ff89443026e391200a2c840c7afcba482893d"
dependencies = [
"data-encoding",
"idna",
"ipnet",
"jni 0.22.4",
"once_cell",
"prefix-trie",
"rand 0.10.3",
"ring",
"thiserror 2.0.18",
"tinyvec",
"tracing",
"url",
]
[[package]]
name = "hickory-resolver"
version = "0.26.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f3da5255c95d5a716857d54b5b8f4e8d67c3484d3beaaaae2ce25063b3ba981"
dependencies = [
"cfg-if",
"futures-util",
"hickory-net",
"hickory-proto",
"ipconfig",
"ipnet",
"jni 0.22.4",
"moka",
"ndk-context",
"once_cell",
"parking_lot",
"rand 0.9.2",
"rand 0.10.3",
"resolv-conf",
"smallvec",
"system-configuration",
"thiserror 2.0.18",
"tokio",
"tracing",
@@ -3070,6 +3132,9 @@ name = "ipnet"
version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130"
dependencies = [
"serde",
]
[[package]]
name = "iri-string"
@@ -3105,19 +3170,68 @@ dependencies = [
"cesu8",
"cfg-if",
"combine",
"jni-sys",
"jni-sys 0.3.0",
"log",
"thiserror 1.0.69",
"walkdir",
"windows-sys 0.45.0",
]
[[package]]
name = "jni"
version = "0.22.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"
dependencies = [
"cfg-if",
"combine",
"jni-macros",
"jni-sys 0.4.1",
"log",
"simd_cesu8",
"thiserror 2.0.18",
"walkdir",
"windows-link",
]
[[package]]
name = "jni-macros"
version = "0.22.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"
dependencies = [
"proc-macro2",
"quote",
"rustc_version",
"simd_cesu8",
"syn 2.0.117",
]
[[package]]
name = "jni-sys"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130"
[[package]]
name = "jni-sys"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"
dependencies = [
"jni-sys-macros",
]
[[package]]
name = "jni-sys-macros"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
dependencies = [
"quote",
"syn 2.0.117",
]
[[package]]
name = "jobserver"
version = "0.1.34"
@@ -3486,12 +3600,12 @@ checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
[[package]]
name = "md-5"
version = "0.10.6"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98"
dependencies = [
"cfg-if",
"digest 0.10.7",
"digest 0.11.3",
]
[[package]]
@@ -3589,9 +3703,9 @@ dependencies = [
[[package]]
name = "mongocrypt"
version = "0.3.2"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8da0cd419a51a5fb44819e290fbdb0665a54f21dead8923446a799c7f4d26ad9"
checksum = "8426a875ded61430d4a811dbfda7633b6b8af0225c547fc6c28b8b0aa7d79a13"
dependencies = [
"bson",
"mongocrypt-sys",
@@ -3601,43 +3715,42 @@ dependencies = [
[[package]]
name = "mongocrypt-sys"
version = "0.1.5+1.15.1"
version = "0.1.6+1.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "224484c5d09285a7b8cb0a0c117e847ebd14cb6e4470ecf68cdb89c503b0edb9"
checksum = "851fac73f7fe22f6a3ab87f720ce509cae7c9fd08e7dd27866cc232dee07ccf4"
[[package]]
name = "mongodb"
version = "3.6.0"
version = "3.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ef2c933617431ad0246fb5b43c425ebdae18c7f7259c87de0726d93b0e7e91b"
checksum = "6466d4601ff396952e1895d88083d1ab03930b812277180eb8258bbe1a10bb0f"
dependencies = [
"base64 0.22.1",
"bitflags",
"bson",
"derive-where",
"derive_more",
"futures-core",
"futures-io",
"futures-util",
"hex",
"hickory-net",
"hickory-proto",
"hickory-resolver",
"hmac 0.12.1",
"hmac 0.13.0",
"macro_magic",
"md-5",
"mongocrypt",
"mongodb-internal-macros",
"pbkdf2 0.12.2",
"pbkdf2",
"percent-encoding",
"rand 0.9.2",
"rustc_version_runtime",
"rustls",
"rustversion",
"serde",
"serde_bytes",
"serde_with",
"sha1 0.10.6",
"sha2 0.10.9",
"sha1 0.11.0",
"sha2 0.11.1",
"socket2 0.6.2",
"stringprep",
"strsim",
@@ -3653,9 +3766,9 @@ dependencies = [
[[package]]
name = "mongodb-internal-macros"
version = "3.6.0"
version = "3.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e5758dc828eb2d02ec30563cba365609d56ddd833190b192beaee2b475a7bb3"
checksum = "995f1171fab2a793f15afd0e9ba1d84116a9411ff8e3467fe9c167462435033d"
dependencies = [
"macro_magic",
"proc-macro2",
@@ -3710,7 +3823,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"
dependencies = [
"bitflags",
"jni-sys",
"jni-sys 0.3.0",
"log",
"ndk-sys",
"num_enum",
@@ -3730,7 +3843,7 @@ version = "0.6.0+11769913"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873"
dependencies = [
"jni-sys",
"jni-sys 0.3.0",
]
[[package]]
@@ -3960,15 +4073,14 @@ checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
[[package]]
name = "openssl"
version = "0.10.75"
version = "0.10.82"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08838db121398ad17ab8531ce9de97b244589089e290a384c900cb9ff7434328"
checksum = "4de8111e94a56adca7ebfe6c365b6d42f99deb69b74b6becacd4204e2f193aa2"
dependencies = [
"bitflags",
"cfg-if",
"foreign-types",
"libc",
"once_cell",
"openssl-macros",
"openssl-sys",
]
@@ -3998,9 +4110,9 @@ checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
[[package]]
name = "openssl-sys"
version = "0.9.111"
version = "0.9.118"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82cab2d520aa75e3c58898289429321eb788c3106963d0dc886ec7a5f4adc321"
checksum = "19c413d6ec9ebaf5e1c829d355cb3e9f783778d700f135be0921d52fce3c60ae"
dependencies = [
"cc",
"libc",
@@ -4152,15 +4264,6 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b867cad97c0791bbd3aaa6472142568c6c9e8f71937e98379f584cfb0cf35bec"
[[package]]
name = "pbkdf2"
version = "0.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"
dependencies = [
"digest 0.10.7",
]
[[package]]
name = "pbkdf2"
version = "0.13.0"
@@ -4197,6 +4300,15 @@ dependencies = [
"indexmap",
]
[[package]]
name = "phf"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7"
dependencies = [
"phf_shared 0.12.1",
]
[[package]]
name = "phf"
version = "0.13.1"
@@ -4204,7 +4316,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"
dependencies = [
"phf_macros",
"phf_shared",
"phf_shared 0.13.1",
"serde",
]
@@ -4215,7 +4327,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1"
dependencies = [
"phf_generator",
"phf_shared",
"phf_shared 0.13.1",
]
[[package]]
@@ -4225,7 +4337,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"
dependencies = [
"fastrand",
"phf_shared",
"phf_shared 0.13.1",
]
[[package]]
@@ -4235,12 +4347,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"
dependencies = [
"phf_generator",
"phf_shared",
"phf_shared 0.13.1",
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "phf_shared"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981"
dependencies = [
"siphasher",
]
[[package]]
name = "phf_shared"
version = "0.13.1"
@@ -4342,6 +4463,17 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
[[package]]
name = "prefix-trie"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cf6e3177f0684016a5c209b00882e15f8bdd3f3bb48f0491df10cd102d0c6e7"
dependencies = [
"either",
"ipnet",
"num-traits",
]
[[package]]
name = "prettyplease"
version = "0.2.37"
@@ -4767,18 +4899,20 @@ dependencies = [
[[package]]
name = "rmcp"
version = "0.16.0"
version = "3.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4c9c94680f75470ee8083a0667988b5d7b5beb70b9f998a8e51de7c682ce60"
checksum = "d24a7e92f4bcaa36b97fa93c4fa7ca8f3e669eced949345b3462dba333c7f909"
dependencies = [
"async-trait",
"base64 0.22.1",
"base64 0.23.1",
"bytes",
"chrono",
"futures",
"http",
"http-body",
"http-body-util",
"indexmap",
"libc",
"pastey",
"pin-project-lite",
"rand 0.10.3",
@@ -4786,6 +4920,7 @@ dependencies = [
"schemars",
"serde",
"serde_json",
"sha2 0.11.1",
"sse-stream",
"thiserror 2.0.18",
"tokio",
@@ -4798,15 +4933,15 @@ dependencies = [
[[package]]
name = "rmcp-macros"
version = "0.16.0"
version = "3.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90c23c8f26cae4da838fbc3eadfaecf2d549d97c04b558e7bd90526a9c28b42a"
checksum = "b3140f24a766f80f9ec1607bde85680959a69b83d46fa9ce87dadab7e67ab029"
dependencies = [
"darling 0.23.0",
"darling 0.24.1",
"proc-macro2",
"quote",
"serde_json",
"syn 2.0.117",
"syn 3.0.9",
]
[[package]]
@@ -5028,7 +5163,7 @@ dependencies = [
"derive_more",
"log",
"new_debug_unreachable",
"phf",
"phf 0.13.1",
"phf_codegen",
"precomputed-hash",
"rustc-hash 2.1.1",
@@ -5302,6 +5437,22 @@ version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2"
[[package]]
name = "simd_cesu8"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"
dependencies = [
"rustc_version",
"simdutf8",
]
[[package]]
name = "simdutf8"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
[[package]]
name = "simple_asn1"
version = "0.6.4"
@@ -5429,9 +5580,9 @@ checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
[[package]]
name = "sse-stream"
version = "0.2.1"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb4dc4d33c68ec1f27d386b5610a351922656e1fdf5c05bbaad930cd1519479a"
checksum = "c25ac7aff0abd1dbc474536e40416e1102c7dd9bfba0b9861c6d357f835dcfb4"
dependencies = [
"bytes",
"futures-util",
@@ -5460,7 +5611,7 @@ checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901"
dependencies = [
"new_debug_unreachable",
"parking_lot",
"phf_shared",
"phf_shared 0.13.1",
"precomputed-hash",
]
@@ -5471,7 +5622,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69"
dependencies = [
"phf_generator",
"phf_shared",
"phf_shared 0.13.1",
"proc-macro2",
"quote",
]
@@ -6345,17 +6496,38 @@ dependencies = [
[[package]]
name = "tree-sitter"
version = "0.24.7"
version = "0.25.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5387dffa7ffc7d2dae12b50c6f7aab8ff79d6210147c6613561fc3d474c6f75"
checksum = "78f873475d258561b06f1c595d93308a7ed124d9977cb26b148c2084a4a3cc87"
dependencies = [
"cc",
"regex",
"regex-syntax",
"serde_json",
"streaming-iterator",
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-c"
version = "0.23.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "afd2b1bf1585dc2ef6d69e87d01db8adb059006649dd5f96f31aa789ee6e9c71"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-c-sharp"
version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67f06accca7b45351758663b8215089e643d53bd9a660ce0349314263737fcb0"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-javascript"
version = "0.23.1"
@@ -6402,6 +6574,16 @@ dependencies = [
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-vb-dotnet"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "180e4a199378505f9305c3d01d6ece8a8d34035f310de1c727693f8a2296025e"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]]
name = "try-lock"
version = "0.2.5"
@@ -6879,7 +7061,7 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57a9779e9f04d2ac1ce317aee707aa2f6b773afba7b931222bff6983843b1576"
dependencies = [
"phf",
"phf 0.13.1",
"phf_codegen",
"string_cache",
"string_cache_codegen",
@@ -7595,7 +7777,7 @@ dependencies = [
"lzma-rust2",
"memchr",
"nix",
"pbkdf2 0.13.0",
"pbkdf2",
"ppmd-rust",
"sha1 0.11.0",
"time",
+2
View File
@@ -28,6 +28,8 @@ chrono = { version = "0.4", features = ["serde"] }
mongodb = { version = "3", features = ["rustls-tls", "compat-3-0-0"] }
reqwest = { version = "0.12", features = ["json", "rustls-tls", "multipart", "cookies", "stream"], default-features = false }
thiserror = "2"
# Source files in UTF-16 or Windows-1252 (code graph, PLC, .NET).
encoding_rs = "0.8"
sha2 = "0.10"
hex = "0.4"
uuid = { version = "1", features = ["v4", "v5", "serde"] }
+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 . .
+3 -1
View File
@@ -176,6 +176,8 @@ The agent exposes a REST API on port 3001:
|--------|----------|-------------|
| `GET` | `/api/v1/health` | Health check |
| `GET` | `/api/v1/stats/overview` | Summary statistics and trends |
| `GET` | `/api/v1/cve-history?days=30[&target=][&project=][&per_target=true]` | Open CVEs with a fixed version per day (UTC) by severity, for the tenant, a target or a project, with the open critical/high findings |
| `GET` | `/api/v1/targets/{id}/top-updates` | The package updates that close the most of a target's open CVEs with a fix |
| `GET` | `/api/v1/targets` | List targets (Prüfobjekte), each with its newest scan run |
| `POST` | `/api/v1/targets` | Create a target |
| `GET` / `PATCH` / `DELETE` | `/api/v1/targets/{id}` | Read, update (name, type, artifacts, `scan_config` incl. `issue_tracker`) or delete a target |
@@ -193,7 +195,7 @@ The agent exposes a REST API on port 3001:
| `PATCH` | `/api/v1/findings/bulk-status` | Update the status of several findings |
| `GET` | `/api/v1/sbom` | List dependencies |
| `GET` | `/api/v1/sbom/export` | Export a target's SBOM (CycloneDX 1.5 or SPDX 2.3) |
| `GET` | `/api/v1/issues` | List cross-tracker issues |
| `GET` | `/api/v1/issues` | List cross-tracker issues (search `q`, `status=open\|closed`, `repo_id`) |
| `GET` | `/api/v1/scan-runs` | Scan execution history |
| `GET` | `/api/v1/graph/{repo_id}` | Code knowledge graph |
| `POST` | `/api/v1/graph/{repo_id}/build` | Trigger graph build |
+2
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 }
+238 -29
View File
@@ -10,9 +10,15 @@ use crate::database::DatabasePool;
use crate::llm::LlmClient;
use crate::pipeline::orchestrator::PipelineOrchestrator;
use crate::registry::RegistryClient;
use crate::scan_gate::{Admission, HeldTarget, ScanGate};
use crate::scan_gate::{Admission, HeldTarget, Job, Priority, ScanGate};
use crate::secrets::SecretBox;
/// A target whose billing changed, with its new billing (t72).
pub type BillingChange = (
mongodb::bson::oid::ObjectId,
compliance_core::models::TargetBilling,
);
/// Default maximum concurrent pentest sessions.
const DEFAULT_MAX_CONCURRENT_SESSIONS: usize = 5;
@@ -133,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;
@@ -142,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),
};
@@ -153,12 +172,106 @@ impl ComplianceAgent {
});
}
/// Store which of the tenant's targets are the plan's included ones and
/// which are extra (t72), from the plan's `included_targets`. Without a
/// registry every target is included. Best-effort: when the plan cannot
/// be read or the targets not updated, the stored split stays.
///
/// # Returns
///
/// The targets whose billing changed, with their new billing.
pub async fn refresh_billing(
&self,
tenant_id: &str,
db: &crate::database::Database,
) -> Vec<BillingChange> {
match self.plan(tenant_id).await {
Some(plan) => {
self.assign_billing(tenant_id, db, plan.included_targets)
.await
}
None => Vec::new(),
}
}
/// The tenant's plan for metering (t72), from its entitlement; without
/// a registry, no limits at all. `None` when the registry did not
/// answer: then the stored billing stays, and counted Prüfungen are
/// neither checked nor charged.
pub async fn plan(&self, tenant_id: &str) -> Option<crate::metering::Plan> {
let Some(registry) = &self.registry else {
return Some(crate::metering::Plan::default());
};
match registry.check_entitlement(tenant_id, None, None).await {
Ok(check) => Some(crate::metering::Plan {
included_targets: check.included_targets(),
limits: check.plan_limits(),
}),
Err(e) => {
tracing::warn!(tenant_id, "plan not read, metering waits: {e}");
None
}
}
}
/// Store the billing of the tenant's targets for a plan that includes
/// `included` targets; best-effort.
async fn assign_billing(
&self,
tenant_id: &str,
db: &crate::database::Database,
included: Option<u32>,
) -> Vec<BillingChange> {
let changes = match crate::metering::assign_billing(db, included).await {
Ok(changes) => {
if !changes.is_empty() {
tracing::info!(tenant_id, changed = changes.len(), "target billing updated");
}
changes
}
Err(e) => {
tracing::warn!(tenant_id, "target billing not updated: {e}");
return Vec::new();
}
};
self.report_extra_peak(tenant_id, db).await;
changes
}
/// Send the month's peak of extra targets as `target.extra` when it
/// rose, and once a day besides (t72). The key carries the peak, so the
/// registry keeps every rise and drops the daily re-send as a duplicate;
/// billing takes the highest quantity per tenant-month. Count only: no
/// target names leave Prüfwerk. Best-effort.
async fn report_extra_peak(&self, tenant_id: &str, db: &crate::database::Database) {
let now = chrono::Utc::now();
match crate::metering::record_extra_peak(db, now).await {
Ok(Some(peak)) => {
let (month, _) = crate::metering::berlin_period(now);
self.emit_usage_quantity(
tenant_id,
"target.extra",
format!("target-extra:{tenant_id}:{month}:{peak}"),
f64::from(peak),
serde_json::json!({ "month": month }),
);
}
Ok(None) => {}
Err(e) => tracing::warn!(tenant_id, "extra targets not recorded: {e}"),
}
}
/// Scan a target, through the [`ScanGate`]: at most `SCAN_CONCURRENCY` scans
/// run at once, and a request for a target that is already being scanned is
/// coalesced — it becomes the one pending follow-up that this task runs next,
/// or it is dropped if a follow-up is already pending. A scheduled scan
/// first waits a random [`crate::scan_gate::start_delay`]. Every trigger
/// (click, webhook, scheduler, demo seed) comes through here.
/// run at once, a person's before scheduled and webhook ones, and a request
/// for a target that is already queued or being scanned is coalesced — it
/// becomes the one pending follow-up that this task runs next, it takes over
/// a queued scan that was not a person's, or it is dropped as covered. A
/// scheduled scan first waits a random [`crate::scan_gate::start_delay`].
/// Every trigger (click, webhook, scheduler, demo seed) comes through here.
///
/// Each request is recorded at once as a `queued` run, which shows that it
/// waits for a slot (t84); a request that will not run has its queued run
/// removed again.
///
/// # Errors
///
@@ -180,15 +293,22 @@ impl ComplianceAgent {
);
tokio::time::sleep(delay).await;
}
let db = self.db_pool.for_tenant_id(tenant_id).await?;
let run_id = queue_run(&db, target_id, &trigger).await;
let key = ScanGate::key(tenant_id, target_id);
match self.scan_gate.admit(&key, trigger.clone()) {
match self
.scan_gate
.admit(&key, Job::new(trigger, run_id.clone()))
{
Admission::Run => {}
Admission::Coalesced => {
Admission::Coalesced { replaced } => {
tracing::info!(
tenant_id,
target_id,
took_over = replaced.is_some(),
"scan already running; follow-up queued"
);
discard_queued_run(&db, replaced.as_deref()).await;
return Ok(());
}
Admission::Dropped => {
@@ -197,57 +317,83 @@ impl ComplianceAgent {
target_id,
"scan and follow-up already queued; dropped"
);
discard_queued_run(&db, run_id.as_deref()).await;
return Ok(());
}
}
// Released on panic or cancellation; a normal finish disarms it.
let held = HeldTarget::new(&self.scan_gate, key.clone());
let mut trigger = trigger;
let result = loop {
let outcome = {
let _slot = self
.scan_gate
.slot()
.await
.map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?;
self.run_one_target_scan(tenant_id, target_id, trigger.clone())
.await
};
// The scan to run is the one current when the slot is granted: a
// person's request may have taken it over while it waited.
let (slot, job) = self
.scan_gate
.start(&key)
.await
.map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?;
let outcome = self.run_one_target_scan(tenant_id, target_id, &job).await;
drop(slot);
if let Err(e) = &outcome {
tracing::error!(tenant_id, target_id, "scan failed: {e}");
fail_queued_run(&db, job.run_id.as_deref(), e).await;
}
match self.scan_gate.finish(&key) {
Some(next) => trigger = next,
None => break outcome,
if !self.scan_gate.finish(&key) {
break outcome;
}
};
held.disarm();
result
}
/// One scan of a target, with no gating: the pipeline plus its usage event.
/// One scan of a target, with no gating: the pipeline plus its usage event,
/// recorded on the run that waited for it and charged as `job` says.
async fn run_one_target_scan(
&self,
tenant_id: &str,
target_id: &str,
trigger: compliance_core::models::ScanTrigger,
job: &Job,
) -> Result<(), crate::error::AgentError> {
let trigger = job.trigger.clone();
let db = self.db_pool.for_tenant_id(tenant_id).await?;
// Whether this target is included or extra decides whether its scan
// counts, and the plan's limits whether a counted one may run (t72).
let plan = self.plan(tenant_id).await;
if let Some(plan) = &plan {
self.assign_billing(tenant_id, &db, plan.included_targets)
.await;
}
let orchestrator =
PipelineOrchestrator::new(self.config.clone(), tenant_id, db.clone(), self.llm.clone())
.with_nuget_license_cache(self.nuget_license_cache.clone())
.with_exploit_cache(self.exploit_cache.clone())
.with_advisory_index(self.advisory_index.clone());
.with_advisory_index(self.advisory_index.clone())
.with_plan_limits(plan.map(|p| p.limits))
.with_charged_as(job.charged_as.clone());
let started = chrono::Utc::now();
let scanned = orchestrator.run_target(target_id, trigger.clone()).await?;
let outcome = orchestrator
.run_target(target_id, trigger.clone(), job.run_id.as_deref())
.await?;
// Support's scans are ours, not the customer's usage; a scheduled scan
// skipped because nothing changed scanned nothing (#465).
if scanned && trigger != compliance_core::models::ScanTrigger::Support {
if outcome.scanned && trigger != compliance_core::models::ScanTrigger::Support {
self.emit_usage(
tenant_id,
"scan.completed",
format!("scan:{tenant_id}:{target_id}:{}", started.timestamp()),
serde_json::json!({ "target_id": target_id, "trigger": format!("{trigger:?}") }),
serde_json::json!({
"target_id": target_id,
"trigger": format!("{trigger:?}"),
"attribution": outcome.attribution,
"counted": outcome.chargeable,
}),
);
}
if let Some(day) = &outcome.booked_prueftag {
self.emit_usage(
tenant_id,
"prueftag.booked",
format!("prueftag:{tenant_id}:{target_id}:{day}"),
serde_json::json!({ "target_id": target_id, "day": day }),
);
}
self.notify_new_findings(tenant_id, target_id, &db, started);
@@ -295,7 +441,7 @@ impl ComplianceAgent {
// slot too. Each PR is distinct work, so it is not coalesced.
let _slot = self
.scan_gate
.slot()
.slot(Priority::Background)
.await
.map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?;
let db = self.db_pool.for_tenant_id(tenant_id).await?;
@@ -371,6 +517,69 @@ impl ComplianceAgent {
}
}
/// Record a scan request for `target_id` as a run waiting for a slot (t84),
/// so it shows at once. Returns its id, or `None` when it could not be
/// written: the scan then runs on a run of its own when it starts.
async fn queue_run(
db: &crate::database::Database,
target_id: &str,
trigger: &compliance_core::models::ScanTrigger,
) -> Option<String> {
let run = compliance_core::models::ScanRun::queued(target_id.to_string(), trigger.clone());
match db.scan_runs().insert_one(&run).await {
Ok(insert) => insert.inserted_id.as_object_id().map(|id| id.to_hex()),
Err(e) => {
tracing::warn!(target_id, "queued scan run not recorded: {e}");
None
}
}
}
/// Remove the queued run `run_id` of a request that will not run, because
/// another queued scan covers it or took it over. A run that has started
/// meanwhile is kept.
async fn discard_queued_run(db: &crate::database::Database, run_id: Option<&str>) {
let Some(oid) = run_id.and_then(|id| mongodb::bson::oid::ObjectId::parse_str(id).ok()) else {
return;
};
if let Err(e) = db
.scan_runs()
.delete_one(mongodb::bson::doc! { "_id": oid, "status": "queued" })
.await
{
tracing::warn!(run_id = %oid, "queued scan run not removed: {e}");
}
}
/// Close the queued run `run_id` as failed when its scan ended with `error`
/// before it started (an unknown target, an unreachable database), so it does
/// not stay queued. A run the scan started records its own outcome.
async fn fail_queued_run(
db: &crate::database::Database,
run_id: Option<&str>,
error: &crate::error::AgentError,
) {
let Some(oid) = run_id.and_then(|id| mongodb::bson::oid::ObjectId::parse_str(id).ok()) else {
return;
};
let (code, message) = error.run_failure();
if let Err(e) = db
.scan_runs()
.update_one(
mongodb::bson::doc! { "_id": oid, "status": "queued" },
mongodb::bson::doc! { "$set": {
"status": "failed",
"error_message": message,
"error_code": mongodb::bson::to_bson(&code).unwrap_or_default(),
"completed_at": mongodb::bson::DateTime::now(),
} },
)
.await
{
tracing::warn!(run_id = %oid, "queued scan run not closed: {e}");
}
}
/// Findings of `target_id` first stored since `since`, by severity; `None`
/// when there are none.
async fn new_findings_summary(
@@ -0,0 +1,218 @@
//! The CVE charts of the overview and a target's page (#952): open CVEs
//! with a fix per day, and the package updates that close the most of them.
//!
//! Both read the tenant's own database; the org-role middleware lets every
//! role that may read call them, like the other target and CVE reads.
use axum::extract::{Extension, Path, Query};
use axum::http::StatusCode;
use axum::Json;
use mongodb::bson::{doc, oid::ObjectId, Document};
use serde::{Deserialize, Deserializer};
use compliance_core::cve_history::{
top_updates, window, CveHistory, OpenFindings, TopUpdate, DEFAULT_DAYS, MAX_DAYS,
};
use compliance_core::models::CveAlert;
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResult};
use super::health::open_findings_by_severity;
use crate::database::Database;
/// The updates a target's "Wo handeln" table lists.
const TOP_UPDATES_SHOWN: usize = 10;
/// The query of [`cve_history`].
#[derive(Debug, Deserialize)]
pub struct HistoryQuery {
/// Days back from today, `1..=90` (clamped); 30 when not given.
#[serde(default = "default_days", deserialize_with = "de_days")]
pub days: u32,
/// Only this target. Takes precedence over `project`.
#[serde(default)]
pub target: Option<String>,
/// Only the targets of this project (`targets.project_ids`).
#[serde(default)]
pub project: Option<String>,
/// Also each target's own series, for the overview's repo cards.
#[serde(default)]
pub per_target: bool,
}
fn default_days() -> u32 {
DEFAULT_DAYS
}
/// Clamp a caller-supplied number of days to `1..=MAX_DAYS`.
fn de_days<'de, D: Deserializer<'de>>(d: D) -> Result<u32, D::Error> {
Ok(u32::deserialize(d)?.clamp(1, MAX_DAYS))
}
/// A non-empty, trimmed query value.
fn given(value: Option<&str>) -> Option<&str> {
value.map(str::trim).filter(|v| !v.is_empty())
}
/// The target ids the query is about: one target, a project's targets, or
/// `None` for every target of the tenant.
async fn scope(db: &Database, query: &HistoryQuery) -> Result<Option<Vec<String>>, StatusCode> {
if let Some(target) = given(query.target.as_deref()) {
return Ok(Some(vec![target.to_string()]));
}
let Some(project) = given(query.project.as_deref()) else {
return Ok(None);
};
let rows: Vec<Document> = collect_cursor_async(
db.onboarded_targets()
.clone_with_type::<Document>()
.find(doc! { "project_ids": project })
.projection(doc! { "_id": 1 })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
)
.await;
Ok(Some(
rows.iter()
.filter_map(|row| row.get_object_id("_id").ok().map(|id| id.to_hex()))
.collect(),
))
}
/// The alerts with a fixed version that may be open at some point after
/// `since`, of `targets` (every target with `None`). The long texts are
/// left out; the history does not need them.
async fn alerts_with_fix(
db: &Database,
targets: Option<&[String]>,
since: chrono::DateTime<chrono::Utc>,
) -> Result<Vec<CveAlert>, StatusCode> {
let mut filter = doc! {
"fixed_versions.0": { "$exists": true },
"$or": [
{ "resolved_at": null },
{ "resolved_at": { "$gte": mongodb::bson::DateTime::from_chrono(since) } },
],
};
if let Some(targets) = targets {
filter.insert("repo_id", doc! { "$in": targets });
}
let cursor = db
.cve_alerts()
.find(filter)
.projection(doc! {
"summary": 0, "llm_impact_summary": 0, "advisories": 0, "exploitation": 0,
})
.await
.map_err(|e| {
tracing::warn!("CVE history: loading alerts failed: {e}");
StatusCode::INTERNAL_SERVER_ERROR
})?;
Ok(collect_cursor_async(cursor).await)
}
/// `GET /api/v1/cve-history?days=30[&target=<id>][&project=<id>][&per_target=true]`
/// — per day (UTC, oldest first, today last) the open CVEs with a fixed
/// version, by severity, for the tenant, one target or one project's
/// targets; plus the open critical and high findings of the same scope.
///
/// A CVE counts on day `d` when, at the end of `d`: its alert was found
/// (`created_at`), not resolved (`resolved_at` unset or later), not settled
/// by a VEX `not_affected` / `fixed` stated by then (`vex.at`), and its
/// advisory names a fixed version. One CVE counts once per target (its
/// GHSA and CVE alias, or two packages, are one), at its highest severity;
/// a tenant's or project's count is the sum over its targets. See
/// [`compliance_core::cve_history`] for what the stored state cannot show.
#[tracing::instrument(skip_all)]
pub async fn cve_history(
Extension(agent): AgentExt,
tenant: TenantCtx,
Query(query): Query<HistoryQuery>,
) -> ApiResult<CveHistory> {
let db = tenant_db(&agent, &tenant).await?;
let now = chrono::Utc::now();
let since = window(now, query.days).first().map_or(now, |(_, end)| *end);
let targets = scope(&db, &query).await?;
let findings_scope = match &targets {
Some(ids) => doc! { "repo_id": { "$in": ids } },
None => doc! {},
};
let (alerts, by_severity) = tokio::join!(
alerts_with_fix(&db, targets.as_deref(), since),
open_findings_by_severity(&db, findings_scope),
);
let mut history = CveHistory::of(&alerts?, now, query.days);
let count = |name: &str| by_severity.get(name).copied().unwrap_or(0);
history.open_findings = OpenFindings {
critical: count("critical"),
high: count("high"),
};
if !query.per_target {
history.targets.clear();
}
Ok(Json(ApiResponse {
data: history,
total: None,
page: None,
}))
}
/// `GET /api/v1/targets/{id}/top-updates` — the package updates that close
/// the most of the target's open CVEs with a fix (at most ten): package,
/// current version, the highest fixed version its alerts name, and how
/// many CVEs (and critical ones) it closes. 404 for a target the tenant
/// does not have.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn target_top_updates(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
) -> ApiResult<Vec<TopUpdate>> {
let oid = ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
let db = tenant_db(&agent, &tenant).await?;
db.onboarded_targets()
.find_one(doc! { "_id": oid })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::NOT_FOUND)?;
let now = chrono::Utc::now();
let ids = [id];
let alerts = alerts_with_fix(&db, Some(&ids), now).await?;
let mut updates = top_updates(&alerts, now);
let total = updates.len() as u64;
updates.truncate(TOP_UPDATES_SHOWN);
Ok(Json(ApiResponse {
data: updates,
total: Some(total),
page: None,
}))
}
#[cfg(test)]
mod tests {
use super::*;
fn query(text: &str) -> HistoryQuery {
let uri: axum::http::Uri = format!("/api/v1/cve-history?{text}").parse().unwrap();
Query::<HistoryQuery>::try_from_uri(&uri).unwrap().0
}
#[test]
fn the_days_are_clamped_and_default_to_thirty() {
assert_eq!(query("").days, 30);
assert_eq!(query("days=0").days, 1);
assert_eq!(query("days=100000").days, MAX_DAYS);
let q = query("days=7&target=t1&per_target=true");
assert_eq!(
(q.days, q.target.as_deref(), q.per_target),
(7, Some("t1"), true)
);
}
#[test]
fn a_blank_scope_means_every_target() {
assert_eq!(given(Some(" ")), None);
assert_eq!(given(Some(" p1 ")), Some("p1"));
assert_eq!(given(None), None);
}
}
@@ -0,0 +1,114 @@
//! A target's CVE alerts counted by severity and VEX status (#957), for the
//! grid the dashboard's "CVEs & VEX" view opens with.
use axum::extract::{Extension, Path};
use axum::http::StatusCode;
use axum::Json;
use mongodb::bson::{doc, Document};
use serde::Deserialize;
use compliance_core::cve_matrix::{CveCell, CveMatrix};
use compliance_core::models::VexStatus;
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResult};
/// The fields of a stored alert the grid reads.
#[derive(Debug, Deserialize)]
struct MatrixRow {
#[serde(default)]
severity: Option<String>,
#[serde(default)]
cvss_score: Option<f64>,
#[serde(default)]
vex: Option<MatrixVex>,
}
/// The status of an alert's VEX statement; the rest of it is not read.
#[derive(Debug, Deserialize)]
struct MatrixVex {
status: VexStatus,
}
impl MatrixRow {
fn cell(&self) -> CveCell {
CveCell::of(
self.severity.as_deref(),
self.cvss_score,
self.vex.as_ref().map(|v| v.status),
)
}
}
/// The alerts of target `id` the grid counts: still reported, as in
/// [`compliance_core::cve_matrix::counts`]. `null` matches a missing
/// `resolved_at` and one stored as `null`.
fn still_reported(id: &str) -> Document {
doc! { "repo_id": id, "resolved_at": null }
}
/// GET /api/v1/targets/{id}/cve-matrix — the target's still-reported CVE
/// alerts counted per severity and VEX status. Scoped to the requester's
/// tenant like `GET /api/v1/targets/{id}/cves`; the org-role middleware
/// lets every reading role in.
///
/// # Errors
///
/// 500 when the tenant's database or the alerts cannot be read.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn target_cve_matrix(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
) -> ApiResult<CveMatrix> {
let db = tenant_db(&agent, &tenant).await?;
// Only the three fields the bucketing reads, not the summaries and
// references of every alert. A row that does not decode is skipped with
// a warning, as the CVE list skips it.
let cursor = db
.cve_alerts()
.clone_with_type::<MatrixRow>()
.find(still_reported(&id))
.projection(doc! { "_id": 0, "severity": 1, "cvss_score": 1, "vex.status": 1 })
.await
.map_err(|e| {
tracing::warn!("CVE matrix not read: {e}");
StatusCode::INTERNAL_SERVER_ERROR
})?;
let rows: Vec<MatrixRow> = collect_cursor_async(cursor).await;
let matrix = CveMatrix::from_cells(rows.iter().map(MatrixRow::cell));
Ok(Json(ApiResponse {
total: Some(matrix.total()),
data: matrix,
page: None,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use compliance_core::cve_matrix::{CveSeverity, VexColumn};
#[test]
fn only_alerts_still_reported_are_read() {
let filter = still_reported("t1");
assert_eq!(filter.get_str("repo_id").ok(), Some("t1"));
assert_eq!(filter.get("resolved_at"), Some(&mongodb::bson::Bson::Null));
}
#[test]
fn a_projected_row_is_bucketed_like_the_alert() {
let row: MatrixRow = mongodb::bson::from_document(doc! {
"severity": "MODERATE",
"vex": { "status": "not_affected" },
})
.expect("a projected alert");
let cell = row.cell();
assert_eq!(cell.severity, CveSeverity::Medium);
assert_eq!(cell.vex, VexColumn::NotAffected);
let bare: MatrixRow = mongodb::bson::from_document(doc! { "severity": null })
.expect("an alert without severity or statement");
assert_eq!(bare.cell(), CveCell::of(None, None, None));
}
}
+176
View File
@@ -69,6 +69,10 @@ pub struct FindingsFilter {
/// groups listing a place in it.
#[serde(default)]
pub variant: Option<String>,
/// Only the findings in one folder, as the folder chart names it
/// ([`path_regex`]).
#[serde(default)]
pub path: Option<String>,
#[serde(default)]
pub sort_by: Option<String>,
#[serde(default)]
@@ -88,6 +92,65 @@ impl FindingsFilter {
}
}
/// Open or closed, as the tickets list filters them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TicketState {
/// Open or in progress.
Open,
/// Closed or resolved.
Closed,
}
impl TicketState {
/// The stored statuses (`in_progress`) this state stands for.
pub fn statuses(self) -> Vec<String> {
let closed = self == Self::Closed;
compliance_core::models::IssueStatus::ALL
.iter()
.filter(|s| s.is_closed() == closed)
.map(ToString::to_string)
.collect()
}
}
/// The query of the tickets list (`GET /api/v1/issues`).
#[derive(Deserialize)]
pub struct IssuesFilter {
/// A word of the title or the ticket number (`913`, `#913`, `PROJ-913`).
#[serde(default)]
pub q: Option<String>,
/// Only open or only closed tickets; an unknown value is refused (400).
#[serde(default)]
pub status: Option<TicketState>,
/// Only the tickets of one target: of its findings and its CVEs.
#[serde(default)]
pub repo_id: Option<String>,
#[serde(default = "default_page", deserialize_with = "de_page")]
pub page: u64,
#[serde(default = "default_limit", deserialize_with = "de_limit")]
pub limit: i64,
}
impl IssuesFilter {
/// Documents to skip for this page. Bounded by construction.
pub fn skip(&self) -> u64 {
self.page
.saturating_sub(1)
.saturating_mul(self.limit as u64)
}
/// The search term, trimmed; `None` when there is none.
pub fn search(&self) -> Option<&str> {
self.q.as_deref().map(str::trim).filter(|q| !q.is_empty())
}
/// The target to filter by; `None` for all.
pub fn target(&self) -> Option<&str> {
self.repo_id.as_deref().filter(|id| !id.is_empty())
}
}
/// Fields a caller may sort findings by.
///
/// `sort_by` went into the sort document verbatim, so a caller could sort on
@@ -136,6 +199,35 @@ pub fn literal_regex(term: &str) -> String {
out
}
/// The `file_path` regex of a folder filter, anchored and literal; `None`
/// for an empty filter.
///
/// The keys are those of the folder chart
/// ([`compliance_core::finding_breakdown::FolderBreakdown::path`]):
/// `/` is the files in the root, `src/*` the files directly in `src`, and
/// `src/` (or `src`) everything below `src`. A leading `/` on a stored path
/// is allowed, as the chart ignores it too.
pub fn path_regex(folder: &str) -> Option<String> {
use compliance_core::finding_breakdown::{DIRECT_SUFFIX, ROOT_FOLDER};
let folder = folder.trim();
if folder.is_empty() {
return None;
}
if folder == ROOT_FOLDER {
return Some("^/?[^/]+$".to_string());
}
let (dir, direct) = match folder.strip_suffix(DIRECT_SUFFIX) {
Some(dir) => (dir, true),
None => (folder, false),
};
let dir = literal_regex(dir.trim_matches('/'));
Some(if direct {
format!("^/?{dir}/[^/]+$")
} else {
format!("^/?{dir}/")
})
}
#[derive(Serialize)]
pub struct ApiResponse<T: Serialize> {
pub data: T,
@@ -412,6 +504,41 @@ mod tests {
assert_eq!(literal_regex(&long).len(), MAX_SEARCH_LEN);
}
#[test]
fn folder_filters_are_anchored_literal_regexes() {
let matches = |folder: &str, path: &str| {
let re = regex::Regex::new(&path_regex(folder).expect("a filter")).expect("valid");
re.is_match(path)
};
assert_eq!(path_regex(""), None);
assert_eq!(path_regex(" "), None);
// Everything below a folder, with or without the trailing slash.
assert!(matches("src/", "src/api/a.rs"));
assert!(matches("src", "src/a.rs"));
assert!(!matches("src/", "srcfoo/a.rs"));
assert!(!matches("src/", "lib/src/a.rs"));
assert!(matches("src/api/", "/src/api/a.rs"));
// Only the files directly in a folder.
assert!(matches("src/*", "src/main.rs"));
assert!(!matches("src/*", "src/api/a.rs"));
// The root.
assert!(matches("/", "README.md"));
assert!(matches("/", "/Cargo.toml"));
assert!(!matches("/", "src/main.rs"));
// Metacharacters in a folder name are literal.
assert_eq!(path_regex("a.b/").as_deref(), Some(r"^/?a\.b/"));
assert!(!matches("a.b/", "axb/c.rs"));
assert!(matches("(x)/", "(x)/y.rs"));
}
#[test]
fn the_findings_filter_takes_a_folder() {
let f: FindingsFilter = serde_json::from_str(r#"{"path":"src/*"}"#).unwrap();
assert_eq!(f.path.as_deref(), Some("src/*"));
let f: FindingsFilter = serde_json::from_str("{}").unwrap();
assert_eq!(f.path, None);
}
#[test]
fn sbom_filter_clamps_the_same_way() {
let f: SbomFilter = serde_json::from_str(r#"{"limit":10000000,"page":0}"#).unwrap();
@@ -478,6 +605,55 @@ mod tests {
assert_eq!(f.severity.as_deref(), Some(""));
}
// ── IssuesFilter ─────────────────────────────────────────────
#[test]
fn issues_filter_defaults_and_clamps() {
let f: IssuesFilter = serde_json::from_str("{}").unwrap();
assert_eq!(f.search(), None);
assert_eq!(f.status, None);
assert_eq!(f.target(), None);
assert_eq!((f.page, f.limit), (1, 50));
let f: IssuesFilter = serde_json::from_str(r#"{"limit":5000,"page":0}"#).unwrap();
assert_eq!(f.limit, MAX_PAGE_SIZE);
assert_eq!(f.skip(), 0);
}
#[test]
fn issues_filter_ignores_blank_search_and_target() {
let f: IssuesFilter = serde_json::from_str(r#"{"q":" ","repo_id":""}"#).unwrap();
assert_eq!(f.search(), None);
assert_eq!(f.target(), None);
let f: IssuesFilter = serde_json::from_str(r##"{"q":" #913 ","repo_id":"t1"}"##).unwrap();
assert_eq!(f.search(), Some("#913"));
assert_eq!(f.target(), Some("t1"));
}
#[test]
fn issues_filter_status_is_open_or_closed_only() {
let f: IssuesFilter = serde_json::from_str(r#"{"status":"closed"}"#).unwrap();
assert_eq!(f.status, Some(TicketState::Closed));
assert!(serde_json::from_str::<IssuesFilter>(r#"{"status":"$ne"}"#).is_err());
}
#[test]
fn ticket_states_cover_every_stored_status_once() {
assert_eq!(TicketState::Open.statuses(), ["open", "in_progress"]);
assert_eq!(TicketState::Closed.statuses(), ["closed", "resolved"]);
// The names are the stored ones.
for name in TicketState::Open
.statuses()
.into_iter()
.chain(TicketState::Closed.statuses())
{
let status: compliance_core::models::IssueStatus =
serde_json::from_value(json!(name)).unwrap();
assert_eq!(status.to_string(), name);
}
}
// ── ApiResponse ──────────────────────────────────────────────
#[test]
@@ -79,9 +79,14 @@ async fn load_inputs(
.map_err(load_err)?,
)
.await,
// A run still waiting for a slot has examined nothing yet (t84).
last_run: db
.scan_runs()
.find_one(by_target)
.find_one({
let mut started = by_target;
started.insert("status", doc! { "$ne": "queued" });
started
})
.sort(doc! { "started_at": -1 })
.await
.map_err(load_err)?,
@@ -0,0 +1,70 @@
//! `GET /api/v1/targets/{id}/finding-breakdown`: a target's open findings
//! by type and severity, and by folder, for the charts of its findings view
//! (#957).
use axum::extract::{Extension, Path};
use mongodb::bson::doc;
use compliance_core::finding_breakdown::{
breakdown, BreakdownRow, FindingBreakdown, OPEN_STATUSES,
};
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResult};
/// The Mongo filter of a target's open (undecided) findings.
fn open_findings_of(target_id: &str) -> mongodb::bson::Document {
let open: Vec<String> = OPEN_STATUSES.iter().map(ToString::to_string).collect();
doc! { "repo_id": target_id, "status": { "$in": open } }
}
/// The open findings of target `id`, counted by type and severity and by
/// folder. Tenant-scoped like the findings list, and read-only, so every
/// role that may read findings may read it. A target without open findings
/// (or of another tenant, whose findings are not in this tenant's database)
/// gets an empty breakdown.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn finding_breakdown(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
) -> ApiResult<FindingBreakdown> {
let db = tenant_db(&agent, &tenant).await?;
// Only the three fields the counts need cross the wire.
let rows: Vec<BreakdownRow> = match db
.findings()
.clone_with_type::<BreakdownRow>()
.find(open_findings_of(&id))
.projection(doc! { "_id": 0, "scan_type": 1, "severity": 1, "file_path": 1 })
.await
{
// A document that does not read is skipped (and logged), not fatal.
Ok(cursor) => collect_cursor_async(cursor).await,
Err(e) => {
tracing::warn!("open findings for the breakdown not read: {e}");
Vec::new()
}
};
let result = breakdown(&rows);
Ok(axum::Json(ApiResponse {
total: Some(result.total),
data: result,
page: None,
}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_targets_undecided_findings_are_counted() {
assert_eq!(
open_findings_of("t1"),
doc! {
"repo_id": "t1",
"status": { "$in": ["open", "triaged", "needs_review"] },
}
);
}
}
@@ -0,0 +1,278 @@
//! Open findings grouped by rule and file, and one decision for a whole
//! group (#951).
//!
//! The grouping is [`compliance_core::models::finding_group`], a pure
//! function over the findings; nothing about groups is stored. A group
//! decision is a status change of every member through the same path as a
//! bulk change ([`super::findings::apply_status`]), so the status history,
//! the issue sync, the evidence pack and VEX see ordinary per-finding
//! changes.
use axum::extract::{Extension, Query};
use axum::http::StatusCode;
use axum::Json;
use mongodb::bson::{doc, Document};
use serde::Deserialize;
use super::dto::{collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResult};
use super::findings::{apply_status, status_update, Actor};
use super::health::OPEN_STATUSES;
use compliance_core::models::finding_group::{group_findings, members_of, FindingGroup, GroupKey};
use compliance_core::models::{Finding, FindingStatus};
use compliance_core::tenant_ctx::TenantCtx;
/// The query of [`list_finding_groups`].
#[derive(Debug, Deserialize)]
pub struct GroupsQuery {
/// Only one target's findings (`Finding::repo_id`).
#[serde(default)]
pub target: Option<String>,
}
/// The body of [`decide_finding_group`].
#[derive(Debug, Deserialize)]
pub struct DecideGroupRequest {
/// The group, as [`list_finding_groups`] named it.
pub key: GroupKey,
/// The decision for every member.
pub status: FindingStatus,
/// Why; required for an accepted risk or a wrong mapping.
#[serde(default)]
pub reason: Option<String>,
}
/// The fields a group never shows, left out of the read: the code, the fix
/// and the history are on each finding's own page.
fn light_projection() -> Document {
doc! {
"code_snippet": 0,
"suggested_fix": 0,
"remediation": 0,
"status_history": 0,
"legacy_fingerprints": 0,
}
}
/// The undecided findings `filter` narrows down to.
async fn undecided_findings(
db: &crate::database::Database,
mut filter: Document,
) -> Result<Vec<Finding>, StatusCode> {
filter.insert("status", doc! { "$in": OPEN_STATUSES.to_vec() });
let cursor = db
.findings()
.find(filter)
.projection(light_projection())
.await
.map_err(|e| {
tracing::warn!("Failed to fetch findings to group: {e}");
StatusCode::INTERNAL_SERVER_ERROR
})?;
Ok(collect_cursor_async(cursor).await)
}
/// GET /api/v1/finding-groups[?target=] — the undecided findings, grouped
/// by rule and file (see [`compliance_core::models::finding_group`]), most
/// severe first.
#[tracing::instrument(skip_all, fields(target = ?query.target))]
pub async fn list_finding_groups(
Extension(agent): AgentExt,
tenant: TenantCtx,
Query(query): Query<GroupsQuery>,
) -> ApiResult<Vec<FindingGroup>> {
let db = tenant_db(&agent, &tenant).await?;
let filter = query
.target
.filter(|t| !t.is_empty())
.map_or_else(Document::new, |target| doc! { "repo_id": target });
let groups = group_findings(undecided_findings(&db, filter).await?);
Ok(Json(ApiResponse {
total: Some(groups.len() as u64),
data: groups,
page: None,
}))
}
/// Whether a person may give a whole group `status`: a decision, not a
/// return to an undecided state (the members are undecided already, and
/// "needs review" is the AI's to set).
fn is_group_decision(status: &FindingStatus) -> bool {
match status {
FindingStatus::FalsePositive
| FindingStatus::AcceptedRisk
| FindingStatus::WrongMapping
| FindingStatus::Ignored
| FindingStatus::Resolved => true,
FindingStatus::Open | FindingStatus::Triaged | FindingStatus::NeedsReview => false,
}
}
/// The status change `req` asks of every member, by `actor`.
///
/// # Errors
///
/// 422 when the status is not a decision, or needs a reason and comes
/// without one.
fn decision_update(req: &DecideGroupRequest, actor: &Actor<'_>) -> Result<Document, StatusCode> {
if !is_group_decision(&req.status) {
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
status_update(&req.status, req.reason.as_deref(), actor)
}
/// The findings that may belong to the group `key`: its rule in its target.
/// The grouping then picks the members from them.
fn candidates_filter(key: &GroupKey) -> Document {
doc! {
"repo_id": &key.repo_id,
"scanner": &key.scanner,
"$or": [
{ "rule_id": &key.rule },
// A finding without a rule id is grouped by its title.
{ "rule_id": { "$in": [null, ""] }, "title": &key.rule },
],
}
}
/// POST /api/v1/finding-groups/decide — give every undecided member of a
/// group the same status, as if each were changed on its own.
///
/// The members are found again from the key, so a member someone decided
/// in the meantime keeps that decision. 404 when the group has no undecided
/// member (any more), 422 as [`decision_update`].
#[tracing::instrument(skip_all, fields(rule = %req.key.rule, scope = ?req.key.scope))]
pub async fn decide_finding_group(
Extension(agent): AgentExt,
tenant: TenantCtx,
Json(req): Json<DecideGroupRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let update = decision_update(&req, &Actor::of(&tenant.0))?;
let db = tenant_db(&agent, &tenant).await?;
let candidates = undecided_findings(&db, candidates_filter(&req.key)).await?;
let oids = members_of(candidates, &req.key);
if oids.is_empty() {
return Err(StatusCode::NOT_FOUND);
}
let filter = doc! {
"_id": { "$in": oids.clone() },
"status": { "$in": OPEN_STATUSES.to_vec() },
};
let members = oids.len();
let modified_count = apply_status(&agent, db, filter, oids, update).await?;
Ok(Json(serde_json::json!({
"status": "updated",
"members": members,
"modified_count": modified_count,
})))
}
#[cfg(test)]
mod tests {
use super::*;
use compliance_core::models::finding_group::GroupScope;
fn key() -> GroupKey {
GroupKey {
repo_id: "repo-1".into(),
scanner: "gdpr-patterns".into(),
rule: "pii-logged".into(),
scope: GroupScope::File,
place: Some("src/patterns.rs".into()),
}
}
fn request(status: FindingStatus, reason: Option<&str>) -> DecideGroupRequest {
DecideGroupRequest {
key: key(),
status,
reason: reason.map(String::from),
}
}
fn user() -> Actor<'static> {
Actor {
id: "u-1",
name: None,
support: false,
}
}
#[test]
fn a_group_takes_only_decisions() {
for status in [
FindingStatus::Open,
FindingStatus::Triaged,
FindingStatus::NeedsReview,
] {
assert_eq!(
decision_update(&request(status.clone(), Some("why")), &user()).err(),
Some(StatusCode::UNPROCESSABLE_ENTITY),
"{status}"
);
}
for status in [
FindingStatus::FalsePositive,
FindingStatus::Ignored,
FindingStatus::Resolved,
] {
assert!(
decision_update(&request(status.clone(), None), &user()).is_ok(),
"{status}"
);
}
}
#[test]
fn an_accepted_risk_for_a_group_needs_a_reason() {
assert_eq!(
decision_update(&request(FindingStatus::AcceptedRisk, None), &user()).err(),
Some(StatusCode::UNPROCESSABLE_ENTITY)
);
assert_eq!(
decision_update(&request(FindingStatus::AcceptedRisk, Some(" ")), &user()).err(),
Some(StatusCode::UNPROCESSABLE_ENTITY)
);
let update = decision_update(
&request(FindingStatus::AcceptedRisk, Some("isolated network")),
&user(),
)
.unwrap_or_default();
let change = update
.get_document("$push")
.and_then(|p| p.get_document("status_history"))
.cloned()
.unwrap_or_default();
assert_eq!(change.get_str("reason").ok(), Some("isolated network"));
assert_eq!(change.get_str("by").ok(), Some("u-1"));
}
#[test]
fn a_request_reads_the_key_and_refuses_an_unknown_status() {
let wire = serde_json::json!({
"key": {
"repo_id": "repo-1",
"scanner": "gdpr-patterns",
"rule": "pii-logged",
"scope": "file",
"place": "src/patterns.rs",
},
"status": "false_positive",
});
let req = serde_json::from_value::<DecideGroupRequest>(wire.clone());
assert_eq!(req.ok().map(|r| r.key), Some(key()));
let mut bad = wire.clone();
bad["status"] = "wontfix".into();
assert!(serde_json::from_value::<DecideGroupRequest>(bad).is_err());
let mut bad_scope = wire;
bad_scope["key"]["scope"] = "everywhere".into();
assert!(serde_json::from_value::<DecideGroupRequest>(bad_scope).is_err());
}
#[test]
fn the_candidates_are_the_rule_in_the_target() {
let filter = candidates_filter(&key());
assert_eq!(filter.get_str("repo_id").ok(), Some("repo-1"));
assert_eq!(filter.get_str("scanner").ok(), Some("gdpr-patterns"));
assert_eq!(filter.get_array("$or").map(Vec::len).ok(), Some(2));
}
}
+61 -9
View File
@@ -29,7 +29,10 @@ pub async fn list_findings(
query.insert("scan_type", scan_type);
}
if let Some(status) = &filter.status {
query.insert("status", status);
query.insert("status", status_filter(status));
}
if let Some(regex) = filter.path.as_deref().and_then(path_regex) {
query.insert("file_path", doc! { "$regex": regex });
}
// Text search across title, description, file_path, rule_id
if let Some(q) = &filter.q {
@@ -109,6 +112,18 @@ pub async fn list_findings(
}))
}
/// The match of a `status` filter: one status, or all undecided ones for
/// [`compliance_core::finding_breakdown::OPEN_STATUS_FILTER`].
fn status_filter(status: &str) -> mongodb::bson::Bson {
use compliance_core::finding_breakdown::{OPEN_STATUSES, OPEN_STATUS_FILTER};
if status == OPEN_STATUS_FILTER {
let open: Vec<String> = OPEN_STATUSES.iter().map(ToString::to_string).collect();
mongodb::bson::Bson::Document(doc! { "$in": open })
} else {
mongodb::bson::Bson::String(status.to_string())
}
}
/// The temporary field the severity sort ranks on.
const SEVERITY_RANK: &str = "_severity_rank";
@@ -214,7 +229,7 @@ impl<'a> Actor<'a> {
}
}
fn status_update(
pub(crate) fn status_update(
status: &FindingStatus,
reason: Option<&str>,
actor: &Actor<'_>,
@@ -231,6 +246,7 @@ fn status_update(
at: chrono::Utc::now(),
reason: reason.map(String::from),
scan: None,
tracker: None,
};
let status = mongodb::bson::to_bson(status).map_err(|_| StatusCode::BAD_REQUEST)?;
let change = mongodb::bson::to_bson(&change).map_err(|_| StatusCode::BAD_REQUEST)?;
@@ -299,18 +315,42 @@ pub async fn bulk_update_finding_status(
let update = status_update(&req.status, req.reason.as_deref(), &Actor::of(&tenant.0))?;
let db = tenant_db(&agent, &tenant).await?;
let result = db
.findings()
.update_many(doc! { "_id": { "$in": oids.clone() } }, update)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
issue_sync(&agent, db).spawn(oids);
let filter = doc! { "_id": { "$in": oids.clone() } };
let modified_count = apply_status(&agent, db, filter, oids, update).await?;
Ok(Json(
serde_json::json!({ "status": "updated", "modified_count": result.modified_count }),
serde_json::json!({ "status": "updated", "modified_count": modified_count }),
))
}
/// Apply the status change `update` (from [`status_update`]) to the findings
/// `filter` matches, then carry the new status over to the issues of `oids`
/// (the findings the filter is about) in the background: the one path every
/// change of many findings takes, a bulk change or a group decision (#951).
///
/// # Returns
///
/// How many findings changed.
///
/// # Errors
///
/// 500 when the database refuses the update.
pub(crate) async fn apply_status(
agent: &crate::agent::ComplianceAgent,
db: crate::database::Database,
filter: mongodb::bson::Document,
oids: Vec<mongodb::bson::oid::ObjectId>,
update: mongodb::bson::Document,
) -> Result<u64, StatusCode> {
let result = db
.findings()
.update_many(filter, update)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
issue_sync(agent, db).spawn(oids);
Ok(result.modified_count)
}
/// PATCH /api/v1/findings/{id}/feedback — store the developer's feedback on a
/// finding. 404 when there is no such finding.
#[tracing::instrument(skip_all, fields(finding_id = %id))]
@@ -342,6 +382,18 @@ pub async fn update_finding_feedback(
mod tests {
use super::*;
#[test]
fn the_undecided_filter_matches_every_open_status() {
assert_eq!(
status_filter("undecided"),
mongodb::bson::Bson::Document(doc! { "$in": ["open", "triaged", "needs_review"] })
);
assert_eq!(
status_filter("resolved"),
mongodb::bson::Bson::String("resolved".into())
);
}
#[test]
fn an_accepted_risk_needs_a_reason() {
assert_eq!(
+114 -4
View File
@@ -6,7 +6,9 @@ use axum::Json;
use mongodb::bson::doc;
use serde::{Deserialize, Serialize};
use compliance_core::models::graph::{CodeEdge, CodeNode, GraphBuildRun, ImpactAnalysis};
use compliance_core::models::graph::{
CodeEdge, CodeNode, GraphBuildRun, GraphBuildStatus, ImpactAnalysis,
};
use compliance_core::tenant_ctx::TenantCtx;
use crate::agent::ComplianceAgent;
@@ -188,6 +190,60 @@ pub async fn get_nodes(
}))
}
/// What the target page shows of a code graph.
#[derive(Serialize)]
pub struct GraphSummary {
/// Declarations: functions, methods, types, PLC blocks (nodes that are
/// not files).
pub units: u32,
pub entry_points: u32,
/// Language codes, sorted (`c`, `csharp`, `structured_text`, …).
pub languages: Vec<String>,
/// Source files left out because they could not be read as text; 0 when
/// none were, or the build did not count them.
pub unreadable_files: u32,
}
impl GraphSummary {
/// The summary of a completed build; `None` for one still running, a
/// failed one, or one stored before its files and entry points were
/// counted.
fn of(build: GraphBuildRun) -> Option<Self> {
if build.status != GraphBuildStatus::Completed {
return None;
}
Some(Self {
units: build.node_count.saturating_sub(build.file_count?),
entry_points: build.entry_point_count?,
languages: build.languages_parsed,
// Not `?`: a build from before this count still shows its card.
unreadable_files: build.unreadable_file_count.unwrap_or(0),
})
}
}
/// GET /api/v1/graph/:repo_id/summary — The latest build's counts, without
/// loading any node: `data` is `null` when there is none to show.
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
pub async fn get_summary(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(repo_id): Path<String>,
) -> Result<Json<ApiResponse<Option<GraphSummary>>>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let build = db
.graph_builds()
.find_one(doc! { "repo_id": &repo_id })
.sort(doc! { "started_at": -1 })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(ApiResponse {
data: build.and_then(GraphSummary::of),
total: None,
page: None,
}))
}
/// GET /api/v1/graph/:repo_id/communities — List detected communities
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
pub async fn get_communities(
@@ -355,7 +411,9 @@ pub async fn get_file_content(
return Err(StatusCode::FORBIDDEN);
}
let content = std::fs::read_to_string(&canonical).map_err(|_| StatusCode::NOT_FOUND)?;
// Decoded as the graph read it, so a UTF-16 or Windows-1252 file opens.
let content =
compliance_core::encoding::read_source(&canonical).map_err(|_| StatusCode::NOT_FOUND)?;
// Cap at 10,000 lines
let truncated: String = content.lines().take(10_000).collect::<Vec<_>>().join("\n");
@@ -434,10 +492,17 @@ pub async fn trigger_build(
}
};
// A PLC target's graph is its POUs, as the scan builds it.
let plc_files = crate::pipeline::plan::build_scan_plan(&repo)
.has(compliance_core::models::ScanType::PlcControlLogic)
.then(|| crate::pipeline::plc::read_tree(&repo_path));
let source = match &plc_files {
Some(files) => crate::pipeline::graph_build::GraphSource::Plc(files),
None => crate::pipeline::graph_build::GraphSource::Tree(&repo_path),
};
let graph_build_id = uuid::Uuid::new_v4().to_string();
let engine = compliance_graph::GraphEngine::new(50_000);
match engine.build_graph(&repo_path, &repo_id, &graph_build_id) {
match crate::pipeline::graph_build::build_graph(source, &repo_id, &graph_build_id) {
Ok((code_graph, build_run)) => {
let store = compliance_graph::graph::persistence::GraphStore::new(db.inner());
let _ = store.delete_repo_graph(&repo_id).await;
@@ -460,3 +525,48 @@ pub async fn trigger_build(
serde_json::json!({ "status": "graph_build_triggered" }),
))
}
#[cfg(test)]
mod tests {
use super::*;
fn completed(nodes: u32, files: Option<u32>, entry_points: Option<u32>) -> GraphBuildRun {
let mut build = GraphBuildRun::new("t".to_string());
build.status = GraphBuildStatus::Completed;
build.node_count = nodes;
build.file_count = files;
build.entry_point_count = entry_points;
build.languages_parsed = vec!["c".to_string()];
build
}
#[test]
fn a_completed_build_counts_its_declarations() {
let summary = GraphSummary::of(completed(120, Some(20), Some(7))).expect("shown");
assert_eq!((summary.units, summary.entry_points), (100, 7));
assert_eq!(summary.languages, ["c"]);
}
#[test]
fn running_failed_and_uncounted_builds_show_nothing() {
let mut running = completed(10, Some(2), Some(1));
running.status = GraphBuildStatus::Running;
assert!(GraphSummary::of(running).is_none());
let mut failed = completed(10, Some(2), Some(1));
failed.status = GraphBuildStatus::Failed;
assert!(GraphSummary::of(failed).is_none());
assert!(GraphSummary::of(completed(10, None, None)).is_none());
}
#[test]
fn unreadable_files_are_shown_and_an_uncounted_build_has_none() {
let mut build = completed(10, Some(2), Some(1));
build.unreadable_file_count = Some(3);
assert_eq!(GraphSummary::of(build).expect("shown").unreadable_files, 3);
let uncounted = completed(10, Some(2), Some(1));
assert_eq!(
GraphSummary::of(uncounted).expect("shown").unreadable_files,
0
);
}
}
+9 -4
View File
@@ -57,14 +57,19 @@ fn health_answer(mongo_reachable: bool) -> (axum::http::StatusCode, Json<serde_j
/// positive, not an accepted risk and not ignored.
pub(crate) const OPEN_STATUSES: [&str; 3] = ["open", "triaged", "needs_review"];
/// How many open findings there are of each severity, by severity name.
async fn open_findings_by_severity(
/// How many open findings there are of each severity, by severity name;
/// only those matching `scope` (e.g. `{"repo_id": …}`), every one with an
/// empty document.
pub(crate) async fn open_findings_by_severity(
db: &crate::database::Database,
scope: mongodb::bson::Document,
) -> std::collections::HashMap<String, u64> {
use futures_util::TryStreamExt;
let mut matching = scope;
matching.insert("status", doc! { "$in": OPEN_STATUSES.to_vec() });
let pipeline = vec![
doc! { "$match": { "status": { "$in": OPEN_STATUSES.to_vec() } } },
doc! { "$match": matching },
doc! { "$group": { "_id": "$severity", "n": { "$sum": 1 } } },
];
let rows: Vec<mongodb::bson::Document> = match db.findings().aggregate(pipeline).await {
@@ -116,7 +121,7 @@ pub async fn stats_overview(
.await
.unwrap_or(0)
},
open_findings_by_severity(db),
open_findings_by_severity(db, doc! {}),
);
let severity = |name: &str| by_severity.get(name).copied().unwrap_or(0);
let total_findings = by_severity.values().sum();
+554
View File
@@ -0,0 +1,554 @@
//! The "Heute" inbox (#950): the workspace's open decisions as cards in four
//! urgency buckets, decisions on a whole card, undo, and putting a card off
//! until a date ("Wiedervorlage").
//!
//! The bucket rules and the cards are [`compliance_core::models::inbox`]'s;
//! this module loads what they are made of and applies decisions through
//! the existing endpoints' code: a finding's status as
//! `PATCH /api/v1/findings/bulk-status` sets it, a CVE alert's VEX statement
//! as `PATCH /api/v1/cves/{id}/vex` does. Writes are role-gated by the org
//! role middleware like every other write.
use std::collections::{BTreeMap, HashMap};
use axum::extract::{Extension, Path, Query};
use axum::http::StatusCode;
use axum::Json;
use chrono::{DateTime, Utc};
use futures_util::StreamExt;
use mongodb::bson::{doc, oid::ObjectId, Bson, Document};
use serde::Deserialize;
use compliance_core::models::inbox::{
alert_undecided, apply_snoozes, cve_cards, finding_cards, view, Bucket, BucketRules, CardKey,
DecideRequest, DecideResponse, InboxAction, InboxCard, InboxFinding, InboxSnooze, InboxView,
OneCardPerFinding, PreviousState, Progress, Reason, SnoozeRequest, SnoozeResponse, UndoRequest,
ViewRequest, DECIDED_STATUSES, DECIDING_VEX, UNDECIDED_STATUSES,
};
use compliance_core::models::{CveAlert, FindingStatus, VexStatus};
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{
collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResult, BulkUpdateStatusRequest,
};
use super::findings::{bulk_update_finding_status, Actor};
use super::vex::{set_cve_vex, VexRequest};
use crate::database::Database;
/// Cards listed when the request names no limit.
const DEFAULT_LIMIT: usize = 100;
/// The most cards one request lists; the counts always cover all.
const MAX_LIMIT: usize = 500;
/// A refusal with its reason, the shape `PATCH /api/v1/cves/{id}/vex` answers
/// with, so the dashboard shows why.
type Refusal = (StatusCode, Json<serde_json::Value>);
fn refuse(code: StatusCode, error: &str) -> Refusal {
(code, Json(serde_json::json!({ "error": error })))
}
/// A database error as a refusal, logged.
fn store_error(e: mongodb::error::Error) -> Refusal {
tracing::warn!("inbox: database error: {e}");
refuse(StatusCode::INTERNAL_SERVER_ERROR, "store")
}
/// The query of [`get_inbox`].
#[derive(Debug, Deserialize)]
pub struct InboxQuery {
/// Only this target's cards, counts and Erstbewertung.
#[serde(default)]
pub target: Option<String>,
/// The bucket whose cards to list (default `today`).
#[serde(default)]
pub bucket: Option<Bucket>,
/// The most cards to list (default 100, at most 500).
#[serde(default)]
pub limit: Option<usize>,
}
/// The bucket rules as configured: the CVE issues' EPSS threshold
/// (`CVE_ISSUE_EPSS_PERCENTILE`, default 0.95), at `now`.
fn rules(now: DateTime<Utc>) -> BucketRules {
BucketRules {
epss_percentile: crate::pipeline::cve_issues::epss_percentile(
std::env::var("CVE_ISSUE_EPSS_PERCENTILE").ok().as_deref(),
),
now,
}
}
/// `values` as a BSON array for an `$in`.
fn bson_list<T: serde::Serialize>(values: &[T]) -> Bson {
mongodb::bson::to_bson(values).unwrap_or_else(|_| Bson::Array(Vec::new()))
}
/// The findings waiting for a decision ([`UNDECIDED_STATUSES`]) matching
/// `filter`, with only the fields the inbox reads.
async fn open_findings(
db: &Database,
mut filter: Document,
) -> Result<Vec<InboxFinding>, mongodb::error::Error> {
filter.insert("status", doc! { "$in": bson_list(&UNDECIDED_STATUSES) });
let projection: Document = InboxFinding::FIELDS
.iter()
.map(|field| ((*field).to_string(), Bson::Int32(1)))
.collect();
let cursor = db
.findings()
.clone_with_type::<InboxFinding>()
.find(filter)
.projection(projection)
.await?;
Ok(collect_cursor_async(cursor).await)
}
/// The CVE alerts waiting for a decision ([`alert_undecided`]) matching
/// `filter`.
async fn open_alerts(
db: &Database,
mut filter: Document,
) -> Result<Vec<CveAlert>, mongodb::error::Error> {
filter.insert("resolved_at", Bson::Null);
filter.insert(
"$or",
vec![
doc! { "vex": Bson::Null },
doc! { "vex.status": VexStatus::UnderInvestigation.as_str() },
],
);
let cursor = db.cve_alerts().find(filter).await?;
let alerts: Vec<CveAlert> = collect_cursor_async(cursor).await;
Ok(alerts.into_iter().filter(alert_undecided).collect())
}
/// The snooze of each card key.
async fn snoozes(db: &Database) -> Result<HashMap<String, InboxSnooze>, mongodb::error::Error> {
let cursor = db.inbox_snoozes().find(doc! {}).await?;
let snoozes: Vec<InboxSnooze> = collect_cursor_async(cursor).await;
Ok(snoozes.into_iter().map(|s| (s.key.clone(), s)).collect())
}
/// The targets' names by id.
async fn target_names(db: &Database) -> Result<HashMap<String, String>, mongodb::error::Error> {
let mut cursor = db
.onboarded_targets()
.clone_with_type::<Document>()
.find(doc! {})
.projection(doc! { "name": 1 })
.await?;
let mut names = HashMap::new();
while let Some(target) = cursor.next().await {
let target = target?;
if let (Ok(id), Ok(name)) = (target.get_object_id("_id"), target.get_str("name")) {
names.insert(id.to_hex(), name.to_string());
}
}
Ok(names)
}
/// The Erstbewertung of `scope` (the workspace, or one target): the open
/// items already loaded, plus the decided ones counted in the database. See
/// [`Progress`] for what counts as decided.
async fn progress(
db: &Database,
target: Option<&str>,
findings: &[InboxFinding],
alerts: &[CveAlert],
) -> Result<Progress, mongodb::error::Error> {
let in_scope = |repo_id: &str| target.is_none_or(|t| t == repo_id);
let scope = || target.map_or_else(Document::new, |t| doc! { "repo_id": t });
let mut decided_findings = scope();
decided_findings.insert("status", doc! { "$in": bson_list(&DECIDED_STATUSES) });
let mut decided_alerts = scope();
decided_alerts.insert("resolved_at", Bson::Null);
decided_alerts.insert("vex.status", doc! { "$in": bson_list(&DECIDING_VEX) });
let decided = db.findings().count_documents(decided_findings).await?
+ db.cve_alerts().count_documents(decided_alerts).await?;
let open = findings.iter().filter(|f| in_scope(&f.repo_id)).count()
+ alerts.iter().filter(|a| in_scope(&a.repo_id)).count();
Ok(Progress {
decided,
total: decided + open as u64,
})
}
/// GET /api/v1/inbox[?target=<id>&bucket=<bucket>&limit=<n>] — the bucket
/// counts, the Erstbewertung, the targets with cards, and the cards of one
/// bucket (default `today`), most urgent first.
///
/// Cards: one per finding, one per target, package and version for CVE
/// alerts. Cards put off until a date are left out until then and come back
/// under `later`.
#[tracing::instrument(skip_all, fields(target = ?query.target, bucket = ?query.bucket))]
pub async fn get_inbox(
Extension(agent): AgentExt,
tenant: TenantCtx,
Query(query): Query<InboxQuery>,
) -> ApiResult<InboxView> {
let db = tenant_db(&agent, &tenant).await?;
let failed = |e: mongodb::error::Error| {
tracing::warn!("inbox: failed to load: {e}");
StatusCode::INTERNAL_SERVER_ERROR
};
let now = Utc::now();
let findings = open_findings(&db, Document::new()).await.map_err(failed)?;
let alerts = open_alerts(&db, Document::new()).await.map_err(failed)?;
let snoozes = snoozes(&db).await.map_err(failed)?;
let names = target_names(&db).await.map_err(failed)?;
let target = query.target.as_deref().filter(|t| !t.is_empty());
let progress = progress(&db, target, &findings, &alerts)
.await
.map_err(failed)?;
let mut cards = finding_cards(&findings, &OneCardPerFinding);
cards.extend(cve_cards(&alerts, &rules(now)));
let request = ViewRequest {
target,
bucket: query.bucket.unwrap_or_default(),
limit: query.limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT),
};
let view = view(
apply_snoozes(cards, &snoozes, now),
&names,
progress,
request,
);
Ok(Json(ApiResponse {
data: view,
total: None,
page: None,
}))
}
/// The card `key` names as it stands now, with what each item is, or why
/// there is none: 400 for a malformed key, 409 when nothing on it waits for
/// a decision any more.
async fn resolve_card(
db: &Database,
key: &str,
) -> Result<(InboxCard, Vec<PreviousState>), Refusal> {
let gone = || {
refuse(
StatusCode::CONFLICT,
"nothing on this card waits for a decision",
)
};
match CardKey::parse(key).ok_or_else(|| refuse(StatusCode::BAD_REQUEST, "bad key"))? {
CardKey::Finding { id } => {
let oid =
ObjectId::parse_str(&id).map_err(|_| refuse(StatusCode::BAD_REQUEST, "bad key"))?;
let findings = open_findings(db, doc! { "_id": oid })
.await
.map_err(store_error)?;
let card = finding_cards(&findings, &OneCardPerFinding)
.into_iter()
.find(|c| c.key == key)
.ok_or_else(gone)?;
let previous = findings
.into_iter()
.map(|f| PreviousState::Finding {
id: f.id.to_hex(),
status: f.status,
})
.collect();
Ok((card, previous))
}
CardKey::CvePackage { target_id } => {
let alerts = open_alerts(db, doc! { "repo_id": &target_id })
.await
.map_err(store_error)?;
let card = cve_cards(&alerts, &rules(Utc::now()))
.into_iter()
.find(|c| c.key == key)
.ok_or_else(gone)?;
let previous = alerts
.into_iter()
.filter_map(|a| {
let id = a.id?.to_hex();
card.item_ids.contains(&id).then(|| PreviousState::Cve {
id,
vex: a.vex.map(|v| v.status),
})
})
.collect();
Ok((card, previous))
}
}
}
/// Set `status` on the findings `ids` the way
/// `PATCH /api/v1/findings/bulk-status` does: recorded in their history with
/// who and why, and their tracker issues closed or reopened.
async fn set_finding_status(
agent: &AgentExt,
tenant: &TenantCtx,
ids: Vec<String>,
status: FindingStatus,
reason: Option<String>,
) -> Result<(), Refusal> {
let request = BulkUpdateStatusRequest {
ids,
status,
reason,
};
bulk_update_finding_status(agent.clone(), tenant.clone(), Json(request))
.await
.map(|_| ())
.map_err(|code| match code {
StatusCode::UNPROCESSABLE_ENTITY => refuse(code, "a reason is required"),
other => refuse(other, "status"),
})
}
/// State `request()` on the alerts `ids` the way `PATCH /api/v1/cves/{id}/vex`
/// does; the first refusal (a missing justification) stops before anything
/// is stored, as every alert gets the same statement.
async fn set_vex(
agent: &AgentExt,
tenant: &TenantCtx,
ids: &[String],
request: impl Fn() -> VexRequest,
) -> Result<(), Refusal> {
for id in ids {
// The answer (the stored statement) is not needed here.
let _stored = set_cve_vex(
agent.clone(),
tenant.clone(),
Path(id.clone()),
Json(request()),
)
.await?;
}
Ok(())
}
/// POST /api/v1/inbox/decide `{key, action, reason?, justification?,
/// statement?}` — apply `action` to every item of card `key`, through the
/// findings' and the VEX endpoints' code, and answer what each item was
/// before (for `POST /api/v1/inbox/undo`). The card's resubmission, if any,
/// is dropped. 409 when nothing on the card waits any more, 422 for an action
/// the card does not offer or without the reason, justification or statement
/// it needs.
#[tracing::instrument(skip_all, fields(key = %req.key, action = ?req.action))]
pub async fn decide(
agent: AgentExt,
tenant: TenantCtx,
Json(req): Json<DecideRequest>,
) -> Result<Json<DecideResponse>, Refusal> {
let db = tenant_db(&agent, &tenant)
.await
.map_err(|code| refuse(code, "tenant"))?;
let (card, previous) = resolve_card(&db, &req.key).await?;
if !card.actions.contains(&req.action) {
return Err(refuse(
StatusCode::UNPROCESSABLE_ENTITY,
"the card does not offer this action",
));
}
let text = |s: &Option<String>| {
s.as_deref()
.map(str::trim)
.filter(|t| !t.is_empty())
.map(String::from)
};
let vex = |status, justification, impact_statement, action_statement| {
move || VexRequest {
status,
justification,
impact_statement: Option::clone(&impact_statement),
action_statement: Option::clone(&action_statement),
}
};
let ids = card.item_ids;
match req.action {
InboxAction::FalsePositive => {
set_finding_status(&agent, &tenant, ids, FindingStatus::FalsePositive, None).await?;
}
InboxAction::AcceptedRisk => {
let reason = text(&req.reason);
set_finding_status(&agent, &tenant, ids, FindingStatus::AcceptedRisk, reason).await?;
}
InboxAction::Confirm => {
set_finding_status(&agent, &tenant, ids, FindingStatus::Triaged, None).await?;
}
InboxAction::NotAffected => {
let statement = vex(
VexStatus::NotAffected,
req.justification,
text(&req.statement),
None,
);
set_vex(&agent, &tenant, &ids, statement).await?;
}
InboxAction::Affected => {
let statement = vex(VexStatus::Affected, None, None, text(&req.statement));
set_vex(&agent, &tenant, &ids, statement).await?;
}
}
db.inbox_snoozes()
.delete_one(doc! { "key": &req.key })
.await
.map_err(store_error)?;
Ok(Json(DecideResponse {
key: req.key,
action: req.action,
previous,
}))
}
/// Whether the items of `previous` are those of card `key`: the finding the
/// key names, or alerts of the key's package version.
async fn belongs_to(db: &Database, key: &str, previous: &[PreviousState]) -> Result<bool, Refusal> {
match CardKey::parse(key).ok_or_else(|| refuse(StatusCode::BAD_REQUEST, "bad key"))? {
CardKey::Finding { id } => Ok(previous
.iter()
.all(|p| matches!(p, PreviousState::Finding { id: item, .. } if *item == id))),
CardKey::CvePackage { .. } => {
let mut oids = Vec::with_capacity(previous.len());
for state in previous {
let PreviousState::Cve { id, .. } = state else {
return Ok(false);
};
oids.push(
ObjectId::parse_str(id)
.map_err(|_| refuse(StatusCode::BAD_REQUEST, "bad id"))?,
);
}
let cursor = db
.cve_alerts()
.find(doc! { "_id": { "$in": &oids } })
.await
.map_err(store_error)?;
let alerts: Vec<CveAlert> = collect_cursor_async(cursor).await;
Ok(alerts.len() == oids.len()
&& alerts.iter().all(|a| {
CardKey::cve_package(&a.repo_id, &a.affected_package, &a.affected_version)
== key
}))
}
}
}
/// POST /api/v1/inbox/undo `{key, previous}` — put the items of a decision
/// on card `key` back, through the same code the decision went through: a
/// finding gets its previous status (a new entry in its history, which keeps
/// the decision on record), an alert `under_investigation` (also when it had
/// no statement before; both leave it open). 422 when an item does not
/// belong to the card or its previous state was not an open one.
#[tracing::instrument(skip_all, fields(key = %req.key))]
pub async fn undo(
agent: AgentExt,
tenant: TenantCtx,
Json(req): Json<UndoRequest>,
) -> Result<Json<serde_json::Value>, Refusal> {
let db = tenant_db(&agent, &tenant)
.await
.map_err(|code| refuse(code, "tenant"))?;
if req.previous.is_empty() || !belongs_to(&db, &req.key, &req.previous).await? {
return Err(refuse(
StatusCode::UNPROCESSABLE_ENTITY,
"the items do not belong to the card",
));
}
let mut by_status: BTreeMap<FindingStatus, Vec<String>> = BTreeMap::new();
let mut alerts = Vec::new();
for state in req.previous {
match state {
PreviousState::Finding { id, status } if UNDECIDED_STATUSES.contains(&status) => {
by_status.entry(status).or_default().push(id);
}
PreviousState::Cve {
id,
vex: None | Some(VexStatus::UnderInvestigation),
} => {
alerts.push(id);
}
PreviousState::Finding { .. } | PreviousState::Cve { .. } => {
return Err(refuse(
StatusCode::UNPROCESSABLE_ENTITY,
"only an open state can be restored",
));
}
}
}
for (status, ids) in by_status {
set_finding_status(&agent, &tenant, ids, status, None).await?;
}
set_vex(&agent, &tenant, &alerts, || VexRequest {
status: VexStatus::UnderInvestigation,
justification: None,
impact_statement: None,
action_statement: None,
})
.await?;
Ok(Json(serde_json::json!({ "status": "restored" })))
}
/// POST /api/v1/inbox/snooze `{key, for}` — put card `key` off: one week, one
/// month, or until a date (`{"kind": "date", "date": "2026-12-01"}`). It is
/// hidden until then and comes back in its own bucket, or earlier when a new
/// CVE or a KEV entry joins it: the snooze records the card's items and
/// whether it was KEV. A second snooze replaces the first. 400 for a
/// malformed key, 409 when nothing on the card waits for a decision, 422 for
/// a date that is not in the future.
#[tracing::instrument(skip_all, fields(key = %req.key))]
pub async fn snooze(
Extension(agent): AgentExt,
tenant: TenantCtx,
Json(req): Json<SnoozeRequest>,
) -> Result<Json<SnoozeResponse>, Refusal> {
if CardKey::parse(&req.key).is_none() {
return Err(refuse(StatusCode::BAD_REQUEST, "bad key"));
}
let now = Utc::now();
let until = req
.snooze_for
.until(now)
.map_err(|e| refuse(StatusCode::UNPROCESSABLE_ENTITY, &e.to_string()))?;
let db = tenant_db(&agent, &tenant)
.await
.map_err(|code| refuse(code, "tenant"))?;
let (card, _) = resolve_card(&db, &req.key).await?;
let actor = Actor::of(&tenant.0);
let record = InboxSnooze {
key: req.key.clone(),
until,
by: actor.id.to_string(),
by_name: actor.name,
at: now,
kev: card.reasons.contains(&Reason::Kev),
items: card.item_ids,
};
db.inbox_snoozes()
.replace_one(doc! { "key": &req.key }, &record)
.upsert(true)
.await
.map_err(store_error)?;
Ok(Json(SnoozeResponse {
key: req.key,
until,
}))
}
/// DELETE /api/v1/inbox/snooze/{key} — take card `key`'s resubmission back
/// (the undo of a snooze); nothing to take back is no error.
#[tracing::instrument(skip_all, fields(key = %key))]
pub async fn unsnooze(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(key): Path<String>,
) -> Result<Json<serde_json::Value>, Refusal> {
if CardKey::parse(&key).is_none() {
return Err(refuse(StatusCode::BAD_REQUEST, "bad key"));
}
let db = tenant_db(&agent, &tenant)
.await
.map_err(|code| refuse(code, "tenant"))?;
db.inbox_snoozes()
.delete_one(doc! { "key": &key })
.await
.map_err(store_error)?;
Ok(Json(serde_json::json!({ "status": "deleted" })))
}
+210 -8
View File
@@ -1,32 +1,42 @@
use axum::extract::{Extension, Query};
use axum::Json;
use mongodb::bson::doc;
use mongodb::bson::{doc, Bson, Document};
use super::dto::*;
use compliance_core::models::issue::cve_issue_prefix;
use compliance_core::models::TrackerIssue;
use compliance_core::tenant_ctx::TenantCtx;
#[tracing::instrument(skip_all)]
/// The tenant's tickets, newest first, searched and filtered by `filter`.
///
/// A ticket stores no target, only the finding it is about: the target filter
/// first looks up the ids of the target's findings that have a ticket.
#[tracing::instrument(skip_all, fields(repo_id = ?filter.repo_id, status = ?filter.status))]
pub async fn list_issues(
Extension(agent): AgentExt,
tenant: TenantCtx,
Query(params): Query<PaginationParams>,
Query(filter): Query<IssuesFilter>,
) -> ApiResult<Vec<TrackerIssue>> {
let db = tenant_db(&agent, &tenant).await?;
let db = &db;
let skip = params.skip();
let finding_ids = match filter.target() {
Some(repo_id) => Some(ticketed_finding_ids(db, repo_id).await),
None => None,
};
let query = issues_query(&filter, finding_ids.as_deref());
let skip = filter.skip();
let total = db
.tracker_issues()
.count_documents(doc! {})
.count_documents(query.clone())
.await
.unwrap_or(0);
let issues = match db
.tracker_issues()
.find(doc! {})
.find(query)
.sort(doc! { "created_at": -1 })
.skip(skip)
.limit(params.limit)
.limit(filter.limit)
.await
{
Ok(cursor) => collect_cursor_async(cursor).await,
@@ -39,6 +49,198 @@ pub async fn list_issues(
Ok(Json(ApiResponse {
data: issues,
total: Some(total),
page: Some(params.page),
page: Some(filter.page),
}))
}
/// The ids (hex) of the findings of target `repo_id` that have a ticket.
///
/// Storing a finding's ticket sets the finding's `tracker_issue_url`
/// (`pipeline::issue_creation`), so the other findings are left out. A failed
/// lookup is logged and leaves only the target's CVE tickets.
async fn ticketed_finding_ids(db: &crate::database::Database, repo_id: &str) -> Vec<String> {
let filter = doc! { "repo_id": repo_id, "tracker_issue_url": { "$ne": Bson::Null } };
match db.findings().distinct("_id", filter).await {
Ok(ids) => ids
.iter()
.filter_map(Bson::as_object_id)
.map(|id| id.to_hex())
.collect(),
Err(e) => {
tracing::warn!("Failed to look up the target's findings: {e}");
Vec::new()
}
}
}
/// The Mongo filter of the tickets list.
///
/// # Arguments
///
/// * `filter` - the caller's search and filters
/// * `finding_ids` - for a target filter, the ids of the target's findings
/// with a ticket ([`ticketed_finding_ids`]); `None` without one
///
/// # Returns
///
/// `{}` for no filter, else an `$and` of the search (title or ticket number),
/// the status and the target.
fn issues_query(filter: &IssuesFilter, finding_ids: Option<&[String]>) -> Document {
let mut clauses: Vec<Document> = Vec::with_capacity(3);
if let Some(term) = filter.search() {
let mut either = vec![doc! { "title": { "$regex": literal_regex(term), "$options": "i" } }];
// `#913` is ticket 913; `913` also finds the Jira key `PROJ-913`.
let number = term.strip_prefix('#').unwrap_or(term).trim();
if !number.is_empty() {
let exact = format!("(^|-){}$", literal_regex(number));
either.push(doc! { "external_id": { "$regex": exact, "$options": "i" } });
}
clauses.push(doc! { "$or": either });
}
if let Some(state) = filter.status {
clauses.push(doc! { "status": { "$in": state.statuses() } });
}
if let (Some(repo_id), Some(ids)) = (filter.target(), finding_ids) {
// A CVE ticket names its target in its key instead of a finding.
let cve = format!("^{}", literal_regex(&cve_issue_prefix(repo_id)));
clauses.push(doc! { "$or": [
{ "finding_id": { "$in": ids } },
{ "finding_id": { "$regex": cve } },
] });
}
if clauses.is_empty() {
Document::new()
} else {
doc! { "$and": clauses }
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
fn filter(json: &str) -> IssuesFilter {
serde_json::from_str(json).unwrap()
}
/// The clauses of the `$and`, by position.
fn clauses(query: &Document) -> Vec<Document> {
query
.get_array("$and")
.unwrap()
.iter()
.map(|c| c.as_document().unwrap().clone())
.collect()
}
/// The external-id regex a search for `term` uses.
fn number_regex(term: &str) -> String {
let query = issues_query(&filter(&format!(r#"{{"q":{term:?}}}"#)), None);
let either = clauses(&query)[0].get_array("$or").unwrap().clone();
let external = either[1].as_document().unwrap();
external
.get_document("external_id")
.unwrap()
.get_str("$regex")
.unwrap()
.to_string()
}
#[test]
fn no_filter_lists_everything() {
assert_eq!(issues_query(&filter("{}"), None), Document::new());
assert_eq!(
issues_query(&filter(r#"{"q":" ","repo_id":""}"#), None),
Document::new()
);
}
#[test]
fn a_number_with_or_without_hash_finds_the_ticket() {
assert_eq!(number_regex("913"), "(^|-)913$");
assert_eq!(number_regex("#913"), "(^|-)913$");
let re = regex::RegexBuilder::new(&number_regex("#913"))
.case_insensitive(true)
.build()
.unwrap();
assert!(re.is_match("913"));
assert!(re.is_match("PROJ-913"));
assert!(!re.is_match("1913"));
assert!(!re.is_match("9130"));
}
#[test]
fn the_search_is_a_literal_title_substring() {
let query = issues_query(&filter(r#"{"q":"(a+)+$"}"#), None);
let either = clauses(&query)[0].get_array("$or").unwrap().clone();
let title = either[0]
.as_document()
.unwrap()
.get_document("title")
.unwrap();
assert_eq!(title.get_str("$regex").unwrap(), r"\(a\+\)\+\$");
assert_eq!(title.get_str("$options").unwrap(), "i");
}
#[test]
fn a_lone_hash_searches_the_title_only() {
let query = issues_query(&filter(r##"{"q":"#"}"##), None);
assert_eq!(clauses(&query)[0].get_array("$or").unwrap().len(), 1);
}
#[test]
fn the_status_filter_takes_both_stored_statuses() {
let query = issues_query(&filter(r#"{"status":"open"}"#), None);
assert_eq!(
clauses(&query)[0],
doc! { "status": { "$in": ["open", "in_progress"] } }
);
}
#[test]
fn the_target_filter_takes_its_findings_and_its_cves() {
let ids = vec!["65a1b2c3d4e5f60718293a4b".to_string()];
let query = issues_query(&filter(r#"{"repo_id":"t1"}"#), Some(&ids));
assert_eq!(
clauses(&query)[0],
doc! { "$or": [
{ "finding_id": { "$in": ["65a1b2c3d4e5f60718293a4b"] } },
{ "finding_id": { "$regex": "^cve:t1:" } },
] }
);
}
#[test]
fn a_target_without_ticketed_findings_still_has_its_cves() {
let query = issues_query(&filter(r#"{"repo_id":"t.1"}"#), Some(&[]));
let either = clauses(&query)[0].get_array("$or").unwrap().clone();
let cve = either[1]
.as_document()
.unwrap()
.get_document("finding_id")
.unwrap();
// The id is matched literally.
assert_eq!(cve.get_str("$regex").unwrap(), r"^cve:t\.1:");
}
#[test]
fn search_status_and_target_all_apply() {
// Search and target are both an `$or`: neither may replace the other.
let query = issues_query(
&filter(r#"{"q":"913","status":"closed","repo_id":"t1"}"#),
Some(&[]),
);
let all = clauses(&query);
assert_eq!(all.len(), 3);
assert!(all[0].get_array("$or").unwrap()[0]
.as_document()
.unwrap()
.contains_key("title"));
assert!(all[1].contains_key("status"));
assert!(all[2].get_array("$or").unwrap()[0]
.as_document()
.unwrap()
.contains_key("finding_id"));
}
}
@@ -0,0 +1,54 @@
//! The tenant's metering this month, for the dashboard's usage view (t72).
use axum::extract::Extension;
use axum::http::StatusCode;
use axum::Json;
use serde::Serialize;
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{tenant_db, AgentExt};
use crate::metering::{month_summary, MonthSummary};
/// The usage view: what was used this month, and what the plan allows.
#[derive(Debug, Serialize)]
struct UsageView {
/// What was used.
#[serde(flatten)]
used: MonthSummary,
/// Whether the plan could be read; without it the limits are unknown,
/// not unlimited.
plan_known: bool,
/// The plan's included targets; `None` is unlimited.
included_targets: Option<u32>,
/// The monthly quota; `None` is unlimited.
monthly_pruefungen: Option<u32>,
/// The customer's Prüftag cap; `None` is no cap.
prueftag_cap: Option<u32>,
}
/// GET /api/v1/metering/usage — the tenant's Prüfungen, Prüftage and extra
/// targets this month (Europe/Berlin), with the plan's limits.
///
/// # Errors
///
/// `500` when the counters cannot be read.
pub async fn get_usage(
Extension(agent): AgentExt,
tenant: TenantCtx,
) -> Result<Json<serde_json::Value>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let used = month_summary(&db, chrono::Utc::now()).await.map_err(|e| {
tracing::error!(tenant_id = %tenant.0.tenant_id, "usage not read: {e}");
StatusCode::INTERNAL_SERVER_ERROR
})?;
let plan = agent.plan(&tenant.0.tenant_id).await;
let view = UsageView {
used,
plan_known: plan.is_some(),
included_targets: plan.and_then(|p| p.included_targets),
monthly_pruefungen: plan.and_then(|p| p.limits.monthly_pruefungen),
prueftag_cap: plan.and_then(|p| p.limits.prueftag_cap),
};
Ok(Json(serde_json::json!({ "data": view })))
}
+8
View File
@@ -1,19 +1,25 @@
pub mod admin;
pub mod chat;
pub mod cve_history;
pub mod cve_matrix;
pub mod dast;
pub mod demo_seed;
pub mod dto;
pub mod evidence;
pub mod finding_breakdown;
pub mod finding_groups;
pub mod findings;
pub mod git_source;
pub mod graph;
pub mod health;
pub mod help_chat;
pub mod inbox;
pub mod issues;
pub mod licenses;
pub mod manual_findings;
pub mod mcp_servers;
pub mod mcp_tokens;
pub mod metering;
pub mod notifications;
pub mod onboarding;
pub mod oscal;
@@ -22,6 +28,8 @@ pub mod platform;
pub mod projects;
pub use pentest_handlers as pentest;
pub mod sbom;
pub mod sbom_ecosystems;
pub mod scan_changes;
pub mod scans;
pub mod support;
pub mod target_input;
+122 -9
View File
@@ -114,7 +114,7 @@ pub async fn list_targets(
// `join!` borrows its futures' arguments, so the collections need names.
let (runs, findings) = (db.scan_runs(), db.findings());
let (mut last_scans, counts) = tokio::join!(
latest_scan_runs(&runs, ids.clone()),
latest_scan_runs(&runs, ids.clone(), true),
findings_counts(&findings, ids),
);
let data = targets
@@ -179,10 +179,13 @@ impl TargetFilter {
}
}
/// The newest scan run of each target in `target_ids`, in one query.
/// The newest scan run of each target in `target_ids`, in one query; with
/// `with_queued`, also a run still waiting for a slot (t84), which the
/// dashboard shows but which has scanned nothing yet.
pub(crate) async fn latest_scan_runs(
runs: &mongodb::Collection<ScanRun>,
target_ids: Vec<String>,
with_queued: bool,
) -> HashMap<String, ScanRun> {
use futures_util::StreamExt;
@@ -190,8 +193,12 @@ pub(crate) async fn latest_scan_runs(
return HashMap::new();
}
// Runs store their target's id as `repo_id`.
let mut matching = doc! { "repo_id": { "$in": target_ids } };
if !with_queued {
matching.insert("status", doc! { "$ne": "queued" });
}
let pipeline = vec![
doc! { "$match": { "repo_id": { "$in": target_ids } } },
doc! { "$match": matching },
doc! { "$sort": { "started_at": -1 } },
doc! { "$group": { "_id": "$repo_id", "run": { "$first": "$$ROOT" } } },
];
@@ -999,6 +1006,100 @@ pub async fn detect_target(
}))
}
/// Why a scan is asked for (`POST /api/v1/targets/{id}/scan?reason=…`).
#[derive(Debug, Default, serde::Deserialize)]
pub struct ScanReason {
/// `new_content` after the customer created the target or uploaded
/// files (t72): it runs only when something changed, as a change-driven
/// Prüfung. Absent: the customer asks for a Prüfung, which always runs
/// and counts.
#[serde(default)]
pub reason: Option<String>,
}
/// The trigger of a scan the customer (`staff: false`) or support asked
/// for, for `reason`. Support's scans are never the customer's usage.
fn requested_trigger(staff: bool, reason: Option<&str>) -> compliance_core::models::ScanTrigger {
use compliance_core::models::ScanTrigger;
if staff {
ScanTrigger::Support
} else if reason == Some("new_content") {
ScanTrigger::NewContent
} else {
ScanTrigger::Manual
}
}
/// `POST /api/v1/targets/{id}/billing/swap`: the included target to swap
/// the extra target `{id}` with.
#[derive(Debug, Deserialize)]
pub struct SwapRequest {
/// The id of the included target that becomes extra.
pub with: String,
}
/// The JSON `error` of a refused swap, for the dashboard to word.
fn swap_refusal_code(refusal: compliance_core::models::SwapRefusal) -> &'static str {
use compliance_core::models::SwapRefusal;
match refusal {
SwapRefusal::Unlimited => "swap_unlimited",
SwapRefusal::NotExtra => "swap_not_extra",
SwapRefusal::NotIncluded => "swap_not_included",
SwapRefusal::Locked => "swap_locked",
}
}
/// POST /api/v1/targets/{id}/billing/swap — swap the extra target `{id}`
/// with the included target `with` (t72): `{id}` becomes included and stays
/// so until the end of the calendar month, `with` becomes extra at once.
/// The number of extra targets, and so the extra-target line, is the same.
///
/// # Errors
///
/// `404` for a target that is not an active one of the tenant, `409` with
/// the reason when the swap is not allowed, `503` when the plan cannot be
/// read.
pub async fn swap_target_billing(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
Json(req): Json<SwapRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
let refuse =
|status: StatusCode, error: &str| (status, Json(serde_json::json!({ "error": error })));
let incoming = parse_oid(&id).map_err(|s| refuse(s, "invalid_id"))?;
let outgoing = parse_oid(&req.with).map_err(|s| refuse(s, "invalid_id"))?;
let db = tenant_db(&agent, &tenant)
.await
.map_err(|s| refuse(s, "database_unavailable"))?;
let tenant_id = tenant.0.tenant_id.as_str();
let plan = agent
.plan(tenant_id)
.await
.ok_or_else(|| refuse(StatusCode::SERVICE_UNAVAILABLE, "plan_unavailable"))?;
let outcome = crate::metering::swap(
&db,
incoming,
outgoing,
plan.included_targets.is_some(),
chrono::Utc::now(),
)
.await
.map_err(|e| {
tracing::error!(tenant_id, "swap failed: {e}");
refuse(StatusCode::INTERNAL_SERVER_ERROR, "swap_failed")
})?;
match outcome {
None => Err(refuse(StatusCode::NOT_FOUND, "target_not_found")),
Some(Err(refusal)) => Err(refuse(StatusCode::CONFLICT, swap_refusal_code(refusal))),
Some(Ok(())) => {
agent.refresh_billing(tenant_id, &db).await;
tracing::info!(tenant_id, incoming = %id, outgoing = %req.with, "targets swapped");
Ok(Json(serde_json::json!({ "data": { "swapped": true } })))
}
}
}
/// POST /api/v1/targets/{id}/scan — trigger a scan for the target.
///
/// Dispatches to the unified pipeline when `UNIFIED_PIPELINE` is set (else the
@@ -1008,6 +1109,7 @@ pub async fn trigger_target_scan(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
Query(reason): Query<ScanReason>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let oid = parse_oid(&id)?;
let db = tenant_db(&agent, &tenant).await?;
@@ -1024,12 +1126,7 @@ pub async fn trigger_target_scan(
let agent_clone = (*agent).clone();
let tenant_id = tenant.0.tenant_id.clone();
// A scan support starts is not the customer's usage.
let trigger = if tenant.0.staff.is_some() {
compliance_core::models::ScanTrigger::Support
} else {
compliance_core::models::ScanTrigger::Manual
};
let trigger = requested_trigger(tenant.0.staff.is_some(), reason.reason.as_deref());
tokio::spawn(async move {
// Always the unified target pipeline — this endpoint is about an
// onboarded target by construction, independent of the global
@@ -1045,6 +1142,22 @@ pub async fn trigger_target_scan(
mod filter_tests {
use super::*;
#[test]
fn a_scan_asked_for_new_content_is_change_driven() {
use compliance_core::models::ScanTrigger;
assert_eq!(requested_trigger(false, None), ScanTrigger::Manual);
assert_eq!(
requested_trigger(false, Some("new_content")),
ScanTrigger::NewContent
);
assert_eq!(requested_trigger(false, Some("other")), ScanTrigger::Manual);
assert_eq!(
requested_trigger(true, Some("new_content")),
ScanTrigger::Support,
"support's scans are never the customer's usage"
);
}
#[test]
fn a_project_filter_matches_its_targets() {
let filter = TargetFilter {
+7 -32
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!({
@@ -575,7 +560,7 @@ pub async fn list_targets(
.collect();
let runs = db.scan_runs();
let (mut last_scans, open, vulns) = tokio::join!(
super::onboarding::latest_scan_runs(&runs, ids.clone()),
super::onboarding::latest_scan_runs(&runs, ids.clone(), false),
open_findings_counts(&db, ids.clone()),
open_vulnerabilities_counts(&db, ids),
);
@@ -655,6 +640,10 @@ fn git_source_json(
"webhook_secret".into(),
new_secret.map_or(serde_json::Value::Null, Into::into),
);
obj.insert(
"webhook_events".into(),
crate::git_source::WEBHOOK_EVENTS.as_slice().into(),
);
}
v
}
@@ -807,20 +796,6 @@ pub async fn delete_git_source(
})))
}
#[cfg(test)]
mod build_info_tests {
use super::*;
#[test]
fn an_unset_or_empty_build_value_falls_back() {
assert_eq!(non_empty_or(None, "0.4.4"), "0.4.4");
assert_eq!(non_empty_or(Some(""), "unknown"), "unknown");
assert_eq!(non_empty_or(Some("0.4.5"), "0.4.4"), "0.4.5");
assert!(!BUILD_VERSION.is_empty());
assert!(!BUILD_COMMIT.is_empty());
}
}
#[cfg(test)]
mod target_count_tests {
use super::*;
+1 -1
View File
@@ -31,7 +31,7 @@ pub async fn sbom_filters(
.unwrap_or_default()
.into_iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.filter(|s| !s.is_empty() && s != "unknown" && s != "file")
.filter(|s| compliance_core::sbom_ecosystems::is_filterable_manager(s))
.collect();
let licenses: Vec<String> = db
@@ -0,0 +1,131 @@
//! GET /api/v1/targets/{id}/sbom-ecosystems: a target's SBOM components per
//! ecosystem, and how many of them have a known vulnerability (#957).
use axum::extract::{Extension, Path};
use axum::http::StatusCode;
use axum::Json;
use futures_util::TryStreamExt;
use mongodb::bson::{doc, Document};
use serde::Deserialize;
use super::dto::{tenant_db, AgentExt, ApiResponse, ApiResult};
use compliance_core::sbom_ecosystems::{rank, EcosystemCount};
use compliance_core::tenant_ctx::TenantCtx;
/// One row of [`pipeline`]: a package manager with its counts. `_id` is
/// `None` for components stored without one.
#[derive(Debug, Deserialize)]
struct EcosystemRow {
#[serde(rename = "_id")]
package_manager: Option<String>,
components: u64,
with_cve: u64,
}
impl From<EcosystemRow> for EcosystemCount {
fn from(row: EcosystemRow) -> Self {
Self {
package_manager: row.package_manager.unwrap_or_default(),
components: row.components,
with_cve: row.with_cve,
}
}
}
/// The aggregation counting the components of target `repo_id` per package
/// manager in the database, so only one row per ecosystem leaves it (never
/// the components with their vulnerability lists, #67).
fn pipeline(repo_id: &str) -> Vec<Document> {
vec![
doc! { "$match": { "repo_id": repo_id } },
doc! { "$group": {
"_id": "$package_manager",
"components": { "$sum": 1 },
// A component stored without the list counts as without a CVE.
"with_cve": { "$sum": { "$cond": [
{ "$gt": [{ "$size": { "$ifNull": ["$known_vulnerabilities", []] } }, 0] },
1,
0,
] } },
} },
]
}
/// GET /api/v1/targets/{id}/sbom-ecosystems — the SBOM components of target
/// `id` per ecosystem the component table can filter by, the largest first.
///
/// # Errors
///
/// `500` when the aggregation fails, so the dashboard says so instead of
/// showing an empty chart.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn list_sbom_ecosystems(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
) -> ApiResult<Vec<EcosystemCount>> {
let db = tenant_db(&agent, &tenant).await?;
let fail = |e: mongodb::error::Error| {
tracing::warn!("Failed to count the SBOM ecosystems: {e}");
StatusCode::INTERNAL_SERVER_ERROR
};
let rows: Vec<Document> = db
.sbom_entries()
.aggregate(pipeline(&id))
.await
.map_err(fail)?
.try_collect()
.await
.map_err(fail)?;
let counts = rows
.into_iter()
.filter_map(|row| mongodb::bson::from_document::<EcosystemRow>(row).ok())
.map(EcosystemCount::from)
.collect();
let ecosystems = rank(counts);
Ok(Json(ApiResponse {
total: Some(ecosystems.len() as u64),
data: ecosystems,
page: None,
}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_pipeline_counts_one_target_per_package_manager() {
let stages = pipeline("t1");
assert_eq!(stages.len(), 2);
assert_eq!(stages[0], doc! { "$match": { "repo_id": "t1" } });
let group = stages[1].get_document("$group").expect("a $group stage");
assert_eq!(group.get_str("_id").ok(), Some("$package_manager"));
assert_eq!(
group.get_document("components").ok(),
Some(&doc! { "$sum": 1 })
);
assert!(group.contains_key("with_cve"));
}
#[test]
fn a_row_reads_as_its_count_whatever_integer_width_mongo_sums_in() {
let row: EcosystemRow = mongodb::bson::from_document(
doc! { "_id": "npm", "components": 412_i32, "with_cve": 7_i64 },
)
.expect("a row");
assert_eq!(
EcosystemCount::from(row),
EcosystemCount {
package_manager: "npm".into(),
components: 412,
with_cve: 7,
}
);
let nameless: EcosystemRow = mongodb::bson::from_document(
doc! { "_id": null, "components": 2_i32, "with_cve": 0_i32 },
)
.expect("a row without a package manager");
assert_eq!(EcosystemCount::from(nameless).package_manager, "");
}
}
@@ -0,0 +1,141 @@
//! A target's "Verlauf" (#957): what each of its last scans changed, the
//! CVE alerts found new and those found gone ([`compliance_core::scan_changes`]).
//!
//! Reads the tenant's own database; the org-role middleware lets every role
//! that may read call it, like the other target reads.
use axum::extract::{Extension, Path, Query};
use axum::http::StatusCode;
use axum::Json;
use mongodb::bson::{doc, oid::ObjectId, DateTime as BsonDateTime, Document};
use serde::{Deserialize, Deserializer};
use compliance_core::models::{CveAlert, ScanRun};
use compliance_core::scan_changes::{changes, ScanChange, DEFAULT_SCANS, MAX_SCANS};
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResult};
/// The query of [`target_scan_changes`].
#[derive(Debug, Deserialize)]
pub struct ChangesQuery {
/// The last scans to show, `1..=50` (clamped); 20 when not given.
#[serde(default = "default_limit", deserialize_with = "de_limit")]
pub limit: usize,
}
fn default_limit() -> usize {
DEFAULT_SCANS
}
/// Clamp a caller-supplied number of scans to `1..=MAX_SCANS`.
fn de_limit<'de, D: Deserializer<'de>>(d: D) -> Result<usize, D::Error> {
Ok(usize::deserialize(d)?.clamp(1, MAX_SCANS))
}
/// Log a database error and answer 500.
fn db_error(what: &str) -> impl FnOnce(mongodb::error::Error) -> StatusCode + '_ {
move |e| {
tracing::warn!("scan changes: {what} failed: {e}");
StatusCode::INTERNAL_SERVER_ERROR
}
}
/// `GET /api/v1/targets/{id}/scan-changes[?limit=20]` — the target's last
/// scans, oldest first, each with the CVE alerts found new and gone since
/// the completed scan before it (most severe first), its status and its new
/// findings. The target's first completed scan is marked `baseline`. 404
/// for a target the tenant does not have.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn target_scan_changes(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
Query(query): Query<ChangesQuery>,
) -> ApiResult<Vec<ScanChange>> {
let oid = ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
let db = tenant_db(&agent, &tenant).await?;
// Only whether it exists: its id is all that is read.
db.onboarded_targets()
.clone_with_type::<Document>()
.find_one(doc! { "_id": oid })
.projection(doc! { "_id": 1 })
.await
.map_err(db_error("reading the target"))?
.ok_or(StatusCode::NOT_FOUND)?;
let runs: Vec<ScanRun> = collect_cursor_async(
db.scan_runs()
.find(doc! { "repo_id": &id })
.sort(doc! { "started_at": -1 })
.limit(i64::try_from(query.limit).unwrap_or(i64::MAX))
.await
.map_err(db_error("listing the runs"))?,
)
.await;
// Where the window of the oldest shown scan starts: the end of the
// completed scan before it, if there is one.
let since = match runs.iter().map(|r| r.started_at).min() {
Some(oldest) => db
.scan_runs()
.find_one(doc! {
"repo_id": &id,
"status": "completed",
"started_at": { "$lt": BsonDateTime::from_chrono(oldest) },
})
.sort(doc! { "started_at": -1 })
.await
.map_err(db_error("finding the scan before"))?
.and_then(|run| run.completed_at),
None => None,
};
let mut filter = doc! { "repo_id": &id };
if let Some(since) = since {
let since = BsonDateTime::from_chrono(since);
filter.insert(
"$or",
vec![
doc! { "created_at": { "$gt": since } },
doc! { "resolved_at": { "$gt": since } },
],
);
}
let alerts: Vec<CveAlert> = collect_cursor_async(
db.cve_alerts()
.find(filter)
.projection(doc! {
"summary": 0, "llm_impact_summary": 0, "advisories": 0, "exploitation": 0,
})
.await
.map_err(db_error("loading the alerts"))?,
)
.await;
let data = changes(&runs, since, &alerts);
Ok(Json(ApiResponse {
total: Some(data.len() as u64),
data,
page: None,
}))
}
#[cfg(test)]
mod tests {
use super::*;
fn query(text: &str) -> ChangesQuery {
let uri: axum::http::Uri = format!("/x?{text}").parse().unwrap_or_default();
Query::<ChangesQuery>::try_from_uri(&uri)
.map(|q| q.0)
.unwrap_or(ChangesQuery { limit: 0 })
}
#[test]
fn the_limit_is_clamped_and_defaults_to_twenty() {
assert_eq!(query("").limit, DEFAULT_SCANS);
assert_eq!(query("limit=0").limit, 1);
assert_eq!(query("limit=999").limit, MAX_SCANS);
assert_eq!(query("limit=5").limit, 5);
}
}
+192 -18
View File
@@ -1,5 +1,6 @@
//! VEX for a target's CVE alerts (#498): list them, state their status, and
//! export the statements as OpenVEX or CycloneDX VEX.
//! VEX for a target's CVE alerts (#498): list them, state their status (one
//! alert, or every open alert of a component at once, #949), and export the
//! statements as OpenVEX or CycloneDX VEX.
use axum::extract::{Extension, Path, Query};
use axum::http::{header, HeaderValue, StatusCode};
@@ -9,6 +10,7 @@ use mongodb::bson::{doc, oid::ObjectId};
use serde::Deserialize;
use compliance_core::csaf_docs;
use compliance_core::cve_groups::{self, CveGroup, PackageKey};
use compliance_core::enisa_docs::{self, EnisaInput, Reportability};
use compliance_core::models::{CveAlert, SbomEntry, VexAssessment, VexJustification, VexStatus};
use compliance_core::tenant_ctx::TenantCtx;
@@ -26,18 +28,8 @@ pub async fn list_target_cves(
Path(id): Path<String>,
) -> ApiResult<Vec<CveAlert>> {
let db = tenant_db(&agent, &tenant).await?;
let alerts: Vec<CveAlert> = match db
.cve_alerts()
.find(doc! { "repo_id": &id })
.sort(doc! { "created_at": -1 })
.await
{
Ok(cursor) => collect_cursor_async(cursor).await,
Err(e) => {
tracing::warn!("Failed to list CVE alerts: {e}");
Vec::new()
}
};
// An unreadable list reads as empty here, as it always has.
let alerts = target_alerts(&db, &id).await.unwrap_or_default();
Ok(Json(ApiResponse {
total: Some(alerts.len() as u64),
data: alerts,
@@ -45,6 +37,23 @@ pub async fn list_target_cves(
}))
}
/// The CVE alerts of target `id`, newest first.
async fn target_alerts(
db: &crate::database::Database,
id: &str,
) -> Result<Vec<CveAlert>, StatusCode> {
let cursor = db
.cve_alerts()
.find(doc! { "repo_id": id })
.sort(doc! { "created_at": -1 })
.await
.map_err(|e| {
tracing::warn!("Failed to list CVE alerts: {e}");
StatusCode::INTERNAL_SERVER_ERROR
})?;
Ok(collect_cursor_async(cursor).await)
}
/// The body of [`set_cve_vex`].
#[derive(Debug, Deserialize)]
pub struct VexRequest {
@@ -57,9 +66,8 @@ pub struct VexRequest {
pub action_statement: Option<String>,
}
/// The statement `req` asks for, by the requester of `tenant`.
fn statement(req: VexRequest, tenant: &TenantCtx) -> VexAssessment {
let actor = Actor::of(&tenant.0);
/// The statement `req` asks for, by `actor`.
fn statement(req: VexRequest, actor: Actor<'_>) -> VexAssessment {
let text = |s: Option<String>| s.map(|t| t.trim().to_string()).filter(|t| !t.is_empty());
VexAssessment {
status: req.status,
@@ -85,7 +93,7 @@ pub async fn set_cve_vex(
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
let fail = |code: StatusCode, error: &str| (code, Json(serde_json::json!({ "error": error })));
let oid = ObjectId::parse_str(&id).map_err(|_| fail(StatusCode::BAD_REQUEST, "bad id"))?;
let vex = statement(req, &tenant);
let vex = statement(req, Actor::of(&tenant.0));
vex.validate()
.map_err(|e| fail(StatusCode::UNPROCESSABLE_ENTITY, &e.to_string()))?;
let db = tenant_db(&agent, &tenant)
@@ -104,6 +112,90 @@ pub async fn set_cve_vex(
Ok(Json(serde_json::json!({ "status": "updated", "vex": vex })))
}
/// GET /api/v1/targets/{id}/cve-groups — the target's open CVE alerts grouped
/// by component (#949): the update that fixes them, their counts per
/// severity, KEV and the highest EPSS score, the most severe group first.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn list_cve_groups(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
) -> ApiResult<Vec<CveGroup>> {
let db = tenant_db(&agent, &tenant).await?;
let groups = cve_groups::group_open_alerts(&target_alerts(&db, &id).await?);
Ok(Json(ApiResponse {
total: Some(groups.len() as u64),
data: groups,
page: None,
}))
}
/// The body of [`set_group_vex`]: the component as [`list_cve_groups`] names
/// it, and the statement as [`set_cve_vex`] takes it.
#[derive(Debug, Deserialize)]
pub struct GroupVexRequest {
#[serde(flatten)]
pub key: PackageKey,
#[serde(flatten)]
pub statement: VexRequest,
}
/// PATCH /api/v1/targets/{id}/cve-groups/vex — state one VEX status on every
/// open alert of a component (#949): one statement per alert, with the
/// validation, author and time of [`set_cve_vex`], so the exports and the
/// CVE issues' auto-close treat them as single decisions. Settled alerts
/// keep their statements. 422 as for one alert, 404 when the component has
/// no open alert.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn set_group_vex(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
Json(req): Json<GroupVexRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
let fail = |code: StatusCode, error: &str| (code, Json(serde_json::json!({ "error": error })));
let vex = statement(req.statement, Actor::of(&tenant.0));
vex.validate()
.map_err(|e| fail(StatusCode::UNPROCESSABLE_ENTITY, &e.to_string()))?;
let db = tenant_db(&agent, &tenant)
.await
.map_err(|code| fail(code, "tenant"))?;
let alerts = target_alerts(&db, &id)
.await
.map_err(|code| fail(code, "load"))?;
let ids = open_alert_ids(&alerts, &req.key);
if ids.is_empty() {
return Err(fail(
StatusCode::NOT_FOUND,
"no open alert of this component",
));
}
let vex_bson = mongodb::bson::to_bson(&vex)
.map_err(|_| fail(StatusCode::INTERNAL_SERVER_ERROR, "encode"))?;
let result = db
.cve_alerts()
.update_many(
doc! { "_id": { "$in": ids }, "repo_id": &id },
doc! { "$set": { "vex": vex_bson } },
)
.await
.map_err(|_| fail(StatusCode::INTERNAL_SERVER_ERROR, "store"))?;
Ok(Json(serde_json::json!({
"status": "updated",
"updated": result.matched_count,
"vex": vex,
})))
}
/// The ids of the open alerts among `alerts` that are about component `key`.
fn open_alert_ids(alerts: &[CveAlert], key: &PackageKey) -> Vec<ObjectId> {
alerts
.iter()
.filter(|a| cve_groups::is_open(a) && key.matches(a))
.filter_map(|a| a.id)
.collect()
}
/// The query of [`export_vex`].
#[derive(Debug, Deserialize)]
pub struct VexExportQuery {
@@ -441,6 +533,88 @@ pub async fn export_enisa(
#[cfg(test)]
mod tests {
use super::*;
use compliance_core::models::{CveSource, VexError};
fn group_request(body: serde_json::Value) -> GroupVexRequest {
serde_json::from_value(body).expect("a group request")
}
fn actor() -> Actor<'static> {
Actor {
id: "u1",
name: Some("Ada Admin".into()),
support: false,
}
}
#[test]
fn a_group_decision_is_validated_like_a_single_one() {
let req = group_request(serde_json::json!({
"package": "vite",
"version": "5.4.21",
"purl": "pkg:npm/vite@5.4.21",
"status": "not_affected",
"impact_statement": " ",
}));
assert_eq!(
req.key,
PackageKey {
package: "vite".into(),
version: "5.4.21".into(),
purl: Some("pkg:npm/vite@5.4.21".into()),
}
);
let vex = statement(req.statement, actor());
assert_eq!(vex.validate(), Err(VexError::NotAffectedWithoutReason));
let req = group_request(serde_json::json!({
"package": "vite",
"version": "5.4.21",
"status": "not_affected",
"justification": "vulnerable_code_not_in_execute_path",
"impact_statement": " Build tool only. ",
}));
assert_eq!(req.key.purl, None);
let vex = statement(req.statement, actor());
assert_eq!(vex.validate(), Ok(()));
assert_eq!(vex.impact_statement.as_deref(), Some("Build tool only."));
assert_eq!(
(vex.by.as_str(), vex.by_name.as_deref(), vex.by_scan),
("u1", Some("Ada Admin"), false)
);
let affected = group_request(serde_json::json!({
"package": "vite",
"version": "5.4.21",
"status": "affected",
}));
assert_eq!(
statement(affected.statement, actor()).validate(),
Err(VexError::AffectedWithoutAction)
);
}
#[test]
fn a_group_decision_reaches_the_open_alerts_of_its_component_only() {
let alert = |cve: &str, version: &str| {
let mut a = CveAlert::new(
cve.into(),
"t1".into(),
"vite".into(),
version.into(),
CveSource::Osv,
);
a.id = Some(ObjectId::new());
a
};
let open = alert("CVE-2025-0001", "5.4.21");
let mut settled = alert("CVE-2025-0002", "5.4.21");
settled.resolved_at = Some(chrono::Utc::now());
let other_version = alert("CVE-2025-0003", "6.0.0");
let alerts = vec![open.clone(), settled, other_version];
let key = PackageKey::of(&open);
assert_eq!(open_alert_ids(&alerts, &key), [open.id.expect("an id")]);
}
#[test]
fn a_publisher_namespace_is_a_web_url_or_the_placeholder() {
@@ -126,11 +126,18 @@ fn routes() -> Vec<(Method, String, bool)> {
(Method::GET, format!("/api/v1/findings/{ID}"), false),
(Method::PATCH, format!("/api/v1/findings/{ID}/status"), true),
(Method::PATCH, "/api/v1/findings/bulk-status".into(), true),
(Method::GET, "/api/v1/inbox".into(), false),
(Method::POST, "/api/v1/inbox/decide".into(), true),
(Method::POST, "/api/v1/inbox/undo".into(), true),
(Method::POST, "/api/v1/inbox/snooze".into(), true),
(Method::DELETE, format!("/api/v1/inbox/snooze/f-{ID}"), true),
(
Method::PATCH,
format!("/api/v1/findings/{ID}/feedback"),
true,
),
(Method::GET, "/api/v1/finding-groups".into(), false),
(Method::POST, "/api/v1/finding-groups/decide".into(), true),
(Method::POST, format!("/api/v1/targets/{ID}/findings"), true),
(
Method::POST,
@@ -142,7 +149,23 @@ fn routes() -> Vec<(Method, String, bool)> {
format!("/api/v1/targets/{ID}/evidence-pack"),
false,
),
(
Method::GET,
format!("/api/v1/targets/{ID}/finding-breakdown"),
false,
),
(Method::GET, "/api/v1/sbom/export".into(), false),
(Method::GET, "/api/v1/cve-history?days=30".into(), false),
(
Method::GET,
format!("/api/v1/targets/{ID}/top-updates"),
false,
),
(
Method::GET,
format!("/api/v1/targets/{ID}/scan-changes"),
false,
),
(Method::GET, "/api/v1/licenses/conclusions".into(), false),
(Method::PUT, "/api/v1/licenses/conclusions".into(), true),
(
+63
View File
@@ -15,6 +15,7 @@ pub fn build_router() -> Router {
.route("/api/v1/stats/overview", get(handlers::stats_overview))
// The tenant's projects (owned by the registry), for assigning targets.
.route("/api/v1/projects", get(handlers::projects::list_projects))
.route("/api/v1/metering/usage", get(handlers::metering::get_usage))
// Whether the caller may use Prüfwerk at all: answered by the
// authentication and entitlement layers in front of it (a blocked
// member gets 403 MEMBER_BLOCKED), for the dashboard's sign-in check.
@@ -84,6 +85,10 @@ pub fn build_router() -> Router {
"/api/v1/targets/{id}/scan",
post(handlers::onboarding::trigger_target_scan),
)
.route(
"/api/v1/targets/{id}/billing/swap",
post(handlers::onboarding::swap_target_billing),
)
.route("/api/v1/findings", get(handlers::list_findings))
.route(
"/api/v1/findings/variants",
@@ -102,16 +107,66 @@ pub fn build_router() -> Router {
"/api/v1/findings/{id}/feedback",
patch(handlers::update_finding_feedback),
)
// Undecided findings grouped by rule and file; one decision per group (#951).
.route(
"/api/v1/finding-groups",
get(handlers::finding_groups::list_finding_groups),
)
.route(
"/api/v1/finding-groups/decide",
post(handlers::finding_groups::decide_finding_group),
)
// The "Heute" inbox (#950): open decisions in urgency buckets.
.route("/api/v1/inbox", get(handlers::inbox::get_inbox))
.route("/api/v1/inbox/decide", post(handlers::inbox::decide))
.route("/api/v1/inbox/undo", post(handlers::inbox::undo))
.route("/api/v1/inbox/snooze", post(handlers::inbox::snooze))
.route(
"/api/v1/inbox/snooze/{key}",
delete(handlers::inbox::unsnooze),
)
// VEX on a target's CVE alerts (#498).
.route(
"/api/v1/targets/{id}/cves",
get(handlers::vex::list_target_cves),
)
.route(
"/api/v1/targets/{id}/cve-matrix",
get(handlers::cve_matrix::target_cve_matrix),
)
// Open CVEs with a fix per day, and the updates closing most (#952).
.route(
"/api/v1/cve-history",
get(handlers::cve_history::cve_history),
)
.route(
"/api/v1/targets/{id}/top-updates",
get(handlers::cve_history::target_top_updates),
)
// What each scan changed, for the target's "Verlauf" (#957).
.route(
"/api/v1/targets/{id}/scan-changes",
get(handlers::scan_changes::target_scan_changes),
)
.route("/api/v1/targets/{id}/vex", get(handlers::vex::export_vex))
.route("/api/v1/targets/{id}/csaf", get(handlers::vex::export_csaf))
.route("/api/v1/targets/{id}/enisa", get(handlers::vex::list_enisa))
.route("/api/v1/cves/{id}/enisa", get(handlers::vex::export_enisa))
.route("/api/v1/cves/{id}/vex", patch(handlers::vex::set_cve_vex))
// The open CVE alerts grouped by component, one decision per group (#949).
.route(
"/api/v1/targets/{id}/cve-groups",
get(handlers::vex::list_cve_groups),
)
.route(
"/api/v1/targets/{id}/cve-groups/vex",
patch(handlers::vex::set_group_vex),
)
// The target's SBOM components per ecosystem (#957).
.route(
"/api/v1/targets/{id}/sbom-ecosystems",
get(handlers::sbom_ecosystems::list_sbom_ecosystems),
)
.route(
"/api/v1/targets/{id}/evidence-pack",
get(handlers::evidence::evidence_pack),
@@ -120,6 +175,10 @@ pub fn build_router() -> Router {
"/api/v1/targets/{id}/compliance",
get(handlers::evidence::compliance_view),
)
.route(
"/api/v1/targets/{id}/finding-breakdown",
get(handlers::finding_breakdown::finding_breakdown),
)
.route(
"/api/v1/compliance/summary",
get(handlers::evidence::compliance_summary),
@@ -194,6 +253,10 @@ pub fn build_router() -> Router {
"/api/v1/graph/{repo_id}/nodes",
get(handlers::graph::get_nodes),
)
.route(
"/api/v1/graph/{repo_id}/summary",
get(handlers::graph::get_summary),
)
.route(
"/api/v1/graph/{repo_id}/communities",
get(handlers::graph::get_communities),
+4 -2
View File
@@ -98,7 +98,9 @@ pub async fn triage_repo_findings(
// to decide.
TriageOutcome::NeedsReview => {
finding.status = FindingStatus::NeedsReview;
finding.triage_action = Some("control_not_confirmed".to_string());
finding.triage_action = Some(
compliance_core::models::finding::TRIAGE_CONTROL_NOT_CONFIRMED.to_string(),
);
finding.triage_rationale.get_or_insert_with(|| {
"The control check did not confirm the CRA requirements this \
finding maps to. Please review whether it is a real issue."
@@ -215,7 +217,7 @@ pub async fn grounded_surface_findings(
/// Read a window of lines around `line` (1-based) from `repo_path/file`.
fn fetch_region(repo_path: &Path, file: &str, line: u32) -> Option<CandidateRegion> {
let content = std::fs::read_to_string(repo_path.join(file)).ok()?;
let content = compliance_core::encoding::read_source(&repo_path.join(file)).ok()?;
let lines: Vec<&str> = content.lines().collect();
if lines.is_empty() {
return None;
+22 -3
View File
@@ -116,8 +116,8 @@ pub const SURFACES: &[Surface] = &[
/// Source file extensions worth reading (skip binaries/assets/lockfiles).
const CODE_EXTS: &[&str] = &[
"py", "js", "ts", "tsx", "jsx", "go", "java", "rb", "php", "rs", "cs", "kt", "c", "h", "cc",
"cpp", "hpp",
"py", "js", "ts", "tsx", "jsx", "go", "java", "rb", "php", "rs", "cs", "vb", "kt", "c", "h",
"cc", "cpp", "hpp",
];
/// Directories never worth walking.
const SKIP_DIRS: &[&str] = &[
@@ -156,7 +156,8 @@ pub fn retrieve(repo_path: &Path, terms: &[&str], excluded: &[String]) -> Vec<Ca
if !meta.is_file() || meta.len() > MAX_FILE_BYTES {
continue;
}
let Ok(content) = std::fs::read_to_string(path) else {
// UTF-8, UTF-16 with a BOM, or Windows-1252; a binary is skipped.
let Ok(content) = compliance_core::encoding::read_source(path) else {
continue;
};
let rel = path
@@ -286,6 +287,24 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_windows_1252_file_is_read() {
let dir = std::env::temp_dir().join(format!("surface-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
// "Prüfung" as Windows-1252 writes it: 0xFC for "ü".
let path = dir.join("app/Auth.cs");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(
&path,
b"// Pr\xFCfung\nbool Login(string u, string p) { }\n",
)
.unwrap();
let regions = retrieve(&dir, terms_for("cra-ai-11"), &[]);
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(regions.len(), 1);
assert!(regions[0].content.contains("Prüfung"));
}
#[test]
fn firmware_update_code_is_read_but_not_the_vendor_hal() {
let dir = std::env::temp_dir().join(format!("surface-{}", uuid::Uuid::new_v4()));
+19
View File
@@ -618,6 +618,19 @@ impl Database {
)
.await?;
// inbox_snoozes (#950): one per card key, and the resubmissions due
self.inbox_snoozes()
.create_index(
IndexModel::builder()
.keys(doc! { "key": 1 })
.options(IndexOptions::builder().unique(true).build())
.build(),
)
.await?;
self.inbox_snoozes()
.create_index(IndexModel::builder().keys(doc! { "until": 1 }).build())
.await?;
tracing::info!("Database indexes ensured");
Ok(())
}
@@ -785,6 +798,12 @@ impl Database {
self.inner.collection("werkbank_jobs")
}
/// The cards of the "Heute" inbox put off until a date (#950).
pub fn inbox_snoozes(&self) -> Collection<compliance_core::models::inbox::InboxSnooze> {
self.inner
.collection(compliance_core::models::inbox::SNOOZES_COLLECTION)
}
#[allow(dead_code)]
pub fn raw_collection(&self, name: &str) -> Collection<mongodb::bson::Document> {
self.inner.collection(name)
+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",
+149 -8
View File
@@ -12,6 +12,9 @@ pub enum SourceAction {
/// A push to the default branch: scan the target, creating it first if
/// the `created` delivery was lost.
Push(GiteaRepo),
/// A person closed or reopened an issue (#953): carry it over to the
/// finding or CVE the issue was opened for, if Prüfwerk opened it.
Issue(IssueEvent),
/// Nothing to do, and why.
Ignore(&'static str),
}
@@ -21,11 +24,40 @@ impl SourceAction {
pub fn repo(&self) -> Option<&GiteaRepo> {
match self {
Self::Created(repo) | Self::Deleted(repo) | Self::Push(repo) => Some(repo),
Self::Issue(event) => Some(&event.repo),
Self::Ignore(_) => None,
}
}
}
/// What happened to an issue.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IssueChange {
Closed,
Reopened,
}
/// An issue closed or reopened in a repository of the organisation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IssueEvent {
pub repo: GiteaRepo,
/// The issue number in the repository (`TrackerIssue::external_id`).
pub number: i64,
pub change: IssueChange,
/// The login of the user who closed or reopened it.
pub sender: String,
}
/// Whether Prüfwerk itself caused an issue event: the sender is the issue's
/// author. Prüfwerk opens its issues as the source's bot user and closes and
/// reopens them as that user, so an author acting on their own issue is the
/// bot. The bot token cannot read its own user (`read:user` is not among its
/// scopes), so the author stands in for it. Gitea logins are
/// case-insensitive.
pub fn is_own_event(sender: &str, author: &str) -> bool {
!sender.is_empty() && sender.eq_ignore_ascii_case(author)
}
/// A branch deletion pushes this as the new head.
const ZERO_SHA: &str = "0000000000000000000000000000000000000000";
@@ -33,19 +65,16 @@ const ZERO_SHA: &str = "0000000000000000000000000000000000000000";
/// organisation. Repositories of any other owner are ignored, so a system
/// webhook (which sees the whole instance) is safe to use.
pub fn route_event(event: &str, payload: &serde_json::Value, org: &str) -> SourceAction {
if !super::WEBHOOK_EVENTS.contains(&event) {
return SourceAction::Ignore("event not handled");
}
let Some(repo) = payload
.get("repository")
.cloned()
.and_then(|r| serde_json::from_value::<GiteaRepo>(r).ok())
else {
return match event {
"repository" | "push" => SourceAction::Ignore("payload without a repository"),
_ => SourceAction::Ignore("event not handled"),
};
return SourceAction::Ignore("payload without a repository");
};
if !matches!(event, "repository" | "push") {
return SourceAction::Ignore("event not handled");
}
if !repo.in_org(org) {
return SourceAction::Ignore("repository outside the configured organisation");
}
@@ -55,6 +84,7 @@ pub fn route_event(event: &str, payload: &serde_json::Value, org: &str) -> Sourc
Some("deleted") => SourceAction::Deleted(repo),
_ => SourceAction::Ignore("repository action not handled"),
},
"issues" => route_issue(payload, repo),
_ => {
let git_ref = payload.get("ref").and_then(|r| r.as_str()).unwrap_or("");
let after = payload.get("after").and_then(|a| a.as_str()).unwrap_or("");
@@ -69,6 +99,41 @@ pub fn route_event(event: &str, payload: &serde_json::Value, org: &str) -> Sourc
}
}
/// Route an `issues` delivery of `repo`: a close or reopen by someone other
/// than Prüfwerk's bot user.
fn route_issue(payload: &serde_json::Value, repo: GiteaRepo) -> SourceAction {
let change = match payload.get("action").and_then(|a| a.as_str()) {
Some("closed") => IssueChange::Closed,
Some("reopened") => IssueChange::Reopened,
_ => return SourceAction::Ignore("issue action not handled"),
};
let issue = payload.get("issue");
let Some(number) = payload
.get("number")
.or_else(|| issue.and_then(|i| i.get("number")))
.and_then(serde_json::Value::as_i64)
else {
return SourceAction::Ignore("issue without a number");
};
// `user.login` of the sender and of the issue's author.
let login = |user: Option<&serde_json::Value>| {
user.and_then(|u| u.get("login"))
.and_then(|l| l.as_str())
.unwrap_or_default()
.to_string()
};
let sender = login(payload.get("sender"));
if is_own_event(&sender, &login(issue.and_then(|i| i.get("user")))) {
return SourceAction::Ignore("issue changed by Prüfwerk's bot user");
}
SourceAction::Issue(IssueEvent {
repo,
number,
change,
sender,
})
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
@@ -161,7 +226,7 @@ mod tests {
);
assert_eq!(
route_event("issues", &json!({}), "kunde"),
SourceAction::Ignore("event not handled")
SourceAction::Ignore("payload without a repository")
);
assert_eq!(
route_event("push", &json!({ "ref": "refs/heads/main" }), "kunde"),
@@ -172,4 +237,80 @@ mod tests {
SourceAction::Ignore("event not handled")
);
}
fn issue_event(action: &str, sender: &str, author: &str) -> serde_json::Value {
json!({
"action": action, "number": 12,
"issue": { "number": 12, "state": "closed", "user": { "login": author } },
"sender": { "login": sender },
"repository": repository("kunde"),
})
}
#[test]
fn a_person_closing_or_reopening_an_issue_is_carried_over() {
let closed = issue_event("closed", "dev-anna", "pruefwerk");
match route_event("issues", &closed, "kunde") {
SourceAction::Issue(e) => assert_eq!(
(e.repo.id, e.number, e.change, e.sender.as_str()),
(42, 12, IssueChange::Closed, "dev-anna")
),
other => panic!("{other:?}"),
}
let reopened = issue_event("reopened", "dev-anna", "pruefwerk");
assert!(matches!(
route_event("issues", &reopened, "kunde"),
SourceAction::Issue(IssueEvent {
change: IssueChange::Reopened,
..
})
));
// The number from the issue when the payload has none on top.
let mut p = issue_event("closed", "dev-anna", "pruefwerk");
p.as_object_mut().unwrap().remove("number");
assert!(matches!(
route_event("issues", &p, "kunde"),
SourceAction::Issue(IssueEvent { number: 12, .. })
));
}
#[test]
fn pruefwerks_own_changes_are_ignored_so_nothing_loops() {
// The bot closed or reopened the issue it opened.
for action in ["closed", "reopened"] {
let p = issue_event(action, "pruefwerk", "pruefwerk");
assert_eq!(
route_event("issues", &p, "kunde"),
SourceAction::Ignore("issue changed by Prüfwerk's bot user")
);
}
assert!(is_own_event("Pruefwerk", "pruefwerk"));
assert!(!is_own_event("dev-anna", "pruefwerk"));
// A payload without a sender is not taken for the bot's.
assert!(!is_own_event("", ""));
}
#[test]
fn other_issue_events_are_ignored() {
for action in ["opened", "edited", "label_updated", "assigned"] {
let p = issue_event(action, "dev-anna", "pruefwerk");
assert_eq!(
route_event("issues", &p, "kunde"),
SourceAction::Ignore("issue action not handled")
);
}
let mut p = issue_event("closed", "dev-anna", "pruefwerk");
p.as_object_mut().unwrap().remove("number");
p["issue"].as_object_mut().unwrap().remove("number");
assert_eq!(
route_event("issues", &p, "kunde"),
SourceAction::Ignore("issue without a number")
);
let mut p = issue_event("closed", "dev-anna", "pruefwerk");
p["repository"] = repository("andere");
assert_eq!(
route_event("issues", &p, "kunde"),
SourceAction::Ignore("repository outside the configured organisation")
);
}
}
+27
View File
@@ -34,6 +34,10 @@ use gitea::{GiteaRepo, RepoLister, SourceClient};
pub const DEFAULT_HOST_PATTERN: &str = r"^[a-z0-9-]+\.code(-stage)?\.breakpilot\.com$";
/// Minutes between syncs unless `GIT_SOURCE_SYNC_MINUTES` says otherwise.
pub const DEFAULT_SYNC_MINUTES: u64 = 30;
/// The Gitea events the organisation or system webhook must send: Prüfwerk
/// cannot register or change the webhook itself (the bot has no
/// administration rights), so the platform API names them for provisioning.
pub const WEBHOOK_EVENTS: [&str; 3] = ["repository", "push", "issues"];
/// The webhook path of a tenant's source, below the webhook server's origin.
pub fn webhook_path(tenant_id: &str) -> String {
format!("/webhook/{tenant_id}/gitea-source")
@@ -454,6 +458,11 @@ pub enum Outcome {
Ensured { target_id: String, scan: bool },
/// The repository's target was archived (`false`: there was none).
Archived(bool),
/// An issue closed or reopened in Gitea was carried back (#953).
Issue {
target_id: String,
detail: &'static str,
},
/// Nothing done.
Ignored(&'static str),
}
@@ -495,6 +504,24 @@ pub async fn apply_action(
scan: true,
})
}
SourceAction::Issue(event) => {
// Only the repository's existing target: an issue event never
// creates one.
let Some(target_id) = db
.onboarded_targets()
.find_one(repo_filter(&source.base_url, event.repo.id))
.await?
.and_then(|t| t.id)
else {
return Ok(Outcome::Ignored("repository has no target"));
};
let target_id = target_id.to_hex();
let done = crate::pipeline::issue_backsync::apply(db, &target_id, &event).await?;
Ok(Outcome::Issue {
target_id,
detail: done.detail(event.change),
})
}
}
}
+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;
+43 -10
View File
@@ -43,14 +43,15 @@ struct OrphanRule {
}
/// Code scans are what customers see, so they get their own `interrupted`
/// status. The rest close as `failed` with [`INTERRUPTED_MESSAGE`]: DAST and
/// status, also those still waiting for a slot: the queue lives in the agent's
/// memory and is gone after a restart (t84). The rest close as `failed` with [`INTERRUPTED_MESSAGE`]: DAST and
/// pentest are off in production, and graph and embedding builds are steps of
/// a scan. A paused pentest session can only be resumed through in-memory
/// state, so after a restart it is as dead as a running one.
const ORPHAN_RULES: [OrphanRule; 5] = [
OrphanRule {
collection: "scan_runs",
open: &["running"],
open: &["queued", "running"],
closed_as: "interrupted",
},
OrphanRule {
@@ -218,12 +219,16 @@ async fn targets_to_resume(
.await?;
let mut out = Vec::new();
for id in ids.iter().filter_map(|v| v.as_str()) {
// Only scans that had started count: one interrupted while it still
// waited for a slot cannot be what stopped the agent. It never got a
// start time of its own, so it still starts when it was requested.
let interruptions = db
.scan_runs()
.count_documents(doc! {
"repo_id": id,
"status": "interrupted",
"completed_at": { "$gte": window },
"$expr": { "$ne": ["$started_at", "$queued_at"] },
})
.await?;
if interruptions > MAX_RECENT_INTERRUPTIONS {
@@ -243,12 +248,25 @@ async fn targets_to_resume(
.await?;
if active > 0 {
// Resumed as it was started: a scan a person started runs even when
// nothing changed since the last completed one (#465).
let trigger = db
// nothing changed since the last completed one (#465). Of a running
// scan and its queued follow-up, a person's wins.
let triggers = db
.scan_runs()
.find_one(doc! { "repo_id": id, "status": "interrupted", "completed_at": closed })
.await?
.map_or(ScanTrigger::Scheduled, |run| run.trigger);
.distinct(
"trigger",
doc! { "repo_id": id, "status": "interrupted", "completed_at": closed },
)
.await?;
let triggers: Vec<ScanTrigger> = triggers
.into_iter()
.filter_map(|t| mongodb::bson::from_bson(t).ok())
.collect();
let trigger = triggers
.iter()
.find(|t| t.started_by_person())
.or_else(|| triggers.first())
.cloned()
.unwrap_or(ScanTrigger::Scheduled);
out.push((id.to_string(), trigger));
}
}
@@ -365,10 +383,11 @@ mod tests {
let archived = insert(archived_target).await;
let earlier_only = insert(target("earlier-only")).await;
// Arrange: runs left open, plus one interrupted an hour ago.
// The scan to resume was started by a person.
// Arrange: runs left open, plus one interrupted an hour ago. The
// target to resume has a scheduled scan running and a person's
// follow-up queued (t84): one interruption, resumed as the person's.
for (id, trigger) in [
(&resumes, ScanTrigger::Manual),
(&resumes, ScanTrigger::Scheduled),
(&looping, ScanTrigger::Scheduled),
(&archived, ScanTrigger::Scheduled),
] {
@@ -377,6 +396,10 @@ mod tests {
.await
.unwrap();
}
db.scan_runs()
.insert_one(ScanRun::queued(resumes.clone(), ScanTrigger::Manual))
.await
.unwrap();
for id in [&looping, &earlier_only] {
let mut run = ScanRun::new(id.clone(), ScanTrigger::Scheduled);
run.status = compliance_core::models::ScanRunStatus::Interrupted;
@@ -423,6 +446,16 @@ mod tests {
}
}
#[test]
fn queued_code_scans_are_closed_at_startup_too() {
let scan_rule = ORPHAN_RULES
.iter()
.find(|r| r.collection == "scan_runs")
.expect("scan_runs rule");
assert!(scan_rule.open.contains(&"queued"));
assert!(scan_rule.open.contains(&"running"));
}
#[test]
fn code_scans_are_interrupted_not_failed() {
let scan_rule = ORPHAN_RULES
+67 -20
View File
@@ -1,7 +1,7 @@
use std::collections::HashMap;
use std::fmt;
use compliance_core::models::{Exploitation, Finding, FindingStatus, Severity};
use compliance_core::models::{Exploitation, Finding, FindingStatus, ReviewReason, Severity};
use serde::{Deserialize, Deserializer};
use serde_json::Value;
@@ -72,7 +72,7 @@ const RESPONSE_SAMPLE_CHARS: usize = 500;
/// `triage_action` of a finding the LLM triage gave no verdict; the reason is
/// in `triage_rationale`, which starts with `skipped: <reason>`.
pub const SKIPPED_ACTION: &str = "skipped";
pub const SKIPPED_ACTION: &str = compliance_core::models::finding::TRIAGE_SKIPPED;
/// The model the triage asks. A trait so tests can drive the triage with a
/// fake model.
@@ -823,12 +823,12 @@ fn drop_trailing_comma(json: &mut String) {
/// A dismissed or low-confidence finding is kept as
/// [`FindingStatus::NeedsReview`], never deleted: the model's rationale goes
/// with it, and a person decides.
///
/// Which of the two it was is read back from the stored verdict
/// ([`Finding::review_reason`]), so the decision lives in one place
/// ([`ReviewReason::of_verdict`]).
fn apply_action(finding: &mut Finding, action: &str, adjusted_confidence: f64) -> Outcome {
match action {
"dismiss" => {
finding.status = FindingStatus::NeedsReview;
Outcome::Dismissed
}
"downgrade" => {
finding.severity = downgrade_severity(&finding.severity);
finding.status = FindingStatus::Triaged;
@@ -839,29 +839,31 @@ fn apply_action(finding: &mut Finding, action: &str, adjusted_confidence: f64) -
finding.status = FindingStatus::Triaged;
Outcome::Upgraded
}
// "confirm" or unknown: kept as reported when the model is confident.
_ if adjusted_confidence >= CONFIDENCE_THRESHOLD => {
finding.status = FindingStatus::Triaged;
Outcome::Confirmed
}
_ => {
finding.status = FindingStatus::NeedsReview;
Outcome::LowConfidence
}
// "dismiss", "confirm" or unknown: triaged when the model is sure it
// is real, else left to a person.
_ => match ReviewReason::of_verdict(action, adjusted_confidence) {
Some(reason) => {
finding.status = FindingStatus::NeedsReview;
match reason {
ReviewReason::LikelyFalseAlarm => Outcome::Dismissed,
ReviewReason::Unsure => Outcome::LowConfidence,
}
}
None => {
finding.status = FindingStatus::Triaged;
Outcome::Confirmed
}
},
}
}
/// Least confidence (after [`adjust_confidence`]) at which a confirmed
/// finding counts as triaged; below it the finding needs review.
const CONFIDENCE_THRESHOLD: f64 = 3.0;
/// Read ~50 lines of surrounding code from the file at the finding's location
fn read_surrounding_context(finding: &Finding) -> Option<String> {
let file_path = finding.file_path.as_deref()?;
let line = finding.line_number? as usize;
// Try to read the file — this works because the repo is cloned locally
let content = std::fs::read_to_string(file_path).ok()?;
let content = compliance_core::encoding::read_source(std::path::Path::new(file_path)).ok()?;
let lines: Vec<&str> = content.lines().collect();
let start = line.saturating_sub(25);
@@ -1104,6 +1106,51 @@ mod tests {
assert_eq!(unsure.status, FindingStatus::NeedsReview);
}
/// A verdict of the model on finding 1.
fn model_verdict(action: &str, confidence: f64) -> TriageResult {
TriageResult {
id: Some("1".into()),
action: action.into(),
confidence,
rationale: "why".into(),
remediation: None,
}
}
#[test]
fn a_finding_kept_for_review_says_why() {
let mut dismissed = finding();
assert_eq!(
apply_verdict(&mut dismissed, &model_verdict("dismiss", 9.0)),
Outcome::Dismissed
);
assert_eq!(
dismissed.review_reason(),
Some(ReviewReason::LikelyFalseAlarm)
);
assert_eq!(dismissed.triage_rationale.as_deref(), Some("why"));
let mut unsure = finding();
assert_eq!(
apply_verdict(&mut unsure, &model_verdict("confirm", 2.0)),
Outcome::LowConfidence
);
assert_eq!(unsure.review_reason(), Some(ReviewReason::Unsure));
// Test code halves the confidence: a 5 there is unsure.
let mut in_tests = finding();
in_tests.file_path = Some("src/tests/buffer.c".into());
assert_eq!(
apply_verdict(&mut in_tests, &model_verdict("confirm", 5.0)),
Outcome::LowConfidence
);
assert_eq!(in_tests.review_reason(), Some(ReviewReason::Unsure));
let mut confirmed = finding();
apply_verdict(&mut confirmed, &model_verdict("confirm", 7.0));
assert_eq!(confirmed.review_reason(), None);
}
#[test]
fn confirmed_and_rerated_findings_pass() {
let mut f = finding();
+535
View File
@@ -0,0 +1,535 @@
//! Metering of a tenant's Prüfungen (t72).
//!
//! **Included and extra targets.** The oldest active targets are included,
//! up to the plan's `included_targets`; every other active target is extra.
//! The split is stored on each target ([`OnboardedTarget::billing`]) and
//! brought up to date before each scan and when a target is created, so
//! archiving an included target moves the oldest extra one up.
//!
//! **Counters.** A counted Prüfung is checked against the plan when it
//! starts ([`usage`] and [`compliance_core::models::admit`]) and charged
//! when it completes ([`charge`]): to the month's quota, else to the
//! target's Prüftag for the day, booking one if none is. Months and days
//! are calendar ones in Europe/Berlin. A run that fails because of us is
//! never charged, so nothing is refunded.
//!
//! [`OnboardedTarget::billing`]: compliance_core::models::OnboardedTarget::billing
use chrono::{DateTime, Utc};
use futures_util::TryStreamExt;
use mongodb::bson::{doc, oid::ObjectId, Document};
use compliance_core::models::{
check_swap, split_included, BillableTarget, DayUsage, IncludedChoice, MonthUsage, PlanLimits,
RunCharge, SwapRefusal, TargetBilling,
};
use crate::database::Database;
use crate::error::AgentError;
/// Store the billing of the tenant's active targets for a plan that
/// includes `included` targets.
///
/// # Arguments
///
/// * `db` - The tenant's database.
/// * `included` - How many targets the plan includes; `None` is unlimited.
///
/// # Returns
///
/// The targets whose billing changed, with their new billing.
///
/// # Errors
///
/// Returns an error if the targets cannot be read or updated.
pub async fn assign_billing(
db: &Database,
included: Option<u32>,
) -> Result<Vec<(ObjectId, TargetBilling)>, AgentError> {
// Only the fields the split needs: a whole target holds its artifacts,
// and older documents may lack fields the model requires.
let docs: Vec<Document> = db
.raw_collection("onboarded_targets")
.find(doc! { "archived_at": null })
.projection(doc! { "_id": 1, "created_at": 1, "billing": 1, "included_choice": 1 })
.await?
.try_collect()
.await?;
let targets: Vec<BillableTarget<ObjectId>> = docs.iter().filter_map(billable).collect();
let changes = split_included(&targets, included);
for wanted in [TargetBilling::Included, TargetBilling::Extra] {
let ids: Vec<ObjectId> = changes
.iter()
.filter(|(_, billing)| *billing == wanted)
.map(|(id, _)| *id)
.collect();
if ids.is_empty() {
continue;
}
let value =
mongodb::bson::to_bson(&wanted).map_err(|e| AgentError::Other(e.to_string()))?;
db.onboarded_targets()
.update_many(
doc! { "_id": { "$in": ids } },
doc! { "$set": { "billing": value } },
)
.await?;
}
Ok(changes)
}
/// A stored target as the split sees it; `None` without an id. A target
/// without a creation time counts as the oldest, one without a billing as
/// included (stored before metering).
fn billable(target: &Document) -> Option<BillableTarget<ObjectId>> {
Some(BillableTarget {
id: target.get_object_id("_id").ok()?,
created_at: target
.get_datetime("created_at")
.map_or(DateTime::<Utc>::MIN_UTC, |at| at.to_chrono()),
billing: target
.get("billing")
.and_then(|b| mongodb::bson::from_bson(b.clone()).ok())
.unwrap_or_default(),
choice: target
.get("included_choice")
.and_then(|c| mongodb::bson::from_bson(c.clone()).ok()),
})
}
/// The first instant after the calendar month (Europe/Berlin) of `at`: until
/// then a target swapped in at `at` stays included.
pub fn end_of_berlin_month(at: DateTime<Utc>) -> DateTime<Utc> {
use chrono::{Datelike, TimeZone};
let local = at.with_timezone(&chrono_tz::Europe::Berlin);
let (year, month) = if local.month() == 12 {
(local.year() + 1, 1)
} else {
(local.year(), local.month() + 1)
};
// Midnight is never skipped or repeated in Berlin (DST changes at 2–3 h).
chrono_tz::Europe::Berlin
.with_ymd_and_hms(year, month, 1, 0, 0, 0)
.earliest()
.map_or(at, |next| next.with_timezone(&Utc))
}
/// Swap the extra target `incoming` with the included target `outgoing`
/// (t72): the one swapped in stays included until the end of the calendar
/// month, the other becomes extra. It records the customer's choice; the
/// next [`assign_billing`] (which the caller runs) moves the billing.
///
/// # Arguments
///
/// * `limited` - Whether the plan limits the included targets.
///
/// # Returns
///
/// `None` when either target is not an active one of the tenant; else
/// whether the swap was made, or why not.
///
/// # Errors
///
/// Returns an error if the targets cannot be read or updated.
pub async fn swap(
db: &Database,
incoming: ObjectId,
outgoing: ObjectId,
limited: bool,
at: DateTime<Utc>,
) -> Result<Option<Result<(), SwapRefusal>>, AgentError> {
let targets = db.onboarded_targets();
let active = |id: ObjectId| doc! { "_id": id, "archived_at": null };
let (Some(swapped_in), Some(swapped_out)) = (
targets.find_one(active(incoming)).await?,
targets.find_one(active(outgoing)).await?,
) else {
return Ok(None);
};
let locked = swapped_out.included_until.is_some_and(|until| until > at);
if let Err(refusal) = check_swap(limited, swapped_in.billing, swapped_out.billing, locked) {
return Ok(Some(Err(refusal)));
}
let to_bson = |v: IncludedChoice| {
mongodb::bson::to_bson(&v).map_err(|e| AgentError::Other(e.to_string()))
};
targets
.update_one(
doc! { "_id": incoming },
doc! { "$set": {
"included_choice": to_bson(IncludedChoice::Included)?,
"included_until": mongodb::bson::DateTime::from_chrono(end_of_berlin_month(at)),
} },
)
.await?;
targets
.update_one(
doc! { "_id": outgoing },
doc! {
"$set": { "included_choice": to_bson(IncludedChoice::Extra)? },
"$unset": { "included_until": "" },
},
)
.await?;
Ok(Some(Ok(())))
}
/// The tenant's plan as metering reads it from the registry.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Plan {
/// How many targets the plan includes; `None` is unlimited.
pub included_targets: Option<u32>,
/// The quota and the customer's Prüftag cap.
pub limits: PlanLimits,
}
/// The tenant's counted Prüfungen and booked Prüftage per month.
const MONTHS: &str = "metering_months";
/// Each target's Prüftag per day, once the quota was used up.
const DAYS: &str = "metering_days";
/// The calendar month and day of `at` in Europe/Berlin, as `YYYY-MM` and
/// `YYYY-MM-DD`: the periods the contract counts in.
pub fn berlin_period(at: DateTime<Utc>) -> (String, String) {
let local = at.with_timezone(&chrono_tz::Europe::Berlin);
(
local.format("%Y-%m").to_string(),
local.format("%Y-%m-%d").to_string(),
)
}
/// The id of a target's counter for one day.
fn day_id(target_id: &str, day: &str) -> String {
format!("{target_id}:{day}")
}
/// A stored counter as a `u32`; missing or negative reads as 0.
fn count(document: Option<&Document>, field: &str) -> u32 {
document
.and_then(|d| d.get(field))
.and_then(mongodb::bson::Bson::as_i64)
.or_else(|| document.and_then(|d| d.get_i32(field).ok()).map(i64::from))
.and_then(|n| u32::try_from(n).ok())
.unwrap_or(0)
}
/// What the tenant used this month and `target_id` today, at `at`.
///
/// # Errors
///
/// Returns an error if the counters cannot be read.
pub async fn usage(
db: &Database,
target_id: &str,
at: DateTime<Utc>,
) -> Result<(MonthUsage, DayUsage), AgentError> {
let (month, day) = berlin_period(at);
let month_doc = db
.raw_collection(MONTHS)
.find_one(doc! { "_id": &month })
.await?;
let day_doc = db
.raw_collection(DAYS)
.find_one(doc! { "_id": day_id(target_id, &day) })
.await?;
Ok((
MonthUsage {
pruefungen: count(month_doc.as_ref(), "pruefungen"),
prueftage: count(month_doc.as_ref(), "prueftage"),
},
DayUsage {
prueftag_booked: day_doc
.as_ref()
.and_then(|d| d.get_bool("prueftag_booked").ok())
.unwrap_or(false),
prueftag_pruefungen: count(day_doc.as_ref(), "prueftag_pruefungen"),
},
))
}
/// What [`charge`] charged a completed Prüfung to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Charged {
/// The quota or the target's Prüftag.
pub charge: RunCharge,
/// The Berlin day (`YYYY-MM-DD`) of a Prüftag this Prüfung booked; it
/// goes to the registry as `prueftag.booked`.
pub booked_prueftag: Option<String>,
}
/// Charge one completed, counted Prüfung on `target_id` at `at`: to the
/// month's quota while it lasts, else to the target's Prüftag that day,
/// booking it if none is. The start of the run checked the limits, so this
/// never refuses; scans of several targets finishing at once can take the
/// quota or a Prüftag over by the ones that raced.
///
/// # Errors
///
/// Returns an error if the counters cannot be written.
pub async fn charge(
db: &Database,
target_id: &str,
limits: PlanLimits,
at: DateTime<Utc>,
) -> Result<Charged, AgentError> {
let (month, day) = berlin_period(at);
let months = db.raw_collection(MONTHS);
months
.update_one(
doc! { "_id": &month },
doc! { "$setOnInsert": { "pruefungen": 0_i64, "prueftage": 0_i64 } },
)
.upsert(true)
.await?;
let quota_filter = match limits.monthly_pruefungen {
// `$not $gte` also matches a month document without the counter.
Some(quota) => doc! {
"_id": &month,
"pruefungen": { "$not": { "$gte": i64::from(quota) } },
},
None => doc! { "_id": &month },
};
let in_quota = months
.update_one(quota_filter, doc! { "$inc": { "pruefungen": 1_i64 } })
.await?;
if in_quota.matched_count == 1 {
return Ok(Charged {
charge: RunCharge::Quota,
booked_prueftag: None,
});
}
let days = db.raw_collection(DAYS);
let id = day_id(target_id, &day);
days.update_one(
doc! { "_id": &id },
doc! { "$setOnInsert": {
"target_id": target_id,
"day": &day,
"month": &month,
"prueftag_booked": false,
"prueftag_pruefungen": 0_i64,
} },
)
.upsert(true)
.await?;
let booked = days
.update_one(
doc! { "_id": &id, "prueftag_booked": false },
doc! { "$set": { "prueftag_booked": true, "prueftag_pruefungen": 1_i64 } },
)
.await?;
if booked.matched_count == 1 {
months
.update_one(
doc! { "_id": &month },
doc! { "$inc": { "prueftage": 1_i64 } },
)
.await?;
return Ok(Charged {
charge: RunCharge::Prueftag,
booked_prueftag: Some(day),
});
}
days.update_one(
doc! { "_id": &id },
doc! { "$inc": { "prueftag_pruefungen": 1_i64 } },
)
.await?;
Ok(Charged {
charge: RunCharge::Prueftag,
booked_prueftag: None,
})
}
/// Record how many of the tenant's active targets are extra at `at`, as
/// the month's peak (t72): the 5,99 € line bills the highest number of
/// extra targets at once in the calendar month (Europe/Berlin).
///
/// # Returns
///
/// The month's peak when it goes to the registry as `target.extra`: when it
/// rose, and once a day besides (a re-send the registry drops as a
/// duplicate of its key). `None` otherwise, and while no target was extra.
///
/// # Errors
///
/// Returns an error if the targets or the month's counters cannot be read
/// or written.
pub async fn record_extra_peak(
db: &Database,
at: DateTime<Utc>,
) -> Result<Option<u32>, AgentError> {
let extra = mongodb::bson::to_bson(&TargetBilling::Extra)
.map_err(|e| AgentError::Other(e.to_string()))?;
let now = db
.onboarded_targets()
.count_documents(doc! { "archived_at": null, "billing": extra })
.await?;
let now = u32::try_from(now).unwrap_or(u32::MAX);
let (month, day) = berlin_period(at);
let months = db.raw_collection(MONTHS);
// The document before the update: the peak and the day it was last sent.
let before = months
.find_one_and_update(
doc! { "_id": &month },
doc! {
"$max": { "extra_peak": i64::from(now) },
"$setOnInsert": { "pruefungen": 0_i64, "prueftage": 0_i64 },
},
)
.upsert(true)
.await?;
let previous = count(before.as_ref(), "extra_peak");
let sent_on = before
.as_ref()
.and_then(|d| d.get_str("extra_sent_on").ok());
let peak = previous.max(now);
if peak == 0 || (peak == previous && sent_on == Some(day.as_str())) {
return Ok(None);
}
months
.update_one(
doc! { "_id": &month },
doc! { "$set": { "extra_sent_on": &day } },
)
.await?;
Ok(Some(peak))
}
/// The tenant's metering this month, for the dashboard (t72).
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
pub struct MonthSummary {
/// The calendar month in Europe/Berlin, `YYYY-MM`.
pub month: String,
/// Counted Prüfungen charged to the quota.
pub pruefungen: u32,
/// Prüftage booked.
pub prueftage: u32,
/// Active targets that are extra now.
pub extra_targets: u32,
/// The highest number of extra targets at once this month, which the
/// extra-target line bills.
pub extra_peak: u32,
}
/// What the tenant used in the month of `at`.
///
/// # Errors
///
/// Returns an error if the counters or the targets cannot be read.
pub async fn month_summary(db: &Database, at: DateTime<Utc>) -> Result<MonthSummary, AgentError> {
let (month, _) = berlin_period(at);
let stored = db
.raw_collection(MONTHS)
.find_one(doc! { "_id": &month })
.await?;
let extra = mongodb::bson::to_bson(&TargetBilling::Extra)
.map_err(|e| AgentError::Other(e.to_string()))?;
let extra_targets = db
.onboarded_targets()
.count_documents(doc! { "archived_at": null, "billing": extra })
.await?;
let extra_targets = u32::try_from(extra_targets).unwrap_or(u32::MAX);
Ok(MonthSummary {
month,
pruefungen: count(stored.as_ref(), "pruefungen"),
prueftage: count(stored.as_ref(), "prueftage"),
extra_targets,
// The peak is recorded when the billing is refreshed; until then
// it is at least what is extra now.
extra_peak: count(stored.as_ref(), "extra_peak").max(extra_targets),
})
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::TimeZone;
#[test]
fn a_swap_holds_until_the_berlin_month_ends() {
let at = |y, m, d, h| {
Utc.with_ymd_and_hms(y, m, d, h, 0, 0)
.single()
.expect("valid")
};
// 1 Dec 00:00 in Berlin (CET) is 30 Nov 23:00 UTC.
assert_eq!(
end_of_berlin_month(at(2026, 11, 6, 9)),
at(2026, 11, 30, 23)
);
// December rolls into January of the next year.
assert_eq!(
end_of_berlin_month(at(2026, 12, 15, 9)),
at(2026, 12, 31, 23)
);
// 1 Aug 00:00 in Berlin (CEST) is 31 Jul 22:00 UTC.
assert_eq!(
end_of_berlin_month(at(2026, 7, 31, 21)),
at(2026, 7, 31, 22)
);
}
#[test]
fn periods_are_calendar_ones_in_berlin() {
let at = |y, m, d, h, min| {
Utc.with_ymd_and_hms(y, m, d, h, min, 0)
.single()
.expect("valid")
};
// 23:30 UTC on 31 Oct is already 1 Nov in Berlin (CET, UTC+1).
assert_eq!(
berlin_period(at(2026, 10, 31, 23, 30)),
("2026-11".to_string(), "2026-11-01".to_string())
);
// In summer (CEST, UTC+2) the day turns at 22:00 UTC.
assert_eq!(berlin_period(at(2026, 7, 14, 21, 59)).1, "2026-07-14");
assert_eq!(berlin_period(at(2026, 7, 14, 22, 0)).1, "2026-07-15");
}
#[test]
fn a_counter_reads_as_zero_when_missing() {
let stored = doc! { "pruefungen": 7_i64, "small": 3_i32, "negative": -1_i64 };
assert_eq!(count(Some(&stored), "pruefungen"), 7);
assert_eq!(count(Some(&stored), "small"), 3);
assert_eq!(count(Some(&stored), "negative"), 0);
assert_eq!(count(Some(&stored), "absent"), 0);
assert_eq!(count(None, "pruefungen"), 0);
}
#[test]
fn a_stored_target_reads_with_defaults_for_what_it_lacks() {
// Arrange
let id = ObjectId::new();
let at = mongodb::bson::DateTime::from_millis(1_700_000_000_000);
let extra = doc! { "_id": id, "created_at": at, "billing": "extra" };
let old = doc! { "_id": id };
// Act
let extra = billable(&extra);
let old = billable(&old);
// Assert
assert_eq!(
extra,
Some(BillableTarget {
id,
created_at: at.to_chrono(),
billing: TargetBilling::Extra,
choice: None,
})
);
assert_eq!(
old,
Some(BillableTarget {
id,
created_at: DateTime::<Utc>::MIN_UTC,
billing: TargetBilling::Included,
choice: None,
})
);
assert_eq!(billable(&doc! { "name": "no id" }), None);
}
}
+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");
}
}
@@ -0,0 +1,178 @@
//! Recording what a scan changes in the stored SBOM (#974): before a stage
//! replaces its part of a target's SBOM, the entries it is about to replace
//! are compared with the new ones ([`compliance_core::component_changes`])
//! and the changes are added to the scan run.
//!
//! Each stage owns its part (the code SBOM, the CODESYS libraries, the
//! firmware components) and records only that part's changes, so the run
//! adds up the changes of all of them. Best effort: a failure is logged and
//! the scan goes on, with the run's changes incomplete.
use futures_util::TryStreamExt;
use mongodb::bson::{doc, oid::ObjectId, to_bson, Document};
use compliance_core::component_changes::{diff, MAX_CHANGES};
use compliance_core::models::SbomEntry;
use crate::database::Database;
use crate::error::AgentError;
/// Add to run `scan_run_id` the changes that replacing target `repo_id`'s
/// stored entries matching `scope` with `entries` makes. The run's changes
/// start empty, so a run whose stages changed nothing says so.
///
/// # Arguments
///
/// * `db` - the tenant database
/// * `scan_run_id` - the run (hex id)
/// * `repo_id` - the target
/// * `scope` - the stage's part of the SBOM, as a filter on the entries
/// * `entries` - what the stage stores instead
pub(crate) async fn record(
db: &Database,
scan_run_id: &str,
repo_id: &str,
scope: Document,
entries: &[SbomEntry],
) {
if let Err(e) = try_record(db, scan_run_id, repo_id, scope, entries).await {
tracing::warn!(repo_id, scan_run_id, "component changes not recorded: {e}");
}
}
async fn try_record(
db: &Database,
scan_run_id: &str,
repo_id: &str,
scope: Document,
entries: &[SbomEntry],
) -> Result<(), AgentError> {
let run = ObjectId::parse_str(scan_run_id).map_err(|e| AgentError::Other(e.to_string()))?;
let mut filter = doc! { "repo_id": repo_id };
filter.extend(scope);
let stored: Vec<Document> = db
.sbom_entries()
.clone_with_type::<Document>()
.find(filter)
.projection(doc! { "package_manager": 1, "name": 1, "version": 1, "_id": 0 })
.await?
.try_collect()
.await?;
let field = |d: &Document, key: &str| d.get_str(key).unwrap_or_default().to_string();
let before: Vec<(String, String, String)> = stored
.iter()
.map(|d| {
(
field(d, "package_manager"),
field(d, "name"),
field(d, "version"),
)
})
.collect();
let before: Vec<(&str, &str, &str)> = before
.iter()
.map(|(m, n, v)| (m.as_str(), n.as_str(), v.as_str()))
.collect();
let after: Vec<(&str, &str, &str)> = entries
.iter()
.map(|e| {
(
e.package_manager.as_str(),
e.name.as_str(),
e.version.as_str(),
)
})
.collect();
let changes = to_bson(&diff(&before, &after)).map_err(|e| AgentError::Other(e.to_string()))?;
let max = i64::try_from(MAX_CHANGES).unwrap_or(i64::MAX);
// One pipeline update: the run's list so far (none yet: empty) and this
// stage's changes, at most the cap.
db.scan_runs()
.update_one(
doc! { "_id": run },
vec![doc! { "$set": { "component_changes": { "$slice": [
{ "$concatArrays": [{ "$ifNull": ["$component_changes", []] }, changes] },
max,
] } } }],
)
.await?;
Ok(())
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use compliance_core::component_changes::ComponentChangeKind;
use compliance_core::models::{ScanRun, ScanTrigger};
fn entry(manager: &str, name: &str, version: &str) -> SbomEntry {
SbomEntry::new("t1".into(), name.into(), version.into(), manager.into())
}
#[tokio::test]
async fn each_stage_adds_the_changes_of_its_own_part() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!("cchg_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP component_changes: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id("component-changes").await.unwrap();
// Arrange: a stored SBOM with a code and a firmware part.
let stored = [
entry("npm", "lodash", "4.17.20"),
entry("npm", "left-pad", "1.3.0"),
entry("firmware", "busybox", "1.36.0"),
];
db.sbom_entries().insert_many(&stored).await.unwrap();
let run_id = db
.scan_runs()
.insert_one(ScanRun::new("t1".into(), ScanTrigger::Manual))
.await
.unwrap()
.inserted_id
.as_object_id()
.unwrap()
.to_hex();
// Act: the code stage replaces its part; the firmware stage keeps
// its own unchanged.
record(
&db,
&run_id,
"t1",
doc! { "package_manager": { "$nin": ["firmware"] } },
&[entry("npm", "lodash", "4.17.21")],
)
.await;
record(
&db,
&run_id,
"t1",
doc! { "package_manager": { "$in": ["firmware"] } },
&[entry("firmware", "busybox", "1.36.0")],
)
.await;
// Assert
let run = db
.scan_runs()
.find_one(doc! { "_id": ObjectId::parse_str(&run_id).unwrap() })
.await
.unwrap()
.unwrap();
let changes = run.component_changes.expect("recorded");
let read: Vec<(ComponentChangeKind, &str)> =
changes.iter().map(|c| (c.kind, c.name.as_str())).collect();
assert_eq!(
read,
[
(ComponentChangeKind::Removed, "left-pad"),
(ComponentChangeKind::Updated, "lodash")
]
);
pool.drop_tenant("component-changes").await.ok();
}
}
+72 -16
View File
@@ -7,6 +7,12 @@
//! updated or removed), the issue is closed with a comment; when it comes back,
//! it is reopened.
//!
//! An issue a person closed in Gitea (#953) stays closed while the scan still
//! finds its CVE: closing it was that person's call, and no VEX statement is
//! made from it (one needs a justification). Once a complete scan no longer
//! finds the CVE, that close is forgotten, so a CVE that comes back reopens
//! the issue as usual.
//!
//! A CVE a VEX statement settles (`not_affected` or `fixed`, by a person, the
//! scan or an imported VEX document) gets no issue. Its open issue is closed
//! with a comment naming the status and the reason when `ISSUE_AUTOCLOSE` is
@@ -24,6 +30,7 @@ use std::collections::{BTreeMap, HashMap};
use mongodb::bson::doc;
use compliance_core::config::IssueAutoclose;
use compliance_core::models::issue::cve_issue_prefix;
use compliance_core::models::notification::{parse_severity, NotificationSeverity};
use compliance_core::models::{CveAlert, IssueStatus, TrackerIssue, VexAssessment, VexStatus};
@@ -95,7 +102,12 @@ pub(crate) struct CveIssueCounts {
/// target, package and CVE, so another version of the same package does not
/// open a second issue.
fn issue_key(target_id: &str, alert: &CveAlert) -> String {
format!("cve:{target_id}:{}:{}", alert.affected_package, alert.cve())
format!(
"{}{}:{}",
cve_issue_prefix(target_id),
alert.affected_package,
alert.cve()
)
}
/// A severity as the `severity:` labels name it.
@@ -163,7 +175,7 @@ pub(crate) async fn sync_cve_issues(
alerts: &[CveAlert],
complete: bool,
) -> Result<CveIssueCounts, AgentError> {
let prefix = format!("cve:{}:", target.target_id);
let prefix = cve_issue_prefix(target.target_id);
let mut existing: HashMap<String, TrackerIssue> = HashMap::new();
let mut cursor = target
.db
@@ -189,7 +201,9 @@ pub(crate) async fn sync_cve_issues(
.filter(|(_, a)| !a.is_resolved_by_vex() && issue_worthy(a, target.epss_percentile))
{
match existing.get(key) {
Some(issue) if is_closed(&issue.status) => {
// A person closed it in Gitea while the CVE is unchanged.
Some(issue) if issue.closed_in_tracker.is_some() => {}
Some(issue) if issue.status.is_closed() => {
let comment = "**Prüfwerk:** Bei der Prüfung erneut gefunden, daher wieder geöffnet.\n\nFound again by the scan, so reopened.";
if set_state(target, issue, comment, "open").await {
record(target.db, issue, IssueStatus::Open).await?;
@@ -210,7 +224,7 @@ pub(crate) async fn sync_cve_issues(
.iter()
.filter_map(|(key, alert)| {
let vex = alert.vex.as_ref().filter(|_| alert.is_resolved_by_vex())?;
let issue = existing.get(key).filter(|i| !is_closed(&i.status))?;
let issue = existing.get(key).filter(|i| !i.status.is_closed())?;
Some((issue, vex))
})
.collect();
@@ -218,7 +232,14 @@ pub(crate) async fn sync_cve_issues(
if complete {
for (key, issue) in &existing {
if present.contains_key(key) || is_closed(&issue.status) {
if present.contains_key(key) {
continue;
}
if issue.status.is_closed() {
// Gone now: if it comes back, it is found again.
if issue.closed_in_tracker.is_some() {
record(target.db, issue, IssueStatus::Closed).await?;
}
continue;
}
let comment = "**Prüfwerk:** Die Prüfung findet diese Schwachstelle nicht mehr: Die Abhängigkeit wurde aktualisiert oder entfernt.\n\nThe scan no longer finds this vulnerability: the dependency was updated or removed.";
@@ -311,11 +332,6 @@ fn vex_comment(vex: &VexAssessment) -> String {
)
}
/// Whether an issue is closed.
fn is_closed(status: &IssueStatus) -> bool {
matches!(status, IssueStatus::Closed | IssueStatus::Resolved)
}
/// The Prüfwerk label ids of a Gitea repository, created where missing;
/// `None` for other trackers or when Gitea refuses.
async fn gitea_label_ids(target: &CveIssueTarget<'_>) -> Option<HashMap<String, i64>> {
@@ -498,12 +514,10 @@ async fn record(
let Some(id) = issue.id else {
return Ok(());
};
let status = mongodb::bson::to_bson(&status).map_err(|e| AgentError::Other(e.to_string()))?;
let update = crate::pipeline::issue_sync::issue_state_update(&status, None)
.map_err(|e| AgentError::Other(e.to_string()))?;
db.tracker_issues()
.update_one(
doc! { "_id": id },
doc! { "$set": { "status": status, "updated_at": mongodb::bson::DateTime::now() } },
)
.update_one(doc! { "_id": id }, update)
.await?;
Ok(())
}
@@ -784,7 +798,9 @@ mod tests {
// It comes back: reopened, not opened twice.
assert_eq!(
sync_cve_issues(&target, &[okhttp], true).await.unwrap(),
sync_cve_issues(&target, std::slice::from_ref(&okhttp), true)
.await
.unwrap(),
CveIssueCounts {
reopened: 1,
..Default::default()
@@ -792,6 +808,46 @@ mod tests {
);
assert_eq!(calls.lock().unwrap().last().unwrap(), "state 100: \"open\"");
// A person closes it in Gitea (#953): the scan that still finds the
// CVE leaves it closed and sends nothing.
let key = format!("cve:target-1:okhttp:{}", okhttp.cve());
db.tracker_issues()
.update_one(
doc! { "finding_id": &key },
doc! { "$set": { "status": "closed", "closed_in_tracker": "dev-anna" } },
)
.await
.unwrap();
let sent = calls.lock().unwrap().len();
assert_eq!(
sync_cve_issues(&target, std::slice::from_ref(&okhttp), true)
.await
.unwrap(),
CveIssueCounts::default()
);
assert_eq!(calls.lock().unwrap().len(), sent);
// Updated away, the close is forgotten; back again, it reopens.
sync_cve_issues(&target, &[], true).await.unwrap();
let stored = db
.tracker_issues()
.find_one(doc! { "finding_id": &key })
.await
.unwrap()
.unwrap();
assert_eq!(
(stored.status, stored.closed_in_tracker),
(IssueStatus::Closed, None)
);
assert_eq!(calls.lock().unwrap().len(), sent, "already closed");
assert_eq!(
sync_cve_issues(&target, &[okhttp], true)
.await
.unwrap()
.reopened,
1
);
pool.drop_tenant("cve-issues").await.ok();
}
+3 -21
View File
@@ -145,33 +145,15 @@ pub(crate) fn relative(root: &Path, path: &Path) -> String {
}
/// The text of a file that may start with a byte-order mark (Visual Studio
/// writes UTF-8 with BOM, older tools UTF-16). `None` for a file too large or
/// writes UTF-8 with BOM, older tools UTF-16) or be Windows-1252, decoded by
/// [`compliance_core::encoding::read_source`]. `None` for a file too large or
/// unreadable.
pub(crate) fn read_text(path: &Path) -> Option<String> {
let meta = std::fs::metadata(path).ok()?;
if meta.len() > MAX_FILE_BYTES {
return None;
}
let bytes = std::fs::read(path).ok()?;
let utf16 = |bytes: &[u8], le: bool| {
let units: Vec<u16> = bytes
.chunks_exact(2)
.map(|c| {
if le {
u16::from_le_bytes([c[0], c[1]])
} else {
u16::from_be_bytes([c[0], c[1]])
}
})
.collect();
String::from_utf16(&units).ok()
};
match bytes.as_slice() {
[0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8(rest.to_vec()).ok(),
[0xFF, 0xFE, rest @ ..] => utf16(rest, true),
[0xFE, 0xFF, rest @ ..] => utf16(rest, false),
_ => String::from_utf8(bytes).ok(),
}
compliance_core::encoding::read_source(path).ok()
}
/// Parse XML the way project and configuration files need: a DTD is allowed
@@ -147,7 +147,8 @@ pub fn detect(root: &Path, repo_id: &str) -> Vec<SbomEntry> {
}) {
let small = entry.metadata().is_ok_and(|m| m.len() <= MAX_HEADER_BYTES);
let Some(text) = small
.then(|| std::fs::read_to_string(entry.path()).ok())
// Vendor SDK headers are often Windows-1252 (a "©" in the banner).
.then(|| compliance_core::encoding::read_source(entry.path()).ok())
.flatten()
else {
continue;
+57 -13
View File
@@ -782,12 +782,24 @@ impl RunFindings {
Ok(closed)
}
/// Close the undecided findings of `scanner` on target `target_id` whose
/// file lies in the excluded paths or the test data this run left out
/// 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. For a stage that stores its findings without this object (the
/// PLC analysis), so nothing it no longer sees is closed as fixed; only
/// what was left out.
/// 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
///
@@ -800,20 +812,23 @@ impl RunFindings {
&mut self,
db: &Database,
target_id: &str,
scanner: &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(doc! {
"repo_id": target_id,
"scanner": scanner,
"status": { "$in": UNDECIDED.to_vec() },
})
.projection(doc! { "file_path": 1 })
.find(filter)
.projection(doc! { "fingerprint": 1, "file_path": 1 })
.await?
.try_collect()
.await?;
@@ -822,6 +837,14 @@ impl RunFindings {
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) {
@@ -950,7 +973,8 @@ fn content_fingerprints(tree: &Path, findings: &mut [Finding]) {
continue;
};
let lines = files.entry(path.clone()).or_insert_with(|| {
std::fs::read_to_string(tree.join(&path))
// Decoded like the scanners read it: UTF-8, UTF-16, Windows-1252.
compliance_core::encoding::read_source(&tree.join(&path))
.ok()
.map(|text| text.lines().map(normalised).collect())
});
@@ -1226,6 +1250,26 @@ mod tests {
assert!(missing[0].legacy_fingerprints.is_empty());
}
#[test]
fn a_windows_1252_file_is_keyed_by_content_as_its_utf8_version_is() {
let dir = std::env::temp_dir().join(format!("cs-fp-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
// "größe" as Windows-1252 writes it (0xF6 0xDF), then the same file
// saved again as UTF-8.
std::fs::write(dir.join("a.c"), b"int x;\nint gr\xF6\xDFe = read();\n").unwrap();
let ansi = keyed(&dir, vec![at("a.c", 2)]);
std::fs::write(dir.join("a.c"), "int x;\nint größe = read();\n").unwrap();
let utf8 = keyed(&dir, vec![at("a.c", 2)]);
let _ = std::fs::remove_dir_all(&dir);
// Keyed by content, with the line-based key kept to adopt the row
// stored under it while the file could not be read.
let line_key = crate::pipeline::dedup::compute_fingerprint(&["repo-1", "rule", "a.c", "2"]);
assert_eq!(ansi[0].legacy_fingerprints, std::slice::from_ref(&line_key));
assert_ne!(ansi[0].fingerprint, line_key);
// Re-saving the file in another encoding keeps the key.
assert_eq!(ansi[0].fingerprint, utf8[0].fingerprint);
}
#[test]
fn a_scanners_own_content_and_groups_are_respected() {
let dir = std::env::temp_dir().join(format!("cs-fp-{}", uuid::Uuid::new_v4()));
+46 -1
View File
@@ -495,7 +495,18 @@ impl GitOps {
_ => "",
};
let content = std::str::from_utf8(line.content()).unwrap_or("");
// A diff line is UTF-8 or, from an older tool, Windows-1252
// (single-byte, so a line decodes on its own). UTF-16 files are
// binary to git and have no lines here.
let bytes = line.content();
let decoded;
let content = match std::str::from_utf8(bytes) {
Ok(text) => text,
Err(_) => {
decoded = compliance_core::encoding::decode(bytes.to_vec()).unwrap_or_default();
decoded.as_str()
}
};
diff_file.hunks.push_str(prefix);
diff_file.hunks.push_str(content);
@@ -919,4 +930,38 @@ mod tests {
.expect_err("private origin must be refused");
assert!(err.to_string().contains("10.0.0.5"), "{err}");
}
#[test]
fn a_windows_1252_line_shows_in_the_diff() {
// Arrange: a file committed, then a line with "für" as Windows-1252
// writes it (0xFC) added in a second commit.
let dir = source_repo();
let repo = git2::Repository::open(&dir).unwrap();
let old = repo.head().unwrap().peel_to_commit().unwrap();
std::fs::write(
dir.join("README.md"),
b"pump controller\n// f\xFCr Halle 2\n",
)
.unwrap();
let mut index = repo.index().unwrap();
index.add_path(Path::new("README.md")).unwrap();
index.write().unwrap();
let tree = repo.find_tree(index.write_tree().unwrap()).unwrap();
let sig = git2::Signature::now("t", "t@example.com").unwrap();
let new = repo
.commit(Some("HEAD"), &sig, &sig, "note", &tree, &[&old])
.unwrap();
// Act
let diff = GitOps::get_diff_content(&dir, &old.id().to_string(), &new.to_string()).unwrap();
std::fs::remove_dir_all(&dir).unwrap();
// Assert: the added line is there, decoded.
assert_eq!(diff.len(), 1);
assert!(
diff[0].hunks.contains("+// für Halle 2"),
"{}",
diff[0].hunks
);
}
}
+56 -13
View File
@@ -1,28 +1,71 @@
use std::path::Path;
use compliance_core::error::CoreError;
use compliance_core::models::graph::GraphBuildRun;
use compliance_core::models::Finding;
use compliance_graph::graph::engine::CodeGraph;
use super::orchestrator::{GraphContext, PipelineOrchestrator};
use super::plc::PlcFile;
use crate::error::AgentError;
/// The most nodes a graph build parses.
const GRAPH_MAX_NODES: u32 = 50_000;
/// What a code graph is built from.
pub(crate) enum GraphSource<'a> {
/// The source files of a checked-out tree, by the graph crate's parsers.
Tree(&'a Path),
/// The POUs of a PLC target, read from every one of its PLC source trees.
Plc(&'a [PlcFile]),
}
/// Build a code graph and detect its communities.
///
/// # Errors
///
/// Returns the graph engine's error when a tree can't be read or the graph
/// can't be assembled.
pub(crate) fn build_graph(
source: GraphSource<'_>,
repo_id: &str,
graph_build_id: &str,
) -> Result<(CodeGraph, GraphBuildRun), CoreError> {
let engine = compliance_graph::GraphEngine::new(GRAPH_MAX_NODES);
match source {
GraphSource::Tree(path) => engine.build_graph(path, repo_id, graph_build_id),
GraphSource::Plc(files) => engine.assemble(
super::plc::graph::parse_output(files, repo_id, graph_build_id),
repo_id,
),
}
}
impl PipelineOrchestrator {
/// Build the code knowledge graph for a repo and compute impact analyses
/// Build the code knowledge graph for a repo, store it in place of the
/// previous one and compute the impact of each finding.
pub(super) async fn build_code_graph(
&self,
repo_path: &std::path::Path,
source: GraphSource<'_>,
repo_id: &str,
findings: &[Finding],
) -> Result<GraphContext, AgentError> {
let graph_build_id = uuid::Uuid::new_v4().to_string();
let engine = compliance_graph::GraphEngine::new(50_000);
let built = build_graph(source, repo_id, &graph_build_id)
.map_err(|e| AgentError::Other(format!("Graph build error: {e}")))?;
self.store_code_graph(built, repo_id, &graph_build_id, findings)
.await
}
let (mut code_graph, build_run) =
engine
.build_graph(repo_path, repo_id, &graph_build_id)
.map_err(|e| AgentError::Other(format!("Graph build error: {e}")))?;
// Apply community detection
compliance_graph::graph::community::apply_communities(&mut code_graph);
// Store graph in MongoDB
/// Replace the repo's stored graph with `built`, and store the impact of
/// each finding that has a file.
async fn store_code_graph(
&self,
(code_graph, build_run): (CodeGraph, GraphBuildRun),
repo_id: &str,
graph_build_id: &str,
findings: &[Finding],
) -> Result<GraphContext, AgentError> {
let store = compliance_graph::graph::persistence::GraphStore::new(self.db.inner());
store
.delete_repo_graph(repo_id)
@@ -42,7 +85,7 @@ impl PipelineOrchestrator {
let impact = analyzer.analyze(
repo_id,
&finding.fingerprint,
&graph_build_id,
graph_build_id,
file_path,
finding.line_number,
);
@@ -0,0 +1,472 @@
//! A person closing or reopening a Prüfwerk issue in Gitea, carried back to
//! the finding (#953).
//!
//! * Closed: an undecided finding becomes resolved, recorded as "closed in the
//! ticket" with the Gitea user's login. The next scan confirms it (not found:
//! it stays resolved) or reopens finding and issue as for any resolved
//! finding found again. A finding a person had already decided keeps that
//! decision; only the issue's state is recorded.
//! * Reopened: a decided finding becomes undecided again (`open`).
//! * CVE issues: only the issue's state and who closed it are recorded. No
//! VEX statement is set, since one needs a justification; the scan leaves
//! the issue closed while the CVE is still there
//! ([`crate::pipeline::cve_issues`]).
//!
//! Nothing here calls the tracker: the issue already is in the state the
//! event (or the poll, [`crate::pipeline::issue_poll`]) reports, and the issue record says so, so the status sync
//! ([`crate::pipeline::issue_sync`]) has nothing to carry over either.
use futures_util::TryStreamExt;
use mongodb::bson::{doc, oid::ObjectId, to_bson, Bson, Document};
use compliance_core::models::{
FindingStatus, IssueStatus, StatusChange, TrackerChangeKind, TrackerIssue, TrackerType,
};
use crate::database::Database;
use crate::error::AgentError;
use crate::git_source::events::{IssueChange, IssueEvent};
use crate::pipeline::issue_creation::ISSUE_STATUSES;
use crate::pipeline::issue_sync::issue_state_update;
/// What carrying an issue event back did, for the delivery record.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum BackSynced {
/// The issue is not one Prüfwerk opened in this repository.
NotOurs,
/// The finding's status changed.
Finding,
/// Only the issue's state was recorded: the finding already had a
/// matching status (a person had decided it, or it was undecided).
IssueOnly,
/// A CVE issue's state was recorded.
Cve,
}
impl BackSynced {
/// The delivery record's detail for this result of `change`.
pub(crate) fn detail(self, change: IssueChange) -> &'static str {
match (self, change) {
(Self::NotOurs, _) => "issue not opened by Prüfwerk",
(Self::Finding, IssueChange::Closed) => "finding resolved: issue closed in Gitea",
(Self::Finding, IssueChange::Reopened) => "finding reopened: issue reopened in Gitea",
(Self::IssueOnly, _) => "issue state recorded; the finding's status already matched",
(Self::Cve, _) => "CVE issue state recorded",
}
}
}
/// The finding statuses `change` moves a finding away from: the undecided
/// ones ([`ISSUE_STATUSES`]) for a close, every other for a reopen.
fn statuses_changed_by(change: IssueChange) -> Document {
let undecided: Vec<String> = ISSUE_STATUSES.iter().map(ToString::to_string).collect();
match change {
IssueChange::Closed => doc! { "$in": undecided },
IssueChange::Reopened => doc! { "$nin": undecided },
}
}
/// The status a finding moves to and how its history records `change`.
fn new_status(change: IssueChange) -> (FindingStatus, TrackerChangeKind) {
match change {
IssueChange::Closed => (FindingStatus::Resolved, TrackerChangeKind::ClosedInTracker),
IssueChange::Reopened => (FindingStatus::Open, TrackerChangeKind::ReopenedInTracker),
}
}
/// Carry `event` back for the managed target `target_id`.
///
/// # Arguments
///
/// * `db` - the tenant database
/// * `target_id` - the target of the event's repository
/// * `event` - the close or reopen, by someone other than Prüfwerk's bot
///
/// # Returns
///
/// What was changed.
///
/// # Errors
///
/// A database error.
pub(crate) async fn apply(
db: &Database,
target_id: &str,
event: &IssueEvent,
) -> Result<BackSynced, AgentError> {
apply_change(db, target_id, event.number, event.change, &event.sender).await
}
/// Carry a close or reopen of issue `number` back for target `target_id`,
/// however it was learnt: a webhook delivery ([`apply`]) or the poll
/// ([`crate::pipeline::issue_poll`]).
///
/// # Arguments
///
/// * `db` - the tenant database
/// * `target_id` - the target of the issue's repository
/// * `number` - the issue number in that repository
/// * `change` - closed or reopened
/// * `sender` - the login of the person who did it, not Prüfwerk's bot
///
/// # Returns
///
/// What was changed.
///
/// # Errors
///
/// A database error.
pub(crate) async fn apply_change(
db: &Database,
target_id: &str,
number: i64,
change: IssueChange,
sender: &str,
) -> Result<BackSynced, AgentError> {
let Some(issue) = find_issue(db, target_id, number).await? else {
return Ok(BackSynced::NotOurs);
};
let (status, closed_by) = match change {
IssueChange::Closed => (IssueStatus::Closed, Some(sender)),
IssueChange::Reopened => (IssueStatus::Open, None),
};
// The issue first: once it reads closed, a status sync running meanwhile
// finds nothing to close (and no comment to write) for the finding.
if let Some(id) = issue.id {
let update =
issue_state_update(&status, closed_by).map_err(|e| AgentError::Other(e.to_string()))?;
let mut filter = doc! { "_id": id };
if closed_by.is_some() {
// A record that already reads closed was closed by Prüfwerk (by
// a bot user other than the issue's author, after a token
// change): there is no person's close to keep.
filter.insert("status", doc! { "$nin": ["closed", "resolved"] });
}
db.tracker_issues().update_one(filter, update).await?;
}
if issue.finding_id.starts_with("cve:") {
return Ok(BackSynced::Cve);
}
let Ok(finding_id) = ObjectId::parse_str(&issue.finding_id) else {
return Ok(BackSynced::IssueOnly);
};
let (new, kind) = new_status(change);
let history = StatusChange::by_tracker(new.clone(), kind, sender);
let to_bson_err = |e: mongodb::bson::ser::Error| AgentError::Other(e.to_string());
// One conditional update, like the scan's status changes: a decision a
// person makes meanwhile is not overwritten.
let res = db
.findings()
.update_one(
doc! { "_id": finding_id, "status": statuses_changed_by(change) },
doc! {
"$set": {
"status": to_bson(&new).map_err(to_bson_err)?,
"updated_at": mongodb::bson::DateTime::now(),
},
"$push": { "status_history": to_bson(&history).map_err(to_bson_err)? },
},
)
.await?;
Ok(if res.modified_count > 0 {
BackSynced::Finding
} else {
BackSynced::IssueOnly
})
}
/// The issue Prüfwerk opened as number `number` in the repository of target
/// `target_id`. Issue numbers repeat across repositories, so a record counts
/// only if it belongs to the target: a CVE issue by its key, a finding issue
/// by its finding.
async fn find_issue(
db: &Database,
target_id: &str,
number: i64,
) -> Result<Option<TrackerIssue>, AgentError> {
let tracker = to_bson(&TrackerType::Gitea).map_err(|e| AgentError::Other(e.to_string()))?;
let candidates: Vec<TrackerIssue> = db
.tracker_issues()
.find(doc! { "external_id": number.to_string(), "tracker_type": tracker })
.await?
.try_collect()
.await?;
let cve_prefix = format!("cve:{target_id}:");
if let Some(cve) = candidates
.iter()
.find(|i| i.finding_id.starts_with(&cve_prefix))
{
return Ok(Some(cve.clone()));
}
let ids: Vec<Bson> = candidates
.iter()
.filter_map(|i| ObjectId::parse_str(&i.finding_id).ok())
.map(Bson::ObjectId)
.collect();
if ids.is_empty() {
return Ok(None);
}
let Some(row) = db
.findings()
.clone_with_type::<Document>()
.find_one(doc! { "_id": { "$in": ids }, "repo_id": target_id })
.projection(doc! { "_id": 1 })
.await?
else {
return Ok(None);
};
let Ok(id) = row.get_object_id("_id") else {
return Ok(None);
};
let id = id.to_hex();
Ok(candidates.into_iter().find(|i| i.finding_id == id))
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use compliance_core::models::{Finding, ScanType, Severity};
use crate::git_source::gitea::GiteaRepo;
#[test]
fn a_close_resolves_undecided_findings_and_a_reopen_reopens_decided_ones() {
assert_eq!(
new_status(IssueChange::Closed),
(FindingStatus::Resolved, TrackerChangeKind::ClosedInTracker)
);
assert_eq!(
new_status(IssueChange::Reopened),
(FindingStatus::Open, TrackerChangeKind::ReopenedInTracker)
);
let closed = statuses_changed_by(IssueChange::Closed);
let moved: Vec<&str> = closed
.get_array("$in")
.unwrap()
.iter()
.filter_map(Bson::as_str)
.collect();
assert_eq!(moved, ["open", "triaged", "needs_review"]);
assert!(statuses_changed_by(IssueChange::Reopened).contains_key("$nin"));
}
#[test]
fn the_delivery_record_says_what_happened() {
assert_eq!(
BackSynced::Finding.detail(IssueChange::Closed),
"finding resolved: issue closed in Gitea"
);
assert_eq!(
BackSynced::NotOurs.detail(IssueChange::Reopened),
"issue not opened by Prüfwerk"
);
}
fn event(change: IssueChange) -> IssueEvent {
let repo: GiteaRepo = serde_json::from_value(serde_json::json!({
"id": 7, "name": "fw", "full_name": "kunde/fw",
}))
.unwrap();
IssueEvent {
repo,
number: 12,
change,
sender: "dev-anna".into(),
}
}
#[tokio::test]
async fn closing_and_reopening_in_gitea_moves_the_finding() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"ibsync_{}",
&uuid::Uuid::new_v4().simple().to_string()[..10]
);
let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP issue_backsync: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id("issue-backsync").await.unwrap();
let target = ObjectId::new().to_hex();
let other_target = ObjectId::new().to_hex();
// Arrange: issue #12 of this target's finding, and #12 of another
// repository's finding (numbers repeat across repositories).
let insert = |repo_id: String, status: FindingStatus| {
let db = db.clone();
async move {
let mut f = Finding::new(
repo_id,
format!("fp-{}", ObjectId::new()),
"semgrep".into(),
ScanType::Sast,
"strcpy".into(),
"d".into(),
Severity::High,
);
f.status = status;
let id = db
.findings()
.insert_one(&f)
.await
.unwrap()
.inserted_id
.as_object_id()
.unwrap();
let issue = TrackerIssue::new(
id.to_hex(),
TrackerType::Gitea,
"12".into(),
"https://kunde.code.breakpilot.com/kunde/fw/issues/12".into(),
"strcpy".into(),
);
db.tracker_issues().insert_one(&issue).await.unwrap();
id
}
};
let other = insert(other_target, FindingStatus::Open).await;
let ours = insert(target.clone(), FindingStatus::NeedsReview).await;
let finding = |id: ObjectId| {
let db = db.clone();
async move {
db.findings()
.find_one(doc! { "_id": id })
.await
.unwrap()
.unwrap()
}
};
let issue_of = |id: ObjectId| {
let db = db.clone();
async move {
db.tracker_issues()
.find_one(doc! { "finding_id": id.to_hex() })
.await
.unwrap()
.unwrap()
}
};
// Act: closed in Gitea.
let done = apply(&db, &target, &event(IssueChange::Closed))
.await
.unwrap();
// Assert: resolved, recorded as closed in the ticket by the user.
assert_eq!(done, BackSynced::Finding);
let f = finding(ours).await;
assert_eq!(f.status, FindingStatus::Resolved);
let last = f.status_history.last().unwrap();
assert_eq!(last.tracker, Some(TrackerChangeKind::ClosedInTracker));
assert_eq!(last.by_name.as_deref(), Some("dev-anna"));
let issue = issue_of(ours).await;
assert_eq!(issue.status, IssueStatus::Closed);
assert_eq!(issue.closed_in_tracker.as_deref(), Some("dev-anna"));
// The other repository's #12 is untouched.
assert_eq!(finding(other).await.status, FindingStatus::Open);
assert_eq!(issue_of(other).await.status, IssueStatus::Open);
// The same delivery again changes nothing more.
let again = apply(&db, &target, &event(IssueChange::Closed))
.await
.unwrap();
assert_eq!(again, BackSynced::IssueOnly);
assert_eq!(finding(ours).await.status_history.len(), 1);
// Reopened in Gitea: undecided again, the closer forgotten.
let done = apply(&db, &target, &event(IssueChange::Reopened))
.await
.unwrap();
assert_eq!(done, BackSynced::Finding);
let f = finding(ours).await;
assert_eq!(f.status, FindingStatus::Open);
assert_eq!(
f.status_history.last().unwrap().tracker,
Some(TrackerChangeKind::ReopenedInTracker)
);
let issue = issue_of(ours).await;
assert_eq!(issue.status, IssueStatus::Open);
assert!(issue.closed_in_tracker.is_none());
// A decision a person made in Prüfwerk is kept on a close.
db.findings()
.update_one(
doc! { "_id": ours },
doc! { "$set": { "status": "accepted_risk" } },
)
.await
.unwrap();
db.tracker_issues()
.update_one(
doc! { "finding_id": ours.to_hex() },
doc! { "$set": { "status": "open" } },
)
.await
.unwrap();
let done = apply(&db, &target, &event(IssueChange::Closed))
.await
.unwrap();
assert_eq!(done, BackSynced::IssueOnly);
assert_eq!(finding(ours).await.status, FindingStatus::AcceptedRisk);
assert_eq!(issue_of(ours).await.status, IssueStatus::Closed);
// An issue Prüfwerk did not open (no record) is not ours.
let mut stranger = event(IssueChange::Closed);
stranger.number = 99;
assert_eq!(
apply(&db, &target, &stranger).await.unwrap(),
BackSynced::NotOurs
);
// A CVE issue: only the record, with who closed it.
let key = format!("cve:{target}:openssl:CVE-2024-0001");
let mut cve = TrackerIssue::new(
key.clone(),
TrackerType::Gitea,
"30".into(),
"https://kunde.code.breakpilot.com/kunde/fw/issues/30".into(),
"[CVE] openssl@3.0.0: CVE-2024-0001".into(),
);
cve.status = IssueStatus::Open;
db.tracker_issues().insert_one(&cve).await.unwrap();
let mut closed = event(IssueChange::Closed);
closed.number = 30;
assert_eq!(apply(&db, &target, &closed).await.unwrap(), BackSynced::Cve);
let stored = db
.tracker_issues()
.find_one(doc! { "finding_id": &key })
.await
.unwrap()
.unwrap();
assert_eq!(stored.status, IssueStatus::Closed);
assert_eq!(stored.closed_in_tracker.as_deref(), Some("dev-anna"));
// Prüfwerk closed it already (the event comes from a bot user other
// than the issue's author, after a token change): no person's close
// is recorded, so a CVE that comes back still reopens it.
let key = format!("cve:{target}:zlib:CVE-2024-0002");
let mut cve = TrackerIssue::new(
key.clone(),
TrackerType::Gitea,
"31".into(),
"https://kunde.code.breakpilot.com/kunde/fw/issues/31".into(),
"[CVE] zlib@1.2.0: CVE-2024-0002".into(),
);
cve.status = IssueStatus::Closed;
db.tracker_issues().insert_one(&cve).await.unwrap();
closed.number = 31;
closed.sender = "pruefwerk-neu".into();
apply(&db, &target, &closed).await.unwrap();
let stored = db
.tracker_issues()
.find_one(doc! { "finding_id": &key })
.await
.unwrap()
.unwrap();
assert!(stored.closed_in_tracker.is_none());
pool.drop_tenant("issue-backsync").await.ok();
}
}
@@ -298,6 +298,7 @@ mod tests {
body: Some(format_issue_body(finding)),
html_url: format!("https://gitea.invalid/o/r/issues/{number}"),
state: "open".into(),
user: None,
}
}
+27 -17
View File
@@ -511,9 +511,14 @@ impl IssueSink<'_> {
finding: &Finding,
title: &str,
) -> Result<TrackerIssue, CoreError> {
let finding_id = finding
.id
.as_ref()
.map(|id| id.to_hex())
.unwrap_or_default();
let mut body = format_issue_body(finding);
if self.managed {
if let Some(link) = finding_link(&self.dashboard, self.repo_id) {
if let Some(link) = finding_link(&self.dashboard, &finding_id) {
body.push_str(&format!(
"\n[Open in Prüfwerk / In Prüfwerk öffnen]({link})"
));
@@ -540,11 +545,7 @@ impl IssueSink<'_> {
.await?
}
};
issue.finding_id = finding
.id
.as_ref()
.map(|id| id.to_hex())
.unwrap_or_default();
issue.finding_id = finding_id;
self.record(finding, &issue).await;
Ok(issue)
}
@@ -706,13 +707,18 @@ fn cra_requirements(control_refs: &[String]) -> Vec<String> {
.collect()
}
/// The finding list of a target in the Prüfwerk dashboard; `None` unless the
/// dashboard's public origin is an https URL.
fn finding_link(dashboard: &str, target_id: &str) -> Option<String> {
/// A finding's page in the Prüfwerk dashboard (#947), where its status is
/// set; a group (#464) has its own id and so its own page. `None` unless the
/// dashboard's public origin is an https URL and the finding has an id.
///
/// # Arguments
///
/// * `dashboard` - the dashboard's public origin (`DASHBOARD_PUBLIC_URL`)
/// * `finding_id` - the finding's id as hex, empty when it has none
fn finding_link(dashboard: &str, finding_id: &str) -> Option<String> {
let dashboard = dashboard.trim_end_matches('/');
dashboard
.starts_with("https://")
.then(|| format!("{dashboard}/findings?target={target_id}"))
(dashboard.starts_with("https://") && !finding_id.is_empty())
.then(|| format!("{dashboard}/findings/{finding_id}"))
}
/// The ids of `names` among the ensured labels; a name without an id is left
@@ -813,6 +819,7 @@ mod tests {
body: body.map(str::to_string),
html_url: format!("https://gitea.invalid/o/r/issues/{number}"),
state: "open".into(),
user: None,
}
}
@@ -924,13 +931,16 @@ mod tests {
}
#[test]
fn links_only_to_an_https_dashboard() {
fn links_the_finding_page_of_an_https_dashboard() {
let id = "6560a1b2c3d4e5f601234567";
assert_eq!(
finding_link("https://pruefwerk.breakpilot.com/", "t1").as_deref(),
Some("https://pruefwerk.breakpilot.com/findings?target=t1")
finding_link("https://pruefwerk.breakpilot.com/", id).as_deref(),
Some("https://pruefwerk.breakpilot.com/findings/6560a1b2c3d4e5f601234567")
);
assert_eq!(finding_link("", "t1"), None);
assert_eq!(finding_link("http://x", "t1"), None);
assert_eq!(finding_link("", id), None);
assert_eq!(finding_link("http://x", id), None);
// a finding without an id has no page to link
assert_eq!(finding_link("https://pruefwerk.breakpilot.com", ""), None);
}
#[test]
+455
View File
@@ -0,0 +1,455 @@
//! Issues closed or reopened in Gitea, learnt by polling (#953).
//!
//! The back-sync ([`super::issue_backsync`]) first came from the managed git
//! source's organisation webhook. Most targets have no such webhook: they are
//! repositories with a Gitea issue tracker. So at every sync interval the poll
//! lists the issues of each target that has Prüfwerk issues (one listing per
//! repository, as a scan makes), compares their state with Prüfwerk's records
//! and, for each that differs, reads from the issue's timeline who closed or
//! reopened it. A person's change is carried back as a webhook delivery is;
//! Prüfwerk's own (its bot user opened the issue) is left alone. Where a
//! webhook delivered the change already, the records match and the poll has
//! nothing to do.
use std::collections::HashMap;
use futures_util::TryStreamExt;
use mongodb::bson::{doc, Bson};
use compliance_core::models::issue::cve_issue_prefix;
use compliance_core::models::{OnboardedTarget, TrackerIssue, TrackerType};
use compliance_core::{AgentConfig, NetGuard};
use crate::agent::ComplianceAgent;
use crate::database::Database;
use crate::error::AgentError;
use crate::git_source::events::{is_own_event, IssueChange};
use crate::pipeline::issue_backsync::{apply_change, BackSynced};
use crate::pipeline::issue_creation::build_tracker;
use crate::pipeline::repo_view::RepoView;
use crate::pipeline::tracker_dispatch::TrackerDispatch;
use crate::secrets::SecretBox;
use crate::trackers::gitea::GiteaIssue;
/// What one poll of a tenant did: counts only, for the log.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub(crate) struct PollSummary {
/// Targets whose issues were listed.
pub targets: u32,
/// Findings resolved or reopened.
pub findings: u32,
/// Issues whose state was recorded without a finding change (a decision
/// a person had made stays; a CVE issue).
pub recorded: u32,
/// Targets whose tracker could not be read.
pub failed: u32,
}
/// What the poll of one target needs, owned by the agent.
#[derive(Clone, Copy)]
struct PollContext<'a> {
db: &'a Database,
config: &'a AgentConfig,
net_guard: NetGuard,
secrets: &'a SecretBox,
}
/// The issues of `listed` whose state differs from Prüfwerk's record of it
/// (`records`: number to closed), with the change and the issue's author.
/// Issues Prüfwerk has no record of are not its own and left out.
fn changes<'a>(
records: &HashMap<i64, bool>,
listed: &'a [GiteaIssue],
) -> Vec<(i64, IssueChange, &'a str)> {
listed
.iter()
.filter_map(
|issue| match (records.get(&issue.number)?, issue.is_closed()) {
(false, true) => Some((issue.number, IssueChange::Closed, issue.author())),
(true, false) => Some((issue.number, IssueChange::Reopened, issue.author())),
(true, true) | (false, false) => None,
},
)
.collect()
}
/// Prüfwerk's Gitea issues of target `target_id`, by number: whether each
/// is closed. A finding's issue is found through the finding (storing an
/// issue sets the finding's `tracker_issue_url`), a CVE issue by its key.
///
/// # Errors
///
/// A database error.
async fn records(db: &Database, target_id: &str) -> Result<HashMap<i64, bool>, AgentError> {
let ticketed = db
.findings()
.distinct(
"_id",
doc! { "repo_id": target_id, "tracker_issue_url": { "$ne": Bson::Null } },
)
.await?;
let finding_ids: Vec<String> = ticketed
.iter()
.filter_map(Bson::as_object_id)
.map(|id| id.to_hex())
.collect();
let cve = format!("^{}", regex::escape(&cve_issue_prefix(target_id)));
let issues: Vec<TrackerIssue> = db
.tracker_issues()
.find(doc! {
"tracker_type": TrackerType::Gitea.to_string(),
"$or": [
{ "finding_id": { "$in": finding_ids } },
{ "finding_id": { "$regex": cve } },
],
})
.await?
.try_collect()
.await?;
Ok(issues
.iter()
.filter_map(|i| Some((i.external_id.parse().ok()?, i.status.is_closed())))
.collect())
}
/// Poll the issues of `target` and carry a person's closes and reopens
/// back. A target without a Gitea tracker or without Prüfwerk issues is
/// skipped without asking Gitea anything.
///
/// # Errors
///
/// The records cannot be read, or Gitea cannot be listed or asked for a
/// timeline: the next poll tries again.
async fn poll_target(
ctx: PollContext<'_>,
target: &OnboardedTarget,
summary: &mut PollSummary,
) -> Result<(), AgentError> {
let (Some(id), Some(code)) = (target.id.map(|id| id.to_hex()), target.code_artifact()) else {
return Ok(());
};
let repo = RepoView::from_target(target, code, ctx.secrets);
let Some(TrackerDispatch::Gitea(gitea)) = build_tracker(ctx.config, ctx.net_guard, &repo)
else {
return Ok(());
};
let (Some(owner), Some(name)) = (repo.tracker_owner.as_deref(), repo.tracker_repo.as_deref())
else {
return Ok(());
};
let records = records(ctx.db, &id).await?;
if records.is_empty() {
return Ok(());
}
summary.targets += 1;
let listed = gitea.list_issues(owner, name).await?;
for (number, change, author) in changes(&records, &listed) {
let closed = change == IssueChange::Closed;
let Some(by) = gitea
.last_state_change_by(owner, name, number, closed)
.await?
.filter(|by| !is_own_event(by, author))
else {
// Prüfwerk's own change whose record was not written, or a
// timeline without the entry: nothing a person decided.
continue;
};
match apply_change(ctx.db, &id, number, change, &by).await? {
BackSynced::Finding => summary.findings += 1,
BackSynced::IssueOnly | BackSynced::Cve => summary.recorded += 1,
BackSynced::NotOurs => {}
}
}
Ok(())
}
/// Poll every active target of tenant `tenant_id`, one after the other so a
/// small Gitea sees one listing at a time.
///
/// # Errors
///
/// Automation is not allowed for the tenant (the same entitlement and
/// ladder rules as the webhook), or its targets cannot be read. A target
/// that fails is counted in [`PollSummary::failed`] and logged.
pub(crate) async fn poll_tenant(
agent: &ComplianceAgent,
tenant_id: &str,
) -> Result<PollSummary, AgentError> {
crate::git_source::automation_allowed(agent, tenant_id)
.await
.map_err(AgentError::Other)?;
let db = agent.db_pool.for_tenant_id(tenant_id).await?;
let targets: Vec<OnboardedTarget> = db
.onboarded_targets()
.find(doc! { "archived_at": null })
.await?
.try_collect()
.await?;
let ctx = PollContext {
db: &db,
config: &agent.config,
net_guard: agent.net_guard,
secrets: &agent.secrets,
};
let mut summary = PollSummary::default();
for target in &targets {
if let Err(e) = poll_target(ctx, target, &mut summary).await {
summary.failed += 1;
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
tracing::warn!(tenant_id, target_id, "issue poll failed: {e}");
}
}
Ok(summary)
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use axum::extract::{Path, Query};
use axum::routing::get;
use axum::{Json, Router};
use compliance_core::models::{
Artifact, Finding, FindingStatus, IssueStatus, IssueTrackerConfig, ScanType, Severity,
TargetType, TrackerChangeKind,
};
use mongodb::bson::oid::ObjectId;
use super::*;
/// A fake Gitea: issue #12 closed by a person, #13 closed by the bot
/// that opened it, #14 reopened by a person, #15 not Prüfwerk's. Every
/// list ends with an empty page, as Gitea's do.
async fn fake_gitea() -> String {
fn page<T: Into<serde_json::Value>>(
q: &HashMap<String, String>,
items: T,
) -> Json<serde_json::Value> {
if q.get("page").map(String::as_str) == Some("1") {
Json(items.into())
} else {
Json(serde_json::json!([]))
}
}
async fn issues(
Path((_o, _r)): Path<(String, String)>,
Query(q): Query<HashMap<String, String>>,
) -> Json<serde_json::Value> {
let issue = |n: i64, state: &str| serde_json::json!({ "number": n, "title": "t", "state": state, "user": { "login": "pruefwerk-bot" } });
page(
&q,
serde_json::json!([
issue(12, "closed"),
issue(13, "closed"),
issue(14, "open"),
issue(15, "closed")
]),
)
}
async fn timeline(
Path((_o, _r, n)): Path<(String, String, i64)>,
Query(q): Query<HashMap<String, String>>,
) -> Json<serde_json::Value> {
let event = |kind: &str, login: &str| serde_json::json!({ "type": kind, "user": { "login": login } });
let events = match n {
12 => serde_json::json!([
event("comment", "pruefwerk-bot"),
event("close", "dev-anna")
]),
13 => serde_json::json!([
event("close", "dev-anna"),
event("reopen", "dev-anna"),
event("close", "Pruefwerk-Bot")
]),
14 => {
serde_json::json!([event("close", "pruefwerk-bot"), event("reopen", "dev-ben")])
}
_ => serde_json::json!([event("close", "dev-anna")]),
};
page(&q, events)
}
let app = Router::new()
.route("/api/v1/repos/{o}/{r}/issues", get(issues))
.route("/api/v1/repos/{o}/{r}/issues/{n}/timeline", get(timeline));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
format!("http://{addr}")
}
#[tokio::test]
async fn a_persons_close_or_reopen_in_gitea_is_carried_back_and_the_bots_is_not() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!("ipoll_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP issue_poll: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id("issue-poll").await.unwrap();
let base = fake_gitea().await;
// Arrange: a target with a Gitea tracker, two open findings with
// issues #12 and #13, and the CVE issue #14 (closed by Prüfwerk).
let mut target = OnboardedTarget::new("fw".into(), TargetType::BackendService);
target
.artifacts
.push(Artifact::git_repo(format!("{base}/kunde/fw.git"), "main"));
target.scan_config.issue_tracker = Some(IssueTrackerConfig {
tracker_type: Some(TrackerType::Gitea),
owner: Some("kunde".into()),
repo: Some("fw".into()),
token: Some("bot-token".into()),
});
let target_id = db
.onboarded_targets()
.insert_one(&target)
.await
.unwrap()
.inserted_id
.as_object_id()
.unwrap();
target.id = Some(target_id);
let target_hex = target_id.to_hex();
let with_issue = |number: &str| {
let db = db.clone();
let target_hex = target_hex.clone();
let base = base.clone();
let number = number.to_string();
async move {
let url = format!("{base}/kunde/fw/issues/{number}");
let mut f = Finding::new(
target_hex,
format!("fp-{number}"),
"semgrep".into(),
ScanType::Sast,
"strcpy".into(),
"d".into(),
Severity::High,
);
f.tracker_issue_url = Some(url.clone());
let id = db
.findings()
.insert_one(&f)
.await
.unwrap()
.inserted_id
.as_object_id()
.unwrap();
let issue = TrackerIssue::new(
id.to_hex(),
TrackerType::Gitea,
number,
url,
"strcpy".into(),
);
db.tracker_issues().insert_one(&issue).await.unwrap();
id
}
};
let closed_by_anna = with_issue("12").await;
let closed_by_bot = with_issue("13").await;
let mut cve = TrackerIssue::new(
format!("{}openssl:CVE-2026-1", cve_issue_prefix(&target_hex)),
TrackerType::Gitea,
"14".into(),
format!("{base}/kunde/fw/issues/14"),
"CVE-2026-1".into(),
);
cve.status = IssueStatus::Closed;
db.tracker_issues().insert_one(&cve).await.unwrap();
let ctx = PollContext {
db: &db,
config: &AgentConfig::default(),
net_guard: NetGuard::allow_private(),
secrets: &SecretBox::without_key(),
};
// Act
let mut summary = PollSummary::default();
poll_target(ctx, &target, &mut summary).await.unwrap();
// Assert: Anna's close resolved her finding, the bot's left the
// other alone, Ben's reopen of the CVE issue is recorded.
assert_eq!(
summary,
PollSummary {
targets: 1,
findings: 1,
recorded: 1,
failed: 0
}
);
let finding = |id: ObjectId| {
let db = db.clone();
async move {
db.findings()
.find_one(doc! { "_id": id })
.await
.unwrap()
.unwrap()
}
};
let resolved = finding(closed_by_anna).await;
assert_eq!(resolved.status, FindingStatus::Resolved);
let last = resolved.status_history.last().unwrap();
assert_eq!(
(last.tracker, last.by_name.as_deref()),
(Some(TrackerChangeKind::ClosedInTracker), Some("dev-anna"))
);
assert_eq!(finding(closed_by_bot).await.status, FindingStatus::Open);
let issue = |number: &str| {
let db = db.clone();
let number = number.to_string();
async move {
db.tracker_issues()
.find_one(doc! { "external_id": number })
.await
.unwrap()
.unwrap()
}
};
let twelve = issue("12").await;
assert_eq!(
(twelve.status, twelve.closed_in_tracker.as_deref()),
(IssueStatus::Closed, Some("dev-anna"))
);
assert_eq!(issue("13").await.status, IssueStatus::Open);
assert_eq!(issue("14").await.status, IssueStatus::Open);
// A second poll finds the records matching (the bot's close aside,
// which stays a person's to decide): nothing more changes.
let mut again = PollSummary::default();
poll_target(ctx, &target, &mut again).await.unwrap();
assert_eq!((again.findings, again.recorded), (0, 0));
pool.drop_tenant("issue-poll").await.ok();
}
fn listed(number: i64, state: &str, author: &str) -> GiteaIssue {
serde_json::from_value(serde_json::json!({
"number": number, "title": "t", "state": state,
"user": { "login": author },
}))
.unwrap()
}
#[test]
fn only_issues_whose_state_differs_from_the_record_are_changes() {
let records: HashMap<i64, bool> = [(1, false), (2, true), (3, false), (4, true)].into();
let issues = [
listed(1, "closed", "bot"),
listed(2, "open", "bot"),
listed(3, "open", "bot"),
listed(4, "closed", "bot"),
// Not Prüfwerk's: no record.
listed(5, "closed", "dev-anna"),
];
assert_eq!(
changes(&records, &issues),
[
(1, IssueChange::Closed, "bot"),
(2, IssueChange::Reopened, "bot")
]
);
}
}
+103 -5
View File
@@ -170,19 +170,40 @@ impl IssueSync {
let Some(id) = issue.id else {
return Ok(());
};
let status = mongodb::bson::to_bson(&status).map_err(|e| e.to_string())?;
let update = issue_state_update(&status, None).map_err(|e| e.to_string())?;
self.db
.tracker_issues()
.update_one(
doc! { "_id": id },
doc! { "$set": { "status": status, "updated_at": mongodb::bson::DateTime::now() } },
)
.update_one(doc! { "_id": id }, update)
.await
.map(drop)
.map_err(|e| e.to_string())
}
}
/// The update that stores an issue's new `status`. `closed_by` is the
/// tracker user who closed it there (#953); when Prüfwerk changes the state,
/// or the issue is reopened, it is `None` and an earlier closer is cleared.
///
/// # Errors
///
/// The status cannot be written as BSON.
pub(crate) fn issue_state_update(
status: &IssueStatus,
closed_by: Option<&str>,
) -> Result<mongodb::bson::Document, mongodb::bson::ser::Error> {
let mut set = doc! {
"status": mongodb::bson::to_bson(status)?,
"updated_at": mongodb::bson::DateTime::now(),
};
Ok(match closed_by {
Some(login) => {
set.insert("closed_in_tracker", login);
doc! { "$set": set }
}
None => doc! { "$set": set, "$unset": { "closed_in_tracker": "" } },
})
}
/// The `risk:accepted` label id per target (`Finding::repo_id`), once
/// resolved; `None` for a target whose repository has no such label.
type RiskLabels = HashMap<String, Option<i64>>;
@@ -492,6 +513,69 @@ mod tests {
assert_eq!(tail, ["state 12: \"closed\"", "labels 12: [42]"]);
}
// Reopened, then a person closes the issue in Gitea (#953): the
// back-sync resolves the finding and records the issue closed, so the
// sync neither comments nor closes it again.
db.findings()
.update_one(
doc! { "_id": finding_id },
doc! { "$set": { "status": "open" } },
)
.await
.unwrap();
sync.sync_one(finding_id, &mut RiskLabels::new())
.await
.unwrap();
assert_eq!(issue_status().await, IssueStatus::Open);
let event = crate::git_source::events::IssueEvent {
repo: serde_json::from_value(serde_json::json!({
"id": 7, "name": "fw", "full_name": "kunde/fw",
}))
.unwrap(),
number: 12,
change: crate::git_source::events::IssueChange::Closed,
sender: "dev-anna".into(),
};
crate::pipeline::issue_backsync::apply(&db, &target_id.to_hex(), &event)
.await
.unwrap();
let before = calls.lock().unwrap().len();
sync.sync_one(finding_id, &mut RiskLabels::new())
.await
.unwrap();
assert_eq!(calls.lock().unwrap().len(), before, "nothing sent to Gitea");
assert_eq!(issue_status().await, IssueStatus::Closed);
// Found again by the next scan: reopened with the usual comment.
db.findings()
.update_one(
doc! { "_id": finding_id },
doc! {
"$set": { "status": "open" },
"$push": { "status_history": mongodb::bson::to_bson(&by_scan(
FindingStatus::Open,
ScanChangeKind::FoundAgain,
)).unwrap() },
},
)
.await
.unwrap();
sync.sync_one(finding_id, &mut RiskLabels::new())
.await
.unwrap();
{
let calls = calls.lock().unwrap();
assert!(calls[before].contains("erneut gefunden"));
assert_eq!(calls[before + 1], "state 12: \"open\"");
}
let reopened = db
.tracker_issues()
.find_one(doc! { "finding_id": finding_id.to_hex() })
.await
.unwrap()
.unwrap();
assert!(reopened.closed_in_tracker.is_none());
pool.drop_tenant("issue-sync").await.ok();
}
@@ -526,6 +610,20 @@ mod tests {
StatusChange::by_scan(status, kind, "run-1")
}
#[test]
fn the_issue_state_keeps_who_closed_it_in_the_tracker_until_it_reopens() {
let closed = issue_state_update(&IssueStatus::Closed, Some("dev-anna")).unwrap();
let set = closed.get_document("$set").unwrap();
assert_eq!(set.get_str("status").unwrap(), "closed");
assert_eq!(set.get_str("closed_in_tracker").unwrap(), "dev-anna");
assert!(!closed.contains_key("$unset"));
let by_pruefwerk = issue_state_update(&IssueStatus::Open, None).unwrap();
assert!(by_pruefwerk
.get_document("$unset")
.unwrap()
.contains_key("closed_in_tracker"));
}
#[test]
fn closing_statuses_close_and_open_ones_reopen() {
assert_eq!(
+4 -1
View File
@@ -5,6 +5,7 @@ pub mod change;
pub mod clamav;
pub mod clone_limit;
pub mod code_review;
pub(crate) mod component_changes;
pub mod cppcheck;
pub(crate) mod csaf_feed;
pub(crate) mod csaf_match;
@@ -23,11 +24,13 @@ pub mod git;
pub mod git_retry;
pub mod git_submodules;
pub mod gitleaks;
mod graph_build;
pub(crate) mod graph_build;
pub mod grouping;
pub mod ios_config;
pub(crate) mod issue_backsync;
mod issue_catchup;
pub(crate) mod issue_creation;
pub(crate) mod issue_poll;
pub(crate) mod issue_sync;
pub mod languages;
pub mod license_policy;
+488 -63
View File
@@ -37,6 +37,20 @@ 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)]
@@ -65,6 +79,13 @@ 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>,
/// Set when this person's scan took over a waiting scheduled, webhook or
/// new-content scan (t84): the trigger it is charged as. Change detection
/// then decides whether it counts, as for that scan.
pub(super) charged_as: Option<ScanTrigger>,
}
impl PipelineOrchestrator {
@@ -81,9 +102,24 @@ impl PipelineOrchestrator {
nuget_license_cache: None,
exploit_cache: None,
advisory_index: None,
plan_limits: None,
charged_as: None,
}
}
/// Charge this run as a scan started by `trigger` would be, when a
/// person's request took that waiting scan over (t84).
pub(crate) fn with_charged_as(mut self, trigger: Option<ScanTrigger>) -> Self {
self.charged_as = trigger;
self
}
/// 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);
@@ -174,25 +210,45 @@ 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;
// Findings deferred by the catch-up's cap still get their issues.
self.catch_up_unchanged(repo, &repo_id).await;
return Ok(0);
.await?;
} else if let Some(original) = &self.charged_as {
let new_commits =
GitOps::has_new_commits(&repo_path, repo.last_scanned_commit.as_deref())?;
self.charge_as_taken_over(
scan_run_id,
&repo_id,
ScanAttribution::detected(original, new_commits || repo.changed_besides_commits),
repo.billing,
)
.await?;
}
// Submodules are part of what the product ships (a HAL, an RTOS).
@@ -255,6 +311,14 @@ 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())
@@ -293,12 +357,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())
@@ -894,8 +960,12 @@ impl PipelineOrchestrator {
self.update_phase(scan_run_id, ScanPhase::GraphBuilding)
.await;
let graph_context = match async {
self.build_code_graph(&repo_path, &repo_id, &all_findings)
.await
self.build_code_graph(
crate::pipeline::graph_build::GraphSource::Tree(&repo_path),
&repo_id,
&all_findings,
)
.await
}
.instrument(tracing::info_span!("stage_graph_building"))
.await
@@ -997,6 +1067,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(),
@@ -1013,15 +1088,23 @@ impl PipelineOrchestrator {
// nothing, so dependencies removed from a repo used to stay in its SBOM
// forever.
if !sbom_entries.is_empty() {
self.db
.sbom_entries()
.delete_many(doc! {
"repo_id": &repo_id,
"package_manager": {
"$nin": crate::pipeline::firmware_sbom::FIRMWARE_MANAGERS.to_vec()
},
})
.await?;
let scope = doc! {
"package_manager": {
"$nin": crate::pipeline::firmware_sbom::FIRMWARE_MANAGERS.to_vec()
},
};
// What this replaces, for the target's history (#974).
crate::pipeline::component_changes::record(
&self.db,
scan_run_id,
&repo_id,
scope.clone(),
&sbom_entries,
)
.await;
let mut filter = doc! { "repo_id": &repo_id };
filter.extend(scope);
self.db.sbom_entries().delete_many(filter).await?;
}
// Persist SBOM entries
@@ -1106,12 +1189,15 @@ impl PipelineOrchestrator {
/// `OnboardedTarget`. Mirrors [`Self::run`] but sources the target from
/// `onboarded_targets` and dispatches by the scan plan.
#[tracing::instrument(skip_all, fields(target_id = %target_id, trigger = ?trigger))]
/// Run one scan of the target `target_id`.
/// Run one scan of the target `target_id`, recorded on the run `queued`
/// that waited for this scan's slot (t84), or on a new run when there is
/// none.
///
/// # 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
///
@@ -1120,7 +1206,8 @@ impl PipelineOrchestrator {
&self,
target_id: &str,
trigger: ScanTrigger,
) -> Result<bool, AgentError> {
queued: Option<&str>,
) -> Result<TargetScanOutcome, AgentError> {
let oid = mongodb::bson::oid::ObjectId::parse_str(target_id)
.map_err(|e| AgentError::Other(e.to_string()))?;
let target = self
@@ -1130,17 +1217,35 @@ 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 insert = self.db.scan_runs().insert_one(&scan_run).await?;
let scan_run_id = insert
.inserted_id
.as_object_id()
.map(|id| id.to_hex())
.unwrap_or_default();
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);
// One that took over a waiting scan counts only as that scan
// would have; change detection decides below (t84).
scan_run.chargeable =
self.charged_as.is_none() && attribution.chargeable(target.billing);
}
scan_run.charged_as = self.charged_as.clone();
let run_oid = self.start_run(&scan_run, queued).await?;
let scan_run_id = run_oid.to_hex();
let run_id = mongodb::bson::Bson::ObjectId(run_oid);
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! {
@@ -1159,10 +1264,7 @@ impl PipelineOrchestrator {
}
self.db
.scan_runs()
.update_one(
doc! { "_id": &insert.inserted_id },
doc! { "$set": completed },
)
.update_one(doc! { "_id": &run_id }, doc! { "$set": completed })
.await?;
// Refresh the target's cached findings count. The shared pipeline
// (Stage 7) increments `repositories`, which the unified path does
@@ -1191,13 +1293,30 @@ 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": &run_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();
self.db
.scan_runs()
.update_one(
doc! { "_id": &insert.inserted_id },
doc! { "_id": &run_id },
doc! { "$set": {
"status": "failed",
"error_message": message,
@@ -1208,16 +1327,258 @@ 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": &run_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(&run_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),
})
}
/// Record that `run` starts now: on the run `queued` that waited for the
/// slot, which moves from `queued` to `running`, or as a new run when
/// there is none or it is gone. Returns the run's id.
///
/// # Errors
///
/// The run could not be written.
async fn start_run(
&self,
run: &ScanRun,
queued: Option<&str>,
) -> Result<mongodb::bson::oid::ObjectId, AgentError> {
if let Some(oid) = queued.and_then(|id| mongodb::bson::oid::ObjectId::parse_str(id).ok()) {
let mut started = doc! {
"status": "running",
"trigger": mongodb::bson::to_bson(&run.trigger)
.map_err(|e| AgentError::Other(e.to_string()))?,
"started_at": mongodb::bson::DateTime::from_chrono(run.started_at),
"chargeable": run.chargeable,
};
if let Some(charged_as) = &run.charged_as {
started.insert(
"charged_as",
mongodb::bson::to_bson(charged_as)
.map_err(|e| AgentError::Other(e.to_string()))?,
);
}
if let Some(attribution) = run.attribution {
started.insert(
"attribution",
mongodb::bson::to_bson(&attribution)
.map_err(|e| AgentError::Other(e.to_string()))?,
);
}
let updated = self
.db
.scan_runs()
.update_one(
doc! { "_id": oid, "status": "queued" },
doc! { "$set": started },
)
.await?;
if updated.matched_count == 1 {
return Ok(oid);
}
}
let insert = self.db.scan_runs().insert_one(run).await?;
insert
.inserted_id
.as_object_id()
.ok_or_else(|| AgentError::Other("the scan run got no id".into()))
}
/// 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(())
}
/// Count the run `scan_run_id`, a person's request that took over a
/// waiting scan, only when `detected` (that scan's attribution from change
/// detection) counts on a target billed as `billing`, and then check it
/// against the plan (t84). The run keeps the person's attribution, so its
/// history shows that a person asked. Several code artifacts: a change in
/// any of them counts it, as in [`Self::attribute_run`].
///
/// # Errors
///
/// [`AgentError::NotAdmitted`] when the plan does not allow a counted
/// Prüfung now.
async fn charge_as_taken_over(
&self,
scan_run_id: &str,
target_id: &str,
detected: ScanAttribution,
billing: TargetBilling,
) -> Result<(), AgentError> {
if !detected.chargeable(billing) {
return Ok(());
}
if let Ok(oid) = mongodb::bson::oid::ObjectId::parse_str(scan_run_id) {
if let Err(e) = self
.db
.scan_runs()
.update_one(doc! { "_id": oid }, doc! { "$set": { "chargeable": true } })
.await
{
tracing::warn!(scan_run_id, "scan run not marked as counted: {e}");
}
}
self.admit_run(scan_run_id, target_id).await
}
/// 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
@@ -1262,6 +1623,27 @@ impl PipelineOrchestrator {
.await;
return Ok(0);
}
// A git target is attributed where its commits are compared.
if !has_git {
let changed = crate::pipeline::change::content_changed(target);
if !trigger.started_by_person() {
self.attribute_run(
scan_run_id,
&target_id,
ScanAttribution::detected(trigger, changed),
target.billing,
)
.await?;
} else if let Some(original) = &self.charged_as {
self.charge_as_taken_over(
scan_run_id,
&target_id,
ScanAttribution::detected(original, changed),
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".
@@ -1471,6 +1853,8 @@ impl PipelineOrchestrator {
// Each source's findings next to the tree they were found in: the
// control mapping below reads the flagged regions from it.
let mut analysed = Vec::with_capacity(sources.len());
// Every tree's POUs, for the code graph.
let mut plc_files = Vec::new();
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
@@ -1489,10 +1873,12 @@ impl PipelineOrchestrator {
left_out.excluded.extend(pruned.excluded);
left_out.test_data.extend(pruned.test_data);
native.extend(crate::pipeline::plc::native_projects(&path));
let files = crate::pipeline::plc::read_tree(&path);
analysed.push((
path.clone(),
crate::pipeline::plc::analyze_tree(&path, target_id),
crate::pipeline::plc::findings(&files, target_id),
));
plc_files.extend(files);
// Control-application SBOM: CODESYS libraries + runtime from a
// `.projectarchive` (uploaded, or committed in the working tree).
let archive = a
@@ -1554,6 +1940,21 @@ impl PipelineOrchestrator {
"PLC control-logic analysis complete"
);
// The POUs and how they use each other, as for a code scan; a stale
// graph is replaced even when no POU was read.
self.update_phase(scan_run_id, ScanPhase::GraphBuilding)
.await;
if let Err(e) = self
.build_code_graph(
crate::pipeline::graph_build::GraphSource::Plc(&plc_files),
target_id,
&all_findings,
)
.await
{
tracing::warn!(target_id, error = %e, "PLC graph building failed");
}
let mut new_count = 0u32;
let mut refreshed_count = 0u32;
for mut finding in all_findings {
@@ -1594,7 +1995,7 @@ impl PipelineOrchestrator {
.with_excluded(left_out.excluded)
.with_test_data(left_out.test_data);
let closed = left_out_run
.resolve_left_out(&self.db, target_id, "plc-control-logic")
.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");
@@ -1777,6 +2178,14 @@ impl PipelineOrchestrator {
if entries.is_empty() {
return Ok(());
}
crate::pipeline::component_changes::record(
&self.db,
scan_run_id,
target_id,
doc! { "package_manager": "codesys" },
&entries,
)
.await;
self.db
.sbom_entries()
.delete_many(doc! { "repo_id": target_id, "package_manager": "codesys" })
@@ -2072,6 +2481,16 @@ impl PipelineOrchestrator {
}
};
if !entries.is_empty() {
crate::pipeline::component_changes::record(
&self.db,
scan_run_id,
target_id,
doc! { "package_manager": {
"$in": crate::pipeline::firmware_sbom::FIRMWARE_MANAGERS.to_vec()
} },
&entries,
)
.await;
// Only the firmware entries: a rescan with no new
// commits skips the SBOM stage, so deleting everything
// here wiped the Syft entries until the next commit.
@@ -3006,6 +3425,7 @@ fn planned_phases(
if config.breakpilot.semantic_mapping {
phases.push(ScanPhase::SemanticControlMapping);
}
phases.push(ScanPhase::GraphBuilding);
if config.plc_runtime.enabled && target.live_url().is_none() {
phases.push(ScanPhase::PlcProvision);
}
@@ -3159,7 +3579,11 @@ mod tests {
assert_eq!(
planned_phases(&target, &plan, &config),
[ScanPhase::Classification, ScanPhase::PlcAnalysis]
[
ScanPhase::Classification,
ScanPhase::PlcAnalysis,
ScanPhase::GraphBuilding
]
);
// The LLM control mapping is a phase of its own, so a long one shows.
@@ -3169,7 +3593,8 @@ mod tests {
[
ScanPhase::Classification,
ScanPhase::PlcAnalysis,
ScanPhase::SemanticControlMapping
ScanPhase::SemanticControlMapping,
ScanPhase::GraphBuilding
]
);
}
+43 -5
View File
@@ -186,9 +186,17 @@ fn scan_with_patterns(
.unwrap_or("")
.to_string();
let content = match std::fs::read_to_string(path) {
Ok(c) => c,
Err(_) => continue, // skip binary files
// Only files a pattern looks at are read at all.
if !patterns.iter().any(|p| p.file_extensions.contains(&ext)) {
continue;
}
// UTF-8, UTF-16 with a BOM, or Windows-1252; a binary is skipped.
let content = match compliance_core::encoding::read_source(path) {
Ok(text) => text,
Err(error) => {
tracing::debug!(file = %path.display(), %error, "pattern scan: file not readable");
continue;
}
};
let relative_path = path
@@ -386,8 +394,12 @@ mod tests {
fn oauth_token_url_matches() {
let scanner = OAuthPatternScanner::new();
let pattern = &scanner.patterns[3]; // oauth-token-url
assert!(pattern.pattern.is_match("access_token = build_url(query)"));
assert!(pattern.pattern.is_match("bearer = url.param"));
// Split, so this file's own line does not match the rule it tests
// when Prüfwerk scans its own repository.
assert!(pattern
.pattern
.is_match(concat!("access_", "token = build_url(query)")));
assert!(pattern.pattern.is_match(concat!("bear", "er = url.param")));
}
// --- Pattern rule file extension filtering ---
@@ -413,4 +425,30 @@ mod tests {
assert!(!pattern.file_extensions.contains(&"rs".to_string()));
assert!(!pattern.file_extensions.contains(&"py".to_string()));
}
// --- file decoding ---
#[test]
fn a_windows_1252_file_is_scanned_not_skipped() {
// Arrange: a C# file written by an older tool, "Größe" as 0xF6 0xDF.
let dir = std::env::temp_dir().join(format!("cs-pat-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("Log.cs"), b"// Gr\xF6\xDFe\nLog(email);\n").unwrap();
let rule = PatternRule {
id: "pii".into(),
title: "t".into(),
description: "d".into(),
pattern: compile_regex(r"Log\(email\)"),
severity: Severity::Medium,
file_extensions: vec!["cs".into()],
};
// Act
let findings = scan_with_patterns(&dir, "repo", &[rule], ScanType::Gdpr, "t").unwrap();
let _ = std::fs::remove_dir_all(&dir);
// Assert: found on its line.
assert_eq!(findings.len(), 1);
assert_eq!(findings[0].line_number, Some(2));
}
}
+118 -1
View File
@@ -14,8 +14,96 @@ pub struct Pou {
pub vars: Vec<VarDecl>,
/// The statement body.
pub body: Vec<Stmt>,
/// 1-based line where the POU header appears (in the source that was parsed).
/// 1-based line where the POU header appears. For a PLCopen POU it is
/// the `<pou>` element's line in the XML; its statements keep the lines
/// of the Structured Text reconstructed from it.
pub line: u32,
/// 1-based line of its `END_*` keyword (the last line when it is
/// missing); for a PLCopen POU, the `</pou>` line.
pub end_line: u32,
}
impl Pou {
/// Call `visit` with the callee and line of every call in the body, bare
/// (`TON1(IN := x);`) or inside an expression (`LIMIT(0, x, 10)`), in
/// source order.
pub fn for_each_call(&self, mut visit: impl FnMut(&str, u32)) {
for stmt in &self.body {
stmt.for_each_call(&mut visit);
}
}
}
impl Stmt {
/// See [`Pou::for_each_call`]. `visit` is `&mut dyn` so the recursion
/// through nested blocks doesn't instantiate a new closure type per level.
fn for_each_call(&self, visit: &mut dyn FnMut(&str, u32)) {
let block = |body: &[Stmt], visit: &mut dyn FnMut(&str, u32)| {
for stmt in body {
stmt.for_each_call(visit);
}
};
match self {
Stmt::Assign { target, value, .. } => {
target.for_each_call(visit);
value.for_each_call(visit);
}
Stmt::If {
branches,
else_body,
..
} => {
for (cond, body) in branches {
cond.for_each_call(visit);
block(body, visit);
}
if let Some(body) = else_body {
block(body, visit);
}
}
Stmt::Case {
selector,
arms,
else_body,
..
} => {
selector.for_each_call(visit);
for (labels, body) in arms {
for label in labels {
label.for_each_call(visit);
}
block(body, visit);
}
if let Some(body) = else_body {
block(body, visit);
}
}
Stmt::For {
from, to, by, body, ..
} => {
from.for_each_call(visit);
to.for_each_call(visit);
if let Some(by) = by {
by.for_each_call(visit);
}
block(body, visit);
}
Stmt::While { cond, body, .. }
| Stmt::Repeat {
body, until: cond, ..
} => {
cond.for_each_call(visit);
block(body, visit);
}
Stmt::Call { callee, args, line } => {
visit(callee, *line);
for arg in args {
arg.value.for_each_call(visit);
}
}
Stmt::Return { .. } | Stmt::Exit { .. } | Stmt::Jump { .. } | Stmt::Label { .. } => {}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -191,6 +279,35 @@ impl Expr {
}
}
/// See [`Pou::for_each_call`].
fn for_each_call(&self, visit: &mut dyn FnMut(&str, u32)) {
match self {
Expr::Int(..)
| Expr::Real(..)
| Expr::Bool(..)
| Expr::Str(..)
| Expr::Time(..)
| Expr::Ident(..) => {}
Expr::Index { base, index, .. } => {
base.for_each_call(visit);
index.for_each_call(visit);
}
Expr::Member { base, .. } | Expr::Unary { expr: base, .. } => {
base.for_each_call(visit);
}
Expr::Binary { lhs, rhs, .. } => {
lhs.for_each_call(visit);
rhs.for_each_call(visit);
}
Expr::Call { callee, args, line } => {
visit(callee, *line);
for arg in args {
arg.value.for_each_call(visit);
}
}
}
}
/// If this expression is a plain identifier, its name.
pub fn as_ident(&self) -> Option<&str> {
match self {
+295
View File
@@ -0,0 +1,295 @@
//! The POUs of a PLC project as code-graph nodes and edges, for
//! [`compliance_graph::GraphEngine::assemble`].
//!
//! - A `PROGRAM` is a module and an entry point: the PLC's tasks run it.
//! - A `FUNCTION_BLOCK` is a class, since each instance keeps its own state.
//! - A `FUNCTION` is a function.
//!
//! A variable whose type is a function block is a dependency on it (a type
//! reference). A call through an instance (`Pump1(Start := x)`) is a call to
//! its type. Standard blocks such as `TON` or `CTU` have no node, so their
//! edges stay unresolved and the engine drops them.
use std::collections::HashMap;
use std::path::Path;
use compliance_core::models::graph::{CodeEdgeKind, CodeNodeKind};
use compliance_core::traits::graph_builder::ParseOutput;
use compliance_graph::parsers::FileGraph;
use super::ast::{Pou, PouKind};
use super::PlcFile;
/// The nodes and edges of every POU in `files`.
///
/// # Arguments
///
/// * `files` - the PLC source files read from one or more trees
/// * `repo_id`, `graph_build_id` - stamped on every node and edge
pub(crate) fn parse_output(files: &[PlcFile], repo_id: &str, graph_build_id: &str) -> ParseOutput {
let mut output = ParseOutput::default();
for file in files {
let language = if file.plcopen {
"plcopen"
} else {
"structured_text"
};
let mut graph = FileGraph::new(
Path::new(&file.rel),
file.line_count,
repo_id,
graph_build_id,
language,
);
for pou in &file.pous {
add_pou(&mut graph, pou);
}
let part = graph.finish();
output.nodes.extend(part.nodes);
output.edges.extend(part.edges);
}
output
}
/// Add `pou`'s node, its type references and its calls.
fn add_pou(graph: &mut FileGraph<'_>, pou: &Pou) {
let qualified = graph.top_level(&pou.name);
let kind = match pou.kind {
PouKind::Program => CodeNodeKind::Module,
PouKind::FunctionBlock => CodeNodeKind::Class,
PouKind::Function => CodeNodeKind::Function,
};
graph.node_at(
qualified.clone(),
pou.name.clone(),
kind,
(pou.line, pou.end_line),
pou.kind == PouKind::Program,
);
// IEC 61131-3 identifiers are case-insensitive, so the instances are
// looked up by their lowercased name.
let mut instances: HashMap<String, &str> = HashMap::with_capacity(pou.vars.len());
for var in &pou.vars {
if !is_identifier(&var.type_name) {
continue; // ARRAY[..] OF, POINTER TO, STRING(80): not a block type
}
graph.edge_at(&qualified, &var.type_name, CodeEdgeKind::TypeRef, var.line);
instances.insert(var.name.to_ascii_lowercase(), var.type_name.as_str());
}
pou.for_each_call(|callee, line| {
let target = instances
.get(&callee.to_ascii_lowercase())
.copied()
.unwrap_or(callee);
graph.edge_at(&qualified, target, CodeEdgeKind::Calls, line);
});
}
/// Whether a declared type is a plain name (`FB_Pump`, `TON`, `INT`).
fn is_identifier(type_name: &str) -> bool {
!type_name.is_empty()
&& type_name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_')
}
#[cfg(test)]
mod tests {
use super::*;
use crate::pipeline::plc::{parser, plcopen};
fn st_file(rel: &str, source: &str) -> PlcFile {
PlcFile {
rel: rel.to_string(),
plcopen: false,
line_count: source.lines().count() as u32,
pous: parser::parse(source),
}
}
const LINE: &str = "\
FUNCTION_BLOCK FB_Pump
VAR_INPUT
Start : BOOL;
END_VAR
VAR
Delay : TON;
END_VAR
Delay(IN := Start, PT := T#2s);
END_FUNCTION_BLOCK
FUNCTION Clamp : INT
VAR_INPUT
x : INT;
END_VAR
Clamp := LIMIT(0, x, 100);
END_FUNCTION
PROGRAM Main
VAR
pump1 : FB_Pump;
level : INT;
END_VAR
PUMP1(Start := TRUE);
IF Clamp(level) > 50 THEN
level := 0;
END_IF;
END_PROGRAM
";
#[test]
fn pous_become_nodes_and_programs_entry_points() {
let output = parse_output(&[st_file("src/line.st", LINE)], "r", "b");
let node = |name: &str| {
output
.nodes
.iter()
.find(|n| n.name == name)
.unwrap_or_else(|| panic!("no node {name}"))
};
assert_eq!(node("line.st").kind, CodeNodeKind::File);
let pump = node("FB_Pump");
assert_eq!(pump.kind, CodeNodeKind::Class);
assert_eq!(pump.qualified_name, "src/line.st::FB_Pump");
assert_eq!((pump.start_line, pump.end_line), (1, 9));
assert!(!pump.is_entry_point);
assert_eq!(node("Clamp").kind, CodeNodeKind::Function);
let main = node("Main");
assert_eq!(main.kind, CodeNodeKind::Module);
assert_eq!((main.start_line, main.end_line), (18, 27));
assert!(main.is_entry_point);
assert!(output.nodes.iter().all(|n| n.language == "structured_text"));
}
#[test]
fn instances_lead_to_their_type_and_calls_to_the_callee() {
let output = parse_output(&[st_file("line.st", LINE)], "r", "b");
let edges: Vec<(&str, CodeEdgeKind)> = output
.edges
.iter()
.filter(|e| e.source == "line.st::Main")
.map(|e| (e.target.as_str(), e.kind.clone()))
.collect();
// The instance declaration and the call through it (in another case)
// lead to FB_Pump; the function is called by name.
let to = |target: &str, kind: CodeEdgeKind| {
edges
.iter()
.filter(|(t, k)| *t == target && *k == kind)
.count()
};
assert_eq!(to("FB_Pump", CodeEdgeKind::TypeRef), 1);
assert_eq!(to("FB_Pump", CodeEdgeKind::Calls), 1);
assert_eq!(to("Clamp", CodeEdgeKind::Calls), 1);
// A standard block keeps its own name and resolves to nothing.
assert!(output
.edges
.iter()
.any(|e| e.source == "line.st::FB_Pump" && e.target == "TON"));
}
#[test]
fn plcopen_pous_span_their_xml_element() {
let xml = r#"<?xml version="1.0" encoding="utf-8"?>
<project>
<types>
<pous>
<pou name="Main" pouType="program">
<interface>
<localVars>
<variable name="pump1"><type><derived name="FB_Pump"/></type></variable>
</localVars>
</interface>
<body>
<ST><xhtml xmlns="http://www.w3.org/1999/xhtml">pump1(Start := TRUE);</xhtml></ST>
</body>
</pou>
</pous>
</types>
</project>
"#;
let file = PlcFile {
rel: "export.xml".to_string(),
plcopen: true,
line_count: xml.lines().count() as u32,
pous: plcopen::parse_plcopen(xml),
};
let output = parse_output(&[file], "r", "b");
let main = output
.nodes
.iter()
.find(|n| n.name == "Main")
.expect("Main is a node");
assert_eq!((main.start_line, main.end_line), (5, 14));
assert_eq!(main.language, "plcopen");
assert!(output
.edges
.iter()
.any(|e| e.target == "FB_Pump" && e.kind == CodeEdgeKind::Calls));
}
#[test]
fn the_engine_links_instances_and_drops_standard_blocks() {
let output = parse_output(&[st_file("line.st", LINE)], "r", "b");
let (graph, run) = compliance_graph::GraphEngine::new(1_000)
.assemble(output, "r")
.expect("assembles");
let linked = |source: &str, target: &str| {
graph
.edges
.iter()
.any(|e| e.source == source && e.target == target)
};
assert!(linked("line.st::Main", "line.st::FB_Pump"));
assert!(linked("line.st::Main", "line.st::Clamp"));
assert!(!graph.edges.iter().any(|e| e.target == "TON"));
assert_eq!(run.languages_parsed, ["structured_text"]);
}
#[test]
fn every_pou_of_the_demo_project_is_a_node() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../examples/plc-demo");
let mut files = crate::pipeline::plc::read_tree(&root);
files.sort_by(|a, b| a.rel.cmp(&b.rel));
let output = parse_output(&files, "r", "b");
let mut pous: Vec<(&str, bool)> = output
.nodes
.iter()
.filter(|n| n.kind != CodeNodeKind::File)
.map(|n| (n.name.as_str(), n.is_entry_point))
.collect();
pous.sort();
assert_eq!(
pous,
[
("ConveyorCtrl", true),
("PumpFbdCtrl", false),
("PumpStationCtrl", false),
("TrafficLight", true),
]
);
assert_eq!(
output
.nodes
.iter()
.filter(|n| n.kind == CodeNodeKind::File)
.count(),
4
);
}
#[test]
fn only_plain_type_names_are_references() {
assert!(is_identifier("FB_Pump"));
assert!(!is_identifier("ARRAY[0..9] OF INT"));
assert!(!is_identifier("STRING(80)"));
assert!(!is_identifier(""));
}
}
+111 -18
View File
@@ -9,6 +9,7 @@
//! scan says so instead of finding nothing in silence (#165).
pub mod ast;
pub(crate) mod graph;
pub mod lexer;
pub mod parser;
pub mod plcopen;
@@ -45,9 +46,26 @@ impl Scanner for PlcControlLogicScanner {
}
}
/// Walk a PLC project tree and produce findings.
pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
let mut findings = Vec::new();
/// A PLC source file and the POUs read from it.
pub(crate) struct PlcFile {
/// The path relative to the tree it was found in.
pub(crate) rel: String,
/// Whether it is a PLCopen XML export rather than Structured Text.
pub(crate) plcopen: bool,
/// Its number of lines.
pub(crate) line_count: u32,
pub(crate) pous: Vec<ast::Pou>,
}
/// Read every PLC source file under `root` (Structured Text, and PLCopen XML
/// exports) into its POUs. Files with no POU are left out.
///
/// Each file is decoded by [`compliance_core::encoding::read_source`]:
/// CODESYS and TIA exports are often Windows-1252 or UTF-16. Files still not
/// readable as text are logged as one warning per tree.
pub(crate) fn read_tree(root: &Path) -> Vec<PlcFile> {
let mut files = Vec::new();
let mut unreadable: u32 = 0;
for entry in walkdir::WalkDir::new(root)
.into_iter()
.filter_map(|e| e.ok())
@@ -66,8 +84,17 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
if !is_st && !is_xml {
continue;
}
let Ok(content) = std::fs::read_to_string(path) else {
continue;
let content = match compliance_core::encoding::read_source(path) {
Ok(text) => text,
Err(error) => {
// A binary `.project` is CODESYS's native format, which
// [`native_projects`] reports; anything else is a loss.
if ext != "project" {
tracing::debug!(file = %path.display(), %error, "PLC source file not readable");
unreadable += 1;
}
continue;
}
};
// A `.project` is read only as a PLCopen export; CODESYS's native one
// is binary ([`native_projects`] reports it).
@@ -82,16 +109,41 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
if pous.is_empty() {
continue;
}
let rel = path
.strip_prefix(root)
.unwrap_or(path)
.to_string_lossy()
.to_string();
for pou in &pous {
files.push(PlcFile {
rel: path
.strip_prefix(root)
.unwrap_or(path)
.to_string_lossy()
.to_string(),
plcopen: is_xml,
line_count: content.lines().count() as u32,
pous,
});
}
// One line per tree; the paths are logged at debug level only.
if unreadable > 0 {
tracing::warn!(
unreadable_files = unreadable,
"PLC source files left out: not readable as text"
);
}
files
}
/// Run the control-logic rules over the POUs of `files`.
pub(crate) fn findings(files: &[PlcFile], repo_id: &str) -> Vec<Finding> {
let mut findings = Vec::new();
for file in files {
for pou in &file.pous {
for hit in rules::analyze(pou) {
let line_s = hit.line.to_string();
let fingerprint =
dedup::compute_fingerprint(&[repo_id, &rel, hit.rule_id, &pou.name, &line_s]);
let fingerprint = dedup::compute_fingerprint(&[
repo_id,
&file.rel,
hit.rule_id,
&pou.name,
&line_s,
]);
let mut f = Finding::new(
repo_id.to_string(),
fingerprint,
@@ -101,7 +153,7 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
hit.description,
hit.severity,
);
f.file_path = Some(rel.clone());
f.file_path = Some(file.rel.clone());
f.line_number = Some(hit.line);
f.rule_id = Some(hit.rule_id.to_string());
f.cwe = hit.cwe.map(String::from);
@@ -113,6 +165,11 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
findings
}
/// Walk a PLC project tree and produce findings.
pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
findings(&read_tree(root), repo_id)
}
/// Whether `content` starts as an XML document (after a byte-order mark and
/// white space).
fn looks_like_xml(content: &str) -> bool {
@@ -152,10 +209,9 @@ pub fn native_projects(root: &Path) -> Vec<String> {
.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)),
// Decoded as [`read_tree`] reads it: a UTF-16 export is no native one.
"project" => !compliance_core::encoding::read_source(path)
.is_ok_and(|text| looks_like_xml(&text)),
"projectarchive" => sbom::check_archive(path).is_ok(),
_ => false,
};
@@ -349,4 +405,41 @@ mod tests {
// The binary project yields no POUs and no error.
assert!(analyze_tree(&root.0, "t").is_empty());
}
#[test]
fn windows_1252_and_utf16_sources_are_read() {
// Arrange: Structured Text as older CODESYS saves it (Windows-1252:
// "Größe" is F6 DF, "€" is 80), and a PLCopen export in UTF-16 LE.
let root =
Scratch(std::env::temp_dir().join(format!("cs-plc-enc-{}", uuid::Uuid::new_v4())));
std::fs::create_dir_all(&root.0).expect("mkdir");
std::fs::write(
root.0.join("legacy.st"),
b"PROGRAM Legacy\nVAR\n s : STRING := 'Gr\xF6\xDFe in \x80';\nEND_VAR\n\
s := 'x'; (* Gr\xF6\xDFe *)\nEND_PROGRAM\n",
)
.expect("write st");
let xml = "<?xml version=\"1.0\" encoding=\"UTF-16\"?>\
<project xmlns=\"http://www.plcopen.org/xml/tc6_0201\"><types><pous>\
<pou name=\"Wide\" pouType=\"program\"><interface><localVars>\
<variable name=\"Größe\"><type><INT/></type></variable></localVars></interface>\
<body><ST><xhtml xmlns=\"http://www.w3.org/1999/xhtml\">x := 1;</xhtml></ST></body>\
</pou></pous></types></project>";
let utf16: Vec<u8> = [0xFF, 0xFE]
.into_iter()
.chain(xml.encode_utf16().flat_map(u16::to_le_bytes))
.collect();
std::fs::write(root.0.join("wide.xml"), utf16).expect("write xml");
// Act
let files = read_tree(&root.0);
// Assert
let mut pous: Vec<&str> = files
.iter()
.flat_map(|f| f.pous.iter().map(|p| p.name.as_str()))
.collect();
pous.sort_unstable();
assert_eq!(pous, ["Legacy", "Wide"]);
}
}
@@ -119,6 +119,7 @@ impl Parser {
body.push(s);
}
}
let end_line = self.line();
self.eat_kw(end);
Some(Pou {
@@ -127,6 +128,7 @@ impl Parser {
vars,
body,
line,
end_line,
})
}
+10 -1
View File
@@ -49,7 +49,16 @@ pub fn parse_plcopen(xml: &str) -> Vec<Pou> {
_ => "PROGRAM",
};
let synthetic = format!("{kw} {name}\n{var_block}{body}\nEND_{kw}\n");
pous.extend(parser::parse(&synthetic));
// Statement lines stay those of the synthetic source (the findings'
// lines and fingerprints use them); the POU itself spans its
// `<pou>` element in the XML, which is what the code graph shows.
let start = doc.text_pos_at(pou.range().start).row;
let end = doc.text_pos_at(pou.range().end).row;
pous.extend(parser::parse(&synthetic).into_iter().map(|mut parsed| {
parsed.line = start;
parsed.end_line = end;
parsed
}));
}
pous
}
@@ -45,6 +45,11 @@ 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`].
@@ -84,6 +89,9 @@ impl RepoView {
findings_count: target.findings_count,
managed: target.source_repo.is_some(),
uploads_allow_skip: crate::pipeline::change::uploads_allow_git_skip(target),
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(),
+6 -4
View File
@@ -19,9 +19,10 @@ pub fn relative_path(root: &Path, path: &str) -> String {
rel.to_string_lossy().replace('\\', "/")
}
/// The whole text of `root/rel`. `None` when the file is unreadable or the
/// path would leave `root`: scanner output is not trusted to stay inside the
/// tree.
/// The whole text of `root/rel`, decoded by
/// [`compliance_core::encoding::read_source`]. `None` when the file is
/// unreadable or the path would leave `root`: scanner output is not trusted
/// to stay inside the tree.
pub fn read_text(root: &Path, rel: &str) -> Option<String> {
let rel_path = Path::new(rel);
if rel_path.is_absolute()
@@ -31,7 +32,8 @@ pub fn read_text(root: &Path, rel: &str) -> Option<String> {
{
return None;
}
std::fs::read_to_string(root.join(rel_path)).ok()
// UTF-16 with a BOM and Windows-1252 too, as the code graph reads them.
compliance_core::encoding::read_source(&root.join(rel_path)).ok()
}
/// Lines `start..=end` (1-based, inclusive) of `root/rel`, capped at
+182 -7
View File
@@ -13,11 +13,19 @@
//! working copy is a git clone, restored on every fetch, or an unpacked
//! upload, unpacked again on every scan, so nothing is lost.
//!
//! Matching is by directory name only, and narrow: `tests/` and `spec/`
//! hold test code that can leak a real secret, and `examples/` or `demo/` are
//! often the product's own code, so neither is matched.
//! 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::path::Path;
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__`),
@@ -32,8 +40,13 @@ const TEST_DATA_DIR_NAMES: &[&str] = &[
"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. A directory inside one that already matched is not
/// 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.
///
@@ -47,6 +60,9 @@ const TEST_DATA_DIR_NAMES: &[&str] = &[
/// "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 {
@@ -54,6 +70,12 @@ pub fn test_data_dirs(root: &Path) -> Vec<String> {
};
// `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;
}
@@ -69,8 +91,97 @@ pub fn test_data_dirs(root: &Path) -> Vec<String> {
walker.skip_current_dir();
}
}
found.sort();
found
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
@@ -228,6 +339,70 @@ mod tests {
);
}
/// 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();
+64
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)]
@@ -634,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", ""] {
+694 -89
View File
@@ -1,74 +1,170 @@
//! How many scans run at once, and what happens to a scan requested while the
//! same target is already being scanned.
//! How many scans run at once, in which order they get a slot, and what
//! happens to a scan requested while the same target is already queued or
//! being scanned.
//!
//! Every scan used to be a bare `tokio::spawn` with no limit. A burst of pushes,
//! a scheduler tick and a few clicks could start any number of scans side by
//! side — each one a clone plus semgrep plus syft — on an 8 GB node, and two
//! scans of the same target shared one checkout directory and corrupted each
//! other. Two rules now apply to every trigger (click, webhook, scheduler):
//! other. These rules now apply to every trigger (click, webhook, scheduler):
//!
//! * **Global:** at most `SCAN_CONCURRENCY` scans run at a time; the rest wait
//! for a slot.
//! * **Per target — coalesce:** one scan runs and at most one more is pending.
//! A request that arrives while one is pending is dropped, because the pending
//! scan will pick up the latest code anyway. Ten pushes during a long scan
//! therefore cost two scans, not ten. Dropped requests are never billed: only
//! a scan that actually ran emits usage.
//! * **Order:** a scan a person started ([`Priority::Person`]) gets a free slot
//! before scheduled, webhook and new-content scans ([`Priority::Background`]);
//! within a class the first to ask is the first served. So that a stream of
//! clicks never starves the scheduler, a waiting background scan gets the
//! slot after [`PERSON_GRANTS_IN_A_ROW`] person scans in a row (t84).
//! * **Per target — coalesce:** one scan of a target waits or runs, and while
//! it runs at most one more is pending. A request while the scan still waits
//! for its slot is covered by it (it reads the latest code once it starts);
//! a request while one is pending is covered by that one. Ten pushes during
//! a long scan therefore cost two scans, not ten. A person's request takes
//! over a waiting or pending scan that was not a person's, so it runs at
//! person priority and always scans. Requests that do not run are never
//! billed: only a scan that actually ran emits usage.
//!
//! Each admitted request carries the id of the run recorded for it while it
//! waits (status `queued`); the gate tells the caller which of those runs will
//! not happen, so no queued run is left behind.
//!
//! A scheduled scan also starts after a random delay of up to
//! [`SCHEDULED_SCAN_JITTER`], so the scans of a tenant's repositories (often
//! all on one git host) do not start in the same second.
use std::sync::Arc;
use std::collections::VecDeque;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use dashmap::mapref::entry::Entry;
use dashmap::DashMap;
use rand::Rng;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use tokio::sync::oneshot;
use compliance_core::models::ScanTrigger;
/// The longest a scheduled scan waits before it starts.
pub const SCHEDULED_SCAN_JITTER: Duration = Duration::from_secs(30);
/// How many slots in a row go to person-started scans while a background scan
/// waits; the next one goes to the background scan.
pub const PERSON_GRANTS_IN_A_ROW: u32 = 3;
/// How long a scan with `trigger` waits before it starts: a random delay of
/// up to [`SCHEDULED_SCAN_JITTER`] for a scheduled scan, none for a scan a
/// webhook or a person started.
pub fn start_delay(trigger: &ScanTrigger) -> Duration {
match trigger {
ScanTrigger::Scheduled => rand::rng().random_range(Duration::ZERO..=SCHEDULED_SCAN_JITTER),
ScanTrigger::Webhook | ScanTrigger::Manual | ScanTrigger::Support => Duration::ZERO,
ScanTrigger::Webhook
| ScanTrigger::Manual
| ScanTrigger::Support
| ScanTrigger::NewContent => Duration::ZERO,
}
}
/// Which queue a scan waits in for a slot.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Priority {
/// Started by a person (the customer or support): served first.
Person,
/// Scheduled, webhook and new-content scans, and PR reviews.
Background,
}
impl Priority {
/// The queue a scan with `trigger` waits in.
pub fn of(trigger: &ScanTrigger) -> Self {
if trigger.started_by_person() {
Self::Person
} else {
Self::Background
}
}
}
/// One scan to run: what started it and the run recorded for it while it
/// waits (`None` when that record could not be written).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Job {
pub trigger: ScanTrigger,
pub run_id: Option<String>,
/// Set when a person's request took over a waiting scan that was not a
/// person's: that scan's trigger, which the run is charged as (t84).
pub charged_as: Option<ScanTrigger>,
}
impl Job {
/// A scan started by `trigger`, recorded as the run `run_id`.
pub fn new(trigger: ScanTrigger, run_id: Option<String>) -> Self {
Self {
trigger,
run_id,
charged_as: None,
}
}
fn priority(&self) -> Priority {
Priority::of(&self.trigger)
}
}
/// What happened to a scan request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Admission {
/// Nothing was running for this target: the caller runs the scan now.
/// Nothing was queued or running for this target: the caller now holds
/// it and runs its scans through [`ScanGate::start`].
Run,
/// A scan is running; this request becomes the single pending follow-up,
/// run by the task that holds the target once it finishes.
Coalesced,
/// A scan is running and a follow-up is already pending: nothing to do.
/// The request will run: as the target's pending follow-up, or in place
/// of the target's waiting scan. `replaced` is the run of the request it
/// took over, which will not happen.
Coalesced { replaced: Option<String> },
/// A scan already queued for this target covers the request: its own run
/// will not happen.
Dropped,
}
/// The scan queue is gone, or the target is no longer held.
#[derive(Debug, thiserror::Error)]
pub enum GateError {
#[error("the scan queue was closed")]
Closed,
#[error("the target is not held")]
NotHeld,
}
/// Global scan slots plus the per-target coalescing state.
#[derive(Debug)]
pub struct ScanGate {
slots: Arc<Semaphore>,
/// Present while a scan of the key is running; the value is the pending
/// follow-up's trigger, if one was requested meanwhile.
running: DashMap<String, Option<ScanTrigger>>,
slots: Arc<Slots>,
/// Present while a scan of the key waits or runs.
targets: DashMap<String, Held>,
}
/// The scans of one target that are queued or running.
#[derive(Debug)]
struct Held {
/// The scan that waits for a slot or runs now.
current: Job,
/// Whether `current` has its slot.
running: bool,
/// The follow-up requested while `current` runs.
pending: Option<Job>,
}
impl ScanGate {
/// A gate allowing `concurrency` scans at once (at least one).
pub fn new(concurrency: usize) -> Self {
Self {
slots: Arc::new(Semaphore::new(concurrency.max(1))),
running: DashMap::new(),
slots: Arc::new(Slots {
queue: Mutex::new(Queue {
free: concurrency.max(1),
person: VecDeque::new(),
background: VecDeque::new(),
person_grants: 0,
}),
}),
targets: DashMap::new(),
}
}
@@ -80,60 +176,253 @@ impl ScanGate {
/// Decide what to do with a scan request for `key`. Atomic per key, so two
/// simultaneous requests can never both be told to [`Admission::Run`].
pub fn admit(&self, key: &str, trigger: ScanTrigger) -> Admission {
match self.running.entry(key.to_string()) {
pub fn admit(&self, key: &str, job: Job) -> Admission {
// Lock order: a target's entry, then the slot queue (in `promote`).
// `start` keeps the same order and `Permit::drop` takes only the queue.
match self.targets.entry(key.to_string()) {
Entry::Vacant(v) => {
v.insert(None);
v.insert(Held {
current: job,
running: false,
pending: None,
});
Admission::Run
}
Entry::Occupied(mut o) if o.get().is_none() => {
o.insert(Some(trigger));
Admission::Coalesced
Entry::Occupied(mut o) => {
let held = o.get_mut();
let person = job.trigger.started_by_person();
// A person's request takes over a queued scan that is not a
// person's: that one might skip as unchanged (#465), theirs
// always scans, e.g. right after they uploaded new files.
let takes_over = |queued: &Job| person && !queued.trigger.started_by_person();
if !held.running {
// The waiting scan reads the latest code once it starts,
// so it covers the request, or the person's takes its
// place, at person priority. It would have run anyway,
// so it is charged as the scan it replaces.
if !takes_over(&held.current) {
return Admission::Dropped;
}
let job = Job {
charged_as: Some(held.current.trigger.clone()),
..job
};
let replaced = std::mem::replace(&mut held.current, job).run_id;
self.slots.promote(key);
return Admission::Coalesced { replaced };
}
match held.pending.as_ref().map(takes_over) {
None => {
held.pending = Some(job);
Admission::Coalesced { replaced: None }
}
Some(true) => {
let replaced = held.pending.replace(job).and_then(|p| p.run_id);
Admission::Coalesced { replaced }
}
Some(false) => Admission::Dropped,
}
}
// A person's request takes over a pending scheduled or webhook
// follow-up: that one may skip as unchanged (#465), theirs always
// scans, e.g. right after they uploaded new files.
Entry::Occupied(mut o)
if trigger.started_by_person()
&& o.get().as_ref().is_some_and(|p| !p.started_by_person()) =>
{
o.insert(Some(trigger));
Admission::Coalesced
}
Entry::Occupied(_) => Admission::Dropped,
}
}
/// Called by the task holding `key` after each scan. Returns the pending
/// follow-up to run next (the target stays held), or `None` once there is
/// nothing left, releasing the target.
pub fn finish(&self, key: &str) -> Option<ScanTrigger> {
match self.running.entry(key.to_string()) {
Entry::Occupied(mut o) => match o.get_mut().take() {
Some(next) => Some(next),
None => {
o.remove();
None
/// Wait for a slot for the held target `key`'s next scan, in the queue of
/// its priority, and return the slot with the scan to run. The scan is the
/// one current when the slot is granted: a person's request may have taken
/// it over meanwhile.
///
/// # Errors
///
/// [`GateError::NotHeld`] if `key` was released meanwhile, and
/// [`GateError::Closed`] if the queue is gone, which this gate never does.
pub async fn start(&self, key: &str) -> Result<(Permit, Job), GateError> {
let waiting = {
let held = self.targets.get(key).ok_or(GateError::NotHeld)?;
self.slots.enqueue(Some(key), held.current.priority())
// The entry's guard is dropped here, before waiting.
};
let permit = waiting.wait().await?;
let mut held = self.targets.get_mut(key).ok_or(GateError::NotHeld)?;
held.running = true;
Ok((permit, held.current.clone()))
}
/// Called by the task holding `key` after each scan. Returns whether a
/// follow-up is pending, to run next through [`Self::start`] (the target
/// stays held), or `false` once there is nothing left, releasing it.
pub fn finish(&self, key: &str) -> bool {
match self.targets.entry(key.to_string()) {
Entry::Occupied(mut o) => {
let held = o.get_mut();
match held.pending.take() {
Some(next) => {
held.current = next;
held.running = false;
true
}
None => {
o.remove();
false
}
}
},
Entry::Vacant(_) => None,
}
Entry::Vacant(_) => false,
}
}
/// Release `key` unconditionally, dropping any pending follow-up. Used when
/// the holding task dies, so the target does not stay "running" forever.
pub fn release(&self, key: &str) {
self.running.remove(key);
self.targets.remove(key);
}
/// Wait for one of the global scan slots. The slot is freed when the
/// returned permit is dropped.
/// Wait for a slot for work that is not a target's scan (a PR review).
/// The slot is freed when the returned permit is dropped.
///
/// # Errors
///
/// Only if the semaphore was closed, which this gate never does.
pub async fn slot(&self) -> Result<OwnedSemaphorePermit, tokio::sync::AcquireError> {
self.slots.clone().acquire_owned().await
/// Only if the queue is gone, which this gate never does.
pub async fn slot(&self, priority: Priority) -> Result<Permit, GateError> {
self.slots.enqueue(None, priority).wait().await
}
}
/// The slots and the two queues waiting for them.
#[derive(Debug)]
struct Slots {
queue: Mutex<Queue>,
}
#[derive(Debug)]
struct Queue {
/// Slots nobody holds. Only above zero while nobody waits.
free: usize,
person: VecDeque<Waiter>,
background: VecDeque<Waiter>,
/// Person scans granted in a row while a background scan waited.
person_grants: u32,
}
/// One request waiting for a slot; the slot is handed over through `grant`.
#[derive(Debug)]
struct Waiter {
/// The target it is for, so a person's request can move it forward.
key: Option<String>,
grant: oneshot::Sender<Permit>,
}
/// A request in a queue, or a slot already granted.
enum Waiting {
Granted(Permit),
Queued(oneshot::Receiver<Permit>),
}
impl Waiting {
async fn wait(self) -> Result<Permit, GateError> {
match self {
Self::Granted(permit) => Ok(permit),
// The sender only goes away unsent with the gate itself.
Self::Queued(grant) => grant.await.map_err(|_| GateError::Closed),
}
}
}
impl Slots {
/// The queue, also after a thread panicked while holding it: every change
/// to it is a single push or pop, so it is never left half-changed.
fn lock(&self) -> MutexGuard<'_, Queue> {
self.queue.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Take a free slot, or join the queue of `priority`.
fn enqueue(self: &Arc<Self>, key: Option<&str>, priority: Priority) -> Waiting {
let mut queue = self.lock();
if queue.free > 0 {
queue.free -= 1;
return Waiting::Granted(Permit::new(self));
}
let (grant, granted) = oneshot::channel();
let waiter = Waiter {
key: key.map(str::to_string),
grant,
};
match priority {
Priority::Person => queue.person.push_back(waiter),
Priority::Background => queue.background.push_back(waiter),
}
Waiting::Queued(granted)
}
/// Move the background request for `key`, if one waits, to the back of
/// the person queue.
fn promote(&self, key: &str) {
let mut queue = self.lock();
let found = queue
.background
.iter()
.position(|w| w.key.as_deref() == Some(key));
if let Some(waiter) = found.and_then(|i| queue.background.remove(i)) {
queue.person.push_back(waiter);
}
}
/// Hand a freed slot to the next request, or keep it free.
fn release(self: &Arc<Self>) {
let mut queue = self.lock();
while let Some(waiter) = queue.next() {
match waiter.grant.send(Permit::new(self)) {
Ok(()) => return,
// The request was given up (its task ended): the permit comes
// back unused, and the slot goes to the next one.
Err(mut unused) => unused.slots = None,
}
}
queue.free += 1;
}
}
impl Queue {
/// The next request to serve: person scans first, except that a waiting
/// background scan gets the slot after [`PERSON_GRANTS_IN_A_ROW`] person
/// scans in a row.
fn next(&mut self) -> Option<Waiter> {
let background_due = self.person.is_empty() || self.person_grants >= PERSON_GRANTS_IN_A_ROW;
if background_due {
if let Some(waiter) = self.background.pop_front() {
self.person_grants = 0;
return Some(waiter);
}
}
let waiter = self.person.pop_front()?;
self.person_grants = if self.background.is_empty() {
0
} else {
self.person_grants + 1
};
Some(waiter)
}
}
/// One scan slot; freed, and handed to the next request, when dropped.
#[derive(Debug)]
pub struct Permit {
/// `None` once the permit was given back unused.
slots: Option<Arc<Slots>>,
}
impl Permit {
fn new(slots: &Arc<Slots>) -> Self {
Self {
slots: Some(Arc::clone(slots)),
}
}
}
impl Drop for Permit {
fn drop(&mut self) {
if let Some(slots) = self.slots.take() {
slots.release();
}
}
}
@@ -172,10 +461,20 @@ impl Drop for HeldTarget<'_> {
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::{start_delay, Admission, HeldTarget, ScanGate, SCHEDULED_SCAN_JITTER};
use super::{
start_delay, Admission, HeldTarget, Job, Priority, ScanGate, PERSON_GRANTS_IN_A_ROW,
SCHEDULED_SCAN_JITTER,
};
use compliance_core::models::ScanTrigger;
use std::sync::{Arc, Mutex};
use std::time::Duration;
type Log = Arc<Mutex<Vec<(String, ScanTrigger)>>>;
fn job(trigger: ScanTrigger, run: &str) -> Job {
Job::new(trigger, Some(run.to_string()))
}
#[test]
fn a_scheduled_scan_waits_within_the_jitter() {
let delays: Vec<Duration> = (0..1000)
@@ -187,63 +486,175 @@ mod tests {
}
#[test]
fn webhook_manual_and_support_scans_start_at_once() {
fn webhook_manual_support_and_new_content_scans_start_at_once() {
for trigger in [
ScanTrigger::Webhook,
ScanTrigger::Manual,
ScanTrigger::Support,
ScanTrigger::NewContent,
] {
assert_eq!(start_delay(&trigger), Duration::ZERO);
}
}
#[test]
fn a_burst_coalesces_into_one_run_and_one_follow_up() {
fn only_a_persons_scan_has_person_priority() {
assert_eq!(Priority::of(&ScanTrigger::Manual), Priority::Person);
assert_eq!(Priority::of(&ScanTrigger::Support), Priority::Person);
for trigger in [
ScanTrigger::Scheduled,
ScanTrigger::Webhook,
ScanTrigger::NewContent,
] {
assert_eq!(Priority::of(&trigger), Priority::Background);
}
}
#[tokio::test]
async fn a_burst_coalesces_into_one_run_and_one_follow_up() {
let gate = ScanGate::new(2);
let key = ScanGate::key("acme", "t1");
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Coalesced);
for _ in 0..8 {
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Dropped);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r1")),
Admission::Run
);
let (_slot, running) = gate.start(&key).await.unwrap();
assert_eq!(running, job(ScanTrigger::Manual, "r1"));
assert_eq!(
gate.admit(&key, job(ScanTrigger::Webhook, "r2")),
Admission::Coalesced { replaced: None }
);
for i in 0..8 {
let run = format!("drop{i}");
assert_eq!(
gate.admit(&key, job(ScanTrigger::Webhook, &run)),
Admission::Dropped
);
}
// The holder runs the one follow-up, then releases the target.
assert!(gate.finish(&key).is_some());
assert!(gate.finish(&key).is_none());
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
assert!(gate.finish(&key));
let (_next, follow_up) = gate.start(&key).await.unwrap();
assert_eq!(follow_up, job(ScanTrigger::Webhook, "r2"));
assert!(!gate.finish(&key));
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r3")),
Admission::Run
);
}
#[test]
fn a_persons_request_takes_over_a_pending_scheduled_follow_up() {
fn a_scan_still_waiting_covers_requests_that_are_not_a_persons() {
let gate = ScanGate::new(1);
let key = ScanGate::key("acme", "t1");
assert_eq!(gate.admit(&key, ScanTrigger::Scheduled), Admission::Run);
assert_eq!(
gate.admit(&key, ScanTrigger::Scheduled),
Admission::Coalesced
gate.admit(&key, job(ScanTrigger::Scheduled, "r1")),
Admission::Run
);
// Not started yet, so it will read the push's code anyway.
assert_eq!(
gate.admit(&key, job(ScanTrigger::Webhook, "r2")),
Admission::Dropped
);
}
#[tokio::test]
async fn a_waiting_scan_taken_over_is_charged_as_the_scan_it_replaces() {
let gate = ScanGate::new(1);
let key = ScanGate::key("acme", "t1");
assert_eq!(
gate.admit(&key, job(ScanTrigger::Webhook, "r1")),
Admission::Run
);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r2")),
Admission::Coalesced {
replaced: Some("r1".into())
}
);
let (_slot, run) = gate.start(&key).await.unwrap();
assert_eq!(run.trigger, ScanTrigger::Manual);
assert_eq!(run.charged_as, Some(ScanTrigger::Webhook));
}
#[tokio::test]
async fn a_persons_follow_up_after_a_running_scan_is_charged_as_theirs() {
let gate = ScanGate::new(1);
let key = ScanGate::key("acme", "t1");
assert_eq!(
gate.admit(&key, job(ScanTrigger::Scheduled, "r1")),
Admission::Run
);
let (running, _) = gate.start(&key).await.unwrap();
// Pending behind the running scan, replacing a scheduled follow-up.
assert_eq!(
gate.admit(&key, job(ScanTrigger::Scheduled, "r2")),
Admission::Coalesced { replaced: None }
);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r3")),
Admission::Coalesced {
replaced: Some("r2".into())
}
);
drop(running);
assert!(gate.finish(&key));
let (_slot, follow_up) = gate.start(&key).await.unwrap();
assert_eq!(follow_up, job(ScanTrigger::Manual, "r3"));
assert_eq!(follow_up.charged_as, None);
}
#[tokio::test]
async fn a_persons_request_takes_over_a_pending_scheduled_follow_up() {
let gate = ScanGate::new(1);
let key = ScanGate::key("acme", "t1");
assert_eq!(
gate.admit(&key, job(ScanTrigger::Scheduled, "r1")),
Admission::Run
);
let _slot = gate.start(&key).await.unwrap();
assert_eq!(
gate.admit(&key, job(ScanTrigger::Scheduled, "r2")),
Admission::Coalesced { replaced: None }
);
// Clicked after uploading new files: the follow-up scans in full.
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Coalesced);
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Dropped);
assert_eq!(gate.admit(&key, ScanTrigger::Support), Admission::Dropped);
// Clicked after uploading new files: the follow-up scans in full, and
// the scheduled follow-up's queued run will not happen.
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r3")),
Admission::Coalesced {
replaced: Some("r2".into())
}
);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Webhook, "r4")),
Admission::Dropped
);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Support, "r5")),
Admission::Dropped
);
assert_eq!(gate.finish(&key), Some(ScanTrigger::Manual));
assert!(gate.finish(&key));
}
#[test]
fn targets_and_tenants_are_independent() {
let gate = ScanGate::new(2);
assert_eq!(
gate.admit(&ScanGate::key("acme", "t1"), ScanTrigger::Manual),
gate.admit(&ScanGate::key("acme", "t1"), job(ScanTrigger::Manual, "a")),
Admission::Run
);
assert_eq!(
gate.admit(&ScanGate::key("acme", "t2"), ScanTrigger::Manual),
gate.admit(&ScanGate::key("acme", "t2"), job(ScanTrigger::Manual, "b")),
Admission::Run
);
// Same target id in another tenant is another target.
assert_eq!(
gate.admit(&ScanGate::key("globex", "t1"), ScanTrigger::Manual),
gate.admit(
&ScanGate::key("globex", "t1"),
job(ScanTrigger::Manual, "c")
),
Admission::Run
);
}
@@ -252,34 +663,228 @@ mod tests {
fn a_dead_holder_does_not_leave_the_target_locked() {
let gate = ScanGate::new(1);
let key = ScanGate::key("acme", "t1");
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r1")),
Admission::Run
);
{
// The holding task ends without calling finish (panic / shutdown).
let _held = HeldTarget::new(&gate, key.clone());
}
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r2")),
Admission::Run
);
}
#[test]
fn a_disarmed_holder_leaves_the_state_to_finish() {
#[tokio::test]
async fn a_disarmed_holder_leaves_the_state_to_finish() {
let gate = ScanGate::new(1);
let key = ScanGate::key("acme", "t1");
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r1")),
Admission::Run
);
let _slot = gate.start(&key).await.unwrap();
HeldTarget::new(&gate, key.clone()).disarm();
// Still held: disarm does not release, finish does.
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Coalesced);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Webhook, "r2")),
Admission::Coalesced { replaced: None }
);
}
/// What `ComplianceAgent::run_target_scan` does once admitted: take a
/// slot, scan (here: log), and run the pending follow-up, if any.
async fn hold_and_scan(gate: Arc<ScanGate>, key: String, log: Log) {
loop {
{
let (_slot, job) = gate.start(&key).await.unwrap();
log.lock().unwrap().push((key.clone(), job.trigger));
}
if !gate.finish(&key) {
break;
}
}
}
/// Admit `trigger` for each of `targets` of tenant `acme`, each with a
/// task that scans it, queued in that order behind a slot held elsewhere.
async fn queue_targets(
gate: &Arc<ScanGate>,
targets: &[&str],
trigger: ScanTrigger,
log: &Log,
) -> Vec<tokio::task::JoinHandle<()>> {
let mut tasks = Vec::new();
for target in targets {
let key = ScanGate::key("acme", target);
assert_eq!(
gate.admit(&key, job(trigger.clone(), target)),
Admission::Run
);
tasks.push(tokio::spawn(hold_and_scan(gate.clone(), key, log.clone())));
// Let it queue for the slot before the next one does.
tokio::task::yield_now().await;
}
tasks
}
fn triggers(log: &Log) -> Vec<ScanTrigger> {
log.lock().unwrap().iter().map(|(_, t)| t.clone()).collect()
}
#[tokio::test]
async fn a_persons_scan_gets_the_next_slot_before_scheduled_scans() {
let gate = Arc::new(ScanGate::new(1));
let log = Log::default();
// Another tenant's scan has the only slot.
let busy = gate.slot(Priority::Background).await.unwrap();
let mut tasks = queue_targets(&gate, &["t1", "t2"], ScanTrigger::Scheduled, &log).await;
tasks.extend(queue_targets(&gate, &["t3"], ScanTrigger::Manual, &log).await);
drop(busy);
for task in tasks {
task.await.unwrap();
}
assert_eq!(
triggers(&log),
[
ScanTrigger::Manual,
ScanTrigger::Scheduled,
ScanTrigger::Scheduled
]
);
}
#[tokio::test]
async fn a_persons_request_takes_over_a_scheduled_scan_still_waiting() {
let gate = Arc::new(ScanGate::new(1));
let log = Log::default();
// Another tenant's scan has the only slot.
let busy = gate.slot(Priority::Background).await.unwrap();
// A scheduler tick admits three targets; all wait for the slot.
let tasks = queue_targets(&gate, &["t1", "t2", "t3"], ScanTrigger::Scheduled, &log).await;
// A person asks for t3 while its scheduled scan still waits, last.
let t3 = ScanGate::key("acme", "t3");
assert_eq!(
gate.admit(&t3, job(ScanTrigger::Manual, "click")),
Admission::Coalesced {
replaced: Some("t3".into())
}
);
drop(busy);
for task in tasks {
task.await.unwrap();
}
// Their scan runs first, once, in place of the scheduled one, and
// is charged as the scheduled one (asserted on the job below).
let order: Vec<(String, ScanTrigger)> = log.lock().unwrap().clone();
assert_eq!(
order,
[
(t3, ScanTrigger::Manual),
(ScanGate::key("acme", "t1"), ScanTrigger::Scheduled),
(ScanGate::key("acme", "t2"), ScanTrigger::Scheduled),
]
);
}
#[tokio::test]
async fn a_persons_follow_up_waits_only_for_the_running_scan() {
let gate = Arc::new(ScanGate::new(1));
let log = Log::default();
let t1 = ScanGate::key("acme", "t1");
assert_eq!(
gate.admit(&t1, job(ScanTrigger::Scheduled, "t1")),
Admission::Run
);
// t1's scheduled scan runs; two more targets queue behind it.
let (running, _) = gate.start(&t1).await.unwrap();
let tasks = queue_targets(&gate, &["t2", "t3"], ScanTrigger::Scheduled, &log).await;
assert_eq!(
gate.admit(&t1, job(ScanTrigger::Manual, "click")),
Admission::Coalesced { replaced: None }
);
// t1's scan ends; its follow-up queues as a person's.
assert!(gate.finish(&t1));
let follow_up = tokio::spawn(hold_and_scan(gate.clone(), t1.clone(), log.clone()));
tokio::task::yield_now().await;
drop(running);
follow_up.await.unwrap();
for task in tasks {
task.await.unwrap();
}
assert_eq!(
triggers(&log),
[
ScanTrigger::Manual,
ScanTrigger::Scheduled,
ScanTrigger::Scheduled
]
);
}
#[tokio::test]
async fn a_stream_of_clicks_does_not_starve_scheduled_scans() {
let gate = Arc::new(ScanGate::new(1));
let log = Log::default();
let busy = gate.slot(Priority::Background).await.unwrap();
let mut tasks = queue_targets(&gate, &["s1"], ScanTrigger::Scheduled, &log).await;
let clicks: Vec<String> = (0..10).map(|i| format!("p{i}")).collect();
let clicks: Vec<&str> = clicks.iter().map(String::as_str).collect();
tasks.extend(queue_targets(&gate, &clicks, ScanTrigger::Manual, &log).await);
drop(busy);
for task in tasks {
task.await.unwrap();
}
let scheduled_at = triggers(&log)
.iter()
.position(|t| *t == ScanTrigger::Scheduled)
.unwrap();
assert_eq!(scheduled_at, PERSON_GRANTS_IN_A_ROW as usize);
}
#[tokio::test]
async fn a_given_up_request_passes_its_slot_on() {
let gate = Arc::new(ScanGate::new(1));
let busy = gate.slot(Priority::Background).await.unwrap();
// A request that waits and is then given up (its task ends).
let gone = tokio::spawn({
let gate = gate.clone();
async move { gate.slot(Priority::Person).await.map(drop) }
});
tokio::task::yield_now().await;
gone.abort();
let _ = gone.await;
drop(busy);
let next = tokio::time::timeout(Duration::from_millis(50), gate.slot(Priority::Background));
assert!(
next.await.is_ok(),
"the slot is not lost to the given-up request"
);
}
#[tokio::test]
async fn slots_bound_how_many_scans_run_at_once() {
let gate = ScanGate::new(2);
let a = gate.slot().await.unwrap();
let _b = gate.slot().await.unwrap();
let a = gate.slot(Priority::Background).await.unwrap();
let _b = gate.slot(Priority::Background).await.unwrap();
// A third slot is not available until one is freed.
let third = tokio::time::timeout(std::time::Duration::from_millis(50), gate.slot()).await;
let third =
tokio::time::timeout(Duration::from_millis(50), gate.slot(Priority::Person)).await;
assert!(third.is_err(), "a third concurrent scan must wait");
drop(a);
let third = tokio::time::timeout(std::time::Duration::from_millis(50), gate.slot()).await;
let third =
tokio::time::timeout(Duration::from_millis(50), gate.slot(Priority::Person)).await;
assert!(third.is_ok(), "a freed slot is reused");
}
}
+28
View File
@@ -126,6 +126,34 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError>
.await
.map_err(|e| AgentError::Scheduler(format!("Failed to add git sync job: {e}")))?;
// Issues a person closed or reopened in Gitea (#953), for the targets no
// webhook reports them for; at the managed git sync's interval.
let poll_agent = agent.clone();
let poll_job = Job::new_repeated_async(agent.git_source.sync_interval, move |_uuid, _lock| {
let agent = poll_agent.clone();
Box::pin(async move {
for tenant_id in scheduler_tenants(&agent).await {
match crate::pipeline::issue_poll::poll_tenant(&agent, &tenant_id).await {
Ok(s) if s.targets > 0 => tracing::info!(
tenant_id,
targets = s.targets,
findings = s.findings,
recorded = s.recorded,
failed = s.failed,
"issue poll done"
),
Ok(_) => {}
Err(e) => tracing::warn!(tenant_id, "issue poll skipped: {e}"),
}
}
})
})
.map_err(|e| AgentError::Scheduler(format!("Failed to create issue poll job: {e}")))?;
sched
.add(poll_job)
.await
.map_err(|e| AgentError::Scheduler(format!("Failed to add issue poll job: {e}")))?;
sched
.start()
.await
+9
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,
+67
View File
@@ -176,6 +176,39 @@ impl GiteaTracker {
.await
}
/// The login of whoever last closed (`closed`) or reopened issue `number`,
/// from its timeline; `None` if the timeline has no such entry. The issue
/// itself does not say who closed it.
///
/// # Errors
///
/// [`CoreError::IssueTracker`] if the timeline cannot be read, or has more
/// than `MAX_TIMELINE_PAGES` pages.
pub async fn last_state_change_by(
&self,
owner: &str,
repo: &str,
number: i64,
closed: bool,
) -> Result<Option<String>, CoreError> {
let kind = if closed { "close" } else { "reopen" };
let events: Vec<GiteaTimelineEvent> = self
.list_all(
"issue timeline",
&format!("/repos/{owner}/{repo}/issues/{number}/timeline"),
MAX_TIMELINE_PAGES,
)
.await?;
// Oldest first: the last matching entry is the current state's.
Ok(events
.into_iter()
.rev()
.find(|e| e.kind == kind)
.and_then(|e| e.user)
.map(|u| u.login)
.filter(|login| !login.is_empty()))
}
/// Make sure the repository has every label in `wanted`, creating the
/// missing ones, and return the id of each by name. Needs write access to
/// the repository's issues, nothing more.
@@ -287,6 +320,25 @@ const LIST_PAGE_SIZE: usize = 50;
const MAX_LABEL_PAGES: usize = 20;
/// Upper bound on issue pages (10 000 issues).
const MAX_ISSUE_PAGES: usize = 200;
/// Upper bound on the timeline pages of one issue (1 000 entries).
const MAX_TIMELINE_PAGES: usize = 20;
/// A Gitea user, by login.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
pub struct GiteaUser {
#[serde(default)]
pub login: String,
}
/// An entry of an issue's timeline, with what a close or reopen needs:
/// `type` is `close`, `reopen`, `comment`, ...
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
struct GiteaTimelineEvent {
#[serde(rename = "type", default)]
kind: String,
#[serde(default)]
user: Option<GiteaUser>,
}
/// An issue as Gitea lists it, with what an issue is matched by.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
@@ -301,6 +353,21 @@ pub struct GiteaIssue {
/// `open` or `closed`.
#[serde(default)]
pub state: String,
/// Who opened it: Prüfwerk's issues are opened by its bot user.
#[serde(default)]
pub user: Option<GiteaUser>,
}
impl GiteaIssue {
/// The login of whoever opened the issue, empty if Gitea did not say.
pub fn author(&self) -> &str {
self.user.as_ref().map_or("", |u| u.login.as_str())
}
/// Whether the issue is closed.
pub fn is_closed(&self) -> bool {
self.state == "closed"
}
}
/// A repository label as Gitea returns it.
+20 -1
View File
@@ -6,7 +6,9 @@
//! source is read through a handle that cannot conjure a tenant database.
//!
//! A verified delivery that asks for work is answered `202 Accepted` at once;
//! the entitlement check, the target and the scan follow in the background,
//! the entitlement check, the target and the scan (or, for an issue closed
//! or reopened by a person, the finding's new status, #953) follow in the
//! background,
//! so a slow registry or Keycloak never runs into Gitea's delivery timeout.
//! What became of it (handled, refused, failed) is recorded for the target
//! page, since Gitea's delivery log only ever sees the `202`.
@@ -199,6 +201,9 @@ fn delivery_of(event: &str, result: &Result<Outcome, NotHandled>) -> WebhookDeli
Ok(Outcome::Archived(false)) => {
(DeliveryResult::Handled, "no active target to archive", None)
}
Ok(Outcome::Issue { target_id, detail }) => {
(DeliveryResult::Handled, *detail, Some(target_id.clone()))
}
Ok(Outcome::Ignored(why)) => (DeliveryResult::Handled, *why, None),
Err(NotHandled::Refused(why)) => (DeliveryResult::Refused, why.as_str(), None),
Err(NotHandled::Failed(why)) => (DeliveryResult::Failed, why.as_str(), None),
@@ -257,6 +262,20 @@ mod tests {
let d = delivery_of("repository", &Ok(ensured(false)));
assert_eq!(d.detail, "target ready, nothing to scan yet");
let issue = Outcome::Issue {
target_id: "t1".into(),
detail: "finding resolved: issue closed in Gitea",
};
let d = delivery_of("issues", &Ok(issue));
assert_eq!(
(d.result, d.detail.as_str(), d.target_id.as_deref()),
(
DeliveryResult::Handled,
"finding resolved: issue closed in Gitea",
Some("t1")
)
);
let d = delivery_of("repository", &Ok(Outcome::Archived(true)));
assert_eq!(
(d.result, d.detail.as_str()),
+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();
}
+149
View File
@@ -483,6 +483,155 @@ async fn platform_api_webhook_and_sync() {
h.pool.drop_tenant(TENANT).await.ok();
}
/// An issue a person closes or reopens in Gitea moves its finding (#953);
/// the same done by Prüfwerk's bot user is ignored, so nothing loops.
#[tokio::test]
async fn an_issue_closed_or_reopened_in_gitea_moves_its_finding() {
use compliance_core::models::{
Finding, FindingStatus, IssueStatus, ScanType, Severity, TrackerChangeKind, TrackerIssue,
TrackerType,
};
let Some(h) = start().await else { return };
let (status, created) = h
.put_source(serde_json::json!({
"base_url": "https://kunde.code.breakpilot.com", "org": "kunde",
"bot_token": "bot-pat", "enabled": false
}))
.await;
assert_eq!(status, 200, "{created}");
assert_eq!(
created["webhook_events"],
serde_json::json!(["repository", "push", "issues"])
);
let secret = created["webhook_secret"].as_str().unwrap().to_string();
h.db.git_sources()
.update_one(doc! {}, doc! { "$set": { "enabled": true } })
.await
.unwrap();
let send = |event: &'static str, body: serde_json::Value| {
let sig = sign(&secret, &serde_json::to_vec(&body).unwrap());
let h = &h;
async move { h.deliver(TENANT, event, &body, Some(sig)).await }
};
// Arrange: the repository's target, a finding and its issue #12.
let repo = repo_json(21, "kunde", "fw");
assert_eq!(
send(
"repository",
serde_json::json!({ "action": "created", "repository": repo })
)
.await,
202
);
Harness::eventually("the target", || async { h.target(21).await.is_some() }).await;
let target_id = h.target(21).await.unwrap().id.unwrap().to_hex();
let mut finding = Finding::new(
target_id.clone(),
"fp-backsync".into(),
"semgrep".into(),
ScanType::Sast,
"strcpy".into(),
"d".into(),
Severity::High,
);
finding.status = FindingStatus::NeedsReview;
let finding_id =
h.db.findings()
.insert_one(&finding)
.await
.unwrap()
.inserted_id
.as_object_id()
.unwrap();
let issue = TrackerIssue::new(
finding_id.to_hex(),
TrackerType::Gitea,
"12".into(),
"https://kunde.code.breakpilot.com/kunde/fw/issues/12".into(),
"strcpy".into(),
);
h.db.tracker_issues().insert_one(&issue).await.unwrap();
let issue_event = |action: &str, sender: &str| {
serde_json::json!({
"action": action, "number": 12,
"issue": { "number": 12, "user": { "login": "pruefwerk" } },
"sender": { "login": sender },
"repository": repo,
})
};
let stored = || async {
let f =
h.db.findings()
.find_one(doc! { "_id": finding_id })
.await
.unwrap()
.unwrap();
let i =
h.db.tracker_issues()
.find_one(doc! { "finding_id": finding_id.to_hex() })
.await
.unwrap()
.unwrap();
(f, i)
};
// Prüfwerk's own close (the bot opened the issue): answered at once,
// nothing changes.
assert_eq!(
send("issues", issue_event("closed", "pruefwerk")).await,
200
);
// A person closes it: resolved, as closed in the ticket by them.
assert_eq!(send("issues", issue_event("closed", "dev-anna")).await, 202);
Harness::eventually("the resolved finding", || async {
stored().await.0.status == FindingStatus::Resolved
})
.await;
let (f, i) = stored().await;
let change = f.status_history.last().unwrap();
assert_eq!(change.tracker, Some(TrackerChangeKind::ClosedInTracker));
assert_eq!(change.by_name.as_deref(), Some("dev-anna"));
assert_eq!(f.status_history.len(), 1, "the bot's close changed nothing");
assert_eq!(
(i.status, i.closed_in_tracker.as_deref()),
(IssueStatus::Closed, Some("dev-anna"))
);
let for_target = compliance_agent::webhooks::deliveries::target_filter(&target_id, None);
Harness::eventually("the recorded issue delivery", || async {
h.db.webhook_deliveries()
.count_documents({
let mut f = for_target.clone();
f.insert("detail", "finding resolved: issue closed in Gitea");
f
})
.await
.unwrap()
== 1
})
.await;
// Reopened: undecided again.
assert_eq!(
send("issues", issue_event("reopened", "dev-anna")).await,
202
);
Harness::eventually("the reopened finding", || async {
stored().await.0.status == FindingStatus::Open
})
.await;
let (f, i) = stored().await;
assert_eq!(
f.status_history.last().unwrap().tracker,
Some(TrackerChangeKind::ReopenedInTracker)
);
assert_eq!((i.status, i.closed_in_tracker), (IssueStatus::Open, None));
h.pool.drop_tenant(TENANT).await.ok();
}
/// A deliveries collection written before the indexes were ensured (a plain
/// one) is converted to a capped one.
#[tokio::test]
+386
View File
@@ -0,0 +1,386 @@
//! The "Heute" inbox (#950) through the real API: cards in their buckets,
//! decisions on a card through the findings' and VEX code, undo, and
//! resubmission dates.
//!
//! Runs against a live Mongo (`TEST_MONGODB_URI`) and skips cleanly without
//! one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
mod common;
use chrono::{Duration, Utc};
use compliance_core::models::inbox::{CardKey, InboxSnooze};
use compliance_core::models::{CveAlert, CveSource, Exploitation, KevEntry};
use mongodb::bson::{doc, oid::ObjectId, Document};
use serde_json::{json, Value};
use common::TestServer;
/// A target id and its name.
const TARGET: &str = "665f1c2ab0c4d1e2f3a4b5c6";
/// Whether a Mongo answers at the test URI.
async fn mongo_reachable() -> bool {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let Ok(client) = mongodb::Client::with_uri_str(&uri).await else {
return false;
};
client
.database("admin")
.run_command(doc! { "ping": 1 })
.await
.is_ok()
}
async fn tenant_db(server: &TestServer) -> mongodb::Database {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
mongodb::Client::with_uri_str(&uri)
.await
.unwrap()
.database(&server.tenant_db_name())
}
/// Store a finding; its id.
async fn finding(
db: &mongodb::Database,
title: &str,
scan_type: &str,
severity: &str,
status: &str,
file: &str,
) -> String {
let id = ObjectId::new();
let now = mongodb::bson::DateTime::now();
db.collection::<Document>("findings")
.insert_one(doc! {
"_id": id,
"repo_id": TARGET,
"fingerprint": format!("fp-{title}"),
"scanner": "test",
"scan_type": scan_type,
"title": title,
"description": title,
"severity": severity,
"status": status,
"file_path": file,
"line_number": 7,
"triage_action": if status == "needs_review" { "dismiss" } else { "confirm" },
"status_history": [],
"created_at": now,
"updated_at": now,
})
.await
.unwrap();
id.to_hex()
}
/// Store a CVE alert of log4j-core 2.14.1; its id.
async fn alert(db: &mongodb::Database, cve: &str, kev: bool) -> String {
let mut a = CveAlert::new(
cve.into(),
TARGET.into(),
"log4j-core".into(),
"2.14.1".into(),
CveSource::Osv,
);
let id = ObjectId::new();
a.id = Some(id);
a.severity = Some("CRITICAL".into());
a.fixed_versions = vec!["2.17.1".into()];
if kev {
a.exploitation = Some(Exploitation {
kev: Some(KevEntry {
date_added: "2021-12-10".into(),
known_ransomware: true,
}),
..Exploitation::default()
});
a.exploited_seen_at = Some(Utc::now() - Duration::hours(2));
}
db.collection::<CveAlert>("cve_alerts")
.insert_one(&a)
.await
.unwrap();
id.to_hex()
}
async fn inbox(server: &TestServer, query: &str) -> Value {
let resp = server.get(&format!("/api/v1/inbox{query}")).await;
assert_eq!(resp.status(), 200);
let body: Value = resp.json().await.unwrap();
body["data"].clone()
}
fn counts(view: &Value) -> [u64; 4] {
let c = &view["counts"];
[
c["today"].as_u64().unwrap(),
c["this_week"].as_u64().unwrap(),
c["later"].as_u64().unwrap(),
c["likely_false_positive"].as_u64().unwrap(),
]
}
#[tokio::test]
async fn the_inbox_buckets_decides_undoes_and_resubmits() {
if !mongo_reachable().await {
eprintln!("SKIP inbox: no MongoDB reachable");
return;
}
let server = TestServer::start().await;
let db = tenant_db(&server).await;
db.collection::<Document>("onboarded_targets")
.insert_one(doc! { "_id": ObjectId::parse_str(TARGET).unwrap(), "name": "Pumpe", "target_type": "software" })
.await
.unwrap();
let secret = finding(
&db,
"AWS key",
"secretdetection",
"medium",
"open",
"src/config.rs",
)
.await;
let _test_secret = finding(
&db,
"Test key",
"secretdetection",
"low",
"open",
"tests/keys.env",
)
.await;
let high = finding(&db, "SQL injection", "sast", "high", "triaged", "src/db.rs").await;
let ai = finding(
&db,
"Weak hash",
"sast",
"medium",
"needs_review",
"src/hash.rs",
)
.await;
finding(
&db,
"Old decision",
"sast",
"low",
"false_positive",
"src/a.rs",
)
.await;
let a1 = alert(&db, "CVE-2021-44228", true).await;
let a2 = alert(&db, "CVE-2021-45046", false).await;
// Today: the secret in code and log4j (KEV); this week: the high finding;
// later: the test secret; the AI's: the dismissed one.
let all = inbox(&server, "").await;
assert_eq!(counts(&all), [2, 1, 1, 1]);
assert_eq!(all["progress"], json!({ "decided": 1, "total": 7 }));
assert_eq!(
all["targets"],
json!([{
"id": TARGET,
"name": "Pumpe",
"counts": { "today": 2, "this_week": 1, "later": 1, "likely_false_positive": 1 },
}])
);
let today = all["cards"].as_array().unwrap();
let log4j = today
.iter()
.find(|c| c["kind"] == "cve_package")
.unwrap()
.clone();
let log4j_key = CardKey::cve_package(TARGET, "log4j-core", "2.14.1");
assert_eq!(log4j["key"], log4j_key);
assert_eq!(log4j["count"], 2);
assert_eq!(log4j["fix_version"], "2.17.1");
assert_eq!(log4j["reasons"][0]["kind"], "kev");
assert!(today
.iter()
.any(|c| c["item_ids"] == json!([secret]) && c["reasons"][0]["kind"] == "secret_in_code"));
let ai_card = inbox(&server, "?bucket=likely_false_positive").await["cards"][0].clone();
assert_eq!(ai_card["actions"], json!(["false_positive", "confirm"]));
assert_eq!(inbox(&server, "?target=other").await["counts"]["today"], 0);
// A CVE decision needs its justification; with it, every alert of the
// card gets the statement, and undo puts them back to open.
let refused = server
.post(
"/api/v1/inbox/decide",
&json!({ "key": log4j_key, "action": "not_affected" }),
)
.await;
assert_eq!(refused.status(), 422);
let decided = server
.post(
"/api/v1/inbox/decide",
&json!({
"key": log4j_key,
"action": "not_affected",
"justification": "vulnerable_code_not_in_execute_path",
}),
)
.await;
assert_eq!(decided.status(), 200);
let decided: Value = decided.json().await.unwrap();
let mut previous = decided["previous"].as_array().unwrap().clone();
previous.sort_by_key(|p| p["id"].as_str().unwrap().to_string());
let mut expected = vec![
json!({ "kind": "cve", "id": a1, "vex": null }),
json!({ "kind": "cve", "id": a2, "vex": null }),
];
expected.sort_by_key(|p| p["id"].as_str().unwrap().to_string());
assert_eq!(previous, expected);
let stored = db
.collection::<CveAlert>("cve_alerts")
.find_one(doc! { "_id": ObjectId::parse_str(&a1).unwrap() })
.await
.unwrap()
.unwrap();
assert_eq!(
stored.vex.map(|v| v.status),
Some(compliance_core::models::VexStatus::NotAffected)
);
let after = inbox(&server, "").await;
assert_eq!(counts(&after), [1, 1, 1, 1]);
assert_eq!(after["progress"], json!({ "decided": 3, "total": 7 }));
let again = server
.post(
"/api/v1/inbox/decide",
&json!({ "key": log4j_key, "action": "affected", "statement": "Update" }),
)
.await;
assert_eq!(again.status(), 409, "nothing left to decide");
let undone = server
.post(
"/api/v1/inbox/undo",
&json!({ "key": log4j_key, "previous": decided["previous"] }),
)
.await;
assert_eq!(undone.status(), 200);
assert_eq!(counts(&inbox(&server, "").await), [2, 1, 1, 1]);
// A finding's risk needs a reason; the status change is recorded as the
// findings endpoint records it, and undo restores the previous status.
let high_key = CardKey::finding(&high);
let no_reason = server
.post(
"/api/v1/inbox/decide",
&json!({ "key": high_key, "action": "accepted_risk" }),
)
.await;
assert_eq!(no_reason.status(), 422);
let not_offered = server
.post(
"/api/v1/inbox/decide",
&json!({ "key": high_key, "action": "confirm" }),
)
.await;
assert_eq!(not_offered.status(), 422);
let accepted: Value = server
.post(
"/api/v1/inbox/decide",
&json!({ "key": high_key, "action": "accepted_risk", "reason": "isolated network" }),
)
.await
.json()
.await
.unwrap();
assert_eq!(
accepted["previous"],
json!([{ "kind": "finding", "id": high, "status": "triaged" }])
);
let stored = db
.collection::<Document>("findings")
.find_one(doc! { "_id": ObjectId::parse_str(&high).unwrap() })
.await
.unwrap()
.unwrap();
assert_eq!(stored.get_str("status").ok(), Some("accepted_risk"));
let history = stored.get_array("status_history").unwrap();
assert_eq!(
history[0].as_document().unwrap().get_str("reason").ok(),
Some("isolated network")
);
assert_eq!(counts(&inbox(&server, "").await), [2, 0, 1, 1]);
let undone = server
.post(
"/api/v1/inbox/undo",
&json!({ "key": high_key, "previous": accepted["previous"] }),
)
.await;
assert_eq!(undone.status(), 200);
assert_eq!(counts(&inbox(&server, "").await), [2, 1, 1, 1]);
// Undo only touches the card's own items.
let foreign = server
.post(
"/api/v1/inbox/undo",
&json!({ "key": high_key, "previous": [{ "kind": "finding", "id": ai, "status": "open" }] }),
)
.await;
assert_eq!(foreign.status(), 422);
// The AI was right: the dismissed finding is a false positive.
let confirmed = server
.post(
"/api/v1/inbox/decide",
&json!({ "key": CardKey::finding(&ai), "action": "false_positive" }),
)
.await;
assert_eq!(confirmed.status(), 200);
assert_eq!(counts(&inbox(&server, "").await), [2, 1, 1, 0]);
// Put off: hidden until the date, then back in its own bucket (today).
let secret_key = CardKey::finding(&secret);
let past = server
.post(
"/api/v1/inbox/snooze",
&json!({ "key": secret_key, "for": { "kind": "date", "date": "2020-01-01" } }),
)
.await;
assert_eq!(past.status(), 422);
let snoozed = server
.post(
"/api/v1/inbox/snooze",
&json!({ "key": secret_key, "for": { "kind": "week" } }),
)
.await;
assert_eq!(snoozed.status(), 200);
assert_eq!(counts(&inbox(&server, "").await), [1, 1, 1, 0]);
let record = db
.collection::<InboxSnooze>("inbox_snoozes")
.find_one(doc! { "key": &secret_key })
.await
.unwrap()
.unwrap();
assert_eq!(record.by, "dev-user");
assert!(record.until > Utc::now() + Duration::days(6));
// The card's items are recorded, so a new one would end the snooze early.
assert_eq!(record.items, std::slice::from_ref(&secret));
db.collection::<Document>("inbox_snoozes")
.update_one(
doc! { "key": &secret_key },
doc! { "$set": { "until": mongodb::bson::DateTime::from_chrono(Utc::now() - Duration::hours(1)) } },
)
.await
.unwrap();
let due = inbox(&server, "?bucket=today").await;
assert_eq!(counts(&due), [2, 1, 1, 0]);
assert!(due["cards"]
.as_array()
.unwrap()
.iter()
.any(|c| c["key"] == secret_key && c["reasons"][0]["kind"] == "resubmission"));
let unsnoozed = server
.delete(&format!("/api/v1/inbox/snooze/{secret_key}"))
.await;
assert_eq!(unsnoozed.status(), 200);
assert_eq!(counts(&inbox(&server, "").await), [2, 1, 1, 0]);
server.cleanup().await;
}
@@ -0,0 +1,89 @@
//! 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, month_summary, 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);
// The usage view reads the same month.
let summary = month_summary(&db, at).await.unwrap();
assert_eq!(summary.month, "2026-11");
assert_eq!((summary.pruefungen, summary.prueftage), (2, 1));
assert_eq!((summary.extra_targets, summary.extra_peak), (0, 0));
pool.drop_tenant(TENANT).await.ok();
}
+4 -3
View File
@@ -563,8 +563,8 @@ async fn collect(agent: &Agent, target_id: &str, run: &Value) -> Collected {
}
/// Wait until each target has a finished scan run that did not exist before
/// seeding. Returns the run per target id; targets still running at the
/// deadline are left out.
/// seeding. Returns the run per target id; targets still queued or running
/// at the deadline are left out.
async fn wait_for_runs(
agent: &Agent,
targets: &[String],
@@ -580,7 +580,8 @@ async fn wait_for_runs(
if done.contains_key(&repo)
|| !targets.contains(&repo)
|| before.contains(&oid(&run))
|| text(&run, "status") == "running"
// Still waiting for a slot (t84) or scanning: not finished.
|| matches!(text(&run, "status").as_str(), "queued" | "running")
{
continue;
}
+64 -1
View File
@@ -196,7 +196,7 @@ async fn only_what_was_left_out_is_closed_for_a_stage_without_a_seen_set() {
.with_excluded(vec!["legacy".to_string()])
.with_test_data(vec!["fixtures".to_string()]);
let closed = run
.resolve_left_out(&db, TARGET, "plc-control-logic")
.resolve_left_out(&db, TARGET, Some("plc-control-logic"))
.await
.unwrap();
@@ -228,3 +228,66 @@ async fn only_what_was_left_out_is_closed_for_a_stage_without_a_seen_set() {
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();
}
+187
View File
@@ -0,0 +1,187 @@
//! A target's "Verlauf" (#957) through the real API: per scan the CVE
//! alerts found new and gone since the completed scan before it.
//!
//! Runs against a live Mongo (`TEST_MONGODB_URI`) and skips cleanly without
//! one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
mod common;
use chrono::{DateTime, Duration, Utc};
use compliance_core::component_changes::{ComponentChange, ComponentChangeKind};
use compliance_core::models::{CveAlert, CveSource, ScanRun, ScanRunStatus, ScanTrigger};
use mongodb::bson::{doc, oid::ObjectId, Document};
use serde_json::Value;
use common::TestServer;
const TARGET: &str = "665f1c2ab0c4d1e2f3a4b5c7";
async fn mongo_reachable() -> bool {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let Ok(client) = mongodb::Client::with_uri_str(&uri).await else {
return false;
};
client
.database("admin")
.run_command(doc! { "ping": 1 })
.await
.is_ok()
}
/// Store a run of the target that started `start` and ended `end`, with the
/// component changes it recorded.
async fn run(
db: &mongodb::Database,
status: ScanRunStatus,
start: DateTime<Utc>,
end: Option<DateTime<Utc>>,
components: Option<Vec<ComponentChange>>,
) {
let mut run = ScanRun::new(TARGET.into(), ScanTrigger::Scheduled);
run.status = status;
run.started_at = start;
run.completed_at = end;
run.component_changes = components;
db.collection::<ScanRun>("scan_runs")
.insert_one(&run)
.await
.unwrap();
}
/// Store an alert of the target found at `created`, gone at `resolved`.
async fn alert(
db: &mongodb::Database,
cve: &str,
created: DateTime<Utc>,
resolved: Option<DateTime<Utc>>,
) {
let mut a = CveAlert::new(
cve.into(),
TARGET.into(),
"openssl".into(),
"3.0.9".into(),
CveSource::Osv,
);
a.severity = Some("HIGH".into());
a.created_at = created;
a.resolved_at = resolved;
db.collection::<CveAlert>("cve_alerts")
.insert_one(&a)
.await
.unwrap();
}
/// The CVE ids of a change's `side` (`new_cves` or `gone_cves`).
fn cves(change: &Value, side: &str) -> Vec<String> {
change[side]
.as_array()
.unwrap()
.iter()
.map(|c| c["cve"].as_str().unwrap().to_string())
.collect()
}
#[tokio::test]
async fn each_scan_shows_the_cves_it_found_new_and_gone() {
if !mongo_reachable().await {
eprintln!("SKIP scan_changes: no MongoDB reachable");
return;
}
let server = TestServer::start().await;
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db = mongodb::Client::with_uri_str(&uri)
.await
.unwrap()
.database(&server.tenant_db_name());
db.collection::<Document>("onboarded_targets")
.insert_one(doc! { "_id": ObjectId::parse_str(TARGET).unwrap(), "name": "Pumpe", "target_type": "software" })
.await
.unwrap();
// Arrange: three scans, the middle one failed; one CVE from the first
// scan goes in the last, one comes with it.
let t0 = Utc::now() - Duration::days(3);
let hour = |h: i64| t0 + Duration::hours(h);
run(&db, ScanRunStatus::Completed, hour(0), Some(hour(1)), None).await;
run(&db, ScanRunStatus::Failed, hour(24), Some(hour(25)), None).await;
// The last one recorded its components (#974): openssl was updated.
let updated = ComponentChange {
kind: ComponentChangeKind::Updated,
package_manager: "npm".into(),
name: "openssl".into(),
from: Some("3.0.9".into()),
to: Some("3.0.11".into()),
};
run(
&db,
ScanRunStatus::Completed,
hour(48),
Some(hour(49)),
Some(vec![updated]),
)
.await;
alert(&db, "CVE-2026-1001", hour(1), Some(hour(49))).await;
alert(&db, "CVE-2026-1002", hour(1), None).await;
alert(&db, "CVE-2026-1003", hour(49), None).await;
// Act
let resp = server
.get(&format!("/api/v1/targets/{TARGET}/scan-changes"))
.await;
assert_eq!(resp.status(), 200);
let body: Value = resp.json().await.unwrap();
let changes = body["data"].as_array().unwrap();
// Assert: oldest first; the first is the baseline, the failed one
// changes nothing, the last has one new and one gone.
assert_eq!(changes.len(), 3);
assert_eq!(changes[0]["baseline"], true);
assert!(cves(&changes[0], "new_cves").is_empty());
assert_eq!(changes[1]["status"], "failed");
assert!(cves(&changes[1], "new_cves").is_empty());
assert_eq!(cves(&changes[2], "new_cves"), ["CVE-2026-1003"]);
assert_eq!(cves(&changes[2], "gone_cves"), ["CVE-2026-1001"]);
// The update took the gone CVE (at 3.0.9). The new one names 3.0.9 too,
// which the update left, so no change explains it: an advisory row,
// after the change of the same component.
assert!(changes[0].get("components").is_none(), "not recorded");
let rows = changes[2]["components"].as_array().unwrap();
let read: Vec<(&str, &str, u64, u64)> = rows
.iter()
.map(|r| {
(
r["kind"].as_str().unwrap(),
r["name"].as_str().unwrap(),
r["cves_new"].as_u64().unwrap(),
r["cves_gone"].as_u64().unwrap(),
)
})
.collect();
assert_eq!(
read,
[("updated", "openssl", 0, 1), ("advisory", "openssl", 1, 0)]
);
// With a limit the oldest scans drop out, and the window of the first
// shown one starts at the end of the completed scan before it.
let resp = server
.get(&format!("/api/v1/targets/{TARGET}/scan-changes?limit=1"))
.await;
let body: Value = resp.json().await.unwrap();
let changes = body["data"].as_array().unwrap();
assert_eq!(changes.len(), 1);
assert_eq!(changes[0]["baseline"], false);
assert_eq!(cves(&changes[0], "new_cves"), ["CVE-2026-1003"]);
// An unknown target is a 404.
let resp = server
.get("/api/v1/targets/665f1c2ab0c4d1e2f3a4b5ff/scan-changes")
.await;
assert_eq!(resp.status(), 404);
server.cleanup().await;
}
+250
View File
@@ -0,0 +1,250 @@
//! A scan request shows at once as a run waiting for a slot (t84): the run is
//! recorded `queued` before the scan gets one of the agent's slots, a person's
//! request takes over a waiting webhook scan without leaving its queued run
//! behind, a request covered by the waiting scan leaves none, and the run
//! leaves `queued` once its scan had its turn. Runs against a live Mongo
//! (`TEST_MONGODB_URI`) and skips cleanly without one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
mod common;
use std::sync::Arc;
use std::time::Duration;
use futures_util::TryStreamExt;
use mongodb::bson::doc;
use compliance_agent::agent::ComplianceAgent;
use compliance_agent::database::Database;
use compliance_agent::scan_gate::Priority;
use compliance_core::models::{ScanRun, ScanRunStatus, ScanTrigger};
use common::dev_config;
const TENANT: &str = "scanqueue";
async fn runs(db: &Database, target_id: &str) -> Vec<ScanRun> {
db.scan_runs()
.find(doc! { "repo_id": target_id })
.await
.unwrap()
.try_collect()
.await
.unwrap()
}
/// Wait until the runs of `target_id` satisfy `done`, and return them.
async fn until(db: &Database, target_id: &str, done: impl Fn(&[ScanRun]) -> bool) -> Vec<ScanRun> {
for _ in 0..200 {
let found = runs(db, target_id).await;
if done(&found) {
return found;
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
panic!(
"runs never reached the expected state: {:?}",
runs(db, target_id).await
);
}
#[tokio::test]
async fn a_request_shows_as_queued_until_its_scan_has_a_slot() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db_name = format!("sq_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]);
let Ok(pool) = compliance_agent::database::DatabasePool::connect(&uri, &db_name).await else {
eprintln!("SKIP scan_queue: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
let mut config = dev_config(uri, db_name);
config.scan_concurrency = 1;
let agent = Arc::new(ComplianceAgent::new(config, pool.clone()));
// No such target, so its scan ends at once when it gets the slot.
let target = mongodb::bson::oid::ObjectId::new().to_hex();
// Arrange: another scan has the only slot.
let busy = agent.scan_gate.slot(Priority::Background).await.unwrap();
// Act 1: a push asks for a scan; it waits, recorded as queued.
let holder = tokio::spawn({
let (agent, target) = (agent.clone(), target.clone());
async move {
agent
.run_target_scan(TENANT, &target, ScanTrigger::Webhook)
.await
}
});
let queued = until(&db, &target, |r| r.len() == 1).await;
assert_eq!(queued[0].status, ScanRunStatus::Queued);
assert_eq!(queued[0].trigger, ScanTrigger::Webhook);
assert!(queued[0].queued_at.is_some());
// Act 2: a person asks while it waits: theirs takes its place, and only
// their queued run is left. Another push is covered and leaves none.
agent
.run_target_scan(TENANT, &target, ScanTrigger::Manual)
.await
.unwrap();
agent
.run_target_scan(TENANT, &target, ScanTrigger::Webhook)
.await
.unwrap();
let waiting = runs(&db, &target).await;
assert_eq!(waiting.len(), 1, "one queued run: {waiting:?}");
assert_eq!(waiting[0].status, ScanRunStatus::Queued);
assert_eq!(waiting[0].trigger, ScanTrigger::Manual);
// Act 3: the slot frees; the person's scan has its turn.
drop(busy);
assert!(holder.await.unwrap().is_err(), "the unknown target fails");
// Assert: the same run, no longer queued.
let done = runs(&db, &target).await;
assert_eq!(done.len(), 1);
assert_eq!(done[0].id, waiting[0].id);
assert_eq!(done[0].status, ScanRunStatus::Failed);
assert!(done[0].completed_at.is_some());
pool.drop_tenant(TENANT).await.ok();
}
#[tokio::test]
async fn the_scan_runs_on_the_run_that_waited() {
use compliance_core::models::{OnboardedTarget, TargetType};
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db_name = format!("sq_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]);
let Ok(pool) = compliance_agent::database::DatabasePool::connect(&uri, &db_name).await else {
eprintln!("SKIP scan_queue: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
let mut config = dev_config(uri, db_name);
config.scan_concurrency = 1;
let agent = Arc::new(ComplianceAgent::new(config, pool.clone()));
// A target with nothing attached yet: its scan has nothing to read.
let target = db
.onboarded_targets()
.insert_one(OnboardedTarget::new(
"empty".into(),
TargetType::BackendService,
))
.await
.unwrap()
.inserted_id
.as_object_id()
.unwrap()
.to_hex();
let busy = agent.scan_gate.slot(Priority::Background).await.unwrap();
let holder = tokio::spawn({
let (agent, target) = (agent.clone(), target.clone());
async move {
agent
.run_target_scan(TENANT, &target, ScanTrigger::Manual)
.await
}
});
let queued = until(&db, &target, |r| r.len() == 1).await;
assert_eq!(queued[0].status, ScanRunStatus::Queued);
tokio::time::sleep(Duration::from_millis(20)).await;
drop(busy);
holder.await.unwrap().ok();
// The scan used the queued run: one run, started after it was requested.
let done = runs(&db, &target).await;
assert_eq!(done.len(), 1, "{done:?}");
assert_eq!(done[0].id, queued[0].id);
assert_ne!(done[0].status, ScanRunStatus::Queued);
assert!(done[0].started_at > done[0].queued_at.unwrap());
pool.drop_tenant(TENANT).await.ok();
}
/// The run of `target`'s scan by `trigger`, started while another scan has the
/// only slot; with `takes_over`, a webhook scan waits first and the person's
/// request takes it over.
async fn scan_with_slot_busy(
agent: &Arc<ComplianceAgent>,
db: &Database,
target: &str,
takes_over: bool,
) -> ScanRun {
let busy = agent.scan_gate.slot(Priority::Background).await.unwrap();
let first = if takes_over {
ScanTrigger::Webhook
} else {
ScanTrigger::Manual
};
let holder = tokio::spawn({
let (agent, target) = (agent.clone(), target.to_string());
async move { agent.run_target_scan(TENANT, &target, first).await }
});
until(db, target, |r| r.len() == 1).await;
if takes_over {
agent
.run_target_scan(TENANT, target, ScanTrigger::Manual)
.await
.unwrap();
}
drop(busy);
holder.await.unwrap().ok();
let mut done = runs(db, target).await;
assert_eq!(done.len(), 1, "{done:?}");
done.remove(0)
}
#[tokio::test]
async fn a_taken_over_scan_is_charged_as_the_scan_it_replaces() {
use compliance_core::models::{OnboardedTarget, ScanAttribution, TargetType};
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db_name = format!("sq_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]);
let Ok(pool) = compliance_agent::database::DatabasePool::connect(&uri, &db_name).await else {
eprintln!("SKIP scan_queue: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
let mut config = dev_config(uri, db_name);
config.scan_concurrency = 1;
let agent = Arc::new(ComplianceAgent::new(config, pool.clone()));
let new_target = || {
let db = db.clone();
async move {
let target = OnboardedTarget::new("t".into(), TargetType::BackendService);
db.onboarded_targets()
.insert_one(target)
.await
.unwrap()
.inserted_id
.as_object_id()
.unwrap()
.to_hex()
}
};
// A person's request that took over a waiting webhook scan of an
// included target: their priority and attribution, but not counted, as
// the webhook scan would not have been.
let included = new_target().await;
let run = scan_with_slot_busy(&agent, &db, &included, true).await;
assert_eq!(run.trigger, ScanTrigger::Manual);
assert_eq!(run.attribution, Some(ScanAttribution::Request));
assert_eq!(run.charged_as, Some(ScanTrigger::Webhook));
assert!(!run.chargeable, "it would have run anyway: {run:?}");
// A person's own scan, not taking any over, counts as their request.
let asked = new_target().await;
let run = scan_with_slot_busy(&agent, &db, &asked, false).await;
assert_eq!(run.attribution, Some(ScanAttribution::Request));
assert_eq!(run.charged_as, None);
assert!(run.chargeable);
pool.drop_tenant(TENANT).await.ok();
}
+150
View File
@@ -0,0 +1,150 @@
//! 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();
}
#[tokio::test]
async fn a_swap_moves_both_and_holds_the_one_swapped_in_until_month_end() {
use compliance_agent::metering::swap;
use compliance_core::models::SwapRefusal;
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!("swap_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP target_billing swap: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
// Arrange: three targets on a plan with two included: the newest is extra.
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]);
assign_billing(&db, Some(2)).await.unwrap();
let nov6 = chrono::TimeZone::with_ymd_and_hms(&Utc, 2026, 11, 6, 9, 0, 0)
.single()
.unwrap();
// Act: swap the newest in for the oldest.
let swapped = swap(&db, newest, oldest, true, nov6).await.unwrap();
assign_billing(&db, Some(2)).await.unwrap();
// Assert: they changed places; the count of extra targets is the same.
assert_eq!(swapped, Some(Ok(())));
assert_eq!(billing(&db, newest).await, TargetBilling::Included);
assert_eq!(billing(&db, oldest).await, TargetBilling::Extra);
assert_eq!(billing(&db, middle).await, TargetBilling::Included);
// The one swapped in stays included this month; another may go out.
assert_eq!(
swap(&db, oldest, newest, true, nov6).await.unwrap(),
Some(Err(SwapRefusal::Locked))
);
assert_eq!(
swap(&db, oldest, middle, true, nov6).await.unwrap(),
Some(Ok(()))
);
assign_billing(&db, Some(2)).await.unwrap();
assert_eq!(billing(&db, middle).await, TargetBilling::Extra);
// From December, the target swapped in on 6 Nov may go out again.
let dec1 = chrono::TimeZone::with_ymd_and_hms(&Utc, 2026, 12, 1, 9, 0, 0)
.single()
.unwrap();
assert_eq!(
swap(&db, middle, newest, true, dec1).await.unwrap(),
Some(Ok(()))
);
assert_eq!(
swap(&db, middle, ObjectId::new(), true, dec1)
.await
.unwrap(),
None,
"an unknown target"
);
pool.drop_tenant(TENANT).await.ok();
}
+2
View File
@@ -45,6 +45,8 @@ serde = { workspace = true }
serde_json = { workspace = true }
chrono = { workspace = true }
thiserror = { workspace = true }
# Decoding source files: BOM sniffing, UTF-16, Windows-1252
encoding_rs = { workspace = true }
sha2 = { workspace = true }
hex = { workspace = true }
uuid = { workspace = 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());
}
}
+172
View File
@@ -0,0 +1,172 @@
//! What a scan changed in a target's SBOM (#974): the components it added,
//! updated and removed, against the SBOM stored before it.
//!
//! A component is its package manager and name; its versions are compared
//! as sets, since a target can hold two copies of a library. One version
//! before and one after is an update; otherwise each version that is new is
//! an addition and each that is gone a removal.
use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
/// The most component changes a scan records; a larger change (a first
/// firmware import, a new build system) keeps the first ones in name order.
pub const MAX_CHANGES: usize = 5000;
/// How a component changed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ComponentChangeKind {
Added,
Updated,
Removed,
}
/// One component a scan added, updated or removed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ComponentChange {
pub kind: ComponentChangeKind,
pub package_manager: String,
pub name: String,
/// The version before; `None` for an addition.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub from: Option<String>,
/// The version after; `None` for a removal.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub to: Option<String>,
}
/// A component as the comparison sees it: package manager, name, version.
pub type ComponentKey<'a> = (&'a str, &'a str, &'a str);
/// The versions of each component (package manager, name) in `components`.
fn by_component<'a>(
components: &[ComponentKey<'a>],
) -> BTreeMap<(&'a str, &'a str), BTreeSet<&'a str>> {
let mut map: BTreeMap<_, BTreeSet<_>> = BTreeMap::new();
for (manager, name, version) in components {
map.entry((*manager, *name)).or_default().insert(*version);
}
map
}
/// The changes from `before` to `after`, by component name, at most
/// [`MAX_CHANGES`].
///
/// # Examples
///
/// ```
/// use compliance_core::component_changes::{diff, ComponentChangeKind};
///
/// let before = [("npm", "lodash", "4.17.20")];
/// let after = [("npm", "lodash", "4.17.21")];
/// let changes = diff(&before, &after);
/// assert_eq!(changes[0].kind, ComponentChangeKind::Updated);
/// ```
pub fn diff(before: &[ComponentKey<'_>], after: &[ComponentKey<'_>]) -> Vec<ComponentChange> {
let (old, new) = (by_component(before), by_component(after));
let empty = BTreeSet::new();
let keys: BTreeSet<_> = old.keys().chain(new.keys()).copied().collect();
let mut changes = Vec::new();
for (manager, name) in keys {
let was = old.get(&(manager, name)).unwrap_or(&empty);
let is = new.get(&(manager, name)).unwrap_or(&empty);
if was == is {
continue;
}
let change = |kind, from: Option<&str>, to: Option<&str>| ComponentChange {
kind,
package_manager: manager.to_string(),
name: name.to_string(),
from: from.map(str::to_string),
to: to.map(str::to_string),
};
if let ([from], [to]) = (
was.iter().collect::<Vec<_>>().as_slice(),
is.iter().collect::<Vec<_>>().as_slice(),
) {
changes.push(change(ComponentChangeKind::Updated, Some(from), Some(to)));
continue;
}
for version in was.difference(is) {
changes.push(change(ComponentChangeKind::Removed, Some(version), None));
}
for version in is.difference(was) {
changes.push(change(ComponentChangeKind::Added, None, Some(version)));
}
}
changes.truncate(MAX_CHANGES);
changes
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_sbom_change_reads_as_additions_updates_and_removals() {
let before = [
("npm", "lodash", "4.17.20"),
("npm", "left-pad", "1.3.0"),
("cargo", "serde", "1.0.200"),
// Two copies, one goes.
("npm", "minimist", "1.2.5"),
("npm", "minimist", "1.2.8"),
];
let after = [
("npm", "lodash", "4.17.21"),
("cargo", "serde", "1.0.200"),
("npm", "minimist", "1.2.8"),
("npm", "zod", "3.23.0"),
];
let changes = diff(&before, &after);
let read: Vec<(ComponentChangeKind, &str, Option<&str>, Option<&str>)> = changes
.iter()
.map(|c| (c.kind, c.name.as_str(), c.from.as_deref(), c.to.as_deref()))
.collect();
assert_eq!(
read,
[
(
ComponentChangeKind::Removed,
"left-pad",
Some("1.3.0"),
None
),
(
ComponentChangeKind::Updated,
"lodash",
Some("4.17.20"),
Some("4.17.21")
),
(
ComponentChangeKind::Removed,
"minimist",
Some("1.2.5"),
None
),
(ComponentChangeKind::Added, "zod", None, Some("3.23.0")),
]
);
assert!(diff(&after, &after).is_empty());
}
#[test]
fn the_same_name_in_another_package_manager_is_another_component() {
let changes = diff(&[("npm", "uuid", "9.0.0")], &[("cargo", "uuid", "9.0.0")]);
let kinds: Vec<_> = changes
.iter()
.map(|c| (c.kind, c.package_manager.as_str()))
.collect();
assert_eq!(
kinds,
[
(ComponentChangeKind::Added, "cargo"),
(ComponentChangeKind::Removed, "npm")
]
);
}
}
+432
View File
@@ -0,0 +1,432 @@
//! A target's open CVE alerts grouped by the component they are in (#949):
//! what one update of the component fixes, so that whoever triages decides
//! once per package instead of once per CVE.
//!
//! Open means not settled: no `not_affected` or `fixed` statement, and not
//! found gone by a complete scan (see [`crate::vex_docs::status_of`]).
use std::cmp::Ordering;
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::models::CveAlert;
use crate::version::cmp_dotted;
use crate::vex_docs::status_of;
/// How severe a CVE is, as the groups count it. `Info` is a CVE the
/// advisory rates neither by name nor by CVSS score.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CveSeverity {
Info,
Low,
Medium,
High,
Critical,
}
impl CveSeverity {
/// The severity of `alert`: the advisory's rating (GitHub's `MODERATE`
/// is medium), else its CVSS score, else `Info`.
pub fn of(alert: &CveAlert) -> Self {
let named = alert.severity.as_deref().map(str::to_ascii_lowercase);
match named.as_deref() {
Some("critical") => Self::Critical,
Some("high") => Self::High,
Some("moderate" | "medium") => Self::Medium,
Some("low") => Self::Low,
_ => match alert.cvss_score {
Some(score) if score >= 9.0 => Self::Critical,
Some(score) if score >= 7.0 => Self::High,
Some(score) if score >= 4.0 => Self::Medium,
Some(score) if score > 0.0 => Self::Low,
_ => Self::Info,
},
}
}
/// The severity as the dashboard's badge names it (`high`).
pub fn as_str(self) -> &'static str {
match self {
Self::Info => "info",
Self::Low => "low",
Self::Medium => "medium",
Self::High => "high",
Self::Critical => "critical",
}
}
}
/// How many CVEs of a group have each severity.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SeverityCounts {
pub critical: usize,
pub high: usize,
pub medium: usize,
pub low: usize,
pub info: usize,
}
impl SeverityCounts {
fn add(&mut self, severity: CveSeverity) {
let count = match severity {
CveSeverity::Critical => &mut self.critical,
CveSeverity::High => &mut self.high,
CveSeverity::Medium => &mut self.medium,
CveSeverity::Low => &mut self.low,
CveSeverity::Info => &mut self.info,
};
*count += 1;
}
/// Each severity with its count, most severe first.
pub fn by_severity(&self) -> [(CveSeverity, usize); 5] {
[
(CveSeverity::Critical, self.critical),
(CveSeverity::High, self.high),
(CveSeverity::Medium, self.medium),
(CveSeverity::Low, self.low),
(CveSeverity::Info, self.info),
]
}
/// The most severe severity counted, `Info` when none is.
pub fn max(&self) -> CveSeverity {
self.by_severity()
.into_iter()
.find(|(_, count)| *count > 0)
.map_or(CveSeverity::Info, |(severity, _)| severity)
}
}
/// The component a group is about, as its alerts name it.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct PackageKey {
pub package: String,
pub version: String,
/// The component's purl (`pkg:npm/vite@5.4.21`), when the alerts carry
/// one.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub purl: Option<String>,
}
impl PackageKey {
/// The key of the component `alert` is about.
pub fn of(alert: &CveAlert) -> Self {
Self {
package: alert.affected_package.clone(),
version: alert.affected_version.clone(),
purl: alert.purl.clone(),
}
}
/// Whether `alert` is about this component.
pub fn matches(&self, alert: &CveAlert) -> bool {
self.package == alert.affected_package
&& self.version == alert.affected_version
&& self.purl == alert.purl
}
}
/// Whether `alert` still asks for a decision: neither stated `not_affected`
/// or `fixed`, nor found gone by a complete scan.
pub fn is_open(alert: &CveAlert) -> bool {
!status_of(alert).resolves()
}
/// The open CVE alerts of one component.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CveGroup {
#[serde(flatten)]
pub key: PackageKey,
/// The highest version above the component's own that the advisories
/// name as fixed: the update that fixes every CVE naming a fix.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fix_version: Option<String>,
/// How many of the CVEs name a fixed version, and so are fixed by
/// updating to `fix_version`.
pub fixable: usize,
/// The CVEs per severity; a CVE in several alerts (a GitHub advisory
/// and the NVD entry it aliases) counts once, at its highest severity.
pub counts: SeverityCounts,
/// Whether any of them is in CISA's KEV catalog.
pub kev: bool,
/// The highest EPSS score among them, 0 to 1.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub epss_max: Option<f64>,
/// The CVE ids, each once, sorted.
pub cve_ids: Vec<String>,
/// The alerts (hex object ids) a group decision states VEX on.
pub alert_ids: Vec<String>,
}
/// What [`group_open_alerts`] gathers per CVE: its highest severity and
/// whether an advisory names a fix above the component's version.
#[derive(Default)]
struct CveTally {
severity: Option<CveSeverity>,
fixable: bool,
}
/// The open alerts of `alerts` grouped by component, the most severe group
/// first (then the one with more CVEs, then by name and version).
pub fn group_open_alerts(alerts: &[CveAlert]) -> Vec<CveGroup> {
let mut by_component: BTreeMap<PackageKey, Vec<&CveAlert>> = BTreeMap::new();
for alert in alerts.iter().filter(|a| is_open(a)) {
by_component
.entry(PackageKey::of(alert))
.or_default()
.push(alert);
}
let mut groups: Vec<CveGroup> = by_component
.into_iter()
.map(|(key, members)| group(key, &members))
.collect();
groups.sort_by(|a, b| {
b.counts
.max()
.cmp(&a.counts.max())
.then_with(|| b.cve_ids.len().cmp(&a.cve_ids.len()))
.then_with(|| a.key.cmp(&b.key))
});
groups
}
/// The group of component `key` from its open alerts `members`.
fn group(key: PackageKey, members: &[&CveAlert]) -> CveGroup {
let above_current = |v: &&String| cmp_dotted(v, &key.version) == Ordering::Greater;
let mut tallies: BTreeMap<&str, CveTally> = BTreeMap::new();
let mut fix_version: Option<&String> = None;
let mut kev = false;
let mut epss_max: Option<f64> = None;
for alert in members {
let tally = tallies.entry(alert.cve()).or_default();
tally.severity = tally.severity.max(Some(CveSeverity::of(alert)));
for fixed in alert.fixed_versions.iter().filter(above_current) {
tally.fixable = true;
if fix_version.is_none_or(|best| cmp_dotted(fixed, best) == Ordering::Greater) {
fix_version = Some(fixed);
}
}
if let Some(exploitation) = &alert.exploitation {
kev |= exploitation.kev.is_some();
if let Some(epss) = &exploitation.epss {
epss_max = Some(epss_max.map_or(epss.score, |m| m.max(epss.score)));
}
}
}
let mut counts = SeverityCounts::default();
for tally in tallies.values() {
counts.add(tally.severity.unwrap_or(CveSeverity::Info));
}
CveGroup {
fix_version: fix_version.cloned(),
fixable: tallies.values().filter(|t| t.fixable).count(),
counts,
kev,
epss_max,
cve_ids: tallies.keys().map(|id| (*id).to_string()).collect(),
alert_ids: members
.iter()
.filter_map(|a| a.id.map(|o| o.to_hex()))
.collect(),
key,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::models::vex::{VexAssessment, VexStatus};
use crate::models::{CveSource, EpssScore, Exploitation, KevEntry};
fn alert(id: &str, package: &str, version: &str, severity: Option<&str>) -> CveAlert {
let mut a = CveAlert::new(
id.into(),
"t1".into(),
package.into(),
version.into(),
CveSource::Osv,
);
a.id = Some(bson::oid::ObjectId::new());
a.purl = Some(format!("pkg:npm/{package}@{version}"));
a.severity = severity.map(String::from);
a
}
fn fixed_in(mut a: CveAlert, versions: &[&str]) -> CveAlert {
a.fixed_versions = versions.iter().map(|v| v.to_string()).collect();
a
}
fn stated(mut a: CveAlert, status: VexStatus) -> CveAlert {
a.vex = Some(VexAssessment {
status,
justification: None,
impact_statement: Some("Build tool only.".into()),
action_statement: None,
by: "u1".into(),
by_name: None,
at: chrono::Utc::now(),
by_scan: false,
});
a
}
#[test]
fn severities_come_from_the_rating_then_the_cvss_score() {
let mut a = alert("CVE-2024-0001", "vite", "5.4.21", Some("MODERATE"));
assert_eq!(CveSeverity::of(&a), CveSeverity::Medium);
a.severity = None;
assert_eq!(CveSeverity::of(&a), CveSeverity::Info);
a.cvss_score = Some(9.8);
assert_eq!(CveSeverity::of(&a), CveSeverity::Critical);
a.cvss_score = Some(0.0);
assert_eq!(CveSeverity::of(&a), CveSeverity::Info);
a.severity = Some("High".into());
assert_eq!(CveSeverity::of(&a), CveSeverity::High);
assert_eq!(
serde_json::to_value(CveSeverity::Critical).ok(),
Some(serde_json::json!("critical"))
);
}
#[test]
fn open_alerts_group_by_component_with_the_highest_fix() {
let alerts = vec![
fixed_in(
alert("CVE-2025-0001", "vite", "5.4.21", Some("HIGH")),
&["5.4.22", "6.3.6"],
),
fixed_in(
alert("CVE-2025-0002", "vite", "5.4.21", Some("LOW")),
&["8.3.3"],
),
fixed_in(alert("CVE-2025-0003", "vite", "5.4.21", None), &["8.10.0"]),
// A fix below the component's version fixes nothing here.
fixed_in(alert("CVE-2025-0004", "vite", "5.4.21", None), &["4.0.0"]),
alert("CVE-2025-0005", "vite", "6.0.0", Some("CRITICAL")),
alert("CVE-2025-0006", "lodash", "4.17.20", Some("HIGH")),
];
let groups = group_open_alerts(&alerts);
let keys: Vec<(&str, &str)> = groups
.iter()
.map(|g| (g.key.package.as_str(), g.key.version.as_str()))
.collect();
// Most severe first; among the two `high` groups, more CVEs first.
assert_eq!(
keys,
[("vite", "6.0.0"), ("vite", "5.4.21"), ("lodash", "4.17.20")]
);
let vite = &groups[1];
assert_eq!(vite.fix_version.as_deref(), Some("8.10.0"));
assert_eq!(vite.fixable, 3);
assert_eq!(
vite.counts,
SeverityCounts {
high: 1,
low: 1,
info: 2,
..SeverityCounts::default()
}
);
assert_eq!(
vite.cve_ids,
[
"CVE-2025-0001",
"CVE-2025-0002",
"CVE-2025-0003",
"CVE-2025-0004"
]
);
assert_eq!(vite.alert_ids.len(), 4);
assert_eq!(groups[2].fix_version, None);
assert_eq!(groups[2].fixable, 0);
}
#[test]
fn settled_alerts_are_left_out_and_a_cve_counts_once() {
let mut gone = alert("CVE-2025-0003", "vite", "5.4.21", Some("HIGH"));
gone.resolved_at = Some(chrono::Utc::now());
let mut ghsa = alert("GHSA-aaaa-bbbb-cccc", "vite", "5.4.21", Some("LOW"));
ghsa.aliases = vec!["CVE-2025-0001".into()];
let alerts = vec![
alert("CVE-2025-0001", "vite", "5.4.21", Some("MEDIUM")),
ghsa,
stated(
alert("CVE-2025-0002", "vite", "5.4.21", Some("CRITICAL")),
VexStatus::NotAffected,
),
gone,
// Affected and under investigation still ask for a decision.
stated(
alert("CVE-2025-0004", "vite", "5.4.21", None),
VexStatus::Affected,
),
];
let groups = group_open_alerts(&alerts);
assert_eq!(groups.len(), 1);
let vite = &groups[0];
assert_eq!(vite.cve_ids, ["CVE-2025-0001", "CVE-2025-0004"]);
assert_eq!(vite.alert_ids.len(), 3);
assert_eq!(
vite.counts,
SeverityCounts {
medium: 1,
info: 1,
..SeverityCounts::default()
}
);
assert!(group_open_alerts(&alerts[2..4]).is_empty());
}
#[test]
fn a_group_has_the_worst_exploitation_of_its_cves() {
let mut kev = alert("CVE-2025-0001", "vite", "5.4.21", Some("LOW"));
kev.exploitation = Some(Exploitation {
kev: Some(KevEntry::default()),
epss: Some(EpssScore {
score: 0.2,
percentile: 0.9,
date: String::new(),
}),
ssvc_exploitation: None,
});
let mut likely = alert("CVE-2025-0002", "vite", "5.4.21", Some("LOW"));
likely.exploitation = Some(Exploitation {
epss: Some(EpssScore {
score: 0.7,
percentile: 0.99,
date: String::new(),
}),
..Exploitation::default()
});
let groups = group_open_alerts(&[kev, likely]);
assert!(groups[0].kev);
assert_eq!(groups[0].epss_max, Some(0.7));
let quiet = group_open_alerts(&[alert("CVE-2025-0003", "vite", "5.4.21", None)]);
assert!(!quiet[0].kev);
assert_eq!(quiet[0].epss_max, None);
}
#[test]
fn a_key_matches_the_alerts_of_its_component_only() {
let a = alert("CVE-2025-0001", "vite", "5.4.21", None);
let key = PackageKey::of(&a);
assert!(key.matches(&a));
let mut other_version = a.clone();
other_version.affected_version = "5.4.22".into();
assert!(!key.matches(&other_version));
let mut without_purl = a.clone();
without_purl.purl = None;
assert!(!key.matches(&without_purl));
// The group's JSON names the component at the top level, as the
// group decision's body does.
let groups = group_open_alerts(&[a]);
let json = serde_json::to_value(&groups[0]).unwrap_or_default();
assert_eq!(json["package"], "vite");
assert_eq!(json["purl"], "pkg:npm/vite@5.4.21");
assert_eq!(json["counts"]["info"], 1);
}
}
+429
View File
@@ -0,0 +1,429 @@
//! Open CVE alerts over time, and the package updates that close the most
//! of them (#952): what the overview's and a target's CVE charts show.
//!
//! Computed from the stored alerts alone, no snapshots: an alert counts on
//! day `d` (UTC) when, at the end of `d`,
//!
//! * it had been found (`created_at`),
//! * it was not resolved yet (`resolved_at` unset or later),
//! * no VEX statement had settled it (`not_affected` or `fixed` stated at
//! `vex.at` or earlier), and
//! * its advisory names a fixed version (`fixed_versions` not empty).
//!
//! The unit is one CVE in one target: the same CVE in two packages of a
//! target (a GHSA and its CVE alias, two copies of a library) counts once,
//! at its highest severity; in two targets it counts twice. A tenant's or a
//! project's series is the sum of its targets' series.
//!
//! Only the current state of an alert is stored, so two things are not
//! seen in the past: an alert reported again after it was resolved loses
//! its `resolved_at` (it shows as open through the gap), and a withdrawn
//! VEX statement is overwritten (the alert shows as open throughout).
use std::cmp::Ordering;
use std::collections::{BTreeMap, HashMap, HashSet};
use chrono::{DateTime, Days, NaiveDate, Utc};
use serde::{Deserialize, Serialize};
use crate::models::notification::{parse_severity, NotificationSeverity};
use crate::models::CveAlert;
use crate::version::cmp_dotted;
/// The days a history covers unless asked otherwise.
pub const DEFAULT_DAYS: u32 = 30;
/// The most days a history may cover.
pub const MAX_DAYS: u32 = 90;
/// One day of a history: the open CVEs with a fixed version, by severity.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CveDay {
/// The day (UTC).
pub date: NaiveDate,
pub critical: u32,
pub high: u32,
pub medium: u32,
pub low: u32,
}
impl CveDay {
/// The critical and high ones: what the charts show.
pub fn urgent(&self) -> u32 {
self.critical + self.high
}
/// Count one CVE of `severity`.
fn count(&mut self, severity: &NotificationSeverity) {
match severity {
NotificationSeverity::Critical => self.critical += 1,
NotificationSeverity::High => self.high += 1,
NotificationSeverity::Medium => self.medium += 1,
NotificationSeverity::Low => self.low += 1,
}
}
/// Add another series' counts of the same day.
fn add(&mut self, other: &Self) {
self.critical += other.critical;
self.high += other.high;
self.medium += other.medium;
self.low += other.low;
}
}
/// Open findings of the same scope, the dashboards' other two tiles.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct OpenFindings {
pub critical: u64,
pub high: u64,
}
/// The answer of `GET /api/v1/cve-history`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CveHistory {
/// Oldest day first, today last.
pub days: Vec<CveDay>,
#[serde(default)]
pub open_findings: OpenFindings,
/// Each target's own series (same days), when asked for; a target
/// without alerts in the window is left out.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub targets: BTreeMap<String, Vec<CveDay>>,
}
/// The days of a window of `days` days ending today (at least one), each
/// with the instant it ends: the next day's midnight, UTC.
pub fn window(now: DateTime<Utc>, days: u32) -> Vec<(NaiveDate, DateTime<Utc>)> {
let today = now.date_naive();
(0..days.max(1))
.rev()
.filter_map(|back| {
let date = today.checked_sub_days(Days::new(u64::from(back)))?;
let end = date.checked_add_days(Days::new(1))?.and_hms_opt(0, 0, 0)?;
Some((date, end.and_utc()))
})
.collect()
}
/// Whether `alert` was open just before `end`: found before it, not
/// resolved and not settled by VEX by then. The fixed version is not
/// checked here.
pub fn open_before(alert: &CveAlert, end: DateTime<Utc>) -> bool {
alert.created_at < end
&& alert.resolved_at.is_none_or(|resolved| resolved >= end)
&& !alert
.vex
.as_ref()
.is_some_and(|vex| vex.status.resolves() && vex.at < end)
}
/// The alerts with a fixed version, by target and CVE id, each with its
/// severity class.
fn by_target_and_cve(
alerts: &[CveAlert],
) -> HashMap<(&str, &str), Vec<(&CveAlert, NotificationSeverity)>> {
let mut groups: HashMap<(&str, &str), Vec<_>> = HashMap::new();
for alert in alerts.iter().filter(|a| !a.fixed_versions.is_empty()) {
let severity = parse_severity(alert.severity.as_deref(), alert.cvss_score);
groups
.entry((alert.repo_id.as_str(), alert.cve()))
.or_default()
.push((alert, severity));
}
groups
}
impl CveHistory {
/// The history of `alerts` over `days` days ending today, with every
/// target's series in [`Self::targets`].
pub fn of(alerts: &[CveAlert], now: DateTime<Utc>, days: u32) -> Self {
let window = window(now, days);
let empty: Vec<CveDay> = window
.iter()
.map(|(date, _)| CveDay {
date: *date,
..CveDay::default()
})
.collect();
let mut targets: BTreeMap<String, Vec<CveDay>> = BTreeMap::new();
for ((repo_id, _), members) in by_target_and_cve(alerts) {
let series = targets
.entry(repo_id.to_string())
.or_insert_with(|| empty.clone());
for (day, (_, end)) in series.iter_mut().zip(&window) {
let highest = members
.iter()
.filter(|(alert, _)| open_before(alert, *end))
.map(|(_, severity)| severity)
.max();
if let Some(severity) = highest {
day.count(severity);
}
}
}
let mut total = empty;
for series in targets.values() {
for (sum, day) in total.iter_mut().zip(series) {
sum.add(day);
}
}
Self {
days: total,
open_findings: OpenFindings::default(),
targets,
}
}
}
/// A package update and the open CVEs with a fix it closes, for a target's
/// "Wo handeln" table.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TopUpdate {
pub package: String,
pub current_version: String,
/// The highest version the alerts name as fixed.
pub fixed_version: String,
/// Open CVEs with a fix in this package and version.
pub cves: u32,
/// The critical ones among them.
pub critical: u32,
}
/// The updates of the packages with open CVEs (open at `now`, with a
/// fixed version), the most CVEs closed first, then the most critical,
/// then by name.
pub fn top_updates(alerts: &[CveAlert], now: DateTime<Utc>) -> Vec<TopUpdate> {
let Some((_, end)) = window(now, 1).pop() else {
return Vec::new();
};
type Key<'a> = (&'a str, &'a str);
let mut packages: HashMap<Key, (HashSet<&str>, HashSet<&str>, &str)> = HashMap::new();
for alert in alerts
.iter()
.filter(|a| !a.fixed_versions.is_empty() && open_before(a, end))
{
let key = (
alert.affected_package.as_str(),
alert.affected_version.as_str(),
);
let (cves, critical, fixed) = packages.entry(key).or_default();
cves.insert(alert.cve());
if parse_severity(alert.severity.as_deref(), alert.cvss_score)
== NotificationSeverity::Critical
{
critical.insert(alert.cve());
}
for version in &alert.fixed_versions {
if fixed.is_empty() || cmp_dotted(version, fixed) == Ordering::Greater {
*fixed = version;
}
}
}
let mut updates: Vec<TopUpdate> = packages
.into_iter()
.map(|((package, current), (cves, critical, fixed))| TopUpdate {
package: package.to_string(),
current_version: current.to_string(),
fixed_version: fixed.to_string(),
cves: u32::try_from(cves.len()).unwrap_or(u32::MAX),
critical: u32::try_from(critical.len()).unwrap_or(u32::MAX),
})
.collect();
updates.sort_by(|a, b| {
b.cves
.cmp(&a.cves)
.then_with(|| b.critical.cmp(&a.critical))
.then_with(|| a.package.cmp(&b.package))
.then_with(|| a.current_version.cmp(&b.current_version))
});
updates
}
#[cfg(test)]
mod tests {
use super::*;
use crate::models::vex::{VexAssessment, VexStatus};
use crate::models::CveSource;
use chrono::TimeZone;
/// 2026-11-10 14:00 UTC.
fn now() -> DateTime<Utc> {
Utc.with_ymd_and_hms(2026, 11, 10, 14, 0, 0).unwrap()
}
fn at(day: u32, hour: u32) -> DateTime<Utc> {
Utc.with_ymd_and_hms(2026, 11, day, hour, 0, 0).unwrap()
}
fn alert(repo: &str, cve: &str, severity: &str, created: DateTime<Utc>) -> CveAlert {
let mut a = CveAlert::new(
cve.into(),
repo.into(),
"log4j-core".into(),
"2.14.1".into(),
CveSource::Osv,
);
a.severity = Some(severity.into());
a.fixed_versions = vec!["2.17.1".into()];
a.created_at = created;
a
}
fn settled(status: VexStatus, when: DateTime<Utc>) -> VexAssessment {
VexAssessment {
status,
justification: None,
impact_statement: None,
action_statement: None,
by: "u1".into(),
by_name: None,
at: when,
by_scan: false,
}
}
/// The urgent (critical + high) count of each day, oldest first.
fn urgent(days: &[CveDay]) -> Vec<u32> {
days.iter().map(CveDay::urgent).collect()
}
#[test]
fn the_window_ends_today_with_each_days_midnight() {
let w = window(now(), 3);
let dates: Vec<String> = w.iter().map(|(d, _)| d.to_string()).collect();
assert_eq!(dates, ["2026-11-08", "2026-11-09", "2026-11-10"]);
assert_eq!(w[2].1, at(11, 0));
assert_eq!(window(now(), 0).len(), 1);
}
#[test]
fn an_alert_never_resolved_is_open_from_the_day_it_was_found() {
let h = CveHistory::of(
&[alert("t1", "CVE-2021-44228", "CRITICAL", at(8, 23))],
now(),
4,
);
assert_eq!(urgent(&h.days), [0, 1, 1, 1]);
assert_eq!(h.days[3].critical, 1);
}
#[test]
fn an_alert_resolved_on_a_day_no_longer_counts_on_that_day() {
let mut found_and_gone = alert("t1", "CVE-2021-44228", "HIGH", at(9, 8));
found_and_gone.resolved_at = Some(at(9, 17));
let mut gone_later = alert("t1", "CVE-2021-45046", "HIGH", at(8, 8));
gone_later.resolved_at = Some(at(10, 9));
let h = CveHistory::of(&[found_and_gone, gone_later], now(), 3);
assert_eq!(urgent(&h.days), [1, 1, 0]);
}
#[test]
fn an_alert_without_a_fixed_version_is_left_out() {
let mut a = alert("t1", "CVE-2021-44228", "CRITICAL", at(8, 8));
a.fixed_versions.clear();
let h = CveHistory::of(&[a.clone()], now(), 3);
assert_eq!(urgent(&h.days), [0, 0, 0]);
assert!(h.targets.is_empty());
assert!(top_updates(&[a], now()).is_empty());
}
#[test]
fn one_cve_counts_once_per_target_at_its_highest_severity() {
// The GHSA and its CVE alias, in two packages of one target.
let mut ghsa = alert("t1", "GHSA-jfh8-c2jp-5v3q", "HIGH", at(8, 8));
ghsa.aliases = vec!["CVE-2021-44228".into()];
ghsa.affected_package = "log4j-api".into();
let cve = alert("t1", "CVE-2021-44228", "CRITICAL", at(9, 8));
// The same CVE in another target counts there too.
let other = alert("t2", "CVE-2021-44228", "HIGH", at(8, 8));
let h = CveHistory::of(&[ghsa, cve, other], now(), 3);
assert_eq!(
h.targets["t1"]
.iter()
.map(|d| (d.critical, d.high))
.collect::<Vec<_>>(),
[(0, 1), (1, 0), (1, 0)]
);
assert_eq!(urgent(&h.targets["t2"]), [1, 1, 1]);
assert_eq!(urgent(&h.days), [2, 2, 2]);
}
#[test]
fn a_vex_statement_settles_an_alert_from_when_it_was_made() {
let mut not_affected = alert("t1", "CVE-2021-44228", "CRITICAL", at(8, 8));
not_affected.vex = Some(settled(VexStatus::NotAffected, at(9, 12)));
// Affected does not settle it.
let mut affected = alert("t1", "CVE-2021-45046", "HIGH", at(8, 8));
affected.vex = Some(settled(VexStatus::Affected, at(8, 9)));
let h = CveHistory::of(&[not_affected, affected], now(), 3);
assert_eq!(urgent(&h.days), [2, 1, 1]);
}
#[test]
fn medium_and_low_are_counted_apart_from_the_urgent_ones() {
let h = CveHistory::of(
&[
alert("t1", "GHSA-4jrv-ppp4-jm57", "MODERATE", at(10, 8)),
alert("t1", "CVE-2020-0001", "LOW", at(10, 8)),
],
now(),
1,
);
assert_eq!(
(h.days[0].medium, h.days[0].low, h.days[0].urgent()),
(1, 1, 0)
);
}
#[test]
fn the_update_closing_the_most_cves_comes_first_with_the_highest_fix() {
let mut first = alert("t1", "CVE-2021-44228", "CRITICAL", at(8, 8));
first.fixed_versions = vec!["2.15.0".into(), "2.12.2".into()];
let mut second = alert("t1", "CVE-2021-45046", "CRITICAL", at(8, 8));
second.fixed_versions = vec!["2.16.0".into()];
// The GHSA of the first CVE: no extra CVE closed.
let mut alias = alert("t1", "GHSA-jfh8-c2jp-5v3q", "CRITICAL", at(8, 8));
alias.aliases = vec!["CVE-2021-44228".into()];
alias.fixed_versions = vec!["2.17.1".into()];
let mut gson = alert("t1", "CVE-2022-25647", "HIGH", at(8, 8));
gson.affected_package = "gson".into();
gson.affected_version = "2.8.8".into();
gson.fixed_versions = vec!["2.8.9".into()];
// Resolved: closes nothing any more.
let mut gone = alert("t1", "CVE-2020-0002", "HIGH", at(8, 8));
gone.affected_package = "jackson".into();
gone.resolved_at = Some(at(9, 8));
let updates = top_updates(&[gson, first, second, alias, gone], now());
assert_eq!(
updates,
[
TopUpdate {
package: "log4j-core".into(),
current_version: "2.14.1".into(),
fixed_version: "2.17.1".into(),
cves: 2,
critical: 2,
},
TopUpdate {
package: "gson".into(),
current_version: "2.8.8".into(),
fixed_version: "2.8.9".into(),
cves: 1,
critical: 0,
},
]
);
}
#[test]
fn equal_counts_rank_the_more_critical_update_first() {
let high = alert("t1", "CVE-2020-0003", "HIGH", at(8, 8));
let mut critical = alert("t1", "CVE-2020-0004", "CRITICAL", at(8, 8));
critical.affected_package = "zlib".into();
let names: Vec<String> = top_updates(&[high, critical], now())
.into_iter()
.map(|u| u.package)
.collect();
assert_eq!(names, ["zlib", "log4j-core"]);
}
}
+442
View File
@@ -0,0 +1,442 @@
//! A target's CVE alerts counted by severity and VEX status (#957): the grid
//! the dashboard's "CVEs & VEX" view opens with, and the filter its cells
//! narrow the CVE list to.
//!
//! The agent counts with [`CveCell::of`] and the dashboard filters the list
//! with [`CveFilter::matches`], which buckets the same way, so a cell's
//! number and the length of the list it opens cannot drift apart. Only
//! alerts that are still reported count ([`counts`]): one a complete scan no
//! longer found (`resolved_at` set) has left the grid.
use serde::{Deserialize, Serialize};
use crate::models::{CveAlert, VexStatus};
/// A row of the grid: the advisory's severity, or `Unknown` when it names
/// none.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CveSeverity {
Critical,
High,
Medium,
Low,
Unknown,
}
impl CveSeverity {
/// Every row, top to bottom.
pub const ALL: [Self; 5] = [
Self::Critical,
Self::High,
Self::Medium,
Self::Low,
Self::Unknown,
];
/// The row of an alert rated `severity` by its advisory (`CRITICAL`,
/// `MODERATE`, `low`; case does not matter), else by its CVSS base score
/// `cvss`, else `Unknown`.
///
/// The advisory's word comes first because it is what the CVE list shows
/// as the alert's badge; the score only fills in when the word is
/// missing or not one of the four.
pub fn of(severity: Option<&str>, cvss: Option<f64>) -> Self {
let word = severity.map(|s| s.trim().to_ascii_lowercase());
match word.as_deref() {
Some("critical") => return Self::Critical,
Some("high") => return Self::High,
Some("medium" | "moderate") => return Self::Medium,
Some("low") => return Self::Low,
_ => {}
}
// Guards rather than range patterns on the `f64`, so that a `NaN`
// score falls through to `Low` like every other score below 4.
match cvss {
Some(score) if score >= 9.0 => Self::Critical,
Some(score) if score >= 7.0 => Self::High,
Some(score) if score >= 4.0 => Self::Medium,
Some(_) => Self::Low,
None => Self::Unknown,
}
}
/// The row's name on the wire and in the dashboard's URL (`high`).
pub const fn as_str(self) -> &'static str {
match self {
Self::Critical => "critical",
Self::High => "high",
Self::Medium => "medium",
Self::Low => "low",
Self::Unknown => "unknown",
}
}
/// The row named `name` by [`Self::as_str`].
pub fn parse(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|s| s.as_str() == name)
}
/// The row's index in [`Self::ALL`].
const fn index(self) -> usize {
self as usize
}
}
/// A column of the grid: the alert's VEX statement, or `Open` while nobody
/// (and no scan) has stated one.
///
/// Unlike [`crate::vex_docs::status_of`], which exports an alert without a
/// statement as `under_investigation`, the grid tells the two apart: "open"
/// is not looked at yet, "under investigation" is being looked at.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VexColumn {
Open,
UnderInvestigation,
Affected,
NotAffected,
Fixed,
}
impl VexColumn {
/// Every column, left to right.
pub const ALL: [Self; 5] = [
Self::Open,
Self::UnderInvestigation,
Self::Affected,
Self::NotAffected,
Self::Fixed,
];
/// The column of an alert whose VEX statement has `status`, `None`
/// without one.
pub const fn of(status: Option<VexStatus>) -> Self {
match status {
None => Self::Open,
Some(VexStatus::UnderInvestigation) => Self::UnderInvestigation,
Some(VexStatus::Affected) => Self::Affected,
Some(VexStatus::NotAffected) => Self::NotAffected,
Some(VexStatus::Fixed) => Self::Fixed,
}
}
/// The column's name on the wire and in the dashboard's URL (`open`).
pub const fn as_str(self) -> &'static str {
match self {
Self::Open => "open",
Self::UnderInvestigation => "under_investigation",
Self::Affected => "affected",
Self::NotAffected => "not_affected",
Self::Fixed => "fixed",
}
}
/// The column named `name` by [`Self::as_str`].
pub fn parse(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|v| v.as_str() == name)
}
/// The column's index in [`Self::ALL`].
const fn index(self) -> usize {
self as usize
}
}
/// The cell of the grid an alert is counted in.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CveCell {
pub severity: CveSeverity,
pub vex: VexColumn,
}
impl CveCell {
/// The cell of an alert rated `severity` / `cvss` with the VEX status
/// `vex` (see [`CveSeverity::of`] and [`VexColumn::of`]).
pub fn of(severity: Option<&str>, cvss: Option<f64>, vex: Option<VexStatus>) -> Self {
Self {
severity: CveSeverity::of(severity, cvss),
vex: VexColumn::of(vex),
}
}
/// The cell `alert` is counted in.
pub fn of_alert(alert: &CveAlert) -> Self {
Self::of(
alert.severity.as_deref(),
alert.cvss_score,
alert.vex.as_ref().map(|v| v.status),
)
}
}
/// Whether `alert` is counted in the grid: still reported by the scans.
pub fn counts(alert: &CveAlert) -> bool {
alert.resolved_at.is_none()
}
/// One non-empty cell of a [`CveMatrix`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct CveMatrixCell {
pub severity: CveSeverity,
pub vex: VexColumn,
pub count: u64,
}
/// A target's still-reported CVE alerts counted per [`CveCell`]. Only the
/// non-empty cells are listed, rows top to bottom and columns left to right;
/// every other cell counts 0.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CveMatrix {
pub cells: Vec<CveMatrixCell>,
}
impl CveMatrix {
/// Count `cells`, one per alert.
///
/// # Examples
///
/// ```
/// use compliance_core::cve_matrix::{CveCell, CveMatrix, CveSeverity, VexColumn};
///
/// let high_open = CveCell::of(Some("HIGH"), None, None);
/// let matrix = CveMatrix::from_cells([high_open, high_open]);
/// assert_eq!(matrix.count(CveSeverity::High, VexColumn::Open), 2);
/// ```
pub fn from_cells(cells: impl IntoIterator<Item = CveCell>) -> Self {
// A fixed 5 x 5 table: one pass, no hashing, and the output order
// falls out of the index order.
let mut table = [[0u64; VexColumn::ALL.len()]; CveSeverity::ALL.len()];
for cell in cells {
table[cell.severity.index()][cell.vex.index()] += 1;
}
let cells = CveSeverity::ALL
.into_iter()
.flat_map(|severity| {
VexColumn::ALL.into_iter().map(move |vex| CveMatrixCell {
severity,
vex,
count: table[severity.index()][vex.index()],
})
})
.filter(|cell| cell.count > 0)
.collect();
Self { cells }
}
/// How many alerts are in the cell of `severity` and `vex`.
pub fn count(&self, severity: CveSeverity, vex: VexColumn) -> u64 {
self.cells
.iter()
.find(|c| c.severity == severity && c.vex == vex)
.map_or(0, |c| c.count)
}
/// The largest count of a cell, 0 when there are none.
pub fn max(&self) -> u64 {
self.cells.iter().map(|c| c.count).max().unwrap_or(0)
}
/// How many alerts are counted in all.
pub fn total(&self) -> u64 {
self.cells.iter().map(|c| c.count).sum()
}
/// How many alerts nobody has assessed yet: the "open" column.
pub fn unassessed(&self) -> u64 {
self.cells
.iter()
.filter(|c| c.vex == VexColumn::Open)
.map(|c| c.count)
.sum()
}
/// The rows the grid shows: the four severities, and "unknown" only
/// when an alert has no severity.
pub fn rows(&self) -> Vec<CveSeverity> {
let has_unknown = self
.cells
.iter()
.any(|c| c.severity == CveSeverity::Unknown);
CveSeverity::ALL
.into_iter()
.filter(|s| *s != CveSeverity::Unknown || has_unknown)
.collect()
}
}
/// What a click in the grid narrows the CVE list to: a severity, a VEX
/// column, or both; `None` leaves that side open. Either way only alerts the
/// grid counts ([`counts`]) pass.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct CveFilter {
pub severity: Option<CveSeverity>,
pub vex: Option<VexColumn>,
}
impl CveFilter {
/// Whether `alert` is in the narrowed list.
pub fn matches(&self, alert: &CveAlert) -> bool {
if !counts(alert) {
return false;
}
let cell = CveCell::of_alert(alert);
self.severity.is_none_or(|s| s == cell.severity) && self.vex.is_none_or(|v| v == cell.vex)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::models::{CveSource, VexAssessment};
fn alert(severity: Option<&str>, cvss: Option<f64>, vex: Option<VexStatus>) -> CveAlert {
CveAlert {
id: None,
cve_id: "CVE-2024-0001".to_string(),
repo_id: "t1".to_string(),
affected_package: "openssl".to_string(),
affected_version: "3.0.0".to_string(),
purl: None,
source: CveSource::Osv,
severity: severity.map(String::from),
cvss_score: cvss,
summary: None,
llm_impact_summary: None,
references: Vec::new(),
aliases: Vec::new(),
fixed_versions: Vec::new(),
exploitation: None,
advisories: Vec::new(),
vex: vex.map(|status| VexAssessment {
status,
justification: None,
impact_statement: None,
action_statement: None,
by: "u1".to_string(),
by_name: None,
at: chrono::Utc::now(),
by_scan: false,
}),
resolved_at: None,
exploited_seen_at: None,
created_at: chrono::Utc::now(),
}
}
#[test]
fn the_advisory_word_picks_the_row_in_any_case() {
assert_eq!(
CveSeverity::of(Some("CRITICAL"), None),
CveSeverity::Critical
);
assert_eq!(CveSeverity::of(Some("high"), None), CveSeverity::High);
assert_eq!(CveSeverity::of(Some("MODERATE"), None), CveSeverity::Medium);
assert_eq!(CveSeverity::of(Some(" Medium "), None), CveSeverity::Medium);
assert_eq!(CveSeverity::of(Some("low"), Some(9.8)), CveSeverity::Low);
}
#[test]
fn the_cvss_score_fills_in_a_missing_or_odd_word() {
assert_eq!(CveSeverity::of(None, Some(9.0)), CveSeverity::Critical);
assert_eq!(
CveSeverity::of(Some("important"), Some(8.1)),
CveSeverity::High
);
assert_eq!(CveSeverity::of(None, Some(4.0)), CveSeverity::Medium);
assert_eq!(CveSeverity::of(None, Some(3.9)), CveSeverity::Low);
}
#[test]
fn without_word_or_score_the_severity_is_unknown() {
assert_eq!(CveSeverity::of(None, None), CveSeverity::Unknown);
assert_eq!(CveSeverity::of(Some("unrated"), None), CveSeverity::Unknown);
}
#[test]
fn no_statement_is_open_and_each_status_has_its_column() {
assert_eq!(VexColumn::of(None), VexColumn::Open);
assert_eq!(
VexColumn::of(Some(VexStatus::UnderInvestigation)),
VexColumn::UnderInvestigation
);
assert_eq!(
VexColumn::of(Some(VexStatus::Affected)),
VexColumn::Affected
);
assert_eq!(
VexColumn::of(Some(VexStatus::NotAffected)),
VexColumn::NotAffected
);
assert_eq!(VexColumn::of(Some(VexStatus::Fixed)), VexColumn::Fixed);
}
#[test]
fn names_round_trip_and_match_the_wire() {
for severity in CveSeverity::ALL {
assert_eq!(CveSeverity::parse(severity.as_str()), Some(severity));
assert_eq!(
serde_json::to_value(severity).ok(),
Some(serde_json::Value::from(severity.as_str()))
);
}
for vex in VexColumn::ALL {
assert_eq!(VexColumn::parse(vex.as_str()), Some(vex));
assert_eq!(
serde_json::to_value(vex).ok(),
Some(serde_json::Value::from(vex.as_str()))
);
}
assert_eq!(CveSeverity::parse("hoch"), None);
assert_eq!(VexColumn::parse(""), None);
}
#[test]
fn the_matrix_counts_each_cell_and_lists_only_non_empty_ones() {
let high_open = CveCell::of(Some("HIGH"), None, None);
let low_fixed = CveCell::of(Some("LOW"), None, Some(VexStatus::Fixed));
let matrix = CveMatrix::from_cells([high_open, low_fixed, high_open]);
assert_eq!(matrix.cells.len(), 2);
assert_eq!(matrix.cells[0].severity, CveSeverity::High);
assert_eq!(matrix.count(CveSeverity::High, VexColumn::Open), 2);
assert_eq!(matrix.count(CveSeverity::Low, VexColumn::Fixed), 1);
assert_eq!(matrix.count(CveSeverity::Critical, VexColumn::Open), 0);
assert_eq!(
(matrix.max(), matrix.total(), matrix.unassessed()),
(2, 3, 2)
);
}
#[test]
fn the_unknown_row_shows_only_when_an_alert_has_no_severity() {
let rated = CveMatrix::from_cells([CveCell::of(Some("high"), None, None)]);
assert_eq!(rated.rows().len(), 4);
let unrated = CveMatrix::from_cells([CveCell::of(None, None, None)]);
assert_eq!(unrated.rows().last(), Some(&CveSeverity::Unknown));
assert_eq!(CveMatrix::default().rows().len(), 4);
}
#[test]
fn the_filter_passes_its_cell_and_never_a_resolved_alert() {
let high_open = alert(Some("HIGH"), None, None);
let high_affected = alert(Some("HIGH"), None, Some(VexStatus::Affected));
let mut resolved = high_open.clone();
resolved.resolved_at = Some(chrono::Utc::now());
let cell = CveFilter {
severity: Some(CveSeverity::High),
vex: Some(VexColumn::Open),
};
assert!(cell.matches(&high_open));
assert!(!cell.matches(&high_affected));
assert!(!cell.matches(&resolved));
let all_open = CveFilter {
severity: None,
vex: Some(VexColumn::Open),
};
assert!(all_open.matches(&high_open));
assert!(CveFilter::default().matches(&high_affected));
assert!(!CveFilter::default().matches(&resolved));
}
}
+186
View File
@@ -0,0 +1,186 @@
//! Source files as text, whatever encoding the tool that wrote them chose.
//!
//! Visual Studio writes UTF-8 with a byte-order mark (BOM) or UTF-16, older
//! .NET and PLC tools write Windows-1252. `std::fs::read_to_string` accepts
//! only UTF-8 (and keeps a UTF-8 BOM as a leading `U+FEFF`), so every reader
//! of source files decodes through [`read_source`] instead:
//!
//! 1. a BOM (UTF-8 `EF BB BF`, UTF-16 LE `FF FE`, UTF-16 BE `FE FF`) names the
//! encoding; the BOM itself is dropped;
//! 2. without one, the bytes are UTF-8 if they are valid UTF-8;
//! 3. otherwise they are Windows-1252, unless they contain a NUL byte: no
//! 1252 text does, but binaries and UTF-16 without a BOM do.
use std::path::Path;
use encoding_rs::{Encoding, UTF_8, WINDOWS_1252};
/// Why a file could not be read as text.
#[derive(Debug, thiserror::Error)]
pub enum SourceTextError {
/// The file could not be read at all (missing, no permission, ...).
#[error("cannot read the file: {0}")]
Io(#[from] std::io::Error),
/// The file's BOM names an encoding its bytes don't follow, e.g. UTF-16
/// with an odd byte count or an unpaired surrogate.
#[error("the file is not valid {0} although its byte-order mark says so")]
Malformed(&'static str),
/// The file has no BOM, is not UTF-8 and contains a NUL byte: a binary
/// file, or UTF-16 we can't tell the byte order of.
#[error("the file is binary or of an unknown encoding")]
Binary,
}
/// Read the file at `path` as text, decoded as the module docs describe.
///
/// # Arguments
///
/// * `path` - the file to read
///
/// # Returns
///
/// The file's text, without a byte-order mark.
///
/// # Errors
///
/// Returns [`SourceTextError::Io`] when the file can't be read, and the
/// errors of [`decode`] when its bytes aren't text.
pub fn read_source(path: &Path) -> Result<String, SourceTextError> {
decode(std::fs::read(path)?)
}
/// Decode a source file's bytes, as the module docs describe.
///
/// Takes the bytes by value so that the common case, UTF-8 without a BOM,
/// becomes the `String` without copying: a Rust `String` is a UTF-8 byte
/// buffer, so `String::from_utf8` only validates and reuses the `Vec`.
///
/// # Arguments
///
/// * `bytes` - the whole file
///
/// # Returns
///
/// The text, without a byte-order mark.
///
/// # Errors
///
/// Returns [`SourceTextError::Malformed`] when a BOM names an encoding the
/// bytes don't follow, and [`SourceTextError::Binary`] for non-UTF-8 bytes
/// that contain a NUL.
///
/// # Examples
///
/// ```
/// use compliance_core::encoding::decode;
///
/// // "€" is 0x80 in Windows-1252.
/// assert_eq!(decode(b"// 5 \x80".to_vec()).ok().as_deref(), Some("// 5 €"));
/// ```
pub fn decode(mut bytes: Vec<u8>) -> Result<String, SourceTextError> {
if let Some((encoding, bom_len)) = Encoding::for_bom(&bytes) {
if encoding == UTF_8 {
// Drop the BOM in place, then validate without another copy.
bytes.drain(..bom_len);
return String::from_utf8(bytes).map_err(|_| SourceTextError::Malformed("UTF-8"));
}
// UTF-16 LE or BE: `None` on an odd byte count or unpaired surrogate.
return encoding
.decode_without_bom_handling_and_without_replacement(&bytes[bom_len..])
.map(|text| text.into_owned())
.ok_or(SourceTextError::Malformed(encoding.name()));
}
match String::from_utf8(bytes) {
Ok(text) => Ok(text),
Err(not_utf8) => {
// Hand the buffer back; `from_utf8` gave up ownership on failure.
let bytes = not_utf8.into_bytes();
if bytes.contains(&0) {
return Err(SourceTextError::Binary);
}
// Windows-1252 maps every byte, so this decoding can't fail.
let (text, _had_errors) = WINDOWS_1252.decode_without_bom_handling(&bytes);
Ok(text.into_owned())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// `text` as UTF-16 with its BOM, in the byte order asked for.
fn utf16(text: &str, little_endian: bool) -> Vec<u8> {
let bom: [u8; 2] = if little_endian {
[0xFF, 0xFE]
} else {
[0xFE, 0xFF]
};
let units = text.encode_utf16().flat_map(|unit| {
if little_endian {
unit.to_le_bytes()
} else {
unit.to_be_bytes()
}
});
bom.into_iter().chain(units).collect()
}
#[test]
fn utf8_without_a_bom_is_kept_as_it_is() {
let text = decode("int größe = 1; // €".as_bytes().to_vec());
assert_eq!(text.ok().as_deref(), Some("int größe = 1; // €"));
}
#[test]
fn a_utf8_bom_is_dropped() {
let mut bytes = vec![0xEF, 0xBB, 0xBF];
bytes.extend_from_slice(b"class A {}");
assert_eq!(decode(bytes).ok().as_deref(), Some("class A {}"));
}
#[test]
fn utf16_with_a_bom_is_decoded_in_both_byte_orders() {
for little_endian in [true, false] {
let text = decode(utf16("class Größe {}", little_endian));
assert_eq!(text.ok().as_deref(), Some("class Größe {}"));
}
}
#[test]
fn windows_1252_is_the_fallback() {
// "Größe" and "€" as Windows-1252 writes them: 0xF6 0xDF and 0x80.
let text = decode(b"// Gr\xF6\xDFe in \x80".to_vec());
assert_eq!(text.ok().as_deref(), Some("// Größe in €"));
}
#[test]
fn malformed_utf16_and_binaries_are_not_text() {
// An odd byte count after a UTF-16 LE BOM.
assert!(matches!(
decode(vec![0xFF, 0xFE, 0x41]),
Err(SourceTextError::Malformed("UTF-16LE"))
));
// An unpaired high surrogate (D800) in UTF-16 BE.
assert!(matches!(
decode(vec![0xFE, 0xFF, 0xD8, 0x00, 0x00, 0x41]),
Err(SourceTextError::Malformed("UTF-16BE"))
));
// Invalid UTF-8 after a UTF-8 BOM.
assert!(matches!(
decode(vec![0xEF, 0xBB, 0xBF, 0xFF]),
Err(SourceTextError::Malformed("UTF-8"))
));
// Not UTF-8 and a NUL: a binary.
assert!(matches!(
decode(vec![0x7F, b'E', b'L', b'F', 0x00, 0xFF]),
Err(SourceTextError::Binary)
));
}
#[test]
fn a_missing_file_is_an_io_error() {
let missing = std::env::temp_dir().join("compliance-core-no-such-file.cs");
assert!(matches!(read_source(&missing), Err(SourceTextError::Io(_))));
}
}
+434
View File
@@ -0,0 +1,434 @@
//! A target's open findings counted for the charts of its findings view
//! (#957): by finding type and severity, and by folder.
//!
//! "Open" is undecided: [`OPEN_STATUSES`], the statuses a finding still gets
//! a tracker issue at (`pipeline::issue_creation::ISSUE_STATUSES` in the
//! agent). Resolved, false positives, accepted risks and ignored findings are
//! decided and left out.
//!
//! The agent computes a [`FindingBreakdown`] with [`breakdown`] over the open
//! findings' type, severity and path; the dashboard reads the same type.
use serde::{Deserialize, Serialize};
use crate::models::{FindingStatus, ScanType, Severity};
/// The statuses of findings nobody has decided about yet.
pub const OPEN_STATUSES: [FindingStatus; 3] = [
FindingStatus::Open,
FindingStatus::Triaged,
FindingStatus::NeedsReview,
];
/// The findings list's `status` filter for all of [`OPEN_STATUSES`], so the
/// list behind a chart shows the findings the chart counts.
pub const OPEN_STATUS_FILTER: &str = "undecided";
/// Every severity, most severe first: the order of the stacked segments and
/// the legend.
pub const SEVERITIES: [Severity; 5] = [
Severity::Critical,
Severity::High,
Severity::Medium,
Severity::Low,
Severity::Info,
];
/// The folder key of the findings in the root of the tree (no directory).
pub const ROOT_FOLDER: &str = "/";
/// The suffix of a folder key that means "only the files directly in it"
/// (`src/*`), next to `src/` meaning everything below `src`.
pub const DIRECT_SUFFIX: &str = "*";
/// The fields of an open finding the breakdown reads (the agent projects
/// the findings to these).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BreakdownRow {
/// The finding type, as the findings list filters by it.
pub scan_type: ScanType,
pub severity: Severity,
/// The file the finding is in, relative to the tree; `None` for findings
/// in no file (a CVE in a dependency, a DAST endpoint).
#[serde(default)]
pub file_path: Option<String>,
}
/// How many findings there are of each severity.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SeverityCounts {
pub critical: u64,
pub high: u64,
pub medium: u64,
pub low: u64,
pub info: u64,
}
impl SeverityCounts {
/// The count of `severity`.
pub fn get(&self, severity: &Severity) -> u64 {
match severity {
Severity::Critical => self.critical,
Severity::High => self.high,
Severity::Medium => self.medium,
Severity::Low => self.low,
Severity::Info => self.info,
}
}
/// Counts one more finding of `severity`.
pub fn add(&mut self, severity: &Severity) {
let count = match severity {
Severity::Critical => &mut self.critical,
Severity::High => &mut self.high,
Severity::Medium => &mut self.medium,
Severity::Low => &mut self.low,
Severity::Info => &mut self.info,
};
*count += 1;
}
/// All findings, of any severity.
pub fn total(&self) -> u64 {
self.critical + self.high + self.medium + self.low + self.info
}
}
/// The open findings of one type.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TypeBreakdown {
pub scan_type: ScanType,
pub counts: SeverityCounts,
}
/// The open findings in one folder.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FolderBreakdown {
/// The folder key, which is also the findings list's `path` filter:
/// `src/` (everything below `src`), `src/*` (only the files directly in
/// `src`), or [`ROOT_FOLDER`] (the files in the root).
pub path: String,
pub count: u64,
/// The most severe of the folder's findings.
pub worst: Severity,
}
/// A target's open findings by type and severity, and by folder.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct FindingBreakdown {
/// The types with open findings, most findings first.
pub by_type: Vec<TypeBreakdown>,
/// The folders with open findings, most findings first.
pub folders: Vec<FolderBreakdown>,
/// Open findings in no file, which the folders leave out.
pub without_file: u64,
/// All open findings.
pub total: u64,
}
/// The folders `path` lies in, outermost first (none for a file in the root).
fn folders_of(path: &str) -> impl Iterator<Item = &str> {
path.rsplit_once('/')
.map_or("", |(dirs, _file)| dirs)
.split('/')
.filter(|dir| !dir.is_empty())
}
/// The folder key `path` is counted under. `split` is the top-level
/// directory shown two levels deep, because it holds most findings.
fn folder_key(path: &str, split: Option<&str>) -> String {
let mut folders = folders_of(path);
match (folders.next(), folders.next()) {
(None, _) => ROOT_FOLDER.to_string(),
(Some(top), None) if split == Some(top) => format!("{top}/{DIRECT_SUFFIX}"),
(Some(top), Some(sub)) if split == Some(top) => format!("{top}/{sub}/"),
(Some(top), _) => format!("{top}/"),
}
}
/// The top-level directory holding more than half of `paths`, which is then
/// shown two levels deep; `None` when there is none, or it has no subfolder
/// with findings (two levels would show nothing new).
fn dominant_dir<'a>(paths: &[&'a str]) -> Option<&'a str> {
let mut counts: Vec<(&str, usize)> = Vec::new();
for top in paths.iter().filter_map(|p| folders_of(p).next()) {
match counts.iter_mut().find(|(dir, _)| *dir == top) {
Some((_, count)) => *count += 1,
None => counts.push((top, 1)),
}
}
let (top, _) = counts
.into_iter()
.find(|(_, count)| count * 2 > paths.len())?;
paths
.iter()
.any(|p| {
let mut folders = folders_of(p);
folders.next() == Some(top) && folders.next().is_some()
})
.then_some(top)
}
/// The file of `row`, `None` when it is in no file.
fn file_of(row: &BreakdownRow) -> Option<&str> {
row.file_path
.as_deref()
.filter(|p| !p.trim_start_matches('/').is_empty())
}
/// Counts the open findings `rows` by type and severity, and by folder.
///
/// Folders are the top-level directories; when one of them holds more than
/// half of the findings in a file, its subfolders are shown instead
/// (`src/api/`), with the files directly in it as `src/*`. Files in the root
/// count under [`ROOT_FOLDER`]. Most findings come first; ties are ordered
/// by the type's name and by the folder's path, so the order does not depend
/// on the order of `rows`.
///
/// # Examples
///
/// ```
/// use compliance_core::finding_breakdown::{breakdown, BreakdownRow};
/// use compliance_core::models::{ScanType, Severity};
///
/// let row = |file: &str| BreakdownRow {
/// scan_type: ScanType::Sast,
/// severity: Severity::High,
/// file_path: Some(file.to_string()),
/// };
/// let result = breakdown(&[row("src/a.rs"), row("docs/b.md"), row("README.md")]);
/// assert_eq!(result.total, 3);
/// assert_eq!(result.by_type[0].counts.high, 3);
/// assert_eq!(result.folders.len(), 3);
/// ```
pub fn breakdown(rows: &[BreakdownRow]) -> FindingBreakdown {
let mut by_type: Vec<TypeBreakdown> = Vec::new();
for row in rows {
match by_type.iter_mut().find(|t| t.scan_type == row.scan_type) {
Some(entry) => entry.counts.add(&row.severity),
None => {
let mut counts = SeverityCounts::default();
counts.add(&row.severity);
by_type.push(TypeBreakdown {
scan_type: row.scan_type,
counts,
});
}
}
}
by_type.sort_by_cached_key(|t| (std::cmp::Reverse(t.counts.total()), t.scan_type.to_string()));
let paths: Vec<&str> = rows.iter().filter_map(file_of).collect();
let split = dominant_dir(&paths);
// Sorted by path, which the stable sort below keeps for equal counts.
let mut folders: std::collections::BTreeMap<String, (u64, Severity)> =
std::collections::BTreeMap::new();
let mut without_file = 0;
for row in rows {
let Some(path) = file_of(row) else {
without_file += 1;
continue;
};
let entry = folders
.entry(folder_key(path, split))
.or_insert((0, row.severity.clone()));
entry.0 += 1;
if row.severity > entry.1 {
entry.1 = row.severity.clone();
}
}
let mut folders: Vec<FolderBreakdown> = folders
.into_iter()
.map(|(path, (count, worst))| FolderBreakdown { path, count, worst })
.collect();
folders.sort_by_key(|f| std::cmp::Reverse(f.count));
FindingBreakdown {
by_type,
folders,
without_file,
total: rows.len() as u64,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn row(scan_type: ScanType, severity: Severity, file: Option<&str>) -> BreakdownRow {
BreakdownRow {
scan_type,
severity,
file_path: file.map(str::to_string),
}
}
fn sast(severity: Severity, file: &str) -> BreakdownRow {
row(ScanType::Sast, severity, Some(file))
}
fn folder_paths(result: &FindingBreakdown) -> Vec<(&str, u64)> {
result
.folders
.iter()
.map(|f| (f.path.as_str(), f.count))
.collect()
}
#[test]
fn open_means_undecided() {
assert_eq!(
OPEN_STATUSES,
[
FindingStatus::Open,
FindingStatus::Triaged,
FindingStatus::NeedsReview
]
);
for decided in [
FindingStatus::Resolved,
FindingStatus::FalsePositive,
FindingStatus::WrongMapping,
FindingStatus::AcceptedRisk,
FindingStatus::Ignored,
] {
assert!(!OPEN_STATUSES.contains(&decided), "{decided} is decided");
}
}
#[test]
fn severities_run_from_critical_to_info() {
let mut sorted = SEVERITIES.to_vec();
sorted.sort_by(|a, b| b.cmp(a));
assert_eq!(sorted, SEVERITIES.to_vec());
assert_eq!(SEVERITIES[0], Severity::Critical);
}
#[test]
fn types_are_counted_per_severity_most_findings_first() {
let rows = [
row(ScanType::Gdpr, Severity::Medium, Some("a/x.rs")),
row(ScanType::Sast, Severity::High, Some("a/y.rs")),
row(ScanType::Sast, Severity::Critical, None),
row(ScanType::Sast, Severity::High, None),
];
let result = breakdown(&rows);
assert_eq!(result.total, 4);
assert_eq!(result.by_type.len(), 2);
let first = &result.by_type[0];
assert_eq!(first.scan_type, ScanType::Sast);
assert_eq!(first.counts.high, 2);
assert_eq!(first.counts.critical, 1);
assert_eq!(first.counts.total(), 3);
assert_eq!(result.by_type[1].scan_type, ScanType::Gdpr);
assert_eq!(result.by_type[1].counts.get(&Severity::Medium), 1);
}
#[test]
fn equal_totals_are_ordered_by_name_whatever_the_row_order() {
let lint = row(ScanType::Lint, Severity::Low, None);
let gdpr = row(ScanType::Gdpr, Severity::Low, None);
let order = |rows: &[BreakdownRow]| -> Vec<ScanType> {
breakdown(rows)
.by_type
.iter()
.map(|t| t.scan_type)
.collect()
};
let expected = [ScanType::Gdpr, ScanType::Lint];
assert_eq!(order(&[lint.clone(), gdpr.clone()]), expected);
assert_eq!(order(&[gdpr, lint]), expected);
}
#[test]
fn folders_are_top_level_with_root_files_as_slash() {
let rows = [
sast(Severity::Low, "src/api/a.rs"),
sast(Severity::Low, "docs/b.md"),
sast(Severity::Low, "docs/deep/c.md"),
sast(Severity::Low, "README.md"),
sast(Severity::Low, "/Cargo.toml"),
];
let result = breakdown(&rows);
assert_eq!(folder_paths(&result), [("/", 2), ("docs/", 2), ("src/", 1)]);
assert_eq!(result.without_file, 0);
}
#[test]
fn a_folder_with_most_findings_is_shown_two_levels_deep() {
let rows = [
sast(Severity::Low, "src/api/a.rs"),
sast(Severity::Low, "src/api/v1/b.rs"),
sast(Severity::Low, "src/ui/c.rs"),
sast(Severity::Low, "src/main.rs"),
sast(Severity::Low, "docs/sub/d.md"),
sast(Severity::Low, "e.toml"),
];
let result = breakdown(&rows);
assert_eq!(
folder_paths(&result),
[
("src/api/", 2),
("/", 1),
("docs/", 1),
("src/*", 1),
("src/ui/", 1)
]
);
}
#[test]
fn half_is_not_most() {
let rows = [
sast(Severity::Low, "src/api/a.rs"),
sast(Severity::Low, "docs/b.md"),
];
assert_eq!(folder_paths(&breakdown(&rows)), [("docs/", 1), ("src/", 1)]);
}
#[test]
fn findings_in_no_file_are_not_in_a_folder() {
let rows = [
row(ScanType::Cve, Severity::High, None),
row(ScanType::Cve, Severity::High, Some("")),
sast(Severity::Low, "lib/a.c"),
];
let result = breakdown(&rows);
assert_eq!(result.without_file, 2);
assert_eq!(result.total, 3);
assert_eq!(folder_paths(&result), [("lib/", 1)]);
}
#[test]
fn a_folder_without_subfolders_is_not_split() {
let rows = [
sast(Severity::Low, "src/a.rs"),
sast(Severity::Low, "src/b.rs"),
sast(Severity::Low, "docs/c/d.md"),
];
assert_eq!(folder_paths(&breakdown(&rows)), [("src/", 2), ("docs/", 1)]);
}
#[test]
fn a_folder_takes_its_worst_severity() {
let rows = [
sast(Severity::Low, "a/x.rs"),
sast(Severity::Critical, "a/y.rs"),
sast(Severity::Medium, "a/z.rs"),
sast(Severity::Info, "b/z.rs"),
];
let result = breakdown(&rows);
let a = result.folders.iter().find(|f| f.path == "a/");
assert_eq!(a.map(|f| f.worst.clone()), Some(Severity::Critical));
}
#[test]
fn the_breakdown_reads_back_from_json() {
let result = breakdown(&[sast(Severity::High, "src/a.rs")]);
let json = serde_json::to_value(&result).expect("serializes");
assert_eq!(json["by_type"][0]["scan_type"], "sast");
assert_eq!(json["folders"][0]["worst"], "high");
let back: FindingBreakdown = serde_json::from_value(json).expect("deserializes");
assert_eq!(back, result);
}
}
+9
View File
@@ -1,11 +1,18 @@
pub mod build_info;
pub mod component_changes;
pub mod config;
pub mod control_check;
pub mod csaf_docs;
pub mod csaf_ingest;
pub mod cve_groups;
pub mod cve_history;
pub mod cve_matrix;
pub mod db;
pub mod encoding;
pub mod enisa_docs;
pub mod error;
pub mod exec_policy;
pub mod finding_breakdown;
#[cfg(feature = "net")]
pub mod guarded_net;
pub mod license_notices;
@@ -13,6 +20,8 @@ pub mod models;
pub mod net_guard;
pub mod purl;
pub mod sbom_docs;
pub mod sbom_ecosystems;
pub mod scan_changes;
pub mod scan_matrix;
pub mod spdx_license;
#[cfg(feature = "telemetry")]
+187
View File
@@ -93,6 +93,10 @@ pub struct StatusChange {
/// which run.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scan: Option<ScanStatusChange>,
/// Set when the finding's issue was closed or reopened in the issue
/// tracker (#953); `by_name` is the tracker user who did it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tracker: Option<TrackerChangeKind>,
}
impl StatusChange {
@@ -118,8 +122,45 @@ impl StatusChange {
kind,
scan_run_id: scan_run_id.to_string(),
}),
tracker: None,
}
}
/// The `by` of every change carried over from the issue tracker.
pub const TRACKER_ACTOR: &'static str = "pruefwerk-tracker";
/// A change carried over from the issue tracker, where the user `login`
/// closed or reopened the finding's issue.
///
/// # Arguments
///
/// * `status` - the status the finding moves to
/// * `kind` - what happened to the issue
/// * `login` - the tracker user who did it, shown as who changed it
pub fn by_tracker(status: FindingStatus, kind: TrackerChangeKind, login: &str) -> Self {
Self {
status,
by: Self::TRACKER_ACTOR.to_string(),
by_name: Some(login.to_string()),
support: false,
at: Utc::now(),
reason: None,
scan: None,
tracker: Some(kind),
}
}
}
/// What happened to a finding's issue in the issue tracker that changed the
/// finding's status.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum TrackerChangeKind {
/// A person closed the issue: the finding counts as resolved until a
/// scan finds it again.
ClosedInTracker,
/// A person reopened the issue: the finding is undecided again.
ReopenedInTracker,
}
/// Why a scan changed a finding's status.
@@ -305,10 +346,156 @@ impl Finding {
}
}
/// `triage_action` of a finding the LLM triage judged a false alarm.
pub const TRIAGE_DISMISS: &str = "dismiss";
/// `triage_action` of a finding the LLM triage gave no verdict; the reason is
/// in `triage_rationale`, which starts with `skipped: <reason>`.
pub const TRIAGE_SKIPPED: &str = "skipped";
/// `triage_action` of a finding the control check did not confirm against the
/// CRA requirements it maps to.
pub const TRIAGE_CONTROL_NOT_CONFIRMED: &str = "control_not_confirmed";
/// Least confidence (0-10, as stored in `confidence`) at which the LLM triage
/// takes a confirmed finding as triaged; below it the finding needs review.
pub const TRIAGE_CONFIDENCE_THRESHOLD: f64 = 3.0;
/// Why the LLM triage left a finding to a person ([`FindingStatus::NeedsReview`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReviewReason {
/// The model dismissed the finding as a likely false alarm.
LikelyFalseAlarm,
/// The model confirmed the finding, but with too little confidence.
Unsure,
}
impl ReviewReason {
/// Why a verdict of the model leaves a finding to a person; `None` when
/// the verdict decides it (confirmed, downgraded or upgraded).
///
/// # Arguments
///
/// * `action` - the model's action (`confirm`, `dismiss`, ...); an unknown
/// one counts as `confirm`
/// * `confidence` - the model's confidence, as stored in `confidence`
pub fn of_verdict(action: &str, confidence: f64) -> Option<Self> {
match action {
TRIAGE_DISMISS => Some(Self::LikelyFalseAlarm),
"downgrade" | "upgrade" => None,
_ if confidence < TRIAGE_CONFIDENCE_THRESHOLD => Some(Self::Unsure),
_ => None,
}
}
}
impl Finding {
/// Why the LLM triage left this finding to a person, read from its stored
/// verdict (`triage_action`, `confidence`); `None` unless it needs review
/// because of that verdict (also when the triage skipped it or the control
/// check put it there).
pub fn review_reason(&self) -> Option<ReviewReason> {
if self.status != FindingStatus::NeedsReview {
return None;
}
match self.triage_action.as_deref()? {
TRIAGE_SKIPPED | TRIAGE_CONTROL_NOT_CONFIRMED => None,
action => ReviewReason::of_verdict(action, self.confidence?),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A finding as the LLM triage leaves it.
fn reviewed(status: FindingStatus, action: &str, confidence: Option<f64>) -> Finding {
let mut finding = Finding::new(
"repo".to_string(),
"fp".to_string(),
"semgrep".to_string(),
ScanType::Sast,
"title".to_string(),
"description".to_string(),
Severity::High,
);
finding.status = status;
finding.triage_action = Some(action.to_string());
finding.confidence = confidence;
finding
}
#[test]
fn a_dismissed_finding_needs_review_as_a_likely_false_alarm() {
let finding = reviewed(FindingStatus::NeedsReview, TRIAGE_DISMISS, Some(9.0));
assert_eq!(
finding.review_reason(),
Some(ReviewReason::LikelyFalseAlarm)
);
}
#[test]
fn a_confirmation_below_the_threshold_is_unsure() {
let unsure = reviewed(FindingStatus::NeedsReview, "confirm", Some(2.9));
assert_eq!(unsure.review_reason(), Some(ReviewReason::Unsure));
// An unknown action counts as a confirmation, as in the triage.
let unknown = reviewed(FindingStatus::NeedsReview, "keep", Some(1.0));
assert_eq!(unknown.review_reason(), Some(ReviewReason::Unsure));
let sure = reviewed(FindingStatus::NeedsReview, "confirm", Some(3.0));
assert_eq!(sure.review_reason(), None);
}
#[test]
fn only_a_finding_that_needs_review_has_a_reason() {
let decided = reviewed(FindingStatus::FalsePositive, TRIAGE_DISMISS, Some(9.0));
assert_eq!(decided.review_reason(), None);
let triaged = reviewed(FindingStatus::Triaged, "confirm", Some(1.0));
assert_eq!(triaged.review_reason(), None);
}
#[test]
fn a_finding_the_model_did_not_put_up_for_review_has_no_reason() {
let mut untriaged = reviewed(FindingStatus::NeedsReview, "confirm", Some(1.0));
untriaged.triage_action = None;
assert_eq!(untriaged.review_reason(), None);
// The control check keeps the model's confidence: it is not the reason.
let control = reviewed(
FindingStatus::NeedsReview,
TRIAGE_CONTROL_NOT_CONFIRMED,
Some(1.0),
);
assert_eq!(control.review_reason(), None);
let skipped = reviewed(FindingStatus::NeedsReview, TRIAGE_SKIPPED, Some(0.5));
assert_eq!(skipped.review_reason(), None);
let no_confidence = reviewed(FindingStatus::NeedsReview, "confirm", None);
assert_eq!(no_confidence.review_reason(), None);
}
#[test]
fn a_change_of_severity_decides_the_finding() {
assert_eq!(ReviewReason::of_verdict("downgrade", 0.0), None);
assert_eq!(ReviewReason::of_verdict("upgrade", 0.0), None);
}
#[test]
fn a_tracker_change_names_the_tracker_user_and_no_scan() {
let change = StatusChange::by_tracker(
FindingStatus::Resolved,
TrackerChangeKind::ClosedInTracker,
"dev-anna",
);
assert_eq!(change.by, StatusChange::TRACKER_ACTOR);
assert_eq!(change.by_name.as_deref(), Some("dev-anna"));
let wire = serde_json::to_value(&change).unwrap_or_default();
assert_eq!(wire["tracker"], "closed_in_tracker");
assert!(wire.get("scan").is_none());
// A change stored before #953 has no `tracker` and still reads.
let mut old = wire.clone();
if let Some(o) = old.as_object_mut() {
o.remove("tracker");
}
let back: Option<StatusChange> = serde_json::from_value(old).ok();
assert!(back.is_some_and(|c| c.tracker.is_none()));
}
#[test]
fn needs_review_reads_and_writes_as_needs_review() {
let wire = serde_json::to_string(&FindingStatus::NeedsReview).unwrap_or_default();
+602
View File
@@ -0,0 +1,602 @@
//! Open findings grouped by rule and place, so that one decision covers
//! every place a rule fired in a file (#951).
//!
//! This is a read-side view: nothing is stored. The grouping (#464) that
//! turns a rule firing all over a repository into one stored finding stays
//! as it is; such a finding is shown here as a group of its own and never
//! merged with others.
//!
//! The rules:
//!
//! * Only undecided findings (open, triaged, needs review) are grouped; a
//! decided one already has its decision.
//! * Findings of one scanner's rule in one file of a target are one group.
//! * When a rule fires in [`DIRECTORY_MIN_FILES`] or more files of one
//! directory, those files are one group for the directory (the files
//! directly in it, not in its subdirectories).
//! * A stored #464 group is a group of its own.
use std::collections::{BTreeMap, HashMap, HashSet};
use bson::oid::ObjectId;
use serde::{Deserialize, Serialize};
use super::finding::{Finding, FindingStatus, Severity};
/// From how many files of one directory a rule's findings are one group
/// for the directory instead of one per file.
pub const DIRECTORY_MIN_FILES: usize = 3;
/// What a group spans.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "snake_case")]
pub enum GroupScope {
/// The places of a rule in one file.
File,
/// The places of a rule in the files of one directory.
Directory,
/// A finding the scan already grouped for the whole repository (#464).
Repository,
}
/// What identifies a group, from the view to the decision: the decision
/// finds the group's members again from it, so it applies to what is open
/// then, not to what a stale view showed.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct GroupKey {
/// The target (`Finding::repo_id`).
pub repo_id: String,
/// The tool that reported it; rule ids are per tool.
pub scanner: String,
/// The rule id, or the title for a finding without one.
pub rule: String,
pub scope: GroupScope,
/// The file ([`GroupScope::File`]), the directory, `""` for the top
/// level ([`GroupScope::Directory`]), or the stored group's fingerprint
/// ([`GroupScope::Repository`]). `None` for findings without a file
/// (a dependency, a web endpoint).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub place: Option<String>,
}
impl GroupKey {
/// The key as one string, for telling groups apart in a view.
pub fn id(&self) -> String {
let scope = match self.scope {
GroupScope::File => "file",
GroupScope::Directory => "dir",
GroupScope::Repository => "repo",
};
format!(
"{}|{}|{}|{scope}|{}",
self.repo_id,
self.scanner,
self.rule,
self.place.as_deref().unwrap_or_default()
)
}
}
/// What the automated review said about a group's members.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct GroupReview {
/// Members the AI dismissed: likely a false alarm.
pub likely_false_alarm: usize,
/// Members the AI was unsure about.
pub unsure: usize,
/// The AI's reason for the first of them (a dismissal first).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rationale: Option<String>,
}
/// Undecided findings of one rule in one place, decided together.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FindingGroup {
pub key: GroupKey,
/// The title of the first member, as the tool wrote it.
pub title: String,
/// The highest severity among the members.
pub severity: Severity,
/// How many places the members stand for: one each, or every place of
/// a stored #464 group.
pub places: usize,
/// Set when the AI flagged members for review.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub review: Option<GroupReview>,
/// The findings, by file and line.
pub members: Vec<Finding>,
}
impl FindingGroup {
/// The group of `members` (at least one) under `key`.
fn new(key: GroupKey, mut members: Vec<Finding>) -> Self {
// `Option` sorts `None` first; members without a line lead.
members.sort_by(|a, b| {
(a.file_path.as_deref(), a.line_number).cmp(&(b.file_path.as_deref(), b.line_number))
});
let severity = members
.iter()
.map(|f| f.severity.clone())
.max()
.unwrap_or(Severity::Info);
let places = members.iter().map(|f| f.occurrences.len().max(1)).sum();
Self {
title: members.first().map(|f| f.title.clone()).unwrap_or_default(),
review: review_of(&members),
key,
severity,
places,
members,
}
}
/// The ids of the members.
pub fn member_ids(&self) -> Vec<ObjectId> {
self.members.iter().filter_map(|f| f.id).collect()
}
}
/// Whether no person has decided about a finding with `status` yet.
pub fn is_undecided(status: &FindingStatus) -> bool {
match status {
FindingStatus::Open | FindingStatus::Triaged | FindingStatus::NeedsReview => true,
FindingStatus::FalsePositive
| FindingStatus::Resolved
| FindingStatus::Ignored
| FindingStatus::AcceptedRisk
| FindingStatus::WrongMapping => false,
}
}
/// What the AI's review said about one finding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AiReview {
/// It dismissed the finding.
LikelyFalseAlarm,
/// It was not confident either way.
Unsure,
}
/// The AI's review of `finding`, when it left the finding for a person.
///
/// Mirrors the predicate PR #958 adds as `Finding::review_reason()`; switch
/// to that once it is merged.
fn ai_review(finding: &Finding) -> Option<AiReview> {
if finding.status != FindingStatus::NeedsReview {
return None;
}
Some(match finding.triage_action.as_deref() {
Some("dismiss") => AiReview::LikelyFalseAlarm,
_ => AiReview::Unsure,
})
}
/// What the AI said about `members`, `None` when it flagged none of them.
fn review_of(members: &[Finding]) -> Option<GroupReview> {
let mut review = GroupReview::default();
let mut unsure_rationale = None;
for finding in members {
let rationale = finding
.triage_rationale
.as_deref()
.map(str::trim)
.filter(|r| !r.is_empty());
match ai_review(finding) {
Some(AiReview::LikelyFalseAlarm) => {
review.likely_false_alarm += 1;
review.rationale = review.rationale.or_else(|| rationale.map(String::from));
}
Some(AiReview::Unsure) => {
review.unsure += 1;
unsure_rationale = unsure_rationale.or(rationale);
}
None => {}
}
}
if review.likely_false_alarm + review.unsure == 0 {
return None;
}
review.rationale = review
.rationale
.or_else(|| unsure_rationale.map(String::from));
Some(review)
}
/// The rule a finding is grouped by: its id, or its title without one.
fn rule_of(finding: &Finding) -> String {
finding
.rule_id
.as_deref()
.filter(|r| !r.is_empty())
.unwrap_or(&finding.title)
.to_string()
}
/// The directory of a repo-relative `path`, `""` at the top level.
fn parent_dir(path: &str) -> &str {
path.rfind(['/', '\\']).map_or("", |i| &path[..i])
}
/// A rule of one tool in one target: (target, scanner, rule).
type RuleInTarget = (String, String, String);
/// Findings by their file (`None`: without one).
type ByFile = BTreeMap<Option<String>, Vec<Finding>>;
/// Group the undecided ones among `findings` (see the module docs); decided
/// findings are left out.
///
/// # Returns
///
/// The groups, most severe first, then the ones with the most places.
///
/// # Examples
///
/// ```
/// use compliance_core::models::finding_group::group_findings;
/// use compliance_core::models::{Finding, ScanType, Severity};
///
/// let at = |line| {
/// let mut f = Finding::new(
/// "repo".into(), format!("fp-{line}"), "gdpr-patterns".into(),
/// ScanType::Sast, "PII data potentially logged".into(), "".into(),
/// Severity::Medium,
/// );
/// f.rule_id = Some("pii-logged".into());
/// f.file_path = Some("src/patterns.rs".into());
/// f.line_number = Some(line);
/// f
/// };
/// let groups = group_findings(vec![at(299), at(302)]);
/// assert_eq!(groups.len(), 1);
/// assert_eq!(groups[0].places, 2);
/// ```
pub fn group_findings(findings: impl IntoIterator<Item = Finding>) -> Vec<FindingGroup> {
let mut groups = Vec::new();
let mut by_rule: HashMap<RuleInTarget, ByFile> = HashMap::new();
for finding in findings.into_iter().filter(|f| is_undecided(&f.status)) {
let rule = rule_of(&finding);
if !finding.occurrences.is_empty() {
let key = GroupKey {
repo_id: finding.repo_id.clone(),
scanner: finding.scanner.clone(),
rule,
scope: GroupScope::Repository,
place: Some(finding.fingerprint.clone()),
};
groups.push(FindingGroup::new(key, vec![finding]));
continue;
}
let file = finding.file_path.clone().filter(|p| !p.is_empty());
by_rule
.entry((finding.repo_id.clone(), finding.scanner.clone(), rule))
.or_default()
.entry(file)
.or_default()
.push(finding);
}
for ((repo_id, scanner, rule), by_file) in by_rule {
let key = |scope, place| GroupKey {
repo_id: repo_id.clone(),
scanner: scanner.clone(),
rule: rule.clone(),
scope,
place,
};
let mut files_per_dir: HashMap<&str, usize> = HashMap::new();
for file in by_file.keys().flatten() {
*files_per_dir.entry(parent_dir(file)).or_default() += 1;
}
let wide_dirs: HashSet<String> = files_per_dir
.into_iter()
.filter(|(_, files)| *files >= DIRECTORY_MIN_FILES)
.map(|(dir, _)| dir.to_string())
.collect();
let mut by_dir: BTreeMap<String, Vec<Finding>> = BTreeMap::new();
for (file, members) in by_file {
match file {
Some(file) if wide_dirs.contains(parent_dir(&file)) => by_dir
.entry(parent_dir(&file).to_string())
.or_default()
.extend(members),
file => groups.push(FindingGroup::new(key(GroupScope::File, file), members)),
}
}
groups.extend(by_dir.into_iter().map(|(dir, members)| {
FindingGroup::new(key(GroupScope::Directory, Some(dir)), members)
}));
}
groups.sort_by(|a, b| {
b.severity
.cmp(&a.severity)
.then(b.places.cmp(&a.places))
.then_with(|| a.key.cmp(&b.key))
});
groups
}
/// The ids of the undecided findings among `findings` that make up the
/// group `key`; empty when there is no such group (any more).
pub fn members_of(findings: impl IntoIterator<Item = Finding>, key: &GroupKey) -> Vec<ObjectId> {
group_findings(findings)
.into_iter()
.find(|g| g.key == *key)
.map(|g| g.member_ids())
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::models::{Occurrence, ScanType};
fn finding(rule: &str, file: &str, line: u32) -> Finding {
let mut f = Finding::new(
"repo-1".into(),
format!("fp-{file}-{line}"),
"gdpr-patterns".into(),
ScanType::Sast,
"PII data potentially logged".into(),
"d".into(),
Severity::Medium,
);
f.id = Some(ObjectId::new());
f.rule_id = Some(rule.into());
f.file_path = Some(file.into());
f.line_number = Some(line);
f
}
fn scopes(groups: &[FindingGroup]) -> Vec<(GroupScope, Option<&str>, usize)> {
groups
.iter()
.map(|g| (g.key.scope, g.key.place.as_deref(), g.members.len()))
.collect()
}
#[test]
fn one_rule_in_one_file_is_one_group() {
let groups = group_findings(vec![
finding("pii-logged", "src/patterns.rs", 302),
finding("pii-logged", "src/patterns.rs", 299),
finding("pii-logged", "src/patterns.rs", 301),
]);
assert_eq!(
scopes(&groups),
[(GroupScope::File, Some("src/patterns.rs"), 3)]
);
assert_eq!(groups[0].places, 3);
let lines: Vec<_> = groups[0].members.iter().map(|f| f.line_number).collect();
assert_eq!(lines, [Some(299), Some(301), Some(302)]);
}
#[test]
fn other_files_and_other_rules_are_other_groups() {
let groups = group_findings(vec![
finding("pii-logged", "src/a.rs", 1),
finding("pii-logged", "lib/b.rs", 1),
finding("other-rule", "src/a.rs", 2),
]);
assert_eq!(groups.len(), 3);
assert!(groups.iter().all(|g| g.key.scope == GroupScope::File));
}
#[test]
fn the_same_rule_id_of_another_tool_is_another_group() {
let mut other = finding("pii-logged", "src/a.rs", 2);
other.scanner = "semgrep".into();
let groups = group_findings(vec![finding("pii-logged", "src/a.rs", 1), other]);
assert_eq!(groups.len(), 2);
}
#[test]
fn many_files_of_one_directory_are_one_group() {
let groups = group_findings(vec![
finding("pii-logged", "src/api/a.rs", 1),
finding("pii-logged", "src/api/a.rs", 9),
finding("pii-logged", "src/api/b.rs", 1),
finding("pii-logged", "src/api/c.rs", 1),
// A subdirectory and another directory stay apart.
finding("pii-logged", "src/api/v2/d.rs", 1),
finding("pii-logged", "src/e.rs", 1),
]);
let mut found = scopes(&groups);
found.sort();
assert_eq!(
found,
[
(GroupScope::File, Some("src/api/v2/d.rs"), 1),
(GroupScope::File, Some("src/e.rs"), 1),
(GroupScope::Directory, Some("src/api"), 4),
]
);
}
#[test]
fn fewer_files_than_the_directory_needs_stay_one_group_per_file() {
let groups = group_findings(vec![
finding("pii-logged", "src/a.rs", 1),
finding("pii-logged", "src/b.rs", 1),
]);
assert_eq!(groups.len(), DIRECTORY_MIN_FILES - 1);
assert!(groups.iter().all(|g| g.key.scope == GroupScope::File));
}
#[test]
fn top_level_files_group_under_the_empty_directory() {
let groups = group_findings(vec![
finding("pii-logged", "a.rs", 1),
finding("pii-logged", "b.rs", 1),
finding("pii-logged", "c.rs", 1),
]);
assert_eq!(scopes(&groups), [(GroupScope::Directory, Some(""), 3)]);
}
#[test]
fn decided_findings_are_left_out() {
let mut decided = finding("pii-logged", "src/a.rs", 2);
decided.status = FindingStatus::FalsePositive;
let mut accepted = finding("pii-logged", "src/a.rs", 3);
accepted.status = FindingStatus::AcceptedRisk;
let mut triaged = finding("pii-logged", "src/a.rs", 4);
triaged.status = FindingStatus::Triaged;
let groups = group_findings(vec![
finding("pii-logged", "src/a.rs", 1),
decided,
accepted,
triaged,
]);
assert_eq!(scopes(&groups), [(GroupScope::File, Some("src/a.rs"), 2)]);
assert!(group_findings(vec![{
let mut f = finding("r", "x.rs", 1);
f.status = FindingStatus::Resolved;
f
}])
.is_empty());
}
#[test]
fn a_stored_group_stays_a_group_of_its_own() {
let mut stored = finding("pii-logged", "src/a.rs", 1);
stored.fingerprint = "group-fp".into();
stored.occurrences = (1..=7)
.map(|line| Occurrence {
file: "src/a.rs".into(),
line: Some(line),
variant: None,
decision: None,
})
.collect();
let groups = group_findings(vec![stored, finding("pii-logged", "src/a.rs", 20)]);
assert_eq!(
scopes(&groups),
[
(GroupScope::Repository, Some("group-fp"), 1),
(GroupScope::File, Some("src/a.rs"), 1),
]
);
assert_eq!(groups[0].places, 7);
}
#[test]
fn findings_without_a_file_or_rule_still_group() {
let mut no_file = finding("CVE-2024-1", "", 0);
no_file.file_path = None;
let mut no_file_2 = no_file.clone();
no_file_2.id = Some(ObjectId::new());
let mut no_rule = finding("", "src/a.rs", 1);
no_rule.rule_id = None;
let groups = group_findings(vec![no_file, no_file_2, no_rule]);
let mut found: Vec<_> = groups
.iter()
.map(|g| (g.key.rule.as_str(), g.key.place.as_deref(), g.members.len()))
.collect();
found.sort();
assert_eq!(
found,
[
("CVE-2024-1", None, 2),
("PII data potentially logged", Some("src/a.rs"), 1),
]
);
}
#[test]
fn the_most_severe_group_leads() {
let mut critical = finding("hardcoded-key", "src/z.rs", 1);
critical.severity = Severity::Critical;
let groups = group_findings(vec![
finding("pii-logged", "src/a.rs", 1),
finding("pii-logged", "src/a.rs", 2),
critical,
]);
assert_eq!(groups[0].severity, Severity::Critical);
assert_eq!(groups[1].places, 2);
}
#[test]
fn the_group_carries_the_ais_reason() {
let mut dismissed = finding("pii-logged", "src/a.rs", 1);
dismissed.status = FindingStatus::NeedsReview;
dismissed.triage_action = Some("dismiss".into());
dismissed.triage_rationale = Some(" Only a user id, no PII. ".into());
let mut unsure = finding("pii-logged", "src/a.rs", 2);
unsure.status = FindingStatus::NeedsReview;
unsure.triage_action = Some("confirm".into());
unsure.triage_rationale = Some("Unclear".into());
let groups = group_findings(vec![
unsure,
dismissed,
finding("pii-logged", "src/a.rs", 3),
]);
assert_eq!(
groups[0].review,
Some(GroupReview {
likely_false_alarm: 1,
unsure: 1,
rationale: Some("Only a user id, no PII.".into()),
})
);
assert_eq!(
group_findings(vec![finding("r", "a.rs", 1)])[0].review,
None
);
}
#[test]
fn the_members_of_a_key_are_found_again() {
let one = finding("pii-logged", "src/a.rs", 1);
let two = finding("pii-logged", "src/a.rs", 2);
let other = finding("pii-logged", "src/b.rs", 1);
let ids = [one.id, two.id];
let all = vec![one, two, other];
let key = GroupKey {
repo_id: "repo-1".into(),
scanner: "gdpr-patterns".into(),
rule: "pii-logged".into(),
scope: GroupScope::File,
place: Some("src/a.rs".into()),
};
let mut found: Vec<_> = members_of(all.clone(), &key)
.into_iter()
.map(Some)
.collect();
found.sort();
let mut expected = ids.to_vec();
expected.sort();
assert_eq!(found, expected);
let gone = GroupKey {
place: Some("src/c.rs".into()),
..key
};
assert!(members_of(all, &gone).is_empty());
}
#[test]
fn a_key_reads_and_writes_by_its_names() {
let key = GroupKey {
repo_id: "r".into(),
scanner: "s".into(),
rule: "x".into(),
scope: GroupScope::Directory,
place: Some("src".into()),
};
let wire = serde_json::to_value(&key).unwrap_or_default();
assert_eq!(wire["scope"], "directory");
assert_eq!(
serde_json::from_value::<GroupKey>(wire).ok().as_ref(),
Some(&key)
);
assert_ne!(
key.id(),
GroupKey {
scope: GroupScope::File,
..key.clone()
}
.id()
);
}
}
+39
View File
@@ -121,6 +121,20 @@ pub struct GraphBuildRun {
pub edge_count: u32,
pub community_count: u32,
pub languages_parsed: Vec<String>,
/// Nodes that are files; the other nodes are the declarations in them.
/// `None` on a build stored before it was counted.
#[serde(default)]
pub file_count: Option<u32>,
/// Nodes that are entry points (`main`, request handlers, interrupt
/// handlers, PLC programs). `None` on a build stored before it was counted.
#[serde(default)]
pub entry_point_count: Option<u32>,
/// Source files left out because they could not be read as text (not
/// UTF-8, UTF-16 with a byte-order mark or Windows-1252, or an I/O
/// error). `None` on a build stored before it was counted, and on a PLC
/// build, whose files are read by the PLC stage.
#[serde(default)]
pub unreadable_file_count: Option<u32>,
pub error_message: Option<String>,
#[serde(with = "super::serde_helpers::bson_datetime")]
pub started_at: DateTime<Utc>,
@@ -139,6 +153,9 @@ impl GraphBuildRun {
edge_count: 0,
community_count: 0,
languages_parsed: Vec::new(),
file_count: None,
entry_point_count: None,
unreadable_file_count: None,
error_message: None,
started_at: Utc::now(),
completed_at: None,
@@ -187,3 +204,25 @@ impl ImpactAnalysis {
}
}
}
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use super::*;
#[test]
fn a_build_stored_before_the_counts_still_reads() {
// Arrange: a stored build as t82 and earlier wrote it.
let mut stored = bson::to_document(&GraphBuildRun::new("r".to_string())).expect("bson");
for field in ["file_count", "entry_point_count", "unreadable_file_count"] {
stored.remove(field);
}
// Act
let build: GraphBuildRun = bson::from_document(stored).expect("old build reads");
// Assert
assert_eq!(build.file_count, None);
assert_eq!(build.unreadable_file_count, None);
}
}
File diff suppressed because it is too large. Load diff
+114
View File
@@ -41,6 +41,49 @@ impl std::fmt::Display for IssueStatus {
}
}
impl IssueStatus {
/// Every status, open ones first.
pub const ALL: [Self; 4] = [Self::Open, Self::InProgress, Self::Closed, Self::Resolved];
/// Whether the ticket is done (closed or resolved); the other two are
/// open.
pub fn is_closed(&self) -> bool {
match self {
Self::Closed | Self::Resolved => true,
Self::Open | Self::InProgress => false,
}
}
}
/// What a ticket is about, as its `finding_id` says.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IssueSubject<'a> {
/// One finding, by its id (the hex of its `ObjectId`).
Finding(&'a str),
/// A known vulnerability in one target's components, by the target id.
Cve {
/// The target (repository) the CVE was found in.
target_id: &'a str,
},
}
/// What the `finding_id` of a CVE ticket starts with.
const CVE_KEY: &str = "cve:";
/// The start of the `finding_id` of every CVE ticket of one target. The whole
/// key is `cve:{target_id}:{package}:{cve}`: one ticket per target, package
/// and CVE.
///
/// # Examples
///
/// ```
/// use compliance_core::models::issue::cve_issue_prefix;
/// assert_eq!(cve_issue_prefix("abc"), "cve:abc:");
/// ```
pub fn cve_issue_prefix(target_id: &str) -> String {
format!("{CVE_KEY}{target_id}:")
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrackerIssue {
#[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
@@ -51,6 +94,10 @@ pub struct TrackerIssue {
pub external_url: String,
pub title: String,
pub status: IssueStatus,
/// The tracker user who closed the issue there (#953), while it stays
/// closed: a person's decision the scan does not undo on its own.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub closed_in_tracker: Option<String>,
#[serde(with = "super::serde_helpers::bson_datetime")]
pub created_at: DateTime<Utc>,
#[serde(with = "super::serde_helpers::bson_datetime")]
@@ -74,8 +121,75 @@ impl TrackerIssue {
external_url,
title,
status: IssueStatus::Open,
closed_in_tracker: None,
created_at: now,
updated_at: now,
}
}
/// What the ticket is about: its finding, or for a CVE ticket the target
/// the CVE is in. `None` when `finding_id` is neither (empty, for an
/// issue whose finding had no id).
pub fn subject(&self) -> Option<IssueSubject<'_>> {
if let Some(rest) = self.finding_id.strip_prefix(CVE_KEY) {
// `rest` is `{target_id}:{package}:{cve}`; `split` always yields
// a first piece, so only an empty one is refused.
return rest
.split(':')
.next()
.filter(|id| !id.is_empty())
.map(|target_id| IssueSubject::Cve { target_id });
}
let id = self.finding_id.as_str();
(id.len() == 24 && id.bytes().all(|b| b.is_ascii_hexdigit()))
.then_some(IssueSubject::Finding(id))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn issue(finding_id: &str) -> TrackerIssue {
TrackerIssue::new(
finding_id.to_string(),
TrackerType::Gitea,
"913".into(),
"https://gitea.invalid/o/r/issues/913".into(),
"[high] semgrep: hardcoded key".into(),
)
}
#[test]
fn a_finding_ticket_is_about_its_finding() {
let id = "65a1b2c3d4e5f60718293a4b";
assert_eq!(issue(id).subject(), Some(IssueSubject::Finding(id)));
}
#[test]
fn a_cve_ticket_is_about_its_target() {
let key = format!("{}openssl:CVE-2024-0001", cve_issue_prefix("tgt1"));
assert_eq!(
issue(&key).subject(),
Some(IssueSubject::Cve { target_id: "tgt1" })
);
}
#[test]
fn a_ticket_without_a_usable_id_is_about_nothing() {
assert_eq!(issue("").subject(), None);
assert_eq!(issue("cve::pkg:CVE-1").subject(), None);
assert_eq!(issue("not-an-object-id").subject(), None);
// The right length, but not hex.
assert_eq!(issue("zzzzzzzzzzzzzzzzzzzzzzzz").subject(), None);
}
#[test]
fn closed_and_resolved_are_closed() {
let closed: Vec<IssueStatus> = IssueStatus::ALL
.into_iter()
.filter(IssueStatus::is_closed)
.collect();
assert_eq!(closed, [IssueStatus::Closed, IssueStatus::Resolved]);
}
}
+181
View File
@@ -351,6 +351,93 @@ pub fn apply(entries: &mut [SbomEntry], conclusions: &[LicenseConclusion]) {
}
}
/// The four groups the licence chart of a target shows (#957), coarser than
/// [`LicenseCategory`]. Declared in chart order, from least to most to
/// look at; the order is also the index into [`LicenseGroupCounts`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LicenseGroup {
/// Public domain, permissive and own code.
Permissive,
/// LGPL, MPL, EPL, CDDL and the like.
WeakCopyleft,
/// GPL, and network copyleft (AGPL).
StrongCopyleft,
/// No licence, one SPDX cannot read, or a proprietary one: a person has
/// to look at it.
Unknown,
}
impl LicenseGroup {
/// Every group, in chart order.
pub const ALL: [Self; 4] = [
Self::Permissive,
Self::WeakCopyleft,
Self::StrongCopyleft,
Self::Unknown,
];
}
impl LicenseCategory {
/// The chart group of this category. A proprietary licence is neither
/// open source nor copyleft, so it is grouped with the unknown ones: its
/// terms are a contract a person has to read.
pub fn group(self) -> LicenseGroup {
match self {
Self::PublicDomain | Self::Permissive | Self::OwnCode => LicenseGroup::Permissive,
Self::WeakCopyleft => LicenseGroup::WeakCopyleft,
Self::StrongCopyleft | Self::NetworkCopyleft => LicenseGroup::StrongCopyleft,
Self::Proprietary | Self::Unclear => LicenseGroup::Unknown,
}
}
}
/// How many components fall into each [`LicenseGroup`].
///
/// # Examples
///
/// ```
/// use compliance_core::models::license::{LicenseGroup, LicenseGroupCounts};
/// use compliance_core::models::LicenseCategory;
///
/// let counts: LicenseGroupCounts = [
/// (LicenseCategory::Permissive, 3),
/// (LicenseCategory::PublicDomain, 1),
/// (LicenseCategory::NetworkCopyleft, 2),
/// ]
/// .into_iter()
/// .collect();
/// assert_eq!(counts.get(LicenseGroup::Permissive), 4);
/// assert_eq!(counts.get(LicenseGroup::StrongCopyleft), 2);
/// assert_eq!(counts.total(), 6);
/// ```
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct LicenseGroupCounts([u64; 4]);
impl LicenseGroupCounts {
/// The components in `group`.
pub fn get(self, group: LicenseGroup) -> u64 {
// A field-less enum casts to its position (`Permissive` is 0).
self.0[group as usize]
}
/// The components in every group.
pub fn total(self) -> u64 {
self.0.iter().sum()
}
}
/// Counts from `(category, components)` pairs, such as the rows of the
/// licence summary.
impl FromIterator<(LicenseCategory, u64)> for LicenseGroupCounts {
fn from_iter<I: IntoIterator<Item = (LicenseCategory, u64)>>(rows: I) -> Self {
let mut counts = Self::default();
for (category, count) in rows {
counts.0[category.group() as usize] += count;
}
counts
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -481,4 +568,98 @@ mod tests {
assert!(LicenseCategory::WeakCopyleft.is_copyleft());
assert!(!LicenseCategory::Proprietary.is_copyleft());
}
#[test]
fn every_category_falls_into_one_chart_group() {
use LicenseCategory as C;
use LicenseGroup as G;
for (category, group) in [
(C::PublicDomain, G::Permissive),
(C::Permissive, G::Permissive),
(C::OwnCode, G::Permissive),
(C::WeakCopyleft, G::WeakCopyleft),
(C::StrongCopyleft, G::StrongCopyleft),
(C::NetworkCopyleft, G::StrongCopyleft),
(C::Proprietary, G::Unknown),
(C::Unclear, G::Unknown),
] {
assert_eq!(category.group(), group, "{category:?}");
}
// Every group is reached, and copyleft groups hold only copyleft.
for group in LicenseGroup::ALL {
let members: Vec<_> = LicenseCategory::ALL
.into_iter()
.filter(|c| c.group() == group)
.collect();
assert!(!members.is_empty(), "{group:?} is empty");
let copyleft = matches!(group, G::WeakCopyleft | G::StrongCopyleft);
assert!(members.iter().all(|c| c.is_copyleft() == copyleft));
}
}
#[test]
fn licence_expressions_fall_into_the_group_of_their_category() {
use crate::spdx_license::category;
use LicenseGroup as G;
for (license, group) in [
("MIT", G::Permissive),
("Apache-2.0", G::Permissive),
("BSD-3-Clause", G::Permissive),
("CC0-1.0", G::Permissive),
("The Apache Software License, Version 2.0", G::Permissive),
("LGPL-2.1-or-later", G::WeakCopyleft),
("MPL-2.0", G::WeakCopyleft),
("EPL-2.0", G::WeakCopyleft),
("CDDL-1.0", G::WeakCopyleft),
("GPL-3.0-only", G::StrongCopyleft),
("GPL-2.0+", G::StrongCopyleft),
("AGPL-3.0-or-later", G::StrongCopyleft),
// `OR`: the most permissive choice counts.
("MIT OR GPL-3.0-only", G::Permissive),
("(LGPL-2.1-only OR GPL-2.0-only)", G::WeakCopyleft),
// `AND`: the most restrictive term counts.
("MIT AND GPL-2.0-only", G::StrongCopyleft),
("Apache-2.0 AND MPL-2.0", G::WeakCopyleft),
// An exception after `WITH` keeps the licence's category (the
// licence policy, #570, reads it the same way).
(
"GPL-2.0-only WITH Classpath-exception-2.0",
G::StrongCopyleft,
),
("Apache-2.0 WITH LLVM-exception", G::Permissive),
// Nothing a person could rely on.
("", G::Unknown),
("NOASSERTION", G::Unknown),
("NONE", G::Unknown),
("LicenseRef-Pump-EULA", G::Unknown),
("Custom Pump License", G::Unknown),
("MIT AND LicenseRef-Pump-EULA", G::Unknown),
] {
assert_eq!(category(license).group(), group, "{license}");
}
}
#[test]
fn group_counts_add_up_the_rows_of_each_group() {
use LicenseCategory as C;
let counts: LicenseGroupCounts = [
(C::Permissive, 10),
(C::OwnCode, 2),
(C::WeakCopyleft, 3),
(C::StrongCopyleft, 40),
(C::NetworkCopyleft, 9),
(C::Unclear, 5),
(C::Proprietary, 1),
]
.into_iter()
.collect();
assert_eq!(counts.get(LicenseGroup::Permissive), 12);
assert_eq!(counts.get(LicenseGroup::WeakCopyleft), 3);
assert_eq!(counts.get(LicenseGroup::StrongCopyleft), 49);
assert_eq!(counts.get(LicenseGroup::Unknown), 6);
assert_eq!(counts.total(), 70);
let empty: LicenseGroupCounts = std::iter::empty().collect();
assert_eq!(empty, LicenseGroupCounts::default());
assert_eq!(empty.total(), 0);
}
}
+566
View File
@@ -0,0 +1,566 @@
//! 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,
}
}
/// The customer's choice for a target's billing, from a swap (t72): the
/// target swapped in is wanted included, the one swapped out extra.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum IncludedChoice {
/// Swapped in: included before the oldest targets.
Included,
/// Swapped out: extra before the newest targets.
Extra,
}
impl IncludedChoice {
/// Where a target with `choice` comes in the split: swapped in first,
/// swapped out last, every other target by age in between.
fn rank(choice: Option<Self>) -> u8 {
match choice {
Some(Self::Included) => 0,
None => 1,
Some(Self::Extra) => 2,
}
}
}
/// Why a swap of an extra target with an included one is not made (t72).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SwapRefusal {
/// The plan includes every target, so there is nothing to swap.
Unlimited,
/// The target to swap in is not extra.
NotExtra,
/// The target to swap out is not included.
NotIncluded,
/// The target to swap out was swapped in this month and stays included
/// until the month's end.
Locked,
}
/// Whether an extra target may be swapped with an included one, by the
/// contract: at any time, except that a target swapped in stays included
/// until the end of its calendar month.
///
/// # Arguments
///
/// * `limited` - Whether the plan limits the included targets.
/// * `incoming` - How the target to swap in is billed now.
/// * `outgoing` - How the target to swap out is billed now.
/// * `outgoing_locked` - Whether the target to swap out is still within
/// the month it was swapped in.
///
/// # Errors
///
/// The [`SwapRefusal`] that stops the swap.
pub fn check_swap(
limited: bool,
incoming: TargetBilling,
outgoing: TargetBilling,
outgoing_locked: bool,
) -> Result<(), SwapRefusal> {
if !limited {
return Err(SwapRefusal::Unlimited);
}
if incoming != TargetBilling::Extra {
return Err(SwapRefusal::NotExtra);
}
if outgoing != TargetBilling::Included {
return Err(SwapRefusal::NotIncluded);
}
if outgoing_locked {
return Err(SwapRefusal::Locked);
}
Ok(())
}
/// 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 customer's choice from a swap, if any.
pub choice: Option<IncludedChoice>,
}
/// The targets whose billing has to change so that the `included` oldest
/// active targets are included and the rest are extra; a target the
/// customer swapped in comes before the oldest, one swapped out after the
/// newest.
///
/// # 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| {
IncludedChoice::rank(a.choice)
.cmp(&IncludedChoice::rank(b.choice))
.then(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,
choice: None,
}
}
#[test]
fn a_swap_moves_one_in_and_one_out() {
// Arrange: two included (days 1, 2) and one extra (day 3); the
// customer swaps 3 in for 1.
let mut incoming = target(3, 3, TargetBilling::Extra);
incoming.choice = Some(IncludedChoice::Included);
let mut outgoing = target(1, 1, TargetBilling::Included);
outgoing.choice = Some(IncludedChoice::Extra);
let targets = [outgoing, target(2, 2, TargetBilling::Included), incoming];
// Act
let mut changes = split_included(&targets, Some(2));
changes.sort_unstable_by_key(|(id, _)| *id);
// Assert: the count of extra targets is the same.
assert_eq!(
changes,
vec![(1, TargetBilling::Extra), (3, TargetBilling::Included)]
);
}
#[test]
fn a_target_swapped_in_this_month_cannot_go_out() {
use TargetBilling::{Extra, Included};
assert_eq!(check_swap(true, Extra, Included, false), Ok(()));
assert_eq!(
check_swap(true, Extra, Included, true),
Err(SwapRefusal::Locked)
);
assert_eq!(
check_swap(true, Included, Included, false),
Err(SwapRefusal::NotExtra)
);
assert_eq!(
check_swap(true, Extra, Extra, false),
Err(SwapRefusal::NotIncluded)
);
assert_eq!(
check_swap(false, Extra, Included, false),
Err(SwapRefusal::Unlimited)
);
}
#[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"
);
}
}
+11 -2
View File
@@ -6,13 +6,16 @@ pub mod dast;
pub mod embedding;
pub mod exclude_paths;
pub mod finding;
pub mod finding_group;
pub mod git_source;
pub mod graph;
pub mod inbox;
pub mod issue;
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;
@@ -44,19 +47,25 @@ 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,
Finding, FindingStatus, Occurrence, ReviewReason, ScanChangeKind, ScanStatusChange, Severity,
StatusChange, TrackerChangeKind,
};
pub use git_source::{GitSource, GitSourceView, SourceRepo, GIT_SOURCE_ID};
pub use graph::{
CodeEdge, CodeEdgeKind, CodeNode, CodeNodeKind, GraphBuildRun, GraphBuildStatus, ImpactAnalysis,
};
pub use issue::{IssueStatus, TrackerIssue, TrackerType};
pub use issue::{IssueStatus, IssueSubject, TrackerIssue, TrackerType};
pub use license::{LicenseCategory, LicenseConclusion, LicenseUsage};
pub use license_policy::{
LegalReview, LicensePolicy, LicenseVerdict, PolicyAction, ReviewDecision,
};
pub use mcp::{McpServerConfig, McpServerStatus, McpTransport};
pub use mcp_token::{McpToken, McpTokenView};
pub use metering::{
admit, check_swap, split_included, Admission, BillableTarget, DayUsage, IncludedChoice,
MonthUsage, PlanLimits, Refusal, RunCharge, ScanAttribution, SwapRefusal, TargetBilling,
PRUEFUNGEN_PER_PRUEFTAG,
};
pub use notification::{CveNotification, NotificationSeverity, NotificationStatus};
pub use onboarding::{
default_compliance_profile, Artifact, ArtifactAuth, ArtifactKind, Classification,
+20
View File
@@ -660,6 +660,23 @@ 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,
/// The customer's choice from a swap of an extra target with an
/// included one (t72); `None` until one is made.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub included_choice: Option<super::metering::IncludedChoice>,
/// Until when a target swapped in stays included: the end of the
/// calendar month (Europe/Berlin) it was swapped in.
#[serde(
default,
skip_serializing_if = "Option::is_none",
with = "super::serde_helpers::opt_bson_datetime"
)]
pub included_until: Option<DateTime<Utc>>,
/// Creation timestamp.
#[serde(
default = "chrono::Utc::now",
@@ -700,6 +717,9 @@ impl OnboardedTarget {
archived_at: None,
last_scan: None,
layer_pins: None,
billing: super::metering::TargetBilling::default(),
included_choice: None,
included_until: None,
created_at: now,
updated_at: now,
}
+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,
}
}
}
Loaded 100 of 196 files, more files were not shown because too many files have changed in this diff. Show more