Compare commits

..
23 Commits
Author SHA1 Message Date
sharangandClaude Opus 5.5 34688fa322 feat(sbom): NuGet licenses from .nuspec files, then nuget.org (#468)
CI / Detect Changes (push) Successful in 3s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Docs (push) Successful in 1m9s
CI / Deploy Agent (push) Successful in 4m44s
CI / Check (push) Skipped
NuGet SBOM entries carried no license: none of the files they come from
names one. Fill it in after the NuGet components are merged (#467):

- local first: the .nuspec of a restored package; <license
  type="expression"> as SPDX, type="file" as LicenseRef-file, an old
  <licenseUrl> mapped to SPDX for well-known license pages, else kept
- then nuget.org: registration leaf (gzip) -> catalogEntry (inline or
  linked on api.nuget.org) -> licenseExpression / licenseFile / licenseUrl
- only real ids at exact versions (no ranges, no DLL-metadata names);
  versions normalised as nuget.org files them (6.2.0.0 -> 6.2.0, 2.0 ->
  2.0.0)
- ids a nuget.config maps to another feed are never sent; a tree whose
  nuget.config lists another feed without a mapping is not looked up
- through guarded_net, 8 at once, 10 s per request, 60 s and 300
  uncached packages per scan; failures stay empty, one warning per scan
- cached across tenants in the admin database (nuget_licenses, TTL: a
  year for a license, a week for none)
- NUGET_LICENSE_LOOKUP=false turns the nuget.org step off

Closes #467

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-10-05 21:50:32 +00:00
sharang 04b4f32807 feat(mobile): legacy Android and Unity builds flagged, not resolved; Android found everywhere (#466)
CI / Check (push) Skipped
CI / Deploy Docs (push) Successful in 1m12s
CI / Detect Changes (push) Successful in 3s
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Successful in 5m0s
CI / Deploy Agent (push) Successful in 6m27s
2026-10-05 21:17:52 +00:00
sharang 0da96110c3 feat(lifecycle): scans interrupted by an agent restart start again (#459)
CI / Deploy Agent (push) Successful in 4m42s
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Dashboard (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
2026-10-05 20:14:27 +00:00
sharang 3822d624e1 fix(git-source): managed targets get the type their code shows (#458)
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 5m41s
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Successful in 4m21s
CI / Deploy MCP (push) Successful in 2m28s
2026-10-05 20:14:21 +00:00
sharang 96da28dd3f fix(llm): a reasoning model out of tokens is asked again with a larger budget (#457)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Dashboard (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Agent (push) Successful in 5m24s
2026-10-05 19:09:08 +00:00
sharang 6c9756bebf feat(secrets): Android signing passwords and Firebase keys; our gitleaks config only (#456)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Dashboard (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Agent (push) Canceled after 0s
2026-10-05 18:31:33 +00:00
sharang d98cbbada4 fix(dashboard): readable tool names for findings, including the new .NET and mobile checks (#455)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Agent (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Successful in 3m31s
2026-10-05 18:26:27 +00:00
sharang 808b6ab3aa fix(mcp): MCP server cards per tenant, not shared by all (#454)
CI / Check (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy Dashboard (push) Canceled after 0s
CI / Deploy Agent (push) Canceled after 0s
2026-10-05 18:19:04 +00:00
sharang 81699b2111 fix(triage): read imperfect batch answers and retry unanswered findings once (#453)
CI / Check (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy MCP (push) Skipped
CI / Deploy Agent (push) Canceled after 0s
2026-10-05 18:15:19 +00:00
sharang 7e3d57b648 feat(issues): critical and high CVEs as issues in managed repositories (#452)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Agent (push) Successful in 5m40s
CI / Deploy Docs (push) Successful in 45s
CI / Deploy Dashboard (push) Successful in 4m23s
CI / Deploy MCP (push) Successful in 2m49s
2026-10-05 17:52:36 +00:00
sharangandClaude Opus 5.5 8926255d6f feat(dotnet): .NET detection, NuGet SBOM, C# rules and config checks (#447)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Agent (push) Successful in 4m42s
CI / Deploy Docs (push) Successful in 1m10s
Minimal .NET/C# support for epic #445 (N1-N5): detection of solutions/projects and target frameworks, NuGet SBOM without build or restore (pkg:nuget purls for OSV, unresolved-dependency warning, end-of-support frameworks), own C# semgrep rule pack, .NET configuration and key-file checks, .NET build output and restored packages not counted as own code. Fixture fixtures/dotnet/framework48, docs .NET-Projekte (DE/EN).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-10-05 14:38:13 +00:00
sharang 654f387c80 feat(issues): a tracker issue follows its finding's status (#451)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Docs (push) Successful in 1m8s
CI / Deploy Agent (push) Successful in 5m45s
2026-10-05 14:14:13 +00:00
sharang 2cbd98e5c0 feat(git): bounded clones, Git LFS made visible, app build output left out (#450)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Successful in 1m12s
CI / Deploy Dashboard (push) Successful in 5m33s
CI / Deploy MCP (push) Successful in 4m11s
CI / Deploy Agent (push) Successful in 7m27s
2026-10-05 14:05:19 +00:00
sharang e92c395e50 feat(classify): Android modules at any depth, Unity, React Native, Flutter, .NET split (#449)
CI / Detect Changes (push) Successful in 4s
CI / Deploy Dashboard (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Check (push) Skipped
CI / Deploy Agent (push) Successful in 7m30s
2026-10-05 14:02:43 +00:00
sharang 3790b9c6cc fix(sast): concurrent scans no longer fail semgrep while staging the rules (#448)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy Agent (push) Successful in 8m13s
2026-10-05 13:48:56 +00:00
sharang 04d0ad5113 feat(sbom): direct dependencies of Gradle builds without a lockfile (#446)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m12s
CI / Deploy Dashboard (push) Successful in 5m44s
CI / Deploy MCP (push) Successful in 3m50s
CI / Deploy Agent (push) Canceled after 0s
2026-10-05 13:39:02 +00:00
sharang a9ca31d60c feat(sast): Android and iOS app analysis with mobsfscan (#442)
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Canceled after 0s
CI / Deploy Docs (push) Canceled after 0s
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Agent (push) Successful in 9m28s
2026-10-05 13:38:45 +00:00
sharang 82736a1eec feat(findings): a scan closes what it no longer finds and reopens what returns (#443)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m14s
CI / Deploy Dashboard (push) Successful in 6m40s
CI / Deploy Agent (push) Successful in 8m37s
CI / Deploy MCP (push) Successful in 3m12s
2026-10-05 13:16:35 +00:00
sharangandClaude Opus 5.5 a66b7a5991 fix(sast): run only our own semgrep rules, no registry rules or metrics (#441)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Docs (push) Successful in 1m11s
CI / Deploy Agent (push) Successful in 4m35s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-10-05 13:03:43 +00:00
sharangandClaude Opus 5.5 260d07c783 feat(agent): managed git source — auto targets and CRA issues (#439) (#444)
CI / Deploy Docs (push) Successful in 1m12s
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy MCP (push) Successful in 4m22s
CI / Deploy Dashboard (push) Successful in 6m15s
CI / Deploy Agent (push) Successful in 7m42s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-10-05 10:39:19 +00:00
sharang 9b85d5148e fix(sbom): no clean-looking result for mobile apps without readable lockfiles (#440)
CI / Detect Changes (push) Successful in 3s
CI / Deploy MCP (push) Skipped
CI / Check (push) Skipped
CI / Deploy Docs (push) Successful in 1m15s
CI / Deploy Dashboard (push) Successful in 6m20s
CI / Deploy Agent (push) Successful in 7m53s
2026-10-01 18:45:27 +00:00
sharangandClaude Opus 5.5 5429ff6f0e fix(auth): enforce tenant org roles; crates at 0.4.4 (#431)
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Successful in 1m11s
CI / Deploy MCP (push) Successful in 4m19s
CI / Deploy Dashboard (push) Successful in 6m7s
CI / Deploy Agent (push) Successful in 7m27s
CI / Check (push) Skipped
Every member of a tenant could use Prüfwerk fully, whatever their org
role: nothing but manual findings checked org_roles. A FINANCE user
could create and delete targets, start scans and triage findings.

Now, as decided on 30.09.2026:
- IT_ADMIN, USER: read and write.
- CXO, LEGAL: read only. GET/HEAD/OPTIONS plus the POSTs that only
  read (OSCAL assess, pentest report export, code chat, help chat).
- FINANCE or no role: no access.

- Agent: one middleware (api::role_gate) right after the JWT one
  refuses with 403 {"error":"forbidden_role","access":...}. It is
  classified by route template, so ids do not matter. Support sessions
  (TenantContext.staff) and requests without a tenant context
  (platform service API, Werkbank runner and admin APIs, health) are
  unchanged. Manual findings stay IT_ADMIN-only.
- Core: ProductAccess and TenantContext::product_access.
- Dashboard: a role without access sees a "no access" page (DE/EN)
  with a link back to the portal, and no server function runs for it.
  Read-only roles get a read-only note, and write actions (add target,
  scan, edit, delete, triage, tokens, MCP servers, pentest control,
  graph/embedding builds, notification dismiss) are hidden. The direct
  MCP server functions check the role, and access tokens are withheld
  from read-only roles.
- MCP server: unchanged. Its tokens are tenant-bound and carry no
  roles, its tools only read, and creating a token now needs write
  access.
- Docs: the roles table in Getting Started.
- The crates are at version 0.4.4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-09-30 21:59:07 +00:00
sharangandClaude Opus 5.5 77164c2050 fix: self-host fonts (no Google Fonts request) and crates at 0.4.3 (#430)
CI / Detect Changes (push) Successful in 6s
CI / Deploy Dashboard (push) Successful in 12m37s
CI / Check (push) Skipped
CI / Deploy Docs (push) Successful in 1m29s
CI / Deploy Agent (push) Successful in 9m53s
CI / Deploy MCP (push) Successful in 4m46s
The dashboard, the docs site and the pentest report no longer load
Google Fonts, so no visitor's IP goes to Google (platform/portal#65,
privacy release gate 4).

- Dashboard: Geist and Geist Mono (variable woff2, SIL OFL 1.1) are
  embedded and served at /fonts/geist.woff2 and /fonts/geist-mono.woff2;
  main.css declares them with @font-face under the same family names.
- Docs: the same woff2 files are bundled by Vite from the theme; the
  Google Fonts links in config.mts are gone.
- Pentest report: preconnects and the Google Fonts stylesheet removed;
  a system font stack instead, with a test that the report references
  no external resource.
- The crates are at version 0.4.3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-09-30 20:48:02 +00:00
264 changed files with 17822 additions and 1315 deletions

No files matched your search

+10
View File
@@ -38,7 +38,17 @@ WEBHOOK_PORT=3002
SCAN_CONCURRENCY=2
SCAN_SCHEDULE=0 0 */6 * * *
CVE_MONITOR_SCHEDULE=0 0 0 * * *
# Managed git sources (#439): hosts a tenant's Gitea may be on (anchored regex),
# minutes between syncs of the org's repositories, and the public origin of the
# webhook server for the webhook URL the platform API returns.
# GIT_SOURCE_HOST_PATTERN=^[a-z0-9-]+\.code(-stage)?\.breakpilot\.com$
# GIT_SOURCE_SYNC_MINUTES=30
# WEBHOOK_PUBLIC_URL=https://pruefwerk-hooks.example.com
GIT_CLONE_BASE_PATH=/tmp/compliance-scanner/repos
# NuGet licenses (#467): look up licenses the tree's .nuspec files do not give
# on api.nuget.org (package id and version only; never for ids a nuget.config
# routes to another feed). Set to false to keep the lookup offline.
NUGET_LICENSE_LOOKUP=true
# Dynamic PLC testing — ephemeral soft-PLC provisioning (#183). Off unless
# enabled; requires the agent container to have Docker access (socket mount).
Generated
+10 -9
View File
@@ -663,7 +663,7 @@ dependencies = [
[[package]]
name = "compliance-agent"
version = "0.4.2"
version = "0.4.4"
dependencies = [
"axum",
"base64",
@@ -701,6 +701,7 @@ dependencies = [
"tokio-cron-scheduler",
"tokio-stream",
"tokio-tungstenite 0.26.2",
"toml",
"tower",
"tower-http",
"tracing",
@@ -714,7 +715,7 @@ dependencies = [
[[package]]
name = "compliance-core"
version = "0.4.2"
version = "0.4.4"
dependencies = [
"aes-gcm",
"axum",
@@ -744,7 +745,7 @@ dependencies = [
[[package]]
name = "compliance-dashboard"
version = "0.4.2"
version = "0.4.4"
dependencies = [
"async-trait",
"axum",
@@ -784,7 +785,7 @@ dependencies = [
[[package]]
name = "compliance-dast"
version = "0.4.2"
version = "0.4.4"
dependencies = [
"base64",
"bollard",
@@ -810,7 +811,7 @@ dependencies = [
[[package]]
name = "compliance-graph"
version = "0.4.2"
version = "0.4.4"
dependencies = [
"bson",
"chrono",
@@ -834,7 +835,7 @@ dependencies = [
[[package]]
name = "compliance-mcp"
version = "0.4.2"
version = "0.4.4"
dependencies = [
"axum",
"bson",
@@ -858,7 +859,7 @@ dependencies = [
[[package]]
name = "compliance-smoke"
version = "0.4.2"
version = "0.4.4"
dependencies = [
"axum",
"compliance-core",
@@ -985,7 +986,7 @@ dependencies = [
[[package]]
name = "control-map"
version = "0.4.2"
version = "0.4.4"
dependencies = [
"serde",
"serde_json",
@@ -6793,7 +6794,7 @@ dependencies = [
[[package]]
name = "werkbank-exec"
version = "0.4.2"
version = "0.4.4"
dependencies = [
"compliance-core",
"compliance-dast",
+16 -1
View File
@@ -9,6 +9,9 @@ ARG GITLEAKS_VERSION=8.21.2
ARG GITLEAKS_SHA256=5bc41815076e6ed6ef8fbecc9d9b75bcae31f39029ceb55da08086315316e3ba
ARG SEMGREP_VERSION=1.177.0
ARG RUFF_VERSION=0.16.8
# mobsfscan pins an older semgrep; it is installed without its dependencies so
# it runs on the semgrep above, and its other dependencies are pinned here.
ARG MOBSFSCAN_VERSION=1.0.1
FROM rust:1.94-bookworm AS builder
@@ -42,6 +45,7 @@ ARG GITLEAKS_VERSION
ARG GITLEAKS_SHA256
ARG SEMGREP_VERSION
ARG RUFF_VERSION
ARG MOBSFSCAN_VERSION
# No recommended packages: python3-pip would otherwise pull in a full C
# toolchain, which nothing at runtime needs.
@@ -74,10 +78,21 @@ RUN curl -sSfL -o /tmp/gitleaks.tar.gz \
RUN pip3 install --break-system-packages --no-cache-dir \
"semgrep==${SEMGREP_VERSION}" "ruff==${RUFF_VERSION}"
# Mobile app SAST (LGPL-3.0). The wrapper clears its substring path ignores;
# see compliance-agent/src/pipeline/mobsfscan.rs.
RUN pip3 install --break-system-packages --no-cache-dir --no-deps \
"mobsfscan==${MOBSFSCAN_VERSION}" \
&& pip3 install --break-system-packages --no-cache-dir \
"libsast==3.1.8" "billiard==4.3.0" "pyyaml==6.0.3" "colorama==0.4.6" \
"sarif-om==1.0.4" "jschema-to-python==1.2.3" "jsonpickle==4.1.2" "pbr==7.0.3" \
"tabulate==0.10.0" "xmltodict==1.0.4"
COPY docker/pruefwerk_mobsfscan.py /opt/pruefwerk/pruefwerk_mobsfscan.py
RUN mkdir -p /opt/pruefwerk \
&& printf '{"rust":"%s","cargo-audit":"%s","syft":"%s","gitleaks":"%s","semgrep":"%s","ruff":"%s","cppcheck":"%s"}\n' \
&& printf '{"rust":"%s","cargo-audit":"%s","syft":"%s","gitleaks":"%s","semgrep":"%s","ruff":"%s","cppcheck":"%s","mobsfscan":"%s"}\n' \
"${RUST_VERSION}" "${CARGO_AUDIT_VERSION}" "${SYFT_VERSION}" "${GITLEAKS_VERSION}" \
"${SEMGREP_VERSION}" "${RUFF_VERSION}" "$(cppcheck --version | cut -d' ' -f2)" \
"${MOBSFSCAN_VERSION}" \
> /opt/pruefwerk/tool-versions.json
# The agent runs unprivileged. It writes only to its home (tool caches), the
+1 -1
View File
@@ -36,7 +36,7 @@ Compliance Scanner is an autonomous agent that continuously monitors git reposit
| Area | Capabilities |
|------|-------------|
| **SAST Scanning** | Semgrep-based static analysis with auto-config rules |
| **SAST Scanning** | Semgrep engine with our own CRA rules (no registry rules), cppcheck for C/C++, mobsfscan for Android and iOS apps |
| **SBOM Generation** | Syft + cargo-audit for complete dependency inventory |
| **CVE Monitoring** | OSV.dev batch queries, NVD CVSS enrichment, SearXNG context |
| **GDPR Patterns** | Detect PII logging, missing consent, hardcoded retention, missing deletion |
+3 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-agent"
version = "0.4.2"
version = "0.4.4"
edition = "2021"
[lints]
@@ -51,6 +51,8 @@ hmac = "0.12"
# Constant-time comparison of the GitLab webhook token.
subtle = "2.6"
walkdir = "2"
# Gradle version catalogs (libs.versions.toml) in mobile and JVM projects.
toml = "0.8"
# Read-only XML tree parsing for PLCopen project files (POU extraction).
roxmltree = "0.20"
base64 = "0.22"
+21
View File
@@ -0,0 +1,21 @@
const { exec } = require("child_process");
const express = require("express");
const app = express();
app.get("/orders/export", (req, res) => {
// ruleid: cra-ai-20-node-shell-command
exec("/usr/local/bin/export-orders --customer " + req.query.customer, (err, stdout) => {
// ruleid: cra-ai-20-node-reflected-input
res.send("<p>Exported for " + req.query.customer + "</p>" + stdout);
});
// ok: cra-ai-20-node-shell-command
exec("uptime", () => {});
// ok: cra-ai-20-node-reflected-input
res.send("<p>" + encodeURIComponent(req.query.customer) + "</p>");
// ok: cra-ai-20-node-shell-command
/a(b)/.exec(req.query.customer);
// ruleid: cra-ai-15-node-cleartext-http
fetch("http://api.example.com/orders");
// ok: cra-ai-15-node-cleartext-http
fetch("https://api.example.com/orders");
});
+57
View File
@@ -0,0 +1,57 @@
import os
import subprocess
import requests
# ruleid: cra-ai-20-python-shell-command
os.system("ping -c 1 " + host)
# ok: cra-ai-20-python-shell-command
os.system("uptime")
# ruleid: cra-ai-20-python-shell-command
subprocess.call("rotate-key --id " + key_id, shell=True)
# ok: cra-ai-20-python-shell-command
subprocess.call("rotate-key --all", shell=True)
# ok: cra-ai-20-python-shell-command
subprocess.call(["rotate-key", "--id", key_id])
# ruleid: cra-ai-20-python-sql-string
cur.execute("SELECT * FROM users WHERE id = " + user_id)
# ruleid: cra-ai-20-python-sql-string
cur.execute(f"SELECT * FROM users WHERE id = {user_id}")
# ruleid: cra-ai-20-python-sql-string
cur.execute("SELECT * FROM users WHERE id = %s" % user_id)
# ok: cra-ai-20-python-sql-string
cur.execute("SELECT * FROM users WHERE id = %s", (user_id,))
# ok: cra-ai-20-python-sql-string
cur.execute("SELECT 1")
# ruleid: cra-ai-8-python-hardcoded-credential
ADMIN_PASSWORD = "admin123"
# ruleid: cra-ai-8-python-hardcoded-credential
API_KEY = "sk_live_51HxYzABCDEFghijklmnopqrstuvwxyz0123456789"
# ok: cra-ai-8-python-hardcoded-credential
ADMIN_PASSWORD = os.environ["ADMIN_PASSWORD"]
# ok: cra-ai-8-python-hardcoded-credential
PASSWORD_FIELD = "password"
# ok: cra-ai-8-python-hardcoded-credential
password = ""
# ok: cra-ai-8-python-hardcoded-credential
password = "changeme"
# ruleid: cra-ai-15-python-cleartext-http
requests.get("http://api.internal.example/" + path)
# ok: cra-ai-15-python-cleartext-http
requests.get("https://api.internal.example/" + path)
# ok: cra-ai-15-python-cleartext-http
requests.get("http://localhost:8080/health")
import pickle
import yaml
# ruleid: cra-ai-20-python-unsafe-deserialization
config = yaml.load(request.data)
# ok: cra-ai-20-python-unsafe-deserialization
config = yaml.load(request.data, Loader=yaml.SafeLoader)
# ok: cra-ai-20-python-unsafe-deserialization
config = yaml.safe_load(request.data)
# ruleid: cra-ai-20-python-unsafe-deserialization
session = pickle.loads(request.cookies["session"])
+162 -1
View File
@@ -1,4 +1,5 @@
# Custom semgrep rules for CRA controls that no off-the-shelf ruleset digs out.
# Prüfwerk's own semgrep rules, the only ones it runs: the Semgrep registry rules
# are licensed for internal use only, not for a service offered to others.
# Each rule id is `cra-ai-<n>-<slug>` and is keyed back to its control via the
# `control-map` LUT (by rule-id suffix, so semgrep's path prefix on check_id does
# not matter). Detection here is deterministic; the grounded LLM judge downstream
@@ -116,6 +117,166 @@ rules:
- pattern: 'crypto.createCipheriv("des", ...)'
- pattern: 'crypto.createCipher(...)'
# --- Python and JavaScript/TypeScript: injection, credentials, transport -------
# A constant string never matches; the reflected-input rule follows Express
# request input (`req.query`, `req.params`, `req.body`) into the response.
# Annotated cases: cra_semgrep.py / cra_semgrep.js, run with
# `semgrep --test compliance-agent/rules`.
- id: cra-ai-20-python-shell-command
languages: [python]
severity: ERROR
message: A shell command is built from a variable, so whoever controls it can run any command (CWE-78). Pass an argument list without shell=True, or validate the value against an allowlist.
metadata:
cwe: ["CWE-78: Improper Neutralization of Special Elements used in an OS Command"]
control: cra-ai-20
patterns:
- pattern-either:
- pattern: os.system($CMD)
- pattern: os.popen($CMD, ...)
- pattern: subprocess.$F($CMD, ..., shell=True, ...)
- metavariable-pattern:
metavariable: $CMD
patterns:
- pattern-not: '"..."'
- id: cra-ai-20-python-sql-string
languages: [python]
severity: ERROR
message: An SQL statement is assembled from a variable, so its value can change the query (SQL injection, CWE-89). Pass values as query parameters (cursor.execute(sql, params)).
metadata:
cwe: ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command"]
control: cra-ai-20
patterns:
- pattern-either:
- pattern: $CUR.execute("..." + $X, ...)
- pattern: $CUR.execute("..." % $X, ...)
- pattern: $CUR.execute(f"...", ...)
- pattern: $CUR.execute("...".format(...), ...)
- pattern: $CUR.executemany("..." + $X, ...)
- pattern-not: $CUR.execute(f"{$C}", ...)
- id: cra-ai-20-python-unsafe-deserialization
languages: [python]
severity: ERROR
message: Data is deserialised with a loader that can build arbitrary objects, so crafted input runs code (CWE-502). Use yaml.safe_load, or JSON for data from outside.
metadata:
cwe: ["CWE-502: Deserialization of Untrusted Data"]
control: cra-ai-20
pattern-either:
- pattern: pickle.loads(...)
- pattern: pickle.load(...)
- pattern: cPickle.loads(...)
- pattern: marshal.loads(...)
- patterns:
- pattern: yaml.load(...)
- pattern-not: yaml.load(..., Loader=yaml.SafeLoader, ...)
- pattern-not: yaml.load(..., Loader=yaml.CSafeLoader, ...)
- pattern-not: yaml.load(..., Loader=SafeLoader, ...)
- pattern: yaml.unsafe_load(...)
- id: cra-ai-20-node-shell-command
languages: [javascript, typescript]
severity: ERROR
message: A shell command is built from a variable, so whoever controls it can run any command (CWE-78). Use execFile/spawn with an argument list, or validate the value against an allowlist.
metadata:
cwe: ["CWE-78: Improper Neutralization of Special Elements used in an OS Command"]
control: cra-ai-20
patterns:
- pattern-either:
- pattern: exec($CMD, ...)
- pattern: execSync($CMD, ...)
- pattern: $CP.exec($CMD, ...)
- pattern: $CP.execSync($CMD, ...)
- pattern-not: exec("...", ...)
- pattern-not: execSync("...", ...)
- pattern-not: $CP.exec("...", ...)
- pattern-not: $CP.execSync("...", ...)
- pattern-not: $CP.exec(`...`, ...)
- pattern-inside: |
$REQ = require("child_process")
...
- pattern-not: $RE.exec($X)
- id: cra-ai-20-node-reflected-input
languages: [javascript, typescript]
severity: WARNING
message: Request input is written into the response without encoding, so a crafted link runs script in the user's browser (reflected XSS, CWE-79). Encode it, or use a template engine that escapes by default.
metadata:
cwe: ["CWE-79: Improper Neutralization of Input During Web Page Generation"]
control: cra-ai-20
mode: taint
pattern-sources:
- pattern-either:
- pattern: $REQ.query
- pattern: $REQ.params
- pattern: $REQ.body
pattern-sinks:
- pattern-either:
- pattern: $RES.send(...)
- pattern: $RES.write(...)
pattern-sanitizers:
- pattern-either:
- pattern: encodeURIComponent(...)
- pattern: escape(...)
- pattern: escapeHtml(...)
- pattern: parseInt(...)
- pattern: Number(...)
- id: cra-ai-8-python-hardcoded-credential
languages: [python]
severity: ERROR
message: $NAME holds a credential written into the code, so every installation ships the same secret (CWE-798). Read it from the environment or a secret store.
metadata:
cwe: ["CWE-798: Use of Hard-coded Credentials"]
control: cra-ai-8
patterns:
- pattern-either:
- pattern: $NAME = "$VALUE"
- pattern: $OBJ.$NAME = "$VALUE"
- metavariable-regex:
metavariable: $NAME
regex: (?i)^[a-z_]*(password|passwd|pwd|secret|api_?key|access_?key|token|credential)s?$
- metavariable-regex:
metavariable: $VALUE
regex: ^(?!(?i:changeme|change-me|xxx+|\*+|todo|example|placeholder|dummy|test)$).{4,}$
- id: cra-ai-15-python-cleartext-http
languages: [python]
severity: WARNING
message: A request goes over plain http://, so it can be read and altered in transit (CWE-319). Use https:// with certificate checking.
metadata:
cwe: ["CWE-319: Cleartext Transmission of Sensitive Information"]
control: cra-ai-15
patterns:
- pattern-either:
- pattern: requests.$M("$URL", ...)
- pattern: requests.$M("$URL" + $X, ...)
- pattern: urllib.request.urlopen("$URL", ...)
- pattern: httpx.$M("$URL", ...)
- pattern: httpx.$M("$URL" + $X, ...)
- metavariable-regex:
metavariable: $URL
regex: ^http://(?!(localhost|127\.|0\.0\.0\.0|\[::1\]))
- id: cra-ai-15-node-cleartext-http
languages: [javascript, typescript]
severity: WARNING
message: A request goes over plain http://, so it can be read and altered in transit (CWE-319). Use https:// with certificate checking.
metadata:
cwe: ["CWE-319: Cleartext Transmission of Sensitive Information"]
control: cra-ai-15
patterns:
- pattern-either:
- pattern: fetch("$URL", ...)
- pattern: fetch("$URL" + $X, ...)
- pattern: axios.$M("$URL", ...)
- pattern: axios.$M("$URL" + $X, ...)
- pattern: http.get("$URL", ...)
- pattern: http.request("$URL", ...)
- metavariable-regex:
metavariable: $URL
regex: ^http://(?!(localhost|127\.|0\.0\.0\.0|\[::1\]))
# --- C/C++ firmware ------------------------------------------------------------
# C and C++ sources alike (`languages: [c, cpp]`), with the `std::` spellings.
# Microcontroller code: unbounded string handling, non-literal format strings,
@@ -0,0 +1,258 @@
// Test cases for cra_semgrep_csharp.yaml: `semgrep --test compliance-agent/rules`.
// Each `ruleid:` line must be found by that rule; each `ok:` line must not.
using System;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Web;
using System.Web.UI;
using System.Xml;
using Newtonsoft.Json;
namespace Plant.Tests
{
public class SqlCases
{
public void Run(SqlConnection conn, string id, PlantContext db)
{
// ruleid: cra-ai-20-csharp-sql-string
var cmd = new SqlCommand("SELECT * FROM Orders WHERE Id = " + id, conn);
// ruleid: cra-ai-20-csharp-sql-string
var cmd2 = new SqlCommand($"DELETE FROM Orders WHERE Id = {id}", conn);
string sql = "SELECT * FROM Users WHERE Name = '" + id + "'";
// ruleid: cra-ai-20-csharp-sql-string
var cmd3 = new SqlCommand(sql, conn);
var sql2 = "SELECT * FROM Lines WHERE Code = '" + id + "'";
// ruleid: cra-ai-20-csharp-sql-string
var cmd4 = new SqlCommand(sql2, conn);
// ruleid: cra-ai-20-csharp-sql-string
cmd.CommandText = String.Format("UPDATE Orders SET State = {0}", id);
// ruleid: cra-ai-20-csharp-sql-string
db.Database.ExecuteSqlCommand("DELETE FROM Log WHERE Day < " + id);
// ruleid: cra-ai-20-csharp-sql-string
var rows = db.Orders.FromSqlRaw($"SELECT * FROM Orders WHERE Id = {id}");
// ok: cra-ai-20-csharp-sql-string
var safe = new SqlCommand("SELECT * FROM Orders WHERE Id = @id", conn);
safe.Parameters.AddWithValue("@id", id);
// ok: cra-ai-20-csharp-sql-string
var constant = new SqlCommand("SELECT * FROM Orders " + "ORDER BY Id", conn);
// ok: cra-ai-20-csharp-sql-string
var interpolated = db.Orders.FromSqlInterpolated($"SELECT * FROM Orders WHERE Id = {id}");
}
}
public class ProcessCases
{
public void Run(string host, string path)
{
// ruleid: cra-ai-20-csharp-process-start
Process.Start("cmd.exe", "/c ping " + host);
var psi = new ProcessStartInfo("tool.exe");
// ruleid: cra-ai-20-csharp-process-start
psi.Arguments = $"--target {host}";
// ok: cra-ai-20-csharp-process-start
Process.Start("notepad.exe");
// ok: cra-ai-20-csharp-process-start
Process.Start(path);
var startInfo = new ProcessStartInfo();
// ruleid: cra-ai-20-csharp-process-start
startInfo.FileName = path + "\\tool.exe";
var dialog = new SaveFileDialog();
// ok: cra-ai-20-csharp-process-start
dialog.FileName = path + ".csv";
}
}
public class DeserializationCases
{
public object Run(Stream input)
{
// ruleid: cra-ai-20-csharp-unsafe-deserialization
var formatter = new BinaryFormatter();
// ruleid: cra-ai-20-csharp-unsafe-deserialization
var ndcs = new NetDataContractSerializer();
// ruleid: cra-ai-20-csharp-unsafe-deserialization
var los = new LosFormatter();
// ruleid: cra-ai-20-csharp-unsafe-deserialization
var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
// ok: cra-ai-20-csharp-unsafe-deserialization
var safeSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.None };
// ok: cra-ai-20-csharp-unsafe-deserialization
var dcs = new DataContractSerializer(typeof(Order));
return formatter.Deserialize(input);
}
}
public class XmlCases
{
public void Unsafe(string xml, string file)
{
XmlDocument doc;
doc = new XmlDocument();
// ruleid: cra-ai-20-csharp-xxe
doc.LoadXml(xml);
var doc2 = new XmlDocument();
// ruleid: cra-ai-20-csharp-xxe
doc2.Load(file);
var reader = new XmlTextReader(file);
// ruleid: cra-ai-20-csharp-xxe
while (reader.Read()) { }
var settings = new XmlReaderSettings();
// ruleid: cra-ai-20-csharp-xxe
settings.DtdProcessing = DtdProcessing.Parse;
// ruleid: cra-ai-20-csharp-xxe
settings.XmlResolver = new XmlUrlResolver();
}
public void Safe(string xml)
{
XmlDocument doc;
doc = new XmlDocument();
doc.XmlResolver = null;
// ok: cra-ai-20-csharp-xxe
doc.LoadXml(xml);
var doc2 = new XmlDocument();
doc2.XmlResolver = null;
// ok: cra-ai-20-csharp-xxe
doc2.LoadXml(xml);
var doc3 = new XmlDocument { XmlResolver = null };
// ok: cra-ai-20-csharp-xxe
doc3.LoadXml(xml);
var reader = new XmlTextReader(xml);
reader.DtdProcessing = DtdProcessing.Prohibit;
// ok: cra-ai-20-csharp-xxe
while (reader.Read()) { }
var settings = new XmlReaderSettings();
// ok: cra-ai-20-csharp-xxe
settings.DtdProcessing = DtdProcessing.Prohibit;
}
}
public class FileController
{
public HttpRequest Request;
public byte[] Download()
{
// ruleid: cra-ai-20-csharp-path-traversal
var path = Path.Combine(@"C:\Plant\Reports", Request.QueryString["file"]);
// ruleid: cra-ai-20-csharp-path-traversal
var text = File.ReadAllText(@"C:\Plant\Logs\" + Request["name"]);
// ok: cra-ai-20-csharp-path-traversal
var safe = Path.Combine(@"C:\Plant\Reports", Path.GetFileName(Request.QueryString["file"]));
return File.ReadAllBytes(safe);
}
}
public class CryptoCases
{
public void Run(byte[] data)
{
// ruleid: cra-ai-13-csharp-broken-hash-or-cipher
var md5 = MD5.Create();
// ruleid: cra-ai-13-csharp-broken-hash-or-cipher
var sha1 = new SHA1CryptoServiceProvider();
// ruleid: cra-ai-13-csharp-broken-hash-or-cipher
var des = new DESCryptoServiceProvider();
// ruleid: cra-ai-13-csharp-broken-hash-or-cipher
var tdes = TripleDES.Create();
// ok: cra-ai-13-csharp-broken-hash-or-cipher
var sha256 = SHA256.Create();
var aes = Aes.Create();
// ruleid: cra-ai-13-csharp-ecb-mode
aes.Mode = CipherMode.ECB;
// ok: cra-ai-13-csharp-ecb-mode
aes.Mode = CipherMode.CBC;
}
}
public class TlsCases
{
public void Run()
{
// ruleid: cra-ai-15-csharp-cert-validation-disabled
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, errors) => true;
// ruleid: cra-ai-15-csharp-cert-validation-disabled
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
var handler = new HttpClientHandler();
// ruleid: cra-ai-15-csharp-cert-validation-disabled
handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
// ok: cra-ai-15-csharp-cert-validation-disabled
handler.ServerCertificateCustomValidationCallback = (msg, cert, chain, errors) => errors == System.Net.Security.SslPolicyErrors.None;
}
}
public class CredentialCases
{
// ruleid: cra-ai-8-csharp-hardcoded-credential
private const string DbPassword = "Plant#2019!";
// ruleid: cra-ai-8-csharp-hardcoded-credential
private static readonly string ApiSecret = "sk_live_51HxQ2a";
// ok: cra-ai-8-csharp-hardcoded-credential
private const string PasswordLabel = "Enter your password";
// ok: cra-ai-8-csharp-hardcoded-credential
private const string AdminPassword = "changeme";
public void Run(Config config)
{
// ruleid: cra-ai-8-csharp-hardcoded-credential
config.SmtpPassword = "mail-pa55word";
// ruleid: cra-ai-8-csharp-hardcoded-credential
var plcPassword = "Siemens#S7-1500";
// ok: cra-ai-8-csharp-hardcoded-credential
config.SmtpPassword = "";
// ok: cra-ai-8-csharp-hardcoded-credential
config.UserName = "operator1";
}
}
}
@@ -0,0 +1,266 @@
# Prüfwerk's own semgrep rules for C# (.NET Framework and .NET), #445. Written
# for Prüfwerk, not adapted from any third-party rule set (the Semgrep registry
# rules may not be used for a service offered to others).
# Same conventions as cra_semgrep.yaml: each rule id is `cra-ai-<n>-<slug>`,
# keyed back to its control via the `control-map` LUT, with its CWE and
# control in the metadata. Keep patterns tight: a false positive that the
# judge refutes marks the whole finding a false positive.
# Test cases: cra_semgrep_csharp.cs (`semgrep --test compliance-agent/rules`).
rules:
# --- cra-ai-20: injection and unsafe input handling --------------------------
- id: cra-ai-20-csharp-sql-string
languages: [csharp]
severity: ERROR
message: SQL text is built from strings (concatenation, interpolation or String.Format) and run as a command — SQL injection (CWE-89). Pass the values as parameters (SqlParameter, AddWithValue, FromSqlInterpolated).
metadata:
cwe: ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"]
control: cra-ai-20
pattern-either:
# The SQL text is built right in the call.
- patterns:
- pattern-either: &sql-sinks
- patterns:
- pattern-either:
- pattern: new $CMD($Q, ...)
- pattern: new $CMD($Q)
- metavariable-regex:
metavariable: $CMD
regex: ^(SqlCommand|OleDbCommand|OdbcCommand|OracleCommand|MySqlCommand|NpgsqlCommand|SQLiteCommand|SqliteCommand|SqlDataAdapter|OleDbDataAdapter)$
- pattern: $X.CommandText = $Q
- pattern: $X.ExecuteSqlCommand($Q, ...)
- pattern: $X.ExecuteSqlRaw($Q, ...)
- pattern: $X.ExecuteSqlRawAsync($Q, ...)
- pattern: $X.FromSqlRaw($Q, ...)
- pattern: $X.SqlQuery($Q, ...)
- pattern: $X.SqlQuery<$T>($Q, ...)
- metavariable-pattern:
metavariable: $Q
patterns: &built-string
- pattern-either:
- pattern: '"..." + $E'
- pattern: $E + "..."
- pattern: String.Format(...)
- pattern: string.Format(...)
- pattern-regex: (?s)^(\$@?|@\$)".*\{
- pattern-not: '"..." + "..."'
# The SQL text is built into a variable first.
- patterns:
- pattern-either:
- pattern-inside: |
$TY $Q = $INIT;
...
- pattern-inside: |
var $Q = $INIT;
...
- pattern-inside: |
$Q = $INIT;
...
- pattern-either: *sql-sinks
- metavariable-pattern:
metavariable: $INIT
patterns: *built-string
- id: cra-ai-20-csharp-process-start
languages: [csharp]
severity: WARNING
message: A process is started with a command line built from strings — command injection if any part comes from outside (CWE-78). Start a fixed program with an argument list (ProcessStartInfo.ArgumentList) and validate the values.
metadata:
cwe: ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"]
control: cra-ai-20
patterns:
- pattern-either:
- pattern: Process.Start($ARG, ...)
- pattern: Process.Start($FILE, $ARG, ...)
- pattern: new ProcessStartInfo($ARG, ...)
- pattern: new ProcessStartInfo($FILE, $ARG, ...)
- pattern: $P.Arguments = $ARG
# Only a ProcessStartInfo's: a file dialog's FileName is no command.
- patterns:
- pattern-either:
- pattern-inside: |
$PT $P = new ProcessStartInfo(...);
...
- pattern-inside: |
var $P = new ProcessStartInfo(...);
...
- pattern-inside: |
$P = new ProcessStartInfo(...);
...
- pattern: $P.FileName = $ARG
- metavariable-pattern:
metavariable: $ARG
patterns:
- pattern-either:
- pattern: '"..." + $E'
- pattern: $E + "..."
- pattern: String.Format(...)
- pattern: string.Format(...)
- pattern: String.Concat(...)
- pattern-regex: (?s)^(\$@?|@\$)".*\{
- pattern-not: '"..." + "..."'
- id: cra-ai-20-csharp-unsafe-deserialization
languages: [csharp]
severity: ERROR
message: $TYPE deserializes type information from its input, so data from outside can run code (CWE-502). Use a serializer bound to known types (System.Text.Json, DataContractSerializer, JSON.NET with TypeNameHandling.None).
metadata:
cwe: ["CWE-502: Deserialization of Untrusted Data"]
control: cra-ai-20
pattern-either:
- patterns:
- pattern: new $TYPE(...)
- metavariable-regex:
metavariable: $TYPE
regex: ^(BinaryFormatter|NetDataContractSerializer|LosFormatter|SoapFormatter|ObjectStateFormatter)$
- patterns:
- pattern: TypeNameHandling.$TYPE
- metavariable-regex:
metavariable: $TYPE
regex: ^(All|Auto|Objects|Arrays)$
- id: cra-ai-20-csharp-xxe
languages: [csharp]
severity: WARNING
message: XML is parsed with DTD processing or an external resolver enabled — external entities can read local files or reach internal hosts (XXE, CWE-611). Set XmlResolver = null and DtdProcessing = DtdProcessing.Prohibit (the default only from .NET Framework 4.5.2 on).
metadata:
cwe: ["CWE-611: Improper Restriction of XML External Entity Reference"]
control: cra-ai-20
pattern-either:
- pattern: $X.XmlResolver = new XmlUrlResolver(...)
- pattern: $X.DtdProcessing = DtdProcessing.Parse
- pattern: $X.ProhibitDtd = false
- patterns:
- pattern-either:
- pattern-inside: |
$D = new XmlDocument();
...
- pattern-inside: |
$DT $D = new XmlDocument();
...
- pattern-inside: |
var $D = new XmlDocument();
...
- pattern-inside: |
$D = new XmlTextReader(...);
...
- pattern-inside: |
$DT $D = new XmlTextReader(...);
...
- pattern-inside: |
var $D = new XmlTextReader(...);
...
- pattern-not-inside: |
$D.XmlResolver = null;
...
- pattern-not-inside: |
$D.DtdProcessing = DtdProcessing.Prohibit;
...
- pattern-not-inside: |
var $D = new $T { ..., XmlResolver = null, ... };
...
- pattern-not-inside: |
$DT $D = new $T { ..., XmlResolver = null, ... };
...
- pattern-either:
- pattern: $D.Load(...)
- pattern: $D.LoadXml(...)
- pattern: $D.Read()
- id: cra-ai-20-csharp-path-traversal
languages: [csharp]
severity: WARNING
message: A file path is built from request input — "..\" in it reaches files outside the intended folder (path traversal, CWE-22). Take only the file name (Path.GetFileName) and check the full path stays under the base folder.
metadata:
cwe: ["CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')"]
control: cra-ai-20
patterns:
- pattern-either:
- pattern: File.$M(..., <... Request.$P ...>, ...)
- pattern: File.$M(..., <... Request[$K] ...>, ...)
- pattern: Path.Combine(..., <... Request.$P ...>, ...)
- pattern: Path.Combine(..., <... Request[$K] ...>, ...)
- pattern: new FileStream(<... Request.$P ...>, ...)
- pattern: new FileStream(<... Request[$K] ...>, ...)
- pattern-not: File.$M(..., <... Path.GetFileName(...) ...>, ...)
- pattern-not: Path.Combine(..., <... Path.GetFileName(...) ...>, ...)
# --- cra-ai-13: Verschlüsselung sensibler Daten ------------------------------
- id: cra-ai-13-csharp-broken-hash-or-cipher
languages: [csharp]
severity: WARNING
message: $ALG is a broken algorithm (MD5, SHA-1, DES, 3DES or RC2) that protects neither integrity nor confidentiality (CWE-327). Use SHA-256 or better, and AES-GCM.
metadata:
cwe: ["CWE-327: Use of a Broken or Risky Cryptographic Algorithm"]
control: cra-ai-13
pattern-either:
- patterns:
- pattern: $ALG.Create(...)
- metavariable-regex:
metavariable: $ALG
regex: ^(MD5|SHA1|DES|TripleDES|RC2)$
- patterns:
- pattern: new $ALG(...)
- metavariable-regex:
metavariable: $ALG
regex: ^(MD5CryptoServiceProvider|MD5Cng|SHA1CryptoServiceProvider|SHA1Managed|SHA1Cng|DESCryptoServiceProvider|TripleDESCryptoServiceProvider|TripleDESCng|RC2CryptoServiceProvider|HMACMD5|HMACSHA1)$
- id: cra-ai-13-csharp-ecb-mode
languages: [csharp]
severity: WARNING
message: ECB mode encrypts equal blocks to equal ciphertext, so the structure of the data shows through (CWE-327). Use AES-GCM, or CBC with a random IV and a MAC.
metadata:
cwe: ["CWE-327: Use of a Broken or Risky Cryptographic Algorithm"]
control: cra-ai-13
pattern: CipherMode.ECB
# --- cra-ai-15: Transport-Schutz ---------------------------------------------
- id: cra-ai-15-csharp-cert-validation-disabled
languages: [csharp]
severity: ERROR
message: TLS certificate validation is switched off (the callback accepts every certificate), so anyone on the network path can read and change the traffic (CWE-295). Remove the callback, or pin the expected certificate.
metadata:
cwe: ["CWE-295: Improper Certificate Validation"]
control: cra-ai-15
pattern-either:
- pattern: HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
- patterns:
- pattern-either:
- pattern: $X.ServerCertificateValidationCallback = $F
- pattern: $X.ServerCertificateValidationCallback += $F
- pattern: $X.ServerCertificateCustomValidationCallback = $F
- pattern: $X.RemoteCertificateValidationCallback = $F
- metavariable-pattern:
metavariable: $F
pattern-either:
- pattern: (...) => true
- pattern: |
delegate { return true; }
- pattern: |
delegate (...) { return true; }
- pattern: |
(...) => { return true; }
# --- cra-ai-8: Keine Default-Passwörter --------------------------------------
- id: cra-ai-8-csharp-hardcoded-credential
languages: [csharp]
severity: ERROR
message: A credential ($NAME) is written into the source — every installation shares it, and it can be read out of the assembly (CWE-798). Load it from protected configuration or a secret store.
metadata:
cwe: ["CWE-798: Use of Hard-coded Credentials"]
control: cra-ai-8
patterns:
- pattern-either:
- pattern: $TYPE $NAME = "$VALUE";
- pattern: var $NAME = "$VALUE";
- pattern: $NAME = "$VALUE"
- pattern: const string $NAME = "$VALUE";
- metavariable-regex:
metavariable: $NAME
regex: (?i)^(.*\.)?\w*(password|passwd|pwd|secret|apikey|api_key|privatekey|private_key|accesskey|access_key|connectionpassword|encryptionkey|aeskey|secretkey|clientsecret)\w*$
- metavariable-regex:
metavariable: $NAME
regex: (?i)^(?!.*(hint|label|prompt|field|name|param|header|policy|length|regex|pattern|format|path|file|url|uri|key(name|id)|placeholder)).*$
# Six characters or more, and not a placeholder left for the installer.
- metavariable-regex:
metavariable: $VALUE
regex: ^(?!(?i:changeme|change_me|password|secret|admin|x{3,}|your_\w*|<[^>]*>|\*+|\{\d+\}|\$\{.*\}|%\w+%)$).{6,}$
+39
View File
@@ -0,0 +1,39 @@
# Prüfwerk's gitleaks configuration: gitleaks' own rules plus the ones below.
# Always passed with --config, so a `.gitleaks.toml` in a scanned repository
# cannot switch rules off.
title = "Prüfwerk"
[extend]
useDefault = true
# Android release signing: a keystore or key password written into a Gradle
# build file signs every build with a secret everyone with the code has.
[[rules]]
id = "android-keystore-password"
description = "Android signing password in a Gradle build file"
regex = '''(?i)\b(?:storePassword|keyPassword)\b\s*(?:=|\()?\s*["']([^"'$\s]{4,})["']'''
path = '''(?i)\.gradle(?:\.kts)?$'''
secretGroup = 1
keywords = ["storepassword", "keypassword"]
# The same, kept in gradle.properties (RELEASE_STORE_PASSWORD=…).
[[rules]]
id = "android-signing-password-property"
description = "Android signing password in gradle.properties"
regex = '''(?im)^\s*[\w.]*(?:store|key|keystore|signing)[\w.]*password\s*[=:]\s*([^\s$]{4,})\s*$'''
path = '''(?i)(?:^|/)gradle\.properties$'''
secretGroup = 1
keywords = ["password"]
# The API key in a Firebase configuration (google-services.json,
# GoogleService-Info.plist). It identifies the app rather than authorising
# anything on its own, but it must be restricted to the app in the Google
# Cloud console; reported at low severity.
[[rules]]
id = "firebase-config-api-key"
description = "Firebase API key in the app's Firebase configuration"
regex = '''(AIza[\w-]{35})'''
path = '''(?i)(?:^|/)(?:google-services\.json|GoogleService-Info\.plist)$'''
secretGroup = 1
keywords = ["aiza"]
+18 -1
View File
@@ -42,6 +42,11 @@ pub struct ComplianceAgent {
/// Seals tenant credentials before they are stored and opens them where
/// they are used (#260).
pub secrets: SecretBox,
/// Managed git sources (#439): allowed hosts, sync interval, webhook origin.
pub git_source: Arc<crate::git_source::Settings>,
/// NuGet licenses looked up on nuget.org, for every tenant (#467): public
/// metadata keyed by package and version, in the admin database.
pub(crate) nuget_license_cache: Arc<crate::pipeline::sbom::MongoLicenseCache>,
}
impl ComplianceAgent {
@@ -61,6 +66,15 @@ impl ComplianceAgent {
let net_guard = NetGuard::from_env(config.app_env);
let scan_gate = Arc::new(ScanGate::new(config.scan_concurrency));
let secrets = SecretBox::from_config(&config);
// `load_config` already refused a malformed value; tests and tools that
// build a config by hand get the defaults.
let git_source = Arc::new(crate::git_source::Settings::from_env().unwrap_or_else(|e| {
tracing::error!("{e}; using the default git source settings");
crate::git_source::Settings::default()
}));
let nuget_license_cache = Arc::new(crate::pipeline::sbom::MongoLicenseCache::new(
&db_pool.admin_db(),
));
Self {
config,
db_pool,
@@ -73,6 +87,8 @@ impl ComplianceAgent {
net_guard,
scan_gate,
secrets,
git_source,
nuget_license_cache,
}
}
@@ -188,7 +204,8 @@ impl ComplianceAgent {
db.clone(),
self.llm.clone(),
self.http.clone(),
);
)
.with_nuget_license_cache(self.nuget_license_cache.clone());
let started = chrono::Utc::now();
orchestrator.run_target(target_id, trigger.clone()).await?;
// Support's scans are ours, not the customer's usage.
+18 -1
View File
@@ -180,6 +180,7 @@ fn status_update(
support: actor.support,
at: chrono::Utc::now(),
reason: reason.map(String::from),
scan: 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)?;
@@ -189,6 +190,20 @@ fn status_update(
})
}
/// The issue sync for status changes in the tenant database `db`: a closed
/// finding closes its issue, a reopened one reopens it.
fn issue_sync(
agent: &crate::agent::ComplianceAgent,
db: crate::database::Database,
) -> crate::pipeline::issue_sync::IssueSync {
crate::pipeline::issue_sync::IssueSync {
db,
config: agent.config.clone(),
secrets: agent.secrets.clone(),
net_guard: agent.net_guard,
}
}
/// PATCH /api/v1/findings/{id}/status — change the status, recording who,
/// when and why. 404 when there is no such finding.
#[tracing::instrument(skip_all, fields(finding_id = %id))]
@@ -210,6 +225,7 @@ pub async fn update_finding_status(
if result.matched_count == 0 {
return Err(StatusCode::NOT_FOUND);
}
issue_sync(&agent, db).spawn(vec![oid]);
Ok(Json(serde_json::json!({ "status": "updated" })))
}
@@ -235,9 +251,10 @@ pub async fn bulk_update_finding_status(
let db = tenant_db(&agent, &tenant).await?;
let result = db
.findings()
.update_many(doc! { "_id": { "$in": oids } }, update)
.update_many(doc! { "_id": { "$in": oids.clone() } }, update)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
issue_sync(&agent, db).spawn(oids);
Ok(Json(
serde_json::json!({ "status": "updated", "modified_count": result.modified_count }),
@@ -0,0 +1,48 @@
//! `GET /api/v1/git-source` — the workspace's managed git source (#439),
//! read-only. The platform configures it (`/api/v1/platform/...`); the
//! organisation's IT administrator and BreakPilot support may look at it.
use axum::http::StatusCode;
use axum::Json;
use compliance_core::models::GitSourceView;
use compliance_core::tenant::OrgRole;
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{tenant_db, AgentExt};
use super::ApiResponse;
/// Whether the caller may see the git source: IT administrators and support.
fn may_view(tenant: &TenantCtx) -> bool {
tenant.0.staff.is_some() || tenant.0.org_roles.contains(&OrgRole::ItAdmin)
}
/// The source without secrets, plus the webhook URL; `data: null` when the
/// workspace has none.
pub async fn get_git_source(
axum::extract::Extension(agent): AgentExt,
tenant: TenantCtx,
) -> Result<Json<ApiResponse<Option<serde_json::Value>>>, StatusCode> {
if !may_view(&tenant) {
return Err(StatusCode::FORBIDDEN);
}
let db = tenant_db(&agent, &tenant).await?;
let source = crate::git_source::load_source(&db)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let data = source.map(|s| {
let mut v = serde_json::to_value(GitSourceView::from(&s)).unwrap_or_default();
if let Some(obj) = v.as_object_mut() {
obj.insert(
"webhook_url".into(),
agent.git_source.webhook_url(&tenant.0.tenant_id).into(),
);
}
v
});
Ok(Json(ApiResponse {
data,
total: None,
page: None,
}))
}
@@ -0,0 +1,241 @@
//! `/api/v1/mcp-servers` — the MCP server cards of the caller's tenant.
//!
//! The dashboard's MCP page lists the servers an LLM client can connect to.
//! The cards live in the tenant's own database, so one tenant never sees or
//! changes another's (#432). Every tenant starts with the three default cards
//! (Findings, SBOM, DAST), created on its first listing. A card's access token
//! is display data (the MCP server authenticates with the tenant's MCP tokens);
//! it is shown only to roles that may change things.
use axum::extract::{Extension, Path, Query};
use axum::http::StatusCode;
use axum::Json;
use chrono::Utc;
use mongodb::bson::{doc, oid::ObjectId};
use compliance_core::models::{McpServerConfig, McpServerStatus, McpTransport};
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{tenant_db, AgentExt};
use crate::database::Database;
/// The default cards: name, description and the tools each exposes.
const DEFAULT_SERVERS: [(&str, &str, &[&str]); 3] = [
(
"Findings MCP",
"Exposes security findings, triage data, and finding summaries to LLM agents",
&["list_findings", "get_finding", "findings_summary"],
),
(
"SBOM MCP",
"Exposes software bill of materials and vulnerability reports to LLM agents",
&["list_sbom_packages", "sbom_vuln_report"],
),
(
"DAST MCP",
"Exposes DAST scan findings and scan summaries to LLM agents",
&["list_dast_findings", "dast_scan_summary"],
),
];
/// Every tool a card created by hand exposes.
const ALL_TOOLS: [&str; 7] = [
"list_findings",
"get_finding",
"findings_summary",
"list_sbom_packages",
"sbom_vuln_report",
"list_dast_findings",
"dast_scan_summary",
];
#[derive(Debug, serde::Deserialize)]
pub struct ListQuery {
/// Where the deployment's MCP server answers (the dashboard's
/// `MCP_ENDPOINT_URL`), for the default cards of a tenant that has none.
#[serde(default)]
pub default_endpoint: Option<String>,
}
#[derive(Debug, serde::Deserialize)]
pub struct CreateRequest {
pub name: String,
pub endpoint_url: String,
#[serde(default)]
pub transport: String,
#[serde(default)]
pub port: Option<u16>,
#[serde(default)]
pub description: Option<String>,
#[serde(default)]
pub mongodb_uri: Option<String>,
#[serde(default)]
pub mongodb_database: Option<String>,
}
/// A fresh display token for a card.
fn new_token() -> String {
format!("mcp_{}", uuid::Uuid::new_v4().simple())
}
/// `value` trimmed, `None` when blank.
fn non_blank(value: Option<String>) -> Option<String> {
value
.map(|v| v.trim().to_string())
.filter(|v| !v.is_empty())
}
/// Create the default cards for a tenant that has no cards yet. `endpoint`
/// must be an http(s) URL; anything else creates nothing.
async fn seed_defaults(db: &Database, endpoint: &str) -> Result<(), mongodb::error::Error> {
let endpoint = endpoint.trim().trim_end_matches('/');
if !(endpoint.starts_with("https://") || endpoint.starts_with("http://")) {
return Ok(());
}
if db.mcp_servers().count_documents(doc! {}).await? > 0 {
return Ok(());
}
let now = Utc::now();
let cards = DEFAULT_SERVERS
.iter()
.map(|(name, description, tools)| McpServerConfig {
id: None,
name: (*name).to_string(),
endpoint_url: format!("{endpoint}/mcp"),
transport: McpTransport::Http,
port: Some(8090),
status: McpServerStatus::Stopped,
access_token: new_token(),
tools_enabled: tools.iter().map(|t| (*t).to_string()).collect(),
description: Some((*description).to_string()),
mongodb_uri: None,
mongodb_database: None,
created_at: now,
updated_at: now,
});
// By name, so two first listings at once do not create them twice.
for card in cards {
let Ok(fields) = mongodb::bson::to_document(&card) else {
continue;
};
db.mcp_servers()
.update_one(doc! { "name": &card.name }, doc! { "$setOnInsert": fields })
.upsert(true)
.await?;
}
Ok(())
}
/// `GET /api/v1/mcp-servers` — the tenant's cards, newest first; the access
/// tokens only for roles that may change things.
#[tracing::instrument(skip_all)]
pub async fn list_mcp_servers(
Extension(agent): AgentExt,
tenant: TenantCtx,
Query(query): Query<ListQuery>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
if let Some(endpoint) = query.default_endpoint.as_deref() {
if let Err(e) = seed_defaults(&db, endpoint).await {
tracing::warn!("could not create the default MCP server cards: {e}");
}
}
let cursor = db
.mcp_servers()
.find(doc! {})
.sort(doc! { "created_at": -1 })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let mut servers: Vec<McpServerConfig> = super::dto::collect_cursor_async(cursor).await;
if !tenant.0.product_access().can_write() {
for server in &mut servers {
server.access_token = String::new();
}
}
Ok(Json(serde_json::json!({ "data": servers })))
}
/// `POST /api/v1/mcp-servers` — add a card to the tenant.
#[tracing::instrument(skip_all)]
pub async fn create_mcp_server(
Extension(agent): AgentExt,
tenant: TenantCtx,
Json(req): Json<CreateRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
if req.name.trim().is_empty() || req.endpoint_url.trim().is_empty() {
return Err(StatusCode::BAD_REQUEST);
}
let db = tenant_db(&agent, &tenant).await?;
let now = Utc::now();
let server = McpServerConfig {
id: None,
name: req.name.trim().to_string(),
endpoint_url: req.endpoint_url.trim().to_string(),
transport: if req.transport == "http" {
McpTransport::Http
} else {
McpTransport::Stdio
},
port: req.port,
status: McpServerStatus::Stopped,
access_token: new_token(),
tools_enabled: ALL_TOOLS.iter().map(|t| (*t).to_string()).collect(),
description: non_blank(req.description),
mongodb_uri: non_blank(req.mongodb_uri),
mongodb_database: non_blank(req.mongodb_database),
created_at: now,
updated_at: now,
};
let inserted = db
.mcp_servers()
.insert_one(&server)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(serde_json::json!({ "id": inserted.inserted_id })))
}
/// `DELETE /api/v1/mcp-servers/{id}` — remove one of the tenant's cards; 404
/// for an id the tenant has not.
#[tracing::instrument(skip_all, fields(server_id = %id))]
pub async fn delete_mcp_server(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
) -> Result<StatusCode, StatusCode> {
let oid = ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
let db = tenant_db(&agent, &tenant).await?;
let deleted = db
.mcp_servers()
.delete_one(doc! { "_id": oid })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if deleted.deleted_count == 0 {
return Err(StatusCode::NOT_FOUND);
}
Ok(StatusCode::NO_CONTENT)
}
/// `POST /api/v1/mcp-servers/{id}/token` — give one of the tenant's cards a
/// new access token; 404 for an id the tenant has not.
#[tracing::instrument(skip_all, fields(server_id = %id))]
pub async fn regenerate_mcp_server_token(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let oid = ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
let db = tenant_db(&agent, &tenant).await?;
let token = new_token();
let updated = db
.mcp_servers()
.update_one(
doc! { "_id": oid },
doc! { "$set": { "access_token": &token, "updated_at": mongodb::bson::DateTime::now() } },
)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if updated.matched_count == 0 {
return Err(StatusCode::NOT_FOUND);
}
Ok(Json(serde_json::json!({ "token": token })))
}
+2
View File
@@ -5,11 +5,13 @@ pub mod demo_seed;
pub mod dto;
pub mod evidence;
pub mod findings;
pub mod git_source;
pub mod graph;
pub mod health;
pub mod help_chat;
pub mod issues;
pub mod manual_findings;
pub mod mcp_servers;
pub mod mcp_tokens;
pub mod notifications;
pub mod onboarding;
+22 -13
View File
@@ -315,25 +315,34 @@ pub async fn update_target(
if let Some(name) = req.name {
set.insert("name", name);
}
// Both merge with what is stored, so the stored target is read once.
let stored = if req.scan_config.is_some()
|| req.artifacts.is_some()
|| req.project_ids.is_some()
|| req.target_type.is_some()
{
Some(
db.onboarded_targets()
.find_one(doc! { "_id": oid })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::NOT_FOUND)?,
)
} else {
None
};
if let Some(tt) = req.target_type {
set.insert(
"target_type",
to_bson(&tt).map_err(|_| StatusCode::BAD_REQUEST)?,
);
// A person picked another type: the scans' detection no longer
// changes it (the editor sends the type on every save, so only a
// change counts).
if stored.as_ref().is_some_and(|s| s.target_type != tt) {
set.insert("type_chosen", true);
}
}
// Both merge with what is stored, so the stored target is read once.
let stored =
if req.scan_config.is_some() || req.artifacts.is_some() || req.project_ids.is_some() {
Some(
db.onboarded_targets()
.find_one(doc! { "_id": oid })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::NOT_FOUND)?,
)
} else {
None
};
let credential_error = |e: SecretError| {
tracing::error!("storing a credential: {e}");
StatusCode::SERVICE_UNAVAILABLE
@@ -547,3 +547,206 @@ pub async fn list_targets(
.collect();
Ok(Json(serde_json::json!({ "items": items })))
}
/// The body of `PUT /api/v1/platform/tenants/{id}/git-source`.
#[derive(Debug, Deserialize)]
pub struct GitSourceBody {
/// `https://<host>` of the tenant's Gitea; the host must match
/// `GIT_SOURCE_HOST_PATTERN`.
pub base_url: String,
/// The organisation whose repositories are checked.
pub org: String,
/// The bot user's access token. Required the first time; left out, the
/// stored one is kept.
#[serde(default)]
pub bot_token: Option<String>,
/// Whether webhooks and the sync act on the source (default true).
#[serde(default)]
pub enabled: Option<bool>,
/// Issue a new webhook secret even though one is stored.
#[serde(default)]
pub rotate_webhook_secret: bool,
}
/// `GET /api/v1/platform/tenants/{id}/git-source` — the tenant's managed git
/// source without its secrets, and the webhook URL to register.
pub async fn get_git_source(
State(st): State<PlatformState>,
Path(tenant_id): Path<String>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let db = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
let source = crate::git_source::load_source(&db)
.await
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?;
Ok(Json(git_source_json(&st.agent, &tenant_id, &source, None)))
}
fn git_source_json(
agent: &ComplianceAgent,
tenant_id: &str,
source: &compliance_core::models::GitSource,
new_secret: Option<String>,
) -> serde_json::Value {
let mut v = serde_json::to_value(compliance_core::models::GitSourceView::from(source))
.unwrap_or_default();
if let Some(obj) = v.as_object_mut() {
obj.insert(
"webhook_url".into(),
agent.git_source.webhook_url(tenant_id).into(),
);
obj.insert(
"webhook_secret".into(),
new_secret.map_or(serde_json::Value::Null, Into::into),
);
}
v
}
/// `PUT /api/v1/platform/tenants/{id}/git-source` — create or replace the
/// tenant's managed git source. The webhook secret is returned only when it
/// is issued (first time, or `rotate_webhook_secret`); otherwise
/// `webhook_secret` is `null` and the registered webhook keeps working, so a
/// retried call breaks nothing. A sync starts right away.
pub async fn put_git_source(
State(st): State<PlatformState>,
Path(tenant_id): Path<String>,
Json(body): Json<GitSourceBody>,
) -> Result<Json<serde_json::Value>, Response> {
use compliance_core::models::{GitSource, GIT_SOURCE_ID};
let bad = |msg: String| {
(
StatusCode::BAD_REQUEST,
Json(serde_json::json!({ "error": "invalid_git_source", "message": msg })),
)
.into_response()
};
let agent = &st.agent;
let base_url = agent
.git_source
.normalize_base_url(&body.base_url)
.map_err(bad)?;
let org = body.org.trim().to_string();
if !crate::git_source::valid_org(&org) {
return Err(bad(format!("'{org}' is not a valid organisation name")));
}
let db = agent
.db_pool
.for_tenant_id(&tenant_id)
.await
.map_err(|e| internal(e).into_response())?;
let stored = crate::git_source::load_source(&db)
.await
.map_err(|e| internal(e).into_response())?;
let sealing_failed = |e: crate::secrets::SecretError| {
tracing::error!("storing a git source credential: {e}");
StatusCode::SERVICE_UNAVAILABLE.into_response()
};
let new_token = body
.bot_token
.as_deref()
.map(str::trim)
.filter(|t| !t.is_empty());
let bot_token = match new_token {
Some(token) => Some(agent.secrets.seal(token).map_err(sealing_failed)?),
None => stored.as_ref().and_then(|s| s.bot_token.clone()),
};
let Some(bot_token) = bot_token else {
return Err(bad("bot_token is required".into()));
};
let (webhook_secret, issued) = match stored.as_ref().and_then(|s| s.webhook_secret.clone()) {
Some(secret) if !body.rotate_webhook_secret => (secret, None),
_ => {
let plain = crate::git_source::generate_webhook_secret();
(
agent.secrets.seal(&plain).map_err(sealing_failed)?,
Some(plain),
)
}
};
let now = chrono::Utc::now();
let source = GitSource {
id: GIT_SOURCE_ID.to_string(),
base_url,
org,
bot_token: Some(bot_token.clone()),
webhook_secret: Some(webhook_secret),
enabled: body.enabled.unwrap_or(true),
created_at: stored.as_ref().map_or(now, |s| s.created_at),
updated_at: now,
last_sync_at: stored.as_ref().and_then(|s| s.last_sync_at),
};
db.git_sources()
.replace_one(doc! { "_id": GIT_SOURCE_ID }, &source)
.upsert(true)
.await
.map_err(|e| internal(e).into_response())?;
// The managed targets clone and open issues with the bot token: a new
// token goes onto them too, or they would keep using the old one.
if new_token.is_some() {
match crate::git_source::retoken_targets(&db, &source.base_url, &bot_token).await {
Ok(0) => {}
Ok(n) => tracing::info!(
tenant_id,
targets = n,
"git source token renewed on targets"
),
Err(e) => tracing::error!(tenant_id, "renewing the git source token on targets: {e}"),
}
}
if let Some(r) = &agent.registry {
r.invalidate(&tenant_id);
}
tracing::info!(tenant_id, base_url = %source.base_url, org = %source.org, enabled = source.enabled, "git source configured");
if source.enabled {
let (agent, tenant) = ((*st.agent).clone(), tenant_id.clone());
tokio::spawn(async move {
match crate::git_source::sync_tenant(&agent, &tenant).await {
Ok(report) => tracing::info!(tenant_id = tenant, ?report, "initial git sync"),
Err(e) => tracing::warn!(tenant_id = tenant, "initial git sync failed: {e}"),
}
});
}
Ok(Json(git_source_json(agent, &tenant_id, &source, issued)))
}
/// `DELETE /api/v1/platform/tenants/{id}/git-source` — remove the source. Its
/// targets are archived (kept with their findings, no longer scanned), since
/// the bot token may be revoked next.
pub async fn delete_git_source(
State(st): State<PlatformState>,
Path(tenant_id): Path<String>,
) -> Result<Json<serde_json::Value>, StatusCode> {
use compliance_core::models::GIT_SOURCE_ID;
let probe = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
let Some(source) = crate::git_source::load_source(&probe)
.await
.map_err(internal)?
else {
return Err(StatusCode::NOT_FOUND);
};
let db = st
.agent
.db_pool
.for_tenant_id(&tenant_id)
.await
.map_err(internal)?;
db.git_sources()
.delete_one(doc! { "_id": GIT_SOURCE_ID })
.await
.map_err(internal)?;
let archived = crate::git_source::archive_all(&db, &source.base_url)
.await
.map_err(internal)?;
tracing::info!(tenant_id, archived, "git source removed");
Ok(Json(serde_json::json!({
"status": "deleted",
"tenant_id": tenant_id,
"targets_archived": archived,
})))
}
+1
View File
@@ -1,4 +1,5 @@
pub mod handlers;
pub mod role_gate;
pub mod routes;
pub mod server;
+124
View File
@@ -0,0 +1,124 @@
//! Org-role enforcement for the customer API (decided 2026-09-30).
//!
//! One middleware for every tenant-scoped route, so no handler can forget it:
//!
//! * `IT_ADMIN`, `USER` — read and write.
//! * `CXO`, `LEGAL` — read only: `GET` / `HEAD` / `OPTIONS`, plus the few
//! `POST` routes that only read ([`READ_ONLY_POSTS`]).
//! * `FINANCE`, or none of these roles — nothing; every request is refused.
//!
//! Refusals are `403 {"error": "forbidden_role", "access": "none" | "read_only"}`.
//!
//! Not judged by org roles, as before:
//! * BreakPilot support ([`compliance_core::TenantContext::staff`]) — the
//! support rules apply (read-only until confirmed, every change audited).
//! * Requests without a [`TenantContext`]: the platform service API, the
//! Werkbank runner and admin APIs (their own token middleware), the health
//! check, and support staff who have not chosen a tenant yet.
//!
//! Handlers may still be stricter (manual findings stay `IT_ADMIN`-only).
use axum::{
extract::{MatchedPath, Request},
http::{Method, StatusCode},
middleware::Next,
response::{IntoResponse, Response},
Json,
};
use compliance_core::{ProductAccess, TenantContext};
/// The JSON `error` of a refusal.
pub const FORBIDDEN_ROLE: &str = "forbidden_role";
/// `POST` routes that only read: a query or an export with a body. Matched
/// against the route template, so an id in the path does not matter. Every
/// other `POST`, `PUT`, `PATCH` and `DELETE` is a write.
pub const READ_ONLY_POSTS: &[&str] = &[
// OSCAL assessment-results for a target's findings (computed, not stored).
"/api/v1/oscal/assess",
// The encrypted pentest report archive (the body carries its password).
"/api/v1/pentest/sessions/{id}/export",
// Questions about a repository's code (RAG); nothing is stored.
"/api/v1/chat/{repo_id}",
// The documentation assistant; nothing is stored.
"/api/v1/help/chat",
];
/// Whether a request with `method` to the route `template` changes anything.
/// A request that matched no route counts by its method alone.
pub fn is_write(method: &Method, template: Option<&str>) -> bool {
if matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS) {
return false;
}
!(*method == Method::POST && template.is_some_and(|t| READ_ONLY_POSTS.contains(&t)))
}
/// Why a request is refused, if it is.
pub fn refusal(
ctx: &TenantContext,
method: &Method,
template: Option<&str>,
) -> Option<ProductAccess> {
match ctx.product_access() {
ProductAccess::Full => None,
ProductAccess::ReadOnly if !is_write(method, template) => None,
denied => Some(denied),
}
}
/// The middleware. Runs after the JWT middleware has attached the
/// [`TenantContext`]; passes every request that has none.
pub async fn require_org_role(request: Request, next: Next) -> Response {
let Some(ctx) = request.extensions().get::<TenantContext>() else {
return next.run(request).await;
};
let template = request
.extensions()
.get::<MatchedPath>()
.map(MatchedPath::as_str);
let Some(access) = refusal(ctx, request.method(), template) else {
return next.run(request).await;
};
tracing::info!(
tenant_id = %ctx.tenant_id,
user_id = %ctx.user_id,
roles = ?ctx.org_roles,
method = %request.method(),
route = template.unwrap_or("-"),
"request refused by org role"
);
(
StatusCode::FORBIDDEN,
Json(serde_json::json!({ "error": FORBIDDEN_ROLE, "access": access })),
)
.into_response()
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod router_tests;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_and_read_only_posts_are_not_writes() {
assert!(!is_write(&Method::GET, Some("/api/v1/targets")));
assert!(!is_write(&Method::HEAD, None));
assert!(!is_write(&Method::OPTIONS, None));
for t in READ_ONLY_POSTS {
assert!(!is_write(&Method::POST, Some(t)), "{t}");
// Only POST is exempt on these routes.
assert!(is_write(&Method::DELETE, Some(t)), "{t}");
}
assert!(is_write(&Method::POST, Some("/api/v1/targets")));
assert!(is_write(&Method::POST, None));
assert!(is_write(
&Method::PATCH,
Some("/api/v1/findings/{id}/status")
));
assert!(is_write(&Method::PUT, None));
assert!(is_write(&Method::DELETE, Some("/api/v1/targets/{id}")));
}
}
@@ -0,0 +1,213 @@
//! Org-role enforcement through the real customer router.
//!
//! Role × method × representative route. The handlers have no agent in
//! these tests, so a request the gate lets through fails later (500, missing
//! extension); what is checked is only whether the gate refused it.
use super::{require_org_role, READ_ONLY_POSTS};
use crate::api::routes::build_router;
use axum::{
body::{to_bytes, Body},
extract::Request,
http::{Method, StatusCode},
middleware::{from_fn, Next},
Router,
};
use compliance_core::{OrgRole, StaffAccess, TenantContext, TenantStatus};
use tower::ServiceExt;
/// Who is calling.
#[derive(Debug, Clone, Copy)]
enum Caller {
ItAdmin,
User,
Cxo,
Legal,
Finance,
NoRoles,
/// BreakPilot support in a customer's tenant (no org roles of its own).
Staff,
/// A service / machine client: no tenant context reaches the gate.
Service,
}
fn ctx(caller: Caller) -> Option<TenantContext> {
let roles = match caller {
Caller::ItAdmin => vec![OrgRole::ItAdmin],
Caller::User => vec![OrgRole::User],
Caller::Cxo => vec![OrgRole::Cxo],
Caller::Legal => vec![OrgRole::Legal],
Caller::Finance => vec![OrgRole::Finance],
Caller::NoRoles | Caller::Staff => vec![],
Caller::Service => return None,
};
Some(TenantContext {
tenant_id: "00000000-0000-0000-0000-000000000001".to_string(),
tenant_slug: "acme".to_string(),
org_roles: roles,
products: vec![],
plan: "professional".to_string(),
status: TenantStatus::Active,
user_id: "u-1".to_string(),
user_name: None,
staff: matches!(caller, Caller::Staff).then(|| StaffAccess {
user_id: "u-1".to_string(),
user_name: None,
}),
})
}
fn router(caller: Caller) -> Router {
let ctx = ctx(caller);
let injector = move |mut req: Request, next: Next| {
let ctx = ctx.clone();
async move {
if let Some(c) = ctx {
req.extensions_mut().insert(c);
}
next.run(req).await
}
};
// Same order as the server: the context is attached, then the gate.
build_router()
.layer(from_fn(require_org_role))
.layer(from_fn(injector))
}
/// Whether the gate refused the request (403 `forbidden_role`).
async fn refused(caller: Caller, method: Method, path: &str) -> bool {
let req = Request::builder()
.method(method)
.uri(path)
.header("content-type", "application/json")
.body(Body::from("{}"))
.expect("request");
let resp = router(caller).oneshot(req).await.expect("oneshot");
if resp.status() != StatusCode::FORBIDDEN {
return false;
}
let body = to_bytes(resp.into_body(), 64 * 1024).await.expect("body");
let json: serde_json::Value = serde_json::from_slice(&body).unwrap_or_default();
json["error"] == "forbidden_role"
}
const ID: &str = "65f000000000000000000001";
/// (method, path, is a write).
fn routes() -> Vec<(Method, String, bool)> {
vec![
(Method::GET, "/api/v1/targets".into(), false),
(Method::POST, "/api/v1/targets".into(), true),
(Method::GET, format!("/api/v1/targets/{ID}"), false),
(Method::PATCH, format!("/api/v1/targets/{ID}"), true),
(Method::DELETE, format!("/api/v1/targets/{ID}"), true),
(Method::POST, format!("/api/v1/targets/{ID}/scan"), true),
(Method::POST, format!("/api/v1/targets/{ID}/detect"), true),
(Method::POST, "/api/v1/targets/demo-seed".into(), true),
(Method::GET, "/api/v1/findings".into(), false),
(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::PATCH,
format!("/api/v1/findings/{ID}/feedback"),
true,
),
(Method::POST, format!("/api/v1/targets/{ID}/findings"), true),
(
Method::POST,
format!("/api/v1/targets/{ID}/findings/import"),
true,
),
(
Method::GET,
format!("/api/v1/targets/{ID}/evidence-pack"),
false,
),
(Method::GET, "/api/v1/sbom/export".into(), false),
(Method::POST, "/api/v1/mcp-tokens".into(), true),
(Method::DELETE, format!("/api/v1/mcp-tokens/{ID}"), true),
(Method::POST, "/api/v1/notifications/read-all".into(), true),
(Method::POST, "/api/v1/pentest/sessions".into(), true),
// POSTs that only read.
(Method::POST, "/api/v1/oscal/assess".into(), false),
(
Method::POST,
format!("/api/v1/pentest/sessions/{ID}/export"),
false,
),
(Method::POST, format!("/api/v1/chat/{ID}"), false),
(Method::POST, "/api/v1/help/chat".into(), false),
]
}
#[tokio::test]
async fn roles_decide_reads_and_writes() {
// (caller, may read, may write)
let matrix = [
(Caller::ItAdmin, true, true),
(Caller::User, true, true),
(Caller::Cxo, true, false),
(Caller::Legal, true, false),
(Caller::Finance, false, false),
(Caller::NoRoles, false, false),
(Caller::Staff, true, true),
(Caller::Service, true, true),
];
for (caller, may_read, may_write) in matrix {
for (method, path, write) in routes() {
let allowed = if write { may_write } else { may_read };
assert_eq!(
refused(caller, method.clone(), &path).await,
!allowed,
"{caller:?} {method} {path}"
);
}
}
}
#[tokio::test]
async fn every_read_only_post_is_a_real_route() {
// A template that no longer matches a route would silently turn back
// into a write: each must be reachable by a read-only role.
for template in READ_ONLY_POSTS {
let path = template.replace("{id}", ID).replace("{repo_id}", ID);
assert!(
!refused(Caller::Cxo, Method::POST, &path).await,
"{template}"
);
}
}
#[tokio::test]
async fn a_refusal_says_which_access_the_role_has() {
let req = |method: Method| {
Request::builder()
.method(method)
.uri("/api/v1/targets")
.body(Body::empty())
.expect("request")
};
let resp = router(Caller::Legal)
.oneshot(req(Method::POST))
.await
.expect("oneshot");
assert_eq!(resp.status(), StatusCode::FORBIDDEN);
let body = to_bytes(resp.into_body(), 4096).await.expect("body");
let json: serde_json::Value = serde_json::from_slice(&body).expect("json");
assert_eq!(
json,
serde_json::json!({ "error": "forbidden_role", "access": "read_only" })
);
let resp = router(Caller::Finance)
.oneshot(req(Method::GET))
.await
.expect("oneshot");
let body = to_bytes(resp.into_body(), 4096).await.expect("body");
let json: serde_json::Value = serde_json::from_slice(&body).expect("json");
assert_eq!(
json,
serde_json::json!({ "error": "forbidden_role", "access": "none" })
);
}
+18
View File
@@ -15,6 +15,11 @@ 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))
// The managed git source, read-only (IT admin and support).
.route(
"/api/v1/git-source",
get(handlers::git_source::get_git_source),
)
// BreakPilot support access: choose and open a customer's tenant.
.route(
"/api/v1/support/tenants",
@@ -120,6 +125,19 @@ pub fn build_router() -> Router {
.route("/api/v1/issues", get(handlers::list_issues))
.route("/api/v1/scan-runs", get(handlers::list_scan_runs))
// MCP token management (per-tenant API tokens for the MCP server)
.route(
"/api/v1/mcp-servers",
get(handlers::mcp_servers::list_mcp_servers)
.post(handlers::mcp_servers::create_mcp_server),
)
.route(
"/api/v1/mcp-servers/{id}",
delete(handlers::mcp_servers::delete_mcp_server),
)
.route(
"/api/v1/mcp-servers/{id}/token",
post(handlers::mcp_servers::regenerate_mcp_server_token),
)
.route(
"/api/v1/mcp-tokens",
get(handlers::mcp_tokens::list_mcp_tokens).post(handlers::mcp_tokens::create_mcp_token),
+14 -4
View File
@@ -18,7 +18,7 @@ use compliance_core::{OrgRole, TenantContext, TenantStatus};
use crate::agent::ComplianceAgent;
use crate::api::handlers;
use crate::api::handlers::platform::{self, PlatformState};
use crate::api::routes;
use crate::api::{role_gate, routes};
use crate::error::AgentError;
/// Synthetic tenant id used when Keycloak isn't configured (local dev,
@@ -310,6 +310,13 @@ pub async fn start_api_server(
"/api/v1/platform/tenants/{id}/data",
delete(platform::delete_data),
)
// The tenant's managed git source (#439).
.route(
"/api/v1/platform/tenants/{id}/git-source",
get(platform::get_git_source)
.put(platform::put_git_source)
.delete(platform::delete_git_source),
)
.layer(middleware::from_fn_with_state(
platform_state.clone(),
platform::require_platform_token,
@@ -414,8 +421,8 @@ pub async fn start_api_server(
registry = agent.registry.is_some(),
"Keycloak JWT auth enabled"
);
// Layers execute outermost-first: Extension(jwks) → JWT → entitlement
// (registry) → support audit → status ladder → handlers.
// Layers execute outermost-first: Extension(jwks) → JWT → org roles
// → entitlement (registry) → support audit → status ladder → handlers.
app = app
.layer(middleware::from_fn(require_tenant_status))
.layer(middleware::from_fn_with_state(
@@ -426,6 +433,7 @@ pub async fn start_api_server(
shared.clone(),
require_entitlement,
))
.layer(middleware::from_fn(role_gate::require_org_role))
.layer(middleware::from_fn(require_jwt_auth))
.layer(Extension(jwks_state));
} else if agent.config.app_env.is_hardened() {
@@ -445,7 +453,9 @@ pub async fn start_api_server(
"Keycloak not configured — running unauthenticated against the dev tenant. \
DO NOT use in any environment with real customer data."
);
app = app.layer(middleware::from_fn(inject_dev_tenant));
app = app
.layer(middleware::from_fn(role_gate::require_org_role))
.layer(middleware::from_fn(inject_dev_tenant));
}
let addr = format!("0.0.0.0:{port}");
+127
View File
@@ -0,0 +1,127 @@
//! The .NET stack of a code tree as classification facts (#445).
//!
//! Facts only: which target type a .NET tree is (desktop, web, service) is the
//! language classifier's call. Recorded per tree:
//!
//! - `dotnet_runtime`: `dotnet-framework`, `dotnet` (.NET Core / 5+) or
//! `dotnet-standard`, once each;
//! - `dotnet_solution`: every solution, a component of its own;
//! - `dotnet_project`: every project with its style and target frameworks,
//! e.g. `src/Hmi/Hmi.csproj (legacy; net48)`.
use std::path::Path;
use compliance_core::models::DetectedFact;
use crate::pipeline::dotnet::{inventory, Inventory};
/// What produced the facts.
const SOURCE: &str = "dotnet-inventory";
/// At most this many solution and project facts each: a large codebase has
/// dozens of projects, and the facts are a summary, not an inventory.
const MAX_FACTS: usize = 100;
/// Add the .NET facts of the tree at `root` to `facts`, skipping any already
/// there.
pub(super) fn add_facts(facts: &mut Vec<DetectedFact>, root: &Path) {
for fact in dotnet_facts(&inventory(root)) {
if !facts
.iter()
.any(|f| f.key == fact.key && f.value == fact.value)
{
facts.push(fact);
}
}
}
/// The facts of an [`Inventory`]; none for a tree without .NET.
fn dotnet_facts(inv: &Inventory) -> Vec<DetectedFact> {
let mut facts = Vec::new();
for runtime in inv.runtimes() {
facts.push(DetectedFact::new(
"dotnet_runtime",
runtime.as_str(),
SOURCE,
));
}
for sln in inv.solutions.iter().take(MAX_FACTS) {
facts.push(DetectedFact::new("dotnet_solution", sln, SOURCE));
}
for project in inv.projects.iter().take(MAX_FACTS) {
let style = if project.sdk_style { "sdk" } else { "legacy" };
let frameworks: Vec<&str> = project
.frameworks
.iter()
.map(|f| f.moniker.as_str())
.collect();
let frameworks = if frameworks.is_empty() {
"inherited".to_string()
} else {
frameworks.join(",")
};
facts.push(DetectedFact::new(
"dotnet_project",
format!("{} ({style}; {frameworks})", project.path),
SOURCE,
));
}
facts
}
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use super::*;
#[test]
fn solutions_projects_and_runtimes_are_recorded_at_any_depth() {
let root = std::env::temp_dir().join(format!("cs-dotnet-facts-{}", uuid::Uuid::new_v4()));
let deep = root.join("src/plant/hmi/app");
std::fs::create_dir_all(&deep).expect("mkdir");
std::fs::write(root.join("src/plant/Plant.sln"), "").expect("write");
std::fs::write(root.join("src/Tools.sln"), "").expect("write");
std::fs::write(
deep.join("Hmi.csproj"),
"<Project ToolsVersion=\"15.0\"><PropertyGroup><TargetFrameworkVersion>v4.8</TargetFrameworkVersion></PropertyGroup></Project>",
)
.expect("write");
std::fs::write(
root.join("src/Api.csproj"),
"<Project Sdk=\"Microsoft.NET.Sdk.Web\"><PropertyGroup><TargetFramework>net8.0</TargetFramework></PropertyGroup></Project>",
)
.expect("write");
let mut facts = Vec::new();
add_facts(&mut facts, &root);
add_facts(&mut facts, &root);
let _ = std::fs::remove_dir_all(&root);
let got: Vec<String> = facts
.iter()
.map(|f| format!("{}={}", f.key, f.value))
.collect();
assert_eq!(
got,
[
"dotnet_runtime=dotnet-framework",
"dotnet_runtime=dotnet",
"dotnet_solution=src/Tools.sln",
"dotnet_solution=src/plant/Plant.sln",
"dotnet_project=src/Api.csproj (sdk; net8.0)",
"dotnet_project=src/plant/hmi/app/Hmi.csproj (legacy; net48)",
]
);
}
#[test]
fn a_tree_without_dotnet_adds_nothing() {
let root = std::env::temp_dir().join(format!("cs-dotnet-facts-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&root).expect("mkdir");
std::fs::write(root.join("main.go"), "package main").expect("write");
let mut facts = Vec::new();
add_facts(&mut facts, &root);
let _ = std::fs::remove_dir_all(&root);
assert!(facts.is_empty());
}
}
+535 -42
View File
@@ -13,8 +13,40 @@ use compliance_core::error::CoreError;
use compliance_core::models::{ArtifactKind, DetectedFact, TargetType};
use compliance_core::traits::{ClassificationInput, ClassifierVerdict, TargetClassifier};
/// Max directory depth scanned for marker files.
const SCAN_DEPTH: usize = 2;
/// Max directory depth scanned for marker files: deep enough for an Android
/// module's `app/src/main/AndroidManifest.xml` inside a monorepo folder.
const SCAN_DEPTH: usize = 6;
/// Directories not searched: build output, installed dependencies and tool
/// caches (Unity's `Library`, `Temp`, `Obj`), which hold other projects'
/// markers.
const SKIPPED_DIRS: &[&str] = &[
".git",
".gradle",
"build",
"node_modules",
"pods",
"deriveddata",
"library",
"temp",
"obj",
"logs",
];
/// Files whose location (relative path) is kept, for checks that need more
/// than the name: an Android module's manifest, Gradle build files, a Unity
/// project's settings.
const LOCATED_FILES: &[&str] = &[
"androidmanifest.xml",
"build.gradle",
"build.gradle.kts",
"projectversion.txt",
"pubspec.yaml",
"web.config",
];
/// Extensions of files whose location is kept: .NET project files.
const LOCATED_EXTENSIONS: &[&str] = &["csproj", "vbproj"];
/// Markers collected from a code tree.
#[derive(Default)]
@@ -22,6 +54,9 @@ struct Markers {
files: HashSet<String>,
dirs: HashSet<String>,
exts: HashSet<String>,
/// Relative paths (`/`-separated, as on disk) of the [`LOCATED_FILES`]
/// and [`LOCATED_EXTENSIONS`].
located: Vec<String>,
}
impl Markers {
@@ -34,45 +69,198 @@ impl Markers {
fn any_dir_ends_with(&self, suffix: &str) -> bool {
self.dirs.iter().any(|d| d.ends_with(suffix))
}
}
/// Recursively collect marker file/dir/extension names up to [`SCAN_DEPTH`].
fn collect_markers(root: &Path) -> Markers {
let mut m = Markers::default();
scan_dir(root, 0, &mut m);
m
}
fn scan_dir(dir: &Path, depth: usize, m: &mut Markers) {
let Ok(entries) = fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
let name = entry.file_name().to_string_lossy().to_lowercase();
if path.is_dir() {
m.dirs.insert(name);
if depth < SCAN_DEPTH {
scan_dir(&path, depth + 1, m);
}
} else {
if let Some(ext) = path.extension() {
m.exts.insert(ext.to_string_lossy().to_lowercase());
}
m.files.insert(name);
}
/// The located files whose path ends with `suffix`.
fn located_ending<'a>(&'a self, suffix: &'a str) -> impl Iterator<Item = &'a String> + 'a {
self.located
.iter()
.filter(move |p| p.to_lowercase().ends_with(suffix))
}
}
/// Whether a `package.json` at `root` looks like a front-end app.
/// Collect marker file/dir/extension names up to [`SCAN_DEPTH`], skipping
/// [`SKIPPED_DIRS`].
fn collect_markers(root: &Path) -> Markers {
let mut m = Markers::default();
let entries = walkdir::WalkDir::new(root)
.min_depth(1)
.max_depth(SCAN_DEPTH)
.into_iter()
.filter_entry(|e| {
!(e.file_type().is_dir()
&& SKIPPED_DIRS.contains(&e.file_name().to_string_lossy().to_lowercase().as_str()))
})
.filter_map(Result::ok);
for entry in entries {
let name = entry.file_name().to_string_lossy().to_lowercase();
if entry.file_type().is_dir() {
m.dirs.insert(name);
continue;
}
if let Some(ext) = entry.path().extension() {
m.exts.insert(ext.to_string_lossy().to_lowercase());
}
let ext = entry
.path()
.extension()
.map(|e| e.to_string_lossy().to_lowercase())
.unwrap_or_default();
if LOCATED_FILES.contains(&name.as_str()) || LOCATED_EXTENSIONS.contains(&ext.as_str()) {
if let Ok(rel) = entry.path().strip_prefix(root) {
m.located.push(rel.to_string_lossy().replace('\\', "/"));
}
}
m.files.insert(name);
}
m.located.sort();
m
}
/// The text of `rel` under `root`, if it is small enough to be a manifest.
fn read_small(root: &Path, rel: &str) -> Option<String> {
const MAX_MANIFEST_BYTES: u64 = 256 * 1024;
let path = root.join(rel);
let size = fs::metadata(&path).ok()?.len();
(size <= MAX_MANIFEST_BYTES)
.then(|| fs::read_to_string(&path).ok())
.flatten()
}
/// The mobile frameworks and app modules in a tree, beyond plain markers.
#[derive(Default)]
struct MobileShape {
/// Android application or library modules: their manifests, or Gradle
/// files applying the Android plugin.
android_modules: Vec<String>,
react_native: bool,
flutter: bool,
/// A Unity project (`ProjectSettings/ProjectVersion.txt`).
unity: bool,
/// A Unity project with Android plugins (`Assets/Plugins/Android`).
unity_android: bool,
}
/// How many .NET projects of each kind a tree holds.
#[derive(Default, Debug, PartialEq)]
struct DotnetShape {
/// WPF or Windows Forms applications.
desktop: usize,
/// ASP.NET (classic or Core) and WCF services.
service: usize,
/// Every project file, including libraries and tools.
projects: usize,
}
/// Markers of a WPF or Windows Forms project, in its project file.
const DESKTOP_PROJECT_MARKERS: &[&str] = &[
"<usewpf>true",
"<usewindowsforms>true",
"presentationframework",
"system.windows.forms",
// The WPF project type GUID of old-style project files.
"60dc8134-eba5-43b8-bcc9-bb4bc16c2548",
];
/// Markers of an ASP.NET or WCF project, in its project file.
const SERVICE_PROJECT_MARKERS: &[&str] = &[
"microsoft.net.sdk.web",
"microsoft.aspnetcore",
"system.web.mvc",
"system.web.http",
"system.servicemodel",
// The ASP.NET web application project type GUID.
"349c5851-65df-11da-9384-00065b846f21",
];
/// The kinds of the .NET projects under `root`. A project is a service when
/// its file names ASP.NET or WCF or a `Web.config` sits beside it, a desktop
/// app when it names WPF or Windows Forms.
fn dotnet_shape(root: &Path, m: &Markers) -> DotnetShape {
let mut shape = DotnetShape::default();
let web_configs: Vec<&str> = m
.located_ending("web.config")
.map(|p| p.rsplit_once('/').map_or("", |(dir, _)| dir))
.collect();
for project in m
.located_ending(".csproj")
.chain(m.located_ending(".vbproj"))
{
shape.projects += 1;
let text = read_small(root, project).unwrap_or_default().to_lowercase();
let dir = project.rsplit_once('/').map_or("", |(dir, _)| dir);
if SERVICE_PROJECT_MARKERS.iter().any(|k| text.contains(k)) || web_configs.contains(&dir) {
shape.service += 1;
} else if DESKTOP_PROJECT_MARKERS.iter().any(|k| text.contains(k)) {
shape.desktop += 1;
}
}
shape
}
/// The confidence for a .NET kind found in `count` of `projects` project
/// files: the dominant kind ranks highest, and none outranks a clear mobile
/// or PLC signal (0.8).
fn dotnet_confidence(count: usize, projects: usize) -> f32 {
// Counts of project files are small; the share needs no more precision.
#[allow(clippy::cast_precision_loss)]
let share = count as f32 / projects.max(1) as f32;
0.55 + 0.2 * share
}
/// What kind of mobile project the tree at `root` is.
fn mobile_shape(root: &Path, m: &Markers) -> MobileShape {
let mut shape = MobileShape::default();
for manifest in m.located_ending("androidmanifest.xml") {
// Every Android manifest names Android code: a Gradle module's
// `src/main/`, an Eclipse (ADT) project's root, a Unity project's
// `Assets/Plugins/Android/`. Only test manifests say nothing about
// the product.
let lower = format!("/{}", manifest.to_lowercase());
if !lower.contains("/androidtest/") && !lower.contains("/test/") {
shape.android_modules.push(manifest.clone());
}
}
for build in m
.located_ending("build.gradle")
.chain(m.located_ending("build.gradle.kts"))
{
let applies_android = read_small(root, build).is_some_and(|text| {
text.contains("com.android.application") || text.contains("com.android.library")
});
let module = build.rsplit_once('/').map_or("", |(dir, _)| dir);
let known = shape.android_modules.iter().any(|m| m.starts_with(module));
if applies_android && !known {
shape.android_modules.push(build.clone());
}
}
shape.react_native =
read_small(root, "package.json").is_some_and(|text| text.contains("\"react-native\""));
shape.flutter = m
.located_ending("pubspec.yaml")
.any(|p| read_small(root, p).is_some_and(|text| text.contains("sdk: flutter")));
// A Unity project's root holds `ProjectSettings/ProjectVersion.txt`.
let unity_roots: Vec<&str> = m
.located_ending("projectsettings/projectversion.txt")
.map(|p| p.rsplit_once('/').map_or("", |(dir, _)| dir))
.map(|settings| settings.rsplit_once('/').map_or("", |(dir, _)| dir))
.collect();
shape.unity = !unity_roots.is_empty();
shape.unity_android = unity_roots
.iter()
.any(|unity| root.join(unity).join("Assets/Plugins/Android").is_dir());
shape
}
/// Whether a `package.json` at `root` looks like a front-end app. A React
/// Native app also names `react`, but it is a mobile app.
fn package_json_is_frontend(root: &Path) -> bool {
let Ok(content) = fs::read_to_string(root.join("package.json")) else {
return false;
};
let c = content.to_lowercase();
["react", "next", "vue", "@angular", "svelte", "vite"]
.iter()
.any(|f| c.contains(f))
!c.contains("\"react-native\"")
&& ["react", "next", "vue", "@angular", "svelte", "vite"]
.iter()
.any(|f| c.contains(f))
}
/// The heuristic classifier: artifact-kind priors + source-tree markers.
@@ -131,16 +319,63 @@ impl HeuristicClassifier {
continue;
};
let m = collect_markers(path);
let shape = mobile_shape(path, &m);
// Mobile (checked first — strongest signal).
if m.has_file("androidmanifest.xml") || m.has_ext("apk") || m.has_ext("aab") {
if !shape.android_modules.is_empty() || m.has_ext("apk") || m.has_ext("aab") {
let mut facts = facts_lang("kotlin/java");
// A repository with several apps (phone and tablet) names each.
facts.extend(
shape
.android_modules
.iter()
.take(10)
.map(|module| DetectedFact::new("android_module", module, "heuristic")),
);
out.push(verdict(
TargetType::AndroidApp,
0.8,
"Android manifest / gradle",
facts_lang("kotlin/java"),
facts,
));
}
for (present, framework) in [
(shape.react_native, "react-native"),
(shape.flutter, "flutter"),
] {
if present {
let mut facts = facts_lang(if shape.flutter { "dart" } else { "javascript" });
facts.push(DetectedFact::new("framework", framework, "heuristic"));
out.push(verdict(
TargetType::AndroidApp,
0.75,
"cross-platform mobile app",
facts,
));
}
}
if shape.unity {
let mut facts = facts_lang("csharp");
facts.push(DetectedFact::new("framework", "unity", "heuristic"));
// Unity keeps the build target out of the repository; Android
// plugins in its Assets, or Android app modules beside it, are
// the sign it ships to Android.
let (target_type, confidence, why) =
if shape.unity_android || !shape.android_modules.is_empty() {
(
TargetType::AndroidApp,
0.8,
"Unity project with Android plugins",
)
} else {
(
TargetType::DesktopApp,
0.6,
"Unity project (build target unknown)",
)
};
out.push(verdict(target_type, confidence, why, facts));
}
if m.any_dir_ends_with(".xcodeproj")
|| m.has_file("info.plist")
|| m.has_file("podfile")
@@ -153,15 +388,39 @@ impl HeuristicClassifier {
facts_lang("swift/objc"),
));
}
// Desktop.
if m.has_ext("sln")
|| m.has_ext("csproj")
|| m.has_ext("vcxproj")
|| m.has_ext("desktop")
{
// .NET, split by what each project builds. A Unity project's
// solution and C# projects are generated by the editor and say
// nothing about the product.
let dotnet = if shape.unity {
DotnetShape::default()
} else {
dotnet_shape(path, &m)
};
if dotnet.desktop > 0 {
out.push(verdict(
TargetType::DesktopApp,
0.7,
dotnet_confidence(dotnet.desktop, dotnet.projects),
"WPF / Windows Forms projects",
facts_lang("csharp"),
));
}
if dotnet.service > 0 || m.has_ext("svc") {
out.push(verdict(
TargetType::BackendService,
dotnet_confidence(dotnet.service.max(1), dotnet.projects),
"ASP.NET / WCF projects",
facts_lang("csharp"),
));
}
// Native desktop projects, and .NET projects of no clear kind
// (libraries, console tools).
let unclear_dotnet = dotnet.desktop == 0
&& dotnet.service == 0
&& (dotnet.projects > 0 || (!shape.unity && m.has_ext("sln")));
if unclear_dotnet || m.has_ext("vcxproj") || m.has_ext("desktop") {
out.push(verdict(
TargetType::DesktopApp,
0.55,
"desktop project files",
facts_lang("dotnet/native"),
));
@@ -330,6 +589,240 @@ mod tests {
assert!(v.iter().any(|x| x.target_type == TargetType::AndroidApp));
}
/// Write `files` (relative path, content) under `root`.
fn write_all(root: &Path, files: &[(&str, &str)]) {
for (rel, content) in files {
let path = root.join(rel);
fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
fs::write(path, content).expect("write");
}
}
/// The verdict with the highest confidence.
fn top(verdicts: &[ClassifierVerdict]) -> TargetType {
verdicts
.iter()
.max_by(|a, b| a.confidence.total_cmp(&b.confidence))
.map(|v| v.target_type)
.expect("a verdict")
}
#[tokio::test]
async fn an_android_app_with_two_modules_and_a_unity_part_is_an_android_app() {
let v = classify_tree(|root| {
write_all(
root,
&[
("settings.gradle", "include ':phone', ':tablet'"),
(
"phone/build.gradle",
"apply plugin: 'com.android.application'",
),
("phone/src/main/AndroidManifest.xml", "<manifest/>"),
(
"tablet/build.gradle",
"apply plugin: 'com.android.application'",
),
("tablet/src/main/AndroidManifest.xml", "<manifest/>"),
(
"unity/ProjectSettings/ProjectVersion.txt",
"m_EditorVersion: 2021.3.1f1",
),
("unity/Assets/Scripts/Pump.cs", "class Pump {}"),
("unity/Assembly-CSharp.csproj", "<Project/>"),
(
"unity/Library/PackageCache/x/AndroidManifest.xml",
"<manifest/>",
),
],
);
})
.await;
assert_eq!(top(&v), TargetType::AndroidApp);
let android = v
.iter()
.find(|x| x.target_type == TargetType::AndroidApp && x.rationale.contains("manifest"))
.expect("android verdict");
let modules: Vec<&str> = android
.facts
.iter()
.filter(|f| f.key == "android_module")
.map(|f| f.value.as_str())
.collect();
assert_eq!(
modules,
[
"phone/src/main/AndroidManifest.xml",
"tablet/src/main/AndroidManifest.xml"
]
);
// The generated Unity C# project is not read as a desktop app.
assert!(!v.iter().any(|x| x.target_type == TargetType::DesktopApp));
}
#[tokio::test]
async fn an_eclipse_adt_project_and_a_unity_plugin_manifest_are_android() {
// The shape of a real pilot repository: an old ADT app (manifest at
// the project root, no Gradle) beside a Unity project whose only
// Android trace is its plugin manifest; Unity's generated C#
// projects alongside.
let v = classify_tree(|root| {
write_all(
root,
&[
("Phone/AndroidManifest.xml", "<manifest/>"),
("Phone/project.properties", "target=android-11"),
("Phone/src/com/example/Main.java", "class Main {}"),
(
"Game/ProjectSettings/ProjectVersion.txt",
"m_EditorVersion: 2019.4.1f1",
),
(
"Game/Assets/Plugins/Android/AndroidManifest.xml",
"<manifest/>",
),
("Game/Assembly-CSharp.csproj", "<Project/>"),
("Phone/src/test/AndroidManifest.xml", "<manifest/>"),
],
);
})
.await;
assert_eq!(top(&v), TargetType::AndroidApp);
let modules: Vec<&str> = v
.iter()
.flat_map(|x| &x.facts)
.filter(|f| f.key == "android_module")
.map(|f| f.value.as_str())
.collect();
assert_eq!(
modules,
[
"Game/Assets/Plugins/Android/AndroidManifest.xml",
"Phone/AndroidManifest.xml"
]
);
assert!(!v.iter().any(|x| x.target_type == TargetType::DesktopApp));
}
#[tokio::test]
async fn a_unity_project_with_android_plugins_is_an_android_app() {
let v = classify_tree(|root| {
write_all(
root,
&[
(
"ProjectSettings/ProjectVersion.txt",
"m_EditorVersion: 2021.3.1f1",
),
("Assets/Plugins/Android/libpump.aar", ""),
],
);
})
.await;
assert_eq!(top(&v), TargetType::AndroidApp);
assert!(v.iter().any(|x| x
.facts
.iter()
.any(|f| f.key == "framework" && f.value == "unity")));
}
#[tokio::test]
async fn a_react_native_app_is_mobile_not_a_web_app() {
let v = classify_tree(|root| {
write_all(
root,
&[
(
"package.json",
r#"{"dependencies":{"react":"18.2.0","react-native":"0.72.0"}}"#,
),
("android/app/src/main/AndroidManifest.xml", "<manifest/>"),
],
);
})
.await;
assert_eq!(top(&v), TargetType::AndroidApp);
assert!(!v.iter().any(|x| x.target_type == TargetType::WebApp));
}
#[tokio::test]
async fn a_flutter_app_is_mobile() {
let v = classify_tree(|root| {
write_all(
root,
&[(
"pubspec.yaml",
"dependencies:\n flutter:\n sdk: flutter\n",
)],
);
})
.await;
assert!(v.iter().any(|x| x
.facts
.iter()
.any(|f| f.key == "framework" && f.value == "flutter")));
}
#[tokio::test]
async fn dotnet_projects_split_into_desktop_and_services_by_majority() {
let wpf = r#"<Project><PropertyGroup><ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids></PropertyGroup><Reference Include="PresentationFramework" /></Project>"#;
let web = r#"<Project><Reference Include="System.Web.Mvc" /></Project>"#;
let wcf = r#"<Project><Reference Include="System.ServiceModel" /></Project>"#;
let services = classify_tree(|root| {
write_all(
root,
&[
("Plant.sln", ""),
("Plant.Client/Plant.Client.csproj", wpf),
("Plant.Web/Plant.Web.csproj", web),
("Plant.Web/Web.config", "<configuration/>"),
("Plant.Service/Plant.Service.csproj", wcf),
("Plant.Service/Pump.svc", ""),
("Plant.Core/Plant.Core.csproj", "<Project/>"),
],
);
})
.await;
assert_eq!(top(&services), TargetType::BackendService);
assert!(services
.iter()
.any(|x| x.target_type == TargetType::DesktopApp));
let desktop = classify_tree(|root| {
write_all(
root,
&[
("Plant.Client/Plant.Client.csproj", wpf),
(
"Plant.Tool/Plant.Tool.csproj",
"<Project Sdk=\"Microsoft.NET.Sdk\"><PropertyGroup><UseWindowsForms>true</UseWindowsForms></PropertyGroup></Project>",
),
],
);
})
.await;
assert_eq!(top(&desktop), TargetType::DesktopApp);
}
#[tokio::test]
async fn markers_inside_build_output_and_dependencies_are_ignored() {
let v = classify_tree(|root| {
write_all(
root,
&[
(
"node_modules/x/android/src/main/AndroidManifest.xml",
"<manifest/>",
),
("app/build/intermediates/AndroidManifest.xml", "<manifest/>"),
("Cargo.toml", "[package]\nname='x'"),
],
);
})
.await;
assert!(!v.iter().any(|x| x.target_type == TargetType::AndroidApp));
}
#[tokio::test]
async fn structured_text_is_plc() {
let v = classify_tree(|root| {
+15 -1
View File
@@ -5,6 +5,7 @@
//! The registry is the heuristic classifier (artifact kinds + source markers)
//! plus the Firmwerk firmware detector (behind a [`FirmwareDetector`] port).
mod dotnet;
mod firmware;
mod language;
@@ -68,7 +69,20 @@ pub async fn classify_target<D: FirmwareDetector>(
detected_by.push("firmwerk".to_string());
}
Ok(rank(verdicts, detected_by, target.target_type))
let mut classification = rank(verdicts, detected_by, target.target_type);
// The .NET stack at any depth, as facts (#445).
for artifact in &target.artifacts {
if !matches!(
artifact.kind,
ArtifactKind::GitRepo | ArtifactKind::SourceArchive
) {
continue;
}
if let Some(path) = working_paths.get(&artifact.id) {
dotnet::add_facts(&mut classification.facts, path);
}
}
Ok(classification)
}
/// Merge verdicts by target type (keeping the max confidence and its rationale),
+3
View File
@@ -24,6 +24,9 @@ pub fn load_config() -> Result<AgentConfig, AgentError> {
// start in every environment, not only hardened ones.
crate::secrets::SecretBox::check_config(&config)
.map_err(|e| AgentError::Config(e.to_string()))?;
// Same for the managed git source settings: a bad host pattern must not
// leave every host (or none) allowed.
crate::git_source::Settings::from_env().map_err(AgentError::Config)?;
if let Err(problems) = config.validate_deployment() {
return Err(AgentError::Config(format!(
"refusing to start in {}:\n - {}",
+30
View File
@@ -505,6 +505,25 @@ impl Database {
)
.await?;
// onboarded_targets: one target per managed-git repository (#439), so
// a `repository` and a `push` delivery racing each other cannot
// create two. Partial: user-onboarded targets have no source repo.
self.onboarded_targets()
.create_index(
IndexModel::builder()
.keys(doc! { "source_repo.base_url": 1, "source_repo.repo_id": 1 })
.options(
IndexOptions::builder()
.unique(true)
.partial_filter_expression(
doc! { "source_repo.repo_id": { "$exists": true } },
)
.build(),
)
.build(),
)
.await?;
// werkbank_jobs: unique job id (idempotent enqueue by job id)
self.werkbank_jobs()
.create_index(
@@ -559,6 +578,11 @@ impl Database {
self.inner.collection("cve_notifications")
}
/// The MCP server cards the dashboard shows (#432).
pub fn mcp_servers(&self) -> Collection<McpServerConfig> {
self.inner.collection("mcp_servers")
}
pub fn tracker_issues(&self) -> Collection<TrackerIssue> {
self.inner.collection("tracker_issues")
}
@@ -592,6 +616,12 @@ impl Database {
self.inner.collection("onboarded_targets")
}
/// The tenant's managed git source (#439): at most one document, with id
/// [`compliance_core::models::GIT_SOURCE_ID`].
pub fn git_sources(&self) -> Collection<compliance_core::models::GitSource> {
self.inner.collection("git_sources")
}
/// A typed handle to an arbitrary collection by name. For bookkeeping
/// collections without a dedicated model (e.g. `schema_migrations`,
/// `onboarding_migration_log`).
+78 -18
View File
@@ -44,10 +44,25 @@ pub enum NotAssessedReason {
/// The control is checked on the target's components (the SBOM and its
/// CVE lookup), and the scan found none: an empty SBOM proves nothing.
NoComponents,
/// The control is checked on the target's components, but the dependencies
/// `manifests` declare could not be listed (no lockfile, or one no tool
/// reads), so the SBOM is incomplete.
DependenciesUnresolved { manifests: Vec<String> },
}
/// How far the target's SBOM speaks for its components.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SbomCoverage {
/// Components were listed, and every manifest in the tree was read.
Complete,
/// The last scan listed no components.
Empty,
/// The dependencies these manifests declare could not be listed.
Unresolved(Vec<String>),
}
/// The tools that check a target's components rather than its code.
const COMPONENT_TOOLS: [&str; 2] = ["syft", "osv"];
const COMPONENT_TOOLS: [&str; 4] = ["syft", "osv", "dotnet-lifecycle", "build-lifecycle"];
/// The tool a skipped stage of a scan run stands for, when that stage is one
/// a control's binding relies on.
@@ -55,7 +70,9 @@ pub fn tool_of_stage(stage: &str) -> Option<&'static str> {
match stage {
"sast" => Some("semgrep"),
"sast_c_cpp" => Some("cppcheck"),
"sast_mobile" => Some("mobsfscan"),
"cve_lookup" => Some("osv"),
"sbom" => Some("syft"),
_ => None,
}
}
@@ -108,13 +125,14 @@ fn counts(finding: &Finding) -> bool {
/// if one of its rules covers one of those languages, and none of the tools
/// that apply is in `failed_tools` (see [`tool_of_stage`]): a scan of C code
/// says nothing about a control only Python rules check, and a CVE lookup
/// that failed says nothing about the components' CVEs.
/// that failed says nothing about the components' CVEs. A control checked on
/// components only is assessed only when `sbom` is [`SbomCoverage::Complete`].
pub fn control_statuses(
map: &ControlMap,
findings: &[Finding],
scanned_languages: Option<&[String]>,
failed_tools: &[&str],
has_components: bool,
sbom: &SbomCoverage,
) -> Vec<ControlStatus> {
map.controls
.iter()
@@ -165,13 +183,22 @@ pub fn control_statuses(
ControlState::NotAssessed,
Some(NotAssessedReason::ToolFailed { tools: failed }),
)
} else if on_components_only && !has_components {
(
ControlState::NotAssessed,
Some(NotAssessedReason::NoComponents),
)
} else {
} else if !on_components_only {
(ControlState::NoViolationFound, None)
} else {
match sbom {
SbomCoverage::Complete => (ControlState::NoViolationFound, None),
SbomCoverage::Empty => (
ControlState::NotAssessed,
Some(NotAssessedReason::NoComponents),
),
SbomCoverage::Unresolved(manifests) => (
ControlState::NotAssessed,
Some(NotAssessedReason::DependenciesUnresolved {
manifests: manifests.clone(),
}),
),
}
}
}
(Coverage::Covered, Some([])) => (
@@ -245,7 +272,7 @@ mod tests {
#[test]
fn every_control_gets_exactly_one_state() {
let map = ControlMap::cra().expect("map");
let statuses = control_statuses(&map, &[], Some(&python()), &[], true);
let statuses = control_statuses(&map, &[], Some(&python()), &[], &SbomCoverage::Complete);
assert_eq!(statuses.len(), map.controls.len());
assert_eq!(
state_of(&statuses, "cra-ai-8"),
@@ -267,7 +294,13 @@ mod tests {
// A real code issue that does not violate this requirement.
finding("cra-ai-9", FindingStatus::WrongMapping),
];
let statuses = control_statuses(&map, &findings, Some(&c_only()), &[], true);
let statuses = control_statuses(
&map,
&findings,
Some(&c_only()),
&[],
&SbomCoverage::Complete,
);
assert_eq!(state_of(&statuses, "cra-ai-8"), ControlState::NotSatisfied);
assert_eq!(
state_of(&statuses, "cra-ai-13"),
@@ -295,7 +328,7 @@ mod tests {
#[test]
fn a_c_scan_claims_nothing_for_controls_only_python_rules_check() {
let map = ControlMap::cra().expect("map");
let statuses = control_statuses(&map, &[], Some(&c_only()), &[], true);
let statuses = control_statuses(&map, &[], Some(&c_only()), &[], &SbomCoverage::Complete);
// Our C rules and cppcheck checked memory safety; gitleaks, secrets.
assert_eq!(
@@ -321,7 +354,7 @@ mod tests {
fn a_mixed_scan_counts_every_language() {
let map = ControlMap::cra().expect("map");
let mixed = vec!["c".to_string(), "python".to_string()];
let statuses = control_statuses(&map, &[], Some(&mixed), &[], true);
let statuses = control_statuses(&map, &[], Some(&mixed), &[], &SbomCoverage::Complete);
assert_eq!(
state_of(&statuses, "cra-ai-1"),
ControlState::NoViolationFound
@@ -335,7 +368,7 @@ mod tests {
#[test]
fn a_scan_without_recorded_languages_only_trusts_language_independent_tools() {
let map = ControlMap::cra().expect("map");
let statuses = control_statuses(&map, &[], Some(&[]), &[], true);
let statuses = control_statuses(&map, &[], Some(&[]), &[], &SbomCoverage::Complete);
assert_eq!(
state_of(&statuses, "cra-ai-9"),
ControlState::NoViolationFound
@@ -349,7 +382,7 @@ mod tests {
#[test]
fn an_empty_sbom_claims_nothing_about_components() {
let map = ControlMap::cra().expect("map");
let statuses = control_statuses(&map, &[], Some(&c_only()), &[], false);
let statuses = control_statuses(&map, &[], Some(&c_only()), &[], &SbomCoverage::Empty);
// cra-ai-22/23/33 are checked on components only: with none found,
// nothing was checked.
for control in ["cra-ai-22", "cra-ai-23", "cra-ai-33"] {
@@ -365,14 +398,40 @@ mod tests {
ControlState::NoViolationFound
);
// With components, the SBOM controls are assessed as before.
let with = control_statuses(&map, &[], Some(&c_only()), &[], true);
let with = control_statuses(&map, &[], Some(&c_only()), &[], &SbomCoverage::Complete);
assert_eq!(state_of(&with, "cra-ai-23"), ControlState::NoViolationFound);
}
#[test]
fn unresolved_dependencies_claim_nothing_about_components() {
let map = ControlMap::cra().expect("map");
let unresolved = SbomCoverage::Unresolved(vec!["android/app/build.gradle".into()]);
let statuses = control_statuses(&map, &[], Some(&c_only()), &[], &unresolved);
for control in ["cra-ai-22", "cra-ai-23", "cra-ai-33"] {
assert_eq!(
status_of(&statuses, control).reason,
Some(NotAssessedReason::DependenciesUnresolved {
manifests: vec!["android/app/build.gradle".into()]
}),
"{control}"
);
}
assert_eq!(
state_of(&statuses, "cra-ai-20"),
ControlState::NoViolationFound
);
}
#[test]
fn a_failed_cve_lookup_claims_nothing_about_component_cves() {
let map = ControlMap::cra().expect("map");
let statuses = control_statuses(&map, &[], Some(&c_only()), &["osv"], true);
let statuses = control_statuses(
&map,
&[],
Some(&c_only()),
&["osv"],
&SbomCoverage::Complete,
);
// cra-ai-22 relies on the CVE lookup (osv) and the SBOM (syft).
assert_eq!(
status_of(&statuses, "cra-ai-22").reason,
@@ -386,13 +445,14 @@ mod tests {
ControlState::NoViolationFound
);
assert_eq!(tool_of_stage("cve_lookup"), Some("osv"));
assert_eq!(tool_of_stage("sast_mobile"), Some("mobsfscan"));
assert_eq!(tool_of_stage("sast_vendor_code"), None);
}
#[test]
fn nothing_is_passed_before_a_scan() {
let map = ControlMap::cra().expect("map");
let statuses = control_statuses(&map, &[], None, &[], true);
let statuses = control_statuses(&map, &[], None, &[], &SbomCoverage::Complete);
assert_eq!(state_of(&statuses, "cra-ai-8"), ControlState::NotAssessed);
assert_eq!(
status_of(&statuses, "cra-ai-8").reason,
+22 -2
View File
@@ -16,7 +16,7 @@ use serde::Serialize;
use sha2::{Digest, Sha256};
use compliance_core::models::oscal_assessment::assess;
use compliance_core::models::{CveAlert, Finding, OnboardedTarget, SbomEntry, ScanRun};
use compliance_core::models::{CveAlert, Finding, OnboardedTarget, SbomEntry, ScanRun, SkipCode};
use compliance_core::sbom_docs;
use crate::error::AgentError;
@@ -174,6 +174,26 @@ pub fn failed_tools(inputs: &EvidenceInputs) -> Vec<&'static str> {
.collect()
}
/// How far the target's SBOM speaks for its components: the last scan's
/// manifests without readable lockfiles (its `sbom_dependencies` skips) make
/// it incomplete, and no components at all make it empty.
pub fn sbom_coverage(inputs: &EvidenceInputs) -> compliance::SbomCoverage {
let unresolved: Vec<String> = inputs
.last_run
.iter()
.flat_map(|run| &run.skipped_stages)
.filter(|s| s.code == Some(SkipCode::DependenciesUnlocked))
.filter_map(|s| s.subject.clone())
.collect();
if !unresolved.is_empty() {
compliance::SbomCoverage::Unresolved(unresolved)
} else if inputs.sbom.is_empty() {
compliance::SbomCoverage::Empty
} else {
compliance::SbomCoverage::Complete
}
}
/// The target's state against every CRA Annex I control.
pub fn compliance_of(inputs: &EvidenceInputs) -> Vec<compliance::ControlStatus> {
control_map::ControlMap::cra()
@@ -183,7 +203,7 @@ pub fn compliance_of(inputs: &EvidenceInputs) -> Vec<compliance::ControlStatus>
&inputs.findings,
scanned_languages(inputs),
&failed_tools(inputs),
!inputs.sbom.is_empty(),
&sbom_coverage(inputs),
);
// The catalog's own ratings, next to our state.
for status in &mut statuses {
+155
View File
@@ -0,0 +1,155 @@
//! What a system/org webhook delivery from a managed Gitea asks for.
use super::gitea::GiteaRepo;
/// The action a delivery maps to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SourceAction {
/// A repository was created: make it a target, scan it unless it is empty.
Created(GiteaRepo),
/// A repository was deleted: archive its target.
Deleted(GiteaRepo),
/// A push to the default branch: scan the target, creating it first if
/// the `created` delivery was lost.
Push(GiteaRepo),
/// Nothing to do, and why.
Ignore(&'static str),
}
/// A branch deletion pushes this as the new head.
const ZERO_SHA: &str = "0000000000000000000000000000000000000000";
/// Route a delivery: `event` is the `X-Gitea-Event` header, `org` the source's
/// 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 {
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"),
};
};
if !matches!(event, "repository" | "push") {
return SourceAction::Ignore("event not handled");
}
if !repo.in_org(org) {
return SourceAction::Ignore("repository outside the configured organisation");
}
match event {
"repository" => match payload.get("action").and_then(|a| a.as_str()) {
Some("created") => SourceAction::Created(repo),
Some("deleted") => SourceAction::Deleted(repo),
_ => SourceAction::Ignore("repository action not handled"),
},
_ => {
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("");
if after == ZERO_SHA {
SourceAction::Ignore("branch deleted")
} else if git_ref != format!("refs/heads/{}", repo.branch()) {
SourceAction::Ignore("push to another branch than the default")
} else {
SourceAction::Push(repo)
}
}
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use serde_json::json;
use super::*;
fn repository(owner: &str) -> serde_json::Value {
json!({
"id": 42, "name": "fw", "full_name": format!("{owner}/fw"),
"owner": { "login": owner }, "default_branch": "main", "empty": true,
})
}
#[test]
fn created_and_deleted() {
let p = json!({ "action": "created", "repository": repository("kunde") });
match route_event("repository", &p, "kunde") {
SourceAction::Created(r) => {
assert_eq!(
(r.id, r.full_name.as_str(), r.empty),
(42, "kunde/fw", true)
);
}
other => panic!("{other:?}"),
}
let p = json!({ "action": "deleted", "repository": repository("kunde") });
assert!(matches!(
route_event("repository", &p, "kunde"),
SourceAction::Deleted(r) if r.id == 42
));
let p = json!({ "action": "renamed", "repository": repository("kunde") });
assert!(matches!(
route_event("repository", &p, "kunde"),
SourceAction::Ignore(_)
));
}
#[test]
fn push_to_the_default_branch_only() {
let push = |git_ref: &str, after: &str| json!({ "ref": git_ref, "after": after, "repository": repository("kunde") });
assert!(matches!(
route_event("push", &push("refs/heads/main", "abc"), "kunde"),
SourceAction::Push(r) if r.id == 42
));
assert_eq!(
route_event("push", &push("refs/heads/feature", "abc"), "kunde"),
SourceAction::Ignore("push to another branch than the default")
);
assert_eq!(
route_event("push", &push("refs/tags/v1", "abc"), "kunde"),
SourceAction::Ignore("push to another branch than the default")
);
assert_eq!(
route_event("push", &push("refs/heads/main", ZERO_SHA), "kunde"),
SourceAction::Ignore("branch deleted")
);
}
#[test]
fn other_orgs_are_ignored_case_insensitively_matched() {
let p = json!({ "action": "created", "repository": repository("andere") });
assert_eq!(
route_event("repository", &p, "kunde"),
SourceAction::Ignore("repository outside the configured organisation")
);
let p = json!({ "action": "created", "repository": repository("Kunde") });
assert!(matches!(
route_event("repository", &p, "kunde"),
SourceAction::Created(_)
));
}
#[test]
fn unknown_events_and_bad_payloads_are_ignored() {
let p = json!({ "action": "opened", "repository": repository("kunde") });
assert_eq!(
route_event("pull_request", &p, "kunde"),
SourceAction::Ignore("event not handled")
);
assert_eq!(
route_event("issues", &json!({}), "kunde"),
SourceAction::Ignore("event not handled")
);
assert_eq!(
route_event("push", &json!({ "ref": "refs/heads/main" }), "kunde"),
SourceAction::Ignore("payload without a repository")
);
assert_eq!(
route_event("", &json!({ "repository": repository("kunde") }), "kunde"),
SourceAction::Ignore("event not handled")
);
}
}
+258
View File
@@ -0,0 +1,258 @@
//! The bits of the Gitea API a managed git source needs: the organisation's
//! repository list, and the repository shape shared with webhook payloads.
use compliance_core::guarded_net::guarded_client_builder;
use compliance_core::NetGuard;
use secrecy::{ExposeSecret, SecretString};
use serde::Deserialize;
use crate::error::AgentError;
/// Repositories per page when listing an organisation.
const PAGE_SIZE: usize = 50;
/// Upper bound on pages (10 000 repositories), so a misbehaving server cannot
/// keep the sync looping.
const MAX_PAGES: usize = 200;
/// A repository as Gitea describes it, in the org repository list and in the
/// `repository` and `push` webhook payloads.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct GiteaRepo {
/// Gitea's id: stable across renames and transfers.
pub id: i64,
pub name: String,
pub full_name: String,
#[serde(default)]
pub owner: Option<GiteaOwner>,
#[serde(default)]
pub default_branch: String,
/// A repository without any commit yet.
#[serde(default)]
pub empty: bool,
/// Archived (read-only) in Gitea.
#[serde(default)]
pub archived: bool,
}
/// A repository owner (user or organisation).
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct GiteaOwner {
#[serde(default)]
pub login: String,
}
impl GiteaRepo {
/// The owner's login: from `owner`, else the first part of `full_name`.
pub fn owner_login(&self) -> &str {
match &self.owner {
Some(o) if !o.login.is_empty() => &o.login,
_ => self.full_name.split('/').next().unwrap_or_default(),
}
}
/// Whether the repository belongs to `org` (Gitea logins are
/// case-insensitive).
pub fn in_org(&self, org: &str) -> bool {
self.owner_login().eq_ignore_ascii_case(org)
}
/// The branch scans follow; `main` when Gitea does not say.
pub fn branch(&self) -> &str {
if self.default_branch.is_empty() {
"main"
} else {
&self.default_branch
}
}
}
/// Something that can list an organisation's repositories. The sync works
/// against this, so it can be tested without a Gitea.
pub trait RepoLister {
/// Every repository of `org`.
fn list_org_repos(
&self,
org: &str,
) -> impl std::future::Future<Output = Result<Vec<GiteaRepo>, AgentError>> + Send;
}
/// The bot's client for one Gitea instance. Guarded like every other call to
/// a tenant-chosen address (#294).
pub struct SourceClient {
base_url: String,
token: SecretString,
http: reqwest::Client,
}
impl SourceClient {
/// A client for `base_url` acting with the bot `token`.
///
/// # Errors
///
/// Returns an error if the HTTP client cannot be built.
pub fn new(base_url: &str, token: SecretString, guard: NetGuard) -> Result<Self, AgentError> {
let http = guarded_client_builder(guard)
.timeout(std::time::Duration::from_secs(30))
.build()
.map_err(|e| AgentError::Other(format!("Gitea client: {e}")))?;
Ok(Self {
base_url: base_url.trim_end_matches('/').to_string(),
token,
http,
})
}
}
impl RepoLister for SourceClient {
async fn list_org_repos(&self, org: &str) -> Result<Vec<GiteaRepo>, AgentError> {
let mut repos = Vec::new();
for page in 1..=MAX_PAGES {
let url = format!(
"{}/api/v1/orgs/{}/repos?page={page}&limit={PAGE_SIZE}",
self.base_url,
urlencoding::encode(org)
);
let resp = self
.http
.get(&url)
.header(
"Authorization",
format!("token {}", self.token.expose_secret()),
)
.send()
.await?;
if !resp.status().is_success() {
return Err(AgentError::Other(format!(
"Gitea listing the repositories of '{org}' returned {}",
resp.status()
)));
}
let batch: Vec<GiteaRepo> = resp.json().await?;
// Only an empty page ends the list: an instance may cap the page
// size below `PAGE_SIZE` (`[api] MAX_RESPONSE_ITEMS`), and taking
// a short page for the last one would archive every repository
// after it.
if batch.is_empty() {
return Ok(repos);
}
repos.extend(batch);
}
Err(AgentError::Other(format!(
"'{org}' lists more than {} repositories; sync stopped",
PAGE_SIZE * MAX_PAGES
)))
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use std::sync::{Arc, Mutex};
use axum::extract::{Path, Query};
use axum::http::HeaderMap;
use axum::routing::get;
use axum::{Json, Router};
use super::*;
fn repo(id: i64, full_name: &str) -> serde_json::Value {
let (owner, name) = full_name.split_once('/').unwrap();
serde_json::json!({
"id": id, "name": name, "full_name": full_name,
"owner": { "login": owner }, "default_branch": "main",
"empty": false, "archived": false,
"clone_url": format!("https://elsewhere.invalid/{full_name}.git"),
})
}
/// A fake Gitea serving `total` repositories of org `kunde`, paginated.
async fn fake_gitea(total: i64, cap: i64, seen: Arc<Mutex<Vec<String>>>) -> String {
let app = Router::new().route(
"/api/v1/orgs/{org}/repos",
get(
move |Path(org): Path<String>,
Query(q): Query<std::collections::HashMap<String, String>>,
headers: HeaderMap| {
let seen = seen.clone();
async move {
seen.lock().unwrap().push(format!(
"{org} page={} auth={}",
q["page"],
headers["authorization"].to_str().unwrap()
));
let page: i64 = q["page"].parse().unwrap();
let limit: i64 = q["limit"].parse::<i64>().unwrap().min(cap);
let from = (page - 1) * limit + 1;
let to = (page * limit).min(total);
let items: Vec<_> = (from..=to)
.map(|i| repo(i, &format!("kunde/r{i}")))
.collect();
Json(items)
}
},
),
);
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 lists_every_page_with_the_bot_token() {
let seen = Arc::new(Mutex::new(Vec::new()));
let base = fake_gitea(120, 50, seen.clone()).await;
let client = SourceClient::new(
&base,
SecretString::from("bot-tok"),
NetGuard::allow_private(),
)
.unwrap();
let repos = client.list_org_repos("kunde").await.unwrap();
assert_eq!(repos.len(), 120);
assert_eq!(repos[119].full_name, "kunde/r120");
let seen = seen.lock().unwrap();
assert_eq!(
*seen,
[
"kunde page=1 auth=token bot-tok",
"kunde page=2 auth=token bot-tok",
"kunde page=3 auth=token bot-tok",
"kunde page=4 auth=token bot-tok",
]
);
}
#[tokio::test]
async fn an_exact_multiple_of_the_page_size_ends_on_an_empty_page() {
let seen = Arc::new(Mutex::new(Vec::new()));
let base = fake_gitea(50, 50, seen.clone()).await;
let client =
SourceClient::new(&base, SecretString::from("t"), NetGuard::allow_private()).unwrap();
assert_eq!(client.list_org_repos("kunde").await.unwrap().len(), 50);
assert_eq!(seen.lock().unwrap().len(), 2);
}
#[tokio::test]
async fn a_capped_page_size_is_not_taken_for_the_end() {
// An instance with MAX_RESPONSE_ITEMS=30 answers 30 per page.
let seen = Arc::new(Mutex::new(Vec::new()));
let base = fake_gitea(70, 30, seen.clone()).await;
let client =
SourceClient::new(&base, SecretString::from("t"), NetGuard::allow_private()).unwrap();
assert_eq!(client.list_org_repos("kunde").await.unwrap().len(), 70);
}
#[test]
fn owner_falls_back_to_the_full_name() {
let r: GiteaRepo = serde_json::from_value(serde_json::json!({
"id": 1, "name": "a", "full_name": "Kunde/a"
}))
.unwrap();
assert_eq!(r.owner_login(), "Kunde");
assert!(r.in_org("kunde"));
assert!(!r.in_org("other"));
assert_eq!(r.branch(), "main");
}
}
+806
View File
@@ -0,0 +1,806 @@
//! Managed git (#439): every repository of a tenant's Gitea organisation
//! becomes a target, is scanned on push, and gets its findings as issues.
//!
//! * [`Settings`] — which hosts a source may point at, the sync interval and
//! the public webhook origin (environment).
//! * [`events`] — what a system/org webhook delivery asks for.
//! * [`sync`] — the periodic diff of the organisation against the targets.
//! * here — creating, refreshing and archiving the targets, and the
//! entitlement check automated triggers go through.
pub mod events;
pub mod gitea;
pub mod sync;
use std::time::Duration;
use mongodb::bson::{doc, to_bson, Document};
use regex::Regex;
use secrecy::SecretString;
use compliance_core::models::{
default_compliance_profile, Artifact, ArtifactAuth, GitSource, IssueTrackerConfig,
OnboardedTarget, ScanTrigger, SourceRepo, TargetType, TrackerType, GIT_SOURCE_ID,
};
use crate::agent::ComplianceAgent;
use crate::database::Database;
use crate::error::AgentError;
use events::SourceAction;
use gitea::{GiteaRepo, RepoLister, SourceClient};
/// Hosts a git source may point at unless `GIT_SOURCE_HOST_PATTERN` says
/// otherwise: the managed instances, production and staging.
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 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")
}
/// Deployment settings of the managed git sources.
#[derive(Debug, Clone)]
pub struct Settings {
host_pattern: Regex,
/// Time between two syncs of every tenant's source.
pub sync_interval: Duration,
/// The public origin of the webhook server (`WEBHOOK_PUBLIC_URL`), for the
/// webhook URL an operator registers in Gitea.
pub webhook_public_url: Option<String>,
}
impl Default for Settings {
fn default() -> Self {
match Self::parse(None, None, None) {
Ok(settings) => settings,
// The defaults are constants, covered by the tests below.
Err(e) => unreachable!("default git source settings: {e}"),
}
}
}
impl Settings {
/// Read `GIT_SOURCE_HOST_PATTERN`, `GIT_SOURCE_SYNC_MINUTES` and
/// `WEBHOOK_PUBLIC_URL`.
///
/// # Errors
///
/// A malformed pattern or interval: startup refuses it rather than run
/// with no or every host allowed.
pub fn from_env() -> Result<Self, String> {
let var = |k: &str| std::env::var(k).ok().filter(|v| !v.trim().is_empty());
Self::parse(
var("GIT_SOURCE_HOST_PATTERN").as_deref(),
var("GIT_SOURCE_SYNC_MINUTES").as_deref(),
var("WEBHOOK_PUBLIC_URL").as_deref(),
)
}
/// Build the settings from raw values (`None` = default).
///
/// # Errors
///
/// See [`Self::from_env`].
pub fn parse(
host_pattern: Option<&str>,
sync_minutes: Option<&str>,
webhook_public_url: Option<&str>,
) -> Result<Self, String> {
let pattern = host_pattern.unwrap_or(DEFAULT_HOST_PATTERN).trim();
// Anchored whatever the operator wrote: the whole host must match.
let host_pattern = Regex::new(&format!("^(?:{pattern})$"))
.map_err(|e| format!("GIT_SOURCE_HOST_PATTERN is not a valid regex: {e}"))?;
let minutes = match sync_minutes {
None => DEFAULT_SYNC_MINUTES,
Some(m) => m
.trim()
.parse::<u64>()
.ok()
.filter(|m| *m > 0)
.ok_or_else(|| {
format!("GIT_SOURCE_SYNC_MINUTES must be a positive number, got '{m}'")
})?,
};
let webhook_public_url = match webhook_public_url {
None => None,
Some(u) if u.starts_with("https://") || u.starts_with("http://") => {
Some(u.trim().trim_end_matches('/').to_string())
}
Some(u) => {
return Err(format!(
"WEBHOOK_PUBLIC_URL must be an http(s) URL, got '{u}'"
))
}
};
Ok(Self {
host_pattern,
sync_interval: Duration::from_secs(minutes * 60),
webhook_public_url,
})
}
/// The canonical `https://<host>` of a source URL, if it may be used: https
/// only, no credentials, port, path, query or fragment, and a host the
/// allowlist pattern matches.
///
/// # Errors
///
/// Why the URL is refused.
pub fn normalize_base_url(&self, raw: &str) -> Result<String, String> {
let url = reqwest::Url::parse(raw.trim()).map_err(|_| "not a URL".to_string())?;
if url.scheme() != "https" {
return Err("only https is allowed".into());
}
if !url.username().is_empty() || url.password().is_some() {
return Err("credentials in the URL are not allowed".into());
}
if url.port().is_some() {
return Err("a port is not allowed".into());
}
if !matches!(url.path(), "" | "/") || url.query().is_some() || url.fragment().is_some() {
return Err("only the instance origin is allowed, without a path".into());
}
let host = url.host_str().unwrap_or_default();
if !self.host_pattern.is_match(host) {
return Err(format!("host '{host}' is not an allowed git source host"));
}
Ok(format!("https://{host}"))
}
/// The URL to register in Gitea for `tenant_id`: absolute when
/// `WEBHOOK_PUBLIC_URL` is set, else only the path.
pub fn webhook_url(&self, tenant_id: &str) -> String {
format!(
"{}{}",
self.webhook_public_url.as_deref().unwrap_or_default(),
webhook_path(tenant_id)
)
}
}
/// Whether `org` is a plausible Gitea organisation name.
pub fn valid_org(org: &str) -> bool {
!org.is_empty()
&& org.len() <= 40
&& org
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
}
/// A fresh webhook secret: 32 random bytes, hex.
pub fn generate_webhook_secret() -> String {
use rand::RngCore;
let mut bytes = [0u8; 32];
rand::rng().fill_bytes(&mut bytes);
hex::encode(bytes)
}
/// Whether automated work (webhook, sync) may change and scan `tenant_id`'s
/// targets now. The same answer the API's entitlement gate and the scheduler
/// give: entitled, not read-only, and on a running rung of the ladder. No
/// registry means dev; a hardened deployment without one refuses.
///
/// # Errors
///
/// Why not.
pub async fn automation_allowed(agent: &ComplianceAgent, tenant_id: &str) -> Result<(), String> {
let Some(registry) = agent.registry.as_ref() else {
if agent.config.app_env.is_hardened() {
return Err("no tenant registry in a hardened deployment".into());
}
return Ok(());
};
let check = registry.check_entitlement(tenant_id, None).await?;
if !check.allowed {
return Err(format!(
"not entitled: {}",
check.reason.unwrap_or_else(|| "no reason given".into())
));
}
let status = check.status.unwrap_or_default();
if check.read_only || !crate::registry::scheduler_runs_for(&status) {
return Err(format!("tenant is read-only (status '{status}')"));
}
Ok(())
}
/// The tenant's source, if one is configured.
///
/// # Errors
///
/// Returns an error if the database cannot be read.
pub async fn load_source(db: &Database) -> Result<Option<GitSource>, AgentError> {
Ok(db
.git_sources()
.find_one(doc! { "_id": GIT_SOURCE_ID })
.await?)
}
/// The clone URL of a repository: built from the source's own origin, never
/// taken from a payload, so the clone, the bot token and the issue tracker all
/// go to the instance the source names.
pub fn clone_url(base_url: &str, full_name: &str) -> String {
format!("{base_url}/{full_name}.git")
}
/// The target for a new repository of a source. `sealed_token` is the source's
/// bot token as stored (sealed); it authenticates the clone and the issues.
pub fn target_for_repo(base_url: &str, repo: &GiteaRepo, sealed_token: String) -> OnboardedTarget {
// A placeholder until detection runs; the scan classifies from the code.
let mut target = OnboardedTarget::new(repo.full_name.clone(), TargetType::BackendService);
let mut artifact = Artifact::git_repo(clone_url(base_url, &repo.full_name), repo.branch());
artifact.display_name = Some(repo.full_name.clone());
artifact.auth = Some(ArtifactAuth {
method: "token".to_string(),
secret: Some(sealed_token.clone()),
..Default::default()
});
target.artifacts.push(artifact);
target.scan_config.issue_tracker = Some(IssueTrackerConfig {
tracker_type: Some(TrackerType::Gitea),
owner: Some(repo.owner_login().to_string()),
repo: Some(repo.name.clone()),
token: Some(sealed_token),
});
target.source_repo = Some(SourceRepo {
base_url: base_url.to_string(),
repo_id: repo.id,
full_name: repo.full_name.clone(),
});
target
}
/// The update that brings a managed target in line with its repository
/// (renamed, other default branch, archived and back), with the array filters
/// it needs; `None` when it already is.
pub fn refresh_update(
target: &OnboardedTarget,
base_url: &str,
repo: &GiteaRepo,
) -> Option<(Document, Vec<Document>)> {
let mut set = Document::new();
let mut filters = Vec::new();
if target.name != repo.full_name {
set.insert("name", &repo.full_name);
}
if target
.source_repo
.as_ref()
.is_some_and(|s| s.full_name != repo.full_name)
{
set.insert("source_repo.full_name", &repo.full_name);
}
if let Some(code) = target.code_artifact() {
let url = clone_url(base_url, &repo.full_name);
let branch = code.git.as_ref().map(|g| g.default_branch.as_str());
if code.source_ref != url {
set.insert("artifacts.$[code].source_ref", url);
}
if branch.is_some_and(|b| b != repo.branch()) {
set.insert("artifacts.$[code].git.default_branch", repo.branch());
}
if set.keys().any(|k| k.starts_with("artifacts.")) {
filters.push(doc! { "code.id": &code.id });
}
}
if let Some(tracker) = &target.scan_config.issue_tracker {
if tracker.owner.as_deref() != Some(repo.owner_login()) {
set.insert("scan_config.issue_tracker.owner", repo.owner_login());
}
if tracker.repo.as_deref() != Some(repo.name.as_str()) {
set.insert("scan_config.issue_tracker.repo", &repo.name);
}
}
let unarchive = target.archived_at.is_some();
if set.is_empty() && !unarchive {
return None;
}
set.insert("updated_at", mongodb::bson::DateTime::now());
let mut update = doc! { "$set": set };
if unarchive {
update.insert("$unset", doc! { "archived_at": "" });
}
Some((update, filters))
}
/// The filter for the target of `repo_id` in the source at `base_url`.
fn repo_filter(base_url: &str, repo_id: i64) -> Document {
doc! { "source_repo.base_url": base_url, "source_repo.repo_id": repo_id }
}
/// A managed target after [`ensure_target`].
#[derive(Debug, Clone)]
pub struct Ensured {
pub target_id: String,
/// Created by this call (so it has never been scanned).
pub created: bool,
}
/// The target of `repo`: found (and refreshed if the repository changed), or
/// created and classified. Idempotent: the same repository id always maps to
/// the same target, also when two deliveries race (unique index).
///
/// # Errors
///
/// Returns an error if the source has no bot token or the database fails.
pub async fn ensure_target(
agent: &ComplianceAgent,
db: &Database,
tenant_id: &str,
source: &GitSource,
repo: &GiteaRepo,
) -> Result<Ensured, AgentError> {
let filter = repo_filter(&source.base_url, repo.id);
if let Some(existing) = db.onboarded_targets().find_one(filter.clone()).await? {
return refresh(db, existing, &source.base_url, repo).await;
}
let token = source
.bot_token
.clone()
.ok_or_else(|| AgentError::Other("the git source has no bot token".into()))?;
let target = target_for_repo(&source.base_url, repo, token);
let created = match crate::targets::create_target(agent, db, tenant_id, target).await {
Ok(created) => created,
Err(AgentError::Database(e)) if crate::werkbank::queue::is_duplicate_key(&e) => {
// Another delivery created it a moment ago.
let existing = db
.onboarded_targets()
.find_one(filter)
.await?
.ok_or_else(|| AgentError::Other("managed target vanished".into()))?;
return refresh(db, existing, &source.base_url, repo).await;
}
Err(e) => return Err(e),
};
let oid = created
.id
.ok_or_else(|| AgentError::Other("created target has no id".into()))?;
// The type from the detection step, as the onboarding wizard suggests it.
if let Some(detected) = crate::targets::detect_target(db, oid).await? {
if let Some(c) = &detected.classification {
let profile = to_bson(&default_compliance_profile(c.suggested))
.map_err(|e| AgentError::Other(e.to_string()))?;
let target_type =
to_bson(&c.suggested).map_err(|e| AgentError::Other(e.to_string()))?;
db.onboarded_targets()
.update_one(
doc! { "_id": oid },
doc! { "$set": { "target_type": target_type, "compliance_profile": profile } },
)
.await?;
}
}
tracing::info!(
tenant_id,
target_id = %oid.to_hex(),
repo = %repo.full_name,
"managed git: target created"
);
Ok(Ensured {
target_id: oid.to_hex(),
created: true,
})
}
async fn refresh(
db: &Database,
existing: OnboardedTarget,
base_url: &str,
repo: &GiteaRepo,
) -> Result<Ensured, AgentError> {
let oid = existing
.id
.ok_or_else(|| AgentError::Other("stored target has no id".into()))?;
if let Some((update, filters)) = refresh_update(&existing, base_url, repo) {
let targets = db.onboarded_targets();
let mut op = targets.update_one(doc! { "_id": oid }, update);
if !filters.is_empty() {
op = op.array_filters(filters);
}
op.await?;
tracing::info!(target_id = %oid.to_hex(), repo = %repo.full_name, "managed git: target refreshed");
}
Ok(Ensured {
target_id: oid.to_hex(),
created: false,
})
}
/// Archive the target of a deleted repository: kept with its findings, no
/// longer scanned. `Ok(false)` when there is none or it already is archived.
///
/// # Errors
///
/// Returns an error if the database fails.
pub async fn archive_target(
db: &Database,
base_url: &str,
repo_id: i64,
) -> Result<bool, AgentError> {
let mut filter = repo_filter(base_url, repo_id);
filter.insert("archived_at", mongodb::bson::Bson::Null);
archive_where(db, filter).await
}
async fn archive_where(db: &Database, filter: Document) -> Result<bool, AgentError> {
let now = mongodb::bson::DateTime::now();
let res = db
.onboarded_targets()
.update_one(
filter,
doc! { "$set": { "archived_at": now, "updated_at": now } },
)
.await?;
Ok(res.modified_count > 0)
}
/// Run a scan of `target_id` in the background (through the scan gate, which
/// emits the usage event).
pub fn spawn_scan(agent: &ComplianceAgent, tenant_id: &str, target_id: &str, trigger: ScanTrigger) {
let (agent, tenant_id, target_id) =
(agent.clone(), tenant_id.to_string(), target_id.to_string());
tokio::spawn(async move {
if let Err(e) = agent.run_target_scan(&tenant_id, &target_id, trigger).await {
tracing::error!(tenant_id, target_id, "managed git scan failed: {e}");
}
});
}
/// What a webhook delivery did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
/// A target was created (or found) and a scan queued if there is code.
Ensured { target_id: String, scan: bool },
/// The repository's target was archived (`false`: there was none).
Archived(bool),
/// Nothing done.
Ignored(&'static str),
}
/// Carry out a routed delivery for `tenant_id`.
///
/// # Errors
///
/// Returns an error if the target cannot be ensured or archived.
pub async fn apply_action(
agent: &ComplianceAgent,
db: &Database,
tenant_id: &str,
source: &GitSource,
action: SourceAction,
) -> Result<Outcome, AgentError> {
match action {
SourceAction::Ignore(why) => Ok(Outcome::Ignored(why)),
SourceAction::Deleted(repo) => Ok(Outcome::Archived(
archive_target(db, &source.base_url, repo.id).await?,
)),
SourceAction::Created(repo) => {
let ensured = ensure_target(agent, db, tenant_id, source, &repo).await?;
// An empty repository has nothing to scan; its first push will.
let scan = ensured.created && !repo.empty;
if scan {
spawn_scan(agent, tenant_id, &ensured.target_id, ScanTrigger::Webhook);
}
Ok(Outcome::Ensured {
target_id: ensured.target_id,
scan,
})
}
SourceAction::Push(repo) => {
let ensured = ensure_target(agent, db, tenant_id, source, &repo).await?;
spawn_scan(agent, tenant_id, &ensured.target_id, ScanTrigger::Webhook);
Ok(Outcome::Ensured {
target_id: ensured.target_id,
scan: true,
})
}
}
}
/// What one sync of a tenant did.
#[derive(Debug, Default, Clone, PartialEq, Eq, serde::Serialize)]
pub struct SyncReport {
pub repos: usize,
pub created: usize,
pub refreshed: usize,
pub archived: usize,
}
/// Sync `tenant_id`'s source, if it has an enabled one and automation is
/// allowed. `Ok(None)` when there is nothing to sync.
///
/// # Errors
///
/// Returns an error if the source cannot be read or listed.
pub async fn sync_tenant(
agent: &ComplianceAgent,
tenant_id: &str,
) -> Result<Option<SyncReport>, AgentError> {
// Read without creating anything: most tenants have no source.
let probe = agent.db_pool.for_existing_tenant_id(tenant_id);
let Some(source) = load_source(&probe).await? else {
return Ok(None);
};
if !source.enabled {
return Ok(None);
}
if let Err(why) = automation_allowed(agent, tenant_id).await {
tracing::info!(tenant_id, "managed git sync skipped: {why}");
return Ok(None);
}
let db = agent.db_pool.for_tenant_id(tenant_id).await?;
let token = agent
.secrets
.open_opt(source.bot_token.as_ref(), "git source bot token")
.ok_or_else(|| AgentError::Other("the git source has no usable bot token".into()))?;
let client = SourceClient::new(&source.base_url, SecretString::from(token), agent.net_guard)?;
let report = sync_with(agent, &db, tenant_id, &source, &client).await?;
db.git_sources()
.update_one(
doc! { "_id": GIT_SOURCE_ID },
doc! { "$set": { "last_sync_at": mongodb::bson::DateTime::now() } },
)
.await?;
Ok(Some(report))
}
/// One sync against `lister`.
///
/// # Errors
///
/// Returns an error if the repositories cannot be listed or the targets read.
/// A single repository that cannot be ensured is logged and skipped.
pub async fn sync_with<L: RepoLister>(
agent: &ComplianceAgent,
db: &Database,
tenant_id: &str,
source: &GitSource,
lister: &L,
) -> Result<SyncReport, AgentError> {
use futures_util::TryStreamExt;
let repos = lister.list_org_repos(&source.org).await?;
let targets: Vec<OnboardedTarget> = db
.onboarded_targets()
.find(doc! { "source_repo.base_url": &source.base_url })
.await?
.try_collect()
.await?;
let plan = sync::plan_sync(&repos, &targets, &source.base_url, &source.org);
let mut report = SyncReport {
repos: repos.len(),
..Default::default()
};
for repo in &plan.ensure {
match ensure_target(agent, db, tenant_id, source, repo).await {
Ok(e) if e.created => {
report.created += 1;
if !repo.empty {
spawn_scan(agent, tenant_id, &e.target_id, ScanTrigger::Scheduled);
}
}
Ok(_) => report.refreshed += 1,
Err(err) => {
tracing::warn!(tenant_id, repo = %repo.full_name, "managed git sync: {err}");
}
}
}
for oid in &plan.archive {
let filter = doc! { "_id": *oid, "archived_at": mongodb::bson::Bson::Null };
if archive_where(db, filter).await? {
report.archived += 1;
}
}
Ok(report)
}
/// Archive every managed target of `base_url`: the source was removed, so
/// nothing may scan with its (possibly revoked) token any more.
///
/// # Errors
///
/// Returns an error if the database fails.
pub async fn archive_all(db: &Database, base_url: &str) -> Result<u64, AgentError> {
let now = mongodb::bson::DateTime::now();
let res = db
.onboarded_targets()
.update_many(
doc! { "source_repo.base_url": base_url, "archived_at": mongodb::bson::Bson::Null },
doc! { "$set": { "archived_at": now, "updated_at": now } },
)
.await?;
Ok(res.modified_count)
}
/// Put a new sealed bot token on every managed target of `base_url` (clone
/// credentials and issue tracker), after the source's token was replaced.
///
/// # Errors
///
/// Returns an error if the database fails.
pub async fn retoken_targets(
db: &Database,
base_url: &str,
sealed_token: &str,
) -> Result<u64, AgentError> {
let res = db
.onboarded_targets()
.update_many(
doc! { "source_repo.base_url": base_url },
doc! { "$set": {
"artifacts.$[git].auth.secret": sealed_token,
"scan_config.issue_tracker.token": sealed_token,
"updated_at": mongodb::bson::DateTime::now(),
} },
)
// Only git artifacts that have credentials: setting a field inside a
// `null` auth would fail the whole update.
.array_filters(vec![
doc! { "git.kind": "git_repo", "git.auth": { "$type": "object" } },
])
.await?;
Ok(res.modified_count)
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
const BASE: &str = "https://kunde.code.breakpilot.com";
fn repo(id: i64, full_name: &str, branch: &str) -> GiteaRepo {
serde_json::from_value(serde_json::json!({
"id": id, "name": full_name.split('/').nth(1).unwrap(),
"full_name": full_name, "owner": { "login": full_name.split('/').next().unwrap() },
"default_branch": branch,
}))
.unwrap()
}
#[test]
fn host_allowlist_default() {
let s = Settings::default();
assert_eq!(
s.normalize_base_url("https://kunde.code.breakpilot.com/")
.unwrap(),
BASE
);
assert_eq!(
s.normalize_base_url("https://BP-Test.code-stage.breakpilot.com")
.unwrap(),
"https://bp-test.code-stage.breakpilot.com"
);
for bad in [
"http://kunde.code.breakpilot.com",
"https://kunde.code.breakpilot.com.evil.com",
"https://evil.com/kunde.code.breakpilot.com",
"https://a.b.code.breakpilot.com",
"https://git.breakpilot.com",
"https://user:pw@kunde.code.breakpilot.com",
"https://kunde.code.breakpilot.com:8443",
"https://kunde.code.breakpilot.com/sub",
"https://kunde.code.breakpilot.com/?x=1",
"ssh://git@kunde.code.breakpilot.com",
"kunde.code.breakpilot.com",
"",
] {
assert!(s.normalize_base_url(bad).is_err(), "{bad} must be refused");
}
}
#[test]
fn host_allowlist_from_the_environment_is_anchored() {
let s = Settings::parse(Some(r"git\.breakpilot\.com"), None, None).unwrap();
assert!(s.normalize_base_url("https://git.breakpilot.com").is_ok());
assert!(s.normalize_base_url("https://xgit.breakpilot.com").is_err());
assert!(s
.normalize_base_url("https://git.breakpilot.com.evil.com")
.is_err());
assert!(Settings::parse(Some("("), None, None).is_err());
}
#[test]
fn settings_parse_interval_and_webhook_origin() {
let s = Settings::default();
assert_eq!(s.sync_interval, Duration::from_secs(30 * 60));
assert_eq!(s.webhook_url("t1"), "/webhook/t1/gitea-source");
let s = Settings::parse(None, Some("5"), Some("https://hooks.example.com/")).unwrap();
assert_eq!(s.sync_interval, Duration::from_secs(300));
assert_eq!(
s.webhook_url("t1"),
"https://hooks.example.com/webhook/t1/gitea-source"
);
assert!(Settings::parse(None, Some("0"), None).is_err());
assert!(Settings::parse(None, Some("x"), None).is_err());
assert!(Settings::parse(None, None, Some("hooks.example.com")).is_err());
}
#[test]
fn orgs_and_secrets() {
assert!(valid_org("bp-test"));
assert!(valid_org("Kunde_1.x"));
assert!(!valid_org(""));
assert!(!valid_org("a/b"));
assert!(!valid_org("a b"));
let a = generate_webhook_secret();
assert_eq!(a.len(), 64);
assert_ne!(a, generate_webhook_secret());
}
#[test]
fn a_repo_becomes_a_managed_target_on_its_own_instance() {
let mut r = repo(7, "kunde/firmware", "develop");
r.owner = None;
let t = target_for_repo(BASE, &r, "enc:v1:tok".into());
assert_eq!(t.name, "kunde/firmware");
let code = t.code_artifact().unwrap();
assert_eq!(
code.source_ref,
"https://kunde.code.breakpilot.com/kunde/firmware.git"
);
assert_eq!(code.git.as_ref().unwrap().default_branch, "develop");
let auth = code.auth.as_ref().unwrap();
assert_eq!(
(auth.method.as_str(), auth.secret.as_deref()),
("token", Some("enc:v1:tok"))
);
let it = t.scan_config.issue_tracker.as_ref().unwrap();
assert_eq!(it.tracker_type, Some(TrackerType::Gitea));
assert_eq!(
(it.owner.as_deref(), it.repo.as_deref()),
(Some("kunde"), Some("firmware"))
);
assert_eq!(it.token.as_deref(), Some("enc:v1:tok"));
assert_eq!(
t.source_repo,
Some(SourceRepo {
base_url: BASE.into(),
repo_id: 7,
full_name: "kunde/firmware".into()
})
);
assert!(!t.webhook_enabled && t.webhook_secret.is_none());
}
#[test]
fn the_same_repo_again_needs_no_change() {
// Idempotency at the record level: ensuring a repository whose target
// exists and matches changes nothing (the unique index covers races).
let r = repo(7, "kunde/fw", "main");
let t = target_for_repo(BASE, &r, "enc".into());
assert!(refresh_update(&t, BASE, &r).is_none());
}
#[test]
fn a_rename_branch_change_or_unarchive_is_refreshed() {
let t = target_for_repo(BASE, &repo(7, "kunde/fw", "main"), "enc".into());
let (update, filters) = refresh_update(&t, BASE, &repo(7, "kunde/fw2", "dev")).unwrap();
let set = update.get_document("$set").unwrap();
assert_eq!(set.get_str("name").unwrap(), "kunde/fw2");
assert_eq!(set.get_str("source_repo.full_name").unwrap(), "kunde/fw2");
assert_eq!(
set.get_str("artifacts.$[code].source_ref").unwrap(),
"https://kunde.code.breakpilot.com/kunde/fw2.git"
);
assert_eq!(
set.get_str("artifacts.$[code].git.default_branch").unwrap(),
"dev"
);
assert_eq!(
set.get_str("scan_config.issue_tracker.repo").unwrap(),
"fw2"
);
assert!(!set.contains_key("scan_config.issue_tracker.owner"));
assert!(!update.contains_key("$unset"));
assert_eq!(filters.len(), 1);
let mut archived = t.clone();
archived.archived_at = Some(chrono::Utc::now());
let (update, filters) =
refresh_update(&archived, BASE, &repo(7, "kunde/fw", "main")).unwrap();
assert!(update.contains_key("$unset"));
assert!(filters.is_empty());
}
}
+123
View File
@@ -0,0 +1,123 @@
//! The periodic sync's diff: the organisation's repositories against the
//! tenant's managed targets. A safety net for lost webhook deliveries.
use mongodb::bson::oid::ObjectId;
use compliance_core::models::OnboardedTarget;
use super::gitea::GiteaRepo;
/// What a sync does.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct SyncPlan {
/// Repositories whose target is missing, archived or out of date
/// (renamed, other default branch): ensured.
pub ensure: Vec<GiteaRepo>,
/// Targets whose repository is gone: archived.
pub archive: Vec<ObjectId>,
}
/// Diff `repos` (the organisation's repositories now) against `targets` (the
/// tenant's managed targets of this source, archived ones included).
pub fn plan_sync(
repos: &[GiteaRepo],
targets: &[OnboardedTarget],
base_url: &str,
org: &str,
) -> SyncPlan {
let repos: Vec<&GiteaRepo> = repos.iter().filter(|r| r.in_org(org)).collect();
let target_of = |id: i64| {
targets.iter().find(|t| {
t.source_repo
.as_ref()
.is_some_and(|s| s.repo_id == id && s.base_url == base_url)
})
};
let ensure = repos
.iter()
.filter(|r| match target_of(r.id) {
None => true,
Some(t) => super::refresh_update(t, base_url, r).is_some(),
})
.map(|r| (*r).clone())
.collect();
let archive = targets
.iter()
.filter(|t| t.archived_at.is_none())
.filter_map(|t| {
let source = t.source_repo.as_ref()?;
let gone = source.base_url == base_url && !repos.iter().any(|r| r.id == source.repo_id);
if gone {
t.id
} else {
None
}
})
.collect();
SyncPlan { ensure, archive }
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use crate::git_source::target_for_repo;
const BASE: &str = "https://kunde.code.breakpilot.com";
fn repo(id: i64, full_name: &str) -> GiteaRepo {
serde_json::from_value(serde_json::json!({
"id": id, "name": full_name.split('/').nth(1).unwrap(),
"full_name": full_name, "owner": { "login": full_name.split('/').next().unwrap() },
"default_branch": "main",
}))
.unwrap()
}
fn target(id: i64, full_name: &str) -> OnboardedTarget {
let mut t = target_for_repo(BASE, &repo(id, full_name), "enc:v1:x".into());
t.id = Some(ObjectId::new());
t
}
#[test]
fn creates_missing_archives_gone_and_leaves_the_rest() {
let repos = [repo(1, "kunde/a"), repo(2, "kunde/b"), repo(3, "andere/c")];
let gone = target(9, "kunde/old");
let targets = vec![target(1, "kunde/a"), gone.clone()];
let plan = plan_sync(&repos, &targets, BASE, "kunde");
assert_eq!(plan.ensure, vec![repo(2, "kunde/b")]);
assert_eq!(plan.archive, vec![gone.id.unwrap()]);
}
#[test]
fn a_second_sync_of_the_same_state_does_nothing() {
let repos = [repo(1, "kunde/a"), repo(2, "kunde/b")];
let targets = vec![target(1, "kunde/a"), target(2, "kunde/b")];
assert_eq!(
plan_sync(&repos, &targets, BASE, "kunde"),
SyncPlan::default()
);
}
#[test]
fn renamed_and_reappeared_repos_are_ensured() {
let mut archived = target(2, "kunde/b");
archived.archived_at = Some(chrono::Utc::now());
let targets = vec![target(1, "kunde/a"), archived];
let repos = [repo(1, "kunde/a-neu"), repo(2, "kunde/b")];
let plan = plan_sync(&repos, &targets, BASE, "kunde");
assert_eq!(plan.ensure, repos.to_vec());
assert!(plan.archive.is_empty());
}
#[test]
fn archived_targets_are_not_archived_again_and_other_instances_untouched() {
let mut archived = target(5, "kunde/x");
archived.archived_at = Some(chrono::Utc::now());
let mut elsewhere = target(6, "kunde/y");
elsewhere.source_repo.as_mut().unwrap().base_url = "https://alt.code.breakpilot.com".into();
let plan = plan_sync(&[], &[archived, elsewhere], BASE, "kunde");
assert_eq!(plan, SyncPlan::default());
}
}
+1
View File
@@ -10,6 +10,7 @@ pub mod demo_seed;
pub mod error;
pub mod evidence;
pub mod fixtures;
pub mod git_source;
pub mod import;
pub mod ingest;
pub mod lifecycle;
+180 -1
View File
@@ -3,7 +3,8 @@
//! A redeploy, crash or out-of-memory kill ends every scan the agent was
//! running without anything recording it, so the run stays `running` forever.
//! [`recover_orphaned_runs`] closes those records once at startup, before
//! anything new can start. [`run_werkbank_sweeper`] returns Werkbank jobs whose
//! anything new can start; [`resume_interrupted_scans`] then starts those
//! code scans again. [`run_werkbank_sweeper`] returns Werkbank jobs whose
//! runner stopped heartbeating to the queue.
//!
//! Both assume one agent per environment, which is how every Orca deployment
@@ -136,6 +137,123 @@ async fn close_open_runs(db: &Database, now: DateTime<Utc>) -> Result<u64, Agent
Ok(closed)
}
/// A target whose scan was interrupted this many times within
/// [`RESUME_WINDOW_HOURS`] is not started again: the scan itself may be what
/// stops the agent (out of memory, a crash), and restarting it would loop.
const MAX_RECENT_INTERRUPTIONS: u64 = 1;
/// The window [`MAX_RECENT_INTERRUPTIONS`] counts in.
const RESUME_WINDOW_HOURS: i64 = 24;
/// Start again the code scans [`recover_orphaned_runs`] closed at `closed_at`
/// (this startup), in every tenant the scheduler runs for, through the normal
/// scan path (scan gate, concurrency). A target that is archived or gone, or
/// whose scans were already interrupted before within the last day, is left
/// for the next scheduled run.
///
/// # Arguments
///
/// * `agent` - the agent, cloned for the background scans
/// * `closed_at` - the time `recover_orphaned_runs` was given
///
/// # Returns
///
/// How many scans were started again.
pub async fn resume_interrupted_scans(
agent: &crate::agent::ComplianceAgent,
closed_at: DateTime<Utc>,
) -> usize {
let mut resumed = 0;
for tenant_id in crate::scheduler::scheduler_tenants(agent).await {
let db = match agent.db_pool.for_tenant_id(&tenant_id).await {
Ok(db) => db,
Err(e) => {
tracing::warn!(tenant_id, "resume: cannot open tenant database: {e}");
continue;
}
};
let targets = match targets_to_resume(&db, closed_at).await {
Ok(targets) => targets,
Err(e) => {
tracing::warn!(tenant_id, "resume: cannot read interrupted scans: {e}");
continue;
}
};
for target_id in targets {
tracing::info!(
tenant_id,
target_id,
"starting a scan interrupted by the restart again"
);
let agent = agent.clone();
let tenant = tenant_id.clone();
tokio::spawn(async move {
if let Err(e) = agent
.run_target_scan(
&tenant,
&target_id,
compliance_core::models::ScanTrigger::Scheduled,
)
.await
{
tracing::warn!(tenant_id = tenant, target_id, "resumed scan failed: {e}");
}
});
resumed += 1;
}
}
resumed
}
/// The targets in `db` whose scan was closed as interrupted at `closed_at`,
/// still active, and not interrupted more than [`MAX_RECENT_INTERRUPTIONS`]
/// times within [`RESUME_WINDOW_HOURS`].
async fn targets_to_resume(
db: &Database,
closed_at: DateTime<Utc>,
) -> Result<Vec<String>, AgentError> {
let closed = BsonDateTime::from_chrono(closed_at);
let window =
BsonDateTime::from_chrono(closed_at - chrono::Duration::hours(RESUME_WINDOW_HOURS));
let ids = db
.scan_runs()
.distinct(
"repo_id",
doc! { "status": "interrupted", "completed_at": closed },
)
.await?;
let mut out = Vec::new();
for id in ids.iter().filter_map(|v| v.as_str()) {
let interruptions = db
.scan_runs()
.count_documents(doc! {
"repo_id": id,
"status": "interrupted",
"completed_at": { "$gte": window },
})
.await?;
if interruptions > MAX_RECENT_INTERRUPTIONS {
tracing::warn!(
target_id = id,
interruptions,
"not resuming a scan interrupted again within a day; the next scheduled run tries"
);
continue;
}
let Ok(oid) = mongodb::bson::oid::ObjectId::parse_str(id) else {
continue;
};
let active = db
.onboarded_targets()
.count_documents(doc! { "_id": oid, "archived_at": { "$exists": false } })
.await?;
if active > 0 {
out.push(id.to_string());
}
}
Ok(out)
}
/// Sweep expired Werkbank leases in every tenant (see
/// [`JobQueue::sweep_expired`]). A tenant whose sweep fails is logged and
/// skipped.
@@ -209,6 +327,67 @@ mod tests {
.expect("status literal matches the enum's serde name")
}
#[tokio::test]
async fn only_scans_this_start_interrupted_are_resumed_once() {
use compliance_core::models::{OnboardedTarget, ScanRun, ScanTrigger, TargetType};
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"resume_{}",
&uuid::Uuid::new_v4().simple().to_string()[..10]
);
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP resume: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id("resume").await.unwrap();
let now = Utc::now();
let target = |name: &str| OnboardedTarget::new(name.into(), TargetType::BackendService);
let insert = |t: OnboardedTarget| {
let db = db.clone();
async move {
db.onboarded_targets()
.insert_one(t)
.await
.unwrap()
.inserted_id
.as_object_id()
.unwrap()
.to_hex()
}
};
let resumes = insert(target("resumes")).await;
let looping = insert(target("looping")).await;
let mut archived_target = target("archived");
archived_target.archived_at = Some(now);
let archived = insert(archived_target).await;
let earlier_only = insert(target("earlier-only")).await;
// Arrange: runs left open, plus one interrupted an hour ago.
for id in [&resumes, &looping, &archived] {
db.scan_runs()
.insert_one(ScanRun::new(id.clone(), ScanTrigger::Scheduled))
.await
.unwrap();
}
for id in [&looping, &earlier_only] {
let mut run = ScanRun::new(id.clone(), ScanTrigger::Scheduled);
run.status = compliance_core::models::ScanRunStatus::Interrupted;
run.completed_at = Some(now - chrono::Duration::hours(1));
db.scan_runs().insert_one(run).await.unwrap();
}
// Act: this start closes the open runs.
close_open_runs(&db, now).await.unwrap();
let resumed = targets_to_resume(&db, now).await.unwrap();
// Assert: only the target interrupted once, by this start, and active.
assert_eq!(resumed, [resumes]);
pool.drop_tenant("resume").await.ok();
}
#[test]
fn rule_statuses_match_the_model_enums() {
// The rules use literals so they can be a `const`; this keeps them in
+135 -3
View File
@@ -156,11 +156,48 @@ impl LlmClient {
self.send_chat_request(&request_body).await
}
/// Internal method to send a chat completion request and parse the response
/// Send a chat completion request and parse the response.
///
/// A reasoning model can spend the whole token budget thinking and return
/// no answer (`finish_reason: length`, the content empty or an unclosed
/// `<think>` block). The request is then sent once more with
/// [`REASONING_RETRY_TOKENS`].
///
/// # Errors
///
/// The gateway's refusal, an unreadable response, or
/// [`REASONING_EXHAUSTED`] when even the larger budget gave no answer.
async fn send_chat_request(
&self,
request_body: &ChatCompletionRequest,
) -> Result<LlmResponse, AgentError> {
let (response, finish_reason) = self.send_once(request_body).await?;
if !exhausted(&response, finish_reason.as_deref()) {
return Ok(response);
}
if request_body.max_tokens.unwrap_or(0) >= REASONING_RETRY_TOKENS {
return Err(AgentError::Other(REASONING_EXHAUSTED.to_string()));
}
tracing::info!(
budget = request_body.max_tokens,
retry = REASONING_RETRY_TOKENS,
"the model used its token budget reasoning and gave no answer; asking again with more"
);
let mut larger = serde_json::to_value(request_body)
.map_err(|e| AgentError::Other(format!("encode chat request: {e}")))?;
larger["max_tokens"] = serde_json::json!(REASONING_RETRY_TOKENS);
let (response, finish_reason) = self.send_once(&larger).await?;
if exhausted(&response, finish_reason.as_deref()) {
return Err(AgentError::Other(REASONING_EXHAUSTED.to_string()));
}
Ok(response)
}
/// One chat completion request, and the reason the model stopped.
async fn send_once<B: serde::Serialize + ?Sized>(
&self,
request_body: &B,
) -> Result<(LlmResponse, Option<String>), AgentError> {
let mut req = self
.http
.post(self.chat_url())
@@ -193,6 +230,7 @@ impl LlmClient {
.choices
.first()
.ok_or_else(|| AgentError::Other("Empty response from LiteLLM".to_string()))?;
let finish_reason = choice.finish_reason.clone();
// Check for tool calls first
if let Some(tool_calls) = &choice.message.tool_calls {
@@ -211,16 +249,33 @@ impl LlmClient {
.collect();
// Capture any reasoning text the LLM included alongside tool calls
let reasoning = choice.message.content.clone().unwrap_or_default();
return Ok(LlmResponse::ToolCalls { calls, reasoning });
return Ok((LlmResponse::ToolCalls { calls, reasoning }, finish_reason));
}
}
// Otherwise return content
let content = choice.message.content.as_deref().unwrap_or_default();
Ok(LlmResponse::Content(without_reasoning(content)))
Ok((
LlmResponse::Content(without_reasoning(content)),
finish_reason,
))
}
}
/// The token budget of the second request when the first ran out while the
/// model was still reasoning.
const REASONING_RETRY_TOKENS: u32 = 16384;
/// The error when the model gave no answer even with
/// [`REASONING_RETRY_TOKENS`].
const REASONING_EXHAUSTED: &str =
"the model used its whole token budget reasoning and gave no answer (finish_reason=length)";
/// Whether a response is no answer because the model ran out of tokens.
fn exhausted(response: &LlmResponse, finish_reason: Option<&str>) -> bool {
matches!(response, LlmResponse::Content(c) if c.is_empty()) && finish_reason == Some("length")
}
/// `content` without a reasoning model's `<think>…</think>` blocks, which some
/// gateways return inline ahead of the answer; the callers parse the answer as
/// JSON. An unterminated block (the model ran out of tokens while thinking)
@@ -258,3 +313,80 @@ mod reasoning_tests {
assert_eq!(without_reasoning("<think>still going"), "");
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod budget_tests {
use std::sync::{Arc, Mutex};
use axum::extract::State;
use axum::routing::post;
use axum::{Json, Router};
use super::*;
/// The `max_tokens` of every request a fake gateway received; it answers
/// "still thinking" until the budget reaches `answers_from`.
type Seen = Arc<Mutex<Vec<u64>>>;
async fn fake_gateway(seen: Seen, answers_from: u64) -> String {
let app = Router::new()
.route(
"/v1/chat/completions",
post(
move |State(seen): State<Seen>, Json(body): Json<serde_json::Value>| async move {
let budget = body["max_tokens"].as_u64().unwrap_or(0);
seen.lock().unwrap().push(budget);
let (content, finish) = if budget >= answers_from {
("<think>done</think>[{\"action\":\"confirm\"}]", "stop")
} else {
("<think>weighing the first finding against", "length")
};
Json(serde_json::json!({
"choices": [{ "message": { "content": content }, "finish_reason": finish }]
}))
},
),
)
.with_state(seen);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
format!("http://{addr}")
}
fn client(base: String) -> LlmClient {
LlmClient::new(
base,
SecretString::from(String::new()),
"m".into(),
"e".into(),
)
}
#[tokio::test]
async fn a_reasoning_model_out_of_tokens_is_asked_again_with_more() {
let seen: Seen = Arc::default();
let llm = client(fake_gateway(seen.clone(), u64::from(REASONING_RETRY_TOKENS)).await);
let answer = llm.chat("s", "u", None).await.unwrap();
assert_eq!(answer, "[{\"action\":\"confirm\"}]");
assert_eq!(*seen.lock().unwrap(), [4096, 16384]);
}
#[tokio::test]
async fn no_answer_even_with_more_says_why() {
let seen: Seen = Arc::default();
let llm = client(fake_gateway(seen.clone(), u64::MAX).await);
let err = llm.chat("s", "u", None).await.unwrap_err();
assert!(err.to_string().contains("finish_reason=length"), "{err}");
assert_eq!(seen.lock().unwrap().len(), 2);
}
#[tokio::test]
async fn an_answer_in_budget_is_one_request() {
let seen: Seen = Arc::default();
let llm = client(fake_gateway(seen.clone(), 0).await);
llm.chat("s", "u", None).await.unwrap();
assert_eq!(*seen.lock().unwrap(), [4096]);
}
}
+433 -80
View File
@@ -1,6 +1,9 @@
use std::ops::Range;
use std::sync::Arc;
use compliance_core::models::{Finding, FindingStatus};
use serde::{Deserialize, Deserializer};
use serde_json::Value;
use crate::llm::LlmClient;
use crate::pipeline::orchestrator::GraphContext;
@@ -55,6 +58,8 @@ Respond with a JSON array, one entry per finding in the same order presented (no
const TRIAGE_MAX_FINDINGS: usize = 600;
/// Triage calls in flight at once.
const TRIAGE_CONCURRENCY: usize = 4;
/// How much of an unreadable model answer goes to the debug log.
const RESPONSE_SAMPLE_CHARS: usize = 500;
/// The findings the LLM triage looks at, by index: the most severe first, at
/// most [`TRIAGE_MAX_FINDINGS`].
@@ -66,14 +71,15 @@ fn triage_selection(findings: &[Finding]) -> Vec<usize> {
selected
}
/// The model's answer for one chunk: its verdicts in chunk order, or `None`
/// when the call failed or its answer could not be read.
/// The model's answer for one chunk: its verdicts in chunk order, at most one
/// per finding. Fewer (none at all when the call failed or its answer could
/// not be read) leave the rest of the chunk without a verdict.
async fn triage_chunk(
llm: &LlmClient,
chunk: &[&Finding],
graph_context: Option<&GraphContext>,
chunk_start: usize,
) -> Option<Vec<TriageResult>> {
) -> Vec<TriageResult> {
let mut user_prompt = String::new();
for (i, finding) in chunk.iter().enumerate() {
@@ -141,39 +147,117 @@ async fn triage_chunk(
{
Ok(response) => response,
Err(e) => {
tracing::warn!("LLM batch triage failed for chunk starting at {chunk_start}: {e}");
return None;
tracing::warn!(
"LLM batch triage failed for chunk starting at {chunk_start}: {e}; {} findings \
affected, left unchanged unless a retry answers them",
chunk.len()
);
return Vec::new();
}
};
let cleaned = response.trim();
let cleaned = if cleaned.starts_with("```") {
cleaned
.trim_start_matches("```json")
.trim_start_matches("```")
.trim_end_matches("```")
.trim()
} else {
cleaned
};
match serde_json::from_str::<Vec<TriageResult>>(cleaned) {
Ok(results) => Some(results),
Err(_) => {
let mut verdicts = match parse_triage_response(&response) {
Ok(verdicts) => verdicts,
Err(e) => {
tracing::warn!(
"Failed to parse batch triage response for chunk starting at {chunk_start}: {cleaned}"
"Failed to parse batch triage response for chunk starting at {chunk_start}: {e}; \
{} findings affected, left unchanged unless a retry answers them",
chunk.len()
);
None
// A sample of the answer only, never the prompt (it carries the code).
let sample: String = response.chars().take(RESPONSE_SAMPLE_CHARS).collect();
tracing::debug!(
"Unreadable batch triage response (first {RESPONSE_SAMPLE_CHARS} chars): {sample}"
);
return Vec::new();
}
};
if verdicts.len() < chunk.len() {
tracing::warn!(
"Batch triage for chunk starting at {chunk_start} answered {} of {} findings",
verdicts.len(),
chunk.len()
);
}
// Extra verdicts belong to no finding of this chunk.
verdicts.truncate(chunk.len());
verdicts
}
/// Ask the model about each batch of positions in `selected`,
/// [`TRIAGE_CONCURRENCY`] batches at a time, and record its verdicts in
/// `verdicts` (indexed like `selected`).
///
/// # Returns
///
/// The positions the model gave no verdict for: one range per batch that fell
/// short.
async fn triage_batches(
llm: &LlmClient,
findings: &[Finding],
selected: &[usize],
batches: &[Range<usize>],
graph_context: Option<&GraphContext>,
verdicts: &mut [Option<TriageResult>],
) -> Vec<Range<usize>> {
let chunks: Vec<Vec<&Finding>> = batches
.iter()
.map(|range| {
selected[range.clone()]
.iter()
.map(|&i| &findings[i])
.collect()
})
.collect();
// A few calls at once; the answers stay in batch order.
let mut answers: Vec<Vec<TriageResult>> = Vec::with_capacity(batches.len());
for (group, ranges) in chunks
.chunks(TRIAGE_CONCURRENCY)
.zip(batches.chunks(TRIAGE_CONCURRENCY))
{
let calls = group
.iter()
.zip(ranges)
.map(|(chunk, range)| triage_chunk(llm, chunk, graph_context, range.start));
answers.extend(futures_util::future::join_all(calls).await);
}
let mut missing = Vec::new();
for (range, answer) in batches.iter().zip(answers) {
let answered = answer.len();
for (slot, verdict) in verdicts[range.clone()].iter_mut().zip(answer) {
*slot = Some(verdict);
}
if answered < range.len() {
missing.push(range.start + answered..range.end);
}
}
missing
}
/// Split each range in two halves (the first one the larger) for a retry in
/// smaller chunks; a single position stays as it is.
fn halves(ranges: &[Range<usize>]) -> Vec<Range<usize>> {
ranges
.iter()
.flat_map(|range| {
let mid = range.start + range.len().div_ceil(2);
[range.start..mid, mid..range.end]
})
.filter(|range| !range.is_empty())
.collect()
}
/// Triage `findings` with the LLM, in chunks: confirm, re-rate or flag each
/// one. Nothing is removed; a flagged finding is kept as "needs review". The
/// most severe findings go first, at most [`TRIAGE_MAX_FINDINGS`], and
/// [`TRIAGE_CONCURRENCY`] chunks are triaged at a time.
/// [`TRIAGE_CONCURRENCY`] chunks are triaged at a time. Findings a chunk got
/// no verdict for (the call failed, the answer was unreadable or cut short)
/// are asked about once more, in chunks half the size; whatever is still
/// unanswered then stays as reported.
///
/// # Returns
///
/// How many findings passed triage (confirmed or re-rated).
/// How many findings passed triage (confirmed, re-rated, or left unchanged).
pub async fn triage_findings(
llm: &Arc<LlmClient>,
findings: &mut [Finding],
@@ -188,53 +272,210 @@ pub async fn triage_findings(
);
}
// Ask for every chunk first (read-only), a few at a time, then apply the
// answers.
let chunks: Vec<&[usize]> = selected.chunks(TRIAGE_CHUNK_SIZE).collect();
let mut answers: Vec<Option<Vec<TriageResult>>> = Vec::with_capacity(chunks.len());
{
let read: &[Finding] = findings;
for (group_no, group) in chunks.chunks(TRIAGE_CONCURRENCY).enumerate() {
let batches: Vec<Vec<&Finding>> = group
.iter()
.map(|indices| indices.iter().map(|&i| &read[i]).collect())
.collect();
let calls = batches.iter().enumerate().map(|(k, batch)| {
let start = (group_no * TRIAGE_CONCURRENCY + k) * TRIAGE_CHUNK_SIZE;
triage_chunk(llm, batch, graph_context, start)
});
answers.extend(futures_util::future::join_all(calls).await);
// Ask for every chunk first (read-only), then apply the answers.
let mut verdicts: Vec<Option<TriageResult>> = (0..selected.len()).map(|_| None).collect();
let batches: Vec<Range<usize>> = (0..selected.len())
.step_by(TRIAGE_CHUNK_SIZE)
.map(|start| start..(start + TRIAGE_CHUNK_SIZE).min(selected.len()))
.collect();
let missing = triage_batches(
llm,
findings,
&selected,
&batches,
graph_context,
&mut verdicts,
)
.await;
if !missing.is_empty() {
// One retry only, in smaller chunks: whatever is left after it stays as reported.
let retry = halves(&missing);
tracing::info!(
"LLM triage: retrying {} findings in {} smaller chunks",
retry.iter().map(Range::len).sum::<usize>(),
retry.len()
);
let unanswered: usize = triage_batches(
llm,
findings,
&selected,
&retry,
graph_context,
&mut verdicts,
)
.await
.iter()
.map(Range::len)
.sum();
if unanswered > 0 {
tracing::warn!(
"LLM triage: no verdict for {unanswered} findings after a retry; \
they stay unchanged, as reported"
);
}
}
let answers = chunks.into_iter().zip(answers);
let mut passed = 0;
for (indices, answer) in answers {
for (pos, &i) in indices.iter().enumerate() {
let finding = &mut findings[i];
// No usable answer for the chunk, or none for this finding: keep
// it as reported.
let Some(result) = answer.as_ref().and_then(|results| results.get(pos)) else {
finding.status = FindingStatus::Triaged;
passed += 1;
continue;
};
let file_classification = classify_file_path(finding.file_path.as_deref());
let adjusted_confidence = adjust_confidence(result.confidence, &file_classification);
finding.confidence = Some(adjusted_confidence);
finding.triage_action = Some(result.action.clone());
finding.triage_rationale = Some(result.rationale.clone());
if let Some(ref remediation) = result.remediation {
finding.remediation = Some(remediation.clone());
}
if apply_action(finding, &result.action, adjusted_confidence) {
passed += 1;
}
for (&i, verdict) in selected.iter().zip(&verdicts) {
let finding = &mut findings[i];
// No usable answer for this finding: keep it as reported.
let Some(result) = verdict else {
finding.status = FindingStatus::Triaged;
passed += 1;
continue;
};
let file_classification = classify_file_path(finding.file_path.as_deref());
let adjusted_confidence = adjust_confidence(result.confidence, &file_classification);
finding.confidence = Some(adjusted_confidence);
finding.triage_action = Some(result.action.clone());
finding.triage_rationale = Some(result.rationale.clone());
if let Some(ref remediation) = result.remediation {
finding.remediation = Some(remediation.clone());
}
if apply_action(finding, &result.action, adjusted_confidence) {
passed += 1;
}
}
passed
}
/// Why a batch triage answer could not be read.
#[derive(Debug, PartialEq, thiserror::Error)]
enum TriageParseError {
/// Neither a JSON array of verdicts, an object wrapping one, nor a single
/// verdict object was found in the answer.
#[error("no JSON array of verdicts in the answer")]
NoVerdicts,
}
/// Read the model's verdicts from its batch answer, tolerating what models
/// tend to wrap around the JSON: markdown fences, prose before or after,
/// trailing commas, an object wrapping the array (`{"results": [...]}`), a
/// bare object for a single finding, and an answer cut off mid-array (the
/// complete leading verdicts are kept). Verdicts stay in answer order; the
/// first element that is not a verdict ends the list, so no later verdict is
/// matched to the wrong finding.
///
/// # Errors
///
/// [`TriageParseError::NoVerdicts`] when no verdict can be read.
fn parse_triage_response(response: &str) -> Result<Vec<TriageResult>, TriageParseError> {
// Every `[` is a candidate start: prose before the array may hold one too.
let from_array = response
.match_indices('[')
.filter_map(|(start, _)| repair_json(&response[start..]))
.find_map(|json| verdicts_in(serde_json::from_str(&json).ok()?));
if let Some(verdicts) = from_array {
return Ok(verdicts);
}
// No array at all: a lone verdict object (a one-finding chunk).
response
.find('{')
.and_then(|start| repair_json(&response[start..]))
.and_then(|json| verdicts_in(serde_json::from_str(&json).ok()?))
.ok_or(TriageParseError::NoVerdicts)
}
/// The leading verdicts in a parsed answer: an array of objects, an object
/// wrapping one, or a single verdict object; `None` when there is no verdict.
fn verdicts_in(value: Value) -> Option<Vec<TriageResult>> {
let items = match value {
Value::Array(items) => items,
Value::Object(mut map) => {
// `Value::take` moves the array out, leaving `null` in its place.
match map
.values_mut()
.find(|v| is_object_array(v))
.map(Value::take)
{
Some(Value::Array(items)) => items,
_ if map.contains_key("action") => vec![Value::Object(map)],
_ => return None,
}
}
Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => return None,
};
// An array of anything else (`[1]` in prose) is not the answer.
if !items.first().is_some_and(Value::is_object) {
return None;
}
let verdicts: Vec<TriageResult> = items
.into_iter()
.map_while(|item| serde_json::from_value(item).ok())
.collect();
// No verdict at all: keep looking (an empty `[]` in prose is not the answer).
(!verdicts.is_empty()).then_some(verdicts)
}
/// `true` for a non-empty array whose elements are all objects.
fn is_object_array(value: &Value) -> bool {
matches!(value, Value::Array(items) if !items.is_empty() && items.iter().all(Value::is_object))
}
/// The JSON value `text` starts with (`[` or `{`), made parseable: anything
/// after its closing bracket is cut off, trailing commas are dropped, and an
/// array cut off mid-element is closed after its last complete element.
/// `None` when `text` does not start with a bracket, the brackets do not
/// match, or a cut-off value has no complete element to keep.
fn repair_json(text: &str) -> Option<String> {
let mut out = String::with_capacity(text.len() + 1);
// Closing brackets still expected, innermost last.
let mut open: Vec<char> = Vec::new();
let mut in_string = false;
let mut escaped = false;
// Length of `out` after the last complete element of the outermost array.
let mut last_element_end = None;
for c in text.chars() {
if out.is_empty() && c != '[' && c != '{' {
return None;
}
if in_string {
out.push(c);
if escaped {
escaped = false;
} else if c == '\\' {
escaped = true;
} else if c == '"' {
in_string = false;
}
continue;
}
match c {
'"' => in_string = true,
'[' => open.push(']'),
'{' => open.push('}'),
']' | '}' => {
drop_trailing_comma(&mut out);
if open.pop() != Some(c) {
return None;
}
match open.len() {
0 => {
out.push(c);
return Some(out);
}
1 if text.starts_with('[') => last_element_end = Some(out.len() + 1),
_ => {}
}
}
_ => {}
}
out.push(c);
}
// Cut off: keep the complete leading elements of an outermost array.
out.truncate(last_element_end?);
out.push(']');
Some(out)
}
/// Remove a `,` (and the whitespace after it) at the end of `json`.
fn drop_trailing_comma(json: &mut String) {
let trimmed = json.trim_end();
if trimmed.ends_with(',') {
json.truncate(trimmed.len() - 1);
}
}
/// Apply the model's `action` to `finding`; `true` when it passed triage.
///
/// A dismissed or low-confidence finding is kept as
@@ -373,18 +614,20 @@ fn upgrade_severity(
}
}
#[derive(serde::Deserialize)]
/// The model's verdict on one finding. Verdicts are matched to findings by
/// position, so the echoed `id` is not read (a model may echo the finding
/// number instead of the fingerprint). Every field is read leniently: a
/// `null`, a number sent as a string, or a missing field takes the default
/// rather than failing the whole verdict.
#[derive(Deserialize)]
struct TriageResult {
/// Finding fingerprint echoed back by the LLM (optional).
#[serde(default)]
#[allow(dead_code)]
id: String,
#[serde(default = "default_action")]
#[serde(default = "default_action", deserialize_with = "action_or_default")]
action: String,
#[serde(default)]
#[serde(default, deserialize_with = "lenient_number")]
confidence: f64,
#[serde(default)]
#[serde(default, deserialize_with = "null_as_empty")]
rationale: String,
#[serde(default)]
remediation: Option<String>,
}
@@ -392,6 +635,26 @@ fn default_action() -> String {
"confirm".to_string()
}
/// `action`, with `null` read as the default action.
fn action_or_default<'de, D: Deserializer<'de>>(deserializer: D) -> Result<String, D::Error> {
Ok(Option::<String>::deserialize(deserializer)?.unwrap_or_else(default_action))
}
/// A string field, with `null` read as empty.
fn null_as_empty<'de, D: Deserializer<'de>>(deserializer: D) -> Result<String, D::Error> {
Ok(Option::<String>::deserialize(deserializer)?.unwrap_or_default())
}
/// A number, also when sent as a string (`"7"`); `0` for `null` or anything
/// that is not a number.
fn lenient_number<'de, D: Deserializer<'de>>(deserializer: D) -> Result<f64, D::Error> {
Ok(match Value::deserialize(deserializer)? {
Value::Number(n) => n.as_f64().unwrap_or_default(),
Value::String(s) => s.trim().parse().unwrap_or_default(),
Value::Null | Value::Bool(_) | Value::Array(_) | Value::Object(_) => 0.0,
})
}
#[cfg(test)]
mod tests {
@@ -656,17 +919,107 @@ mod tests {
}
#[test]
fn triage_result_with_markdown_fences() {
// Simulate LLM wrapping response in markdown code fences
let raw = "```json\n{\"action\":\"upgrade\",\"confidence\":9,\"rationale\":\"critical\",\"remediation\":null}\n```";
let cleaned = raw
.trim()
.trim_start_matches("```json")
.trim_start_matches("```")
.trim_end_matches("```")
.trim();
let r: TriageResult = serde_json::from_str(cleaned).unwrap();
assert_eq!(r.action, "upgrade");
assert_eq!(r.confidence, 9.0);
fn triage_result_reads_nulls_numeric_strings_and_numeric_ids() {
let json = r#"{"id":3,"action":null,"confidence":"7","rationale":null,"remediation":null}"#;
let r: TriageResult = serde_json::from_str(json).unwrap();
assert_eq!(r.action, "confirm");
assert_eq!(r.confidence, 7.0);
assert_eq!(r.rationale, "");
assert!(r.remediation.is_none());
}
// ── Batch response parsing ───────────────────────────────────
fn actions(response: &str) -> Vec<String> {
parse_triage_response(response)
.unwrap()
.into_iter()
.map(|r| r.action)
.collect()
}
#[test]
fn parses_a_plain_array() {
let raw = r#"[{"action":"dismiss","confidence":1},{"action":"confirm","confidence":8}]"#;
assert_eq!(actions(raw), ["dismiss", "confirm"]);
}
#[test]
fn parses_a_fenced_array() {
let raw = "```json\n[{\"action\":\"upgrade\",\"confidence\":9}]\n```";
assert_eq!(actions(raw), ["upgrade"]);
}
#[test]
fn parses_an_array_between_prose() {
let raw = "Here is my triage [2 findings]:\n```\n[{\"action\":\"dismiss\",\
\"rationale\":\"uses buf[0] safely\"},{\"action\":\"confirm\"}]\n```\n\
Let me know if you need more.";
assert_eq!(actions(raw), ["dismiss", "confirm"]);
}
#[test]
fn parses_trailing_commas() {
let raw = r#"[{"action":"dismiss","confidence":2,}, {"action":"confirm"},]"#;
assert_eq!(actions(raw), ["dismiss", "confirm"]);
}
#[test]
fn parses_an_object_wrapping_the_array() {
let raw = r#"{"results": [{"action":"downgrade"},{"action":"confirm"}]}"#;
assert_eq!(actions(raw), ["downgrade", "confirm"]);
}
#[test]
fn parses_a_single_verdict_object() {
let raw = r#"```json
{"action":"dismiss","confidence":1,"rationale":"test code"}
```"#;
assert_eq!(actions(raw), ["dismiss"]);
}
#[test]
fn a_truncated_array_keeps_its_complete_verdicts() {
let raw = r#"[{"action":"dismiss","rationale":"a } in [text]"},{"action":"confirm"},{"action":"upg"#;
assert_eq!(actions(raw), ["dismiss", "confirm"]);
}
#[test]
fn a_verdict_that_cannot_be_read_ends_the_list() {
// The third verdict must not slide onto the second finding.
let raw = r#"[{"action":"dismiss"},{"action":["x"]},{"action":"confirm"}]"#;
assert_eq!(actions(raw), ["dismiss"]);
let raw = r#"[{"action":"dismiss"},null,{"action":"confirm"}]"#;
assert_eq!(actions(raw), ["dismiss"]);
}
#[test]
fn an_empty_array_in_prose_is_not_the_answer() {
let raw = r#"No dependencies []. Verdicts: [{"action":"confirm"}]"#;
assert_eq!(actions(raw), ["confirm"]);
}
#[test]
fn garbage_is_an_error() {
for raw in [
"",
"I cannot triage these findings.",
"[1, 2, 3]",
"{\"note\": \"nothing here\"}",
"[{\"action\":\"dismi",
] {
assert_eq!(
parse_triage_response(raw).err(),
Some(TriageParseError::NoVerdicts),
"{raw}"
);
}
}
#[test]
fn the_retry_halves_each_unanswered_range() {
assert_eq!(halves(&[Range { start: 0, end: 9 }]), [0..5, 5..9]);
assert_eq!(halves(&[3..4, 30..60]), [3..4, 30..45, 45..60]);
assert!(halves(&[]).is_empty());
}
}
+3
View File
@@ -47,6 +47,9 @@ pub(crate) struct ChatCompletionResponse {
#[derive(Deserialize)]
pub(crate) struct ChatChoice {
pub(crate) message: ChatResponseMessage,
/// Why the model stopped; `length` when it ran out of tokens.
#[serde(default)]
pub(crate) finish_reason: Option<String>,
}
#[derive(Deserialize)]
+11 -2
View File
@@ -30,9 +30,18 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Before anything can start a new run, close the runs the previous agent
// process left open when it stopped.
match lifecycle::recover_orphaned_runs(&agent.db_pool, chrono::Utc::now()).await {
let started_at = chrono::Utc::now();
match lifecycle::recover_orphaned_runs(&agent.db_pool, started_at).await {
Ok(0) => {}
Ok(closed) => tracing::warn!(closed, "closed runs left open by the previous agent"),
Ok(closed) => {
tracing::warn!(closed, "closed runs left open by the previous agent");
// The code scans among them start again, in the background.
let resume_agent = agent.clone();
tokio::spawn(async move {
let resumed = lifecycle::resume_interrupted_scans(&resume_agent, started_at).await;
tracing::info!(resumed, "scans interrupted by the restart started again");
});
}
Err(e) => tracing::error!("closing runs left open by the previous agent failed: {e}"),
}
@@ -124,9 +124,6 @@ pub(super) fn build_html_report(ctx: &ReportContext) -> String {
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Penetration Test Report — {target_name}</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Libre+Baskerville:ital,wght@0,400;0,700;1,400&family=Source+Sans+3:ital,wght@0,300;0,400;0,600;0,700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
{styles_html}
</head>
<body>
@@ -412,6 +409,29 @@ mod tests {
assert!(html.contains("https://example.com"));
}
#[test]
fn report_loads_nothing_from_a_third_party() {
let ctx = make_report_context(
vec![make_finding(Severity::High, "SQL Injection", true)],
vec![make_attack_node("sqlmap")],
);
let html = build_html_report(&ctx);
for needle in [
"googleapis",
"gstatic",
"preconnect",
"<link",
"@import",
"url(http",
"src=\"http",
] {
assert!(!html.contains(needle), "report contains {needle:?}");
}
// The fonts come from the reader's system, with generic fallbacks.
assert!(html.contains("--font-sans:"));
assert!(html.contains("sans-serif;"));
}
#[test]
fn report_contains_requester_info() {
let ctx = make_report_context(vec![], vec![]);
@@ -27,9 +27,11 @@ pub(super) fn styles() -> String {
--sev-medium: #a16207;
--sev-low: #1d4ed8;
--sev-info: #4b5563;
--font-serif: 'Libre Baskerville', 'Georgia', serif;
--font-sans: 'Source Sans 3', 'Helvetica Neue', sans-serif;
--font-mono: 'JetBrains Mono', 'Consolas', monospace;
/* System fonts only: the report is a standalone file and fetches
nothing from a font CDN. The named faces apply where installed. */
--font-serif: 'Libre Baskerville', Georgia, 'Times New Roman', serif;
--font-sans: 'Source Sans 3', system-ui, -apple-system, 'Segoe UI', 'Helvetica Neue', Arial, sans-serif;
--font-mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace;
}
body {
@@ -642,7 +644,7 @@ table.tools-table td:first-child {
border: 1px solid #fecaca;
border-left: 3px solid #dc2626;
padding: 8px 10px;
font-family: 'JetBrains Mono', monospace;
font-family: var(--font-mono);
font-size: 8pt;
line-height: 1.5;
white-space: pre-wrap;
@@ -655,7 +657,7 @@ table.tools-table td:first-child {
border: 1px solid #bbf7d0;
border-left: 3px solid #16a34a;
padding: 8px 10px;
font-family: 'JetBrains Mono', monospace;
font-family: var(--font-mono);
font-size: 8pt;
line-height: 1.5;
white-space: pre-wrap;
@@ -0,0 +1,367 @@
//! Build systems and platforms past their end of life, as findings.
//!
//! Prüfwerk does not read the dependencies of end-of-life build systems: an
//! Eclipse/ADT Android project (`default.properties` or `project.properties`
//! beside the manifest, no Gradle) or a Unity project without
//! `Packages/manifest.json` has no machine-readable list of what it ships, so
//! no complete SBOM and no CVE monitoring are possible. That is the finding,
//! and modernising the build is the remedy. The platform such a project builds
//! for is a finding of its own when it no longer gets security updates (an
//! old Android API level, an old Unity editor).
use std::path::Path;
use compliance_core::models::{ScanType, Severity};
use compliance_core::traits::{ScanOutput, Scanner};
use compliance_core::CoreError;
use crate::pipeline::dotnet::config::{into_finding, Hit};
/// The scanner name of these findings.
pub const SCANNER: &str = "build-lifecycle";
/// Below this Android API level (Android 10) no Android release receives
/// security updates any more.
const OLDEST_PATCHED_ANDROID_API: u32 = 29;
/// How deep projects are looked for.
const MAX_DEPTH: usize = 8;
/// Directories never searched: build output, dependencies, tool caches.
const SKIPPED_DIRS: &[&str] = &[
".git",
".gradle",
"build",
"bin",
"gen",
"node_modules",
"Library",
"Temp",
"Pods",
];
/// The checks over a tree.
#[derive(Debug, Default)]
pub struct BuildLifecycleScanner;
impl Scanner for BuildLifecycleScanner {
fn name(&self) -> &str {
SCANNER
}
fn scan_type(&self) -> ScanType {
ScanType::Sbom
}
#[tracing::instrument(skip_all)]
async fn scan(&self, repo_path: &Path, repo_id: &str) -> Result<ScanOutput, CoreError> {
let root = repo_path.to_path_buf();
let hits = tokio::task::spawn_blocking(move || check_tree(&root))
.await
.map_err(|e| CoreError::Scanner {
scanner: SCANNER.to_string(),
source: Box::new(e),
})?;
Ok(ScanOutput {
findings: hits
.into_iter()
.map(|hit| into_finding(repo_path, repo_id, hit))
.collect(),
sbom_entries: Vec::new(),
})
}
}
/// Every check over the tree under `root`.
pub(crate) fn check_tree(root: &Path) -> Vec<Hit> {
let mut hits = Vec::new();
let files = walkdir::WalkDir::new(root)
.min_depth(1)
.max_depth(MAX_DEPTH)
.sort_by_file_name()
.into_iter()
.filter_entry(|e| {
!(e.file_type().is_dir()
&& SKIPPED_DIRS.contains(&e.file_name().to_string_lossy().as_ref()))
})
.filter_map(Result::ok)
.filter(|e| e.file_type().is_file());
for entry in files {
let Some(dir) = entry.path().parent() else {
continue;
};
match entry.file_name().to_string_lossy().as_ref() {
"AndroidManifest.xml" => hits.extend(check_adt_project(root, dir)),
"ProjectVersion.txt" if dir.file_name().is_some_and(|n| n == "ProjectSettings") => {
if let Some(project) = dir.parent() {
hits.extend(check_unity_project(root, project));
}
}
_ => {}
}
}
hits
}
/// `path` relative to `root`, `/`-separated.
fn relative(root: &Path, path: &Path) -> String {
path.strip_prefix(root)
.unwrap_or(path)
.to_string_lossy()
.replace('\\', "/")
}
/// An Eclipse/ADT Android project in `dir`: its properties file names the
/// target API, and no Gradle build lists its dependencies.
fn check_adt_project(root: &Path, dir: &Path) -> Vec<Hit> {
let gradle = ["build.gradle", "build.gradle.kts"]
.iter()
.any(|f| dir.join(f).is_file());
let Some(properties) = ["project.properties", "default.properties"]
.iter()
.map(|f| dir.join(f))
.find(|p| p.is_file())
else {
return Vec::new();
};
if gradle {
return Vec::new();
}
let path = relative(root, &properties);
let text = std::fs::read_to_string(&properties).unwrap_or_default();
let target = text
.lines()
.enumerate()
.find(|(_, l)| l.trim_start().starts_with("target="));
let line = target.map_or(1, |(i, _)| u32::try_from(i + 1).unwrap_or(1));
let mut hits = vec![Hit {
scanner: SCANNER,
scan_type: ScanType::Sbom,
rule_id: "legacy-build-system-no-sbom",
title: "Legacy build system: the SBOM cannot be determined".to_string(),
description: format!(
"{} is an Eclipse/ADT Android project (no Gradle build). Its dependencies are not \
declared in any machine-readable form, so no complete SBOM and no CVE monitoring \
are possible for it.",
relative(root, dir)
),
remediation: "Migrate the project to Gradle with the Android Gradle Plugin (Android \
Studio imports ADT projects), declare its libraries as Gradle \
dependencies and commit a gradle.lockfile.",
severity: Severity::Medium,
cwe: "CWE-1104",
path: path.clone(),
line: Some(line),
}];
if let Some(api) = target.and_then(|(_, l)| android_api(l)) {
if api < OLDEST_PATCHED_ANDROID_API {
hits.push(Hit {
scanner: SCANNER,
scan_type: ScanType::Sbom,
rule_id: "android-sdk-end-of-support",
title: format!("Android API {api} receives no security updates"),
description: format!(
"{} builds against Android API {api}. Android releases below API \
{OLDEST_PATCHED_ANDROID_API} (Android 10) receive no security updates, \
so the platform the app is built for stays vulnerable.",
relative(root, dir)
),
remediation: "Raise the target and minimum API level to a supported Android \
release (after migrating the build to Gradle) and test on it.",
severity: Severity::Medium,
cwe: "CWE-1104",
path,
line: Some(line),
});
}
}
hits
}
/// The API level a `target=` line names: `target=android-11`, or
/// `target=Google Inc.:Google APIs:8`.
fn android_api(line: &str) -> Option<u32> {
let value = line.trim().strip_prefix("target=")?.trim();
value
.rsplit(['-', ':'])
.next()
.and_then(|n| n.trim().parse().ok())
}
/// A Unity project at `project`: without `Packages/manifest.json` its packages
/// are not declared; an editor version out of support is a finding of its own.
fn check_unity_project(root: &Path, project: &Path) -> Vec<Hit> {
let version_file = project.join("ProjectSettings/ProjectVersion.txt");
let path = relative(root, &version_file);
let version = std::fs::read_to_string(&version_file)
.unwrap_or_default()
.lines()
.find_map(|l| {
l.trim()
.strip_prefix("m_EditorVersion:")
.map(|v| v.trim().to_string())
})
.unwrap_or_default();
let mut hits = Vec::new();
if !project.join("Packages/manifest.json").is_file() {
hits.push(Hit {
scanner: SCANNER,
scan_type: ScanType::Sbom,
rule_id: "legacy-build-system-no-sbom",
title: "Legacy build system: the SBOM cannot be determined".to_string(),
description: format!(
"{} is a Unity project without Packages/manifest.json. The Unity packages and \
plug-ins it ships are not declared in any machine-readable form, so no \
complete SBOM and no CVE monitoring are possible for it.",
relative(root, project)
),
remediation: "Move the project to a current Unity LTS release with the Unity \
Package Manager, and commit its Packages/ folder (manifest.json \
and packages-lock.json).",
severity: Severity::Medium,
cwe: "CWE-1104",
path: path.clone(),
line: Some(1),
});
}
if unity_out_of_support(&version) {
hits.push(Hit {
scanner: SCANNER,
scan_type: ScanType::Sbom,
rule_id: "unity-editor-end-of-support",
title: format!("Unity {version} receives no security updates"),
description: format!(
"{} is built with Unity {version}, a release Unity no longer supports. The \
Unity runtime is part of the shipped app, and security fixes are only \
published for supported releases.",
relative(root, project)
),
remediation: "Upgrade the project to a supported Unity LTS release.",
severity: Severity::Medium,
cwe: "CWE-1104",
path,
line: Some(1),
});
}
hits
}
/// Whether a Unity editor version is certainly out of support: every release
/// before 2021, and the tech-stream releases of 2021 to 2023 (only the LTS
/// release of a year, `.3`, was supported beyond the next one). Later LTS
/// releases are not judged here.
fn unity_out_of_support(version: &str) -> bool {
let mut parts = version.split('.');
let (Some(year), Some(minor)) = (
parts.next().and_then(|y| y.parse::<u32>().ok()),
parts.next().and_then(|m| m.parse::<u32>().ok()),
) else {
return false;
};
match year {
2000..=2020 => true,
2021..=2023 => minor != 3,
_ => false,
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
/// A scratch tree holding `files`, removed on drop.
struct Tree(std::path::PathBuf);
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn tree(files: &[(&str, &str)]) -> Tree {
let dir = std::env::temp_dir().join(format!("cs-buildlc-{}", uuid::Uuid::new_v4()));
for (path, content) in files {
let full = dir.join(path);
std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir");
std::fs::write(full, content).expect("write");
}
Tree(dir)
}
fn hits(t: &Tree) -> Vec<String> {
check_tree(&t.0)
.into_iter()
.map(|h| format!("{} {}:{}", h.rule_id, h.path, h.line.unwrap_or(0)))
.collect()
}
#[test]
fn the_pilot_shape_gives_legacy_build_and_lifecycle_findings() {
let t = tree(&[
("Mobile App/AndroidManifest.xml", "<manifest/>"),
(
"Mobile App/default.properties",
"# generated\nsplit.density=false\ntarget=android-8\n",
),
("Tablet App/AndroidManifest.xml", "<manifest/>"),
(
"Tablet App/project.properties",
"target=Google Inc.:Google APIs:11\n",
),
(
"Unity/ProjectSettings/ProjectVersion.txt",
"m_EditorVersion: 2019.2.4f1\n",
),
]);
assert_eq!(
hits(&t),
[
"legacy-build-system-no-sbom Mobile App/default.properties:3",
"android-sdk-end-of-support Mobile App/default.properties:3",
"legacy-build-system-no-sbom Tablet App/project.properties:1",
"android-sdk-end-of-support Tablet App/project.properties:1",
"legacy-build-system-no-sbom Unity/ProjectSettings/ProjectVersion.txt:1",
"unity-editor-end-of-support Unity/ProjectSettings/ProjectVersion.txt:1",
]
);
}
#[test]
fn modern_builds_give_nothing() {
let t = tree(&[
("app/src/main/AndroidManifest.xml", "<manifest/>"),
("app/build.gradle", "android { compileSdk 34 }"),
// An ADT layout that has moved to Gradle keeps its properties.
("legacy/AndroidManifest.xml", "<manifest/>"),
("legacy/project.properties", "target=android-34"),
(
"legacy/build.gradle",
"apply plugin: 'com.android.application'",
),
(
"game/ProjectSettings/ProjectVersion.txt",
"m_EditorVersion: 6000.0.23f1\n",
),
("game/Packages/manifest.json", "{\"dependencies\":{}}"),
]);
assert!(hits(&t).is_empty(), "{:?}", hits(&t));
}
#[test]
fn unity_support_is_judged_conservatively() {
assert!(unity_out_of_support("2019.2.4f1"));
assert!(unity_out_of_support("2020.3.48f1"));
assert!(unity_out_of_support("2021.2.19f1"));
assert!(unity_out_of_support("2023.1.20f1"));
assert!(!unity_out_of_support("2022.3.50f1"));
assert!(!unity_out_of_support("6000.0.23f1"));
assert!(!unity_out_of_support("garbage"));
}
#[test]
fn android_targets_are_read_in_both_forms() {
assert_eq!(android_api("target=android-8"), Some(8));
assert_eq!(android_api("target=Google Inc.:Google APIs:11"), Some(11));
assert_eq!(android_api("target=android-L"), None);
}
}
+298 -61
View File
@@ -1,3 +1,5 @@
use std::collections::{BTreeSet, HashMap};
use compliance_core::models::{CveAlert, CveSource, SbomEntry, VulnRef};
use compliance_core::CoreError;
@@ -30,72 +32,137 @@ impl CveScanner {
}
}
/// Match every SBOM entry with a purl against OSV, attaching the
/// advisories to the entries and returning one alert per advisory.
///
/// # Returns
///
/// The alerts, and in [`CveLookup::unchecked`] the components OSV could not
/// speak for: those of a package manager OSV has no advisories for
/// (CocoaPods), and those of a batch OSV refused. Either kind is unknown,
/// not free of CVEs.
///
/// # Errors
///
/// Returns `CoreError::Http` when OSV cannot be reached or its answer
/// cannot be read.
#[tracing::instrument(skip_all)]
pub async fn scan_dependencies(
&self,
repo_id: &str,
entries: &mut [SbomEntry],
) -> Result<Vec<CveAlert>, CoreError> {
) -> Result<CveLookup, CoreError> {
tracing::info!("scanning {} SBOM entries for known CVEs", entries.len());
let mut alerts = Vec::new();
let mut lookup = CveLookup::default();
// Batch query OSV.dev
let osv_results = self.query_osv_batch(entries).await?;
for (idx, vulns) in osv_results.into_iter().enumerate() {
if let Some(entry) = entries.get_mut(idx) {
for vuln in &vulns {
entry.known_vulnerabilities.push(VulnRef {
id: vuln.id.clone(),
source: "osv".to_string(),
severity: vuln.severity.clone(),
url: Some(format!("https://osv.dev/vulnerability/{}", vuln.id)),
});
let (osv_results, refused) = self.query_osv_batch(entries).await?;
for (entry, vulns) in entries.iter_mut().zip(osv_results) {
for vuln in vulns {
entry.known_vulnerabilities.push(VulnRef {
id: vuln.id.clone(),
source: "osv".to_string(),
severity: vuln.severity,
url: Some(format!("https://osv.dev/vulnerability/{}", vuln.id)),
});
let mut alert = CveAlert::new(
vuln.id,
repo_id.to_string(),
entry.name.clone(),
entry.version.clone(),
CveSource::Osv,
);
alert.summary = vuln.summary;
lookup.alerts.push(alert);
}
}
lookup.unchecked = entries
.iter()
.enumerate()
.filter(|(i, e)| refused.contains(i) || without_osv_advisories(e))
.map(|(_, e)| format!("{} {}", e.name, e.version))
.collect();
let mut alert = CveAlert::new(
vuln.id.clone(),
repo_id.to_string(),
entry.name.clone(),
entry.version.clone(),
CveSource::Osv,
);
alert.summary = vuln.summary.clone();
alerts.push(alert);
// The batch answer names only the advisory: read each one once for
// its summary, severity, CVE alias and fixed versions.
let ids: BTreeSet<String> = lookup.alerts.iter().map(|a| a.cve_id.clone()).collect();
let details = self.osv_details(ids).await;
let purls: HashMap<(String, String), Option<String>> = entries
.iter()
.map(|e| ((e.name.clone(), e.version.clone()), e.purl.clone()))
.collect();
for alert in &mut lookup.alerts {
let Some(detail) = details.get(&alert.cve_id) else {
continue;
};
let purl = purls
.get(&(
alert.affected_package.clone(),
alert.affected_version.clone(),
))
.cloned()
.flatten();
alert.summary = detail.summary.clone().or(alert.summary.take());
alert.severity = detail.severity.clone();
alert.aliases = detail.aliases.clone();
alert.fixed_versions = detail.fixed_for(purl.as_deref(), &alert.affected_package);
}
for entry in entries.iter_mut() {
for vuln in &mut entry.known_vulnerabilities {
if let Some(detail) = details.get(&vuln.id) {
vuln.severity = detail.severity.clone().or(vuln.severity.take());
}
}
}
// Enrich with NVD CVSS scores
for alert in &mut alerts {
if let Ok(Some(cvss)) = self.query_nvd(&alert.cve_id).await {
// NVD's CVSS score where the advisory itself rates nothing (NVD is
// rate-limited, so it is asked only then).
for alert in lookup.alerts.iter_mut().filter(|a| a.severity.is_none()) {
if let Ok(Some(cvss)) = self.query_nvd(alert.cve()).await {
alert.cvss_score = Some(cvss);
}
}
Ok(alerts)
Ok(lookup)
}
async fn query_osv_batch(&self, entries: &[SbomEntry]) -> Result<Vec<Vec<OsvVuln>>, CoreError> {
/// Ask OSV about every entry it has advisories for.
///
/// # Returns
///
/// The advisories of each entry, in the order of `entries` (empty for an
/// entry that was not asked about), and the indices of the entries whose
/// batch OSV refused.
///
/// # Errors
///
/// Returns `CoreError::Http` when OSV cannot be reached or its answer
/// cannot be read.
async fn query_osv_batch(
&self,
entries: &[SbomEntry],
) -> Result<(Vec<Vec<OsvVuln>>, Vec<usize>), CoreError> {
const OSV_BATCH_SIZE: usize = 500;
let queries: Vec<_> = entries
let mut results: Vec<Vec<OsvVuln>> = std::iter::repeat_with(Vec::new)
.take(entries.len())
.collect();
let mut refused = Vec::new();
// Each query keeps the index of its entry: an entry without a purl is
// not asked about, and must not shift the answers onto its neighbours.
let queries: Vec<(usize, &str)> = entries
.iter()
.filter_map(|e| {
e.purl.as_ref().map(|purl| {
serde_json::json!({
"package": { "purl": purl }
})
})
})
.enumerate()
.filter(|(_, e)| !without_osv_advisories(e))
.filter_map(|(i, e)| e.purl.as_deref().map(|purl| (i, purl)))
.collect();
if queries.is_empty() {
return Ok(Vec::new());
}
let mut all_vulns: Vec<Vec<OsvVuln>> = Vec::with_capacity(queries.len());
for chunk in queries.chunks(OSV_BATCH_SIZE) {
let body = serde_json::json!({ "queries": chunk });
let body = serde_json::json!({
"queries": chunk
.iter()
.map(|(_, purl)| serde_json::json!({ "package": { "purl": purl } }))
.collect::<Vec<_>>()
});
let resp = self
.http
@@ -112,8 +179,7 @@ impl CveScanner {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
tracing::warn!("OSV.dev returned {status}: {body}");
// Push empty results for this chunk so indices stay aligned
all_vulns.extend(std::iter::repeat_with(Vec::new).take(chunk.len()));
refused.extend(chunk.iter().map(|(i, _)| *i));
continue;
}
@@ -122,24 +188,54 @@ impl CveScanner {
CoreError::Http(format!("Failed to parse OSV.dev response: {e}"))
})?;
let chunk_vulns = result.results.into_iter().map(|r| {
r.vulns
.unwrap_or_default()
.into_iter()
.map(|v| OsvVuln {
id: v.id,
summary: v.summary,
severity: v.database_specific.and_then(|d| {
d.get("severity").and_then(|s| s.as_str()).map(String::from)
}),
})
.collect()
});
all_vulns.extend(chunk_vulns);
for ((index, _), answer) in chunk.iter().zip(result.results) {
if let Some(slot) = results.get_mut(*index) {
*slot = answer
.vulns
.unwrap_or_default()
.into_iter()
.map(|v| OsvVuln {
id: v.id,
summary: v.summary,
severity: v.database_specific.and_then(|d| {
d.get("severity").and_then(|s| s.as_str()).map(String::from)
}),
})
.collect();
}
}
}
Ok(all_vulns)
Ok((results, refused))
}
/// OSV's record of each advisory in `ids`, read concurrently. An
/// advisory OSV cannot return is left out: its alert keeps what the batch
/// answer said.
async fn osv_details(&self, ids: BTreeSet<String>) -> HashMap<String, OsvDetail> {
use futures_util::StreamExt;
const CONCURRENT_LOOKUPS: usize = 8;
futures_util::stream::iter(ids)
.map(|id| async move {
let url = format!("https://api.osv.dev/v1/vulns/{id}");
let record: serde_json::Value = self
.http
.get(&url)
.send()
.await
.ok()?
.error_for_status()
.ok()?
.json()
.await
.ok()?;
Some((id, OsvDetail::parse(&record)))
})
.buffer_unordered(CONCURRENT_LOOKUPS)
.filter_map(|detail| async move { detail })
.collect()
.await
}
async fn query_nvd(&self, cve_id: &str) -> Result<Option<f64>, CoreError> {
@@ -280,7 +376,7 @@ impl CveScanner {
}
}
/// What an NVD lookup found, and what it could not check.
/// What a CVE lookup found, and what it could not check.
#[derive(Debug, Default)]
pub struct CveLookup {
/// The CVEs that affect the components in use.
@@ -326,6 +422,92 @@ fn record_nvd(
.collect()
}
/// What an OSV advisory record says beyond its id.
#[derive(Debug, Default, Clone, PartialEq)]
struct OsvDetail {
summary: Option<String>,
/// The advisory's own rating (`CRITICAL`, `HIGH`, `MODERATE`, `LOW`), as
/// GitHub's advisories carry it.
severity: Option<String>,
aliases: Vec<String>,
/// Per affected package (its versionless purl and name), the versions
/// that fix it.
affected: Vec<(Option<String>, String, Vec<String>)>,
}
impl OsvDetail {
/// Read an OSV vulnerability record.
fn parse(record: &serde_json::Value) -> Self {
let text = |v: &serde_json::Value| v.as_str().map(str::to_string);
let affected = record["affected"]
.as_array()
.into_iter()
.flatten()
.map(|a| {
let fixed = a["ranges"]
.as_array()
.into_iter()
.flatten()
.flat_map(|r| r["events"].as_array().into_iter().flatten())
.filter_map(|e| text(&e["fixed"]))
.collect::<Vec<_>>();
(
text(&a["package"]["purl"]),
text(&a["package"]["name"]).unwrap_or_default(),
fixed,
)
})
.collect();
Self {
summary: text(&record["summary"]).filter(|s| !s.is_empty()),
severity: text(&record["database_specific"]["severity"]),
aliases: record["aliases"]
.as_array()
.into_iter()
.flatten()
.filter_map(text)
.collect(),
affected,
}
}
/// The fixed versions for the package with `purl` (or `name`), at most a
/// few: an advisory can list one per release line.
fn fixed_for(&self, purl: Option<&str>, name: &str) -> Vec<String> {
const MAX_FIXED: usize = 3;
let base = purl.map(|p| p.split('@').next().unwrap_or(p));
let mut out: Vec<String> = self
.affected
.iter()
.filter(|(p, n, _)| match (base, p.as_deref()) {
(Some(base), Some(p)) => p == base,
_ => {
n == name
|| n.ends_with(&format!(":{name}"))
|| n.ends_with(&format!("/{name}"))
}
})
.flat_map(|(_, _, fixed)| fixed.iter().cloned())
.collect();
out.dedup();
out.truncate(MAX_FIXED);
out
}
}
/// Purl types of package managers OSV publishes no advisories for. Asking
/// about them returns nothing, which must not read as "no CVEs".
const PURL_TYPES_WITHOUT_OSV: &[&str] = &["pkg:cocoapods/"];
/// Whether `entry` belongs to a package manager OSV has no advisories for.
fn without_osv_advisories(entry: &SbomEntry) -> bool {
entry.package_manager == crate::pipeline::sbom::unity::UNITY_MANAGER
|| entry
.purl
.as_deref()
.is_some_and(|purl| PURL_TYPES_WITHOUT_OSV.iter().any(|t| purl.starts_with(t)))
}
/// The CODESYS runtime component (name + version) from an SBOM, if present. The
/// runtime carries the version CODESYS advisories key off; the internal library
/// components do not.
@@ -367,6 +549,61 @@ mod tests {
SbomEntry::new("t".into(), name.into(), ver.into(), pm.into())
}
#[test]
fn an_osv_record_gives_severity_alias_and_the_packages_fix() {
let record = serde_json::json!({
"id": "GHSA-3cqm-mf7h-prrj",
"summary": "Square OkHttp can accept the wrong certificate",
"aliases": ["A-171980069", "CVE-2021-0341"],
"database_specific": { "severity": "HIGH", "cwe_ids": ["CWE-295"] },
"affected": [
{
"package": {
"name": "com.squareup.okhttp3:okhttp",
"ecosystem": "Maven",
"purl": "pkg:maven/com.squareup.okhttp3/okhttp"
},
"ranges": [{ "type": "ECOSYSTEM", "events": [{ "introduced": "0" }, { "fixed": "4.9.2" }] }]
},
{
"package": { "name": "com.example:other", "ecosystem": "Maven" },
"ranges": [{ "type": "ECOSYSTEM", "events": [{ "introduced": "0" }, { "fixed": "9.9" }] }]
}
]
});
let detail = OsvDetail::parse(&record);
assert_eq!(detail.severity.as_deref(), Some("HIGH"));
assert_eq!(
detail.fixed_for(
Some("pkg:maven/com.squareup.okhttp3/okhttp@3.12.0"),
"okhttp"
),
["4.9.2"]
);
// Without a purl the package name decides.
assert_eq!(detail.fixed_for(None, "okhttp"), ["4.9.2"]);
let mut alert = CveAlert::new(
"GHSA-3cqm-mf7h-prrj".into(),
"t".into(),
"okhttp".into(),
"3.12.0".into(),
CveSource::Osv,
);
alert.aliases = detail.aliases;
assert_eq!(alert.cve(), "CVE-2021-0341");
}
#[test]
fn cocoapods_components_are_not_asked_about_but_reported_unchecked() {
let mut pod = entry("AFNetworking", "2.5.1", "cocoapods");
pod.purl = Some("pkg:cocoapods/AFNetworking@2.5.1".into());
let mut jar = entry("okhttp", "3.12.0", "maven");
jar.purl = Some("pkg:maven/com.squareup.okhttp3/okhttp@3.12.0".into());
assert!(without_osv_advisories(&pod));
assert!(!without_osv_advisories(&jar));
assert!(!without_osv_advisories(&entry("lwIP", "2.1.2", "embedded")));
}
#[test]
fn finds_the_codesys_runtime_component() {
let entries = vec![
+483
View File
@@ -0,0 +1,483 @@
//! Known vulnerabilities in a managed repository's dependencies, as issues.
//!
//! For a target from a managed git source (#439), every critical or high CVE
//! in its components becomes one issue per package and CVE, labelled like the
//! finding issues plus `cve`, with the fixed version where the advisory names
//! one. When a later complete scan no longer finds the CVE (the dependency was
//! updated or removed), the issue is closed with a comment; when it comes back,
//! it is reopened.
use std::collections::{BTreeMap, HashMap};
use mongodb::bson::doc;
use compliance_core::models::notification::{parse_severity, NotificationSeverity};
use compliance_core::models::{CveAlert, IssueStatus, TrackerIssue};
use crate::database::Database;
use crate::error::AgentError;
use crate::pipeline::tracker_dispatch::TrackerDispatch;
use crate::trackers::gitea::{pruefwerk_labels, LABEL_CRA_ANNEX_I, LABEL_CVE, LABEL_PRUEFWERK};
/// The CRA requirements a known vulnerability in a component bears on.
const CVE_CONTROLS: [&str; 2] = ["cra-ai-22", "cra-ai-33"];
/// Where the issues of one target go.
pub(crate) struct CveIssueTarget<'a> {
pub db: &'a Database,
pub tracker: &'a TrackerDispatch,
pub owner: &'a str,
pub repo: &'a str,
/// The scanned target (`CveAlert::repo_id`).
pub target_id: &'a str,
/// The dashboard's public URL, for a link back; empty for none.
pub dashboard: &'a str,
}
/// What [`sync_cve_issues`] did.
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct CveIssueCounts {
pub created: u32,
pub reopened: u32,
pub closed: u32,
}
/// The key a CVE issue is stored under (`TrackerIssue::finding_id`): one per
/// target, package and CVE, so another version of the same package does not
/// open a second issue.
fn issue_key(target_id: &str, alert: &CveAlert) -> String {
format!("cve:{target_id}:{}:{}", alert.affected_package, alert.cve())
}
/// A severity as the `severity:` labels name it.
fn severity_name(severity: &NotificationSeverity) -> &'static str {
match severity {
NotificationSeverity::Critical => "critical",
NotificationSeverity::High => "high",
NotificationSeverity::Medium => "medium",
NotificationSeverity::Low => "low",
}
}
/// Whether an alert is severe enough for an issue.
fn issue_worthy(alert: &CveAlert) -> bool {
matches!(
parse_severity(alert.severity.as_deref(), alert.cvss_score),
NotificationSeverity::Critical | NotificationSeverity::High
)
}
/// Open, reopen and close the CVE issues of one target to match `alerts`.
///
/// # Arguments
///
/// * `target` - where the issues go
/// * `alerts` - every CVE the scan found in the target's components
/// * `complete` - whether every component was matched; only then is a CVE
/// that is missing from `alerts` known to be gone, and its issue closed
///
/// # Errors
///
/// A database error. A tracker call that fails is logged and skipped.
pub(crate) async fn sync_cve_issues(
target: &CveIssueTarget<'_>,
alerts: &[CveAlert],
complete: bool,
) -> Result<CveIssueCounts, AgentError> {
let prefix = format!("cve:{}:", target.target_id);
let mut existing: HashMap<String, TrackerIssue> = HashMap::new();
let mut cursor = target
.db
.tracker_issues()
.find(doc! { "finding_id": { "$regex": format!("^{}", regex::escape(&prefix)) } })
.await?;
while cursor.advance().await? {
let issue = cursor.deserialize_current()?;
existing.insert(issue.finding_id.clone(), issue);
}
// Every CVE still present, and of those the ones worth an issue (the
// first version of a package stands for it).
let present: BTreeMap<String, &CveAlert> = alerts
.iter()
.map(|a| (issue_key(target.target_id, a), a))
.rev()
.collect();
let label_ids = gitea_label_ids(target).await;
let mut counts = CveIssueCounts::default();
for (key, alert) in present.iter().filter(|(_, a)| issue_worthy(a)) {
match existing.get(key) {
Some(issue) if is_closed(&issue.status) => {
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?;
counts.reopened += 1;
}
}
Some(_) => {}
None => {
if create(target, key, alert, label_ids.as_ref()).await? {
counts.created += 1;
}
}
}
}
if complete {
for (key, issue) in &existing {
if present.contains_key(key) || is_closed(&issue.status) {
continue;
}
let comment = "**Prüfwerk:** Die Prüfung findet diese Schwachstelle nicht mehr: Die Abhängigkeit wurde aktualisiert oder entfernt.\n\nThe scan no longer finds this vulnerability: the dependency was updated or removed.";
if set_state(target, issue, comment, "closed").await {
record(target.db, issue, IssueStatus::Closed).await?;
counts.closed += 1;
}
}
}
Ok(counts)
}
/// 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>> {
let TrackerDispatch::Gitea(gitea) = target.tracker else {
return None;
};
match gitea
.ensure_labels(target.owner, target.repo, &pruefwerk_labels())
.await
{
Ok(ids) => Some(ids),
Err(e) => {
tracing::warn!(error = %e, "could not ensure the Prüfwerk labels for CVE issues");
None
}
}
}
/// Open the issue for `alert` and store it under `key`.
async fn create(
target: &CveIssueTarget<'_>,
key: &str,
alert: &CveAlert,
label_ids: Option<&HashMap<String, i64>>,
) -> Result<bool, AgentError> {
let severity = severity_name(&parse_severity(alert.severity.as_deref(), alert.cvss_score));
let title = format!(
"[CVE] {}@{}: {}",
alert.affected_package,
alert.affected_version,
alert.cve()
);
let body = issue_body(alert, severity, target);
let names = [
LABEL_PRUEFWERK.to_string(),
LABEL_CRA_ANNEX_I.to_string(),
format!("severity:{severity}"),
LABEL_CVE.to_string(),
];
let result = match (target.tracker, label_ids) {
(TrackerDispatch::Gitea(gitea), Some(ids)) => {
let ids: Vec<i64> = names.iter().filter_map(|n| ids.get(n).copied()).collect();
gitea
.create_issue_with_label_ids(target.owner, target.repo, &title, &body, &ids)
.await
}
(tracker, _) => {
tracker
.create_issue(target.owner, target.repo, &title, &body, &names)
.await
}
};
match result {
Ok(mut issue) => {
issue.finding_id = key.to_string();
target.db.tracker_issues().insert_one(&issue).await?;
Ok(true)
}
Err(e) => {
tracing::warn!(key, error = %e, "could not open the CVE issue");
Ok(false)
}
}
}
/// The issue text: what is affected, how badly, what fixes it, and the CRA
/// requirements concerned.
fn issue_body(alert: &CveAlert, severity: &str, target: &CveIssueTarget<'_>) -> String {
let mut body = format!(
"**{}** betrifft / affects **{} {}**.\n",
alert.cve(),
alert.affected_package,
alert.affected_version
);
if let Some(summary) = alert.summary.as_deref().filter(|s| !s.is_empty()) {
body.push_str(&format!("\n{summary}\n"));
}
body.push_str(&format!("\n- Schweregrad / Severity: {severity}"));
if let Some(score) = alert.cvss_score {
body.push_str(&format!(" (CVSS {score:.1})"));
}
body.push('\n');
match alert.fixed_versions.as_slice() {
[] => body
.push_str("- Behoben in / Fixed in: keine Version bekannt / no fixed version known\n"),
fixed => body.push_str(&format!("- Behoben in / Fixed in: {}\n", fixed.join(", "))),
}
body.push_str(&format!(
"- Advisory: https://osv.dev/vulnerability/{}\n",
alert.cve_id
));
body.push_str("\n### CRA\n\n");
let map = control_map::ControlMap::cra().ok();
for id in CVE_CONTROLS {
let title = map
.as_ref()
.and_then(|m| m.coverage(id))
.map(|c| c.title.clone())
.unwrap_or_default();
body.push_str(&format!("- {id} — {title} (Annex I)\n"));
}
let dashboard = target.dashboard.trim_end_matches('/');
if dashboard.starts_with("https://") {
body.push_str(&format!(
"\n[In Prüfwerk öffnen / Open in Prüfwerk]({dashboard}/targets/{})\n",
target.target_id
));
}
body
}
/// Comment on `issue` and set it to `state`; whether both worked.
async fn set_state(
target: &CveIssueTarget<'_>,
issue: &TrackerIssue,
comment: &str,
state: &str,
) -> bool {
let number = issue.external_id.as_str();
let done = async {
target
.tracker
.add_comment(target.owner, target.repo, number, comment)
.await?;
target
.tracker
.update_issue_status(target.owner, target.repo, number, state)
.await
};
match done.await {
Ok(()) => true,
Err(e) => {
tracing::warn!(issue = number, error = %e, "could not update the CVE issue");
false
}
}
}
/// Store an issue's new state.
async fn record(
db: &Database,
issue: &TrackerIssue,
status: IssueStatus,
) -> Result<(), AgentError> {
let Some(id) = issue.id else {
return Ok(());
};
let status = mongodb::bson::to_bson(&status).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() } },
)
.await?;
Ok(())
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use std::sync::{Arc, Mutex};
use axum::extract::{Path, State};
use axum::routing::{get, patch, post};
use axum::{Json, Router};
use compliance_core::models::CveSource;
use compliance_core::NetGuard;
use secrecy::SecretString;
use crate::trackers::gitea::GiteaTracker;
/// The calls a fake Gitea received.
type Calls = Arc<Mutex<Vec<String>>>;
async fn fake_gitea(calls: Calls) -> String {
async fn labels() -> Json<serde_json::Value> {
Json(serde_json::json!(pruefwerk_labels()
.iter()
.enumerate()
.map(|(i, l)| serde_json::json!({ "id": i as i64 + 1, "name": l.name, "color": "fff" }))
.collect::<Vec<_>>()))
}
async fn create(
State(calls): State<Calls>,
Json(body): Json<serde_json::Value>,
) -> (axum::http::StatusCode, Json<serde_json::Value>) {
let mut calls = calls.lock().unwrap();
let number = 100 + calls.len();
calls.push(format!(
"create {number}: {} labels={}",
body["title"].as_str().unwrap_or_default(),
body["labels"]
));
calls.push(format!(
"body {number}: {}",
body["body"].as_str().unwrap_or_default()
));
(
axum::http::StatusCode::CREATED,
Json(
serde_json::json!({ "number": number, "html_url": format!("https://git/i/{number}") }),
),
)
}
async fn comment(
State(calls): State<Calls>,
Path((_o, _r, n)): Path<(String, String, String)>,
) -> axum::http::StatusCode {
calls.lock().unwrap().push(format!("comment {n}"));
axum::http::StatusCode::CREATED
}
async fn state(
State(calls): State<Calls>,
Path((_o, _r, n)): Path<(String, String, String)>,
Json(body): Json<serde_json::Value>,
) -> Json<serde_json::Value> {
calls
.lock()
.unwrap()
.push(format!("state {n}: {}", body["state"]));
Json(serde_json::json!({}))
}
let app = Router::new()
.route("/api/v1/repos/{o}/{r}/labels", get(labels))
.route("/api/v1/repos/{o}/{r}/issues", post(create))
.route("/api/v1/repos/{o}/{r}/issues/{n}/comments", post(comment))
.route("/api/v1/repos/{o}/{r}/issues/{n}", patch(state))
.with_state(calls);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
format!("http://{addr}")
}
fn alert(package: &str, version: &str, id: &str, severity: &str) -> CveAlert {
let mut a = CveAlert::new(
id.into(),
"target-1".into(),
package.into(),
version.into(),
CveSource::Osv,
);
a.severity = Some(severity.into());
a.aliases = vec!["CVE-2021-0341".into()];
a.fixed_versions = vec!["4.9.2".into()];
a.summary = Some("Square OkHttp can accept the wrong certificate".into());
a
}
#[tokio::test]
async fn severe_cves_open_issues_that_close_when_the_dependency_is_fixed() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"cveiss_{}",
&uuid::Uuid::new_v4().simple().to_string()[..10]
);
let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP cve_issues: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id("cve-issues").await.unwrap();
let calls: Calls = Arc::default();
let base = fake_gitea(calls.clone()).await;
let gitea =
GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap();
let tracker = TrackerDispatch::Gitea(gitea);
let target = CveIssueTarget {
db: &db,
tracker: &tracker,
owner: "kunde",
repo: "app",
target_id: "target-1",
dashboard: "https://pruefwerk.example",
};
let okhttp = alert("okhttp", "3.12.0", "GHSA-3cqm-mf7h-prrj", "HIGH");
let minor = alert("gson", "2.8.8", "GHSA-4jrv-ppp4-jm57", "MODERATE");
// A high CVE opens one issue; a moderate one opens none.
let counts = sync_cve_issues(&target, &[okhttp.clone(), minor.clone()], true)
.await
.unwrap();
assert_eq!(
counts,
CveIssueCounts {
created: 1,
..Default::default()
}
);
{
let calls = calls.lock().unwrap();
assert!(calls[0].starts_with("create 100: [CVE] okhttp@3.12.0: CVE-2021-0341 labels=["));
// pruefwerk (1), cra:annex-i (2), severity:high (4), cve (7).
assert!(calls[0].ends_with("labels=[1,2,4,7]"), "{}", calls[0]);
assert!(calls[1].contains("Fixed in: 4.9.2"));
assert!(calls[1].contains("cra-ai-22"));
assert!(calls[1].contains("https://pruefwerk.example/targets/target-1"));
}
// The same scan again: nothing new. An incomplete scan closes nothing.
assert_eq!(
sync_cve_issues(&target, std::slice::from_ref(&okhttp), true)
.await
.unwrap(),
CveIssueCounts::default()
);
assert_eq!(
sync_cve_issues(&target, &[], false).await.unwrap(),
CveIssueCounts::default()
);
// The dependency is updated: the complete scan finds it no more.
assert_eq!(
sync_cve_issues(&target, &[minor], true).await.unwrap(),
CveIssueCounts {
closed: 1,
..Default::default()
}
);
assert_eq!(
calls.lock().unwrap().last().unwrap(),
"state 100: \"closed\""
);
// It comes back: reopened, not opened twice.
assert_eq!(
sync_cve_issues(&target, &[okhttp], true).await.unwrap(),
CveIssueCounts {
reopened: 1,
..Default::default()
}
);
assert_eq!(calls.lock().unwrap().last().unwrap(), "state 100: \"open\"");
pool.drop_tenant("cve-issues").await.ok();
}
}
@@ -0,0 +1,711 @@
//! .NET configuration, key files and target frameworks (#445).
//!
//! Three kinds of findings, each from files alone:
//!
//! - **configuration** (`dotnet-config`): `web.config`, `app.config` and other
//! `*.config` files with a clear-text password, debug compilation, detailed
//! errors shown to everyone, cookies without `requireSSL`/`httpOnlyCookies`,
//! or a WCF binding without transport security;
//! - **key and publish files** (`secret-files`): signing keys (`.snk`, `.pfx`,
//! `.p12`), Java/Android keystores (`.jks`, `.keystore`) and publish
//! profiles (`.pubxml`, `.pubxml.user`, `.publishsettings`) committed to
//! the repository;
//! - **target frameworks past their end of support** (`dotnet-lifecycle`).
//!
//! Build output, restored packages and IDE state (`bin/`, `obj/`,
//! `packages/`, `.vs/`) are not read.
use std::path::Path;
use compliance_core::models::{Finding, ScanType, Severity};
use compliance_core::traits::{ScanOutput, Scanner};
use compliance_core::CoreError;
use super::{inventory, line_of, parse_xml, read_text, relative, walk_sources};
use crate::pipeline::dedup;
/// The scanner name of configuration findings.
pub const CONFIG_SCANNER: &str = "dotnet-config";
/// The scanner name of committed key and publish files.
pub const SECRET_FILES_SCANNER: &str = "secret-files";
/// The scanner name of end-of-support target frameworks.
pub const LIFECYCLE_SCANNER: &str = "dotnet-lifecycle";
/// Every scanner name [`DotnetConfigScanner`] reports findings under; a
/// completed scan speaks for all of them.
pub const SCANNERS: [&str; 3] = [CONFIG_SCANNER, SECRET_FILES_SCANNER, LIFECYCLE_SCANNER];
/// What a check found, before it becomes a [`Finding`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Hit {
pub scanner: &'static str,
pub scan_type: ScanType,
pub rule_id: &'static str,
pub title: String,
pub description: String,
pub remediation: &'static str,
pub severity: Severity,
pub cwe: &'static str,
pub path: String,
pub line: Option<u32>,
}
/// The .NET configuration, key-file and lifecycle checks over a tree.
#[derive(Debug, Default)]
pub struct DotnetConfigScanner {
/// The day end-of-support dates are compared with (today, in a scan).
pub today: Option<chrono::NaiveDate>,
}
impl Scanner for DotnetConfigScanner {
fn name(&self) -> &str {
CONFIG_SCANNER
}
fn scan_type(&self) -> ScanType {
ScanType::Sast
}
#[tracing::instrument(skip_all)]
async fn scan(&self, repo_path: &Path, repo_id: &str) -> Result<ScanOutput, CoreError> {
let root = repo_path.to_path_buf();
let today = self
.today
.unwrap_or_else(|| chrono::Utc::now().date_naive());
// A check that did not finish must not read as "nothing found": the
// run would close the findings it reported before.
let hits = tokio::task::spawn_blocking(move || check_tree(&root, today))
.await
.map_err(|e| CoreError::Scanner {
scanner: CONFIG_SCANNER.to_string(),
source: Box::new(e),
})?;
let findings = hits
.into_iter()
.map(|hit| into_finding(repo_path, repo_id, hit))
.collect();
Ok(ScanOutput {
findings,
sbom_entries: Vec::new(),
})
}
}
/// A [`Hit`] as a finding of `repo_id`.
pub(crate) fn into_finding(repo_path: &Path, repo_id: &str, hit: Hit) -> Finding {
let line = hit.line.unwrap_or(0).to_string();
let fingerprint = dedup::compute_fingerprint(&[repo_id, hit.rule_id, &hit.path, &line]);
let mut finding = Finding::new(
repo_id.to_string(),
fingerprint,
hit.scanner.to_string(),
hit.scan_type,
hit.title,
hit.description,
hit.severity,
);
finding.rule_id = Some(hit.rule_id.to_string());
finding.cwe = Some(hit.cwe.to_string());
finding.remediation = Some(hit.remediation.to_string());
finding.code_snippet = hit
.line
.and_then(|l| crate::pipeline::source_text::read_lines(repo_path, &hit.path, l, l));
finding.line_number = hit.line;
finding.file_path = Some(hit.path);
finding
}
/// Every check over the tree under `root`, judged on `today`.
pub(crate) fn check_tree(root: &Path, today: chrono::NaiveDate) -> Vec<Hit> {
let mut hits = Vec::new();
for entry in walk_sources(root) {
let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
let path = relative(root, entry.path());
if name.ends_with(".config") && !name.ends_with(".debug.config") {
if let Some(text) = read_text(entry.path()) {
hits.extend(check_config(entry.path(), &path, &text));
}
}
if let Some(hit) = check_key_file(entry.path(), &name, &path) {
hits.push(hit);
}
}
hits.extend(check_frameworks(root, today));
hits
}
/// Values that stand for a secret rather than being one: empty, masked, or a
/// token a deployment substitutes.
fn is_placeholder(value: &str) -> bool {
let v = value.trim().trim_matches(['\'', '"']);
let lower = v.to_ascii_lowercase();
v.is_empty()
|| v.chars()
.all(|c| matches!(c, '*' | 'x' | 'X' | '.' | '-' | '_'))
|| lower.contains("redacted")
|| lower.contains("placeholder")
|| lower.contains("changeme")
|| lower.contains("your_password")
|| lower.contains("yourpassword")
|| (v.starts_with("${") || v.starts_with("$(") || v.starts_with("#{"))
|| (v.starts_with('%') && v.ends_with('%'))
|| (v.starts_with("__") && v.ends_with("__"))
|| (v.starts_with('{') && v.ends_with('}'))
|| (v.starts_with('<') && v.ends_with('>'))
|| (v.starts_with('[') && v.ends_with(']'))
}
/// The password of a connection string (`Password=` or `Pwd=`), when it is a
/// real value. Entity Framework wraps the provider's connection string in
/// quotes; its keys are found the same way.
fn connection_string_password(conn: &str) -> Option<&str> {
conn.split(';').find_map(|part| {
let (key, value) = part.split_once('=')?;
let key = key
.trim()
.trim_start_matches(['"', '\''])
.to_ascii_lowercase();
let key = key.rsplit(['"', ' ']).next().unwrap_or(&key);
(matches!(key, "password" | "pwd") && !is_placeholder(value)).then_some(value)
})
}
/// Setting names under `<appSettings>` that hold a secret.
fn is_secret_setting(key: &str) -> bool {
let k = key.to_ascii_lowercase();
[
"password",
"passwd",
"pwd",
"secret",
"apikey",
"api_key",
"accesskey",
"privatekey",
]
.iter()
.any(|s| k.contains(s))
&& !k.ends_with("file")
&& !k.ends_with("path")
&& !k.contains("length")
&& !k.contains("policy")
}
/// The sibling transform `*.Release.config` of `path`, if any, as text: a
/// release transform that removes `debug` or sets `customErrors` fixes the
/// published configuration, so the base file's development values are fine.
fn release_transform(path: &Path) -> Option<String> {
let stem = path.file_stem()?.to_string_lossy();
let dir = path.parent()?;
let wanted = format!("{stem}.release.config").to_ascii_lowercase();
std::fs::read_dir(dir)
.ok()?
.filter_map(Result::ok)
.find(|e| e.file_name().to_string_lossy().to_ascii_lowercase() == wanted)
.and_then(|e| read_text(&e.path()))
}
/// The checks of one `*.config` file.
fn check_config(full: &Path, path: &str, text: &str) -> Vec<Hit> {
let Some(doc) = parse_xml(text) else {
return Vec::new();
};
let release = release_transform(full).unwrap_or_default();
let mut hits = Vec::new();
let hit = |rule_id, title: String, description: String, remediation, severity, cwe, line| Hit {
scanner: CONFIG_SCANNER,
scan_type: ScanType::Sast,
rule_id,
title,
description,
remediation,
severity,
cwe,
path: path.to_string(),
line: Some(line),
};
let under = |node: roxmltree::Node<'_, '_>, name: &str| {
node.ancestors()
.any(|a| a.is_element() && a.tag_name().name() == name)
};
for node in doc.descendants().filter(|n| n.is_element()) {
let line = line_of(&doc, node);
match node.tag_name().name() {
"add" if under(node, "connectionStrings") => {
let conn = node.attribute("connectionString").unwrap_or_default();
if connection_string_password(conn).is_some() {
let name = node.attribute("name").unwrap_or("a connection string");
hits.push(hit(
"dotnet-config-cleartext-password",
format!("Clear-text database password in connection string \"{name}\""),
"The connection string carries its password in clear text. Everyone \
with access to the repository or the installed application can read \
it, and every installation shares it."
.to_string(),
"Use integrated (Windows) authentication or a managed identity, or \
keep the password out of the file: encrypt the section \
(aspnet_regiis -pe / ProtectedConfigurationProvider) or inject it at \
deployment from a secret store.",
Severity::High,
"CWE-260",
line,
));
}
}
"add" if under(node, "appSettings") => {
let key = node.attribute("key").unwrap_or_default();
let value = node.attribute("value").unwrap_or_default();
if is_secret_setting(key) && value.len() >= 4 && !is_placeholder(value) {
hits.push(hit(
"dotnet-config-cleartext-password",
format!("Clear-text secret in application setting \"{key}\""),
"An application setting named like a password or key holds its value \
in clear text in the configuration file."
.to_string(),
"Move the secret to a secret store or protected configuration and \
inject it at deployment.",
Severity::High,
"CWE-260",
line,
));
}
}
"compilation" if node.attribute("debug").is_some_and(is_true) => {
if !release.contains("RemoveAttributes(debug)") {
hits.push(hit(
"dotnet-config-debug-compilation",
"ASP.NET compiled in debug mode (compilation debug=\"true\")".to_string(),
"Debug compilation disables optimisations and batch compilation and \
keeps debug symbols and detailed errors in the deployed application."
.to_string(),
"Set debug=\"false\" for production, or remove the attribute with a \
Web.Release.config transform (xdt:Transform=\"RemoveAttributes(debug)\").",
Severity::Medium,
"CWE-489",
line,
));
}
}
"customErrors"
if node
.attribute("mode")
.is_some_and(|m| m.eq_ignore_ascii_case("off")) =>
{
if !release.contains("customErrors") {
hits.push(hit(
"dotnet-config-custom-errors-off",
"Detailed ASP.NET errors shown to every client (customErrors mode=\"Off\")"
.to_string(),
"With customErrors off, stack traces, source lines and configuration \
details reach any visitor who triggers an error."
.to_string(),
"Set mode=\"RemoteOnly\" or \"On\" with a generic error page.",
Severity::Medium,
"CWE-209",
line,
));
}
}
"httpCookies" => {
let missing: Vec<&str> = ["requireSSL", "httpOnlyCookies"]
.into_iter()
.filter(|a| !node.attribute(*a).is_some_and(is_true))
.collect();
if !missing.is_empty() {
hits.push(hit(
"dotnet-config-insecure-cookies",
format!("Cookies without {}", missing.join(" and ")),
"Without requireSSL the session and authentication cookies are also \
sent over plain HTTP; without httpOnlyCookies scripts can read them."
.to_string(),
"Set <httpCookies requireSSL=\"true\" httpOnlyCookies=\"true\" />.",
Severity::Medium,
"CWE-614",
line,
));
}
}
"security" if under(node, "bindings") && under(node, "system.serviceModel") => {
let binding_kind = node
.ancestors()
.nth(2)
.map(|n| n.tag_name().name())
.unwrap_or_default();
let mode = node.attribute("mode").unwrap_or_default();
// Named pipes never leave the machine.
let insecure = matches!(mode, "None" | "TransportCredentialOnly")
&& binding_kind != "netNamedPipeBinding";
if insecure {
hits.push(wcf_hit(path, line, binding_kind, mode));
}
}
"binding"
if node.parent().is_some_and(|p| {
p.tag_name().name() == "basicHttpBinding" && under(p, "bindings")
}) && !node
.children()
.any(|c| c.is_element() && c.tag_name().name() == "security") =>
{
hits.push(wcf_hit(path, line, "basicHttpBinding", "None (default)"));
}
"endpoint"
if node.attribute("binding") == Some("basicHttpBinding")
&& node
.attribute("bindingConfiguration")
.is_none_or(str::is_empty)
&& under(node, "system.serviceModel") =>
{
hits.push(wcf_hit(path, line, "basicHttpBinding", "None (default)"));
}
_ => {}
}
}
hits
}
/// An unprotected WCF binding.
fn wcf_hit(path: &str, line: u32, binding: &str, mode: &str) -> Hit {
Hit {
scanner: CONFIG_SCANNER,
scan_type: ScanType::Sast,
rule_id: "dotnet-config-wcf-insecure-binding",
title: format!("WCF {binding} without transport security (mode {mode})"),
description: "Messages of this WCF binding, credentials included, travel unencrypted \
and unauthenticated."
.to_string(),
remediation: "Use security mode=\"Transport\" (HTTPS) or \
\"TransportWithMessageCredential\"; for basicHttpBinding add \
<security mode=\"Transport\" />.",
severity: Severity::High,
cwe: "CWE-319",
path: path.to_string(),
line: Some(line),
}
}
fn is_true(value: &str) -> bool {
value.trim().eq_ignore_ascii_case("true")
}
/// The smallest strong-name key file that holds a private key: a public key
/// alone (`sn -p`) is 160 bytes, a 1024-bit key pair 596.
const SNK_KEY_PAIR_MIN_BYTES: u64 = 300;
/// A key or publish file committed to the repository.
fn check_key_file(full: &Path, name: &str, path: &str) -> Option<Hit> {
let (rule_id, what, severity, cwe, remediation) =
if name.ends_with(".pfx") || name.ends_with(".p12") {
(
"secret-file-private-key",
"A PKCS#12 certificate store (private key) is committed to the repository",
Severity::High,
"CWE-321",
"Remove it from the repository and its history, revoke and replace the \
certificate, and load it from a certificate store or secret store at build time.",
)
} else if name.ends_with(".jks") || name.ends_with(".keystore") {
(
"secret-file-private-key",
"A Java/Android keystore is committed to the repository",
Severity::High,
"CWE-321",
"Remove it from the repository and its history, rotate the keys it holds (for an \
Android upload key, request a reset), and keep it in a secret store used by CI.",
)
} else if name.ends_with(".snk") {
let size = std::fs::metadata(full).map(|m| m.len()).unwrap_or(0);
if size < SNK_KEY_PAIR_MIN_BYTES {
return None;
}
(
"secret-file-signing-key",
"A strong-name key pair (.snk) is committed to the repository",
Severity::Medium,
"CWE-321",
"Keep only the public key in the repository (delay signing, `sn -p`) and sign in \
CI from a protected key.",
)
} else if name.ends_with(".publishsettings") || name.ends_with(".pubxml.user") {
(
"secret-file-publish-profile",
"A publish profile with deployment credentials is committed to the repository",
Severity::High,
"CWE-260",
"Remove it from the repository and its history, reset the deployment credentials, \
and add *.publishsettings and *.pubxml.user to .gitignore.",
)
} else if name.ends_with(".pubxml") {
let has_password = read_text(full).is_some_and(|t| {
let lower = t.to_ascii_lowercase();
lower.contains("<password>") && !lower.contains("<password></password>")
});
if !has_password {
return None;
}
(
"secret-file-publish-profile",
"A publish profile with a deployment password is committed to the repository",
Severity::High,
"CWE-260",
"Remove the password from the profile and its history, reset it, and let Visual \
Studio keep it in the .pubxml.user file (not committed) or use CI secrets.",
)
} else {
return None;
};
Some(Hit {
scanner: SECRET_FILES_SCANNER,
scan_type: ScanType::SecretDetection,
rule_id,
title: what.to_string(),
description: format!(
"{what}. Anyone with read access to the source can use it; a key in the history \
stays there after the file is deleted."
),
remediation,
severity,
cwe,
path: path.to_string(),
line: None,
})
}
/// Projects that target a framework past Microsoft's end of support.
fn check_frameworks(root: &Path, today: chrono::NaiveDate) -> Vec<Hit> {
let mut hits = Vec::new();
for project in inventory(root).projects {
for tf in &project.frameworks {
let Some((ended, product)) = super::end_of_support(&tf.moniker) else {
continue;
};
if ended > today {
continue;
}
hits.push(Hit {
scanner: LIFECYCLE_SCANNER,
scan_type: ScanType::Sbom,
rule_id: "dotnet-framework-end-of-support",
title: format!("{product} is out of support since {ended}"),
description: format!(
"{} targets {product} ({}). Microsoft has not shipped security updates for \
it since {ended}, so vulnerabilities found in the runtime stay open on \
every installation.",
project.path, tf.moniker
),
remediation: "Retarget the project to a supported version (.NET Framework \
4.8/4.8.1, or a supported .NET release) and test it there.",
severity: Severity::Medium,
cwe: "CWE-1104",
path: project.path.clone(),
line: Some(tf.line),
});
}
}
hits
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
struct Tree(std::path::PathBuf);
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn tree(files: &[(&str, &[u8])]) -> Tree {
let dir = std::env::temp_dir().join(format!("cs-dotnet-config-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).expect("mkdir");
for (path, content) in files {
let full = dir.join(path);
std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir");
std::fs::write(full, content).expect("write");
}
Tree(dir)
}
fn today() -> chrono::NaiveDate {
chrono::NaiveDate::from_ymd_opt(2026, 10, 5).unwrap()
}
fn rules(hits: &[Hit]) -> Vec<String> {
let mut out: Vec<String> = hits
.iter()
.map(|h| format!("{} {}:{}", h.rule_id, h.path, h.line.unwrap_or(0)))
.collect();
out.sort();
out
}
const WEB_CONFIG: &str = r#"<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="Plant" connectionString="Data Source=db01;Initial Catalog=Plant;User ID=plant;Password=S3cret!2019" providerName="System.Data.SqlClient" />
<add name="Masked" connectionString="Server=db;User Id=sa;Password=***REDACTED***" />
<add name="Empty" connectionString="Server=db;User Id=sa;Password=;" />
<add name="Integrated" connectionString="Server=db;Integrated Security=SSPI" />
<add name="Ef" connectionString="metadata=res://*/M.csdl;provider connection string=&quot;data source=db;user id=app;pwd=Tr0ub4dor;&quot;" />
</connectionStrings>
<appSettings>
<add key="SmtpPassword" value="mail-pa55" />
<add key="PasswordMinLength" value="12" />
<add key="ApiKey" value="" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.8" />
<customErrors mode="Off" />
<httpCookies httpOnlyCookies="true" />
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Plain" />
<binding name="Tls"><security mode="Transport" /></binding>
</basicHttpBinding>
<wsHttpBinding>
<binding name="Open"><security mode="None" /></binding>
</wsHttpBinding>
<netNamedPipeBinding>
<binding name="Local"><security mode="None" /></binding>
</netNamedPipeBinding>
</bindings>
<services>
<service name="Plant.Service">
<endpoint address="" binding="basicHttpBinding" contract="IPlant" />
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="Tls" contract="IPlant" />
</service>
</services>
</system.serviceModel>
</configuration>"#;
#[test]
fn a_web_config_yields_each_check_once() {
let t = tree(&[("Web/Web.config", WEB_CONFIG.as_bytes())]);
assert_eq!(
rules(&check_tree(&t.0, today())),
[
"dotnet-config-cleartext-password Web/Web.config:11",
"dotnet-config-cleartext-password Web/Web.config:4",
"dotnet-config-cleartext-password Web/Web.config:8",
"dotnet-config-custom-errors-off Web/Web.config:17",
"dotnet-config-debug-compilation Web/Web.config:16",
"dotnet-config-insecure-cookies Web/Web.config:18",
"dotnet-config-wcf-insecure-binding Web/Web.config:23",
"dotnet-config-wcf-insecure-binding Web/Web.config:27",
"dotnet-config-wcf-insecure-binding Web/Web.config:35",
]
);
}
#[test]
fn a_release_transform_clears_the_development_settings() {
let t = tree(&[
(
"Web/Web.config",
br#"<configuration><system.web>
<compilation debug="true" />
<customErrors mode="Off" />
</system.web></configuration>"#,
),
(
"Web/Web.Release.config",
br#"<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"><system.web>
<compilation xdt:Transform="RemoveAttributes(debug)" />
<customErrors mode="RemoteOnly" xdt:Transform="Replace" />
</system.web></configuration>"#,
),
]);
assert!(check_tree(&t.0, today()).is_empty());
}
#[test]
fn build_output_and_packages_are_not_read() {
let config = br#"<configuration><system.web><compilation debug="true" /></system.web></configuration>"#;
let t = tree(&[
("Web/bin/Web.dll.config", config),
("Web/obj/Debug/Web.config", config),
("packages/Some.Pkg.1.0.0/content/web.config", config),
("packages/Some.Pkg.1.0.0/Some.Pkg.snk", &[0u8; 596]),
]);
assert!(check_tree(&t.0, today()).is_empty());
}
#[test]
fn key_and_publish_files_are_reported() {
let t = tree(&[
("Signing/Plant.snk", &[7u8; 596]),
("Signing/PublicOnly.snk", &[7u8; 160]),
("Certs/device.pfx", b"\x30\x82"),
("android/app/release.keystore", b"\xfe\xed\xfe\xed"),
(
"Web/Properties/PublishProfiles/Prod.pubxml",
b"<Project><PropertyGroup><UserName>deploy</UserName></PropertyGroup></Project>",
),
(
"Web/Properties/PublishProfiles/Test.pubxml",
b"<Project><PropertyGroup><Password>hunter22</Password></PropertyGroup></Project>",
),
("Web/Prod.PublishSettings", b"<publishData userPWD=\"x\" />"),
]);
assert_eq!(
rules(&check_tree(&t.0, today())),
[
"secret-file-private-key Certs/device.pfx:0",
"secret-file-private-key android/app/release.keystore:0",
"secret-file-publish-profile Web/Prod.PublishSettings:0",
"secret-file-publish-profile Web/Properties/PublishProfiles/Test.pubxml:0",
"secret-file-signing-key Signing/Plant.snk:0",
]
);
}
#[test]
fn frameworks_past_their_support_are_reported() {
let project = |v: &str| {
format!(
"<Project ToolsVersion=\"15.0\">\n<PropertyGroup>\n<TargetFrameworkVersion>{v}</TargetFrameworkVersion>\n</PropertyGroup>\n</Project>"
)
};
let (old, new) = (project("v4.5"), project("v4.8"));
let t = tree(&[
("Legacy/Legacy.csproj", old.as_bytes()),
("Hmi/Hmi.csproj", new.as_bytes()),
]);
let hits = check_tree(&t.0, today());
assert_eq!(
rules(&hits),
["dotnet-framework-end-of-support Legacy/Legacy.csproj:3"]
);
assert_eq!(hits[0].cwe, "CWE-1104");
assert!(
hits[0].title.contains(".NET Framework 4.5"),
"{}",
hits[0].title
);
}
#[test]
fn placeholders_are_not_passwords() {
for p in [
"",
"***REDACTED***",
"${DB_PASSWORD}",
"#{DbPassword}#",
"__DbPassword__",
"%DB_PW%",
"xxxx",
"<password>",
] {
assert!(is_placeholder(p), "{p}");
}
assert!(!is_placeholder("S3cret!2019"));
assert_eq!(
connection_string_password("Server=a;User Id=b;Password=hunter2;"),
Some("hunter2")
);
assert_eq!(
connection_string_password("Server=a;Integrated Security=true"),
None
);
}
}
@@ -0,0 +1,143 @@
//! The .NET Framework 4.8 fixture (`fixtures/dotnet/framework48`) end to end,
//! without a build and without network: inventory, NuGet SBOM, the
//! unresolved-dependency warning, configuration and key-file findings, and
//! what is not own code (#445). The C# rules run when semgrep is installed.
#![allow(clippy::expect_used, clippy::unwrap_used)]
use std::path::{Path, PathBuf};
use compliance_core::traits::Scanner;
use super::config::check_tree;
use super::{inventory, Runtime};
fn fixture() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("../fixtures/dotnet/framework48")
}
#[test]
fn projects_and_runtime_are_detected() {
let inv = inventory(&fixture());
assert_eq!(inv.solutions, ["Plant.sln"]);
let projects: Vec<String> = inv
.projects
.iter()
.map(|p| {
let tfms: Vec<&str> = p.frameworks.iter().map(|f| f.moniker.as_str()).collect();
format!("{} {} {}", p.path, p.sdk_style, tfms.join(","))
})
.collect();
assert_eq!(
projects,
[
"Plant.Hmi/Plant.Hmi.csproj false net48",
"Plant.Legacy/Plant.Legacy.csproj false net40",
"Plant.Web/Plant.Web.csproj false net48",
]
);
assert_eq!(inv.runtimes(), [Runtime::Framework]);
}
#[test]
fn nuget_components_and_the_unresolved_warning() {
let mut purls: Vec<String> = crate::pipeline::sbom::nuget_components(&fixture(), "r")
.into_iter()
.filter_map(|e| e.purl)
.collect();
purls.sort();
assert_eq!(
purls,
[
"pkg:nuget/BouncyCastle@1.8.5",
"pkg:nuget/EntityFramework@6.2.0",
"pkg:nuget/Newtonsoft.Json@12.0.1",
"pkg:nuget/log4net@2.0.8",
]
);
// packages.config lists transitive packages too; the PackageReference
// project without a lockfile does not.
let unresolved: Vec<String> = crate::pipeline::sbom::unlocked_ecosystems(&fixture())
.into_iter()
.map(|u| u.manifest)
.collect();
assert_eq!(unresolved, ["Plant.Web/Plant.Web.csproj"]);
}
#[test]
fn configuration_key_file_and_lifecycle_findings() {
let today = chrono::NaiveDate::from_ymd_opt(2026, 10, 5).unwrap();
let mut hits: Vec<String> = check_tree(&fixture(), today)
.into_iter()
.map(|h| {
format!(
"{} {} {}:{} {}",
h.scanner,
h.rule_id,
h.path,
h.line.unwrap_or(0),
h.cwe
)
})
.collect();
hits.sort();
assert_eq!(
hits,
[
"dotnet-config dotnet-config-cleartext-password Plant.Web/Web.config:4 CWE-260",
"dotnet-config dotnet-config-debug-compilation Plant.Web/Web.config:7 CWE-489",
"dotnet-config dotnet-config-wcf-insecure-binding Plant.Web/Web.config:14 CWE-319",
"dotnet-lifecycle dotnet-framework-end-of-support Plant.Legacy/Plant.Legacy.csproj:6 CWE-1104",
"secret-files secret-file-signing-key Signing/Plant.snk:0 CWE-321",
]
);
}
#[test]
fn build_output_and_restored_packages_are_not_own_code() {
assert_eq!(
crate::pipeline::vendor::vendor_dirs(&fixture()),
["Plant.Hmi/bin", "packages"]
);
}
#[tokio::test]
async fn the_csharp_rules_find_the_planted_weaknesses() {
let installed = std::process::Command::new("semgrep")
.arg("--version")
.output()
.is_ok_and(|o| o.status.success());
if !installed {
eprintln!("semgrep not installed; skipping");
return;
}
let root = fixture();
let vendor = crate::pipeline::vendor::vendor_dirs(&root);
let output = crate::pipeline::semgrep::SemgrepScanner::new(vendor)
.scan(&root, "r")
.await
.expect("semgrep");
let mut found: Vec<String> = output
.findings
.iter()
.map(|f| {
let rule = f.rule_id.as_deref().unwrap_or_default();
let rule = rule.rsplit('.').next().unwrap_or(rule);
format!(
"{rule} {}:{}",
f.file_path.as_deref().unwrap_or_default(),
f.line_number.unwrap_or(0)
)
})
.collect();
found.sort();
assert_eq!(
found,
[
"cra-ai-13-csharp-broken-hash-or-cipher Plant.Web/OrderService.svc.cs:33",
"cra-ai-15-csharp-cert-validation-disabled Plant.Web/OrderService.svc.cs:16",
"cra-ai-20-csharp-sql-string Plant.Web/OrderService.svc.cs:21",
"cra-ai-20-csharp-unsafe-deserialization Plant.Web/OrderService.svc.cs:27",
]
);
}
+461
View File
@@ -0,0 +1,461 @@
//! .NET solutions and projects in a source tree (#445).
//!
//! Read without a build and without `dotnet restore`: the solution and project
//! files are XML and text, and everything here comes from them. Nothing of the
//! customer's is executed, and no package source is contacted.
//!
//! - [`inventory`] lists the solutions (`.sln`) and projects (`.csproj`,
//! `.vbproj`, `.fsproj`) with their project style and target frameworks;
//! - [`end_of_support`] says whether a target framework is past Microsoft's
//! end of support;
//! - [`config`] checks configuration files and committed key files.
pub mod config;
#[cfg(test)]
mod fixture_tests;
use std::path::Path;
/// Directories that hold build output, IDE state, restored packages or test
/// results, never a project's own project files.
pub(crate) const SKIPPED_DIRS: &[&str] = &[
".git",
".vs",
"bin",
"obj",
"packages",
"node_modules",
"TestResults",
];
/// How deep project files are looked for.
const MAX_DEPTH: usize = 16;
/// Largest XML file read (a project file is a few kilobytes; a generated
/// `project.assets.json` can reach a few megabytes).
pub(crate) const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024;
/// Which .NET a target framework belongs to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Runtime {
/// The Windows-only .NET Framework (1.0 to 4.8.1).
Framework,
/// .NET Core and .NET 5 and later.
Modern,
/// .NET Standard: a contract, not a runtime of its own.
Standard,
}
impl Runtime {
/// The value recorded on the target (`dotnet-framework`, `dotnet`,
/// `dotnet-standard`).
pub fn as_str(self) -> &'static str {
match self {
Runtime::Framework => "dotnet-framework",
Runtime::Modern => "dotnet",
Runtime::Standard => "dotnet-standard",
}
}
}
/// One target framework of a project, as a target framework moniker
/// (`net48`, `net8.0`, `netstandard2.0`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TargetFramework {
/// The moniker, lower-case, without a platform suffix (`-windows`).
pub moniker: String,
/// The line of the project file that names it (1-based).
pub line: u32,
}
/// A .NET project file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DotnetProject {
/// Relative to the tree, `/`-separated.
pub path: String,
/// SDK style (`<Project Sdk="Microsoft.NET.Sdk">`), as opposed to the old,
/// verbose style of .NET Framework projects.
pub sdk_style: bool,
/// The target frameworks it names; empty when it inherits them (from a
/// `Directory.Build.props`) or names them through a property.
pub frameworks: Vec<TargetFramework>,
}
/// The .NET solutions and projects of a tree.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Inventory {
/// Solution files, relative and sorted. Each one is a component of its own.
pub solutions: Vec<String>,
/// Project files, sorted by path.
pub projects: Vec<DotnetProject>,
}
impl Inventory {
/// Whether the tree holds any .NET solution or project.
pub fn is_empty(&self) -> bool {
self.solutions.is_empty() && self.projects.is_empty()
}
/// The runtimes the projects target, without repeats, in a fixed order.
pub fn runtimes(&self) -> Vec<Runtime> {
let all: Vec<Runtime> = self
.projects
.iter()
.flat_map(|p| &p.frameworks)
.filter_map(|f| runtime_of(&f.moniker))
.collect();
[Runtime::Framework, Runtime::Modern, Runtime::Standard]
.into_iter()
.filter(|r| all.contains(r))
.collect()
}
}
/// Whether `name` is a .NET project file.
pub(crate) fn is_project_file(name: &str) -> bool {
let lower = name.to_ascii_lowercase();
[".csproj", ".vbproj", ".fsproj"]
.iter()
.any(|ext| lower.ends_with(ext))
}
/// Every file under `root` outside [`SKIPPED_DIRS`], to [`MAX_DEPTH`].
pub(crate) fn walk_sources(root: &Path) -> impl Iterator<Item = walkdir::DirEntry> {
walkdir::WalkDir::new(root)
.min_depth(1)
.max_depth(MAX_DEPTH)
.sort_by_file_name()
.into_iter()
.filter_entry(|e| {
!(e.file_type().is_dir()
&& SKIPPED_DIRS
.iter()
.any(|d| e.file_name().to_string_lossy().eq_ignore_ascii_case(d)))
})
.filter_map(Result::ok)
.filter(|e| e.file_type().is_file())
}
/// `path` relative to `root`, `/`-separated.
pub(crate) fn relative(root: &Path, path: &Path) -> String {
path.strip_prefix(root)
.unwrap_or(path)
.to_string_lossy()
.replace('\\', "/")
}
/// 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
/// 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(),
}
}
/// Parse XML the way project and configuration files need: a DTD is allowed
/// (some old `.config` files carry one) but never expanded beyond the
/// parser's limits.
pub(crate) fn parse_xml(text: &str) -> Option<roxmltree::Document<'_>> {
let options = roxmltree::ParsingOptions {
allow_dtd: true,
..roxmltree::ParsingOptions::default()
};
roxmltree::Document::parse_with_options(text, options).ok()
}
/// The 1-based line `node` starts on.
pub(crate) fn line_of(doc: &roxmltree::Document<'_>, node: roxmltree::Node<'_, '_>) -> u32 {
doc.text_pos_at(node.range().start).row
}
/// The .NET solutions and projects under `root`.
pub fn inventory(root: &Path) -> Inventory {
let mut inv = Inventory::default();
for entry in walk_sources(root) {
let name = entry.file_name().to_string_lossy();
if name.to_ascii_lowercase().ends_with(".sln") {
inv.solutions.push(relative(root, entry.path()));
} else if is_project_file(&name) {
let path = relative(root, entry.path());
let project = read_text(entry.path())
.and_then(|text| parse_project(&path, &text))
.unwrap_or(DotnetProject {
path,
sdk_style: false,
frameworks: Vec::new(),
});
inv.projects.push(project);
}
}
inv.solutions.sort();
inv.projects.sort_by(|a, b| a.path.cmp(&b.path));
inv
}
/// Read a project file's style and target frameworks.
fn parse_project(path: &str, text: &str) -> Option<DotnetProject> {
let doc = parse_xml(text)?;
let root = doc.root_element();
let sdk_style = root.attribute("Sdk").is_some()
|| root
.children()
.any(|c| c.is_element() && c.tag_name().name() == "Sdk");
let mut frameworks: Vec<TargetFramework> = Vec::new();
for node in root.descendants().filter(|n| n.is_element()) {
let monikers: Vec<String> = match node.tag_name().name() {
"TargetFramework" | "TargetFrameworks" => node
.text()
.unwrap_or_default()
.split(';')
.filter_map(normalise_moniker)
.collect(),
"TargetFrameworkVersion" => node
.text()
.and_then(framework_version_moniker)
.into_iter()
.collect(),
_ => continue,
};
let line = line_of(&doc, node);
for moniker in monikers {
if !frameworks.iter().any(|f| f.moniker == moniker) {
frameworks.push(TargetFramework { moniker, line });
}
}
}
Some(DotnetProject {
path: path.to_string(),
sdk_style,
frameworks,
})
}
/// A `<TargetFramework>` value as a moniker: lower-case, without the platform
/// suffix (`net8.0-windows` is `net8.0`). `None` for an MSBuild property
/// reference or an empty value.
fn normalise_moniker(raw: &str) -> Option<String> {
let value = raw.trim();
if value.is_empty() || value.contains("$(") {
return None;
}
let base = value.split('-').next().unwrap_or(value);
Some(base.to_ascii_lowercase())
}
/// An old-style `<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>` as
/// a moniker (`net452`).
fn framework_version_moniker(raw: &str) -> Option<String> {
let version = raw.trim().trim_start_matches(['v', 'V']);
if version.is_empty() || !version.chars().all(|c| c.is_ascii_digit() || c == '.') {
return None;
}
Some(format!("net{}", version.replace('.', "")))
}
/// Which runtime a moniker targets; `None` for one this does not know
/// (`uap10.0`, `xamarinios10`, …).
pub fn runtime_of(moniker: &str) -> Option<Runtime> {
if moniker.starts_with("netstandard") {
return Some(Runtime::Standard);
}
if moniker.starts_with("netcoreapp") {
return Some(Runtime::Modern);
}
let rest = moniker.strip_prefix("net")?;
if rest.is_empty() || !rest.chars().all(|c| c.is_ascii_digit() || c == '.') {
return None;
}
// `net5.0` and later carry a dot; .NET Framework monikers never do.
Some(if rest.contains('.') {
Runtime::Modern
} else {
Runtime::Framework
})
}
/// Microsoft's end of support for each target framework that has one, as an
/// ISO date and the name customers know it by. Versions not listed are
/// supported (.NET Framework 4.8 and 4.8.1 follow the Windows they ship with).
///
/// Sources: the .NET Framework and .NET lifecycle pages on
/// learn.microsoft.com (.NET Framework 4.5.2, 4.6 and 4.6.1 ended
/// 2022-04-26, 4.6.2 ends 2027-01-12; .NET 8 and .NET 9 end 2026-11-10).
const END_OF_SUPPORT: &[(&str, &str, &str)] = &[
("net11", "2011-07-12", ".NET Framework 1.1"),
("net20", "2011-07-12", ".NET Framework 2.0"),
("net30", "2011-07-12", ".NET Framework 3.0"),
("net35", "2029-01-09", ".NET Framework 3.5 SP1"),
("net40", "2016-01-12", ".NET Framework 4.0"),
("net403", "2016-01-12", ".NET Framework 4.0.3"),
("net45", "2016-01-12", ".NET Framework 4.5"),
("net451", "2016-01-12", ".NET Framework 4.5.1"),
("net452", "2022-04-26", ".NET Framework 4.5.2"),
("net46", "2022-04-26", ".NET Framework 4.6"),
("net461", "2022-04-26", ".NET Framework 4.6.1"),
("net462", "2027-01-12", ".NET Framework 4.6.2"),
("netcoreapp1.0", "2019-06-27", ".NET Core 1.0"),
("netcoreapp1.1", "2019-06-27", ".NET Core 1.1"),
("netcoreapp2.0", "2018-10-01", ".NET Core 2.0"),
("netcoreapp2.1", "2021-08-21", ".NET Core 2.1"),
("netcoreapp2.2", "2019-12-23", ".NET Core 2.2"),
("netcoreapp3.0", "2020-03-03", ".NET Core 3.0"),
("netcoreapp3.1", "2022-12-13", ".NET Core 3.1"),
("net5.0", "2022-05-10", ".NET 5"),
("net6.0", "2024-11-12", ".NET 6"),
("net7.0", "2024-05-14", ".NET 7"),
("net8.0", "2026-11-10", ".NET 8"),
("net9.0", "2026-11-10", ".NET 9"),
("net10.0", "2028-11-14", ".NET 10"),
];
/// When `moniker` lost (or loses) Microsoft's support, and its product name.
/// `None` for a version without an announced end, or one not known here.
pub fn end_of_support(moniker: &str) -> Option<(chrono::NaiveDate, &'static str)> {
END_OF_SUPPORT
.iter()
.find(|(m, _, _)| *m == moniker)
.and_then(|(_, date, name)| {
chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d")
.ok()
.map(|d| (d, *name))
})
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
/// A scratch tree holding `files` (relative path, content), removed on drop.
pub(crate) struct Tree(pub std::path::PathBuf);
impl Tree {
pub(crate) fn new(files: &[(&str, &str)]) -> Self {
let dir = std::env::temp_dir().join(format!("cs-dotnet-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).expect("mkdir");
for (path, content) in files {
let full = dir.join(path);
std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir");
std::fs::write(full, content).expect("write");
}
Tree(dir)
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
const OLD_STYLE: &str = "\u{feff}<?xml version=\"1.0\" encoding=\"utf-8\"?>
<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
</PropertyGroup>
</Project>";
const SDK_STYLE: &str = r#"<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net8.0-windows;net48;$(ExtraTfm)</TargetFrameworks>
</PropertyGroup>
</Project>"#;
#[test]
fn projects_and_solutions_are_found_at_any_depth() {
let tree = Tree::new(&[
("Tools.sln", ""),
("src/Plant/Plant.sln", ""),
("src/Plant/Hmi/Hmi.csproj", OLD_STYLE),
("src/Plant/Service/Service.vbproj", SDK_STYLE),
("src/Plant/Hmi/bin/Debug/Copy.csproj", SDK_STYLE),
("src/Plant/Hmi/obj/Hmi.csproj.nuget.g.props", ""),
]);
let inv = inventory(&tree.0);
assert_eq!(inv.solutions, ["Tools.sln", "src/Plant/Plant.sln"]);
let paths: Vec<&str> = inv.projects.iter().map(|p| p.path.as_str()).collect();
assert_eq!(
paths,
[
"src/Plant/Hmi/Hmi.csproj",
"src/Plant/Service/Service.vbproj"
]
);
let old = &inv.projects[0];
assert!(!old.sdk_style);
assert_eq!(
old.frameworks,
[TargetFramework {
moniker: "net452".into(),
line: 5
}]
);
let sdk = &inv.projects[1];
assert!(sdk.sdk_style);
let monikers: Vec<&str> = sdk.frameworks.iter().map(|f| f.moniker.as_str()).collect();
assert_eq!(monikers, ["net8.0", "net48"]);
assert_eq!(inv.runtimes(), [Runtime::Framework, Runtime::Modern]);
}
#[test]
fn monikers_belong_to_their_runtime() {
assert_eq!(runtime_of("net48"), Some(Runtime::Framework));
assert_eq!(runtime_of("net35"), Some(Runtime::Framework));
assert_eq!(runtime_of("net8.0"), Some(Runtime::Modern));
assert_eq!(runtime_of("netcoreapp3.1"), Some(Runtime::Modern));
assert_eq!(runtime_of("netstandard2.0"), Some(Runtime::Standard));
assert_eq!(runtime_of("uap10.0"), None);
assert_eq!(runtime_of("net"), None);
}
#[test]
fn old_framework_versions_have_ended() {
let today = chrono::NaiveDate::from_ymd_opt(2026, 10, 5).unwrap();
for ended in [
"net40", "net45", "net451", "net452", "net46", "net461", "net6.0",
] {
let (date, _) = end_of_support(ended).expect(ended);
assert!(date <= today, "{ended}");
}
assert!(end_of_support("net48").is_none());
assert!(end_of_support("net481").is_none());
let (net8, name) = end_of_support("net8.0").unwrap();
assert!(net8 > today);
assert_eq!(name, ".NET 8");
}
#[test]
fn utf16_project_files_are_read() {
let tree = Tree::new(&[]);
let path = tree.0.join("Legacy.csproj");
let mut bytes = vec![0xFF, 0xFE];
for unit in "<Project><PropertyGroup><TargetFrameworkVersion>v4.0</TargetFrameworkVersion></PropertyGroup></Project>".encode_utf16() {
bytes.extend(unit.to_le_bytes());
}
std::fs::write(&path, bytes).unwrap();
let inv = inventory(&tree.0);
assert_eq!(inv.projects[0].frameworks[0].moniker, "net40");
}
}
+172 -7
View File
@@ -5,13 +5,20 @@
//! change them (severity, status, rationale, control refs);
//! [`RunFindings::write_back`] stores those changes on the rows already saved,
//! without undoing a status a person set in the meantime.
//!
//! At the end of a scan, [`RunFindings::resolve_missing`] marks resolved the
//! findings a scanner that completed did not report again, and
//! [`RunFindings::save_new`] reopens a resolved finding that is reported
//! again. Only scanners whose run is known to have completed count (see
//! [`RunFindings::completed`]): a tool that failed quietly must not close
//! everything it found before.
use std::collections::{HashMap, HashSet};
use futures_util::TryStreamExt;
use mongodb::bson::{doc, oid::ObjectId, to_bson, Bson, Document};
use compliance_core::models::{Finding, FindingStatus};
use compliance_core::models::{Finding, FindingStatus, ScanChangeKind, StatusChange};
use crate::database::Database;
use crate::error::AgentError;
@@ -23,8 +30,22 @@ pub struct RunFindings {
inserted: HashMap<String, ObjectId>,
/// Already stored by an earlier run; never saved again.
earlier: HashSet<String>,
/// Scanners (`Finding::scanner`) that completed in this run, so their
/// findings this run did not see are gone from the code.
completed: HashSet<String>,
/// Findings this run closed or reopened, for their issues.
status_changed: Vec<ObjectId>,
}
/// Statuses a scan may close: nobody has decided about the finding yet. A
/// false positive, an accepted risk, an ignored finding and a wrong mapping
/// are a person's decision and stay as they are.
const UNDECIDED: [&str; 3] = ["open", "triaged", "needs_review"];
/// How many findings one update names: keeps each query small however many a
/// scan closes.
const UPDATE_CHUNK: usize = 500;
impl RunFindings {
/// Nothing saved yet for the run `scan_run_id`.
pub fn new(scan_run_id: &str) -> Self {
@@ -32,9 +53,18 @@ impl RunFindings {
scan_run_id: scan_run_id.to_string(),
inserted: HashMap::new(),
earlier: HashSet::new(),
completed: HashSet::new(),
status_changed: Vec::new(),
}
}
/// Record that `scanner` ran to completion over the whole tree. Call it
/// before saving that scanner's findings, so a resolved one it reports
/// again is reopened.
pub fn completed(&mut self, scanner: &str) {
self.completed.insert(scanner.to_string());
}
/// How many findings this run saw first.
pub fn new_count(&self) -> u32 {
u32::try_from(self.inserted.len()).unwrap_or(u32::MAX)
@@ -67,18 +97,37 @@ impl RunFindings {
return Ok(0);
}
// Which of them an earlier run already stored (fingerprints only).
let stored: HashSet<String> = db
// Which of them an earlier run already stored.
let stored_rows: Vec<Document> = db
.findings()
.clone_with_type::<Document>()
.find(doc! { "fingerprint": { "$in": unknown.iter().collect::<Vec<_>>() } })
.projection(doc! { "fingerprint": 1 })
.projection(doc! { "fingerprint": 1, "status": 1, "scanner": 1 })
.await?
.try_collect::<Vec<Document>>()
.await?
.into_iter()
.try_collect()
.await?;
let stored: HashSet<String> = stored_rows
.iter()
.filter_map(|d| d.get_str("fingerprint").ok().map(str::to_owned))
.collect();
// A resolved finding its completed scanner reports again is back.
let reopen: Vec<ObjectId> = stored_rows
.iter()
.filter(|d| d.get_str("status") == Ok("resolved"))
.filter(|d| {
d.get_str("scanner")
.is_ok_and(|scanner| self.completed.contains(scanner))
})
.filter_map(|d| d.get_object_id("_id").ok())
.collect();
self.set_status(
db,
&reopen,
&["resolved"],
FindingStatus::Open,
ScanChangeKind::FoundAgain,
)
.await?;
// The first finding of each new fingerprint (a scan can report the
// same one twice).
@@ -188,6 +237,122 @@ impl RunFindings {
Ok(new_findings)
}
/// Mark resolved the findings of `target_id` that a scanner which
/// completed in this run stored earlier but did not report this time.
/// Call it once, after [`Self::write_back`] succeeded: a run that fails
/// part-way must not close anything.
///
/// The scan covers one tree per run, so everything it saw is in this
/// object; a run over several trees would need one seen-set for all.
///
/// # Arguments
///
/// * `db` - the tenant database
/// * `target_id` - the scanned target (`Finding::repo_id`)
/// * `vendor` - the tree's vendor directories: a finding whose file now
/// lies in one is closed as vendor code, not as fixed
///
/// # Returns
///
/// How many findings were closed.
///
/// # Errors
///
/// A database error.
pub async fn resolve_missing(
&mut self,
db: &Database,
target_id: &str,
vendor: &[String],
) -> Result<u32, AgentError> {
if self.completed.is_empty() {
return Ok(0);
}
let candidates: Vec<Document> = db
.findings()
.clone_with_type::<Document>()
.find(doc! {
"repo_id": target_id,
"scanner": { "$in": self.completed.iter().collect::<Vec<_>>() },
"status": { "$in": UNDECIDED.to_vec() },
})
.projection(doc! { "fingerprint": 1, "file_path": 1 })
.await?
.try_collect()
.await?;
let (mut fixed, mut vendored) = (Vec::new(), Vec::new());
for row in &candidates {
let (Ok(id), Ok(fingerprint)) = (row.get_object_id("_id"), row.get_str("fingerprint"))
else {
continue;
};
if self.inserted.contains_key(fingerprint) || self.earlier.contains(fingerprint) {
continue;
}
let in_vendor = row
.get_str("file_path")
.is_ok_and(|file| crate::pipeline::vendor::in_vendor_dir(file, vendor));
if in_vendor {
vendored.push(id);
} else {
fixed.push(id);
}
}
for (ids, kind) in [
(&fixed, ScanChangeKind::NoLongerFound),
(&vendored, ScanChangeKind::NowVendorCode),
] {
self.set_status(db, ids, &UNDECIDED, FindingStatus::Resolved, kind)
.await?;
}
let closed = u32::try_from(fixed.len() + vendored.len()).unwrap_or(u32::MAX);
if closed > 0 {
tracing::info!(
scan_run_id = %self.scan_run_id,
fixed = fixed.len(),
vendored = vendored.len(),
"resolved findings the scan no longer reports"
);
}
Ok(closed)
}
/// Move the findings `ids` whose status is still one of `from` to `to`,
/// with a history entry saying this run did it and why. The `from` guard
/// leaves alone a finding a person changed in the meantime.
async fn set_status(
&mut self,
db: &Database,
ids: &[ObjectId],
from: &[&str],
to: FindingStatus,
kind: ScanChangeKind,
) -> Result<(), AgentError> {
if ids.is_empty() {
return Ok(());
}
let change = bson_of(&StatusChange::by_scan(to.clone(), kind, &self.scan_run_id))?;
let to = bson_of(&to)?;
self.status_changed.extend_from_slice(ids);
for chunk in ids.chunks(UPDATE_CHUNK) {
db.findings()
.update_many(
doc! { "_id": { "$in": chunk.to_vec() }, "status": { "$in": from.to_vec() } },
doc! {
"$set": { "status": to.clone(), "updated_at": mongodb::bson::DateTime::now() },
"$push": { "status_history": change.clone() },
},
)
.await?;
}
Ok(())
}
/// The findings this run closed or reopened (their issues follow).
pub fn status_changed(&self) -> &[ObjectId] {
&self.status_changed
}
/// Give each finding this run saved its row id.
fn stamp_ids(&self, findings: &mut [Finding]) {
for finding in findings.iter_mut() {
+219 -8
View File
@@ -96,6 +96,74 @@ impl RepoCredentials {
}
}
/// Limits on one clone or fetch, so a huge or slow repository ends the scan
/// with a reason instead of holding a scan slot indefinitely.
///
/// Set per deployment: `GIT_CLONE_TIMEOUT_SECS` (default 1800),
/// `GIT_CLONE_MAX_MB` (default 4096) and `GIT_CLONE_DEPTH` (unset: the full
/// history, which the secret scan of earlier commits and PR reviews need).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CloneLimits {
/// How long the transfer of one clone or fetch may take.
pub timeout: std::time::Duration,
/// How many bytes one clone or fetch may receive.
pub max_bytes: usize,
/// Clone only this many commits of history; `None` clones all of it.
pub depth: Option<i32>,
}
impl Default for CloneLimits {
fn default() -> Self {
Self {
timeout: std::time::Duration::from_secs(1800),
max_bytes: 4096 * 1024 * 1024,
depth: None,
}
}
}
impl CloneLimits {
/// The limits this deployment sets, the defaults where it sets none or
/// an unreadable value.
pub fn from_env() -> Self {
let read = |key: &str| {
std::env::var(key)
.ok()
.and_then(|v| v.trim().parse::<u64>().ok())
};
let defaults = Self::default();
Self {
timeout: read("GIT_CLONE_TIMEOUT_SECS")
.filter(|s| *s > 0)
.map_or(defaults.timeout, std::time::Duration::from_secs),
max_bytes: read("GIT_CLONE_MAX_MB")
.filter(|mb| *mb > 0)
.and_then(|mb| usize::try_from(mb.saturating_mul(1024 * 1024)).ok())
.unwrap_or(defaults.max_bytes),
depth: read("GIT_CLONE_DEPTH")
.filter(|d| *d > 0)
.and_then(|d| i32::try_from(d).ok()),
}
}
/// Why a transfer that has run for `elapsed` and received `bytes` must
/// stop, if it must.
fn exceeded(&self, elapsed: std::time::Duration, bytes: usize) -> Option<String> {
if elapsed > self.timeout {
return Some(format!(
"the repository did not download within {} minutes (GIT_CLONE_TIMEOUT_SECS)",
self.timeout.as_secs() / 60
));
}
(bytes > self.max_bytes).then(|| {
format!(
"the repository is larger than the download limit of {} MB (GIT_CLONE_MAX_MB)",
self.max_bytes / (1024 * 1024)
)
})
}
}
pub struct GitOps {
base_path: PathBuf,
/// The tenant every checkout this instance makes belongs to.
@@ -103,6 +171,8 @@ pub struct GitOps {
credentials: RepoCredentials,
/// Where a clone or fetch may connect (#256, #294).
net_guard: NetGuard,
/// How long and how large a clone or fetch may be.
limits: CloneLimits,
}
impl GitOps {
@@ -117,6 +187,59 @@ impl GitOps {
tenant_id: tenant_id.to_string(),
credentials,
net_guard,
limits: CloneLimits::from_env(),
}
}
/// The same operations with other limits (tests).
#[cfg(test)]
fn with_limits(mut self, limits: CloneLimits) -> Self {
self.limits = limits;
self
}
/// Fetch options for one bounded transfer: the credentials, no
/// redirects, and a progress check that stops the transfer once it
/// exceeds [`CloneLimits`], leaving the reason in `stopped`.
fn limited_fetch_options<'a>(
&'a self,
stopped: &'a std::cell::RefCell<Option<String>>,
depth: Option<i32>,
) -> FetchOptions<'a> {
let mut callbacks = if self.credentials.has_credentials() {
self.credentials.make_callbacks()
} else {
RemoteCallbacks::new()
};
let started = std::time::Instant::now();
let limits = self.limits;
callbacks.transfer_progress(move |progress| {
match limits.exceeded(started.elapsed(), progress.received_bytes()) {
Some(reason) => {
*stopped.borrow_mut() = Some(reason);
false
}
None => true,
}
});
let mut fetch_opts = FetchOptions::new();
// A redirect could lead anywhere, past the check in `check_remote`.
fetch_opts.follow_redirects(RemoteRedirect::None);
fetch_opts.remote_callbacks(callbacks);
if let Some(depth) = depth {
fetch_opts.depth(depth);
}
fetch_opts
}
/// `error`, or the limit that stopped the transfer if one did.
fn transfer_error(
stopped: std::cell::RefCell<Option<String>>,
error: git2::Error,
) -> AgentError {
match stopped.into_inner() {
Some(reason) => AgentError::Other(reason),
None => error.into(),
}
}
@@ -170,7 +293,12 @@ impl GitOps {
// an empty checkout behind for the next run to try to fetch.
self.check_remote(git_url)?;
std::fs::create_dir_all(&repo_path)?;
self.clone_repo(git_url, &repo_path)?;
if let Err(e) = self.clone_repo(git_url, &repo_path) {
// A half-cloned directory would be fetched, not cloned, next
// time.
let _ = std::fs::remove_dir_all(&repo_path);
return Err(e);
}
tracing::info!("Cloned {git_url} to {}", repo_path.display());
}
@@ -180,19 +308,25 @@ impl GitOps {
#[tracing::instrument(skip_all)]
fn clone_repo(&self, git_url: &str, repo_path: &Path) -> Result<(), AgentError> {
tracing::info!("cloning repo from {}", git_url);
let stopped = std::cell::RefCell::new(None);
let mut builder = git2::build::RepoBuilder::new();
let fetch_opts = self.credentials.fetch_options();
builder.fetch_options(fetch_opts);
builder.clone(git_url, repo_path)?;
Ok(())
builder.fetch_options(self.limited_fetch_options(&stopped, self.limits.depth));
let cloned = builder.clone(git_url, repo_path);
drop(builder);
cloned
.map(drop)
.map_err(|e| Self::transfer_error(stopped, e))
}
fn fetch(&self, repo_path: &Path) -> Result<(), AgentError> {
let repo = Repository::open(repo_path)?;
let mut remote = repo.find_remote("origin")?;
self.check_remote(remote.url().unwrap_or_default())?;
let mut fetch_opts = self.credentials.fetch_options();
remote.fetch(&[] as &[&str], Some(&mut fetch_opts), None)?;
let stopped = std::cell::RefCell::new(None);
let mut fetch_opts = self.limited_fetch_options(&stopped, None);
let fetched = remote.fetch(&[] as &[&str], Some(&mut fetch_opts), None);
drop(fetch_opts);
fetched.map_err(|e| Self::transfer_error(stopped, e))?;
// Fast-forward to origin/HEAD
let fetch_head = repo.find_reference("FETCH_HEAD")?;
@@ -207,6 +341,22 @@ impl GitOps {
Ok(())
}
/// The patterns `.gitattributes` keeps in Git LFS (`*.psd filter=lfs …`).
/// libgit2 runs no LFS filter, so those files stay pointer files in the
/// checkout: their content is neither downloaded nor scanned.
pub fn lfs_patterns(repo_path: &Path) -> Vec<String> {
std::fs::read_to_string(repo_path.join(".gitattributes"))
.map(|text| {
text.lines()
.filter(|line| line.contains("filter=lfs"))
.filter_map(|line| line.split_whitespace().next())
.filter(|pattern| !pattern.starts_with('#'))
.map(str::to_string)
.collect()
})
.unwrap_or_default()
}
/// Build credentials from a repo view's own HTTPS token. There is no
/// agent-wide fallback credential any more — see [`reject_ssh_url`].
pub fn make_repo_credentials(repo: &crate::pipeline::repo_view::RepoView) -> RepoCredentials {
@@ -329,12 +479,51 @@ pub struct DiffFile {
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::{clone_dir, reject_ssh_url, GitOps, RepoCredentials};
use super::{clone_dir, reject_ssh_url, CloneLimits, GitOps, RepoCredentials};
use compliance_core::NetGuard;
use std::path::Path;
const BASE: &str = "/data/repos";
#[test]
fn a_transfer_stops_past_its_time_or_size() {
let limits = CloneLimits {
timeout: std::time::Duration::from_secs(60),
max_bytes: 1024,
depth: None,
};
let second = std::time::Duration::from_secs(1);
assert_eq!(limits.exceeded(second, 512), None);
assert!(limits
.exceeded(second, 2048)
.is_some_and(|r| r.contains("GIT_CLONE_MAX_MB")));
assert!(limits
.exceeded(std::time::Duration::from_secs(61), 0)
.is_some_and(|r| r.contains("GIT_CLONE_TIMEOUT_SECS")));
}
#[test]
fn the_defaults_clone_the_full_history_within_limits() {
let limits = CloneLimits::default();
assert_eq!(limits.depth, None);
assert_eq!(limits.max_bytes, 4096 * 1024 * 1024);
assert_eq!(limits.timeout.as_secs(), 1800);
}
#[test]
fn lfs_patterns_come_from_gitattributes() {
let dir = std::env::temp_dir().join(format!("cs-lfs-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join(".gitattributes"),
"*.psd filter=lfs diff=lfs merge=lfs -text\n*.txt text\nAssets/**/*.fbx filter=lfs diff=lfs merge=lfs -text\n",
)
.unwrap();
assert_eq!(GitOps::lfs_patterns(&dir), ["*.psd", "Assets/**/*.fbx"]);
std::fs::remove_dir_all(&dir).unwrap();
assert!(GitOps::lfs_patterns(&dir).is_empty());
}
#[test]
fn same_target_name_in_two_tenants_gets_two_directories() {
let a = clone_dir(Path::new(BASE), "tenant-a", "acme-firmware");
@@ -426,6 +615,28 @@ mod tests {
)
}
/// Against a real public repository; run with `--ignored` and network.
#[test]
#[ignore = "needs network"]
fn a_clone_past_its_size_limit_stops_and_leaves_nothing_behind() {
let scratch =
Scratch(std::env::temp_dir().join(format!("cs-git-{}", uuid::Uuid::new_v4())));
let ops = git_ops(&scratch.0).with_limits(CloneLimits {
max_bytes: 64 * 1024,
..CloneLimits::default()
});
let err = ops
.clone_or_fetch("https://github.com/github/gitignore.git", "big")
.expect_err("over the limit");
assert!(err.to_string().contains("GIT_CLONE_MAX_MB"), "{err}");
assert!(!ops.clone_path("big").exists(), "no half-cloned directory");
let small = git_ops(&scratch.0)
.clone_or_fetch("https://github.com/octocat/Hello-World.git", "small")
.expect("within the limits");
assert!(small.join("README").exists());
}
#[test]
fn a_remote_on_a_private_address_is_refused_before_connecting() {
let scratch =
+171 -1
View File
@@ -8,6 +8,48 @@ use crate::pipeline::dedup;
pub struct GitleaksScanner;
/// gitleaks' own rules plus ours (Android signing passwords, Firebase API
/// keys), passed with `--config` on every run.
const RULES: &str = include_str!("../../rules/gitleaks.toml");
/// Our rule for the API key of a Firebase configuration file.
const FIREBASE_RULE: &str = "firebase-config-api-key";
/// The Firebase configuration files [`FIREBASE_RULE`] covers; gitleaks' own
/// `gcp-api-key` reports the same key there, once is enough.
const FIREBASE_CONFIGS: [&str; 2] = ["google-services.json", "googleservice-info.plist"];
/// Whether a result only repeats what [`FIREBASE_RULE`] reports.
fn repeats_firebase_rule(rule_id: &str, file: &str) -> bool {
let name = file.rsplit('/').next().unwrap_or(file).to_lowercase();
rule_id == "gcp-api-key" && FIREBASE_CONFIGS.contains(&name.as_str())
}
/// The configuration of one run, in a temporary directory of its own (a
/// shared file would let concurrent scans pull it from under each other),
/// removed on drop.
struct RunConfig(std::path::PathBuf);
impl RunConfig {
fn write() -> std::io::Result<Self> {
let dir = std::env::temp_dir().join(format!("cs-gitleaks-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir)?;
let config = Self(dir);
std::fs::write(config.file(), RULES)?;
Ok(config)
}
fn file(&self) -> std::path::PathBuf {
self.0.join("gitleaks.toml")
}
}
impl Drop for RunConfig {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// How to point gitleaks at a tree. `detect` walks a git checkout's history;
/// on a directory that is not a checkout it scans **nothing** and reports no
/// leaks — a silent miss — so a plain tree (an uploaded source archive) is
@@ -31,10 +73,19 @@ impl Scanner for GitleaksScanner {
#[tracing::instrument(skip_all)]
async fn scan(&self, repo_path: &Path, repo_id: &str) -> Result<ScanOutput, CoreError> {
// Our configuration, always: without --config gitleaks reads a
// `.gitleaks.toml` from the scanned repository, which could switch
// rules off.
let config = RunConfig::write().map_err(|e| CoreError::Scanner {
scanner: "gitleaks".to_string(),
source: Box::new(e),
})?;
let output = tokio::time::timeout(
std::time::Duration::from_secs(300),
crate::pipeline::tool_cmd::tool("gitleaks", &[])
.args(source_args(repo_path))
.arg("--config")
.arg(config.file())
.args([
"--report-format",
"json",
@@ -67,8 +118,12 @@ impl Scanner for GitleaksScanner {
let findings = results
.into_iter()
.filter(|r| !is_allowlisted(&r.file))
.filter(|r| !repeats_firebase_rule(&r.rule_id, &r.file))
.map(|r| {
let severity = match r.rule_id.as_str() {
// It identifies the app; the risk is a key left
// unrestricted, not the key being known.
FIREBASE_RULE => Severity::Low,
s if s.contains("private-key") => Severity::Critical,
s if s.contains("token") || s.contains("password") || s.contains("secret") => {
Severity::High
@@ -85,13 +140,22 @@ impl Scanner for GitleaksScanner {
]);
let title = format!("Secret detected: {}", r.description);
let description = format!(
let mut description = format!(
"Potential secret ({}) found in {}:{}. Match: {}",
r.rule_id,
r.file,
r.start_line,
r.r#match.chars().take(80).collect::<String>(),
);
if r.rule_id == FIREBASE_RULE {
description.push_str(
"\n\nA Firebase API key in the app's configuration is shipped with the \
app and identifies it; it is not a secret on its own. Restrict it to the \
app (Android package and signing certificate, iOS bundle id) and to the \
APIs it needs in the Google Cloud console, so it cannot be used \
elsewhere.",
);
}
let mut finding = Finding::new(
repo_id.to_string(),
@@ -151,6 +215,112 @@ struct GitleaksResult {
mod tests {
use super::*;
#[test]
fn the_firebase_key_is_reported_once() {
assert!(repeats_firebase_rule(
"gcp-api-key",
"app/google-services.json"
));
assert!(repeats_firebase_rule(
"gcp-api-key",
"ios/PumpApp/GoogleService-Info.plist"
));
assert!(!repeats_firebase_rule("gcp-api-key", "src/maps.js"));
assert!(!repeats_firebase_rule(
FIREBASE_RULE,
"app/google-services.json"
));
}
#[test]
fn our_rules_extend_gitleaks_own() {
let config: toml::Table = RULES.parse().expect("valid TOML");
assert_eq!(config["extend"]["useDefault"].as_bool(), Some(true));
let ids: Vec<&str> = config["rules"]
.as_array()
.expect("rules")
.iter()
.filter_map(|r| r["id"].as_str())
.collect();
assert_eq!(
ids,
[
"android-keystore-password",
"android-signing-password-property",
FIREBASE_RULE
]
);
}
/// With the real gitleaks, where installed: signing passwords and
/// Firebase keys are found, and a repository's own `.gitleaks.toml`
/// changes nothing. (A `.gitleaksignore` in the repository is honoured
/// by gitleaks whatever it is told, like an inline `gitleaks:allow`.)
#[tokio::test]
async fn mobile_secrets_are_found_whatever_the_repository_configures() {
if std::process::Command::new("gitleaks")
.arg("version")
.output()
.is_err()
{
eprintln!("SKIP: gitleaks not installed");
return;
}
let dir = std::env::temp_dir().join(format!("cs-leaks-{}", uuid::Uuid::new_v4()));
let files = [
(
"app/build.gradle",
"signingConfigs { release {\n storePassword \"Pump-Release-2024!\"\n keyPassword System.getenv(\"KEY_PASSWORD\")\n} }\n",
),
("gradle.properties", "RELEASE_KEY_PASSWORD=Pump-Key-2024!\n"),
(
"app/google-services.json",
"{ \"api_key\": [{ \"current_key\": \"AIzaSyD3x9mK2pQ7rT1vW4yZ8bC6nF0hJ5lL2aB\" }] }\n",
),
// A repository trying to switch everything off.
(".gitleaks.toml", "[allowlist]\npaths = [\".*\"]\n"),
];
for (path, content) in files {
let full = dir.join(path);
std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir");
std::fs::write(full, content).expect("write");
}
let output = GitleaksScanner.scan(&dir, "t").await.expect("scan");
let _ = std::fs::remove_dir_all(&dir);
let mut found: Vec<(String, String, Severity)> = output
.findings
.into_iter()
.map(|f| {
(
f.rule_id.unwrap_or_default(),
f.file_path.unwrap_or_default(),
f.severity,
)
})
.collect();
found.sort_by(|a, b| a.0.cmp(&b.0));
assert_eq!(
found,
[
(
"android-keystore-password".to_string(),
"app/build.gradle".to_string(),
Severity::High
),
(
"android-signing-password-property".to_string(),
"gradle.properties".to_string(),
Severity::High
),
(
FIREBASE_RULE.to_string(),
"app/google-services.json".to_string(),
Severity::Low
),
]
);
}
// --- is_allowlisted tests ---
#[test]
+274 -71
View File
@@ -12,73 +12,46 @@ impl PipelineOrchestrator {
/// Build an issue tracker client from a repository's tracker configuration.
/// Returns `None` if the repo has no tracker configured.
pub(super) fn build_tracker(&self, repo: &RepoView) -> Option<TrackerDispatch> {
let tracker_type = repo.tracker_type.as_ref()?;
// Per-repo token takes precedence, fall back to global config
match tracker_type {
TrackerType::GitHub => {
let token = repo.tracker_token.clone().or_else(|| {
self.config.github_token.as_ref().map(|t| {
use secrecy::ExposeSecret;
t.expose_secret().to_string()
})
})?;
let secret = secrecy::SecretString::from(token);
match trackers::github::GitHubTracker::new(&secret) {
Ok(t) => Some(TrackerDispatch::GitHub(t)),
Err(e) => {
tracing::warn!("Failed to build GitHub tracker: {e}");
None
}
}
}
TrackerType::GitLab => {
let base_url = self
.config
.gitlab_url
.clone()
.unwrap_or_else(|| "https://gitlab.com".to_string());
let token = repo.tracker_token.clone().or_else(|| {
self.config.gitlab_token.as_ref().map(|t| {
use secrecy::ExposeSecret;
t.expose_secret().to_string()
})
})?;
let secret = secrecy::SecretString::from(token);
Some(TrackerDispatch::GitLab(
trackers::gitlab::GitLabTracker::new(base_url, secret),
))
}
TrackerType::Gitea => {
let token = repo.tracker_token.clone()?;
let base_url = extract_base_url(&repo.git_url)?;
let secret = secrecy::SecretString::from(token);
match trackers::gitea::GiteaTracker::new(base_url, secret, self.net_guard) {
Ok(t) => Some(TrackerDispatch::Gitea(t)),
Err(e) => {
tracing::warn!("Failed to build Gitea tracker: {e}");
None
}
}
}
TrackerType::Jira => {
let base_url = self.config.jira_url.clone()?;
let email = self.config.jira_email.clone()?;
let project_key = self.config.jira_project_key.clone()?;
let token = repo.tracker_token.clone().or_else(|| {
self.config.jira_api_token.as_ref().map(|t| {
use secrecy::ExposeSecret;
t.expose_secret().to_string()
})
})?;
let secret = secrecy::SecretString::from(token);
Some(TrackerDispatch::Jira(trackers::jira::JiraTracker::new(
base_url,
email,
secret,
project_key,
)))
}
build_tracker(&self.config, self.net_guard, repo)
}
/// Open, reopen and close the CVE issues of a managed repository (see
/// [`crate::pipeline::cve_issues`]); other targets get none.
pub(super) async fn sync_cve_issues(
&self,
repo: &RepoView,
repo_id: &str,
alerts: &[CveAlert],
complete: bool,
) -> Result<(), AgentError> {
if !repo.managed {
return Ok(());
}
let (Some(tracker), Some(owner), Some(name)) = (
self.build_tracker(repo),
repo.tracker_owner.as_deref(),
repo.tracker_repo.as_deref(),
) else {
return Ok(());
};
let dashboard = std::env::var("DASHBOARD_PUBLIC_URL").unwrap_or_default();
let target = crate::pipeline::cve_issues::CveIssueTarget {
db: &self.db,
tracker: &tracker,
owner,
repo: name,
target_id: repo_id,
dashboard: &dashboard,
};
let counts =
crate::pipeline::cve_issues::sync_cve_issues(&target, alerts, complete).await?;
tracing::info!(
"[{repo_id}] CVE issues: {} opened, {} reopened, {} closed",
counts.created,
counts.reopened,
counts.closed
);
Ok(())
}
/// Create tracker issues for new findings (severity >= Medium).
@@ -135,6 +108,28 @@ impl PipelineOrchestrator {
tracker.name()
);
// A managed repository (#439) gets its labels created once per run
// and attached by id. If that fails (no permission), the issues are
// still opened, with the label names in the body as before.
let managed_labels = match (&tracker, repo.managed) {
(TrackerDispatch::Gitea(gitea), true) => match gitea
.ensure_labels(
owner,
tracker_repo_name,
&trackers::gitea::pruefwerk_labels(),
)
.await
{
Ok(ids) => Some(ids),
Err(e) => {
tracing::warn!("[{repo_id}] Could not ensure the Prüfwerk labels: {e}");
None
}
},
_ => None,
};
let dashboard = std::env::var("DASHBOARD_PUBLIC_URL").unwrap_or_default();
let mut created = 0u32;
for finding in actionable {
let title = format!(
@@ -167,17 +162,43 @@ impl PipelineOrchestrator {
if found_existing {
continue;
}
let body = format_issue_body(finding);
let mut body = format_issue_body(finding);
if repo.managed {
if let Some(link) = finding_link(&dashboard, repo_id) {
body.push_str(&format!(
"\n[Open in Prüfwerk / In Prüfwerk öffnen]({link})"
));
}
}
let labels = vec![
format!("severity:{}", finding.severity),
format!("scanner:{}", finding.scanner),
"compliance-scanner".to_string(),
];
match tracker
.create_issue(owner, tracker_repo_name, &title, &body, &labels)
.await
{
let result = match (&tracker, &managed_labels) {
(TrackerDispatch::Gitea(gitea), Some(ids)) => {
let label_ids = label_ids(
ids,
&trackers::gitea::issue_label_names(&finding.severity.to_string()),
);
gitea
.create_issue_with_label_ids(
owner,
tracker_repo_name,
&title,
&body,
&label_ids,
)
.await
}
_ => {
tracker
.create_issue(owner, tracker_repo_name, &title, &body, &labels)
.await
}
};
match result {
Ok(mut issue) => {
issue.finding_id = finding
.id
@@ -218,6 +239,87 @@ impl PipelineOrchestrator {
}
}
/// Build an issue tracker client from a repository's tracker configuration.
/// Returns `None` if the repo has no tracker configured.
///
/// # Arguments
///
/// * `config` - the agent configuration (global tracker tokens and URLs)
/// * `net_guard` - where a self-hosted tracker may connect
/// * `repo` - the target, with its own tracker settings and token
pub(crate) fn build_tracker(
config: &compliance_core::AgentConfig,
net_guard: compliance_core::NetGuard,
repo: &RepoView,
) -> Option<TrackerDispatch> {
let tracker_type = repo.tracker_type.as_ref()?;
// Per-repo token takes precedence, fall back to global config
match tracker_type {
TrackerType::GitHub => {
let token = repo.tracker_token.clone().or_else(|| {
config.github_token.as_ref().map(|t| {
use secrecy::ExposeSecret;
t.expose_secret().to_string()
})
})?;
let secret = secrecy::SecretString::from(token);
match trackers::github::GitHubTracker::new(&secret) {
Ok(t) => Some(TrackerDispatch::GitHub(t)),
Err(e) => {
tracing::warn!("Failed to build GitHub tracker: {e}");
None
}
}
}
TrackerType::GitLab => {
let base_url = config
.gitlab_url
.clone()
.unwrap_or_else(|| "https://gitlab.com".to_string());
let token = repo.tracker_token.clone().or_else(|| {
config.gitlab_token.as_ref().map(|t| {
use secrecy::ExposeSecret;
t.expose_secret().to_string()
})
})?;
let secret = secrecy::SecretString::from(token);
Some(TrackerDispatch::GitLab(
trackers::gitlab::GitLabTracker::new(base_url, secret),
))
}
TrackerType::Gitea => {
let token = repo.tracker_token.clone()?;
let base_url = extract_base_url(&repo.git_url)?;
let secret = secrecy::SecretString::from(token);
match trackers::gitea::GiteaTracker::new(base_url, secret, net_guard) {
Ok(t) => Some(TrackerDispatch::Gitea(t)),
Err(e) => {
tracing::warn!("Failed to build Gitea tracker: {e}");
None
}
}
}
TrackerType::Jira => {
let base_url = config.jira_url.clone()?;
let email = config.jira_email.clone()?;
let project_key = config.jira_project_key.clone()?;
let token = repo.tracker_token.clone().or_else(|| {
config.jira_api_token.as_ref().map(|t| {
use secrecy::ExposeSecret;
t.expose_secret().to_string()
})
})?;
let secret = secrecy::SecretString::from(token);
Some(TrackerDispatch::Jira(trackers::jira::JiraTracker::new(
base_url,
email,
secret,
project_key,
)))
}
}
}
/// Format a finding into a markdown issue body for the tracker.
pub(super) fn format_issue_body(finding: &Finding) -> String {
let mut body = String::new();
@@ -232,6 +334,9 @@ pub(super) fn format_issue_body(finding: &Finding) -> String {
if let Some(cwe) = &finding.cwe {
body.push_str(&format!("**CWE:** {}\n", cwe));
}
for requirement in cra_requirements(&finding.control_refs) {
body.push_str(&format!("**CRA:** {requirement}\n"));
}
body.push_str(&format!("\n### Description\n\n{}\n", finding.description));
@@ -262,3 +367,101 @@ pub(super) fn format_issue_body(finding: &Finding) -> String {
body
}
/// The CRA requirements a finding is evidence for, as `cra-ai-8 — <title>`,
/// from its stamped `control_refs`. Titles come from the CRA control map.
fn cra_requirements(control_refs: &[String]) -> Vec<String> {
let map = control_map::ControlMap::cra().ok();
control_refs
.iter()
.filter(|id| id.starts_with("cra-"))
.map(|id| {
match map
.as_ref()
.and_then(|m| m.coverage(id))
.map(|c| c.title.as_str())
.filter(|t| !t.is_empty())
{
Some(title) => format!("{id} — {title} (Annex I)"),
None => format!("{id} (Annex I)"),
}
})
.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> {
let dashboard = dashboard.trim_end_matches('/');
dashboard
.starts_with("https://")
.then(|| format!("{dashboard}/findings?target={target_id}"))
}
/// The ids of `names` among the ensured labels; a name without an id is left
/// out.
fn label_ids(ids: &std::collections::HashMap<String, i64>, names: &[String]) -> Vec<i64> {
names.iter().filter_map(|n| ids.get(n).copied()).collect()
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
#[test]
fn cra_requirements_name_the_control() {
let refs = vec!["cra-ai-1".to_string(), "iec-x".to_string()];
let lines = cra_requirements(&refs);
assert_eq!(lines.len(), 1);
assert!(lines[0].starts_with("cra-ai-1 — "), "{lines:?}");
assert!(lines[0].ends_with("(Annex I)"));
assert_eq!(
cra_requirements(&["cra-unknown".to_string()]),
["cra-unknown (Annex I)"]
);
}
#[test]
fn the_body_carries_cwe_and_cra() {
let mut f = Finding::new(
"r".into(),
"fp1".into(),
"semgrep".into(),
ScanType::Sast,
"SQL injection".into(),
"desc".into(),
Severity::High,
);
f.cwe = Some("CWE-89".into());
f.control_refs = vec!["cra-ai-1".into()];
let body = format_issue_body(&f);
assert!(body.contains("**CWE:** CWE-89"));
assert!(body.contains("**CRA:** cra-ai-1"));
assert!(body.contains("`fp1`"));
}
#[test]
fn links_only_to_an_https_dashboard() {
assert_eq!(
finding_link("https://pruefwerk.breakpilot.com/", "t1").as_deref(),
Some("https://pruefwerk.breakpilot.com/findings?target=t1")
);
assert_eq!(finding_link("", "t1"), None);
assert_eq!(finding_link("http://x", "t1"), None);
}
#[test]
fn label_ids_follow_the_names() {
let ids = std::collections::HashMap::from([
("pruefwerk".to_string(), 1),
("cra:annex-i".to_string(), 2),
("severity:high".to_string(), 5),
]);
let names = crate::trackers::gitea::issue_label_names("high");
assert_eq!(label_ids(&ids, &names), vec![1, 2, 5]);
// a label that could not be ensured is simply left off
let names = crate::trackers::gitea::issue_label_names("low");
assert_eq!(label_ids(&ids, &names), vec![1, 2]);
}
}
+485
View File
@@ -0,0 +1,485 @@
//! A finding's status, carried over to the issue opened for it.
//!
//! When a finding is closed in Prüfwerk (fixed, a false alarm, set aside, or
//! an accepted risk) its issue in the repository is closed with a comment
//! saying why; an accepted risk also gets the `risk:accepted` label on Gitea.
//! A finding that comes back (the scan finds it again, or a person reopens it)
//! reopens its issue. The sync reads each finding's status when it runs, so a
//! change made in between is the one carried over.
use mongodb::bson::{doc, oid::ObjectId};
use compliance_core::models::{
FindingStatus, IssueStatus, OnboardedTarget, ScanChangeKind, StatusChange, TrackerIssue,
};
use compliance_core::{AgentConfig, NetGuard};
use crate::database::Database;
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::{pruefwerk_labels, LABEL_ACCEPTED_RISK};
/// What the sync needs from the agent, owned so it can run in the background.
#[derive(Clone)]
pub(crate) struct IssueSync {
pub db: Database,
pub config: AgentConfig,
pub secrets: SecretBox,
pub net_guard: NetGuard,
}
/// What a finding's status means for its issue.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum IssueAction {
/// Close it; `accepted_risk` also labels it.
Close {
accepted_risk: bool,
},
Reopen,
}
impl IssueAction {
/// The action for a finding with `status`.
fn for_status(status: &FindingStatus) -> Self {
match status {
FindingStatus::Open | FindingStatus::Triaged | FindingStatus::NeedsReview => {
Self::Reopen
}
FindingStatus::AcceptedRisk => Self::Close {
accepted_risk: true,
},
FindingStatus::Resolved
| FindingStatus::FalsePositive
| FindingStatus::WrongMapping
| FindingStatus::Ignored => Self::Close {
accepted_risk: false,
},
}
}
/// Whether the issue, in `status`, already reflects this action.
fn done(self, status: &IssueStatus) -> bool {
let closed = matches!(status, IssueStatus::Closed | IssueStatus::Resolved);
match self {
Self::Close { .. } => closed,
Self::Reopen => !closed,
}
}
}
impl IssueSync {
/// Carry the current status of the findings `ids` over to their issues,
/// in the background. Findings without an issue are skipped; a tracker
/// that cannot be reached is logged, and the next change tries again.
pub(crate) fn spawn(self, ids: Vec<ObjectId>) {
if ids.is_empty() {
return;
}
tokio::spawn(async move {
for id in ids {
if let Err(e) = self.sync_one(id).await {
tracing::warn!(finding = %id, error = %e, "issue status not synced");
}
}
});
}
/// Carry the status of finding `id` over to its issue, if it has one.
async fn sync_one(&self, id: ObjectId) -> Result<(), String> {
let Some(issue) = self
.db
.tracker_issues()
.find_one(doc! { "finding_id": id.to_hex() })
.await
.map_err(|e| e.to_string())?
else {
return Ok(());
};
let finding = self
.db
.findings()
.find_one(doc! { "_id": id })
.await
.map_err(|e| e.to_string())?
.ok_or("finding gone")?;
let action = IssueAction::for_status(&finding.status);
if action.done(&issue.status) {
return Ok(());
}
let target_id = ObjectId::parse_str(&finding.repo_id).map_err(|e| e.to_string())?;
let target: OnboardedTarget = self
.db
.onboarded_targets()
.find_one(doc! { "_id": target_id })
.await
.map_err(|e| e.to_string())?
.ok_or("target gone")?;
let code = target
.code_artifact()
.ok_or("target has no code artifact")?;
let repo = RepoView::from_target(&target, code, &self.secrets);
let tracker =
build_tracker(&self.config, self.net_guard, &repo).ok_or("no tracker configured")?;
let (Some(owner), Some(name)) =
(repo.tracker_owner.as_deref(), repo.tracker_repo.as_deref())
else {
return Err("tracker owner or repository not set".into());
};
let comment = comment(&finding.status, finding.status_history.last());
let number = issue.external_id.as_str();
tracker
.add_comment(owner, name, number, &comment)
.await
.map_err(|e| e.to_string())?;
if let IssueAction::Close {
accepted_risk: true,
} = action
{
label_accepted_risk(&tracker, owner, name, number).await;
}
let (state, status) = match action {
IssueAction::Close { .. } => ("closed", IssueStatus::Closed),
IssueAction::Reopen => ("open", IssueStatus::Open),
};
tracker
.update_issue_status(owner, name, number, state)
.await
.map_err(|e| e.to_string())?;
self.record(&issue, status).await
}
/// Store the issue's new state.
async fn record(&self, issue: &TrackerIssue, status: IssueStatus) -> Result<(), String> {
let Some(id) = issue.id else {
return Ok(());
};
let status = mongodb::bson::to_bson(&status).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() } },
)
.await
.map(drop)
.map_err(|e| e.to_string())
}
}
/// Put the `risk:accepted` label on a Gitea issue. Other trackers keep only
/// the comment; a label that cannot be set does not stop the close.
async fn label_accepted_risk(tracker: &TrackerDispatch, owner: &str, repo: &str, number: &str) {
let TrackerDispatch::Gitea(gitea) = tracker else {
return;
};
let labelled = async {
let ids = gitea
.ensure_labels(owner, repo, &pruefwerk_labels())
.await?;
let label: Vec<i64> = ids.get(LABEL_ACCEPTED_RISK).copied().into_iter().collect();
gitea.add_labels(owner, repo, number, &label).await
};
if let Err(e) = labelled.await {
tracing::warn!(error = %e, "could not label the accepted risk");
}
}
/// The comment explaining a change to `status`, German then English like the
/// labels, with the reason a person or the scan gave.
fn comment(status: &FindingStatus, change: Option<&StatusChange>) -> String {
let by_scan = change.and_then(|c| c.scan.as_ref()).map(|s| s.kind);
let (de, en) = match (status, by_scan) {
(FindingStatus::Resolved, Some(ScanChangeKind::NoLongerFound)) => (
"Bei der Prüfung nicht mehr gefunden, daher als behoben markiert.",
"No longer found by the scan, so marked resolved.",
),
(FindingStatus::Resolved, Some(ScanChangeKind::NowVendorCode)) => (
"Die Datei gilt jetzt als Herstellercode und ist von den Befunden ausgenommen.",
"The file now counts as vendor code, which is left out of the findings.",
),
(FindingStatus::Resolved, _) => (
"In Prüfwerk als behoben markiert.",
"Marked resolved in Prüfwerk.",
),
(FindingStatus::FalsePositive, _) => (
"In Prüfwerk als Fehlalarm (Regel) markiert.",
"Marked a false positive (rule) in Prüfwerk.",
),
(FindingStatus::WrongMapping, _) => (
"In Prüfwerk als Fehlalarm (Zuordnung) markiert: Die CRA-Anforderung trifft nicht zu.",
"Marked a false positive (mapping) in Prüfwerk: the CRA requirement does not apply.",
),
(FindingStatus::Ignored, _) => ("In Prüfwerk ignoriert.", "Ignored in Prüfwerk."),
(FindingStatus::AcceptedRisk, _) => (
"In Prüfwerk als akzeptiertes Risiko geschlossen, nicht behoben.",
"Closed in Prüfwerk as an accepted risk, not fixed.",
),
(_, Some(ScanChangeKind::FoundAgain)) => (
"Bei der Prüfung erneut gefunden, daher wieder geöffnet.",
"Found again by the scan, so reopened.",
),
_ => ("In Prüfwerk wieder geöffnet.", "Reopened in Prüfwerk."),
};
let mut text = format!("**Prüfwerk:** {de}\n\n{en}");
if let Some(reason) = change
.and_then(|c| c.reason.as_deref())
.filter(|r| !r.trim().is_empty())
{
text.push_str(&format!("\n\n> {}", reason.trim().replace('\n', "\n> ")));
}
text
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use std::sync::{Arc, Mutex};
use axum::extract::{Path, State};
use axum::routing::{get, patch, post};
use axum::{Json, Router};
use compliance_core::models::{
Artifact, Finding, IssueTrackerConfig, ScanType, Severity, TargetType, TrackerType,
};
/// The calls a fake Gitea received, as `"<what> <issue>: <detail>"`.
type Calls = Arc<Mutex<Vec<String>>>;
async fn fake_gitea(calls: Calls) -> String {
async fn labels() -> Json<serde_json::Value> {
// Every Prüfwerk label exists already; risk:accepted is id 42.
Json(serde_json::json!(pruefwerk_labels()
.iter()
.enumerate()
.map(|(i, l)| serde_json::json!({
"id": if l.name == LABEL_ACCEPTED_RISK { 42 } else { i as i64 },
"name": l.name,
"color": "ffffff",
}))
.collect::<Vec<_>>()))
}
async fn comment(
State(calls): State<Calls>,
Path((_o, _r, n)): Path<(String, String, String)>,
Json(body): Json<serde_json::Value>,
) -> axum::http::StatusCode {
let text = body["body"].as_str().unwrap_or_default();
calls.lock().unwrap().push(format!("comment {n}: {text}"));
axum::http::StatusCode::CREATED
}
async fn state(
State(calls): State<Calls>,
Path((_o, _r, n)): Path<(String, String, String)>,
Json(body): Json<serde_json::Value>,
) -> Json<serde_json::Value> {
calls
.lock()
.unwrap()
.push(format!("state {n}: {}", body["state"]));
Json(serde_json::json!({}))
}
async fn add_labels(
State(calls): State<Calls>,
Path((_o, _r, n)): Path<(String, String, String)>,
Json(body): Json<serde_json::Value>,
) -> Json<serde_json::Value> {
calls
.lock()
.unwrap()
.push(format!("labels {n}: {}", body["labels"]));
Json(serde_json::json!([]))
}
let app = Router::new()
.route("/api/v1/repos/{o}/{r}/labels", get(labels))
.route("/api/v1/repos/{o}/{r}/issues/{n}/comments", post(comment))
.route("/api/v1/repos/{o}/{r}/issues/{n}", patch(state))
.route("/api/v1/repos/{o}/{r}/issues/{n}/labels", post(add_labels))
.with_state(calls);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
format!("http://{addr}")
}
#[tokio::test]
async fn an_issue_follows_its_findings_status() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!("isync_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP issue_sync: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id("issue-sync").await.unwrap();
let calls: Calls = Arc::default();
let base = fake_gitea(calls.clone()).await;
// Arrange: a managed repository's target, a finding and its issue #12.
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();
let mut finding = Finding::new(
target_id.to_hex(),
"fp-1".into(),
"semgrep".into(),
ScanType::Sast,
"strcpy".into(),
"d".into(),
Severity::High,
);
finding.status = FindingStatus::Resolved;
finding.status_history.push(StatusChange::by_scan(
FindingStatus::Resolved,
ScanChangeKind::NoLongerFound,
"run-1",
));
let finding_id = 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(),
format!("{base}/kunde/fw/issues/12"),
"strcpy".into(),
);
db.tracker_issues().insert_one(&issue).await.unwrap();
let sync = IssueSync {
db: db.clone(),
config: AgentConfig::default(),
secrets: SecretBox::without_key(),
net_guard: NetGuard::allow_private(),
};
let issue_status = || async {
db.tracker_issues()
.find_one(doc! { "finding_id": finding_id.to_hex() })
.await
.unwrap()
.unwrap()
.status
};
// Act + assert: the scan closed it, so the issue closes with a comment.
sync.sync_one(finding_id).await.unwrap();
assert_eq!(issue_status().await, IssueStatus::Closed);
{
let calls = calls.lock().unwrap();
assert!(calls[0]
.starts_with("comment 12: **Prüfwerk:** Bei der Prüfung nicht mehr gefunden"));
assert_eq!(calls[1], "state 12: \"closed\"");
}
// Synced again with no change: nothing more is sent.
sync.sync_one(finding_id).await.unwrap();
assert_eq!(calls.lock().unwrap().len(), 2);
// It comes back: the issue reopens.
db.findings()
.update_one(
doc! { "_id": finding_id },
doc! { "$set": { "status": "open" } },
)
.await
.unwrap();
sync.sync_one(finding_id).await.unwrap();
assert_eq!(issue_status().await, IssueStatus::Open);
assert_eq!(calls.lock().unwrap().last().unwrap(), "state 12: \"open\"");
// A person accepts the risk: labelled, then closed.
db.findings()
.update_one(
doc! { "_id": finding_id },
doc! { "$set": { "status": "accepted_risk" } },
)
.await
.unwrap();
sync.sync_one(finding_id).await.unwrap();
{
let calls = calls.lock().unwrap();
let tail: Vec<&str> = calls.iter().rev().take(2).map(String::as_str).collect();
assert_eq!(tail, ["state 12: \"closed\"", "labels 12: [42]"]);
}
pool.drop_tenant("issue-sync").await.ok();
}
fn by_scan(status: FindingStatus, kind: ScanChangeKind) -> StatusChange {
StatusChange::by_scan(status, kind, "run-1")
}
#[test]
fn closing_statuses_close_and_open_ones_reopen() {
assert_eq!(
IssueAction::for_status(&FindingStatus::Resolved),
IssueAction::Close {
accepted_risk: false
}
);
assert_eq!(
IssueAction::for_status(&FindingStatus::AcceptedRisk),
IssueAction::Close {
accepted_risk: true
}
);
assert_eq!(
IssueAction::for_status(&FindingStatus::NeedsReview),
IssueAction::Reopen
);
// Nothing to do when the issue already matches.
assert!(IssueAction::Reopen.done(&IssueStatus::Open));
assert!(IssueAction::Close {
accepted_risk: false
}
.done(&IssueStatus::Closed));
assert!(!IssueAction::Reopen.done(&IssueStatus::Closed));
}
#[test]
fn the_comment_says_why_in_german_and_english() {
let fixed = comment(
&FindingStatus::Resolved,
Some(&by_scan(
FindingStatus::Resolved,
ScanChangeKind::NoLongerFound,
)),
);
assert!(fixed.contains("nicht mehr gefunden") && fixed.contains("No longer found"));
let back = comment(
&FindingStatus::Open,
Some(&by_scan(FindingStatus::Open, ScanChangeKind::FoundAgain)),
);
assert!(back.contains("erneut gefunden"));
let mut risk = by_scan(FindingStatus::AcceptedRisk, ScanChangeKind::NoLongerFound);
risk.scan = None;
risk.reason = Some("Only reachable on the isolated machine network.".into());
let accepted = comment(&FindingStatus::AcceptedRisk, Some(&risk));
assert!(accepted.contains("akzeptiertes Risiko"));
assert!(accepted.ends_with("> Only reachable on the isolated machine network."));
}
}
@@ -26,6 +26,9 @@ fn language_of(extension: &str) -> Option<&'static str> {
"rs" => "rust",
"cs" => "csharp",
"swift" => "swift",
// Objective-C; `.m` is also MATLAB's extension, which only means
// mobsfscan looks at a tree it finds nothing in.
"m" | "mm" => "objc",
_ => return None,
})
}
+507
View File
@@ -0,0 +1,507 @@
//! Mobile app SAST with mobsfscan (LGPL-3.0, rules used unchanged).
//!
//! mobsfscan checks Android and iOS source: Java and Kotlin, Swift and
//! Objective-C code (WebView bridges, weak crypto, insecure storage, TLS
//! handling), and the AndroidManifest and Info.plist settings (debuggable,
//! backups, cleartext traffic, App Transport Security exceptions). It runs its
//! rules on the semgrep engine with metrics off.
//!
//! Two of its defaults are not safe for a customer's tree, so the image runs it
//! through a wrapper (`docker/pruefwerk_mobsfscan.py`) and always passes our own config:
//! - libsast skips every file whose path merely *contains* an ignored name, and
//! the defaults include `spec` and `fixtures`, so code under `inspection/`
//! would vanish. The wrapper clears them; ours are anchored as `/name/`.
//! - Without `-c`, mobsfscan reads a `.mobsf` file from the scanned tree, which
//! would let the repository switch rules off.
//!
//! And with `--type auto` it configures the iOS rules only when the tree has no
//! Android code, so a React Native, Flutter or monorepo app would be checked as
//! Android only. It runs once per platform present instead.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use compliance_core::models::{Finding, ScanType, Severity};
use compliance_core::traits::{ScanOutput, Scanner};
use compliance_core::CoreError;
use crate::pipeline::dedup;
use crate::pipeline::source_text::{read_lines, read_text, relative_path};
/// The wrapper the agent image installs (see `Dockerfile.agent`).
const WRAPPER: &str = "/opt/pruefwerk/pruefwerk_mobsfscan.py";
/// Source languages of Android apps, by the names
/// [`crate::pipeline::languages`] records.
const ANDROID_LANGUAGES: [&str; 2] = ["java", "kotlin"];
/// Source languages of iOS apps.
const IOS_LANGUAGES: [&str; 2] = ["swift", "objc"];
/// Directories never analysed: build output, installed dependencies and tool
/// caches. Vendor directories are added per tree.
const SKIPPED_DIRS: &[&str] = &[
".git",
".gradle",
"build",
"DerivedData",
"node_modules",
"Pods",
"Carthage",
];
/// How long a scan may take before it is stopped and recorded as failed.
const TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600);
/// mobsfscan over a tree, skipping vendor and build directories.
#[derive(Debug, Default)]
pub struct MobsfscanScanner {
/// Directories (relative to the tree) left out of the analysis.
excluded: Vec<String>,
/// The `--type` of each run: `android`, `ios`, or both.
platforms: Vec<&'static str>,
}
impl MobsfscanScanner {
/// A scanner for a tree whose source `languages` include one mobsfscan
/// checks, skipping the `excluded` vendor directories; `None` otherwise.
///
/// # Arguments
///
/// * `languages` - the source languages found outside vendor code
/// * `excluded` - vendor directories relative to the tree
pub fn for_languages(languages: &[String], excluded: &[String]) -> Option<Self> {
let has = |set: &[&str]| languages.iter().any(|l| set.contains(&l.as_str()));
let platforms: Vec<&'static str> = [
("android", has(&ANDROID_LANGUAGES)),
("ios", has(&IOS_LANGUAGES)),
]
.into_iter()
.filter_map(|(platform, present)| present.then_some(platform))
.collect();
(!platforms.is_empty()).then(|| Self {
excluded: excluded.to_vec(),
platforms,
})
}
/// The `.mobsf` config passed with `-c`: the skipped and vendor
/// directories, anchored so a name only matches a whole path component.
fn config(&self) -> String {
let mut config = String::from("---\n- ignore-paths:\n");
for dir in SKIPPED_DIRS
.iter()
.copied()
.chain(self.excluded.iter().map(String::as_str))
{
// Quoted for YAML; a vendor path has no quote or backslash.
config.push_str(&format!(" - \"/{dir}/\"\n"));
}
config
}
}
impl Scanner for MobsfscanScanner {
fn name(&self) -> &str {
"mobsfscan"
}
fn scan_type(&self) -> ScanType {
ScanType::Sast
}
#[tracing::instrument(skip_all)]
async fn scan(&self, repo_path: &Path, repo_id: &str) -> Result<ScanOutput, CoreError> {
let work = WorkFiles::new(&self.config()).map_err(|e| failed(Box::new(e)))?;
let mut findings = Vec::new();
for platform in &self.platforms {
findings.extend(run(repo_path, repo_id, platform, &work).await?);
}
Ok(ScanOutput {
findings,
sbom_entries: Vec::new(),
})
}
}
/// A scanner error with `source` as its cause.
fn failed(source: Box<dyn std::error::Error + Send + Sync>) -> CoreError {
CoreError::Scanner {
scanner: "mobsfscan".to_string(),
source,
}
}
/// One mobsfscan run over `repo_path` with the rules of `platform`.
///
/// # Errors
///
/// Returns `CoreError::Scanner` when mobsfscan cannot start, times out, exits
/// with an error, or reports errors and nothing else.
async fn run(
repo_path: &Path,
repo_id: &str,
platform: &str,
work: &WorkFiles,
) -> Result<Vec<Finding>, CoreError> {
let report_path = work.report(platform);
let mut cmd = crate::pipeline::tool_cmd::tool("python3", &[]);
cmd.arg(WRAPPER)
// Threads, not processes: mobsfscan's default process pool breaks
// under Python 3.14's start method, and semgrep runs as its own
// process anyway.
.args(["--json", "--no-fail", "--multiprocessing", "thread"])
.args(["--type", platform, "-c"])
.arg(work.config())
.arg("-o")
.arg(&report_path)
// Code matches come back absolute, manifest and plist matches
// relative to the working directory: from the tree, both resolve.
.arg(repo_path)
.current_dir(repo_path);
let output = tokio::time::timeout(TIMEOUT, cmd.output())
.await
.map_err(|_| failed("timed out after 10 minutes".into()))?
.map_err(|e| failed(Box::new(e)))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let tail: String = stderr.lines().rev().take(3).collect::<Vec<_>>().join(" / ");
return Err(failed(
format!("{platform} run exited with {}: {tail}", output.status).into(),
));
}
let report = std::fs::read(&report_path).map_err(|e| failed(Box::new(e)))?;
let report: Report = serde_json::from_slice(&report)?;
// A tool error with nothing found means nothing was checked.
if report.results.is_empty() && !report.errors.is_empty() {
return Err(failed(
format!(
"{platform} run reported errors: {}",
report.errors.join(" / ")
)
.into(),
));
}
for error in &report.errors {
tracing::warn!(%error, platform, "mobsfscan reported an error");
}
Ok(report.findings(repo_path, repo_id))
}
/// mobsfscan's JSON report.
#[derive(Debug, serde::Deserialize)]
struct Report {
#[serde(default)]
results: BTreeMap<String, RuleResult>,
#[serde(default)]
errors: Vec<String>,
}
/// One rule's matches and what it says about them.
#[derive(Debug, serde::Deserialize)]
struct RuleResult {
/// Where the rule matched. Empty for the "best practice" rules, which
/// report that a protection is missing from the whole app (no pinning, no
/// root detection); those are heuristics with no location to show.
#[serde(default)]
files: Vec<Match>,
metadata: Metadata,
}
#[derive(Debug, serde::Deserialize)]
struct Match {
file_path: String,
match_lines: (u32, u32),
#[serde(default)]
match_string: String,
}
#[derive(Debug, serde::Deserialize)]
struct Metadata {
#[serde(default)]
cwe: String,
#[serde(default)]
description: String,
#[serde(default)]
masvs: String,
#[serde(default)]
reference: String,
#[serde(default)]
severity: String,
}
impl Report {
/// One finding per rule and location.
fn findings(self, root: &Path, repo_id: &str) -> Vec<Finding> {
self.results
.into_iter()
.flat_map(|(rule, result)| {
result
.files
.iter()
.map(|m| finding(root, repo_id, &rule, &result.metadata, m))
.collect::<Vec<_>>()
})
.collect()
}
}
/// The finding for rule `rule` matching at `m`.
fn finding(root: &Path, repo_id: &str, rule: &str, meta: &Metadata, m: &Match) -> Finding {
let file = relative_path(root, &m.file_path);
let (start, end) = located(root, &file, m);
let fingerprint =
dedup::compute_fingerprint(&[repo_id, "mobsfscan", rule, &file, &start.to_string()]);
let mut description = meta.description.clone();
if !meta.masvs.is_empty() {
description.push_str(&format!("\n\nOWASP MASVS: {}", meta.masvs));
}
if !meta.reference.is_empty() {
description.push_str(&format!("\nReference: {}", meta.reference));
}
let mut finding = Finding::new(
repo_id.to_string(),
fingerprint,
"mobsfscan".to_string(),
ScanType::Sast,
title(&meta.description, rule),
description,
match meta.severity.as_str() {
"ERROR" => Severity::High,
"WARNING" => Severity::Medium,
"INFO" => Severity::Low,
_ => Severity::Info,
},
);
finding.code_snippet = read_lines(root, &file, start, end);
finding.rule_id = Some(rule.to_string());
finding.cwe = normalise_cwe(&meta.cwe);
finding.line_number = Some(start);
finding.file_path = Some(file);
finding
}
/// The lines a match covers. Manifest and plist rules report line 1 with the
/// setting as `key=value` or `key<limit`; the line that sets the key is the
/// one to show. A match described in prose keeps line 1.
fn located(root: &Path, file: &str, m: &Match) -> (u32, u32) {
let is_config = file.ends_with(".xml") || file.ends_with(".plist");
let Some(key) = setting_key(&m.match_string) else {
return m.match_lines;
};
if m.match_lines != (1, 1) || !is_config {
return m.match_lines;
}
let Some(text) = read_text(root, file) else {
return m.match_lines;
};
text.lines()
.position(|line| line.contains(key))
.and_then(|i| u32::try_from(i + 1).ok())
.map_or(m.match_lines, |line| (line, line))
}
/// The setting a manifest or plist match names: `android:debuggable` in
/// `android:debuggable=true`, `android:minSdkVersion` in
/// `android:minSdkVersion<29`. `None` for prose.
fn setting_key(match_string: &str) -> Option<&str> {
let end = match_string
.find(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '_' | ':' | '.')))?;
let follows = match_string[end..].chars().next()?;
(end > 0 && matches!(follows, '=' | '<' | '>' | '!')).then(|| &match_string[..end])
}
/// A short title: the description's first sentence, or the rule id.
fn title(description: &str, rule: &str) -> String {
let first = description
.split_once(". ")
.map_or(description, |(first, _)| first)
.trim()
.trim_end_matches('.');
if first.is_empty() {
rule.to_string()
} else {
first.to_string()
}
}
/// `CWE-NNN` from mobsfscan's `cwe-489` or `CWE-327: Use of a Broken …`.
fn normalise_cwe(cwe: &str) -> Option<String> {
let rest = cwe
.get(..4)?
.eq_ignore_ascii_case("cwe-")
.then(|| &cwe[4..])?;
let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
(!digits.is_empty()).then(|| format!("CWE-{digits}"))
}
/// The config and report files of one run, in a temporary directory removed
/// on drop.
struct WorkFiles(PathBuf);
impl WorkFiles {
fn new(config: &str) -> std::io::Result<Self> {
let dir = std::env::temp_dir().join(format!("cs-mobsfscan-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir)?;
let files = Self(dir);
std::fs::write(files.config(), config)?;
Ok(files)
}
fn config(&self) -> PathBuf {
self.0.join(".mobsf")
}
fn report(&self, platform: &str) -> PathBuf {
self.0.join(format!("{platform}.json"))
}
}
impl Drop for WorkFiles {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
/// A scratch tree holding `files`, removed on drop.
struct Tree(PathBuf);
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn tree(files: &[(&str, &str)]) -> Tree {
let dir = std::env::temp_dir().join(format!("cs-mobsf-{}", uuid::Uuid::new_v4()));
for (path, content) in files {
let full = dir.join(path);
std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir");
std::fs::write(full, content).expect("write");
}
Tree(dir)
}
const MANIFEST: &str = "<manifest>\n <application\n android:debuggable=\"true\">\n </application>\n</manifest>\n";
fn report(root: &Path) -> String {
format!(
r#"{{
"errors": [],
"results": {{
"android_manifest_debugging_enabled": {{
"files": [{{
"file_path": "{root}/app/src/main/AndroidManifest.xml",
"match_lines": [1, 1],
"match_string": "android:debuggable=true"
}}],
"metadata": {{
"cwe": "cwe-489",
"description": "Debugging was enabled on the app which makes it easier for reverse engineers to hook a debugger to it. This allows dumping a stack trace.",
"masvs": "code-2",
"reference": "https://mas.owasp.org/",
"severity": "ERROR"
}}
}},
"android_root_detection": {{
"metadata": {{
"cwe": "CWE-919: Weaknesses in Mobile Applications",
"description": "This app does not have root detection capabilities.",
"severity": "INFO"
}}
}}
}}
}}"#,
root = root.display()
)
}
#[test]
fn a_manifest_finding_points_at_the_line_that_sets_it() {
let dir = tree(&[("app/src/main/AndroidManifest.xml", MANIFEST)]);
let parsed: Report = serde_json::from_str(&report(&dir.0)).expect("report");
let findings = parsed.findings(&dir.0, "t");
// The app-wide "missing protection" heuristic has no location.
assert_eq!(findings.len(), 1);
let f = &findings[0];
assert_eq!(
f.file_path.as_deref(),
Some("app/src/main/AndroidManifest.xml")
);
assert_eq!(f.line_number, Some(3));
assert_eq!(f.cwe.as_deref(), Some("CWE-489"));
assert_eq!(f.severity, Severity::High);
assert_eq!(
f.title,
"Debugging was enabled on the app which makes it easier for reverse engineers to hook a debugger to it"
);
assert!(f.description.contains("OWASP MASVS: code-2"));
assert_eq!(
f.rule_id.as_deref(),
Some("android_manifest_debugging_enabled")
);
}
#[test]
fn a_setting_key_is_read_only_from_a_comparison() {
assert_eq!(
setting_key("android:debuggable=true"),
Some("android:debuggable")
);
assert_eq!(
setting_key("android:minSdkVersion<29"),
Some("android:minSdkVersion")
);
assert_eq!(
setting_key("NSAllowsArbitraryLoads=true"),
Some("NSAllowsArbitraryLoads")
);
assert_eq!(setting_key("Activity exported, targetSdk<29"), None);
assert_eq!(setting_key(""), None);
}
#[test]
fn cwe_ids_are_normalised() {
assert_eq!(normalise_cwe("cwe-489").as_deref(), Some("CWE-489"));
assert_eq!(
normalise_cwe("CWE-327: Use of a Broken or Risky Cryptographic Algorithm").as_deref(),
Some("CWE-327")
);
assert_eq!(normalise_cwe(""), None);
assert_eq!(normalise_cwe("n/a"), None);
}
#[test]
fn each_platform_present_gets_its_own_run() {
let platforms = |l: &[&str]| {
let langs: Vec<String> = l.iter().map(|s| s.to_string()).collect();
MobsfscanScanner::for_languages(&langs, &[]).map(|s| s.platforms)
};
assert_eq!(platforms(&["kotlin"]), Some(vec!["android"]));
assert_eq!(platforms(&["c", "objc"]), Some(vec!["ios"]));
// A React Native or Flutter app: both, or the iOS rules never run.
assert_eq!(
platforms(&["java", "javascript", "swift"]),
Some(vec!["android", "ios"])
);
assert_eq!(platforms(&["python", "c"]), None);
}
#[test]
fn the_config_anchors_every_skipped_directory() {
let scanner =
MobsfscanScanner::for_languages(&["swift".to_string()], &["Vendor/SDK".to_string()])
.expect("scanner");
let config = scanner.config();
assert!(config.starts_with("---\n- ignore-paths:\n"));
assert!(config.contains(" - \"/Pods/\"\n"));
assert!(config.contains(" - \"/Vendor/SDK/\"\n"));
assert!(!config.contains("spec"));
}
}
+5
View File
@@ -1,7 +1,10 @@
pub mod build_lifecycle;
pub mod code_review;
pub mod cppcheck;
pub mod cve;
pub(crate) mod cve_issues;
pub mod dedup;
pub mod dotnet;
pub mod embedded_versions;
pub mod finding_store;
pub mod firmware_sbom;
@@ -10,8 +13,10 @@ pub mod git_submodules;
pub mod gitleaks;
mod graph_build;
mod issue_creation;
pub(crate) mod issue_sync;
pub mod languages;
pub mod lint;
pub mod mobsfscan;
pub mod nvd_cpe;
pub mod orchestrator;
pub mod patterns;
+221 -24
View File
@@ -15,10 +15,11 @@ use crate::pipeline::cve::CveScanner;
use crate::pipeline::git::GitOps;
use crate::pipeline::gitleaks::GitleaksScanner;
use crate::pipeline::lint::LintScanner;
use crate::pipeline::mobsfscan::MobsfscanScanner;
use crate::pipeline::patterns::{GdprPatternScanner, OAuthPatternScanner};
use crate::pipeline::plan::build_scan_plan;
use crate::pipeline::repo_view::RepoView;
use crate::pipeline::sbom::SbomScanner;
use crate::pipeline::sbom::{LicenseCache, NugetRegistry, SbomScanner};
use crate::pipeline::semgrep::SemgrepScanner;
use crate::secrets::SecretBox;
@@ -45,6 +46,8 @@ pub struct PipelineOrchestrator {
pub(super) secrets: SecretBox,
/// Where clones and tracker calls may connect (#256, #294).
pub(super) net_guard: NetGuard,
/// The cross-tenant cache of NuGet licenses (#467).
pub(super) nuget_license_cache: Option<Arc<dyn LicenseCache>>,
}
impl PipelineOrchestrator {
@@ -65,9 +68,16 @@ impl PipelineOrchestrator {
http,
secrets,
net_guard,
nuget_license_cache: None,
}
}
/// 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);
self
}
#[tracing::instrument(skip_all, fields(repo_id = repo.name.as_str()))]
async fn run_pipeline(
&self,
@@ -87,6 +97,22 @@ impl PipelineOrchestrator {
self.net_guard,
);
let repo_path = git_ops.clone_or_fetch(&repo.git_url, &repo.checkout)?;
let lfs = GitOps::lfs_patterns(&repo_path);
if !lfs.is_empty() {
self.skip_stage(
scan_run_id,
SkippedStage::new(
"lfs_objects",
SkipCode::LfsNotFetched,
format!(
"files stored in Git LFS were not downloaded and not scanned: {}",
lfs.join(", ")
),
)
.about(lfs.join(", ")),
)
.await;
}
// A scheduled or webhook scan of an unchanged repository has nothing
// new to find; one a person started always runs (after an update of
@@ -193,7 +219,10 @@ impl PipelineOrchestrator {
.instrument(tracing::info_span!("stage_sast"))
.await
{
Ok(output) => all_findings.extend(output.findings),
Ok(output) => {
run_findings.completed("semgrep");
all_findings.extend(output.findings);
}
Err(e) => {
tracing::warn!("[{repo_id}] Semgrep failed: {e}");
// A failed analysis must not read as clean code.
@@ -213,7 +242,10 @@ impl PipelineOrchestrator {
.instrument(tracing::info_span!("stage_sast_cpp"))
.await
{
Ok(output) => all_findings.extend(output.findings),
Ok(output) => {
run_findings.completed("cppcheck");
all_findings.extend(output.findings);
}
Err(e) => {
tracing::warn!("[{repo_id}] cppcheck failed: {e}");
self.skip_stage(
@@ -229,26 +261,64 @@ impl PipelineOrchestrator {
}
}
}
// Android and iOS code and settings: mobsfscan has the rules for Java,
// Kotlin, Swift and Objective-C that our own pack does not.
if let Some(mobsfscan) = MobsfscanScanner::for_languages(&languages, &vendor) {
match mobsfscan
.scan(&repo_path, &repo_id)
.instrument(tracing::info_span!("stage_sast_mobile"))
.await
{
Ok(output) => {
run_findings.completed("mobsfscan");
all_findings.extend(output.findings);
}
Err(e) => {
tracing::warn!("[{repo_id}] mobsfscan failed: {e}");
self.skip_stage(
scan_run_id,
SkippedStage::new(
"sast_mobile",
SkipCode::ToolFailed,
"mobsfscan did not complete",
)
.about("mobsfscan"),
)
.await;
}
}
}
run_findings.save_new(&self.db, &mut all_findings).await?;
// Stage 2: SBOM Generation
tracing::info!("[{repo_id}] Stage 2: SBOM Generation");
self.update_phase(scan_run_id, ScanPhase::SbomGeneration)
.await;
let mut sbom_entries = match async {
let (mut sbom_entries, syft_failure) = async {
let sbom_scanner =
SbomScanner::new(compliance_core::ExecPolicy::from_env(self.config.app_env));
sbom_scanner.scan(&repo_path, &repo_id).await
SbomScanner::new(compliance_core::ExecPolicy::from_env(self.config.app_env))
.with_nuget_registry(NugetRegistry::from_env(
self.net_guard,
self.nuget_license_cache.clone(),
));
sbom_scanner.generate(&repo_path, &repo_id).await
}
.instrument(tracing::info_span!("stage_sbom_generation"))
.await
{
Ok(output) => output.sbom_entries,
Err(e) => {
tracing::warn!("[{repo_id}] SBOM generation failed: {e}");
Vec::new()
}
};
.await;
// Syft reads the lockfiles and archives: without it the SBOM is short
// of most components, and the SBOM requirements are not assessed.
if let Some(reason) = syft_failure {
self.skip_stage(
scan_run_id,
SkippedStage::new(
"sbom",
SkipCode::ToolFailed,
format!("syft did not complete: {reason}"),
)
.about("syft"),
)
.await;
}
// A manifest with no lockfile pins no versions, and generating one runs
// the project's own code, which this deployment may not. Syft reports
@@ -299,6 +369,9 @@ impl PipelineOrchestrator {
k.expose_secret().to_string()
}),
);
// Whether every component was matched: only then is a CVE missing
// from this scan known to be gone (and its issue closed).
let mut cve_complete = true;
let mut cve_alerts = match tokio::time::timeout(
std::time::Duration::from_secs(600),
async {
@@ -310,14 +383,21 @@ impl PipelineOrchestrator {
)
.await
{
Ok(Ok(alerts)) => alerts,
Ok(Ok(lookup)) => {
cve_complete &= lookup.unchecked.is_empty();
self.record_osv_unchecked(scan_run_id, &lookup.unchecked)
.await;
lookup.alerts
}
Ok(Err(e)) => {
cve_complete = false;
tracing::warn!("[{repo_id}] CVE scanning failed: {e}");
self.record_cve_gap(scan_run_id, "OSV", "the OSV lookup failed")
.await;
Vec::new()
}
Err(_) => {
cve_complete = false;
tracing::warn!("[{repo_id}] CVE scanning timed out after 10 minutes");
self.record_cve_gap(
scan_run_id,
@@ -339,6 +419,7 @@ impl PipelineOrchestrator {
Ok(lookup) => {
cve_alerts.extend(lookup.alerts);
if !lookup.unchecked.is_empty() {
cve_complete = false;
self.record_cve_gap(
scan_run_id,
&format!("NVD: {}", lookup.unchecked.join(", ")),
@@ -348,6 +429,7 @@ impl PipelineOrchestrator {
}
}
Err(_) => {
cve_complete = false;
tracing::warn!("[{repo_id}] embedded-library CVE match timed out");
self.record_cve_gap(
scan_run_id,
@@ -363,22 +445,56 @@ impl PipelineOrchestrator {
self.update_phase(scan_run_id, ScanPhase::PatternScanning)
.await;
{
let mut pattern_findings: Vec<Finding> = async {
let (mut pattern_findings, completed) = async {
let mut findings = Vec::new();
let mut completed = Vec::new();
let gdpr = GdprPatternScanner::new();
match gdpr.scan(&repo_path, &repo_id).await {
Ok(output) => findings.extend(output.findings),
Ok(output) => {
completed.push(gdpr.name().to_string());
findings.extend(output.findings);
}
Err(e) => tracing::warn!("[{repo_id}] GDPR pattern scan failed: {e}"),
}
let oauth = OAuthPatternScanner::new();
match oauth.scan(&repo_path, &repo_id).await {
Ok(output) => findings.extend(output.findings),
Ok(output) => {
completed.push(oauth.name().to_string());
findings.extend(output.findings);
}
Err(e) => tracing::warn!("[{repo_id}] OAuth pattern scan failed: {e}"),
}
findings
// .NET configuration, committed key files and end-of-support
// target frameworks (#445), under three scanner names.
let dotnet = crate::pipeline::dotnet::config::DotnetConfigScanner::default();
match dotnet.scan(&repo_path, &repo_id).await {
Ok(output) => {
completed.extend(
crate::pipeline::dotnet::config::SCANNERS
.iter()
.map(|s| s.to_string()),
);
findings.extend(output.findings);
}
Err(e) => tracing::warn!("[{repo_id}] .NET configuration scan failed: {e}"),
}
// End-of-life build systems and platforms (ADT, Unity
// without UPM, old Android API levels and Unity editors).
let build = crate::pipeline::build_lifecycle::BuildLifecycleScanner;
match build.scan(&repo_path, &repo_id).await {
Ok(output) => {
completed.push(crate::pipeline::build_lifecycle::SCANNER.to_string());
findings.extend(output.findings);
}
Err(e) => tracing::warn!("[{repo_id}] build lifecycle check failed: {e}"),
}
(findings, completed)
}
.instrument(tracing::info_span!("stage_pattern_scanning"))
.await;
for scanner in &completed {
run_findings.completed(scanner);
}
outside_vendor(&mut pattern_findings);
all_findings.extend(pattern_findings);
}
@@ -396,6 +512,7 @@ impl PipelineOrchestrator {
.await
{
Ok(mut output) => {
run_findings.completed("gitleaks");
outside_vendor(&mut output.findings);
all_findings.extend(output.findings);
}
@@ -522,6 +639,20 @@ impl PipelineOrchestrator {
// an earlier run stored.
let new_findings = run_findings.write_back(&self.db, &mut all_findings).await?;
let new_count = run_findings.new_count();
// Findings a completed scanner no longer reports are gone from the
// code. Lint (a linter can fail on its own without the stage failing)
// and the LLM checks (not repeatable) do not close anything.
run_findings
.resolve_missing(&self.db, &repo_id, &vendor)
.await?;
// Their issues follow: closed with a comment, or reopened.
crate::pipeline::issue_sync::IssueSync {
db: self.db.clone(),
config: self.config.clone(),
secrets: self.secrets.clone(),
net_guard: self.net_guard,
}
.spawn(run_findings.status_changed().to_vec());
// Replace this stage's SBOM entries (not the firmware or CODESYS ones,
// which their own steps own). Entries store the target id as a hex
@@ -576,6 +707,12 @@ impl PipelineOrchestrator {
{
tracing::warn!("[{repo_id}] Issue creation failed: {e}");
}
if let Err(e) = self
.sync_cve_issues(repo, &repo_id, &cve_alerts, cve_complete)
.await
{
tracing::warn!("[{repo_id}] CVE issue sync failed: {e}");
}
// The onboarded target's findings_count and the git artifact's
// last_scanned_commit watermark are persisted by `finalize_target` after
@@ -1125,7 +1262,11 @@ impl PipelineOrchestrator {
)
.await
{
Ok(Ok(a)) => a,
Ok(Ok(lookup)) => {
self.record_osv_unchecked(scan_run_id, &lookup.unchecked)
.await;
lookup.alerts
}
Ok(Err(e)) => {
tracing::warn!(target_id, error = %e, "control-app CVE scan failed");
self.record_cve_gap(scan_run_id, "OSV", "the OSV lookup failed")
@@ -1303,13 +1444,29 @@ impl PipelineOrchestrator {
crate::pipeline::firmware_sbom::is_firmware_target(classification.suggested);
if let (Some(oid), Ok(bson)) = (target.id, mongodb::bson::to_bson(&classification))
{
let mut set = doc! { "classification": bson };
// A managed target was created before its repository had
// code, so with a default type: the code decides it now.
if let Some(detected) = target.detected_type(&classification) {
let profile = compliance_core::models::default_compliance_profile(detected);
if let (Ok(tt), Ok(profile)) = (
mongodb::bson::to_bson(&detected),
mongodb::bson::to_bson(&profile),
) {
tracing::info!(
target_id,
from = %target.target_type,
to = %detected,
"managed target typed by its code"
);
set.insert("target_type", tt);
set.insert("compliance_profile", profile);
}
}
let _ = self
.db
.onboarded_targets()
.update_one(
doc! { "_id": oid },
doc! { "$set": { "classification": bson } },
)
.update_one(doc! { "_id": oid }, doc! { "$set": set })
.await;
}
}
@@ -1594,6 +1751,21 @@ impl PipelineOrchestrator {
.await;
}
/// Record the components OSV did not check (a package manager without
/// advisories, a refused batch), so the CVE count is not read as complete.
async fn record_osv_unchecked(&self, scan_run_id: &str, unchecked: &[String]) {
if unchecked.is_empty() {
return;
}
self.record_cve_gap(
scan_run_id,
&format!("OSV: {}", component_list(unchecked)),
"these components were not matched against OSV, which has no advisories \
for their package manager (CocoaPods, Unity) or refused the request",
)
.await;
}
/// Control mapping for the PLC path (`run_plc_scan` is separate from
/// `run_pipeline`, which does its own). PLC findings carry
/// file_path/line/cwe, so the semantic pass reads each region under its
@@ -1761,6 +1933,24 @@ fn planned_phases(
/// The skipped-stage id recorded when CVE matching is incomplete.
pub const CVE_LOOKUP_STAGE: &str = "cve_lookup";
/// How many components a skipped stage names before it only counts the rest.
const LISTED_COMPONENTS: usize = 10;
/// `components` as a readable list, the first [`LISTED_COMPONENTS`] by name
/// and the rest counted: an iOS app can pull in a hundred pods.
fn component_list(components: &[String]) -> String {
let listed = components
.iter()
.take(LISTED_COMPONENTS)
.map(String::as_str)
.collect::<Vec<_>>()
.join(", ");
match components.len().saturating_sub(LISTED_COMPONENTS) {
0 => listed,
more => format!("{listed} and {more} more"),
}
}
/// Extract the scheme + host from a git URL.
/// e.g. "https://gitea.example.com/owner/repo.git" -> "https://gitea.example.com"
/// e.g. "ssh://git@gitea.example.com:22/owner/repo.git" -> "https://gitea.example.com"
@@ -1794,6 +1984,13 @@ mod tests {
Artifact, ArtifactAuth, IssueTrackerConfig, TargetType, TrackerType,
};
#[test]
fn a_long_component_list_names_ten_and_counts_the_rest() {
let pods: Vec<String> = (1..=12).map(|i| format!("Pod{i} 1.0")).collect();
assert_eq!(component_list(&pods[..2]), "Pod1 1.0, Pod2 1.0");
assert!(component_list(&pods).ends_with("Pod10 1.0 and 2 more"));
}
#[test]
fn a_code_target_plans_the_code_stages_in_order() {
let mut target = OnboardedTarget::new("fw".to_string(), TargetType::FirmwareRtos);
@@ -37,6 +37,9 @@ pub struct RepoView {
pub auth_username: Option<String>,
pub last_scanned_commit: Option<String>,
pub findings_count: u32,
/// Created by a managed git source (#439): its Gitea issues get the
/// Prüfwerk/CRA labels and a link into Prüfwerk.
pub managed: bool,
}
impl RepoView {
@@ -63,6 +66,7 @@ impl RepoView {
auth_username: None,
last_scanned_commit: None,
findings_count: target.findings_count,
managed: target.source_repo.is_some(),
};
if let Some(git) = &code.git {
view.default_branch = git.default_branch.clone();
@@ -0,0 +1,487 @@
//! Direct dependencies of a Gradle build that has no lockfile.
//!
//! Without `gradle.lockfile` the SBOM tooling lists nothing for an Android or
//! JVM app, and resolving the build would run its build scripts, which a scan
//! must not do. What the build files *declare* can still be read: the
//! coordinates written into `build.gradle(.kts)`, versions kept in `ext`
//! variables or `gradle.properties`, and the version catalog
//! (`gradle/libs.versions.toml`). Only dependencies that ship with the app
//! count (implementation, api, runtime; not test, lint or annotation
//! processors), and only exact versions: a range or a version Gradle resolves
//! itself (`+`, `latest.release`) says nothing about what is in the app.
//!
//! These are the direct dependencies only. What they pull in stays unknown, so
//! the scan still reports the build as unlocked (see [`super::mobile`]).
use std::collections::{BTreeSet, HashMap};
use std::path::Path;
use std::sync::LazyLock;
use compliance_core::models::SbomEntry;
use regex::Regex;
use super::mobile::{MAX_DEPTH, SKIPPED_DIRS};
/// A literal coordinate after a configuration name:
/// `implementation 'g:a:v'`, `api("g:a:$v")`, `compile "g:a:${v}@aar"`.
static COORDINATE: LazyLock<Option<Regex>> = LazyLock::new(|| {
Regex::new(r#"\b(\w+)\s*\(?\s*["']([\w.\-]+):([\w.\-]+):([^"'@\s:]+)(?:@\w+)?["']"#).ok()
});
/// Groovy's map notation: `implementation group: 'g', name: 'a', version: 'v'`.
static MAP_COORDINATE: LazyLock<Option<Regex>> = LazyLock::new(|| {
Regex::new(
r#"\b(\w+)\s*\(?\s*group\s*:\s*["']([^"']+)["']\s*,\s*name\s*:\s*["']([^"']+)["']\s*,\s*version\s*:\s*["']([^"']+)["']"#,
)
.ok()
});
/// A catalog accessor after a configuration name: `implementation(libs.okhttp)`,
/// `api libs.bundles.network`.
static CATALOG_USE: LazyLock<Option<Regex>> =
LazyLock::new(|| Regex::new(r"\b(\w+)\s*\(?\s*(\w+)\.([\w.]+)").ok());
/// A version kept in a variable: `ext.okhttp_version = '3.12.0'`,
/// `def okhttp = "3.12.0"`, `val okhttp = "3.12.0"`, or a line of an
/// `ext { okhttp = '3.12.0' }` block.
static VARIABLE: LazyLock<Option<Regex>> = LazyLock::new(|| {
Regex::new(r#"(?m)^\s*(?:ext\.|def\s+|val\s+)?([A-Za-z_]\w*)\s*=\s*["']([^"'$]+)["']"#).ok()
});
/// A variable reference inside a version: `$okhttp`, `${versions.okhttp}`,
/// `${rootProject.ext.okhttp}`. The last segment names the variable.
static REFERENCE: LazyLock<Option<Regex>> = LazyLock::new(|| Regex::new(r"\$\{?([\w.]+)\}?").ok());
/// Lockfiles that make the parse unnecessary: Syft reads them, and they also
/// pin what the direct dependencies pull in.
const LOCKFILES: [&str; 2] = ["gradle.lockfile", "settings-gradle.lockfile"];
/// The build files, catalogs and properties of one tree.
#[derive(Default)]
struct GradleFiles {
builds: Vec<String>,
/// Catalog accessor name (`libs` for `libs.versions.toml`) and its text.
catalogs: Vec<(String, String)>,
properties: Vec<String>,
locked: bool,
}
/// The dependencies the Gradle builds under `root` declare with an exact
/// version, as SBOM entries; empty when a Gradle lockfile pins them (Syft
/// reads that instead) or the tree has no Gradle build.
///
/// # Arguments
///
/// * `root` - the checked-out or unpacked source tree
/// * `repo_id` - the target the entries belong to
///
/// # Returns
///
/// One `maven` entry with a purl per distinct coordinate, so the CVE lookup
/// matches it.
pub(crate) fn declared_dependencies(root: &Path, repo_id: &str) -> Vec<SbomEntry> {
let files = read_files(root);
if files.locked || files.builds.is_empty() {
return Vec::new();
}
let variables = variables(&files);
let mut coordinates: BTreeSet<(String, String, String)> = BTreeSet::new();
for build in &files.builds {
coordinates.extend(literal_coordinates(build, &variables));
}
for (accessor, catalog) in &files.catalogs {
coordinates.extend(catalog_coordinates(accessor, catalog, &files.builds));
}
coordinates
.into_iter()
.map(|(group, artifact, version)| {
let mut entry = SbomEntry::new(
repo_id.to_string(),
artifact.clone(),
version.clone(),
"maven".to_string(),
);
entry.purl = Some(format!("pkg:maven/{group}/{artifact}@{version}"));
entry
})
.collect()
}
/// Walk `root` once for build files, catalogs, properties and lockfiles.
fn read_files(root: &Path) -> GradleFiles {
let mut files = GradleFiles::default();
let entries = walkdir::WalkDir::new(root)
.min_depth(1)
.max_depth(MAX_DEPTH)
.sort_by_file_name()
.into_iter()
.filter_entry(|e| {
!(e.file_type().is_dir()
&& SKIPPED_DIRS.contains(&e.file_name().to_string_lossy().as_ref()))
})
.filter_map(Result::ok)
.filter(|e| e.file_type().is_file());
for entry in entries {
let name = entry.file_name().to_string_lossy();
if LOCKFILES.contains(&name.as_ref()) {
files.locked = true;
continue;
}
let read = || std::fs::read_to_string(entry.path()).ok();
match name.as_ref() {
"build.gradle" | "build.gradle.kts" => files.builds.extend(read()),
"gradle.properties" => files.properties.extend(read()),
_ => {
if let Some(accessor) = name.strip_suffix(".versions.toml") {
if let Some(text) = read() {
files.catalogs.push((accessor.to_string(), text));
}
}
}
}
}
files
}
/// Every variable a build file or `gradle.properties` sets to a plain
/// string, by name. A name set twice keeps its first value.
fn variables(files: &GradleFiles) -> HashMap<String, String> {
let mut out = HashMap::new();
for text in &files.properties {
for line in text.lines() {
if let Some((key, value)) = line.split_once('=') {
let key = key.trim();
if !key.starts_with('#') && !key.is_empty() {
out.entry(key.to_string())
.or_insert_with(|| value.trim().to_string());
}
}
}
}
if let Some(re) = VARIABLE.as_ref() {
for build in &files.builds {
for caps in re.captures_iter(build) {
out.entry(caps[1].to_string())
.or_insert_with(|| caps[2].to_string());
}
}
}
out
}
/// Whether a dependency in configuration `config` ships with the app.
fn ships(config: &str) -> bool {
let config = config.to_ascii_lowercase();
let build_only = [
"test",
"androidtest",
"kapt",
"ksp",
"annotationprocessor",
"lint",
"classpath",
"detekt",
];
if build_only.iter().any(|p| config.starts_with(p)) {
return false;
}
["implementation", "api", "compile", "runtimeonly", "runtime"]
.iter()
.any(|s| config.ends_with(s))
}
/// `version` with its variable references filled in from `variables`, if it
/// is then an exact version.
fn exact_version(version: &str, variables: &HashMap<String, String>) -> Option<String> {
let resolved = match REFERENCE.as_ref() {
Some(re) if version.contains('$') => {
let mut unresolved = false;
let text = re.replace_all(version, |caps: &regex::Captures<'_>| {
let name = caps[1].rsplit('.').next().unwrap_or_default();
variables.get(name).cloned().unwrap_or_else(|| {
unresolved = true;
String::new()
})
});
if unresolved {
return None;
}
text.into_owned()
}
_ => version.to_string(),
};
let exact = resolved.chars().next().is_some_and(|c| c.is_ascii_digit())
&& !resolved.contains(['+', '[', ']', '(', ')', ',', '*', '$'])
&& !resolved.contains("latest");
exact.then_some(resolved)
}
/// The shipped coordinates written into one build file.
fn literal_coordinates(
build: &str,
variables: &HashMap<String, String>,
) -> Vec<(String, String, String)> {
[COORDINATE.as_ref(), MAP_COORDINATE.as_ref()]
.into_iter()
.flatten()
.flat_map(|re| re.captures_iter(build))
.filter(|caps| ships(&caps[1]))
.filter_map(|caps| {
let version = exact_version(&caps[4], variables)?;
Some((caps[2].to_string(), caps[3].to_string(), version))
})
.collect()
}
/// A catalog alias as Gradle's accessor spells it: `androidx-core_ktx`
/// becomes `androidx.core.ktx`.
fn accessor_path(alias: &str) -> String {
alias.replace(['-', '_'], ".").to_ascii_lowercase()
}
/// The shipped coordinates a version catalog contributes: its libraries and
/// bundles that a build file uses in a shipped configuration.
fn catalog_coordinates(
accessor: &str,
catalog: &str,
builds: &[String],
) -> Vec<(String, String, String)> {
let Ok(table) = catalog.parse::<toml::Table>() else {
tracing::warn!(accessor, "unreadable Gradle version catalog");
return Vec::new();
};
let versions = table.get("versions").and_then(toml::Value::as_table);
let libraries: HashMap<String, (String, String, String)> = table
.get("libraries")
.and_then(toml::Value::as_table)
.into_iter()
.flatten()
.filter_map(|(alias, spec)| Some((accessor_path(alias), library(spec, versions)?)))
.collect();
let bundles: HashMap<String, Vec<String>> = table
.get("bundles")
.and_then(toml::Value::as_table)
.into_iter()
.flatten()
.map(|(alias, members)| {
let members = members
.as_array()
.into_iter()
.flatten()
.filter_map(toml::Value::as_str)
.map(accessor_path)
.collect();
(accessor_path(alias), members)
})
.collect();
let Some(re) = CATALOG_USE.as_ref() else {
return Vec::new();
};
let mut out = Vec::new();
for build in builds {
for caps in re.captures_iter(build) {
if &caps[2] != accessor || !ships(&caps[1]) {
continue;
}
let path = caps[3].to_ascii_lowercase();
let used: Vec<&String> = match path.strip_prefix("bundles.") {
Some(bundle) => bundles.get(bundle).into_iter().flatten().collect(),
None => vec![&path],
};
out.extend(used.into_iter().filter_map(|p| libraries.get(p).cloned()));
}
}
out
}
/// A catalog library's coordinate with an exact version: `"g:a:v"`,
/// `{ module = "g:a", version = "v" }`, `{ group, name, version.ref }` or a
/// version table (`strictly`, `require`).
fn library(spec: &toml::Value, versions: Option<&toml::Table>) -> Option<(String, String, String)> {
if let Some(text) = spec.as_str() {
let mut parts = text.split(':');
let (group, artifact, version) = (parts.next()?, parts.next()?, parts.next()?);
let version = exact_version(version, &HashMap::new())?;
return Some((group.to_string(), artifact.to_string(), version));
}
let spec = spec.as_table()?;
let (group, artifact) = match spec.get("module").and_then(toml::Value::as_str) {
Some(module) => module.split_once(':')?,
None => (spec.get("group")?.as_str()?, spec.get("name")?.as_str()?),
};
let version = match spec.get("version")? {
toml::Value::String(v) => v.clone(),
toml::Value::Table(t) => match t.get("ref").and_then(toml::Value::as_str) {
Some(name) => version_of(versions?.get(name)?)?,
None => version_of(&toml::Value::Table(t.clone()))?,
},
_ => return None,
};
let version = exact_version(&version, &HashMap::new())?;
Some((group.to_string(), artifact.to_string(), version))
}
/// The version a `[versions]` entry pins: the string, or its `strictly` or
/// `require` part.
fn version_of(value: &toml::Value) -> Option<String> {
match value {
toml::Value::String(v) => Some(v.clone()),
toml::Value::Table(t) => ["strictly", "require"]
.iter()
.find_map(|k| t.get(*k).and_then(toml::Value::as_str))
.map(str::to_string),
_ => None,
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
/// A scratch tree holding `files` (relative path, content), removed on
/// drop.
struct Tree(std::path::PathBuf);
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn tree(files: &[(&str, &str)]) -> Tree {
let dir = std::env::temp_dir().join(format!("cs-gradle-{}", uuid::Uuid::new_v4()));
for (path, content) in files {
let full = dir.join(path);
std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir");
std::fs::write(full, content).expect("write");
}
Tree(dir)
}
fn purls(files: &[(&str, &str)]) -> Vec<String> {
let dir = tree(files);
declared_dependencies(&dir.0, "t")
.into_iter()
.filter_map(|e| e.purl)
.collect()
}
#[test]
fn every_pattern_compiles() {
for re in [
&COORDINATE,
&MAP_COORDINATE,
&CATALOG_USE,
&VARIABLE,
&REFERENCE,
] {
assert!(re.is_some());
}
}
#[test]
fn a_legacy_android_build_lists_its_shipped_dependencies() {
let root = r#"
buildscript {
ext.okhttp_version = '3.12.0'
dependencies { classpath 'com.android.tools.build:gradle:3.5.0' }
}
"#;
let app = r#"
dependencies {
implementation "com.squareup.okhttp3:okhttp:$okhttp_version"
implementation 'com.google.code.gson:gson:2.8.8'
phoneImplementation group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.60'
compile 'com.android.support:appcompat-v7:28.0.0@aar'
testImplementation 'junit:junit:4.12'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.0'
implementation 'com.example:dynamic:1.+'
implementation "com.example:unknown:$notDefined"
}
"#;
assert_eq!(
purls(&[("build.gradle", root), ("app/build.gradle", app)]),
vec![
"pkg:maven/com.android.support/appcompat-v7@28.0.0",
"pkg:maven/com.google.code.gson/gson@2.8.8",
"pkg:maven/com.squareup.okhttp3/okhttp@3.12.0",
"pkg:maven/org.bouncycastle/bcprov-jdk15on@1.60",
]
);
}
#[test]
fn a_version_catalog_counts_only_what_a_build_ships() {
let catalog = r#"
[versions]
okhttp = "3.12.0"
room = { strictly = "2.6.1" }
junit = "4.13.2"
[libraries]
okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" }
room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" }
gson = "com.google.code.gson:gson:2.8.8"
junit = { module = "junit:junit", version.ref = "junit" }
core-ktx = { module = "androidx.core:core-ktx" }
[bundles]
storage = ["room-runtime", "gson"]
"#;
let app = r#"
dependencies {
implementation(libs.okhttp)
implementation(libs.bundles.storage)
implementation(libs.core.ktx)
testImplementation(libs.junit)
}
"#;
assert_eq!(
purls(&[
("gradle/libs.versions.toml", catalog),
("app/build.gradle.kts", app),
]),
vec![
"pkg:maven/androidx.room/room-runtime@2.6.1",
"pkg:maven/com.google.code.gson/gson@2.8.8",
"pkg:maven/com.squareup.okhttp3/okhttp@3.12.0",
]
);
}
#[test]
fn versions_from_gradle_properties_are_resolved() {
assert_eq!(
purls(&[
("gradle.properties", "# versions\nokhttpVersion=3.12.0\n"),
(
"app/build.gradle.kts",
"dependencies { implementation(\"com.squareup.okhttp3:okhttp:${okhttpVersion}\") }",
),
]),
vec!["pkg:maven/com.squareup.okhttp3/okhttp@3.12.0"]
);
}
#[test]
fn a_locked_build_is_left_to_the_lockfile() {
assert!(purls(&[
(
"app/build.gradle",
"dependencies { implementation 'a.b:c:1.0' }"
),
("app/gradle.lockfile", "a.b:c:1.0=releaseRuntimeClasspath"),
])
.is_empty());
}
#[test]
fn build_output_is_not_read() {
assert!(purls(&[(
"app/build/intermediates/build.gradle",
"dependencies { implementation 'a.b:c:1.0' }"
)])
.is_empty());
}
}
@@ -0,0 +1,328 @@
//! Mobile package managers whose dependencies the SBOM cannot list.
//!
//! An Android, iOS or Flutter app declares its dependencies in a manifest
//! (`build.gradle.kts`, `Podfile`, `Package.swift`, `pubspec.yaml`), but only
//! the lockfile beside it says which versions ship. Syft reads the lockfiles
//! and nothing else, so an app without them gets an SBOM with no packages and
//! no CVEs, which reads like a clean result. Generating the lockfiles would run
//! the project's build scripts, which a scan must not do.
//!
//! Unlike npm or Cargo, these manifests rarely sit at the repository root: a
//! React Native or Flutter app keeps them under `android/` and `ios/`, a native
//! app under `app/` or next to its Xcode project. So the tree is walked, and an
//! ecosystem counts as locked when any of its lockfiles is anywhere in it: a
//! Gradle module or a Dart package without a lockfile of its own is normal
//! when the app that uses it has one.
use std::path::Path;
use super::UnlockedEcosystem;
/// How deep manifests are looked for. Deep enough for a React Native app's
/// `android/app/build.gradle` inside a monorepo package.
pub(super) const MAX_DEPTH: usize = 8;
/// Directories never searched: build output, installed dependencies and tool
/// caches, which hold other projects' manifests and lockfiles.
pub(super) const SKIPPED_DIRS: &[&str] = &[
".git",
".gradle",
".dart_tool",
".symlinks",
"build",
"DerivedData",
"node_modules",
"Pods",
"Carthage",
];
/// A mobile package manager: what declares its dependencies and what pins
/// them.
struct Ecosystem {
/// File names that declare dependencies.
manifests: &'static [&'static str],
/// File names that pin versions; any one of them anywhere in the tree
/// counts.
lockfiles: &'static [&'static str],
/// Why the versions are not read.
problem: &'static str,
/// What to commit so they are.
remedy: &'static str,
}
const GRADLE: Ecosystem = Ecosystem {
manifests: &[
"build.gradle",
"build.gradle.kts",
"settings.gradle",
"settings.gradle.kts",
],
lockfiles: &["gradle.lockfile", "settings-gradle.lockfile"],
problem: "declares Gradle dependencies but no gradle.lockfile pins them; only the direct \
dependencies with an exact version are listed, not what they pull in",
remedy: "enable Gradle dependency locking (`dependencyLocking { lockAllConfigurations() }`) \
and commit the gradle.lockfile files (`./gradlew dependencies --write-locks`)",
};
const COCOAPODS: Ecosystem = Ecosystem {
manifests: &["Podfile"],
lockfiles: &["Podfile.lock"],
problem: "declares CocoaPods dependencies but no Podfile.lock pins them",
remedy: "commit Podfile.lock",
};
const SWIFTPM: Ecosystem = Ecosystem {
manifests: &["Package.swift"],
lockfiles: &["Package.resolved"],
problem: "declares Swift packages but no Package.resolved pins them",
remedy: "commit Package.resolved (in an Xcode project it lives under \
`*.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/`)",
};
const PUB: Ecosystem = Ecosystem {
manifests: &["pubspec.yaml"],
lockfiles: &["pubspec.lock"],
problem: "declares Dart/Flutter dependencies but no pubspec.lock pins them",
remedy: "commit the app's pubspec.lock",
};
/// Carthage has a lockfile, but no SBOM tool reads it, so it is reported
/// whether or not `Cartfile.resolved` is present.
const CARTHAGE: Ecosystem = Ecosystem {
manifests: &["Cartfile"],
lockfiles: &[],
problem: "declares Carthage dependencies, which no SBOM tool reads",
remedy: "move them to Swift Package Manager or CocoaPods, or list them by hand",
};
const ECOSYSTEMS: [&Ecosystem; 5] = [&GRADLE, &COCOAPODS, &SWIFTPM, &PUB, &CARTHAGE];
/// Where [`SWIFTPM`] sits in [`ECOSYSTEMS`].
const SWIFTPM_AT: usize = 2;
/// Marks an Xcode project that uses Swift packages without a `Package.swift`.
const XCODE_PACKAGE_REFERENCE: &str = "XCRemoteSwiftPackageReference";
/// What the walk saw: the shallowest manifest of each ecosystem (its depth
/// and relative path) and whether any of its lockfiles exists.
#[derive(Default)]
struct Seen {
manifest: [Option<(usize, String)>; ECOSYSTEMS.len()],
locked: [bool; ECOSYSTEMS.len()],
}
impl Seen {
/// Keep `path` as ecosystem `i`'s manifest unless a shallower one (or an
/// earlier one at the same depth) was already seen: the app's own
/// manifest names the gap better than a nested library's.
fn manifest(&mut self, i: usize, depth: usize, path: impl FnOnce() -> String) {
if self.manifest[i]
.as_ref()
.is_none_or(|(seen_depth, _)| depth < *seen_depth)
{
self.manifest[i] = Some((depth, path()));
}
}
}
/// The mobile ecosystems under `root` that declare dependencies the SBOM
/// cannot list, one entry per ecosystem naming its shallowest manifest.
///
/// # Arguments
///
/// * `root` - the checked-out or unpacked source tree
///
/// # Returns
///
/// An empty list when the tree has no mobile manifests or every one is backed
/// by a lockfile the SBOM reads.
pub(crate) fn unlocked_mobile_ecosystems(root: &Path) -> Vec<UnlockedEcosystem> {
let seen = walk(root);
ECOSYSTEMS
.iter()
.zip(seen.manifest)
.zip(seen.locked)
.filter_map(|((eco, manifest), locked)| {
let (_, manifest) = manifest?;
(!locked).then_some(UnlockedEcosystem {
manifest,
problem: eco.problem,
remedy: eco.remedy,
})
})
.collect()
}
/// Walk `root` once, recording manifests and lockfiles of every ecosystem.
fn walk(root: &Path) -> Seen {
let mut seen = Seen::default();
let entries = walkdir::WalkDir::new(root)
.min_depth(1)
.max_depth(MAX_DEPTH)
.sort_by_file_name()
.into_iter()
.filter_entry(|e| {
!(e.file_type().is_dir()
&& SKIPPED_DIRS.contains(&e.file_name().to_string_lossy().as_ref()))
})
.filter_map(Result::ok)
.filter(|e| e.file_type().is_file());
for entry in entries {
let name = entry.file_name().to_string_lossy();
let relative = || {
entry
.path()
.strip_prefix(root)
.map(|p| p.to_string_lossy().replace('\\', "/"))
.unwrap_or_else(|_| name.to_string())
};
for (i, eco) in ECOSYSTEMS.iter().enumerate() {
if eco.lockfiles.contains(&name.as_ref()) {
seen.locked[i] = true;
}
if eco.manifests.contains(&name.as_ref()) {
seen.manifest(i, entry.depth(), relative);
}
}
// An Xcode project can depend on Swift packages with no Package.swift
// in the tree; its project file names them.
if name == "project.pbxproj"
&& seen.manifest[SWIFTPM_AT].is_none()
&& std::fs::read_to_string(entry.path())
.is_ok_and(|text| text.contains(XCODE_PACKAGE_REFERENCE))
{
seen.manifest(SWIFTPM_AT, entry.depth(), relative);
}
}
seen
}
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use super::*;
/// A scratch tree holding `files` (relative path, content), removed on
/// drop.
struct Tree(std::path::PathBuf);
impl Tree {
fn path(&self) -> &Path {
&self.0
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn tree(files: &[(&str, &str)]) -> Tree {
let dir = std::env::temp_dir().join(format!("cs-mobile-{}", uuid::Uuid::new_v4()));
for (path, content) in files {
let full = dir.join(path);
if let Some(parent) = full.parent() {
std::fs::create_dir_all(parent).expect("mkdir");
}
std::fs::write(full, content).expect("write");
}
Tree(dir)
}
fn manifests(root: &Path) -> Vec<String> {
unlocked_mobile_ecosystems(root)
.into_iter()
.map(|e| e.manifest)
.collect()
}
#[test]
fn swiftpm_sits_where_the_xcode_check_expects_it() {
assert!(std::ptr::eq(ECOSYSTEMS[SWIFTPM_AT], &SWIFTPM));
}
#[test]
fn a_gradle_app_without_a_lockfile_is_reported_by_its_nested_manifest() {
let dir = tree(&[("android/app/build.gradle.kts", "dependencies {}")]);
let found = unlocked_mobile_ecosystems(dir.path());
assert_eq!(found.len(), 1);
assert_eq!(found[0].manifest, "android/app/build.gradle.kts");
assert!(found[0].problem.contains("gradle.lockfile"));
}
#[test]
fn one_lockfile_anywhere_locks_the_ecosystem() {
let dir = tree(&[
("settings.gradle.kts", ""),
("core/build.gradle.kts", ""),
("app/build.gradle.kts", ""),
("app/gradle.lockfile", "empty="),
("ios/Podfile", ""),
("ios/Podfile.lock", ""),
("pubspec.yaml", ""),
("pubspec.lock", ""),
("packages/widgets/pubspec.yaml", ""),
]);
assert!(manifests(dir.path()).is_empty());
}
#[test]
fn each_unlocked_ecosystem_is_reported_once() {
let dir = tree(&[
("ios/Podfile", ""),
("Package.swift", ""),
("pubspec.yaml", ""),
("lib/pubspec.yaml", ""),
]);
assert_eq!(
manifests(dir.path()),
vec!["ios/Podfile", "Package.swift", "pubspec.yaml"]
);
}
#[test]
fn an_xcode_project_using_swift_packages_needs_its_package_resolved() {
let pbxproj = "/* XCRemoteSwiftPackageReference \"swift-nio\" */";
let unlocked = tree(&[("PumpApp.xcodeproj/project.pbxproj", pbxproj)]);
assert_eq!(
manifests(unlocked.path()),
vec!["PumpApp.xcodeproj/project.pbxproj"]
);
let locked = tree(&[
("PumpApp.xcodeproj/project.pbxproj", pbxproj),
(
"PumpApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved",
"{}",
),
]);
assert!(manifests(locked.path()).is_empty());
}
#[test]
fn an_xcode_project_without_swift_packages_is_not_reported() {
let dir = tree(&[("PumpApp.xcodeproj/project.pbxproj", "// no packages")]);
assert!(manifests(dir.path()).is_empty());
}
#[test]
fn carthage_is_reported_even_with_its_resolved_file() {
let dir = tree(&[("Cartfile", ""), ("Cartfile.resolved", "")]);
assert_eq!(manifests(dir.path()), vec!["Cartfile"]);
}
#[test]
fn installed_dependencies_and_build_output_are_not_searched() {
let dir = tree(&[
("node_modules/react-native/android/build.gradle", ""),
("ios/Pods/Local Podspecs/Podfile", ""),
("android/build/intermediates/pubspec.yaml", ""),
]);
assert!(manifests(dir.path()).is_empty());
}
#[test]
fn a_tree_without_mobile_manifests_reports_nothing() {
let dir = tree(&[("package.json", "{}"), ("src/main.c", "")]);
assert!(manifests(dir.path()).is_empty());
}
}
+107 -13
View File
@@ -1,5 +1,15 @@
mod cargo_audit;
mod gradle;
mod mobile;
mod nuget;
mod nuget_license;
pub(crate) use nuget::is_restored_package;
#[cfg(test)]
pub(crate) use nuget::nuget_components;
pub(crate) use nuget_license::{LicenseCache, MongoLicenseCache, NugetRegistry};
mod syft;
pub(crate) mod unity;
use std::path::Path;
@@ -11,11 +21,23 @@ use crate::pipeline::tool_cmd::{run_bounded, tool_in, CARGO_ENV, NPM_ENV};
pub struct SbomScanner {
exec: ExecPolicy,
/// Where NuGet licenses missing from the tree are looked up (#467);
/// `None` reads only the tree's `.nuspec` files.
nuget_registry: Option<NugetRegistry>,
}
impl SbomScanner {
pub fn new(exec: ExecPolicy) -> Self {
Self { exec }
Self {
exec,
nuget_registry: None,
}
}
/// Look up the NuGet licenses the tree does not carry on nuget.org.
pub(crate) fn with_nuget_registry(mut self, registry: Option<NugetRegistry>) -> Self {
self.nuget_registry = registry;
self
}
}
@@ -30,7 +52,27 @@ impl Scanner for SbomScanner {
#[tracing::instrument(skip_all)]
async fn scan(&self, repo_path: &Path, repo_id: &str) -> Result<ScanOutput, CoreError> {
let (entries, _syft_failure) = self.generate(repo_path, repo_id).await;
Ok(ScanOutput {
findings: Vec::new(),
sbom_entries: entries,
})
}
}
impl SbomScanner {
/// The SBOM of `repo_path`, and why Syft did not complete if it did not:
/// then the SBOM is short of everything Syft reads (lockfiles, archives),
/// which the caller records rather than showing an SBOM that looks
/// complete.
#[tracing::instrument(skip_all)]
pub async fn generate(
&self,
repo_path: &Path,
repo_id: &str,
) -> (Vec<SbomEntry>, Option<String>) {
let mut entries = Vec::new();
let mut syft_failure = None;
// Generate missing lock files so Syft can resolve the full dependency tree
generate_lockfiles(repo_path, self.exec).await;
@@ -38,9 +80,42 @@ impl Scanner for SbomScanner {
// Run syft for SBOM generation
match syft::run_syft(repo_path, repo_id).await {
Ok(syft_entries) => entries.extend(syft_entries),
Err(e) => tracing::warn!("syft failed: {e}"),
Err(e) => {
tracing::warn!("syft failed: {e}");
syft_failure = Some(e.to_string());
}
}
// A Gradle build without a lockfile gives Syft nothing; its build files
// still name the direct dependencies.
let tree = repo_path.to_path_buf();
let target = repo_id.to_string();
let declared =
tokio::task::spawn_blocking(move || gradle::declared_dependencies(&tree, &target))
.await
.unwrap_or_default();
for entry in declared {
if !entries.iter().any(|e| e.purl == entry.purl) {
entries.push(entry);
}
}
// Unity projects: the editor version and the packages `Packages/` pins.
let tree = repo_path.to_path_buf();
let target = repo_id.to_string();
entries.extend(
tokio::task::spawn_blocking(move || unity::unity_components(&tree, &target))
.await
.unwrap_or_default(),
);
// NuGet packages from packages.config, project files and restored
// package folders, which Syft does not read (#445).
nuget::merge_nuget(&mut entries, nuget::nuget_components(repo_path, repo_id));
// Their licenses: from the restored packages' .nuspec, then nuget.org.
nuget_license::enrich_nuget_licenses(repo_path, &mut entries, self.nuget_registry.as_ref())
.await;
// Enrich Cargo entries with license info from cargo metadata
enrich_cargo_licenses(repo_path, &mut entries, self.exec).await;
@@ -50,10 +125,7 @@ impl Scanner for SbomScanner {
Err(e) => tracing::warn!("cargo-audit skipped: {e}"),
}
Ok(ScanOutput {
findings: Vec::new(),
sbom_entries: entries,
})
(entries, syft_failure)
}
}
@@ -62,8 +134,9 @@ impl Scanner for SbomScanner {
/// not run here, or it may have failed). Syft reports nothing for it, so the
/// SBOM would be silently short of those dependencies.
pub(crate) struct UnlockedEcosystem {
/// What the tree declares (`package.json`, `pyproject.toml`).
pub manifest: &'static str,
/// What the tree declares, relative to its root (`package.json`,
/// `android/app/build.gradle.kts`).
pub manifest: String,
/// Why its versions were not read.
pub problem: &'static str,
/// What to commit so they are.
@@ -86,6 +159,11 @@ const NPM_LOCKFILES: &[&str] = &[
/// after [`generate_lockfiles`]: it reads the tree as Syft will see it, so a
/// lockfile that was generated counts and one that could not be does not. An
/// empty result means every manifest present is backed by a lockfile.
///
/// npm, Python and Cargo are checked at the root, where their workspaces keep
/// the lockfile; the mobile package managers anywhere in the tree (see
/// [`mobile`]), and every .NET project with `<PackageReference>` items (see
/// [`nuget`]).
pub(crate) fn unlocked_ecosystems(repo_path: &Path) -> Vec<UnlockedEcosystem> {
let has = |name: &str| repo_path.join(name).exists();
let mut out = Vec::new();
@@ -98,13 +176,13 @@ pub(crate) fn unlocked_ecosystems(repo_path: &Path) -> Vec<UnlockedEcosystem> {
// Bun's binary lockfile is opaque to the SBOM tooling; its text
// successor (the default since Bun 1.2) is read.
out.push(UnlockedEcosystem {
manifest: "package.json",
manifest: "package.json".into(),
problem: "is locked only by bun.lockb, Bun's binary lockfile, which is not read",
remedy: "commit the text bun.lock (`bun install --save-text-lockfile`)",
});
} else if !readable {
out.push(UnlockedEcosystem {
manifest: "package.json",
manifest: "package.json".into(),
problem: "declares dependencies but no lockfile pins them",
remedy: "commit package-lock.json, yarn.lock, pnpm-lock.yaml or bun.lock",
});
@@ -116,7 +194,7 @@ pub(crate) fn unlocked_ecosystems(repo_path: &Path) -> Vec<UnlockedEcosystem> {
if let Some(manifest) = python_manifest {
if !PIP_LOCKFILES.iter().any(|f| has(f)) {
out.push(UnlockedEcosystem {
manifest,
manifest: manifest.into(),
problem: "declares dependencies but no lockfile pins them",
remedy: "commit requirements.txt, poetry.lock, Pipfile.lock or uv.lock",
});
@@ -124,11 +202,27 @@ pub(crate) fn unlocked_ecosystems(repo_path: &Path) -> Vec<UnlockedEcosystem> {
}
if has("Cargo.toml") && !has("Cargo.lock") {
out.push(UnlockedEcosystem {
manifest: "Cargo.toml",
manifest: "Cargo.toml".into(),
problem: "declares dependencies but no lockfile pins them",
remedy: "commit Cargo.lock",
});
}
out.extend(mobile::unlocked_mobile_ecosystems(repo_path));
// End-of-life build systems declare nothing readable (see
// `build_lifecycle`, which reports them as findings too).
out.extend(
crate::pipeline::build_lifecycle::check_tree(repo_path)
.into_iter()
.filter(|hit| hit.rule_id == "legacy-build-system-no-sbom")
.map(|hit| UnlockedEcosystem {
manifest: hit.path,
problem: "belongs to a legacy build system (Eclipse/ADT, or Unity without \
Packages/manifest.json) whose dependencies cannot be read",
remedy: "migrate the build (Gradle with the Android Gradle Plugin, or a \
current Unity LTS with the Package Manager)",
}),
);
out.extend(nuget::unresolved_projects(repo_path));
out
}
@@ -347,7 +441,7 @@ mod unlocked_tests {
}
}
fn names(tree: &Tree) -> Vec<&'static str> {
fn names(tree: &Tree) -> Vec<String> {
unlocked_ecosystems(&tree.0)
.into_iter()
.map(|e| e.manifest)
+603
View File
@@ -0,0 +1,603 @@
//! NuGet packages of a .NET tree, read without a build or a restore (#445).
//!
//! Syft reads `packages.lock.json` and `*.deps.json`, which a typical .NET
//! Framework codebase has neither of: its packages are in `packages.config`
//! files, `<PackageReference>` items and the `packages/` folder NuGet restores
//! into (often committed). This reads all of them:
//!
//! - `packages.config`: every package the project installed, transitive ones
//! included (NuGet writes them all there), so such a project is resolved;
//! - `<PackageReference>` in project files, with its version as an attribute,
//! a child element, a `VersionOverride`, or from the central
//! `Directory.Packages.props`; only the direct dependencies;
//! - `packages.lock.json` and `obj/project.assets.json`: the full resolution;
//! - `packages/<Id>.<Version>/` folders: what was restored (and committed).
//!
//! A project with `<PackageReference>` items and neither a lockfile nor an
//! assets file beside it has unknown transitive dependencies:
//! [`unresolved_projects`] reports it, so the SBOM does not look complete.
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use compliance_core::models::SbomEntry;
use super::UnlockedEcosystem;
use crate::pipeline::dotnet::{is_project_file, parse_xml, read_text, relative, walk_sources};
/// The package manager name SBOM entries carry, as Syft names it.
const NUGET: &str = "nuget";
/// One NuGet package as a source names it.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Package {
id: String,
/// The exact version, or `None` when only a range is known.
version: Option<String>,
/// The declared range, when it is not an exact version.
requirement: Option<String>,
}
/// Every NuGet package the tree under `root` names, as SBOM entries with a
/// `pkg:nuget/<id>@<version>` purl for the CVE lookup. A package with only a
/// version range gets no purl (it would match the advisories of every
/// version) and carries the range as its requirement.
pub(crate) fn nuget_components(root: &Path, repo_id: &str) -> Vec<SbomEntry> {
let mut packages: Vec<Package> = Vec::new();
let central = central_versions(root);
for entry in walk_sources(root) {
let name = entry.file_name().to_string_lossy();
let lower = name.to_ascii_lowercase();
if lower == "packages.config" {
packages.extend(read_packages_config(entry.path()));
} else if lower == "packages.lock.json" {
packages.extend(read_lock_file(entry.path()));
} else if is_project_file(&name) {
packages.extend(read_package_references(entry.path(), &central));
// `obj/` is skipped by the walk; the assets file in it is read here.
if let Some(dir) = entry.path().parent() {
packages.extend(read_assets_file(&dir.join("obj/project.assets.json")));
}
}
}
packages.extend(restored_packages(root));
let mut seen: HashSet<(String, String)> = HashSet::new();
let mut out = Vec::new();
for p in packages {
let key = (
p.id.to_ascii_lowercase(),
p.version
.clone()
.or_else(|| p.requirement.clone())
.unwrap_or_default()
.to_ascii_lowercase(),
);
if !seen.insert(key) {
continue;
}
let mut entry = SbomEntry::new(
repo_id.to_string(),
p.id.clone(),
p.version.clone().unwrap_or_default(),
NUGET.to_string(),
);
entry.purl = p
.version
.as_ref()
.map(|v| format!("pkg:nuget/{}@{}", p.id, v));
entry.version_requirement = p.requirement;
out.push(entry);
}
out
}
/// Add the [`nuget_components`] not already in `entries` (Syft reads
/// `packages.lock.json` too). Matched by name and version, case-insensitively,
/// as NuGet ids are.
pub(crate) fn merge_nuget(entries: &mut Vec<SbomEntry>, nuget: Vec<SbomEntry>) {
for n in nuget {
let known = entries.iter().any(|e| {
e.package_manager == NUGET
&& e.name.eq_ignore_ascii_case(&n.name)
&& e.version.eq_ignore_ascii_case(&n.version)
});
if !known {
entries.push(n);
}
}
}
/// The projects whose transitive NuGet dependencies are unknown: they declare
/// `<PackageReference>` items and have no `packages.lock.json` and no
/// `obj/project.assets.json` beside them. A `packages.config` project is
/// never one: its file lists the transitive packages too.
pub(crate) fn unresolved_projects(root: &Path) -> Vec<UnlockedEcosystem> {
walk_sources(root)
.filter(|e| is_project_file(&e.file_name().to_string_lossy()))
.filter(|e| {
read_text(e.path()).is_some_and(|text| text.contains("<PackageReference"))
&& e.path().parent().is_some_and(|dir| {
!dir.join("packages.lock.json").is_file()
&& !dir.join("obj/project.assets.json").is_file()
})
})
.map(|e| UnlockedEcosystem {
manifest: relative(root, e.path()),
problem: "declares NuGet packages with <PackageReference>, but neither a \
packages.lock.json nor an obj/project.assets.json lists the \
transitive ones",
remedy: "set <RestorePackagesWithLockFile>true</RestorePackagesWithLockFile> \
(in the project or a Directory.Build.props), restore once and commit \
packages.lock.json",
})
.collect()
}
/// A version NuGet would restore exactly: `1.2.3`, `[1.2.3]`, `1.2.3-beta`.
/// `None` for a floating version or a range (`1.*`, `[1.0,2.0)`).
pub(super) fn exact_version(raw: &str) -> Option<String> {
let v = raw.trim();
let v = v
.strip_prefix('[')
.and_then(|s| s.strip_suffix(']'))
.unwrap_or(v)
.trim();
let valid = !v.is_empty()
&& v.chars().next().is_some_and(|c| c.is_ascii_digit())
&& v.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '+'))
&& !v.contains('*');
valid.then(|| v.to_string())
}
/// A package from an id and a declared version (exact or a range).
fn package(id: &str, declared: &str) -> Option<Package> {
let id = id.trim();
if id.is_empty() || id.contains("$(") || declared.contains("$(") {
return None;
}
let version = exact_version(declared);
let requirement =
(version.is_none() && !declared.trim().is_empty()).then(|| declared.trim().to_string());
Some(Package {
id: id.to_string(),
version,
requirement,
})
}
/// `<package id="…" version="…" />` entries of a `packages.config`.
fn read_packages_config(path: &Path) -> Vec<Package> {
let Some(text) = read_text(path) else {
return Vec::new();
};
let Some(doc) = parse_xml(&text) else {
return Vec::new();
};
doc.descendants()
.filter(|n| n.is_element() && n.tag_name().name() == "package")
.filter_map(|n| package(n.attribute("id")?, n.attribute("version")?))
.collect()
}
/// The central versions of every `Directory.Packages.props` in the tree, by
/// its directory: `<PackageVersion Include="…" Version="…" />`.
fn central_versions(root: &Path) -> Vec<(PathBuf, HashMap<String, String>)> {
let mut out = Vec::new();
for entry in walk_sources(root) {
if !entry
.file_name()
.to_string_lossy()
.eq_ignore_ascii_case("Directory.Packages.props")
{
continue;
}
let Some(text) = read_text(entry.path()) else {
continue;
};
let Some(doc) = parse_xml(&text) else {
continue;
};
let versions = doc
.descendants()
.filter(|n| n.is_element() && n.tag_name().name() == "PackageVersion")
.filter_map(|n| {
let id = n.attribute("Include").or(n.attribute("Update"))?;
let version = n
.attribute("Version")
.map(str::to_string)
.or_else(|| child_text(n, "Version").map(str::to_string))?;
Some((id.to_ascii_lowercase(), version))
})
.collect();
if let Some(dir) = entry.path().parent() {
out.push((dir.to_path_buf(), versions));
}
}
// Deepest first: the nearest file above a project is the one that applies.
out.sort_by_key(|(dir, _)| std::cmp::Reverse(dir.components().count()));
out
}
/// The text of `node`'s child element `name`.
fn child_text<'a>(node: roxmltree::Node<'a, '_>, name: &str) -> Option<&'a str> {
node.children()
.find(|c| c.is_element() && c.tag_name().name() == name)
.and_then(|c| c.text())
}
/// The `<PackageReference>` items of a project file.
fn read_package_references(
path: &Path,
central: &[(PathBuf, HashMap<String, String>)],
) -> Vec<Package> {
let Some(text) = read_text(path) else {
return Vec::new();
};
let Some(doc) = parse_xml(&text) else {
return Vec::new();
};
let central_for = |id: &str| {
central
.iter()
.find(|(dir, _)| path.starts_with(dir))
.and_then(|(_, versions)| versions.get(&id.to_ascii_lowercase()))
.cloned()
};
doc.descendants()
.filter(|n| n.is_element() && n.tag_name().name() == "PackageReference")
.filter_map(|n| {
let id = n.attribute("Include")?;
let declared = n
.attribute("VersionOverride")
.or(n.attribute("Version"))
.map(str::to_string)
.or_else(|| child_text(n, "VersionOverride").map(str::to_string))
.or_else(|| child_text(n, "Version").map(str::to_string))
.or_else(|| central_for(id))
.unwrap_or_default();
package(id, &declared)
})
.collect()
}
/// The packages of a `packages.lock.json`, every target framework, without
/// the project-to-project references.
fn read_lock_file(path: &Path) -> Vec<Package> {
#[derive(serde::Deserialize)]
struct Lock {
#[serde(default)]
dependencies: HashMap<String, HashMap<String, Locked>>,
}
#[derive(serde::Deserialize)]
struct Locked {
#[serde(rename = "type", default)]
kind: String,
#[serde(default)]
resolved: Option<String>,
}
let Some(lock) = read_text(path).and_then(|t| serde_json::from_str::<Lock>(&t).ok()) else {
return Vec::new();
};
let mut out: Vec<Package> = lock
.dependencies
.into_values()
.flatten()
.filter(|(_, l)| !l.kind.eq_ignore_ascii_case("project"))
.filter_map(|(id, l)| package(&id, l.resolved.as_deref()?))
.collect();
out.sort_by(|a, b| a.id.cmp(&b.id));
out
}
/// The packages of an `obj/project.assets.json` (keys `Id/Version` of its
/// `libraries`), without the project references.
fn read_assets_file(path: &Path) -> Vec<Package> {
#[derive(serde::Deserialize)]
struct Assets {
#[serde(default)]
libraries: HashMap<String, Library>,
}
#[derive(serde::Deserialize)]
struct Library {
#[serde(rename = "type", default)]
kind: String,
}
if !path.is_file() {
return Vec::new();
}
let Some(assets) = read_text(path).and_then(|t| serde_json::from_str::<Assets>(&t).ok()) else {
return Vec::new();
};
let mut out: Vec<Package> = assets
.libraries
.into_iter()
.filter(|(_, l)| l.kind == "package")
.filter_map(|(key, _)| {
let (id, version) = key.split_once('/')?;
package(id, version)
})
.collect();
out.sort_by(|a, b| a.id.cmp(&b.id));
out
}
/// The packages restored into (and often committed with) a `packages/`
/// folder: `packages/<Id>.<Version>/` holding a `.nupkg` or the package's
/// `lib/`. Folders are found next to any solution or project, at any depth.
fn restored_packages(root: &Path) -> Vec<Package> {
let mut out = Vec::new();
let walker = walkdir::WalkDir::new(root)
.min_depth(1)
.max_depth(16)
.sort_by_file_name()
.into_iter()
.filter_entry(|e| {
let name = e.file_name().to_string_lossy();
!(e.file_type().is_dir()
&& [".git", "node_modules", "bin", "obj", ".vs"]
.iter()
.any(|d| name.eq_ignore_ascii_case(d)))
});
let mut walker = walker;
while let Some(entry) = walker.next() {
let Ok(entry) = entry else {
continue;
};
if !entry.file_type().is_dir() || !entry.file_name().eq_ignore_ascii_case("packages") {
continue;
}
let Ok(children) = std::fs::read_dir(entry.path()) else {
continue;
};
let mut found: Vec<Package> = children
.filter_map(Result::ok)
.filter(|c| c.file_type().is_ok_and(|t| t.is_dir()))
.filter(|c| is_restored_package(&c.path()))
.filter_map(|c| split_package_folder(&c.file_name().to_string_lossy()))
.collect();
if !found.is_empty() {
found.sort_by(|a, b| a.id.cmp(&b.id));
out.extend(found);
walker.skip_current_dir();
}
}
out
}
/// Whether `dir` is a package NuGet restored: named `<Id>.<Version>`, and
/// holding a `.nupkg` or the `lib/`, `build/` or `tools/` folder of one. Both
/// are needed: a JavaScript workspace package has a `lib/` too, but not a
/// version in its folder name.
pub(crate) fn is_restored_package(dir: &Path) -> bool {
dir.file_name()
.is_some_and(|n| split_package_folder(&n.to_string_lossy()).is_some())
&& holds_package_content(dir)
}
/// Whether `dir` holds a `.nupkg`, or the `lib/`, `build/` or `tools/` folder
/// of one.
fn holds_package_content(dir: &Path) -> bool {
std::fs::read_dir(dir).is_ok_and(|entries| {
entries.filter_map(Result::ok).any(|e| {
let name = e.file_name().to_string_lossy().to_ascii_lowercase();
name.ends_with(".nupkg")
|| (e.file_type().is_ok_and(|t| t.is_dir())
&& matches!(name.as_str(), "lib" | "build" | "tools"))
})
})
}
/// `Newtonsoft.Json.12.0.1` as id `Newtonsoft.Json` and version `12.0.1`:
/// the version is the shortest dotted tail that is one.
fn split_package_folder(name: &str) -> Option<Package> {
name.match_indices('.').find_map(|(i, _)| {
let (id, rest) = (&name[..i], &name[i + 1..]);
let numeric = rest.split(['-', '+']).next().unwrap_or(rest);
let parts: Vec<&str> = numeric.split('.').collect();
let is_version = (2..=4).contains(&parts.len())
&& parts
.iter()
.all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()));
(is_version && !id.is_empty()).then(|| Package {
id: id.to_string(),
version: Some(rest.to_string()),
requirement: None,
})
})
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
struct Tree(PathBuf);
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn tree(files: &[(&str, &str)]) -> Tree {
let dir = std::env::temp_dir().join(format!("cs-nuget-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).expect("mkdir");
for (path, content) in files {
let full = dir.join(path);
std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir");
std::fs::write(full, content).expect("write");
}
Tree(dir)
}
fn purls(root: &Path) -> Vec<String> {
let mut out: Vec<String> = nuget_components(root, "r")
.into_iter()
.map(|e| {
e.purl
.unwrap_or_else(|| format!("{} {}", e.name, e.version_requirement.unwrap()))
})
.collect();
out.sort();
out
}
#[test]
fn packages_config_lists_its_packages() {
let t = tree(&[(
"Hmi/packages.config",
r#"<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="12.0.1" targetFramework="net48" />
<package id="log4net" version="2.0.8" targetFramework="net48" />
</packages>"#,
)]);
assert_eq!(
purls(&t.0),
[
"pkg:nuget/Newtonsoft.Json@12.0.1",
"pkg:nuget/log4net@2.0.8"
]
);
}
#[test]
fn package_references_take_every_version_form() {
let t = tree(&[
(
"Directory.Packages.props",
r#"<Project><ItemGroup>
<PackageVersion Include="Serilog" Version="2.10.0" />
</ItemGroup></Project>"#,
),
(
"src/App/App.csproj",
r#"<Project Sdk="Microsoft.NET.Sdk"><ItemGroup>
<PackageReference Include="Dapper" Version="2.0.4" />
<PackageReference Include="BouncyCastle">
<Version>1.8.5</Version>
</PackageReference>
<PackageReference Include="Serilog" />
<PackageReference Include="Polly" Version="7.*" />
<PackageReference Include="Exact" Version="[3.1.0]" />
</ItemGroup></Project>"#,
),
]);
assert_eq!(
purls(&t.0),
[
"Polly 7.*",
"pkg:nuget/BouncyCastle@1.8.5",
"pkg:nuget/Dapper@2.0.4",
"pkg:nuget/Exact@3.1.0",
"pkg:nuget/Serilog@2.10.0",
]
);
// Direct references only: the project is reported as unresolved.
let unresolved = unresolved_projects(&t.0);
assert_eq!(unresolved.len(), 1);
assert_eq!(unresolved[0].manifest, "src/App/App.csproj");
}
#[test]
fn lockfiles_and_assets_resolve_the_transitive_packages() {
let t = tree(&[
(
"A/A.csproj",
r#"<Project Sdk="Microsoft.NET.Sdk"><ItemGroup><PackageReference Include="Dapper" Version="2.0.4" /></ItemGroup></Project>"#,
),
(
"A/packages.lock.json",
r#"{"version":1,"dependencies":{"net48":{
"Dapper":{"type":"Direct","requested":"[2.0.4, )","resolved":"2.0.4"},
"System.Memory":{"type":"Transitive","resolved":"4.5.4"},
"B":{"type":"Project"}}}}"#,
),
(
"B/B.csproj",
r#"<Project Sdk="Microsoft.NET.Sdk"><ItemGroup><PackageReference Include="Polly" Version="7.2.1" /></ItemGroup></Project>"#,
),
(
"B/obj/project.assets.json",
r#"{"libraries":{"Polly/7.2.1":{"type":"package"},"A/1.0.0":{"type":"project"}}}"#,
),
]);
assert_eq!(
purls(&t.0),
[
"pkg:nuget/Dapper@2.0.4",
"pkg:nuget/Polly@7.2.1",
"pkg:nuget/System.Memory@4.5.4",
]
);
assert!(unresolved_projects(&t.0).is_empty());
}
#[test]
fn restored_package_folders_are_components() {
let t = tree(&[
("Plant.sln", ""),
(
"packages/Newtonsoft.Json.12.0.1/Newtonsoft.Json.12.0.1.nupkg",
"",
),
(
"packages/EntityFramework.6.2.0/lib/net45/EntityFramework.dll",
"",
),
// Not a restored package: no .nupkg, no lib/.
("packages/widgets/package.json", "{}"),
]);
assert_eq!(
purls(&t.0),
[
"pkg:nuget/EntityFramework@6.2.0",
"pkg:nuget/Newtonsoft.Json@12.0.1",
]
);
}
#[test]
fn package_folder_names_split_at_the_version() {
let split = |n: &str| {
let p = split_package_folder(n).unwrap();
(p.id, p.version.unwrap())
};
assert_eq!(
split("Microsoft.AspNet.Mvc.5.2.7"),
("Microsoft.AspNet.Mvc".into(), "5.2.7".into())
);
assert_eq!(
split("Foo.2.Bar.1.0.0-beta1"),
("Foo.2.Bar".into(), "1.0.0-beta1".into())
);
assert!(split_package_folder("NoVersion").is_none());
}
#[test]
fn syft_entries_are_not_repeated() {
let mut entries = vec![SbomEntry::new(
"r".into(),
"newtonsoft.json".into(),
"12.0.1".into(),
"nuget".into(),
)];
let t = tree(&[(
"packages.config",
r#"<packages><package id="Newtonsoft.Json" version="12.0.1" /><package id="Dapper" version="2.0.4" /></packages>"#,
)]);
merge_nuget(&mut entries, nuget_components(&t.0, "r"));
assert_eq!(entries.len(), 2);
}
#[test]
fn a_packages_config_project_is_resolved() {
let t = tree(&[
(
"Hmi/Hmi.csproj",
"<Project ToolsVersion=\"15.0\"></Project>",
),
("Hmi/packages.config", "<packages />"),
]);
assert!(unresolved_projects(&t.0).is_empty());
}
}
File diff suppressed because it is too large. Load diff
+55 -3
View File
@@ -6,7 +6,7 @@ use compliance_core::CoreError;
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
pub(super) async fn run_syft(repo_path: &Path, repo_id: &str) -> Result<Vec<SbomEntry>, CoreError> {
let output = tokio::time::timeout(
std::time::Duration::from_secs(300),
std::time::Duration::from_secs(600),
crate::pipeline::tool_cmd::tool("syft", &["SYFT_CACHE_DIR"])
.arg(repo_path)
.args(["-o", "cyclonedx-json"])
@@ -19,7 +19,7 @@ pub(super) async fn run_syft(repo_path: &Path, repo_id: &str) -> Result<Vec<Sbom
.await
.map_err(|_| CoreError::Scanner {
scanner: "syft".to_string(),
source: "timed out after 5 minutes".into(),
source: "timed out after 10 minutes".into(),
})?
.map_err(|e| CoreError::Scanner {
scanner: "syft".to_string(),
@@ -55,7 +55,7 @@ pub(super) async fn run_syft(repo_path: &Path, repo_id: &str) -> Result<Vec<Sbom
c.version.unwrap_or_else(|| "unknown".to_string()),
package_manager,
);
entry.purl = c.purl;
entry.purl = c.purl.map(canonical_purl);
entry.license = c.licenses.and_then(|ls| extract_license(&ls));
entry
})
@@ -122,6 +122,32 @@ fn extract_license(entries: &[CdxLicenseWrapper]) -> Option<String> {
Some(parts.join(" OR "))
}
/// `purl` in the form advisory databases look it up by.
///
/// Syft names a Swift package by its repository URL followed by the package
/// identity again, `pkg:swift/github.com/apple/swift-nio.git/swift-nio@2.40.0`.
/// The purl spec (and OSV, which keys Swift advisories by repository URL)
/// expects `pkg:swift/github.com/apple/swift-nio@2.40.0`: in Syft's form every
/// Swift package matched no advisory at all. Every other purl, and a Swift one
/// already in that form, is returned unchanged.
fn canonical_purl(purl: String) -> String {
let Some(rest) = purl.strip_prefix("pkg:swift/") else {
return purl;
};
// The version, qualifiers and subpath follow the name unchanged.
let (path, tail) = rest.split_at(rest.find(['@', '?', '#']).unwrap_or(rest.len()));
let Some((namespace, name)) = path.rsplit_once('/') else {
return purl;
};
let repository = namespace.strip_suffix(".git").unwrap_or(namespace);
match repository.rsplit_once('/') {
Some((_, repo_name)) if repo_name.eq_ignore_ascii_case(name) => {
format!("pkg:swift/{repository}{tail}")
}
_ => purl,
}
}
/// Extract the ecosystem/package-manager from a PURL string.
/// e.g. "pkg:npm/lodash@4.17.21" -> "npm", "pkg:cargo/serde@1.0" -> "cargo"
fn extract_ecosystem_from_purl(purl: &str) -> Option<String> {
@@ -143,6 +169,32 @@ fn extract_ecosystem_from_purl(purl: &str) -> Option<String> {
mod tests {
use super::*;
#[test]
fn a_swift_purl_is_keyed_by_its_repository() {
assert_eq!(
canonical_purl(
"pkg:swift/github.com/apple/swift-nio-http2.git/swift-nio-http2@1.19.0".into()
),
"pkg:swift/github.com/apple/swift-nio-http2@1.19.0"
);
assert_eq!(
canonical_purl("pkg:swift/github.com/Alamofire/Alamofire/alamofire@5.6.0".into()),
"pkg:swift/github.com/Alamofire/Alamofire@5.6.0"
);
}
#[test]
fn a_canonical_or_foreign_purl_is_left_alone() {
for purl in [
"pkg:swift/github.com/apple/swift-nio-http2@1.19.0",
"pkg:swift/swift-nio@2.0.0",
"pkg:maven/com.squareup.okhttp3/okhttp@3.12.0",
"pkg:cocoapods/AFNetworking@2.5.1",
] {
assert_eq!(canonical_purl(purl.into()), purl);
}
}
// --- extract_ecosystem_from_purl tests ---
#[test]
+203
View File
@@ -0,0 +1,203 @@
//! Components of Unity projects.
//!
//! A Unity project is recognised by `ProjectSettings/ProjectVersion.txt`. The
//! editor version written there is itself a component of the shipped app
//! (Unity's runtime is built into it), and an outdated one matters for the CRA.
//! The Unity packages the project uses are read from `Packages/packages-lock.json`
//! (exact versions, with what they pull in) or else `Packages/manifest.json`.
//! A project without `Packages/` has packages nobody can list; that is an
//! end-of-life build, reported by [`crate::pipeline::build_lifecycle`].
//!
//! No advisory database covers Unity or its packages, so these components are
//! listed as not matched for CVEs (see [`crate::pipeline::cve`]).
use std::path::{Path, PathBuf};
use compliance_core::models::SbomEntry;
use super::mobile::{MAX_DEPTH, SKIPPED_DIRS};
/// The package manager name of every Unity component.
pub(crate) const UNITY_MANAGER: &str = "unity";
/// The name of the component standing for the editor (and runtime) version.
const EDITOR_COMPONENT: &str = "Unity Editor";
/// The Unity projects under `root`: the directories holding
/// `ProjectSettings/ProjectVersion.txt`.
fn unity_projects(root: &Path) -> Vec<PathBuf> {
walkdir::WalkDir::new(root)
.min_depth(1)
.max_depth(MAX_DEPTH)
.sort_by_file_name()
.into_iter()
.filter_entry(|e| {
!(e.file_type().is_dir()
&& SKIPPED_DIRS.contains(&e.file_name().to_string_lossy().as_ref()))
})
.filter_map(Result::ok)
.filter(|e| e.file_type().is_file() && e.file_name() == "ProjectVersion.txt")
.filter_map(|e| {
let settings = e.path().parent()?;
(settings.file_name()? == "ProjectSettings")
.then(|| settings.parent().map(Path::to_path_buf))
.flatten()
})
.collect()
}
/// The editor version `ProjectVersion.txt` names (`m_EditorVersion: 2019.2.4f1`).
fn editor_version(project: &Path) -> Option<String> {
let text = std::fs::read_to_string(project.join("ProjectSettings/ProjectVersion.txt")).ok()?;
text.lines()
.find_map(|line| line.trim().strip_prefix("m_EditorVersion:"))
.map(|v| v.trim().to_string())
.filter(|v| !v.is_empty())
}
/// The packages a project's `Packages/` folder pins: from
/// `packages-lock.json` the registry and git packages (not Unity's built-in
/// modules or the project's own embedded and local packages), else from
/// `manifest.json` those with an exact version. `None` without either file.
fn packages(project: &Path) -> Option<Vec<(String, String)>> {
let dir = project.join("Packages");
let read = |name: &str| -> Option<serde_json::Value> {
serde_json::from_str(&std::fs::read_to_string(dir.join(name)).ok()?).ok()
};
if let Some(lock) = read("packages-lock.json") {
let deps = lock["dependencies"].as_object()?;
return Some(
deps.iter()
.filter(|(_, p)| matches!(p["source"].as_str(), Some("registry" | "git")))
.filter_map(|(name, p)| Some((name.clone(), p["version"].as_str()?.to_string())))
.collect(),
);
}
let manifest = read("manifest.json")?;
let deps = manifest["dependencies"].as_object()?;
Some(
deps.iter()
.filter(|(name, _)| !name.starts_with("com.unity.modules."))
.filter_map(|(name, v)| Some((name.clone(), v.as_str()?.to_string())))
.filter(|(_, v)| v.chars().next().is_some_and(|c| c.is_ascii_digit()))
.collect(),
)
}
/// The Unity components under `root`: each project's editor version and the
/// packages its `Packages/` folder pins.
///
/// # Arguments
///
/// * `root` - the checked-out or unpacked source tree
/// * `repo_id` - the target the entries belong to
pub(crate) fn unity_components(root: &Path, repo_id: &str) -> Vec<SbomEntry> {
let mut out = Vec::new();
for project in unity_projects(root) {
if let Some(version) = editor_version(&project) {
out.push(SbomEntry::new(
repo_id.to_string(),
EDITOR_COMPONENT.to_string(),
version,
UNITY_MANAGER.to_string(),
));
}
for (name, version) in packages(&project).unwrap_or_default() {
out.push(SbomEntry::new(
repo_id.to_string(),
name,
version,
UNITY_MANAGER.to_string(),
));
}
}
out.sort_by(|a, b| (&a.name, &a.version).cmp(&(&b.name, &b.version)));
out.dedup_by(|a, b| a.name == b.name && a.version == b.version);
out
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
/// A scratch tree holding `files`, removed on drop.
struct Tree(PathBuf);
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn tree(files: &[(&str, &str)]) -> Tree {
let dir = std::env::temp_dir().join(format!("cs-unity-{}", uuid::Uuid::new_v4()));
for (path, content) in files {
let full = dir.join(path);
std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir");
std::fs::write(full, content).expect("write");
}
Tree(dir)
}
fn components(t: &Tree) -> Vec<String> {
unity_components(&t.0, "t")
.into_iter()
.map(|e| format!("{}@{}", e.name, e.version))
.collect()
}
const VERSION: &str =
"m_EditorVersion: 2019.2.4f1\nm_EditorVersionWithRevision: 2019.2.4f1 (c63b2af89a85)\n";
#[test]
fn a_unity_project_without_packages_lists_its_editor() {
let t = tree(&[("GT Unity/ProjectSettings/ProjectVersion.txt", VERSION)]);
assert_eq!(components(&t), ["Unity Editor@2019.2.4f1"]);
}
#[test]
fn the_lock_lists_registry_and_git_packages_only() {
let lock = r#"{ "dependencies": {
"com.unity.textmeshpro": { "version": "2.0.1", "depth": 0, "source": "registry" },
"com.unity.modules.ui": { "version": "1.0.0", "depth": 0, "source": "builtin" },
"com.example.own": { "version": "file:own", "depth": 0, "source": "embedded" },
"com.vendor.sdk": { "version": "https://git.example/sdk.git#1.4.0", "depth": 0, "source": "git" }
} }"#;
let t = tree(&[
("ProjectSettings/ProjectVersion.txt", VERSION),
("Packages/packages-lock.json", lock),
("Packages/manifest.json", "{}"),
]);
assert_eq!(
components(&t),
[
"Unity Editor@2019.2.4f1",
"com.unity.textmeshpro@2.0.1",
"com.vendor.sdk@https://git.example/sdk.git#1.4.0",
]
);
}
#[test]
fn without_a_lock_the_manifest_gives_exact_versions() {
let manifest = r#"{ "dependencies": {
"com.unity.analytics": "3.3.2",
"com.unity.modules.audio": "1.0.0",
"com.example.local": "file:../local"
} }"#;
let t = tree(&[
("ProjectSettings/ProjectVersion.txt", VERSION),
("Packages/manifest.json", manifest),
]);
assert_eq!(
components(&t),
["Unity Editor@2019.2.4f1", "com.unity.analytics@3.3.2"]
);
}
#[test]
fn a_tree_without_unity_has_nothing() {
let t = tree(&[("src/main.c", "int main;")]);
assert!(components(&t).is_empty());
}
}
+109 -27
View File
@@ -10,28 +10,55 @@ use crate::pipeline::source_text::{read_lines, relative_path};
/// What open-source semgrep writes in place of the matched code.
const REDACTED_LINES: &str = "requires login";
/// Custom CRA-control detectors bundled into the binary and staged to a temp file
/// at scan time so semgrep can `--config` them alongside the auto ruleset. These
/// cover controls no off-the-shelf rule digs out (secure defaults, weak password
/// hashing, insecure session cookies, weak data-at-rest ciphers); each rule id is
/// keyed back to its control by the `control-map` LUT.
const CRA_RULES: &str = include_str!("../../rules/cra_semgrep.yaml");
/// Our own CRA-control rules, bundled into the binary and staged to temp
/// files at scan time: every `rules/*.yaml` pack, one per language family
/// (a test keeps this list complete). They are the only rules semgrep runs:
/// the Semgrep registry rules (`--config=auto`, `p/...`) are licensed for
/// internal use only, not for a service offered to others, and `auto` cannot
/// run without sending metrics to Semgrep. Each rule id is keyed back to its
/// control by the `control-map` LUT.
///
/// Each pack is staged under its own fixed name: semgrep prefixes a rule's
/// check_id with the config path, and the check_id is part of a finding's
/// fingerprint, so the first pack keeps the name it always had.
const RULE_PACKS: &[(&str, &str)] = &[
(
"compliance-cra-semgrep.yaml",
include_str!("../../rules/cra_semgrep.yaml"),
),
(
"compliance-cra-semgrep-csharp.yaml",
include_str!("../../rules/cra_semgrep_csharp.yaml"),
),
];
/// Write the bundled CRA rules to a stable temp path (atomic: unique tmp +
/// rename). Returns `None` on failure — the scan then runs with auto rules only.
async fn stage_cra_rules() -> Option<PathBuf> {
/// Write the bundled rule packs to stable temp paths (atomic: unique tmp +
/// rename). The tmp name is unique per call, not per process: scans run
/// concurrently in one agent, and a shared tmp file let one scan rename it
/// away while another was still writing it, failing that scan's SAST stage.
///
/// # Errors
///
/// Returns `CoreError::Scanner` when a file cannot be written: without it
/// semgrep would skip those rules, and the stage must read as failed, not
/// clean.
async fn stage_cra_rules() -> Result<Vec<PathBuf>, CoreError> {
let dir = std::env::temp_dir();
let path = dir.join("compliance-cra-semgrep.yaml");
let tmp = dir.join(format!("compliance-cra-semgrep.{}.tmp", std::process::id()));
if let Err(e) = tokio::fs::write(&tmp, CRA_RULES).await {
tracing::warn!(error = %e, "failed to stage custom CRA semgrep rules; using auto rules only");
return None;
let mut staged_paths = Vec::with_capacity(RULE_PACKS.len());
for (name, rules) in RULE_PACKS {
let path = dir.join(name);
let tmp = dir.join(format!("{name}.{}.tmp", uuid::Uuid::new_v4()));
let staged = async {
tokio::fs::write(&tmp, rules).await?;
tokio::fs::rename(&tmp, &path).await
};
staged.await.map_err(|e| CoreError::Scanner {
scanner: "semgrep".to_string(),
source: format!("could not stage the CRA rules ({name}): {e}").into(),
})?;
staged_paths.push(path);
}
if let Err(e) = tokio::fs::rename(&tmp, &path).await {
tracing::warn!(error = %e, "failed to stage custom CRA semgrep rules; using auto rules only");
return None;
}
Some(path)
Ok(staged_paths)
}
/// semgrep over a tree, skipping vendor directories.
@@ -59,15 +86,25 @@ impl Scanner for SemgrepScanner {
#[tracing::instrument(skip_all)]
async fn scan(&self, repo_path: &Path, repo_id: &str) -> Result<ScanOutput, CoreError> {
let cra_rules = stage_cra_rules().await;
let rule_packs = stage_cra_rules().await?;
// Empty environment + kill-on-drop: semgrep only needs to find itself
// and write temp files, and a timed-out run must actually die.
let mut command = crate::pipeline::tool_cmd::tool("semgrep", &["SEMGREP_RULES"]);
command.arg("--config=auto");
if let Some(path) = &cra_rules {
command.arg(format!("--config={}", path.display()));
// and write temp files, and a timed-out run must actually die. No
// metrics and no version check: nothing about a customer's code leaves
// the scan.
let mut command = crate::pipeline::tool_cmd::tool("semgrep", &[]);
for pack in &rule_packs {
command.arg(format!("--config={}", pack.display()));
}
command.args(["--json", "--quiet", "--max-memory", "500", "--jobs", "2"]);
command.args([
"--metrics=off",
"--disable-version-check",
"--json",
"--quiet",
"--max-memory",
"500",
"--jobs",
"2",
]);
// Anchored at the tree root: a bare `Drivers` would also skip a
// customer's own `app/Drivers/`.
for dir in &self.excluded {
@@ -200,7 +237,11 @@ mod tests {
fn rule_languages() -> std::collections::HashMap<String, Vec<String>> {
let mut out = std::collections::HashMap::new();
let mut id = None;
for line in CRA_RULES.lines().map(str::trim) {
for line in RULE_PACKS
.iter()
.flat_map(|(_, rules)| rules.lines())
.map(str::trim)
{
if let Some(rest) = line.strip_prefix("- id:") {
id = Some(rest.trim().to_string());
} else if let (Some(rest), Some(rule)) = (line.strip_prefix("languages:"), id.take()) {
@@ -245,6 +286,47 @@ mod tests {
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn concurrent_scans_all_get_the_rules() {
let tasks: Vec<_> = (0..32).map(|_| tokio::spawn(stage_cra_rules())).collect();
for task in tasks {
let paths = task.await.unwrap().expect("staged");
assert_eq!(paths.len(), RULE_PACKS.len());
for (path, (_, rules)) in paths.iter().zip(RULE_PACKS) {
assert_eq!(std::fs::read_to_string(path).unwrap(), *rules);
}
}
}
#[test]
fn every_rule_file_is_bundled() {
// A pack added to rules/ but not to RULE_PACKS would never run.
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("rules");
let mut on_disk: Vec<String> = std::fs::read_dir(&dir)
.unwrap_or_else(|e| panic!("{}: {e}", dir.display()))
.filter_map(Result::ok)
.map(|e| e.file_name().to_string_lossy().to_string())
.filter(|n| n.ends_with(".yaml") || n.ends_with(".yml"))
.collect();
on_disk.sort();
let mut bundled: Vec<String> = RULE_PACKS
.iter()
.map(|(_, rules)| {
std::fs::read_dir(&dir)
.unwrap_or_else(|e| panic!("{e}"))
.filter_map(Result::ok)
.find(|e| std::fs::read_to_string(e.path()).is_ok_and(|t| t == *rules))
.map(|e| e.file_name().to_string_lossy().to_string())
.unwrap_or_default()
})
.collect();
bundled.sort();
assert_eq!(on_disk, bundled);
// The first pack keeps its staged name: check_ids, and with them the
// fingerprints of existing findings, depend on it.
assert_eq!(RULE_PACKS[0].0, "compliance-cra-semgrep.yaml");
}
#[test]
fn extract_cwe_handles_list_and_normalises() {
let md = serde_json::json!({"cwe": ["CWE-798: Use of Hard-coded Credentials"]});
+12 -6
View File
@@ -19,12 +19,11 @@ pub fn relative_path(root: &Path, path: &str) -> String {
rel.to_string_lossy().replace('\\', "/")
}
/// Lines `start..=end` (1-based, inclusive) of `root/rel`, capped at
/// [`MAX_SNIPPET_LINES`]. `None` when the file is unreadable or the path would
/// leave `root`.
pub fn read_lines(root: &Path, rel: &str, start: u32, end: u32) -> Option<String> {
/// 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.
pub fn read_text(root: &Path, rel: &str) -> Option<String> {
let rel_path = Path::new(rel);
// Scanner output is not trusted to stay inside the tree.
if rel_path.is_absolute()
|| rel_path
.components()
@@ -32,9 +31,16 @@ pub fn read_lines(root: &Path, rel: &str, start: u32, end: u32) -> Option<String
{
return None;
}
std::fs::read_to_string(root.join(rel_path)).ok()
}
/// Lines `start..=end` (1-based, inclusive) of `root/rel`, capped at
/// [`MAX_SNIPPET_LINES`]. `None` when the file is unreadable or the path would
/// leave `root`.
pub fn read_lines(root: &Path, rel: &str, start: u32, end: u32) -> Option<String> {
let start = start.max(1);
let end = end.max(start).min(start + MAX_SNIPPET_LINES - 1);
let text = std::fs::read_to_string(root.join(rel_path)).ok()?;
let text = read_text(root, rel)?;
let lines: Vec<&str> = text
.lines()
.skip(start as usize - 1)
+1 -1
View File
@@ -110,7 +110,7 @@ mod tests {
// `Command`'s environment is not readable back, so assert on what we can
// see: the program, and that building one does not panic with a cleared
// environment plus extras.
let cmd = tool("semgrep", &["SEMGREP_RULES"]);
let cmd = tool("semgrep", &[]);
assert_eq!(cmd.as_std().get_program(), "semgrep");
assert!(cmd.as_std().get_envs().count() > 0, "allowlist applied");
}
@@ -37,6 +37,50 @@ impl TrackerDispatch {
}
}
/// Open or close the issue `external_id` (`"open"`, `"closed"`).
pub(crate) async fn update_issue_status(
&self,
owner: &str,
repo: &str,
external_id: &str,
status: &str,
) -> Result<(), compliance_core::error::CoreError> {
match self {
Self::GitHub(t) => {
t.update_issue_status(owner, repo, external_id, status)
.await
}
Self::GitLab(t) => {
t.update_issue_status(owner, repo, external_id, status)
.await
}
Self::Gitea(t) => {
t.update_issue_status(owner, repo, external_id, status)
.await
}
Self::Jira(t) => {
t.update_issue_status(owner, repo, external_id, status)
.await
}
}
}
/// Comment `body` on the issue `external_id`.
pub(crate) async fn add_comment(
&self,
owner: &str,
repo: &str,
external_id: &str,
body: &str,
) -> Result<(), compliance_core::error::CoreError> {
match self {
Self::GitHub(t) => t.add_comment(owner, repo, external_id, body).await,
Self::GitLab(t) => t.add_comment(owner, repo, external_id, body).await,
Self::Gitea(t) => t.add_comment(owner, repo, external_id, body).await,
Self::Jira(t) => t.add_comment(owner, repo, external_id, body).await,
}
}
pub(crate) async fn find_existing_issue(
&self,
owner: &str,
+152 -2
View File
@@ -13,7 +13,10 @@
//! `Core/`, `Middlewares/`, and `Middleware/` next to `Drivers/` (the
//! FreeRTOS/ST reference projects);
//! - a vendored library wherever it sits, recognised by the files it always
//! ships (Mbed TLS, lwIP, the FreeRTOS kernel, wolfSSL, FatFs).
//! ships (Mbed TLS, lwIP, the FreeRTOS kernel, wolfSSL, FatFs);
//! - .NET build output and restored packages: `bin/` and `obj/` beside a
//! project or solution, `packages/` holding restored NuGet packages, `.vs/`,
//! `.nuget/` and `TestResults/` (#445).
use std::path::Path;
@@ -130,10 +133,86 @@ fn is_vendor_dir(name: &str, path: &Path) -> bool {
}
// STM32Cube generates `Core/` for the application and `Drivers/` for the
// HAL, CMSIS and BSP. Only in that layout is `Drivers/` the vendor's.
name == "drivers"
if name == "drivers"
&& path
.parent()
.is_some_and(|parent| has_child_dir(parent, "core"))
{
return true;
}
is_mobile_build_dir(name, path) || is_dotnet_build_dir(name, path)
}
/// Unity's generated folders, next to its `ProjectSettings/`.
const UNITY_GENERATED: &[&str] = &["library", "temp", "obj", "logs", "builds", "usersettings"];
/// Whether the directory `name` (lower-cased) at `path` is build output, a
/// tool cache or installed third-party code of an Android, iOS or Unity
/// project, committed by mistake or by habit. Matched only beside the file
/// that makes it so, so a customer's own `build/` or `plugins/` stays theirs.
fn is_mobile_build_dir(name: &str, path: &Path) -> bool {
let Some(parent) = path.parent() else {
return false;
};
let beside = |file: &str| parent.join(file).is_file();
match name {
// Gradle's output and cache of a module or the root project.
"build" => beside("build.gradle") || beside("build.gradle.kts"),
".gradle" => true,
// CocoaPods and Carthage install third-party code into the tree.
"pods" => beside("Podfile"),
"carthage" => beside("Cartfile"),
"deriveddata" => true,
// Unity: the editor's caches and builds, and Asset Store packages in
// `Assets/Plugins`.
_ if UNITY_GENERATED.contains(&name) => parent.join("ProjectSettings").is_dir(),
"plugins" => {
parent_is(path, "assets")
&& parent
.parent()
.is_some_and(|project| project.join("ProjectSettings").is_dir())
}
_ => false,
}
}
/// .NET directories that are never the project's own code (#445), compared
/// lower-case: Visual Studio's state, NuGet's old tool folder and test
/// results always; `bin/` and `obj/` next to a project file; `packages/`
/// only when it holds restored NuGet packages (a JavaScript monorepo's
/// `packages/` is its own code).
const DOTNET_ALWAYS_DIRS: &[&str] = &[".vs", ".nuget", "testresults"];
/// Whether the directory `name` (lower-cased) at `path` is .NET build output,
/// IDE state or restored NuGet packages.
fn is_dotnet_build_dir(name: &str, path: &Path) -> bool {
if DOTNET_ALWAYS_DIRS.contains(&name) {
return true;
}
let beside_project = || {
path.parent().is_some_and(|parent| {
std::fs::read_dir(parent).is_ok_and(|entries| {
entries.filter_map(Result::ok).any(|e| {
let file = e.file_name().to_string_lossy().to_string();
crate::pipeline::dotnet::is_project_file(&file)
|| file.to_ascii_lowercase().ends_with(".sln")
})
})
})
};
match name {
"bin" | "obj" => beside_project(),
"packages" => {
path.join("repositories.config").is_file()
|| std::fs::read_dir(path).is_ok_and(|entries| {
entries.filter_map(Result::ok).any(|e| {
e.file_type().is_ok_and(|t| t.is_dir())
&& crate::pipeline::sbom::is_restored_package(&e.path())
})
})
}
_ => false,
}
}
/// Whether `path` is one of ST's generated vendor folders, by ST's own
@@ -284,6 +363,43 @@ mod tests {
assert!(vendor_dirs(&t.0).is_empty());
}
#[test]
fn mobile_and_unity_build_output_is_left_out() {
let t = Tree::new(&[
"app/build/intermediates",
"app/src/main/java",
".gradle/8.0",
"ios/Pods/AFNetworking",
"game/Library/PackageCache",
"game/Temp",
"game/Assets/Plugins/Firebase",
"game/Assets/Scripts",
"game/ProjectSettings",
])
.with_files(&["app/build.gradle", "ios/Podfile"]);
assert_eq!(
vendor_dirs(&t.0),
[
".gradle",
"app/build",
"game/Assets/Plugins",
"game/Library",
"game/Temp",
"ios/Pods",
]
);
}
#[test]
fn a_build_or_plugins_folder_outside_those_projects_is_the_customers() {
let t = Tree::new(&[
"tools/build/scripts",
"src/plugins/export",
"Assets/Plugins/x",
]);
assert!(vendor_dirs(&t.0).is_empty());
}
#[test]
fn a_customers_own_drivers_folder_is_kept() {
// No generated Core/ beside it: these are the customer's drivers.
@@ -314,4 +430,38 @@ mod tests {
]
);
}
#[test]
fn dotnet_build_output_and_restored_packages_are_not_own_code() {
let t = Tree::new(&[
"Plant/Hmi/bin/Debug",
"Plant/Hmi/obj/Debug",
"Plant/.vs/Plant/v17",
"Plant/TestResults/run1",
// A JavaScript monorepo's packages/ (even with compiled lib/) and
// a script bin/ are own code.
"web/packages/widgets/src",
"web/packages/widgets/lib",
"tools/bin",
])
.with_files(&[
"Plant/Plant.sln",
"Plant/Hmi/Hmi.csproj",
"Plant/packages/Newtonsoft.Json.12.0.1/Newtonsoft.Json.12.0.1.nupkg",
"web/packages/widgets/package.json",
"web/packages/widgets/lib/index.js",
"web/package.json",
"tools/bin/deploy.sh",
]);
assert_eq!(
vendor_dirs(&t.0),
[
"Plant/.vs",
"Plant/Hmi/bin",
"Plant/Hmi/obj",
"Plant/TestResults",
"Plant/packages"
]
);
}
}
+34 -3
View File
@@ -65,6 +65,29 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError>
.await
.map_err(|e| AgentError::Scheduler(format!("Failed to add CVE monitor job: {e}")))?;
// Managed git sync (#439): the organisation's repositories against the
// targets, a safety net for lost webhook deliveries.
let sync_agent = agent.clone();
let sync_job = Job::new_repeated_async(agent.git_source.sync_interval, move |_uuid, _lock| {
let agent = sync_agent.clone();
Box::pin(async move {
for tenant_id in scheduler_tenants(&agent).await {
match crate::git_source::sync_tenant(&agent, &tenant_id).await {
Ok(Some(report)) => {
tracing::info!(tenant_id, ?report, "managed git sync done");
}
Ok(None) => {}
Err(e) => tracing::warn!(tenant_id, "managed git sync failed: {e}"),
}
}
})
})
.map_err(|e| AgentError::Scheduler(format!("Failed to create git sync job: {e}")))?;
sched
.add(sync_job)
.await
.map_err(|e| AgentError::Scheduler(format!("Failed to add git sync job: {e}")))?;
sched
.start()
.await
@@ -102,7 +125,7 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError>
///
/// We never panic out of this function — the scheduler must keep
/// firing even if the registry is offline.
async fn scheduler_tenants(agent: &ComplianceAgent) -> Vec<String> {
pub(crate) async fn scheduler_tenants(agent: &ComplianceAgent) -> Vec<String> {
if let Some(registry) = agent.registry.as_ref() {
match registry.list_tenants().await {
Ok(rows) => {
@@ -161,7 +184,13 @@ async fn scan_all_repos(agent: &ComplianceAgent, tenant_id: &str) {
None => return,
};
let cursor = match db.onboarded_targets().find(doc! {}).await {
// Archived targets (their managed repository was deleted) keep their
// findings but are not scanned any more.
let cursor = match db
.onboarded_targets()
.find(doc! { "archived_at": null })
.await
{
Ok(c) => c,
Err(e) => {
tracing::error!("Failed to list targets for tenant '{tenant_id}': {e}");
@@ -253,8 +282,10 @@ async fn monitor_cves(agent: &ComplianceAgent, tenant_id: &str) {
};
// Scan dependencies for CVEs
// The periodic monitor only refreshes alerts; a scan records which
// components could not be checked.
let alerts = match scanner.scan_dependencies(&repo_id, &mut repo_entries).await {
Ok(a) => a,
Ok(lookup) => lookup.alerts,
Err(e) => {
tracing::warn!("CVE monitor: scan failed for {repo_name}: {e}");
continue;
+387 -23
View File
@@ -1,3 +1,5 @@
use std::collections::HashMap;
use compliance_core::error::CoreError;
use compliance_core::guarded_net::guarded_client_builder;
use compliance_core::models::{TrackerIssue, TrackerType};
@@ -35,42 +37,162 @@ impl GiteaTracker {
fn api_url(&self, path: &str) -> String {
format!("{}/api/v1{}", self.base_url, path)
}
}
impl IssueTracker for GiteaTracker {
fn name(&self) -> &str {
"gitea"
fn auth(&self) -> String {
format!("token {}", self.token.expose_secret())
}
async fn create_issue(
/// Every label of a repository, all pages.
///
/// # Errors
///
/// [`CoreError::IssueTracker`] if Gitea cannot be asked or answers with an
/// error.
pub async fn list_labels(&self, owner: &str, repo: &str) -> Result<Vec<GiteaLabel>, CoreError> {
let mut labels = Vec::new();
for page in 1..=MAX_LABEL_PAGES {
let url = self.api_url(&format!(
"/repos/{owner}/{repo}/labels?page={page}&limit={LABEL_PAGE_SIZE}"
));
let resp = self
.http
.get(&url)
.header("Authorization", self.auth())
.send()
.await
.map_err(|e| CoreError::IssueTracker(format!("Gitea list labels failed: {e}")))?;
if !resp.status().is_success() {
let status = resp.status();
return Err(CoreError::IssueTracker(format!(
"Gitea list labels returned {status}"
)));
}
let batch: Vec<GiteaLabel> = resp.json().await.map_err(|e| {
CoreError::IssueTracker(format!("Failed to parse Gitea labels: {e}"))
})?;
// Only an empty page ends the list (the instance may cap the
// page size below ours).
if batch.is_empty() {
break;
}
labels.extend(batch);
}
Ok(labels)
}
/// 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.
///
/// # Errors
///
/// [`CoreError::IssueTracker`] if the labels cannot be listed or a missing
/// one cannot be created.
pub async fn ensure_labels(
&self,
owner: &str,
repo: &str,
wanted: &[LabelSpec],
) -> Result<HashMap<String, i64>, CoreError> {
let existing = self.list_labels(owner, repo).await?;
let mut ids: HashMap<String, i64> =
existing.iter().map(|l| (l.name.clone(), l.id)).collect();
for spec in missing_labels(&existing, wanted) {
let url = self.api_url(&format!("/repos/{owner}/{repo}/labels"));
let resp = self
.http
.post(&url)
.header("Authorization", self.auth())
.json(&serde_json::json!({
"name": spec.name,
"color": spec.color,
"description": spec.description,
}))
.send()
.await
.map_err(|e| CoreError::IssueTracker(format!("Gitea create label failed: {e}")))?;
if !resp.status().is_success() {
let status = resp.status();
return Err(CoreError::IssueTracker(format!(
"Gitea create label '{}' returned {status}",
spec.name
)));
}
let label: GiteaLabel = resp.json().await.map_err(|e| {
CoreError::IssueTracker(format!("Failed to parse Gitea label: {e}"))
})?;
ids.insert(label.name, label.id);
}
Ok(ids)
}
/// Attach the labels `label_ids` to the existing issue `external_id`.
///
/// # Errors
///
/// [`CoreError::IssueTracker`] if Gitea cannot be reached or refuses.
pub async fn add_labels(
&self,
owner: &str,
repo: &str,
external_id: &str,
label_ids: &[i64],
) -> Result<(), CoreError> {
let url = self.api_url(&format!(
"/repos/{owner}/{repo}/issues/{external_id}/labels"
));
let resp = self
.http
.post(&url)
.header("Authorization", self.auth())
.json(&serde_json::json!({ "labels": label_ids }))
.send()
.await
.map_err(|e| CoreError::IssueTracker(format!("Gitea add labels failed: {e}")))?;
if !resp.status().is_success() {
return Err(CoreError::IssueTracker(format!(
"Gitea add labels returned {}",
resp.status()
)));
}
Ok(())
}
/// Create an issue with the given labels attached by id (see
/// [`Self::ensure_labels`]).
///
/// # Errors
///
/// [`CoreError::IssueTracker`] if Gitea refuses the issue.
pub async fn create_issue_with_label_ids(
&self,
owner: &str,
repo: &str,
title: &str,
body: &str,
labels: &[String],
label_ids: &[i64],
) -> Result<TrackerIssue, CoreError> {
self.post_issue(
owner,
repo,
title,
serde_json::json!({ "title": title, "body": body, "labels": label_ids }),
)
.await
}
async fn post_issue(
&self,
owner: &str,
repo: &str,
title: &str,
payload: serde_json::Value,
) -> Result<TrackerIssue, CoreError> {
let url = self.api_url(&format!("/repos/{owner}/{repo}/issues"));
// Gitea expects label IDs (integers), not names. Append label names
// to the body instead since resolving IDs would require extra API calls.
let mut full_body = body.to_string();
if !labels.is_empty() {
full_body.push_str("\n\n**Labels:** ");
full_body.push_str(&labels.join(", "));
}
let payload = serde_json::json!({
"title": title,
"body": full_body,
});
let resp = self
.http
.post(&url)
.header(
"Authorization",
format!("token {}", self.token.expose_secret()),
)
.header("Authorization", self.auth())
.json(&payload)
.send()
.await
@@ -97,6 +219,133 @@ impl IssueTracker for GiteaTracker {
title.to_string(),
))
}
}
/// Labels per page when listing a repository's labels.
const LABEL_PAGE_SIZE: usize = 50;
/// Upper bound on label pages, so a misbehaving server cannot loop us.
const MAX_LABEL_PAGES: usize = 20;
/// A repository label as Gitea returns it.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
pub struct GiteaLabel {
pub id: i64,
pub name: String,
}
/// A label Prüfwerk puts on the issues it opens in a managed repository.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LabelSpec {
pub name: String,
/// `#rrggbb`.
pub color: String,
pub description: String,
}
impl LabelSpec {
fn new(name: &str, color: &str, description: &str) -> Self {
Self {
name: name.to_string(),
color: color.to_string(),
description: description.to_string(),
}
}
}
/// The label every Prüfwerk issue in a managed repository carries.
pub const LABEL_PRUEFWERK: &str = "pruefwerk";
/// The CRA label: the essential cybersecurity requirements of Annex I.
pub const LABEL_CRA_ANNEX_I: &str = "cra:annex-i";
/// The labels of a managed repository (#439): `pruefwerk`, `cra:annex-i` and
/// one `severity:*` per severity that gets an issue.
/// The label of an issue about a known vulnerability in a dependency.
pub const LABEL_CVE: &str = "cve";
/// The label of an issue whose finding is an accepted risk (closed in
/// Prüfwerk with a reason, not fixed).
pub const LABEL_ACCEPTED_RISK: &str = "risk:accepted";
pub fn pruefwerk_labels() -> Vec<LabelSpec> {
vec![
LabelSpec::new(
LABEL_PRUEFWERK,
"#1f6feb",
"Befund aus Prüfwerk / Prüfwerk finding",
),
LabelSpec::new(
LABEL_CRA_ANNEX_I,
"#6e40c9",
"CRA Anhang I, wesentliche Cybersicherheitsanforderungen / CRA Annex I",
),
LabelSpec::new(
"severity:critical",
"#b60205",
"Schweregrad kritisch / critical",
),
LabelSpec::new("severity:high", "#d93f0b", "Schweregrad hoch / high"),
LabelSpec::new("severity:medium", "#fbca04", "Schweregrad mittel / medium"),
LabelSpec::new("severity:low", "#0e8a16", "Schweregrad niedrig / low"),
LabelSpec::new(
LABEL_CVE,
"#d73a4a",
"Bekannte Schwachstelle in einer Abhängigkeit / known vulnerability in a dependency",
),
LabelSpec::new(
LABEL_ACCEPTED_RISK,
"#5319e7",
"Risiko akzeptiert, nicht behoben / accepted risk, not fixed",
),
]
}
/// The labels of `wanted` that `existing` does not have (by exact name).
pub fn missing_labels<'a>(existing: &[GiteaLabel], wanted: &'a [LabelSpec]) -> Vec<&'a LabelSpec> {
wanted
.iter()
.filter(|w| !existing.iter().any(|e| e.name == w.name))
.collect()
}
/// The label names for an issue about a finding of `severity` (`info` has no
/// severity label).
pub fn issue_label_names(severity: &str) -> Vec<String> {
let mut names = vec![LABEL_PRUEFWERK.to_string(), LABEL_CRA_ANNEX_I.to_string()];
if matches!(severity, "critical" | "high" | "medium" | "low") {
names.push(format!("severity:{severity}"));
}
names
}
impl IssueTracker for GiteaTracker {
fn name(&self) -> &str {
"gitea"
}
async fn create_issue(
&self,
owner: &str,
repo: &str,
title: &str,
body: &str,
labels: &[String],
) -> Result<TrackerIssue, CoreError> {
// Gitea expects label IDs (integers), not names. A tracker the user
// configured gets the names in the body; a managed repository has its
// labels ensured and attached by id (`create_issue_with_label_ids`).
let mut full_body = body.to_string();
if !labels.is_empty() {
full_body.push_str("\n\n**Labels:** ");
full_body.push_str(&labels.join(", "));
}
self.post_issue(
owner,
repo,
title,
serde_json::json!({ "title": title, "body": full_body }),
)
.await
}
async fn update_issue_status(
&self,
@@ -286,3 +535,118 @@ impl IssueTracker for GiteaTracker {
}
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use std::sync::{Arc, Mutex};
use axum::extract::{Path, State};
use axum::routing::get;
use axum::{Json, Router};
use super::*;
#[test]
fn missing_labels_by_exact_name() {
let existing = vec![
GiteaLabel {
id: 1,
name: "pruefwerk".into(),
},
GiteaLabel {
id: 2,
name: "Severity:High".into(),
},
];
let wanted = pruefwerk_labels();
let missing: Vec<&str> = missing_labels(&existing, &wanted)
.iter()
.map(|l| l.name.as_str())
.collect();
assert_eq!(
missing,
[
"cra:annex-i",
"severity:critical",
"severity:high",
"severity:medium",
"severity:low",
"cve",
"risk:accepted"
]
);
assert!(wanted
.iter()
.all(|l| l.color.len() == 7 && l.color.starts_with('#')));
}
#[test]
fn issue_labels_per_severity() {
assert_eq!(
issue_label_names("critical"),
["pruefwerk", "cra:annex-i", "severity:critical"]
);
assert_eq!(issue_label_names("info"), ["pruefwerk", "cra:annex-i"]);
}
type Labels = Arc<Mutex<Vec<(i64, String)>>>;
/// A fake Gitea holding the labels of one repository.
async fn fake_gitea(labels: Labels) -> String {
async fn list(
State(labels): State<Labels>,
Path((_o, _r)): Path<(String, String)>,
) -> Json<serde_json::Value> {
let all = labels.lock().unwrap().clone();
Json(serde_json::json!(all
.iter()
.map(|(id, name)| serde_json::json!({ "id": id, "name": name, "color": "ffffff" }))
.collect::<Vec<_>>()))
}
async fn create(
State(labels): State<Labels>,
Path((_o, _r)): Path<(String, String)>,
Json(body): Json<serde_json::Value>,
) -> (axum::http::StatusCode, Json<serde_json::Value>) {
let mut all = labels.lock().unwrap();
let id = 100 + all.len() as i64;
let name = body["name"].as_str().unwrap().to_string();
assert!(body["color"].as_str().unwrap().starts_with('#'));
all.push((id, name.clone()));
(
axum::http::StatusCode::CREATED,
Json(serde_json::json!({ "id": id, "name": name })),
)
}
let app = Router::new()
.route(
"/api/v1/repos/{owner}/{repo}/labels",
get(list).post(create),
)
.with_state(labels);
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 ensure_labels_creates_only_the_missing_ones_once() {
let labels: Labels = Arc::new(Mutex::new(vec![(7, "pruefwerk".to_string())]));
let base = fake_gitea(labels.clone()).await;
let tracker =
GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap();
let wanted = pruefwerk_labels();
let ids = tracker.ensure_labels("kunde", "fw", &wanted).await.unwrap();
assert_eq!(ids.len(), 8);
assert_eq!(ids["pruefwerk"], 7);
assert_eq!(labels.lock().unwrap().len(), 8);
// A second run finds them all and creates nothing.
let again = tracker.ensure_labels("kunde", "fw", &wanted).await.unwrap();
assert_eq!(again, ids);
assert_eq!(labels.lock().unwrap().len(), 8);
}
}
+1 -1
View File
@@ -135,7 +135,7 @@ async fn handle_pull_request(
StatusCode::OK
}
fn verify_signature(secret: &str, body: &[u8], signature: &str) -> bool {
pub(crate) fn verify_signature(secret: &str, body: &[u8], signature: &str) -> bool {
// Gitea sends raw hex (no sha256= prefix)
let sig_bytes = match hex::decode(signature) {
Ok(b) => b,
@@ -0,0 +1,133 @@
//! `POST /webhook/{tenant_id}/gitea-source` — the system/org webhook of a
//! tenant's managed Gitea (#439).
//!
//! Authenticated by `X-Gitea-Signature`: HMAC-SHA256 of the body under the
//! source's webhook secret. Until that is verified nothing is created: the
//! source is read through a handle that cannot conjure a tenant database.
use std::sync::Arc;
use axum::body::Bytes;
use axum::extract::{Extension, Path};
use axum::http::{HeaderMap, StatusCode};
use crate::agent::ComplianceAgent;
use crate::git_source::{self, events};
pub async fn handle_gitea_source_webhook(
Extension(agent): Extension<Arc<ComplianceAgent>>,
Path(tenant_id): Path<String>,
headers: HeaderMap,
body: Bytes,
) -> StatusCode {
let probe = agent.db_pool.for_existing_tenant_id(&tenant_id);
let source = match git_source::load_source(&probe).await {
Ok(Some(source)) if source.enabled => source,
Ok(_) => {
tracing::warn!("Gitea source webhook: no enabled git source in tenant '{tenant_id}'");
return StatusCode::NOT_FOUND;
}
Err(e) => {
tracing::error!("Gitea source webhook: reading the git source failed: {e}");
return StatusCode::INTERNAL_SERVER_ERROR;
}
};
// Fail closed: a source whose secret cannot be opened accepts nothing.
let Some(secret) = agent
.secrets
.open_opt(source.webhook_secret.as_ref(), "git source webhook secret")
else {
tracing::warn!(
"Gitea source webhook: tenant '{tenant_id}' has no webhook secret; rejected"
);
return StatusCode::UNAUTHORIZED;
};
let signature = header(&headers, "x-gitea-signature");
if !super::gitea::verify_signature(&secret, &body, signature) {
tracing::warn!("Gitea source webhook: invalid signature for tenant '{tenant_id}'");
return StatusCode::UNAUTHORIZED;
}
let event = header(&headers, "x-gitea-event");
let payload: serde_json::Value = match serde_json::from_slice(&body) {
Ok(v) => v,
Err(e) => {
tracing::warn!("Gitea source webhook: invalid JSON: {e}");
return StatusCode::BAD_REQUEST;
}
};
let action = events::route_event(event, &payload, &source.org);
if let events::SourceAction::Ignore(why) = action {
tracing::debug!(tenant_id, event, "Gitea source webhook ignored: {why}");
return StatusCode::OK;
}
// Automated work follows the same entitlement and ladder rules as the
// scheduler. Refused visibly, so the delivery log in Gitea shows it.
if let Err(why) = git_source::automation_allowed(&agent, &tenant_id).await {
tracing::info!(tenant_id, "Gitea source webhook refused: {why}");
return StatusCode::FORBIDDEN;
}
let db = match agent.db_pool.for_tenant_id(&tenant_id).await {
Ok(db) => db,
Err(e) => {
tracing::error!("Gitea source webhook: tenant database: {e}");
return StatusCode::INTERNAL_SERVER_ERROR;
}
};
match git_source::apply_action(&agent, &db, &tenant_id, &source, action).await {
Ok(outcome) => {
tracing::info!(tenant_id, event, ?outcome, "Gitea source webhook handled");
StatusCode::OK
}
Err(e) => {
tracing::error!(tenant_id, event, "Gitea source webhook failed: {e}");
StatusCode::INTERNAL_SERVER_ERROR
}
}
}
fn header<'a>(headers: &'a HeaderMap, name: &str) -> &'a str {
headers
.get(name)
.and_then(|v| v.to_str().ok())
.unwrap_or("")
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use hmac::{Hmac, Mac};
use sha2::Sha256;
use crate::webhooks::gitea::verify_signature;
fn sign(secret: &str, body: &[u8]) -> String {
let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).unwrap();
mac.update(body);
hex::encode(mac.finalize().into_bytes())
}
#[test]
fn signature_valid_invalid_missing() {
let body = br#"{"action":"created"}"#;
let good = sign("s3cret", body);
assert!(verify_signature("s3cret", body, &good));
// another secret, another body, a tampered or non-hex signature
assert!(!verify_signature("other", body, &good));
assert!(!verify_signature(
"s3cret",
br#"{"action":"deleted"}"#,
&good
));
let mut tampered = good.clone();
tampered.replace_range(0..1, if good.starts_with('0') { "1" } else { "0" });
assert!(!verify_signature("s3cret", body, &tampered));
assert!(!verify_signature("s3cret", body, "zz"));
// GitHub-style prefix is not Gitea's format
assert!(!verify_signature("s3cret", body, &format!("sha256={good}")));
// missing header
assert!(!verify_signature("s3cret", body, ""));
}
}
+1
View File
@@ -1,4 +1,5 @@
pub mod gitea;
pub mod gitea_source;
pub mod github;
pub mod gitlab;
pub mod server;
+7 -1
View File
@@ -7,7 +7,7 @@ use compliance_core::shutdown::{self, Shutdown};
use crate::agent::ComplianceAgent;
use crate::error::AgentError;
use crate::webhooks::{gitea, github, gitlab};
use crate::webhooks::{gitea, gitea_source, github, gitlab};
/// Serve the webhook receivers on `agent.config.webhook_port` until `shutdown`
/// fires, then drain in-flight deliveries for at most
@@ -38,6 +38,12 @@ pub async fn start_webhook_server(
"/webhook/{tenant_id}/gitea/{repo_id}",
post(gitea::handle_gitea_webhook),
)
// The managed git source's system/org webhook (#439): one per tenant,
// HMAC-verified with the source's secret.
.route(
"/webhook/{tenant_id}/gitea-source",
post(gitea_source::handle_gitea_source_webhook),
)
.layer(Extension(Arc::new(agent.clone())));
let addr = format!("0.0.0.0:{}", agent.config.webhook_port);
+1 -1
View File
@@ -279,7 +279,7 @@ fn bson_dt(dt: DateTime<Utc>) -> BsonDateTime {
/// Whether a Mongo error is a duplicate-key (E11000) violation — a job with this
/// id is already enqueued.
fn is_duplicate_key(e: &mongodb::error::Error) -> bool {
pub(crate) fn is_duplicate_key(e: &mongodb::error::Error) -> bool {
match &*e.kind {
ErrorKind::Write(WriteFailure::WriteError(we)) => we.code == 11000,
_ => false,
+400
View File
@@ -0,0 +1,400 @@
//! Managed git source (#439) against a live Mongo: the platform API stores the
//! source sealed and hands out the webhook secret once, the org webhook is
//! HMAC-checked and creates exactly one target per repository however often
//! (or concurrently) it is delivered, deletion archives, and the sync diffs a
//! mocked Gitea listing. Skips cleanly when no Mongo is reachable.
//!
//! Every repository here is empty, so no scan (and no clone) is started.
#![allow(clippy::expect_used, clippy::unwrap_used)]
mod common;
use std::sync::Arc;
use axum::routing::{get, post};
use axum::{Extension, Router};
use hmac::{Hmac, Mac};
use mongodb::bson::doc;
use sha2::Sha256;
use compliance_agent::agent::ComplianceAgent;
use compliance_agent::api::handlers::platform::{self, PlatformState};
use compliance_agent::database::{Database, DatabasePool};
use compliance_agent::error::AgentError;
use compliance_agent::git_source::gitea::{GiteaRepo, RepoLister};
use compliance_agent::webhooks::gitea_source::handle_gitea_source_webhook;
use common::dev_config;
const TENANT: &str = "gitsrc";
struct Harness {
base_url: String,
client: reqwest::Client,
pool: DatabasePool,
db: Database,
agent: Arc<ComplianceAgent>,
}
async fn start() -> Option<Harness> {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db_name = format!("gs_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]);
let Ok(pool) = DatabasePool::connect(&uri, &db_name).await else {
eprintln!("SKIP git_source: no MongoDB reachable at {uri}");
return None;
};
let db = pool.for_tenant_id(TENANT).await.expect("tenant db");
let agent = Arc::new(ComplianceAgent::new(dev_config(uri, db_name), pool.clone()));
let state = PlatformState {
agent: agent.clone(),
jwks: None,
};
let app = Router::new()
.route(
"/api/v1/platform/tenants/{id}/git-source",
get(platform::get_git_source)
.put(platform::put_git_source)
.delete(platform::delete_git_source),
)
.with_state(state)
.route(
"/webhook/{tenant_id}/gitea-source",
post(handle_gitea_source_webhook),
)
.layer(Extension(agent.clone()));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move {
axum::serve(listener, app).await.ok();
});
Some(Harness {
base_url: format!("http://127.0.0.1:{port}"),
client: reqwest::Client::new(),
pool,
db,
agent,
})
}
fn sign(secret: &str, body: &[u8]) -> String {
let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).unwrap();
mac.update(body);
hex::encode(mac.finalize().into_bytes())
}
fn repo_json(id: i64, owner: &str, name: &str) -> serde_json::Value {
serde_json::json!({
"id": id, "name": name, "full_name": format!("{owner}/{name}"),
"owner": { "login": owner }, "default_branch": "main", "empty": true,
})
}
impl Harness {
async fn put_source(&self, body: serde_json::Value) -> (u16, serde_json::Value) {
let resp = self
.client
.put(format!(
"{}/api/v1/platform/tenants/{TENANT}/git-source",
self.base_url
))
.json(&body)
.send()
.await
.unwrap();
let status = resp.status().as_u16();
(status, resp.json().await.unwrap_or_default())
}
async fn deliver(
&self,
tenant: &str,
event: &str,
body: &serde_json::Value,
sig: Option<String>,
) -> u16 {
let bytes = serde_json::to_vec(body).unwrap();
let mut req = self
.client
.post(format!("{}/webhook/{tenant}/gitea-source", self.base_url))
.header("X-Gitea-Event", event)
.header("Content-Type", "application/json");
if let Some(sig) = sig {
req = req.header("X-Gitea-Signature", sig);
}
req.body(bytes).send().await.unwrap().status().as_u16()
}
async fn managed_count(&self, repo_id: i64) -> u64 {
self.db
.onboarded_targets()
.count_documents(doc! { "source_repo.repo_id": repo_id })
.await
.unwrap()
}
}
#[tokio::test]
async fn platform_api_webhook_and_sync() {
let Some(h) = start().await else { return };
// ── platform API ────────────────────────────────────────────────────
let (status, body) = h
.put_source(serde_json::json!({
"base_url": "https://evil.example.com", "org": "kunde", "bot_token": "t"
}))
.await;
assert_eq!(status, 400, "{body}");
let (status, _) = h
.put_source(serde_json::json!({
"base_url": "https://kunde.code.breakpilot.com", "org": "kunde"
}))
.await;
assert_eq!(status, 400, "a first PUT needs the bot token");
// Disabled first, so the PUT's own sync does not reach out to the host.
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}");
let secret = created["webhook_secret"].as_str().unwrap().to_string();
assert_eq!(secret.len(), 64);
assert_eq!(created["webhook_url"], "/webhook/gitsrc/gitea-source");
assert_eq!(created["base_url"], "https://kunde.code.breakpilot.com");
assert!(!created.to_string().contains("bot-pat"));
let stored =
h.db.raw_collection("git_sources")
.find_one(doc! {})
.await
.unwrap()
.unwrap();
assert!(stored.get_str("bot_token").unwrap().starts_with("enc:v1:"));
let sealed_secret = stored.get_str("webhook_secret").unwrap().to_string();
assert!(sealed_secret.starts_with("enc:v1:"));
// A retried PUT keeps the secret (and does not show it again).
let (status, again) = h
.put_source(serde_json::json!({
"base_url": "https://kunde.code.breakpilot.com", "org": "kunde", "enabled": false
}))
.await;
assert_eq!(status, 200);
assert!(again["webhook_secret"].is_null());
let stored =
h.db.raw_collection("git_sources")
.find_one(doc! {})
.await
.unwrap()
.unwrap();
assert_eq!(stored.get_str("webhook_secret").unwrap(), sealed_secret);
let got: serde_json::Value = h
.client
.get(format!(
"{}/api/v1/platform/tenants/{TENANT}/git-source",
h.base_url
))
.send()
.await
.unwrap()
.json()
.await
.unwrap();
assert_eq!(got["has_bot_token"], true);
assert!(got["webhook_secret"].is_null());
assert!(!got.to_string().contains("enc:v1"));
// ── webhook ─────────────────────────────────────────────────────────
let created_evt =
serde_json::json!({ "action": "created", "repository": repo_json(11, "kunde", "fw") });
let body = serde_json::to_vec(&created_evt).unwrap();
// disabled source: not there
assert_eq!(
h.deliver(
TENANT,
"repository",
&created_evt,
Some(sign(&secret, &body))
)
.await,
404
);
h.db.git_sources()
.update_one(doc! {}, doc! { "$set": { "enabled": true } })
.await
.unwrap();
assert_eq!(
h.deliver(TENANT, "repository", &created_evt, None).await,
401
);
assert_eq!(
h.deliver(
TENANT,
"repository",
&created_evt,
Some(sign("wrong", &body))
)
.await,
401
);
assert_eq!(
h.deliver(
"no-such-tenant",
"repository",
&created_evt,
Some(sign(&secret, &body))
)
.await,
404
);
assert_eq!(h.managed_count(11).await, 0);
// Twice at once and once more: one target.
let sig = sign(&secret, &body);
let (a, b) = tokio::join!(
h.deliver(TENANT, "repository", &created_evt, Some(sig.clone())),
h.deliver(TENANT, "repository", &created_evt, Some(sig.clone())),
);
assert_eq!((a, b), (200, 200));
assert_eq!(
h.deliver(TENANT, "repository", &created_evt, Some(sig))
.await,
200
);
assert_eq!(h.managed_count(11).await, 1);
let target =
h.db.onboarded_targets()
.find_one(doc! { "source_repo.repo_id": 11_i64 })
.await
.unwrap()
.unwrap();
assert_eq!(target.name, "kunde/fw");
assert_eq!(
target.code_artifact().unwrap().source_ref,
"https://kunde.code.breakpilot.com/kunde/fw.git"
);
assert!(target.classification.is_some(), "detection ran");
// Another organisation's repository is ignored.
let other =
serde_json::json!({ "action": "created", "repository": repo_json(12, "andere", "x") });
let ob = serde_json::to_vec(&other).unwrap();
assert_eq!(
h.deliver(TENANT, "repository", &other, Some(sign(&secret, &ob)))
.await,
200
);
assert_eq!(h.managed_count(12).await, 0);
// Deleted: archived, not removed.
let deleted =
serde_json::json!({ "action": "deleted", "repository": repo_json(11, "kunde", "fw") });
let db_ = serde_json::to_vec(&deleted).unwrap();
assert_eq!(
h.deliver(TENANT, "repository", &deleted, Some(sign(&secret, &db_)))
.await,
200
);
let target =
h.db.onboarded_targets()
.find_one(doc! { "source_repo.repo_id": 11_i64 })
.await
.unwrap()
.unwrap();
assert!(target.archived_at.is_some());
// ── sync against a mocked listing ───────────────────────────────────
struct Listing(Vec<GiteaRepo>);
impl RepoLister for Listing {
async fn list_org_repos(&self, _org: &str) -> Result<Vec<GiteaRepo>, AgentError> {
Ok(self.0.clone())
}
}
let repo =
|id, name| serde_json::from_value::<GiteaRepo>(repo_json(id, "kunde", name)).unwrap();
let source = compliance_agent::git_source::load_source(&h.db)
.await
.unwrap()
.unwrap();
// fw (11) is back, docs (13) is new.
let listing = Listing(vec![repo(11, "fw"), repo(13, "docs")]);
let report =
compliance_agent::git_source::sync_with(&h.agent, &h.db, TENANT, &source, &listing)
.await
.unwrap();
assert_eq!(
(report.created, report.refreshed, report.archived),
(1, 1, 0)
);
// docs gone again: archived; a second identical sync changes nothing.
let listing = Listing(vec![repo(11, "fw")]);
let report =
compliance_agent::git_source::sync_with(&h.agent, &h.db, TENANT, &source, &listing)
.await
.unwrap();
assert_eq!(
(report.created, report.refreshed, report.archived),
(0, 0, 1)
);
let report =
compliance_agent::git_source::sync_with(&h.agent, &h.db, TENANT, &source, &listing)
.await
.unwrap();
assert_eq!(
(report.created, report.refreshed, report.archived),
(0, 0, 0)
);
assert_eq!(h.managed_count(11).await + h.managed_count(13).await, 2);
// ── a new bot token reaches the managed targets ─────────────────────
let (status, _) = h
.put_source(serde_json::json!({
"base_url": "https://kunde.code.breakpilot.com", "org": "kunde",
"bot_token": "bot-pat-2", "enabled": false
}))
.await;
assert_eq!(status, 200);
let target =
h.db.onboarded_targets()
.find_one(doc! { "source_repo.repo_id": 11_i64 })
.await
.unwrap()
.unwrap();
let tracker_token = target.scan_config.issue_tracker.unwrap().token.unwrap();
let git_token = target.artifacts[0]
.auth
.as_ref()
.unwrap()
.secret
.clone()
.unwrap();
assert_eq!(h.agent.secrets.open(&tracker_token).unwrap(), "bot-pat-2");
assert_eq!(h.agent.secrets.open(&git_token).unwrap(), "bot-pat-2");
// ── delete: the source goes, its targets are archived ───────────────
let resp: serde_json::Value = h
.client
.delete(format!(
"{}/api/v1/platform/tenants/{TENANT}/git-source",
h.base_url
))
.send()
.await
.unwrap()
.json()
.await
.unwrap();
assert_eq!(resp["targets_archived"], 1);
assert!(compliance_agent::git_source::load_source(&h.db)
.await
.unwrap()
.is_none());
h.pool.drop_tenant(TENANT).await.ok();
}
+158
View File
@@ -0,0 +1,158 @@
//! MCP server cards per tenant (#432): one tenant's cards are invisible and
//! untouchable for another, every tenant gets the default cards once, and a
//! read-only role sees no access tokens. Runs against a live Mongo and skips
//! cleanly without one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
mod common;
use std::sync::Arc;
use axum::extract::{Extension, Path, Query};
use axum::http::StatusCode;
use axum::Json;
use compliance_agent::agent::ComplianceAgent;
use compliance_agent::api::handlers::mcp_servers::{
create_mcp_server, delete_mcp_server, list_mcp_servers, regenerate_mcp_server_token,
CreateRequest, ListQuery,
};
use compliance_agent::database::DatabasePool;
use compliance_core::tenant_ctx::TenantCtx;
use compliance_core::{OrgRole, TenantContext, TenantStatus};
use common::dev_config;
fn tenant(id: &str, role: OrgRole) -> TenantCtx {
TenantCtx(TenantContext {
tenant_id: id.to_string(),
tenant_slug: id.to_string(),
org_roles: vec![role],
products: vec!["compliance-scanner".to_string()],
plan: "starter".to_string(),
status: TenantStatus::Active,
user_id: "u-1".to_string(),
user_name: None,
staff: None,
})
}
async fn names(agent: &Arc<ComplianceAgent>, who: TenantCtx) -> Vec<(String, String, String)> {
let Json(body) = list_mcp_servers(
Extension(agent.clone()),
who,
Query(ListQuery {
default_endpoint: Some("https://pruefwerk.example".into()),
}),
)
.await
.unwrap();
body["data"]
.as_array()
.unwrap()
.iter()
.map(|s| {
(
s["name"].as_str().unwrap().to_string(),
s["_id"]["$oid"].as_str().unwrap_or_default().to_string(),
s["access_token"].as_str().unwrap_or_default().to_string(),
)
})
.collect()
}
#[tokio::test]
async fn mcp_server_cards_are_per_tenant() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db_name = format!("mcps_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
let Ok(pool) = DatabasePool::connect(&uri, &db_name).await else {
eprintln!("SKIP mcp_servers: no MongoDB reachable at {uri}");
return;
};
let agent = Arc::new(ComplianceAgent::new(dev_config(uri, db_name), pool.clone()));
let (a, b) = ("tenant-a", "tenant-b");
// Every tenant starts with the three default cards, once.
let first = names(&agent, tenant(a, OrgRole::ItAdmin)).await;
assert_eq!(first.len(), 3);
assert_eq!(names(&agent, tenant(a, OrgRole::ItAdmin)).await.len(), 3);
// Tenant A adds a card.
let _created = create_mcp_server(
Extension(agent.clone()),
tenant(a, OrgRole::ItAdmin),
Json(CreateRequest {
name: "A's own".into(),
endpoint_url: "https://mcp.a.example/mcp".into(),
transport: "http".into(),
port: None,
description: None,
mongodb_uri: Some("mongodb://secret-a".into()),
mongodb_database: None,
}),
)
.await
.unwrap();
let a_cards = names(&agent, tenant(a, OrgRole::ItAdmin)).await;
let (_, a_id, a_token) = a_cards
.iter()
.find(|(name, _, _)| name == "A's own")
.cloned()
.expect("A sees its card");
assert!(a_token.starts_with("mcp_"));
// Tenant B sees only its own defaults, and cannot touch A's card.
let b_cards = names(&agent, tenant(b, OrgRole::ItAdmin)).await;
assert_eq!(b_cards.len(), 3);
assert!(!b_cards
.iter()
.any(|(name, id, _)| name == "A's own" || *id == a_id));
assert_eq!(
delete_mcp_server(
Extension(agent.clone()),
tenant(b, OrgRole::ItAdmin),
Path(a_id.clone())
)
.await
.unwrap_err(),
StatusCode::NOT_FOUND
);
assert_eq!(
regenerate_mcp_server_token(
Extension(agent.clone()),
tenant(b, OrgRole::ItAdmin),
Path(a_id.clone())
)
.await
.unwrap_err(),
StatusCode::NOT_FOUND
);
assert!(names(&agent, tenant(a, OrgRole::ItAdmin))
.await
.iter()
.any(|(_, id, token)| *id == a_id && *token == a_token));
// A read-only role sees the cards without their tokens.
let read_only = names(&agent, tenant(a, OrgRole::Cxo)).await;
assert_eq!(read_only.len(), 4);
assert!(read_only.iter().all(|(_, _, token)| token.is_empty()));
// A deletes its own card.
assert_eq!(
delete_mcp_server(
Extension(agent.clone()),
tenant(a, OrgRole::ItAdmin),
Path(a_id)
)
.await
.unwrap(),
StatusCode::NO_CONTENT
);
assert_eq!(names(&agent, tenant(a, OrgRole::ItAdmin)).await.len(), 3);
for t in [a, b] {
pool.drop_tenant(t).await.ok();
}
}
+7 -18
View File
@@ -17,9 +17,8 @@
//! - a blessed snapshot in `fixtures/nightly/baselines/<key>.json`:
//! - **exact**: scan status, skipped stages, SBOM components, and findings
//! from deterministic scanners (PLC rules, secrets, patterns, lint, our own
//! `cra-ai-*` semgrep rules);
//! - **at least**: CVE and advisory ids, and semgrep registry rules, whose
//! sources change daily;
//! `cra-ai-*` semgrep rules, the only ones semgrep runs);
//! - **at least**: CVE and advisory ids, whose sources change daily;
//! - **ignored**: LLM code review and triage. Control refs, which the LLM
//! control judge stamps, are reported under "advisory" but do not gate.
//!
@@ -336,8 +335,6 @@ struct Snapshot {
findings: BTreeSet<String>,
/// CVE and advisory ids; the run must contain at least these.
cves: BTreeSet<String>,
/// Semgrep registry rules; the run must contain at least these.
registry_rules: BTreeSet<String>,
}
impl Snapshot {
@@ -380,11 +377,6 @@ impl Snapshot {
out.extend(exact("SBOM component", &self.sbom, &baseline.sbom));
out.extend(exact("finding", &self.findings, &baseline.findings));
out.extend(at_least("CVE", &self.cves, &baseline.cves));
out.extend(at_least(
"registry rule",
&self.registry_rules,
&baseline.registry_rules,
));
out
}
}
@@ -465,8 +457,6 @@ async fn collect(agent: &Agent, target_id: &str, run: &Value) -> Collected {
snapshot.cves.insert(rule);
} else if scan_type == "codereview" {
// LLM output: runs, never gates.
} else if scanner == "semgrep" && !rule.starts_with("cra-ai-") {
snapshot.registry_rules.insert(rule);
} else {
let file = Path::new(&text(f, "file_path"))
.file_name()
@@ -734,26 +724,25 @@ mod unit {
skipped_stages: set(&["dast"]),
sbom: set(&["cargo:itoa@1.0.15"]),
findings: set(&["gitleaks:aws-key a.py:3"]),
cves: set(&["CVE-2020-1"]),
registry_rules: set(&["python.lang.x"]),
cves: set(&["CVE-2020-1", "GHSA-xxxx-yyyy-zzzz"]),
};
let mut run = blessed.clone();
assert!(run.diff(&blessed).is_empty());
run.sbom = set(&["cargo:itoa@1.0.16"]);
run.cves = set(&["CVE-2020-1", "CVE-2026-9"]); // a new CVE is fine
run.registry_rules = set(&[]);
// A new CVE is fine, a lost one is not.
run.cves = set(&["CVE-2020-1", "CVE-2026-9"]);
run.scan_status = "failed".into();
let diff = run.diff(&blessed);
for needle in [
"scan status failed, blessed completed",
"missing SBOM component: cargo:itoa@1.0.15",
"unexpected SBOM component: cargo:itoa@1.0.16",
"missing registry rule: python.lang.x",
"missing CVE: GHSA-xxxx-yyyy-zzzz",
] {
assert!(diff.iter().any(|d| d == needle), "{needle} not in {diff:?}");
}
assert!(!diff.iter().any(|d| d.contains("CVE")), "{diff:?}");
assert!(!diff.iter().any(|d| d.contains("CVE-2026-9")), "{diff:?}");
}
#[test]
+146
View File
@@ -0,0 +1,146 @@
//! Findings a scan no longer reports are closed, and reopened when reported
//! again. Runs against a live Mongo (`TEST_MONGODB_URI`) and skips cleanly
//! without one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
use compliance_agent::database::{Database, DatabasePool};
use compliance_agent::pipeline::finding_store::RunFindings;
use compliance_core::models::{
Finding, FindingStatus, ScanChangeKind, ScanType, Severity, StatusChange,
};
use mongodb::bson::doc;
const TENANT: &str = "resolve-findings";
const TARGET: &str = "target-1";
fn finding(fingerprint: &str, scanner: &str, file: &str) -> Finding {
let mut f = Finding::new(
TARGET.into(),
fingerprint.into(),
scanner.into(),
ScanType::Sast,
format!("issue {fingerprint}"),
"desc".into(),
Severity::High,
);
f.file_path = Some(file.into());
f
}
async fn row(db: &Database, fingerprint: &str) -> Finding {
db.findings()
.find_one(doc! { "fingerprint": fingerprint })
.await
.unwrap()
.unwrap()
}
/// The reason a scan recorded on the last history entry of `f`.
fn last_scan_change(f: &Finding) -> Option<ScanChangeKind> {
f.status_history
.last()
.filter(|c| c.by == StatusChange::SCAN_ACTOR)
.and_then(|c| c.scan.as_ref())
.map(|s| s.kind)
}
#[tokio::test]
async fn a_scan_closes_what_it_no_longer_finds_and_reopens_what_returns() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"resolve_{}",
&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 these.
let mut decided = finding("fp-false-positive", "semgrep", "src/c.c");
decided.status = FindingStatus::FalsePositive;
let mut other_target = finding("fp-other-target", "semgrep", "src/a.c");
other_target.repo_id = "target-2".into();
db.findings()
.insert_many([
finding("fp-kept", "semgrep", "src/a.c"),
finding("fp-fixed", "semgrep", "src/b.c"),
finding("fp-vendor", "semgrep", "Drivers/STM32F4xx_HAL_Driver/x.c"),
finding("fp-lint", "clippy", "src/lib.rs"),
decided,
other_target,
])
.await
.unwrap();
// A run in which no scanner completed closes nothing.
let mut idle = RunFindings::new("run-idle");
assert_eq!(idle.resolve_missing(&db, TARGET, &[]).await.unwrap(), 0);
// Act: semgrep completes and reports only fp-kept.
let mut run = RunFindings::new("run-2");
run.completed("semgrep");
let mut seen = vec![finding("fp-kept", "semgrep", "src/a.c")];
run.write_back(&db, &mut seen).await.unwrap();
let vendor = vec!["Drivers".to_string()];
let closed = run.resolve_missing(&db, TARGET, &vendor).await.unwrap();
// Assert: fixed and vendored closed, each with its reason; the rest kept.
assert_eq!(closed, 2);
let fixed = row(&db, "fp-fixed").await;
assert_eq!(fixed.status, FindingStatus::Resolved);
assert_eq!(
last_scan_change(&fixed),
Some(ScanChangeKind::NoLongerFound)
);
let vendored = row(&db, "fp-vendor").await;
assert_eq!(vendored.status, FindingStatus::Resolved);
assert_eq!(
last_scan_change(&vendored),
Some(ScanChangeKind::NowVendorCode)
);
assert_eq!(row(&db, "fp-kept").await.status, FindingStatus::Open);
assert_eq!(
row(&db, "fp-false-positive").await.status,
FindingStatus::FalsePositive,
"a person's decision stays"
);
assert_eq!(
row(&db, "fp-lint").await.status,
FindingStatus::Open,
"a scanner that did not complete closes nothing"
);
assert_eq!(
row(&db, "fp-other-target").await.status,
FindingStatus::Open,
"another target's findings are not touched"
);
// Act: the fixed finding comes back. A scanner that did not complete in
// this run does not reopen it; one that did, does.
let mut quiet = RunFindings::new("run-3");
quiet
.save_new(&db, &mut [finding("fp-fixed", "semgrep", "src/b.c")])
.await
.unwrap();
assert_eq!(row(&db, "fp-fixed").await.status, FindingStatus::Resolved);
let mut again = RunFindings::new("run-4");
again.completed("semgrep");
again
.save_new(&db, &mut [finding("fp-fixed", "semgrep", "src/b.c")])
.await
.unwrap();
let reopened = row(&db, "fp-fixed").await;
assert_eq!(reopened.status, FindingStatus::Open);
assert_eq!(
last_scan_change(&reopened),
Some(ScanChangeKind::FoundAgain)
);
assert_eq!(reopened.status_history.len(), 2);
pool.drop_tenant(TENANT).await.ok();
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-core"
version = "0.4.2"
version = "0.4.4"
edition = "2021"
[lints]
+2 -1
View File
@@ -28,5 +28,6 @@ pub use error::CoreError;
pub use exec_policy::ExecPolicy;
pub use net_guard::{NetGuard, NetGuardError};
pub use tenant::{
OrgRole, StaffAccess, TenantContext, TenantStatus, SUPPORT_ROLES, SUPPORT_TENANT_HEADER,
OrgRole, ProductAccess, StaffAccess, TenantContext, TenantStatus, SUPPORT_ROLES,
SUPPORT_TENANT_HEADER,
};
+5
View File
@@ -25,6 +25,11 @@ pub struct AuthInfo {
/// for support before choosing one.
#[serde(default)]
pub support_tenant: Option<SupportTenant>,
/// What the user's org roles allow in Prüfwerk; decides whether the
/// app shows at all and whether write actions show. The agent enforces
/// the same rule on every request.
#[serde(default)]
pub access: crate::ProductAccess,
}
/// A customer tenant opened by BreakPilot support.
+21
View File
@@ -23,11 +23,30 @@ pub struct CveAlert {
pub summary: Option<String>,
pub llm_impact_summary: Option<String>,
pub references: Vec<String>,
/// Other ids of the same advisory (a GHSA's `CVE-…`).
#[serde(default)]
pub aliases: Vec<String>,
/// The versions of the affected package that fix it, when the advisory
/// names them.
#[serde(default)]
pub fixed_versions: Vec<String>,
#[serde(with = "super::serde_helpers::bson_datetime")]
pub created_at: DateTime<Utc>,
}
impl CveAlert {
/// The CVE id of the advisory: its own id, or a `CVE-` alias of a GHSA
/// or ecosystem advisory; otherwise its own id.
pub fn cve(&self) -> &str {
if self.cve_id.starts_with("CVE-") {
return &self.cve_id;
}
self.aliases
.iter()
.find(|a| a.starts_with("CVE-"))
.map_or(self.cve_id.as_str(), String::as_str)
}
pub fn new(
cve_id: String,
repo_id: String,
@@ -47,6 +66,8 @@ impl CveAlert {
summary: None,
llm_impact_summary: None,
references: Vec::new(),
aliases: Vec::new(),
fixed_versions: Vec::new(),
created_at: Utc::now(),
}
}
+53 -1
View File
@@ -89,6 +89,57 @@ pub struct StatusChange {
/// Why; required when a risk is accepted.
#[serde(default)]
pub reason: Option<String>,
/// Set when a scan changed the status rather than a person: why, and
/// which run.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scan: Option<ScanStatusChange>,
}
impl StatusChange {
/// The `by` of every change a scan made.
pub const SCAN_ACTOR: &'static str = "pruefwerk-scan";
/// A change the scan run `scan_run_id` made, for the reason `kind`.
///
/// # Arguments
///
/// * `status` - the status the finding moves to
/// * `kind` - why the scan changed it
/// * `scan_run_id` - the run that changed it
pub fn by_scan(status: FindingStatus, kind: ScanChangeKind, scan_run_id: &str) -> Self {
Self {
status,
by: Self::SCAN_ACTOR.to_string(),
by_name: None,
support: false,
at: Utc::now(),
reason: None,
scan: Some(ScanStatusChange {
kind,
scan_run_id: scan_run_id.to_string(),
}),
}
}
}
/// Why a scan changed a finding's status.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ScanChangeKind {
/// The scanner that reported it completed and did not report it again:
/// the code was fixed or removed (or moved, which reports it anew).
NoLongerFound,
/// Its file now lies in vendor code, which is left out of the findings.
NowVendorCode,
/// A finding marked resolved was reported again.
FoundAgain,
}
/// The scan behind a [`StatusChange`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ScanStatusChange {
pub kind: ScanChangeKind,
pub scan_run_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -131,7 +182,8 @@ pub struct Finding {
/// How to reproduce the finding, for findings from a manual test.
#[serde(default)]
pub reproduction: Option<String>,
/// Every status change made by a person, oldest first.
/// Every status change, oldest first: those made by a person, and those
/// a scan made ([`StatusChange::scan`]).
#[serde(default)]
pub status_history: Vec<StatusChange>,
#[serde(with = "super::serde_helpers::bson_datetime")]
+149
View File
@@ -0,0 +1,149 @@
//! A tenant's managed git source (#439).
//!
//! BreakPilot runs one Gitea instance per customer. A [`GitSource`] names that
//! instance and the organisation whose repositories Prüfwerk checks: every
//! repository in it becomes a target automatically (by system/org webhook and
//! by a periodic sync), and findings come back as issues in the repository.
//!
//! One source per tenant, stored in the tenant database under a fixed id.
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use super::credentials::Credentials;
/// The `_id` of a tenant's (single) git source document.
pub const GIT_SOURCE_ID: &str = "default";
/// The managed git instance of a tenant, as stored.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitSource {
/// Always [`GIT_SOURCE_ID`]: one source per tenant.
#[serde(rename = "_id")]
pub id: String,
/// The instance origin, `https://<host>` without a path or trailing slash.
pub base_url: String,
/// The organisation whose repositories are checked.
pub org: String,
/// The bot user's access token, sealed at rest.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub bot_token: Option<String>,
/// The HMAC secret of the system/org webhook, sealed at rest.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub webhook_secret: Option<String>,
/// Whether webhooks and the periodic sync act on this source.
#[serde(default)]
pub enabled: bool,
/// When the source was first configured.
#[serde(
default = "chrono::Utc::now",
with = "super::serde_helpers::bson_datetime"
)]
pub created_at: DateTime<Utc>,
/// When the source was last changed.
#[serde(
default = "chrono::Utc::now",
with = "super::serde_helpers::bson_datetime"
)]
pub updated_at: DateTime<Utc>,
/// When the periodic sync last listed the organisation's repositories.
#[serde(default, with = "super::serde_helpers::opt_bson_datetime")]
pub last_sync_at: Option<DateTime<Utc>>,
}
impl Credentials for GitSource {
fn credentials_mut(&mut self) -> Vec<&mut Option<String>> {
vec![&mut self.bot_token, &mut self.webhook_secret]
}
}
/// A git source as the API shows it: no credentials, only whether they are set.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct GitSourceView {
pub base_url: String,
pub org: String,
pub enabled: bool,
pub has_bot_token: bool,
pub has_webhook_secret: bool,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub last_sync_at: Option<DateTime<Utc>>,
}
impl From<&GitSource> for GitSourceView {
fn from(s: &GitSource) -> Self {
Self {
base_url: s.base_url.clone(),
org: s.org.clone(),
enabled: s.enabled,
has_bot_token: s.bot_token.is_some(),
has_webhook_secret: s.webhook_secret.is_some(),
created_at: s.created_at,
updated_at: s.updated_at,
last_sync_at: s.last_sync_at,
}
}
}
/// The repository a target was created for by a git source. Its presence is
/// what makes a target "managed": created, renamed and archived by the source,
/// with CRA-labelled issues.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SourceRepo {
/// The source's `base_url` when the target was created.
pub base_url: String,
/// Gitea's repository id: stable across renames and transfers.
pub repo_id: i64,
/// `owner/name` as last seen.
pub full_name: String,
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
fn source() -> GitSource {
let now = Utc::now();
GitSource {
id: GIT_SOURCE_ID.into(),
base_url: "https://kunde.code.breakpilot.com".into(),
org: "kunde".into(),
bot_token: Some("sec-token".into()),
webhook_secret: Some("sec-hook".into()),
enabled: true,
created_at: now,
updated_at: now,
last_sync_at: None,
}
}
#[test]
fn both_secrets_are_credentials() {
let mut s = source();
let mut v: Vec<String> = s
.credentials_mut()
.into_iter()
.filter_map(|slot| slot.clone())
.collect();
v.sort();
assert_eq!(v, ["sec-hook", "sec-token"]);
}
#[test]
fn the_view_carries_no_secret() {
let view = GitSourceView::from(&source());
let json = serde_json::to_string(&view).unwrap();
assert!(!json.contains("sec-"), "{json}");
assert!(view.has_bot_token && view.has_webhook_secret);
}
#[test]
fn bson_round_trip() {
let s = source();
let b = bson::to_bson(&s).unwrap();
let back: GitSource = bson::from_bson(b).unwrap();
assert_eq!(back.base_url, s.base_url);
assert_eq!(back.bot_token, s.bot_token);
}
}
+5 -1
View File
@@ -5,6 +5,7 @@ pub mod cve;
pub mod dast;
pub mod embedding;
pub mod finding;
pub mod git_source;
pub mod graph;
pub mod issue;
pub mod mcp;
@@ -30,7 +31,10 @@ pub use dast::{
DastTarget, DastTargetType, DastVulnType,
};
pub use embedding::{CodeEmbedding, EmbeddingBuildRun, EmbeddingBuildStatus};
pub use finding::{Finding, FindingStatus, Severity, StatusChange};
pub use finding::{
Finding, FindingStatus, ScanChangeKind, ScanStatusChange, Severity, StatusChange,
};
pub use git_source::{GitSource, GitSourceView, SourceRepo, GIT_SOURCE_ID};
pub use graph::{
CodeEdge, CodeEdgeKind, CodeNode, CodeNodeKind, GraphBuildRun, GraphBuildStatus, ImpactAnalysis,
};
+83
View File
@@ -529,6 +529,21 @@ pub struct ComplianceProfile {
/// The sensible default compliance scope for a target type. Firmware / PLC /
/// embedded default to CRA + IEC 62443; software defaults to GDPR + SOC 2.
impl OnboardedTarget {
/// The type a scan's `classification` gives a managed target, when it
/// should change: the target came from a managed git source (created
/// before its repository had any code, so typed by default), no person
/// chose its type, the classifier found evidence (not just the fallback
/// to the current type), and the evidence names another type.
pub fn detected_type(&self, classification: &Classification) -> Option<TargetType> {
let detected = self.source_repo.is_some()
&& !self.type_chosen
&& !classification.candidates.is_empty()
&& classification.suggested != self.target_type;
detected.then_some(classification.suggested)
}
}
pub fn default_compliance_profile(target_type: TargetType) -> ComplianceProfile {
use ComplianceFramework::{Cra, Gdpr, Iec62443, Soc2};
let frameworks = match target_type {
@@ -594,6 +609,22 @@ pub struct OnboardedTarget {
/// what gets checked follows `compliance_profile`.
#[serde(default)]
pub project_ids: Vec<String>,
/// The managed-git repository this target was created for (#439); `None`
/// for a target a user onboarded.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source_repo: Option<super::git_source::SourceRepo>,
/// A person changed the target's type. A managed target's type otherwise
/// follows what each scan detects (see [`OnboardedTarget::detected_type`]).
#[serde(default)]
pub type_chosen: bool,
/// When the target was archived because its repository was deleted.
/// Archived targets keep their findings but are no longer scanned.
#[serde(
default,
skip_serializing_if = "Option::is_none",
with = "super::serde_helpers::opt_bson_datetime"
)]
pub archived_at: Option<DateTime<Utc>>,
/// Creation timestamp.
#[serde(
default = "chrono::Utc::now",
@@ -629,6 +660,9 @@ impl OnboardedTarget {
webhook_secret: None,
findings_count: 0,
project_ids: Vec::new(),
source_repo: None,
type_chosen: false,
archived_at: None,
created_at: now,
updated_at: now,
}
@@ -662,6 +696,55 @@ impl OnboardedTarget {
mod tests {
use super::*;
fn classified(suggested: TargetType, evidence: bool) -> Classification {
Classification {
suggested,
candidates: if evidence {
vec![TargetTypeCandidate {
target_type: suggested,
confidence: 0.8,
rationale: "Android manifest / gradle".into(),
}]
} else {
Vec::new()
},
facts: Vec::new(),
detected_by: Vec::new(),
detected_at: Utc::now(),
confirmed: false,
}
}
#[test]
fn a_managed_targets_type_follows_its_code_until_a_person_picks_one() {
let mut managed = OnboardedTarget::new("gt-mobile".into(), TargetType::BackendService);
managed.source_repo = Some(super::super::git_source::SourceRepo {
base_url: "https://kunde.code.example".into(),
repo_id: 7,
full_name: "kunde/gt-mobile".into(),
});
let android = classified(TargetType::AndroidApp, true);
assert_eq!(
managed.detected_type(&android),
Some(TargetType::AndroidApp)
);
// An empty repository gives no evidence: the default stays.
assert_eq!(
managed.detected_type(&classified(TargetType::BackendService, false)),
None
);
// Already right: nothing to change.
managed.target_type = TargetType::AndroidApp;
assert_eq!(managed.detected_type(&android), None);
// A person's choice stands.
managed.target_type = TargetType::DesktopApp;
managed.type_chosen = true;
assert_eq!(managed.detected_type(&android), None);
// A target a person onboarded keeps the type they gave it.
let onboarded = OnboardedTarget::new("fw".into(), TargetType::BackendService);
assert_eq!(onboarded.detected_type(&android), None);
}
fn sample_target() -> OnboardedTarget {
let mut t = OnboardedTarget::new("acme-web".to_string(), TargetType::WebApp);
t.artifacts.push(Artifact::git_repo(
+3
View File
@@ -202,6 +202,9 @@ pub enum SkipCode {
/// Some components were not matched against known vulnerabilities;
/// `subject` names the lookup, and the components where known.
CveLookupIncomplete,
/// Files kept in Git LFS were not downloaded (binary assets, not
/// analysed); `subject` lists the LFS patterns of `.gitattributes`.
LfsNotFetched,
/// A scheduled or webhook scan found no new commits since the last scan,
/// so nothing was scanned again.
NoNewCommits,
+107
View File
@@ -118,6 +118,57 @@ impl OrgRole {
}
}
/// What an organisation member may do in Prüfwerk, by their org roles
/// (decided 2026-09-30):
///
/// * `IT_ADMIN`, `USER` — [`ProductAccess::Full`]: read and write.
/// * `CXO`, `LEGAL` — [`ProductAccess::ReadOnly`]: findings, reports, SBOM,
/// evidence and exports, but no change of any kind.
/// * `FINANCE`, or none of these roles — [`ProductAccess::None`].
///
/// The strongest role a user holds wins. BreakPilot support sessions are not
/// judged by org roles (see [`TenantContext::product_access`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ProductAccess {
/// Read and write.
Full,
/// Read only: every write is refused.
ReadOnly,
/// No access at all. The default, so a missing value never grants access.
#[default]
None,
}
impl ProductAccess {
/// The access the org `roles` grant.
pub fn for_roles(roles: &[OrgRole]) -> Self {
if roles
.iter()
.any(|r| matches!(r, OrgRole::ItAdmin | OrgRole::User))
{
Self::Full
} else if roles
.iter()
.any(|r| matches!(r, OrgRole::Cxo | OrgRole::Legal))
{
Self::ReadOnly
} else {
Self::None
}
}
/// Whether anything may be read.
pub fn can_read(self) -> bool {
!matches!(self, Self::None)
}
/// Whether anything may be changed.
pub fn can_write(self) -> bool {
matches!(self, Self::Full)
}
}
/// Keycloak realm roles of BreakPilot staff who may open any tenant for
/// support (covered by the AVV). Granted through the company sign-in.
pub const SUPPORT_ROLES: &[&str] = &["BREAKPILOT_ADMIN", "SUPPORT_ENGINEER"];
@@ -187,6 +238,16 @@ impl TenantContext {
}
}
/// What this request may do in Prüfwerk. BreakPilot support keeps its
/// own rules (read-only until the registry confirms the tenant, every
/// change audited), so it is not judged by org roles.
pub fn product_access(&self) -> ProductAccess {
if self.staff.is_some() {
return ProductAccess::Full;
}
ProductAccess::for_roles(&self.org_roles)
}
/// True if the caller holds at least one of the listed roles.
pub fn has_any_role(&self, roles: &[OrgRole]) -> bool {
self.org_roles.iter().any(|r| roles.contains(r))
@@ -227,6 +288,52 @@ mod tests {
assert!(!TenantStatus::Active.is_demo());
}
#[test]
fn product_access_follows_the_strongest_role() {
use OrgRole::*;
let cases: &[(&[OrgRole], ProductAccess)] = &[
(&[ItAdmin], ProductAccess::Full),
(&[User], ProductAccess::Full),
(&[Cxo], ProductAccess::ReadOnly),
(&[Legal], ProductAccess::ReadOnly),
(&[Finance], ProductAccess::None),
(&[Unknown], ProductAccess::None),
(&[], ProductAccess::None),
(&[Finance, Legal], ProductAccess::ReadOnly),
(&[Cxo, User], ProductAccess::Full),
(&[Finance, ItAdmin], ProductAccess::Full),
];
for (roles, want) in cases {
assert_eq!(ProductAccess::for_roles(roles), *want, "{roles:?}");
}
assert!(ProductAccess::Full.can_write());
assert!(!ProductAccess::ReadOnly.can_write());
assert!(ProductAccess::ReadOnly.can_read());
assert!(!ProductAccess::None.can_read());
assert_eq!(ProductAccess::default(), ProductAccess::None);
}
#[test]
fn support_is_not_judged_by_org_roles() {
let ctx = TenantContext {
tenant_id: "t1".into(),
tenant_slug: "acme".into(),
org_roles: vec![],
products: vec![],
plan: String::new(),
status: TenantStatus::Restricted,
user_id: "s".into(),
user_name: None,
staff: Some(StaffAccess {
user_id: "s".into(),
user_name: None,
}),
};
assert_eq!(ctx.product_access(), ProductAccess::Full);
let customer = TenantContext { staff: None, ..ctx };
assert_eq!(customer.product_access(), ProductAccess::None);
}
#[test]
fn has_any_role_matches() {
let ctx = TenantContext {
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-dashboard"
version = "0.4.2"
version = "0.4.4"
edition = "2021"
default-run = "compliance-dashboard"
@@ -0,0 +1,92 @@
Copyright (c) 2023 Vercel, in collaboration with basement.studio
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION AND CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+40 -1
View File
@@ -6,7 +6,25 @@
with the portal (platform/portal src/app/globals.css).
═══════════════════════════════════════════════════════════════ */
@import url('https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700;800&family=Geist+Mono:wght@400;500;600&display=swap');
/* ── Fonts ──
Geist and Geist Mono (SIL OFL 1.1, assets/fonts/OFL-Geist.txt), served by
the dashboard itself at /fonts/ (infrastructure/server.rs). No third-party
font CDN: a visitor's browser talks to this host only. */
@font-face {
font-family: 'Geist';
src: url('/fonts/geist.woff2') format('woff2');
font-weight: 100 900;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: 'Geist Mono';
src: url('/fonts/geist-mono.woff2') format('woff2');
font-weight: 100 900;
font-style: normal;
font-display: swap;
}
/* ── Design Tokens (light, the default) ── */
:root {
@@ -5451,3 +5469,24 @@ input[type="file"] {
.project-filter { margin-left: 0; width: 100%; }
.project-filter select { flex: 1; min-width: 0; }
}
/* Org roles: the page for a role without access, and the read-only note. */
.no-access-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
margin-top: 16px;
}
.read-only-banner {
display: flex;
align-items: center;
gap: 8px;
margin: -8px 0 16px;
padding: 8px 14px;
border-radius: 10px;
background: var(--accent-muted);
border: 1px solid var(--border);
color: var(--text-secondary);
font-size: 13px;
}
@@ -2,6 +2,7 @@ use dioxus::prelude::*;
use crate::app::Route;
use crate::components::help_chat::HelpChat;
use crate::components::no_access::{NoAccess, ReadOnlyBanner};
use crate::components::notification_bell::NotificationBell;
use crate::components::sidebar::Sidebar;
use crate::components::support::{SupportBanner, SupportPicker};
@@ -50,8 +51,16 @@ pub fn AppShell() -> Element {
ToastContainer {}
}
}
// A role without access to Prüfwerk (FINANCE, or none): no navigation
// and no page, so nothing is fetched or shown.
Some(Ok(info)) if info.authenticated && !info.access.can_read() => {
rsx! {
NoAccess { portal_url: info.portal_url.clone() }
}
}
Some(Ok(info)) if info.authenticated => {
use_context_provider(|| Signal::new(info.clone()));
let read_only = !info.access.can_write();
rsx! {
div { class: "app-shell",
Sidebar {}
@@ -59,6 +68,9 @@ pub fn AppShell() -> Element {
if let Some(tenant) = info.support_tenant.clone() {
SupportBanner { tenant }
}
if read_only {
ReadOnlyBanner {}
}
Outlet::<Route> {}
}
NotificationBell {}
@@ -12,6 +12,7 @@ pub mod help_chat;
pub mod lang_toggle;
pub mod manual_findings;
pub mod markdown;
pub mod no_access;
pub mod notification_bell;
pub mod page_header;
pub mod pagination;
@@ -0,0 +1,54 @@
//! What a user sees whose org role has no access to Prüfwerk (`FINANCE`, or
//! no role at all), and the notice for roles that may only read.
use compliance_core::models::auth::AuthInfo;
use dioxus::prelude::*;
use dioxus_free_icons::icons::bs_icons::{BsEye, BsShieldLock};
use dioxus_free_icons::Icon;
use crate::components::lang_toggle::LangToggle;
use crate::i18n::texts::access as tx;
use crate::i18n::use_lang;
/// Whether the signed-in user's role may change anything. Write actions
/// (add, scan, delete, triage, tokens, settings) show only when it may; the
/// agent refuses them either way.
pub fn use_can_write() -> bool {
try_use_context::<Signal<AuthInfo>>().is_some_and(|info| info.read().access.can_write())
}
/// The whole page for a role without access: no navigation, no data.
#[component]
pub fn NoAccess(portal_url: String) -> Element {
let lang = use_lang()();
rsx! {
main { class: "support-picker",
div { class: "support-picker-card", role: "alert",
div { class: "support-picker-head",
span { class: "support-picker-mark", Icon { icon: BsShieldLock, width: 18, height: 18 } }
h1 { {tx::NO_ACCESS_TITLE.get(lang)} }
}
p { class: "support-picker-intro", {tx::NO_ACCESS_BODY.get(lang)} }
div { class: "no-access-actions",
if !portal_url.is_empty() {
a { class: "btn btn-primary", href: "{portal_url}", {tx::BACK_TO_PORTAL.get(lang)} }
}
a { class: "btn btn-ghost", href: "/logout", {tx::SIGN_OUT.get(lang)} }
LangToggle { collapsed: true }
}
}
}
}
}
/// A line at the top of the page for roles that may only read.
#[component]
pub fn ReadOnlyBanner() -> Element {
let lang = use_lang()();
rsx! {
div { class: "read-only-banner", role: "status",
Icon { icon: BsEye, width: 14, height: 14 }
span { {tx::READ_ONLY.get(lang)} }
}
}
}
@@ -9,6 +9,7 @@ use crate::infrastructure::notifications::{
#[component]
pub fn NotificationBell() -> Element {
let can_write = crate::components::no_access::use_can_write();
let mut is_open = use_signal(|| false);
let mut count = use_signal(|| 0u64);
let mut notifications = use_signal(Vec::new);
@@ -42,9 +43,12 @@ pub fn NotificationBell() -> Element {
if let Ok(resp) = fetch_notifications().await {
notifications.set(resp.data);
}
// Mark all as read when panel opens
let _ = mark_all_notifications_read().await;
count.set(0);
// Mark all as read when panel opens; a read-only role leaves the
// tenant's alerts as they are.
if can_write {
let _ = mark_all_notifications_read().await;
count.set(0);
}
is_loading.set(false);
});
};
@@ -124,11 +128,13 @@ pub fn NotificationBell() -> Element {
if let Some(score) = notif.cvss_score {
span { class: "notification-cvss", "CVSS {score:.1}" }
}
button {
class: "notification-dismiss-btn",
title: "Dismiss",
onclick: move |_| on_dismiss(dismiss_id.clone()),
Icon { icon: BsXCircle, width: 14, height: 14 }
if can_write {
button {
class: "notification-dismiss-btn",
title: "Dismiss",
onclick: move |_| on_dismiss(dismiss_id.clone()),
Icon { icon: BsXCircle, width: 14, height: 14 }
}
}
}
div { class: "notification-item-pkg",
Loaded 100 of 264 files, more files were not shown because too many files have changed in this diff. Show more