Compare commits

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

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

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

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

## What changes

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

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

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

## Tests

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

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

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

---------

Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Reviewed-on: #927
2026-11-06 14:30:07 +00:00
sharang c28f9e186b fix(mcp): rmcp 3.9, with the Host check of the Streamable HTTP server (#909)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 5m8s
CI / Deploy Dashboard (push) Successful in 6m43s
CI / Deploy Agent (push) Successful in 8m54s
2026-11-05 19:31:06 +00:00
sharang 4480e8b509 fix(scan): Prüfwerk's own code no longer flags its test literals (#908)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 8s
CI / Deploy Dashboard (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Agent (push) Successful in 5m37s
2026-11-05 19:12:37 +00:00
sharang aa1c9b5d2b fix(docs): update the docs site's dependencies within their ranges (#907)
CI / Agent integration (push) Skipped
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 10s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Agent (push) Canceled after 0s
CI / Deploy Docs (push) Successful in 1m21s
2026-11-05 19:12:16 +00:00
sharang b2b9fd2a02 fix(scan): a Semgrep rule pack with its samples is test data (#905)
CI / Agent integration (push) Skipped
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 11s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Agent (push) Canceled after 0s
CI / Deploy Docs (push) Successful in 1m13s
2026-11-05 19:11:56 +00:00
sharang 8d839ed5ad fix(deps): openssl 0.10.82 and mongodb 3.10 (hickory 0.26) (#906)
CI / Agent integration (push) Skipped
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 7s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 3m51s
CI / Deploy Dashboard (push) Successful in 4m25s
CI / Deploy Agent (push) Successful in 7m20s
2026-11-05 19:11:42 +00:00
sharang b079cf9267 fix(scan): findings in test data and excluded paths close, whichever scanner stored them (#904)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 6s
CI / Deploy Dashboard (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Agent (push) Successful in 6m47s
2026-11-05 17:56:00 +00:00
sharang 2157ae2d42 fix(telemetry): service.version reports the release, not the crate version (#883)
CI / Agent integration (push) Skipped
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 4m40s
CI / Deploy Dashboard (push) Successful in 6m12s
CI / Deploy Agent (push) Successful in 8m36s
2026-11-05 17:32:27 +00:00
sharang 13d09dc830 fix(sbom): a component the build installed is badged "Im Image (gebaut)" (#881)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy MCP (push) Skipped
CI / Deploy Docs (push) Successful in 1m11s
CI / Deploy Agent (push) Successful in 8m28s
CI / Deploy Dashboard (push) Successful in 5m14s
2026-11-05 08:30:19 +00:00
55 changed files with 3617 additions and 1008 deletions

No files matched your search

+5 -19
View File
@@ -1,23 +1,9 @@
[advisories]
ignore = [
# hickory-proto 0.25.x pulled in transitively via mongodb → hickory-resolver.
# MongoDB 3.x has not yet released with hickory-resolver 0.26.x, so we cannot
# upgrade past this without a mongodb release. Both are DNS-layer DoS vectors
# requiring a MITM/controlled DNS server against MongoDB's hostname resolution —
# not a realistic attack surface here. Revisit when mongodb bumps hickory.
# hickory-proto, pulled in transitively via mongodb → hickory-resolver
# (0.26.3 since mongodb 3.10, which fixed RUSTSEC-2026-0119). The NSEC3 loop
# is in DNSSEC validation, which the driver does not use, and needs a
# MITM/controlled DNS server against MongoDB's hostname resolution — not a
# realistic attack surface here. Revisit when hickory ships a fix.
"RUSTSEC-2026-0118", # NSEC3 loop, no fix available upstream
"RUSTSEC-2026-0119", # O(n²) name compression, fixed in hickory-proto >=0.26.1
# rmcp 0.16.0 — DNS rebinding in Streamable HTTP server transport (missing
# Host header validation). Patched in rmcp >= 1.4.0, which is a major API
# version jump from our pin; rmcp shipped 0.x → 1.x → 2.x in three months
# and the migration touches every tool handler + the auth middleware we
# just landed in #92. Threat model in our deployment: the MCP server is
# exposed at a public hostname (comp-mcp-dev.breakpilot.com) behind orca's
# TLS-terminating ingress with per-tenant bearer auth — the attack model
# (browser DNS-rebinding into localhost MCP server) doesn't directly apply.
# Defense-in-depth Host-header check is still a worthwhile follow-up.
# FOLLOW-UP: bump rmcp to 2.x in a dedicated PR (M7.3 follow-up, sized
# multi-hour due to API surface change).
"RUSTSEC-2026-0189",
]
+5
View File
@@ -146,6 +146,11 @@ DASHBOARD_SESSION_KEY=
# MCP Server
MCP_ENDPOINT_URL=http://localhost:8090
# The hostnames (or host:port) clients reach the MCP server at, comma-separated:
# the public hostname behind the ingress and the in-network name the dashboard
# uses. Requests with another Host header are refused (DNS rebinding
# protection). Unset, the Host header is not checked and a warning is logged.
# MCP_ALLOWED_HOSTS=pruefwerk-stage.breakpilot.com,compliance-mcp:8090
# Absolute health URL for the default MCP server card. Set it where an ingress
# routes /mcp/* to a server that serves /health at its own root (staging:
# https://pruefwerk-stage.breakpilot.com/mcp/health). Derived from
+14
View File
@@ -151,9 +151,16 @@ jobs:
# compliance-core's integration tests need no services.
- name: Tests (core integration)
run: cargo test -p compliance-core --tests
# The dashboard crate compiles as the library and as its test harness at
# once, each rustc at about 1.65 GB: two of them exceed the job's 3 GiB
# and get OOM-killed (signal 9). One at a time for these two steps.
- name: Tests (dashboard server)
env:
CARGO_BUILD_JOBS: "1"
run: cargo test -p compliance-dashboard --features server --no-default-features
- name: Tests (dashboard web)
env:
CARGO_BUILD_JOBS: "1"
run: cargo test -p compliance-dashboard --features web --no-default-features
- name: Show sccache stats
@@ -374,9 +381,16 @@ jobs:
apk add --no-cache git curl openssl
git init && git remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git"
git fetch --depth=1 origin "${GITHUB_SHA}" && git checkout FETCH_HEAD
# service.version in telemetry: the latest release tag without its v,
# as for the agent. No tag → empty, and the crate version is used.
git fetch --quiet --unshallow --tags origin || true
TAG=$(git describe --tags --abbrev=0 --match 'v[0-9]*' 2>/dev/null || true)
PRUEFWERK_VERSION="${TAG#v}"
echo "version: ${PRUEFWERK_VERSION:-crate}"
IMAGE=repo.breakpilot.com/pruefwerk/compliance-dashboard
echo "$REGISTRY_PASSWORD" | docker login repo.breakpilot.com -u "$REGISTRY_USERNAME" --password-stdin
DOCKER_BUILDKIT=1 docker build --pull --secret id=git_token,env=PLATFORM_CI_TOKEN \
--build-arg PRUEFWERK_VERSION="${PRUEFWERK_VERSION}" \
-f Dockerfile.dashboard -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
docker push "$IMAGE:latest" && docker push "$IMAGE:${GITHUB_SHA}"
{ command -v cosign >/dev/null 2>&1 || curl -sSfLo /usr/local/bin/cosign https://github.com/sigstore/cosign/releases/download/v2.4.3/cosign-linux-amd64 || wget -qO /usr/local/bin/cosign https://github.com/sigstore/cosign/releases/download/v2.4.3/cosign-linux-amd64; } || echo "::warning::cosign fetch failed"
+11
View File
@@ -0,0 +1,11 @@
# Made-up secrets in Prüfwerk's own tests, found by the secret scanner in the
# git history (commit:file:rule:line, as gitleaks fingerprints them). Neither is
# a real credential; the history keeps them, so they are listed here.
#
# A Firebase-shaped key in the test that the real scanner still finds Firebase
# keys (compliance-agent/src/pipeline/gitleaks.rs).
6c9756bebf599eb16112d693c769cd752292d6a9:compliance-agent/src/pipeline/gitleaks.rs:gcp-api-key:278
d42b429273668bd285440596fd78e564d34b01ef:compliance-agent/src/pipeline/gitleaks.rs:gcp-api-key:278
# The throwaway MongoDB root password of a CI test container.
3ef5c28a97f169ed03009f70a9a20a7c9095f0b2:.gitea/workflows/ci.yml:generic-password:170
5424074d26552882c6529c2dd9d309b9cc37376a:.gitea/workflows/ci.yml:generic-password:72
Generated
+223 -77
View File
@@ -526,6 +526,16 @@ dependencies = [
"windows-link",
]
[[package]]
name = "chrono-tz"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3"
dependencies = [
"chrono",
"phf 0.12.1",
]
[[package]]
name = "ciborium"
version = "0.2.2"
@@ -596,6 +606,7 @@ dependencies = [
"axum",
"base64 0.22.1",
"chrono",
"chrono-tz",
"compliance-core",
"compliance-dast",
"compliance-graph",
@@ -1114,7 +1125,7 @@ dependencies = [
"cssparser-macros",
"dtoa-short",
"itoa",
"phf",
"phf 0.13.1",
"smallvec",
]
@@ -1166,6 +1177,16 @@ dependencies = [
"darling_macro 0.23.0",
]
[[package]]
name = "darling"
version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"
dependencies = [
"darling_core 0.24.1",
"darling_macro 0.24.1",
]
[[package]]
name = "darling_core"
version = "0.21.3"
@@ -1193,6 +1214,19 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "darling_core"
version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"
dependencies = [
"ident_case",
"proc-macro2",
"quote",
"strsim",
"syn 3.0.9",
]
[[package]]
name = "darling_macro"
version = "0.21.3"
@@ -1215,6 +1249,17 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "darling_macro"
version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"
dependencies = [
"darling_core 0.24.1",
"quote",
"syn 3.0.9",
]
[[package]]
name = "dashmap"
version = "6.1.0"
@@ -1368,7 +1413,7 @@ dependencies = [
"dioxus-cli-config 0.7.3",
"http",
"infer",
"jni",
"jni 0.21.1",
"js-sys",
"ndk",
"ndk-context",
@@ -2037,18 +2082,6 @@ dependencies = [
"cfg-if",
]
[[package]]
name = "enum-as-inner"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "enumset"
version = "1.1.10"
@@ -2647,23 +2680,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hickory-proto"
version = "0.25.2"
name = "hickory-net"
version = "0.26.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8a6fe56c0038198998a6f217ca4e7ef3a5e51f46163bd6dd60b5c71ca6c6502"
checksum = "c480823ed7c2c5d0f09c41020cb6b7c28029ce60ec42dc942158dcf22f8e0a4d"
dependencies = [
"async-trait",
"cfg-if",
"data-encoding",
"enum-as-inner",
"futures-channel",
"futures-io",
"futures-util",
"hickory-proto",
"idna",
"ipnet",
"once_cell",
"rand 0.9.2",
"ring",
"jni 0.22.4",
"rand 0.10.3",
"thiserror 2.0.18",
"tinyvec",
"tokio",
@@ -2672,21 +2704,46 @@ dependencies = [
]
[[package]]
name = "hickory-resolver"
version = "0.25.2"
name = "hickory-proto"
version = "0.26.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc62a9a99b0bfb44d2ab95a7208ac952d31060efc16241c87eaf36406fecf87a"
checksum = "12b92608f679a6fa515dd1d15c1ff89443026e391200a2c840c7afcba482893d"
dependencies = [
"data-encoding",
"idna",
"ipnet",
"jni 0.22.4",
"once_cell",
"prefix-trie",
"rand 0.10.3",
"ring",
"thiserror 2.0.18",
"tinyvec",
"tracing",
"url",
]
[[package]]
name = "hickory-resolver"
version = "0.26.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f3da5255c95d5a716857d54b5b8f4e8d67c3484d3beaaaae2ce25063b3ba981"
dependencies = [
"cfg-if",
"futures-util",
"hickory-net",
"hickory-proto",
"ipconfig",
"ipnet",
"jni 0.22.4",
"moka",
"ndk-context",
"once_cell",
"parking_lot",
"rand 0.9.2",
"rand 0.10.3",
"resolv-conf",
"smallvec",
"system-configuration",
"thiserror 2.0.18",
"tokio",
"tracing",
@@ -3070,6 +3127,9 @@ name = "ipnet"
version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130"
dependencies = [
"serde",
]
[[package]]
name = "iri-string"
@@ -3105,19 +3165,68 @@ dependencies = [
"cesu8",
"cfg-if",
"combine",
"jni-sys",
"jni-sys 0.3.0",
"log",
"thiserror 1.0.69",
"walkdir",
"windows-sys 0.45.0",
]
[[package]]
name = "jni"
version = "0.22.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"
dependencies = [
"cfg-if",
"combine",
"jni-macros",
"jni-sys 0.4.1",
"log",
"simd_cesu8",
"thiserror 2.0.18",
"walkdir",
"windows-link",
]
[[package]]
name = "jni-macros"
version = "0.22.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"
dependencies = [
"proc-macro2",
"quote",
"rustc_version",
"simd_cesu8",
"syn 2.0.117",
]
[[package]]
name = "jni-sys"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130"
[[package]]
name = "jni-sys"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"
dependencies = [
"jni-sys-macros",
]
[[package]]
name = "jni-sys-macros"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
dependencies = [
"quote",
"syn 2.0.117",
]
[[package]]
name = "jobserver"
version = "0.1.34"
@@ -3486,12 +3595,12 @@ checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
[[package]]
name = "md-5"
version = "0.10.6"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98"
dependencies = [
"cfg-if",
"digest 0.10.7",
"digest 0.11.3",
]
[[package]]
@@ -3589,9 +3698,9 @@ dependencies = [
[[package]]
name = "mongocrypt"
version = "0.3.2"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8da0cd419a51a5fb44819e290fbdb0665a54f21dead8923446a799c7f4d26ad9"
checksum = "8426a875ded61430d4a811dbfda7633b6b8af0225c547fc6c28b8b0aa7d79a13"
dependencies = [
"bson",
"mongocrypt-sys",
@@ -3601,43 +3710,42 @@ dependencies = [
[[package]]
name = "mongocrypt-sys"
version = "0.1.5+1.15.1"
version = "0.1.6+1.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "224484c5d09285a7b8cb0a0c117e847ebd14cb6e4470ecf68cdb89c503b0edb9"
checksum = "851fac73f7fe22f6a3ab87f720ce509cae7c9fd08e7dd27866cc232dee07ccf4"
[[package]]
name = "mongodb"
version = "3.6.0"
version = "3.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ef2c933617431ad0246fb5b43c425ebdae18c7f7259c87de0726d93b0e7e91b"
checksum = "6466d4601ff396952e1895d88083d1ab03930b812277180eb8258bbe1a10bb0f"
dependencies = [
"base64 0.22.1",
"bitflags",
"bson",
"derive-where",
"derive_more",
"futures-core",
"futures-io",
"futures-util",
"hex",
"hickory-net",
"hickory-proto",
"hickory-resolver",
"hmac 0.12.1",
"hmac 0.13.0",
"macro_magic",
"md-5",
"mongocrypt",
"mongodb-internal-macros",
"pbkdf2 0.12.2",
"pbkdf2",
"percent-encoding",
"rand 0.9.2",
"rustc_version_runtime",
"rustls",
"rustversion",
"serde",
"serde_bytes",
"serde_with",
"sha1 0.10.6",
"sha2 0.10.9",
"sha1 0.11.0",
"sha2 0.11.1",
"socket2 0.6.2",
"stringprep",
"strsim",
@@ -3653,9 +3761,9 @@ dependencies = [
[[package]]
name = "mongodb-internal-macros"
version = "3.6.0"
version = "3.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e5758dc828eb2d02ec30563cba365609d56ddd833190b192beaee2b475a7bb3"
checksum = "995f1171fab2a793f15afd0e9ba1d84116a9411ff8e3467fe9c167462435033d"
dependencies = [
"macro_magic",
"proc-macro2",
@@ -3710,7 +3818,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"
dependencies = [
"bitflags",
"jni-sys",
"jni-sys 0.3.0",
"log",
"ndk-sys",
"num_enum",
@@ -3730,7 +3838,7 @@ version = "0.6.0+11769913"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873"
dependencies = [
"jni-sys",
"jni-sys 0.3.0",
]
[[package]]
@@ -3960,15 +4068,14 @@ checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
[[package]]
name = "openssl"
version = "0.10.75"
version = "0.10.82"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08838db121398ad17ab8531ce9de97b244589089e290a384c900cb9ff7434328"
checksum = "4de8111e94a56adca7ebfe6c365b6d42f99deb69b74b6becacd4204e2f193aa2"
dependencies = [
"bitflags",
"cfg-if",
"foreign-types",
"libc",
"once_cell",
"openssl-macros",
"openssl-sys",
]
@@ -3998,9 +4105,9 @@ checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
[[package]]
name = "openssl-sys"
version = "0.9.111"
version = "0.9.118"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82cab2d520aa75e3c58898289429321eb788c3106963d0dc886ec7a5f4adc321"
checksum = "19c413d6ec9ebaf5e1c829d355cb3e9f783778d700f135be0921d52fce3c60ae"
dependencies = [
"cc",
"libc",
@@ -4152,15 +4259,6 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b867cad97c0791bbd3aaa6472142568c6c9e8f71937e98379f584cfb0cf35bec"
[[package]]
name = "pbkdf2"
version = "0.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"
dependencies = [
"digest 0.10.7",
]
[[package]]
name = "pbkdf2"
version = "0.13.0"
@@ -4197,6 +4295,15 @@ dependencies = [
"indexmap",
]
[[package]]
name = "phf"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7"
dependencies = [
"phf_shared 0.12.1",
]
[[package]]
name = "phf"
version = "0.13.1"
@@ -4204,7 +4311,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"
dependencies = [
"phf_macros",
"phf_shared",
"phf_shared 0.13.1",
"serde",
]
@@ -4215,7 +4322,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1"
dependencies = [
"phf_generator",
"phf_shared",
"phf_shared 0.13.1",
]
[[package]]
@@ -4225,7 +4332,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"
dependencies = [
"fastrand",
"phf_shared",
"phf_shared 0.13.1",
]
[[package]]
@@ -4235,12 +4342,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"
dependencies = [
"phf_generator",
"phf_shared",
"phf_shared 0.13.1",
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "phf_shared"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981"
dependencies = [
"siphasher",
]
[[package]]
name = "phf_shared"
version = "0.13.1"
@@ -4342,6 +4458,17 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
[[package]]
name = "prefix-trie"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cf6e3177f0684016a5c209b00882e15f8bdd3f3bb48f0491df10cd102d0c6e7"
dependencies = [
"either",
"ipnet",
"num-traits",
]
[[package]]
name = "prettyplease"
version = "0.2.37"
@@ -4767,18 +4894,20 @@ dependencies = [
[[package]]
name = "rmcp"
version = "0.16.0"
version = "3.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4c9c94680f75470ee8083a0667988b5d7b5beb70b9f998a8e51de7c682ce60"
checksum = "d24a7e92f4bcaa36b97fa93c4fa7ca8f3e669eced949345b3462dba333c7f909"
dependencies = [
"async-trait",
"base64 0.22.1",
"base64 0.23.1",
"bytes",
"chrono",
"futures",
"http",
"http-body",
"http-body-util",
"indexmap",
"libc",
"pastey",
"pin-project-lite",
"rand 0.10.3",
@@ -4786,6 +4915,7 @@ dependencies = [
"schemars",
"serde",
"serde_json",
"sha2 0.11.1",
"sse-stream",
"thiserror 2.0.18",
"tokio",
@@ -4798,15 +4928,15 @@ dependencies = [
[[package]]
name = "rmcp-macros"
version = "0.16.0"
version = "3.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90c23c8f26cae4da838fbc3eadfaecf2d549d97c04b558e7bd90526a9c28b42a"
checksum = "b3140f24a766f80f9ec1607bde85680959a69b83d46fa9ce87dadab7e67ab029"
dependencies = [
"darling 0.23.0",
"darling 0.24.1",
"proc-macro2",
"quote",
"serde_json",
"syn 2.0.117",
"syn 3.0.9",
]
[[package]]
@@ -5028,7 +5158,7 @@ dependencies = [
"derive_more",
"log",
"new_debug_unreachable",
"phf",
"phf 0.13.1",
"phf_codegen",
"precomputed-hash",
"rustc-hash 2.1.1",
@@ -5302,6 +5432,22 @@ version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2"
[[package]]
name = "simd_cesu8"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"
dependencies = [
"rustc_version",
"simdutf8",
]
[[package]]
name = "simdutf8"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
[[package]]
name = "simple_asn1"
version = "0.6.4"
@@ -5429,9 +5575,9 @@ checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
[[package]]
name = "sse-stream"
version = "0.2.1"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb4dc4d33c68ec1f27d386b5610a351922656e1fdf5c05bbaad930cd1519479a"
checksum = "c25ac7aff0abd1dbc474536e40416e1102c7dd9bfba0b9861c6d357f835dcfb4"
dependencies = [
"bytes",
"futures-util",
@@ -5460,7 +5606,7 @@ checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901"
dependencies = [
"new_debug_unreachable",
"parking_lot",
"phf_shared",
"phf_shared 0.13.1",
"precomputed-hash",
]
@@ -5471,7 +5617,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69"
dependencies = [
"phf_generator",
"phf_shared",
"phf_shared 0.13.1",
"proc-macro2",
"quote",
]
@@ -6879,7 +7025,7 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57a9779e9f04d2ac1ce317aee707aa2f6b773afba7b931222bff6983843b1576"
dependencies = [
"phf",
"phf 0.13.1",
"phf_codegen",
"string_cache",
"string_cache_codegen",
@@ -7595,7 +7741,7 @@ dependencies = [
"lzma-rust2",
"memchr",
"nix",
"pbkdf2 0.13.0",
"pbkdf2",
"ppmd-rust",
"sha1 0.11.0",
"time",
+3
View File
@@ -5,6 +5,9 @@ RUN cargo install dioxus-cli --version 0.7.3 --locked
# Legal pages linked from the sidebar; the defaults are breakpilot.com's.
ARG IMPRINT_URL=https://breakpilot.com/impressum
ARG PRIVACY_URL=https://breakpilot.com/datenschutz
# The release telemetry reports as service.version (CI passes the latest
# release tag); empty falls back to the crate version.
ARG PRUEFWERK_VERSION=
WORKDIR /app
COPY . .
+2
View File
@@ -33,6 +33,8 @@ tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
chrono = { workspace = true }
# Calendar days and months of metering in Europe/Berlin (t72).
chrono-tz = "0.10"
mongodb = { workspace = true }
reqwest = { workspace = true }
thiserror = { workspace = true }
+134 -5
View File
@@ -13,6 +13,12 @@ use crate::registry::RegistryClient;
use crate::scan_gate::{Admission, HeldTarget, ScanGate};
use crate::secrets::SecretBox;
/// A target whose billing changed, with its new billing (t72).
pub type BillingChange = (
mongodb::bson::oid::ObjectId,
compliance_core::models::TargetBilling,
);
/// Default maximum concurrent pentest sessions.
const DEFAULT_MAX_CONCURRENT_SESSIONS: usize = 5;
@@ -133,6 +139,19 @@ impl ComplianceAgent {
metric: &str,
key: String,
properties: serde_json::Value,
) {
self.emit_usage_quantity(tenant_id, metric, key, 1.0, properties);
}
/// [`Self::emit_usage`] with a `quantity` other than one, such as the
/// month's peak of extra targets (t72).
pub fn emit_usage_quantity(
&self,
tenant_id: &str,
metric: &str,
key: String,
quantity: f64,
properties: serde_json::Value,
) {
let Some(registry) = self.registry.clone() else {
return;
@@ -142,7 +161,7 @@ impl ComplianceAgent {
tenant_id: tenant_id.to_string(),
product: registry.product().to_string(),
metric: metric.to_string(),
quantity: 1.0,
quantity,
occurred_at: chrono::Utc::now().to_rfc3339(),
properties: Some(properties),
};
@@ -153,6 +172,95 @@ impl ComplianceAgent {
});
}
/// Store which of the tenant's targets are the plan's included ones and
/// which are extra (t72), from the plan's `included_targets`. Without a
/// registry every target is included. Best-effort: when the plan cannot
/// be read or the targets not updated, the stored split stays.
///
/// # Returns
///
/// The targets whose billing changed, with their new billing.
pub async fn refresh_billing(
&self,
tenant_id: &str,
db: &crate::database::Database,
) -> Vec<BillingChange> {
match self.plan(tenant_id).await {
Some(plan) => {
self.assign_billing(tenant_id, db, plan.included_targets)
.await
}
None => Vec::new(),
}
}
/// The tenant's plan for metering (t72), from its entitlement; without
/// a registry, no limits at all. `None` when the registry did not
/// answer: then the stored billing stays, and counted Prüfungen are
/// neither checked nor charged.
pub async fn plan(&self, tenant_id: &str) -> Option<crate::metering::Plan> {
let Some(registry) = &self.registry else {
return Some(crate::metering::Plan::default());
};
match registry.check_entitlement(tenant_id, None, None).await {
Ok(check) => Some(crate::metering::Plan {
included_targets: check.included_targets(),
limits: check.plan_limits(),
}),
Err(e) => {
tracing::warn!(tenant_id, "plan not read, metering waits: {e}");
None
}
}
}
/// Store the billing of the tenant's targets for a plan that includes
/// `included` targets; best-effort.
async fn assign_billing(
&self,
tenant_id: &str,
db: &crate::database::Database,
included: Option<u32>,
) -> Vec<BillingChange> {
let changes = match crate::metering::assign_billing(db, included).await {
Ok(changes) => {
if !changes.is_empty() {
tracing::info!(tenant_id, changed = changes.len(), "target billing updated");
}
changes
}
Err(e) => {
tracing::warn!(tenant_id, "target billing not updated: {e}");
return Vec::new();
}
};
self.report_extra_peak(tenant_id, db).await;
changes
}
/// Send the month's peak of extra targets as `target.extra` when it
/// rose, and once a day besides (t72). The key carries the peak, so the
/// registry keeps every rise and drops the daily re-send as a duplicate;
/// billing takes the highest quantity per tenant-month. Count only: no
/// target names leave Prüfwerk. Best-effort.
async fn report_extra_peak(&self, tenant_id: &str, db: &crate::database::Database) {
let now = chrono::Utc::now();
match crate::metering::record_extra_peak(db, now).await {
Ok(Some(peak)) => {
let (month, _) = crate::metering::berlin_period(now);
self.emit_usage_quantity(
tenant_id,
"target.extra",
format!("target-extra:{tenant_id}:{month}:{peak}"),
f64::from(peak),
serde_json::json!({ "month": month }),
);
}
Ok(None) => {}
Err(e) => tracing::warn!(tenant_id, "extra targets not recorded: {e}"),
}
}
/// Scan a target, through the [`ScanGate`]: at most `SCAN_CONCURRENCY` scans
/// run at once, and a request for a target that is already being scanned is
/// coalesced — it becomes the one pending follow-up that this task runs next,
@@ -233,21 +341,42 @@ impl ComplianceAgent {
trigger: compliance_core::models::ScanTrigger,
) -> Result<(), crate::error::AgentError> {
let db = self.db_pool.for_tenant_id(tenant_id).await?;
// Whether this target is included or extra decides whether its scan
// counts, and the plan's limits whether a counted one may run (t72).
let plan = self.plan(tenant_id).await;
if let Some(plan) = &plan {
self.assign_billing(tenant_id, &db, plan.included_targets)
.await;
}
let orchestrator =
PipelineOrchestrator::new(self.config.clone(), tenant_id, db.clone(), self.llm.clone())
.with_nuget_license_cache(self.nuget_license_cache.clone())
.with_exploit_cache(self.exploit_cache.clone())
.with_advisory_index(self.advisory_index.clone());
.with_advisory_index(self.advisory_index.clone())
.with_plan_limits(plan.map(|p| p.limits));
let started = chrono::Utc::now();
let scanned = orchestrator.run_target(target_id, trigger.clone()).await?;
let outcome = orchestrator.run_target(target_id, trigger.clone()).await?;
// Support's scans are ours, not the customer's usage; a scheduled scan
// skipped because nothing changed scanned nothing (#465).
if scanned && trigger != compliance_core::models::ScanTrigger::Support {
if outcome.scanned && trigger != compliance_core::models::ScanTrigger::Support {
self.emit_usage(
tenant_id,
"scan.completed",
format!("scan:{tenant_id}:{target_id}:{}", started.timestamp()),
serde_json::json!({ "target_id": target_id, "trigger": format!("{trigger:?}") }),
serde_json::json!({
"target_id": target_id,
"trigger": format!("{trigger:?}"),
"attribution": outcome.attribution,
"counted": outcome.chargeable,
}),
);
}
if let Some(day) = &outcome.booked_prueftag {
self.emit_usage(
tenant_id,
"prueftag.booked",
format!("prueftag:{tenant_id}:{target_id}:{day}"),
serde_json::json!({ "target_id": target_id, "day": day }),
);
}
self.notify_new_findings(tenant_id, target_id, &db, started);
@@ -999,6 +999,30 @@ pub async fn detect_target(
}))
}
/// Why a scan is asked for (`POST /api/v1/targets/{id}/scan?reason=…`).
#[derive(Debug, Default, serde::Deserialize)]
pub struct ScanReason {
/// `new_content` after the customer created the target or uploaded
/// files (t72): it runs only when something changed, as a change-driven
/// Prüfung. Absent: the customer asks for a Prüfung, which always runs
/// and counts.
#[serde(default)]
pub reason: Option<String>,
}
/// The trigger of a scan the customer (`staff: false`) or support asked
/// for, for `reason`. Support's scans are never the customer's usage.
fn requested_trigger(staff: bool, reason: Option<&str>) -> compliance_core::models::ScanTrigger {
use compliance_core::models::ScanTrigger;
if staff {
ScanTrigger::Support
} else if reason == Some("new_content") {
ScanTrigger::NewContent
} else {
ScanTrigger::Manual
}
}
/// POST /api/v1/targets/{id}/scan — trigger a scan for the target.
///
/// Dispatches to the unified pipeline when `UNIFIED_PIPELINE` is set (else the
@@ -1008,6 +1032,7 @@ pub async fn trigger_target_scan(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
Query(reason): Query<ScanReason>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let oid = parse_oid(&id)?;
let db = tenant_db(&agent, &tenant).await?;
@@ -1024,12 +1049,7 @@ pub async fn trigger_target_scan(
let agent_clone = (*agent).clone();
let tenant_id = tenant.0.tenant_id.clone();
// A scan support starts is not the customer's usage.
let trigger = if tenant.0.staff.is_some() {
compliance_core::models::ScanTrigger::Support
} else {
compliance_core::models::ScanTrigger::Manual
};
let trigger = requested_trigger(tenant.0.staff.is_some(), reason.reason.as_deref());
tokio::spawn(async move {
// Always the unified target pipeline — this endpoint is about an
// onboarded target by construction, independent of the global
@@ -1045,6 +1065,22 @@ pub async fn trigger_target_scan(
mod filter_tests {
use super::*;
#[test]
fn a_scan_asked_for_new_content_is_change_driven() {
use compliance_core::models::ScanTrigger;
assert_eq!(requested_trigger(false, None), ScanTrigger::Manual);
assert_eq!(
requested_trigger(false, Some("new_content")),
ScanTrigger::NewContent
);
assert_eq!(requested_trigger(false, Some("other")), ScanTrigger::Manual);
assert_eq!(
requested_trigger(true, Some("new_content")),
ScanTrigger::Support,
"support's scans are never the customer's usage"
);
}
#[test]
fn a_project_filter_matches_its_targets() {
let filter = TargetFilter {
+2 -31
View File
@@ -18,6 +18,8 @@ use mongodb::bson::{doc, Document};
use serde::{Deserialize, Serialize};
use compliance_core::auth::{validate_service_token, JwksState};
// Re-exported: the VEX, evidence and change-detection code import them from here.
pub use compliance_core::build_info::{BUILD_COMMIT, BUILD_VERSION};
use crate::agent::ComplianceAgent;
@@ -432,23 +434,6 @@ pub async fn usage(
}))
}
/// The build version: `PRUEFWERK_VERSION` at compile time (CI: the latest
/// release tag without its `v`), else the crate version.
pub const BUILD_VERSION: &str =
non_empty_or(option_env!("PRUEFWERK_VERSION"), env!("CARGO_PKG_VERSION"));
/// The commit the build is from: `PRUEFWERK_COMMIT` at compile time (CI:
/// the full SHA), else "unknown". The portal's version line shows 8 characters.
pub const BUILD_COMMIT: &str = non_empty_or(option_env!("PRUEFWERK_COMMIT"), "unknown");
/// A Docker build arg left empty is an empty env var, not an unset one.
const fn non_empty_or(value: Option<&'static str>, fallback: &'static str) -> &'static str {
match value {
Some(v) if !v.is_empty() => v,
_ => fallback,
}
}
/// `GET /api/v1/platform/version` — contract handshake (§4.1 /version).
pub async fn version(State(st): State<PlatformState>) -> Json<serde_json::Value> {
Json(serde_json::json!({
@@ -807,20 +792,6 @@ pub async fn delete_git_source(
})))
}
#[cfg(test)]
mod build_info_tests {
use super::*;
#[test]
fn an_unset_or_empty_build_value_falls_back() {
assert_eq!(non_empty_or(None, "0.4.4"), "0.4.4");
assert_eq!(non_empty_or(Some(""), "unknown"), "unknown");
assert_eq!(non_empty_or(Some("0.4.5"), "0.4.4"), "0.4.5");
assert!(!BUILD_VERSION.is_empty());
assert!(!BUILD_COMMIT.is_empty());
}
}
#[cfg(test)]
mod target_count_tests {
use super::*;
+6
View File
@@ -42,6 +42,11 @@ pub enum AgentError {
#[error("the archive password set on the target does not open it")]
ArchivePasswordWrong,
/// A counted Prüfung the plan does not allow now (t72): not an error of
/// the scan, which ends without scanning.
#[error("not run: {0:?}")]
NotAdmitted(compliance_core::models::Refusal),
#[error("{0}")]
Other(String),
}
@@ -73,6 +78,7 @@ impl AgentError {
| Self::Config(_)
| Self::Secret(_)
| Self::Exec(_)
| Self::NotAdmitted(_)
| Self::Other(_) => (
RunErrorCode::Internal,
"the scan stopped because of an internal error",
+1
View File
@@ -17,6 +17,7 @@ pub mod ingest;
pub mod license_conclusions;
pub mod lifecycle;
pub mod llm;
pub mod metering;
pub mod pentest;
pub mod pipeline;
pub mod rag;
+383
View File
@@ -0,0 +1,383 @@
//! Metering of a tenant's Prüfungen (t72).
//!
//! **Included and extra targets.** The oldest active targets are included,
//! up to the plan's `included_targets`; every other active target is extra.
//! The split is stored on each target ([`OnboardedTarget::billing`]) and
//! brought up to date before each scan and when a target is created, so
//! archiving an included target moves the oldest extra one up.
//!
//! **Counters.** A counted Prüfung is checked against the plan when it
//! starts ([`usage`] and [`compliance_core::models::admit`]) and charged
//! when it completes ([`charge`]): to the month's quota, else to the
//! target's Prüftag for the day, booking one if none is. Months and days
//! are calendar ones in Europe/Berlin. A run that fails because of us is
//! never charged, so nothing is refunded.
//!
//! [`OnboardedTarget::billing`]: compliance_core::models::OnboardedTarget::billing
use chrono::{DateTime, Utc};
use futures_util::TryStreamExt;
use mongodb::bson::{doc, oid::ObjectId, Document};
use compliance_core::models::{
split_included, BillableTarget, DayUsage, MonthUsage, PlanLimits, RunCharge, TargetBilling,
};
use crate::database::Database;
use crate::error::AgentError;
/// Store the billing of the tenant's active targets for a plan that
/// includes `included` targets.
///
/// # Arguments
///
/// * `db` - The tenant's database.
/// * `included` - How many targets the plan includes; `None` is unlimited.
///
/// # Returns
///
/// The targets whose billing changed, with their new billing.
///
/// # Errors
///
/// Returns an error if the targets cannot be read or updated.
pub async fn assign_billing(
db: &Database,
included: Option<u32>,
) -> Result<Vec<(ObjectId, TargetBilling)>, AgentError> {
// Only the three fields the split needs: a whole target holds its
// artifacts, and older documents may lack fields the model requires.
let docs: Vec<Document> = db
.raw_collection("onboarded_targets")
.find(doc! { "archived_at": null })
.projection(doc! { "_id": 1, "created_at": 1, "billing": 1 })
.await?
.try_collect()
.await?;
let targets: Vec<BillableTarget<ObjectId>> = docs.iter().filter_map(billable).collect();
let changes = split_included(&targets, included);
for wanted in [TargetBilling::Included, TargetBilling::Extra] {
let ids: Vec<ObjectId> = changes
.iter()
.filter(|(_, billing)| *billing == wanted)
.map(|(id, _)| *id)
.collect();
if ids.is_empty() {
continue;
}
let value =
mongodb::bson::to_bson(&wanted).map_err(|e| AgentError::Other(e.to_string()))?;
db.onboarded_targets()
.update_many(
doc! { "_id": { "$in": ids } },
doc! { "$set": { "billing": value } },
)
.await?;
}
Ok(changes)
}
/// A stored target as the split sees it; `None` without an id. A target
/// without a creation time counts as the oldest, one without a billing as
/// included (stored before metering).
fn billable(target: &Document) -> Option<BillableTarget<ObjectId>> {
Some(BillableTarget {
id: target.get_object_id("_id").ok()?,
created_at: target
.get_datetime("created_at")
.map_or(DateTime::<Utc>::MIN_UTC, |at| at.to_chrono()),
billing: target
.get("billing")
.and_then(|b| mongodb::bson::from_bson(b.clone()).ok())
.unwrap_or_default(),
})
}
/// The tenant's plan as metering reads it from the registry.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Plan {
/// How many targets the plan includes; `None` is unlimited.
pub included_targets: Option<u32>,
/// The quota and the customer's Prüftag cap.
pub limits: PlanLimits,
}
/// The tenant's counted Prüfungen and booked Prüftage per month.
const MONTHS: &str = "metering_months";
/// Each target's Prüftag per day, once the quota was used up.
const DAYS: &str = "metering_days";
/// The calendar month and day of `at` in Europe/Berlin, as `YYYY-MM` and
/// `YYYY-MM-DD`: the periods the contract counts in.
pub fn berlin_period(at: DateTime<Utc>) -> (String, String) {
let local = at.with_timezone(&chrono_tz::Europe::Berlin);
(
local.format("%Y-%m").to_string(),
local.format("%Y-%m-%d").to_string(),
)
}
/// The id of a target's counter for one day.
fn day_id(target_id: &str, day: &str) -> String {
format!("{target_id}:{day}")
}
/// A stored counter as a `u32`; missing or negative reads as 0.
fn count(document: Option<&Document>, field: &str) -> u32 {
document
.and_then(|d| d.get(field))
.and_then(mongodb::bson::Bson::as_i64)
.or_else(|| document.and_then(|d| d.get_i32(field).ok()).map(i64::from))
.and_then(|n| u32::try_from(n).ok())
.unwrap_or(0)
}
/// What the tenant used this month and `target_id` today, at `at`.
///
/// # Errors
///
/// Returns an error if the counters cannot be read.
pub async fn usage(
db: &Database,
target_id: &str,
at: DateTime<Utc>,
) -> Result<(MonthUsage, DayUsage), AgentError> {
let (month, day) = berlin_period(at);
let month_doc = db
.raw_collection(MONTHS)
.find_one(doc! { "_id": &month })
.await?;
let day_doc = db
.raw_collection(DAYS)
.find_one(doc! { "_id": day_id(target_id, &day) })
.await?;
Ok((
MonthUsage {
pruefungen: count(month_doc.as_ref(), "pruefungen"),
prueftage: count(month_doc.as_ref(), "prueftage"),
},
DayUsage {
prueftag_booked: day_doc
.as_ref()
.and_then(|d| d.get_bool("prueftag_booked").ok())
.unwrap_or(false),
prueftag_pruefungen: count(day_doc.as_ref(), "prueftag_pruefungen"),
},
))
}
/// What [`charge`] charged a completed Prüfung to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Charged {
/// The quota or the target's Prüftag.
pub charge: RunCharge,
/// The Berlin day (`YYYY-MM-DD`) of a Prüftag this Prüfung booked; it
/// goes to the registry as `prueftag.booked`.
pub booked_prueftag: Option<String>,
}
/// Charge one completed, counted Prüfung on `target_id` at `at`: to the
/// month's quota while it lasts, else to the target's Prüftag that day,
/// booking it if none is. The start of the run checked the limits, so this
/// never refuses; scans of several targets finishing at once can take the
/// quota or a Prüftag over by the ones that raced.
///
/// # Errors
///
/// Returns an error if the counters cannot be written.
pub async fn charge(
db: &Database,
target_id: &str,
limits: PlanLimits,
at: DateTime<Utc>,
) -> Result<Charged, AgentError> {
let (month, day) = berlin_period(at);
let months = db.raw_collection(MONTHS);
months
.update_one(
doc! { "_id": &month },
doc! { "$setOnInsert": { "pruefungen": 0_i64, "prueftage": 0_i64 } },
)
.upsert(true)
.await?;
let quota_filter = match limits.monthly_pruefungen {
// `$not $gte` also matches a month document without the counter.
Some(quota) => doc! {
"_id": &month,
"pruefungen": { "$not": { "$gte": i64::from(quota) } },
},
None => doc! { "_id": &month },
};
let in_quota = months
.update_one(quota_filter, doc! { "$inc": { "pruefungen": 1_i64 } })
.await?;
if in_quota.matched_count == 1 {
return Ok(Charged {
charge: RunCharge::Quota,
booked_prueftag: None,
});
}
let days = db.raw_collection(DAYS);
let id = day_id(target_id, &day);
days.update_one(
doc! { "_id": &id },
doc! { "$setOnInsert": {
"target_id": target_id,
"day": &day,
"month": &month,
"prueftag_booked": false,
"prueftag_pruefungen": 0_i64,
} },
)
.upsert(true)
.await?;
let booked = days
.update_one(
doc! { "_id": &id, "prueftag_booked": false },
doc! { "$set": { "prueftag_booked": true, "prueftag_pruefungen": 1_i64 } },
)
.await?;
if booked.matched_count == 1 {
months
.update_one(
doc! { "_id": &month },
doc! { "$inc": { "prueftage": 1_i64 } },
)
.await?;
return Ok(Charged {
charge: RunCharge::Prueftag,
booked_prueftag: Some(day),
});
}
days.update_one(
doc! { "_id": &id },
doc! { "$inc": { "prueftag_pruefungen": 1_i64 } },
)
.await?;
Ok(Charged {
charge: RunCharge::Prueftag,
booked_prueftag: None,
})
}
/// Record how many of the tenant's active targets are extra at `at`, as
/// the month's peak (t72): the 5,99 € line bills the highest number of
/// extra targets at once in the calendar month (Europe/Berlin).
///
/// # Returns
///
/// The month's peak when it goes to the registry as `target.extra`: when it
/// rose, and once a day besides (a re-send the registry drops as a
/// duplicate of its key). `None` otherwise, and while no target was extra.
///
/// # Errors
///
/// Returns an error if the targets or the month's counters cannot be read
/// or written.
pub async fn record_extra_peak(
db: &Database,
at: DateTime<Utc>,
) -> Result<Option<u32>, AgentError> {
let extra = mongodb::bson::to_bson(&TargetBilling::Extra)
.map_err(|e| AgentError::Other(e.to_string()))?;
let now = db
.onboarded_targets()
.count_documents(doc! { "archived_at": null, "billing": extra })
.await?;
let now = u32::try_from(now).unwrap_or(u32::MAX);
let (month, day) = berlin_period(at);
let months = db.raw_collection(MONTHS);
// The document before the update: the peak and the day it was last sent.
let before = months
.find_one_and_update(
doc! { "_id": &month },
doc! {
"$max": { "extra_peak": i64::from(now) },
"$setOnInsert": { "pruefungen": 0_i64, "prueftage": 0_i64 },
},
)
.upsert(true)
.await?;
let previous = count(before.as_ref(), "extra_peak");
let sent_on = before
.as_ref()
.and_then(|d| d.get_str("extra_sent_on").ok());
let peak = previous.max(now);
if peak == 0 || (peak == previous && sent_on == Some(day.as_str())) {
return Ok(None);
}
months
.update_one(
doc! { "_id": &month },
doc! { "$set": { "extra_sent_on": &day } },
)
.await?;
Ok(Some(peak))
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::TimeZone;
#[test]
fn periods_are_calendar_ones_in_berlin() {
let at = |y, m, d, h, min| {
Utc.with_ymd_and_hms(y, m, d, h, min, 0)
.single()
.expect("valid")
};
// 23:30 UTC on 31 Oct is already 1 Nov in Berlin (CET, UTC+1).
assert_eq!(
berlin_period(at(2026, 10, 31, 23, 30)),
("2026-11".to_string(), "2026-11-01".to_string())
);
// In summer (CEST, UTC+2) the day turns at 22:00 UTC.
assert_eq!(berlin_period(at(2026, 7, 14, 21, 59)).1, "2026-07-14");
assert_eq!(berlin_period(at(2026, 7, 14, 22, 0)).1, "2026-07-15");
}
#[test]
fn a_counter_reads_as_zero_when_missing() {
let stored = doc! { "pruefungen": 7_i64, "small": 3_i32, "negative": -1_i64 };
assert_eq!(count(Some(&stored), "pruefungen"), 7);
assert_eq!(count(Some(&stored), "small"), 3);
assert_eq!(count(Some(&stored), "negative"), 0);
assert_eq!(count(Some(&stored), "absent"), 0);
assert_eq!(count(None, "pruefungen"), 0);
}
#[test]
fn a_stored_target_reads_with_defaults_for_what_it_lacks() {
// Arrange
let id = ObjectId::new();
let at = mongodb::bson::DateTime::from_millis(1_700_000_000_000);
let extra = doc! { "_id": id, "created_at": at, "billing": "extra" };
let old = doc! { "_id": id };
// Act
let extra = billable(&extra);
let old = billable(&old);
// Assert
assert_eq!(
extra,
Some(BillableTarget {
id,
created_at: at.to_chrono(),
billing: TargetBilling::Extra,
})
);
assert_eq!(
old,
Some(BillableTarget {
id,
created_at: DateTime::<Utc>::MIN_UTC,
billing: TargetBilling::Included,
})
);
assert_eq!(billable(&doc! { "name": "no id" }), None);
}
}
+43
View File
@@ -70,6 +70,22 @@ pub fn uploads_allow_git_skip(target: &OnboardedTarget) -> bool {
upload_skip_enabled() && uploads_match(target)
}
/// Whether a file uploaded to `target` changed since its last completed
/// scan: it has uploads, and they are not the ones that scan read. For
/// metering (t72), independent of [`upload_skip_enabled`].
pub fn uploads_changed(target: &OnboardedTarget) -> bool {
target.artifacts.iter().any(is_upload) && !uploads_match(target)
}
/// Whether the customer changed what `target`, which has no git repository,
/// gives a scan to read since its last completed one: it was never scanned,
/// its uploads changed, or it has a live URL (the service changes on its
/// own). A scheduled scan that runs without such a change is our own rescan
/// (t72).
pub fn content_changed(target: &OnboardedTarget) -> bool {
target.live_url().is_some() || target.last_scan.is_none() || uploads_changed(target)
}
/// Whether the uploads of `target` are the ones its last completed scan read.
fn uploads_match(target: &OnboardedTarget) -> bool {
target
@@ -219,4 +235,31 @@ mod tests {
let unhashed = target(vec![upload("a", None)]);
assert_eq!(upload_inputs(&unhashed), None);
}
#[test]
fn only_a_change_the_customer_made_is_a_content_change() {
// Arrange: a target scanned once, by an older build.
let mut t = target(vec![upload("a", Some("h1"))]);
assert!(content_changed(&t), "never scanned");
t.last_scan = Some(LastScan {
build: "0.0.1+old".into(),
inputs: upload_inputs(&t),
});
// Act / Assert: a new build alone is no change of the customer's.
assert!(!content_changed(&t));
assert!(!uploads_changed(&t));
t.artifacts[0].content_hash = Some("h2".into());
assert!(content_changed(&t), "another upload");
assert!(uploads_changed(&t));
let mut live = target(vec![Artifact::live_url("https://pump.example.com")]);
live.last_scan = Some(LastScan {
build: build_id(),
inputs: None,
});
assert!(content_changed(&live), "a live service changes on its own");
assert!(!uploads_changed(&live), "nothing uploaded");
}
}
+35 -12
View File
@@ -782,12 +782,24 @@ impl RunFindings {
Ok(closed)
}
/// Close the undecided findings of `scanner` on target `target_id` whose
/// file lies in the excluded paths or the test data this run left out
/// Close the undecided findings on target `target_id` whose file lies in
/// the excluded paths or the test data this run left out
/// ([`Self::with_excluded`], [`Self::with_test_data`]), each with its
/// reason. For a stage that stores its findings without this object (the
/// PLC analysis), so nothing it no longer sees is closed as fixed; only
/// what was left out.
/// reason. Nothing is closed as fixed; only what was left out.
///
/// [`Self::resolve_missing`] only closes what a scanner that completed no
/// longer reports. A scanner that did not run cannot close its findings in
/// a left-out path, although nothing can see them any more: cppcheck runs
/// only on a tree with C, so once a fixture held the tree's only C, its
/// findings would stay open for good. This closes them, whichever scanner
/// stored them. A finding this run reported again is kept.
///
/// # Arguments
///
/// * `db` - the tenant database
/// * `target_id` - the scanned target (`Finding::repo_id`)
/// * `scanner` - only this scanner's findings (a stage that stores its
/// findings without this object, the PLC analysis), or `None` for all
///
/// # Returns
///
@@ -800,20 +812,23 @@ impl RunFindings {
&mut self,
db: &Database,
target_id: &str,
scanner: &str,
scanner: Option<&str>,
) -> Result<u32, AgentError> {
if self.excluded.is_empty() && self.test_data.is_empty() {
return Ok(0);
}
let mut filter = doc! {
"repo_id": target_id,
"status": { "$in": UNDECIDED.to_vec() },
};
if let Some(scanner) = scanner {
filter.insert("scanner", scanner);
}
let rows: Vec<Document> = db
.findings()
.clone_with_type::<Document>()
.find(doc! {
"repo_id": target_id,
"scanner": scanner,
"status": { "$in": UNDECIDED.to_vec() },
})
.projection(doc! { "file_path": 1 })
.find(filter)
.projection(doc! { "fingerprint": 1, "file_path": 1 })
.await?
.try_collect()
.await?;
@@ -822,6 +837,14 @@ impl RunFindings {
let (Ok(id), Ok(file)) = (row.get_object_id("_id"), row.get_str("file_path")) else {
continue;
};
// Something in this run still reports it, so it is not left out:
// closing it would only see it reopened by the next run.
let reported = row
.get_str("fingerprint")
.is_ok_and(|fp| self.inserted.contains_key(fp) || self.earlier.contains(fp));
if reported {
continue;
}
if crate::pipeline::vendor::in_vendor_dir(file, &self.excluded) {
excluded.push(id);
} else if crate::pipeline::vendor::in_vendor_dir(file, &self.test_data) {
+289 -37
View File
@@ -37,6 +37,20 @@ pub struct GraphContext {
pub impacts: Vec<compliance_core::models::graph::ImpactAnalysis>,
}
/// How a scan of an onboarded target went, for its usage events (t72).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TargetScanOutcome {
/// `false` when it was skipped because nothing changed (#465), or the
/// plan did not allow it now.
pub scanned: bool,
/// Why it ran; `None` when it was skipped.
pub attribution: Option<ScanAttribution>,
/// Whether it counts toward the customer's usage.
pub chargeable: bool,
/// The Berlin day (`YYYY-MM-DD`) of a Prüftag this scan booked.
pub booked_prueftag: Option<String>,
}
/// What a scan left out of its working copy before the first stage, as
/// paths relative to the tree.
#[derive(Debug, Default)]
@@ -65,6 +79,9 @@ pub struct PipelineOrchestrator {
pub(super) exploit_cache: Option<Arc<dyn ExploitCache>>,
/// The vendor CSAF advisories (#515); none in tests.
pub(super) advisory_index: Option<Arc<dyn crate::pipeline::csaf_match::AdvisoryIndex>>,
/// The tenant's plan limits for metering (t72); `None` when not known,
/// and then counted Prüfungen are neither checked nor charged.
pub(super) plan_limits: Option<PlanLimits>,
}
impl PipelineOrchestrator {
@@ -81,9 +98,16 @@ impl PipelineOrchestrator {
nuget_license_cache: None,
exploit_cache: None,
advisory_index: None,
plan_limits: None,
}
}
/// Check and charge counted Prüfungen against `limits` (t72).
pub(crate) fn with_plan_limits(mut self, limits: Option<PlanLimits>) -> Self {
self.plan_limits = limits;
self
}
/// Cache the NuGet licenses looked up on nuget.org in `cache` (#467).
pub(crate) fn with_nuget_license_cache(mut self, cache: Arc<dyn LicenseCache>) -> Self {
self.nuget_license_cache = Some(cache);
@@ -174,25 +198,35 @@ impl PipelineOrchestrator {
// new to find; one a person started always runs (after a changed
// setting it can find something else), a new Prüfwerk build scans
// once (#465), and so does a file uploaded to the target since.
if !trigger.started_by_person()
&& repo.uploads_allow_skip
&& repo.last_scanned_build.as_deref()
== Some(crate::pipeline::change::build_id().as_str())
&& !GitOps::has_new_commits(&repo_path, repo.last_scanned_commit.as_deref())?
{
tracing::info!("[{repo_id}] No new commits, skipping scan");
self.skip_stage(
if !trigger.started_by_person() {
let new_commits =
GitOps::has_new_commits(&repo_path, repo.last_scanned_commit.as_deref())?;
if !new_commits
&& repo.uploads_allow_skip
&& repo.last_scanned_build.as_deref()
== Some(crate::pipeline::change::build_id().as_str())
{
tracing::info!("[{repo_id}] No new commits, skipping scan");
self.skip_stage(
scan_run_id,
SkippedStage::new(
"change_detection",
SkipCode::NoNewCommits,
"no new commits since the last scan",
),
)
.await;
// Findings deferred by the catch-up's cap still get their issues.
self.catch_up_unchanged(repo, &repo_id).await;
return Ok(0);
}
self.attribute_run(
scan_run_id,
SkippedStage::new(
"change_detection",
SkipCode::NoNewCommits,
"no new commits since the last scan",
),
&repo_id,
ScanAttribution::detected(trigger, new_commits || repo.changed_besides_commits),
repo.billing,
)
.await;
// Findings deferred by the catch-up's cap still get their issues.
self.catch_up_unchanged(repo, &repo_id).await;
return Ok(0);
.await?;
}
// Submodules are part of what the product ships (a HAL, an RTOS).
@@ -255,6 +289,14 @@ impl PipelineOrchestrator {
tokio::task::spawn_blocking(move || crate::pipeline::variants::app_variants(&tree))
.await
.unwrap_or_default();
// Left out of the tree, but a scanner that walks the git history
// (gitleaks) still sees what was committed there.
let left_out_dirs: Vec<String> = left_out
.excluded
.iter()
.chain(&left_out.test_data)
.cloned()
.collect();
let mut run_findings = crate::pipeline::finding_store::RunFindings::new(scan_run_id)
.with_variants(variants)
.with_tree(repo_path.clone())
@@ -293,12 +335,14 @@ impl PipelineOrchestrator {
.await;
}
// The same vendor code is left out of every code scanner's findings:
// the pattern, secret and lint scanners walk the whole tree.
// the pattern, secret and lint scanners walk the whole tree. So are the
// left-out paths, for the secret scanner, which reads the history.
let outside_vendor = |findings: &mut Vec<Finding>| {
findings.retain(|f| {
!f.file_path
.as_deref()
.is_some_and(|p| crate::pipeline::vendor::in_vendor_dir(p, &vendor))
!f.file_path.as_deref().is_some_and(|p| {
crate::pipeline::vendor::in_vendor_dir(p, &vendor)
|| crate::pipeline::vendor::in_vendor_dir(p, &left_out_dirs)
})
})
};
match SemgrepScanner::new(vendor.clone())
@@ -997,6 +1041,11 @@ impl PipelineOrchestrator {
run_findings
.resolve_missing(&self.db, &repo_id, &vendor)
.await?;
// And what an earlier scan stored in a left-out path, also of a scanner
// that did not run this time.
run_findings
.resolve_left_out(&self.db, &repo_id, None)
.await?;
// Their issues follow: closed with a comment, or reopened.
crate::pipeline::issue_sync::IssueSync {
db: self.db.clone(),
@@ -1110,8 +1159,9 @@ impl PipelineOrchestrator {
///
/// # Returns
///
/// Whether it scanned: `false` when it was skipped because nothing changed
/// since the last completed scan (a scheduled or webhook scan, #465).
/// Whether it scanned (`false` when it was skipped because nothing changed
/// since the last completed scan, a scheduled or webhook scan, #465), and
/// how it is metered (t72).
///
/// # Errors
///
@@ -1120,7 +1170,7 @@ impl PipelineOrchestrator {
&self,
target_id: &str,
trigger: ScanTrigger,
) -> Result<bool, AgentError> {
) -> Result<TargetScanOutcome, AgentError> {
let oid = mongodb::bson::oid::ObjectId::parse_str(target_id)
.map_err(|e| AgentError::Other(e.to_string()))?;
let target = self
@@ -1130,7 +1180,13 @@ impl PipelineOrchestrator {
.await?
.ok_or_else(|| AgentError::Other(format!("Onboarded target {target_id} not found")))?;
let scan_run = ScanRun::new(target_id.to_string(), trigger.clone());
let mut scan_run = ScanRun::new(target_id.to_string(), trigger.clone());
// A scan a person started is attributed from the start; change
// detection attributes the others (t72).
if let Some(attribution) = ScanAttribution::of_person(&trigger) {
scan_run.attribution = Some(attribution);
scan_run.chargeable = attribution.chargeable(target.billing);
}
let insert = self.db.scan_runs().insert_one(&scan_run).await?;
let scan_run_id = insert
.inserted_id
@@ -1138,9 +1194,20 @@ impl PipelineOrchestrator {
.map(|id| id.to_hex())
.unwrap_or_default();
let result = self
.run_target_pipeline(&target, &scan_run_id, &trigger)
.await;
// A counted Prüfung a person started is checked against the plan
// before anything runs (t72).
let admitted = if scan_run.chargeable {
self.admit_run(&scan_run_id, target_id).await
} else {
Ok(())
};
let result = match admitted {
Ok(()) => {
self.run_target_pipeline(&target, &scan_run_id, &trigger)
.await
}
Err(e) => Err(e),
};
match &result {
Ok(count) => {
let mut completed = doc! {
@@ -1191,6 +1258,23 @@ impl PipelineOrchestrator {
)
.await?;
}
// The plan does not allow it now: the run ends without scanning,
// and the target keeps what its last scan read, so the change is
// scanned once it may be.
Err(AgentError::NotAdmitted(refusal)) => {
tracing::info!(target_id, ?refusal, "counted Prüfung not run");
self.db
.scan_runs()
.update_one(
doc! { "_id": &insert.inserted_id },
doc! { "$set": {
"status": "completed",
"current_phase": "completed",
"completed_at": mongodb::bson::DateTime::now(),
} },
)
.await?;
}
Err(e) => {
tracing::error!(target_id, error = %e, "Unified scan pipeline failed");
let (code, message) = e.run_failure();
@@ -1208,16 +1292,171 @@ impl PipelineOrchestrator {
.await?;
}
}
result?;
let skipped = self
let refused = matches!(result, Err(AgentError::NotAdmitted(_)));
let invalid_input = matches!(
result,
Err(AgentError::ArchivePasswordRequired | AgentError::ArchivePasswordWrong)
);
// Read back without hiding the scan's own error behind a failed read.
let run = self
.db
.scan_runs()
.count_documents(doc! {
"_id": &insert.inserted_id,
"skipped_stages.stage": "change_detection",
})
.await?;
Ok(skipped == 0)
.find_one(doc! { "_id": &insert.inserted_id })
.await
.ok()
.flatten();
let unchanged = run.as_ref().is_some_and(|r| {
r.skipped_stages
.iter()
.any(|s| s.stage == "change_detection")
});
let chargeable = run.as_ref().is_some_and(|r| r.chargeable);
let attribution = run.and_then(|r| r.attribution);
// A counted Prüfung is charged when it completed, or when it failed on
// the customer's input; a failure of ours never is (t72).
let charged = if chargeable && ((result.is_ok() && !unchanged) || invalid_input) {
self.charge_run(&insert.inserted_id, target_id).await
} else {
None
};
if !refused {
result?;
}
Ok(TargetScanOutcome {
scanned: !refused && !unchanged,
attribution,
chargeable,
booked_prueftag: charged.and_then(|c| c.booked_prueftag),
})
}
/// Check a counted Prüfung against the plan before it scans (t72):
/// the quota, today's Prüftag on the target, the customer's cap. It runs
/// when the plan's limits or the usage are not known.
///
/// # Errors
///
/// [`AgentError::NotAdmitted`] when the plan does not allow it now; why
/// is recorded on the run.
async fn admit_run(&self, scan_run_id: &str, target_id: &str) -> Result<(), AgentError> {
let Some(limits) = self.plan_limits else {
return Ok(());
};
let (month, day) =
match crate::metering::usage(&self.db, target_id, chrono::Utc::now()).await {
Ok(usage) => usage,
Err(e) => {
tracing::warn!(target_id, "usage not read, the Prüfung runs: {e}");
return Ok(());
}
};
let Admission::Refused(refusal) = admit(limits, month, day) else {
return Ok(());
};
let (code, reason) = match refusal {
Refusal::DailyLimit => (
SkipCode::PrueftagLimitReached,
"the quota is used up and today's Prüftag on the target has had its Prüfungen",
),
Refusal::PrueftagCap => (
SkipCode::PrueftagCapReached,
"the quota is used up and the customer's Prüftag limit is reached",
),
};
self.skip_stage(scan_run_id, SkippedStage::new("metering", code, reason))
.await;
Err(AgentError::NotAdmitted(refusal))
}
/// Charge the completed, counted run `run_id` on `target_id` and record
/// what it was charged to (t72). Nothing is charged when the plan's
/// limits are not known. Best-effort: a counter that cannot be written is
/// logged.
async fn charge_run(
&self,
run_id: &mongodb::bson::Bson,
target_id: &str,
) -> Option<crate::metering::Charged> {
let limits = self.plan_limits?;
match crate::metering::charge(&self.db, target_id, limits, chrono::Utc::now()).await {
Ok(charged) => {
if let Ok(value) = mongodb::bson::to_bson(&charged.charge) {
if let Err(e) = self
.db
.scan_runs()
.update_one(
doc! { "_id": run_id.clone() },
doc! { "$set": { "charge": value } },
)
.await
{
tracing::warn!(target_id, "charge not recorded on the run: {e}");
}
}
Some(charged)
}
Err(e) => {
tracing::warn!(target_id, "Prüfung not charged: {e}");
None
}
}
}
/// Record why the run `scan_run_id` on `target_id` runs and whether it
/// counts, on a target billed as `billing`, and check a counted one
/// against the plan (t72). A run with several code artifacts is
/// attributed once per artifact; a change found in any of them wins over
/// our rescan. The record is best-effort, like [`Self::skip_stage`].
///
/// # Errors
///
/// [`AgentError::NotAdmitted`] when the plan does not allow a counted
/// Prüfung now.
async fn attribute_run(
&self,
scan_run_id: &str,
target_id: &str,
attribution: ScanAttribution,
billing: TargetBilling,
) -> Result<(), AgentError> {
let chargeable = attribution.chargeable(billing);
self.record_attribution(scan_run_id, attribution, chargeable)
.await;
if chargeable {
self.admit_run(scan_run_id, target_id).await?;
}
Ok(())
}
/// Store `attribution` and `chargeable` on the run, unless it already
/// reads as a change.
async fn record_attribution(
&self,
scan_run_id: &str,
attribution: ScanAttribution,
chargeable: bool,
) {
let Ok(oid) = mongodb::bson::oid::ObjectId::parse_str(scan_run_id) else {
return;
};
let Ok(value) = mongodb::bson::to_bson(&attribution) else {
return;
};
let change = mongodb::bson::to_bson(&ScanAttribution::Change).unwrap_or_default();
if let Err(e) = self
.db
.scan_runs()
.update_one(
doc! { "_id": oid, "attribution": { "$ne": change } },
doc! { "$set": {
"attribution": value,
"chargeable": chargeable,
} },
)
.await
{
tracing::warn!(scan_run_id, "scan run not attributed: {e}");
}
}
/// Run the applicable scans for a target. For a code target this reuses the
@@ -1262,6 +1501,19 @@ impl PipelineOrchestrator {
.await;
return Ok(0);
}
// A git target is attributed where its commits are compared.
if !trigger.started_by_person() && !has_git {
self.attribute_run(
scan_run_id,
&target_id,
ScanAttribution::detected(
trigger,
crate::pipeline::change::content_changed(target),
),
target.billing,
)
.await?;
}
let plan = build_scan_plan(target);
// An attached artifact nothing analyses is recorded, never passed over:
// a completed run must not read as "we looked and found nothing".
@@ -1594,7 +1846,7 @@ impl PipelineOrchestrator {
.with_excluded(left_out.excluded)
.with_test_data(left_out.test_data);
let closed = left_out_run
.resolve_left_out(&self.db, target_id, "plc-control-logic")
.resolve_left_out(&self.db, target_id, Some("plc-control-logic"))
.await?;
if closed > 0 {
tracing::info!(target_id, closed, "PLC findings in left-out paths resolved");
+6 -2
View File
@@ -386,8 +386,12 @@ mod tests {
fn oauth_token_url_matches() {
let scanner = OAuthPatternScanner::new();
let pattern = &scanner.patterns[3]; // oauth-token-url
assert!(pattern.pattern.is_match("access_token = build_url(query)"));
assert!(pattern.pattern.is_match("bearer = url.param"));
// Split, so this file's own line does not match the rule it tests
// when Prüfwerk scans its own repository.
assert!(pattern
.pattern
.is_match(concat!("access_", "token = build_url(query)")));
assert!(pattern.pattern.is_match(concat!("bear", "er = url.param")));
}
// --- Pattern rule file extension filtering ---
@@ -45,6 +45,11 @@ pub struct RepoView {
/// Whether the target's uploaded files let a scheduled scan without new
/// commits be skipped ([`crate::pipeline::change::uploads_allow_git_skip`]).
pub uploads_allow_skip: bool,
/// Whether the customer changed something besides the commits since the
/// last completed scan: an uploaded file, or a live URL to probe (t72).
pub changed_besides_commits: bool,
/// How the target is billed, for whether its scan counts (t72).
pub billing: compliance_core::models::TargetBilling,
/// Whether the tree is read as Yocto layers (its recipe inventory): it
/// was classified as one, or the target is a Yocto target. Set by the
/// caller after classification; `false` from [`Self::from_target`].
@@ -84,6 +89,9 @@ impl RepoView {
findings_count: target.findings_count,
managed: target.source_repo.is_some(),
uploads_allow_skip: crate::pipeline::change::uploads_allow_git_skip(target),
changed_besides_commits: target.live_url().is_some()
|| crate::pipeline::change::uploads_changed(target),
billing: target.billing,
yocto_layers: false,
exclude_paths: target.scan_config.exclude_paths.clone(),
build_outputs: Vec::new(),
+182 -7
View File
@@ -13,11 +13,19 @@
//! working copy is a git clone, restored on every fetch, or an unpacked
//! upload, unpacked again on every scan, so nothing is lost.
//!
//! Matching is by directory name only, and narrow: `tests/` and `spec/`
//! hold test code that can leak a real secret, and `examples/` or `demo/` are
//! often the product's own code, so neither is matched.
//! Matching is by directory name, and narrow: `tests/` and `spec/` hold test
//! code that can leak a real secret, and `examples/` or `demo/` are often the
//! product's own code, so neither is matched.
//!
//! One more kind is found by its content: a Semgrep rule pack. Semgrep's own
//! test convention puts each rule `X.yaml` next to the sample it is tested
//! on, `X.py` or `X.cs`, and the samples hold the flaws the rules must find.
//! A directory with such a pair is test data with everything below it (a
//! vendored pack's manifests too), unless it is the tree itself.
use std::path::Path;
use std::collections::{HashMap, HashSet};
use std::ffi::OsString;
use std::path::{Path, PathBuf};
/// Directory names that hold test data by convention, compared
/// case-insensitively: `fixtures` (Rails, pytest, Jest's `__fixtures__`),
@@ -32,8 +40,13 @@ const TEST_DATA_DIR_NAMES: &[&str] = &[
"test_fixtures",
];
/// A rule file larger than this is not read: Semgrep rule files are a few
/// kilobytes, and a large YAML file is data, not a rule pack.
const MAX_RULE_FILE_BYTES: u64 = 1024 * 1024;
/// The top-most test-data directories under `root`, relative to it with `/`
/// separators, sorted. A directory inside one that already matched is not
/// separators, sorted: those named like test data, and Semgrep rule packs
/// with their samples. A directory inside one that already matched is not
/// listed again, `root` itself is never listed, and a symbolic link is never
/// followed or listed.
///
@@ -47,6 +60,9 @@ const TEST_DATA_DIR_NAMES: &[&str] = &[
/// "pkg/parser/testdata"]`.
pub fn test_data_dirs(root: &Path) -> Vec<String> {
let mut found = Vec::new();
// YAML files outside the test data found so far: rule pack candidates,
// checked once the walk is done.
let mut yaml_files = Vec::new();
let mut walker = walkdir::WalkDir::new(root).min_depth(1).into_iter();
while let Some(entry) = walker.next() {
let Ok(entry) = entry else {
@@ -54,6 +70,12 @@ pub fn test_data_dirs(root: &Path) -> Vec<String> {
};
// `file_type()` does not follow links: a link to a directory is a
// link here, never a directory.
if entry.file_type().is_file() {
if is_yaml(entry.path()) {
yaml_files.push(entry.into_path());
}
continue;
}
if !entry.file_type().is_dir() {
continue;
}
@@ -69,8 +91,97 @@ pub fn test_data_dirs(root: &Path) -> Vec<String> {
walker.skip_current_dir();
}
}
found.sort();
found
found.extend(rule_pack_dirs(root, &yaml_files));
top_most(found)
}
/// The directories, relative to `root`, of the `yaml_files` that are Semgrep
/// rules with a sample of the same name next to them. Each directory is read
/// once, and a rule file only when such a sample exists.
fn rule_pack_dirs(root: &Path, yaml_files: &[PathBuf]) -> Vec<String> {
// Per directory: the names (without extension) of its files that are not
// YAML, the possible samples.
let mut samples: HashMap<&Path, HashSet<OsString>> = HashMap::new();
let mut packs: HashSet<&Path> = HashSet::new();
for rule in yaml_files {
let (Some(dir), Some(stem)) = (rule.parent(), rule.file_stem()) else {
continue;
};
if dir == root || packs.contains(dir) {
continue;
}
let names = samples.entry(dir).or_insert_with(|| sample_stems(dir));
if names.contains(stem) && is_semgrep_rule_file(rule) {
packs.insert(dir);
}
}
packs
.into_iter()
.filter_map(|dir| dir.strip_prefix(root).ok())
.map(|rel| rel.to_string_lossy().replace('\\', "/"))
.collect()
}
/// The names without extension of the regular files in `dir` that are not
/// YAML.
fn sample_stems(dir: &Path) -> HashSet<OsString> {
let Ok(entries) = std::fs::read_dir(dir) else {
return HashSet::new();
};
entries
.flatten()
.filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
.map(|e| e.path())
.filter(|p| !is_yaml(p))
.filter_map(|p| p.file_stem().map(OsString::from))
.collect()
}
/// Whether `path` ends in `.yaml` or `.yml`.
fn is_yaml(path: &Path) -> bool {
path.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("yaml") || ext.eq_ignore_ascii_case("yml"))
}
/// Whether the file at `path` is a Semgrep rule file: a `rules` list with at
/// least one rule naming its `id`, `languages` and `message`, which Semgrep
/// requires of every rule.
fn is_semgrep_rule_file(path: &Path) -> bool {
if !std::fs::metadata(path).is_ok_and(|m| m.len() <= MAX_RULE_FILE_BYTES) {
return false;
}
let Ok(text) = std::fs::read_to_string(path) else {
return false;
};
let Ok(docs) = yaml_rust2::YamlLoader::load_from_str(&text) else {
return false;
};
docs.first()
.and_then(|doc| doc["rules"].as_vec())
.is_some_and(|rules| {
rules.iter().any(|rule| {
rule["id"].as_str().is_some()
&& !rule["languages"].is_badvalue()
&& !rule["message"].is_badvalue()
})
})
}
/// `dirs` sorted, without those inside another one listed.
fn top_most(mut dirs: Vec<String>) -> Vec<String> {
dirs.sort();
dirs.dedup();
let mut kept: Vec<String> = Vec::with_capacity(dirs.len());
for dir in dirs {
let inside = kept.iter().any(|outer| {
dir.strip_prefix(outer.as_str())
.is_some_and(|rest| rest.starts_with('/'))
});
if !inside {
kept.push(dir);
}
}
kept
}
/// Remove the `paths` (the [`test_data_dirs`], or the directories and files
@@ -228,6 +339,70 @@ mod tests {
);
}
/// A Semgrep rule file with one rule.
const RULE: &str = "rules:\n - id: no-exec\n languages: [python]\n \
message: exec runs code\n severity: ERROR\n pattern: exec(...)\n";
fn write_text(root: &Path, rel: &str, text: &str) {
let path = root.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
#[test]
fn a_semgrep_rule_pack_with_its_samples_is_test_data() {
let (_base, root) = tree();
// A pack: a rule and its sample, with a vendored pack below it.
write_text(&root, "agent/rules/cra.yaml", RULE);
write(&root, "agent/rules/cra.py");
write(&root, "agent/rules/vendor/gitlab/java/pom.xml");
write_text(
&root,
"agent/rules/vendor/gitlab/java/inject/ognl.yml",
RULE,
);
write(&root, "agent/rules/vendor/gitlab/java/inject/ognl.java");
// Not packs: a configuration next to the code it configures, a rule
// without a sample, and a rule pack that is the tree itself.
write_text(&root, "app/settings.yaml", "debug: true\n");
write(&root, "app/settings.py");
write_text(&root, "ci/.semgrep.yml", RULE);
write(&root, "ci/build.sh");
write_text(&root, "local.yaml", RULE);
write(&root, "local.py");
let dirs = test_data_dirs(&root);
assert!(dirs.contains(&"agent/rules".to_string()));
assert!(
!dirs.iter().any(|d| d.starts_with("agent/rules/")),
"a pack inside the pack is not listed again: {dirs:?}"
);
for not_test_data in ["app", "ci", ""] {
assert!(
!dirs.contains(&not_test_data.to_string()),
"{not_test_data}"
);
}
}
#[test]
fn a_large_or_unreadable_yaml_file_is_not_a_rule_file() {
let base = Scratch::new();
write_text(base.path(), "big.yaml", &"x: 1\n".repeat(300_000));
write_text(base.path(), "broken.yaml", "rules: [\n");
write_text(base.path(), "rule.yaml", RULE);
assert!(!is_semgrep_rule_file(&base.path().join("big.yaml")));
assert!(!is_semgrep_rule_file(&base.path().join("broken.yaml")));
assert!(is_semgrep_rule_file(&base.path().join("rule.yaml")));
}
#[test]
fn only_the_top_most_directories_are_kept() {
let dirs = ["a/b", "a", "a-x", "a/b/c", "b"].map(String::from).to_vec();
assert_eq!(top_most(dirs), ["a", "a-x", "b"]);
}
#[test]
fn the_tree_itself_is_never_test_data() {
let base = Scratch::new();
+64
View File
@@ -63,6 +63,30 @@ impl EntitlementCheck {
pub fn member_blocked(&self) -> bool {
!self.allowed && self.reason.as_deref() == Some(MEMBER_BLOCKED)
}
/// How many targets the tenant's plan includes (t72):
/// `limits.included_targets`. `None` when the plan sets no limit (no
/// limits, the key missing or null), so every target is included.
pub fn included_targets(&self) -> Option<u32> {
self.limit("included_targets")
}
/// The plan's monthly quota and the customer's Prüftag cap (t72), from
/// `limits.monthly_pruefungen` and `limits.prueftag_cap`; a missing or
/// null key is no limit.
pub fn plan_limits(&self) -> compliance_core::models::PlanLimits {
compliance_core::models::PlanLimits {
monthly_pruefungen: self.limit("monthly_pruefungen"),
prueftag_cap: self.limit("prueftag_cap"),
}
}
/// The whole-number limit `key`; `None` when absent or null.
fn limit(&self, key: &str) -> Option<u32> {
let n = self.limits.as_ref()?.get(key)?.as_u64()?;
// A count beyond u32 is no limit in practice.
Some(u32::try_from(n).unwrap_or(u32::MAX))
}
}
#[derive(Debug, Clone, Deserialize)]
@@ -634,6 +658,46 @@ pub fn scheduler_runs_for(status: &str) -> bool {
mod tests {
use super::*;
#[test]
fn the_plan_sets_how_many_targets_are_included() {
let check = |limits: serde_json::Value| -> EntitlementCheck {
serde_json::from_value(serde_json::json!({ "allowed": true, "limits": limits }))
.expect("an entitlement answer")
};
assert_eq!(
check(serde_json::json!({ "included_targets": 5 })).included_targets(),
Some(5)
);
assert_eq!(
check(serde_json::json!({ "included_targets": null })).included_targets(),
None
);
assert_eq!(check(serde_json::json!({})).included_targets(), None);
assert_eq!(check(serde_json::Value::Null).included_targets(), None);
}
#[test]
fn the_plan_sets_the_quota_and_the_cap() {
let check: EntitlementCheck = serde_json::from_value(serde_json::json!({
"allowed": true,
"limits": { "included_targets": 5, "monthly_pruefungen": 100, "prueftag_cap": 0 },
}))
.expect("an entitlement answer");
assert_eq!(
check.plan_limits(),
compliance_core::models::PlanLimits {
monthly_pruefungen: Some(100),
prueftag_cap: Some(0),
}
);
assert_eq!(
EntitlementCheck::default().plan_limits(),
compliance_core::models::PlanLimits::default(),
"Enterprise: no limits"
);
}
#[test]
fn ladder_filter() {
for s in ["active", "trial", "demo", "warning", ""] {
+6 -2
View File
@@ -38,7 +38,10 @@ pub const SCHEDULED_SCAN_JITTER: Duration = Duration::from_secs(30);
pub fn start_delay(trigger: &ScanTrigger) -> Duration {
match trigger {
ScanTrigger::Scheduled => rand::rng().random_range(Duration::ZERO..=SCHEDULED_SCAN_JITTER),
ScanTrigger::Webhook | ScanTrigger::Manual | ScanTrigger::Support => Duration::ZERO,
ScanTrigger::Webhook
| ScanTrigger::Manual
| ScanTrigger::Support
| ScanTrigger::NewContent => Duration::ZERO,
}
}
@@ -187,11 +190,12 @@ mod tests {
}
#[test]
fn webhook_manual_and_support_scans_start_at_once() {
fn webhook_manual_support_and_new_content_scans_start_at_once() {
for trigger in [
ScanTrigger::Webhook,
ScanTrigger::Manual,
ScanTrigger::Support,
ScanTrigger::NewContent,
] {
assert_eq!(start_delay(&trigger), Duration::ZERO);
}
+9
View File
@@ -26,6 +26,15 @@ pub async fn create_target(
) -> Result<OnboardedTarget, AgentError> {
let res = db.onboarded_targets().insert_one(&target).await?;
target.id = res.inserted_id.as_object_id();
// A target beyond the plan's included ones is extra from the start (t72).
if let Some((_, billing)) = agent
.refresh_billing(tenant_id, db)
.await
.into_iter()
.find(|(id, _)| Some(*id) == target.id)
{
target.billing = billing;
}
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
agent.emit_usage(
tenant_id,
+80
View File
@@ -0,0 +1,80 @@
//! The month's peak of extra targets goes to the registry when it rises and
//! once a day besides; a new month starts again (t72). Runs against a live
//! Mongo (`TEST_MONGODB_URI`) and skips cleanly without one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
use chrono::{Duration, TimeZone, Utc};
use compliance_agent::database::DatabasePool;
use compliance_agent::metering::{assign_billing, charge, record_extra_peak};
use compliance_core::models::{OnboardedTarget, PlanLimits, RunCharge, TargetType};
use mongodb::bson::doc;
const TENANT: &str = "extra-peak";
#[tokio::test]
async fn the_peak_is_sent_when_it_rises_and_once_a_day() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"extrapeak_{}",
&uuid::Uuid::new_v4().simple().to_string()[..10]
);
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP extra_peak: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
// Arrange: three targets on a plan that includes one, on 6 Nov.
let mut ids = Vec::new();
for days in [3, 2, 1] {
let mut target = OnboardedTarget::new(format!("t{days}"), TargetType::FirmwareRtos);
target.created_at = Utc::now() - Duration::days(days);
let res = db.onboarded_targets().insert_one(&target).await.unwrap();
ids.push(res.inserted_id.as_object_id().unwrap());
}
assign_billing(&db, Some(1)).await.unwrap();
let nov6 = Utc.with_ymd_and_hms(2026, 11, 6, 9, 0, 0).single().unwrap();
// Act / Assert: two extra targets, sent once that day.
assert_eq!(record_extra_peak(&db, nov6).await.unwrap(), Some(2));
assert_eq!(record_extra_peak(&db, nov6).await.unwrap(), None);
// One extra target is archived: the month's peak stays two.
db.onboarded_targets()
.update_one(
doc! { "_id": ids[2] },
doc! { "$set": { "archived_at": mongodb::bson::DateTime::now() } },
)
.await
.unwrap();
assign_billing(&db, Some(1)).await.unwrap();
assert_eq!(record_extra_peak(&db, nov6).await.unwrap(), None);
assert_eq!(
record_extra_peak(&db, nov6 + Duration::days(1))
.await
.unwrap(),
Some(2),
"re-sent once the next day"
);
// A new month starts from the targets extra now.
let dec1 = Utc.with_ymd_and_hms(2026, 12, 1, 9, 0, 0).single().unwrap();
assert_eq!(record_extra_peak(&db, dec1).await.unwrap(), Some(1));
// The month document the peak created still counts the quota.
let plan = PlanLimits {
monthly_pruefungen: Some(1),
prueftag_cap: None,
};
assert_eq!(
charge(&db, "t", plan, dec1).await.unwrap().charge,
RunCharge::Quota
);
assert_eq!(
charge(&db, "t", plan, dec1).await.unwrap().charge,
RunCharge::Prueftag
);
pool.drop_tenant(TENANT).await.ok();
}
@@ -0,0 +1,83 @@
//! Counted Prüfungen go to the month's quota first; once it is used up, the
//! first one on a target that day books a Prüftag that allows six (t72).
//! Runs against a live Mongo (`TEST_MONGODB_URI`) and skips cleanly without
//! one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
use chrono::{TimeZone, Utc};
use compliance_agent::database::DatabasePool;
use compliance_agent::metering::{charge, usage};
use compliance_core::models::{
admit, Admission, PlanLimits, Refusal, RunCharge, PRUEFUNGEN_PER_PRUEFTAG,
};
const TENANT: &str = "metering-counters";
#[tokio::test]
async fn the_quota_then_a_prueftag_of_six_then_nothing() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"metering_{}",
&uuid::Uuid::new_v4().simple().to_string()[..10]
);
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP metering_counters: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
// Arrange: a quota of two and a cap of one Prüftag, on 6 Nov in Berlin.
let plan = PlanLimits {
monthly_pruefungen: Some(2),
prueftag_cap: Some(1),
};
let at = Utc.with_ymd_and_hms(2026, 11, 6, 9, 0, 0).single().unwrap();
let admitted = |target: &'static str| {
let db = db.clone();
async move {
let (month, day) = usage(&db, target, at).await.unwrap();
admit(plan, month, day)
}
};
// Act / Assert: the quota first.
for _ in 0..2 {
assert_eq!(admitted("a").await, Admission::Quota);
let charged = charge(&db, "a", plan, at).await.unwrap();
assert_eq!(charged.charge, RunCharge::Quota);
assert_eq!(charged.booked_prueftag, None);
}
// The quota is used up: the next one books target a's Prüftag.
assert_eq!(admitted("a").await, Admission::BookPrueftag);
let booked = charge(&db, "a", plan, at).await.unwrap();
assert_eq!(booked.charge, RunCharge::Prueftag);
assert_eq!(booked.booked_prueftag.as_deref(), Some("2026-11-06"));
// It allows six in all; the seventh that day does not run.
for _ in 1..PRUEFUNGEN_PER_PRUEFTAG {
assert_eq!(admitted("a").await, Admission::Prueftag);
let charged = charge(&db, "a", plan, at).await.unwrap();
assert_eq!(charged.booked_prueftag, None, "no second booking");
}
assert_eq!(admitted("a").await, Admission::Refused(Refusal::DailyLimit));
// Another target would need a second Prüftag, over the cap of one.
assert_eq!(
admitted("b").await,
Admission::Refused(Refusal::PrueftagCap)
);
// The next calendar day in Berlin is a new day for target a.
let tomorrow = Utc
.with_ymd_and_hms(2026, 11, 6, 23, 30, 0)
.single()
.unwrap();
let (month, day) = usage(&db, "a", tomorrow).await.unwrap();
assert!(!day.prueftag_booked, "7 Nov in Berlin");
assert_eq!(month.prueftage, 1);
assert_eq!(month.pruefungen, 2);
pool.drop_tenant(TENANT).await.ok();
}
+64 -1
View File
@@ -196,7 +196,7 @@ async fn only_what_was_left_out_is_closed_for_a_stage_without_a_seen_set() {
.with_excluded(vec!["legacy".to_string()])
.with_test_data(vec!["fixtures".to_string()]);
let closed = run
.resolve_left_out(&db, TARGET, "plc-control-logic")
.resolve_left_out(&db, TARGET, Some("plc-control-logic"))
.await
.unwrap();
@@ -228,3 +228,66 @@ async fn only_what_was_left_out_is_closed_for_a_stage_without_a_seen_set() {
pool.drop_tenant(TENANT).await.ok();
}
#[tokio::test]
async fn left_out_findings_close_whichever_scanner_stored_them() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"leftoutall_{}",
&uuid::Uuid::new_v4().simple().to_string()[..10]
);
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP resolve_findings: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
// Arrange: an earlier scan stored findings of scanners that do not run
// now (no C, no BitBake left in the tree), one in the test data that this
// run still reports, and one outside the left-out paths.
db.findings()
.insert_many([
finding("fp-cppcheck", "cppcheck", "fixtures/firmware/sensors.c"),
finding("fp-recipe", "yocto-config", "legacy/image.bb"),
finding("fp-reported", "gitleaks", "fixtures/app/.env.local"),
finding("fp-kept", "cppcheck", "src/main.c"),
])
.await
.unwrap();
// Act: only gitleaks completes, and it reports fp-reported again.
let mut run = RunFindings::new("run-all")
.with_excluded(vec!["legacy".to_string()])
.with_test_data(vec!["fixtures".to_string()]);
run.completed("gitleaks");
let mut seen = vec![finding(
"fp-reported",
"gitleaks",
"fixtures/app/.env.local",
)];
run.write_back(&db, &mut seen).await.unwrap();
run.resolve_missing(&db, TARGET, &[]).await.unwrap();
let closed = run.resolve_left_out(&db, TARGET, None).await.unwrap();
// Assert: the left-out findings close with their reason, although their
// scanner did not run; one this run reported, and one outside, stay.
assert_eq!(closed, 2);
let cppcheck = row(&db, "fp-cppcheck").await;
assert_eq!(cppcheck.status, FindingStatus::Resolved);
assert_eq!(
last_scan_change(&cppcheck),
Some(ScanChangeKind::NowTestData)
);
let recipe = row(&db, "fp-recipe").await;
assert_eq!(recipe.status, FindingStatus::Resolved);
assert_eq!(last_scan_change(&recipe), Some(ScanChangeKind::NowExcluded));
assert_eq!(
row(&db, "fp-reported").await.status,
FindingStatus::Open,
"a finding this run reported is not closed"
);
assert_eq!(row(&db, "fp-kept").await.status, FindingStatus::Open);
pool.drop_tenant(TENANT).await.ok();
}
+82
View File
@@ -0,0 +1,82 @@
//! The oldest active targets are the plan's included ones; the rest are
//! extra, and an extra one moves up when an included one is archived (t72).
//! Runs against a live Mongo (`TEST_MONGODB_URI`) and skips cleanly without
//! one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
use chrono::{Duration, Utc};
use compliance_agent::database::{Database, DatabasePool};
use compliance_agent::metering::assign_billing;
use compliance_core::models::{OnboardedTarget, TargetBilling, TargetType};
use mongodb::bson::{doc, oid::ObjectId};
const TENANT: &str = "target-billing";
async fn billing(db: &Database, id: ObjectId) -> TargetBilling {
db.onboarded_targets()
.find_one(doc! { "_id": id })
.await
.unwrap()
.unwrap()
.billing
}
#[tokio::test]
async fn the_oldest_targets_are_included_and_an_extra_one_moves_up() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"billing_{}",
&uuid::Uuid::new_v4().simple().to_string()[..10]
);
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP target_billing: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
// Arrange: three targets, created a day apart.
let mut ids = Vec::new();
for days in [3, 2, 1] {
let mut target = OnboardedTarget::new(format!("t{days}"), TargetType::FirmwareRtos);
target.created_at = Utc::now() - Duration::days(days);
let res = db.onboarded_targets().insert_one(&target).await.unwrap();
ids.push(res.inserted_id.as_object_id().unwrap());
}
let (oldest, middle, newest) = (ids[0], ids[1], ids[2]);
// Act: a plan with two included targets.
let changes = assign_billing(&db, Some(2)).await.unwrap();
// Assert: only the newest is extra, and it is the one change.
assert_eq!(changes, vec![(newest, TargetBilling::Extra)]);
assert_eq!(billing(&db, oldest).await, TargetBilling::Included);
assert_eq!(billing(&db, middle).await, TargetBilling::Included);
assert_eq!(billing(&db, newest).await, TargetBilling::Extra);
assert!(
assign_billing(&db, Some(2)).await.unwrap().is_empty(),
"nothing changes a second time"
);
// Act: the oldest is archived.
db.onboarded_targets()
.update_one(
doc! { "_id": oldest },
doc! { "$set": { "archived_at": mongodb::bson::DateTime::now() } },
)
.await
.unwrap();
assign_billing(&db, Some(2)).await.unwrap();
// Assert: the extra one moved up.
assert_eq!(billing(&db, newest).await, TargetBilling::Included);
// Act / Assert: a plan without a limit includes every target.
assign_billing(&db, Some(0)).await.unwrap();
assert_eq!(billing(&db, middle).await, TargetBilling::Extra);
assign_billing(&db, None).await.unwrap();
assert_eq!(billing(&db, middle).await, TargetBilling::Included);
pool.drop_tenant(TENANT).await.ok();
}
+38
View File
@@ -0,0 +1,38 @@
//! The release a binary was built as, read at compile time.
//!
//! CI passes the latest release tag (without its `v`) as `PRUEFWERK_VERSION`
//! and the commit as `PRUEFWERK_COMMIT` to the image build. The crate version
//! is only the fallback for a local build: it is not bumped per release, so
//! anything that names the running version (the agent's `/version` handshake,
//! telemetry's `service.version`, evidence tooling) uses these constants.
/// The build version: `PRUEFWERK_VERSION` at compile time, else the crate
/// version.
pub const BUILD_VERSION: &str =
non_empty_or(option_env!("PRUEFWERK_VERSION"), env!("CARGO_PKG_VERSION"));
/// The commit the build is from: `PRUEFWERK_COMMIT` at compile time (CI: the
/// full SHA), else "unknown". The portal's version line shows 8 characters.
pub const BUILD_COMMIT: &str = non_empty_or(option_env!("PRUEFWERK_COMMIT"), "unknown");
/// A Docker build arg left empty is an empty env var, not an unset one.
const fn non_empty_or(value: Option<&'static str>, fallback: &'static str) -> &'static str {
match value {
Some(v) if !v.is_empty() => v,
_ => fallback,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_unset_or_empty_build_value_falls_back() {
assert_eq!(non_empty_or(None, "0.4.4"), "0.4.4");
assert_eq!(non_empty_or(Some(""), "unknown"), "unknown");
assert_eq!(non_empty_or(Some("0.4.5"), "0.4.4"), "0.4.5");
assert!(!BUILD_VERSION.is_empty());
assert!(!BUILD_COMMIT.is_empty());
}
}
+1
View File
@@ -1,3 +1,4 @@
pub mod build_info;
pub mod config;
pub mod control_check;
pub mod csaf_docs;
+440
View File
@@ -0,0 +1,440 @@
//! Metering (t72): whether a target is one of the plan's included targets,
//! why a scan ran, and whether that scan counts toward the customer's usage.
//!
//! The contract (Leistungsbeschreibung Prüfwerk §2 Abs. 4–5, §7): change-driven
//! scans of an included target are not counted; Prüfungen the customer
//! requests are, and so is every scan of an extra target. Our own rescans and
//! support's scans never are.
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use super::repository::ScanTrigger;
/// Whether a target is one of the plan's included targets or an extra one
/// (billed per month on top).
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum TargetBilling {
/// One of the plan's included targets. Targets stored before metering
/// existed read as included.
#[default]
Included,
/// A target beyond the plan's included ones.
Extra,
}
/// Why a scan ran, as far as metering is concerned.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ScanAttribution {
/// Started because something changed: new commits, other uploaded
/// files, or a live URL (scanned on every schedule).
Change,
/// The customer asked for it (dashboard or API).
Request,
/// Our own: a scheduled scan where nothing the customer changed, only
/// the Prüfwerk build. Never counted.
Rescan,
/// Started by Breakpilot support in the customer's tenant. Never counted.
Support,
}
impl ScanAttribution {
/// The attribution a scan started by a person has from the start, before
/// any change detection; `None` for a scheduled or webhook scan, which
/// change detection attributes.
pub fn of_person(trigger: &ScanTrigger) -> Option<Self> {
match trigger {
ScanTrigger::Manual => Some(Self::Request),
ScanTrigger::Support => Some(Self::Support),
ScanTrigger::Scheduled | ScanTrigger::Webhook | ScanTrigger::NewContent => None,
}
}
/// The attribution of a scan that runs, from its trigger and whether
/// change detection found a change the customer made.
///
/// # Arguments
///
/// * `trigger` - What started the scan.
/// * `content_changed` - New commits, other uploaded files, or a live
/// URL. Ignored for a scan a person started.
pub fn detected(trigger: &ScanTrigger, content_changed: bool) -> Self {
match Self::of_person(trigger) {
Some(person) => person,
None if content_changed => Self::Change,
None => Self::Rescan,
}
}
/// Whether a scan with this attribution, on a target billed as
/// `billing`, counts toward the customer's usage once it completes.
///
/// # Examples
///
/// ```
/// use compliance_core::models::{ScanAttribution, TargetBilling};
///
/// assert!(!ScanAttribution::Change.chargeable(TargetBilling::Included));
/// assert!(ScanAttribution::Change.chargeable(TargetBilling::Extra));
/// assert!(ScanAttribution::Request.chargeable(TargetBilling::Included));
/// assert!(!ScanAttribution::Rescan.chargeable(TargetBilling::Extra));
/// ```
pub fn chargeable(self, billing: TargetBilling) -> bool {
match self {
Self::Request => true,
Self::Change => billing == TargetBilling::Extra,
Self::Rescan | Self::Support => false,
}
}
}
/// How many counted Prüfungen one Prüftag allows on its target that day.
pub const PRUEFUNGEN_PER_PRUEFTAG: u32 = 6;
/// What the tenant's plan allows per calendar month (Europe/Berlin).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PlanLimits {
/// Counted Prüfungen in the quota; `None` is unlimited (no Prüftage).
pub monthly_pruefungen: Option<u32>,
/// Prüftage the customer allows; `None` is no cap, `Some(0)` none.
pub prueftag_cap: Option<u32>,
}
/// What the tenant used so far this month.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct MonthUsage {
/// Counted Prüfungen charged to the quota.
pub pruefungen: u32,
/// Prüftage booked.
pub prueftage: u32,
}
/// What one target used today, once the quota was used up.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DayUsage {
/// Whether a Prüftag is booked for the target today.
pub prueftag_booked: bool,
/// Counted Prüfungen charged to that Prüftag.
pub prueftag_pruefungen: u32,
}
/// What a counted Prüfung was charged to.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum RunCharge {
/// The month's quota.
Quota,
/// The target's Prüftag for that day.
Prueftag,
}
/// Whether a counted Prüfung may run, and what it is charged to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Admission {
/// Within the month's quota.
Quota,
/// On the target's Prüftag already booked today.
Prueftag,
/// The quota is used up: this Prüfung books today's Prüftag.
BookPrueftag,
/// It does not run.
Refused(Refusal),
}
/// Why a counted Prüfung does not run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Refusal {
/// Today's Prüftag on the target is used up; there is no second one.
DailyLimit,
/// The quota is used up and the customer's Prüftag cap is reached.
PrueftagCap,
}
/// Whether one more counted Prüfung on a target may run, by the contract
/// (LB Prüfwerk §2 Abs. 5): the quota first; once it is used up, the first
/// counted Prüfung on a target that day books a Prüftag (unless the cap is
/// reached), which allows [`PRUEFUNGEN_PER_PRUEFTAG`] from then on.
///
/// # Examples
///
/// ```
/// use compliance_core::models::{admit, Admission, DayUsage, MonthUsage, PlanLimits};
///
/// let plan = PlanLimits { monthly_pruefungen: Some(100), prueftag_cap: None };
/// let used_up = MonthUsage { pruefungen: 100, prueftage: 0 };
/// assert_eq!(admit(plan, used_up, DayUsage::default()), Admission::BookPrueftag);
/// ```
pub fn admit(limits: PlanLimits, month: MonthUsage, day: DayUsage) -> Admission {
let Some(quota) = limits.monthly_pruefungen else {
return Admission::Quota;
};
if month.pruefungen < quota {
return Admission::Quota;
}
if day.prueftag_booked {
return if day.prueftag_pruefungen < PRUEFUNGEN_PER_PRUEFTAG {
Admission::Prueftag
} else {
Admission::Refused(Refusal::DailyLimit)
};
}
match limits.prueftag_cap {
Some(cap) if month.prueftage >= cap => Admission::Refused(Refusal::PrueftagCap),
_ => Admission::BookPrueftag,
}
}
/// One active target as [`split_included`] sees it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BillableTarget<Id> {
/// The target's id.
pub id: Id,
/// When it was created: the oldest targets are the included ones.
pub created_at: DateTime<Utc>,
/// How it is billed now.
pub billing: TargetBilling,
}
/// The targets whose billing has to change so that the `included` oldest
/// active targets are included and the rest are extra.
///
/// # Arguments
///
/// * `targets` - The tenant's active (not archived) targets, in any order.
/// Ties on `created_at` are broken by id, so the split is stable.
/// * `included` - How many targets the plan includes; `None` is unlimited.
///
/// # Returns
///
/// Each target whose billing differs from what it should be, with the
/// billing it should have. Empty when nothing changes.
pub fn split_included<Id: Ord + Clone>(
targets: &[BillableTarget<Id>],
included: Option<u32>,
) -> Vec<(Id, TargetBilling)> {
let mut ordered: Vec<&BillableTarget<Id>> = targets.iter().collect();
ordered.sort_unstable_by(|a, b| a.created_at.cmp(&b.created_at).then(a.id.cmp(&b.id)));
// `usize::MAX` stands for "no limit"; a u32 always fits a usize here.
let limit = included.map_or(usize::MAX, |n| n as usize);
ordered
.into_iter()
.enumerate()
.filter_map(|(rank, target)| {
let wanted = if rank < limit {
TargetBilling::Included
} else {
TargetBilling::Extra
};
(target.billing != wanted).then(|| (target.id.clone(), wanted))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::TimeZone;
fn target(id: u32, day: u32, billing: TargetBilling) -> BillableTarget<u32> {
BillableTarget {
id,
created_at: Utc
.with_ymd_and_hms(2026, 11, day, 0, 0, 0)
.single()
.expect("valid date"),
billing,
}
}
#[test]
fn the_oldest_targets_are_included_and_the_rest_extra() {
// Arrange: three included targets, created on days 3, 1 and 2.
let targets = [
target(1, 3, TargetBilling::Included),
target(2, 1, TargetBilling::Included),
target(3, 2, TargetBilling::Included),
];
// Act
let changes = split_included(&targets, Some(2));
// Assert: only the newest one moves to extra.
assert_eq!(changes, vec![(1, TargetBilling::Extra)]);
}
#[test]
fn an_extra_target_moves_up_when_an_included_one_leaves() {
let targets = [
target(2, 2, TargetBilling::Included),
target(3, 3, TargetBilling::Extra),
];
assert_eq!(
split_included(&targets, Some(2)),
vec![(3, TargetBilling::Included)]
);
}
#[test]
fn without_a_limit_every_target_is_included() {
let targets = [
target(1, 1, TargetBilling::Extra),
target(2, 2, TargetBilling::Included),
];
assert_eq!(
split_included(&targets, None),
vec![(1, TargetBilling::Included)]
);
}
#[test]
fn equal_creation_times_split_by_id() {
let targets = [
target(9, 1, TargetBilling::Included),
target(4, 1, TargetBilling::Included),
];
assert_eq!(
split_included(&targets, Some(1)),
vec![(9, TargetBilling::Extra)]
);
}
#[test]
fn a_scan_a_person_started_keeps_its_attribution() {
assert_eq!(
ScanAttribution::detected(&ScanTrigger::Manual, false),
ScanAttribution::Request
);
assert_eq!(
ScanAttribution::detected(&ScanTrigger::Support, true),
ScanAttribution::Support
);
}
#[test]
fn a_scheduled_scan_is_a_change_or_our_rescan() {
assert_eq!(
ScanAttribution::detected(&ScanTrigger::Scheduled, true),
ScanAttribution::Change
);
assert_eq!(
ScanAttribution::detected(&ScanTrigger::Webhook, false),
ScanAttribution::Rescan
);
assert_eq!(
ScanAttribution::detected(&ScanTrigger::NewContent, true),
ScanAttribution::Change,
"an upload is the customer's change"
);
}
#[test]
fn what_counts_follows_the_contract() {
use ScanAttribution::{Change, Request, Rescan, Support};
use TargetBilling::{Extra, Included};
let counted: Vec<(ScanAttribution, TargetBilling)> = [Change, Request, Rescan, Support]
.into_iter()
.flat_map(|a| [(a, Included), (a, Extra)])
.filter(|(a, b)| a.chargeable(*b))
.collect();
assert_eq!(
counted,
vec![(Change, Extra), (Request, Included), (Request, Extra)]
);
}
const PLAN: PlanLimits = PlanLimits {
monthly_pruefungen: Some(100),
prueftag_cap: Some(2),
};
#[test]
fn the_quota_comes_first() {
let month = MonthUsage {
pruefungen: 99,
prueftage: 0,
};
assert_eq!(admit(PLAN, month, DayUsage::default()), Admission::Quota);
}
#[test]
fn a_used_up_quota_books_a_prueftag_that_allows_six() {
let month = MonthUsage {
pruefungen: 100,
prueftage: 1,
};
assert_eq!(
admit(PLAN, month, DayUsage::default()),
Admission::BookPrueftag
);
let booked = |used| DayUsage {
prueftag_booked: true,
prueftag_pruefungen: used,
};
assert_eq!(admit(PLAN, month, booked(5)), Admission::Prueftag);
assert_eq!(
admit(PLAN, month, booked(PRUEFUNGEN_PER_PRUEFTAG)),
Admission::Refused(Refusal::DailyLimit)
);
}
#[test]
fn the_cap_stops_new_prueftage_but_not_a_booked_one() {
let month = MonthUsage {
pruefungen: 100,
prueftage: 2,
};
assert_eq!(
admit(PLAN, month, DayUsage::default()),
Admission::Refused(Refusal::PrueftagCap)
);
let booked = DayUsage {
prueftag_booked: true,
prueftag_pruefungen: 1,
};
assert_eq!(admit(PLAN, month, booked), Admission::Prueftag);
let none_allowed = PlanLimits {
prueftag_cap: Some(0),
..PLAN
};
let nothing_booked = MonthUsage {
pruefungen: 100,
prueftage: 0,
};
assert_eq!(
admit(none_allowed, nothing_booked, DayUsage::default()),
Admission::Refused(Refusal::PrueftagCap)
);
}
#[test]
fn without_a_quota_everything_runs() {
let unlimited = PlanLimits::default();
let month = MonthUsage {
pruefungen: 10_000,
prueftage: 0,
};
assert_eq!(
admit(unlimited, month, DayUsage::default()),
Admission::Quota
);
}
#[test]
fn stored_names_are_snake_case() {
assert_eq!(
serde_json::to_value(TargetBilling::Extra).expect("serializes"),
"extra"
);
assert_eq!(
serde_json::to_value(ScanAttribution::Rescan).expect("serializes"),
"rescan"
);
}
}
+5
View File
@@ -13,6 +13,7 @@ pub mod license;
pub mod license_policy;
pub mod mcp;
pub mod mcp_token;
pub mod metering;
pub mod notification;
pub mod onboarding;
pub mod oscal;
@@ -57,6 +58,10 @@ pub use license_policy::{
};
pub use mcp::{McpServerConfig, McpServerStatus, McpTransport};
pub use mcp_token::{McpToken, McpTokenView};
pub use metering::{
admit, split_included, Admission, BillableTarget, DayUsage, MonthUsage, PlanLimits, Refusal,
RunCharge, ScanAttribution, TargetBilling, PRUEFUNGEN_PER_PRUEFTAG,
};
pub use notification::{CveNotification, NotificationSeverity, NotificationStatus};
pub use onboarding::{
default_compliance_profile, Artifact, ArtifactAuth, ArtifactKind, Classification,
+6
View File
@@ -660,6 +660,11 @@ pub struct OnboardedTarget {
/// its last scan; `None` for every other target.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub layer_pins: Option<super::yocto::LayerPins>,
/// Whether the target is one of the plan's included targets or an extra
/// one (t72). The agent sets it from the plan; stored, so it never flips
/// unseen.
#[serde(default)]
pub billing: super::metering::TargetBilling,
/// Creation timestamp.
#[serde(
default = "chrono::Utc::now",
@@ -700,6 +705,7 @@ impl OnboardedTarget {
archived_at: None,
last_scan: None,
layer_pins: None,
billing: super::metering::TargetBilling::default(),
created_at: now,
updated_at: now,
}
+5 -1
View File
@@ -10,6 +10,10 @@ pub enum ScanTrigger {
/// Started by BreakPilot support in the customer's tenant; not counted
/// as the customer's usage.
Support,
/// Started after the customer gave the target new content: created it,
/// or uploaded files (t72). Like a scheduled scan, it runs only when
/// something changed, and then it is a change-driven Prüfung.
NewContent,
}
impl ScanTrigger {
@@ -18,7 +22,7 @@ impl ScanTrigger {
pub fn started_by_person(&self) -> bool {
match self {
Self::Manual | Self::Support => true,
Self::Scheduled | Self::Webhook => false,
Self::Scheduled | Self::Webhook | Self::NewContent => false,
}
}
}
+28 -1
View File
@@ -184,6 +184,20 @@ pub struct ScanRun {
/// at the end of this run (sbomqs, #496); `None` when it was not scored.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sbom_quality: Option<super::sbom::SbomQuality>,
/// Why the run ran, for metering (t72): set when it starts for a scan a
/// person started, and by change detection otherwise. `None` for a run
/// skipped because nothing changed, and in runs from before metering.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attribution: Option<super::metering::ScanAttribution>,
/// Whether the run counts toward the customer's usage once it completes
/// ([`super::metering::ScanAttribution::chargeable`] for the target's
/// billing when it was attributed).
#[serde(default)]
pub chargeable: bool,
/// What the run was charged to once it counted; `None` while it runs,
/// and for a run that did not count.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub charge: Option<super::metering::RunCharge>,
}
/// Why a stage was skipped, or what a run note is about
@@ -270,6 +284,12 @@ pub enum SkipCode {
/// layer pins or `LAYERSERIES_COMPAT`, so its support period was not
/// checked.
ReleaseUnknown,
/// The month's quota is used up and today's Prüftag on the target has
/// had its Prüfungen, so this counted Prüfung did not run (t72).
PrueftagLimitReached,
/// The month's quota is used up and the Prüftag limit the customer set
/// is reached, so this counted Prüfung did not run (t72).
PrueftagCapReached,
}
impl SkipCode {
@@ -304,7 +324,9 @@ impl SkipCode {
| Self::PlatformProjectGenerated
| Self::UploadUnchanged
| Self::TooLargeToScan
| Self::ReleaseUnknown => false,
| Self::ReleaseUnknown
| Self::PrueftagLimitReached
| Self::PrueftagCapReached => false,
}
}
}
@@ -410,6 +432,9 @@ impl ScanRun {
languages: Vec::new(),
planned_phases: Vec::new(),
sbom_quality: None,
attribution: None,
chargeable: false,
charge: None,
}
}
}
@@ -474,6 +499,8 @@ mod skipped_stage_tests {
SkipCode::PlatformProjectGenerated,
SkipCode::UploadUnchanged,
SkipCode::TooLargeToScan,
SkipCode::PrueftagLimitReached,
SkipCode::PrueftagCapReached,
];
assert!(notes.iter().all(|c| c.is_informational()));
assert!(skips.iter().all(|c| !c.is_informational()));
+4 -1
View File
@@ -55,7 +55,10 @@ fn build_resource(service_name: &str) -> Resource {
let name = std::env::var("OTEL_SERVICE_NAME").unwrap_or_else(|_| service_name.to_string());
Resource::builder()
.with_service_name(name)
.with_attributes([KeyValue::new("service.version", env!("CARGO_PKG_VERSION"))])
.with_attributes([KeyValue::new(
"service.version",
crate::build_info::BUILD_VERSION,
)])
.build()
}
+4
View File
@@ -4793,6 +4793,10 @@ tbody tr:last-child td {
margin-bottom: 2px;
}
.targets-extra {
margin-top: 4px;
}
.targets-cra {
min-width: 220px;
}
@@ -6,8 +6,8 @@ use dioxus::prelude::*;
use crate::i18n::texts::{common, kinds, onboarding as otx, targets as tx};
use crate::i18n::use_lang;
use crate::infrastructure::onboarding::{
is_file_kind, plc_format_for, set_archive_password, upload_target_artifact, ArchivePassword,
PasswordOutcome, UNSUPPORTED_ARCHIVE,
is_file_kind, plc_format_for, set_archive_password, trigger_new_content_scan,
upload_target_artifact, ArchivePassword, PasswordOutcome, UNSUPPORTED_ARCHIVE,
};
/// The upload row for target `target_id`; `on_uploaded` runs once the file
@@ -82,6 +82,7 @@ pub fn ArtifactUpload(target_id: String, on_uploaded: EventHandler<()>) -> Eleme
onclick: move |_| {
let Some(picked) = file() else { return; };
let (id, kind, pw) = (target_id.clone(), kind(), password());
let scan_id = id.clone();
let format = (kind == "plc_project").then(|| plc_format.read().clone());
busy.set(true);
spawn(async move {
@@ -115,10 +116,21 @@ pub fn ArtifactUpload(target_id: String, on_uploaded: EventHandler<()>) -> Eleme
}
}
};
// New content starts its change-driven scan (t72); a
// failed start leaves the file for the next scan.
let scanning = match &result {
Ok(()) => trigger_new_content_scan(scan_id).await.is_ok(),
Err(_) => false,
};
busy.set(false);
match result {
Ok(()) => {
note.set(Some((true, tx::UPLOADED.get(lang).to_string())));
let uploaded = if scanning {
tx::UPLOADED
} else {
tx::UPLOADED_NOT_SCANNED
};
note.set(Some((true, uploaded.get(lang).to_string())));
file.set(None);
password.set(String::new());
on_uploaded.call(());
+60 -6
View File
@@ -713,6 +713,28 @@ pub mod scans {
so it was not scanned again. \"Run scan\" always scans in full."
.into()
}
(SkipCode::PrueftagLimitReached, Lang::De) => {
"Nicht geprüft: Das Monatskontingent ist aufgebraucht, und der heutige Prüftag \
für dieses Prüfobjekt hat seine Prüfungen bereits erreicht. Morgen ist wieder \
eine Prüfung möglich."
.into()
}
(SkipCode::PrueftagLimitReached, Lang::En) => {
"Not scanned: the monthly quota is used up and today's Prüftag for this target \
has had all its scans. It can be scanned again tomorrow."
.into()
}
(SkipCode::PrueftagCapReached, Lang::De) => {
"Nicht geprüft: Das Monatskontingent ist aufgebraucht, und Ihr Limit für \
Prüftage ist erreicht. Gezählte Prüfungen laufen wieder ab dem nächsten Monat \
oder nach einer Erhöhung des Limits im Portal."
.into()
}
(SkipCode::PrueftagCapReached, Lang::En) => {
"Not scanned: the monthly quota is used up and your Prüftag limit is reached. \
Counted scans run again next month, or once you raise the limit in the portal."
.into()
}
(SkipCode::TooLargeToScan, Lang::De) => {
format!("Zu groß für die Suche nach Schadsoftware, nicht geprüft: {subject}")
}
@@ -843,6 +865,17 @@ pub mod targets {
de: "+ Prüfobjekt anlegen",
en: "+ Add a target",
};
/// Badge of a target beyond the plan's included ones (t72).
pub const EXTRA: Text = Text {
de: "Zusätzliches Prüfobjekt",
en: "Extra target",
};
pub const EXTRA_HINT: Text = Text {
de: "Über die in Ihrem Tarif enthaltenen Prüfobjekte hinaus: wird monatlich \
zusätzlich berechnet, und jede seiner Prüfungen zählt zu Ihrem Kontingent.",
en: "Beyond the targets your plan includes: billed monthly on top, and each of \
its scans counts toward your quota.",
};
pub const COL_NAME: Text = Text {
de: "Name",
en: "Name",
@@ -1085,9 +1118,9 @@ pub mod targets {
};
pub const UPLOAD_HINT: Text = Text {
de: "Ein Archiv (zip, tar, tar.gz), ein SPS-Projekt oder ein Firmware-Image. Die Datei \
wird sofort hochgeladen und bei der nächsten Prüfung geprüft.",
wird sofort hochgeladen und gleich danach geprüft.",
en: "An archive (zip, tar, tar.gz), a PLC project or a firmware image. It is uploaded \
at once and checked by the next scan.",
at once and scanned right after.",
};
pub const UPLOAD: Text = Text {
de: "Hochladen",
@@ -1140,8 +1173,14 @@ pub mod targets {
}
}
pub const UPLOADED: Text = Text {
de: "Hochgeladen. Starten Sie die Prüfung, um die Datei zu prüfen.",
en: "Uploaded. Start a scan to check the file.",
de: "Hochgeladen. Die Prüfung der neuen Datei startet.",
en: "Uploaded. The scan of the new file is starting.",
};
pub const UPLOADED_NOT_SCANNED: Text = Text {
de: "Hochgeladen. Die Prüfung konnte nicht gestartet werden; die nächste \
geplante Prüfung liest die Datei.",
en: "Uploaded. The scan could not be started; the next scheduled scan reads \
the file.",
};
pub const EVIDENCE_BUILDING: Text = Text {
de: "Wird erstellt …",
@@ -2296,12 +2335,27 @@ pub mod sbom {
de: "Yocto-Rezeptinventar (nicht die SBOM des Images): aus den Rezepten im Layer-Baum gelesen, ohne Build. Layer-Overrides und PACKAGECONFIG sind nicht aufgelöst; es listet daher mehr, als das Image enthält. Was ein Image-Rezept installiert, ist mit „Im Image (deklariert)“ markiert.",
en: "Yocto recipe inventory (not the image SBOM): read from the recipes in the layer tree, without a build. Layer overrides and PACKAGECONFIG are not resolved, so it lists more than the image contains. What an image recipe installs is marked \"In the image (declared)\".",
};
/// A component an image recipe installs (its badge and filter).
/// The badge of a component an image recipe installs.
pub const IN_IMAGE: Text = Text {
de: "Im Image (deklariert)",
en: "In the image (declared)",
};
/// The badge's and the filter's tooltip; the badge adds the images.
/// The badge of a component the build installed (its image SPDX).
pub const IN_IMAGE_BUILT: Text = Text {
de: "Im Image (gebaut)",
en: "In the image (built)",
};
/// The in-image filter's choice: declared or built alike.
pub const IN_IMAGE_ANY: Text = Text {
de: "Im Image",
en: "In the image",
};
/// The in-image filter's tooltip.
pub const IN_IMAGE_FILTER_HINT: Text = Text {
de: "Vom Build installiert (Image-SPDX) oder von den Image-Rezepten deklariert.",
en: "Installed by the build (image SPDX) or declared by the image recipes.",
};
/// The declared badge's tooltip; the badge adds the images.
pub const IN_IMAGE_HINT: Text = Text {
de: "Aus den Rezepten gelesen (IMAGE_INSTALL, Paketgruppen eine Ebene tief, IMAGE_FEATURES), nicht von BitBake aufgelöst: Overrides, PACKAGECONFIG und von DISTRO_FEATURES abhängige Pakete sind nicht berücksichtigt.",
en: "Read from the recipes (IMAGE_INSTALL, package groups one level deep, IMAGE_FEATURES), not resolved by bitbake: overrides, PACKAGECONFIG and packages that depend on DISTRO_FEATURES are not taken into account.",
@@ -606,7 +606,24 @@ pub async fn delete_target(id: String) -> Result<serde_json::Value, ServerFnErro
super::agent_client::json_or_error(resp).await
}
/// Trigger a scan for a target.
/// Start the scan of a target that just got new content: it was created,
/// or files were uploaded to it (t72). It runs only when something changed,
/// as a change-driven Prüfung that does not count on an included target.
#[server]
pub async fn trigger_new_content_scan(id: String) -> Result<serde_json::Value, ServerFnError> {
let resp = super::agent_client::agent_request(
reqwest::Method::POST,
&format!("/api/v1/targets/{id}/scan?reason=new_content"),
)
.await?
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
super::agent_client::json_or_error(resp).await
}
/// Trigger a scan for a target: the customer asks for a Prüfung, which
/// always runs and counts (t72).
#[server]
pub async fn trigger_target_scan(id: String) -> Result<serde_json::Value, ServerFnError> {
let resp = super::agent_client::agent_request(
+3 -3
View File
@@ -17,7 +17,7 @@ use crate::i18n::texts::{common, kinds, onboarding as tx};
use crate::i18n::{format_bytes, use_lang};
use crate::infrastructure::onboarding::{
create_target, detect_target, enable_target_scans, fetch_applicable_scans, is_file_kind,
plc_format_for, set_archive_password, trigger_target_scan, upload_target_artifact,
plc_format_for, set_archive_password, trigger_new_content_scan, upload_target_artifact,
validate_artifact_ref, validate_target_name, ArchivePassword, ArtifactInputDto,
PasswordOutcome, UNSUPPORTED_ARCHIVE,
};
@@ -591,7 +591,7 @@ pub fn OnboardingPage() -> Element {
return;
}
}
first_scan.set(match trigger_target_scan(id).await {
first_scan.set(match trigger_new_content_scan(id).await {
Ok(_) => FirstScan::Started,
Err(e) => FirstScan::Failed(e.to_string()),
});
@@ -750,7 +750,7 @@ pub fn OnboardingPage() -> Element {
let offers_optin = !source_only && !optin_scans(&applicable).is_empty();
scans.set(applicable);
if upload_errors.read().is_empty() && !offers_optin {
first_scan.set(match trigger_target_scan(id).await {
first_scan.set(match trigger_new_content_scan(id).await {
Ok(_) => FirstScan::Started,
Err(e) => FirstScan::Failed(e.to_string()),
});
+11 -10
View File
@@ -206,13 +206,13 @@ pub fn SbomPage(target: String) -> Element {
}
select {
class: "sbom-filter-select",
title: tx::IN_IMAGE_HINT.get(lang),
title: tx::IN_IMAGE_FILTER_HINT.get(lang),
onchange: move |e| {
in_image_filter.set((e.value() == "true").then_some(true));
page.set(1);
},
option { value: "", {tx::ALL_COMPONENTS.get(lang)} }
option { value: "true", {tx::IN_IMAGE.get(lang)} }
option { value: "true", {tx::IN_IMAGE_ANY.get(lang)} }
}
select {
class: "sbom-filter-select",
@@ -354,13 +354,14 @@ pub fn SbomPage(target: String) -> Element {
let edit_target = target.clone();
let edit_existing = entry.concluded.clone();
let row_key_click = row_key.clone();
// Which images hold it, and how that is known, on the badge's tooltip.
let in_image_title = entry.in_image.as_ref().map(|i| {
let hint = match i.basis {
compliance_core::models::InImageBasis::Declared => tx::IN_IMAGE_HINT,
compliance_core::models::InImageBasis::Built => tx::IN_IMAGE_BUILT_HINT,
// How it is known to be in the image names the badge; the
// tooltip adds which images hold it.
let in_image_badge = entry.in_image.as_ref().map(|i| {
let (label, hint) = match i.basis {
compliance_core::models::InImageBasis::Declared => (tx::IN_IMAGE, tx::IN_IMAGE_HINT),
compliance_core::models::InImageBasis::Built => (tx::IN_IMAGE_BUILT, tx::IN_IMAGE_BUILT_HINT),
};
format!("{} (Images: {})", hint.get(lang), i.images.join(", "))
(label.get(lang), format!("{} (Images: {})", hint.get(lang), i.images.join(", ")))
});
rsx! {
tr {
@@ -385,12 +386,12 @@ pub fn SbomPage(target: String) -> Element {
td {
style: "font-weight: 500;",
"{entry.name}"
if let Some(title) = in_image_title {
if let Some((label, title)) = in_image_badge {
" "
span {
class: "badge badge-success",
title: "{title}",
{tx::IN_IMAGE.get(lang)}
{label}
}
}
}
@@ -233,6 +233,13 @@ pub fn TargetsPage() -> Element {
"{name}"
}
span { class: "targets-type", "{ttype}" }
if str_at(t, "billing") == "extra" {
span {
class: "badge badge-neutral targets-extra",
title: tx::EXTRA_HINT.get(lang),
{tx::EXTRA.get(lang)}
}
}
if let Some(Ok(all)) = projects.read().clone() {
ProjectChips { ids: project_ids_of(t), projects: all }
}
+1 -1
View File
@@ -5,7 +5,7 @@ edition = "2021"
[dependencies]
compliance-core = { workspace = true, features = ["mongodb", "axum"] }
rmcp = { version = "0.16", features = ["server", "macros", "transport-io", "transport-streamable-http-server"] }
rmcp = { version = "3.9", features = ["server", "macros", "transport-io", "transport-streamable-http-server"] }
tokio = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
+55 -1
View File
@@ -60,7 +60,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
))
},
Arc::new(LocalSessionManager::default()),
StreamableHttpServerConfig::default(),
http_config(std::env::var("MCP_ALLOWED_HOSTS").ok().as_deref()),
);
let router = axum::Router::new()
@@ -112,3 +112,57 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
/// The Streamable HTTP configuration, with the `Host` values the server
/// answers to (DNS rebinding protection).
///
/// # Arguments
///
/// * `allowed_hosts` - `MCP_ALLOWED_HOSTS`: the hostnames or `host:port`
/// authorities clients reach the server at, comma-separated (the public
/// hostname behind the ingress, and the in-network name the dashboard
/// uses). Unset or empty, `Host` is not checked: the server sits behind the
/// ingress and per-tenant bearer tokens, as before rmcp checked it, and a
/// warning says so.
///
/// # Returns
///
/// rmcp's defaults with the host check set from `allowed_hosts`.
fn http_config(allowed_hosts: Option<&str>) -> StreamableHttpServerConfig {
let hosts: Vec<&str> = allowed_hosts
.unwrap_or_default()
.split(',')
.map(str::trim)
.filter(|h| !h.is_empty())
.collect();
let config = StreamableHttpServerConfig::default();
if hosts.is_empty() {
tracing::warn!("MCP_ALLOWED_HOSTS is not set; the Host header is not checked");
config.disable_allowed_hosts()
} else {
tracing::info!(?hosts, "MCP server answers to these hosts");
config.with_allowed_hosts(hosts)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn allowed_hosts_are_read_from_a_comma_separated_list() {
let config = http_config(Some(
" pruefwerk-stage.breakpilot.com, compliance-mcp:8090 ,",
));
assert_eq!(
config.allowed_hosts,
["pruefwerk-stage.breakpilot.com", "compliance-mcp:8090"]
);
}
#[test]
fn without_allowed_hosts_the_host_is_not_checked() {
assert!(http_config(None).allowed_hosts.is_empty());
assert!(http_config(Some(" , ")).allowed_hosts.is_empty());
}
}
+7 -12
View File
@@ -256,17 +256,12 @@ impl ComplianceMcpServer {
#[tool_handler]
impl ServerHandler for ComplianceMcpServer {
fn get_info(&self) -> ServerInfo {
ServerInfo {
protocol_version: ProtocolVersion::V_2024_11_05,
capabilities: ServerCapabilities::builder()
.enable_tools()
.build(),
server_info: Implementation::from_build_env(),
instructions: Some(
"Prüfwerk MCP server. Start with list_targets; each target's id is the repo_id/target_id the other tools take. Query findings, the CRA control mapping (OSCAL), SBOMs (CycloneDX, SPDX), CVE alerts, scan runs, DAST results and pentest sessions of your tenant."
.to_string(),
),
}
fn get_info(&self) -> ServerConfig {
ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
.with_protocol_version(ProtocolVersion::V_2024_11_05)
.with_server_info(Implementation::from_build_env())
.with_instructions(
"Prüfwerk MCP server. Start with list_targets; each target's id is the repo_id/target_id the other tools take. Query findings, the CRA control mapping (OSCAL), SBOMs (CycloneDX, SPDX), CVE alerts, scan runs, DAST results and pentest sessions of your tenant.",
)
}
}
+2 -2
View File
@@ -134,7 +134,7 @@ pub async fn list_dast_findings(
let json = serde_json::to_string_pretty(&results)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
#[derive(Debug, Deserialize, JsonSchema)]
@@ -210,5 +210,5 @@ pub async fn dast_scan_summary(
let json = serde_json::to_string_pretty(&summary)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
+3 -3
View File
@@ -153,7 +153,7 @@ pub async fn list_findings(
let json = serde_json::to_string_pretty(&results)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
#[derive(Debug, Deserialize, JsonSchema)]
@@ -179,7 +179,7 @@ pub async fn get_finding(
let json = serde_json::to_string_pretty(&finding)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
#[derive(Debug, Deserialize, JsonSchema)]
@@ -252,5 +252,5 @@ pub async fn findings_summary(
let json = serde_json::to_string_pretty(&summary)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
+1 -1
View File
@@ -39,7 +39,7 @@ where
pub fn json_result<T: serde::Serialize>(value: &T) -> Result<CallToolResult, McpError> {
let json = serde_json::to_string_pretty(value)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
/// A database error as an internal MCP error.
+1 -1
View File
@@ -47,5 +47,5 @@ pub async fn oscal_assessment(
let document = assess(&findings, chrono::Utc::now());
let json = serde_json::to_string_pretty(&document)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
+5 -5
View File
@@ -152,7 +152,7 @@ pub async fn list_pentest_sessions(
let json = serde_json::to_string_pretty(&results)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
// ── Get Pentest Session ────────────────────────────────────────
@@ -181,7 +181,7 @@ pub async fn get_pentest_session(
let json = serde_json::to_string_pretty(&session)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
// ── Get Attack Chain ───────────────────────────────────────────
@@ -223,7 +223,7 @@ pub async fn get_attack_chain(
let json = serde_json::to_string_pretty(&results)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
// ── Get Pentest Messages ───────────────────────────────────────
@@ -265,7 +265,7 @@ pub async fn get_pentest_messages(
let json = serde_json::to_string_pretty(&results)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
// ── Pentest Stats ──────────────────────────────────────────────
@@ -344,5 +344,5 @@ pub async fn pentest_stats(
let json = serde_json::to_string_pretty(&summary)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
+3 -3
View File
@@ -134,7 +134,7 @@ pub async fn list_sbom_packages(
let json = serde_json::to_string_pretty(&results)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
#[derive(Debug, Deserialize, JsonSchema)]
@@ -190,7 +190,7 @@ pub async fn sbom_vuln_report(
let json = serde_json::to_string_pretty(&report)
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
Ok(CallToolResult::success(vec![Content::text(json)]))
Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}
/// The SBOM exchange formats `get_sbom` writes.
@@ -405,5 +405,5 @@ pub async fn third_party_notices(
include_build_only: params.include_build_only,
},
);
Ok(CallToolResult::success(vec![Content::text(text)]))
Ok(CallToolResult::success(vec![ContentBlock::text(text)]))
}
+480
View File
@@ -0,0 +1,480 @@
# Active testing: a throwaway copy first, the live system later
**Status:** proposed design for the user to decide (t83) · 2026-11-06, revised
2026-11-07 after the registry review. Nothing is enabled by this note.
**Not published:** `docs/design/` is excluded from the documentation site.
## Summary
Production runs with `PW_FEATURES=source_only`. That switches off DAST, the
LLM-driven pentest, the ICS probe and OpenPLC provision-and-test for the whole
deployment. The Leistungsbeschreibung (LB 1.0.2, §4 Abs. 3) excludes active tests.
Production can import results from a test someone else ran (#337, #349).
**The proposal: active tests run against a throwaway copy by default.**
1. **The Prüfumgebung (default).** We build the customer's application from the repository
Prüfwerk already has. It is built and started in a short-lived, isolated sandbox. While
building, the only way out is a package mirror; while testing, the network is internal
only. DAST and the automated pentest run against that copy only. Then everything is
thrown away. We never send traffic to a customer's server.
2. **The code graph steers the test.** Routes taken from the code say what to test,
instead of a crawl guessing. A static finding that an entry point reaches is tried
against the copy. It is then reported as *confirmed exploitable* or *possible*.
3. **Live testing is not part of phase 1.** It would cover what only the live system
shows: TLS, headers, exposed ports, WAF, cloud configuration. It needs written
authorisation, our source IPs, rate limits and complaint handling, and that load is
out of proportion for now. The analysis below (L1–L7) stays so it can be decided later.
4. **Price per Testtag**, a unit like the Prüftag: up to 3 runs of one target on one day.
A run costs a build plus a sandbox, so it can't be unlimited. The customer books a
Testtag only by starting a run, and can cap them per month.
**Why the copy first:**
| | Prüfumgebung (copy) | Live system |
| --- | --- | --- |
| Authorisation | The code is the customer's and already ours to process under the Prüfwerk contract; the copy runs on our hardware. No third party is touched. | Written authorisation, proof of ownership, a time window |
| Traffic from our IPs to the internet | none | yes: complaints, abuse reports, WAF blocks |
| Aggressive tests (writes, fuzzing, LLM-chosen URLs) | allowed: the copy is thrown away | restricted to non-destructive at a low rate |
| Logged-in tests | easy: the Prüfprofil brings test users | needs the customer's credentials (unused today, see L4) |
| What it can't show | the real deployment (TLS, WAF, reverse proxy, cloud, real data) | that is exactly what it shows |
| Hard part | **building it** (see [What qualifies](#what-qualifies-and-what-doesnt)) | legal and operations |
## What exists today
All of this was checked against `origin/main` (168cbe9).
### Engines
| Engine | What it does | Where |
| --- | --- | --- |
| DAST | Our own Rust code; there is no ZAP or Nuclei inside (those are import formats only). Steps: recon, a depth-limited crawler, then five agents in parallel: SQL injection, XSS, auth bypass, SSRF, API fuzzer. Targets: web app, REST API, GraphQL. | `compliance-dast` |
| Automated pentest | An LLM tool loop: at most 50 iterations, 30 min by default, at most 5 sessions at once. Tools: the DAST agents, plus TLS, headers, cookies, CSP, CORS, DNS/DMARC, a rate-limit tester, an OpenAPI parser and a Chrome browser over CDP. | `compliance-agent/src/pentest`, `compliance-dast/src/tools` |
| ICS probe | Read-only: Modbus/TCP function codes 0x03, 0x01 and 0x2B/0x0E; the OPC UA HEL/ACK handshake; EtherNet/IP ListIdentity; a TCP connect scan of nine OT ports; 5 s per probe. | `werkbank-exec/src/ics` |
| OpenPLC provision-and-test | Starts a throwaway OpenPLC container per scan, loads the ST program extracted from the customer's PLC project, and runs DAST and the ICS probe against it. | `werkbank-exec/src/plc` |
### The sandbox base we already have
`werkbank-exec/src/plc/provision.rs` (306 lines) is the nearest thing to a Prüfumgebung:
- **Container hardening:**
- one container per scan, named uniquely;
- `--memory`, `--cpus` and `--pids-limit 512`;
- `--security-opt no-new-privileges` and `--stop-timeout 5`;
- no `-p`, so no port is ever published to the host.
- **Cleanup:**
- an owner label;
- a reaper that removes instances older than twice their maximum lifetime.
- **Tests:** the `docker` argument list comes from pure functions, so it is unit-tested
without Docker.
- **The DAST guard:** it runs DAST with `NetGuard::allow_private()`, but only against
that instance (`werkbank-exec/src/plc/mod.rs:253`).
**What it does not do, and a Prüfumgebung needs:**
| Gap | Today | Needed |
| --- | --- | --- |
| Network isolation | The container joins **the agent's own network** (`--network cfg.network`), so it can reach the agent, Mongo and the internet. | Building: outbound only through a package mirror (below). Testing: a fresh `docker network create --internal` per run, holding only the copy, its dependencies and the test tools. Nothing else is reachable, and nothing leaves. |
| Building | It runs a ready-made OpenPLC image. | Build the customer's image from their Dockerfile or Compose file (below). |
| Several containers | one | A Compose project: the app plus a database, cache and so on. |
| Readiness | A fixed Modbus/WebVisu port. | A health URL from the Prüfprofil, with a deadline. |
| Isolation strength | A plain Docker container, started through a Docker socket mount, which is root on the host. | Customer code is untrusted. A run needs a VM boundary (Kata/Firecracker or gVisor `runsc`), on a host that is **not** a platform node. |
| Gate | `PLC_RUNTIME_ENABLED` | The existing `PW_ALLOW_UNTRUSTED_CODE_EXEC` policy (`compliance-core/src/exec_policy.rs:83`) already says tenant code may run only "on a single-tenant or sandboxed deployment". The multi-tenant agent keeps it off. |
**Where the Prüfumgebung runs.** It runs on a Breakpilot-hosted **Werkbank runner**: a
dedicated host outside the platform nodes, not inside the agent. The Werkbank contract
already has the right shape. The control plane queues a job, and a runner leases it,
provisions, runs and posts results (`handlers/werkbank_jobs.rs`). `JobType` already has
`Dast` and `Pentest` (`compliance-core/src/models/werkbank.rs:25-33`), but nothing creates
them yet; `enqueue` only builds PLC provision jobs. On production the Werkbank path is
off.
The same runner design also serves a customer who wants the Prüfumgebung inside their own
network. That is the on-premises Werkbank direction already decided.
### What the graph does today
- **The pentest reads the graph.** `pentest/context.rs:93-140` loads up to 50 nodes
with `is_entry_point: true` and links SAST findings to them by file path. The prompt
gets a "Code Entry Points (Knowledge Graph)" section (`prompt_builder.rs:205-271`).
- **Reachability exists.** `compliance-graph/src/graph/impact.rs:30-70` searches
backwards from a finding to the entry points that reach it. It also builds call chains
of up to 10 hops, and forward blast radius. Triage puts this in its prompt
(`llm/triage.rs:317-344`).
- **Entry points are coarse.**
- Rust: `main`, `#[test]`, `#[tokio::main]` and every `pub` function.
- JavaScript: every exported function.
- Python: `main`, `__main__` and the decorators `app.route`, `app.get` and `app.post`.
- TypeScript: its own rule.
- There is no HTTP route model (method, path, parameters), and C and C# are not parsed
(that is t82).
- **No exploitability status.** Nothing marks a finding as confirmed exploitable. A
DAST finding and a SAST finding on the same weakness are not linked.
### Tests
| Area | Tests | In CI |
| --- | --- | --- |
| net_guard, guarded_net | 10 + 5 unit tests | yes |
| ICS probe, OpenPLC provisioning | 13 + 10 unit tests | yes |
| Pentest orchestrator, prompt builder | 7 + 20 unit tests | yes |
| DAST agents and tools | about 63 unit tests | **no**: `compliance-dast` is missing from CI's clippy and test steps (`ci.yml:128-164`) |
| DAST API | 2 integration tests | yes |
| A full run against a real target | none; there is no `pw-target` | no |
## Proposed design
### 1. The Prüfumgebung (default)
**The Prüfprofil.** The customer describes how to start their application. It can be a
file in the repository (`.breakpilot/pruefprofil.yml`) or a form on the target page:
- **compose:** the path of the Compose file, or a Dockerfile with a port.
- **service:** the container and port under test.
- **health:** a URL that answers 200 once the app is up.
- **seed:** an optional command that loads test data.
- **users:** test accounts with roles, which makes logged-in testing possible.
- **env:** configuration and **test secrets only**. The profile says so, and a check
refuses values that look like real keys, using the secret scanner we already run.
**A run, in outline:**
- The control plane queues a Werkbank job with the target's code and Prüfprofil.
- A Breakpilot-hosted runner builds the copy, waits for its health URL, runs DAST or the
automated pentest against it, posts the findings back, and throws everything away.
- The detailed runner and isolation design is a follow-up, written and reviewed with
infra before any code.
### The build needs the network
Building a Dockerfile already runs customer code: every `RUN` step is a command from the
repository. It also downloads packages (npm, NuGet, pip, Maven, apt). So the build is as
untrusted as the test and gets the same protection:
- **The same VM sandbox** as the test, on the same runner, never on a platform node.
- **Outbound traffic only through a package mirror.** The build network reaches a
pull-through proxy for the public registries (npm, NuGet, PyPI, Maven Central, Debian
and Alpine mirrors, Docker Hub through Harbor) and nothing else. No other egress: no
DNS to the outside, no Git clones from arbitrary hosts, no `curl` to the internet. A
build that needs anything else fails, and the build log says which host it tried.
- **The test phase stays internal-only.** The built images move to a fresh internal
network without the mirror; the test tools join it there.
- **Base images** come through the same Harbor proxy, so they are cached and logged.
**Private package feeds** need real credentials, and the Prüfprofil forbids those. Two
options:
1. **Not supported in phase 1** (recommended). A build that needs a private feed fails
as the customer's input, and the Probelauf shows it for free. The customer can vendor
the packages into the repository or publish a build image to us instead.
2. **Later: a feed token stored separately.** It is stored in the tenant's secret store,
not in the Prüfprofil; write-only from the portal, so nobody reads it back after
saving; scoped read-only to that one feed; and injected only into the build step as a
BuildKit secret, never into the image, the test phase or a log. The mirror allowlist
then gets that feed's host for this tenant only.
### Where the data lives and when it is deleted
The runner host is a new place where customer code is processed, so:
- **Location:** in Germany. If it is not our own hardware, the provider goes on the AVV's
subprocessor list before the first customer run.
- **TOM:** the runner (VM isolation, egress only through the mirror, deletion after each
run, access only for the platform team) is added to the technical and organisational
measures.
- **During a run:** the checkout, images, containers, volumes and networks exist only on
the runner, on the run's own disk, and are removed at the end of the run, with a reaper
for leftovers. Nothing is pushed to a registry.
- **After a run, on the platform** (in the tenant's database, like scan results):
- the findings;
- the build log and the start log, capped in size and passed through the secret
scanner before storing.
They are deleted with the target or the tenant, or after a retention period to be set
(proposed: logs 90 days, findings like other findings).
- **The runner keeps no customer data** after a run. Its own logs carry run ids and
counts, never code, paths or repository names.
### What qualifies and what doesn't
| Target | Prüfumgebung | Notes |
| --- | --- | --- |
| Web app or API with a working Dockerfile or Compose file and a Prüfprofil | **yes** | Phase 1. Linux containers only. |
| ASP.NET on .NET 6 or later | yes, with a Dockerfile | Routes from code need the C# parser (t82). |
| ASP.NET on .NET Framework (Windows only) | **no** | It would need Windows containers, which we don't offer. |
| PLC programs (ST, PLCopen) | yes, through the existing OpenPLC Werkbank path | Already built; off on production. |
| Firmware | only through emulation | Not in phase 1; a separate decision. |
| Desktop HMI, mobile apps | no | Static analysis only. |
| A repository with no Dockerfile or Compose file | no | We don't guess how to build it. The target page says what is missing. |
**Building is the hard part, and the note says so plainly.** Most customer repositories
don't start cleanly from a fresh checkout. They depend on a database, configuration or
private packages. Phase 1 therefore takes only what the customer has made startable: a
working Dockerfile or Compose file plus a Prüfprofil. A free **Probelauf** lets the
customer find this out before paying (see the next section).
### When the build fails
The Testtag is what is billed, not the run. A run **counts** unless it failed through our
fault: a finished run (also one stopped at its time limit, with what it found) and a run
that failed on the customer's input both count.
| Cause | Example | Counts toward the 3 runs |
| --- | --- | --- |
| Ours | The runner fails, our time limit is hit through our own load, a toolchain we claim to support is missing | **no**; the customer can start another run |
| The customer's input | The Dockerfile doesn't build, the health URL never answers, the Prüfprofil is missing or wrong | **yes**, as with t72's "failures on the customer's input count" |
| Probelauf | Only build and start, then a health check, with no test | **no**, and it books no Testtag, so the customer can fix their profile for free |
**A Testtag is charged unless all of its runs failed through our fault** (the user's
decision, 2026-11-07). A run that fails on the customer's input counts and makes the
Testtag chargeable; the free Probelauf is how a customer checks their build first.
The run's page shows which of these it was, with the build log, so the customer can fix
their side.
### Limits per run
- **Wall clock:** about 15 min to build and start, about 30 min to test, 60 min in total.
At the limit the run stops and keeps what it found.
- **Resources:** a fixed CPU, memory and disk budget per run (proposed: 4 CPUs, 8 GB,
20 GB), sized together with infra.
- **Concurrency:** one run per tenant at a time, and a fixed number per runner.
- **Cleanup:** nothing survives a run: images, containers, networks and data are removed
every time, and a reaper removes leftovers.
### 2. The graph steers the test
| Step | Exists | New |
| --- | --- | --- |
| Entry points in the pentest prompt | yes (`pentest/context.rs`) | – |
| From a finding back to the entry points that reach it, with call chains | yes (`graph/impact.rs`, used in triage) | – |
| **HTTP routes from code** (method, path, parameters) | no; entry points are coarse | Route extractors per framework: ASP.NET attributes and minimal APIs (after the C# parser of t82), Express, Flask/FastAPI, axum. An OpenAPI file in the repository counts too. The test goes through exactly these routes instead of crawling. |
| **Confirm a static finding** | no | For a SAST finding whose entry point is a route, the matching DAST check runs against that route on the copy (SQL injection for CWE-89, XSS for CWE-79, SSRF for CWE-918 and so on). |
| **Exploitability status** on a finding | no | `confirmed exploitable` (the copy showed it), `possible` (reachable, not shown) or `not tested`. The finding list and the CRA view can sort by it. |
The benefit: fewer false alarms in front of the customer, and a smaller LLM budget,
because the pentest starts from known routes and known suspects instead of exploring.
### 3. Live testing (not in phase 1)
Live testing covers what a copy can't show: TLS, security headers, exposed ports, WAF
behaviour and cloud configuration.
**Recommendation: leave it out of phase 1 entirely** and decide later. The legal work
(authorisation clause, ownership proof), the complaint handling and the operations
(published IPs, abuse contact, kill switches) are a fixed load that a small add-on
price doesn't carry: the earlier suggestion of 29 € a month with 5 runs is too low for it.
The analysis stays here so the decision can be made on it later. If it comes, it is off
by default and switched on per tenant.
**Conditions:**
- **Written authorisation:** the customer owns the target or is authorised in writing by
the owner. Draft clause below, for legal review.
- **Proof of ownership:** a DNS record or file token, checked before every run.
- **A time window** set by the customer, inside which runs may start.
- **Our source IPs**, published so customers can allowlist them, with reverse DNS and an
info page naming Breakpilot.
- **Rate limits:** low request rates, non-destructive checks only, a short time limit.
- **Complaint handling:** an abuse contact, a runbook, and kill switches globally, per
tenant, per target and per run.
**What has to change in the code before live testing** (from the survey; none of it is
reachable on production today):
| # | Gap | Size |
| --- | --- | --- |
| L1 | No ownership check exists. | M |
| L2 | Once enabled, every live-URL target would get DAST and the ICS probe every 6 hours (`change.rs:86`). Live tests must run only on request. | S |
| L3 | The target's rate limit is ignored (a fixed 100 ms in `dast.rs:172`); there is no page cap, no timeout and no overall deadline; DAST runs outside the scan concurrency limit. | M |
| L4 | `auth_config` is stored but unused, so live tests are unauthenticated. | M (later) |
| L5 | The pentest's browser and the URLs the LLM picks are not held to the target host. | M |
| L6 | `allow_destructive` is enforced only for DELETE. | S |
| L7 | The DAST and pentest routes check no role. | S |
These also apply to the Prüfumgebung, except L1 and L2:
- `compliance-dast` has to join CI;
- the routes need a role check (L7);
- the caps in L3 keep a run inside its budget.
**Draft clause** (live add-on only), for legal review:
> Der Kunde versichert, dass er Inhaber des angegebenen Prüfobjekts ist oder vom Inhaber
> schriftlich ermächtigt wurde, aktive Sicherheitsprüfungen daran zu beauftragen. Er
> beauftragt Breakpilot, das Prüfobjekt im angegebenen Zeitfenster von den in der
> Leistungsbeschreibung genannten Quell-IP-Adressen aus automatisiert zu prüfen. Der
> Kunde sorgt für eine aktuelle Sicherung und informiert betroffene Dritte, etwa seinen
> Hosting-Anbieter. Er stellt Breakpilot von Ansprüchen Dritter frei, die auf einer
> fehlenden oder unzutreffenden Ermächtigung beruhen.
### 4. Entitlement per tenant
`PW_FEATURES=source_only` stays as the global kill switch. Below it, the tenant registry
decides per tenant, as in t72:
- The entitlement check already takes an `addon` parameter that every caller passes as
`None` (`registry.rs:369`).
- The add-on name: `pruefumgebung` (and `live_testing`, only if that is decided later).
- The dashboard reads features only from the global `/version` handshake. It needs a
tenant-scoped answer: add the add-ons to the usage response of t72
(`GET /api/v1/metering/usage`).
- **Booking:** a Testtag is booked only when the customer starts a run by hand, on the
first run of that target on that day. Never automatically, never from a schedule or
a scan, and a Probelauf never books one.
- **A monthly cap set by the customer** in the portal, like `prueftag_cap`: at most N
Testtage per calendar month, none by default. At the cap, starting a run that would
book a new Testtag is refused with a message; runs on a Testtag already booked that day
still work.
- Usage events, counts only, never names:
- `testtag.booked`, key `testtag:{tenant}:{target}:{YYYY-MM-DD}`, with the number of
runs that count at the end of the day (0, when every run failed through our fault,
means not charged);
- `probelauf.run`, a count only, with no ERP item.
- Recommendation: an active run does **not** count against the t72 Prüfung quota. It is
metered on its own.
- **Testtage in the plans** (a decision for the user). Suggestion: none included in
Standard and Business in phase 1, until we have measured the cost per run on stage;
Enterprise by arrangement. A later option is N per month in Business (for example 2).
### 5. Cost and price
**Our cost per run** is an estimate, to be measured on stage:
- **Compute:**
- building and starting the copy takes about 10–15 min on 4 CPUs;
- a test takes about 30 min, with the copy and the test tools together on about 4 CPUs;
- in total about 2.5–3 CPU-hours and up to 8 GB of memory per run.
- **On a dedicated runner host** (assumption, to confirm with infra: 16 cores and 64 GB
at about 100–150 € per month), that is about 4 runs at once:
- full use: well under 0.10 € of compute per run;
- 10 % use: about 0.30–0.60 € per run.
- **The automated pentest** adds LLM time on our own model: up to 50 rounds, roughly
0.5–1 million tokens per session. That is GPU time, not money per token; measure it on
stage.
- **Fixed costs** are lower than for live testing (no complaints, no legal exposure to
third parties). They remain the runner host, support for failed builds, and the
Prüfprofil help.
**Price suggestion**, set against the 9,99 € Prüftag and the 5,99 € extra target:
ERP item codes follow the ERP scheme:
| Item | Contents | Suggestion |
| --- | --- | --- |
| `CRA-CSA-CLD-TST` (Testtag) | The Prüfumgebung for one target on one Berlin day, with up to 3 runs (DAST or automated pentest), so a customer can fix and test again the same day; not charged when all of its runs failed through our fault | 24,99 € per Testtag |
| Probelauf | Build and start only, no test | free; no ERP item, counted by `probelauf.run` |
Only if live testing is decided later (codes reserved, prices to be set then; the earlier
29 € a month with 5 runs is too low for the fixed load):
| Item | Contents |
| --- | --- |
| `CRA-CSA-CLD-LIV` | Live add-on, monthly, per tenant |
| `CRA-CSA-CLD-LRN` | An extra live run beyond those included |
A Testtag mirrors the Prüftag that customers already know. It caps our cost per booking,
and it fits how fixes really go: test, fix, test again.
## Test plan on stage
1. **pw-target:** our own deliberately vulnerable web app with a Dockerfile and a
Prüfprofil. Ideally one in ASP.NET, which also tests the C# routes from t82, and one
in Node.
2. **A repository with Compose:** an open-source app with a database in its Compose
file, to prove that several containers build and start.
3. **Probelauf:** for both, it passes; with a broken Dockerfile it fails visibly, as the
customer's fault, books no Testtag and is not charged.
4. **Runs:** DAST and the automated pentest on both. The known vulnerabilities of
pw-target are the baseline; add a nightly fixture that compares against it.
5. **Graph steering:** the routes found in code match pw-target's real routes. A planted
SQL injection found by SAST comes back as `confirmed exploitable`, and an
unreachable one as `possible`.
6. **Limits and cleanup:** the run stops at its time limit; nothing is left behind after
a run; a second run of the same tenant waits.
7. **Entitlement and metering:**
- a tenant without the add-on is refused;
- a Testtag is booked once, by the first run started by hand, and allows 3 runs;
- a run that fails on our side doesn't use one of the 3; a Testtag whose runs all
failed on our side is reported with 0 and not charged;
- a run that fails on a broken Dockerfile counts, and its Testtag is charged;
- at the monthly cap, a run that would book a new Testtag is refused;
- the usage events carry counts only.
8. **Measure** minutes, CPU, memory and LLM tokens per run, for the price.
9. **Build network:** a build that fetches from the package mirror passes; one that
tries any other host fails, and its log names the host.
10. **Live add-on:** not in phase 1; only after the user decides on it. It would run
against pw-target under a public stage name, reachable only from stage's own
address, and cover the ownership check, the time window, the rate limits and the
kill switches.
Production stays on `source_only` until the user gives the go.
## Decisions for the user
1. **The Prüfumgebung as the default** for active tests. Recommended.
2. **Live testing out of phase 1** entirely, to be decided later on the L1–L7 analysis.
Recommended.
3. **Phase 1 scope:** web apps and APIs with a Dockerfile or Compose file plus a
Prüfprofil; PLC through the existing OpenPLC path; firmware later.
4. **Private package feeds:** not supported in phase 1 (recommended), or a separately
stored, write-only feed token used only during the build.
5. **Charging** (decided 2026-11-07): billed per Testtag; failures on our side don't use
one of the 3 runs, failures on the customer's input do; a Testtag is charged unless
all of its runs failed through our fault; the Probelauf is free and books nothing.
6. **Price:** the Testtag (`CRA-CSA-CLD-TST`) at 24,99 €.
7. **Testtage in the plans:** none in Standard and Business in phase 1, Enterprise by
arrangement (suggestion); or N per month in Business.
8. **Retention:** build and start logs 90 days (proposed), findings like other findings.
9. **The runner host:** in Germany; own hardware or a provider that goes on the AVV's
subprocessor list. With infra.
10. **Order:**
1. `compliance-dast` into CI, the role check and the caps (L3, L7);
2. the runner, build-network and isolation design with infra, plus the AVV and TOM
entries;
3. the Prüfprofil;
4. routes from code (after t82);
5. the exploitability status;
6. the stage test plan.
## Needed from the registry, ERP and LB side
**For the registry and ERP:**
- The add-on `pruefumgebung` (`live_testing` only if decided later).
- The ERP item `CRA-CSA-CLD-TST` (Testtag). `CRA-CSA-CLD-LIV` and `CRA-CSA-CLD-LRN` are
reserved for a later live add-on. The Probelauf has no ERP item.
- A customer-set monthly Testtag cap in the portal, like `prueftag_cap`, none by default.
- The usage events `testtag.booked` (with the number of runs that count) and
`probelauf.run`, counts only.
**For the AVV and TOM:** the runner host as a place of processing (Germany), and its
provider as a subprocessor if it is not our own hardware.
**LB wording** for the version that ships phase 1. It replaces the exclusion in §4
Abs. 3 for tenants who booked the add-on:
> **Prüfumgebung (Zusatzleistung).** Für gebuchte Mandanten baut Prüfwerk die Anwendung
> des Kunden aus dem bereitgestellten Quellcode in einer abgeschotteten, nur für diese
> Prüfung erzeugten Umgebung in Deutschland auf und prüft sie dort aktiv auf
> Schwachstellen, unter anderem SQL-Injection, Cross-Site-Scripting, Umgehung der
> Zugriffskontrolle und Server-Side Request Forgery. Systeme des Kunden oder Dritter
> werden dabei nicht angesprochen; beim Aufbau werden Pakete ausschließlich über einen
> Paket-Spiegel aus öffentlichen Quellen bezogen. Voraussetzung ist ein lauffähiges
> Dockerfile oder eine Compose-Datei sowie ein Prüfprofil mit Testdaten; produktive
> Daten oder Zugangsdaten dürfen nicht enthalten sein. Die Umgebung wird nach jeder
> Prüfung vollständig gelöscht.
>
> Abgerechnet wird je **Testtag**. Ein Testtag umfasst bis zu drei Prüfläufe eines
> Prüfobjekts an einem Kalendertag (Europe/Berlin) und wird nur gebucht, wenn der Kunde
> einen Prüflauf startet, nie automatisch. Ein Prüflauf, der aus Gründen fehlschlägt,
> die Breakpilot zu vertreten hat, wird nicht auf die drei Prüfläufe angerechnet. Ein
> Testtag wird nicht berechnet, wenn alle seine Prüfläufe aus Gründen fehlschlagen, die
> Breakpilot zu vertreten hat. Der Kunde kann im Portal
> eine monatliche Höchstzahl an Testtagen festlegen. Ein Probelauf (nur Aufbau und
> Start) ist kostenfrei. Die Prüfung ist automatisiert und ersetzt keinen manuellen
> Penetrationstest.
**For a later live add-on** (only if decided), a starting point:
> **Live-Prüfung (Zusatzleistung).** Auf gesonderte Beauftragung prüft Prüfwerk ein vom
> Kunden benanntes, erreichbares System, dessen Inhaberschaft der Kunde nachgewiesen
> hat, im vereinbarten Zeitfenster von den unten genannten Quell-IP-Adressen aus mit
> nicht-destruktiven Prüfungen (u. a. TLS, Sicherheits-Header, offene Dienste).
> Steuerungen und industrielle Protokolle werden nicht aus dem Rechenzentrum geprüft.
+13 -3
View File
@@ -28,7 +28,10 @@ names while the scan runs.
`fixtures`, `__fixtures__`, `testdata`, `test_data`, `test-data`,
`test-fixtures` or `test_fixtures` (at any depth) hold sample projects and
lockfiles that are not what the product ships, so they produce no code
findings, no SBOM components and no CVEs. `tests/`, `spec/` and
findings, no SBOM components and no CVEs. A Semgrep rule pack counts as
test data too, with everything below it: a directory that holds a rule
file `X.yaml` next to the sample it is tested on (`X.py`, `X.cs`), as
`semgrep --test` expects. `tests/`, `spec/` and
`examples/` are scanned as usual. Paths the target's settings exclude are
left out the same way (see
[Leaving Paths out of the Scan](/guide/repositories#leaving-paths-out-of-the-scan)).
@@ -73,11 +76,18 @@ New findings appear on the target's page while the scan is still running.
Click **Prüfung starten** (Run scan), either in the row of the target in the
**Prüfobjekte** list or at the top of the target's page. The scan starts in the
background and the message "Prüfung gestartet. Den Fortschritt sehen Sie unter
Prüfläufe." appears. A new target is scanned once as soon as you create it in
the **Neues Prüfobjekt** wizard.
Prüfläufe." appears.
A manual scan always scans in full, even if nothing changed.
### Scan after new content
Creating a target in the wizard and uploading a file to a target start a scan
of the new content right away. Like a scheduled scan, it runs only when
something changed. Through the API, ask for it with
`POST /api/v1/targets/{id}/scan?reason=new_content`; without `reason`, the
scan is a Prüfung you request, which always runs in full.
### Scheduled Scans
Targets are scanned automatically on a recurring schedule: by default every 6
+4 -2
View File
@@ -278,7 +278,8 @@ the tree (with none, the component names the configuration file instead).
**Where it shows.** A badge **Im Image (deklariert)** next to the component in
the SBOM view, whose tooltip names the images and says it is read from the
recipes, not resolved by bitbake; a filter of the same name; and the SBOM list
recipes, not resolved by bitbake; the filter **Im Image** (*In the image*),
which also takes the components the build installed; and the SBOM list
puts these components first. The component's evidence line names the images,
the CycloneDX export carries the property `pruefwerk:component:in_image`
(`declared: pump-image`), and the SPDX export adds it to the package `comment`.
@@ -322,7 +323,8 @@ wizard or under **Datei hinzufügen** on the target:
**What the SPDX gives.** One component per recipe that has packages in the image
(BusyBox's `busybox`, `busybox-syslog` and `busybox-udhcpc` are one component),
with the version the build used, the declared licence and the CPE. These carry
the badge **Im Image** with the tooltip *installed by the build*. They are joined
the badge **Im Image (gebaut)** (*In the image (built)*), whose tooltip says the
build installed them. They are joined
with the recipe inventory by recipe name: the version the build used wins over the
`PV` in the tree (`busybox_1.35.0.bb` in the layer, 1.36.1 built), and both
evidence lines stay. For an image the SPDX covers, a recipe the image recipes
+611 -746
View File
File diff suppressed because it is too large. Load diff
+4 -3
View File
@@ -53,16 +53,17 @@ class FakeProjects:
def run(argv: list[str], projects: FakeProjects | None) -> int:
"""Run the script with `argv`; its exit status (0 when it returns)."""
source = SCRIPT.read_text(encoding="utf-8")
scope: dict[str, object] = {"__name__": "__main__", "__file__": str(SCRIPT)}
# The Script Engine's globals; runpy adds __name__ and __file__.
scope: dict[str, object] = {}
if projects is not None:
scope["projects"] = projects
import runpy
import sys
saved = sys.argv
sys.argv = argv
try:
exec(compile(source, str(SCRIPT), "exec"), scope)
runpy.run_path(str(SCRIPT), init_globals=scope, run_name="__main__")
except SystemExit as stop:
return int(stop.code or 0)
finally: