Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
001ab17b47 | ||
|
|
202f5ea325 | ||
|
|
ec5a68a982 | ||
|
|
96d97ae6eb | ||
|
|
6d8e63c226 | ||
|
|
99f0bb33e9 | ||
|
|
f7c2c03415 | ||
|
|
fce9edfbeb | ||
|
|
d4bfb4dc2a | ||
|
|
6fe7874ccd | ||
|
|
420ce241cd | ||
|
|
8972db0594 | ||
|
|
e9bda32dc6 | ||
|
|
a35b57ee50 | ||
|
|
e09c0d0a9d | ||
|
|
17633083e0 | ||
|
|
bcb6bfd91c | ||
|
|
87078a25b2 | ||
|
|
d1a4147488 | ||
|
|
6ab3390db3 | ||
|
|
2a10a932b0 | ||
|
|
bf24fb3370 | ||
|
|
96aab82382 | ||
|
|
0bd7ae560e | ||
|
|
6d78d2cd1e | ||
|
|
33394cc609 | ||
|
|
fdf22e99c0 | ||
|
|
08c68db65f | ||
|
|
ce93cc08d5 | ||
|
|
a3cfaf422f | ||
|
|
aee2f5b9eb | ||
|
|
a3e0618283 | ||
|
|
827b7196b5 | ||
|
|
9a0d690036 | ||
|
|
e399cea0b6 | ||
|
|
e6e5b14a04 | ||
|
|
80eb7f462c | ||
|
|
52d3735d21 | ||
|
|
62da6dbbf7 | ||
|
|
5f7c947fb3 | ||
|
|
79b8bef8ba | ||
|
|
33eb46df76 | ||
|
|
d7316dc403 | ||
|
|
12b7e9b6b8 | ||
|
|
6d700589fe | ||
|
|
492247625e | ||
|
|
6a6587a074 | ||
|
|
33b1b3127c | ||
|
|
0441220330 | ||
|
|
9d23b2c8e0 | ||
|
|
6752f54036 | ||
|
|
0249aee44a | ||
|
|
48c113bc41 | ||
|
|
88495f0c77 | ||
|
|
c62b5c7ee2 | ||
|
|
ff62bf4210 | ||
|
|
32bdada66b | ||
|
|
a5fb0aa947 | ||
|
|
8f7a2afe4d | ||
|
|
338849d050 | ||
|
|
fe318c2b85 | ||
|
|
8386032565 | ||
|
|
efb2c8a1ea | ||
|
|
52359d1786 | ||
|
|
5efc267075 | ||
|
|
dae80043e6 | ||
|
|
0e0dfadf56 | ||
|
|
fbf3a7cf29 | ||
|
|
c6d2d07999 | ||
|
|
44a48957c1 | ||
|
|
fe2414a3c0 | ||
|
|
f90bfcc5c6 | ||
|
|
27e8c866ba | ||
|
|
42c7b09151 | ||
|
|
d4cbdc822a | ||
|
|
af9c640bc1 | ||
|
|
40c7557349 | ||
|
|
0444f18a8e | ||
|
|
616732b3a3 | ||
|
|
6611c5b691 | ||
|
|
85959907b7 | ||
|
|
bc4553d576 | ||
|
|
592f947de7 | ||
|
|
55da128a3c | ||
|
|
06d2f458e6 | ||
|
|
cc3a9c7130 | ||
|
|
eef3ccdf43 | ||
|
|
aa64e2b25a | ||
|
|
6557f03d7c | ||
|
|
d9850bef90 | ||
|
|
728f3ab3bc | ||
|
|
7eb4d8054a | ||
|
|
cf08ab222d | ||
|
|
99b7769ed8 | ||
|
|
5822b51cec | ||
|
|
498d1cc443 | ||
|
|
b84c75dc2e | ||
|
|
710fdcab6f | ||
|
|
e0c54c4659 | ||
|
|
8dcdad9fe7 | ||
|
|
53bd93c96e | ||
|
|
0834547a74 |
No files matched your search
+1
-1
@@ -13,7 +13,7 @@ ignore = [
|
||||
# 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.meghsakha.com) behind orca's
|
||||
# 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.
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
# Build context: sources only. Keeps local builds from sending gigabytes of
|
||||
# build output to the daemon, and keeps local secrets (.env) out of it.
|
||||
.git
|
||||
.claude
|
||||
target
|
||||
**/node_modules
|
||||
docs/.vitepress/dist
|
||||
docs/.vitepress/cache
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
*.log
|
||||
+93
-3
@@ -30,6 +30,12 @@ NVD_API_KEY=
|
||||
|
||||
# Agent
|
||||
AGENT_PORT=3001
|
||||
# Port of the separate webhook listener (Git push / PR events).
|
||||
WEBHOOK_PORT=3002
|
||||
# Scans (and PR reviews) running at once across all tenants; each is a clone
|
||||
# plus semgrep and syft. Requests for a target already being scanned coalesce
|
||||
# into one follow-up instead of running in parallel.
|
||||
SCAN_CONCURRENCY=2
|
||||
SCAN_SCHEDULE=0 0 */6 * * *
|
||||
CVE_MONITOR_SCHEDULE=0 0 0 * * *
|
||||
GIT_CLONE_BASE_PATH=/tmp/compliance-scanner/repos
|
||||
@@ -39,7 +45,7 @@ GIT_CLONE_BASE_PATH=/tmp/compliance-scanner/repos
|
||||
# When on, a PLC/SPS target with control logic but no reachable device gets its
|
||||
# logic instantiated on a throwaway OpenPLC, probed, then torn down.
|
||||
PLC_RUNTIME_ENABLED=0
|
||||
PLC_RUNTIME_IMAGE=registry.meghsakha.com/openplc:latest
|
||||
PLC_RUNTIME_IMAGE=repo.breakpilot.com/pruefwerk/openplc:latest
|
||||
PLC_RUNTIME_NETWORK=certifai
|
||||
PLC_RUNTIME_MEMORY=512m
|
||||
PLC_RUNTIME_CPUS=0.5
|
||||
@@ -48,16 +54,72 @@ PLC_RUNTIME_OPENPLC_USER=openplc
|
||||
PLC_RUNTIME_OPENPLC_PASSWORD=openplc
|
||||
|
||||
# Werkbank runner API (/api/v1/werkbank/jobs/*, /api/v1/werkbank/artifacts/*).
|
||||
# When set, mounts the runner-facing queue + artifact endpoints behind this
|
||||
# bearer token; runners present the same token. Unset = endpoints not mounted.
|
||||
# Mounted when this static token is set OR a tenant registry is configured
|
||||
# (runners then present portal-issued `bp_…` API keys with scope
|
||||
# werkbank:runner, verified via the registry). Unset + no registry = not mounted.
|
||||
WERKBANK_RUNNER_TOKEN=
|
||||
|
||||
# Breakpilot Platform (PRODUCT_INTEGRATION_SPEC 2.0)
|
||||
# Deployment environment: dev (default) | staging | production.
|
||||
# Anything but dev is HARDENED: the agent, dashboard and MCP server refuse to
|
||||
# start unless auth is fully configured, instead of quietly serving
|
||||
# unauthenticated as the `dev` tenant. Required in staging/production:
|
||||
# KEYCLOAK_URL, KEYCLOAK_REALM, KEYCLOAK_AUDIENCE, CORS_ALLOWED_ORIGINS,
|
||||
# TENANT_REGISTRY_URL, TENANT_REGISTRY_CLIENT_ID/_SECRET,
|
||||
# PLATFORM_ALLOWED_CLIENTS, SECRETS_ENCRYPTION_KEY (+ MCP_PORT for
|
||||
# compliance-mcp, DASHBOARD_SESSION_KEY for the dashboard).
|
||||
APP_ENV=dev
|
||||
# 64 hex characters (32 bytes) that seal tenant credentials (git and tracker
|
||||
# tokens, webhook secrets) at rest. Generate with `openssl rand -hex 32`. Without
|
||||
# it the agent refuses to store a credential. Changing it makes every stored
|
||||
# credential unreadable, so keep it with the database backups.
|
||||
SECRETS_ENCRYPTION_KEY=
|
||||
# Catalog key this deployment serves; used for entitlement checks, usage
|
||||
# events and the platform handshake.
|
||||
PRODUCT_KEY=pruefwerk
|
||||
# Tenant registry: entitlement authority (POST /v1/internal/entitlements/check,
|
||||
# cached ≤60 s, fail-closed), tenant list for the scheduler, API-key verify.
|
||||
# Unset = claims-only mode (dev).
|
||||
TENANT_REGISTRY_URL=
|
||||
# client_credentials for the registry (Keycloak client `pruefwerk-svc-<env>`).
|
||||
TENANT_REGISTRY_CLIENT_ID=
|
||||
TENANT_REGISTRY_CLIENT_SECRET=
|
||||
# JWT audience that user/service tokens must carry (scope `pruefwerk-audience`).
|
||||
# Default `pruefwerk`; an empty string disables audience validation — dev only,
|
||||
# rejected at startup when APP_ENV is staging/production.
|
||||
KEYCLOAK_AUDIENCE=pruefwerk
|
||||
# Browser origins allowed by CORS (csv). Unset = permissive — dev only,
|
||||
# rejected at startup when APP_ENV is staging/production.
|
||||
CORS_ALLOWED_ORIGINS=https://app-stage.breakpilot.com,https://pruefwerk-stage.breakpilot.com
|
||||
# Keycloak client ids (azp) allowed on /api/v1/platform/* with a service token.
|
||||
# The built-in default (tenant-registry-svc-{stage,prod},portal-svc-{stage,prod})
|
||||
# applies in dev only; staging/production must name its own clients.
|
||||
PLATFORM_ALLOWED_CLIENTS=
|
||||
|
||||
# Dashboard
|
||||
DASHBOARD_PORT=8080
|
||||
AGENT_API_URL=http://localhost:3001
|
||||
# 128 hex characters (64 bytes): half signs the session cookie, half seals the
|
||||
# session records in Mongo (they hold the user's Keycloak tokens). Generate
|
||||
# with `openssl rand -hex 64`. Required in staging/production; unset in dev
|
||||
# means sessions end when the dashboard restarts.
|
||||
DASHBOARD_SESSION_KEY=
|
||||
# The platform portal, for the sidebar's "Zur Plattform" link to the user's
|
||||
# workspace (<PORTAL_URL>/<tenant_slug>/dashboard). Staging:
|
||||
# https://app-stage.breakpilot.com, production: https://app.breakpilot.com.
|
||||
# Unset hides the link.
|
||||
# PORTAL_URL=
|
||||
# The docs site the sidebar links to. Default /docs/ (the docs container on
|
||||
# the dashboard host); production uses https://docs.breakpilot.com/pruefwerk/.
|
||||
# DOCS_URL=
|
||||
|
||||
# MCP Server
|
||||
MCP_ENDPOINT_URL=http://localhost: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
|
||||
# MCP_ENDPOINT_URL when unset.
|
||||
# MCP_HEALTH_URL=
|
||||
|
||||
# Keycloak (required for authentication)
|
||||
KEYCLOAK_URL=http://localhost:8080
|
||||
@@ -66,6 +128,34 @@ KEYCLOAK_CLIENT_ID=compliance-dashboard
|
||||
REDIRECT_URI=http://localhost:8080/auth/callback
|
||||
APP_URL=http://localhost:8080
|
||||
|
||||
# Control mapping (OSCAL catalog from breakpilot-compliance)
|
||||
# Unset BREAKPILOT_BASE_URL to run snapshot-only: the image ships a CRA catalog
|
||||
# snapshot, so findings still carry control_refs without the backend. The
|
||||
# master-controls catalog is DB-derived and not shipped — turn the semantic pass
|
||||
# off when running snapshot-only.
|
||||
# BREAKPILOT_BASE_URL=https://api-dev.breakpilot.ai
|
||||
# BREAKPILOT_TOKEN=
|
||||
BREAKPILOT_SNAPSHOT_DIR=/data/compliance-scanner/oscal
|
||||
# BREAKPILOT_SEMANTIC_MAPPING=false
|
||||
# BREAKPILOT_GROUNDED_CHECKS=true
|
||||
|
||||
# Execute code from the repositories being scanned, or fetch from hosts they
|
||||
# name? A few stages do: cargo clippy compiles the repo (build.rs, proc
|
||||
# macros), ESLint runs from the repo's own node_modules, pip-compile builds
|
||||
# sdists (setup.py), the firmware reproducible build shells out to Nix with
|
||||
# sandbox=false, and npm / cargo lockfile generation and cargo metadata fetch
|
||||
# whatever the manifests name (#330). They are OFF unless this is set, and a
|
||||
# staging/production APP_ENV ignores it — the agent holds every tenant's data.
|
||||
# Without them, commit a lockfile; firmware SBOMs come from an imported
|
||||
# Firmwerk bundle.
|
||||
# PW_ALLOW_UNTRUSTED_CODE_EXEC=1
|
||||
|
||||
# Deployment feature flags (comma list). `source_only` = static analysis only:
|
||||
# the scan pipeline skips DAST, pentest, the ICS probe and the ephemeral PLC
|
||||
# runtime (recorded as skipped stages, not failures), and the dashboard hides
|
||||
# those actions. Staging runs with it until that infrastructure is deployed.
|
||||
# PW_FEATURES=source_only
|
||||
|
||||
# OpenTelemetry (optional - omit to disable)
|
||||
# OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
|
||||
# OTEL_SERVICE_NAME=compliance-agent
|
||||
+80
-47
@@ -21,14 +21,14 @@ env:
|
||||
# creds (same bucket as werkpilot). Requires repo secrets HETZNER_S3_ACCESS_KEY
|
||||
# and HETZNER_S3_SECRET_KEY.
|
||||
RUSTC_WRAPPER: /usr/local/bin/sccache
|
||||
SCCACHE_BUCKET: breakpilot-sccache
|
||||
SCCACHE_BUCKET: bp-sccache
|
||||
SCCACHE_ENDPOINT: https://nbg1.your-objectstorage.com
|
||||
SCCACHE_REGION: auto
|
||||
SCCACHE_S3_USE_SSL: "true"
|
||||
SCCACHE_S3_KEY_PREFIX: compliance-scanner
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.HETZNER_S3_ACCESS_KEY }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.HETZNER_S3_SECRET_KEY }}
|
||||
# compliance-agent depends on tramiton-core via git; use the system git so the
|
||||
# compliance-agent depends on firmwerk-core via git; use the system git so the
|
||||
# credential rewrite below (see "Configure git auth ...") is honored on fetch.
|
||||
CARGO_NET_GIT_FETCH_WITH_CLI: "true"
|
||||
# Throttle cargo so a ~670-crate concurrent download burst doesn't 429 the
|
||||
@@ -36,12 +36,14 @@ env:
|
||||
CARGO_NET_RETRY: "10"
|
||||
CARGO_HTTP_MULTIPLEXING: "false"
|
||||
|
||||
# Cancel superseded PR runs, but NEVER cancel main-branch runs — those build and
|
||||
# deploy per-service images, and cancelling one merge's deploy when the next
|
||||
# merge lands leaves a service un-deployed (as happened between two back-to-back
|
||||
# merges). So cancel-in-progress only for pull_request events.
|
||||
# Cancel superseded PR runs, but NEVER drop a main-branch run: each one deploys
|
||||
# only the services its own commit changed, so a dropped run leaves a service
|
||||
# un-deployed. `cancel-in-progress: false` is not enough, because a group keeps
|
||||
# one pending run and cancels a queued one when the next merge lands. So main
|
||||
# runs get a group per commit; the deploy jobs' own groups keep each service's
|
||||
# deploys in merge order.
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.sha }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
@@ -62,7 +64,7 @@ jobs:
|
||||
git fetch --depth=1 origin "${GITHUB_SHA}"
|
||||
git checkout FETCH_HEAD
|
||||
# Resolve crates.io deps through the self-hosted Kellnr mirror (cached,
|
||||
# crates.io-independent). Git deps (tramiton-core) are unaffected — source
|
||||
# crates.io-independent). Git deps (firmwerk-core) are unaffected — source
|
||||
# replacement only applies to crates.io-sourced crates.
|
||||
- name: Use Kellnr crates.io mirror
|
||||
run: |
|
||||
@@ -72,7 +74,7 @@ jobs:
|
||||
echo '[source.crates-io]'
|
||||
echo 'replace-with = "kellnr"'
|
||||
echo '[registries.kellnr]'
|
||||
echo 'index = "sparse+https://crates.meghsakha.com/api/v1/cratesio/"'
|
||||
echo 'index = "sparse+https://crates.breakpilot.com/api/v1/cratesio/"'
|
||||
} >> "$CARGO_HOME/config.toml"
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
@@ -86,16 +88,16 @@ jobs:
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
# compliance-agent has a git dependency on tramiton-core (a private repo on
|
||||
# compliance-agent has a git dependency on firmwerk-core (a private repo on
|
||||
# this Gitea instance). Rewrite its SSH URL to HTTPS + a PAT so the runner
|
||||
# can fetch it. Requires the repo secret TRAMITON_FETCH_TOKEN (a Gitea PAT
|
||||
# with read:repository, owned by a user with access to sharang/tramiton).
|
||||
# can fetch it. Uses the org secret PLATFORM_CI_TOKEN (bot `platform-ci`,
|
||||
# read-only member of the platform org).
|
||||
# (Honored on fetch because CARGO_NET_GIT_FETCH_WITH_CLI=true uses system git.)
|
||||
- name: Configure git auth for private tramiton dependency
|
||||
- name: Configure git auth for the private firmwerk dependency
|
||||
run: |
|
||||
git config --global \
|
||||
url."https://sharang:${{ secrets.TRAMITON_FETCH_TOKEN }}@gitea.meghsakha.com/".insteadOf \
|
||||
"ssh://git@gitea.meghsakha.com:22222/"
|
||||
url."https://platform-ci:${{ secrets.PLATFORM_CI_TOKEN }}@git.breakpilot.com/".insteadOf \
|
||||
"ssh://git@git.breakpilot.com:22222/"
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
@@ -105,19 +107,22 @@ jobs:
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
# Clippy (compiles once, sccache reuses across feature sets)
|
||||
# Clippy (compiles once, sccache reuses across feature sets). --all-targets
|
||||
# lints test code too; tests may unwrap (clippy.toml), production may not.
|
||||
- name: Clippy (core)
|
||||
run: cargo clippy -p compliance-core --all-targets -- -D warnings
|
||||
- name: Clippy (agent)
|
||||
run: cargo clippy -p compliance-agent -- -D warnings
|
||||
run: cargo clippy -p compliance-agent --all-targets -- -D warnings
|
||||
- name: Clippy (dashboard server)
|
||||
run: cargo clippy -p compliance-dashboard --features server --no-default-features -- -D warnings
|
||||
run: cargo clippy -p compliance-dashboard --features server --no-default-features --all-targets -- -D warnings
|
||||
- name: Clippy (dashboard web)
|
||||
run: cargo clippy -p compliance-dashboard --features web --no-default-features -- -D warnings
|
||||
run: cargo clippy -p compliance-dashboard --features web --no-default-features --all-targets -- -D warnings
|
||||
- name: Clippy (mcp)
|
||||
run: cargo clippy -p compliance-mcp -- -D warnings
|
||||
run: cargo clippy -p compliance-mcp --all-targets -- -D warnings
|
||||
- name: Clippy (werkbank-exec)
|
||||
run: cargo clippy -p werkbank-exec -- -D warnings
|
||||
run: cargo clippy -p werkbank-exec --all-targets -- -D warnings
|
||||
- name: Clippy (control-map)
|
||||
run: cargo clippy -p control-map -- -D warnings
|
||||
run: cargo clippy -p control-map --all-targets -- -D warnings
|
||||
|
||||
# Security audit
|
||||
- name: Security Audit
|
||||
@@ -128,6 +133,9 @@ jobs:
|
||||
# Tests (reuses compilation artifacts from clippy)
|
||||
- name: Tests (core + agent + werkbank-exec + control-map)
|
||||
run: cargo test -p compliance-core -p compliance-agent -p werkbank-exec -p control-map --lib
|
||||
# compliance-core's integration tests need no services.
|
||||
- name: Tests (core integration)
|
||||
run: cargo test -p compliance-core --tests
|
||||
- name: Tests (dashboard server)
|
||||
run: cargo test -p compliance-dashboard --features server --no-default-features
|
||||
- name: Tests (dashboard web)
|
||||
@@ -168,8 +176,9 @@ jobs:
|
||||
echo "Changed files:"
|
||||
echo "$CHANGED"
|
||||
|
||||
# Agent: core libs, agent code, agent Dockerfile
|
||||
if echo "$CHANGED" | grep -qE '^(compliance-core/|compliance-agent/|compliance-graph/|compliance-dast/|Dockerfile\.agent|Cargo\.(toml|lock))'; then
|
||||
# Agent: core libs, agent code, agent Dockerfile, and the docs and
|
||||
# README the help assistant answers from (baked into the image)
|
||||
if echo "$CHANGED" | grep -qE '^(compliance-core/|compliance-agent/|compliance-graph/|compliance-dast/|Dockerfile\.agent|Cargo\.(toml|lock)|docs/|README\.md)'; then
|
||||
echo "agent=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "agent=false" >> "$GITHUB_OUTPUT"
|
||||
@@ -201,62 +210,79 @@ jobs:
|
||||
runs-on: docker
|
||||
needs: [detect-changes]
|
||||
if: needs.detect-changes.outputs.agent == 'true'
|
||||
# One agent deploy at a time, in merge order. A queued one may be replaced
|
||||
# by a newer one, which builds from a later main and so includes it.
|
||||
concurrency:
|
||||
group: deploy-agent
|
||||
cancel-in-progress: false
|
||||
container:
|
||||
image: docker:27-cli
|
||||
steps:
|
||||
- name: Build, push and trigger orca redeploy
|
||||
env:
|
||||
# PAT for fetching the private tramiton-core git dependency during the
|
||||
# PAT for fetching the private firmwerk git dependency during the
|
||||
# image build (injected as a BuildKit secret, never baked into a layer).
|
||||
TRAMITON_FETCH_TOKEN: ${{ secrets.TRAMITON_FETCH_TOKEN }}
|
||||
PLATFORM_CI_TOKEN: ${{ secrets.PLATFORM_CI_TOKEN }}
|
||||
run: |
|
||||
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
|
||||
IMAGE=repo.meghsakha.com/certifai/compliance-agent
|
||||
echo "$REGISTRY_PASSWORD" | docker login repo.meghsakha.com -u "$REGISTRY_USERNAME" --password-stdin
|
||||
DOCKER_BUILDKIT=1 docker build --secret id=tramiton_token,env=TRAMITON_FETCH_TOKEN \
|
||||
IMAGE=repo.breakpilot.com/pruefwerk/compliance-agent
|
||||
echo "$REGISTRY_PASSWORD" | docker login repo.breakpilot.com -u "$REGISTRY_USERNAME" --password-stdin
|
||||
DOCKER_BUILDKIT=1 docker build --secret id=git_token,env=PLATFORM_CI_TOKEN \
|
||||
-f Dockerfile.agent -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
|
||||
docker push "$IMAGE:latest" && docker push "$IMAGE:${GITHUB_SHA}"
|
||||
{ command -v cosign >/dev/null 2>&1 || curl -sSfLo /usr/local/bin/cosign https://github.com/sigstore/cosign/releases/download/v2.4.3/cosign-linux-amd64 || wget -qO /usr/local/bin/cosign https://github.com/sigstore/cosign/releases/download/v2.4.3/cosign-linux-amd64; } || echo "::warning::cosign fetch failed"
|
||||
chmod +x /usr/local/bin/cosign 2>/dev/null || true
|
||||
cosign sign --yes --key env://COSIGN_KEY "$IMAGE:latest" || echo "::warning::cosign failed"
|
||||
PAYLOAD=$(printf '{"ref":"refs/heads/main","repository":{"full_name":"sharang/compliance-scanner-agent"},"head_commit":{"id":"%s","message":"deploy agent"}}' "${GITHUB_SHA}")
|
||||
PAYLOAD=$(printf '{"ref":"refs/heads/main","repository":{"full_name":"platform/pruefwerk"},"head_commit":{"id":"%s","message":"deploy agent"}}' "${GITHUB_SHA}")
|
||||
if [ -z "${{ vars.ORCA_WEBHOOK_URL }}" ]; then echo "::notice::ORCA_WEBHOOK_URL not set — image pushed, no redeploy triggered"; exit 0; fi
|
||||
SIG=$(printf '%s' "$PAYLOAD" | openssl dgst -sha256 -hmac "${{ secrets.ORCA_WEBHOOK_SECRET }}" | awk '{print $2}')
|
||||
RESP=$(curl -fsS -w "\nHTTP %{http_code}" -X POST "http://46.225.100.82:6880/api/v1/webhooks/github" -H "Content-Type: application/json" -H "X-Hub-Signature-256: sha256=$SIG" -d "$PAYLOAD"); echo "$RESP"
|
||||
RESP=$(curl -fsS -w "\nHTTP %{http_code}" -X POST "${{ vars.ORCA_WEBHOOK_URL }}" -H "Content-Type: application/json" -H "X-Hub-Signature-256: sha256=$SIG" -d "$PAYLOAD"); echo "$RESP"
|
||||
|
||||
deploy-dashboard:
|
||||
name: Deploy Dashboard
|
||||
runs-on: docker
|
||||
needs: [detect-changes]
|
||||
if: needs.detect-changes.outputs.dashboard == 'true'
|
||||
# One dashboard deploy at a time, in merge order. A queued one may be replaced
|
||||
# by a newer one, which builds from a later main and so includes it.
|
||||
concurrency:
|
||||
group: deploy-dashboard
|
||||
cancel-in-progress: false
|
||||
container:
|
||||
image: docker:27-cli
|
||||
steps:
|
||||
- name: Build, push and trigger orca redeploy
|
||||
env:
|
||||
TRAMITON_FETCH_TOKEN: ${{ secrets.TRAMITON_FETCH_TOKEN }}
|
||||
PLATFORM_CI_TOKEN: ${{ secrets.PLATFORM_CI_TOKEN }}
|
||||
run: |
|
||||
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
|
||||
IMAGE=repo.meghsakha.com/certifai/compliance-dashboard
|
||||
echo "$REGISTRY_PASSWORD" | docker login repo.meghsakha.com -u "$REGISTRY_USERNAME" --password-stdin
|
||||
DOCKER_BUILDKIT=1 docker build --secret id=tramiton_token,env=TRAMITON_FETCH_TOKEN \
|
||||
IMAGE=repo.breakpilot.com/pruefwerk/compliance-dashboard
|
||||
echo "$REGISTRY_PASSWORD" | docker login repo.breakpilot.com -u "$REGISTRY_USERNAME" --password-stdin
|
||||
DOCKER_BUILDKIT=1 docker build --secret id=git_token,env=PLATFORM_CI_TOKEN \
|
||||
-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"
|
||||
chmod +x /usr/local/bin/cosign 2>/dev/null || true
|
||||
cosign sign --yes --key env://COSIGN_KEY "$IMAGE:latest" || echo "::warning::cosign failed"
|
||||
PAYLOAD=$(printf '{"ref":"refs/heads/main","repository":{"full_name":"sharang/compliance-scanner-agent"},"head_commit":{"id":"%s","message":"deploy dashboard"}}' "${GITHUB_SHA}")
|
||||
PAYLOAD=$(printf '{"ref":"refs/heads/main","repository":{"full_name":"platform/pruefwerk"},"head_commit":{"id":"%s","message":"deploy dashboard"}}' "${GITHUB_SHA}")
|
||||
if [ -z "${{ vars.ORCA_WEBHOOK_URL }}" ]; then echo "::notice::ORCA_WEBHOOK_URL not set — image pushed, no redeploy triggered"; exit 0; fi
|
||||
SIG=$(printf '%s' "$PAYLOAD" | openssl dgst -sha256 -hmac "${{ secrets.ORCA_WEBHOOK_SECRET }}" | awk '{print $2}')
|
||||
RESP=$(curl -fsS -w "\nHTTP %{http_code}" -X POST "http://46.225.100.82:6880/api/v1/webhooks/github" -H "Content-Type: application/json" -H "X-Hub-Signature-256: sha256=$SIG" -d "$PAYLOAD"); echo "$RESP"
|
||||
RESP=$(curl -fsS -w "\nHTTP %{http_code}" -X POST "${{ vars.ORCA_WEBHOOK_URL }}" -H "Content-Type: application/json" -H "X-Hub-Signature-256: sha256=$SIG" -d "$PAYLOAD"); echo "$RESP"
|
||||
|
||||
deploy-docs:
|
||||
name: Deploy Docs
|
||||
runs-on: docker
|
||||
needs: [detect-changes]
|
||||
if: needs.detect-changes.outputs.docs == 'true'
|
||||
# One docs deploy at a time, in merge order. A queued one may be replaced
|
||||
# by a newer one, which builds from a later main and so includes it.
|
||||
concurrency:
|
||||
group: deploy-docs
|
||||
cancel-in-progress: false
|
||||
container:
|
||||
image: docker:27-cli
|
||||
steps:
|
||||
@@ -265,40 +291,47 @@ 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
|
||||
IMAGE=repo.meghsakha.com/certifai/compliance-docs
|
||||
echo "$REGISTRY_PASSWORD" | docker login repo.meghsakha.com -u "$REGISTRY_USERNAME" --password-stdin
|
||||
IMAGE=repo.breakpilot.com/pruefwerk/compliance-docs
|
||||
echo "$REGISTRY_PASSWORD" | docker login repo.breakpilot.com -u "$REGISTRY_USERNAME" --password-stdin
|
||||
docker build -f Dockerfile.docs -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
|
||||
docker push "$IMAGE:latest" && docker push "$IMAGE:${GITHUB_SHA}"
|
||||
{ command -v cosign >/dev/null 2>&1 || curl -sSfLo /usr/local/bin/cosign https://github.com/sigstore/cosign/releases/download/v2.4.3/cosign-linux-amd64 || wget -qO /usr/local/bin/cosign https://github.com/sigstore/cosign/releases/download/v2.4.3/cosign-linux-amd64; } || echo "::warning::cosign fetch failed"
|
||||
chmod +x /usr/local/bin/cosign 2>/dev/null || true
|
||||
cosign sign --yes --key env://COSIGN_KEY "$IMAGE:latest" || echo "::warning::cosign failed"
|
||||
PAYLOAD=$(printf '{"ref":"refs/heads/main","repository":{"full_name":"sharang/compliance-scanner-agent"},"head_commit":{"id":"%s","message":"deploy docs"}}' "${GITHUB_SHA}")
|
||||
PAYLOAD=$(printf '{"ref":"refs/heads/main","repository":{"full_name":"platform/pruefwerk"},"head_commit":{"id":"%s","message":"deploy docs"}}' "${GITHUB_SHA}")
|
||||
if [ -z "${{ vars.ORCA_WEBHOOK_URL }}" ]; then echo "::notice::ORCA_WEBHOOK_URL not set — image pushed, no redeploy triggered"; exit 0; fi
|
||||
SIG=$(printf '%s' "$PAYLOAD" | openssl dgst -sha256 -hmac "${{ secrets.ORCA_WEBHOOK_SECRET }}" | awk '{print $2}')
|
||||
RESP=$(curl -fsS -w "\nHTTP %{http_code}" -X POST "http://46.225.100.82:6880/api/v1/webhooks/github" -H "Content-Type: application/json" -H "X-Hub-Signature-256: sha256=$SIG" -d "$PAYLOAD"); echo "$RESP"
|
||||
RESP=$(curl -fsS -w "\nHTTP %{http_code}" -X POST "${{ vars.ORCA_WEBHOOK_URL }}" -H "Content-Type: application/json" -H "X-Hub-Signature-256: sha256=$SIG" -d "$PAYLOAD"); echo "$RESP"
|
||||
|
||||
deploy-mcp:
|
||||
name: Deploy MCP
|
||||
runs-on: docker
|
||||
needs: [detect-changes]
|
||||
if: needs.detect-changes.outputs.mcp == 'true'
|
||||
# One mcp deploy at a time, in merge order. A queued one may be replaced
|
||||
# by a newer one, which builds from a later main and so includes it.
|
||||
concurrency:
|
||||
group: deploy-mcp
|
||||
cancel-in-progress: false
|
||||
container:
|
||||
image: docker:27-cli
|
||||
steps:
|
||||
- name: Build, push and trigger orca redeploy
|
||||
env:
|
||||
TRAMITON_FETCH_TOKEN: ${{ secrets.TRAMITON_FETCH_TOKEN }}
|
||||
PLATFORM_CI_TOKEN: ${{ secrets.PLATFORM_CI_TOKEN }}
|
||||
run: |
|
||||
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
|
||||
IMAGE=repo.meghsakha.com/certifai/compliance-mcp
|
||||
echo "$REGISTRY_PASSWORD" | docker login repo.meghsakha.com -u "$REGISTRY_USERNAME" --password-stdin
|
||||
DOCKER_BUILDKIT=1 docker build --secret id=tramiton_token,env=TRAMITON_FETCH_TOKEN \
|
||||
IMAGE=repo.breakpilot.com/pruefwerk/compliance-mcp
|
||||
echo "$REGISTRY_PASSWORD" | docker login repo.breakpilot.com -u "$REGISTRY_USERNAME" --password-stdin
|
||||
DOCKER_BUILDKIT=1 docker build --secret id=git_token,env=PLATFORM_CI_TOKEN \
|
||||
-f Dockerfile.mcp -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
|
||||
docker push "$IMAGE:latest" && docker push "$IMAGE:${GITHUB_SHA}"
|
||||
{ command -v cosign >/dev/null 2>&1 || curl -sSfLo /usr/local/bin/cosign https://github.com/sigstore/cosign/releases/download/v2.4.3/cosign-linux-amd64 || wget -qO /usr/local/bin/cosign https://github.com/sigstore/cosign/releases/download/v2.4.3/cosign-linux-amd64; } || echo "::warning::cosign fetch failed"
|
||||
chmod +x /usr/local/bin/cosign 2>/dev/null || true
|
||||
cosign sign --yes --key env://COSIGN_KEY "$IMAGE:latest" || echo "::warning::cosign failed"
|
||||
PAYLOAD=$(printf '{"ref":"refs/heads/main","repository":{"full_name":"sharang/compliance-scanner-agent"},"head_commit":{"id":"%s","message":"deploy mcp"}}' "${GITHUB_SHA}")
|
||||
PAYLOAD=$(printf '{"ref":"refs/heads/main","repository":{"full_name":"platform/pruefwerk"},"head_commit":{"id":"%s","message":"deploy mcp"}}' "${GITHUB_SHA}")
|
||||
if [ -z "${{ vars.ORCA_WEBHOOK_URL }}" ]; then echo "::notice::ORCA_WEBHOOK_URL not set — image pushed, no redeploy triggered"; exit 0; fi
|
||||
SIG=$(printf '%s' "$PAYLOAD" | openssl dgst -sha256 -hmac "${{ secrets.ORCA_WEBHOOK_SECRET }}" | awk '{print $2}')
|
||||
RESP=$(curl -fsS -w "\nHTTP %{http_code}" -X POST "http://46.225.100.82:6880/api/v1/webhooks/github" -H "Content-Type: application/json" -H "X-Hub-Signature-256: sha256=$SIG" -d "$PAYLOAD"); echo "$RESP"
|
||||
RESP=$(curl -fsS -w "\nHTTP %{http_code}" -X POST "${{ vars.ORCA_WEBHOOK_URL }}" -H "Content-Type: application/json" -H "X-Hub-Signature-256: sha256=$SIG" -d "$PAYLOAD"); echo "$RESP"
|
||||
+159
-13
@@ -1,24 +1,47 @@
|
||||
name: Nightly E2E Tests
|
||||
name: Nightly scan regression
|
||||
|
||||
# Scans the fixture corpus (fixtures/demo-targets and fixtures/nightly) with
|
||||
# the agent image built from main and compares the results with the blessed
|
||||
# baselines in fixtures/nightly/baselines (#188, epic #309). A regression
|
||||
# anywhere between a tool bump and a parser change turns this red before a
|
||||
# customer sees it.
|
||||
#
|
||||
# Run it by hand with "bless" ticked after an intended change: the job then
|
||||
# rewrites the baselines instead of comparing, and the new files are in the
|
||||
# `nightly-report` artifact to commit.
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 3 * * *' # 3 AM UTC daily
|
||||
workflow_dispatch: # Allow manual trigger
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
bless:
|
||||
description: "Rewrite the baselines from this run (commit them from the artifact)"
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
RUSTFLAGS: "-D warnings"
|
||||
RUSTC_WRAPPER: /usr/local/bin/sccache
|
||||
SCCACHE_DIR: /tmp/sccache
|
||||
TEST_MONGODB_URI: "mongodb://root:example@mongo:27017/?authSource=admin"
|
||||
SCCACHE_BUCKET: bp-sccache
|
||||
SCCACHE_ENDPOINT: https://nbg1.your-objectstorage.com
|
||||
SCCACHE_REGION: auto
|
||||
SCCACHE_S3_USE_SSL: "true"
|
||||
SCCACHE_S3_KEY_PREFIX: compliance-scanner
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.HETZNER_S3_ACCESS_KEY }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.HETZNER_S3_SECRET_KEY }}
|
||||
CARGO_NET_GIT_FETCH_WITH_CLI: "true"
|
||||
CARGO_NET_RETRY: "10"
|
||||
CARGO_HTTP_MULTIPLEXING: "false"
|
||||
|
||||
concurrency:
|
||||
group: nightly-e2e
|
||||
group: nightly-scans
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
e2e:
|
||||
name: E2E Tests
|
||||
scans:
|
||||
name: Scan regression
|
||||
runs-on: docker
|
||||
container:
|
||||
image: rust:1.94-bookworm
|
||||
@@ -28,6 +51,25 @@ jobs:
|
||||
env:
|
||||
MONGO_INITDB_ROOT_USERNAME: root
|
||||
MONGO_INITDB_ROOT_PASSWORD: example
|
||||
# The image main deployed. Dev mode (no Keycloak): the harness talks to
|
||||
# the unauthenticated dev tenant; source_only matches staging.
|
||||
agent:
|
||||
image: repo.breakpilot.com/pruefwerk/compliance-agent:latest
|
||||
credentials:
|
||||
username: ${{ secrets.REGISTRY_USERNAME }}
|
||||
password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
env:
|
||||
APP_ENV: dev
|
||||
MONGODB_URI: mongodb://root:example@mongo:27017/?authSource=admin
|
||||
MONGODB_DATABASE: nightly
|
||||
PW_FEATURES: source_only
|
||||
# Optional. Without an LLM the control judge stamps no control refs,
|
||||
# which the report lists as advisory; it never fails the run.
|
||||
LITELLM_URL: ${{ secrets.NIGHTLY_LITELLM_URL }}
|
||||
LITELLM_API_KEY: ${{ secrets.NIGHTLY_LITELLM_API_KEY }}
|
||||
# Optional. The CODESYS CVE match queries NVD, which rate-limits
|
||||
# unauthenticated clients; a key keeps those CVEs from going missing.
|
||||
NVD_API_KEY: ${{ secrets.NIGHTLY_NVD_API_KEY }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
run: |
|
||||
@@ -36,17 +78,121 @@ jobs:
|
||||
git fetch --depth=1 origin "${GITHUB_SHA:-refs/heads/main}"
|
||||
git checkout FETCH_HEAD
|
||||
|
||||
- name: Use Kellnr crates.io mirror
|
||||
run: |
|
||||
: "${CARGO_HOME:=/usr/local/cargo}"
|
||||
mkdir -p "$CARGO_HOME"
|
||||
{
|
||||
echo '[source.crates-io]'
|
||||
echo 'replace-with = "kellnr"'
|
||||
echo '[registries.kellnr]'
|
||||
echo 'index = "sparse+https://crates.breakpilot.com/api/v1/cratesio/"'
|
||||
} >> "$CARGO_HOME/config.toml"
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
- name: Install sccache
|
||||
run: |
|
||||
curl -fsSL https://github.com/mozilla/sccache/releases/download/v0.9.1/sccache-v0.9.1-x86_64-unknown-linux-musl.tar.gz \
|
||||
| tar xz --strip-components=1 -C /usr/local/bin/ sccache-v0.9.1-x86_64-unknown-linux-musl/sccache
|
||||
curl -fsSL https://github.com/mozilla/sccache/releases/download/v0.10.0/sccache-v0.10.0-x86_64-unknown-linux-musl.tar.gz \
|
||||
| tar xz --strip-components=1 -C /usr/local/bin/ sccache-v0.10.0-x86_64-unknown-linux-musl/sccache
|
||||
chmod +x /usr/local/bin/sccache
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
- name: Run E2E tests
|
||||
run: cargo test -p compliance-agent --test e2e -- --test-threads=4
|
||||
# The harness links compliance-agent, which depends on the private
|
||||
# firmwerk repo; same PAT rewrite as in ci.yml.
|
||||
- name: Configure git auth for the private firmwerk dependency
|
||||
run: |
|
||||
git config --global \
|
||||
url."https://platform-ci:${{ secrets.PLATFORM_CI_TOKEN }}@git.breakpilot.com/".insteadOf \
|
||||
"ssh://git@git.breakpilot.com:22222/"
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
- name: Show sccache stats
|
||||
run: sccache --show-stats
|
||||
# The real CODESYS sample is ~10 MB, so it is fetched at a pinned commit
|
||||
# and checksum rather than committed. fixtures/nightly/targets.json skips
|
||||
# its target where NIGHTLY_CODESYS_SAMPLE is unset.
|
||||
- name: Fetch the CODESYS sample
|
||||
run: |
|
||||
curl -fsSL -o /tmp/csv-blackbox.projectarchive \
|
||||
"https://github.com/Proemion/codesys-examples/raw/164d8eea7b7483f764b4959788fd2a733624e576/CSV-BlackBox-Writter/CSV-BlackBox-Writter.projectarchive"
|
||||
echo "8e1150728e33fc0f5e2572bc060545497cfa64308c927c0d81ecda71873db265 /tmp/csv-blackbox.projectarchive" \
|
||||
| sha256sum -c -
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
# The upstream Zephyr example application, at a pinned commit so the
|
||||
# result does not drift with upstream main. codeload zips are not
|
||||
# byte-stable, so the commit pin (not a checksum) is the guarantee.
|
||||
- name: Fetch the Zephyr example application
|
||||
run: |
|
||||
curl -fsSL -o /tmp/zephyr-example.zip \
|
||||
"https://codeload.github.com/zephyrproject-rtos/example-application/zip/38a6d9b276ed434454900130cacc87d058d3ac62"
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
- name: Wait for the agent
|
||||
run: |
|
||||
for i in $(seq 1 90); do
|
||||
curl -fsS http://agent:3001/api/v1/health && exit 0
|
||||
sleep 2
|
||||
done
|
||||
echo "agent did not become healthy" >&2
|
||||
exit 1
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
- name: Scan the corpus and compare with the baselines
|
||||
run: cargo test -p compliance-agent --test nightly -- --nocapture
|
||||
env:
|
||||
NIGHTLY_AGENT_URL: http://agent:3001
|
||||
NIGHTLY_CODESYS_SAMPLE: /tmp/csv-blackbox.projectarchive
|
||||
NIGHTLY_ZEPHYR_EXAMPLE: /tmp/zephyr-example.zip
|
||||
NIGHTLY_BLESS: ${{ inputs.bless && '1' || '0' }}
|
||||
|
||||
# upload-artifact is a Node action and the Rust image has no node.
|
||||
- name: Install node for the artifact upload
|
||||
if: always()
|
||||
run: |
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq --no-install-recommends nodejs >/dev/null
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
- name: Keep the report and this run's snapshots
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: nightly-report
|
||||
path: |
|
||||
target/nightly/
|
||||
fixtures/nightly/baselines/
|
||||
|
||||
# One open issue tracks a red nightly: opened on the first failure,
|
||||
# commented on while it stays red. Needs NIGHTLY_ALERT_TOKEN (issue write
|
||||
# on this repo); without it the job still fails, just without the issue.
|
||||
- name: Alert
|
||||
if: failure() && github.event_name == 'schedule'
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
TOKEN: ${{ secrets.NIGHTLY_ALERT_TOKEN }}
|
||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
run: |
|
||||
if [ -z "$TOKEN" ]; then
|
||||
echo "::warning::NIGHTLY_ALERT_TOKEN is not set; not opening an issue"
|
||||
exit 0
|
||||
fi
|
||||
api="${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}"
|
||||
title="Nightly scan regression is red"
|
||||
body="The nightly scan regression failed: ${RUN_URL} (report in the nightly-report artifact)."
|
||||
number=$(curl -fsS -H "Authorization: token $TOKEN" \
|
||||
"$api/issues?state=open&type=issues&q=$(printf %s "$title" | sed 's/ /%20/g')" \
|
||||
| python3 -c "import json,sys; print(next((i['number'] for i in json.load(sys.stdin) if i['title']==sys.argv[1]), ''))" "$title")
|
||||
payload=$(python3 -c "import json,sys; print(json.dumps({'title': sys.argv[1], 'body': sys.argv[2]}))" "$title" "$body")
|
||||
if [ -n "$number" ]; then
|
||||
curl -fsS -X POST -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
|
||||
"$api/issues/$number/comments" -d "$payload" >/dev/null
|
||||
else
|
||||
curl -fsS -X POST -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
|
||||
"$api/issues" -d "$payload" >/dev/null
|
||||
fi
|
||||
Generated
+142
-63
@@ -104,6 +104,12 @@ dependencies = [
|
||||
"rustversion",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arraydeque"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236"
|
||||
|
||||
[[package]]
|
||||
name = "askama_escape"
|
||||
version = "0.13.0"
|
||||
@@ -659,7 +665,6 @@ dependencies = [
|
||||
name = "compliance-agent"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"axum",
|
||||
"base64",
|
||||
"chrono",
|
||||
@@ -669,6 +674,10 @@ dependencies = [
|
||||
"control-map",
|
||||
"dashmap",
|
||||
"dotenvy",
|
||||
"firmwerk-core",
|
||||
"firmwerk-repro",
|
||||
"firmwerk-sbom",
|
||||
"flate2",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"git2",
|
||||
@@ -685,6 +694,8 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"subtle",
|
||||
"tar",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tokio-cron-scheduler",
|
||||
@@ -694,9 +705,6 @@ dependencies = [
|
||||
"tower-http",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"tramiton-core",
|
||||
"tramiton-repro",
|
||||
"tramiton-sbom",
|
||||
"urlencoding",
|
||||
"uuid",
|
||||
"walkdir",
|
||||
@@ -708,7 +716,9 @@ dependencies = [
|
||||
name = "compliance-core"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"axum",
|
||||
"base64",
|
||||
"bson",
|
||||
"chrono",
|
||||
"hex",
|
||||
@@ -736,6 +746,7 @@ dependencies = [
|
||||
name = "compliance-dashboard"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64",
|
||||
"bson",
|
||||
@@ -748,8 +759,10 @@ dependencies = [
|
||||
"dioxus-logger 0.6.2",
|
||||
"dotenvy",
|
||||
"gloo-timers",
|
||||
"hex",
|
||||
"js-sys",
|
||||
"mongodb",
|
||||
"pulldown-cmark",
|
||||
"rand 0.9.2",
|
||||
"reqwest",
|
||||
"secrecy",
|
||||
@@ -765,6 +778,7 @@ dependencies = [
|
||||
"url",
|
||||
"uuid",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
@@ -2141,12 +2155,63 @@ version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
|
||||
|
||||
[[package]]
|
||||
name = "filetime"
|
||||
version = "0.2.29"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
|
||||
|
||||
[[package]]
|
||||
name = "firmwerk-core"
|
||||
version = "0.6.0"
|
||||
source = "git+ssh://git@git.breakpilot.com:22222/platform/firmwerk.git?tag=v0.6.0#232caeb1997f900f114fcbc1c1f78036de1d7348"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"tempfile",
|
||||
"thiserror 1.0.69",
|
||||
"toml",
|
||||
"walkdir",
|
||||
"yaml-rust2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "firmwerk-repro"
|
||||
version = "0.6.0"
|
||||
source = "git+ssh://git@git.breakpilot.com:22222/platform/firmwerk.git?tag=v0.6.0#232caeb1997f900f114fcbc1c1f78036de1d7348"
|
||||
dependencies = [
|
||||
"firmwerk-core",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tempfile",
|
||||
"thiserror 1.0.69",
|
||||
"toml",
|
||||
"walkdir",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "firmwerk-sbom"
|
||||
version = "0.6.0"
|
||||
source = "git+ssh://git@git.breakpilot.com:22222/platform/firmwerk.git?tag=v0.6.0#232caeb1997f900f114fcbc1c1f78036de1d7348"
|
||||
dependencies = [
|
||||
"firmwerk-core",
|
||||
"firmwerk-repro",
|
||||
"object",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fixedbitset"
|
||||
version = "0.5.7"
|
||||
@@ -2474,9 +2539,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "h2"
|
||||
version = "0.4.13"
|
||||
version = "0.4.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54"
|
||||
checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16"
|
||||
dependencies = [
|
||||
"atomic-waker",
|
||||
"bytes",
|
||||
@@ -2536,6 +2601,24 @@ dependencies = [
|
||||
"foldhash 0.2.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
dependencies = [
|
||||
"foldhash 0.2.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashlink"
|
||||
version = "0.12.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb"
|
||||
dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "headers"
|
||||
version = "0.4.1"
|
||||
@@ -4285,6 +4368,24 @@ dependencies = [
|
||||
"psl-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pulldown-cmark"
|
||||
version = "0.13.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e9f068eba8e7071c5f9511831b44f32c740d5adf574e990f946ddb53db2f314e"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"memchr",
|
||||
"pulldown-cmark-escape",
|
||||
"unicase",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pulldown-cmark-escape"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"
|
||||
|
||||
[[package]]
|
||||
name = "quinn"
|
||||
version = "0.11.9"
|
||||
@@ -4716,9 +4817,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.23.37"
|
||||
version = "0.23.45"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "758025cb5fccfd3bc2fd74708fd4682be41d99e5dff73c377c0646c6012c73a4"
|
||||
checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
|
||||
dependencies = [
|
||||
"log",
|
||||
"once_cell",
|
||||
@@ -4753,9 +4854,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.103.13"
|
||||
version = "0.103.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"
|
||||
checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
@@ -5588,6 +5689,17 @@ version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
|
||||
|
||||
[[package]]
|
||||
name = "tar"
|
||||
version = "0.4.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
|
||||
dependencies = [
|
||||
"filetime",
|
||||
"libc",
|
||||
"xattr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.26.0"
|
||||
@@ -6035,7 +6147,6 @@ dependencies = [
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tower-sessions-core",
|
||||
"tower-sessions-memory-store",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
@@ -6060,18 +6171,6 @@ dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tower-sessions-memory-store"
|
||||
version = "0.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "713fabf882b6560a831e2bbed6204048b35bdd60e50bbb722902c74f8df33460"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"time",
|
||||
"tokio",
|
||||
"tower-sessions-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing"
|
||||
version = "0.1.44"
|
||||
@@ -6173,46 +6272,6 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tramiton-core"
|
||||
version = "0.4.1"
|
||||
source = "git+ssh://git@gitea.meghsakha.com:22222/sharang/tramiton.git?tag=v0.4.1#ae4fc1376279f9edb9882605b20877335e7ba8ba"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"tempfile",
|
||||
"thiserror 1.0.69",
|
||||
"toml",
|
||||
"walkdir",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tramiton-repro"
|
||||
version = "0.4.1"
|
||||
source = "git+ssh://git@gitea.meghsakha.com:22222/sharang/tramiton.git?tag=v0.4.1#ae4fc1376279f9edb9882605b20877335e7ba8ba"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tempfile",
|
||||
"thiserror 1.0.69",
|
||||
"toml",
|
||||
"tramiton-core",
|
||||
"walkdir",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tramiton-sbom"
|
||||
version = "0.4.1"
|
||||
source = "git+ssh://git@gitea.meghsakha.com:22222/sharang/tramiton.git?tag=v0.4.1#ae4fc1376279f9edb9882605b20877335e7ba8ba"
|
||||
dependencies = [
|
||||
"object",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tramiton-core",
|
||||
"tramiton-repro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tree-sitter"
|
||||
version = "0.24.7"
|
||||
@@ -7305,6 +7364,16 @@ dependencies = [
|
||||
"tap",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xattr"
|
||||
version = "1.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rustix 1.1.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xxhash-rust"
|
||||
version = "0.8.15"
|
||||
@@ -7320,6 +7389,16 @@ dependencies = [
|
||||
"lzma-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "yaml-rust2"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "57e5b818a27a4cd30884ea380857a5e56f7ec3ba24a3990a3cc0b95af3238e18"
|
||||
dependencies = [
|
||||
"arraydeque",
|
||||
"hashlink",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "yoke"
|
||||
version = "0.8.1"
|
||||
|
||||
+4
-1
@@ -26,7 +26,7 @@ tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
mongodb = { version = "3", features = ["rustls-tls", "compat-3-0-0"] }
|
||||
reqwest = { version = "0.12", features = ["json", "rustls-tls", "multipart", "cookies"], default-features = false }
|
||||
reqwest = { version = "0.12", features = ["json", "rustls-tls", "multipart", "cookies", "stream"], default-features = false }
|
||||
thiserror = "2"
|
||||
sha2 = "0.10"
|
||||
hex = "0.4"
|
||||
@@ -34,6 +34,9 @@ uuid = { version = "1", features = ["v4", "v5", "serde"] }
|
||||
secrecy = { version = "0.10", features = ["serde"] }
|
||||
regex = "1"
|
||||
zip = { version = "2", features = ["aes-crypto", "deflate"] }
|
||||
# Uploaded tar and tar.gz source archives (ingest).
|
||||
tar = "0.4"
|
||||
flate2 = "1"
|
||||
dashmap = "6"
|
||||
tokio-stream = { version = "0.1", features = ["sync"] }
|
||||
aes-gcm = "0.10"
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ default_platform = "web"
|
||||
asset_dir = "assets"
|
||||
|
||||
[web.app]
|
||||
title = "Compliance Scanner Dashboard"
|
||||
title = "Prüfwerk · BreakPilot"
|
||||
|
||||
[web.watcher]
|
||||
reload_html = true
|
||||
|
||||
+90
-58
@@ -1,86 +1,118 @@
|
||||
# Pinned versions of every tool the agent runs. They are also written to
|
||||
# /opt/pruefwerk/tool-versions.json, so evidence can name the tool that
|
||||
# produced a finding. Bump a version together with its checksum.
|
||||
ARG RUST_VERSION=1.98.1
|
||||
ARG CARGO_AUDIT_VERSION=0.22.2
|
||||
ARG SYFT_VERSION=1.52.0
|
||||
ARG SYFT_SHA256=caeedb81fb0491615f1ebd1761e4145d41ee86dd2cc7bf80669f9f5ad9d6133d
|
||||
ARG GITLEAKS_VERSION=8.21.2
|
||||
ARG GITLEAKS_SHA256=5bc41815076e6ed6ef8fbecc9d9b75bcae31f39029ceb55da08086315316e3ba
|
||||
ARG SEMGREP_VERSION=1.177.0
|
||||
ARG RUFF_VERSION=0.16.8
|
||||
|
||||
FROM rust:1.94-bookworm AS builder
|
||||
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
# compliance-agent depends on the private tramiton-core git repo. Authenticate
|
||||
# compliance-agent depends on the private firmwerk git repo (platform/firmwerk). Authenticate
|
||||
# the fetch with a PAT passed as a BuildKit secret (never baked into a layer).
|
||||
# Build with: DOCKER_BUILDKIT=1 docker build --secret id=tramiton_token,env=TRAMITON_FETCH_TOKEN ...
|
||||
RUN --mount=type=secret,id=tramiton_token \
|
||||
if [ -s /run/secrets/tramiton_token ]; then \
|
||||
# Build with: DOCKER_BUILDKIT=1 docker build --secret id=git_token,env=PLATFORM_CI_TOKEN ...
|
||||
RUN --mount=type=secret,id=git_token \
|
||||
if [ -s /run/secrets/git_token ]; then \
|
||||
git config --global \
|
||||
url."https://sharang:$(cat /run/secrets/tramiton_token)@gitea.meghsakha.com/".insteadOf \
|
||||
"ssh://git@gitea.meghsakha.com:22222/"; \
|
||||
url."https://platform-ci:$(cat /run/secrets/git_token)@git.breakpilot.com/".insteadOf \
|
||||
"ssh://git@git.breakpilot.com:22222/"; \
|
||||
fi && \
|
||||
CARGO_NET_GIT_FETCH_WITH_CLI=true cargo build --release -p compliance-agent
|
||||
|
||||
# A throwaway stage that packs a real nix store (store paths + the validity DB)
|
||||
# into a compressed bootstrap tarball. Only the tarball is copied into the final
|
||||
# image, so we don't carry a raw /nix copy layer.
|
||||
FROM nixos/nix:latest AS nixseed
|
||||
RUN tar -C / -czf /nix-bootstrap.tar.gz nix
|
||||
# cargo-audit is compiled here, where a C toolchain exists, so the runtime image
|
||||
# needs none.
|
||||
FROM rust:1.94-bookworm AS cargo-audit
|
||||
ARG CARGO_AUDIT_VERSION
|
||||
RUN cargo install cargo-audit --version "${CARGO_AUDIT_VERSION}" --locked
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
RUN apt-get update && apt-get install -y ca-certificates libssl3 git curl python3 python3-pip npm golang-go php-cli && rm -rf /var/lib/apt/lists/*
|
||||
# The runtime without the agent binary: every scanner, pinned. Buildable on its
|
||||
# own (`--target tools`), which is how the tool installs are tested.
|
||||
FROM debian:bookworm-slim AS tools
|
||||
ARG RUST_VERSION
|
||||
ARG CARGO_AUDIT_VERSION
|
||||
ARG SYFT_VERSION
|
||||
ARG SYFT_SHA256
|
||||
ARG GITLEAKS_VERSION
|
||||
ARG GITLEAKS_SHA256
|
||||
ARG SEMGREP_VERSION
|
||||
ARG RUFF_VERSION
|
||||
|
||||
# Install Cargo (minimal, for cargo metadata / cargo audit / generate-lockfile)
|
||||
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable --profile minimal
|
||||
ENV PATH="/root/.cargo/bin:${PATH}"
|
||||
RUN cargo install cargo-audit
|
||||
# No recommended packages: python3-pip would otherwise pull in a full C
|
||||
# toolchain, which nothing at runtime needs.
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
ca-certificates libssl3 git curl python3 python3-pip npm cppcheck \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install Composer for PHP dependency resolution
|
||||
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
|
||||
# Cargo resolves Rust lockfiles and metadata for the SBOM stage. Installed
|
||||
# system-wide so the unprivileged user can run it; its caches go to the user's
|
||||
# CARGO_HOME below.
|
||||
ENV RUSTUP_HOME=/usr/local/rustup \
|
||||
PATH=/usr/local/cargo/bin:${PATH}
|
||||
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \
|
||||
| CARGO_HOME=/usr/local/cargo sh -s -- -y --no-modify-path --profile minimal \
|
||||
--default-toolchain "${RUST_VERSION}"
|
||||
|
||||
# Install Bundler for Ruby dependency resolution
|
||||
RUN apt-get update && apt-get install -y ruby && rm -rf /var/lib/apt/lists/* && gem install bundler
|
||||
RUN curl -sSfL -o /tmp/syft.tar.gz \
|
||||
"https://github.com/anchore/syft/releases/download/v${SYFT_VERSION}/syft_${SYFT_VERSION}_linux_amd64.tar.gz" \
|
||||
&& echo "${SYFT_SHA256} /tmp/syft.tar.gz" | sha256sum -c - \
|
||||
&& tar -xzf /tmp/syft.tar.gz -C /usr/local/bin syft \
|
||||
&& rm /tmp/syft.tar.gz
|
||||
|
||||
# Install syft for SBOM generation
|
||||
RUN curl -sSfL https://raw.githubusercontent.com/anchore/syft/main/install.sh | sh -s -- -b /usr/local/bin
|
||||
RUN curl -sSfL -o /tmp/gitleaks.tar.gz \
|
||||
"https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}/gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz" \
|
||||
&& echo "${GITLEAKS_SHA256} /tmp/gitleaks.tar.gz" | sha256sum -c - \
|
||||
&& tar -xzf /tmp/gitleaks.tar.gz -C /usr/local/bin gitleaks \
|
||||
&& rm /tmp/gitleaks.tar.gz
|
||||
|
||||
# Install gitleaks for secret detection
|
||||
RUN curl -sSfL https://github.com/gitleaks/gitleaks/releases/download/v8.21.2/gitleaks_8.21.2_linux_x64.tar.gz \
|
||||
| tar -xz -C /usr/local/bin gitleaks
|
||||
RUN pip3 install --break-system-packages --no-cache-dir \
|
||||
"semgrep==${SEMGREP_VERSION}" "ruff==${RUFF_VERSION}"
|
||||
|
||||
# Install semgrep for static analysis
|
||||
RUN pip3 install --break-system-packages semgrep
|
||||
RUN mkdir -p /opt/pruefwerk \
|
||||
&& printf '{"rust":"%s","cargo-audit":"%s","syft":"%s","gitleaks":"%s","semgrep":"%s","ruff":"%s","cppcheck":"%s"}\n' \
|
||||
"${RUST_VERSION}" "${CARGO_AUDIT_VERSION}" "${SYFT_VERSION}" "${GITLEAKS_VERSION}" \
|
||||
"${SEMGREP_VERSION}" "${RUFF_VERSION}" "$(cppcheck --version | cut -d' ' -f2)" \
|
||||
> /opt/pruefwerk/tool-versions.json
|
||||
|
||||
# Install ruff for Python linting
|
||||
RUN pip3 install --break-system-packages ruff
|
||||
|
||||
# Real nix for the tramiton reproducible-build firmware SBOM.
|
||||
#
|
||||
# nix-portable's proot fallback can't run here: user namespaces are blocked by
|
||||
# the container's default seccomp/apparmor profile, and orca exposes no way to
|
||||
# relax it. So ship a *real* nix and disable its build sandbox
|
||||
# (`sandbox = false`) — a plain gcc/make firmware build needs no user namespace,
|
||||
# so it runs fine under the locked-down profile with no proot involved.
|
||||
#
|
||||
# The store is shipped as a bootstrap tarball and seeded onto /nix at first
|
||||
# start (see docker/agent-entrypoint.sh), so a persistent /nix volume survives
|
||||
# redeploys. A missing/broken nix just falls back to the analysis-only SBOM.
|
||||
COPY --from=nixseed /nix-bootstrap.tar.gz /opt/nix-bootstrap.tar.gz
|
||||
ENV PATH="/nix/var/nix/profiles/default/bin:${PATH}"
|
||||
RUN mkdir -p /etc/nix && printf '%s\n' \
|
||||
'experimental-features = nix-command flakes' \
|
||||
'sandbox = false' \
|
||||
'build-users-group =' \
|
||||
'substituters = https://cache.nixos.org' \
|
||||
'trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=' \
|
||||
> /etc/nix/nix.conf
|
||||
# The agent runs unprivileged. It writes only to its home (tool caches), the
|
||||
# data root (uploaded artifacts, the OSCAL snapshot; mount a volume there) and
|
||||
# /tmp (git checkouts), so the rest of the filesystem can be read-only.
|
||||
RUN useradd --uid 10001 --user-group --create-home --home-dir /home/app --shell /usr/sbin/nologin app \
|
||||
&& mkdir -p /data/compliance-scanner/artifacts /data/compliance-scanner/oscal \
|
||||
&& chown -R app:app /data/compliance-scanner
|
||||
ENV HOME=/home/app \
|
||||
CARGO_HOME=/home/app/.cargo \
|
||||
ARTIFACT_STORE_BASE_PATH=/data/compliance-scanner/artifacts \
|
||||
BREAKPILOT_SNAPSHOT_DIR=/data/compliance-scanner/oscal
|
||||
|
||||
FROM tools
|
||||
COPY --from=cargo-audit /usr/local/cargo/bin/cargo-audit /usr/local/cargo/bin/cargo-audit
|
||||
COPY --from=builder /app/target/release/compliance-agent /usr/local/bin/compliance-agent
|
||||
COPY docker/agent-entrypoint.sh /usr/local/bin/agent-entrypoint.sh
|
||||
RUN chmod +x /usr/local/bin/agent-entrypoint.sh
|
||||
COPY --chmod=0755 docker/agent-entrypoint.sh /usr/local/bin/agent-entrypoint.sh
|
||||
# OSCAL control-catalog snapshot: lets control mapping run without the
|
||||
# breakpilot-compliance backend. The entrypoint seeds it into
|
||||
# BREAKPILOT_SNAPSHOT_DIR on start (copy-if-absent).
|
||||
COPY --from=builder /app/compliance-agent/controls/snapshot /opt/breakpilot/oscal-snapshot
|
||||
|
||||
# Copy documentation for the help chat assistant
|
||||
COPY --from=builder /app/README.md /app/README.md
|
||||
COPY --from=builder /app/docs /app/docs
|
||||
ENV HELP_DOCS_PATH=/app
|
||||
|
||||
# Ensure SSH key directory exists
|
||||
RUN mkdir -p /data/compliance-scanner/ssh
|
||||
|
||||
USER app
|
||||
EXPOSE 3001 3002
|
||||
|
||||
# Seeds /nix (fresh volume) from the bootstrap tarball, then runs the agent.
|
||||
ENTRYPOINT ["/usr/local/bin/agent-entrypoint.sh"]
|
||||
# Liveness from the agent's own health endpoint (#262 makes it report its
|
||||
# dependencies too).
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
|
||||
CMD curl -fsS "http://127.0.0.1:${AGENT_PORT:-3001}/api/v1/health" || exit 1
|
||||
|
||||
# Checks the data directories are writable, seeds the OSCAL snapshot, then runs
|
||||
# the agent.
|
||||
ENTRYPOINT ["/usr/local/bin/agent-entrypoint.sh"]
|
||||
+20
-9
@@ -2,31 +2,42 @@ FROM rust:1.94-bookworm AS builder
|
||||
|
||||
RUN cargo install dioxus-cli --version 0.7.3 --locked
|
||||
|
||||
ARG DOCS_URL=/docs
|
||||
# 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
|
||||
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
ENV DOCS_URL=${DOCS_URL}
|
||||
# compliance-agent (a workspace member) depends on the private tramiton-core git
|
||||
ENV IMPRINT_URL=${IMPRINT_URL} \
|
||||
PRIVACY_URL=${PRIVACY_URL}
|
||||
# compliance-agent (a workspace member) depends on the private firmwerk git
|
||||
# repo, so the workspace resolve needs it even to build the dashboard.
|
||||
# Authenticate the fetch with a PAT passed as a BuildKit secret.
|
||||
RUN --mount=type=secret,id=tramiton_token \
|
||||
if [ -s /run/secrets/tramiton_token ]; then \
|
||||
RUN --mount=type=secret,id=git_token \
|
||||
if [ -s /run/secrets/git_token ]; then \
|
||||
git config --global \
|
||||
url."https://sharang:$(cat /run/secrets/tramiton_token)@gitea.meghsakha.com/".insteadOf \
|
||||
"ssh://git@gitea.meghsakha.com:22222/"; \
|
||||
url."https://platform-ci:$(cat /run/secrets/git_token)@git.breakpilot.com/".insteadOf \
|
||||
"ssh://git@git.breakpilot.com:22222/"; \
|
||||
fi && \
|
||||
CARGO_NET_GIT_FETCH_WITH_CLI=true dx build --release --package compliance-dashboard
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
RUN apt-get update && apt-get install -y ca-certificates libssl3 && rm -rf /var/lib/apt/lists/*
|
||||
# curl only serves the healthcheck.
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates libssl3 curl \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& useradd --uid 10001 --user-group --no-create-home --shell /usr/sbin/nologin app
|
||||
|
||||
WORKDIR /app
|
||||
COPY --from=builder /app/target/dx/compliance-dashboard/release/web/compliance-dashboard /app/compliance-dashboard
|
||||
COPY --from=builder /app/target/dx/compliance-dashboard/release/web/public /app/public
|
||||
|
||||
ENV IP=0.0.0.0
|
||||
# Sessions live in Mongo, so the dashboard writes nothing to its filesystem.
|
||||
USER app
|
||||
EXPOSE 8080
|
||||
|
||||
ENTRYPOINT ["./compliance-dashboard"]
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
|
||||
CMD curl -fsS "http://127.0.0.1:${PORT:-8080}/health" || exit 1
|
||||
|
||||
ENTRYPOINT ["./compliance-dashboard"]
|
||||
+2
-1
@@ -10,6 +10,7 @@ RUN npm run build
|
||||
FROM nginx:alpine
|
||||
RUN rm /etc/nginx/conf.d/default.conf
|
||||
COPY docs/nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY --from=builder /app/.vitepress/dist /usr/share/nginx/html
|
||||
# base is /docs/ (see docs/.vitepress/config.mts) — the site lives under /docs/
|
||||
COPY --from=builder /app/.vitepress/dist /usr/share/nginx/html/docs
|
||||
EXPOSE 80
|
||||
|
||||
+15
-8
@@ -2,25 +2,32 @@ FROM rust:1.94-bookworm AS builder
|
||||
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
# compliance-agent (a workspace member) depends on the private tramiton-core git
|
||||
# compliance-agent (a workspace member) depends on the private firmwerk git
|
||||
# repo, so the workspace resolve needs it even to build the mcp binary.
|
||||
# Authenticate the fetch with a PAT passed as a BuildKit secret.
|
||||
RUN --mount=type=secret,id=tramiton_token \
|
||||
if [ -s /run/secrets/tramiton_token ]; then \
|
||||
RUN --mount=type=secret,id=git_token \
|
||||
if [ -s /run/secrets/git_token ]; then \
|
||||
git config --global \
|
||||
url."https://sharang:$(cat /run/secrets/tramiton_token)@gitea.meghsakha.com/".insteadOf \
|
||||
"ssh://git@gitea.meghsakha.com:22222/"; \
|
||||
url."https://platform-ci:$(cat /run/secrets/git_token)@git.breakpilot.com/".insteadOf \
|
||||
"ssh://git@git.breakpilot.com:22222/"; \
|
||||
fi && \
|
||||
CARGO_NET_GIT_FETCH_WITH_CLI=true cargo build --release -p compliance-mcp
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
RUN apt-get update && apt-get install -y ca-certificates libssl3 && rm -rf /var/lib/apt/lists/*
|
||||
# curl only serves the healthcheck.
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates libssl3 curl \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& useradd --uid 10001 --user-group --no-create-home --shell /usr/sbin/nologin app
|
||||
|
||||
COPY --from=builder /app/target/release/compliance-mcp /usr/local/bin/compliance-mcp
|
||||
|
||||
ENV MCP_PORT=8090
|
||||
# The MCP server writes nothing to its filesystem.
|
||||
USER app
|
||||
EXPOSE 8090
|
||||
|
||||
ENV MCP_PORT=8090
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||
CMD curl -fsS "http://127.0.0.1:${MCP_PORT}/health" || exit 1
|
||||
|
||||
ENTRYPOINT ["compliance-mcp"]
|
||||
|
||||
@@ -146,6 +146,28 @@ docker compose up -d
|
||||
|
||||
This starts MongoDB, SearXNG, the agent (port 3001), and the dashboard (port 8080).
|
||||
|
||||
### Nightly scan regression
|
||||
|
||||
Every night CI scans the fixture corpus with the agent image built from `main`
|
||||
and compares the results with the baselines in `fixtures/nightly/baselines/`
|
||||
(`.gitea/workflows/nightly.yml`). The corpus is the demo targets
|
||||
(`fixtures/demo-targets/targets.json`, seeded by the agent itself) plus the
|
||||
nightly-only fixtures (`fixtures/nightly/targets.json`: CODESYS archives, a
|
||||
ladder diagram, a live PLC endpoint, a corrupt archive), which the harness
|
||||
onboards through the API. The real CODESYS sample is not committed; point
|
||||
`NIGHTLY_CODESYS_SAMPLE` at it or its target is skipped. To run it against any
|
||||
agent in dev mode (use a fresh database: a rescan of an unchanged repo skips
|
||||
most stages, so it records less than a first scan):
|
||||
|
||||
```bash
|
||||
NIGHTLY_AGENT_URL=http://localhost:3001 \
|
||||
cargo test -p compliance-agent --test nightly -- --nocapture
|
||||
```
|
||||
|
||||
After an intended change to scan results, re-bless with `NIGHTLY_BLESS=1` (or
|
||||
run the workflow by hand with "bless" ticked) and commit the baseline diff with
|
||||
the change. The report lands in `target/nightly/report.md`.
|
||||
|
||||
## REST API
|
||||
|
||||
The agent exposes a REST API on port 3001:
|
||||
@@ -154,43 +176,55 @@ The agent exposes a REST API on port 3001:
|
||||
|--------|----------|-------------|
|
||||
| `GET` | `/api/v1/health` | Health check |
|
||||
| `GET` | `/api/v1/stats/overview` | Summary statistics and trends |
|
||||
| `GET` | `/api/v1/repositories` | List tracked repositories |
|
||||
| `POST` | `/api/v1/repositories` | Add a repository to track |
|
||||
| `POST` | `/api/v1/repositories/:id/scan` | Trigger a manual scan |
|
||||
| `GET` | `/api/v1/targets` | List targets (Prüfobjekte), each with its newest scan run |
|
||||
| `POST` | `/api/v1/targets` | Create a target |
|
||||
| `GET` / `PATCH` / `DELETE` | `/api/v1/targets/{id}` | Read, update (name, type, artifacts, `scan_config` incl. `issue_tracker`) or delete a target |
|
||||
| `POST` | `/api/v1/targets/{id}/artifacts` | Add a git repository, URL or text artifact |
|
||||
| `POST` | `/api/v1/targets/{id}/artifacts/upload` | Upload a file artifact (multipart, up to 512 MiB) |
|
||||
| `PUT` | `/api/v1/targets/{id}/artifacts/{artifact_id}/archive-password` | Set the password of a password-protected archive |
|
||||
| `POST` | `/api/v1/targets/{id}/scan` | Trigger a manual scan |
|
||||
| `GET` | `/api/v1/targets/{id}/compliance` | CRA Annex I status of a target |
|
||||
| `GET` | `/api/v1/targets/{id}/evidence-pack` | Evidence pack (ZIP) |
|
||||
| `POST` | `/api/v1/targets/{id}/findings` | Add a finding from a manual test |
|
||||
| `POST` | `/api/v1/targets/{id}/findings/import` | Import SARIF 2.1.0 or ZAP JSON |
|
||||
| `GET` | `/api/v1/findings` | List findings (filterable) |
|
||||
| `GET` | `/api/v1/findings/:id` | Get finding with code evidence |
|
||||
| `PATCH` | `/api/v1/findings/:id/status` | Update finding status |
|
||||
| `GET` | `/api/v1/findings/{id}` | Get finding with code evidence |
|
||||
| `PATCH` | `/api/v1/findings/{id}/status` | Update finding status (with `reason` where required) |
|
||||
| `PATCH` | `/api/v1/findings/bulk-status` | Update the status of several findings |
|
||||
| `GET` | `/api/v1/sbom` | List dependencies |
|
||||
| `GET` | `/api/v1/sbom/export` | Export a target's SBOM (CycloneDX 1.5 or SPDX 2.3) |
|
||||
| `GET` | `/api/v1/issues` | List cross-tracker issues |
|
||||
| `GET` | `/api/v1/scan-runs` | Scan execution history |
|
||||
| `GET` | `/api/v1/graph/:repo_id` | Code knowledge graph |
|
||||
| `POST` | `/api/v1/graph/:repo_id/build` | Trigger graph build |
|
||||
| `GET` | `/api/v1/graph/{repo_id}` | Code knowledge graph |
|
||||
| `POST` | `/api/v1/graph/{repo_id}/build` | Trigger graph build |
|
||||
| `GET` | `/api/v1/dast/targets` | List DAST targets |
|
||||
| `POST` | `/api/v1/dast/targets` | Add DAST target |
|
||||
| `GET` | `/api/v1/dast/findings` | List DAST findings |
|
||||
| `POST` | `/api/v1/chat/:repo_id` | RAG-powered code chat |
|
||||
| `POST` | `/api/v1/chat/{repo_id}` | RAG-powered code chat |
|
||||
| `POST` | `/api/v1/help/chat` | Documentation-grounded help chat |
|
||||
| `POST` | `/api/v1/pentest/sessions` | Create pentest session |
|
||||
| `POST` | `/api/v1/pentest/sessions/:id/export` | Export encrypted pentest report |
|
||||
| `POST` | `/webhook/github` | GitHub webhook (HMAC-SHA256) |
|
||||
| `POST` | `/webhook/gitlab` | GitLab webhook (token verify) |
|
||||
| `POST` | `/webhook/gitea` | Gitea webhook |
|
||||
| `POST` | `/api/v1/pentest/sessions/{id}/export` | Export encrypted pentest report |
|
||||
| `POST` | `/webhook/{tenant_id}/github/{repo_id}` | GitHub webhook (HMAC-SHA256) |
|
||||
| `POST` | `/webhook/{tenant_id}/gitlab/{repo_id}` | GitLab webhook (token verify) |
|
||||
| `POST` | `/webhook/{tenant_id}/gitea/{repo_id}` | Gitea webhook |
|
||||
|
||||
## Dashboard Pages
|
||||
|
||||
| Page | Description |
|
||||
|------|-------------|
|
||||
| **Overview** | Stat cards, severity distribution, AI chat cards, MCP status |
|
||||
| **Repositories** | Add/manage tracked repos, trigger scans, webhook config |
|
||||
| **Findings** | Filterable table by severity, type, status, scanner |
|
||||
| **Finding Detail** | Code evidence, remediation, suggested fix, linked issue |
|
||||
| **Übersicht** (Overview) | Figures, CRA status by target, most severe open findings; AI chat and MCP cards outside source-only deployments |
|
||||
| **Prüfobjekte** (Targets) | Targets with last scan, CRA status and findings; **Prüfung starten** |
|
||||
| **Neues Prüfobjekt** (Onboard) | Wizard: type, artifacts (git, zip/tar/tar.gz, PLC project, firmware image), review, first scan |
|
||||
| **Target page** | CRA status, SBOM figures, open findings, scan runs, edit, evidence pack, manual findings |
|
||||
| **Findings** | Filterable table by target, severity, type, status |
|
||||
| **Finding Detail** | Code evidence, CRA refs, remediation, status with reason and history, linked issue |
|
||||
| **SBOM** | Dependency inventory with vulnerability badges, license summary |
|
||||
| **Issues** | Cross-tracker view (GitHub + GitLab + Jira + Gitea) |
|
||||
| **Code Graph** | Interactive architecture visualization, impact analysis |
|
||||
| **AI Chat** | RAG-powered Q&A about repository code |
|
||||
| **DAST** | Dynamic scanning targets, findings, and scan history |
|
||||
| **Pentest** | AI-driven pentest sessions, attack chain visualization |
|
||||
| **MCP Servers** | Model Context Protocol server management |
|
||||
| **MCP Servers** | Model Context Protocol server management (reached from the overview's MCP card; no sidebar entry) |
|
||||
| **Help Chat** | Floating assistant (available on every page) for product Q&A |
|
||||
|
||||
## Project Structure
|
||||
|
||||
@@ -1 +1,5 @@
|
||||
avoid-breaking-exported-api = false
|
||||
# Tests may unwrap: a panic is how a test fails. Production code keeps the
|
||||
# workspace-wide deny on unwrap_used / expect_used.
|
||||
allow-unwrap-in-tests = true
|
||||
allow-expect-in-tests = true
|
||||
+17
-11
@@ -7,7 +7,7 @@ edition = "2021"
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
compliance-core = { workspace = true, features = ["mongodb", "telemetry", "axum"] }
|
||||
compliance-core = { workspace = true, features = ["mongodb", "telemetry", "axum", "secrets"] }
|
||||
control-map = { workspace = true }
|
||||
compliance-graph = { path = "../compliance-graph" }
|
||||
compliance-dast = { path = "../compliance-dast" }
|
||||
@@ -15,15 +15,18 @@ compliance-dast = { path = "../compliance-dast" }
|
||||
# used by the Werkbank runner.
|
||||
werkbank-exec = { path = "../werkbank-exec" }
|
||||
# Native firmware build/target detection for bare-metal & RTOS artifacts.
|
||||
# Same-company IP, used directly (not via CLI) so the whole tramiton suite is
|
||||
# available to the onboarding classifier. NOTE: CI must be able to fetch this
|
||||
# Same-company IP, used directly (not via CLI) so the whole firmwerk suite is
|
||||
# available to the onboarding classifier. Repo: git.breakpilot.com/platform/firmwerk;
|
||||
# crates are firmwerk-* from tag v0.6.0 (declared-dependency SBOM, #38).
|
||||
# NOTE: CI must be able to fetch this
|
||||
# private repo (see the git-auth step in .gitea/workflows/ci.yml).
|
||||
tramiton-core = { git = "ssh://git@gitea.meghsakha.com:22222/sharang/tramiton.git", tag = "v0.4.1" }
|
||||
# tramiton-repro drives the reproducible build (NixBackend seal_and_build) that
|
||||
# yields a sealed lock; `libraries_from_inputs` is the analysis-only fallback.
|
||||
tramiton-repro = { git = "ssh://git@gitea.meghsakha.com:22222/sharang/tramiton.git", tag = "v0.4.1" }
|
||||
# tramiton-sbom renders the bill of materials from a sealed lock (+ binary SCA).
|
||||
tramiton-sbom = { git = "ssh://git@gitea.meghsakha.com:22222/sharang/tramiton.git", tag = "v0.4.1" }
|
||||
firmwerk-core = { git = "ssh://git@git.breakpilot.com:22222/platform/firmwerk.git", tag = "v0.6.0" }
|
||||
# firmwerk-repro drives the reproducible build (NixBackend seal_and_build) that
|
||||
# yields a sealed lock.
|
||||
firmwerk-repro = { git = "ssh://git@git.breakpilot.com:22222/platform/firmwerk.git", tag = "v0.6.0" }
|
||||
# firmwerk-sbom renders the bill of materials from a sealed lock or, without a
|
||||
# build, from the analysed plan (+ binary SCA).
|
||||
firmwerk-sbom = { git = "ssh://git@git.breakpilot.com:22222/platform/firmwerk.git", tag = "v0.6.0" }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
@@ -45,6 +48,8 @@ octocrab = "0.44"
|
||||
tokio-cron-scheduler = "0.13"
|
||||
dotenvy = "0.15"
|
||||
hmac = "0.12"
|
||||
# Constant-time comparison of the GitLab webhook token.
|
||||
subtle = "2.6"
|
||||
walkdir = "2"
|
||||
# Read-only XML tree parsing for PLCopen project files (POU extraction).
|
||||
roxmltree = "0.20"
|
||||
@@ -53,7 +58,8 @@ urlencoding = "2"
|
||||
futures-util = "0.3"
|
||||
jsonwebtoken = "9"
|
||||
zip = { workspace = true }
|
||||
aes-gcm = { workspace = true }
|
||||
tar = { workspace = true }
|
||||
flate2 = { workspace = true }
|
||||
tokio-tungstenite = { version = "0.26", features = ["rustls-tls-webpki-roots"] }
|
||||
futures-core = "0.3"
|
||||
dashmap = { workspace = true }
|
||||
@@ -61,7 +67,7 @@ tokio-stream = { workspace = true }
|
||||
rand = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
compliance-core = { workspace = true, features = ["mongodb", "axum"] }
|
||||
compliance-core = { workspace = true, features = ["mongodb", "axum", "secrets"] }
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
reqwest = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -115,3 +115,119 @@ rules:
|
||||
- pattern: 'crypto.createCipheriv("des-ecb", ...)'
|
||||
- pattern: 'crypto.createCipheriv("des", ...)'
|
||||
- pattern: 'crypto.createCipher(...)'
|
||||
|
||||
# --- C/C++ firmware ------------------------------------------------------------
|
||||
# C and C++ sources alike (`languages: [c, cpp]`), with the `std::` spellings.
|
||||
# Microcontroller code: unbounded string handling, non-literal format strings,
|
||||
# credentials compiled into every device, broken crypto and predictable
|
||||
# randomness. Memory-safety defects that need data flow (out-of-bounds
|
||||
# writes, uninitialised reads) come from cppcheck, not from these patterns.
|
||||
- id: cra-ai-20-c-unbounded-string-function
|
||||
languages: [c, cpp]
|
||||
severity: ERROR
|
||||
message: $FN() writes without a bound on the destination — input longer than the buffer overflows it (CWE-120). Use a bounded call (snprintf, strncpy/strlcpy with the buffer size).
|
||||
metadata:
|
||||
cwe: ["CWE-120: Buffer Copy without Checking Size of Input"]
|
||||
control: cra-ai-20
|
||||
patterns:
|
||||
- pattern: $FN(...)
|
||||
- metavariable-regex:
|
||||
metavariable: $FN
|
||||
regex: ^(std::)?(gets|strcpy|strcat|sprintf|vsprintf|wcscpy|wcscat)$
|
||||
|
||||
- id: cra-ai-20-c-scanf-unbounded-string
|
||||
languages: [c, cpp]
|
||||
severity: ERROR
|
||||
message: A "%s" conversion without a field width reads unbounded input into a fixed buffer (CWE-120). Give the conversion a width, e.g. "%15s".
|
||||
metadata:
|
||||
cwe: ["CWE-120: Buffer Copy without Checking Size of Input"]
|
||||
control: cra-ai-20
|
||||
patterns:
|
||||
- pattern-either:
|
||||
- pattern: scanf($FMT, ...)
|
||||
- pattern: sscanf($SRC, $FMT, ...)
|
||||
- pattern: fscanf($FILE, $FMT, ...)
|
||||
- metavariable-regex:
|
||||
metavariable: $FMT
|
||||
regex: ^".*%s.*"$
|
||||
|
||||
- id: cra-ai-20-c-non-literal-format-string
|
||||
languages: [c, cpp]
|
||||
severity: WARNING
|
||||
message: The format string is not a literal — text an attacker controls can read or write memory through format specifiers (CWE-134). Print it with a literal format, e.g. printf("%s", text).
|
||||
metadata:
|
||||
cwe: ["CWE-134: Use of Externally-Controlled Format String"]
|
||||
control: cra-ai-20
|
||||
patterns:
|
||||
- pattern-either:
|
||||
- pattern: printf($FMT, ...)
|
||||
- pattern: vprintf($FMT, ...)
|
||||
- pattern: fprintf($F, $FMT, ...)
|
||||
- pattern: sprintf($B, $FMT, ...)
|
||||
- pattern: snprintf($B, $N, $FMT, ...)
|
||||
- pattern: syslog($P, $FMT, ...)
|
||||
# C++ reaches the same functions through std::.
|
||||
- pattern: std::printf($FMT, ...)
|
||||
- pattern: std::fprintf($F, $FMT, ...)
|
||||
- pattern: std::sprintf($B, $FMT, ...)
|
||||
- pattern: std::snprintf($B, $N, $FMT, ...)
|
||||
# Not a literal, and not an upper-case macro (`#define GET_REQUEST
|
||||
# "GET / HTTP/1.1"`): a macro like that expands to a literal.
|
||||
- metavariable-regex:
|
||||
metavariable: $FMT
|
||||
regex: ^(?![A-Z][A-Z0-9_]*$)[^"]
|
||||
|
||||
- id: cra-ai-8-c-hardcoded-credential
|
||||
languages: [c, cpp]
|
||||
severity: ERROR
|
||||
message: A credential ($NAME) is written into the firmware source — every device ships the same secret, and it can be read out of the image (CWE-798). Provision it per device at production or first boot.
|
||||
metadata:
|
||||
cwe: ["CWE-798: Use of Hard-coded Credentials"]
|
||||
control: cra-ai-8
|
||||
patterns:
|
||||
- pattern-either:
|
||||
- pattern: $TYPE $NAME = "$VALUE";
|
||||
- pattern: $TYPE *$NAME = "$VALUE";
|
||||
- pattern: $TYPE $NAME[] = "$VALUE";
|
||||
- pattern: $TYPE $NAME[$N] = "$VALUE";
|
||||
# The usual embedded style: a macro in a config header
|
||||
# (`#define WIFI_PASS "..."`), which semgrep's C patterns do not see.
|
||||
- pattern-regex: '(?m)^[ \t]*#[ \t]*define[ \t]+(?P<NAME>\w+)[ \t]+"(?P<VALUE>[^"]*)"'
|
||||
- metavariable-regex:
|
||||
metavariable: $NAME
|
||||
regex: (?i).*((^|_)pass($|_)|passw|pwd|secret|api_?key|token|psk|credential).*
|
||||
# Six characters or more, and not a placeholder left for the installer.
|
||||
- metavariable-regex:
|
||||
metavariable: $VALUE
|
||||
regex: ^(?!(?i:changeme|change_me|password|secret|admin|x{3,}|your_\w*|<[^>]*>|\*+)$).{6,}$
|
||||
|
||||
- id: cra-ai-13-c-broken-hash-or-cipher
|
||||
languages: [c, cpp]
|
||||
severity: WARNING
|
||||
message: $FN uses a broken algorithm (MD5, SHA-1 or DES) that protects neither integrity nor confidentiality (CWE-327). Use SHA-256 or better, and AES-GCM or ChaCha20-Poly1305.
|
||||
metadata:
|
||||
cwe: ["CWE-327: Use of a Broken or Risky Cryptographic Algorithm"]
|
||||
control: cra-ai-13
|
||||
patterns:
|
||||
- pattern: $FN(...)
|
||||
- metavariable-regex:
|
||||
metavariable: $FN
|
||||
regex: ^(MD5|MD5_Init|MD5_Update|MD5_Final|SHA1|SHA1_Init|SHA1_Update|SHA1_Final|DES_\w+|mbedtls_md5\w*|mbedtls_sha1\w*|mbedtls_des_\w+|wc_Md5\w*|wc_InitSha|wc_ShaUpdate|wc_ShaFinal|wc_Des_\w+)$
|
||||
|
||||
- id: cra-ai-16-c-predictable-random
|
||||
languages: [c, cpp]
|
||||
severity: WARNING
|
||||
message: rand() is predictable, so $NAME can be guessed (CWE-338). Take keys, nonces and tokens from the MCU's hardware RNG or a DRBG.
|
||||
metadata:
|
||||
cwe: ["CWE-338: Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)"]
|
||||
control: cra-ai-16
|
||||
patterns:
|
||||
- pattern-either:
|
||||
- pattern: $NAME = rand();
|
||||
- pattern: $NAME = rand() % $M;
|
||||
- pattern: $NAME = ($T) rand();
|
||||
- pattern: $TYPE $NAME = rand();
|
||||
- pattern: $TYPE $NAME = rand() % $M;
|
||||
- metavariable-regex:
|
||||
metavariable: $NAME
|
||||
regex: (?i).*(key|nonce|iv|token|salt|secret|challenge|session).*
|
||||
+293
-14
@@ -4,11 +4,14 @@ use dashmap::DashMap;
|
||||
use tokio::sync::{broadcast, watch, Semaphore};
|
||||
|
||||
use compliance_core::models::pentest::PentestEvent;
|
||||
use compliance_core::AgentConfig;
|
||||
use compliance_core::{AgentConfig, NetGuard};
|
||||
|
||||
use crate::database::DatabasePool;
|
||||
use crate::llm::LlmClient;
|
||||
use crate::pipeline::orchestrator::PipelineOrchestrator;
|
||||
use crate::registry::RegistryClient;
|
||||
use crate::scan_gate::{Admission, HeldTarget, ScanGate};
|
||||
use crate::secrets::SecretBox;
|
||||
|
||||
/// Default maximum concurrent pentest sessions.
|
||||
const DEFAULT_MAX_CONCURRENT_SESSIONS: usize = 5;
|
||||
@@ -28,6 +31,17 @@ pub struct ComplianceAgent {
|
||||
pub session_pause: Arc<DashMap<String, watch::Sender<bool>>>,
|
||||
/// Semaphore limiting concurrent pentest sessions.
|
||||
pub session_semaphore: Arc<Semaphore>,
|
||||
/// Platform tenant-registry client (entitlements, tenant list, API keys,
|
||||
/// usage events). `None` when `TENANT_REGISTRY_URL` is unset (dev).
|
||||
pub registry: Option<Arc<RegistryClient>>,
|
||||
/// Where tenants may point a scan (SSRF policy). Public-only unless an
|
||||
/// on-premise deployment opts in via `PW_ALLOW_PRIVATE_TARGETS`.
|
||||
pub net_guard: NetGuard,
|
||||
/// Global scan slots and per-target coalescing (#258).
|
||||
pub scan_gate: Arc<ScanGate>,
|
||||
/// Seals tenant credentials before they are stored and opens them where
|
||||
/// they are used (#260).
|
||||
pub secrets: SecretBox,
|
||||
}
|
||||
|
||||
impl ComplianceAgent {
|
||||
@@ -43,6 +57,10 @@ impl ComplianceAgent {
|
||||
.connect_timeout(std::time::Duration::from_secs(10))
|
||||
.build()
|
||||
.unwrap_or_default();
|
||||
let registry = RegistryClient::from_config(&config, http.clone());
|
||||
let net_guard = NetGuard::from_env(config.app_env);
|
||||
let scan_gate = Arc::new(ScanGate::new(config.scan_concurrency));
|
||||
let secrets = SecretBox::from_config(&config);
|
||||
Self {
|
||||
config,
|
||||
db_pool,
|
||||
@@ -51,6 +69,10 @@ impl ComplianceAgent {
|
||||
session_streams: Arc::new(DashMap::new()),
|
||||
session_pause: Arc::new(DashMap::new()),
|
||||
session_semaphore: Arc::new(Semaphore::new(DEFAULT_MAX_CONCURRENT_SESSIONS)),
|
||||
registry,
|
||||
net_guard,
|
||||
scan_gate,
|
||||
secrets,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,25 +82,154 @@ impl ComplianceAgent {
|
||||
repo_id: &str,
|
||||
trigger: compliance_core::models::ScanTrigger,
|
||||
) -> Result<(), crate::error::AgentError> {
|
||||
let db = self.db_pool.for_tenant_id(tenant_id).await?;
|
||||
let orchestrator =
|
||||
PipelineOrchestrator::new(self.config.clone(), db, self.llm.clone(), self.http.clone());
|
||||
orchestrator.run_target(repo_id, trigger).await
|
||||
self.run_target_scan(tenant_id, repo_id, trigger).await
|
||||
}
|
||||
|
||||
/// Alias for [`Self::run_scan`] — every scan runs the unified onboarded-target
|
||||
/// pipeline. Kept as a distinct name for the `/targets/{id}/scan` endpoint's
|
||||
/// intent.
|
||||
/// Push one usage event to the tenant-registry (PRODUCT_INTEGRATION_SPEC
|
||||
/// 2.0 §9.2) in the background. `key` makes retries idempotent; the
|
||||
/// registry forwards the event to ERPNext. No-op without a registry.
|
||||
pub fn emit_usage(
|
||||
&self,
|
||||
tenant_id: &str,
|
||||
metric: &str,
|
||||
key: String,
|
||||
properties: serde_json::Value,
|
||||
) {
|
||||
let Some(registry) = self.registry.clone() else {
|
||||
return;
|
||||
};
|
||||
let event = crate::registry::UsageEvent {
|
||||
idempotency_key: key,
|
||||
tenant_id: tenant_id.to_string(),
|
||||
product: registry.product().to_string(),
|
||||
metric: metric.to_string(),
|
||||
quantity: 1.0,
|
||||
occurred_at: chrono::Utc::now().to_rfc3339(),
|
||||
properties: Some(properties),
|
||||
};
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = registry.push_usage_events(&[event]).await {
|
||||
tracing::warn!("usage event push failed: {e}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Scan a target, through the [`ScanGate`]: at most `SCAN_CONCURRENCY` scans
|
||||
/// run at once, and a request for a target that is already being scanned is
|
||||
/// coalesced — it becomes the one pending follow-up that this task runs next,
|
||||
/// or it is dropped if a follow-up is already pending. Every trigger
|
||||
/// (click, webhook, scheduler, demo seed) comes through here.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns the last scan's error. A coalesced or dropped request is `Ok`.
|
||||
pub async fn run_target_scan(
|
||||
&self,
|
||||
tenant_id: &str,
|
||||
target_id: &str,
|
||||
trigger: compliance_core::models::ScanTrigger,
|
||||
) -> Result<(), crate::error::AgentError> {
|
||||
let key = ScanGate::key(tenant_id, target_id);
|
||||
match self.scan_gate.admit(&key, trigger.clone()) {
|
||||
Admission::Run => {}
|
||||
Admission::Coalesced => {
|
||||
tracing::info!(
|
||||
tenant_id,
|
||||
target_id,
|
||||
"scan already running; follow-up queued"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
Admission::Dropped => {
|
||||
tracing::info!(
|
||||
tenant_id,
|
||||
target_id,
|
||||
"scan and follow-up already queued; dropped"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
// Released on panic or cancellation; a normal finish disarms it.
|
||||
let held = HeldTarget::new(&self.scan_gate, key.clone());
|
||||
let mut trigger = trigger;
|
||||
let result = loop {
|
||||
let outcome = {
|
||||
let _slot = self
|
||||
.scan_gate
|
||||
.slot()
|
||||
.await
|
||||
.map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?;
|
||||
self.run_one_target_scan(tenant_id, target_id, trigger.clone())
|
||||
.await
|
||||
};
|
||||
if let Err(e) = &outcome {
|
||||
tracing::error!(tenant_id, target_id, "scan failed: {e}");
|
||||
}
|
||||
match self.scan_gate.finish(&key) {
|
||||
Some(next) => trigger = next,
|
||||
None => break outcome,
|
||||
}
|
||||
};
|
||||
held.disarm();
|
||||
result
|
||||
}
|
||||
|
||||
/// One scan of a target, with no gating: the pipeline plus its usage event.
|
||||
async fn run_one_target_scan(
|
||||
&self,
|
||||
tenant_id: &str,
|
||||
target_id: &str,
|
||||
trigger: compliance_core::models::ScanTrigger,
|
||||
) -> Result<(), crate::error::AgentError> {
|
||||
let db = self.db_pool.for_tenant_id(tenant_id).await?;
|
||||
let orchestrator =
|
||||
PipelineOrchestrator::new(self.config.clone(), db, self.llm.clone(), self.http.clone());
|
||||
orchestrator.run_target(target_id, trigger).await
|
||||
let orchestrator = PipelineOrchestrator::new(
|
||||
self.config.clone(),
|
||||
tenant_id,
|
||||
db.clone(),
|
||||
self.llm.clone(),
|
||||
self.http.clone(),
|
||||
);
|
||||
let started = chrono::Utc::now();
|
||||
orchestrator.run_target(target_id, trigger.clone()).await?;
|
||||
// Support's scans are ours, not the customer's usage.
|
||||
if 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:?}") }),
|
||||
);
|
||||
}
|
||||
self.notify_new_findings(tenant_id, target_id, &db, started);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Tell the workspace (by mail, through the platform) when a scan found
|
||||
/// something that was not there before. "New" is what the pipeline
|
||||
/// inserted during this scan: it only inserts a finding whose fingerprint
|
||||
/// is not stored yet. Background and best-effort; no registry, no mail.
|
||||
fn notify_new_findings(
|
||||
&self,
|
||||
tenant_id: &str,
|
||||
target_id: &str,
|
||||
db: &crate::database::Database,
|
||||
started: chrono::DateTime<chrono::Utc>,
|
||||
) {
|
||||
let Some(registry) = self.registry.clone() else {
|
||||
return;
|
||||
};
|
||||
let (db, tenant_id, target_id) = (db.clone(), tenant_id.to_string(), target_id.to_string());
|
||||
tokio::spawn(async move {
|
||||
match new_findings_summary(&db, &tenant_id, &target_id, started).await {
|
||||
Ok(Some(n)) => {
|
||||
if let Err(e) = registry.notify_new_findings(&n).await {
|
||||
tracing::warn!(tenant_id, target_id, "findings notification failed: {e}");
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => tracing::warn!(tenant_id, target_id, "findings summary failed: {e}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Run a PR review: scan the diff and post review comments.
|
||||
@@ -90,6 +241,13 @@ impl ComplianceAgent {
|
||||
base_sha: &str,
|
||||
head_sha: &str,
|
||||
) -> Result<(), crate::error::AgentError> {
|
||||
// A PR review clones and runs semgrep like a scan, so it takes a scan
|
||||
// slot too. Each PR is distinct work, so it is not coalesced.
|
||||
let _slot = self
|
||||
.scan_gate
|
||||
.slot()
|
||||
.await
|
||||
.map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?;
|
||||
let db = self.db_pool.for_tenant_id(tenant_id).await?;
|
||||
let oid = mongodb::bson::oid::ObjectId::parse_str(repo_id)
|
||||
.map_err(|e| crate::error::AgentError::Other(e.to_string()))?;
|
||||
@@ -103,10 +261,15 @@ impl ComplianceAgent {
|
||||
let code = target.code_artifact().ok_or_else(|| {
|
||||
crate::error::AgentError::Other(format!("Target {repo_id} has no code artifact"))
|
||||
})?;
|
||||
let repo = crate::pipeline::repo_view::RepoView::from_target(&target, code);
|
||||
let repo = crate::pipeline::repo_view::RepoView::from_target(&target, code, &self.secrets);
|
||||
|
||||
let orchestrator =
|
||||
PipelineOrchestrator::new(self.config.clone(), db, self.llm.clone(), self.http.clone());
|
||||
let orchestrator = PipelineOrchestrator::new(
|
||||
self.config.clone(),
|
||||
tenant_id,
|
||||
db,
|
||||
self.llm.clone(),
|
||||
self.http.clone(),
|
||||
);
|
||||
orchestrator
|
||||
.run_pr_review(&repo, repo_id, pr_number, base_sha, head_sha)
|
||||
.await
|
||||
@@ -162,3 +325,119 @@ impl ComplianceAgent {
|
||||
self.session_pause.remove(session_id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Findings of `target_id` first stored since `since`, by severity; `None`
|
||||
/// when there are none.
|
||||
async fn new_findings_summary(
|
||||
db: &crate::database::Database,
|
||||
tenant_id: &str,
|
||||
target_id: &str,
|
||||
since: chrono::DateTime<chrono::Utc>,
|
||||
) -> Result<Option<crate::registry::FindingsNotification>, mongodb::error::Error> {
|
||||
use mongodb::bson::doc;
|
||||
let since_bson = mongodb::bson::DateTime::from_chrono(since);
|
||||
let mut counts = [0u64; 5]; // critical, high, medium, low, info
|
||||
for (i, sev) in ["critical", "high", "medium", "low", "info"]
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
counts[i] = db
|
||||
.findings()
|
||||
.count_documents(doc! { "repo_id": target_id, "severity": *sev, "created_at": { "$gte": since_bson } })
|
||||
.await?;
|
||||
}
|
||||
let total: u64 = counts.iter().sum();
|
||||
if total == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let name = match mongodb::bson::oid::ObjectId::parse_str(target_id) {
|
||||
Ok(oid) => db
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await?
|
||||
.map(|t| t.name)
|
||||
.unwrap_or_else(|| target_id.to_string()),
|
||||
Err(_) => target_id.to_string(),
|
||||
};
|
||||
Ok(Some(findings_notification(
|
||||
tenant_id,
|
||||
target_id,
|
||||
name,
|
||||
counts,
|
||||
since,
|
||||
dashboard_url(),
|
||||
)))
|
||||
}
|
||||
|
||||
/// The public dashboard origin (DASHBOARD_PUBLIC_URL), for the mail's link.
|
||||
fn dashboard_url() -> String {
|
||||
std::env::var("DASHBOARD_PUBLIC_URL").unwrap_or_default()
|
||||
}
|
||||
|
||||
fn findings_notification(
|
||||
tenant_id: &str,
|
||||
target_id: &str,
|
||||
target_name: String,
|
||||
counts: [u64; 5],
|
||||
since: chrono::DateTime<chrono::Utc>,
|
||||
dashboard: String,
|
||||
) -> crate::registry::FindingsNotification {
|
||||
let dashboard = dashboard.trim_end_matches('/');
|
||||
crate::registry::FindingsNotification {
|
||||
tenant_id: tenant_id.to_string(),
|
||||
key: format!("findings:{tenant_id}:{target_id}:{}", since.timestamp()),
|
||||
target_name,
|
||||
new_count: counts.iter().sum(),
|
||||
critical: counts[0],
|
||||
high: counts[1],
|
||||
medium: counts[2],
|
||||
low: counts[3] + counts[4],
|
||||
url: if dashboard.starts_with("https://") {
|
||||
format!("{dashboard}/findings?target={target_id}")
|
||||
} else {
|
||||
String::new()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod notification_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn summary_counts_and_link() {
|
||||
let since = chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap();
|
||||
let n = findings_notification(
|
||||
"t1",
|
||||
"tg1",
|
||||
"Pump".into(),
|
||||
[1, 2, 0, 3, 4],
|
||||
since,
|
||||
"https://pruefwerk.breakpilot.com/".into(),
|
||||
);
|
||||
assert_eq!(n.new_count, 10);
|
||||
assert_eq!((n.critical, n.high, n.medium, n.low), (1, 2, 0, 7));
|
||||
assert_eq!(n.key, "findings:t1:tg1:1700000000");
|
||||
assert_eq!(
|
||||
n.url,
|
||||
"https://pruefwerk.breakpilot.com/findings?target=tg1"
|
||||
);
|
||||
// no or non-https dashboard: the platform links its own page
|
||||
assert_eq!(
|
||||
findings_notification("t", "g", "x".into(), [0, 0, 1, 0, 0], since, String::new()).url,
|
||||
""
|
||||
);
|
||||
assert_eq!(
|
||||
findings_notification(
|
||||
"t",
|
||||
"g",
|
||||
"x".into(),
|
||||
[0, 0, 1, 0, 0],
|
||||
since,
|
||||
"http://x".into()
|
||||
)
|
||||
.url,
|
||||
""
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -144,6 +144,9 @@ pub async fn build_embeddings(
|
||||
// the JWT/dev context isn't available inside detached tasks.
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let agent_clone = (*agent).clone();
|
||||
// The detached task has no request context, so carry the tenant id with it —
|
||||
// it selects the tenant's own checkout directory.
|
||||
let tenant_id = tenant.0.tenant_id.clone();
|
||||
tokio::spawn(async move {
|
||||
let repo = match db
|
||||
.onboarded_targets()
|
||||
@@ -201,15 +204,16 @@ pub async fn build_embeddings(
|
||||
return;
|
||||
}
|
||||
};
|
||||
let view = crate::pipeline::repo_view::RepoView::from_target(&repo, code);
|
||||
let creds = crate::pipeline::git::RepoCredentials {
|
||||
ssh_key_path: Some(agent_clone.config.ssh_key_path.clone()),
|
||||
auth_token: view.auth_token.clone(),
|
||||
auth_username: view.auth_username.clone(),
|
||||
};
|
||||
let git_ops =
|
||||
crate::pipeline::git::GitOps::new(&agent_clone.config.git_clone_base_path, creds);
|
||||
let repo_path = match git_ops.clone_or_fetch(&view.git_url, &view.name) {
|
||||
let view =
|
||||
crate::pipeline::repo_view::RepoView::from_target(&repo, code, &agent_clone.secrets);
|
||||
let creds = crate::pipeline::git::GitOps::make_repo_credentials(&view);
|
||||
let git_ops = crate::pipeline::git::GitOps::new(
|
||||
&agent_clone.config.git_clone_base_path,
|
||||
&tenant_id,
|
||||
creds,
|
||||
agent_clone.net_guard,
|
||||
);
|
||||
let repo_path = match git_ops.clone_or_fetch(&view.git_url, &view.checkout) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to clone repo for embedding build: {e}");
|
||||
|
||||
@@ -7,6 +7,7 @@ use mongodb::bson::doc;
|
||||
use serde::Deserialize;
|
||||
|
||||
use compliance_core::models::dast::{DastFinding, DastScanRun, DastTarget, DastTargetType};
|
||||
use compliance_core::models::Credentials;
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use crate::agent::ComplianceAgent;
|
||||
@@ -52,7 +53,7 @@ pub async fn list_targets(
|
||||
) -> Result<Json<ApiResponse<Vec<DastTarget>>>, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let db = &db;
|
||||
let skip = (params.page.saturating_sub(1)) * params.limit as u64;
|
||||
let skip = params.skip();
|
||||
let total = db
|
||||
.dast_targets()
|
||||
.count_documents(doc! {})
|
||||
@@ -74,7 +75,7 @@ pub async fn list_targets(
|
||||
};
|
||||
|
||||
Ok(Json(ApiResponse {
|
||||
data: targets,
|
||||
data: targets.redacted(),
|
||||
total: Some(total),
|
||||
page: Some(params.page),
|
||||
}))
|
||||
@@ -87,6 +88,12 @@ pub async fn add_target(
|
||||
tenant: TenantCtx,
|
||||
Json(req): Json<AddTargetRequest>,
|
||||
) -> Result<Json<ApiResponse<DastTarget>>, StatusCode> {
|
||||
// The tenant picks this URL and we make the requests, so it decides where
|
||||
// the agent connects (#256). Refuse anything not publicly routable.
|
||||
if let Err(e) = agent.net_guard.check_url(&req.base_url) {
|
||||
tracing::warn!(tenant_id = %tenant.0.tenant_id, "DAST target refused: {e}");
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
let mut target = DastTarget::new(req.name, req.base_url, req.target_type);
|
||||
target.repo_id = req.repo_id;
|
||||
target.excluded_paths = req.excluded_paths;
|
||||
@@ -95,13 +102,25 @@ pub async fn add_target(
|
||||
target.allow_destructive = req.allow_destructive;
|
||||
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
db.dast_targets()
|
||||
let res = db
|
||||
.dast_targets()
|
||||
.insert_one(&target)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let target_id = res
|
||||
.inserted_id
|
||||
.as_object_id()
|
||||
.map(|id| id.to_hex())
|
||||
.unwrap_or_default();
|
||||
agent.emit_usage(
|
||||
&tenant.0.tenant_id,
|
||||
"target.added",
|
||||
format!("dast-target:{}:{target_id}", tenant.0.tenant_id),
|
||||
serde_json::json!({ "target_id": target_id, "kind": "dast" }),
|
||||
);
|
||||
|
||||
Ok(Json(ApiResponse {
|
||||
data: target,
|
||||
data: target.redacted(),
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
@@ -114,6 +133,11 @@ pub async fn trigger_scan(
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
// A source-only deployment has no browser/runtime infrastructure, so a DAST
|
||||
// run could only fail at reconnaissance. Say so instead.
|
||||
if agent.config.features.source_only() {
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
let oid = mongodb::bson::oid::ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
|
||||
@@ -124,13 +148,39 @@ pub async fn trigger_scan(
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
|
||||
// Re-check at use: the target may have been stored before this policy
|
||||
// existed, and a hostname can be repointed after registration.
|
||||
let guard = agent.net_guard;
|
||||
let base_url = target.base_url.clone();
|
||||
let resolved = tokio::task::spawn_blocking(move || {
|
||||
let parsed = guard.check_url(&base_url)?;
|
||||
let port = parsed
|
||||
.port
|
||||
.unwrap_or(if parsed.scheme == "https" { 443 } else { 80 });
|
||||
guard.check_resolved(&parsed.host, port)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
if let Err(e) = resolved {
|
||||
tracing::warn!(tenant_id = %tenant.0.tenant_id, "DAST scan refused: {e}");
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
let tenant_id = tenant.0.tenant_id.clone();
|
||||
let usage_agent = agent.clone();
|
||||
tokio::spawn(async move {
|
||||
let orchestrator = compliance_dast::DastOrchestrator::new(100);
|
||||
let orchestrator = compliance_dast::DastOrchestrator::new(100, guard);
|
||||
match orchestrator.run_scan(&target, Vec::new()).await {
|
||||
Ok((scan_run, findings)) => {
|
||||
if let Err(e) = db.dast_scan_runs().insert_one(&scan_run).await {
|
||||
tracing::error!("Failed to store DAST scan run: {e}");
|
||||
}
|
||||
usage_agent.emit_usage(
|
||||
&tenant_id,
|
||||
"scan.completed",
|
||||
format!("dast:{tenant_id}:{id}:{}", chrono::Utc::now().timestamp()),
|
||||
serde_json::json!({ "target_id": id, "kind": "dast", "findings": findings.len() }),
|
||||
);
|
||||
for finding in &findings {
|
||||
if let Err(e) = db.dast_findings().insert_one(finding).await {
|
||||
tracing::error!("Failed to store DAST finding: {e}");
|
||||
@@ -156,7 +206,7 @@ pub async fn list_scan_runs(
|
||||
) -> Result<Json<ApiResponse<Vec<DastScanRun>>>, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let db = &db;
|
||||
let skip = (params.page.saturating_sub(1)) * params.limit as u64;
|
||||
let skip = params.skip();
|
||||
let total = db
|
||||
.dast_scan_runs()
|
||||
.count_documents(doc! {})
|
||||
@@ -194,7 +244,7 @@ pub async fn list_findings(
|
||||
) -> Result<Json<ApiResponse<Vec<DastFinding>>>, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let db = &db;
|
||||
let skip = (params.page.saturating_sub(1)) * params.limit as u64;
|
||||
let skip = params.skip();
|
||||
let total = db
|
||||
.dast_findings()
|
||||
.count_documents(doc! {})
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
//! Demo-target seeding from the dashboard.
|
||||
//!
|
||||
//! `GET /api/v1/targets/demo-seed` lists the curated targets the agent ships;
|
||||
//! `POST` creates them for the caller's tenant and starts a scan for each. The
|
||||
//! work itself lives in [`crate::demo_seed`], which the nightly `demo/reset`
|
||||
//! calls with no user token.
|
||||
|
||||
use axum::extract::Extension;
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use serde::Serialize;
|
||||
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use crate::demo_seed::{self, DemoTargetSummary, SeedRequest, SeededTarget};
|
||||
|
||||
use super::dto::tenant_db;
|
||||
use super::AgentExt;
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct DemoTargetsResponse {
|
||||
pub targets: Vec<DemoTargetSummary>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct SeedResponse {
|
||||
pub seeded: Vec<SeededTarget>,
|
||||
}
|
||||
|
||||
/// GET /api/v1/targets/demo-seed — what "Add demo targets" would create.
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn list_demo_targets(
|
||||
_tenant: TenantCtx,
|
||||
) -> Result<Json<DemoTargetsResponse>, StatusCode> {
|
||||
let targets = demo_seed::manifest_summary().map_err(|e| {
|
||||
tracing::error!(error = %e, "bundled demo manifest is unreadable");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
Ok(Json(DemoTargetsResponse { targets }))
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets/demo-seed — seed the caller's tenant. 202: the targets
|
||||
/// exist and their scans are running in the background.
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn seed_demo_targets(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
body: Option<Json<SeedRequest>>,
|
||||
) -> Result<(StatusCode, Json<SeedResponse>), StatusCode> {
|
||||
let req = body.map(|Json(b)| b).unwrap_or_default();
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let seeded = demo_seed::seed_tenant(&agent, &db, &tenant.0.tenant_id, &req)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
// An unknown key is the caller's mistake; anything else is ours.
|
||||
tracing::warn!(error = %e, "demo seed rejected");
|
||||
match e {
|
||||
crate::fixtures::FixtureError::UnknownKeys(_) => StatusCode::BAD_REQUEST,
|
||||
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
}
|
||||
})?;
|
||||
Ok((StatusCode::ACCEPTED, Json(SeedResponse { seeded })))
|
||||
}
|
||||
@@ -3,14 +3,35 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
use compliance_core::models::ScanRun;
|
||||
|
||||
/// The largest page a caller may ask for.
|
||||
///
|
||||
/// `limit` and `page` arrive from the query string, so they are attacker-chosen
|
||||
/// numbers that decide how much the agent loads into memory and hands back.
|
||||
/// `?limit=10000000` used to be honoured. Both are clamped **while
|
||||
/// deserializing**, so no handler can forget to do it.
|
||||
pub const MAX_PAGE_SIZE: i64 = 200;
|
||||
|
||||
/// Upper bound on `page`, so `skip` cannot overflow or ask Mongo to walk an
|
||||
/// absurd offset. At [`MAX_PAGE_SIZE`] this is still 20M documents deep.
|
||||
pub const MAX_PAGE: u64 = 100_000;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct PaginationParams {
|
||||
#[serde(default = "default_page")]
|
||||
#[serde(default = "default_page", deserialize_with = "de_page")]
|
||||
pub page: u64,
|
||||
#[serde(default = "default_limit")]
|
||||
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
||||
pub limit: i64,
|
||||
}
|
||||
|
||||
impl PaginationParams {
|
||||
/// Documents to skip for this page. Bounded by construction.
|
||||
pub fn skip(&self) -> u64 {
|
||||
self.page
|
||||
.saturating_sub(1)
|
||||
.saturating_mul(self.limit as u64)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn default_page() -> u64 {
|
||||
1
|
||||
}
|
||||
@@ -18,10 +39,24 @@ pub(crate) fn default_limit() -> i64 {
|
||||
50
|
||||
}
|
||||
|
||||
/// Clamp a caller-supplied page number to `1..=MAX_PAGE`.
|
||||
pub(crate) fn de_page<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
|
||||
Ok(u64::deserialize(d)?.clamp(1, MAX_PAGE))
|
||||
}
|
||||
|
||||
/// Clamp a caller-supplied page size to `1..=MAX_PAGE_SIZE`.
|
||||
pub(crate) fn de_limit<'de, D: serde::Deserializer<'de>>(d: D) -> Result<i64, D::Error> {
|
||||
Ok(i64::deserialize(d)?.clamp(1, MAX_PAGE_SIZE))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct FindingsFilter {
|
||||
#[serde(default)]
|
||||
pub repo_id: Option<String>,
|
||||
/// Only the findings a given scan run found first (the dashboard reveals
|
||||
/// them when the run ends).
|
||||
#[serde(default)]
|
||||
pub scan_run_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub severity: Option<String>,
|
||||
#[serde(default)]
|
||||
@@ -34,12 +69,69 @@ pub struct FindingsFilter {
|
||||
pub sort_by: Option<String>,
|
||||
#[serde(default)]
|
||||
pub sort_order: Option<String>,
|
||||
#[serde(default = "default_page")]
|
||||
#[serde(default = "default_page", deserialize_with = "de_page")]
|
||||
pub page: u64,
|
||||
#[serde(default = "default_limit")]
|
||||
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
||||
pub limit: i64,
|
||||
}
|
||||
|
||||
impl FindingsFilter {
|
||||
/// Documents to skip for this page. Bounded by construction.
|
||||
pub fn skip(&self) -> u64 {
|
||||
self.page
|
||||
.saturating_sub(1)
|
||||
.saturating_mul(self.limit as u64)
|
||||
}
|
||||
}
|
||||
|
||||
/// Fields a caller may sort findings by.
|
||||
///
|
||||
/// `sort_by` went into the sort document verbatim, so a caller could sort on
|
||||
/// any field at all — unindexed ones cost a full collection scan plus an
|
||||
/// in-memory sort, and a `$`-prefixed name is not a field. An unknown value
|
||||
/// falls back to the default rather than erroring, so existing clients keep
|
||||
/// working.
|
||||
pub const SORTABLE_FINDING_FIELDS: &[&str] = &[
|
||||
"created_at",
|
||||
"updated_at",
|
||||
"severity",
|
||||
"scan_type",
|
||||
"status",
|
||||
"file_path",
|
||||
"rule_id",
|
||||
"repo_id",
|
||||
"title",
|
||||
"confidence",
|
||||
];
|
||||
|
||||
/// The sort field to use, defaulting to `created_at`.
|
||||
pub fn finding_sort_field(requested: Option<&str>) -> &'static str {
|
||||
requested
|
||||
.and_then(|r| SORTABLE_FINDING_FIELDS.iter().find(|f| **f == r))
|
||||
.copied()
|
||||
.unwrap_or("created_at")
|
||||
}
|
||||
|
||||
/// The longest search term accepted.
|
||||
pub const MAX_SEARCH_LEN: usize = 128;
|
||||
|
||||
/// Turn a caller's search term into a literal regex.
|
||||
///
|
||||
/// The term used to reach Mongo as a regex, so `(a+)+$` was a
|
||||
/// catastrophic-backtracking denial of service and `.*` a full scan. Every
|
||||
/// metacharacter is escaped, so the search means what a user expects — a
|
||||
/// substring — and nothing more.
|
||||
pub fn literal_regex(term: &str) -> String {
|
||||
let mut out = String::with_capacity(term.len() + 8);
|
||||
for c in term.chars().take(MAX_SEARCH_LEN) {
|
||||
if "\\^$.|?*+()[]{}".contains(c) {
|
||||
out.push('\\');
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct ApiResponse<T: Serialize> {
|
||||
pub data: T,
|
||||
@@ -97,13 +189,20 @@ fn default_branch() -> String {
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct UpdateStatusRequest {
|
||||
pub status: String,
|
||||
/// Typed, so an unknown status is refused (422) instead of being stored
|
||||
/// and breaking every later read of the finding.
|
||||
pub status: compliance_core::models::FindingStatus,
|
||||
/// Why; required for `accepted_risk`.
|
||||
#[serde(default)]
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct BulkUpdateStatusRequest {
|
||||
pub ids: Vec<String>,
|
||||
pub status: String,
|
||||
pub status: compliance_core::models::FindingStatus,
|
||||
#[serde(default)]
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -123,12 +222,21 @@ pub struct SbomFilter {
|
||||
pub has_vulns: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub license: Option<String>,
|
||||
#[serde(default = "default_page")]
|
||||
#[serde(default = "default_page", deserialize_with = "de_page")]
|
||||
pub page: u64,
|
||||
#[serde(default = "default_limit")]
|
||||
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
||||
pub limit: i64,
|
||||
}
|
||||
|
||||
impl SbomFilter {
|
||||
/// Documents to skip for this page. Bounded by construction.
|
||||
pub fn skip(&self) -> u64 {
|
||||
self.page
|
||||
.saturating_sub(1)
|
||||
.saturating_mul(self.limit as u64)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct SbomExportParams {
|
||||
pub repo_id: String,
|
||||
@@ -244,9 +352,63 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pagination_params_zero_page() {
|
||||
fn pagination_params_clamp_hostile_input() {
|
||||
// Page 0 would make `skip` underflow; it becomes the first page.
|
||||
let p: PaginationParams = serde_json::from_str(r#"{"page":0}"#).unwrap();
|
||||
assert_eq!(p.page, 0);
|
||||
assert_eq!(p.page, 1);
|
||||
assert_eq!(p.skip(), 0);
|
||||
|
||||
// A caller cannot ask the agent to load ten million documents.
|
||||
let p: PaginationParams = serde_json::from_str(r#"{"limit":10000000}"#).unwrap();
|
||||
assert_eq!(p.limit, MAX_PAGE_SIZE);
|
||||
|
||||
let p: PaginationParams = serde_json::from_str(r#"{"limit":-5}"#).unwrap();
|
||||
assert_eq!(p.limit, 1);
|
||||
|
||||
// And cannot push `skip` past what Mongo can reasonably serve.
|
||||
let p: PaginationParams =
|
||||
serde_json::from_str(r#"{"page":99999999999,"limit":200}"#).unwrap();
|
||||
assert_eq!(p.page, MAX_PAGE);
|
||||
assert_eq!(p.skip(), (MAX_PAGE - 1) * 200);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sort_field_is_an_allowlist() {
|
||||
assert_eq!(finding_sort_field(Some("severity")), "severity");
|
||||
assert_eq!(finding_sort_field(None), "created_at");
|
||||
// Not a field, an unindexed field, or an operator: all fall back.
|
||||
assert_eq!(finding_sort_field(Some("$where")), "created_at");
|
||||
assert_eq!(finding_sort_field(Some("description")), "created_at");
|
||||
assert_eq!(finding_sort_field(Some("")), "created_at");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_terms_are_literal_not_regex() {
|
||||
// A plain term is unchanged.
|
||||
assert_eq!(literal_regex("openssl"), "openssl");
|
||||
// The classic catastrophic-backtracking pattern becomes a literal.
|
||||
assert_eq!(literal_regex("(a+)+$"), r"\(a\+\)\+\$");
|
||||
// As does a match-everything scan.
|
||||
assert_eq!(literal_regex(".*"), r"\.\*");
|
||||
// Over-long terms are truncated rather than rejected.
|
||||
let long = "x".repeat(MAX_SEARCH_LEN + 50);
|
||||
assert_eq!(literal_regex(&long).len(), MAX_SEARCH_LEN);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sbom_filter_clamps_the_same_way() {
|
||||
let f: SbomFilter = serde_json::from_str(r#"{"limit":10000000,"page":0}"#).unwrap();
|
||||
assert_eq!(f.limit, MAX_PAGE_SIZE);
|
||||
assert_eq!(f.page, 1);
|
||||
assert_eq!(f.skip(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn findings_filter_clamps_the_same_way() {
|
||||
let f: FindingsFilter = serde_json::from_str(r#"{"limit":5000,"page":0}"#).unwrap();
|
||||
assert_eq!(f.limit, MAX_PAGE_SIZE);
|
||||
assert_eq!(f.page, 1);
|
||||
assert_eq!(f.skip(), 0);
|
||||
}
|
||||
|
||||
// ── FindingsFilter ───────────────────────────────────────────
|
||||
@@ -428,21 +590,30 @@ mod tests {
|
||||
#[test]
|
||||
fn update_status_request() {
|
||||
let r: UpdateStatusRequest = serde_json::from_str(r#"{"status":"resolved"}"#).unwrap();
|
||||
assert_eq!(r.status, "resolved");
|
||||
assert_eq!(r.status, compliance_core::models::FindingStatus::Resolved);
|
||||
assert_eq!(r.reason, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bulk_update_status_request() {
|
||||
let r: BulkUpdateStatusRequest =
|
||||
serde_json::from_str(r#"{"ids":["a","b"],"status":"dismissed"}"#).unwrap();
|
||||
serde_json::from_str(r#"{"ids":["a","b"],"status":"false_positive"}"#).unwrap();
|
||||
assert_eq!(r.ids, vec!["a", "b"]);
|
||||
assert_eq!(r.status, "dismissed");
|
||||
assert_eq!(
|
||||
r.status,
|
||||
compliance_core::models::FindingStatus::FalsePositive
|
||||
);
|
||||
// Not a status: stored, it broke every later read of those findings.
|
||||
assert!(serde_json::from_str::<BulkUpdateStatusRequest>(
|
||||
r#"{"ids":["a"],"status":"dismissed"}"#
|
||||
)
|
||||
.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bulk_update_status_empty_ids() {
|
||||
let r: BulkUpdateStatusRequest =
|
||||
serde_json::from_str(r#"{"ids":[],"status":"x"}"#).unwrap();
|
||||
serde_json::from_str(r#"{"ids":[],"status":"open"}"#).unwrap();
|
||||
assert!(r.ids.is_empty());
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
//! `GET /api/v1/targets/{id}/evidence-pack`: the target's evidence as a ZIP
|
||||
//! (see [`crate::evidence`]), for the dashboard's download and for
|
||||
//! breakpilot's document service to pull.
|
||||
|
||||
use axum::extract::{Extension, Path, Query};
|
||||
use axum::http::{header, HeaderValue, StatusCode};
|
||||
use axum::response::IntoResponse;
|
||||
use axum::Json;
|
||||
use mongodb::bson::{doc, oid::ObjectId};
|
||||
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use super::dto::{collect_cursor_async, tenant_db, AgentExt};
|
||||
use super::sbom::MAX_EXPORT_COMPONENTS;
|
||||
use crate::agent::ComplianceAgent;
|
||||
use crate::database::Database;
|
||||
use crate::evidence::compliance::ControlState;
|
||||
use crate::evidence::{build_pack, compliance_of, EvidenceInputs};
|
||||
|
||||
/// Most findings one pack is built from in memory.
|
||||
const MAX_PACK_FINDINGS: u64 = 50_000;
|
||||
|
||||
/// Everything stored about target `id`: 404 for an unknown target, 413 when it
|
||||
/// is too large to build in memory.
|
||||
async fn load_inputs(
|
||||
agent: &ComplianceAgent,
|
||||
db: &Database,
|
||||
id: &str,
|
||||
) -> Result<EvidenceInputs, StatusCode> {
|
||||
let oid = ObjectId::parse_str(id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let target = db
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
|
||||
let by_target = doc! { "repo_id": id };
|
||||
let findings_count = db
|
||||
.findings()
|
||||
.count_documents(by_target.clone())
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let sbom_count = db
|
||||
.sbom_entries()
|
||||
.count_documents(by_target.clone())
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
if findings_count > MAX_PACK_FINDINGS || sbom_count > MAX_EXPORT_COMPONENTS {
|
||||
return Err(StatusCode::PAYLOAD_TOO_LARGE);
|
||||
}
|
||||
|
||||
let load_err = |e: mongodb::error::Error| {
|
||||
tracing::warn!("evidence: {e}");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
};
|
||||
Ok(EvidenceInputs {
|
||||
findings: collect_cursor_async(
|
||||
db.findings()
|
||||
.find(by_target.clone())
|
||||
.await
|
||||
.map_err(load_err)?,
|
||||
)
|
||||
.await,
|
||||
sbom: collect_cursor_async(
|
||||
db.sbom_entries()
|
||||
.find(by_target.clone())
|
||||
.await
|
||||
.map_err(load_err)?,
|
||||
)
|
||||
.await,
|
||||
cves: collect_cursor_async(
|
||||
db.cve_alerts()
|
||||
.find(by_target.clone())
|
||||
.await
|
||||
.map_err(load_err)?,
|
||||
)
|
||||
.await,
|
||||
last_run: db
|
||||
.scan_runs()
|
||||
.find_one(by_target)
|
||||
.sort(doc! { "started_at": -1 })
|
||||
.await
|
||||
.map_err(load_err)?,
|
||||
catalog: crate::controls::cra_catalog(&agent.config).await,
|
||||
target,
|
||||
})
|
||||
}
|
||||
|
||||
/// How many controls are in each state, keyed as the API names the states.
|
||||
fn state_counts(controls: &[crate::evidence::compliance::ControlStatus]) -> serde_json::Value {
|
||||
let count = |state: ControlState| controls.iter().filter(|c| c.state == state).count();
|
||||
serde_json::json!({
|
||||
"not_satisfied": count(ControlState::NotSatisfied),
|
||||
"no_violation_found": count(ControlState::NoViolationFound),
|
||||
"not_assessed": count(ControlState::NotAssessed),
|
||||
"not_code_checkable": count(ControlState::NotCodeCheckable),
|
||||
})
|
||||
}
|
||||
|
||||
/// Targets whose CRA status is computed at the same time for the summary.
|
||||
const SUMMARY_CONCURRENCY: usize = 4;
|
||||
|
||||
/// GET /api/v1/compliance/summary — every target's CRA state counts, for the
|
||||
/// overview. A target too large to evaluate in memory is listed with
|
||||
/// `counts: null` rather than failing the whole summary.
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn compliance_summary(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
use futures_util::StreamExt;
|
||||
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let ids: Vec<String> = collect_cursor_async(
|
||||
db.onboarded_targets()
|
||||
.clone_with_type::<mongodb::bson::Document>()
|
||||
.find(doc! {})
|
||||
.projection(doc! { "_id": 1 })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
|
||||
)
|
||||
.await
|
||||
.into_iter()
|
||||
.filter_map(|d| d.get_object_id("_id").ok().map(|oid| oid.to_hex()))
|
||||
.collect();
|
||||
|
||||
let (agent, db) = (&agent, &db);
|
||||
let rows: Vec<serde_json::Value> = futures_util::stream::iter(ids)
|
||||
.map(|id| async move {
|
||||
match load_inputs(agent, db, &id).await {
|
||||
Ok(inputs) => serde_json::json!({
|
||||
"target_id": id,
|
||||
"counts": state_counts(&compliance_of(&inputs)),
|
||||
"sbom_components": inputs.sbom.len(),
|
||||
"cve_alerts": inputs.cves.len(),
|
||||
}),
|
||||
Err(status) => {
|
||||
tracing::warn!(target_id = %id, %status, "compliance summary: skipped");
|
||||
serde_json::json!({ "target_id": id, "counts": null })
|
||||
}
|
||||
}
|
||||
})
|
||||
.buffered(SUMMARY_CONCURRENCY)
|
||||
.collect()
|
||||
.await;
|
||||
Ok(Json(serde_json::json!({ "data": rows })))
|
||||
}
|
||||
|
||||
/// GET /api/v1/targets/{id}/compliance — the target's state against every CRA
|
||||
/// Annex I control, with the findings against each and the last scan.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn compliance_view(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let inputs = load_inputs(&agent, &db, &id).await?;
|
||||
let controls = compliance_of(&inputs);
|
||||
Ok(Json(serde_json::json!({
|
||||
"data": {
|
||||
"target_id": id,
|
||||
"target_name": inputs.target.name,
|
||||
"counts": state_counts(&controls),
|
||||
"last_scan": inputs.last_run,
|
||||
"sbom_components": inputs.sbom.len(),
|
||||
"cve_alerts": inputs.cves.len(),
|
||||
"controls": controls,
|
||||
}
|
||||
})))
|
||||
}
|
||||
|
||||
/// GET /api/v1/targets/{id}/evidence-pack — 404 for an unknown target, 413
|
||||
/// when it is too large to build in memory.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn evidence_pack(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<impl IntoResponse, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let inputs = load_inputs(&agent, &db, &id).await?;
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let (zip, _files) = tokio::task::spawn_blocking(move || build_pack(&inputs, now))
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.map_err(|e| {
|
||||
tracing::warn!("evidence pack: {e}");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
agent.emit_usage(
|
||||
&tenant.0.tenant_id,
|
||||
"evidence_pack.generated",
|
||||
format!("evidence:{}:{id}:{}", tenant.0.tenant_id, now.timestamp()),
|
||||
serde_json::json!({ "target_id": id }),
|
||||
);
|
||||
let filename = format!("pruefwerk-evidence-{id}-{}.zip", now.format("%Y%m%d"));
|
||||
let disposition = HeaderValue::from_str(&format!("attachment; filename=\"{filename}\""))
|
||||
.unwrap_or_else(|_| HeaderValue::from_static("attachment"));
|
||||
Ok((
|
||||
[
|
||||
(
|
||||
header::CONTENT_TYPE,
|
||||
HeaderValue::from_static("application/zip"),
|
||||
),
|
||||
(header::CONTENT_DISPOSITION, disposition),
|
||||
],
|
||||
zip,
|
||||
))
|
||||
}
|
||||
|
||||
/// Most control ids one lookup describes.
|
||||
const MAX_CONTROL_LOOKUP: usize = 50;
|
||||
|
||||
/// The query of [`describe_controls`]: comma-separated control ids.
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
pub struct ControlIdsQuery {
|
||||
ids: String,
|
||||
}
|
||||
|
||||
/// GET /api/v1/controls?ids=mc-1,mc-2 — what the master controls stamped on
|
||||
/// a finding require, for the finding page. Unknown ids are left out; at
|
||||
/// most [`MAX_CONTROL_LOOKUP`] are described.
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn describe_controls(
|
||||
Extension(agent): AgentExt,
|
||||
_tenant: TenantCtx,
|
||||
Query(query): Query<ControlIdsQuery>,
|
||||
) -> Json<serde_json::Value> {
|
||||
let ids: Vec<String> = query
|
||||
.ids
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|id| !id.is_empty())
|
||||
.take(MAX_CONTROL_LOOKUP)
|
||||
.map(String::from)
|
||||
.collect();
|
||||
let controls = crate::controls::describe_master_controls(&agent.config, &ids).await;
|
||||
Json(serde_json::json!({ "data": controls }))
|
||||
}
|
||||
@@ -4,7 +4,7 @@ use axum::Json;
|
||||
use mongodb::bson::doc;
|
||||
|
||||
use super::dto::*;
|
||||
use compliance_core::models::Finding;
|
||||
use compliance_core::models::{Finding, FindingStatus, StatusChange};
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
#[tracing::instrument(skip_all, fields(repo_id = ?filter.repo_id, severity = ?filter.severity, scan_type = ?filter.scan_type))]
|
||||
@@ -19,6 +19,9 @@ pub async fn list_findings(
|
||||
if let Some(repo_id) = &filter.repo_id {
|
||||
query.insert("repo_id", repo_id);
|
||||
}
|
||||
if let Some(scan_run_id) = &filter.scan_run_id {
|
||||
query.insert("scan_run_id", scan_run_id);
|
||||
}
|
||||
if let Some(severity) = &filter.severity {
|
||||
query.insert("severity", severity);
|
||||
}
|
||||
@@ -31,7 +34,7 @@ pub async fn list_findings(
|
||||
// Text search across title, description, file_path, rule_id
|
||||
if let Some(q) = &filter.q {
|
||||
if !q.is_empty() {
|
||||
let regex = doc! { "$regex": q, "$options": "i" };
|
||||
let regex = doc! { "$regex": super::dto::literal_regex(q), "$options": "i" };
|
||||
query.insert(
|
||||
"$or",
|
||||
mongodb::bson::bson!([
|
||||
@@ -45,28 +48,43 @@ pub async fn list_findings(
|
||||
}
|
||||
|
||||
// Dynamic sort
|
||||
let sort_field = filter.sort_by.as_deref().unwrap_or("created_at");
|
||||
let sort_field = super::dto::finding_sort_field(filter.sort_by.as_deref());
|
||||
let sort_dir: i32 = match filter.sort_order.as_deref() {
|
||||
Some("asc") => 1,
|
||||
_ => -1,
|
||||
};
|
||||
let sort_doc = doc! { sort_field: sort_dir };
|
||||
|
||||
let skip = (filter.page.saturating_sub(1)) * filter.limit as u64;
|
||||
let skip = filter.skip();
|
||||
let total = db
|
||||
.findings()
|
||||
.count_documents(query.clone())
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
|
||||
let findings = match db
|
||||
.findings()
|
||||
.find(query)
|
||||
.sort(sort_doc)
|
||||
.skip(skip)
|
||||
.limit(filter.limit)
|
||||
.await
|
||||
{
|
||||
// Severity is stored as its name, which sorts alphabetically; rank it
|
||||
// for that one sort, newest first within a severity.
|
||||
let found = if sort_field == "severity" {
|
||||
let pipeline = vec![
|
||||
doc! { "$match": query },
|
||||
doc! { "$addFields": { SEVERITY_RANK: severity_rank() } },
|
||||
doc! { "$sort": { SEVERITY_RANK: sort_dir, "created_at": -1 } },
|
||||
doc! { "$skip": i64::try_from(skip).unwrap_or(i64::MAX) },
|
||||
doc! { "$limit": filter.limit },
|
||||
doc! { "$project": { SEVERITY_RANK: 0 } },
|
||||
];
|
||||
db.findings()
|
||||
.aggregate(pipeline)
|
||||
.with_type::<Finding>()
|
||||
.await
|
||||
} else {
|
||||
db.findings()
|
||||
.find(query)
|
||||
.sort(doc! { sort_field: sort_dir })
|
||||
.skip(skip)
|
||||
.limit(filter.limit)
|
||||
.await
|
||||
};
|
||||
let findings = match found {
|
||||
Ok(cursor) => collect_cursor_async(cursor).await,
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to fetch findings: {e}");
|
||||
@@ -81,6 +99,22 @@ pub async fn list_findings(
|
||||
}))
|
||||
}
|
||||
|
||||
/// The temporary field the severity sort ranks on.
|
||||
const SEVERITY_RANK: &str = "_severity_rank";
|
||||
|
||||
/// A finding's severity as a number, critical highest, for sorting.
|
||||
fn severity_rank() -> mongodb::bson::Document {
|
||||
doc! { "$switch": {
|
||||
"branches": [
|
||||
{ "case": { "$eq": ["$severity", "critical"] }, "then": 4 },
|
||||
{ "case": { "$eq": ["$severity", "high"] }, "then": 3 },
|
||||
{ "case": { "$eq": ["$severity", "medium"] }, "then": 2 },
|
||||
{ "case": { "$eq": ["$severity", "low"] }, "then": 1 },
|
||||
],
|
||||
"default": 0,
|
||||
} }
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(finding_id = %id))]
|
||||
pub async fn get_finding(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -103,6 +137,60 @@ pub async fn get_finding(
|
||||
}))
|
||||
}
|
||||
|
||||
/// The `$set` and `$push` of a status change by `user`, or 422 when a status
|
||||
/// that needs a reason (an accepted risk, a wrong CRA mapping) comes without
|
||||
/// one.
|
||||
/// Who changes a finding, as its history records it.
|
||||
struct Actor<'a> {
|
||||
/// The Keycloak user id.
|
||||
id: &'a str,
|
||||
/// The name the customer reads; "BreakPilot-Support (name)" for support.
|
||||
name: Option<String>,
|
||||
/// BreakPilot support rather than one of the tenant's users.
|
||||
support: bool,
|
||||
}
|
||||
|
||||
impl<'a> Actor<'a> {
|
||||
/// The requester of `ctx`.
|
||||
fn of(ctx: &'a compliance_core::TenantContext) -> Self {
|
||||
Self {
|
||||
id: &ctx.user_id,
|
||||
name: match &ctx.staff {
|
||||
Some(staff) => Some(staff.label()),
|
||||
None => ctx.user_name.clone(),
|
||||
},
|
||||
support: ctx.staff.is_some(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn status_update(
|
||||
status: &FindingStatus,
|
||||
reason: Option<&str>,
|
||||
actor: &Actor<'_>,
|
||||
) -> Result<mongodb::bson::Document, StatusCode> {
|
||||
let reason = reason.map(str::trim).filter(|r| !r.is_empty());
|
||||
if status.needs_reason() && reason.is_none() {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
let change = StatusChange {
|
||||
status: status.clone(),
|
||||
by: actor.id.to_string(),
|
||||
by_name: actor.name.clone(),
|
||||
support: actor.support,
|
||||
at: chrono::Utc::now(),
|
||||
reason: reason.map(String::from),
|
||||
};
|
||||
let status = mongodb::bson::to_bson(status).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let change = mongodb::bson::to_bson(&change).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
Ok(doc! {
|
||||
"$set": { "status": status, "updated_at": mongodb::bson::DateTime::now() },
|
||||
"$push": { "status_history": change },
|
||||
})
|
||||
}
|
||||
|
||||
/// PATCH /api/v1/findings/{id}/status — change the status, recording who,
|
||||
/// when and why. 404 when there is no such finding.
|
||||
#[tracing::instrument(skip_all, fields(finding_id = %id))]
|
||||
pub async fn update_finding_status(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -111,19 +199,22 @@ pub async fn update_finding_status(
|
||||
Json(req): Json<UpdateStatusRequest>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let oid = mongodb::bson::oid::ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let update = status_update(&req.status, req.reason.as_deref(), &Actor::of(&tenant.0))?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
|
||||
db.findings()
|
||||
.update_one(
|
||||
doc! { "_id": oid },
|
||||
doc! { "$set": { "status": &req.status, "updated_at": mongodb::bson::DateTime::now() } },
|
||||
)
|
||||
let result = db
|
||||
.findings()
|
||||
.update_one(doc! { "_id": oid }, update)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
if result.matched_count == 0 {
|
||||
return Err(StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
Ok(Json(serde_json::json!({ "status": "updated" })))
|
||||
}
|
||||
|
||||
/// PATCH /api/v1/findings/bulk-status — the same change on many findings.
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn bulk_update_finding_status(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -139,14 +230,12 @@ pub async fn bulk_update_finding_status(
|
||||
if oids.is_empty() {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
let update = status_update(&req.status, req.reason.as_deref(), &Actor::of(&tenant.0))?;
|
||||
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let result = db
|
||||
.findings()
|
||||
.update_many(
|
||||
doc! { "_id": { "$in": oids } },
|
||||
doc! { "$set": { "status": &req.status, "updated_at": mongodb::bson::DateTime::now() } },
|
||||
)
|
||||
.update_many(doc! { "_id": { "$in": oids } }, update)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
@@ -175,3 +264,89 @@ pub async fn update_finding_feedback(
|
||||
|
||||
Ok(Json(serde_json::json!({ "status": "updated" })))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_accepted_risk_needs_a_reason() {
|
||||
assert_eq!(
|
||||
status_update(&FindingStatus::AcceptedRisk, None, &user("u")).err(),
|
||||
Some(StatusCode::UNPROCESSABLE_ENTITY)
|
||||
);
|
||||
assert_eq!(
|
||||
status_update(&FindingStatus::AcceptedRisk, Some(" "), &user("u")).err(),
|
||||
Some(StatusCode::UNPROCESSABLE_ENTITY)
|
||||
);
|
||||
assert!(status_update(
|
||||
&FindingStatus::AcceptedRisk,
|
||||
Some("isolated network"),
|
||||
&user("u")
|
||||
)
|
||||
.is_ok());
|
||||
assert_eq!(
|
||||
status_update(&FindingStatus::WrongMapping, None, &user("u")).err(),
|
||||
Some(StatusCode::UNPROCESSABLE_ENTITY)
|
||||
);
|
||||
assert!(status_update(&FindingStatus::FalsePositive, None, &user("u")).is_ok());
|
||||
assert!(status_update(&FindingStatus::Resolved, None, &user("u")).is_ok());
|
||||
}
|
||||
|
||||
fn user(id: &str) -> Actor<'_> {
|
||||
Actor {
|
||||
id,
|
||||
name: None,
|
||||
support: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_by_support_is_marked_as_such() {
|
||||
let actor = Actor {
|
||||
id: "s-1",
|
||||
name: Some("BreakPilot-Support (Sharang)".to_string()),
|
||||
support: true,
|
||||
};
|
||||
let update = status_update(&FindingStatus::WrongMapping, Some("wrong control"), &actor)
|
||||
.unwrap_or_default();
|
||||
let change = update
|
||||
.get_document("$push")
|
||||
.and_then(|p| p.get_document("status_history"))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
assert_eq!(change.get_str("by").ok(), Some("s-1"));
|
||||
assert_eq!(
|
||||
change.get_str("by_name").ok(),
|
||||
Some("BreakPilot-Support (Sharang)")
|
||||
);
|
||||
assert_eq!(change.get_bool("support").ok(), Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_sets_the_status_and_records_who_and_why() {
|
||||
let update = status_update(
|
||||
&FindingStatus::AcceptedRisk,
|
||||
Some(" isolated "),
|
||||
&user("u-7"),
|
||||
)
|
||||
.unwrap_or_default();
|
||||
let set = update.get_document("$set").cloned().unwrap_or_default();
|
||||
assert_eq!(set.get_str("status").ok(), Some("accepted_risk"));
|
||||
let change = update
|
||||
.get_document("$push")
|
||||
.and_then(|p| p.get_document("status_history"))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
assert_eq!(change.get_str("by").ok(), Some("u-7"));
|
||||
assert_eq!(change.get_str("reason").ok(), Some("isolated"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_status_is_refused_when_read() {
|
||||
let bad = serde_json::from_value::<UpdateStatusRequest>(
|
||||
serde_json::json!({ "status": "wontfix" }),
|
||||
);
|
||||
assert!(bad.is_err());
|
||||
}
|
||||
}
|
||||
@@ -12,25 +12,46 @@ use compliance_core::tenant_ctx::TenantCtx;
|
||||
use crate::agent::ComplianceAgent;
|
||||
|
||||
use super::dto::tenant_db;
|
||||
use super::{collect_cursor_async, ApiResponse};
|
||||
use super::{collect_cursor_async, ApiResponse, PaginationParams};
|
||||
|
||||
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
||||
|
||||
/// The largest graph returned to the browser in one response.
|
||||
///
|
||||
/// A force-directed layout is unreadable well before this, and loading every
|
||||
/// edge of a very large repository into agent memory was #63. Larger graphs are
|
||||
/// truncated and say so; a community-level view is the follow-up for them.
|
||||
pub const MAX_GRAPH_EDGES: i64 = 10_000;
|
||||
|
||||
/// The most members listed per community; `member_count` stays exact.
|
||||
pub const MAX_COMMUNITY_MEMBERS: i64 = 50;
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct GraphData {
|
||||
pub build: Option<GraphBuildRun>,
|
||||
pub nodes: Vec<CodeNode>,
|
||||
pub edges: Vec<CodeEdge>,
|
||||
/// `true` when the graph has more than [`MAX_GRAPH_EDGES`] edges and only
|
||||
/// the first of them (and the nodes they connect) are returned.
|
||||
pub truncated: bool,
|
||||
/// Edges in the full graph, so a truncated view can say "showing N of M".
|
||||
pub total_edges: u64,
|
||||
/// Nodes in the full graph.
|
||||
pub total_nodes: u64,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct SearchParams {
|
||||
pub q: String,
|
||||
#[serde(default = "default_search_limit")]
|
||||
pub limit: usize,
|
||||
/// Clamped to `1..=MAX_PAGE_SIZE` while deserializing, like every list.
|
||||
#[serde(
|
||||
default = "default_search_limit",
|
||||
deserialize_with = "super::dto::de_limit"
|
||||
)]
|
||||
pub limit: i64,
|
||||
}
|
||||
|
||||
fn default_search_limit() -> usize {
|
||||
fn default_search_limit() -> i64 {
|
||||
50
|
||||
}
|
||||
|
||||
@@ -52,19 +73,30 @@ pub async fn get_graph(
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
let (nodes, edges) = if build.is_some() {
|
||||
let (nodes, edges, truncated, total_edges, total_nodes) = if build.is_some() {
|
||||
// Filter by repo_id only — delete_repo_graph clears old data before each rebuild,
|
||||
// so there is only one set of nodes/edges per repo.
|
||||
let filter = doc! { "repo_id": &repo_id };
|
||||
let total_edges = db
|
||||
.graph_edges()
|
||||
.count_documents(filter.clone())
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
let total_nodes = db
|
||||
.graph_nodes()
|
||||
.count_documents(filter.clone())
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
|
||||
let all_nodes: Vec<CodeNode> = match db.graph_nodes().find(filter.clone()).await {
|
||||
Ok(cursor) => collect_cursor_async(cursor).await,
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to fetch graph nodes: {e}");
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
let edges: Vec<CodeEdge> = match db.graph_edges().find(filter).await {
|
||||
// Edges first and bounded; stable order so a truncated view is the same
|
||||
// on every load.
|
||||
let edges: Vec<CodeEdge> = match db
|
||||
.graph_edges()
|
||||
.find(filter)
|
||||
.sort(doc! { "_id": 1 })
|
||||
.limit(MAX_GRAPH_EDGES)
|
||||
.await
|
||||
{
|
||||
Ok(cursor) => collect_cursor_async(cursor).await,
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to fetch graph edges: {e}");
|
||||
@@ -72,19 +104,34 @@ pub async fn get_graph(
|
||||
}
|
||||
};
|
||||
|
||||
// Remove disconnected nodes (no edges) to keep the graph clean
|
||||
let connected: std::collections::HashSet<&str> = edges
|
||||
// Only the nodes those edges connect — disconnected nodes were dropped
|
||||
// before as well — fetched by name instead of loading all of them.
|
||||
let connected: Vec<&str> = edges
|
||||
.iter()
|
||||
.flat_map(|e| [e.source.as_str(), e.target.as_str()])
|
||||
.collect();
|
||||
let nodes = all_nodes
|
||||
.collect::<std::collections::HashSet<_>>()
|
||||
.into_iter()
|
||||
.filter(|n| connected.contains(n.qualified_name.as_str()))
|
||||
.collect();
|
||||
let nodes: Vec<CodeNode> = if connected.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
match db
|
||||
.graph_nodes()
|
||||
.find(doc! { "repo_id": &repo_id, "qualified_name": { "$in": connected } })
|
||||
.await
|
||||
{
|
||||
Ok(cursor) => collect_cursor_async(cursor).await,
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to fetch graph nodes: {e}");
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
(nodes, edges)
|
||||
let truncated = total_edges > edges.len() as u64;
|
||||
(nodes, edges, truncated, total_edges, total_nodes)
|
||||
} else {
|
||||
(Vec::new(), Vec::new())
|
||||
(Vec::new(), Vec::new(), false, 0, 0)
|
||||
};
|
||||
|
||||
Ok(Json(ApiResponse {
|
||||
@@ -92,6 +139,9 @@ pub async fn get_graph(
|
||||
build,
|
||||
nodes,
|
||||
edges,
|
||||
truncated,
|
||||
total_edges,
|
||||
total_nodes,
|
||||
},
|
||||
total: None,
|
||||
page: None,
|
||||
@@ -104,12 +154,26 @@ pub async fn get_nodes(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(repo_id): Path<String>,
|
||||
Query(params): Query<PaginationParams>,
|
||||
) -> Result<Json<ApiResponse<Vec<CodeNode>>>, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let db = &db;
|
||||
let filter = doc! { "repo_id": &repo_id };
|
||||
|
||||
let nodes: Vec<CodeNode> = match db.graph_nodes().find(filter).await {
|
||||
// Documented as paginated but returned every node of the repository (#63).
|
||||
let total = db
|
||||
.graph_nodes()
|
||||
.count_documents(filter.clone())
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
let nodes: Vec<CodeNode> = match db
|
||||
.graph_nodes()
|
||||
.find(filter)
|
||||
.sort(doc! { "_id": 1 })
|
||||
.skip(params.skip())
|
||||
.limit(params.limit)
|
||||
.await
|
||||
{
|
||||
Ok(cursor) => collect_cursor_async(cursor).await,
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to fetch graph nodes: {e}");
|
||||
@@ -117,11 +181,10 @@ pub async fn get_nodes(
|
||||
}
|
||||
};
|
||||
|
||||
let total = nodes.len() as u64;
|
||||
Ok(Json(ApiResponse {
|
||||
data: nodes,
|
||||
total: Some(total),
|
||||
page: None,
|
||||
page: Some(params.page),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -134,37 +197,50 @@ pub async fn get_communities(
|
||||
) -> Result<Json<ApiResponse<Vec<CommunityInfo>>>, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let db = &db;
|
||||
let filter = doc! { "repo_id": &repo_id };
|
||||
|
||||
let nodes: Vec<CodeNode> = match db.graph_nodes().find(filter).await {
|
||||
Ok(cursor) => collect_cursor_async(cursor).await,
|
||||
// Grouped in Mongo rather than by loading every node of the repository into
|
||||
// the agent (#63); `$firstN` keeps each member list bounded while
|
||||
// `member_count` stays exact.
|
||||
let pipeline = vec![
|
||||
doc! { "$match": { "repo_id": &repo_id, "community_id": { "$ne": null } } },
|
||||
doc! { "$group": {
|
||||
"_id": "$community_id",
|
||||
"member_count": { "$sum": 1 },
|
||||
"members": { "$firstN": { "input": "$qualified_name", "n": MAX_COMMUNITY_MEMBERS } },
|
||||
} },
|
||||
doc! { "$sort": { "_id": 1 } },
|
||||
];
|
||||
// One aggregation row. BSON may carry the counts as Int32 or Int64 depending
|
||||
// on size; deserializing into i64 accepts both.
|
||||
#[derive(Deserialize)]
|
||||
struct CommunityRow {
|
||||
#[serde(rename = "_id")]
|
||||
community_id: i64,
|
||||
member_count: i64,
|
||||
members: Vec<String>,
|
||||
}
|
||||
|
||||
let result: Vec<CommunityInfo> = match db.graph_nodes().aggregate(pipeline).await {
|
||||
Ok(cursor) => {
|
||||
use futures_util::StreamExt;
|
||||
cursor
|
||||
.filter_map(|row| async move {
|
||||
let row: CommunityRow = mongodb::bson::from_document(row.ok()?).ok()?;
|
||||
Some(CommunityInfo {
|
||||
community_id: u32::try_from(row.community_id).ok()?,
|
||||
member_count: u32::try_from(row.member_count).ok()?,
|
||||
members: row.members,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
.await
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to fetch graph nodes for communities: {e}");
|
||||
tracing::warn!("Failed to aggregate graph communities: {e}");
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
|
||||
let mut communities: std::collections::HashMap<u32, Vec<String>> =
|
||||
std::collections::HashMap::new();
|
||||
for node in &nodes {
|
||||
if let Some(cid) = node.community_id {
|
||||
communities
|
||||
.entry(cid)
|
||||
.or_default()
|
||||
.push(node.qualified_name.clone());
|
||||
}
|
||||
}
|
||||
|
||||
let mut result: Vec<CommunityInfo> = communities
|
||||
.into_iter()
|
||||
.map(|(id, members)| CommunityInfo {
|
||||
community_id: id,
|
||||
member_count: members.len() as u32,
|
||||
members,
|
||||
})
|
||||
.collect();
|
||||
result.sort_by_key(|c| c.community_id);
|
||||
|
||||
let total = result.len() as u64;
|
||||
Ok(Json(ApiResponse {
|
||||
data: result,
|
||||
@@ -218,15 +294,11 @@ pub async fn search_symbols(
|
||||
// Simple text search on qualified_name and name fields
|
||||
let filter = doc! {
|
||||
"repo_id": &repo_id,
|
||||
"name": { "$regex": ¶ms.q, "$options": "i" },
|
||||
// Literal substring, not a caller-supplied regex (same fix as #64).
|
||||
"name": { "$regex": super::dto::literal_regex(¶ms.q), "$options": "i" },
|
||||
};
|
||||
|
||||
let nodes: Vec<CodeNode> = match db
|
||||
.graph_nodes()
|
||||
.find(filter)
|
||||
.limit(params.limit as i64)
|
||||
.await
|
||||
{
|
||||
let nodes: Vec<CodeNode> = match db.graph_nodes().find(filter).limit(params.limit).await {
|
||||
Ok(cursor) => collect_cursor_async(cursor).await,
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to search graph nodes: {e}");
|
||||
@@ -253,7 +325,7 @@ pub async fn get_file_content(
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let db = &db;
|
||||
|
||||
// Look up the repository to get repo name
|
||||
// Look up the repository to find its checkout
|
||||
let repo = db
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "_id": mongodb::bson::oid::ObjectId::parse_str(&repo_id).ok() })
|
||||
@@ -261,17 +333,24 @@ pub async fn get_file_content(
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
|
||||
let base_path = std::path::Path::new(&agent.config.git_clone_base_path);
|
||||
let file_path = base_path.join(&repo.name).join(¶ms.path);
|
||||
// The checkout is per tenant — read only from the caller's own. It is
|
||||
// named after the code artifact, as ingest clones it.
|
||||
let checkout = repo
|
||||
.code_artifact()
|
||||
.map(|code| code.id.as_str())
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let repo_dir = crate::pipeline::git::clone_dir(
|
||||
std::path::Path::new(&agent.config.git_clone_base_path),
|
||||
&tenant.0.tenant_id,
|
||||
checkout,
|
||||
);
|
||||
let file_path = repo_dir.join(¶ms.path);
|
||||
|
||||
// Security: ensure we don't escape the repo directory
|
||||
let canonical = file_path
|
||||
.canonicalize()
|
||||
.map_err(|_| StatusCode::NOT_FOUND)?;
|
||||
let base_canonical = base_path
|
||||
.join(&repo.name)
|
||||
.canonicalize()
|
||||
.map_err(|_| StatusCode::NOT_FOUND)?;
|
||||
let base_canonical = repo_dir.canonicalize().map_err(|_| StatusCode::NOT_FOUND)?;
|
||||
if !canonical.starts_with(&base_canonical) {
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
@@ -315,6 +394,9 @@ pub async fn trigger_build(
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let agent_clone = (*agent).clone();
|
||||
// The detached task has no request context, so carry the tenant id with it —
|
||||
// it selects the tenant's own checkout directory.
|
||||
let tenant_id = tenant.0.tenant_id.clone();
|
||||
tokio::spawn(async move {
|
||||
let repo = match db
|
||||
.onboarded_targets()
|
||||
@@ -335,15 +417,16 @@ pub async fn trigger_build(
|
||||
return;
|
||||
}
|
||||
};
|
||||
let view = crate::pipeline::repo_view::RepoView::from_target(&repo, code);
|
||||
let creds = crate::pipeline::git::RepoCredentials {
|
||||
ssh_key_path: Some(agent_clone.config.ssh_key_path.clone()),
|
||||
auth_token: view.auth_token.clone(),
|
||||
auth_username: view.auth_username.clone(),
|
||||
};
|
||||
let git_ops =
|
||||
crate::pipeline::git::GitOps::new(&agent_clone.config.git_clone_base_path, creds);
|
||||
let repo_path = match git_ops.clone_or_fetch(&view.git_url, &view.name) {
|
||||
let view =
|
||||
crate::pipeline::repo_view::RepoView::from_target(&repo, code, &agent_clone.secrets);
|
||||
let creds = crate::pipeline::git::GitOps::make_repo_credentials(&view);
|
||||
let git_ops = crate::pipeline::git::GitOps::new(
|
||||
&agent_clone.config.git_clone_base_path,
|
||||
&tenant_id,
|
||||
creds,
|
||||
agent_clone.net_guard,
|
||||
);
|
||||
let repo_path = match git_ops.clone_or_fetch(&view.git_url, &view.checkout) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to clone repo for graph build: {e}");
|
||||
|
||||
@@ -10,16 +10,39 @@ pub async fn health() -> Json<serde_json::Value> {
|
||||
Json(serde_json::json!({ "status": "ok" }))
|
||||
}
|
||||
|
||||
/// GET /api/v1/settings/ssh-public-key — the agent's SSH deploy public key,
|
||||
/// for adding as a read-only deploy key on private git targets.
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn get_ssh_public_key(
|
||||
axum::extract::Extension(agent): AgentExt,
|
||||
) -> Result<Json<serde_json::Value>, axum::http::StatusCode> {
|
||||
let public_path = format!("{}.pub", agent.config.ssh_key_path);
|
||||
let public_key =
|
||||
std::fs::read_to_string(&public_path).map_err(|_| axum::http::StatusCode::NOT_FOUND)?;
|
||||
Ok(Json(serde_json::json!({ "public_key": public_key.trim() })))
|
||||
/// Findings that still need someone's attention: not resolved, not a false
|
||||
/// positive, not an accepted risk and not ignored.
|
||||
pub(crate) const OPEN_STATUSES: [&str; 3] = ["open", "triaged", "needs_review"];
|
||||
|
||||
/// How many open findings there are of each severity, by severity name.
|
||||
async fn open_findings_by_severity(
|
||||
db: &crate::database::Database,
|
||||
) -> std::collections::HashMap<String, u64> {
|
||||
use futures_util::TryStreamExt;
|
||||
|
||||
let pipeline = vec![
|
||||
doc! { "$match": { "status": { "$in": OPEN_STATUSES.to_vec() } } },
|
||||
doc! { "$group": { "_id": "$severity", "n": { "$sum": 1 } } },
|
||||
];
|
||||
let rows: Vec<mongodb::bson::Document> = match db.findings().aggregate(pipeline).await {
|
||||
Ok(cursor) => cursor.try_collect().await.unwrap_or_default(),
|
||||
Err(e) => {
|
||||
tracing::warn!("overview: counting open findings failed: {e}");
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
rows.into_iter()
|
||||
.filter_map(|row| {
|
||||
let severity = row.get_str("_id").ok()?.to_string();
|
||||
// `$sum` of 1s is an int32 until it overflows into int64.
|
||||
let n = row
|
||||
.get_i32("n")
|
||||
.map(i64::from)
|
||||
.or_else(|_| row.get_i64("n"))
|
||||
.ok()?;
|
||||
Some((severity, u64::try_from(n).ok()?))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all)]
|
||||
@@ -30,43 +53,36 @@ pub async fn stats_overview(
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let db = &db;
|
||||
|
||||
let total_repositories = db
|
||||
.onboarded_targets()
|
||||
.count_documents(doc! {})
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
let total_findings = db.findings().count_documents(doc! {}).await.unwrap_or(0);
|
||||
let critical_findings = db
|
||||
.findings()
|
||||
.count_documents(doc! { "severity": "critical" })
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
let high_findings = db
|
||||
.findings()
|
||||
.count_documents(doc! { "severity": "high" })
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
let medium_findings = db
|
||||
.findings()
|
||||
.count_documents(doc! { "severity": "medium" })
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
let low_findings = db
|
||||
.findings()
|
||||
.count_documents(doc! { "severity": "low" })
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
let total_sbom_entries = db
|
||||
.sbom_entries()
|
||||
.count_documents(doc! {})
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
let total_cve_alerts = db.cve_alerts().count_documents(doc! {}).await.unwrap_or(0);
|
||||
let total_issues = db
|
||||
.tracker_issues()
|
||||
.count_documents(doc! {})
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
let (total_repositories, total_sbom_entries, total_cve_alerts, total_issues, by_severity) = tokio::join!(
|
||||
async {
|
||||
db.onboarded_targets()
|
||||
.count_documents(doc! {})
|
||||
.await
|
||||
.unwrap_or(0)
|
||||
},
|
||||
async {
|
||||
db.sbom_entries()
|
||||
.count_documents(doc! {})
|
||||
.await
|
||||
.unwrap_or(0)
|
||||
},
|
||||
async { db.cve_alerts().count_documents(doc! {}).await.unwrap_or(0) },
|
||||
async {
|
||||
db.tracker_issues()
|
||||
.count_documents(doc! {})
|
||||
.await
|
||||
.unwrap_or(0)
|
||||
},
|
||||
open_findings_by_severity(db),
|
||||
);
|
||||
let severity = |name: &str| by_severity.get(name).copied().unwrap_or(0);
|
||||
let total_findings = by_severity.values().sum();
|
||||
let (critical_findings, high_findings, medium_findings, low_findings) = (
|
||||
severity("critical"),
|
||||
severity("high"),
|
||||
severity("medium"),
|
||||
severity("low"),
|
||||
);
|
||||
|
||||
let recent_scans: Vec<ScanRun> = match db
|
||||
.scan_runs()
|
||||
|
||||
@@ -47,7 +47,19 @@ fn find_project_root(start: &Path) -> Option<PathBuf> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Read README.md + all docs/**/*.md (excluding node_modules).
|
||||
/// Directories under `docs/` that are not customer documentation: internal
|
||||
/// design notes (left out of the site by `srcExclude` too), the site's own
|
||||
/// config, and dependencies.
|
||||
const UNPUBLISHED_DOCS: &[&str] = &["design", ".vitepress", "node_modules"];
|
||||
|
||||
/// Whether `rel` (a path relative to `docs/`) is part of the published docs,
|
||||
/// so the assistant answers only from what customers can read.
|
||||
fn is_published(rel: &Path) -> bool {
|
||||
!rel.components()
|
||||
.any(|c| UNPUBLISHED_DOCS.iter().any(|dir| c.as_os_str() == *dir))
|
||||
}
|
||||
|
||||
/// Read README.md + the published docs/**/*.md.
|
||||
fn load_docs(root: &Path) -> String {
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
|
||||
@@ -56,15 +68,12 @@ fn load_docs(root: &Path) -> String {
|
||||
parts.push(format!("<!-- file: README.md -->\n{content}"));
|
||||
}
|
||||
|
||||
// docs/**/*.md, skipping node_modules
|
||||
for entry in WalkDir::new(root.join("docs"))
|
||||
// docs/**/*.md as the docs site publishes them
|
||||
let docs = root.join("docs");
|
||||
for entry in WalkDir::new(&docs)
|
||||
.follow_links(false)
|
||||
.into_iter()
|
||||
.filter_entry(|e| {
|
||||
!e.path()
|
||||
.components()
|
||||
.any(|c| c.as_os_str() == "node_modules")
|
||||
})
|
||||
.filter_entry(|e| e.path().strip_prefix(&docs).is_ok_and(is_published))
|
||||
.filter_map(|e| e.ok())
|
||||
{
|
||||
let path = entry.path();
|
||||
@@ -171,21 +180,23 @@ pub async fn help_chat(
|
||||
let context = doc_context();
|
||||
|
||||
let system_prompt = if context.is_empty() {
|
||||
"You are a helpful assistant for the Compliance Scanner project. \
|
||||
Answer questions about how to use and configure it. \
|
||||
No documentation was loaded at startup, so rely on your general knowledge."
|
||||
"You are the help assistant of Prüfwerk, BreakPilot's security and CRA \
|
||||
compliance scanner. Answer questions about how to use it, in the language \
|
||||
the question is asked in. No documentation was loaded, so say when you are \
|
||||
unsure rather than guessing."
|
||||
.to_string()
|
||||
} else {
|
||||
format!(
|
||||
"You are a helpful assistant for the Compliance Scanner project. \
|
||||
Answer questions about how to use, configure, and understand it \
|
||||
using the documentation below as your primary source of truth.\n\n\
|
||||
"You are the help assistant of Prüfwerk, BreakPilot's security and CRA \
|
||||
compliance scanner. Answer questions about how to use, configure, and \
|
||||
understand it using the documentation below as your source of truth.\n\n\
|
||||
Rules:\n\
|
||||
- Prefer information from the provided docs over general knowledge\n\
|
||||
- Quote or reference the relevant doc section when it helps\n\
|
||||
- If the docs do not cover the topic, say so clearly\n\
|
||||
- Be concise — lead with the answer, then explain if needed\n\
|
||||
- Use markdown formatting for readability\n\n\
|
||||
- Answer in the language the question is asked in (usually German)\n\
|
||||
- Lead with a direct answer (yes/no when the question allows), then the details\n\
|
||||
- Prefer the docs over general knowledge; if they do not cover it, say so\n\
|
||||
- Name the documentation page by its title, never by its file path\n\
|
||||
- Keep it short: a few sentences or a short list, for a narrow chat panel\n\
|
||||
- Use markdown (bold, lists, inline code); no tables, no HTML\n\n\
|
||||
## Project Documentation\n\n{context}"
|
||||
)
|
||||
};
|
||||
@@ -215,3 +226,19 @@ pub async fn help_chat(
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn internal_design_notes_are_not_help_context() {
|
||||
assert!(is_published(Path::new("guide/repositories.md")));
|
||||
assert!(is_published(Path::new("")));
|
||||
assert!(!is_published(Path::new(
|
||||
"design/derive-checks-from-controls.md"
|
||||
)));
|
||||
assert!(!is_published(Path::new(".vitepress/theme/index.md")));
|
||||
assert!(!is_published(Path::new("node_modules/x/README.md")));
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ pub async fn list_issues(
|
||||
) -> ApiResult<Vec<TrackerIssue>> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let db = &db;
|
||||
let skip = (params.page.saturating_sub(1)) * params.limit as u64;
|
||||
let skip = params.skip();
|
||||
let total = db
|
||||
.tracker_issues()
|
||||
.count_documents(doc! {})
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
//! Findings from a manual DAST run or a penetration test: entered in a form,
|
||||
//! or imported from the tool's report. They sit next to the scan's findings
|
||||
//! on the target (see [`crate::import`]).
|
||||
//!
|
||||
//! Writing findings into a tenant's record is an administrator's action: the
|
||||
//! tester is given an account in the customer's organisation with the
|
||||
//! `IT_ADMIN` role.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::body::Bytes;
|
||||
use axum::extract::{Extension, Path, Query};
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use mongodb::bson::{doc, oid::ObjectId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use compliance_core::models::{Finding, ScanType};
|
||||
use compliance_core::tenant::OrgRole;
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use super::dto::tenant_db;
|
||||
use super::ApiResponse;
|
||||
use crate::agent::ComplianceAgent;
|
||||
use crate::database::Database;
|
||||
use crate::import::{sarif, zap, ManualFinding, Provenance};
|
||||
|
||||
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
||||
|
||||
/// Largest report an import accepts.
|
||||
pub const MAX_IMPORT_BYTES: usize = 20 * 1024 * 1024;
|
||||
|
||||
/// What kind of manual test a finding comes from.
|
||||
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ManualKind {
|
||||
Dast,
|
||||
Pentest,
|
||||
}
|
||||
|
||||
impl From<ManualKind> for ScanType {
|
||||
fn from(kind: ManualKind) -> Self {
|
||||
match kind {
|
||||
ManualKind::Dast => ScanType::Dast,
|
||||
ManualKind::Pentest => ScanType::Pentest,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `POST /api/v1/targets/{id}/findings`.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct CreateFindingRequest {
|
||||
pub kind: ManualKind,
|
||||
/// The tool used, if any; `manual` otherwise.
|
||||
#[serde(default)]
|
||||
pub tool: Option<String>,
|
||||
#[serde(flatten)]
|
||||
pub finding: ManualFinding,
|
||||
}
|
||||
|
||||
/// The report formats an import reads.
|
||||
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ImportFormat {
|
||||
Sarif,
|
||||
Zap,
|
||||
}
|
||||
|
||||
/// `?format=&kind=` of an import.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ImportParams {
|
||||
pub format: ImportFormat,
|
||||
pub kind: ManualKind,
|
||||
}
|
||||
|
||||
/// What an import did.
|
||||
#[derive(Debug, Serialize, PartialEq, Eq)]
|
||||
pub struct ImportSummary {
|
||||
/// Findings in the report.
|
||||
pub total: usize,
|
||||
/// Findings added.
|
||||
pub imported: usize,
|
||||
/// Findings already on the target (the same report imported again).
|
||||
pub duplicates: usize,
|
||||
}
|
||||
|
||||
/// Only an organisation's IT administrator writes findings by hand.
|
||||
fn require_admin(tenant: &TenantCtx) -> Result<(), StatusCode> {
|
||||
if tenant.0.org_roles.contains(&OrgRole::ItAdmin) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(StatusCode::FORBIDDEN)
|
||||
}
|
||||
}
|
||||
|
||||
/// The target must exist in this tenant.
|
||||
async fn require_target(db: &Database, id: &str) -> Result<(), StatusCode> {
|
||||
let oid = ObjectId::parse_str(id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
db.onboarded_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.map(|_| ())
|
||||
.ok_or(StatusCode::NOT_FOUND)
|
||||
}
|
||||
|
||||
/// Store `finding` unless one with its fingerprint exists. Returns whether it
|
||||
/// was added.
|
||||
async fn insert_new(db: &Database, finding: &mut Finding) -> Result<bool, StatusCode> {
|
||||
let existing = db
|
||||
.findings()
|
||||
.find_one(doc! { "fingerprint": &finding.fingerprint })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
if existing.is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
let res = db
|
||||
.findings()
|
||||
.insert_one(&*finding)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
finding.id = res.inserted_id.as_object_id();
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets/{id}/findings — add one finding by hand. 409 when the
|
||||
/// same finding (tool, title, location) is already on the target.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn create_finding(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
Json(req): Json<CreateFindingRequest>,
|
||||
) -> Result<(StatusCode, Json<ApiResponse<Finding>>), StatusCode> {
|
||||
require_admin(&tenant)?;
|
||||
if req.finding.title.trim().is_empty() {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
// Shown on the finding: a name, or "BreakPilot-Support (name)".
|
||||
let reported_by = tenant.0.actor_label();
|
||||
require_target(&db, &id).await?;
|
||||
let tool = req
|
||||
.tool
|
||||
.filter(|t| !t.trim().is_empty())
|
||||
.unwrap_or_else(|| "manual".to_string());
|
||||
let mut finding = req.finding.into_finding(Provenance {
|
||||
target_id: &id,
|
||||
scan_type: req.kind.into(),
|
||||
scanner: &tool,
|
||||
reported_by: &reported_by,
|
||||
});
|
||||
if !insert_new(&db, &mut finding).await? {
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
Ok((
|
||||
StatusCode::CREATED,
|
||||
Json(ApiResponse {
|
||||
data: finding,
|
||||
total: None,
|
||||
page: None,
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets/{id}/findings/import?format=sarif|zap&kind=dast|pentest
|
||||
/// — the body is the report itself. Findings already on the target are
|
||||
/// skipped, so importing a report again adds nothing.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn import_findings(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
Query(params): Query<ImportParams>,
|
||||
body: Bytes,
|
||||
) -> Result<Json<ApiResponse<ImportSummary>>, StatusCode> {
|
||||
require_admin(&tenant)?;
|
||||
let parsed: Vec<(String, ManualFinding)> = match params.format {
|
||||
ImportFormat::Sarif => sarif::parse(&body),
|
||||
ImportFormat::Zap => zap::parse(&body).map(|f| {
|
||||
f.into_iter()
|
||||
.map(|x| ("OWASP ZAP".to_string(), x))
|
||||
.collect()
|
||||
}),
|
||||
}
|
||||
.map_err(|e| {
|
||||
tracing::info!("import refused: {e}");
|
||||
StatusCode::UNPROCESSABLE_ENTITY
|
||||
})?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
// Shown on the finding: a name, or "BreakPilot-Support (name)".
|
||||
let reported_by = tenant.0.actor_label();
|
||||
require_target(&db, &id).await?;
|
||||
|
||||
let mut summary = ImportSummary {
|
||||
total: parsed.len(),
|
||||
imported: 0,
|
||||
duplicates: 0,
|
||||
};
|
||||
for (tool, manual) in parsed {
|
||||
let mut finding = manual.into_finding(Provenance {
|
||||
target_id: &id,
|
||||
scan_type: params.kind.into(),
|
||||
scanner: &tool,
|
||||
reported_by: &reported_by,
|
||||
});
|
||||
if insert_new(&db, &mut finding).await? {
|
||||
summary.imported += 1;
|
||||
} else {
|
||||
summary.duplicates += 1;
|
||||
}
|
||||
}
|
||||
Ok(Json(ApiResponse {
|
||||
data: summary,
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::tenant::{TenantContext, TenantStatus};
|
||||
|
||||
fn tenant(roles: Vec<OrgRole>) -> TenantCtx {
|
||||
TenantCtx(TenantContext {
|
||||
tenant_id: "t".into(),
|
||||
tenant_slug: "t".into(),
|
||||
org_roles: roles,
|
||||
products: vec![],
|
||||
plan: "dev".into(),
|
||||
status: TenantStatus::Active,
|
||||
user_id: "u".into(),
|
||||
user_name: None,
|
||||
staff: None,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_an_it_admin_writes_findings() {
|
||||
assert_eq!(require_admin(&tenant(vec![OrgRole::ItAdmin])), Ok(()));
|
||||
assert_eq!(
|
||||
require_admin(&tenant(vec![OrgRole::User, OrgRole::Cxo])),
|
||||
Err(StatusCode::FORBIDDEN)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_form_finding_reads_kind_tool_and_fields() {
|
||||
let req: CreateFindingRequest = serde_json::from_value(serde_json::json!({
|
||||
"kind": "pentest",
|
||||
"title": "Telnet open with default password",
|
||||
"severity": "critical",
|
||||
"cwe": "1392",
|
||||
"location": "tcp://192.0.2.10:23",
|
||||
"reproduction": "telnet 192.0.2.10, log in as root/root",
|
||||
}))
|
||||
.unwrap_or_else(|e| panic!("request parses: {e}"));
|
||||
assert_eq!(ScanType::from(req.kind), ScanType::Pentest);
|
||||
assert_eq!(req.tool, None);
|
||||
assert_eq!(req.finding.cwe.as_deref(), Some("1392"));
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,27 @@
|
||||
pub mod admin;
|
||||
pub mod chat;
|
||||
pub mod dast;
|
||||
pub mod demo_seed;
|
||||
pub mod dto;
|
||||
pub mod evidence;
|
||||
pub mod findings;
|
||||
pub mod graph;
|
||||
pub mod health;
|
||||
pub mod help_chat;
|
||||
pub mod issues;
|
||||
pub mod manual_findings;
|
||||
pub mod mcp_tokens;
|
||||
pub mod notifications;
|
||||
pub mod onboarding;
|
||||
pub mod oscal;
|
||||
pub mod pentest_handlers;
|
||||
pub mod platform;
|
||||
pub mod projects;
|
||||
pub use pentest_handlers as pentest;
|
||||
pub mod sbom;
|
||||
pub mod scans;
|
||||
pub mod support;
|
||||
pub mod target_input;
|
||||
pub mod werkbank_jobs;
|
||||
|
||||
// Re-export all handler functions so routes.rs can use `handlers::function_name`
|
||||
|
||||
@@ -40,9 +40,14 @@ pub async fn list_notifications(
|
||||
filter.insert("repo_id", repo_id.as_str());
|
||||
}
|
||||
|
||||
let page = params.page.unwrap_or(1).max(1);
|
||||
let limit = params.limit.unwrap_or(50).min(200);
|
||||
let skip = (page - 1) * limit as u64;
|
||||
// Same bounds as every other list: a negative limit or a huge page used to
|
||||
// wrap `skip` into an enormous offset.
|
||||
let page = params.page.unwrap_or(1).clamp(1, super::dto::MAX_PAGE);
|
||||
let limit = params
|
||||
.limit
|
||||
.unwrap_or(50)
|
||||
.clamp(1, super::dto::MAX_PAGE_SIZE);
|
||||
let skip = (page - 1).saturating_mul(limit as u64);
|
||||
|
||||
let total = db
|
||||
.cve_notifications()
|
||||
|
||||
@@ -12,52 +12,23 @@ use mongodb::bson::{doc, oid::ObjectId, to_bson};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use compliance_core::models::{
|
||||
Artifact, ArtifactKind, ComplianceProfile, OnboardedTarget, PlcFormat, TargetScanConfig,
|
||||
TargetType,
|
||||
ArtifactKind, ComplianceProfile, Credentials, DetectedFact, Finding, OnboardedTarget,
|
||||
PlcFormat, ScanRun, TargetType,
|
||||
};
|
||||
use compliance_core::scan_matrix::{applicable_scans, supports_pentest};
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use crate::agent::ComplianceAgent;
|
||||
use crate::classify::{classify_target, MockFirmwareDetector};
|
||||
use crate::secrets::SecretError;
|
||||
use crate::targets::{upload_dest, uploaded_artifact, MAX_UPLOAD_BYTES};
|
||||
|
||||
use super::dto::tenant_db;
|
||||
use super::target_input::{merge_artifacts, ArtifactInput, ScanConfigUpdate};
|
||||
use super::{collect_cursor_async, ApiResponse, PaginationParams};
|
||||
|
||||
type AgentExt = Extension<Arc<ComplianceAgent>>;
|
||||
|
||||
/// A client-supplied artifact spec. The server builds the [`Artifact`] (and its
|
||||
/// id) from it, so clients never set internal fields.
|
||||
#[derive(Deserialize)]
|
||||
pub struct ArtifactInput {
|
||||
pub kind: ArtifactKind,
|
||||
pub source_ref: String,
|
||||
#[serde(default)]
|
||||
pub branch: Option<String>,
|
||||
#[serde(default)]
|
||||
pub plc_format: Option<PlcFormat>,
|
||||
}
|
||||
|
||||
impl ArtifactInput {
|
||||
fn build(&self) -> Artifact {
|
||||
let s = self.source_ref.clone();
|
||||
match self.kind {
|
||||
ArtifactKind::GitRepo => {
|
||||
Artifact::git_repo(s, self.branch.clone().unwrap_or_else(|| "main".to_string()))
|
||||
}
|
||||
ArtifactKind::LiveUrl => Artifact::live_url(s),
|
||||
ArtifactKind::FirmwareImage => Artifact::firmware_image(s),
|
||||
ArtifactKind::SourceArchive => Artifact::source_archive(s),
|
||||
ArtifactKind::MobilePackage => Artifact::mobile_package(s),
|
||||
ArtifactKind::ContainerImage => Artifact::container_image(s),
|
||||
ArtifactKind::PlcProject => {
|
||||
Artifact::plc_project(s, self.plc_format.unwrap_or(PlcFormat::PlcopenXml))
|
||||
}
|
||||
ArtifactKind::PlaintextDescription => Artifact::plaintext(s),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct CreateTargetRequest {
|
||||
pub name: String,
|
||||
@@ -72,10 +43,15 @@ pub struct CreateTargetRequest {
|
||||
pub struct UpdateTargetRequest {
|
||||
pub name: Option<String>,
|
||||
pub target_type: Option<TargetType>,
|
||||
pub scan_config: Option<TargetScanConfig>,
|
||||
/// Fields left out keep their stored values.
|
||||
pub scan_config: Option<ScanConfigUpdate>,
|
||||
pub compliance_profile: Option<ComplianceProfile>,
|
||||
pub scan_schedule: Option<String>,
|
||||
/// Replace the target's artifacts wholesale (used by the dashboard editor).
|
||||
/// The tenant's projects this target belongs to; replaces the stored
|
||||
/// list. Each must be one of the tenant's projects in the registry.
|
||||
pub project_ids: Option<Vec<String>>,
|
||||
/// The target's artifacts (the dashboard editor sends all of them). Each
|
||||
/// keeps the token and uploaded file of the stored artifact it matches.
|
||||
#[serde(default)]
|
||||
pub artifacts: Option<Vec<ArtifactInput>>,
|
||||
}
|
||||
@@ -100,23 +76,26 @@ fn parse_oid(id: &str) -> Result<ObjectId, StatusCode> {
|
||||
ObjectId::parse_str(id).map_err(|_| StatusCode::BAD_REQUEST)
|
||||
}
|
||||
|
||||
/// GET /api/v1/targets — list onboarded targets (paginated).
|
||||
/// GET /api/v1/targets — list onboarded targets (paginated), each with its
|
||||
/// newest scan run.
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn list_targets(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Query(params): Query<PaginationParams>,
|
||||
) -> Result<Json<ApiResponse<Vec<OnboardedTarget>>>, StatusCode> {
|
||||
Query(filter): Query<TargetFilter>,
|
||||
) -> Result<Json<ApiResponse<Vec<TargetListItem>>>, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let skip = (params.page.saturating_sub(1)) * params.limit as u64;
|
||||
let skip = params.skip();
|
||||
let query = filter.to_query();
|
||||
let total = db
|
||||
.onboarded_targets()
|
||||
.count_documents(doc! {})
|
||||
.count_documents(query.clone())
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
let targets = match db
|
||||
.onboarded_targets()
|
||||
.find(doc! {})
|
||||
.find(query)
|
||||
.skip(skip)
|
||||
.limit(params.limit)
|
||||
.await
|
||||
@@ -127,13 +106,143 @@ pub async fn list_targets(
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
let ids: Vec<String> = targets
|
||||
.iter()
|
||||
.filter_map(|t| t.id.map(|id| id.to_hex()))
|
||||
.collect();
|
||||
// `join!` borrows its futures' arguments, so the collections need names.
|
||||
let (runs, findings) = (db.scan_runs(), db.findings());
|
||||
let (mut last_scans, counts) = tokio::join!(
|
||||
latest_scan_runs(&runs, ids.clone()),
|
||||
findings_counts(&findings, ids),
|
||||
);
|
||||
let data = targets
|
||||
.redacted()
|
||||
.into_iter()
|
||||
.map(|mut target| {
|
||||
let hex = target.id.map(|id| id.to_hex()).unwrap_or_default();
|
||||
// The stored count only moves when a scan runs; manual findings,
|
||||
// imports and deletions change the real number, so count now.
|
||||
if let Some(count) = counts.as_ref() {
|
||||
target.findings_count = count.get(&hex).copied().unwrap_or(0);
|
||||
}
|
||||
let last_scan = last_scans.remove(&hex);
|
||||
TargetListItem { target, last_scan }
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(ApiResponse {
|
||||
data: targets,
|
||||
data,
|
||||
total: Some(total),
|
||||
page: Some(params.page),
|
||||
}))
|
||||
}
|
||||
|
||||
/// A target in the list, with its most recent scan run, so the list can show
|
||||
/// whether the last scan is running, finished or failed.
|
||||
#[derive(Serialize)]
|
||||
pub struct TargetListItem {
|
||||
/// The target, credentials redacted.
|
||||
#[serde(flatten)]
|
||||
pub target: OnboardedTarget,
|
||||
/// The newest scan run; `None` before the first scan.
|
||||
pub last_scan: Option<ScanRun>,
|
||||
}
|
||||
|
||||
/// Which targets a list shows (`?project=<id>`).
|
||||
#[derive(Debug, Default, serde::Deserialize)]
|
||||
pub struct TargetFilter {
|
||||
/// Only the targets that belong to this project.
|
||||
#[serde(default)]
|
||||
pub project: Option<String>,
|
||||
}
|
||||
|
||||
impl TargetFilter {
|
||||
/// The Mongo filter for these targets.
|
||||
pub fn to_query(&self) -> mongodb::bson::Document {
|
||||
match self
|
||||
.project
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|p| !p.is_empty())
|
||||
{
|
||||
Some(project) => doc! { "project_ids": project },
|
||||
None => doc! {},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The newest scan run of each target in `target_ids`, in one query.
|
||||
pub(crate) async fn latest_scan_runs(
|
||||
runs: &mongodb::Collection<ScanRun>,
|
||||
target_ids: Vec<String>,
|
||||
) -> HashMap<String, ScanRun> {
|
||||
use futures_util::StreamExt;
|
||||
|
||||
if target_ids.is_empty() {
|
||||
return HashMap::new();
|
||||
}
|
||||
// Runs store their target's id as `repo_id`.
|
||||
let pipeline = vec![
|
||||
doc! { "$match": { "repo_id": { "$in": target_ids } } },
|
||||
doc! { "$sort": { "started_at": -1 } },
|
||||
doc! { "$group": { "_id": "$repo_id", "run": { "$first": "$$ROOT" } } },
|
||||
];
|
||||
match runs.aggregate(pipeline).await {
|
||||
Ok(cursor) => {
|
||||
cursor
|
||||
.filter_map(|row| async move {
|
||||
let run = row.ok()?.get_document("run").ok()?.clone();
|
||||
let run: ScanRun = mongodb::bson::from_document(run).ok()?;
|
||||
Some((run.repo_id.clone(), run))
|
||||
})
|
||||
.collect()
|
||||
.await
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to fetch the targets' last scan runs: {e}");
|
||||
HashMap::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The number of findings of each target in `target_ids`, in one query.
|
||||
///
|
||||
/// Targets without findings are absent from the map. `None` when the query
|
||||
/// fails, so the caller keeps the stored counts instead of showing zeros.
|
||||
async fn findings_counts(
|
||||
findings: &mongodb::Collection<Finding>,
|
||||
target_ids: Vec<String>,
|
||||
) -> Option<HashMap<String, u32>> {
|
||||
use futures_util::StreamExt;
|
||||
|
||||
if target_ids.is_empty() {
|
||||
return Some(HashMap::new());
|
||||
}
|
||||
// Findings store their target's id as `repo_id`.
|
||||
let pipeline = vec![
|
||||
doc! { "$match": { "repo_id": { "$in": target_ids } } },
|
||||
doc! { "$group": { "_id": "$repo_id", "count": { "$sum": 1 } } },
|
||||
];
|
||||
match findings.aggregate(pipeline).await {
|
||||
Ok(cursor) => Some(
|
||||
cursor
|
||||
.filter_map(|row| async move {
|
||||
let row = row.ok()?;
|
||||
let id = row.get_str("_id").ok()?.to_string();
|
||||
// `$sum` over ones yields an int32 for any count a target can hold.
|
||||
let count = u32::try_from(row.get_i32("count").ok()?).ok()?;
|
||||
Some((id, count))
|
||||
})
|
||||
.collect()
|
||||
.await,
|
||||
),
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to count the targets' findings: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets — create an onboarded target.
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn create_target(
|
||||
@@ -143,7 +252,10 @@ pub async fn create_target(
|
||||
) -> Result<Json<ApiResponse<OnboardedTarget>>, StatusCode> {
|
||||
let mut target = OnboardedTarget::new(req.name, req.target_type);
|
||||
target.description = req.description;
|
||||
target.artifacts = req.artifacts.iter().map(ArtifactInput::build).collect();
|
||||
target.artifacts = merge_artifacts(&agent.secrets, &req.artifacts, &[]).map_err(|e| {
|
||||
tracing::error!("storing a credential: {e}");
|
||||
StatusCode::SERVICE_UNAVAILABLE
|
||||
})?;
|
||||
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let res = db
|
||||
@@ -152,8 +264,15 @@ pub async fn create_target(
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
target.id = res.inserted_id.as_object_id();
|
||||
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
|
||||
agent.emit_usage(
|
||||
&tenant.0.tenant_id,
|
||||
"target.added",
|
||||
format!("target:{}:{target_id}", tenant.0.tenant_id),
|
||||
serde_json::json!({ "target_id": target_id, "target_type": format!("{:?}", target.target_type) }),
|
||||
);
|
||||
Ok(Json(ApiResponse {
|
||||
data: target,
|
||||
data: target.redacted(),
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
@@ -175,7 +294,7 @@ pub async fn get_target(
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
Ok(Json(ApiResponse {
|
||||
data: target,
|
||||
data: target.redacted(),
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
@@ -202,7 +321,27 @@ pub async fn update_target(
|
||||
to_bson(&tt).map_err(|_| StatusCode::BAD_REQUEST)?,
|
||||
);
|
||||
}
|
||||
if let Some(sc) = req.scan_config {
|
||||
// Both merge with what is stored, so the stored target is read once.
|
||||
let stored =
|
||||
if req.scan_config.is_some() || req.artifacts.is_some() || req.project_ids.is_some() {
|
||||
Some(
|
||||
db.onboarded_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let credential_error = |e: SecretError| {
|
||||
tracing::error!("storing a credential: {e}");
|
||||
StatusCode::SERVICE_UNAVAILABLE
|
||||
};
|
||||
if let (Some(update), Some(stored)) = (req.scan_config, stored.as_ref()) {
|
||||
let sc = update
|
||||
.apply(&agent.secrets, &stored.scan_config)
|
||||
.map_err(credential_error)?;
|
||||
set.insert(
|
||||
"scan_config",
|
||||
to_bson(&sc).map_err(|_| StatusCode::BAD_REQUEST)?,
|
||||
@@ -217,8 +356,23 @@ pub async fn update_target(
|
||||
if let Some(ss) = req.scan_schedule {
|
||||
set.insert("scan_schedule", ss);
|
||||
}
|
||||
if let Some(arts) = req.artifacts {
|
||||
let built: Vec<Artifact> = arts.iter().map(ArtifactInput::build).collect();
|
||||
// Written to the audit log once the change is stored.
|
||||
let mut projects_audit = None;
|
||||
if let (Some(requested), Some(stored)) = (req.project_ids, stored.as_ref()) {
|
||||
let known = super::projects::tenant_projects(&agent, &tenant.0.tenant_id).await?;
|
||||
let ids = super::projects::validated_project_ids(&requested, &known)?;
|
||||
projects_audit = super::projects::projects_changed_entry(
|
||||
&tenant.0,
|
||||
(&id, &stored.name),
|
||||
&stored.project_ids,
|
||||
&ids,
|
||||
&known,
|
||||
);
|
||||
set.insert("project_ids", ids);
|
||||
}
|
||||
if let (Some(arts), Some(stored)) = (req.artifacts, stored.as_ref()) {
|
||||
let built =
|
||||
merge_artifacts(&agent.secrets, &arts, &stored.artifacts).map_err(credential_error)?;
|
||||
set.insert(
|
||||
"artifacts",
|
||||
to_bson(&built).map_err(|_| StatusCode::BAD_REQUEST)?,
|
||||
@@ -229,11 +383,36 @@ pub async fn update_target(
|
||||
.update_one(doc! { "_id": oid }, doc! { "$set": set })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
// Background and best-effort: the registry being down never fails the
|
||||
// change itself.
|
||||
if let (Some(entry), Some(registry)) = (projects_audit, agent.registry.clone()) {
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = registry.append_audit(&entry).await {
|
||||
tracing::warn!(target_id = %entry.target_id, "project change not audited: {e}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
get_target(Extension(agent), tenant, Path(id)).await
|
||||
}
|
||||
|
||||
/// DELETE /api/v1/targets/{id} — remove the target and its findings/scans.
|
||||
/// Remove a deleted target's clones, uploads, work trees and blobs from disk.
|
||||
/// Best-effort: a path that cannot be removed is logged, and the deletion of
|
||||
/// the records stands.
|
||||
async fn remove_target_files(agent: &ComplianceAgent, tenant_id: &str, target: &OnboardedTarget) {
|
||||
let config = agent.config.clone();
|
||||
let paths = crate::retention::target_paths(&config, tenant_id, target);
|
||||
let removal = tokio::task::spawn_blocking(move || crate::retention::remove(&config, &paths))
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
for failure in &removal.failed {
|
||||
tracing::warn!("target files not removed: {failure}");
|
||||
}
|
||||
tracing::info!(removed = removal.removed, "target files removed");
|
||||
}
|
||||
|
||||
/// DELETE /api/v1/targets/{id} — remove the target, its findings/scans and
|
||||
/// its files on disk.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn delete_target(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -242,10 +421,19 @@ pub async fn delete_target(
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let oid = parse_oid(&id)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
// Read first: its name and artifacts say where its files are on disk.
|
||||
let stored = db
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
db.onboarded_targets()
|
||||
.delete_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
if let Some(target) = stored {
|
||||
remove_target_files(&agent, &tenant.0.tenant_id, &target).await;
|
||||
}
|
||||
// Cascade all data keyed by repo_id == target id (best-effort).
|
||||
let db = &db;
|
||||
let _ = db.findings().delete_many(doc! { "repo_id": &id }).await;
|
||||
@@ -366,7 +554,11 @@ pub async fn add_artifact(
|
||||
) -> Result<Json<ApiResponse<OnboardedTarget>>, StatusCode> {
|
||||
let oid = parse_oid(&id)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let artifact = to_bson(&input.build()).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let artifact = input.build(&agent.secrets, None).map_err(|e| {
|
||||
tracing::error!("storing a credential: {e}");
|
||||
StatusCode::SERVICE_UNAVAILABLE
|
||||
})?;
|
||||
let artifact = to_bson(&artifact).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
db.onboarded_targets()
|
||||
.update_one(
|
||||
doc! { "_id": oid },
|
||||
@@ -378,12 +570,16 @@ pub async fn add_artifact(
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets/{id}/artifacts/upload — attach an artifact by uploading
|
||||
/// its file (PLC project, firmware image, source archive, mobile package). The
|
||||
/// bytes are written to the artifact blob store and referenced by `stored_path`,
|
||||
/// so ingest resolves them locally (no URL fetch).
|
||||
/// its file (PLC project, firmware image, source archive, mobile package).
|
||||
///
|
||||
/// Multipart fields: `file` (required), `kind` (required, snake_case
|
||||
/// `ArtifactKind`), `plc_format` (optional, for PLC projects).
|
||||
/// The file is **streamed to disk** chunk by chunk as it arrives, never held in
|
||||
/// memory whole (it used to be read into one buffer of up to 512 MiB, per
|
||||
/// request), and refused with 413 past [`MAX_UPLOAD_BYTES`]. The stored path is
|
||||
/// referenced by `stored_path`, so ingest resolves it locally.
|
||||
///
|
||||
/// Multipart fields: `file` (required, exactly one), `kind` (required,
|
||||
/// snake_case `ArtifactKind`), `plc_format` (optional, for PLC projects), in
|
||||
/// any order.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn upload_artifact(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -406,69 +602,57 @@ pub async fn upload_artifact(
|
||||
let mut kind: Option<ArtifactKind> = None;
|
||||
let mut plc_format: Option<PlcFormat> = None;
|
||||
let mut filename = String::from("upload.bin");
|
||||
let mut bytes: Option<axum::body::Bytes> = None;
|
||||
// Owns the file on disk until the artifact record references it; any early
|
||||
// return below deletes it.
|
||||
let mut stored: Option<StoredUpload> = None;
|
||||
|
||||
while let Some(field) = multipart
|
||||
.next_field()
|
||||
.await
|
||||
.map_err(|_| StatusCode::BAD_REQUEST)?
|
||||
{
|
||||
while let Some(mut field) = multipart.next_field().await.map_err(|e| e.status())? {
|
||||
match field.name().unwrap_or("") {
|
||||
"kind" => {
|
||||
let v = field.text().await.map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let v = field.text().await.map_err(|e| e.status())?;
|
||||
kind = parse_enum(&v);
|
||||
}
|
||||
"plc_format" => {
|
||||
let v = field.text().await.map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let v = field.text().await.map_err(|e| e.status())?;
|
||||
plc_format = parse_enum(&v);
|
||||
}
|
||||
"file" => {
|
||||
if stored.is_some() {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
if let Some(fname) = field.file_name() {
|
||||
filename = fname.to_string();
|
||||
}
|
||||
bytes = Some(field.bytes().await.map_err(|_| StatusCode::BAD_REQUEST)?);
|
||||
let dest = upload_dest(&agent, &id, &filename)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let mut upload = StoredUpload::new(dest);
|
||||
upload.size = stream_to_disk(&mut field, &upload.path, MAX_UPLOAD_BYTES).await?;
|
||||
stored = Some(upload);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let (Some(kind), Some(bytes)) = (kind, bytes) else {
|
||||
let (Some(kind), Some(upload)) = (kind, stored) else {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
};
|
||||
|
||||
// Store the uploaded bytes under the artifact blob store.
|
||||
let safe_name: String = filename
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') {
|
||||
c
|
||||
} else {
|
||||
'_'
|
||||
// Non-file kinds (git repo, live URL, container ref, text) use the JSON
|
||||
// add-artifact endpoint, not upload.
|
||||
let mut artifact = uploaded_artifact(kind, plc_format, &filename, &upload.path, upload.size)
|
||||
.ok_or(StatusCode::BAD_REQUEST)?;
|
||||
if kind != ArtifactKind::FirmwareImage {
|
||||
match archive_check(upload.path.clone()).await? {
|
||||
// 7z and rar are never unpacked: say so now, not after a scan.
|
||||
ArchiveCheck::Unsupported => return Err(StatusCode::UNSUPPORTED_MEDIA_TYPE),
|
||||
// Kept, and marked: the dashboard asks for the password.
|
||||
ArchiveCheck::Encrypted => {
|
||||
artifact
|
||||
.detected
|
||||
.push(DetectedFact::new(ARCHIVE_ENCRYPTED_FACT, "true", "upload"))
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let dir = std::path::Path::new(&agent.config.artifact_store_base_path)
|
||||
.join("uploads")
|
||||
.join(&id);
|
||||
std::fs::create_dir_all(&dir).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let dest = dir.join(format!("{}_{safe_name}", uuid::Uuid::new_v4()));
|
||||
std::fs::write(&dest, bytes.as_ref()).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
// Build the artifact for this kind, referencing the stored file.
|
||||
let mut artifact = match kind {
|
||||
ArtifactKind::PlcProject => Artifact::plc_project(
|
||||
filename.clone(),
|
||||
plc_format.unwrap_or(PlcFormat::PlcopenXml),
|
||||
),
|
||||
ArtifactKind::FirmwareImage => Artifact::firmware_image(filename.clone()),
|
||||
ArtifactKind::SourceArchive => Artifact::source_archive(filename.clone()),
|
||||
ArtifactKind::MobilePackage => Artifact::mobile_package(filename.clone()),
|
||||
// Non-file kinds (git repo, live URL, container ref, text) use the JSON
|
||||
// add-artifact endpoint, not upload.
|
||||
_ => return Err(StatusCode::BAD_REQUEST),
|
||||
};
|
||||
artifact.stored_path = Some(dest.to_string_lossy().to_string());
|
||||
artifact.size_bytes = Some(bytes.len() as u64);
|
||||
ArchiveCheck::Plain => {}
|
||||
}
|
||||
}
|
||||
|
||||
let artifact_bson = to_bson(&artifact).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
db.onboarded_targets()
|
||||
@@ -478,10 +662,197 @@ pub async fn upload_artifact(
|
||||
)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
upload.keep();
|
||||
|
||||
get_target(Extension(agent), tenant, Path(id)).await
|
||||
}
|
||||
|
||||
/// The fact an upload records on a password-protected archive.
|
||||
pub const ARCHIVE_ENCRYPTED_FACT: &str = "archive_encrypted";
|
||||
|
||||
/// What an uploaded file is, as far as unpacking goes.
|
||||
enum ArchiveCheck {
|
||||
/// A 7z or rar archive: refused.
|
||||
Unsupported,
|
||||
/// A zip with encrypted entries: needs a password.
|
||||
Encrypted,
|
||||
/// Anything else: a plain archive or a single file.
|
||||
Plain,
|
||||
}
|
||||
|
||||
/// Check the uploaded file at `path` (on a blocking thread: it reads the file).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 500 when the file cannot be read.
|
||||
async fn archive_check(path: std::path::PathBuf) -> Result<ArchiveCheck, StatusCode> {
|
||||
use crate::ingest::archive::{self, ArchiveFormat, ExtractError};
|
||||
|
||||
tokio::task::spawn_blocking(move || {
|
||||
if archive::unsupported_format(&path)?.is_some() {
|
||||
return Ok(ArchiveCheck::Unsupported);
|
||||
}
|
||||
if ArchiveFormat::sniff(&path)? != Some(ArchiveFormat::Zip) {
|
||||
return Ok(ArchiveCheck::Plain);
|
||||
}
|
||||
Ok(match archive::zip_encryption(&path, None) {
|
||||
Err(ExtractError::PasswordRequired) => ArchiveCheck::Encrypted,
|
||||
// A zip that does not open is reported by the scan, like before.
|
||||
_ => ArchiveCheck::Plain,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.map_err(|_: std::io::Error| StatusCode::INTERNAL_SERVER_ERROR)
|
||||
}
|
||||
|
||||
/// The body of [`set_archive_password`].
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ArchivePasswordRequest {
|
||||
/// The archive's password.
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
/// PUT /api/v1/targets/{id}/artifacts/{artifact_id}/archive-password — set the
|
||||
/// password of an uploaded, password-protected archive.
|
||||
///
|
||||
/// The password is checked against the stored file first, then stored sealed
|
||||
/// like a git token; the API never returns it. It travels in this JSON body,
|
||||
/// never in the upload's URL.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 404 without the target or artifact; 409 when the artifact is not a
|
||||
/// password-protected zip; 422 when the password does not open it; 503 when
|
||||
/// the deployment has no key to seal it with.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id, artifact_id = %artifact_id))]
|
||||
pub async fn set_archive_password(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path((id, artifact_id)): Path<(String, String)>,
|
||||
Json(req): Json<ArchivePasswordRequest>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
use crate::ingest::archive::{self, ArchiveFormat, ExtractError};
|
||||
|
||||
let oid = parse_oid(&id)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let target = db
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let artifact = target
|
||||
.artifacts
|
||||
.iter()
|
||||
.find(|a| a.id == artifact_id)
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let path = crate::ingest::local_source(artifact).map_err(|_| StatusCode::CONFLICT)?;
|
||||
|
||||
let password = req.password.clone();
|
||||
let checked = tokio::task::spawn_blocking(move || {
|
||||
if ArchiveFormat::sniff(&path).ok().flatten() != Some(ArchiveFormat::Zip) {
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
match archive::zip_encryption(&path, Some(password.as_bytes())) {
|
||||
Ok(true) => Ok(()),
|
||||
Ok(false) => Err(StatusCode::CONFLICT),
|
||||
Err(ExtractError::WrongPassword) => Err(StatusCode::UNPROCESSABLE_ENTITY),
|
||||
Err(_) => Err(StatusCode::CONFLICT),
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
checked?;
|
||||
|
||||
let sealed = agent.secrets.seal(&req.password).map_err(|e| {
|
||||
tracing::error!("sealing an archive password: {e}");
|
||||
StatusCode::SERVICE_UNAVAILABLE
|
||||
})?;
|
||||
let auth = compliance_core::models::ArtifactAuth {
|
||||
method: crate::ingest::ARCHIVE_PASSWORD_METHOD.to_string(),
|
||||
secret: Some(sealed),
|
||||
..Default::default()
|
||||
};
|
||||
let auth = to_bson(&auth).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
db.onboarded_targets()
|
||||
.update_one(
|
||||
doc! { "_id": oid, "artifacts.id": &artifact_id },
|
||||
doc! { "$set": {
|
||||
"artifacts.$.auth": auth,
|
||||
"updated_at": mongodb::bson::DateTime::now(),
|
||||
} },
|
||||
)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
/// Write one multipart field to `dest` as its chunks arrive, refusing more than
|
||||
/// `max` bytes. Returns the number of bytes written.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 413 past `max`, the multipart error's own status for a malformed or
|
||||
/// over-limit body, 500 if the file cannot be written.
|
||||
async fn stream_to_disk(
|
||||
field: &mut axum::extract::multipart::Field<'_>,
|
||||
dest: &std::path::Path,
|
||||
max: u64,
|
||||
) -> Result<u64, StatusCode> {
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
let mut file = tokio::fs::File::create(dest)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let mut written: u64 = 0;
|
||||
while let Some(chunk) = field.chunk().await.map_err(|e| e.status())? {
|
||||
written += chunk.len() as u64;
|
||||
if written > max {
|
||||
return Err(StatusCode::PAYLOAD_TOO_LARGE);
|
||||
}
|
||||
file.write_all(&chunk)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
}
|
||||
file.flush()
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
/// An uploaded file on disk that is deleted when dropped, unless [`Self::keep`]
|
||||
/// is called once the artifact record references it. This is what stops a
|
||||
/// rejected, oversized or half-received upload from being left on disk.
|
||||
struct StoredUpload {
|
||||
path: std::path::PathBuf,
|
||||
size: u64,
|
||||
keep: bool,
|
||||
}
|
||||
|
||||
impl StoredUpload {
|
||||
fn new(path: std::path::PathBuf) -> Self {
|
||||
Self {
|
||||
path,
|
||||
size: 0,
|
||||
keep: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The artifact now references this file; leave it in place.
|
||||
fn keep(mut self) {
|
||||
self.keep = true;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for StoredUpload {
|
||||
fn drop(&mut self) {
|
||||
if !self.keep {
|
||||
let _ = std::fs::remove_file(&self.path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Deserialize a snake_case enum value from a plain string.
|
||||
fn parse_enum<T: for<'de> Deserialize<'de>>(s: &str) -> Option<T> {
|
||||
serde_json::from_value(serde_json::Value::String(s.to_string())).ok()
|
||||
@@ -508,9 +879,11 @@ pub async fn applicable_scans_for_target(
|
||||
.map(|o| ScanOptionDto {
|
||||
scan: o.scan.to_string(),
|
||||
default_on: o.default_on,
|
||||
// A scan nothing runs yet reads as blocked to every client, so the
|
||||
// wizard neither pre-selects nor offers it.
|
||||
blocked_reason: o.unrunnable_reason(),
|
||||
rationale: o.rationale,
|
||||
required_artifact: o.required_artifact.map(|k| k.to_string()),
|
||||
blocked_reason: o.blocked_reason,
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -528,7 +901,7 @@ pub async fn applicable_scans_for_target(
|
||||
///
|
||||
/// This is the lightweight pass: it classifies from artifact kinds without
|
||||
/// ingesting (cloning) sources, so it returns immediately. Deep detection (after
|
||||
/// ingest, with tramiton firmware analysis) is a follow-up background step.
|
||||
/// ingest, with Firmwerk firmware analysis) is a follow-up background step.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn detect_target(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -564,7 +937,7 @@ pub async fn detect_target(
|
||||
target.classification = Some(classification);
|
||||
|
||||
Ok(Json(ApiResponse {
|
||||
data: target,
|
||||
data: target.redacted(),
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
@@ -595,20 +968,37 @@ 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
|
||||
};
|
||||
tokio::spawn(async move {
|
||||
// Always the unified target pipeline — this endpoint is about an
|
||||
// onboarded target by construction, independent of the global
|
||||
// `unified_pipeline` transition flag used by the legacy paths.
|
||||
if let Err(e) = agent_clone
|
||||
.run_target_scan(
|
||||
&tenant_id,
|
||||
&id,
|
||||
compliance_core::models::ScanTrigger::Manual,
|
||||
)
|
||||
.await
|
||||
{
|
||||
if let Err(e) = agent_clone.run_target_scan(&tenant_id, &id, trigger).await {
|
||||
tracing::error!("Manual target scan failed for {id}: {e}");
|
||||
}
|
||||
});
|
||||
Ok(Json(serde_json::json!({ "status": "scan_triggered" })))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod filter_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_project_filter_matches_its_targets() {
|
||||
let filter = TargetFilter {
|
||||
project: Some(" p1 ".to_string()),
|
||||
};
|
||||
assert_eq!(filter.to_query(), doc! { "project_ids": "p1" });
|
||||
assert_eq!(TargetFilter::default().to_query(), doc! {});
|
||||
let blank = TargetFilter {
|
||||
project: Some(String::new()),
|
||||
};
|
||||
assert_eq!(blank.to_query(), doc! {});
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use mongodb::bson::doc;
|
||||
use serde::Deserialize;
|
||||
|
||||
use compliance_core::models::pentest::*;
|
||||
use compliance_core::models::Credentials;
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use crate::agent::ComplianceAgent;
|
||||
@@ -47,6 +48,14 @@ pub async fn create_session(
|
||||
tenant: TenantCtx,
|
||||
Json(req): Json<CreateSessionRequest>,
|
||||
) -> Result<Json<ApiResponse<PentestSession>>, (StatusCode, String)> {
|
||||
// Source-only deployment: no runtime target to attack, no tooling deployed.
|
||||
if agent.config.features.source_only() {
|
||||
return Err((
|
||||
StatusCode::CONFLICT,
|
||||
"Pentest sessions are not available in this environment (static analysis only)."
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
// Try to acquire a concurrency permit
|
||||
let permit = agent
|
||||
.session_semaphore
|
||||
@@ -72,6 +81,12 @@ pub async fn create_session(
|
||||
));
|
||||
}
|
||||
|
||||
// The wizard's app_url becomes a DAST target and then live traffic, so
|
||||
// it is the same outbound decision as a DAST target (#256).
|
||||
if let Err(e) = agent.net_guard.check_url(&config.app_url) {
|
||||
return Err((StatusCode::BAD_REQUEST, e.to_string()));
|
||||
}
|
||||
|
||||
// Look up or auto-create DastTarget by app_url
|
||||
let target = match db
|
||||
.dast_targets()
|
||||
@@ -124,9 +139,15 @@ pub async fn create_session(
|
||||
}
|
||||
}
|
||||
|
||||
// Stored sealed; the orchestrator below works on the in-memory copy.
|
||||
let mut stored = session.clone();
|
||||
agent
|
||||
.secrets
|
||||
.seal_unsealed(&mut stored)
|
||||
.map_err(|e| (StatusCode::SERVICE_UNAVAILABLE, e.to_string()))?;
|
||||
let insert_result = db
|
||||
.pentest_sessions()
|
||||
.insert_one(&session)
|
||||
.insert_one(&stored)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
(
|
||||
@@ -197,43 +218,6 @@ pub async fn create_session(
|
||||
}
|
||||
}
|
||||
|
||||
// Encrypt credentials before they linger in memory
|
||||
let mut session_for_task = session.clone();
|
||||
if let Some(ref mut cfg) = session_for_task.config {
|
||||
cfg.auth.username = cfg
|
||||
.auth
|
||||
.username
|
||||
.as_ref()
|
||||
.map(|u| crate::pentest::crypto::encrypt(u));
|
||||
cfg.auth.password = cfg
|
||||
.auth
|
||||
.password
|
||||
.as_ref()
|
||||
.map(|p| crate::pentest::crypto::encrypt(p));
|
||||
}
|
||||
|
||||
// Persist encrypted credentials to DB
|
||||
if session_for_task.config.is_some() {
|
||||
if let Some(sid) = session.id {
|
||||
let _ = db
|
||||
.pentest_sessions()
|
||||
.update_one(
|
||||
doc! { "_id": sid },
|
||||
doc! { "$set": {
|
||||
"config.auth.username": session_for_task.config.as_ref()
|
||||
.and_then(|c| c.auth.username.as_deref())
|
||||
.map(|s| mongodb::bson::Bson::String(s.to_string()))
|
||||
.unwrap_or(mongodb::bson::Bson::Null),
|
||||
"config.auth.password": session_for_task.config.as_ref()
|
||||
.and_then(|c| c.auth.password.as_deref())
|
||||
.map(|s| mongodb::bson::Bson::String(s.to_string()))
|
||||
.unwrap_or(mongodb::bson::Bson::Null),
|
||||
}},
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
let initial_message = config
|
||||
.initial_instructions
|
||||
.clone()
|
||||
@@ -247,13 +231,19 @@ pub async fn create_session(
|
||||
});
|
||||
|
||||
let llm = agent.llm.clone();
|
||||
let net_guard = agent.net_guard;
|
||||
let db_for_orchestrator = db.clone();
|
||||
let session_clone = session.clone();
|
||||
let target_clone = target.clone();
|
||||
let agent_ref = agent.clone();
|
||||
tokio::spawn(async move {
|
||||
let orchestrator =
|
||||
PentestOrchestrator::new(llm, db_for_orchestrator, event_tx, Some(pause_rx));
|
||||
let orchestrator = PentestOrchestrator::new(
|
||||
llm,
|
||||
db_for_orchestrator,
|
||||
event_tx,
|
||||
Some(pause_rx),
|
||||
net_guard,
|
||||
);
|
||||
orchestrator
|
||||
.run_session_guarded(&session_clone, &target_clone, &initial_message)
|
||||
.await;
|
||||
@@ -263,19 +253,8 @@ pub async fn create_session(
|
||||
drop(permit);
|
||||
});
|
||||
|
||||
// Redact credentials in response
|
||||
let mut response_session = session;
|
||||
if let Some(ref mut cfg) = response_session.config {
|
||||
if cfg.auth.username.is_some() {
|
||||
cfg.auth.username = Some("********".to_string());
|
||||
}
|
||||
if cfg.auth.password.is_some() {
|
||||
cfg.auth.password = Some("********".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Json(ApiResponse {
|
||||
data: response_session,
|
||||
data: session.redacted(),
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
@@ -339,13 +318,19 @@ pub async fn create_session(
|
||||
});
|
||||
|
||||
let llm = agent.llm.clone();
|
||||
let net_guard = agent.net_guard;
|
||||
let db_for_orchestrator = db.clone();
|
||||
let session_clone = session.clone();
|
||||
let target_clone = target.clone();
|
||||
let agent_ref = agent.clone();
|
||||
tokio::spawn(async move {
|
||||
let orchestrator =
|
||||
PentestOrchestrator::new(llm, db_for_orchestrator, event_tx, Some(pause_rx));
|
||||
let orchestrator = PentestOrchestrator::new(
|
||||
llm,
|
||||
db_for_orchestrator,
|
||||
event_tx,
|
||||
Some(pause_rx),
|
||||
net_guard,
|
||||
);
|
||||
orchestrator
|
||||
.run_session_guarded(&session_clone, &target_clone, &initial_message)
|
||||
.await;
|
||||
@@ -354,7 +339,7 @@ pub async fn create_session(
|
||||
});
|
||||
|
||||
Ok(Json(ApiResponse {
|
||||
data: session,
|
||||
data: session.redacted(),
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
@@ -436,7 +421,7 @@ pub async fn list_sessions(
|
||||
};
|
||||
|
||||
Ok(Json(ApiResponse {
|
||||
data: sessions,
|
||||
data: sessions.redacted(),
|
||||
total: Some(total),
|
||||
page: Some(params.page),
|
||||
}))
|
||||
@@ -470,7 +455,7 @@ pub async fn get_session(
|
||||
}
|
||||
|
||||
Ok(Json(ApiResponse {
|
||||
data: session,
|
||||
data: session.redacted(),
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
@@ -491,7 +476,7 @@ pub async fn send_message(
|
||||
.map_err(|s| (s, "failed to acquire tenant database".to_string()))?;
|
||||
|
||||
// Verify session exists and is running
|
||||
let session = db
|
||||
let mut session = db
|
||||
.pentest_sessions()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
@@ -509,6 +494,8 @@ pub async fn send_message(
|
||||
format!("Session is {}, cannot send messages", session.status),
|
||||
));
|
||||
}
|
||||
// The orchestrator puts the test account's credentials into the prompt.
|
||||
agent.secrets.open_in_place(&mut session);
|
||||
|
||||
// Look up the target
|
||||
let target_oid = mongodb::bson::oid::ObjectId::parse_str(&session.target_id).map_err(|_| {
|
||||
@@ -544,6 +531,7 @@ pub async fn send_message(
|
||||
|
||||
// Spawn orchestrator to continue the session
|
||||
let llm = agent.llm.clone();
|
||||
let net_guard = agent.net_guard;
|
||||
let db_for_orchestrator = db.clone();
|
||||
let message = req.message.clone();
|
||||
|
||||
@@ -559,7 +547,8 @@ pub async fn send_message(
|
||||
.unwrap_or_else(|| agent.register_session_stream(&session_id));
|
||||
|
||||
tokio::spawn(async move {
|
||||
let orchestrator = PentestOrchestrator::new(llm, db_for_orchestrator, event_tx, None);
|
||||
let orchestrator =
|
||||
PentestOrchestrator::new(llm, db_for_orchestrator, event_tx, None, net_guard);
|
||||
orchestrator
|
||||
.run_session_guarded(&session, &target, &message)
|
||||
.await;
|
||||
@@ -642,7 +631,7 @@ pub async fn stop_session(
|
||||
})?;
|
||||
|
||||
Ok(Json(ApiResponse {
|
||||
data: updated,
|
||||
data: updated.redacted(),
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
@@ -740,6 +729,11 @@ pub async fn resume_session(
|
||||
}))
|
||||
}
|
||||
|
||||
/// The most attack-chain nodes returned for one session. A pentest run is
|
||||
/// already bounded by its iteration budget; this keeps a runaway session from
|
||||
/// being loaded whole into agent memory.
|
||||
const MAX_ATTACK_CHAIN_NODES: i64 = 2_000;
|
||||
|
||||
/// GET /api/v1/pentest/sessions/:id/attack-chain — Get attack chain nodes for a session
|
||||
#[tracing::instrument(skip_all, fields(session_id = %id))]
|
||||
pub async fn get_attack_chain(
|
||||
@@ -750,10 +744,20 @@ pub async fn get_attack_chain(
|
||||
let _oid = mongodb::bson::oid::ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
|
||||
// The dashboard draws the whole chain, so this is capped rather than paged
|
||||
// (#66): `total` is the real count, and `total > data.len()` means the chain
|
||||
// was truncated.
|
||||
let filter = doc! { "session_id": &id };
|
||||
let total = db
|
||||
.attack_chain_nodes()
|
||||
.count_documents(filter.clone())
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
let nodes = match db
|
||||
.attack_chain_nodes()
|
||||
.find(doc! { "session_id": &id })
|
||||
.find(filter)
|
||||
.sort(doc! { "started_at": 1 })
|
||||
.limit(MAX_ATTACK_CHAIN_NODES)
|
||||
.await
|
||||
{
|
||||
Ok(cursor) => collect_cursor_async(cursor).await,
|
||||
@@ -763,7 +767,6 @@ pub async fn get_attack_chain(
|
||||
}
|
||||
};
|
||||
|
||||
let total = nodes.len() as u64;
|
||||
Ok(Json(ApiResponse {
|
||||
data: nodes,
|
||||
total: Some(total),
|
||||
|
||||
@@ -0,0 +1,549 @@
|
||||
//! Platform lifecycle + usage endpoints (`/api/v1/platform/*`,
|
||||
//! PRODUCT_INTEGRATION_SPEC 2.0 §4.1). Called by the tenant-registry and the
|
||||
//! portal with a platform SERVICE TOKEN (client_credentials JWT from the same
|
||||
//! realm, `aud` = this product, `azp` in `PLATFORM_ALLOWED_CLIENTS`).
|
||||
//!
|
||||
//! Tenant ids are the registry UUIDs; the Mongo database per tenant is
|
||||
//! `<prefix>_<tenant_id>`.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::{Path, Query, Request, State};
|
||||
use axum::http::{header, StatusCode};
|
||||
use axum::middleware::Next;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::Json;
|
||||
use futures_util::TryStreamExt;
|
||||
use mongodb::bson::{doc, Document};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use compliance_core::auth::{validate_service_token, JwksState};
|
||||
|
||||
use crate::agent::ComplianceAgent;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct PlatformState {
|
||||
pub agent: Arc<ComplianceAgent>,
|
||||
pub jwks: Option<JwksState>,
|
||||
}
|
||||
|
||||
/// Collection that records lifecycle markers per tenant database.
|
||||
const STATE_COLLECTION: &str = "platform_state";
|
||||
|
||||
/// Service-token gate. Without Keycloak (dev) the endpoints are open and a
|
||||
/// warning is logged once per request.
|
||||
pub async fn require_platform_token(
|
||||
State(st): State<PlatformState>,
|
||||
request: Request,
|
||||
next: Next,
|
||||
) -> Response {
|
||||
let Some(jwks) = st.jwks.as_ref() else {
|
||||
if st.agent.config.app_env.is_hardened() {
|
||||
// These endpoints export and delete a tenant's data; they are never
|
||||
// open outside dev, whatever the rest of the configuration says.
|
||||
tracing::error!("platform endpoints unavailable: no Keycloak in a hardened deployment");
|
||||
return (StatusCode::SERVICE_UNAVAILABLE, "auth not configured").into_response();
|
||||
}
|
||||
tracing::warn!("platform endpoints called without Keycloak configured (dev)");
|
||||
return next.run(request).await;
|
||||
};
|
||||
let token = request
|
||||
.headers()
|
||||
.get(header::AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|s| s.strip_prefix("Bearer "))
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty());
|
||||
let Some(token) = token else {
|
||||
return (StatusCode::UNAUTHORIZED, "Missing bearer token").into_response();
|
||||
};
|
||||
match validate_service_token(token, jwks).await {
|
||||
Ok(claims)
|
||||
if st
|
||||
.agent
|
||||
.config
|
||||
.platform_allowed_clients
|
||||
.iter()
|
||||
.any(|c| c == &claims.azp) =>
|
||||
{
|
||||
next.run(request).await
|
||||
}
|
||||
Ok(claims) => {
|
||||
tracing::warn!(azp = %claims.azp, "client not allowed on platform endpoints");
|
||||
(StatusCode::FORBIDDEN, "client not allowed").into_response()
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("platform token rejected: {e}");
|
||||
(StatusCode::UNAUTHORIZED, "Invalid token").into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
pub struct LifecycleBody {
|
||||
#[serde(default)]
|
||||
pub plan: Option<String>,
|
||||
#[serde(default)]
|
||||
pub config: Option<serde_json::Value>,
|
||||
#[serde(default)]
|
||||
pub reason: Option<String>,
|
||||
#[serde(default)]
|
||||
pub scheduled_erasure_at: Option<String>,
|
||||
#[serde(default)]
|
||||
pub confirm: Option<String>,
|
||||
#[serde(default)]
|
||||
pub tenant_id: Option<String>,
|
||||
/// `demo/reset` only: repopulate the tenant with the bundled demo targets
|
||||
/// and start their scans (the nightly sales-demo reset).
|
||||
#[serde(default)]
|
||||
pub seed: bool,
|
||||
}
|
||||
|
||||
async fn set_marker(
|
||||
agent: &ComplianceAgent,
|
||||
tenant_id: &str,
|
||||
state: &str,
|
||||
extra: Document,
|
||||
) -> Result<(), StatusCode> {
|
||||
let db = agent
|
||||
.db_pool
|
||||
.for_tenant_id(tenant_id)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
let mut set = doc! { "state": state, "updated_at": mongodb::bson::DateTime::now() };
|
||||
set.extend(extra);
|
||||
db.raw_collection(STATE_COLLECTION)
|
||||
.update_one(
|
||||
doc! { "_id": "lifecycle" },
|
||||
doc! { "$set": set, "$setOnInsert": { "created_at": mongodb::bson::DateTime::now() } },
|
||||
)
|
||||
.upsert(true)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
if let Some(r) = &agent.registry {
|
||||
r.invalidate(tenant_id);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn internal<E: std::fmt::Display>(e: E) -> StatusCode {
|
||||
tracing::error!("platform endpoint failed: {e}");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
|
||||
/// `POST /api/v1/platform/tenants/{id}/provision` — idempotent: creates the
|
||||
/// tenant database (indexes) and records the plan/limits.
|
||||
pub async fn provision(
|
||||
State(st): State<PlatformState>,
|
||||
Path(tenant_id): Path<String>,
|
||||
body: Option<Json<LifecycleBody>>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let b = body.map(|Json(b)| b).unwrap_or_default();
|
||||
let mut extra = doc! {};
|
||||
if let Some(p) = &b.plan {
|
||||
extra.insert("plan", p.clone());
|
||||
}
|
||||
if let Some(c) = &b.config {
|
||||
if let Ok(bs) = mongodb::bson::to_bson(c) {
|
||||
extra.insert("limits", bs);
|
||||
}
|
||||
}
|
||||
set_marker(&st.agent, &tenant_id, "provisioned", extra).await?;
|
||||
Ok(Json(
|
||||
serde_json::json!({ "status": "provisioned", "tenant_id": tenant_id }),
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn suspend(
|
||||
State(st): State<PlatformState>,
|
||||
Path(tenant_id): Path<String>,
|
||||
body: Option<Json<LifecycleBody>>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let reason = body.and_then(|Json(b)| b.reason).unwrap_or_default();
|
||||
set_marker(
|
||||
&st.agent,
|
||||
&tenant_id,
|
||||
"suspended",
|
||||
doc! { "reason": reason },
|
||||
)
|
||||
.await?;
|
||||
Ok(Json(
|
||||
serde_json::json!({ "status": "suspended", "tenant_id": tenant_id }),
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn reactivate(
|
||||
State(st): State<PlatformState>,
|
||||
Path(tenant_id): Path<String>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
set_marker(&st.agent, &tenant_id, "active", doc! {}).await?;
|
||||
Ok(Json(
|
||||
serde_json::json!({ "status": "active", "tenant_id": tenant_id }),
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn terminate(
|
||||
State(st): State<PlatformState>,
|
||||
Path(tenant_id): Path<String>,
|
||||
body: Option<Json<LifecycleBody>>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let b = body.map(|Json(b)| b).unwrap_or_default();
|
||||
set_marker(
|
||||
&st.agent,
|
||||
&tenant_id,
|
||||
"terminated",
|
||||
doc! { "reason": b.reason.unwrap_or_default(), "scheduled_erasure_at": b.scheduled_erasure_at.unwrap_or_default() },
|
||||
)
|
||||
.await?;
|
||||
Ok(Json(
|
||||
serde_json::json!({ "status": "terminated", "tenant_id": tenant_id }),
|
||||
))
|
||||
}
|
||||
|
||||
/// `GET /api/v1/platform/tenants/{id}/export` — every collection of the
|
||||
/// tenant database as one JSON document (`{collection: [docs…]}`). Good for
|
||||
/// the export window sizes we expect on staging; large tenants get a
|
||||
/// streamed archive later.
|
||||
pub async fn export(
|
||||
State(st): State<PlatformState>,
|
||||
Path(tenant_id): Path<String>,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let db = st
|
||||
.agent
|
||||
.db_pool
|
||||
.for_tenant_id(&tenant_id)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
let names = db.inner().list_collection_names().await.map_err(internal)?;
|
||||
let mut out = serde_json::Map::new();
|
||||
for name in names {
|
||||
let docs: Vec<Document> = db
|
||||
.raw_collection(&name)
|
||||
.find(doc! {})
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.try_collect()
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
out.insert(name, serde_json::to_value(docs).map_err(internal)?);
|
||||
}
|
||||
let body = serde_json::json!({
|
||||
"tenant_id": tenant_id,
|
||||
"product": st.agent.config.product_key,
|
||||
"exported_at": chrono::Utc::now().to_rfc3339(),
|
||||
"collections": out,
|
||||
});
|
||||
Ok((
|
||||
[(
|
||||
header::CONTENT_DISPOSITION,
|
||||
format!(
|
||||
"attachment; filename=\"{}-{}-export.json\"",
|
||||
st.agent.config.product_key, tenant_id
|
||||
),
|
||||
)],
|
||||
Json(body),
|
||||
)
|
||||
.into_response())
|
||||
}
|
||||
|
||||
/// `DELETE /api/v1/platform/tenants/{id}/data` — GDPR erasure: drops the
|
||||
/// tenant database and removes its code from disk (clones, uploads, work
|
||||
/// trees, blobs, runner artifacts). Requires `{"confirm": "<slug or id>"}`.
|
||||
pub async fn delete_data(
|
||||
State(st): State<PlatformState>,
|
||||
Path(tenant_id): Path<String>,
|
||||
body: Option<Json<LifecycleBody>>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let confirm = body.and_then(|Json(b)| b.confirm).unwrap_or_default();
|
||||
if confirm.is_empty() {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
// Where the tenant's code lies on disk, read before its records go.
|
||||
let config = st.agent.config.clone();
|
||||
let mut paths = crate::retention::tenant_paths(&config, &tenant_id);
|
||||
let db = st
|
||||
.agent
|
||||
.db_pool
|
||||
.for_tenant_id(&tenant_id)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
let targets: Vec<compliance_core::models::OnboardedTarget> =
|
||||
match db.onboarded_targets().find(mongodb::bson::doc! {}).await {
|
||||
Ok(cursor) => super::collect_cursor_async(cursor).await,
|
||||
Err(e) => return Err(internal(e)),
|
||||
};
|
||||
for target in &targets {
|
||||
paths.extend(crate::retention::target_paths(&config, &tenant_id, target));
|
||||
}
|
||||
st.agent
|
||||
.db_pool
|
||||
.drop_tenant(&tenant_id)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
let removal = tokio::task::spawn_blocking(move || crate::retention::remove(&config, &paths))
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
for failure in &removal.failed {
|
||||
tracing::warn!(tenant_id, "tenant files not removed: {failure}");
|
||||
}
|
||||
if let Some(r) = &st.agent.registry {
|
||||
r.invalidate(&tenant_id);
|
||||
}
|
||||
Ok(Json(serde_json::json!({
|
||||
"status": "deleted",
|
||||
"tenant_id": tenant_id,
|
||||
"files_removed": removal.removed,
|
||||
"files_not_removed": removal.failed.len(),
|
||||
})))
|
||||
}
|
||||
|
||||
/// `POST /api/v1/platform/tenants/demo/reset` — drops and re-creates the
|
||||
/// demo tenant database. With `{"seed": true}` it then re-seeds the bundled
|
||||
/// demo targets and starts their scans, which is what the nightly reset of the
|
||||
/// sales demo tenant needs: no user token, same code path as the dashboard's
|
||||
/// "Add demo targets".
|
||||
pub async fn demo_reset(
|
||||
State(st): State<PlatformState>,
|
||||
body: Option<Json<LifecycleBody>>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let b = body.map(|Json(b)| b).unwrap_or_default();
|
||||
let tenant_id = b.tenant_id.unwrap_or_else(|| "demo".to_string());
|
||||
st.agent
|
||||
.db_pool
|
||||
.drop_tenant(&tenant_id)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
let db = st
|
||||
.agent
|
||||
.db_pool
|
||||
.for_tenant_id(&tenant_id)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
if !b.seed {
|
||||
return Ok(Json(
|
||||
serde_json::json!({ "status": "reset", "tenant_id": tenant_id }),
|
||||
));
|
||||
}
|
||||
let seeded = crate::demo_seed::seed_tenant(
|
||||
&st.agent,
|
||||
&db,
|
||||
&tenant_id,
|
||||
&crate::demo_seed::SeedRequest::default(),
|
||||
)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
Ok(Json(serde_json::json!({
|
||||
"status": "reset",
|
||||
"tenant_id": tenant_id,
|
||||
"seeded": seeded,
|
||||
})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct UsageQuery {
|
||||
pub tenant_id: String,
|
||||
#[serde(default)]
|
||||
pub from: Option<String>,
|
||||
#[serde(default)]
|
||||
pub to: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct UsageResponse {
|
||||
pub tenant_id: String,
|
||||
pub product: String,
|
||||
pub period: serde_json::Value,
|
||||
pub metrics: serde_json::Value,
|
||||
}
|
||||
|
||||
/// `GET /api/v1/platform/usage?tenant_id=&from=&to=` — dashboard metrics
|
||||
/// (billing uses the pushed usage events, §9.2).
|
||||
pub async fn usage(
|
||||
State(st): State<PlatformState>,
|
||||
Query(q): Query<UsageQuery>,
|
||||
) -> Result<Json<UsageResponse>, StatusCode> {
|
||||
let db = st
|
||||
.agent
|
||||
.db_pool
|
||||
.for_tenant_id(&q.tenant_id)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
let parse = |s: &Option<String>| -> Result<Option<mongodb::bson::DateTime>, StatusCode> {
|
||||
match s {
|
||||
None => Ok(None),
|
||||
Some(v) => chrono::DateTime::parse_from_rfc3339(v)
|
||||
.map(|d| {
|
||||
Some(mongodb::bson::DateTime::from_chrono(
|
||||
d.with_timezone(&chrono::Utc),
|
||||
))
|
||||
})
|
||||
.map_err(|_| StatusCode::BAD_REQUEST),
|
||||
}
|
||||
};
|
||||
let (from, to) = (parse(&q.from)?, parse(&q.to)?);
|
||||
let mut range = doc! {};
|
||||
if let Some(f) = from {
|
||||
range.insert("$gte", f);
|
||||
}
|
||||
if let Some(t) = to {
|
||||
range.insert("$lte", t);
|
||||
}
|
||||
let completed = if range.is_empty() {
|
||||
doc! { "status": "completed" }
|
||||
} else {
|
||||
doc! { "status": "completed", "completed_at": range.clone() }
|
||||
};
|
||||
let scans = db
|
||||
.scan_runs()
|
||||
.count_documents(completed.clone())
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
let dast = db
|
||||
.dast_scan_runs()
|
||||
.count_documents(completed)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
let targets = db
|
||||
.onboarded_targets()
|
||||
.count_documents(doc! {})
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
let findings = db
|
||||
.findings()
|
||||
.count_documents(doc! {})
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
let pentests = db
|
||||
.pentest_sessions()
|
||||
.count_documents(doc! {})
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
Ok(Json(UsageResponse {
|
||||
tenant_id: q.tenant_id,
|
||||
product: st.agent.config.product_key.clone(),
|
||||
period: serde_json::json!({ "from": q.from, "to": q.to }),
|
||||
metrics: serde_json::json!({
|
||||
"scans_completed": scans,
|
||||
"dast_scans_completed": dast,
|
||||
"targets": targets,
|
||||
"findings": findings,
|
||||
"pentest_sessions": pentests,
|
||||
}),
|
||||
}))
|
||||
}
|
||||
|
||||
/// `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!({
|
||||
"product": st.agent.config.product_key,
|
||||
"version": env!("CARGO_PKG_VERSION"),
|
||||
"contract": "2.0",
|
||||
// Deployment feature flags (PW_FEATURES). The dashboard reads the same
|
||||
// set the agent enforces instead of carrying its own copy of the env.
|
||||
"features": st.agent.config.features.flags(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// A target as the portal lists it for a project.
|
||||
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
|
||||
pub struct PlatformTarget {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub target_type: compliance_core::models::TargetType,
|
||||
/// When its newest scan started; `None` before the first.
|
||||
pub last_scan_at: Option<chrono::DateTime<chrono::Utc>>,
|
||||
/// Findings that still need attention.
|
||||
pub open_findings: u64,
|
||||
/// Its projects that the registry still lists.
|
||||
pub project_ids: Vec<String>,
|
||||
}
|
||||
|
||||
/// Open findings of each target in `target_ids`, in one query.
|
||||
async fn open_findings_counts(
|
||||
db: &crate::database::Database,
|
||||
target_ids: Vec<String>,
|
||||
) -> Result<std::collections::HashMap<String, u64>, StatusCode> {
|
||||
let pipeline = vec![
|
||||
doc! { "$match": {
|
||||
"repo_id": { "$in": target_ids },
|
||||
"status": { "$in": super::health::OPEN_STATUSES.to_vec() },
|
||||
} },
|
||||
doc! { "$group": { "_id": "$repo_id", "n": { "$sum": 1 } } },
|
||||
];
|
||||
let rows: Vec<Document> = db
|
||||
.findings()
|
||||
.aggregate(pipeline)
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.try_collect()
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
Ok(rows
|
||||
.iter()
|
||||
.filter_map(|row| {
|
||||
let id = row.get_str("_id").ok()?.to_string();
|
||||
let n = row
|
||||
.get_i32("n")
|
||||
.map(i64::from)
|
||||
.or_else(|_| row.get_i64("n"))
|
||||
.ok()?;
|
||||
Some((id, u64::try_from(n).ok()?))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// `GET /api/v1/platform/tenants/{id}/targets?project=<id>` — the tenant's
|
||||
/// targets (one project's, with `project`), for the portal through the
|
||||
/// registry. Read-only. Project ids the registry no longer lists are left
|
||||
/// out; when it cannot be asked, the stored ids are returned as they are.
|
||||
pub async fn list_targets(
|
||||
State(st): State<PlatformState>,
|
||||
Path(tenant_id): Path<String>,
|
||||
Query(filter): Query<super::onboarding::TargetFilter>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let db = st
|
||||
.agent
|
||||
.db_pool
|
||||
.for_tenant_id(&tenant_id)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
let targets: Vec<compliance_core::models::OnboardedTarget> = db
|
||||
.onboarded_targets()
|
||||
.find(filter.to_query())
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.try_collect()
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
let ids: Vec<String> = targets
|
||||
.iter()
|
||||
.filter_map(|t| t.id.map(|id| id.to_hex()))
|
||||
.collect();
|
||||
let runs = db.scan_runs();
|
||||
let (mut last_scans, open) = tokio::join!(
|
||||
super::onboarding::latest_scan_runs(&runs, ids.clone()),
|
||||
open_findings_counts(&db, ids),
|
||||
);
|
||||
let open = open?;
|
||||
let known = super::projects::tenant_projects(&st.agent, &tenant_id)
|
||||
.await
|
||||
.ok();
|
||||
let items: Vec<PlatformTarget> = targets
|
||||
.into_iter()
|
||||
.map(|t| {
|
||||
let id = t.id.map(|id| id.to_hex()).unwrap_or_default();
|
||||
PlatformTarget {
|
||||
last_scan_at: last_scans.remove(&id).map(|run| run.started_at),
|
||||
open_findings: open.get(&id).copied().unwrap_or(0),
|
||||
project_ids: match known.as_deref() {
|
||||
Some(known) => super::projects::known_project_ids(&t.project_ids, known),
|
||||
None => t.project_ids,
|
||||
},
|
||||
name: t.name,
|
||||
target_type: t.target_type,
|
||||
id,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(serde_json::json!({ "items": items })))
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
//! A tenant's projects, which the platform registry owns: listing them for
|
||||
//! the dashboard, and checking assignments against them.
|
||||
//!
|
||||
//! Targets store the ids of the projects they belong to (`project_ids`). A
|
||||
//! project deleted in the registry drops out of its list, and readers show
|
||||
//! only ids they still find there.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use axum::extract::Extension;
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
|
||||
use compliance_core::models::Project;
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use super::dto::AgentExt;
|
||||
use crate::agent::ComplianceAgent;
|
||||
|
||||
/// The tenant's projects from the registry. Empty without a registry (dev).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// `503` when the registry could not answer.
|
||||
pub async fn tenant_projects(
|
||||
agent: &ComplianceAgent,
|
||||
tenant_id: &str,
|
||||
) -> Result<Vec<Project>, StatusCode> {
|
||||
let Some(registry) = agent.registry.as_ref() else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
registry.list_projects(tenant_id).await.map_err(|e| {
|
||||
tracing::error!(tenant_id, "project list unavailable: {e}");
|
||||
StatusCode::SERVICE_UNAVAILABLE
|
||||
})
|
||||
}
|
||||
|
||||
/// `requested` as stored: trimmed, without duplicates, in the given order.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// `422` when an id is not one of the tenant's projects (`known`).
|
||||
pub fn validated_project_ids(
|
||||
requested: &[String],
|
||||
known: &[Project],
|
||||
) -> Result<Vec<String>, StatusCode> {
|
||||
let known: HashSet<&str> = known.iter().map(|p| p.id.as_str()).collect();
|
||||
let mut seen = HashSet::with_capacity(requested.len());
|
||||
let mut ids = Vec::with_capacity(requested.len());
|
||||
for id in requested.iter().map(|id| id.trim()) {
|
||||
if !known.contains(id) {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
if seen.insert(id) {
|
||||
ids.push(id.to_string());
|
||||
}
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// The ids in `ids` that are still one of the tenant's projects.
|
||||
pub fn known_project_ids(ids: &[String], known: &[Project]) -> Vec<String> {
|
||||
ids.iter()
|
||||
.filter(|id| known.iter().any(|p| &p.id == *id))
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The audit entry for a change of target `target_id`'s projects from
|
||||
/// `before` to `after`, naming each project from `known` (a deleted one with
|
||||
/// an empty name). `None` when nothing changed.
|
||||
pub fn projects_changed_entry(
|
||||
ctx: &compliance_core::TenantContext,
|
||||
(target_id, target_name): (&str, &str),
|
||||
before: &[String],
|
||||
after: &[String],
|
||||
known: &[Project],
|
||||
) -> Option<crate::registry::AuditEntry> {
|
||||
let named = |id: &String| {
|
||||
let name = known
|
||||
.iter()
|
||||
.find(|p| &p.id == id)
|
||||
.map_or("", |p| p.name.as_str());
|
||||
serde_json::json!({ "id": id, "name": name })
|
||||
};
|
||||
let added: Vec<_> = after
|
||||
.iter()
|
||||
.filter(|id| !before.contains(id))
|
||||
.map(named)
|
||||
.collect();
|
||||
let removed: Vec<_> = before
|
||||
.iter()
|
||||
.filter(|id| !after.contains(id))
|
||||
.map(named)
|
||||
.collect();
|
||||
if added.is_empty() && removed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(
|
||||
crate::registry::AuditEntry::by(
|
||||
ctx,
|
||||
"target.projects_changed",
|
||||
serde_json::json!({ "added": added, "removed": removed }),
|
||||
)
|
||||
.about_target(target_id, target_name),
|
||||
)
|
||||
}
|
||||
|
||||
/// GET /api/v1/projects — the tenant's projects, for choosing and showing
|
||||
/// them in the dashboard.
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn list_projects(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let projects = tenant_projects(&agent, &tenant.0.tenant_id).await?;
|
||||
Ok(Json(serde_json::json!({ "data": projects })))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::ProjectKind;
|
||||
|
||||
fn project(id: &str) -> Project {
|
||||
Project {
|
||||
id: id.to_string(),
|
||||
name: format!("Projekt {id}"),
|
||||
kind: ProjectKind::Product,
|
||||
description: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assignments_are_trimmed_and_deduplicated() {
|
||||
let known = [project("p1"), project("p2")];
|
||||
let ids = validated_project_ids(
|
||||
&["p2".to_string(), " p1 ".to_string(), "p2".to_string()],
|
||||
&known,
|
||||
);
|
||||
assert_eq!(ids, Ok(vec!["p2".to_string(), "p1".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_project_is_refused() {
|
||||
let known = [project("p1")];
|
||||
assert_eq!(
|
||||
validated_project_ids(&["p9".to_string()], &known),
|
||||
Err(StatusCode::UNPROCESSABLE_ENTITY)
|
||||
);
|
||||
assert_eq!(validated_project_ids(&[], &known), Ok(Vec::new()));
|
||||
}
|
||||
|
||||
fn ctx(staff: bool) -> compliance_core::TenantContext {
|
||||
compliance_core::TenantContext {
|
||||
tenant_id: "t-1".to_string(),
|
||||
tenant_slug: "faller".to_string(),
|
||||
org_roles: Vec::new(),
|
||||
products: Vec::new(),
|
||||
plan: String::new(),
|
||||
status: compliance_core::TenantStatus::Active,
|
||||
user_id: "u-1".to_string(),
|
||||
user_name: Some("Anna Faller".to_string()),
|
||||
staff: staff.then(|| compliance_core::StaffAccess {
|
||||
user_id: "u-1".to_string(),
|
||||
user_name: Some("Sharang".to_string()),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_projects_change_is_audited_with_names() {
|
||||
let known = [project("p1"), project("p2")];
|
||||
let entry = projects_changed_entry(
|
||||
&ctx(false),
|
||||
("abc", "Lok-Steuerung"),
|
||||
&["p1".to_string(), "gone".to_string()],
|
||||
&["p1".to_string(), "p2".to_string()],
|
||||
&known,
|
||||
)
|
||||
.expect("a change");
|
||||
assert_eq!(entry.action, "target.projects_changed");
|
||||
assert_eq!(entry.actor_type, "user");
|
||||
assert_eq!(entry.actor_name, "Anna Faller");
|
||||
assert_eq!(
|
||||
(entry.target_type.as_str(), entry.target_id.as_str()),
|
||||
("target", "abc")
|
||||
);
|
||||
assert_eq!(entry.target_name, "Lok-Steuerung");
|
||||
assert_eq!(
|
||||
entry.metadata,
|
||||
serde_json::json!({
|
||||
"added": [{ "id": "p2", "name": "Projekt p2" }],
|
||||
"removed": [{ "id": "gone", "name": "" }]
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn support_is_audited_as_staff_and_no_change_as_nothing() {
|
||||
let known = [project("p1")];
|
||||
let entry =
|
||||
projects_changed_entry(&ctx(true), ("abc", "x"), &[], &["p1".to_string()], &known)
|
||||
.expect("a change");
|
||||
assert_eq!(entry.actor_type, "staff");
|
||||
assert_eq!(entry.actor_name, "BreakPilot-Support (Sharang)");
|
||||
assert!(projects_changed_entry(
|
||||
&ctx(false),
|
||||
("abc", "x"),
|
||||
&["p1".to_string()],
|
||||
&["p1".to_string()],
|
||||
&known
|
||||
)
|
||||
.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleted_projects_drop_out_on_read() {
|
||||
let known = [project("p1")];
|
||||
assert_eq!(
|
||||
known_project_ids(&["p1".to_string(), "gone".to_string()], &known),
|
||||
["p1".to_string()]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,14 @@ use super::dto::*;
|
||||
use compliance_core::models::SbomEntry;
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
/// Components above which an export is refused instead of built (#67). An
|
||||
/// SBOM is a compliance document, so it is never truncated: a repository this
|
||||
/// large gets a clear error, not a partial file.
|
||||
pub(crate) const MAX_EXPORT_COMPONENTS: u64 = 100_000;
|
||||
|
||||
/// Package names listed per license in the summary; `count` stays exact.
|
||||
const MAX_LICENSE_PACKAGES: i64 = 100;
|
||||
|
||||
const COPYLEFT_LICENSES: &[&str] = &[
|
||||
"GPL-2.0",
|
||||
"GPL-2.0-only",
|
||||
@@ -79,7 +87,10 @@ pub async fn list_sbom(
|
||||
}
|
||||
if let Some(q) = &filter.q {
|
||||
if !q.is_empty() {
|
||||
query.insert("name", doc! { "$regex": q, "$options": "i" });
|
||||
query.insert(
|
||||
"name",
|
||||
doc! { "$regex": super::dto::literal_regex(q), "$options": "i" },
|
||||
);
|
||||
}
|
||||
}
|
||||
if let Some(has_vulns) = filter.has_vulns {
|
||||
@@ -93,7 +104,7 @@ pub async fn list_sbom(
|
||||
query.insert("license", license);
|
||||
}
|
||||
|
||||
let skip = (filter.page.saturating_sub(1)) * filter.limit as u64;
|
||||
let skip = filter.skip();
|
||||
let total = db
|
||||
.sbom_entries()
|
||||
.count_documents(query.clone())
|
||||
@@ -130,6 +141,18 @@ pub async fn export_sbom(
|
||||
) -> Result<impl IntoResponse, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let db = &db;
|
||||
let components = db
|
||||
.sbom_entries()
|
||||
.count_documents(doc! { "repo_id": ¶ms.repo_id })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
if components > MAX_EXPORT_COMPONENTS {
|
||||
tracing::warn!(
|
||||
components,
|
||||
"SBOM export refused: too large to build in memory"
|
||||
);
|
||||
return Err(StatusCode::PAYLOAD_TOO_LARGE);
|
||||
}
|
||||
let entries: Vec<SbomEntry> = match db
|
||||
.sbom_entries()
|
||||
.find(doc! { "repo_id": ¶ms.repo_id })
|
||||
@@ -142,77 +165,11 @@ pub async fn export_sbom(
|
||||
}
|
||||
};
|
||||
|
||||
let subject = format!("repo-{}", params.repo_id);
|
||||
let body = if params.format == "spdx" {
|
||||
// SPDX 2.3 format
|
||||
let packages: Vec<serde_json::Value> = entries
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, e)| {
|
||||
serde_json::json!({
|
||||
"SPDXID": format!("SPDXRef-Package-{i}"),
|
||||
"name": e.name,
|
||||
"versionInfo": e.version,
|
||||
"downloadLocation": "NOASSERTION",
|
||||
"licenseConcluded": e.license.as_deref().unwrap_or("NOASSERTION"),
|
||||
"externalRefs": e.purl.as_ref().map(|p| vec![serde_json::json!({
|
||||
"referenceCategory": "PACKAGE-MANAGER",
|
||||
"referenceType": "purl",
|
||||
"referenceLocator": p,
|
||||
})]).unwrap_or_default(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
serde_json::json!({
|
||||
"spdxVersion": "SPDX-2.3",
|
||||
"dataLicense": "CC0-1.0",
|
||||
"SPDXID": "SPDXRef-DOCUMENT",
|
||||
"name": format!("sbom-{}", params.repo_id),
|
||||
"documentNamespace": format!("https://compliance-scanner/sbom/{}", params.repo_id),
|
||||
"packages": packages,
|
||||
})
|
||||
compliance_core::sbom_docs::spdx(&entries, ¶ms.repo_id)
|
||||
} else {
|
||||
// CycloneDX 1.5 format
|
||||
let components: Vec<serde_json::Value> = entries
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let mut comp = serde_json::json!({
|
||||
"type": "library",
|
||||
"name": e.name,
|
||||
"version": e.version,
|
||||
"group": e.package_manager,
|
||||
});
|
||||
if let Some(purl) = &e.purl {
|
||||
comp["purl"] = serde_json::Value::String(purl.clone());
|
||||
}
|
||||
if let Some(license) = &e.license {
|
||||
comp["licenses"] = serde_json::json!([{ "license": { "id": license } }]);
|
||||
}
|
||||
if !e.known_vulnerabilities.is_empty() {
|
||||
comp["vulnerabilities"] = serde_json::json!(
|
||||
e.known_vulnerabilities.iter().map(|v| serde_json::json!({
|
||||
"id": v.id,
|
||||
"source": { "name": v.source },
|
||||
"ratings": v.severity.as_ref().map(|s| vec![serde_json::json!({"severity": s})]).unwrap_or_default(),
|
||||
})).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
comp
|
||||
})
|
||||
.collect();
|
||||
|
||||
serde_json::json!({
|
||||
"bomFormat": "CycloneDX",
|
||||
"specVersion": "1.5",
|
||||
"version": 1,
|
||||
"metadata": {
|
||||
"component": {
|
||||
"type": "application",
|
||||
"name": format!("repo-{}", params.repo_id),
|
||||
}
|
||||
},
|
||||
"components": components,
|
||||
})
|
||||
compliance_core::sbom_docs::cyclonedx(&entries, &subject)
|
||||
};
|
||||
|
||||
let json_str =
|
||||
@@ -253,35 +210,47 @@ pub async fn license_summary(
|
||||
query.insert("repo_id", repo_id);
|
||||
}
|
||||
|
||||
let entries: Vec<SbomEntry> = match db.sbom_entries().find(query).await {
|
||||
Ok(cursor) => collect_cursor_async(cursor).await,
|
||||
// Grouped in Mongo: this used to load every SBOM entry of the tenant (with
|
||||
// its vulnerability list) into the agent when no repo was given (#67).
|
||||
#[derive(serde::Deserialize)]
|
||||
struct LicenseRow {
|
||||
#[serde(rename = "_id")]
|
||||
license: String,
|
||||
count: i64,
|
||||
packages: Vec<String>,
|
||||
}
|
||||
let pipeline = vec![
|
||||
doc! { "$match": query },
|
||||
doc! { "$group": {
|
||||
"_id": { "$ifNull": ["$license", "Unknown"] },
|
||||
"count": { "$sum": 1 },
|
||||
"packages": { "$firstN": { "input": "$name", "n": MAX_LICENSE_PACKAGES } },
|
||||
} },
|
||||
];
|
||||
let mut summaries: Vec<LicenseSummary> = match db.sbom_entries().aggregate(pipeline).await {
|
||||
Ok(cursor) => {
|
||||
use futures_util::StreamExt;
|
||||
cursor
|
||||
.filter_map(|row| async move {
|
||||
let row: LicenseRow = mongodb::bson::from_document(row.ok()?).ok()?;
|
||||
let upper = row.license.to_uppercase();
|
||||
Some(LicenseSummary {
|
||||
is_copyleft: COPYLEFT_LICENSES
|
||||
.iter()
|
||||
.any(|c| upper.contains(&c.to_uppercase())),
|
||||
license: row.license,
|
||||
count: u64::try_from(row.count).unwrap_or(0),
|
||||
packages: row.packages,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
.await
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to fetch SBOM entries for license summary: {e}");
|
||||
tracing::warn!("Failed to aggregate SBOM licenses: {e}");
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
|
||||
let mut license_map: std::collections::HashMap<String, Vec<String>> =
|
||||
std::collections::HashMap::new();
|
||||
for entry in &entries {
|
||||
let lic = entry.license.as_deref().unwrap_or("Unknown").to_string();
|
||||
license_map.entry(lic).or_default().push(entry.name.clone());
|
||||
}
|
||||
|
||||
let mut summaries: Vec<LicenseSummary> = license_map
|
||||
.into_iter()
|
||||
.map(|(license, packages)| {
|
||||
let is_copyleft = COPYLEFT_LICENSES
|
||||
.iter()
|
||||
.any(|c| license.to_uppercase().contains(&c.to_uppercase()));
|
||||
LicenseSummary {
|
||||
license,
|
||||
count: packages.len() as u64,
|
||||
is_copyleft,
|
||||
packages,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
summaries.sort_by_key(|s| std::cmp::Reverse(s.count));
|
||||
|
||||
Ok(Json(ApiResponse {
|
||||
@@ -300,29 +269,8 @@ pub async fn sbom_diff(
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let db = &db;
|
||||
|
||||
let entries_a: Vec<SbomEntry> = match db
|
||||
.sbom_entries()
|
||||
.find(doc! { "repo_id": ¶ms.repo_a })
|
||||
.await
|
||||
{
|
||||
Ok(cursor) => collect_cursor_async(cursor).await,
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to fetch SBOM entries for repo_a: {e}");
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
|
||||
let entries_b: Vec<SbomEntry> = match db
|
||||
.sbom_entries()
|
||||
.find(doc! { "repo_id": ¶ms.repo_b })
|
||||
.await
|
||||
{
|
||||
Ok(cursor) => collect_cursor_async(cursor).await,
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to fetch SBOM entries for repo_b: {e}");
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
let entries_a = diff_rows(db, ¶ms.repo_a).await;
|
||||
let entries_b = diff_rows(db, ¶ms.repo_b).await;
|
||||
|
||||
// Build maps by (name, package_manager) -> version
|
||||
let map_a: std::collections::HashMap<(String, String), String> = entries_a
|
||||
@@ -388,3 +336,31 @@ pub async fn sbom_diff(
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// The three fields a diff compares, for one repository.
|
||||
///
|
||||
/// A diff must be complete, so it is not capped; instead it loads only
|
||||
/// name, package manager and version, not whole entries with their
|
||||
/// vulnerability lists (#67).
|
||||
#[derive(serde::Deserialize)]
|
||||
struct DiffRow {
|
||||
name: String,
|
||||
package_manager: String,
|
||||
version: String,
|
||||
}
|
||||
|
||||
async fn diff_rows(db: &crate::database::Database, repo_id: &str) -> Vec<DiffRow> {
|
||||
match db
|
||||
.sbom_entries()
|
||||
.clone_with_type::<DiffRow>()
|
||||
.find(doc! { "repo_id": repo_id })
|
||||
.projection(doc! { "_id": 0, "name": 1, "package_manager": 1, "version": 1 })
|
||||
.await
|
||||
{
|
||||
Ok(cursor) => collect_cursor_async(cursor).await,
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to fetch SBOM entries for diff: {e}");
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,51 @@
|
||||
use axum::extract::{Extension, Query};
|
||||
use axum::Json;
|
||||
use mongodb::bson::doc;
|
||||
use mongodb::bson::{doc, Document};
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::dto::*;
|
||||
use compliance_core::models::ScanRun;
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
/// Which scan runs to list.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
pub struct ScanRunFilter {
|
||||
/// Only the runs of this target (its id), for the target's scan history.
|
||||
#[serde(default)]
|
||||
pub target_id: Option<String>,
|
||||
}
|
||||
|
||||
impl ScanRunFilter {
|
||||
/// The MongoDB filter: runs store their target's id as `repo_id`.
|
||||
fn to_document(&self) -> Document {
|
||||
match self.target_id.as_deref().filter(|id| !id.is_empty()) {
|
||||
Some(id) => doc! { "repo_id": id },
|
||||
None => doc! {},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// GET /api/v1/scan-runs?target_id=&page=&limit= — newest first.
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn list_scan_runs(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Query(params): Query<PaginationParams>,
|
||||
Query(filter): Query<ScanRunFilter>,
|
||||
) -> ApiResult<Vec<ScanRun>> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let db = &db;
|
||||
let skip = (params.page.saturating_sub(1)) * params.limit as u64;
|
||||
let total = db.scan_runs().count_documents(doc! {}).await.unwrap_or(0);
|
||||
let skip = params.skip();
|
||||
let query = filter.to_document();
|
||||
let total = db
|
||||
.scan_runs()
|
||||
.count_documents(query.clone())
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
|
||||
let scans = match db
|
||||
.scan_runs()
|
||||
.find(doc! {})
|
||||
.find(query)
|
||||
.sort(doc! { "started_at": -1 })
|
||||
.skip(skip)
|
||||
.limit(params.limit)
|
||||
@@ -38,3 +64,25 @@ pub async fn list_scan_runs(
|
||||
page: Some(params.page),
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_target_filter_selects_its_runs_only() {
|
||||
let filter = ScanRunFilter {
|
||||
target_id: Some("65f0c0ffee".to_string()),
|
||||
};
|
||||
assert_eq!(filter.to_document(), doc! { "repo_id": "65f0c0ffee" });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_or_empty_target_lists_every_run() {
|
||||
assert_eq!(ScanRunFilter::default().to_document(), doc! {});
|
||||
let empty = ScanRunFilter {
|
||||
target_id: Some(String::new()),
|
||||
};
|
||||
assert_eq!(empty.to_document(), doc! {});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
//! BreakPilot support access: the tenants support may open, and opening one.
|
||||
//!
|
||||
//! Support staff (Keycloak realm roles [`compliance_core::SUPPORT_ROLES`])
|
||||
//! choose a tenant in the dashboard, which then names it in every request
|
||||
//! (`X-Pruefwerk-Tenant`). The JWT middleware and `require_entitlement`
|
||||
//! confirm the choice; these routes only list and open.
|
||||
|
||||
use axum::extract::Extension;
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use serde::Serialize;
|
||||
|
||||
use compliance_core::tenant_ctx::{StaffCtx, TenantCtx};
|
||||
|
||||
use super::dto::AgentExt;
|
||||
use crate::registry::RegistryTenant;
|
||||
|
||||
/// A tenant as the support picker lists it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
pub struct SupportTenant {
|
||||
pub id: String,
|
||||
pub slug: String,
|
||||
pub name: String,
|
||||
pub status: String,
|
||||
}
|
||||
|
||||
impl From<RegistryTenant> for SupportTenant {
|
||||
fn from(t: RegistryTenant) -> Self {
|
||||
Self {
|
||||
id: t.id,
|
||||
slug: t.slug,
|
||||
name: t.name,
|
||||
status: t.status,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Order the picker by name (then slug), case-insensitively.
|
||||
fn picker_order(mut tenants: Vec<SupportTenant>) -> Vec<SupportTenant> {
|
||||
tenants.sort_by_cached_key(|t| (t.name.to_lowercase(), t.slug.clone()));
|
||||
tenants
|
||||
}
|
||||
|
||||
/// GET /api/v1/support/tenants — every tenant, for support to choose from.
|
||||
/// 403 for anyone but support; 503 without a registry.
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn list_tenants(
|
||||
Extension(agent): AgentExt,
|
||||
StaffCtx(_staff): StaffCtx,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let registry = agent
|
||||
.registry
|
||||
.as_ref()
|
||||
.ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let tenants = registry.list_tenants().await.map_err(|e| {
|
||||
tracing::error!("support tenant list failed: {e}");
|
||||
StatusCode::SERVICE_UNAVAILABLE
|
||||
})?;
|
||||
let tenants = picker_order(tenants.into_iter().map(SupportTenant::from).collect());
|
||||
Ok(Json(serde_json::json!({ "data": tenants })))
|
||||
}
|
||||
|
||||
/// POST /api/v1/support/session — open the tenant named in the header. The
|
||||
/// middleware has confirmed it with the registry and records the opening in
|
||||
/// the audit log; this answers what was opened. 403 for anyone but support.
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn open_session(tenant: TenantCtx) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
if tenant.0.staff.is_none() {
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
Ok(Json(serde_json::json!({
|
||||
"data": {
|
||||
"tenant_id": tenant.0.tenant_id,
|
||||
"slug": tenant.0.tenant_slug,
|
||||
"status": tenant.0.status,
|
||||
}
|
||||
})))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn tenant(name: &str, slug: &str) -> SupportTenant {
|
||||
SupportTenant {
|
||||
id: format!("id-{slug}"),
|
||||
slug: slug.to_string(),
|
||||
name: name.to_string(),
|
||||
status: "active".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_picker_lists_tenants_by_name() {
|
||||
let ordered = picker_order(vec![
|
||||
tenant("Gebr. Faller", "faller"),
|
||||
tenant("acme", "acme"),
|
||||
tenant("Breakpilot Demo", "demo"),
|
||||
]);
|
||||
let names: Vec<&str> = ordered.iter().map(|t| t.name.as_str()).collect();
|
||||
assert_eq!(names, ["acme", "Breakpilot Demo", "Gebr. Faller"]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
//! What a client may send to create or change a target, and how it combines
|
||||
//! with what is stored.
|
||||
//!
|
||||
//! The API never returns a credential, so a client that echoes a target back
|
||||
//! (the dashboard's editor does) cannot send its git token or its uploaded
|
||||
//! file. Anything left out therefore keeps its stored value: an artifact keeps
|
||||
//! its token and its uploaded file, and a scan config keeps every field the
|
||||
//! request does not name (#304).
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use compliance_core::models::{
|
||||
Artifact, ArtifactAuth, ArtifactKind, Environment, IssueTrackerConfig, PentestConfig,
|
||||
PentestStrategy, PlcFormat, ScanType, TargetScanConfig,
|
||||
};
|
||||
|
||||
use crate::secrets::{SecretBox, SecretError};
|
||||
|
||||
/// The auth method of a git access token.
|
||||
const TOKEN_METHOD: &str = "token";
|
||||
|
||||
/// A client-supplied artifact spec. The server builds the [`Artifact`] (and its
|
||||
/// id) from it, so clients never set internal fields.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ArtifactInput {
|
||||
pub kind: ArtifactKind,
|
||||
pub source_ref: String,
|
||||
#[serde(default)]
|
||||
pub branch: Option<String>,
|
||||
#[serde(default)]
|
||||
pub plc_format: Option<PlcFormat>,
|
||||
/// A git access token for a private repository (#303). Sent: stored
|
||||
/// sealed. Sent empty: removed. Left out: the stored one is kept.
|
||||
#[serde(default)]
|
||||
pub token: Option<String>,
|
||||
/// The username that goes with `token`; the clone uses `x-access-token`
|
||||
/// when there is none.
|
||||
#[serde(default)]
|
||||
pub username: Option<String>,
|
||||
}
|
||||
|
||||
impl ArtifactInput {
|
||||
/// The artifact to store. `stored` is the artifact this input updates, if
|
||||
/// any: its id, uploaded file, ingest record and credentials carry over.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`SecretError::NoKey`] when a new token arrives and the deployment has
|
||||
/// no key to seal it with.
|
||||
pub fn build(
|
||||
&self,
|
||||
secrets: &SecretBox,
|
||||
stored: Option<&Artifact>,
|
||||
) -> Result<Artifact, SecretError> {
|
||||
let mut artifact = crate::targets::reference_artifact(
|
||||
self.kind,
|
||||
self.source_ref.clone(),
|
||||
self.branch.clone(),
|
||||
self.plc_format,
|
||||
);
|
||||
if let Some(stored) = stored {
|
||||
artifact.id = stored.id.clone();
|
||||
artifact.display_name = stored.display_name.clone();
|
||||
artifact.stored_path = stored.stored_path.clone();
|
||||
artifact.content_hash = stored.content_hash.clone();
|
||||
artifact.size_bytes = stored.size_bytes;
|
||||
artifact.detected = stored.detected.clone();
|
||||
artifact.ingested_at = stored.ingested_at;
|
||||
artifact.auth = stored.auth.clone();
|
||||
}
|
||||
if self.kind == ArtifactKind::GitRepo {
|
||||
artifact.auth = self.git_auth(secrets, stored.and_then(|s| s.auth.as_ref()))?;
|
||||
}
|
||||
Ok(artifact)
|
||||
}
|
||||
|
||||
/// The git credentials after this input: the token sealed, kept or
|
||||
/// removed (see [`SecretBox::take_update`]), with its username.
|
||||
fn git_auth(
|
||||
&self,
|
||||
secrets: &SecretBox,
|
||||
stored: Option<&ArtifactAuth>,
|
||||
) -> Result<Option<ArtifactAuth>, SecretError> {
|
||||
let mut secret = self.token.clone();
|
||||
secrets.take_update(&mut secret, stored.and_then(|a| a.secret.as_ref()))?;
|
||||
let Some(secret) = secret else {
|
||||
return Ok(None);
|
||||
};
|
||||
let username = self
|
||||
.username
|
||||
.clone()
|
||||
.filter(|u| !u.trim().is_empty())
|
||||
.or_else(|| stored.and_then(|a| a.username.clone()));
|
||||
Ok(Some(ArtifactAuth {
|
||||
method: TOKEN_METHOD.to_string(),
|
||||
username,
|
||||
secret: Some(secret),
|
||||
..Default::default()
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the artifacts of an update from `inputs`, carrying over what each
|
||||
/// stored artifact holds that a client cannot send. An input matches the first
|
||||
/// stored artifact of the same kind and source that no earlier input took.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// As [`ArtifactInput::build`].
|
||||
pub fn merge_artifacts(
|
||||
secrets: &SecretBox,
|
||||
inputs: &[ArtifactInput],
|
||||
stored: &[Artifact],
|
||||
) -> Result<Vec<Artifact>, SecretError> {
|
||||
let mut taken = vec![false; stored.len()];
|
||||
inputs
|
||||
.iter()
|
||||
.map(|input| {
|
||||
let matched = stored.iter().enumerate().position(|(i, a)| {
|
||||
!taken[i] && a.kind == input.kind && a.source_ref == input.source_ref
|
||||
});
|
||||
if let Some(i) = matched {
|
||||
taken[i] = true;
|
||||
}
|
||||
input.build(secrets, matched.map(|i| &stored[i]))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A change to a target's scan config. A field left out keeps its stored
|
||||
/// value: enabling a scan must not remove the issue tracker (#304).
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
pub struct ScanConfigUpdate {
|
||||
pub enabled_scans: Option<Vec<ScanType>>,
|
||||
pub disabled_scans: Option<Vec<ScanType>>,
|
||||
pub environment: Option<Environment>,
|
||||
pub allow_destructive: Option<bool>,
|
||||
pub strategy: Option<PentestStrategy>,
|
||||
pub pentest: Option<PentestConfig>,
|
||||
pub issue_tracker: Option<IssueTrackerConfig>,
|
||||
}
|
||||
|
||||
impl ScanConfigUpdate {
|
||||
/// `stored` with this update applied. Credentials in a sent tracker or
|
||||
/// pentest block are sealed; one left out of the block keeps the stored
|
||||
/// value (the API never returns them).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`SecretError::NoKey`] when a new credential arrives without a key.
|
||||
pub fn apply(
|
||||
self,
|
||||
secrets: &SecretBox,
|
||||
stored: &TargetScanConfig,
|
||||
) -> Result<TargetScanConfig, SecretError> {
|
||||
let mut merged = stored.clone();
|
||||
if let Some(v) = self.enabled_scans {
|
||||
merged.enabled_scans = v;
|
||||
}
|
||||
if let Some(v) = self.disabled_scans {
|
||||
merged.disabled_scans = v;
|
||||
}
|
||||
if let Some(v) = self.environment {
|
||||
merged.environment = v;
|
||||
}
|
||||
if let Some(v) = self.allow_destructive {
|
||||
merged.allow_destructive = v;
|
||||
}
|
||||
if let Some(v) = self.strategy {
|
||||
merged.strategy = Some(v);
|
||||
}
|
||||
if let Some(mut tracker) = self.issue_tracker {
|
||||
let kept = stored.issue_tracker.as_ref().and_then(|t| t.token.as_ref());
|
||||
secrets.take_update(&mut tracker.token, kept)?;
|
||||
merged.issue_tracker = Some(tracker);
|
||||
}
|
||||
if let Some(mut pentest) = self.pentest {
|
||||
let kept = stored.pentest.as_ref().map(|p| &p.auth);
|
||||
secrets.take_update(
|
||||
&mut pentest.auth.password,
|
||||
kept.and_then(|a| a.password.as_ref()),
|
||||
)?;
|
||||
secrets.take_update(
|
||||
&mut pentest.auth.imap_password,
|
||||
kept.and_then(|a| a.imap_password.as_ref()),
|
||||
)?;
|
||||
merged.pentest = Some(pentest);
|
||||
}
|
||||
Ok(merged)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn secrets() -> SecretBox {
|
||||
SecretBox::from_key(&[7u8; 32]).expect("32-byte key")
|
||||
}
|
||||
|
||||
fn input(kind: ArtifactKind, source_ref: &str) -> ArtifactInput {
|
||||
ArtifactInput {
|
||||
kind,
|
||||
source_ref: source_ref.to_string(),
|
||||
branch: None,
|
||||
plc_format: None,
|
||||
token: None,
|
||||
username: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn git_input(token: Option<&str>) -> ArtifactInput {
|
||||
ArtifactInput {
|
||||
branch: Some("main".to_string()),
|
||||
token: token.map(String::from),
|
||||
..input(ArtifactKind::GitRepo, "https://git.example.com/acme/fw.git")
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_git_token_is_stored_sealed() {
|
||||
let s = secrets();
|
||||
let artifact = git_input(Some("pat-123")).build(&s, None).unwrap();
|
||||
let auth = artifact.auth.expect("auth");
|
||||
assert_eq!(auth.method, TOKEN_METHOD);
|
||||
let sealed = auth.secret.expect("secret");
|
||||
assert!(SecretBox::is_sealed(&sealed));
|
||||
assert_eq!(s.open(&sealed).unwrap(), "pat-123");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_without_the_token_keeps_it_and_the_upload() {
|
||||
let s = secrets();
|
||||
let mut stored = git_input(Some("pat-123")).build(&s, None).unwrap();
|
||||
stored.content_hash = Some("abc".into());
|
||||
let upload = Artifact {
|
||||
stored_path: Some("/data/uploads/fw.tar.gz".into()),
|
||||
..crate::targets::reference_artifact(
|
||||
ArtifactKind::SourceArchive,
|
||||
"fw.tar.gz".into(),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
};
|
||||
let stored_all = vec![stored.clone(), upload.clone()];
|
||||
|
||||
// What the dashboard's editor sends: no token, no stored path.
|
||||
let inputs = vec![
|
||||
git_input(None),
|
||||
input(ArtifactKind::SourceArchive, "fw.tar.gz"),
|
||||
];
|
||||
let merged = merge_artifacts(&s, &inputs, &stored_all).unwrap();
|
||||
|
||||
assert_eq!(merged[0].id, stored.id);
|
||||
assert_eq!(
|
||||
merged[0].auth.as_ref().unwrap().secret,
|
||||
stored.auth.unwrap().secret
|
||||
);
|
||||
assert_eq!(merged[0].content_hash.as_deref(), Some("abc"));
|
||||
assert_eq!(merged[1].id, upload.id);
|
||||
assert_eq!(merged[1].stored_path, upload.stored_path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_token_can_be_replaced_or_cleared() {
|
||||
let s = secrets();
|
||||
let stored = git_input(Some("old")).build(&s, None).unwrap();
|
||||
|
||||
let replaced = git_input(Some("new")).build(&s, Some(&stored)).unwrap();
|
||||
let secret = replaced.auth.unwrap().secret.unwrap();
|
||||
assert_eq!(s.open(&secret).unwrap(), "new");
|
||||
|
||||
let cleared = git_input(Some("")).build(&s, Some(&stored)).unwrap();
|
||||
assert!(cleared.auth.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enabling_a_scan_keeps_the_tracker_and_its_token() {
|
||||
let s = secrets();
|
||||
let stored = TargetScanConfig {
|
||||
issue_tracker: Some(IssueTrackerConfig {
|
||||
token: Some(s.seal("tracker-pat").unwrap()),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let update = ScanConfigUpdate {
|
||||
enabled_scans: Some(vec![ScanType::IcsProbe]),
|
||||
..Default::default()
|
||||
};
|
||||
let merged = update.apply(&s, &stored).unwrap();
|
||||
assert_eq!(merged.enabled_scans, vec![ScanType::IcsProbe]);
|
||||
assert_eq!(
|
||||
merged.issue_tracker.unwrap().token,
|
||||
stored.issue_tracker.unwrap().token
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,21 @@
|
||||
//! Werkbank runner endpoints (`/api/v1/werkbank/jobs/*`).
|
||||
//!
|
||||
//! The pull API a Werkbank runner talks to: lease a job, heartbeat while it runs,
|
||||
//! and post the result back. Machine auth is a **static bearer token**
|
||||
//! (`WERKBANK_RUNNER_TOKEN`) — not a Keycloak JWT, because a runner acts across
|
||||
//! tenants (each request names its `tenant`). Routes are only mounted when the
|
||||
//! token is configured; with none set they don't exist (404).
|
||||
//! and post the result back. Machine auth is a portal-issued API key bound to
|
||||
//! one tenant (scope `werkbank:runner`) — not a Keycloak JWT, because a runner
|
||||
//! is a machine.
|
||||
//!
|
||||
//! A deployment-wide static bearer (`WERKBANK_RUNNER_TOKEN`) is still accepted
|
||||
//! on a **dev** deployment, where it is the only option before the platform is
|
||||
//! wired up. It names no tenant, so it can act for any of them; a hardened
|
||||
//! deployment ([`compliance_core::config::AppEnv::is_hardened`]) refuses it.
|
||||
//! Routes are only mounted when one of the two is configured.
|
||||
//!
|
||||
//! On completion the runner's findings are persisted against the job's target,
|
||||
//! so a job run by a remote runner lands the same findings an in-process run
|
||||
//! would (WB-05, the control-plane cut-over).
|
||||
|
||||
use axum::extract::{Extension, Path, Request};
|
||||
use axum::extract::{Extension, Path, Query, Request};
|
||||
use axum::http::{header, StatusCode};
|
||||
use axum::middleware::Next;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
@@ -35,9 +40,6 @@ pub async fn require_runner_token(
|
||||
request: Request,
|
||||
next: Next,
|
||||
) -> Response {
|
||||
let Some(expected) = agent.config.werkbank_runner_token.as_ref() else {
|
||||
return (StatusCode::NOT_FOUND, "werkbank runner API disabled").into_response();
|
||||
};
|
||||
let presented = request
|
||||
.headers()
|
||||
.get(header::AUTHORIZATION)
|
||||
@@ -48,18 +50,95 @@ pub async fn require_runner_token(
|
||||
let Some(presented) = presented else {
|
||||
return (StatusCode::UNAUTHORIZED, "Missing bearer token").into_response();
|
||||
};
|
||||
// Portal-issued API key (tenant-registry, scope werkbank:runner) — the
|
||||
// platform way (contract 2.0 §5.B / add-on runners).
|
||||
if presented.starts_with("bp_") {
|
||||
let Some(registry) = agent.registry.as_ref() else {
|
||||
return (StatusCode::UNAUTHORIZED, "API keys need a tenant registry").into_response();
|
||||
};
|
||||
return match registry.verify_api_key(presented).await {
|
||||
Ok(v) if runner_key_accepted(v.valid, &v.scopes) => {
|
||||
// The key is tenant-scoped: every request must name that tenant.
|
||||
let mut request = request;
|
||||
request.extensions_mut().insert(RunnerTenant(v.tenant_id));
|
||||
next.run(request).await
|
||||
}
|
||||
Ok(_) => (StatusCode::UNAUTHORIZED, "Invalid or unscoped API key").into_response(),
|
||||
Err(e) => {
|
||||
tracing::error!("runner api-key verify unavailable: {e}");
|
||||
(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"API key verification unavailable",
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
};
|
||||
}
|
||||
// Static runner token (pre-platform deployments). It is bound to no tenant,
|
||||
// so a holder can act for every tenant at once — acceptable on a laptop,
|
||||
// never where real tenants live.
|
||||
if agent.config.app_env.is_hardened() {
|
||||
tracing::warn!(
|
||||
app_env = agent.config.app_env.as_str(),
|
||||
"static WERKBANK_RUNNER_TOKEN presented on a hardened deployment — refused"
|
||||
);
|
||||
return (
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"The static runner token is not accepted in this deployment; \
|
||||
use a portal-issued API key with the werkbank:runner scope",
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
let Some(expected) = agent.config.werkbank_runner_token.as_ref() else {
|
||||
return (StatusCode::UNAUTHORIZED, "Invalid runner token").into_response();
|
||||
};
|
||||
if !constant_time_eq(presented, expected.expose_secret()) {
|
||||
return (StatusCode::UNAUTHORIZED, "Invalid runner token").into_response();
|
||||
}
|
||||
next.run(request).await
|
||||
}
|
||||
|
||||
/// The scope a portal-issued API key must carry to drive the runner endpoints.
|
||||
const RUNNER_SCOPE: &str = "werkbank:runner";
|
||||
|
||||
/// Whether a verified API key may drive the runner endpoints.
|
||||
///
|
||||
/// The scope is **required**. This used to also accept any key whose `product`
|
||||
/// was this product, which made every `pruefwerk` API key — a dashboard key, a
|
||||
/// reporting key — a runner key that could lease and complete other tenants'
|
||||
/// jobs. Product membership says who issued the key, not what it may do.
|
||||
fn runner_key_accepted(valid: bool, scopes: &[String]) -> bool {
|
||||
valid && scopes.iter().any(|s| s == RUNNER_SCOPE)
|
||||
}
|
||||
|
||||
/// Tenant a registry API key is bound to (set by [`require_runner_token`]).
|
||||
/// Absent for the static runner token (pre-platform deployments).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RunnerTenant(pub String);
|
||||
|
||||
/// Reject a request that names a tenant other than the one its API key is
|
||||
/// bound to (PRODUCT_INTEGRATION_SPEC 2.0 §8.7 isolation).
|
||||
fn ensure_tenant(
|
||||
bound: &Option<Extension<RunnerTenant>>,
|
||||
requested: &str,
|
||||
) -> Result<(), StatusCode> {
|
||||
match bound {
|
||||
Some(Extension(RunnerTenant(t))) if t != requested => {
|
||||
tracing::warn!(bound = %t, requested, "runner key used for another tenant");
|
||||
Err(StatusCode::FORBIDDEN)
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `POST /api/v1/werkbank/jobs/lease` — lease the oldest runnable job, or `204`.
|
||||
#[tracing::instrument(skip_all, fields(tenant = %req.tenant, runner = %req.runner_id))]
|
||||
pub async fn lease(
|
||||
Extension(agent): AgentExt,
|
||||
bound: Option<Extension<RunnerTenant>>,
|
||||
Json(req): Json<LeaseRequest>,
|
||||
) -> Result<Response, StatusCode> {
|
||||
ensure_tenant(&bound, &req.tenant)?;
|
||||
let queue = JobQueue::new(&tenant_db(&agent, &req.tenant).await?);
|
||||
let leased = queue
|
||||
.lease(
|
||||
@@ -81,8 +160,10 @@ pub async fn lease(
|
||||
#[tracing::instrument(skip_all, fields(tenant = %req.tenant, job = %req.job_id))]
|
||||
pub async fn heartbeat(
|
||||
Extension(agent): AgentExt,
|
||||
bound: Option<Extension<RunnerTenant>>,
|
||||
Json(req): Json<HeartbeatRequest>,
|
||||
) -> Result<Response, StatusCode> {
|
||||
ensure_tenant(&bound, &req.tenant)?;
|
||||
let queue = JobQueue::new(&tenant_db(&agent, &req.tenant).await?);
|
||||
let ack = queue
|
||||
.heartbeat(
|
||||
@@ -104,8 +185,10 @@ pub async fn heartbeat(
|
||||
#[tracing::instrument(skip_all, fields(tenant = %req.tenant, job = %req.job_id))]
|
||||
pub async fn complete(
|
||||
Extension(agent): AgentExt,
|
||||
bound: Option<Extension<RunnerTenant>>,
|
||||
Json(req): Json<CompleteRequest>,
|
||||
) -> Result<Json<CompleteResponse>, StatusCode> {
|
||||
ensure_tenant(&bound, &req.tenant)?;
|
||||
let db = tenant_db(&agent, &req.tenant).await?;
|
||||
let queue = JobQueue::new(&db);
|
||||
let now = chrono::Utc::now();
|
||||
@@ -124,17 +207,47 @@ pub async fn complete(
|
||||
Ok(Json(CompleteResponse { recorded }))
|
||||
}
|
||||
|
||||
/// `GET /api/v1/werkbank/artifacts/{hash}` — serve a content-addressed blob (the
|
||||
/// program a runner needs to load). The hash is validated against traversal by
|
||||
/// [`crate::ingest::blob::read_blob`]; a runner fetches this for a job's `blob`
|
||||
/// input.
|
||||
/// Which tenant's artifact store a fetch reads from.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ArtifactQuery {
|
||||
/// Required with the static runner token, which names no tenant of its own.
|
||||
/// With a tenant-bound API key it is optional, and must match the key.
|
||||
pub tenant: Option<String>,
|
||||
}
|
||||
|
||||
/// `GET /api/v1/werkbank/artifacts/{hash}?tenant=…` — serve a content-addressed
|
||||
/// blob (the program a runner needs to load) **from the caller's own tenant
|
||||
/// store**.
|
||||
///
|
||||
/// Blobs are addressed by hash, and the hash is in the job record, so a store
|
||||
/// shared across tenants let any valid runner key fetch any tenant's program
|
||||
/// source. The read is now bound to the tenant the key is bound to
|
||||
/// ([`RunnerTenant`]); another tenant's blob is simply absent from that subtree
|
||||
/// and the request 404s. The hash itself is still validated against traversal by
|
||||
/// [`crate::ingest::blob::read_tenant_blob`].
|
||||
#[tracing::instrument(skip_all, fields(hash = %hash))]
|
||||
pub async fn serve_artifact(
|
||||
Extension(agent): AgentExt,
|
||||
bound: Option<Extension<RunnerTenant>>,
|
||||
Path(hash): Path<String>,
|
||||
Query(q): Query<ArtifactQuery>,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let tenant = match (&bound, q.tenant.as_deref()) {
|
||||
// A named tenant must be the one the key is bound to.
|
||||
(_, Some(requested)) => {
|
||||
ensure_tenant(&bound, requested)?;
|
||||
requested.to_string()
|
||||
}
|
||||
(Some(Extension(RunnerTenant(t))), None) => t.clone(),
|
||||
// Static runner token and no `?tenant=`: there is nothing to scope the
|
||||
// read to, and an unscoped read is the bug being fixed.
|
||||
(None, None) => {
|
||||
tracing::warn!("artifact fetch without a tenant");
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
};
|
||||
let base = std::path::Path::new(&agent.config.artifact_store_base_path);
|
||||
match crate::ingest::blob::read_blob(base, &hash) {
|
||||
match crate::ingest::blob::read_tenant_blob(base, &tenant, &hash) {
|
||||
Ok(bytes) => {
|
||||
Ok(([(header::CONTENT_TYPE, "application/octet-stream")], bytes).into_response())
|
||||
}
|
||||
@@ -166,8 +279,10 @@ pub struct EnqueueResponse {
|
||||
#[tracing::instrument(skip_all, fields(tenant = %req.tenant, target = %req.target_id))]
|
||||
pub async fn enqueue(
|
||||
Extension(agent): AgentExt,
|
||||
bound: Option<Extension<RunnerTenant>>,
|
||||
Json(req): Json<EnqueueRequest>,
|
||||
) -> Result<Json<EnqueueResponse>, StatusCode> {
|
||||
ensure_tenant(&bound, &req.tenant)?;
|
||||
let db = tenant_db(&agent, &req.tenant).await?;
|
||||
let oid = ObjectId::parse_str(&req.target_id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let target = db
|
||||
@@ -179,8 +294,9 @@ pub async fn enqueue(
|
||||
|
||||
// Extract the control-logic program from the target's PLC-source artifacts
|
||||
// (same selection as the in-process PLC scan).
|
||||
let ctx = crate::ingest::IngestContext::from_config(&agent.config, &req.target_id);
|
||||
let ingest_set = crate::ingest::ingest_all(&target, &ctx).map_err(internal)?;
|
||||
let ctx = crate::ingest::IngestContext::from_config(&agent.config, &req.tenant, &req.target_id);
|
||||
// An artifact that cannot be read simply offers no program below.
|
||||
let ingest_set = crate::ingest::ingest_all(&target, &ctx);
|
||||
let program = target
|
||||
.artifacts
|
||||
.iter()
|
||||
@@ -198,10 +314,12 @@ pub async fn enqueue(
|
||||
})
|
||||
.ok_or(StatusCode::UNPROCESSABLE_ENTITY)?;
|
||||
|
||||
// Stash the program source so the runner can fetch it by hash.
|
||||
// Stash the program source in this tenant's store so its runner — and only
|
||||
// its runner — can fetch it by hash.
|
||||
let base = std::path::Path::new(&agent.config.artifact_store_base_path);
|
||||
let hash =
|
||||
crate::ingest::blob::store_bytes(base, program.source.as_bytes()).map_err(internal)?;
|
||||
crate::ingest::blob::store_tenant_bytes(base, &req.tenant, program.source.as_bytes())
|
||||
.map_err(internal)?;
|
||||
|
||||
let job_id = format!("job_{}", uuid::Uuid::new_v4().simple());
|
||||
let job = Job::plc_provision(
|
||||
@@ -277,7 +395,11 @@ fn constant_time_eq(a: &str, b: &str) -> bool {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::constant_time_eq;
|
||||
use super::{constant_time_eq, runner_key_accepted, RUNNER_SCOPE};
|
||||
|
||||
fn scopes(list: &[&str]) -> Vec<String> {
|
||||
list.iter().map(|s| s.to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn token_compare() {
|
||||
@@ -286,4 +408,31 @@ mod tests {
|
||||
assert!(!constant_time_eq("secret", "secretx"));
|
||||
assert!(!constant_time_eq("", "x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_with_the_runner_scope_is_accepted() {
|
||||
assert!(runner_key_accepted(true, &scopes([RUNNER_SCOPE].as_ref())));
|
||||
assert!(runner_key_accepted(
|
||||
true,
|
||||
&scopes(&["scan:read", RUNNER_SCOPE])
|
||||
));
|
||||
}
|
||||
|
||||
/// The regression this guards: a key issued for this product but with no
|
||||
/// runner scope (a dashboard or reporting key) used to pass, because the
|
||||
/// check accepted `scope OR product == pruefwerk`.
|
||||
#[test]
|
||||
fn a_pruefwerk_key_without_the_runner_scope_is_rejected() {
|
||||
assert!(!runner_key_accepted(true, &scopes(&["scan:read"])));
|
||||
assert!(!runner_key_accepted(true, &scopes(&["werkbank:admin"])));
|
||||
assert!(!runner_key_accepted(true, &[]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invalid_key_is_rejected_even_with_the_scope() {
|
||||
assert!(!runner_key_accepted(
|
||||
false,
|
||||
&scopes([RUNNER_SCOPE].as_ref())
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,41 @@
|
||||
use axum::routing::{delete, get, patch, post};
|
||||
use axum::extract::DefaultBodyLimit;
|
||||
use axum::routing::{delete, get, patch, post, put};
|
||||
use axum::Router;
|
||||
|
||||
use crate::api::handlers;
|
||||
|
||||
/// Allowance on top of the file itself for the multipart framing: boundaries,
|
||||
/// part headers and the small `kind` / `plc_format` text fields.
|
||||
const MULTIPART_OVERHEAD: usize = 1024 * 1024;
|
||||
|
||||
pub fn build_router() -> Router {
|
||||
Router::new()
|
||||
.route("/api/v1/health", get(handlers::health))
|
||||
.route("/api/v1/oscal/assess", post(handlers::oscal::assess_target))
|
||||
.route("/api/v1/stats/overview", get(handlers::stats_overview))
|
||||
// The tenant's projects (owned by the registry), for assigning targets.
|
||||
.route("/api/v1/projects", get(handlers::projects::list_projects))
|
||||
// BreakPilot support access: choose and open a customer's tenant.
|
||||
.route(
|
||||
"/api/v1/settings/ssh-public-key",
|
||||
get(handlers::get_ssh_public_key),
|
||||
"/api/v1/support/tenants",
|
||||
get(handlers::support::list_tenants),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/support/session",
|
||||
post(handlers::support::open_session),
|
||||
)
|
||||
// Unified onboarding targets (#131).
|
||||
.route(
|
||||
"/api/v1/targets",
|
||||
get(handlers::onboarding::list_targets).post(handlers::onboarding::create_target),
|
||||
)
|
||||
// Curated demo targets (D3). Registered before "/targets/{id}" for
|
||||
// readability; the router matches the literal segment first either way.
|
||||
.route(
|
||||
"/api/v1/targets/demo-seed",
|
||||
get(handlers::demo_seed::list_demo_targets)
|
||||
.post(handlers::demo_seed::seed_demo_targets),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}",
|
||||
get(handlers::onboarding::get_target)
|
||||
@@ -29,7 +48,16 @@ pub fn build_router() -> Router {
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/artifacts/upload",
|
||||
post(handlers::onboarding::upload_artifact),
|
||||
// The one route that takes large bodies — and it streams them to
|
||||
// disk. Every other route keeps axum's 2 MiB default, so a JSON
|
||||
// endpoint can no longer be sent a 512 MiB body to buffer.
|
||||
post(handlers::onboarding::upload_artifact).layer(DefaultBodyLimit::max(
|
||||
crate::targets::MAX_UPLOAD_BYTES as usize + MULTIPART_OVERHEAD,
|
||||
)),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/artifacts/{artifact_id}/archive-password",
|
||||
put(handlers::onboarding::set_archive_password),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/applicable-scans",
|
||||
@@ -57,6 +85,33 @@ pub fn build_router() -> Router {
|
||||
"/api/v1/findings/{id}/feedback",
|
||||
patch(handlers::update_finding_feedback),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/evidence-pack",
|
||||
get(handlers::evidence::evidence_pack),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/compliance",
|
||||
get(handlers::evidence::compliance_view),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/compliance/summary",
|
||||
get(handlers::evidence::compliance_summary),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/controls",
|
||||
get(handlers::evidence::describe_controls),
|
||||
)
|
||||
// Findings from a manual DAST run or penetration test.
|
||||
.route(
|
||||
"/api/v1/targets/{id}/findings",
|
||||
post(handlers::manual_findings::create_finding),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/findings/import",
|
||||
post(handlers::manual_findings::import_findings).layer(DefaultBodyLimit::max(
|
||||
handlers::manual_findings::MAX_IMPORT_BYTES,
|
||||
)),
|
||||
)
|
||||
.route("/api/v1/sbom", get(handlers::list_sbom))
|
||||
.route("/api/v1/sbom/filters", get(handlers::sbom_filters))
|
||||
.route("/api/v1/sbom/export", get(handlers::export_sbom))
|
||||
|
||||
@@ -1,21 +1,23 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::{DefaultBodyLimit, Request};
|
||||
use axum::http::HeaderValue;
|
||||
use axum::extract::{DefaultBodyLimit, Request, State};
|
||||
use axum::http::{HeaderValue, Method, StatusCode};
|
||||
use axum::middleware::Next;
|
||||
use axum::response::Response;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{delete, get, post};
|
||||
use axum::{middleware, Extension, Router};
|
||||
use tokio::sync::RwLock;
|
||||
use tower_http::cors::CorsLayer;
|
||||
use axum::{middleware, Extension, Json, Router};
|
||||
use tower_http::cors::{Any, CorsLayer};
|
||||
use tower_http::set_header::SetResponseHeaderLayer;
|
||||
use tower_http::trace::TraceLayer;
|
||||
|
||||
use compliance_core::auth::{require_jwt_auth, require_tenant_status, JwksState};
|
||||
use compliance_core::{TenantContext, TenantStatus};
|
||||
use compliance_core::config::AppEnv;
|
||||
use compliance_core::shutdown::{self, Shutdown};
|
||||
use compliance_core::{OrgRole, TenantContext, TenantStatus};
|
||||
|
||||
use crate::agent::ComplianceAgent;
|
||||
use crate::api::handlers;
|
||||
use crate::api::handlers::platform::{self, PlatformState};
|
||||
use crate::api::routes;
|
||||
use crate::error::AgentError;
|
||||
|
||||
@@ -25,6 +27,10 @@ use crate::error::AgentError;
|
||||
/// just to poke at the API. Override via `DEV_TENANT_ID`.
|
||||
const DEFAULT_DEV_TENANT_ID: &str = "dev";
|
||||
|
||||
/// Largest job result a Werkbank runner may post. Every other JSON route keeps
|
||||
/// axum's 2 MiB default; only uploads (streamed) and this one go higher.
|
||||
const RUNNER_RESULT_MAX_BYTES: usize = 32 * 1024 * 1024;
|
||||
|
||||
/// Inject a synthetic [`TenantContext`] for any request that lacks one.
|
||||
/// Only mounted when Keycloak is NOT configured; with KC, the real
|
||||
/// `require_jwt_auth` middleware owns this and we never reach here
|
||||
@@ -39,19 +45,282 @@ pub async fn inject_dev_tenant(mut request: Request, next: Next) -> Response {
|
||||
let ctx = TenantContext {
|
||||
tenant_slug: tenant_id.clone(),
|
||||
tenant_id,
|
||||
org_roles: vec![],
|
||||
// The single local user administers the dev organisation.
|
||||
org_roles: vec![OrgRole::ItAdmin],
|
||||
products: vec![],
|
||||
plan: "dev".to_string(),
|
||||
status: TenantStatus::Active,
|
||||
user_id: "dev-user".to_string(),
|
||||
user_name: None,
|
||||
staff: None,
|
||||
};
|
||||
request.extensions_mut().insert(ctx);
|
||||
}
|
||||
next.run(request).await
|
||||
}
|
||||
|
||||
pub async fn start_api_server(agent: ComplianceAgent, port: u16) -> Result<(), AgentError> {
|
||||
/// Registry-backed entitlement gate (contract 2.0 §4.4). Runs after the JWT
|
||||
/// middleware; with no registry configured (dev) it is a no-op. The
|
||||
/// registry's answer is authoritative for the ladder status too, so a
|
||||
/// stale `tenant_status` claim never widens access.
|
||||
pub async fn require_entitlement(
|
||||
State(agent): State<Arc<ComplianceAgent>>,
|
||||
mut request: Request,
|
||||
next: Next,
|
||||
) -> Response {
|
||||
// Support access names its tenant in a header: only the registry can
|
||||
// confirm it exists, so without one there is no support access at all.
|
||||
if let Some(ctx) = request
|
||||
.extensions()
|
||||
.get::<TenantContext>()
|
||||
.filter(|c| c.staff.is_some())
|
||||
.cloned()
|
||||
{
|
||||
let Some(registry) = agent.registry.as_ref() else {
|
||||
tracing::error!("support access needs the tenant registry — denying");
|
||||
return entitlement_unavailable();
|
||||
};
|
||||
return match registry.get_tenant(&ctx.tenant_id).await {
|
||||
Ok(Some(tenant)) => {
|
||||
request
|
||||
.extensions_mut()
|
||||
.insert(confirmed_support_context(ctx, &tenant));
|
||||
next.run(request).await
|
||||
}
|
||||
Ok(None) => (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(serde_json::json!({ "error": "unknown_tenant" })),
|
||||
)
|
||||
.into_response(),
|
||||
Err(e) => {
|
||||
tracing::error!(tenant_id = %ctx.tenant_id, "support tenant lookup failed: {e}");
|
||||
entitlement_unavailable()
|
||||
}
|
||||
};
|
||||
}
|
||||
let Some(registry) = agent.registry.as_ref() else {
|
||||
if agent.config.app_env.is_hardened() {
|
||||
// Unreachable after `validate_deployment`, but never widen access
|
||||
// just because a registry client failed to build.
|
||||
tracing::error!("no tenant registry configured in a hardened deployment — denying");
|
||||
return (
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
Json(serde_json::json!({ "error": "entitlement_unavailable" })),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
return next.run(request).await;
|
||||
};
|
||||
let Some(ctx) = request.extensions().get::<TenantContext>().cloned() else {
|
||||
return next.run(request).await;
|
||||
};
|
||||
match registry.check_entitlement(&ctx.tenant_id, None).await {
|
||||
Ok(check) if check.allowed => {
|
||||
let mut ctx = ctx;
|
||||
if let Some(st) = check.status.as_deref().and_then(TenantStatus::parse) {
|
||||
ctx.status = st;
|
||||
}
|
||||
if check.read_only && !ctx.status.blocks_writes() && !ctx.status.is_halted() {
|
||||
ctx.status = TenantStatus::Restricted;
|
||||
}
|
||||
request.extensions_mut().insert(ctx);
|
||||
next.run(request).await
|
||||
}
|
||||
Ok(check) => (
|
||||
StatusCode::FORBIDDEN,
|
||||
Json(serde_json::json!({
|
||||
"error": "not_entitled",
|
||||
"product": registry.product(),
|
||||
"reason": check.reason,
|
||||
"status": check.status,
|
||||
})),
|
||||
)
|
||||
.into_response(),
|
||||
Err(e) => {
|
||||
tracing::error!(tenant_id = %ctx.tenant_id, "entitlement check unavailable: {e}");
|
||||
(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
Json(serde_json::json!({ "error": "entitlement_unavailable" })),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 503 when the registry cannot answer: access is never widened on doubt.
|
||||
fn entitlement_unavailable() -> Response {
|
||||
(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
Json(serde_json::json!({ "error": "entitlement_unavailable" })),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
/// A support context once the registry has confirmed its tenant: the real
|
||||
/// slug and ladder status replace the read-only placeholder. Support is not
|
||||
/// held to the customer's plan limits, but the ladder still applies (a
|
||||
/// halted or archived tenant stays closed).
|
||||
fn confirmed_support_context(
|
||||
mut ctx: TenantContext,
|
||||
tenant: &crate::registry::RegistryTenant,
|
||||
) -> TenantContext {
|
||||
ctx.tenant_slug = tenant.slug.clone();
|
||||
// An unknown status stays read-only.
|
||||
ctx.status = TenantStatus::parse(&tenant.status).unwrap_or(TenantStatus::Restricted);
|
||||
ctx
|
||||
}
|
||||
|
||||
/// Record every change BreakPilot support makes in a tenant, refused ones
|
||||
/// included, in the platform's audit log. Reads are not logged one by one;
|
||||
/// opening a tenant is (`POST /api/v1/support/session`). Background and
|
||||
/// best-effort: an unreachable registry never blocks support.
|
||||
pub async fn audit_support_writes(
|
||||
State(agent): State<Arc<ComplianceAgent>>,
|
||||
request: Request,
|
||||
next: Next,
|
||||
) -> Response {
|
||||
let staff_ctx = request
|
||||
.extensions()
|
||||
.get::<TenantContext>()
|
||||
.filter(|c| c.staff.is_some())
|
||||
.cloned();
|
||||
let method = request.method().clone();
|
||||
let path = request.uri().path().to_string();
|
||||
let response = next.run(request).await;
|
||||
let (Some(ctx), Some(registry)) = (staff_ctx, agent.registry.clone()) else {
|
||||
return response;
|
||||
};
|
||||
if matches!(method, Method::GET | Method::HEAD | Method::OPTIONS) {
|
||||
return response;
|
||||
}
|
||||
let entry = support_audit_entry(&ctx, method.as_str(), &path, response.status().as_u16());
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = registry.append_audit(&entry).await {
|
||||
tracing::warn!(tenant_id = %entry.tenant_id, "support audit not recorded: {e}");
|
||||
}
|
||||
});
|
||||
response
|
||||
}
|
||||
|
||||
/// The audit entry for a support request. The path names the resource; the
|
||||
/// query and body are left out, as they may carry customer data.
|
||||
fn support_audit_entry(
|
||||
ctx: &TenantContext,
|
||||
method: &str,
|
||||
path: &str,
|
||||
status: u16,
|
||||
) -> crate::registry::AuditEntry {
|
||||
crate::registry::AuditEntry::by(
|
||||
ctx,
|
||||
"pruefwerk.support_access",
|
||||
serde_json::json!({ "method": method, "path": path, "status": status }),
|
||||
)
|
||||
}
|
||||
|
||||
fn cors_layer(origins: &[String], app_env: AppEnv) -> CorsLayer {
|
||||
if origins.is_empty() {
|
||||
if app_env.is_hardened() {
|
||||
// Unreachable after `validate_deployment`; deny rather than fall
|
||||
// back to permissive if it ever is reached.
|
||||
tracing::error!("CORS_ALLOWED_ORIGINS empty in a hardened deployment — denying all");
|
||||
return CorsLayer::new();
|
||||
}
|
||||
tracing::warn!("CORS_ALLOWED_ORIGINS not set — CORS is permissive (dev only)");
|
||||
return CorsLayer::permissive();
|
||||
}
|
||||
let parsed: Vec<HeaderValue> = origins
|
||||
.iter()
|
||||
.filter_map(|o| HeaderValue::from_str(o).ok())
|
||||
.collect();
|
||||
CorsLayer::new()
|
||||
.allow_origin(parsed)
|
||||
.allow_methods(Any)
|
||||
.allow_headers(Any)
|
||||
}
|
||||
|
||||
/// Serve the REST API on `port` until `shutdown` fires, then drain in-flight
|
||||
/// requests for at most [`shutdown::GRACE_PERIOD`].
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if Keycloak is missing in a hardened environment, the port
|
||||
/// cannot be bound, or serving fails.
|
||||
pub async fn start_api_server(
|
||||
agent: ComplianceAgent,
|
||||
port: u16,
|
||||
shutdown: Shutdown,
|
||||
) -> Result<(), AgentError> {
|
||||
let shared = Arc::new(agent.clone());
|
||||
let jwks_state = match (&agent.config.keycloak_url, &agent.config.keycloak_realm) {
|
||||
(Some(kc_url), Some(kc_realm)) => {
|
||||
let issuer = format!("{}/realms/{kc_realm}", kc_url.trim_end_matches('/'));
|
||||
if agent.config.keycloak_audience.is_none() {
|
||||
tracing::warn!(
|
||||
"KEYCLOAK_AUDIENCE empty — JWT audience is not validated (dev only)"
|
||||
);
|
||||
}
|
||||
Some(JwksState::new(
|
||||
format!("{issuer}/protocol/openid-connect/certs"),
|
||||
Some(issuer),
|
||||
agent.config.keycloak_audience.clone(),
|
||||
))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
// Platform lifecycle + usage endpoints (contract 2.0 §4.1), service-token
|
||||
// gated. Always mounted; without Keycloak they are open (dev, logged).
|
||||
let platform_state = PlatformState {
|
||||
agent: shared.clone(),
|
||||
jwks: jwks_state.clone(),
|
||||
};
|
||||
let platform_router: Router = Router::new()
|
||||
.route("/api/v1/platform/usage", get(platform::usage))
|
||||
.route(
|
||||
"/api/v1/platform/tenants/demo/reset",
|
||||
post(platform::demo_reset),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/platform/tenants/{id}/provision",
|
||||
post(platform::provision),
|
||||
)
|
||||
// The portal's view of a tenant's targets (per project), through the
|
||||
// registry. Read-only.
|
||||
.route(
|
||||
"/api/v1/platform/tenants/{id}/targets",
|
||||
get(platform::list_targets),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/platform/tenants/{id}/suspend",
|
||||
post(platform::suspend),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/platform/tenants/{id}/reactivate",
|
||||
post(platform::reactivate),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/platform/tenants/{id}/terminate",
|
||||
post(platform::terminate),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/platform/tenants/{id}/export",
|
||||
get(platform::export),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/platform/tenants/{id}/data",
|
||||
delete(platform::delete_data),
|
||||
)
|
||||
.layer(middleware::from_fn_with_state(
|
||||
platform_state.clone(),
|
||||
platform::require_platform_token,
|
||||
))
|
||||
.with_state(platform_state.clone())
|
||||
// The contract handshake is public (§4.1 /version): no token needed.
|
||||
.route(
|
||||
"/api/v1/platform/version",
|
||||
get(platform::version).with_state(platform_state),
|
||||
);
|
||||
|
||||
// Admin sub-router. Routes are only mounted when ADMIN_API_TOKEN is
|
||||
// configured — without it, the paths don't exist at all (404 rather
|
||||
// than 401), so an operator who hasn't opted in can't fingerprint
|
||||
@@ -72,11 +341,13 @@ pub async fn start_api_server(agent: ComplianceAgent, port: u16) -> Result<(), A
|
||||
Router::new()
|
||||
};
|
||||
|
||||
// Werkbank runner API. Like admin, only mounted when its bearer token is
|
||||
// configured; runners authenticate with WERKBANK_RUNNER_TOKEN (not a JWT).
|
||||
let werkbank_router: Router = if agent.config.werkbank_runner_token.is_some() {
|
||||
// Werkbank runner API. Mounted when a static runner token is configured OR
|
||||
// a registry is available (runners then present portal-issued API keys).
|
||||
let werkbank_router: Router = if agent.config.werkbank_runner_token.is_some()
|
||||
|| agent.registry.is_some()
|
||||
{
|
||||
tracing::info!(
|
||||
"Werkbank runner API enabled — /api/v1/werkbank/jobs/* behind WERKBANK_RUNNER_TOKEN"
|
||||
"Werkbank runner API enabled — /api/v1/werkbank/jobs/* (static token and/or registry API keys)"
|
||||
);
|
||||
Router::new()
|
||||
.route(
|
||||
@@ -89,7 +360,10 @@ pub async fn start_api_server(agent: ComplianceAgent, port: u16) -> Result<(), A
|
||||
)
|
||||
.route(
|
||||
"/api/v1/werkbank/jobs/complete",
|
||||
post(handlers::werkbank_jobs::complete),
|
||||
// A job's result carries all its findings as JSON, which can
|
||||
// outgrow the 2 MiB default. The route is behind a runner key.
|
||||
post(handlers::werkbank_jobs::complete)
|
||||
.layer(DefaultBodyLimit::max(RUNNER_RESULT_MAX_BYTES)),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/werkbank/jobs/enqueue",
|
||||
@@ -109,11 +383,12 @@ pub async fn start_api_server(agent: ComplianceAgent, port: u16) -> Result<(), A
|
||||
let mut app = routes::build_router()
|
||||
.merge(admin_router)
|
||||
.merge(werkbank_router)
|
||||
// Allow large artifact uploads (PLC .projectarchive, firmware images,
|
||||
// mobile packages) — axum's default request-body limit is only 2 MiB.
|
||||
.layer(DefaultBodyLimit::max(512 * 1024 * 1024))
|
||||
.layer(Extension(Arc::new(agent.clone())))
|
||||
.layer(CorsLayer::permissive())
|
||||
.merge(platform_router)
|
||||
.layer(Extension(shared.clone()))
|
||||
.layer(cors_layer(
|
||||
&agent.config.cors_allowed_origins,
|
||||
agent.config.app_env,
|
||||
))
|
||||
.layer(TraceLayer::new_for_http())
|
||||
// Security headers (defense-in-depth, primary enforcement via Traefik)
|
||||
.layer(SetResponseHeaderLayer::overriding(
|
||||
@@ -133,22 +408,35 @@ pub async fn start_api_server(agent: ComplianceAgent, port: u16) -> Result<(), A
|
||||
HeaderValue::from_static("strict-origin-when-cross-origin"),
|
||||
));
|
||||
|
||||
if let (Some(kc_url), Some(kc_realm)) =
|
||||
(&agent.config.keycloak_url, &agent.config.keycloak_realm)
|
||||
{
|
||||
let jwks_url = format!("{kc_url}/realms/{kc_realm}/protocol/openid-connect/certs");
|
||||
let jwks_state = JwksState {
|
||||
jwks: Arc::new(RwLock::new(None)),
|
||||
jwks_url,
|
||||
};
|
||||
tracing::info!("Keycloak JWT auth enabled for realm '{kc_realm}'");
|
||||
// Layers execute outermost-first. Extension(jwks_state) must run
|
||||
// before require_jwt_auth so the middleware can read it; the
|
||||
// status gate runs after JWT so TenantContext is in extensions.
|
||||
if let Some(jwks_state) = jwks_state {
|
||||
tracing::info!(
|
||||
issuer = ?jwks_state.issuer, audience = ?jwks_state.audience,
|
||||
registry = agent.registry.is_some(),
|
||||
"Keycloak JWT auth enabled"
|
||||
);
|
||||
// Layers execute outermost-first: Extension(jwks) → JWT → entitlement
|
||||
// (registry) → support audit → status ladder → handlers.
|
||||
app = app
|
||||
.layer(middleware::from_fn(require_tenant_status))
|
||||
.layer(middleware::from_fn_with_state(
|
||||
shared.clone(),
|
||||
audit_support_writes,
|
||||
))
|
||||
.layer(middleware::from_fn_with_state(
|
||||
shared.clone(),
|
||||
require_entitlement,
|
||||
))
|
||||
.layer(middleware::from_fn(require_jwt_auth))
|
||||
.layer(Extension(jwks_state));
|
||||
} else if agent.config.app_env.is_hardened() {
|
||||
// `validate_deployment` rejects this configuration at load time; this
|
||||
// is the second lock on the same door, so no code path can ever mount
|
||||
// the dev-tenant injector outside dev.
|
||||
return Err(AgentError::Config(format!(
|
||||
"APP_ENV={} requires Keycloak (KEYCLOAK_URL + KEYCLOAK_REALM); \
|
||||
refusing to serve unauthenticated",
|
||||
agent.config.app_env.as_str()
|
||||
)));
|
||||
} else {
|
||||
let tenant_id =
|
||||
std::env::var("DEV_TENANT_ID").unwrap_or_else(|_| DEFAULT_DEV_TENANT_ID.to_string());
|
||||
@@ -166,9 +454,72 @@ pub async fn start_api_server(agent: ComplianceAgent, port: u16) -> Result<(), A
|
||||
.map_err(|e| AgentError::Other(format!("Failed to bind to {addr}: {e}")))?;
|
||||
|
||||
tracing::info!("REST API listening on {addr}");
|
||||
axum::serve(listener, app)
|
||||
shutdown::serve(listener, app, shutdown, shutdown::GRACE_PERIOD)
|
||||
.await
|
||||
.map_err(|e| AgentError::Other(format!("API server error: {e}")))?;
|
||||
tracing::info!("REST API stopped");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod support_tests {
|
||||
use super::*;
|
||||
|
||||
fn support_ctx() -> TenantContext {
|
||||
TenantContext {
|
||||
tenant_id: "00000000-0000-0000-0000-000000000002".to_string(),
|
||||
tenant_slug: String::new(),
|
||||
org_roles: vec![OrgRole::ItAdmin],
|
||||
products: Vec::new(),
|
||||
plan: String::new(),
|
||||
status: TenantStatus::Restricted,
|
||||
user_id: "s-1".to_string(),
|
||||
user_name: Some("Sharang".to_string()),
|
||||
staff: Some(compliance_core::StaffAccess {
|
||||
user_id: "s-1".to_string(),
|
||||
user_name: Some("Sharang".to_string()),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn registry_tenant(status: &str) -> crate::registry::RegistryTenant {
|
||||
crate::registry::RegistryTenant {
|
||||
id: "00000000-0000-0000-0000-000000000002".to_string(),
|
||||
slug: "faller".to_string(),
|
||||
name: "Gebr. Faller".to_string(),
|
||||
status: status.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_registry_confirms_slug_and_status() {
|
||||
let ctx = confirmed_support_context(support_ctx(), ®istry_tenant("active"));
|
||||
assert_eq!(ctx.tenant_slug, "faller");
|
||||
assert_eq!(ctx.status, TenantStatus::Active);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_registry_status_stays_read_only() {
|
||||
let ctx = confirmed_support_context(support_ctx(), ®istry_tenant("something-new"));
|
||||
assert_eq!(ctx.status, TenantStatus::Restricted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_support_change_is_audited_without_its_content() {
|
||||
let entry =
|
||||
support_audit_entry(&support_ctx(), "PATCH", "/api/v1/findings/abc/status", 200);
|
||||
assert_eq!(entry.tenant_id, "00000000-0000-0000-0000-000000000002");
|
||||
assert_eq!(entry.action, "pruefwerk.support_access");
|
||||
assert_eq!(entry.actor_id, "s-1");
|
||||
assert_eq!(entry.actor_name, "BreakPilot-Support (Sharang)");
|
||||
assert_eq!(
|
||||
entry.metadata,
|
||||
serde_json::json!({
|
||||
"method": "PATCH",
|
||||
"path": "/api/v1/findings/abc/status",
|
||||
"status": 200
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
//! Firmware classification via tramiton.
|
||||
//! Firmware classification via Firmwerk.
|
||||
//!
|
||||
//! tramiton is the company's firmware build/repro engine; we do not re-implement
|
||||
//! its detection. We depend on `tramiton-core` directly (same-company IP) and run
|
||||
//! Firmwerk is the company's firmware build/repro engine; we do not re-implement
|
||||
//! its detection. We depend on `firmwerk-core` directly (same-company IP) and run
|
||||
//! its provider analysis in-process behind a [`FirmwareDetector`] port, mapping
|
||||
//! tramiton's `BuildPlan` onto a [`TargetType`]. A deterministic
|
||||
//! Firmwerk's `BuildPlan` onto a [`TargetType`]. A deterministic
|
||||
//! [`MockFirmwareDetector`] backs the tests so CI unit tests need neither the
|
||||
//! tramiton sources nor a real firmware tree.
|
||||
//! Firmwerk sources nor a real firmware tree.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
@@ -13,9 +13,9 @@ use compliance_core::error::CoreError;
|
||||
use compliance_core::models::{DetectedFact, TargetType};
|
||||
use compliance_core::traits::ClassifierVerdict;
|
||||
|
||||
/// A minimal firmware-detection summary, mapped from tramiton's `BuildPlan`.
|
||||
/// Kept small and tramiton-independent so the classifier and the test mock don't
|
||||
/// need to construct a full tramiton plan.
|
||||
/// A minimal firmware-detection summary, mapped from Firmwerk's `BuildPlan`.
|
||||
/// Kept small and Firmwerk-independent so the classifier and the test mock don't
|
||||
/// need to construct a full Firmwerk plan.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct FirmwareDetection {
|
||||
/// The detecting provider (e.g. `zephyr`, `cmake`, `source-archaeology`).
|
||||
@@ -43,35 +43,35 @@ pub struct FirmwareTarget {
|
||||
pub arch: Option<String>,
|
||||
}
|
||||
|
||||
/// A source of tramiton firmware detection.
|
||||
/// A source of Firmwerk firmware detection.
|
||||
#[allow(async_fn_in_trait)]
|
||||
pub trait FirmwareDetector: Send + Sync {
|
||||
/// Run detection over a path, returning a firmware detection if tramiton
|
||||
/// Run detection over a path, returning a firmware detection if Firmwerk
|
||||
/// could form a build plan.
|
||||
async fn detect(&self, path: &Path) -> Result<Option<FirmwareDetection>, CoreError>;
|
||||
}
|
||||
|
||||
/// Uses `tramiton-core` in-process. The analysis is blocking (filesystem walk),
|
||||
/// Uses `firmwerk-core` in-process. The analysis is blocking (filesystem walk),
|
||||
/// so it runs on a blocking thread to avoid stalling the async runtime. A path
|
||||
/// with no recognizable build system yields `Ok(None)`.
|
||||
pub struct TramitonNative;
|
||||
pub struct FirmwerkNative;
|
||||
|
||||
impl FirmwareDetector for TramitonNative {
|
||||
impl FirmwareDetector for FirmwerkNative {
|
||||
async fn detect(&self, path: &Path) -> Result<Option<FirmwareDetection>, CoreError> {
|
||||
let path = path.to_path_buf();
|
||||
let plan = tokio::task::spawn_blocking(move || {
|
||||
let repo = tramiton_core::Repo::new(&path);
|
||||
tramiton_core::provider::analyze(&repo)
|
||||
let repo = firmwerk_core::Repo::new(&path);
|
||||
firmwerk_core::provider::analyze(&repo)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| CoreError::Other(format!("tramiton detect task join error: {e}")))?
|
||||
.map_err(|e| CoreError::Other(format!("tramiton analyze error: {e}")))?;
|
||||
.map_err(|e| CoreError::Other(format!("firmwerk detect task join error: {e}")))?
|
||||
.map_err(|e| CoreError::Other(format!("firmwerk analyze error: {e}")))?;
|
||||
Ok(plan.map(|bp| detection_from_build_plan(&bp)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Map tramiton's `BuildPlan` onto our minimal detection summary.
|
||||
fn detection_from_build_plan(bp: &tramiton_core::BuildPlan) -> FirmwareDetection {
|
||||
/// Map Firmwerk's `BuildPlan` onto our minimal detection summary.
|
||||
fn detection_from_build_plan(bp: &firmwerk_core::BuildPlan) -> FirmwareDetection {
|
||||
FirmwareDetection {
|
||||
provider: bp.provider.clone(),
|
||||
confidence: bp.confidence.to_string(),
|
||||
@@ -103,7 +103,7 @@ pub fn detection_to_target_type(det: &FirmwareDetection) -> TargetType {
|
||||
}
|
||||
}
|
||||
|
||||
/// Map tramiton's confidence label to a `[0,1]` score.
|
||||
/// Map Firmwerk's confidence label to a `[0,1]` score.
|
||||
fn confidence_score(label: &str) -> f32 {
|
||||
match label.to_lowercase().as_str() {
|
||||
"high" => 0.9,
|
||||
@@ -120,26 +120,26 @@ pub fn detection_to_verdict(det: &FirmwareDetection) -> ClassifierVerdict {
|
||||
let mut facts = vec![DetectedFact::new(
|
||||
"build_system",
|
||||
det.build_system.clone(),
|
||||
"tramiton",
|
||||
"firmwerk",
|
||||
)];
|
||||
if let Some(fw) = &det.framework {
|
||||
facts.push(DetectedFact::new("framework", fw.clone(), "tramiton"));
|
||||
facts.push(DetectedFact::new("framework", fw.clone(), "firmwerk"));
|
||||
}
|
||||
if let Some(mcu) = &det.target.mcu {
|
||||
facts.push(DetectedFact::new("mcu", mcu.clone(), "tramiton"));
|
||||
facts.push(DetectedFact::new("mcu", mcu.clone(), "firmwerk"));
|
||||
}
|
||||
if let Some(board) = &det.target.board {
|
||||
facts.push(DetectedFact::new("board", board.clone(), "tramiton"));
|
||||
facts.push(DetectedFact::new("board", board.clone(), "firmwerk"));
|
||||
}
|
||||
if let Some(arch) = &det.target.arch {
|
||||
facts.push(DetectedFact::new("arch", arch.clone(), "tramiton"));
|
||||
facts.push(DetectedFact::new("arch", arch.clone(), "firmwerk"));
|
||||
}
|
||||
ClassifierVerdict {
|
||||
target_type,
|
||||
confidence: confidence_score(&det.confidence),
|
||||
facts,
|
||||
rationale: format!(
|
||||
"tramiton detected build system '{}'{}",
|
||||
"firmwerk detected build system '{}'{}",
|
||||
det.build_system,
|
||||
det.framework
|
||||
.as_ref()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Heuristic target-type classification from artifact kinds and source markers.
|
||||
//!
|
||||
//! Complements the tramiton firmware detector: this handles web / backend /
|
||||
//! Complements the Firmwerk firmware detector: this handles web / backend /
|
||||
//! mobile / desktop / PLC by sniffing manifest files and file extensions in the
|
||||
//! ingested code trees, plus strong priors from the artifact kinds themselves
|
||||
//! (a PLC-project artifact is a PLC target; an `.ipa` is an iOS app).
|
||||
@@ -108,7 +108,7 @@ impl HeuristicClassifier {
|
||||
ArtifactKind::FirmwareImage => out.push(verdict(
|
||||
TargetType::FirmwareBareMetal,
|
||||
0.35,
|
||||
"firmware image (pending tramiton detection)",
|
||||
"firmware image (pending firmwerk detection)",
|
||||
vec![],
|
||||
)),
|
||||
ArtifactKind::LiveUrl if input.artifacts.len() == 1 => {
|
||||
|
||||
@@ -3,13 +3,13 @@
|
||||
//! Runs the classifier registry over a target's artifacts and their ingested
|
||||
//! working paths, then merges and ranks the verdicts into a [`Classification`].
|
||||
//! The registry is the heuristic classifier (artifact kinds + source markers)
|
||||
//! plus the tramiton firmware detector (behind a [`FirmwareDetector`] port).
|
||||
//! plus the Firmwerk firmware detector (behind a [`FirmwareDetector`] port).
|
||||
|
||||
mod firmware;
|
||||
mod language;
|
||||
|
||||
pub use firmware::{
|
||||
FirmwareDetection, FirmwareDetector, FirmwareTarget, MockFirmwareDetector, TramitonNative,
|
||||
FirmwareDetection, FirmwareDetector, FirmwareTarget, FirmwerkNative, MockFirmwareDetector,
|
||||
};
|
||||
pub use language::HeuristicClassifier;
|
||||
|
||||
@@ -25,7 +25,7 @@ use compliance_core::traits::{ClassificationInput, ClassifierVerdict, TargetClas
|
||||
use firmware::detection_to_verdict;
|
||||
|
||||
/// Classify a target from its artifacts and their ingested working paths, using
|
||||
/// the heuristic classifier plus the tramiton firmware detector. Verdicts are
|
||||
/// the heuristic classifier plus the Firmwerk firmware detector. Verdicts are
|
||||
/// merged (max confidence per target type) and ranked into a [`Classification`].
|
||||
pub async fn classify_target<D: FirmwareDetector>(
|
||||
target: &OnboardedTarget,
|
||||
@@ -47,8 +47,8 @@ pub async fn classify_target<D: FirmwareDetector>(
|
||||
}
|
||||
verdicts.extend(heuristic);
|
||||
|
||||
// Tramiton firmware detection over firmware / code working paths.
|
||||
let mut tramiton_used = false;
|
||||
// Firmwerk firmware detection over firmware / code working paths.
|
||||
let mut firmwerk_used = false;
|
||||
for artifact in &target.artifacts {
|
||||
if !matches!(
|
||||
artifact.kind,
|
||||
@@ -61,11 +61,11 @@ pub async fn classify_target<D: FirmwareDetector>(
|
||||
};
|
||||
if let Some(detection) = firmware_detector.detect(path).await? {
|
||||
verdicts.push(detection_to_verdict(&detection));
|
||||
tramiton_used = true;
|
||||
firmwerk_used = true;
|
||||
}
|
||||
}
|
||||
if tramiton_used {
|
||||
detected_by.push("tramiton".to_string());
|
||||
if firmwerk_used {
|
||||
detected_by.push("firmwerk".to_string());
|
||||
}
|
||||
|
||||
Ok(rank(verdicts, detected_by, target.target_type))
|
||||
@@ -205,9 +205,9 @@ mod tests {
|
||||
let c = classify_target(&target, &wp, &detector)
|
||||
.await
|
||||
.expect("classify");
|
||||
// tramiton's high-confidence RTOS verdict beats the weak firmware prior.
|
||||
// Firmwerk's high-confidence RTOS verdict beats the weak firmware prior.
|
||||
assert_eq!(c.suggested, TargetType::FirmwareRtos);
|
||||
assert!(c.detected_by.contains(&"tramiton".to_string()));
|
||||
assert!(c.detected_by.contains(&"firmwerk".to_string()));
|
||||
assert!(c.facts.iter().any(|f| f.key == "mcu"));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use compliance_core::config::{BreakpilotConfig, PlcRuntimeConfig};
|
||||
use compliance_core::config::{AppEnv, BreakpilotConfig, Features, PlcRuntimeConfig};
|
||||
use compliance_core::AgentConfig;
|
||||
use secrecy::SecretString;
|
||||
|
||||
@@ -17,6 +17,24 @@ fn env_secret_opt(key: &str) -> Option<SecretString> {
|
||||
}
|
||||
|
||||
pub fn load_config() -> Result<AgentConfig, AgentError> {
|
||||
let app_env =
|
||||
AppEnv::parse(&env_var_opt("APP_ENV").unwrap_or_default()).map_err(AgentError::Config)?;
|
||||
let config = build_config(app_env)?;
|
||||
// A malformed key would leave every credential unstorable, so refuse to
|
||||
// start in every environment, not only hardened ones.
|
||||
crate::secrets::SecretBox::check_config(&config)
|
||||
.map_err(|e| AgentError::Config(e.to_string()))?;
|
||||
if let Err(problems) = config.validate_deployment() {
|
||||
return Err(AgentError::Config(format!(
|
||||
"refusing to start in {}:\n - {}",
|
||||
app_env.as_str(),
|
||||
problems.join("\n - ")
|
||||
)));
|
||||
}
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
fn build_config(app_env: AppEnv) -> Result<AgentConfig, AgentError> {
|
||||
Ok(AgentConfig {
|
||||
mongodb_uri: env_var("MONGODB_URI")?,
|
||||
mongodb_database: env_var_opt("MONGODB_DATABASE")
|
||||
@@ -41,6 +59,13 @@ pub fn load_config() -> Result<AgentConfig, AgentError> {
|
||||
agent_port: env_var_opt("AGENT_PORT")
|
||||
.and_then(|p| p.parse().ok())
|
||||
.unwrap_or(3001),
|
||||
webhook_port: env_var_opt("WEBHOOK_PORT")
|
||||
.and_then(|p| p.parse().ok())
|
||||
.unwrap_or(3002),
|
||||
scan_concurrency: env_var_opt("SCAN_CONCURRENCY")
|
||||
.and_then(|v| v.parse::<usize>().ok())
|
||||
.filter(|n| *n > 0)
|
||||
.unwrap_or(2),
|
||||
scan_schedule: env_var_opt("SCAN_SCHEDULE").unwrap_or_else(|| "0 0 */6 * * *".to_string()),
|
||||
cve_monitor_schedule: env_var_opt("CVE_MONITOR_SCHEDULE")
|
||||
.unwrap_or_else(|| "0 0 * * * *".to_string()),
|
||||
@@ -48,8 +73,6 @@ pub fn load_config() -> Result<AgentConfig, AgentError> {
|
||||
.unwrap_or_else(|| "/tmp/compliance-scanner/repos".to_string()),
|
||||
artifact_store_base_path: env_var_opt("ARTIFACT_STORE_BASE_PATH")
|
||||
.unwrap_or_else(|| "/data/compliance-scanner/artifacts".to_string()),
|
||||
ssh_key_path: env_var_opt("SSH_KEY_PATH")
|
||||
.unwrap_or_else(|| "/data/compliance-scanner/ssh/id_ed25519".to_string()),
|
||||
keycloak_url: env_var_opt("KEYCLOAK_URL"),
|
||||
keycloak_realm: env_var_opt("KEYCLOAK_REALM"),
|
||||
keycloak_admin_username: env_var_opt("KEYCLOAK_ADMIN_USERNAME"),
|
||||
@@ -63,13 +86,57 @@ pub fn load_config() -> Result<AgentConfig, AgentError> {
|
||||
pentest_imap_username: env_var_opt("PENTEST_IMAP_USERNAME"),
|
||||
pentest_imap_password: env_secret_opt("PENTEST_IMAP_PASSWORD"),
|
||||
admin_api_token: env_secret_opt("ADMIN_API_TOKEN"),
|
||||
secrets_encryption_key: env_secret_opt("SECRETS_ENCRYPTION_KEY"),
|
||||
tenant_registry_url: env_var_opt("TENANT_REGISTRY_URL"),
|
||||
plc_runtime: load_plc_runtime_config(),
|
||||
werkbank_runner_token: env_secret_opt("WERKBANK_RUNNER_TOKEN"),
|
||||
breakpilot: load_breakpilot_config(),
|
||||
product_key: env_var_opt("PRODUCT_KEY").unwrap_or_else(|| "pruefwerk".to_string()),
|
||||
// Audience defaults to the product key; set KEYCLOAK_AUDIENCE="" to disable in dev.
|
||||
keycloak_audience: match std::env::var("KEYCLOAK_AUDIENCE") {
|
||||
Ok(v) if v.is_empty() => None,
|
||||
Ok(v) => Some(v),
|
||||
Err(_) => Some("pruefwerk".to_string()),
|
||||
},
|
||||
tenant_registry_client_id: env_var_opt("TENANT_REGISTRY_CLIENT_ID"),
|
||||
tenant_registry_client_secret: env_secret_opt("TENANT_REGISTRY_CLIENT_SECRET"),
|
||||
cors_allowed_origins: env_csv("CORS_ALLOWED_ORIGINS"),
|
||||
platform_allowed_clients: {
|
||||
// Built-in defaults are a dev convenience only: a hardened
|
||||
// deployment names the clients it trusts, so a prod agent never
|
||||
// accepts a staging service token (validate_deployment enforces it).
|
||||
let v = env_csv("PLATFORM_ALLOWED_CLIENTS");
|
||||
if v.is_empty() && !app_env.is_hardened() {
|
||||
[
|
||||
"tenant-registry-svc-stage",
|
||||
"tenant-registry-svc-prod",
|
||||
"portal-svc-stage",
|
||||
"portal-svc-prod",
|
||||
]
|
||||
.iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect()
|
||||
} else {
|
||||
v
|
||||
}
|
||||
},
|
||||
features: Features::parse(&env_var_opt("PW_FEATURES").unwrap_or_default()),
|
||||
app_env,
|
||||
})
|
||||
}
|
||||
|
||||
fn env_csv(key: &str) -> Vec<String> {
|
||||
env_var_opt(key)
|
||||
.map(|s| {
|
||||
s.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(String::from)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Build the ephemeral soft-PLC provisioning config from the environment,
|
||||
/// falling back to [`PlcRuntimeConfig::default`] for any unset knob. Disabled
|
||||
/// unless `PLC_RUNTIME_ENABLED` is truthy — it requires Docker access.
|
||||
|
||||
@@ -31,7 +31,11 @@ impl<J: ControlJudge> GroundedControlChecker<J> {
|
||||
) -> Vec<Finding> {
|
||||
let mut findings = Vec::new();
|
||||
for region in regions {
|
||||
let verdict = self.judge.judge(spec, region).await;
|
||||
// No verdict (model down, unreadable answer) means no new finding
|
||||
// here; this pass only adds findings, it never removes one.
|
||||
let Ok(verdict) = self.judge.judge(spec, region).await else {
|
||||
continue;
|
||||
};
|
||||
if let Some(finding) = ground(spec, region, &verdict, repo_id) {
|
||||
findings.push(finding);
|
||||
}
|
||||
@@ -43,6 +47,7 @@ impl<J: ControlJudge> GroundedControlChecker<J> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::controls::JudgeError;
|
||||
use compliance_core::control_check::LlmVerdict;
|
||||
use compliance_core::models::finding::Severity;
|
||||
|
||||
@@ -53,8 +58,12 @@ mod tests {
|
||||
}
|
||||
|
||||
impl ControlJudge for StubJudge {
|
||||
async fn judge(&self, _spec: &ControlCheckSpec, _region: &CandidateRegion) -> LlmVerdict {
|
||||
self.verdict.clone()
|
||||
async fn judge(
|
||||
&self,
|
||||
_spec: &ControlCheckSpec,
|
||||
_region: &CandidateRegion,
|
||||
) -> Result<LlmVerdict, JudgeError> {
|
||||
Ok(self.verdict.clone())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,10 +28,32 @@ violate, set violates=false and leave snippet empty. (4) Prefer false over guess
|
||||
Respond with STRICT JSON only, no prose: \
|
||||
{\"violates\": bool, \"snippet\": \"<verbatim code or empty>\", \"cwe\": \"CWE-NNN or null\", \"confidence\": 0.0-1.0}";
|
||||
|
||||
/// Why the judge gave no verdict. Neither case says anything about the code,
|
||||
/// so a caller must never read it as "no violation".
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum JudgeError {
|
||||
/// The model could not be reached or returned an error.
|
||||
#[error("the control judge could not be reached: {0}")]
|
||||
Unavailable(String),
|
||||
/// The model answered, but not with a readable verdict.
|
||||
#[error("the control judge's answer could not be read: {0}")]
|
||||
Unreadable(String),
|
||||
}
|
||||
|
||||
/// Judges one (control, region). Async-in-trait so a stub can drive tests.
|
||||
#[allow(async_fn_in_trait)]
|
||||
pub trait ControlJudge: Send + Sync {
|
||||
async fn judge(&self, spec: &ControlCheckSpec, region: &CandidateRegion) -> LlmVerdict;
|
||||
/// The verdict for `region` against `spec`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`JudgeError`] when there is no verdict: the model was unavailable or
|
||||
/// its answer unreadable.
|
||||
async fn judge(
|
||||
&self,
|
||||
spec: &ControlCheckSpec,
|
||||
region: &CandidateRegion,
|
||||
) -> Result<LlmVerdict, JudgeError>;
|
||||
}
|
||||
|
||||
/// The real judge: the LLM at temperature 0 with the closed, verbatim-snippet prompt.
|
||||
@@ -46,17 +68,21 @@ impl LlmControlJudge {
|
||||
}
|
||||
|
||||
impl ControlJudge for LlmControlJudge {
|
||||
async fn judge(&self, spec: &ControlCheckSpec, region: &CandidateRegion) -> LlmVerdict {
|
||||
async fn judge(
|
||||
&self,
|
||||
spec: &ControlCheckSpec,
|
||||
region: &CandidateRegion,
|
||||
) -> Result<LlmVerdict, JudgeError> {
|
||||
let user = build_user_prompt(spec, region);
|
||||
match self.llm.chat(SYSTEM_PROMPT, &user, Some(0.0)).await {
|
||||
Ok(response) => parse_verdict(&response),
|
||||
Err(e) => {
|
||||
// Fail closed: a transient model error yields no finding, never a
|
||||
// fabricated one.
|
||||
let response = self
|
||||
.llm
|
||||
.chat(SYSTEM_PROMPT, &user, Some(0.0))
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::warn!(control = %spec.control_id, error = %e, "control judge call failed");
|
||||
no_violation()
|
||||
}
|
||||
}
|
||||
JudgeError::Unavailable(e.to_string())
|
||||
})?;
|
||||
parse_verdict(&response)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,36 +110,29 @@ struct RawVerdict {
|
||||
confidence: f64,
|
||||
}
|
||||
|
||||
/// Parse the model's JSON verdict, tolerant of ```json fencing. Any parse failure
|
||||
/// degrades to a non-violation (never a fabricated finding).
|
||||
fn parse_verdict(response: &str) -> LlmVerdict {
|
||||
/// Parse the model's JSON verdict, tolerant of ```json fencing.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`JudgeError::Unreadable`] when the answer is not a verdict; that is no
|
||||
/// decision either way, never a fabricated finding or a silent "no violation".
|
||||
fn parse_verdict(response: &str) -> Result<LlmVerdict, JudgeError> {
|
||||
let cleaned = response
|
||||
.trim()
|
||||
.trim_start_matches("```json")
|
||||
.trim_start_matches("```")
|
||||
.trim_end_matches("```")
|
||||
.trim();
|
||||
match serde_json::from_str::<RawVerdict>(cleaned) {
|
||||
Ok(raw) => LlmVerdict {
|
||||
violates: raw.violates,
|
||||
snippet: raw.snippet,
|
||||
cwe: raw.cwe.filter(|c| !c.trim().is_empty()),
|
||||
confidence: raw.confidence,
|
||||
},
|
||||
Err(e) => {
|
||||
tracing::debug!(error = %e, "failed to parse control verdict; treating as non-violation");
|
||||
no_violation()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn no_violation() -> LlmVerdict {
|
||||
LlmVerdict {
|
||||
violates: false,
|
||||
snippet: String::new(),
|
||||
cwe: None,
|
||||
confidence: 0.0,
|
||||
}
|
||||
let raw = serde_json::from_str::<RawVerdict>(cleaned).map_err(|e| {
|
||||
tracing::debug!(error = %e, "failed to parse control verdict");
|
||||
JudgeError::Unreadable(e.to_string())
|
||||
})?;
|
||||
Ok(LlmVerdict {
|
||||
violates: raw.violates,
|
||||
snippet: raw.snippet,
|
||||
cwe: raw.cwe.filter(|c| !c.trim().is_empty()),
|
||||
confidence: raw.confidence,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -134,21 +153,27 @@ mod tests {
|
||||
#[test]
|
||||
fn parses_plain_and_fenced_json() {
|
||||
let plain = r#"{"violates": true, "snippet": "PASSWORD = \"x\"", "cwe": "CWE-798", "confidence": 0.9}"#;
|
||||
let v = parse_verdict(plain);
|
||||
let Ok(v) = parse_verdict(plain) else {
|
||||
panic!("a plain JSON verdict parses");
|
||||
};
|
||||
assert!(v.violates);
|
||||
assert_eq!(v.snippet, "PASSWORD = \"x\"");
|
||||
assert_eq!(v.cwe.as_deref(), Some("CWE-798"));
|
||||
|
||||
let fenced = "```json\n{\"violates\": false, \"snippet\": \"\", \"cwe\": null, \"confidence\": 0.1}\n```";
|
||||
assert!(!parse_verdict(fenced).violates);
|
||||
assert!(matches!(parse_verdict(fenced), Ok(v) if !v.violates));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn garbage_and_empty_cwe_are_safe() {
|
||||
assert!(!parse_verdict("not json at all").violates); // fail closed
|
||||
fn an_unreadable_answer_is_an_error_not_a_verdict() {
|
||||
// Neither "violates" nor "does not violate": the caller must not decide.
|
||||
assert!(matches!(
|
||||
parse_verdict("not json at all"),
|
||||
Err(JudgeError::Unreadable(_))
|
||||
));
|
||||
let no_cwe =
|
||||
parse_verdict(r#"{"violates": true, "snippet": "x", "cwe": " ", "confidence": 0.5}"#);
|
||||
assert!(no_cwe.cwe.is_none()); // blank CWE normalised away
|
||||
assert!(matches!(no_cwe, Ok(v) if v.cwe.is_none())); // blank CWE normalised away
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
//! What a master control says, for a reader looking at a finding mapped to it.
|
||||
//!
|
||||
//! The semantic pass stamps master-control ids (`mc-10056`) on findings; the
|
||||
//! dashboard has no catalog of its own, so it asks the agent what they mean.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use serde::Serialize;
|
||||
use tokio::sync::OnceCell;
|
||||
|
||||
use compliance_core::traits::Control;
|
||||
use compliance_core::AgentConfig;
|
||||
|
||||
use super::scan_triage::provider_for;
|
||||
|
||||
/// A master control as a reader sees it next to a finding.
|
||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
|
||||
pub struct ControlSummary {
|
||||
/// The id stamped on findings (`mc-10056`).
|
||||
pub id: String,
|
||||
/// The catalog's label (`MC-10056`).
|
||||
pub label: String,
|
||||
/// What the control requires: the first requirement of its statement.
|
||||
pub statement: String,
|
||||
}
|
||||
|
||||
/// The master-controls catalog by id, loaded once per agent process. The
|
||||
/// catalog ships with the image, so a new one arrives with a redeploy. A
|
||||
/// failed load is not cached: the next lookup tries again.
|
||||
static MASTER_CONTROLS: OnceCell<HashMap<String, ControlSummary>> = OnceCell::const_new();
|
||||
|
||||
/// Describe `ids` from the master-controls catalog, in the order given.
|
||||
/// Ids the catalog does not know (a CRA id, a control since removed) are left
|
||||
/// out.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Empty when no catalog is configured or it cannot be loaded (logged).
|
||||
pub async fn describe_master_controls(config: &AgentConfig, ids: &[String]) -> Vec<ControlSummary> {
|
||||
let catalog = MASTER_CONTROLS
|
||||
.get_or_try_init(|| async {
|
||||
let provider = provider_for(config).ok_or("no controls catalog configured")?;
|
||||
let doc = provider.load_master_controls().await.map_err(|e| {
|
||||
tracing::warn!(error = %e, "master-controls catalog unavailable");
|
||||
"master-controls catalog unavailable"
|
||||
})?;
|
||||
Ok::<_, &str>(by_id(&doc.to_controls()))
|
||||
})
|
||||
.await;
|
||||
match catalog {
|
||||
Ok(catalog) => ids
|
||||
.iter()
|
||||
.filter_map(|id| catalog.get(id).cloned())
|
||||
.collect(),
|
||||
Err(_) => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Index `controls` by id, each with its first requirement as the statement.
|
||||
/// The catalog joins a master control's requirements with ` | `.
|
||||
fn by_id(controls: &[Control]) -> HashMap<String, ControlSummary> {
|
||||
controls
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let statement = c.text.split(" | ").next().unwrap_or_default().trim();
|
||||
let summary = ControlSummary {
|
||||
id: c.id.clone(),
|
||||
label: c.id.to_ascii_uppercase(),
|
||||
statement: statement.to_string(),
|
||||
};
|
||||
(c.id.clone(), summary)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::onboarding::ComplianceFramework;
|
||||
|
||||
fn control(id: &str, text: &str) -> Control {
|
||||
Control {
|
||||
id: id.to_string(),
|
||||
framework: ComplianceFramework::Cra,
|
||||
title: "slug_title".to_string(),
|
||||
text: text.to_string(),
|
||||
source: None,
|
||||
severity: None,
|
||||
evidence_type: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_control_reads_as_its_label_and_first_requirement() {
|
||||
let catalog = by_id(&[control(
|
||||
"mc-10056",
|
||||
"Erklärung unterzeichnen. | Zugang gewähren. | Kopie aufbewahren.",
|
||||
)]);
|
||||
|
||||
assert_eq!(
|
||||
catalog.get("mc-10056"),
|
||||
Some(&ControlSummary {
|
||||
id: "mc-10056".to_string(),
|
||||
label: "MC-10056".to_string(),
|
||||
statement: "Erklärung unterzeichnen.".to_string(),
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
mod checker;
|
||||
mod index;
|
||||
mod judge;
|
||||
mod lookup;
|
||||
mod oscal_provider;
|
||||
mod scan_triage;
|
||||
mod semantic;
|
||||
@@ -16,8 +17,11 @@ mod triage;
|
||||
|
||||
pub use checker::GroundedControlChecker;
|
||||
pub use index::ControlIndex;
|
||||
pub use judge::{ControlJudge, LlmControlJudge, PROMPT_VERSION};
|
||||
pub use judge::{ControlJudge, JudgeError, LlmControlJudge, PROMPT_VERSION};
|
||||
pub use lookup::{describe_master_controls, ControlSummary};
|
||||
pub use oscal_provider::OscalControlsProvider;
|
||||
pub use scan_triage::{grounded_surface_findings, semantic_stamp_findings, triage_repo_findings};
|
||||
pub use scan_triage::{
|
||||
cra_catalog, grounded_surface_findings, semantic_stamp_findings, triage_repo_findings,
|
||||
};
|
||||
pub use semantic::SemanticControlChecker;
|
||||
pub use triage::{ControlTriage, TriageOutcome};
|
||||
@@ -7,7 +7,7 @@
|
||||
//! consumes. The producer owns the catalog; we own the assessment — this is the
|
||||
//! ingest half of the loop.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
|
||||
@@ -20,34 +20,53 @@ use compliance_core::traits::{Control, ControlQuery, ControlsProvider};
|
||||
/// and snapshots it locally for deterministic / offline reuse.
|
||||
pub struct OscalControlsProvider {
|
||||
http: reqwest::Client,
|
||||
base_url: String,
|
||||
/// `None` = snapshot-only: no fetch, serve whatever is under `snapshot_dir`
|
||||
/// (baked into the image or written by an earlier online run).
|
||||
base_url: Option<String>,
|
||||
token: Option<SecretString>,
|
||||
snapshot_dir: PathBuf,
|
||||
}
|
||||
|
||||
impl OscalControlsProvider {
|
||||
/// Create a provider. `base_url` is the breakpilot-compliance root (e.g.
|
||||
/// `http://backend-compliance:8002`); `snapshot_dir` is where catalog
|
||||
/// snapshots are written so a later scan can reuse them without the network.
|
||||
/// `http://backend-compliance:8002`) or `None` for snapshot-only mode;
|
||||
/// `snapshot_dir` is where catalog snapshots are written so a later scan can
|
||||
/// reuse them without the network.
|
||||
pub fn new(
|
||||
http: reqwest::Client,
|
||||
base_url: impl Into<String>,
|
||||
base_url: Option<String>,
|
||||
token: Option<SecretString>,
|
||||
snapshot_dir: impl Into<PathBuf>,
|
||||
) -> Self {
|
||||
Self {
|
||||
http,
|
||||
base_url: base_url.into(),
|
||||
base_url,
|
||||
token,
|
||||
snapshot_dir: snapshot_dir.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn catalog_url(&self, framework: &str) -> String {
|
||||
format!(
|
||||
"{}/api/compliance/v1/oscal/catalog?framework={framework}",
|
||||
self.base_url.trim_end_matches('/')
|
||||
)
|
||||
fn catalog_url(&self, framework: &str) -> Option<String> {
|
||||
self.base_url.as_deref().map(|b| {
|
||||
format!(
|
||||
"{}/api/compliance/v1/oscal/catalog?framework={framework}",
|
||||
b.trim_end_matches('/')
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// True when at least one `oscal-catalog-*.json` snapshot exists, i.e. the
|
||||
/// provider can serve catalogs without a backend.
|
||||
pub fn has_snapshots(snapshot_dir: &Path) -> bool {
|
||||
std::fs::read_dir(snapshot_dir)
|
||||
.map(|rd| {
|
||||
rd.flatten().any(|e| {
|
||||
let n = e.file_name();
|
||||
let n = n.to_string_lossy();
|
||||
n.starts_with("oscal-catalog-") && n.ends_with(".json")
|
||||
})
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn snapshot_path(&self, framework: &str) -> PathBuf {
|
||||
@@ -57,7 +76,12 @@ impl OscalControlsProvider {
|
||||
|
||||
/// Fetch the raw catalog bytes for a framework token over HTTP.
|
||||
async fn fetch_raw(&self, framework: &str) -> Result<Vec<u8>, CoreError> {
|
||||
let mut req = self.http.get(self.catalog_url(framework));
|
||||
let Some(url) = self.catalog_url(framework) else {
|
||||
return Err(CoreError::Http(
|
||||
"no catalog backend configured (snapshot-only mode)".to_string(),
|
||||
));
|
||||
};
|
||||
let mut req = self.http.get(url);
|
||||
if let Some(token) = &self.token {
|
||||
req = req.bearer_auth(token.expose_secret());
|
||||
}
|
||||
@@ -178,15 +202,20 @@ mod tests {
|
||||
"props":[],"parts":[{"name":"statement","prose":"require mfa"}]}]}]}}"#;
|
||||
|
||||
fn provider(dir: &std::path::Path) -> OscalControlsProvider {
|
||||
OscalControlsProvider::new(reqwest::Client::new(), "http://unused/", None, dir)
|
||||
OscalControlsProvider::new(
|
||||
reqwest::Client::new(),
|
||||
Some("http://unused/".to_string()),
|
||||
None,
|
||||
dir,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_catalog_url_and_snapshot_path() {
|
||||
let p = provider(std::path::Path::new("/snap"));
|
||||
assert_eq!(
|
||||
p.catalog_url("cra"),
|
||||
"http://unused/api/compliance/v1/oscal/catalog?framework=cra"
|
||||
p.catalog_url("cra").as_deref(),
|
||||
Some("http://unused/api/compliance/v1/oscal/catalog?framework=cra")
|
||||
);
|
||||
assert_eq!(
|
||||
p.snapshot_path("cra"),
|
||||
@@ -202,6 +231,8 @@ mod tests {
|
||||
title: title.into(),
|
||||
text: String::new(),
|
||||
source: None,
|
||||
severity: None,
|
||||
evidence_type: None,
|
||||
};
|
||||
let controls = vec![
|
||||
mk("a", "logging policy"),
|
||||
@@ -226,4 +257,66 @@ mod tests {
|
||||
assert_eq!(doc.framework(), Some(ComplianceFramework::Cra));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The snapshot shipped in the image must parse and carry the full CRA
|
||||
/// catalog — a truncated or reshaped refresh would silently disable control
|
||||
/// mapping in snapshot-only environments.
|
||||
#[test]
|
||||
fn shipped_cra_snapshot_parses_with_all_controls() {
|
||||
const SHIPPED: &str = include_str!("../../controls/snapshot/oscal-catalog-cra.json");
|
||||
let doc: OscalDocument = serde_json::from_str(SHIPPED).unwrap();
|
||||
assert_eq!(doc.framework(), Some(ComplianceFramework::Cra));
|
||||
assert_eq!(doc.to_controls().len(), 40);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shipped_master_controls_snapshot_parses_with_its_declared_count() {
|
||||
// Taken once from breakpilot-compliance (#382); the semantic pass reads
|
||||
// it in snapshot-only mode, where the backend is not reachable.
|
||||
const SHIPPED: &str =
|
||||
include_str!("../../controls/snapshot/oscal-catalog-master-controls.json");
|
||||
let doc: OscalDocument = serde_json::from_str(SHIPPED).unwrap();
|
||||
let declared: usize = doc
|
||||
.catalog
|
||||
.metadata
|
||||
.props
|
||||
.iter()
|
||||
.find(|p| p.name == "control-count")
|
||||
.and_then(|p| p.value.parse().ok())
|
||||
.unwrap();
|
||||
assert_eq!(doc.to_controls().len(), declared);
|
||||
assert!(declared > 2_000, "{declared}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_control_map_and_the_shipped_catalog_name_the_same_controls() {
|
||||
// The map is ours, the catalog breakpilot-compliance's: a control one
|
||||
// has and the other lacks would never be triaged or never be shown.
|
||||
const SHIPPED: &str = include_str!("../../controls/snapshot/oscal-catalog-cra.json");
|
||||
let doc: OscalDocument = serde_json::from_str(SHIPPED).unwrap();
|
||||
let mut catalog: Vec<String> = doc.to_controls().into_iter().map(|c| c.id).collect();
|
||||
let map = control_map::ControlMap::cra().unwrap();
|
||||
let mut mapped: Vec<String> = map.controls.into_iter().map(|c| c.control).collect();
|
||||
catalog.sort();
|
||||
mapped.sort();
|
||||
assert_eq!(catalog, mapped);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn snapshot_only_mode_serves_baked_catalog() {
|
||||
let dir = std::env::temp_dir().join(format!("oscal-test-{}", uuid::Uuid::new_v4()));
|
||||
assert!(!OscalControlsProvider::has_snapshots(&dir));
|
||||
let online = provider(&dir);
|
||||
online
|
||||
.write_snapshot("cra", MINI_CATALOG.as_bytes())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(OscalControlsProvider::has_snapshots(&dir));
|
||||
let offline = OscalControlsProvider::new(reqwest::Client::new(), None, None, &dir);
|
||||
assert!(offline.catalog_url("cra").is_none());
|
||||
let doc = offline.load(ComplianceFramework::Cra).await.unwrap();
|
||||
assert_eq!(doc.to_controls().len(), 1);
|
||||
assert!(offline.load_master_controls().await.is_err());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -10,9 +10,12 @@ use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use futures_util::StreamExt;
|
||||
|
||||
use compliance_core::control_check::{CandidateRegion, ControlCheckSpec};
|
||||
use compliance_core::models::finding::{Finding, FindingStatus, Severity};
|
||||
use compliance_core::models::onboarding::ComplianceFramework;
|
||||
use compliance_core::traits::Control;
|
||||
use compliance_core::AgentConfig;
|
||||
use control_map::ControlMap;
|
||||
|
||||
@@ -25,6 +28,14 @@ use crate::llm::LlmClient;
|
||||
|
||||
/// Nearest master controls judged per code region in the semantic pass.
|
||||
const SEMANTIC_TOP_K: usize = 5;
|
||||
/// Control-triage judge calls in flight at once.
|
||||
const CONTROL_TRIAGE_CONCURRENCY: usize = 8;
|
||||
/// Most findings one scan maps semantically: each costs an embedding and up
|
||||
/// to [`SEMANTIC_TOP_K`] judge calls, so an uncapped pass would add tens of
|
||||
/// minutes to a large scan. The most severe unmapped ones go first.
|
||||
const SEMANTIC_MAX_FINDINGS: usize = 40;
|
||||
/// Findings judged at the same time.
|
||||
const SEMANTIC_CONCURRENCY: usize = 4;
|
||||
|
||||
/// Lines of context to read on each side of a finding's line.
|
||||
const REGION_WINDOW: usize = 6;
|
||||
@@ -38,15 +49,9 @@ pub async fn triage_repo_findings(
|
||||
repo_path: &Path,
|
||||
findings: &mut [Finding],
|
||||
) -> usize {
|
||||
let Some(base_url) = config.breakpilot.base_url.clone() else {
|
||||
return 0; // control triage is opt-in via BREAKPILOT_BASE_URL
|
||||
let Some(provider) = provider_for(config) else {
|
||||
return 0; // control triage is opt-in via BREAKPILOT_BASE_URL or a snapshot
|
||||
};
|
||||
let provider = OscalControlsProvider::new(
|
||||
reqwest::Client::new(),
|
||||
base_url,
|
||||
config.breakpilot.token.clone(),
|
||||
&config.breakpilot.snapshot_dir,
|
||||
);
|
||||
let specs = build_specs(&provider).await;
|
||||
if specs.is_empty() {
|
||||
return 0;
|
||||
@@ -60,30 +65,88 @@ pub async fn triage_repo_findings(
|
||||
};
|
||||
let triage = ControlTriage::new(LlmControlJudge::new(llm), map, specs);
|
||||
|
||||
// The judge reads each finding's code; its calls run a few at a time, and
|
||||
// the outcomes are applied once all are in.
|
||||
let candidates: Vec<(usize, CandidateRegion)> = findings
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, f)| {
|
||||
let region = fetch_region(repo_path, f.file_path.as_deref()?, f.line_number?)?;
|
||||
Some((i, region))
|
||||
})
|
||||
.collect();
|
||||
let mut outcomes = Vec::with_capacity(candidates.len());
|
||||
{
|
||||
let read: &[Finding] = findings;
|
||||
for group in candidates.chunks(CONTROL_TRIAGE_CONCURRENCY) {
|
||||
let calls = group
|
||||
.iter()
|
||||
.map(|(i, region)| triage.triage(&read[*i], region));
|
||||
outcomes.extend(futures_util::future::join_all(calls).await);
|
||||
}
|
||||
}
|
||||
|
||||
let mut tagged = 0;
|
||||
for finding in findings.iter_mut() {
|
||||
let (Some(file), Some(line)) = (finding.file_path.clone(), finding.line_number) else {
|
||||
continue;
|
||||
};
|
||||
let Some(region) = fetch_region(repo_path, &file, line) else {
|
||||
continue;
|
||||
};
|
||||
match triage.triage(finding, ®ion).await {
|
||||
for ((i, _), outcome) in candidates.iter().zip(outcomes) {
|
||||
let finding = &mut findings[*i];
|
||||
match outcome {
|
||||
TriageOutcome::Confirmed(controls) => {
|
||||
finding.control_refs = controls;
|
||||
tagged += 1;
|
||||
}
|
||||
TriageOutcome::FalsePositive => {
|
||||
finding.status = FindingStatus::FalsePositive;
|
||||
finding.triage_action = Some("control_false_positive".to_string());
|
||||
// The judge refuted the mapping: the finding stays, for a person
|
||||
// to decide.
|
||||
TriageOutcome::NeedsReview => {
|
||||
finding.status = FindingStatus::NeedsReview;
|
||||
finding.triage_action = Some("control_not_confirmed".to_string());
|
||||
finding.triage_rationale.get_or_insert_with(|| {
|
||||
"The control check did not confirm the CRA requirements this \
|
||||
finding maps to. Please review whether it is a real issue."
|
||||
.to_string()
|
||||
});
|
||||
}
|
||||
TriageOutcome::Unmapped => {}
|
||||
TriageOutcome::Undecided | TriageOutcome::Unmapped => {}
|
||||
}
|
||||
}
|
||||
tagged
|
||||
}
|
||||
|
||||
/// Build the control requirement specs (by id) from the ingested OSCAL catalog.
|
||||
/// The catalog source for this agent: the breakpilot backend when
|
||||
/// `BREAKPILOT_BASE_URL` is set, else the baked/previously written snapshots
|
||||
/// under `BREAKPILOT_SNAPSHOT_DIR`. `None` = control triage is off.
|
||||
pub(super) fn provider_for(config: &AgentConfig) -> Option<OscalControlsProvider> {
|
||||
let snapshot_dir = Path::new(&config.breakpilot.snapshot_dir);
|
||||
if config.breakpilot.base_url.is_none() && !OscalControlsProvider::has_snapshots(snapshot_dir) {
|
||||
return None;
|
||||
}
|
||||
Some(OscalControlsProvider::new(
|
||||
reqwest::Client::new(),
|
||||
config.breakpilot.base_url.clone(),
|
||||
config.breakpilot.token.clone(),
|
||||
snapshot_dir,
|
||||
))
|
||||
}
|
||||
|
||||
/// The CRA catalog's controls by id (from the backend or the baked snapshot),
|
||||
/// for the ratings the CRA status shows. Empty when no catalog is available.
|
||||
pub async fn cra_catalog(config: &AgentConfig) -> HashMap<String, Control> {
|
||||
let Some(provider) = provider_for(config) else {
|
||||
return HashMap::new();
|
||||
};
|
||||
match provider.load(ComplianceFramework::Cra).await {
|
||||
Ok(doc) => doc
|
||||
.to_controls()
|
||||
.into_iter()
|
||||
.map(|c| (c.id.clone(), c))
|
||||
.collect(),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "could not load the CRA catalog");
|
||||
HashMap::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn build_specs(provider: &OscalControlsProvider) -> HashMap<String, ControlCheckSpec> {
|
||||
let mut specs = HashMap::new();
|
||||
match provider.load(ComplianceFramework::Cra).await {
|
||||
@@ -96,7 +159,8 @@ async fn build_specs(provider: &OscalControlsProvider) -> HashMap<String, Contro
|
||||
title: control.title,
|
||||
requirement: control.text,
|
||||
default_cwe: None,
|
||||
severity: Severity::Medium,
|
||||
// The catalog's rating; Medium where it has none.
|
||||
severity: control.severity.unwrap_or(Severity::Medium),
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -121,27 +185,26 @@ pub async fn grounded_surface_findings(
|
||||
repo_path: &Path,
|
||||
repo_id: &str,
|
||||
) -> Vec<Finding> {
|
||||
let Some(base_url) = config.breakpilot.base_url.clone() else {
|
||||
let Some(provider) = provider_for(config) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let provider = OscalControlsProvider::new(
|
||||
reqwest::Client::new(),
|
||||
base_url,
|
||||
config.breakpilot.token.clone(),
|
||||
&config.breakpilot.snapshot_dir,
|
||||
);
|
||||
let specs = build_specs(&provider).await;
|
||||
if specs.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let checker = GroundedControlChecker::new(LlmControlJudge::new(llm));
|
||||
// The vendor SDK is not the customer's code: its surfaces are left out.
|
||||
let tree = repo_path.to_path_buf();
|
||||
let vendor = tokio::task::spawn_blocking(move || crate::pipeline::vendor::vendor_dirs(&tree))
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut out = Vec::new();
|
||||
for surf in surface::SURFACES {
|
||||
let Some(spec) = specs.get(surf.control_id) else {
|
||||
continue; // catalog doesn't carry this control
|
||||
};
|
||||
let regions = surface::retrieve(repo_path, surf.terms);
|
||||
let regions = surface::retrieve(repo_path, surf.terms, &vendor);
|
||||
if regions.is_empty() {
|
||||
continue;
|
||||
}
|
||||
@@ -183,15 +246,9 @@ pub async fn semantic_stamp_findings(
|
||||
repo_path: &Path,
|
||||
findings: &mut [Finding],
|
||||
) -> usize {
|
||||
let Some(base_url) = config.breakpilot.base_url.clone() else {
|
||||
let Some(provider) = provider_for(config) else {
|
||||
return 0;
|
||||
};
|
||||
let provider = OscalControlsProvider::new(
|
||||
reqwest::Client::new(),
|
||||
base_url,
|
||||
config.breakpilot.token.clone(),
|
||||
&config.breakpilot.snapshot_dir,
|
||||
);
|
||||
let doc = match provider.load_master_controls().await {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
@@ -222,51 +279,47 @@ pub async fn semantic_stamp_findings(
|
||||
};
|
||||
let checker = SemanticControlChecker::new(LlmControlJudge::new(llm.clone()));
|
||||
|
||||
let mut tagged = 0;
|
||||
for finding in findings.iter_mut() {
|
||||
if finding.status == FindingStatus::FalsePositive {
|
||||
continue;
|
||||
}
|
||||
let (Some(file), Some(line)) = (finding.file_path.clone(), finding.line_number) else {
|
||||
continue;
|
||||
};
|
||||
let Some(region) = fetch_region(repo_path, &file, line) else {
|
||||
continue;
|
||||
};
|
||||
// Retrieve on the finding's intent + the code, not the region alone: two
|
||||
// findings in one file share overlapping windows and otherwise embed alike,
|
||||
// collapsing onto the same controls. The finding's title/description carry
|
||||
// the discriminating signal (e.g. "brute-force protection" vs "weak hash").
|
||||
// The raw `region` still goes to the judge for snippet grounding.
|
||||
let query = format!(
|
||||
"{}\n{}\n\n{}",
|
||||
finding.title, finding.description, region.content
|
||||
let candidates = semantic_candidates(findings);
|
||||
let considered = findings
|
||||
.iter()
|
||||
.filter(|f| {
|
||||
!matches!(
|
||||
f.status,
|
||||
FindingStatus::FalsePositive | FindingStatus::WrongMapping
|
||||
) && f.control_refs.is_empty()
|
||||
})
|
||||
.count();
|
||||
if candidates.len() < considered {
|
||||
tracing::info!(
|
||||
"semantic pass: the {} most severe of {considered} unmapped findings",
|
||||
candidates.len()
|
||||
);
|
||||
let query_emb = match llm.embed(vec![query]).await {
|
||||
Ok(mut embs) => match embs.pop() {
|
||||
Some(v) => v,
|
||||
None => continue,
|
||||
},
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "query embed failed; skipping finding");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Judged a few at a time: each finding costs an embedding and up to
|
||||
// SEMANTIC_TOP_K judge calls.
|
||||
let results: Vec<(usize, Vec<String>)> = {
|
||||
let (index, checker, llm) = (&index, &checker, &llm);
|
||||
let findings: &[Finding] = findings;
|
||||
futures_util::stream::iter(candidates)
|
||||
.map(|i| async move {
|
||||
let refs = semantic_refs(llm, checker, index, repo_path, &findings[i]).await;
|
||||
(i, refs)
|
||||
})
|
||||
.buffer_unordered(SEMANTIC_CONCURRENCY)
|
||||
.collect()
|
||||
.await
|
||||
};
|
||||
|
||||
let mut tagged = 0;
|
||||
for (i, refs) in results {
|
||||
let Some(finding) = findings.get_mut(i) else {
|
||||
continue;
|
||||
};
|
||||
let confirmed = checker
|
||||
.check(
|
||||
&index,
|
||||
®ion,
|
||||
&query_emb,
|
||||
SEMANTIC_TOP_K,
|
||||
&finding.repo_id,
|
||||
)
|
||||
.await;
|
||||
let before = finding.control_refs.len();
|
||||
for f in confirmed {
|
||||
for cref in f.control_refs {
|
||||
if !finding.control_refs.contains(&cref) {
|
||||
finding.control_refs.push(cref);
|
||||
}
|
||||
for cref in refs {
|
||||
if !finding.control_refs.contains(&cref) {
|
||||
finding.control_refs.push(cref);
|
||||
}
|
||||
}
|
||||
if finding.control_refs.len() > before {
|
||||
@@ -276,10 +329,108 @@ pub async fn semantic_stamp_findings(
|
||||
tagged
|
||||
}
|
||||
|
||||
/// The findings the semantic pass looks at, by index: not false positives,
|
||||
/// not already mapped by the CRA triage, with a code location, most severe
|
||||
/// first, at most [`SEMANTIC_MAX_FINDINGS`].
|
||||
fn semantic_candidates(findings: &[Finding]) -> Vec<usize> {
|
||||
let mut candidates: Vec<usize> = findings
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, f)| {
|
||||
!matches!(
|
||||
f.status,
|
||||
FindingStatus::FalsePositive | FindingStatus::WrongMapping
|
||||
) && f.control_refs.is_empty()
|
||||
&& f.file_path.is_some()
|
||||
&& f.line_number.is_some()
|
||||
})
|
||||
.map(|(i, _)| i)
|
||||
.collect();
|
||||
// Stable, so equally severe findings keep their scan order.
|
||||
candidates.sort_by(|a, b| findings[*b].severity.cmp(&findings[*a].severity));
|
||||
candidates.truncate(SEMANTIC_MAX_FINDINGS);
|
||||
candidates
|
||||
}
|
||||
|
||||
/// The master-control ids the judge confirms for one finding; empty when its
|
||||
/// region cannot be read or embedded.
|
||||
async fn semantic_refs(
|
||||
llm: &LlmClient,
|
||||
checker: &SemanticControlChecker<LlmControlJudge>,
|
||||
index: &ControlIndex,
|
||||
repo_path: &Path,
|
||||
finding: &Finding,
|
||||
) -> Vec<String> {
|
||||
let (Some(file), Some(line)) = (finding.file_path.as_deref(), finding.line_number) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(region) = fetch_region(repo_path, file, line) else {
|
||||
return Vec::new();
|
||||
};
|
||||
// Retrieve on the finding's intent + the code, not the region alone: two
|
||||
// findings in one file share overlapping windows and otherwise embed alike,
|
||||
// collapsing onto the same controls. The finding's title/description carry
|
||||
// the discriminating signal (e.g. "brute-force protection" vs "weak hash").
|
||||
// The raw `region` still goes to the judge for snippet grounding.
|
||||
let query = format!(
|
||||
"{}\n{}\n\n{}",
|
||||
finding.title, finding.description, region.content
|
||||
);
|
||||
let query_emb = match llm.embed(vec![query]).await {
|
||||
Ok(mut embs) => match embs.pop() {
|
||||
Some(v) => v,
|
||||
None => return Vec::new(),
|
||||
},
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "query embed failed; skipping finding");
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
checker
|
||||
.check(index, ®ion, &query_emb, SEMANTIC_TOP_K, &finding.repo_id)
|
||||
.await
|
||||
.into_iter()
|
||||
.flat_map(|f| f.control_refs)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_semantic_pass_takes_the_most_severe_unmapped_findings() {
|
||||
let mk = |severity: Severity, refs: &[&str], status: FindingStatus| {
|
||||
let mut f = Finding::new(
|
||||
"t".into(),
|
||||
format!("fp-{severity}-{}", refs.len()),
|
||||
"plc-control-logic".into(),
|
||||
compliance_core::models::scan::ScanType::Sast,
|
||||
"x".into(),
|
||||
"d".into(),
|
||||
severity,
|
||||
);
|
||||
f.file_path = Some("pump.st".into());
|
||||
f.line_number = Some(3);
|
||||
f.control_refs = refs.iter().map(|r| r.to_string()).collect();
|
||||
f.status = status;
|
||||
f
|
||||
};
|
||||
let findings = vec![
|
||||
mk(Severity::Low, &[], FindingStatus::Open),
|
||||
mk(Severity::Critical, &[], FindingStatus::Open),
|
||||
mk(Severity::High, &["cra-ai-8"], FindingStatus::Open), // mapped already
|
||||
mk(Severity::High, &[], FindingStatus::FalsePositive),
|
||||
mk(Severity::High, &[], FindingStatus::NeedsReview),
|
||||
];
|
||||
assert_eq!(semantic_candidates(&findings), [1, 4, 0]);
|
||||
|
||||
let many: Vec<Finding> = (0..SEMANTIC_MAX_FINDINGS + 5)
|
||||
.map(|_| mk(Severity::Medium, &[], FindingStatus::Open))
|
||||
.collect();
|
||||
assert_eq!(semantic_candidates(&many).len(), SEMANTIC_MAX_FINDINGS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_region_windows_around_the_line() {
|
||||
let dir = std::env::temp_dir().join(format!("triage-region-{}", uuid::Uuid::new_v4()));
|
||||
|
||||
@@ -38,7 +38,11 @@ impl<J: ControlJudge> SemanticControlChecker<J> {
|
||||
let candidates = index.nearest(query_embedding, k);
|
||||
let mut findings = Vec::new();
|
||||
for spec in &candidates {
|
||||
let verdict = self.judge.judge(spec, region).await;
|
||||
// No verdict (model down, unreadable answer) means no new finding
|
||||
// here; this pass only adds findings, it never removes one.
|
||||
let Ok(verdict) = self.judge.judge(spec, region).await else {
|
||||
continue;
|
||||
};
|
||||
if let Some(finding) = ground(spec, region, &verdict, repo_id) {
|
||||
findings.push(finding);
|
||||
}
|
||||
@@ -50,6 +54,7 @@ impl<J: ControlJudge> SemanticControlChecker<J> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::controls::JudgeError;
|
||||
use compliance_core::control_check::{ControlCheckSpec, LlmVerdict};
|
||||
use compliance_core::models::finding::Severity;
|
||||
|
||||
@@ -57,8 +62,12 @@ mod tests {
|
||||
verdict: LlmVerdict,
|
||||
}
|
||||
impl ControlJudge for StubJudge {
|
||||
async fn judge(&self, _s: &ControlCheckSpec, _r: &CandidateRegion) -> LlmVerdict {
|
||||
self.verdict.clone()
|
||||
async fn judge(
|
||||
&self,
|
||||
_s: &ControlCheckSpec,
|
||||
_r: &CandidateRegion,
|
||||
) -> Result<LlmVerdict, JudgeError> {
|
||||
Ok(self.verdict.clone())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
//! finding grounds to the surface snippet, so nothing fabricated survives.
|
||||
//!
|
||||
//! Retrieval is intentionally cheap and bounded: keyword match + a fixed window,
|
||||
//! capped per control to keep the downstream LLM cost predictable.
|
||||
//! capped per control to keep the downstream LLM cost predictable. C and C++
|
||||
//! firmware is read too, without its vendor SDK (HAL, CMSIS, middleware), which
|
||||
//! would otherwise fill the cap with code the customer does not own.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
@@ -26,7 +28,7 @@ pub struct Surface {
|
||||
/// the hybrid coverage (the pattern-expressible half is custom semgrep rules).
|
||||
pub const SURFACES: &[Surface] = &[
|
||||
Surface {
|
||||
control_id: "cra-ai-6", // Integritaetspruefung
|
||||
control_id: "cra-ai-6", // Integritätsprüfung
|
||||
terms: &[
|
||||
"checksum",
|
||||
"sha256",
|
||||
@@ -34,6 +36,7 @@ pub const SURFACES: &[Surface] = &[
|
||||
"hmac",
|
||||
"integrity",
|
||||
"verify",
|
||||
"crc32",
|
||||
],
|
||||
},
|
||||
Surface {
|
||||
@@ -60,29 +63,61 @@ pub const SURFACES: &[Surface] = &[
|
||||
},
|
||||
Surface {
|
||||
control_id: "cra-ai-24", // Security-Logging
|
||||
terms: &["login", "authorize", "permission", "role", "admin", "audit"],
|
||||
terms: &[
|
||||
"login",
|
||||
"authorize",
|
||||
"permission",
|
||||
"role",
|
||||
"admin",
|
||||
"audit",
|
||||
"syslog",
|
||||
],
|
||||
},
|
||||
Surface {
|
||||
control_id: "cra-ai-27", // Log-Integritaet und -Aufbewahrung
|
||||
terms: &["logging", "logger", "getlogger", "audit_log"],
|
||||
control_id: "cra-ai-27", // Log-Integrität und -Aufbewahrung
|
||||
terms: &["logging", "logger", "getlogger", "audit_log", "syslog"],
|
||||
},
|
||||
Surface {
|
||||
control_id: "cra-ai-28", // Sichere Update-Mechanismen
|
||||
terms: &["update", "upgrade", "download", "firmware"],
|
||||
terms: &[
|
||||
"update",
|
||||
"upgrade",
|
||||
"download",
|
||||
"firmware",
|
||||
"bootloader",
|
||||
"ota_",
|
||||
"hal_flash",
|
||||
],
|
||||
},
|
||||
Surface {
|
||||
control_id: "cra-ai-29", // Update-Authentizitaet
|
||||
terms: &["update", "signature", "verify", "pubkey", "certificate"],
|
||||
control_id: "cra-ai-29", // Update-Authentizität
|
||||
terms: &[
|
||||
"update",
|
||||
"signature",
|
||||
"verify",
|
||||
"pubkey",
|
||||
"certificate",
|
||||
"ecdsa",
|
||||
"secure_boot",
|
||||
],
|
||||
},
|
||||
Surface {
|
||||
control_id: "cra-ai-30", // Update-Integritaet
|
||||
terms: &["update", "checksum", "digest", "integrity", "verify"],
|
||||
control_id: "cra-ai-30", // Update-Integrität
|
||||
terms: &[
|
||||
"update",
|
||||
"checksum",
|
||||
"digest",
|
||||
"integrity",
|
||||
"verify",
|
||||
"crc32",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
/// Source file extensions worth reading (skip binaries/assets/lockfiles).
|
||||
const CODE_EXTS: &[&str] = &[
|
||||
"py", "js", "ts", "tsx", "jsx", "go", "java", "rb", "php", "rs", "cs", "kt",
|
||||
"py", "js", "ts", "tsx", "jsx", "go", "java", "rb", "php", "rs", "cs", "kt", "c", "h", "cc",
|
||||
"cpp", "hpp",
|
||||
];
|
||||
/// Directories never worth walking.
|
||||
const SKIP_DIRS: &[&str] = &[
|
||||
@@ -103,12 +138,13 @@ const MAX_REGIONS_PER_CONTROL: usize = 8;
|
||||
const MAX_FILE_BYTES: u64 = 512 * 1024;
|
||||
|
||||
/// Deterministically retrieve up to [`MAX_REGIONS_PER_CONTROL`] code regions in
|
||||
/// `repo_path` whose lines mention any of `terms`. Hits close together within a
|
||||
/// file are merged into one region; results are capped to bound LLM cost.
|
||||
pub fn retrieve(repo_path: &Path, terms: &[&str]) -> Vec<CandidateRegion> {
|
||||
/// `repo_path` whose lines mention any of `terms`, outside the `excluded`
|
||||
/// (vendor) directories. Hits close together within a file are merged into one
|
||||
/// region; results are capped to bound LLM cost.
|
||||
pub fn retrieve(repo_path: &Path, terms: &[&str], excluded: &[String]) -> Vec<CandidateRegion> {
|
||||
let lowered: Vec<String> = terms.iter().map(|t| t.to_lowercase()).collect();
|
||||
let mut regions = Vec::new();
|
||||
for entry in walk(repo_path) {
|
||||
for entry in walk(repo_path, excluded) {
|
||||
if regions.len() >= MAX_REGIONS_PER_CONTROL {
|
||||
break;
|
||||
}
|
||||
@@ -173,15 +209,17 @@ fn has_code_ext(path: &Path) -> bool {
|
||||
.is_some_and(|e| CODE_EXTS.contains(&e))
|
||||
}
|
||||
|
||||
fn walk(root: &Path) -> Vec<walkdir::DirEntry> {
|
||||
walkdir::WalkDir::new(root)
|
||||
.into_iter()
|
||||
.filter_entry(|e| {
|
||||
let name = e.file_name().to_string_lossy();
|
||||
!SKIP_DIRS.contains(&name.as_ref())
|
||||
})
|
||||
.filter_map(|e| e.ok())
|
||||
.collect()
|
||||
/// Every entry under `root` outside the `excluded` directories and
|
||||
/// [`SKIP_DIRS`].
|
||||
fn walk<'a>(
|
||||
root: &'a Path,
|
||||
excluded: &'a [String],
|
||||
) -> impl Iterator<Item = walkdir::DirEntry> + 'a {
|
||||
crate::pipeline::vendor::walk_outside(root, excluded).filter(|e| {
|
||||
!e.path()
|
||||
.components()
|
||||
.any(|c| SKIP_DIRS.contains(&c.as_os_str().to_string_lossy().as_ref()))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -231,7 +269,7 @@ mod tests {
|
||||
"app/auth.py",
|
||||
"import x\n\n\n\n\n\n\ndef login(u, p):\n return check(u, p)\n",
|
||||
);
|
||||
let regions = retrieve(&dir, terms_for("cra-ai-11"));
|
||||
let regions = retrieve(&dir, terms_for("cra-ai-11"), &[]);
|
||||
assert_eq!(regions.len(), 1);
|
||||
assert!(regions[0].content.contains("def login"));
|
||||
assert_eq!(regions[0].file, "app/auth.py");
|
||||
@@ -244,7 +282,31 @@ mod tests {
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
write(&dir, "README.md", "login and password and audit\n"); // not code ext
|
||||
write(&dir, "node_modules/pkg/index.js", "function login() {}\n"); // vendored
|
||||
assert!(retrieve(&dir, terms_for("cra-ai-11")).is_empty());
|
||||
assert!(retrieve(&dir, terms_for("cra-ai-11"), &[]).is_empty());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn firmware_update_code_is_read_but_not_the_vendor_hal() {
|
||||
let dir = std::env::temp_dir().join(format!("surface-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
write(
|
||||
&dir,
|
||||
"Core/Src/ota.c",
|
||||
"#include \"ota.h\"\n\n\n\n\n\n\nint ota_apply(const uint8_t *image) {\n return HAL_FLASH_Program(0, 0, 0);\n}\n",
|
||||
);
|
||||
write(
|
||||
&dir,
|
||||
"Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_flash.c",
|
||||
"HAL_StatusTypeDef HAL_FLASH_Program(void) { return 0; }\n",
|
||||
);
|
||||
write(&dir, "Core/Inc/main.h", "#pragma once\n");
|
||||
|
||||
let vendor = crate::pipeline::vendor::vendor_dirs(&dir);
|
||||
let regions = retrieve(&dir, terms_for("cra-ai-28"), &vendor);
|
||||
|
||||
assert_eq!(regions.len(), 1, "{regions:?}");
|
||||
assert_eq!(regions[0].file, "Core/Src/ota.c");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
//! Triage step: confirm/refute a deterministic tool finding against the controls
|
||||
//! it maps to (via the `control-map` LUT), grounding the judgment.
|
||||
//!
|
||||
//! This is where the LLM finally enters — as a **false-positive filter over tool
|
||||
//! output**, never as the detector (the ZeroFalse / IRIS pattern). A tool
|
||||
//! (semgrep, gitleaks, syft/osv) detects deterministically; `controls_for(tool,
|
||||
//! cwe)` attaches the finding to the control(s) it's evidence for; the grounded
|
||||
//! judge then confirms or refutes each, and only judgments anchored to real code
|
||||
//! survive.
|
||||
//! This is where the LLM finally enters — as a **reviewer of the mapping**, never
|
||||
//! as the detector (the ZeroFalse / IRIS pattern). A tool (semgrep, gitleaks,
|
||||
//! syft/osv) detects deterministically; `controls_for(tool, cwe)` attaches the
|
||||
//! finding to the control(s) it's evidence for; the grounded judge then confirms
|
||||
//! or refutes each, and only judgments anchored to real code count.
|
||||
//!
|
||||
//! The judge decides the mapping, never whether the finding exists: a refuted
|
||||
//! finding goes to a person for review, and one without a verdict is left as it
|
||||
//! is.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use compliance_core::control_check::{ground, CandidateRegion, ControlCheckSpec};
|
||||
@@ -24,8 +28,12 @@ pub enum TriageOutcome {
|
||||
/// Maps to controls and the grounded judge confirmed at least one — keep the
|
||||
/// finding and tag it with these control ids.
|
||||
Confirmed(Vec<String>),
|
||||
/// Maps to controls but the judge grounded none — treat as a false positive.
|
||||
FalsePositive,
|
||||
/// Maps to controls, and the judge refuted every one it could check — a
|
||||
/// person should look at it.
|
||||
NeedsReview,
|
||||
/// Maps to controls, but no verdict was reached (model unavailable, answer
|
||||
/// unreadable, or no requirement text) — leave the finding as it is.
|
||||
Undecided,
|
||||
}
|
||||
|
||||
/// Triages tool findings against the control map, confirming with a grounded judge.
|
||||
@@ -47,7 +55,7 @@ impl<J: ControlJudge> ControlTriage<J> {
|
||||
// Match by CWE (off-the-shelf findings) and/or rule id (our custom
|
||||
// detectors, which carry no LUT-bound CWE). A finding with neither is
|
||||
// simply unmapped.
|
||||
let mapped = self.map.controls_for_finding(
|
||||
let mapped = self.map.bindings_for_finding(
|
||||
&finding.scanner,
|
||||
finding.cwe.as_deref(),
|
||||
finding.rule_id.as_deref(),
|
||||
@@ -57,22 +65,46 @@ impl<J: ControlJudge> ControlTriage<J> {
|
||||
}
|
||||
|
||||
let mut confirmed = Vec::new();
|
||||
for entry in mapped {
|
||||
let mut refuted = 0_usize;
|
||||
let mut undecided = 0_usize;
|
||||
for (entry, binding) in mapped {
|
||||
let Some(spec) = self.specs.get(&entry.control) else {
|
||||
undecided += 1;
|
||||
continue;
|
||||
};
|
||||
let verdict = self.judge.judge(spec, region).await;
|
||||
// The verdict only counts if it grounds to real code in the region.
|
||||
if ground(spec, region, &verdict, &finding.repo_id).is_some() {
|
||||
confirmed.push(entry.control.clone());
|
||||
// The binding's own check text, where it has one: what this
|
||||
// tool's finding means for the control, not the control's prose.
|
||||
let spec = match &binding.check {
|
||||
Some(check) => Cow::Owned(ControlCheckSpec {
|
||||
requirement: check.clone(),
|
||||
..spec.clone()
|
||||
}),
|
||||
None => Cow::Borrowed(spec),
|
||||
};
|
||||
match self.judge.judge(&spec, region).await {
|
||||
// The verdict only counts if it grounds to real code in the region.
|
||||
Ok(verdict) if ground(&spec, region, &verdict, &finding.repo_id).is_some() => {
|
||||
confirmed.push(entry.control.clone());
|
||||
}
|
||||
Ok(_) => refuted += 1,
|
||||
Err(_) => undecided += 1,
|
||||
}
|
||||
}
|
||||
|
||||
if confirmed.is_empty() {
|
||||
TriageOutcome::FalsePositive
|
||||
} else {
|
||||
TriageOutcome::Confirmed(confirmed)
|
||||
}
|
||||
outcome(confirmed, refuted, undecided)
|
||||
}
|
||||
}
|
||||
|
||||
/// The outcome from the per-control results: any confirmation wins; a
|
||||
/// refutation needs every checkable control refuted, and a single missing
|
||||
/// verdict leaves the finding undecided.
|
||||
fn outcome(confirmed: Vec<String>, refuted: usize, undecided: usize) -> TriageOutcome {
|
||||
if !confirmed.is_empty() {
|
||||
TriageOutcome::Confirmed(confirmed)
|
||||
} else if undecided == 0 && refuted > 0 {
|
||||
TriageOutcome::NeedsReview
|
||||
} else {
|
||||
TriageOutcome::Undecided
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,12 +115,48 @@ mod tests {
|
||||
use compliance_core::models::finding::Severity;
|
||||
use compliance_core::models::scan::ScanType;
|
||||
|
||||
use crate::controls::JudgeError;
|
||||
|
||||
struct StubJudge {
|
||||
verdict: LlmVerdict,
|
||||
}
|
||||
impl ControlJudge for StubJudge {
|
||||
async fn judge(&self, _s: &ControlCheckSpec, _r: &CandidateRegion) -> LlmVerdict {
|
||||
self.verdict.clone()
|
||||
async fn judge(
|
||||
&self,
|
||||
_s: &ControlCheckSpec,
|
||||
_r: &CandidateRegion,
|
||||
) -> Result<LlmVerdict, JudgeError> {
|
||||
Ok(self.verdict.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// A judge that remembers the requirement text it was asked about.
|
||||
#[derive(Default)]
|
||||
struct RecordingJudge {
|
||||
asked: std::sync::Mutex<Vec<String>>,
|
||||
}
|
||||
impl ControlJudge for RecordingJudge {
|
||||
async fn judge(
|
||||
&self,
|
||||
spec: &ControlCheckSpec,
|
||||
_r: &CandidateRegion,
|
||||
) -> Result<LlmVerdict, JudgeError> {
|
||||
if let Ok(mut asked) = self.asked.lock() {
|
||||
asked.push(spec.requirement.clone());
|
||||
}
|
||||
Err(JudgeError::Unavailable("recording only".into()))
|
||||
}
|
||||
}
|
||||
|
||||
/// A judge that never answers, as when the model is down.
|
||||
struct DownJudge;
|
||||
impl ControlJudge for DownJudge {
|
||||
async fn judge(
|
||||
&self,
|
||||
_s: &ControlCheckSpec,
|
||||
_r: &CandidateRegion,
|
||||
) -> Result<LlmVerdict, JudgeError> {
|
||||
Err(JudgeError::Unavailable("connection refused".into()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,8 +216,22 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refuted_mapped_finding_is_false_positive() {
|
||||
// Maps to cra-ai-8, but the judge doesn't confirm (no violation) → FP.
|
||||
async fn refuted_mapped_finding_needs_review() {
|
||||
// CWE-798 maps to cra-ai-8, 9 and 16; the judge confirms none of them,
|
||||
// so a person decides.
|
||||
let mut specs = specs();
|
||||
for id in ["cra-ai-9", "cra-ai-16"] {
|
||||
specs.insert(
|
||||
id.to_string(),
|
||||
ControlCheckSpec {
|
||||
control_id: id.into(),
|
||||
title: id.into(),
|
||||
requirement: "requirement".into(),
|
||||
default_cwe: None,
|
||||
severity: Severity::Medium,
|
||||
},
|
||||
);
|
||||
}
|
||||
let triage = ControlTriage::new(
|
||||
StubJudge {
|
||||
verdict: LlmVerdict {
|
||||
@@ -160,10 +242,73 @@ mod tests {
|
||||
},
|
||||
},
|
||||
ControlMap::cra().unwrap(),
|
||||
specs(),
|
||||
specs,
|
||||
);
|
||||
let out = triage.triage(&semgrep_finding("CWE-798"), ®ion()).await;
|
||||
assert_eq!(out, TriageOutcome::FalsePositive);
|
||||
assert_eq!(out, TriageOutcome::NeedsReview);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_judge_that_is_down_decides_nothing() {
|
||||
let triage = ControlTriage::new(DownJudge, ControlMap::cra().unwrap(), specs());
|
||||
let out = triage.triage(&semgrep_finding("CWE-798"), ®ion()).await;
|
||||
assert_eq!(out, TriageOutcome::Undecided);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_control_without_requirement_text_decides_nothing() {
|
||||
// cra-ai-8 maps, but the catalog has no spec for it: nothing was judged.
|
||||
let triage = ControlTriage::new(
|
||||
StubJudge {
|
||||
verdict: LlmVerdict {
|
||||
violates: false,
|
||||
snippet: String::new(),
|
||||
cwe: None,
|
||||
confidence: 0.1,
|
||||
},
|
||||
},
|
||||
ControlMap::cra().unwrap(),
|
||||
HashMap::new(),
|
||||
);
|
||||
let out = triage.triage(&semgrep_finding("CWE-798"), ®ion()).await;
|
||||
assert_eq!(out, TriageOutcome::Undecided);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_judge_reads_the_bindings_check_not_the_controls_prose() {
|
||||
// cra-ai-16's catalog prose is about key storage; a rand() finding is
|
||||
// judged against what that finding means instead.
|
||||
let mut specs = HashMap::new();
|
||||
specs.insert(
|
||||
"cra-ai-16".to_string(),
|
||||
ControlCheckSpec {
|
||||
control_id: "cra-ai-16".into(),
|
||||
title: "Key management".into(),
|
||||
requirement: "Keys in an HSM or vault".into(),
|
||||
default_cwe: None,
|
||||
severity: Severity::High,
|
||||
},
|
||||
);
|
||||
let triage =
|
||||
ControlTriage::new(RecordingJudge::default(), ControlMap::cra().unwrap(), specs);
|
||||
let mut f = semgrep_finding("CWE-338");
|
||||
f.rule_id = Some("cra-ai-16-c-predictable-random".into());
|
||||
|
||||
let _ = triage.triage(&f, ®ion()).await;
|
||||
|
||||
let asked = triage.judge.asked.lock().unwrap().clone();
|
||||
assert_eq!(asked.len(), 1, "{asked:?}");
|
||||
assert!(asked[0].contains("rand()"), "{asked:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_missing_verdict_keeps_a_refutation_undecided() {
|
||||
assert_eq!(outcome(vec![], 2, 0), TriageOutcome::NeedsReview);
|
||||
assert_eq!(outcome(vec![], 1, 1), TriageOutcome::Undecided);
|
||||
assert_eq!(
|
||||
outcome(vec!["cra-ai-8".into()], 1, 1),
|
||||
TriageOutcome::Confirmed(vec!["cra-ai-8".into()])
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -107,6 +107,22 @@ impl DatabasePool {
|
||||
Ok(db)
|
||||
}
|
||||
|
||||
/// A read-only handle to a tenant database **without** creating anything.
|
||||
///
|
||||
/// [`Self::for_tenant_id`] ensures indexes, and `createIndex` materializes
|
||||
/// the database and its collections. On an authenticated path that is what
|
||||
/// you want; on an unauthenticated one it is a write primitive: a webhook
|
||||
/// POST naming any `tenant_id` conjured `<prefix>_<tenant_id>` and its
|
||||
/// indexes before anything checked the tenant existed. Reads through this
|
||||
/// handle create nothing — a lookup in an unknown tenant simply finds
|
||||
/// nothing, which the caller turns into a 404.
|
||||
///
|
||||
/// Use it for the lookup that *establishes* the caller's right to be here;
|
||||
/// switch to [`Self::for_tenant_id`] once that has succeeded.
|
||||
pub fn for_existing_tenant_id(&self, tenant_id: &str) -> Database {
|
||||
Database::from_database(self.client.database(&self.tenant_db_name(tenant_id)))
|
||||
}
|
||||
|
||||
/// Compute the Mongo database name for a tenant. Public for tests
|
||||
/// and tenant offboarding (`pool.client().database(name).drop()`).
|
||||
///
|
||||
@@ -196,6 +212,21 @@ impl DatabasePool {
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Every tenant database that exists, opened without creating anything
|
||||
/// (like [`Self::for_existing_tenant_id`]). Works from the database names
|
||||
/// themselves, so hash-fallback databases are included, which
|
||||
/// [`Self::list_tenant_ids`] cannot do. Skips the admin database.
|
||||
pub async fn existing_tenant_dbs(&self) -> Result<Vec<Database>, AgentError> {
|
||||
let admin = self.admin_db_name();
|
||||
Ok(self
|
||||
.list_tenant_db_names()
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter(|name| *name != admin)
|
||||
.map(|name| Database::from_database(self.client.database(&name)))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Drop the database for a specific tenant. Used by GDPR delete
|
||||
/// and tenant offboarding. Idempotent — dropping a non-existent
|
||||
/// database is a no-op at the driver level.
|
||||
@@ -447,6 +478,15 @@ impl Database {
|
||||
)
|
||||
.await?;
|
||||
|
||||
// onboarded_targets: multikey on project ids (the `?project=` filter)
|
||||
self.onboarded_targets()
|
||||
.create_index(
|
||||
IndexModel::builder()
|
||||
.keys(doc! { "project_ids": 1 })
|
||||
.build(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
// onboarded_targets: multikey on artifact kind
|
||||
self.onboarded_targets()
|
||||
.create_index(
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
//! Seed a tenant with the curated demo targets.
|
||||
//!
|
||||
//! The demo manifest ([`crate::fixtures`]) is compiled into the agent, so a
|
||||
//! prospect on a fresh trial can populate their workspace from the dashboard
|
||||
//! ("Add demo targets") instead of running the ops curl script, and the nightly
|
||||
//! `demo/reset` can repopulate the sales tenant with no user token in sight.
|
||||
//!
|
||||
//! Everything runs through [`crate::targets`] — the same create → upload →
|
||||
//! detect path the onboarding API takes — so seeded targets are ordinary
|
||||
//! targets: same records, same `target.added` usage events, same scans.
|
||||
|
||||
use mongodb::bson::{doc, oid::ObjectId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use compliance_core::models::ScanTrigger;
|
||||
|
||||
use crate::agent::ComplianceAgent;
|
||||
use crate::database::Database;
|
||||
use crate::fixtures::{DemoTarget, DemoTargets, FixtureError};
|
||||
use crate::targets;
|
||||
|
||||
/// What the caller asked to seed.
|
||||
#[derive(Debug, Clone, Default, Deserialize)]
|
||||
pub struct SeedRequest {
|
||||
/// Manifest keys to seed; empty seeds every target.
|
||||
#[serde(default)]
|
||||
pub names: Vec<String>,
|
||||
/// Re-run the scan for a target that already exists.
|
||||
#[serde(default)]
|
||||
pub rescan: bool,
|
||||
}
|
||||
|
||||
/// Per-target result. `status` is `queued` (created, scan started), `exists`
|
||||
/// (already there, nothing done) or `failed`.
|
||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
|
||||
pub struct SeededTarget {
|
||||
/// The manifest key.
|
||||
pub name: String,
|
||||
pub target_id: Option<String>,
|
||||
/// Always `None` today: the scan is started in the background and its
|
||||
/// `ScanRun` id does not exist yet when this returns.
|
||||
pub scan_id: Option<String>,
|
||||
pub status: String,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
impl SeededTarget {
|
||||
const QUEUED: &'static str = "queued";
|
||||
const EXISTS: &'static str = "exists";
|
||||
const FAILED: &'static str = "failed";
|
||||
|
||||
fn queued(key: &str, target_id: String) -> Self {
|
||||
Self {
|
||||
name: key.to_string(),
|
||||
target_id: Some(target_id),
|
||||
scan_id: None,
|
||||
status: Self::QUEUED.to_string(),
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn exists(key: &str, target_id: String) -> Self {
|
||||
Self {
|
||||
name: key.to_string(),
|
||||
target_id: Some(target_id),
|
||||
scan_id: None,
|
||||
status: Self::EXISTS.to_string(),
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn failed(key: &str, err: impl std::fmt::Display) -> Self {
|
||||
Self {
|
||||
name: key.to_string(),
|
||||
target_id: None,
|
||||
scan_id: None,
|
||||
status: Self::FAILED.to_string(),
|
||||
error: Some(err.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One manifest entry as the dashboard lists it before seeding.
|
||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
|
||||
pub struct DemoTargetSummary {
|
||||
/// Manifest key — what [`SeedRequest::names`] takes.
|
||||
pub key: String,
|
||||
/// Display name, prefix included (what the target is called once seeded).
|
||||
pub name: String,
|
||||
/// Target type token (`plc_sps`, `backend_service`, …).
|
||||
pub kind: String,
|
||||
pub description: Option<String>,
|
||||
/// True when no required artifact needs a live endpoint — the only kind of
|
||||
/// target a `source_only` deployment can scan end to end.
|
||||
pub source_only: bool,
|
||||
}
|
||||
|
||||
/// The bundled manifest, summarised for the dashboard.
|
||||
pub fn manifest_summary() -> Result<Vec<DemoTargetSummary>, FixtureError> {
|
||||
let manifest = DemoTargets::bundled()?;
|
||||
Ok(manifest
|
||||
.targets
|
||||
.iter()
|
||||
.map(|t| DemoTargetSummary {
|
||||
key: t.key.clone(),
|
||||
name: manifest.full_name(t),
|
||||
kind: format!("{:?}", t.target_type).to_lowercase(),
|
||||
description: t.description.clone(),
|
||||
source_only: t.source_only(),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Seed `tenant_id` with the selected demo targets and start a scan for each
|
||||
/// newly created one. Never fails as a whole: a target that cannot be seeded is
|
||||
/// reported as `failed` and the rest continue.
|
||||
pub async fn seed_tenant(
|
||||
agent: &ComplianceAgent,
|
||||
db: &Database,
|
||||
tenant_id: &str,
|
||||
req: &SeedRequest,
|
||||
) -> Result<Vec<SeededTarget>, FixtureError> {
|
||||
let manifest = DemoTargets::bundled()?;
|
||||
let selected = manifest.select(&req.names)?;
|
||||
let mut out = Vec::with_capacity(selected.len());
|
||||
for t in selected {
|
||||
let full_name = manifest.full_name(t);
|
||||
out.push(
|
||||
match seed_one(agent, db, tenant_id, t, &full_name, req.rescan).await {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
tracing::warn!(tenant_id, key = %t.key, error = %e, "demo seed failed");
|
||||
SeededTarget::failed(&t.key, e)
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
async fn seed_one(
|
||||
agent: &ComplianceAgent,
|
||||
db: &Database,
|
||||
tenant_id: &str,
|
||||
demo: &DemoTarget,
|
||||
full_name: &str,
|
||||
rescan: bool,
|
||||
) -> Result<SeededTarget, crate::error::AgentError> {
|
||||
// Idempotent by display name: the seeder owns the "Demo · " prefix, so a
|
||||
// second call finds its own targets rather than duplicating them.
|
||||
if let Some(existing) = db
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "name": full_name })
|
||||
.await?
|
||||
{
|
||||
let id = existing.id.map(|i| i.to_hex()).unwrap_or_default();
|
||||
if !rescan {
|
||||
return Ok(SeededTarget::exists(&demo.key, id));
|
||||
}
|
||||
spawn_scan(agent, tenant_id, &id);
|
||||
return Ok(SeededTarget::queued(&demo.key, id));
|
||||
}
|
||||
|
||||
// Reference artifacts (git repo, live URL, …) go in at creation; uploads
|
||||
// need the target id for their blob path, so they are attached after.
|
||||
let mut target =
|
||||
compliance_core::models::OnboardedTarget::new(full_name.to_string(), demo.target_type);
|
||||
target.description = demo.description.clone();
|
||||
for a in demo.artifacts.iter().filter(|a| !a.is_upload()) {
|
||||
match a.resolved_source_ref() {
|
||||
Some(source_ref) => target.artifacts.push(targets::reference_artifact(
|
||||
a.kind,
|
||||
source_ref,
|
||||
a.branch.clone(),
|
||||
a.plc_format,
|
||||
)),
|
||||
// Optional env-only artifacts (a live PLC, a firmware image) are
|
||||
// simply absent where that infrastructure is not deployed.
|
||||
None if a.optional || a.env_only() => continue,
|
||||
None => {
|
||||
return Err(crate::error::AgentError::Other(format!(
|
||||
"demo target {}: artifact {:?} has no source_ref",
|
||||
demo.key, a.kind
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let target = targets::create_target(agent, db, tenant_id, target).await?;
|
||||
let oid: ObjectId = target
|
||||
.id
|
||||
.ok_or_else(|| crate::error::AgentError::Other("target insert returned no id".into()))?;
|
||||
let target_id = oid.to_hex();
|
||||
|
||||
for a in demo.artifacts.iter().filter(|a| a.is_upload()) {
|
||||
let content = a
|
||||
.upload_content()
|
||||
.map_err(|e| crate::error::AgentError::Other(e.to_string()))?;
|
||||
let Some(content) = content else {
|
||||
if a.optional || a.env_only() {
|
||||
continue;
|
||||
}
|
||||
return Err(crate::error::AgentError::Other(format!(
|
||||
"demo target {}: upload fixture missing",
|
||||
demo.key
|
||||
)));
|
||||
};
|
||||
let stored = targets::store_upload(agent, &target_id, &content.filename, &content.bytes)?;
|
||||
let Some(artifact) = targets::uploaded_artifact(
|
||||
a.kind,
|
||||
a.plc_format,
|
||||
&content.filename,
|
||||
&stored,
|
||||
content.bytes.len() as u64,
|
||||
) else {
|
||||
return Err(crate::error::AgentError::Other(format!(
|
||||
"demo target {}: {:?} is not an upload kind",
|
||||
demo.key, a.kind
|
||||
)));
|
||||
};
|
||||
targets::attach_artifact(db, oid, &artifact).await?;
|
||||
}
|
||||
|
||||
targets::detect_target(db, oid).await?;
|
||||
spawn_scan(agent, tenant_id, &target_id);
|
||||
Ok(SeededTarget::queued(&demo.key, target_id))
|
||||
}
|
||||
|
||||
/// Start a scan in the background, exactly as the manual "Run scan" button
|
||||
/// does. The scan run is created inside the pipeline, so there is no id to
|
||||
/// return here.
|
||||
fn spawn_scan(agent: &ComplianceAgent, tenant_id: &str, target_id: &str) {
|
||||
let agent = agent.clone();
|
||||
let tenant_id = tenant_id.to_string();
|
||||
let target_id = target_id.to_string();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = agent
|
||||
.run_target_scan(&tenant_id, &target_id, ScanTrigger::Manual)
|
||||
.await
|
||||
{
|
||||
tracing::error!(tenant_id, target_id, error = %e, "demo seed scan failed");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn summary_lists_the_bundled_manifest() {
|
||||
let s = manifest_summary().expect("bundled manifest");
|
||||
assert!(!s.is_empty());
|
||||
// Every shipped demo target is scannable without live infrastructure.
|
||||
assert!(s.iter().all(|t| t.source_only), "{s:?}");
|
||||
assert!(s.iter().all(|t| t.name.starts_with("Demo · ")), "{s:?}");
|
||||
let keys: Vec<&str> = s.iter().map(|t| t.key.as_str()).collect();
|
||||
assert!(keys.contains(&"git-cra-vuln-demo"), "{keys:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seed_request_defaults_to_everything_without_rescan() {
|
||||
let r: SeedRequest = serde_json::from_str("{}").expect("empty body");
|
||||
assert!(r.names.is_empty());
|
||||
assert!(!r.rescan);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_keys_are_rejected_before_anything_is_created() {
|
||||
let manifest = DemoTargets::bundled().expect("bundled");
|
||||
let err = manifest
|
||||
.select(&["nope".to_string()])
|
||||
.expect_err("unknown key");
|
||||
assert!(matches!(err, FixtureError::UnknownKeys(_)), "{err:?}");
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
use compliance_core::models::RunErrorCode;
|
||||
use compliance_core::CoreError;
|
||||
use thiserror::Error;
|
||||
|
||||
@@ -27,13 +28,59 @@ pub enum AgentError {
|
||||
#[error("Configuration error: {0}")]
|
||||
Config(String),
|
||||
|
||||
#[error(transparent)]
|
||||
Secret(#[from] crate::secrets::SecretError),
|
||||
|
||||
#[error("Dynamic-execution error: {0}")]
|
||||
Exec(#[from] werkbank_exec::ExecError),
|
||||
|
||||
/// An uploaded archive is password-protected and no password is set.
|
||||
#[error("the archive is password-protected; set its password on the target")]
|
||||
ArchivePasswordRequired,
|
||||
|
||||
/// The password set for an uploaded archive does not open it.
|
||||
#[error("the archive password set on the target does not open it")]
|
||||
ArchivePasswordWrong,
|
||||
|
||||
#[error("{0}")]
|
||||
Other(String),
|
||||
}
|
||||
|
||||
impl AgentError {
|
||||
/// What a scan run that stopped on this error records: a stable code and
|
||||
/// a plain English sentence, never the error's own text, which can hold
|
||||
/// server paths and internal details (it goes to the log instead).
|
||||
pub fn run_failure(&self) -> (RunErrorCode, &'static str) {
|
||||
match self {
|
||||
Self::Git(_) => (
|
||||
RunErrorCode::RepositoryUnreachable,
|
||||
"the repository could not be cloned or fetched",
|
||||
),
|
||||
Self::ArchivePasswordRequired => (
|
||||
RunErrorCode::ArchivePasswordRequired,
|
||||
"the archive is password-protected and no password is set",
|
||||
),
|
||||
Self::ArchivePasswordWrong => (
|
||||
RunErrorCode::ArchivePasswordWrong,
|
||||
"the stored password does not open the archive",
|
||||
),
|
||||
Self::Core(_)
|
||||
| Self::Database(_)
|
||||
| Self::Http(_)
|
||||
| Self::Json(_)
|
||||
| Self::Io(_)
|
||||
| Self::Scheduler(_)
|
||||
| Self::Config(_)
|
||||
| Self::Secret(_)
|
||||
| Self::Exec(_)
|
||||
| Self::Other(_) => (
|
||||
RunErrorCode::Internal,
|
||||
"the scan stopped because of an internal error",
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<AgentError> for axum::http::StatusCode {
|
||||
fn from(err: AgentError) -> Self {
|
||||
match err {
|
||||
@@ -42,3 +89,23 @@ impl From<AgentError> for axum::http::StatusCode {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_failed_run_records_no_raw_error() {
|
||||
let io = AgentError::Io(std::io::Error::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
"/data/compliance-scanner/artifacts/work/65f0/a1: no such file",
|
||||
));
|
||||
let (code, message) = io.run_failure();
|
||||
assert_eq!(code, RunErrorCode::Internal);
|
||||
assert!(!message.contains('/'), "{message}");
|
||||
assert_eq!(
|
||||
AgentError::ArchivePasswordWrong.run_failure().0,
|
||||
RunErrorCode::ArchivePasswordWrong
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
//! Where a target stands against each CRA Annex I requirement (#283).
|
||||
//!
|
||||
//! Every control of the map gets exactly one state, so nothing is silently
|
||||
//! missing: violated (with the findings that say so), no violation found,
|
||||
//! not assessed yet, or not checkable in code at all (a design property,
|
||||
//! which the breakpilot-compliance process covers).
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use compliance_core::models::{Finding, FindingStatus};
|
||||
use control_map::{ControlMap, Coverage};
|
||||
|
||||
/// A control's state for one target.
|
||||
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ControlState {
|
||||
/// Open findings are evidence against it.
|
||||
NotSatisfied,
|
||||
/// Checkable in code, scanned, and nothing is against it.
|
||||
NoViolationFound,
|
||||
/// Checkable in code, but not by this scan: none completed yet, no tool
|
||||
/// checks it, or none of its rules covers the scanned code's languages.
|
||||
NotAssessed,
|
||||
/// A design property no code scan can decide (breakpilot-compliance).
|
||||
NotCodeCheckable,
|
||||
}
|
||||
|
||||
/// Why a control that can be checked in code was not assessed.
|
||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum NotAssessedReason {
|
||||
/// No scan of the target has completed yet.
|
||||
NotScanned,
|
||||
/// Checkable in code, but no tool of ours checks it yet.
|
||||
NoTool,
|
||||
/// The scan found code in `languages`, but none of the control's rules
|
||||
/// covers them.
|
||||
NoRuleForLanguages { languages: Vec<String> },
|
||||
/// The scan predates language detection; a new scan tells.
|
||||
LanguagesUnknown,
|
||||
/// A tool that checks it did not complete in the last scan (semgrep,
|
||||
/// cppcheck, or the CVE lookup), so nothing can be claimed either way.
|
||||
ToolFailed { tools: Vec<String> },
|
||||
/// The control is checked on the target's components (the SBOM and its
|
||||
/// CVE lookup), and the scan found none: an empty SBOM proves nothing.
|
||||
NoComponents,
|
||||
}
|
||||
|
||||
/// The tools that check a target's components rather than its code.
|
||||
const COMPONENT_TOOLS: [&str; 2] = ["syft", "osv"];
|
||||
|
||||
/// The tool a skipped stage of a scan run stands for, when that stage is one
|
||||
/// a control's binding relies on.
|
||||
pub fn tool_of_stage(stage: &str) -> Option<&'static str> {
|
||||
match stage {
|
||||
"sast" => Some("semgrep"),
|
||||
"sast_c_cpp" => Some("cppcheck"),
|
||||
"cve_lookup" => Some("osv"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A finding as the compliance view lists it.
|
||||
#[derive(Debug, Clone, Serialize, PartialEq)]
|
||||
pub struct FindingRef {
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub severity: String,
|
||||
pub status: String,
|
||||
pub location: Option<String>,
|
||||
}
|
||||
|
||||
/// One control and the target's state against it.
|
||||
#[derive(Debug, Clone, Serialize, PartialEq)]
|
||||
pub struct ControlStatus {
|
||||
pub control: String,
|
||||
pub title: String,
|
||||
pub state: ControlState,
|
||||
/// Why a control is not code-checkable, from the map.
|
||||
pub note: Option<String>,
|
||||
/// Why a checkable control was not assessed; set only in that state.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub reason: Option<NotAssessedReason>,
|
||||
/// How severe a violation is, as the catalog rates it.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub severity: Option<String>,
|
||||
/// How the control is evidenced, as the catalog says (`code`, `process`,
|
||||
/// `hybrid`, `document`).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub evidence_type: Option<String>,
|
||||
pub findings: Vec<FindingRef>,
|
||||
}
|
||||
|
||||
/// Whether a finding still counts against its controls: a false positive, a
|
||||
/// wrong CRA mapping and a resolved finding do not; an accepted risk still
|
||||
/// does.
|
||||
fn counts(finding: &Finding) -> bool {
|
||||
!matches!(
|
||||
finding.status,
|
||||
FindingStatus::FalsePositive | FindingStatus::WrongMapping | FindingStatus::Resolved
|
||||
)
|
||||
}
|
||||
|
||||
/// The state of every control in `map` for a target with `findings`.
|
||||
///
|
||||
/// `scanned_languages` holds the source languages of the last completed scan,
|
||||
/// `None` before any scan completed. A control is "no violation found" only
|
||||
/// if one of its rules covers one of those languages, and none of the tools
|
||||
/// that apply is in `failed_tools` (see [`tool_of_stage`]): a scan of C code
|
||||
/// says nothing about a control only Python rules check, and a CVE lookup
|
||||
/// that failed says nothing about the components' CVEs.
|
||||
pub fn control_statuses(
|
||||
map: &ControlMap,
|
||||
findings: &[Finding],
|
||||
scanned_languages: Option<&[String]>,
|
||||
failed_tools: &[&str],
|
||||
has_components: bool,
|
||||
) -> Vec<ControlStatus> {
|
||||
map.controls
|
||||
.iter()
|
||||
.map(|entry| {
|
||||
let against: Vec<FindingRef> = findings
|
||||
.iter()
|
||||
.filter(|f| counts(f) && f.control_refs.contains(&entry.control))
|
||||
.map(|f| FindingRef {
|
||||
id: f.id.map(|id| id.to_hex()).unwrap_or_default(),
|
||||
title: f.title.clone(),
|
||||
severity: f.severity.to_string(),
|
||||
status: f.status.to_string(),
|
||||
location: match (&f.file_path, f.line_number) {
|
||||
(Some(file), Some(line)) => Some(format!("{file}:{line}")),
|
||||
(Some(file), None) => Some(file.clone()),
|
||||
_ => None,
|
||||
},
|
||||
})
|
||||
.collect();
|
||||
let (state, reason) = if !against.is_empty() {
|
||||
(ControlState::NotSatisfied, None)
|
||||
} else {
|
||||
match (entry.status, scanned_languages) {
|
||||
(Coverage::NotCodeCheckable, _) => (ControlState::NotCodeCheckable, None),
|
||||
(Coverage::NeedsTooling, _) => {
|
||||
(ControlState::NotAssessed, Some(NotAssessedReason::NoTool))
|
||||
}
|
||||
(Coverage::Covered, None) => (
|
||||
ControlState::NotAssessed,
|
||||
Some(NotAssessedReason::NotScanned),
|
||||
),
|
||||
(Coverage::Covered, Some(languages)) if entry.checked_for(languages) => {
|
||||
let mut failed: Vec<String> = entry
|
||||
.scans
|
||||
.iter()
|
||||
.filter(|b| b.applies_to(languages))
|
||||
.map(|b| b.tool.as_str())
|
||||
.filter(|tool| failed_tools.contains(tool))
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
failed.dedup();
|
||||
let on_components_only = entry
|
||||
.scans
|
||||
.iter()
|
||||
.all(|b| COMPONENT_TOOLS.contains(&b.tool.as_str()));
|
||||
if !failed.is_empty() {
|
||||
(
|
||||
ControlState::NotAssessed,
|
||||
Some(NotAssessedReason::ToolFailed { tools: failed }),
|
||||
)
|
||||
} else if on_components_only && !has_components {
|
||||
(
|
||||
ControlState::NotAssessed,
|
||||
Some(NotAssessedReason::NoComponents),
|
||||
)
|
||||
} else {
|
||||
(ControlState::NoViolationFound, None)
|
||||
}
|
||||
}
|
||||
(Coverage::Covered, Some([])) => (
|
||||
ControlState::NotAssessed,
|
||||
Some(NotAssessedReason::LanguagesUnknown),
|
||||
),
|
||||
(Coverage::Covered, Some(languages)) => (
|
||||
ControlState::NotAssessed,
|
||||
Some(NotAssessedReason::NoRuleForLanguages {
|
||||
languages: languages.to_vec(),
|
||||
}),
|
||||
),
|
||||
}
|
||||
};
|
||||
ControlStatus {
|
||||
control: entry.control.clone(),
|
||||
title: entry.title.clone(),
|
||||
state,
|
||||
note: entry.note.clone(),
|
||||
reason,
|
||||
severity: None,
|
||||
evidence_type: None,
|
||||
findings: against,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::{ScanType, Severity};
|
||||
|
||||
fn finding(control: &str, status: FindingStatus) -> Finding {
|
||||
let mut f = Finding::new(
|
||||
"t".into(),
|
||||
format!("fp-{control}-{status}"),
|
||||
"semgrep".into(),
|
||||
ScanType::Sast,
|
||||
"Hard-coded credential".into(),
|
||||
"d".into(),
|
||||
Severity::High,
|
||||
);
|
||||
f.control_refs = vec![control.into()];
|
||||
f.file_path = Some("Core/Src/comms.c".into());
|
||||
f.line_number = Some(9);
|
||||
f.status = status;
|
||||
f
|
||||
}
|
||||
|
||||
fn python() -> Vec<String> {
|
||||
vec!["python".into()]
|
||||
}
|
||||
|
||||
fn c_only() -> Vec<String> {
|
||||
vec!["c".into()]
|
||||
}
|
||||
|
||||
fn status_of<'a>(statuses: &'a [ControlStatus], control: &str) -> &'a ControlStatus {
|
||||
statuses
|
||||
.iter()
|
||||
.find(|s| s.control == control)
|
||||
.expect("every control is listed")
|
||||
}
|
||||
|
||||
fn state_of(statuses: &[ControlStatus], control: &str) -> ControlState {
|
||||
status_of(statuses, control).state
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_control_gets_exactly_one_state() {
|
||||
let map = ControlMap::cra().expect("map");
|
||||
let statuses = control_statuses(&map, &[], Some(&python()), &[], true);
|
||||
assert_eq!(statuses.len(), map.controls.len());
|
||||
assert_eq!(
|
||||
state_of(&statuses, "cra-ai-8"),
|
||||
ControlState::NoViolationFound
|
||||
);
|
||||
assert_eq!(
|
||||
state_of(&statuses, "cra-ai-2"),
|
||||
ControlState::NotCodeCheckable
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_findings_violate_and_closed_ones_do_not() {
|
||||
let map = ControlMap::cra().expect("map");
|
||||
let findings = [
|
||||
finding("cra-ai-8", FindingStatus::AcceptedRisk),
|
||||
finding("cra-ai-13", FindingStatus::FalsePositive),
|
||||
finding("cra-ai-16", FindingStatus::Resolved),
|
||||
// A real code issue that does not violate this requirement.
|
||||
finding("cra-ai-9", FindingStatus::WrongMapping),
|
||||
];
|
||||
let statuses = control_statuses(&map, &findings, Some(&c_only()), &[], true);
|
||||
assert_eq!(state_of(&statuses, "cra-ai-8"), ControlState::NotSatisfied);
|
||||
assert_eq!(
|
||||
state_of(&statuses, "cra-ai-13"),
|
||||
ControlState::NoViolationFound
|
||||
);
|
||||
assert_eq!(
|
||||
state_of(&statuses, "cra-ai-16"),
|
||||
ControlState::NoViolationFound
|
||||
);
|
||||
assert_eq!(
|
||||
state_of(&statuses, "cra-ai-9"),
|
||||
ControlState::NoViolationFound
|
||||
);
|
||||
let violated = statuses
|
||||
.iter()
|
||||
.find(|s| s.control == "cra-ai-8")
|
||||
.expect("listed");
|
||||
assert_eq!(
|
||||
violated.findings[0].location.as_deref(),
|
||||
Some("Core/Src/comms.c:9")
|
||||
);
|
||||
assert_eq!(violated.findings[0].status, "accepted_risk");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_c_scan_claims_nothing_for_controls_only_python_rules_check() {
|
||||
let map = ControlMap::cra().expect("map");
|
||||
let statuses = control_statuses(&map, &[], Some(&c_only()), &[], true);
|
||||
|
||||
// Our C rules and cppcheck checked memory safety; gitleaks, secrets.
|
||||
assert_eq!(
|
||||
state_of(&statuses, "cra-ai-20"),
|
||||
ControlState::NoViolationFound
|
||||
);
|
||||
assert_eq!(
|
||||
state_of(&statuses, "cra-ai-9"),
|
||||
ControlState::NoViolationFound
|
||||
);
|
||||
// Only Python/JS rules check secure defaults: not assessed, and why.
|
||||
let defaults = status_of(&statuses, "cra-ai-1");
|
||||
assert_eq!(defaults.state, ControlState::NotAssessed);
|
||||
assert_eq!(
|
||||
defaults.reason,
|
||||
Some(NotAssessedReason::NoRuleForLanguages {
|
||||
languages: c_only()
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mixed_scan_counts_every_language() {
|
||||
let map = ControlMap::cra().expect("map");
|
||||
let mixed = vec!["c".to_string(), "python".to_string()];
|
||||
let statuses = control_statuses(&map, &[], Some(&mixed), &[], true);
|
||||
assert_eq!(
|
||||
state_of(&statuses, "cra-ai-1"),
|
||||
ControlState::NoViolationFound
|
||||
);
|
||||
assert_eq!(
|
||||
state_of(&statuses, "cra-ai-20"),
|
||||
ControlState::NoViolationFound
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scan_without_recorded_languages_only_trusts_language_independent_tools() {
|
||||
let map = ControlMap::cra().expect("map");
|
||||
let statuses = control_statuses(&map, &[], Some(&[]), &[], true);
|
||||
assert_eq!(
|
||||
state_of(&statuses, "cra-ai-9"),
|
||||
ControlState::NoViolationFound
|
||||
);
|
||||
assert_eq!(
|
||||
status_of(&statuses, "cra-ai-1").reason,
|
||||
Some(NotAssessedReason::LanguagesUnknown)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_sbom_claims_nothing_about_components() {
|
||||
let map = ControlMap::cra().expect("map");
|
||||
let statuses = control_statuses(&map, &[], Some(&c_only()), &[], false);
|
||||
// cra-ai-22/23/33 are checked on components only: with none found,
|
||||
// nothing was checked.
|
||||
for control in ["cra-ai-22", "cra-ai-23", "cra-ai-33"] {
|
||||
assert_eq!(
|
||||
status_of(&statuses, control).reason,
|
||||
Some(NotAssessedReason::NoComponents),
|
||||
"{control}"
|
||||
);
|
||||
}
|
||||
// Controls checked in the code are unaffected.
|
||||
assert_eq!(
|
||||
state_of(&statuses, "cra-ai-20"),
|
||||
ControlState::NoViolationFound
|
||||
);
|
||||
// With components, the SBOM controls are assessed as before.
|
||||
let with = control_statuses(&map, &[], Some(&c_only()), &[], true);
|
||||
assert_eq!(state_of(&with, "cra-ai-23"), ControlState::NoViolationFound);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_cve_lookup_claims_nothing_about_component_cves() {
|
||||
let map = ControlMap::cra().expect("map");
|
||||
let statuses = control_statuses(&map, &[], Some(&c_only()), &["osv"], true);
|
||||
// cra-ai-22 relies on the CVE lookup (osv) and the SBOM (syft).
|
||||
assert_eq!(
|
||||
status_of(&statuses, "cra-ai-22").reason,
|
||||
Some(NotAssessedReason::ToolFailed {
|
||||
tools: vec!["osv".into()]
|
||||
})
|
||||
);
|
||||
// Memory safety does not depend on it.
|
||||
assert_eq!(
|
||||
state_of(&statuses, "cra-ai-20"),
|
||||
ControlState::NoViolationFound
|
||||
);
|
||||
assert_eq!(tool_of_stage("cve_lookup"), Some("osv"));
|
||||
assert_eq!(tool_of_stage("sast_vendor_code"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_is_passed_before_a_scan() {
|
||||
let map = ControlMap::cra().expect("map");
|
||||
let statuses = control_statuses(&map, &[], None, &[], true);
|
||||
assert_eq!(state_of(&statuses, "cra-ai-8"), ControlState::NotAssessed);
|
||||
assert_eq!(
|
||||
status_of(&statuses, "cra-ai-8").reason,
|
||||
Some(NotAssessedReason::NotScanned)
|
||||
);
|
||||
assert!(statuses
|
||||
.iter()
|
||||
.all(|s| s.state != ControlState::NoViolationFound));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
//! The evidence pack: everything Prüfwerk knows about one target, as files a
|
||||
//! conformity process can keep (#285).
|
||||
//!
|
||||
//! It is served on request (API, MCP) and pulled by breakpilot's document
|
||||
//! service, which writes the reports; Prüfwerk renders no PDF. Each file's
|
||||
//! sha256 is in `manifest.json`, with the scan run, the tool versions and the
|
||||
//! hash of the control catalog that produced the CRA mapping, so a report
|
||||
//! built from the pack can say exactly what it rests on.
|
||||
|
||||
pub mod compliance;
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::Serialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use compliance_core::models::oscal_assessment::assess;
|
||||
use compliance_core::models::{CveAlert, Finding, OnboardedTarget, SbomEntry, ScanRun};
|
||||
use compliance_core::sbom_docs;
|
||||
|
||||
use crate::error::AgentError;
|
||||
|
||||
/// Where the image records the versions of the tools it ships.
|
||||
const TOOL_VERSIONS_PATH: &str = "/opt/pruefwerk/tool-versions.json";
|
||||
|
||||
/// What the pack is built from.
|
||||
pub struct EvidenceInputs {
|
||||
pub target: OnboardedTarget,
|
||||
pub findings: Vec<Finding>,
|
||||
pub sbom: Vec<SbomEntry>,
|
||||
pub cves: Vec<CveAlert>,
|
||||
/// The newest scan run, if the target was ever scanned.
|
||||
pub last_run: Option<ScanRun>,
|
||||
/// The CRA catalog's controls by id, for their ratings; empty without one.
|
||||
pub catalog: std::collections::HashMap<String, compliance_core::traits::Control>,
|
||||
}
|
||||
|
||||
/// One file of the pack, as `manifest.json` lists it.
|
||||
#[derive(Debug, Serialize, PartialEq, Eq)]
|
||||
pub struct ManifestFile {
|
||||
pub name: String,
|
||||
pub sha256: String,
|
||||
pub bytes: usize,
|
||||
}
|
||||
|
||||
/// `manifest.json`.
|
||||
#[derive(Debug, Serialize)]
|
||||
struct Manifest {
|
||||
product: &'static str,
|
||||
version: &'static str,
|
||||
generated_at: DateTime<Utc>,
|
||||
target: serde_json::Value,
|
||||
last_scan_run: Option<serde_json::Value>,
|
||||
/// The tools in the image that produced the findings, when known.
|
||||
tool_versions: Option<serde_json::Value>,
|
||||
control_catalog: serde_json::Value,
|
||||
counts: serde_json::Value,
|
||||
files: Vec<ManifestFile>,
|
||||
}
|
||||
|
||||
/// The pack as a ZIP, and the manifest's file list.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When a document cannot be serialised or the archive cannot be written.
|
||||
pub fn build_pack(
|
||||
inputs: &EvidenceInputs,
|
||||
at: DateTime<Utc>,
|
||||
) -> Result<(Vec<u8>, Vec<ManifestFile>), AgentError> {
|
||||
let subject = inputs.target.name.as_str();
|
||||
let files: Vec<(&str, Vec<u8>)> = vec![
|
||||
(
|
||||
"oscal-assessment-results.json",
|
||||
json(&assess(&inputs.findings, at))?,
|
||||
),
|
||||
(
|
||||
"sbom.cdx.json",
|
||||
json(&sbom_docs::cyclonedx(&inputs.sbom, subject))?,
|
||||
),
|
||||
(
|
||||
"sbom.spdx.json",
|
||||
json(&sbom_docs::spdx(&inputs.sbom, subject))?,
|
||||
),
|
||||
("findings.json", json(&inputs.findings)?),
|
||||
("findings.csv", findings_csv(&inputs.findings).into_bytes()),
|
||||
("cve-alerts.json", json(&inputs.cves)?),
|
||||
("cra-compliance.json", json(&compliance_of(inputs))?),
|
||||
];
|
||||
let listed: Vec<ManifestFile> = files
|
||||
.iter()
|
||||
.map(|(name, bytes)| ManifestFile {
|
||||
name: (*name).to_string(),
|
||||
sha256: hex::encode(Sha256::digest(bytes)),
|
||||
bytes: bytes.len(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
let catalog = control_map::ControlMap::cra_source();
|
||||
let manifest = Manifest {
|
||||
product: "Prüfwerk",
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
generated_at: at,
|
||||
target: serde_json::json!({
|
||||
"id": inputs.target.id.map(|id| id.to_hex()),
|
||||
"name": inputs.target.name,
|
||||
"type": inputs.target.target_type.to_string(),
|
||||
}),
|
||||
last_scan_run: inputs.last_run.as_ref().map(|run| {
|
||||
serde_json::json!({
|
||||
"id": run.id.map(|id| id.to_hex()),
|
||||
"status": run.status,
|
||||
"started_at": run.started_at,
|
||||
"completed_at": run.completed_at,
|
||||
"skipped_stages": run.skipped_stages,
|
||||
})
|
||||
}),
|
||||
tool_versions: std::fs::read(TOOL_VERSIONS_PATH)
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice(&b).ok()),
|
||||
control_catalog: serde_json::json!({
|
||||
"framework": "CRA Annex I",
|
||||
"map_sha256": hex::encode(Sha256::digest(catalog.as_bytes())),
|
||||
}),
|
||||
counts: serde_json::json!({
|
||||
"findings": inputs.findings.len(),
|
||||
"sbom_components": inputs.sbom.len(),
|
||||
"cve_alerts": inputs.cves.len(),
|
||||
}),
|
||||
files: listed,
|
||||
};
|
||||
let manifest_bytes = json(&manifest)?;
|
||||
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let options: zip::write::SimpleFileOptions = Default::default();
|
||||
for (name, bytes) in files
|
||||
.iter()
|
||||
.map(|(n, b)| (*n, b.as_slice()))
|
||||
.chain(std::iter::once((
|
||||
"manifest.json",
|
||||
manifest_bytes.as_slice(),
|
||||
)))
|
||||
{
|
||||
zip.start_file(name, options)
|
||||
.map_err(|e| AgentError::Other(e.to_string()))?;
|
||||
zip.write_all(bytes)?;
|
||||
}
|
||||
let archive = zip
|
||||
.finish()
|
||||
.map_err(|e| AgentError::Other(e.to_string()))?
|
||||
.into_inner();
|
||||
Ok((archive, manifest.files))
|
||||
}
|
||||
|
||||
/// The source languages of the target's last completed scan, `None` before
|
||||
/// one completed: only then can a control without findings be called free of
|
||||
/// violations, and only for the languages it covers.
|
||||
pub fn scanned_languages(inputs: &EvidenceInputs) -> Option<&[String]> {
|
||||
inputs
|
||||
.last_run
|
||||
.as_ref()
|
||||
.filter(|run| run.completed_at.is_some())
|
||||
.map(|run| run.languages.as_slice())
|
||||
}
|
||||
|
||||
/// The tools that did not complete in the target's last scan (a skipped
|
||||
/// stage a control relies on: semgrep, cppcheck, the CVE lookup).
|
||||
pub fn failed_tools(inputs: &EvidenceInputs) -> Vec<&'static str> {
|
||||
inputs
|
||||
.last_run
|
||||
.iter()
|
||||
.flat_map(|run| &run.skipped_stages)
|
||||
.filter_map(|s| compliance::tool_of_stage(&s.stage))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The target's state against every CRA Annex I control.
|
||||
pub fn compliance_of(inputs: &EvidenceInputs) -> Vec<compliance::ControlStatus> {
|
||||
control_map::ControlMap::cra()
|
||||
.map(|map| {
|
||||
let mut statuses = compliance::control_statuses(
|
||||
&map,
|
||||
&inputs.findings,
|
||||
scanned_languages(inputs),
|
||||
&failed_tools(inputs),
|
||||
!inputs.sbom.is_empty(),
|
||||
);
|
||||
// The catalog's own ratings, next to our state.
|
||||
for status in &mut statuses {
|
||||
if let Some(control) = inputs.catalog.get(&status.control) {
|
||||
status.severity = control.severity.as_ref().map(ToString::to_string);
|
||||
status.evidence_type = control.evidence_type.clone();
|
||||
}
|
||||
}
|
||||
statuses
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `value` as pretty-printed JSON.
|
||||
fn json<T: Serialize>(value: &T) -> Result<Vec<u8>, AgentError> {
|
||||
serde_json::to_vec_pretty(value).map_err(|e| AgentError::Other(e.to_string()))
|
||||
}
|
||||
|
||||
/// The findings as CSV, one row each, for a spreadsheet.
|
||||
fn findings_csv(findings: &[Finding]) -> String {
|
||||
let mut out =
|
||||
String::from("id,severity,status,type,scanner,rule_id,cwe,location,title,cra_controls\n");
|
||||
for f in findings {
|
||||
let location = match (&f.file_path, f.line_number) {
|
||||
(Some(file), Some(line)) => format!("{file}:{line}"),
|
||||
(Some(file), None) => file.clone(),
|
||||
_ => String::new(),
|
||||
};
|
||||
let row = [
|
||||
f.id.map(|id| id.to_hex()).unwrap_or_default(),
|
||||
f.severity.to_string(),
|
||||
f.status.to_string(),
|
||||
f.scan_type.to_string(),
|
||||
f.scanner.clone(),
|
||||
f.rule_id.clone().unwrap_or_default(),
|
||||
f.cwe.clone().unwrap_or_default(),
|
||||
location,
|
||||
f.title.clone(),
|
||||
f.control_refs.join(" "),
|
||||
];
|
||||
let cells: Vec<String> = row.iter().map(|c| csv_cell(c)).collect();
|
||||
out.push_str(&cells.join(","));
|
||||
out.push('\n');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A CSV cell, quoted when it holds a comma, quote or line break. A leading
|
||||
/// `=`, `+`, `-` or `@` is prefixed with `'` so a spreadsheet does not run a
|
||||
/// finding's text as a formula.
|
||||
fn csv_cell(value: &str) -> String {
|
||||
let value = if value.starts_with(['=', '+', '-', '@']) {
|
||||
format!("'{value}")
|
||||
} else {
|
||||
value.to_string()
|
||||
};
|
||||
if value.contains([',', '"', '\n', '\r']) {
|
||||
format!("\"{}\"", value.replace('"', "\"\""))
|
||||
} else {
|
||||
value
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::{ScanType, Severity, TargetType};
|
||||
use std::io::Read;
|
||||
|
||||
fn inputs() -> EvidenceInputs {
|
||||
let mut finding = Finding::new(
|
||||
"t1".into(),
|
||||
"fp".into(),
|
||||
"semgrep".into(),
|
||||
ScanType::Sast,
|
||||
"Hard-coded credential, \"admin\"".into(),
|
||||
"d".into(),
|
||||
Severity::High,
|
||||
);
|
||||
finding.cwe = Some("CWE-798".into());
|
||||
finding.file_path = Some("Core/Src/comms.c".into());
|
||||
finding.line_number = Some(9);
|
||||
finding.control_refs = vec!["cra-ai-8".into()];
|
||||
EvidenceInputs {
|
||||
target: OnboardedTarget::new("sensor-node".into(), TargetType::FirmwareBareMetal),
|
||||
findings: vec![finding],
|
||||
sbom: vec![SbomEntry::new(
|
||||
"t1".into(),
|
||||
"FreeRTOS".into(),
|
||||
"10.3.1".into(),
|
||||
"embedded".into(),
|
||||
)],
|
||||
cves: vec![],
|
||||
last_run: None,
|
||||
catalog: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pack_holds_every_file_and_the_manifest_hashes_match() {
|
||||
let (zip_bytes, listed) = build_pack(&inputs(), Utc::now()).expect("pack");
|
||||
let mut archive =
|
||||
zip::ZipArchive::new(std::io::Cursor::new(zip_bytes)).expect("a valid zip");
|
||||
let mut names: Vec<String> = archive.file_names().map(String::from).collect();
|
||||
names.sort();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
"cra-compliance.json",
|
||||
"cve-alerts.json",
|
||||
"findings.csv",
|
||||
"findings.json",
|
||||
"manifest.json",
|
||||
"oscal-assessment-results.json",
|
||||
"sbom.cdx.json",
|
||||
"sbom.spdx.json",
|
||||
]
|
||||
);
|
||||
for file in &listed {
|
||||
let mut bytes = Vec::new();
|
||||
archive
|
||||
.by_name(&file.name)
|
||||
.expect("listed file present")
|
||||
.read_to_end(&mut bytes)
|
||||
.expect("read");
|
||||
assert_eq!(
|
||||
hex::encode(Sha256::digest(&bytes)),
|
||||
file.sha256,
|
||||
"{}",
|
||||
file.name
|
||||
);
|
||||
}
|
||||
let mut manifest = String::new();
|
||||
archive
|
||||
.by_name("manifest.json")
|
||||
.expect("manifest")
|
||||
.read_to_string(&mut manifest)
|
||||
.expect("read");
|
||||
let manifest: serde_json::Value = serde_json::from_str(&manifest).expect("json");
|
||||
assert_eq!(manifest["counts"]["findings"], 1);
|
||||
assert_eq!(
|
||||
manifest["control_catalog"]["map_sha256"]
|
||||
.as_str()
|
||||
.map(str::len),
|
||||
Some(64)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_cells_are_quoted_and_formulas_defused() {
|
||||
let csv = findings_csv(&inputs().findings);
|
||||
assert!(
|
||||
csv.contains("\"Hard-coded credential, \"\"admin\"\"\""),
|
||||
"{csv}"
|
||||
);
|
||||
assert!(csv.contains("Core/Src/comms.c:9"));
|
||||
assert_eq!(csv_cell("=HYPERLINK(1)"), "'=HYPERLINK(1)");
|
||||
assert_eq!(csv_cell("plain"), "plain");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,767 @@
|
||||
//! Curated demo targets (#187).
|
||||
//!
|
||||
//! `fixtures/demo-targets/targets.json` is the versioned, reproducible set of
|
||||
//! representative targets every scan path can be exercised against: PlcSps
|
||||
//! (composite and pure control logic), a plain git SAST repo and an RTOS
|
||||
//! firmware repo. The manifest is consumed by:
|
||||
//!
|
||||
//! * the demo seeder ([`crate::demo_seed`]) behind
|
||||
//! `POST /api/v1/targets/demo-seed` and the platform `demo/reset` — which
|
||||
//! onboards the targets in-process (no HTTP self-calls),
|
||||
//! * `scripts/seed-demo-targets.sh` — a thin ops wrapper around that endpoint,
|
||||
//! * the nightly regression (#188) — the `expect` block is the golden
|
||||
//! baseline per target,
|
||||
//! * the lib tests below — which keep the manifest well-formed and assert the
|
||||
//! PLC baselines offline (no Mongo, no network) on every CI run.
|
||||
//!
|
||||
//! The manifest *and* every `upload` fixture it references are compiled into
|
||||
//! the agent binary ([`MANIFEST_JSON`], [`bundled_upload`]) so a deployed
|
||||
//! agent seeds without a checkout; [`DemoTargets::load`] still reads the
|
||||
//! on-disk copy for tooling that wants an edited manifest.
|
||||
//!
|
||||
//! Artifacts come in two flavours: `source_ref` (git URL / live URL / image
|
||||
//! ref; may be overridden by the env var named in `source_ref_env`) and
|
||||
//! `upload` (a workspace-relative file bundled into the binary; may instead
|
||||
//! come from the env var named in `upload_env`). Artifacts flagged `optional`
|
||||
//! are skipped when their env var is unset, so the set seeds cleanly without
|
||||
//! OT infra.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use compliance_core::models::onboarding::{ArtifactKind, PlcFormat, TargetType};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Manifest path, relative to the workspace root.
|
||||
pub const MANIFEST_PATH: &str = "fixtures/demo-targets/targets.json";
|
||||
|
||||
/// The manifest as compiled into the binary.
|
||||
pub const MANIFEST_JSON: &str = include_str!("../../fixtures/demo-targets/targets.json");
|
||||
|
||||
/// Upload fixtures compiled into the binary, keyed by their manifest `upload`
|
||||
/// path. Every `upload` in [`MANIFEST_JSON`] must have an entry here — the
|
||||
/// `manifest_is_well_formed` test enforces it.
|
||||
const BUNDLED_UPLOADS: &[(&str, &[u8])] = &[
|
||||
(
|
||||
"examples/plc-demo/pump_station.st",
|
||||
include_bytes!("../../examples/plc-demo/pump_station.st"),
|
||||
),
|
||||
(
|
||||
"examples/plc-demo/pump_fbd.xml",
|
||||
include_bytes!("../../examples/plc-demo/pump_fbd.xml"),
|
||||
),
|
||||
(
|
||||
"examples/plc-demo/conveyor.xml",
|
||||
include_bytes!("../../examples/plc-demo/conveyor.xml"),
|
||||
),
|
||||
(
|
||||
"examples/plc-demo/traffic_light.st",
|
||||
include_bytes!("../../examples/plc-demo/traffic_light.st"),
|
||||
),
|
||||
];
|
||||
|
||||
/// The bytes of a bundled upload fixture, by manifest `upload` path.
|
||||
pub fn bundled_upload(path: &str) -> Option<&'static [u8]> {
|
||||
BUNDLED_UPLOADS
|
||||
.iter()
|
||||
.find(|(p, _)| *p == path)
|
||||
.map(|(_, bytes)| *bytes)
|
||||
}
|
||||
|
||||
/// Why a manifest could not be loaded.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum FixtureError {
|
||||
#[error("read {path}: {source}")]
|
||||
Io {
|
||||
path: PathBuf,
|
||||
#[source]
|
||||
source: std::io::Error,
|
||||
},
|
||||
#[error("parse {path}: {source}")]
|
||||
Parse {
|
||||
path: PathBuf,
|
||||
#[source]
|
||||
source: serde_json::Error,
|
||||
},
|
||||
/// `select` was asked for keys the manifest does not define.
|
||||
#[error("unknown demo target(s): {}", .0.join(", "))]
|
||||
UnknownKeys(Vec<String>),
|
||||
}
|
||||
|
||||
/// The whole demo-target set.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DemoTargets {
|
||||
/// Bumped on incompatible manifest changes.
|
||||
pub schema_version: u32,
|
||||
/// Prepended to every target name on seed; the seed script's `--reset`
|
||||
/// deletes exactly the targets carrying this prefix.
|
||||
pub name_prefix: String,
|
||||
pub targets: Vec<DemoTarget>,
|
||||
}
|
||||
|
||||
/// One curated target.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DemoTarget {
|
||||
/// Stable machine key (used in baseline reports, as the `name` on the
|
||||
/// demo-seed API and as the default `repo_id`-ish handle in nightly output).
|
||||
pub key: String,
|
||||
/// Human name (without the prefix).
|
||||
pub name: String,
|
||||
pub target_type: TargetType,
|
||||
#[serde(default)]
|
||||
pub description: Option<String>,
|
||||
#[serde(default)]
|
||||
pub artifacts: Vec<DemoArtifact>,
|
||||
/// Opt-in scans to switch on before the first scan (`scan_config.
|
||||
/// enabled_scans`, wire names such as `icsprobe`), as a customer would.
|
||||
/// Applied by the nightly harness to the fixtures it onboards itself.
|
||||
#[serde(default)]
|
||||
pub enabled_scans: Vec<String>,
|
||||
/// Golden baseline for the nightly regression.
|
||||
#[serde(default)]
|
||||
pub expect: Expect,
|
||||
}
|
||||
|
||||
impl DemoTarget {
|
||||
/// True when every *required* artifact is static (no live endpoint the
|
||||
/// scan would need to reach). Optional env-only live URLs don't count —
|
||||
/// they are skipped when their env var is unset.
|
||||
pub fn source_only(&self) -> bool {
|
||||
!self
|
||||
.artifacts
|
||||
.iter()
|
||||
.any(|a| a.kind == ArtifactKind::LiveUrl && !a.optional)
|
||||
}
|
||||
}
|
||||
|
||||
/// The archive format a fixture directory is uploaded as.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Pack {
|
||||
/// A `.zip`, what the dashboard's users send most.
|
||||
#[default]
|
||||
Zip,
|
||||
/// A `.tar.gz`, as exported from Linux build hosts and git forges.
|
||||
TarGz,
|
||||
}
|
||||
|
||||
/// One artifact of a curated target.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DemoArtifact {
|
||||
pub kind: ArtifactKind,
|
||||
/// Literal reference (git URL, live URL, image ref) — the default when
|
||||
/// `source_ref_env` is unset in the environment.
|
||||
#[serde(default)]
|
||||
pub source_ref: Option<String>,
|
||||
/// Env var that overrides `source_ref` at seed time.
|
||||
#[serde(default)]
|
||||
pub source_ref_env: Option<String>,
|
||||
/// Workspace-relative file to upload as this artifact's content.
|
||||
#[serde(default)]
|
||||
pub upload: Option<String>,
|
||||
/// Env var holding an absolute path to upload instead of `upload`.
|
||||
#[serde(default)]
|
||||
pub upload_env: Option<String>,
|
||||
#[serde(default)]
|
||||
pub branch: Option<String>,
|
||||
/// Commit the baseline was recorded against (informational: the agent
|
||||
/// clones `branch`; re-pin when the baseline moves).
|
||||
#[serde(default)]
|
||||
pub pin: Option<String>,
|
||||
#[serde(default)]
|
||||
pub pin_tag: Option<String>,
|
||||
#[serde(default)]
|
||||
pub plc_format: Option<PlcFormat>,
|
||||
/// How a directory `upload` is packed before it is sent.
|
||||
#[serde(default)]
|
||||
pub pack: Pack,
|
||||
/// Skip silently when the env var is unset (needs infra not every
|
||||
/// environment has).
|
||||
#[serde(default)]
|
||||
pub optional: bool,
|
||||
}
|
||||
|
||||
/// The content of an upload-style artifact, resolved for seeding.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UploadContent {
|
||||
/// File name the artifact is recorded under.
|
||||
pub filename: String,
|
||||
pub bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
impl DemoArtifact {
|
||||
/// The upload path, resolved against the workspace root. `None` for
|
||||
/// reference-style artifacts or env-only uploads whose var is unset.
|
||||
pub fn upload_path(&self, root: &Path) -> Option<PathBuf> {
|
||||
if let Some(p) = self.upload_env_path() {
|
||||
return Some(p);
|
||||
}
|
||||
self.upload.as_ref().map(|p| root.join(p))
|
||||
}
|
||||
|
||||
/// Absolute path from `upload_env`, when that var is set and non-empty.
|
||||
fn upload_env_path(&self) -> Option<PathBuf> {
|
||||
let var = self.upload_env.as_ref()?;
|
||||
std::env::var(var)
|
||||
.ok()
|
||||
.filter(|p| !p.is_empty())
|
||||
.map(PathBuf::from)
|
||||
}
|
||||
|
||||
/// True when this artifact only exists if its env var is provided.
|
||||
pub fn env_only(&self) -> bool {
|
||||
self.upload.is_none() && self.source_ref.is_none()
|
||||
}
|
||||
|
||||
/// True for upload-style artifacts (bundled file or env-provided path).
|
||||
pub fn is_upload(&self) -> bool {
|
||||
self.upload.is_some() || self.upload_env.is_some()
|
||||
}
|
||||
|
||||
/// The reference to onboard for a reference-style artifact: the env
|
||||
/// override when set, else the literal `source_ref`. `None` for an
|
||||
/// optional artifact whose env var is unset: its literal points at
|
||||
/// infrastructure (an in-cluster PLC simulator) that only exists where the
|
||||
/// var is set, and onboarding it anyway failed the whole scan once
|
||||
/// internal hosts were refused (#256). Same rule as
|
||||
/// `scripts/seed-demo-targets.sh`.
|
||||
pub fn resolved_source_ref(&self) -> Option<String> {
|
||||
if let Some(var) = &self.source_ref_env {
|
||||
match std::env::var(var) {
|
||||
Ok(v) if !v.is_empty() => return Some(v),
|
||||
_ if self.optional => return None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
self.source_ref.clone()
|
||||
}
|
||||
|
||||
/// The bytes to upload for an upload-style artifact: the file named by
|
||||
/// `upload_env` when that var is set, else the bundled fixture. `Ok(None)`
|
||||
/// when there is nothing to upload (env var unset, no bundled path).
|
||||
pub fn upload_content(&self) -> Result<Option<UploadContent>, FixtureError> {
|
||||
if let Some(path) = self.upload_env_path() {
|
||||
let bytes = std::fs::read(&path).map_err(|source| FixtureError::Io {
|
||||
path: path.clone(),
|
||||
source,
|
||||
})?;
|
||||
let filename = path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| "upload.bin".to_string());
|
||||
return Ok(Some(UploadContent { filename, bytes }));
|
||||
}
|
||||
let Some(rel) = self.upload.as_deref() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(bytes) = bundled_upload(rel) else {
|
||||
return Err(FixtureError::Io {
|
||||
path: PathBuf::from(rel),
|
||||
source: std::io::Error::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
"fixture not bundled into the agent binary",
|
||||
),
|
||||
});
|
||||
};
|
||||
let filename = Path::new(rel)
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| rel.to_string());
|
||||
Ok(Some(UploadContent {
|
||||
filename,
|
||||
bytes: bytes.to_vec(),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
/// Golden baseline; every field is optional so a target can assert only what
|
||||
/// is deterministic for it.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct Expect {
|
||||
/// Lower bound on total findings after a full scan.
|
||||
#[serde(default)]
|
||||
pub min_findings: Option<usize>,
|
||||
/// Rule ids that must be present among SAST findings.
|
||||
#[serde(default)]
|
||||
pub sast_rule_ids: Vec<String>,
|
||||
/// CWE ids (`CWE-NNN`) that must be present.
|
||||
#[serde(default)]
|
||||
pub cwes: Vec<String>,
|
||||
/// Control refs (e.g. `cra-ai-8`) that must be stamped on some finding.
|
||||
#[serde(default)]
|
||||
pub control_refs: Vec<String>,
|
||||
/// At least one finding must carry some control ref.
|
||||
#[serde(default)]
|
||||
pub control_refs_any: bool,
|
||||
/// Lower bound on SBOM components.
|
||||
#[serde(default)]
|
||||
pub min_sbom_components: Option<usize>,
|
||||
/// Lower bound on code-graph nodes, so a language the graph builder stops
|
||||
/// understanding is caught. Node counts move with the parsers, so this is a
|
||||
/// floor, never an exact count.
|
||||
#[serde(default)]
|
||||
pub min_graph_nodes: Option<u64>,
|
||||
/// Scans `applicable-scans` must offer for this target.
|
||||
#[serde(default)]
|
||||
pub scans_offered: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub pentest_supported: Option<bool>,
|
||||
/// `key -> value` facts `detect` must surface.
|
||||
#[serde(default)]
|
||||
pub detected_facts: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// What a finished scan of one target produced, reduced to what [`Expect`]
|
||||
/// can assert on. Built by the nightly harness from the agent's API.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Observed {
|
||||
pub findings: usize,
|
||||
pub rule_ids: BTreeSet<String>,
|
||||
pub cwes: BTreeSet<String>,
|
||||
pub control_refs: BTreeSet<String>,
|
||||
/// Whether any finding carries a control ref.
|
||||
pub any_control_ref: bool,
|
||||
pub sbom_components: usize,
|
||||
/// Nodes in the code graph built for this target.
|
||||
pub graph_nodes: u64,
|
||||
pub scans_offered: BTreeSet<String>,
|
||||
pub pentest_supported: Option<bool>,
|
||||
pub detected_facts: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl Expect {
|
||||
/// Every way `observed` falls short of the deterministic part of this
|
||||
/// baseline, as readable lines. Empty means the target meets it.
|
||||
///
|
||||
/// Control refs are checked separately by [`Self::llm_violations`]: they
|
||||
/// are stamped by the grounded LLM control judge, and LLM output never
|
||||
/// gates the nightly regression.
|
||||
pub fn violations(&self, observed: &Observed) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
if let Some(min) = self.min_findings {
|
||||
if observed.findings < min {
|
||||
out.push(format!(
|
||||
"{} findings, expected at least {min}",
|
||||
observed.findings
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(min) = self.min_sbom_components {
|
||||
if observed.sbom_components < min {
|
||||
out.push(format!(
|
||||
"{} SBOM components, expected at least {min}",
|
||||
observed.sbom_components
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(min) = self.min_graph_nodes {
|
||||
if observed.graph_nodes < min {
|
||||
out.push(format!(
|
||||
"{} code-graph nodes, expected at least {min}",
|
||||
observed.graph_nodes
|
||||
));
|
||||
}
|
||||
}
|
||||
let missing = |what: &str, wanted: &[String], got: &BTreeSet<String>| {
|
||||
wanted
|
||||
.iter()
|
||||
.filter(|w| !got.contains(w.as_str()))
|
||||
.map(|w| format!("missing {what} {w}"))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
out.extend(missing("rule", &self.sast_rule_ids, &observed.rule_ids));
|
||||
out.extend(missing("CWE", &self.cwes, &observed.cwes));
|
||||
out.extend(missing(
|
||||
"offered scan",
|
||||
&self.scans_offered,
|
||||
&observed.scans_offered,
|
||||
));
|
||||
if let Some(want) = self.pentest_supported {
|
||||
if observed.pentest_supported != Some(want) {
|
||||
out.push(format!(
|
||||
"pentest_supported is {:?}, expected {want}",
|
||||
observed.pentest_supported
|
||||
));
|
||||
}
|
||||
}
|
||||
for (key, want) in &self.detected_facts {
|
||||
match observed.detected_facts.get(key) {
|
||||
Some(got) if got == want => {}
|
||||
Some(got) => out.push(format!("fact {key} = {got}, expected {want}")),
|
||||
None => out.push(format!("fact {key} not detected, expected {want}")),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Shortfalls in the control refs, which only the LLM control judge
|
||||
/// stamps today. Reported, not gating.
|
||||
pub fn llm_violations(&self, observed: &Observed) -> Vec<String> {
|
||||
let mut out: Vec<String> = self
|
||||
.control_refs
|
||||
.iter()
|
||||
.filter(|r| !observed.control_refs.contains(r.as_str()))
|
||||
.map(|r| format!("missing control ref {r}"))
|
||||
.collect();
|
||||
if self.control_refs_any && !observed.any_control_ref {
|
||||
out.push("no finding carries a control ref".to_string());
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl DemoTargets {
|
||||
/// Workspace root, derived from this crate's manifest dir.
|
||||
pub fn workspace_root() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.parent()
|
||||
.map(Path::to_path_buf)
|
||||
.unwrap_or_else(|| PathBuf::from("."))
|
||||
}
|
||||
|
||||
/// The manifest compiled into the binary — what a deployed agent seeds.
|
||||
pub fn bundled() -> Result<Self, FixtureError> {
|
||||
serde_json::from_str(MANIFEST_JSON).map_err(|source| FixtureError::Parse {
|
||||
path: PathBuf::from(MANIFEST_PATH),
|
||||
source,
|
||||
})
|
||||
}
|
||||
|
||||
/// Load the checked-in manifest from disk.
|
||||
pub fn load() -> Result<Self, FixtureError> {
|
||||
Self::load_from(&Self::workspace_root().join(MANIFEST_PATH))
|
||||
}
|
||||
|
||||
/// Load a manifest from an explicit path.
|
||||
pub fn load_from(path: &Path) -> Result<Self, FixtureError> {
|
||||
let raw = std::fs::read_to_string(path).map_err(|source| FixtureError::Io {
|
||||
path: path.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
serde_json::from_str(&raw).map_err(|source| FixtureError::Parse {
|
||||
path: path.to_path_buf(),
|
||||
source,
|
||||
})
|
||||
}
|
||||
|
||||
/// Display name as the seeder creates it.
|
||||
pub fn full_name(&self, t: &DemoTarget) -> String {
|
||||
format!("{}{}", self.name_prefix, t.name)
|
||||
}
|
||||
|
||||
/// The targets with the given keys, in manifest order. An empty `keys`
|
||||
/// selects every target; any key the manifest lacks is an error (so a typo
|
||||
/// never silently seeds nothing).
|
||||
pub fn select(&self, keys: &[String]) -> Result<Vec<&DemoTarget>, FixtureError> {
|
||||
if keys.is_empty() {
|
||||
return Ok(self.targets.iter().collect());
|
||||
}
|
||||
let unknown: Vec<String> = keys
|
||||
.iter()
|
||||
.filter(|k| !self.targets.iter().any(|t| &t.key == *k))
|
||||
.cloned()
|
||||
.collect();
|
||||
if !unknown.is_empty() {
|
||||
return Err(FixtureError::UnknownKeys(unknown));
|
||||
}
|
||||
Ok(self
|
||||
.targets
|
||||
.iter()
|
||||
.filter(|t| keys.contains(&t.key))
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::pipeline::plc::analyze_tree;
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
|
||||
fn manifest() -> DemoTargets {
|
||||
DemoTargets::bundled().expect("bundled demo manifest parses")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bundled_manifest_matches_checked_in_file() {
|
||||
let on_disk = DemoTargets::load().expect("demo manifest loads from disk");
|
||||
let bundled = manifest();
|
||||
let keys = |m: &DemoTargets| m.targets.iter().map(|t| t.key.clone()).collect::<Vec<_>>();
|
||||
assert_eq!(keys(&on_disk), keys(&bundled));
|
||||
assert_eq!(on_disk.name_prefix, bundled.name_prefix);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manifest_is_well_formed() {
|
||||
let m = manifest();
|
||||
let root = DemoTargets::workspace_root();
|
||||
assert_eq!(m.schema_version, 1);
|
||||
assert!(!m.targets.is_empty());
|
||||
|
||||
let mut keys = HashSet::new();
|
||||
for t in &m.targets {
|
||||
assert!(keys.insert(t.key.as_str()), "duplicate key {}", t.key);
|
||||
assert!(!t.artifacts.is_empty(), "{}: needs artifacts", t.key);
|
||||
for a in &t.artifacts {
|
||||
let refs = usize::from(a.source_ref.is_some()) + usize::from(a.upload.is_some());
|
||||
let env_only = a.env_only();
|
||||
assert!(
|
||||
refs == 1 || (env_only && a.optional),
|
||||
"{}: artifact {:?} must have exactly one of source_ref/upload, \
|
||||
or be optional + env-only",
|
||||
t.key,
|
||||
a.kind
|
||||
);
|
||||
if let Some(p) = &a.upload {
|
||||
assert!(root.join(p).is_file(), "{}: upload {p} missing", t.key);
|
||||
// The deployed agent seeds from the binary, so every upload
|
||||
// must be bundled and byte-identical to the checked-in file.
|
||||
let bundled =
|
||||
bundled_upload(p).unwrap_or_else(|| panic!("{}: {p} not bundled", t.key));
|
||||
let on_disk = std::fs::read(root.join(p)).expect("fixture readable");
|
||||
assert_eq!(bundled, on_disk.as_slice(), "{}: {p} bundle drifted", t.key);
|
||||
}
|
||||
match a.kind {
|
||||
ArtifactKind::PlcProject => {
|
||||
assert!(
|
||||
a.plc_format.is_some(),
|
||||
"{}: PLC upload needs plc_format",
|
||||
t.key
|
||||
);
|
||||
}
|
||||
ArtifactKind::GitRepo => {
|
||||
assert!(a.branch.is_some(), "{}: git artifact needs branch", t.key);
|
||||
assert!(a.pin.is_some(), "{}: git artifact needs a pin", t.key);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Coverage the demo asks for: PlcSps, firmware, plain git — every one
|
||||
// scannable from source alone (the staging demo runs `source_only`).
|
||||
let types: HashSet<TargetType> = m.targets.iter().map(|t| t.target_type).collect();
|
||||
for want in [
|
||||
TargetType::PlcSps,
|
||||
TargetType::FirmwareRtos,
|
||||
TargetType::BackendService,
|
||||
] {
|
||||
assert!(types.contains(&want), "manifest lacks a {want:?} target");
|
||||
}
|
||||
for t in &m.targets {
|
||||
assert!(t.source_only(), "{}: demo set must be source-only", t.key);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn demo_set_has_the_expected_targets() {
|
||||
let m = manifest();
|
||||
let keys: Vec<&str> = m.targets.iter().map(|t| t.key.as_str()).collect();
|
||||
assert_eq!(
|
||||
keys,
|
||||
[
|
||||
"plc-pump-station",
|
||||
"plc-conveyor-line",
|
||||
"git-cra-vuln-demo",
|
||||
"firmware-zephyr-example",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_only_ignores_optional_live_urls() {
|
||||
let mut t = DemoTarget {
|
||||
key: "k".into(),
|
||||
name: "n".into(),
|
||||
target_type: TargetType::WebApp,
|
||||
description: None,
|
||||
artifacts: vec![DemoArtifact {
|
||||
kind: ArtifactKind::LiveUrl,
|
||||
source_ref: Some("http://x".into()),
|
||||
source_ref_env: None,
|
||||
upload: None,
|
||||
upload_env: None,
|
||||
branch: None,
|
||||
pin: None,
|
||||
pin_tag: None,
|
||||
plc_format: None,
|
||||
pack: Pack::Zip,
|
||||
optional: true,
|
||||
}],
|
||||
enabled_scans: Vec::new(),
|
||||
expect: Expect::default(),
|
||||
};
|
||||
assert!(t.source_only());
|
||||
t.artifacts[0].optional = false;
|
||||
assert!(!t.source_only());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_all_some_and_unknown() {
|
||||
let m = manifest();
|
||||
assert_eq!(m.select(&[]).unwrap().len(), m.targets.len());
|
||||
|
||||
let some = m
|
||||
.select(&[
|
||||
"git-cra-vuln-demo".to_string(),
|
||||
"plc-pump-station".to_string(),
|
||||
])
|
||||
.unwrap();
|
||||
// Manifest order, not request order.
|
||||
let keys: Vec<&str> = some.iter().map(|t| t.key.as_str()).collect();
|
||||
assert_eq!(keys, ["plc-pump-station", "git-cra-vuln-demo"]);
|
||||
|
||||
let err = m
|
||||
.select(&["plc-pump-station".to_string(), "nope".to_string()])
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, FixtureError::UnknownKeys(ref k) if k == &["nope".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upload_content_comes_from_the_bundle() {
|
||||
let m = manifest();
|
||||
let pump = m
|
||||
.targets
|
||||
.iter()
|
||||
.find(|t| t.key == "plc-pump-station")
|
||||
.unwrap();
|
||||
let st = pump
|
||||
.artifacts
|
||||
.iter()
|
||||
.find(|a| a.upload.as_deref() == Some("examples/plc-demo/pump_station.st"))
|
||||
.unwrap();
|
||||
let content = st.upload_content().unwrap().expect("bundled");
|
||||
assert_eq!(content.filename, "pump_station.st");
|
||||
assert!(!content.bytes.is_empty());
|
||||
|
||||
// Optional env-only uploads resolve to nothing when their var is unset.
|
||||
let fw = pump
|
||||
.artifacts
|
||||
.iter()
|
||||
.find(|a| a.kind == ArtifactKind::FirmwareImage)
|
||||
.unwrap();
|
||||
assert!(fw.optional && fw.env_only());
|
||||
assert!(fw.upload_content().unwrap().is_none());
|
||||
|
||||
// An optional reference with an env override is skipped when the var
|
||||
// is unset, not onboarded with its in-cluster default.
|
||||
let live = pump
|
||||
.artifacts
|
||||
.iter()
|
||||
.find(|a| a.kind == ArtifactKind::LiveUrl)
|
||||
.unwrap();
|
||||
assert!(live.optional && live.source_ref.is_some());
|
||||
if std::env::var("DEMO_PLC_MODBUS_URL").is_err() {
|
||||
assert_eq!(live.resolved_source_ref(), None);
|
||||
}
|
||||
}
|
||||
|
||||
/// Offline golden baseline: the checked-in PLC fixtures must keep producing
|
||||
/// the rule ids the manifest promises. Runs the real control-logic
|
||||
/// analyzer over the fixture files.
|
||||
#[test]
|
||||
fn plc_fixtures_meet_golden_baseline() {
|
||||
let m = manifest();
|
||||
let root = DemoTargets::workspace_root();
|
||||
let all = analyze_tree(&root.join("examples/plc-demo"), "demo");
|
||||
|
||||
for t in m
|
||||
.targets
|
||||
.iter()
|
||||
.filter(|t| t.target_type == TargetType::PlcSps)
|
||||
{
|
||||
let files: Vec<String> = t
|
||||
.artifacts
|
||||
.iter()
|
||||
.filter(|a| a.kind == ArtifactKind::PlcProject)
|
||||
.filter_map(|a| a.upload.as_deref())
|
||||
.filter_map(|p| Path::new(p).file_name())
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.collect();
|
||||
assert!(!files.is_empty(), "{}: no PLC uploads", t.key);
|
||||
|
||||
let mine: Vec<_> = all
|
||||
.iter()
|
||||
.filter(|f| {
|
||||
f.file_path
|
||||
.as_deref()
|
||||
.is_some_and(|p| files.iter().any(|n| p.ends_with(n.as_str())))
|
||||
})
|
||||
.collect();
|
||||
let rules: BTreeSet<&str> = mine.iter().filter_map(|f| f.rule_id.as_deref()).collect();
|
||||
eprintln!("{} -> {} findings, rules {:?}", t.key, mine.len(), rules);
|
||||
|
||||
if let Some(min) = t.expect.min_findings {
|
||||
assert!(
|
||||
mine.len() >= min,
|
||||
"{}: {} findings < min {min}",
|
||||
t.key,
|
||||
mine.len()
|
||||
);
|
||||
}
|
||||
for r in &t.expect.sast_rule_ids {
|
||||
assert!(
|
||||
rules.contains(r.as_str()),
|
||||
"{}: missing rule {r}; got {rules:?}",
|
||||
t.key
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expect_reports_each_shortfall_and_passes_a_match() {
|
||||
let expect = Expect {
|
||||
min_findings: Some(3),
|
||||
sast_rule_ids: vec!["plc-safety-bypass".into()],
|
||||
cwes: vec!["CWE-798".into()],
|
||||
control_refs: vec!["cra-ai-8".into()],
|
||||
control_refs_any: true,
|
||||
min_sbom_components: Some(1),
|
||||
min_graph_nodes: Some(2),
|
||||
scans_offered: vec!["sast".into()],
|
||||
pentest_supported: Some(false),
|
||||
detected_facts: BTreeMap::from([("build_system".into(), "zephyr".into())]),
|
||||
};
|
||||
let good = Observed {
|
||||
findings: 3,
|
||||
rule_ids: BTreeSet::from(["plc-safety-bypass".into()]),
|
||||
cwes: BTreeSet::from(["CWE-798".into()]),
|
||||
control_refs: BTreeSet::from(["cra-ai-8".into()]),
|
||||
any_control_ref: true,
|
||||
sbom_components: 1,
|
||||
graph_nodes: 2,
|
||||
scans_offered: BTreeSet::from(["sast".into()]),
|
||||
pentest_supported: Some(false),
|
||||
detected_facts: BTreeMap::from([("build_system".into(), "zephyr".into())]),
|
||||
};
|
||||
assert!(expect.violations(&good).is_empty());
|
||||
assert!(expect.llm_violations(&good).is_empty());
|
||||
|
||||
let empty = Observed::default();
|
||||
let v = expect.violations(&empty);
|
||||
for needle in [
|
||||
"0 findings",
|
||||
"0 SBOM components",
|
||||
"0 code-graph nodes",
|
||||
"missing rule plc-safety-bypass",
|
||||
"missing CWE CWE-798",
|
||||
"missing offered scan sast",
|
||||
"pentest_supported is None",
|
||||
"fact build_system not detected",
|
||||
] {
|
||||
assert!(
|
||||
v.iter().any(|l| l.contains(needle)),
|
||||
"{needle} not in {v:?}"
|
||||
);
|
||||
}
|
||||
assert!(!v.iter().any(|l| l.contains("control ref")), "{v:?}");
|
||||
assert_eq!(
|
||||
expect.llm_violations(&empty),
|
||||
[
|
||||
"missing control ref cra-ai-8",
|
||||
"no finding carries a control ref"
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
//! Findings from outside the scan pipeline: entered by hand, or imported from
|
||||
//! a tool's report (SARIF 2.1.0, OWASP ZAP JSON).
|
||||
//!
|
||||
//! A DAST run or a penetration test is done by a person, not by the agent. Its
|
||||
//! results still belong next to the scan's findings, with the same fields, so
|
||||
//! the customer sees one list and the evidence pack one set.
|
||||
|
||||
pub mod sarif;
|
||||
pub mod zap;
|
||||
|
||||
use compliance_core::models::{Finding, ScanType, Severity};
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::pipeline::dedup;
|
||||
|
||||
/// Longest excerpt of evidence (a request or response) kept on a finding.
|
||||
const MAX_EVIDENCE_CHARS: usize = 4_000;
|
||||
|
||||
/// What a finding from a manual test says, whether typed into the form or
|
||||
/// read from a report.
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq)]
|
||||
pub struct ManualFinding {
|
||||
pub title: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
pub severity: Severity,
|
||||
/// `CWE-79`, or just `79`.
|
||||
#[serde(default)]
|
||||
pub cwe: Option<String>,
|
||||
#[serde(default)]
|
||||
pub cvss_score: Option<f64>,
|
||||
/// Where it was found: a URL, an endpoint, a file.
|
||||
#[serde(default)]
|
||||
pub location: Option<String>,
|
||||
/// A request or response excerpt that shows it.
|
||||
#[serde(default)]
|
||||
pub evidence: Option<String>,
|
||||
#[serde(default)]
|
||||
pub reproduction: Option<String>,
|
||||
#[serde(default)]
|
||||
pub remediation: Option<String>,
|
||||
/// The tool's rule or plugin id, for an imported finding.
|
||||
#[serde(default)]
|
||||
pub rule_id: Option<String>,
|
||||
}
|
||||
|
||||
/// Where a finding came from, for the stored record.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Provenance<'a> {
|
||||
/// The target the finding belongs to.
|
||||
pub target_id: &'a str,
|
||||
/// `Dast` or `Pentest`.
|
||||
pub scan_type: ScanType,
|
||||
/// The tool that found it, or `manual`.
|
||||
pub scanner: &'a str,
|
||||
/// The user who entered or imported it.
|
||||
pub reported_by: &'a str,
|
||||
}
|
||||
|
||||
impl ManualFinding {
|
||||
/// The finding as stored. Its fingerprint covers the target, tool, rule,
|
||||
/// title and location, so importing the same report twice adds nothing.
|
||||
pub fn into_finding(self, from: Provenance<'_>) -> Finding {
|
||||
let cwe = self.cwe.as_deref().and_then(normalise_cwe);
|
||||
let fingerprint = dedup::compute_fingerprint(&[
|
||||
from.target_id,
|
||||
from.scanner,
|
||||
&from.scan_type.to_string(),
|
||||
self.rule_id.as_deref().unwrap_or_default(),
|
||||
&self.title,
|
||||
self.location.as_deref().unwrap_or_default(),
|
||||
]);
|
||||
let mut finding = Finding::new(
|
||||
from.target_id.to_string(),
|
||||
fingerprint,
|
||||
from.scanner.to_string(),
|
||||
from.scan_type,
|
||||
self.title,
|
||||
self.description,
|
||||
self.severity,
|
||||
);
|
||||
finding.control_refs = cwe.as_deref().map(control_refs).unwrap_or_default();
|
||||
finding.cwe = cwe;
|
||||
finding.cvss_score = self.cvss_score.filter(|s| (0.0..=10.0).contains(s));
|
||||
finding.file_path = self.location.filter(|l| !l.trim().is_empty());
|
||||
finding.code_snippet = self.evidence.map(|e| truncate(&e, MAX_EVIDENCE_CHARS));
|
||||
finding.reproduction = self.reproduction.filter(|r| !r.trim().is_empty());
|
||||
finding.remediation = self.remediation.filter(|r| !r.trim().is_empty());
|
||||
finding.rule_id = self.rule_id;
|
||||
finding.reported_by = Some(from.reported_by.to_string());
|
||||
finding
|
||||
}
|
||||
}
|
||||
|
||||
/// `CWE-79` from `79`, `cwe-79` or `CWE-79`; `None` for anything else.
|
||||
pub fn normalise_cwe(raw: &str) -> Option<String> {
|
||||
let digits = raw.trim().to_ascii_uppercase();
|
||||
let digits = digits.strip_prefix("CWE-").unwrap_or(&digits);
|
||||
(!digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit()) && digits != "0")
|
||||
.then(|| format!("CWE-{digits}"))
|
||||
}
|
||||
|
||||
/// The CRA controls a verified weakness is evidence for (see
|
||||
/// [`control_map::ControlMap::controls_for_cwe`]).
|
||||
fn control_refs(cwe: &str) -> Vec<String> {
|
||||
control_map::ControlMap::cra()
|
||||
.map(|map| {
|
||||
map.controls_for_cwe(cwe)
|
||||
.into_iter()
|
||||
.map(|c| c.control.clone())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `text` cut to at most `max` characters, on a character boundary.
|
||||
fn truncate(text: &str, max: usize) -> String {
|
||||
match text.char_indices().nth(max) {
|
||||
Some((cut, _)) => format!("{}…", &text[..cut]),
|
||||
None => text.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A severity from a CVSS-style score (0–10).
|
||||
pub fn severity_from_score(score: f64) -> Severity {
|
||||
match score {
|
||||
s if s >= 9.0 => Severity::Critical,
|
||||
s if s >= 7.0 => Severity::High,
|
||||
s if s >= 4.0 => Severity::Medium,
|
||||
s if s > 0.0 => Severity::Low,
|
||||
_ => Severity::Info,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn provenance() -> Provenance<'static> {
|
||||
Provenance {
|
||||
target_id: "t1",
|
||||
scan_type: ScanType::Pentest,
|
||||
scanner: "manual",
|
||||
reported_by: "u-1",
|
||||
}
|
||||
}
|
||||
|
||||
fn finding(title: &str, location: Option<&str>) -> ManualFinding {
|
||||
ManualFinding {
|
||||
title: title.to_string(),
|
||||
description: "d".to_string(),
|
||||
severity: Severity::High,
|
||||
cwe: Some("79".to_string()),
|
||||
cvss_score: Some(7.5),
|
||||
location: location.map(String::from),
|
||||
evidence: Some("x".repeat(MAX_EVIDENCE_CHARS + 10)),
|
||||
reproduction: Some(" ".to_string()),
|
||||
remediation: None,
|
||||
rule_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_manual_finding_is_stored_like_a_scanned_one() {
|
||||
let f =
|
||||
finding("Reflected XSS", Some("https://device.local/login")).into_finding(provenance());
|
||||
assert_eq!(f.scan_type, ScanType::Pentest);
|
||||
assert_eq!(f.cwe.as_deref(), Some("CWE-79"));
|
||||
assert_eq!(f.file_path.as_deref(), Some("https://device.local/login"));
|
||||
assert_eq!(f.reported_by.as_deref(), Some("u-1"));
|
||||
assert_eq!(f.reproduction, None, "blank text is not stored");
|
||||
assert!(f
|
||||
.code_snippet
|
||||
.is_some_and(|e| e.chars().count() == MAX_EVIDENCE_CHARS + 1));
|
||||
assert!(!f.control_refs.is_empty(), "CWE-79 maps to a CRA control");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_finding_twice_has_one_fingerprint() {
|
||||
let a = finding("XSS", Some("/a")).into_finding(provenance());
|
||||
let b = finding("XSS", Some("/a")).into_finding(provenance());
|
||||
let c = finding("XSS", Some("/b")).into_finding(provenance());
|
||||
assert_eq!(a.fingerprint, b.fingerprint);
|
||||
assert_ne!(a.fingerprint, c.fingerprint);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cwes_and_scores_are_read_leniently() {
|
||||
assert_eq!(normalise_cwe("cwe-89").as_deref(), Some("CWE-89"));
|
||||
assert_eq!(normalise_cwe(" 22 ").as_deref(), Some("CWE-22"));
|
||||
assert_eq!(normalise_cwe("0"), None);
|
||||
assert_eq!(normalise_cwe("CWE-"), None);
|
||||
assert_eq!(normalise_cwe("injection"), None);
|
||||
assert_eq!(severity_from_score(9.8), Severity::Critical);
|
||||
assert_eq!(severity_from_score(5.0), Severity::Medium);
|
||||
assert_eq!(severity_from_score(0.0), Severity::Info);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
//! SARIF 2.1.0: what most security tools can write (Burp and ZAP through
|
||||
//! extensions, Nuclei, CodeQL, semgrep, commercial DAST tools).
|
||||
//!
|
||||
//! Only what a finding needs is read; everything else in the document is
|
||||
//! ignored, so a tool's extensions do not break the import.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::{normalise_cwe, severity_from_score, ManualFinding};
|
||||
use compliance_core::models::Severity;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Log {
|
||||
/// Required, as in the schema: a JSON document without it is not SARIF,
|
||||
/// and must not import as an empty report.
|
||||
runs: Vec<Run>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Run {
|
||||
tool: Tool,
|
||||
#[serde(default)]
|
||||
results: Vec<SarifResult>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Tool {
|
||||
driver: Driver,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Driver {
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
rules: Vec<Rule>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Rule {
|
||||
id: String,
|
||||
#[serde(default, rename = "shortDescription")]
|
||||
short_description: Option<Message>,
|
||||
#[serde(default, rename = "fullDescription")]
|
||||
full_description: Option<Message>,
|
||||
#[serde(default)]
|
||||
help: Option<Message>,
|
||||
#[serde(default)]
|
||||
properties: Option<Properties>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
struct Properties {
|
||||
#[serde(default)]
|
||||
tags: Vec<String>,
|
||||
/// GitHub's convention: a CVSS-like score as a string or number.
|
||||
#[serde(default, rename = "security-severity")]
|
||||
security_severity: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Message {
|
||||
#[serde(default)]
|
||||
text: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct SarifResult {
|
||||
#[serde(default, rename = "ruleId")]
|
||||
rule_id: Option<String>,
|
||||
#[serde(default)]
|
||||
level: Option<String>,
|
||||
message: Message,
|
||||
#[serde(default)]
|
||||
locations: Vec<Location>,
|
||||
#[serde(default)]
|
||||
properties: Option<Properties>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Location {
|
||||
#[serde(default, rename = "physicalLocation")]
|
||||
physical: Option<PhysicalLocation>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PhysicalLocation {
|
||||
#[serde(default, rename = "artifactLocation")]
|
||||
artifact: Option<ArtifactLocation>,
|
||||
#[serde(default)]
|
||||
region: Option<Region>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ArtifactLocation {
|
||||
#[serde(default)]
|
||||
uri: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Region {
|
||||
#[serde(default, rename = "startLine")]
|
||||
start_line: Option<u32>,
|
||||
#[serde(default)]
|
||||
snippet: Option<Message>,
|
||||
}
|
||||
|
||||
/// The findings of a SARIF document, each with the name of the tool that
|
||||
/// reported it.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When the document is not SARIF (no `runs`, or a run without a tool).
|
||||
pub fn parse(json: &[u8]) -> Result<Vec<(String, ManualFinding)>, serde_json::Error> {
|
||||
let log: Log = serde_json::from_slice(json)?;
|
||||
Ok(log
|
||||
.runs
|
||||
.into_iter()
|
||||
.flat_map(|run| {
|
||||
let tool = run.tool.driver.name;
|
||||
let rules: HashMap<String, Rule> = run
|
||||
.tool
|
||||
.driver
|
||||
.rules
|
||||
.into_iter()
|
||||
.map(|r| (r.id.clone(), r))
|
||||
.collect();
|
||||
run.results
|
||||
.into_iter()
|
||||
.map(|result| (tool.clone(), to_finding(result, &rules)))
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn to_finding(result: SarifResult, rules: &HashMap<String, Rule>) -> ManualFinding {
|
||||
let rule = result.rule_id.as_deref().and_then(|id| rules.get(id));
|
||||
let score = result
|
||||
.properties
|
||||
.as_ref()
|
||||
.and_then(score_of)
|
||||
.or_else(|| rule.and_then(|r| r.properties.as_ref()).and_then(score_of));
|
||||
let severity = score.map_or_else(
|
||||
|| level_severity(result.level.as_deref()),
|
||||
severity_from_score,
|
||||
);
|
||||
let tags = rule
|
||||
.and_then(|r| r.properties.as_ref())
|
||||
.map(|p| p.tags.as_slice())
|
||||
.unwrap_or_default();
|
||||
let physical = result.locations.first().and_then(|l| l.physical.as_ref());
|
||||
let location = physical
|
||||
.and_then(|p| p.artifact.as_ref())
|
||||
.and_then(|a| a.uri.clone())
|
||||
.map(|uri| {
|
||||
match physical
|
||||
.and_then(|p| p.region.as_ref())
|
||||
.and_then(|r| r.start_line)
|
||||
{
|
||||
Some(line) => format!("{uri}:{line}"),
|
||||
None => uri,
|
||||
}
|
||||
});
|
||||
let title = rule
|
||||
.and_then(|r| r.short_description.as_ref())
|
||||
.map(|m| m.text.clone())
|
||||
.filter(|t| !t.is_empty())
|
||||
.or_else(|| result.rule_id.clone())
|
||||
.unwrap_or_else(|| first_line(&result.message.text));
|
||||
let description = match rule.and_then(|r| r.full_description.as_ref()) {
|
||||
Some(full) if !full.text.is_empty() && full.text != result.message.text => {
|
||||
format!("{}\n\n{}", result.message.text, full.text)
|
||||
}
|
||||
_ => result.message.text.clone(),
|
||||
};
|
||||
ManualFinding {
|
||||
title,
|
||||
description,
|
||||
severity,
|
||||
cwe: tags.iter().find_map(|t| cwe_from_tag(t)),
|
||||
cvss_score: score,
|
||||
location,
|
||||
evidence: physical
|
||||
.and_then(|p| p.region.as_ref())
|
||||
.and_then(|r| r.snippet.as_ref())
|
||||
.map(|s| s.text.clone()),
|
||||
reproduction: None,
|
||||
remediation: rule.and_then(|r| r.help.as_ref()).map(|h| h.text.clone()),
|
||||
rule_id: result.rule_id,
|
||||
}
|
||||
}
|
||||
|
||||
/// `external/cwe/cwe-79` (CodeQL, semgrep) or `CWE-79`.
|
||||
fn cwe_from_tag(tag: &str) -> Option<String> {
|
||||
let lower = tag.to_ascii_lowercase();
|
||||
let id = lower.rsplit('/').next().unwrap_or(&lower);
|
||||
id.starts_with("cwe-").then(|| normalise_cwe(id)).flatten()
|
||||
}
|
||||
|
||||
fn score_of(p: &Properties) -> Option<f64> {
|
||||
match p.security_severity.as_ref()? {
|
||||
serde_json::Value::Number(n) => n.as_f64(),
|
||||
serde_json::Value::String(s) => s.trim().parse().ok(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn level_severity(level: Option<&str>) -> Severity {
|
||||
match level {
|
||||
Some("error") => Severity::High,
|
||||
Some("note") => Severity::Low,
|
||||
Some("none") => Severity::Info,
|
||||
// SARIF's default level is `warning`.
|
||||
_ => Severity::Medium,
|
||||
}
|
||||
}
|
||||
|
||||
fn first_line(text: &str) -> String {
|
||||
text.lines()
|
||||
.next()
|
||||
.unwrap_or("Finding")
|
||||
.chars()
|
||||
.take(160)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const REPORT: &str = r#"{
|
||||
"version": "2.1.0",
|
||||
"runs": [{
|
||||
"tool": { "driver": { "name": "Nuclei", "rules": [{
|
||||
"id": "default-login",
|
||||
"shortDescription": { "text": "Default credentials accepted" },
|
||||
"fullDescription": { "text": "The web UI accepts admin/admin." },
|
||||
"help": { "text": "Force a password change on first login." },
|
||||
"properties": { "tags": ["security", "external/cwe/cwe-1392"], "security-severity": "9.1" }
|
||||
}]}},
|
||||
"results": [
|
||||
{ "ruleId": "default-login", "level": "error",
|
||||
"message": { "text": "admin/admin works on /login" },
|
||||
"locations": [{ "physicalLocation": { "artifactLocation": { "uri": "https://192.0.2.10/login" } } }] },
|
||||
{ "level": "note", "message": { "text": "Server banner discloses version\nnginx/1.18" } }
|
||||
]
|
||||
}]
|
||||
}"#;
|
||||
|
||||
#[test]
|
||||
fn results_become_findings_with_rule_details() {
|
||||
let findings = parse(REPORT.as_bytes()).expect("sarif");
|
||||
assert_eq!(findings.len(), 2);
|
||||
let (tool, login) = &findings[0];
|
||||
assert_eq!(tool, "Nuclei");
|
||||
assert_eq!(login.title, "Default credentials accepted");
|
||||
assert_eq!(
|
||||
login.severity,
|
||||
Severity::Critical,
|
||||
"security-severity 9.1 wins over the level"
|
||||
);
|
||||
assert_eq!(login.cwe.as_deref(), Some("CWE-1392"));
|
||||
assert_eq!(login.location.as_deref(), Some("https://192.0.2.10/login"));
|
||||
assert!(login.description.contains("admin/admin works"));
|
||||
assert!(login.description.contains("accepts admin/admin"));
|
||||
assert_eq!(
|
||||
login.remediation.as_deref(),
|
||||
Some("Force a password change on first login.")
|
||||
);
|
||||
|
||||
let (_, banner) = &findings[1];
|
||||
assert_eq!(banner.title, "Server banner discloses version");
|
||||
assert_eq!(banner.severity, Severity::Low);
|
||||
assert_eq!(banner.location, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_that_is_not_sarif_is_refused() {
|
||||
assert!(
|
||||
parse(br#"{"runs": [{"results": []}]}"#).is_err(),
|
||||
"a run needs a tool"
|
||||
);
|
||||
assert!(parse(br#"{"not": "sarif"}"#).is_err(), "runs is required");
|
||||
assert!(parse(b"not json").is_err());
|
||||
assert!(parse(br#"{"runs": []}"#).is_ok_and(|f| f.is_empty()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
//! OWASP ZAP's JSON report ("Traditional JSON Report").
|
||||
//!
|
||||
//! ZAP reports one alert per rule and site, with every URL it fired on as an
|
||||
//! instance. One finding per alert keeps a crawl of a hundred pages with the
|
||||
//! same missing header from becoming a hundred findings; the first instance is
|
||||
//! its location, and the count is said in the description.
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::ManualFinding;
|
||||
use compliance_core::models::Severity;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Report {
|
||||
site: Vec<Site>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Site {
|
||||
#[serde(default)]
|
||||
alerts: Vec<Alert>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Alert {
|
||||
#[serde(default)]
|
||||
pluginid: String,
|
||||
#[serde(default)]
|
||||
alert: String,
|
||||
#[serde(default)]
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
riskcode: String,
|
||||
#[serde(default)]
|
||||
desc: String,
|
||||
#[serde(default)]
|
||||
solution: String,
|
||||
#[serde(default)]
|
||||
cweid: String,
|
||||
#[serde(default)]
|
||||
instances: Vec<Instance>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Instance {
|
||||
#[serde(default)]
|
||||
uri: String,
|
||||
#[serde(default)]
|
||||
method: String,
|
||||
#[serde(default)]
|
||||
param: String,
|
||||
#[serde(default)]
|
||||
evidence: String,
|
||||
}
|
||||
|
||||
/// The findings of a ZAP JSON report.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When the document is not a ZAP report (no `site` list).
|
||||
pub fn parse(json: &[u8]) -> Result<Vec<ManualFinding>, serde_json::Error> {
|
||||
let report: Report = serde_json::from_slice(json)?;
|
||||
Ok(report
|
||||
.site
|
||||
.into_iter()
|
||||
.flat_map(|site| site.alerts)
|
||||
.map(to_finding)
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn to_finding(alert: Alert) -> ManualFinding {
|
||||
let title = if alert.alert.is_empty() {
|
||||
alert.name
|
||||
} else {
|
||||
alert.alert
|
||||
};
|
||||
let first = alert.instances.first();
|
||||
let mut description = strip_html(&alert.desc);
|
||||
if alert.instances.len() > 1 {
|
||||
description.push_str(&format!(
|
||||
"\n\nFound on {} URLs; the first is shown.",
|
||||
alert.instances.len()
|
||||
));
|
||||
}
|
||||
ManualFinding {
|
||||
title,
|
||||
description,
|
||||
severity: risk_severity(&alert.riskcode),
|
||||
cwe: Some(alert.cweid).filter(|c| !c.is_empty() && c != "-1"),
|
||||
cvss_score: None,
|
||||
location: first.map(|i| i.uri.clone()).filter(|u| !u.is_empty()),
|
||||
evidence: first.and_then(|i| {
|
||||
let parts: Vec<String> = [
|
||||
(!i.method.is_empty()).then(|| format!("{} {}", i.method, i.uri)),
|
||||
(!i.param.is_empty()).then(|| format!("param: {}", i.param)),
|
||||
(!i.evidence.is_empty()).then(|| format!("evidence: {}", i.evidence)),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.collect();
|
||||
(!parts.is_empty()).then(|| parts.join("\n"))
|
||||
}),
|
||||
reproduction: None,
|
||||
remediation: Some(strip_html(&alert.solution)).filter(|s| !s.is_empty()),
|
||||
rule_id: Some(alert.pluginid).filter(|p| !p.is_empty()),
|
||||
}
|
||||
}
|
||||
|
||||
/// ZAP's risk code: 3 high, 2 medium, 1 low, 0 informational.
|
||||
fn risk_severity(code: &str) -> Severity {
|
||||
match code.trim() {
|
||||
"3" => Severity::High,
|
||||
"2" => Severity::Medium,
|
||||
"1" => Severity::Low,
|
||||
_ => Severity::Info,
|
||||
}
|
||||
}
|
||||
|
||||
/// ZAP writes its texts as HTML paragraphs; keep the words, one paragraph per
|
||||
/// line.
|
||||
fn strip_html(html: &str) -> String {
|
||||
let mut text = String::with_capacity(html.len());
|
||||
let mut in_tag = false;
|
||||
let mut tag = String::new();
|
||||
for c in html.chars() {
|
||||
match (in_tag, c) {
|
||||
(false, '<') => {
|
||||
in_tag = true;
|
||||
tag.clear();
|
||||
}
|
||||
(true, '>') => {
|
||||
in_tag = false;
|
||||
if tag.eq_ignore_ascii_case("/p") || tag.eq_ignore_ascii_case("br") {
|
||||
text.push('\n');
|
||||
}
|
||||
}
|
||||
(true, c) => tag.push(c),
|
||||
(false, c) => text.push(c),
|
||||
}
|
||||
}
|
||||
text.lines()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const REPORT: &str = r#"{
|
||||
"@version": "2.15.0",
|
||||
"site": [{
|
||||
"@name": "https://192.0.2.10",
|
||||
"alerts": [
|
||||
{ "pluginid": "10038", "alert": "Content Security Policy (CSP) Header Not Set",
|
||||
"riskcode": "2", "confidence": "3", "cweid": "693",
|
||||
"desc": "<p>CSP is an added layer of security.</p><p>It helps against XSS.</p>",
|
||||
"solution": "<p>Set the Content-Security-Policy header.</p>",
|
||||
"instances": [
|
||||
{ "uri": "https://192.0.2.10/", "method": "GET", "param": "", "evidence": "" },
|
||||
{ "uri": "https://192.0.2.10/login", "method": "GET", "param": "", "evidence": "" }
|
||||
] },
|
||||
{ "pluginid": "10096", "alert": "Timestamp Disclosure", "riskcode": "0",
|
||||
"cweid": "-1", "desc": "", "solution": "", "instances": [] }
|
||||
]
|
||||
}]
|
||||
}"#;
|
||||
|
||||
#[test]
|
||||
fn one_finding_per_alert_with_its_first_url() {
|
||||
let findings = parse(REPORT.as_bytes()).expect("zap");
|
||||
assert_eq!(findings.len(), 2);
|
||||
let csp = &findings[0];
|
||||
assert_eq!(csp.severity, Severity::Medium);
|
||||
assert_eq!(csp.cwe.as_deref(), Some("693"));
|
||||
assert_eq!(csp.location.as_deref(), Some("https://192.0.2.10/"));
|
||||
assert_eq!(csp.rule_id.as_deref(), Some("10038"));
|
||||
assert!(csp
|
||||
.description
|
||||
.starts_with("CSP is an added layer of security.\nIt helps"));
|
||||
assert!(csp.description.contains("Found on 2 URLs"));
|
||||
assert_eq!(
|
||||
csp.remediation.as_deref(),
|
||||
Some("Set the Content-Security-Policy header.")
|
||||
);
|
||||
assert_eq!(csp.evidence.as_deref(), Some("GET https://192.0.2.10/"));
|
||||
|
||||
let ts = &findings[1];
|
||||
assert_eq!(ts.severity, Severity::Info);
|
||||
assert_eq!(ts.cwe, None, "ZAP's -1 means no CWE");
|
||||
assert_eq!(ts.location, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_that_is_not_a_zap_report_is_refused() {
|
||||
assert!(parse(br#"{"runs": []}"#).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,644 @@
|
||||
//! Unpacking uploaded archives (zip, tar, tar.gz) into a working directory.
|
||||
//!
|
||||
//! The stored blob has no file name, so the format is read from its first
|
||||
//! bytes, not guessed from an extension. Every format is held to the same
|
||||
//! [`ExtractLimits`], and nothing an archive says about its own paths or sizes
|
||||
//! is trusted: entries that would leave the destination are skipped, and the
|
||||
//! byte budget counts what is actually written.
|
||||
//!
|
||||
//! A password-protected zip (ZipCrypto or AES) is decrypted with the
|
||||
//! password stored on the artifact; a missing or wrong one is its own error,
|
||||
//! so the customer is asked for it instead of seeing a failed scan. 7z and
|
||||
//! rar are not unpacked; [`unsupported_format`] names them so the upload can
|
||||
//! say so.
|
||||
|
||||
use std::fs::{self, File};
|
||||
use std::io::{self, Read};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
use flate2::read::GzDecoder;
|
||||
|
||||
use crate::error::AgentError;
|
||||
|
||||
/// A tar header is one 512-byte block; its magic sits at offset 257.
|
||||
const TAR_BLOCK: u64 = 512;
|
||||
const TAR_MAGIC_OFFSET: usize = 257;
|
||||
const TAR_MAGIC: &[u8] = b"ustar";
|
||||
|
||||
/// What one archive may expand to.
|
||||
///
|
||||
/// Extraction used to trust the archive completely: a few-kilobyte zip bomb
|
||||
/// expands to terabytes and fills the node's disk. The limits are enforced on
|
||||
/// bytes actually written, not on the sizes an entry declares about itself,
|
||||
/// since those are attacker-controlled.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ExtractLimits {
|
||||
/// Most entries (files and directories) one archive may contain.
|
||||
pub max_entries: usize,
|
||||
/// Most bytes the whole archive may expand to on disk.
|
||||
pub max_total_bytes: u64,
|
||||
}
|
||||
|
||||
impl Default for ExtractLimits {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_entries: 100_000,
|
||||
max_total_bytes: 2 * 1024 * 1024 * 1024,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why an archive could not be unpacked.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ExtractError {
|
||||
/// The archive is encrypted and no password is set for it.
|
||||
#[error("the archive is password-protected and no password is set")]
|
||||
PasswordRequired,
|
||||
/// The archive is encrypted and the stored password does not open it.
|
||||
#[error("the archive password is wrong")]
|
||||
WrongPassword,
|
||||
/// Anything else: corrupt, too large, or the disk failed.
|
||||
#[error(transparent)]
|
||||
Other(#[from] AgentError),
|
||||
}
|
||||
|
||||
impl From<io::Error> for ExtractError {
|
||||
fn from(e: io::Error) -> Self {
|
||||
Self::Other(e.into())
|
||||
}
|
||||
}
|
||||
|
||||
/// Archive formats recognised but not unpacked, by their leading bytes.
|
||||
const UNSUPPORTED_FORMATS: &[(&[u8], &str)] =
|
||||
&[(b"7z\xBC\xAF\x27\x1C", "7z"), (b"Rar!\x1A\x07", "rar")];
|
||||
|
||||
/// The name of an archive format ingest does not unpack (7z, rar), when the
|
||||
/// file at `path` is one; `None` otherwise.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error when the file cannot be opened or read.
|
||||
pub fn unsupported_format(path: &Path) -> io::Result<Option<&'static str>> {
|
||||
let head = leading_block(File::open(path)?)?;
|
||||
Ok(UNSUPPORTED_FORMATS
|
||||
.iter()
|
||||
.find(|(magic, _)| head.starts_with(magic))
|
||||
.map(|(_, name)| *name))
|
||||
}
|
||||
|
||||
/// Whether the zip at `path` is password-protected, checking `password`
|
||||
/// against it when one is given.
|
||||
///
|
||||
/// The smallest encrypted entry is read in full: ZipCrypto accepts about one
|
||||
/// wrong password in 256 at the header, and only the entry's checksum tells.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `false` for a zip without encrypted entries (a password is then not
|
||||
/// needed); `true` when it is encrypted and `password` opens it.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`ExtractError::PasswordRequired`] when it is encrypted and no password is
|
||||
/// given, [`ExtractError::WrongPassword`] when the password does not open it,
|
||||
/// [`ExtractError::Other`] when it is not a readable zip.
|
||||
pub fn zip_encryption(path: &Path, password: Option<&[u8]>) -> Result<bool, ExtractError> {
|
||||
let mut zip = zip::ZipArchive::new(File::open(path)?)
|
||||
.map_err(|e| AgentError::Other(format!("open zip: {e}")))?;
|
||||
let mut smallest: Option<(usize, u64)> = None;
|
||||
for i in 0..zip.len() {
|
||||
let Ok(entry) = zip.by_index_raw(i) else {
|
||||
continue;
|
||||
};
|
||||
if entry.encrypted()
|
||||
&& !entry.is_dir()
|
||||
&& smallest.is_none_or(|(_, size)| entry.size() < size)
|
||||
{
|
||||
smallest = Some((i, entry.size()));
|
||||
}
|
||||
}
|
||||
let Some((index, _)) = smallest else {
|
||||
return Ok(false);
|
||||
};
|
||||
let password = password.ok_or(ExtractError::PasswordRequired)?;
|
||||
let mut entry = zip
|
||||
.by_index_decrypt(index, password)
|
||||
.map_err(|_| ExtractError::WrongPassword)?;
|
||||
io::copy(&mut entry, &mut io::sink()).map_err(|_| ExtractError::WrongPassword)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The archive formats ingest unpacks.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ArchiveFormat {
|
||||
/// A zip container (also APK/AAB/IPA and CODESYS `.projectarchive`).
|
||||
Zip,
|
||||
/// An uncompressed tar.
|
||||
Tar,
|
||||
/// A gzip-compressed tar (`.tar.gz`, `.tgz`).
|
||||
TarGz,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ArchiveFormat {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Zip => "zip",
|
||||
Self::Tar => "tar",
|
||||
Self::TarGz => "tar.gz",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ArchiveFormat {
|
||||
/// The format of the file at `path`, read from its leading bytes. `None`
|
||||
/// for a file that is not an archive (a single `.st` or `.c` upload), and
|
||||
/// for a gzip that does not hold a tar (a lone compressed file).
|
||||
///
|
||||
/// A gzip whose content cannot be decoded is still reported as
|
||||
/// [`ArchiveFormat::TarGz`]: it was meant to be an archive, and unpacking it
|
||||
/// must fail visibly rather than be scanned as one opaque file.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error when the file cannot be opened or read.
|
||||
pub fn sniff(path: &Path) -> io::Result<Option<Self>> {
|
||||
let head = leading_block(File::open(path)?)?;
|
||||
if head.starts_with(b"PK\x03\x04") || head.starts_with(b"PK\x05\x06") {
|
||||
return Ok(Some(Self::Zip));
|
||||
}
|
||||
if head.starts_with(&[0x1f, 0x8b]) {
|
||||
return Ok(match leading_block(GzDecoder::new(File::open(path)?)) {
|
||||
Ok(inner) if !is_tar_header(&inner) => None,
|
||||
_ => Some(Self::TarGz),
|
||||
});
|
||||
}
|
||||
Ok(is_tar_header(&head).then_some(Self::Tar))
|
||||
}
|
||||
}
|
||||
|
||||
/// The first tar block of `reader`, or less when it is shorter.
|
||||
fn leading_block(reader: impl Read) -> io::Result<Vec<u8>> {
|
||||
// `Read::take` is Python's `f.read(n)`: it stops after `n` bytes.
|
||||
let mut block = Vec::with_capacity(TAR_BLOCK as usize);
|
||||
reader.take(TAR_BLOCK).read_to_end(&mut block)?;
|
||||
Ok(block)
|
||||
}
|
||||
|
||||
/// Whether `block` is a POSIX (ustar) or GNU tar header.
|
||||
fn is_tar_header(block: &[u8]) -> bool {
|
||||
block.get(TAR_MAGIC_OFFSET..TAR_MAGIC_OFFSET + TAR_MAGIC.len()) == Some(TAR_MAGIC)
|
||||
}
|
||||
|
||||
/// Unpack `archive` of the given `format` into `dest` (created if needed),
|
||||
/// refusing archives that exceed `limits`. `password` opens encrypted zip
|
||||
/// entries; tar has no encryption and ignores it.
|
||||
///
|
||||
/// On any error the partly written `dest` is removed, so a caller never finds
|
||||
/// half an archive (or half a bomb) left behind in the working directory.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`ExtractError::PasswordRequired`] or [`ExtractError::WrongPassword`] for
|
||||
/// an encrypted zip without the right password; [`ExtractError::Other`] when
|
||||
/// the archive is corrupt, an entry cannot be written, or the archive exceeds
|
||||
/// `limits`.
|
||||
pub fn extract(
|
||||
format: ArchiveFormat,
|
||||
archive: &Path,
|
||||
dest: &Path,
|
||||
limits: ExtractLimits,
|
||||
password: Option<&[u8]>,
|
||||
) -> Result<(), ExtractError> {
|
||||
let result = File::open(archive)
|
||||
.map_err(ExtractError::from)
|
||||
.and_then(|file| match format {
|
||||
ArchiveFormat::Zip => extract_zip(file, dest, limits, password),
|
||||
ArchiveFormat::Tar => Ok(extract_tar(file, dest, limits)?),
|
||||
ArchiveFormat::TarGz => Ok(extract_tar(GzDecoder::new(file), dest, limits)?),
|
||||
});
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_dir_all(dest);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn extract_zip(
|
||||
file: File,
|
||||
dest: &Path,
|
||||
limits: ExtractLimits,
|
||||
password: Option<&[u8]>,
|
||||
) -> Result<(), ExtractError> {
|
||||
let mut zip =
|
||||
zip::ZipArchive::new(file).map_err(|e| AgentError::Other(format!("open zip: {e}")))?;
|
||||
if zip.len() > limits.max_entries {
|
||||
return Err(too_many_entries(limits).into());
|
||||
}
|
||||
fs::create_dir_all(dest)?;
|
||||
let mut budget = Budget::new(limits);
|
||||
for i in 0..zip.len() {
|
||||
let entry = match password {
|
||||
Some(password) => zip.by_index_decrypt(i, password),
|
||||
None => zip.by_index(i),
|
||||
};
|
||||
let mut entry = entry.map_err(|e| match e {
|
||||
zip::result::ZipError::UnsupportedArchive(zip::result::ZipError::PASSWORD_REQUIRED) => {
|
||||
ExtractError::PasswordRequired
|
||||
}
|
||||
zip::result::ZipError::InvalidPassword => ExtractError::WrongPassword,
|
||||
other => AgentError::Other(format!("read zip entry: {other}")).into(),
|
||||
})?;
|
||||
// `enclosed_name` returns `None` for traversal-unsafe paths — skip them.
|
||||
let Some(rel) = entry.enclosed_name() else {
|
||||
continue;
|
||||
};
|
||||
let out = dest.join(rel);
|
||||
if entry.is_dir() {
|
||||
fs::create_dir_all(&out)?;
|
||||
} else {
|
||||
let encrypted = entry.encrypted();
|
||||
budget.write(&mut entry, &out).map_err(|e| match e {
|
||||
// ZipCrypto lets about one wrong password in 256 past its
|
||||
// header check; the entry's checksum then fails on reading.
|
||||
AgentError::Io(_) if encrypted => ExtractError::WrongPassword,
|
||||
other => other.into(),
|
||||
})?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn extract_tar(reader: impl Read, dest: &Path, limits: ExtractLimits) -> Result<(), AgentError> {
|
||||
let mut archive = tar::Archive::new(reader);
|
||||
fs::create_dir_all(dest)?;
|
||||
let mut budget = Budget::new(limits);
|
||||
let entries = archive
|
||||
.entries()
|
||||
.map_err(|e| AgentError::Other(format!("read tar: {e}")))?;
|
||||
for (index, entry) in entries.enumerate() {
|
||||
if index >= limits.max_entries {
|
||||
return Err(too_many_entries(limits));
|
||||
}
|
||||
let mut entry = entry.map_err(|e| AgentError::Other(format!("read tar entry: {e}")))?;
|
||||
let path = entry
|
||||
.path()
|
||||
.map_err(|e| AgentError::Other(format!("read tar entry name: {e}")))?;
|
||||
let Some(rel) = enclosed(&path) else {
|
||||
continue;
|
||||
};
|
||||
let out = dest.join(rel);
|
||||
match entry.header().entry_type() {
|
||||
tar::EntryType::Directory => fs::create_dir_all(&out)?,
|
||||
tar::EntryType::Regular | tar::EntryType::Continuous => {
|
||||
budget.write(&mut entry, &out)?;
|
||||
}
|
||||
// Symbolic and hard links, devices and FIFOs are never created: a
|
||||
// link could point anywhere on the agent's disk, and a later entry
|
||||
// written "through" it would land outside `dest`.
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `path` as a relative path that stays inside the destination, or `None` when
|
||||
/// it is absolute, climbs with `..`, or names nothing.
|
||||
fn enclosed(path: &Path) -> Option<PathBuf> {
|
||||
let mut rel = PathBuf::new();
|
||||
for component in path.components() {
|
||||
match component {
|
||||
Component::Normal(part) => rel.push(part),
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir | Component::RootDir | Component::Prefix(_) => return None,
|
||||
}
|
||||
}
|
||||
(!rel.as_os_str().is_empty()).then_some(rel)
|
||||
}
|
||||
|
||||
fn too_many_entries(limits: ExtractLimits) -> AgentError {
|
||||
AgentError::Other(format!(
|
||||
"archive has more than the {} entries allowed",
|
||||
limits.max_entries
|
||||
))
|
||||
}
|
||||
|
||||
/// The bytes one extraction may still write.
|
||||
struct Budget {
|
||||
remaining: u64,
|
||||
limit: u64,
|
||||
}
|
||||
|
||||
impl Budget {
|
||||
fn new(limits: ExtractLimits) -> Self {
|
||||
Self {
|
||||
remaining: limits.max_total_bytes,
|
||||
limit: limits.max_total_bytes,
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy `entry` to `out`, charging what was written against the budget.
|
||||
fn write(&mut self, entry: &mut impl Read, out: &Path) -> Result<(), AgentError> {
|
||||
if let Some(parent) = out.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
// Read at most one byte past what is left of the budget: getting that
|
||||
// byte proves the archive is over the limit, whatever its headers say.
|
||||
let mut outfile = File::create(out)?;
|
||||
let written = io::copy(&mut entry.take(self.remaining + 1), &mut outfile)?;
|
||||
if written > self.remaining {
|
||||
return Err(AgentError::Other(format!(
|
||||
"archive expands beyond {} bytes",
|
||||
self.limit
|
||||
)));
|
||||
}
|
||||
self.remaining -= written;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
|
||||
/// A unique scratch directory, removed on drop.
|
||||
struct Scratch(PathBuf);
|
||||
impl Scratch {
|
||||
fn new() -> Self {
|
||||
let p = std::env::temp_dir().join(format!("cs-archive-{}", uuid::Uuid::new_v4()));
|
||||
fs::create_dir_all(&p).expect("mkdir scratch");
|
||||
Self(p)
|
||||
}
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn roomy() -> ExtractLimits {
|
||||
ExtractLimits::default()
|
||||
}
|
||||
|
||||
/// A tar of `(path, body)` regular files.
|
||||
fn tar_bytes(files: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut builder = tar::Builder::new(Vec::new());
|
||||
for (path, body) in files {
|
||||
let mut header = tar::Header::new_gnu();
|
||||
header.set_size(body.len() as u64);
|
||||
header.set_mode(0o644);
|
||||
header.set_cksum();
|
||||
builder
|
||||
.append_data(&mut header, path, *body)
|
||||
.expect("append");
|
||||
}
|
||||
builder.into_inner().expect("finish tar")
|
||||
}
|
||||
|
||||
fn gzip(bytes: &[u8]) -> Vec<u8> {
|
||||
let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
|
||||
enc.write_all(bytes).expect("gzip");
|
||||
enc.finish().expect("finish gzip")
|
||||
}
|
||||
|
||||
fn zip_bytes(files: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut w = zip::ZipWriter::new(io::Cursor::new(Vec::new()));
|
||||
let opts: zip::write::SimpleFileOptions = Default::default();
|
||||
for (path, body) in files {
|
||||
w.start_file(*path, opts).expect("start");
|
||||
w.write_all(body).expect("write");
|
||||
}
|
||||
w.finish().expect("finish").into_inner()
|
||||
}
|
||||
|
||||
/// A zip whose one file is AES-256 encrypted with `password`.
|
||||
fn aes_zip(password: &str) -> Vec<u8> {
|
||||
let mut w = zip::ZipWriter::new(io::Cursor::new(Vec::new()));
|
||||
let opts: zip::write::SimpleFileOptions = Default::default();
|
||||
w.start_file(
|
||||
"src/main.c",
|
||||
opts.with_aes_encryption(zip::AesMode::Aes256, password),
|
||||
)
|
||||
.expect("start");
|
||||
w.write_all(b"int main(void) { return 0; }\n")
|
||||
.expect("write");
|
||||
w.finish().expect("finish").into_inner()
|
||||
}
|
||||
|
||||
/// Made with `zip -P pilot-2026` (the crate cannot write ZipCrypto).
|
||||
const ZIPCRYPTO: &[u8] = include_bytes!("../../tests/fixtures/archives/zipcrypto.zip");
|
||||
const SEVEN_ZIP: &[u8] = include_bytes!("../../tests/fixtures/archives/sample.7z");
|
||||
|
||||
#[test]
|
||||
fn an_encrypted_zip_asks_for_its_password_and_opens_with_it() {
|
||||
let s = Scratch::new();
|
||||
for (name, bytes, password) in [
|
||||
("aes.zip", aes_zip("s3cret"), "s3cret"),
|
||||
("zipcrypto.zip", ZIPCRYPTO.to_vec(), "pilot-2026"),
|
||||
] {
|
||||
let archive = file_with(s.path(), name, &bytes);
|
||||
let dest = s.path().join(format!("out-{name}"));
|
||||
|
||||
assert!(matches!(
|
||||
zip_encryption(&archive, None),
|
||||
Err(ExtractError::PasswordRequired)
|
||||
));
|
||||
assert!(matches!(
|
||||
zip_encryption(&archive, Some(b"wrong")),
|
||||
Err(ExtractError::WrongPassword)
|
||||
));
|
||||
assert!(matches!(
|
||||
zip_encryption(&archive, Some(password.as_bytes())),
|
||||
Ok(true)
|
||||
));
|
||||
|
||||
assert!(matches!(
|
||||
extract(ArchiveFormat::Zip, &archive, &dest, roomy(), None),
|
||||
Err(ExtractError::PasswordRequired)
|
||||
));
|
||||
assert!(!dest.exists(), "{name}: nothing is left half-written");
|
||||
assert!(matches!(
|
||||
extract(ArchiveFormat::Zip, &archive, &dest, roomy(), Some(b"wrong")),
|
||||
Err(ExtractError::WrongPassword)
|
||||
));
|
||||
extract(
|
||||
ArchiveFormat::Zip,
|
||||
&archive,
|
||||
&dest,
|
||||
roomy(),
|
||||
Some(password.as_bytes()),
|
||||
)
|
||||
.expect("the right password opens it");
|
||||
assert!(dest.join("src/main.c").is_file(), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_zip_needs_no_password() {
|
||||
let s = Scratch::new();
|
||||
let archive = file_with(s.path(), "plain.zip", &zip_bytes(&[("a.c", b"int a;")]));
|
||||
assert!(matches!(zip_encryption(&archive, None), Ok(false)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seven_zip_and_rar_are_named_as_unsupported() {
|
||||
let s = Scratch::new();
|
||||
let seven = file_with(s.path(), "a.7z", SEVEN_ZIP);
|
||||
let rar = file_with(s.path(), "a.rar", b"Rar!\x1A\x07\x01\x00rest");
|
||||
let zip = file_with(s.path(), "a.zip", &zip_bytes(&[("a.c", b"int a;")]));
|
||||
assert_eq!(unsupported_format(&seven).expect("read"), Some("7z"));
|
||||
assert_eq!(unsupported_format(&rar).expect("read"), Some("rar"));
|
||||
assert_eq!(unsupported_format(&zip).expect("read"), None);
|
||||
}
|
||||
|
||||
fn file_with(dir: &Path, name: &str, bytes: &[u8]) -> PathBuf {
|
||||
let p = dir.join(name);
|
||||
fs::write(&p, bytes).expect("write");
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formats_are_read_from_the_content() {
|
||||
let s = Scratch::new();
|
||||
let tar = tar_bytes(&[("a.c", b"int x;")]);
|
||||
let cases = [
|
||||
(zip_bytes(&[("a.c", b"int x;")]), Some(ArchiveFormat::Zip)),
|
||||
(tar.clone(), Some(ArchiveFormat::Tar)),
|
||||
(gzip(&tar), Some(ArchiveFormat::TarGz)),
|
||||
// A lone gzipped file is not an archive to unpack.
|
||||
(gzip(b"just a log line"), None),
|
||||
(b"PROGRAM main END_PROGRAM".to_vec(), None),
|
||||
(Vec::new(), None),
|
||||
];
|
||||
for (i, (bytes, want)) in cases.into_iter().enumerate() {
|
||||
let path = file_with(s.path(), &format!("blob{i}"), &bytes);
|
||||
assert_eq!(
|
||||
ArchiveFormat::sniff(&path).expect("sniff"),
|
||||
want,
|
||||
"case {i}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tar_gz_unpacks_like_a_zip() {
|
||||
let s = Scratch::new();
|
||||
let files: &[(&str, &[u8])] = &[("proj/Core/Src/main.c", b"int main(void);")];
|
||||
for (name, bytes, format) in [
|
||||
("z", zip_bytes(files), ArchiveFormat::Zip),
|
||||
("t", tar_bytes(files), ArchiveFormat::Tar),
|
||||
("g", gzip(&tar_bytes(files)), ArchiveFormat::TarGz),
|
||||
] {
|
||||
let archive = file_with(s.path(), name, &bytes);
|
||||
let dest = s.path().join(format!("out-{name}"));
|
||||
extract(format, &archive, &dest, roomy(), None).expect("extract");
|
||||
assert_eq!(
|
||||
fs::read_to_string(dest.join("proj/Core/Src/main.c")).expect("read"),
|
||||
"int main(void);",
|
||||
"{format}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tar_entries_cannot_leave_the_destination() {
|
||||
let s = Scratch::new();
|
||||
// `append_data` refuses `..`, so write the hostile names by hand.
|
||||
let mut builder = tar::Builder::new(Vec::new());
|
||||
for name in ["../escape.txt", "/abs.txt", "ok.txt"] {
|
||||
let mut header = tar::Header::new_old();
|
||||
header.as_old_mut().name[..name.len()].copy_from_slice(name.as_bytes());
|
||||
header.set_size(2);
|
||||
header.set_mode(0o644);
|
||||
header.set_cksum();
|
||||
builder.append(&header, &b"hi"[..]).expect("append");
|
||||
}
|
||||
let mut link = tar::Header::new_gnu();
|
||||
link.set_entry_type(tar::EntryType::Symlink);
|
||||
link.set_size(0);
|
||||
link.set_cksum();
|
||||
builder
|
||||
.append_link(&mut link, "etc", "/etc")
|
||||
.expect("append link");
|
||||
let archive = file_with(s.path(), "evil.tar", &builder.into_inner().expect("tar"));
|
||||
|
||||
let dest = s.path().join("out");
|
||||
extract(ArchiveFormat::Tar, &archive, &dest, roomy(), None).expect("extract");
|
||||
assert!(dest.join("ok.txt").is_file());
|
||||
assert!(!s.path().join("escape.txt").exists());
|
||||
assert!(!dest.join("abs.txt").exists());
|
||||
assert!(fs::symlink_metadata(dest.join("etc")).is_err(), "no links");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tar_bomb_is_refused_and_cleaned_up() {
|
||||
let s = Scratch::new();
|
||||
let zeros = vec![0u8; 1024 * 1024];
|
||||
let files: Vec<(String, &[u8])> = (0..3)
|
||||
.map(|i| (format!("f{i}.bin"), zeros.as_slice()))
|
||||
.collect();
|
||||
let refs: Vec<(&str, &[u8])> = files.iter().map(|(n, b)| (n.as_str(), *b)).collect();
|
||||
let archive = file_with(s.path(), "bomb", &gzip(&tar_bytes(&refs)));
|
||||
let dest = s.path().join("out");
|
||||
let limits = ExtractLimits {
|
||||
max_entries: 100,
|
||||
max_total_bytes: 2 * 1024 * 1024,
|
||||
};
|
||||
let err = extract(ArchiveFormat::TarGz, &archive, &dest, limits, None).expect_err("refuse");
|
||||
assert!(err.to_string().contains("expands beyond"), "{err}");
|
||||
assert!(!dest.exists(), "partial output must be removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_entries_are_refused_in_every_format() {
|
||||
let s = Scratch::new();
|
||||
let files: &[(&str, &[u8])] = &[("a", b"1"), ("b", b"2"), ("c", b"3")];
|
||||
let limits = ExtractLimits {
|
||||
max_entries: 2,
|
||||
max_total_bytes: u64::MAX / 2,
|
||||
};
|
||||
for (name, bytes, format) in [
|
||||
("z", zip_bytes(files), ArchiveFormat::Zip),
|
||||
("g", gzip(&tar_bytes(files)), ArchiveFormat::TarGz),
|
||||
] {
|
||||
let archive = file_with(s.path(), name, &bytes);
|
||||
let dest = s.path().join(format!("out-{name}"));
|
||||
let err = extract(format, &archive, &dest, limits, None).expect_err("refuse");
|
||||
assert!(err.to_string().contains("entries"), "{format}: {err}");
|
||||
assert!(!dest.exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_corrupt_tar_gz_fails_instead_of_passing_as_a_file() {
|
||||
let s = Scratch::new();
|
||||
let mut bytes = gzip(&tar_bytes(&[("a.c", b"int x;")]));
|
||||
bytes.truncate(bytes.len() / 2);
|
||||
let archive = file_with(s.path(), "cut", &bytes);
|
||||
assert_eq!(
|
||||
ArchiveFormat::sniff(&archive).expect("sniff"),
|
||||
Some(ArchiveFormat::TarGz)
|
||||
);
|
||||
let dest = s.path().join("out");
|
||||
assert!(extract(ArchiveFormat::TarGz, &archive, &dest, roomy(), None).is_err());
|
||||
assert!(!dest.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_archive_exactly_at_the_limits_extracts_whole() {
|
||||
let s = Scratch::new();
|
||||
let body = vec![0u8; 1024];
|
||||
let files: &[(&str, &[u8])] = &[("a", &body), ("b", &body), ("c", &body)];
|
||||
let limits = ExtractLimits {
|
||||
max_entries: 3,
|
||||
max_total_bytes: 3 * 1024,
|
||||
};
|
||||
let archive = file_with(s.path(), "t", &tar_bytes(files));
|
||||
let dest = s.path().join("out");
|
||||
extract(ArchiveFormat::Tar, &archive, &dest, limits, None).expect("at the limit is fine");
|
||||
assert_eq!(fs::read(dest.join("c")).expect("read").len(), 1024);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
//! Content-addressed blob storage and archive extraction for ingest.
|
||||
//! Content-addressed blob storage and working directories for ingest.
|
||||
//!
|
||||
//! Blobs are stored at `<base>/blobs/<sha[0:2]>/<sha>` and deduplicated by
|
||||
//! digest; per-run working directories live under `<base>/work/`.
|
||||
|
||||
use std::fs::{self, File};
|
||||
use std::io::{self, Read};
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
@@ -32,12 +32,26 @@ pub fn hash_file(path: &Path) -> Result<(String, u64), AgentError> {
|
||||
Ok((hex::encode(hasher.finalize()), total))
|
||||
}
|
||||
|
||||
/// Store raw bytes in the content-addressed blob store under `base`, returning
|
||||
/// the SHA-256 digest. Used to stash a small derived artifact (e.g. the extracted
|
||||
/// The root of one tenant's runner-artifact store:
|
||||
/// `<base>/tenants/<tenant>/blobs`.
|
||||
///
|
||||
/// Runner artifacts are addressed by content hash, and a hash is guessable from
|
||||
/// the job record — so a store shared across tenants means any authenticated
|
||||
/// runner can fetch any tenant's program source. Giving each tenant its own
|
||||
/// subtree makes that structurally impossible: the path a request can reach is
|
||||
/// fixed by the tenant its key is bound to, not by the hash it asks for.
|
||||
fn tenant_blob_root(base: &Path, tenant: &str) -> PathBuf {
|
||||
base.join("tenants")
|
||||
.join(crate::tenant_path::tenant_segment(tenant))
|
||||
.join("blobs")
|
||||
}
|
||||
|
||||
/// Store raw bytes in `tenant`'s content-addressed blob store, returning the
|
||||
/// SHA-256 digest. Used to stash a small derived artifact (e.g. the extracted
|
||||
/// PLC program source) so a Werkbank runner can fetch it by hash. Idempotent.
|
||||
pub fn store_bytes(base: &Path, bytes: &[u8]) -> Result<String, AgentError> {
|
||||
pub fn store_tenant_bytes(base: &Path, tenant: &str, bytes: &[u8]) -> Result<String, AgentError> {
|
||||
let sha = hex::encode(Sha256::digest(bytes));
|
||||
let dir = base.join("blobs").join(&sha[0..2]);
|
||||
let dir = tenant_blob_root(base, tenant).join(&sha[0..2]);
|
||||
fs::create_dir_all(&dir)?;
|
||||
let dest = dir.join(&sha);
|
||||
if !dest.exists() {
|
||||
@@ -46,13 +60,14 @@ pub fn store_bytes(base: &Path, bytes: &[u8]) -> Result<String, AgentError> {
|
||||
Ok(sha)
|
||||
}
|
||||
|
||||
/// Read a blob's bytes by its SHA-256 digest. Rejects a non-hex/wrong-length hash
|
||||
/// so a request can't traverse outside the blob store.
|
||||
pub fn read_blob(base: &Path, sha: &str) -> Result<Vec<u8>, AgentError> {
|
||||
/// Read a blob's bytes from `tenant`'s store by SHA-256 digest. Rejects a
|
||||
/// non-hex/wrong-length hash so a request can't traverse outside the store, and
|
||||
/// a digest another tenant stored is simply not there (`NotFound`).
|
||||
pub fn read_tenant_blob(base: &Path, tenant: &str, sha: &str) -> Result<Vec<u8>, AgentError> {
|
||||
if sha.len() != 64 || !sha.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return Err(AgentError::Other(format!("invalid content hash '{sha}'")));
|
||||
}
|
||||
let path = base.join("blobs").join(&sha[0..2]).join(sha);
|
||||
let path = tenant_blob_root(base, tenant).join(&sha[0..2]).join(sha);
|
||||
Ok(fs::read(path)?)
|
||||
}
|
||||
|
||||
@@ -71,35 +86,6 @@ pub fn store_file(base: &Path, src: &Path, sha: &str) -> Result<PathBuf, AgentEr
|
||||
Ok(dest)
|
||||
}
|
||||
|
||||
/// Extract a zip archive into `dest` (created if needed). `enclosed_name`
|
||||
/// sanitizes each entry path, so this is safe against zip-slip traversal.
|
||||
pub fn extract_zip(archive: &Path, dest: &Path) -> Result<(), AgentError> {
|
||||
let file = File::open(archive)?;
|
||||
let mut zip =
|
||||
zip::ZipArchive::new(file).map_err(|e| AgentError::Other(format!("open zip: {e}")))?;
|
||||
fs::create_dir_all(dest)?;
|
||||
for i in 0..zip.len() {
|
||||
let mut entry = zip
|
||||
.by_index(i)
|
||||
.map_err(|e| AgentError::Other(format!("read zip entry: {e}")))?;
|
||||
// `enclosed_name` returns `None` for traversal-unsafe paths — skip them.
|
||||
let Some(rel) = entry.enclosed_name() else {
|
||||
continue;
|
||||
};
|
||||
let out = dest.join(rel);
|
||||
if entry.is_dir() {
|
||||
fs::create_dir_all(&out)?;
|
||||
} else {
|
||||
if let Some(parent) = out.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
let mut outfile = File::create(&out)?;
|
||||
io::copy(&mut entry, &mut outfile)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The working directory for one artifact of a target: `<base>/work/<target>/<artifact>`.
|
||||
pub fn work_dir(base: &Path, target_id: &str, artifact_id: &str) -> PathBuf {
|
||||
base.join("work").join(target_id).join(artifact_id)
|
||||
@@ -157,22 +143,40 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_zip_writes_entries() {
|
||||
fn a_tenants_blob_is_invisible_to_another_tenant() {
|
||||
let base = Scratch::new();
|
||||
let archive = base.path().join("a.zip");
|
||||
{
|
||||
let file = File::create(&archive).expect("create");
|
||||
let mut w = zip::ZipWriter::new(file);
|
||||
let opts: zip::write::SimpleFileOptions = Default::default();
|
||||
w.start_file("dir/hello.txt", opts).expect("start");
|
||||
io::Write::write_all(&mut w, b"hi").expect("write");
|
||||
w.finish().expect("finish");
|
||||
}
|
||||
let dest = base.path().join("out");
|
||||
extract_zip(&archive, &dest).expect("extract");
|
||||
let sha = store_tenant_bytes(base.path(), "tenant-a", b"tenant-a program").expect("store");
|
||||
|
||||
// The owning tenant reads it back.
|
||||
assert_eq!(
|
||||
fs::read_to_string(dest.join("dir/hello.txt")).expect("read"),
|
||||
"hi"
|
||||
read_tenant_blob(base.path(), "tenant-a", &sha).expect("own blob"),
|
||||
b"tenant-a program"
|
||||
);
|
||||
// Another tenant asking for the very same digest gets nothing.
|
||||
assert!(
|
||||
read_tenant_blob(base.path(), "tenant-b", &sha).is_err(),
|
||||
"tenant-b must not read tenant-a's blob"
|
||||
);
|
||||
// Identical content stored by another tenant is a separate file.
|
||||
let sha_b =
|
||||
store_tenant_bytes(base.path(), "tenant-b", b"tenant-a program").expect("store");
|
||||
assert_eq!(sha, sha_b, "content addressing is unchanged");
|
||||
assert!(read_tenant_blob(base.path(), "tenant-b", &sha).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tenant_blob_rejects_a_non_hash_and_cannot_traverse() {
|
||||
let base = Scratch::new();
|
||||
for bad in ["..", "../../etc/passwd", "short", ""] {
|
||||
assert!(
|
||||
read_tenant_blob(base.path(), "t", bad).is_err(),
|
||||
"{bad} should not be a valid content hash"
|
||||
);
|
||||
}
|
||||
// A traversal attempt in the tenant id stays under the store root.
|
||||
let sha = store_tenant_bytes(base.path(), "../../escape", b"x").expect("store");
|
||||
let root = base.path().join("tenants");
|
||||
assert!(root.exists(), "store must stay under <base>/tenants");
|
||||
assert!(read_tenant_blob(base.path(), "../../escape", &sha).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -4,18 +4,22 @@
|
||||
//! path plus recorded metadata (content hash, size, discovered facts) that the
|
||||
//! classifier and scanners consume. Every blob is SHA-256 hashed — that digest
|
||||
//! is also the reconciliation key against sibling products (a firmware sha256
|
||||
//! matches tramiton's `Artifact.sha256`).
|
||||
//! matches Firmwerk's `Artifact.sha256`).
|
||||
|
||||
pub(crate) mod archive;
|
||||
pub(crate) mod blob;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use compliance_core::models::{Artifact, ArtifactKind, DetectedFact, OnboardedTarget};
|
||||
use compliance_core::AgentConfig;
|
||||
use compliance_core::models::{
|
||||
Artifact, ArtifactKind, DetectedFact, OnboardedTarget, ScanStep, SkipCode, SkippedStage,
|
||||
};
|
||||
use compliance_core::{AgentConfig, NetGuard};
|
||||
|
||||
use crate::error::AgentError;
|
||||
use crate::pipeline::git::{GitOps, RepoCredentials};
|
||||
use crate::secrets::SecretBox;
|
||||
|
||||
/// The paths and identifiers an ingest needs. Decoupled from the full
|
||||
/// [`AgentConfig`] so ingest is testable without a complete config.
|
||||
@@ -24,20 +28,46 @@ pub struct IngestContext<'a> {
|
||||
pub artifact_store_base: &'a Path,
|
||||
/// Base directory for git clones.
|
||||
pub git_clone_base: &'a str,
|
||||
/// Default SSH key path (used when an artifact provides none).
|
||||
pub ssh_key_path: &'a str,
|
||||
/// The tenant these artifacts belong to. Namespaces the git clone directory
|
||||
/// so two tenants never share a checkout.
|
||||
pub tenant_id: &'a str,
|
||||
/// The id of the target these artifacts belong to (namespaces working dirs).
|
||||
pub target_id: &'a str,
|
||||
/// Where this deployment may fetch from (SSRF policy, #256).
|
||||
pub net_guard: NetGuard,
|
||||
/// Opens the artifacts' sealed credentials (#260).
|
||||
pub secrets: SecretBox,
|
||||
/// Where to report each long step as it starts, so a running scan shows
|
||||
/// it; `None` when nobody is watching.
|
||||
pub progress: Option<tokio::sync::mpsc::UnboundedSender<ScanStep>>,
|
||||
}
|
||||
|
||||
impl<'a> IngestContext<'a> {
|
||||
/// Build an ingest context from the agent config for a given target.
|
||||
pub fn from_config(config: &'a AgentConfig, target_id: &'a str) -> Self {
|
||||
/// Build an ingest context from the agent config for a given tenant's target.
|
||||
pub fn from_config(config: &'a AgentConfig, tenant_id: &'a str, target_id: &'a str) -> Self {
|
||||
Self {
|
||||
artifact_store_base: Path::new(&config.artifact_store_base_path),
|
||||
git_clone_base: &config.git_clone_base_path,
|
||||
ssh_key_path: &config.ssh_key_path,
|
||||
tenant_id,
|
||||
target_id,
|
||||
net_guard: NetGuard::from_env(config.app_env),
|
||||
secrets: SecretBox::from_config(config),
|
||||
progress: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Report each long step to `progress` as it starts.
|
||||
#[must_use]
|
||||
pub fn with_progress(mut self, progress: tokio::sync::mpsc::UnboundedSender<ScanStep>) -> Self {
|
||||
self.progress = Some(progress);
|
||||
self
|
||||
}
|
||||
|
||||
/// Tell the watcher, if any, that `step` has started. A watcher that
|
||||
/// has gone away is not an error: the ingest itself carries on.
|
||||
fn report(&self, step: ScanStep) {
|
||||
if let Some(progress) = &self.progress {
|
||||
let _ = progress.send(step);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -60,9 +90,51 @@ pub struct IngestedArtifact {
|
||||
}
|
||||
|
||||
/// All ingested artifacts for a target, keyed by artifact id.
|
||||
#[derive(Default)]
|
||||
pub struct IngestSet {
|
||||
/// The ingested artifacts, keyed by [`Artifact::id`].
|
||||
pub by_artifact: HashMap<String, IngestedArtifact>,
|
||||
/// The artifacts that could not be ingested. The others still are: one
|
||||
/// broken upload does not cost the target its repository.
|
||||
pub failures: Vec<IngestFailure>,
|
||||
}
|
||||
|
||||
/// An artifact that could not be ingested, and why.
|
||||
#[derive(Debug)]
|
||||
pub struct IngestFailure {
|
||||
/// The artifact's [`Artifact::id`].
|
||||
pub artifact_id: String,
|
||||
/// What the user called it: the file name, or the URL.
|
||||
pub artifact_name: String,
|
||||
/// What went wrong.
|
||||
pub error: AgentError,
|
||||
}
|
||||
|
||||
impl IngestFailure {
|
||||
/// The skipped stage to record: a missing or wrong archive password has
|
||||
/// its own, so the dashboard can say what to do. Any other error stays in
|
||||
/// the log; the run names only the artifact, never a server path.
|
||||
pub fn skipped(&self) -> SkippedStage {
|
||||
let name = self.artifact_name.as_str();
|
||||
let stage = match self.error {
|
||||
AgentError::ArchivePasswordRequired => SkippedStage::new(
|
||||
"archive_password_required",
|
||||
SkipCode::ArchivePasswordRequired,
|
||||
format!("{name} is password-protected and no password is set"),
|
||||
),
|
||||
AgentError::ArchivePasswordWrong => SkippedStage::new(
|
||||
"archive_password_wrong",
|
||||
SkipCode::ArchivePasswordWrong,
|
||||
format!("the stored password does not open {name}"),
|
||||
),
|
||||
_ => SkippedStage::new(
|
||||
"ingest",
|
||||
SkipCode::ArtifactNotIngested,
|
||||
format!("{name} could not be read"),
|
||||
),
|
||||
};
|
||||
stage.about(name)
|
||||
}
|
||||
}
|
||||
|
||||
impl IngestSet {
|
||||
@@ -81,17 +153,30 @@ impl IngestSet {
|
||||
}
|
||||
}
|
||||
|
||||
/// Ingest every artifact on a target.
|
||||
pub fn ingest_all(
|
||||
target: &OnboardedTarget,
|
||||
ctx: &IngestContext<'_>,
|
||||
) -> Result<IngestSet, AgentError> {
|
||||
let mut by_artifact = HashMap::new();
|
||||
/// Ingest every artifact on a target. An artifact that fails is recorded in
|
||||
/// [`IngestSet::failures`], and the rest are still ingested.
|
||||
pub fn ingest_all(target: &OnboardedTarget, ctx: &IngestContext<'_>) -> IngestSet {
|
||||
let mut by_artifact = HashMap::with_capacity(target.artifacts.len());
|
||||
let mut failures = Vec::new();
|
||||
for artifact in &target.artifacts {
|
||||
let ingested = ingest_artifact(artifact, ctx)?;
|
||||
by_artifact.insert(artifact.id.clone(), ingested);
|
||||
match ingest_artifact(artifact, ctx) {
|
||||
Ok(ingested) => {
|
||||
by_artifact.insert(artifact.id.clone(), ingested);
|
||||
}
|
||||
Err(error) => failures.push(IngestFailure {
|
||||
artifact_id: artifact.id.clone(),
|
||||
artifact_name: artifact
|
||||
.display_name
|
||||
.clone()
|
||||
.unwrap_or_else(|| artifact.source_ref.clone()),
|
||||
error,
|
||||
}),
|
||||
}
|
||||
}
|
||||
IngestSet {
|
||||
by_artifact,
|
||||
failures,
|
||||
}
|
||||
Ok(IngestSet { by_artifact })
|
||||
}
|
||||
|
||||
/// Ingest a single artifact, dispatching on its kind.
|
||||
@@ -109,10 +194,18 @@ pub fn ingest_artifact(
|
||||
artifact,
|
||||
DetectedFact::new("container_ref", artifact.source_ref.as_str(), "ingest"),
|
||||
)),
|
||||
ArtifactKind::LiveUrl => Ok(metadata_only(
|
||||
artifact,
|
||||
DetectedFact::new("live_url", artifact.source_ref.as_str(), "ingest"),
|
||||
)),
|
||||
ArtifactKind::LiveUrl => {
|
||||
// A live URL is scanned by the DAST and ICS stages, so it is an
|
||||
// outbound request the tenant chose: check it before recording it.
|
||||
// PLC endpoints (`modbus://`, `opc.tcp://`) are live URLs too.
|
||||
ctx.net_guard
|
||||
.check_live_url(&artifact.source_ref)
|
||||
.map_err(|e| AgentError::Other(e.to_string()))?;
|
||||
Ok(metadata_only(
|
||||
artifact,
|
||||
DetectedFact::new("live_url", artifact.source_ref.as_str(), "ingest"),
|
||||
))
|
||||
}
|
||||
ArtifactKind::PlaintextDescription => Ok(metadata_only(
|
||||
artifact,
|
||||
DetectedFact::new(
|
||||
@@ -129,9 +222,23 @@ fn ingest_git(
|
||||
artifact: &Artifact,
|
||||
ctx: &IngestContext<'_>,
|
||||
) -> Result<IngestedArtifact, AgentError> {
|
||||
let creds = credentials_for(artifact, ctx.ssh_key_path);
|
||||
let git_ops = GitOps::new(ctx.git_clone_base, creds);
|
||||
// `file://`, a bare path or an internal host would clone from the agent's
|
||||
// own disk or the platform network — including another tenant's checkout.
|
||||
ctx.net_guard
|
||||
.check_git_url(&artifact.source_ref)
|
||||
.map_err(|e| AgentError::Other(e.to_string()))?;
|
||||
let creds = credentials_for(artifact, &ctx.secrets);
|
||||
let git_ops = GitOps::new(ctx.git_clone_base, ctx.tenant_id, creds, ctx.net_guard);
|
||||
ctx.report(ScanStep::CloneRepository);
|
||||
let repo_path = git_ops.clone_or_fetch(&artifact.source_ref, &artifact.id)?;
|
||||
// Classification needs the submodules too: a build system or RTOS may
|
||||
// live in one.
|
||||
ctx.report(ScanStep::FetchSubmodules);
|
||||
let facts = git_ops
|
||||
.update_submodules(&repo_path, &artifact.source_ref)
|
||||
.into_iter()
|
||||
.map(|skipped| DetectedFact::new("submodule_skipped", skipped, "ingest"))
|
||||
.collect();
|
||||
let head = GitOps::get_head_sha(&repo_path).ok();
|
||||
Ok(IngestedArtifact {
|
||||
artifact_id: artifact.id.clone(),
|
||||
@@ -139,13 +246,19 @@ fn ingest_git(
|
||||
working_path: Some(repo_path),
|
||||
content_hash: head,
|
||||
size_bytes: None,
|
||||
facts: Vec::new(),
|
||||
facts,
|
||||
})
|
||||
}
|
||||
|
||||
/// Store a blob artifact content-addressed. When `extract` is set and the blob
|
||||
/// is a zip container (source archive, APK/AAB/IPA), also unpack it into a
|
||||
/// working directory; otherwise the working path is the stored blob.
|
||||
/// is an archive (zip, tar, tar.gz; source archives and APK/AAB/IPA), also
|
||||
/// unpack it into a working directory; otherwise the working path is the
|
||||
/// stored blob.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// An uploaded source archive that cannot be unpacked is an error: the scan
|
||||
/// must fail visibly rather than complete over a tree that was never there.
|
||||
fn ingest_blob(
|
||||
artifact: &Artifact,
|
||||
ctx: &IngestContext<'_>,
|
||||
@@ -158,32 +271,49 @@ fn ingest_blob(
|
||||
|
||||
let mut facts = Vec::new();
|
||||
let working_path = if extract {
|
||||
if let Some(format) = archive::unsupported_format(&stored)? {
|
||||
return Err(AgentError::Other(format!(
|
||||
"{format} archives are not supported; upload a zip, tar or tar.gz"
|
||||
)));
|
||||
}
|
||||
let dest = blob::work_dir(base, ctx.target_id, &artifact.id);
|
||||
match blob::extract_zip(&stored, &dest) {
|
||||
Ok(()) => dest,
|
||||
Err(e) => {
|
||||
// Not a zip container — this is a single uploaded file (e.g. a
|
||||
// `.st`/`.xml` PLC project or a `.tar.gz`). The content-addressed
|
||||
// blob has no extension, so materialize it into a working dir
|
||||
// under its original name; extension-based scanners (PLC) can then
|
||||
// discover it and report a readable path.
|
||||
facts.push(DetectedFact::new(
|
||||
"archive_unextracted",
|
||||
e.to_string(),
|
||||
"ingest",
|
||||
));
|
||||
match materialize_single(&stored, &dest, &blob_file_name(artifact)) {
|
||||
Ok(dir) => dir,
|
||||
Err(copy_err) => {
|
||||
facts.push(DetectedFact::new(
|
||||
"materialize_failed",
|
||||
copy_err.to_string(),
|
||||
"ingest",
|
||||
));
|
||||
stored.clone()
|
||||
let password = archive_password(artifact, &ctx.secrets);
|
||||
match archive::ArchiveFormat::sniff(&stored)? {
|
||||
Some(format) => {
|
||||
ctx.report(ScanStep::UnpackArchive);
|
||||
match archive::extract(
|
||||
format,
|
||||
&stored,
|
||||
&dest,
|
||||
archive::ExtractLimits::default(),
|
||||
password.as_deref().map(str::as_bytes),
|
||||
) {
|
||||
Ok(()) => project_root(dest),
|
||||
Err(archive::ExtractError::PasswordRequired) => {
|
||||
return Err(AgentError::ArchivePasswordRequired)
|
||||
}
|
||||
Err(archive::ExtractError::WrongPassword) => {
|
||||
return Err(AgentError::ArchivePasswordWrong)
|
||||
}
|
||||
Err(archive::ExtractError::Other(e)) => {
|
||||
let reason =
|
||||
format!("the uploaded {format} archive could not be unpacked: {e}");
|
||||
if artifact.kind == ArtifactKind::SourceArchive {
|
||||
return Err(AgentError::Other(reason));
|
||||
}
|
||||
// A PLC project or mobile package: kept as one file
|
||||
// for the stage that reads it, which reports on it.
|
||||
as_single_file(artifact, &stored, &dest, reason, &mut facts)
|
||||
}
|
||||
}
|
||||
}
|
||||
None => as_single_file(
|
||||
artifact,
|
||||
&stored,
|
||||
&dest,
|
||||
"not an archive".into(),
|
||||
&mut facts,
|
||||
),
|
||||
}
|
||||
} else {
|
||||
stored.clone()
|
||||
@@ -199,6 +329,54 @@ fn ingest_blob(
|
||||
})
|
||||
}
|
||||
|
||||
/// The project root of an extracted archive. GitHub's "Download ZIP" and most
|
||||
/// tools wrap the project in a single top-level folder (`repo-<sha>/`), and
|
||||
/// build-system detection only looks at the root, so a wrapper made a Zephyr
|
||||
/// app read as "no build system". Descend while the directory holds nothing
|
||||
/// but one folder (a macOS `__MACOSX` sidecar does not count).
|
||||
fn project_root(mut dir: PathBuf) -> PathBuf {
|
||||
loop {
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else {
|
||||
return dir;
|
||||
};
|
||||
let entries: Vec<_> = entries
|
||||
.filter_map(Result::ok)
|
||||
.filter(|e| e.file_name() != "__MACOSX")
|
||||
.collect();
|
||||
match entries.as_slice() {
|
||||
// `file_type` does not follow symlinks, so this never leaves `dir`.
|
||||
[only] if only.file_type().is_ok_and(|t| t.is_dir()) => dir = only.path(),
|
||||
_ => return dir,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The working path for a blob that is used as one file rather than unpacked
|
||||
/// (a `.st`/`.xml` PLC project, a single source file), recording `reason`.
|
||||
/// The content-addressed blob has no extension, so it is materialized into
|
||||
/// `dest` under its original name: extension-based scanners (PLC) can then
|
||||
/// discover it and report a readable path.
|
||||
fn as_single_file(
|
||||
artifact: &Artifact,
|
||||
stored: &Path,
|
||||
dest: &Path,
|
||||
reason: String,
|
||||
facts: &mut Vec<DetectedFact>,
|
||||
) -> PathBuf {
|
||||
facts.push(DetectedFact::new("archive_unextracted", reason, "ingest"));
|
||||
match materialize_single(stored, dest, &blob_file_name(artifact)) {
|
||||
Ok(dir) => dir,
|
||||
Err(copy_err) => {
|
||||
facts.push(DetectedFact::new(
|
||||
"materialize_failed",
|
||||
copy_err.to_string(),
|
||||
"ingest",
|
||||
));
|
||||
stored.to_path_buf()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy a stored blob into `dest`/`name`, returning `dest`. Used when an
|
||||
/// "extractable" artifact turns out to be a single file rather than an archive.
|
||||
fn materialize_single(stored: &Path, dest: &Path, name: &str) -> Result<PathBuf, AgentError> {
|
||||
@@ -232,14 +410,23 @@ fn metadata_only(artifact: &Artifact, fact: DetectedFact) -> IngestedArtifact {
|
||||
}
|
||||
}
|
||||
|
||||
/// The local file backing a blob artifact: its `stored_path` if already
|
||||
/// uploaded, else its `source_ref` interpreted as a filesystem path.
|
||||
fn local_source(artifact: &Artifact) -> Result<PathBuf, AgentError> {
|
||||
let path = artifact
|
||||
.stored_path
|
||||
.as_deref()
|
||||
.unwrap_or(artifact.source_ref.as_str());
|
||||
let path = PathBuf::from(path);
|
||||
/// The local file backing a blob artifact: its `stored_path`, i.e. a blob this
|
||||
/// agent stored itself.
|
||||
///
|
||||
/// `source_ref` used to be read as a filesystem path when `stored_path` was
|
||||
/// absent, which let an API caller name any file the agent could read
|
||||
/// (`/data/compliance-scanner/ssh/id_ed25519`, another tenant's checkout) and
|
||||
/// have it ingested as their own artifact. Blob artifacts now have to be
|
||||
/// uploaded.
|
||||
pub(crate) fn local_source(artifact: &Artifact) -> Result<PathBuf, AgentError> {
|
||||
let Some(stored) = artifact.stored_path.as_deref() else {
|
||||
return Err(AgentError::Other(format!(
|
||||
"artifact {} has no uploaded content — upload the file instead of \
|
||||
referencing a server path",
|
||||
artifact.id
|
||||
)));
|
||||
};
|
||||
let path = PathBuf::from(stored);
|
||||
if !path.exists() {
|
||||
return Err(AgentError::Other(format!(
|
||||
"artifact {} source not found at {}",
|
||||
@@ -250,14 +437,27 @@ fn local_source(artifact: &Artifact) -> Result<PathBuf, AgentError> {
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// Build git credentials from an artifact's auth plus a default SSH key path.
|
||||
fn credentials_for(artifact: &Artifact, default_ssh_key_path: &str) -> RepoCredentials {
|
||||
/// Build git credentials from an artifact's own auth. HTTPS token only: there
|
||||
/// is no agent-wide SSH key to fall back to any more, because one shared key
|
||||
/// authenticated every tenant's clone (see
|
||||
/// [`crate::pipeline::git::reject_ssh_url`]).
|
||||
/// The auth method under which an archive's password is stored.
|
||||
pub const ARCHIVE_PASSWORD_METHOD: &str = "archive_password";
|
||||
|
||||
/// The password of a password-protected archive artifact, opened; `None`
|
||||
/// when none is set.
|
||||
fn archive_password(artifact: &Artifact, secrets: &SecretBox) -> Option<String> {
|
||||
artifact
|
||||
.auth
|
||||
.as_ref()
|
||||
.filter(|a| a.method == ARCHIVE_PASSWORD_METHOD)
|
||||
.and_then(|a| secrets.open_opt(a.secret.as_ref(), "archive password"))
|
||||
}
|
||||
|
||||
fn credentials_for(artifact: &Artifact, secrets: &SecretBox) -> RepoCredentials {
|
||||
let auth = artifact.auth.as_ref();
|
||||
RepoCredentials {
|
||||
ssh_key_path: auth
|
||||
.and_then(|a| a.ssh_key_path.clone())
|
||||
.or_else(|| Some(default_ssh_key_path.to_string())),
|
||||
auth_token: auth.and_then(|a| a.secret.clone()),
|
||||
auth_token: auth.and_then(|a| secrets.open_opt(a.secret.as_ref(), "git token")),
|
||||
auth_username: auth.and_then(|a| a.username.clone()),
|
||||
}
|
||||
}
|
||||
@@ -287,11 +487,70 @@ mod tests {
|
||||
IngestContext {
|
||||
artifact_store_base: store,
|
||||
git_clone_base: "/tmp/cs-ingest-test-repos",
|
||||
ssh_key_path: "/tmp/cs-ingest-test-ssh",
|
||||
tenant_id: "test-tenant",
|
||||
target_id,
|
||||
net_guard: NetGuard::public_only(),
|
||||
secrets: SecretBox::without_key(),
|
||||
progress: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_remotes_that_would_read_our_own_disk_are_refused() {
|
||||
let scratch = Scratch::new();
|
||||
let store = scratch.0.join("store");
|
||||
let ctx = ctx_for(&store, "t1");
|
||||
for url in [
|
||||
"file:///tmp/compliance-scanner/repos/other-tenant/app",
|
||||
"/var/lib/secrets",
|
||||
"git@gitea:org/repo.git",
|
||||
"https://gitea/org/repo.git",
|
||||
] {
|
||||
let artifact = Artifact::git_repo(url.to_string(), "main".to_string());
|
||||
assert!(
|
||||
ingest_artifact(&artifact, &ctx).is_err(),
|
||||
"{url} should be refused"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_urls_pointing_at_internal_hosts_are_refused() {
|
||||
let scratch = Scratch::new();
|
||||
let store = scratch.0.join("store");
|
||||
let ctx = ctx_for(&store, "t1");
|
||||
for url in [
|
||||
"http://169.254.169.254/latest/meta-data/",
|
||||
"http://pruefwerk-mongo:27017",
|
||||
"http://127.0.0.1:3001/api/v1/targets",
|
||||
] {
|
||||
let artifact = Artifact::live_url(url);
|
||||
assert!(
|
||||
ingest_artifact(&artifact, &ctx).is_err(),
|
||||
"{url} should be refused"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blob_artifact_cannot_name_a_server_path() {
|
||||
let scratch = Scratch::new();
|
||||
let store = scratch.0.join("store");
|
||||
let secret = scratch.0.join("id_ed25519");
|
||||
std::fs::write(&secret, b"PRIVATE KEY").expect("write");
|
||||
|
||||
let ctx = ctx_for(&store, "t1");
|
||||
// No stored_path: the caller is naming a file on the agent's disk.
|
||||
let artifact = Artifact::firmware_image(secret.to_string_lossy().to_string());
|
||||
let Err(err) = ingest_artifact(&artifact, &ctx) else {
|
||||
panic!("naming a server path must be refused");
|
||||
};
|
||||
assert!(
|
||||
err.to_string().contains("upload"),
|
||||
"error should point at uploading: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn firmware_blob_is_hashed_and_stored() {
|
||||
let scratch = Scratch::new();
|
||||
@@ -300,7 +559,10 @@ mod tests {
|
||||
std::fs::write(&fw, b"firmware-bytes").expect("write");
|
||||
|
||||
let ctx = ctx_for(&store, "t1");
|
||||
let artifact = Artifact::firmware_image(fw.to_string_lossy().to_string());
|
||||
// Blob artifacts carry their uploaded location in `stored_path`, the
|
||||
// way the upload handler records it.
|
||||
let mut artifact = Artifact::firmware_image("fw.bin".to_string());
|
||||
artifact.stored_path = Some(fw.to_string_lossy().to_string());
|
||||
let out = ingest_artifact(&artifact, &ctx).expect("ingest");
|
||||
|
||||
assert_eq!(out.kind, ArtifactKind::FirmwareImage);
|
||||
@@ -333,17 +595,40 @@ mod tests {
|
||||
let ctx = ctx_for(&store, "t1");
|
||||
|
||||
let mut target = OnboardedTarget::new("t".to_string(), TargetType::FirmwareBareMetal);
|
||||
target.artifacts.push({
|
||||
let mut a = Artifact::firmware_image("fw.bin".to_string());
|
||||
a.stored_path = Some(fw.to_string_lossy().to_string());
|
||||
a
|
||||
});
|
||||
target
|
||||
.artifacts
|
||||
.push(Artifact::firmware_image(fw.to_string_lossy().to_string()));
|
||||
target.artifacts.push(Artifact::live_url("https://x"));
|
||||
.push(Artifact::live_url("https://example.com/x"));
|
||||
|
||||
let set = ingest_all(&target, &ctx).expect("ingest all");
|
||||
let set = ingest_all(&target, &ctx);
|
||||
assert_eq!(set.by_artifact.len(), 2);
|
||||
// Only the firmware artifact yields a working path.
|
||||
assert_eq!(set.working_paths().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_single_wrapper_folder_is_unwrapped() {
|
||||
let scratch = Scratch::new();
|
||||
let root = scratch.0.join("extracted");
|
||||
let app = root.join("example-application-38a6d9b").join("app");
|
||||
std::fs::create_dir_all(&app).expect("mkdir");
|
||||
std::fs::create_dir_all(root.join("__MACOSX")).expect("mkdir");
|
||||
std::fs::write(app.join("prj.conf"), "").expect("write");
|
||||
std::fs::write(root.join("example-application-38a6d9b/west.yml"), "").expect("write");
|
||||
|
||||
// Wrapper plus sidecar: descend to the folder that holds the project.
|
||||
assert_eq!(
|
||||
project_root(root.clone()),
|
||||
root.join("example-application-38a6d9b")
|
||||
);
|
||||
// A directory with several entries is already the root.
|
||||
assert_eq!(project_root(app.clone()), app);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credentials_prefer_artifact_auth() {
|
||||
let mut artifact = Artifact::git_repo("https://git/x", "main");
|
||||
@@ -353,22 +638,127 @@ mod tests {
|
||||
secret: Some("pat".to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
let creds = credentials_for(&artifact, "/default/ssh/key");
|
||||
let creds = credentials_for(&artifact, &SecretBox::without_key());
|
||||
assert_eq!(creds.auth_token.as_deref(), Some("pat"));
|
||||
assert_eq!(creds.auth_username.as_deref(), Some("bob"));
|
||||
}
|
||||
|
||||
/// No agent-wide credential is invented for an artifact that carries none:
|
||||
/// the shared SSH deploy key that used to fill this in belonged to every
|
||||
/// tenant at once.
|
||||
#[test]
|
||||
fn credentials_fall_back_to_default_ssh_key() {
|
||||
let artifact = Artifact::git_repo("git@host:x.git", "main");
|
||||
let creds = credentials_for(&artifact, "/default/ssh/key");
|
||||
assert_eq!(creds.ssh_key_path.as_deref(), Some("/default/ssh/key"));
|
||||
fn credentials_are_empty_without_artifact_auth() {
|
||||
let artifact = Artifact::git_repo("https://host/x.git", "main");
|
||||
let creds = credentials_for(&artifact, &SecretBox::without_key());
|
||||
assert!(creds.auth_token.is_none());
|
||||
assert!(creds.auth_username.is_none());
|
||||
}
|
||||
|
||||
/// A single uploaded PLC file (not an archive) must land in a working dir
|
||||
/// under its original name so the PLC scanner can discover it by extension
|
||||
/// and report a readable path — the demo's upload → scan path.
|
||||
/// A source-archive artifact for `bytes`, as the upload handler stores it.
|
||||
fn uploaded_archive(dir: &Path, name: &str, bytes: &[u8]) -> Artifact {
|
||||
let path = dir.join(name);
|
||||
std::fs::create_dir_all(dir).expect("mkdir uploads");
|
||||
std::fs::write(&path, bytes).expect("write upload");
|
||||
let mut artifact = Artifact::source_archive(name);
|
||||
artifact.stored_path = Some(path.to_string_lossy().to_string());
|
||||
artifact
|
||||
}
|
||||
|
||||
const ZIPCRYPTO: &[u8] = include_bytes!("../../tests/fixtures/archives/zipcrypto.zip");
|
||||
const SEVEN_ZIP: &[u8] = include_bytes!("../../tests/fixtures/archives/sample.7z");
|
||||
|
||||
#[test]
|
||||
fn unpacking_an_archive_is_reported_as_a_step() {
|
||||
let scratch = Scratch::new();
|
||||
let store = scratch.0.join("store");
|
||||
let (progress, mut steps) = tokio::sync::mpsc::unbounded_channel();
|
||||
let ctx = ctx_for(&store, "t-step").with_progress(progress);
|
||||
let artifact = uploaded_archive(&scratch.0.join("uploads"), "fw.zip", ZIPCRYPTO);
|
||||
|
||||
// The password is missing, but the unpacking was started.
|
||||
let _ = ingest_artifact(&artifact, &ctx);
|
||||
|
||||
assert_eq!(steps.try_recv().ok(), Some(ScanStep::UnpackArchive));
|
||||
assert!(steps.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_password_protected_archive_opens_with_its_stored_password() {
|
||||
let scratch = Scratch::new();
|
||||
let store = scratch.0.join("store");
|
||||
let ctx = ctx_for(&store, "t-pw");
|
||||
let mut artifact = uploaded_archive(&scratch.0.join("uploads"), "fw.zip", ZIPCRYPTO);
|
||||
|
||||
assert!(matches!(
|
||||
ingest_artifact(&artifact, &ctx),
|
||||
Err(AgentError::ArchivePasswordRequired)
|
||||
));
|
||||
|
||||
// Without a key the box keeps values as they are, like a dev agent.
|
||||
artifact.auth = Some(ArtifactAuth {
|
||||
method: ARCHIVE_PASSWORD_METHOD.into(),
|
||||
secret: Some("wrong".into()),
|
||||
..Default::default()
|
||||
});
|
||||
assert!(matches!(
|
||||
ingest_artifact(&artifact, &ctx),
|
||||
Err(AgentError::ArchivePasswordWrong)
|
||||
));
|
||||
|
||||
artifact.auth = Some(ArtifactAuth {
|
||||
method: ARCHIVE_PASSWORD_METHOD.into(),
|
||||
secret: Some("pilot-2026".into()),
|
||||
..Default::default()
|
||||
});
|
||||
let out = ingest_artifact(&artifact, &ctx).expect("opens");
|
||||
let root = out.working_path.expect("working path");
|
||||
assert!(root.join("main.c").is_file(), "{root:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_7z_upload_is_refused_by_name() {
|
||||
let scratch = Scratch::new();
|
||||
let store = scratch.0.join("store");
|
||||
let ctx = ctx_for(&store, "t-7z");
|
||||
let artifact = uploaded_archive(&scratch.0.join("uploads"), "fw.7z", SEVEN_ZIP);
|
||||
let Err(err) = ingest_artifact(&artifact, &ctx) else {
|
||||
panic!("a 7z upload must be refused");
|
||||
};
|
||||
assert!(
|
||||
err.to_string().contains("7z archives are not supported"),
|
||||
"{err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_failing_artifact_does_not_cost_the_others() {
|
||||
let scratch = Scratch::new();
|
||||
let store = scratch.0.join("store");
|
||||
let ctx = ctx_for(&store, "t-mixed");
|
||||
let uploads = scratch.0.join("uploads");
|
||||
let mut target = OnboardedTarget::new("mixed".into(), TargetType::FirmwareRtos);
|
||||
target
|
||||
.artifacts
|
||||
.push(uploaded_archive(&uploads, "locked.zip", ZIPCRYPTO));
|
||||
target
|
||||
.artifacts
|
||||
.push(Artifact::live_url("https://example.com/x"));
|
||||
|
||||
let set = ingest_all(&target, &ctx);
|
||||
|
||||
assert_eq!(set.by_artifact.len(), 1, "the URL is still ingested");
|
||||
assert_eq!(set.failures.len(), 1);
|
||||
let skipped = set.failures[0].skipped();
|
||||
assert_eq!(skipped.stage, "archive_password_required");
|
||||
assert_eq!(skipped.code, Some(SkipCode::ArchivePasswordRequired));
|
||||
// The run names the file, never where it is stored.
|
||||
assert_eq!(skipped.subject.as_deref(), Some("locked.zip"));
|
||||
assert!(!skipped.reason.contains('/'), "{}", skipped.reason);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_uploaded_plc_file_is_materialized_and_scannable() {
|
||||
use compliance_core::models::PlcFormat;
|
||||
|
||||
@@ -6,14 +6,24 @@ pub mod classify;
|
||||
pub mod config;
|
||||
pub mod controls;
|
||||
pub mod database;
|
||||
pub mod demo_seed;
|
||||
pub mod error;
|
||||
pub mod evidence;
|
||||
pub mod fixtures;
|
||||
pub mod import;
|
||||
pub mod ingest;
|
||||
pub mod lifecycle;
|
||||
pub mod llm;
|
||||
pub mod pentest;
|
||||
pub mod pipeline;
|
||||
pub mod rag;
|
||||
pub mod registry;
|
||||
pub mod retention;
|
||||
pub mod scan_gate;
|
||||
pub mod scheduler;
|
||||
pub mod ssh;
|
||||
pub mod secrets;
|
||||
pub mod targets;
|
||||
pub mod tenant_path;
|
||||
#[allow(dead_code)]
|
||||
pub mod trackers;
|
||||
pub mod webhooks;
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
//! Keeps work from staying stuck across an agent restart (#65).
|
||||
//!
|
||||
//! A redeploy, crash or out-of-memory kill ends every scan the agent was
|
||||
//! running without anything recording it, so the run stays `running` forever.
|
||||
//! [`recover_orphaned_runs`] closes those records once at startup, before
|
||||
//! anything new can start. [`run_werkbank_sweeper`] returns Werkbank jobs whose
|
||||
//! runner stopped heartbeating to the queue.
|
||||
//!
|
||||
//! Both assume one agent per environment, which is how every Orca deployment
|
||||
//! runs today. With two replicas, one agent's startup would close runs the
|
||||
//! other is still working on.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use mongodb::bson::{doc, DateTime as BsonDateTime};
|
||||
use tokio::time::MissedTickBehavior;
|
||||
|
||||
use compliance_core::models::RunErrorCode;
|
||||
use compliance_core::shutdown::Shutdown;
|
||||
|
||||
use crate::database::{Database, DatabasePool};
|
||||
use crate::error::AgentError;
|
||||
use crate::werkbank::{JobQueue, SweepOutcome};
|
||||
|
||||
/// Recorded as `error_message` on every run closed at startup.
|
||||
pub const INTERRUPTED_MESSAGE: &str = "interrupted by agent restart";
|
||||
|
||||
/// How often expired Werkbank leases are swept.
|
||||
pub const WERKBANK_SWEEP_INTERVAL: Duration = Duration::from_secs(60);
|
||||
|
||||
/// A job whose lease has expired this many times is marked `expired` instead
|
||||
/// of being queued again, so a job that keeps killing its runner stops.
|
||||
pub const WERKBANK_MAX_ATTEMPTS: u32 = 3;
|
||||
|
||||
/// A kind of run record a stopped agent can leave open, and how it is closed.
|
||||
struct OrphanRule {
|
||||
collection: &'static str,
|
||||
/// Statuses that only a live agent process ever moves on from.
|
||||
open: &'static [&'static str],
|
||||
closed_as: &'static str,
|
||||
}
|
||||
|
||||
/// Code scans are what customers see, so they get their own `interrupted`
|
||||
/// status. The rest close as `failed` with [`INTERRUPTED_MESSAGE`]: DAST and
|
||||
/// pentest are off in production, and graph and embedding builds are steps of
|
||||
/// a scan. A paused pentest session can only be resumed through in-memory
|
||||
/// state, so after a restart it is as dead as a running one.
|
||||
const ORPHAN_RULES: [OrphanRule; 5] = [
|
||||
OrphanRule {
|
||||
collection: "scan_runs",
|
||||
open: &["running"],
|
||||
closed_as: "interrupted",
|
||||
},
|
||||
OrphanRule {
|
||||
collection: "graph_builds",
|
||||
open: &["running"],
|
||||
closed_as: "failed",
|
||||
},
|
||||
OrphanRule {
|
||||
collection: "embedding_builds",
|
||||
open: &["running"],
|
||||
closed_as: "failed",
|
||||
},
|
||||
OrphanRule {
|
||||
collection: "dast_scan_runs",
|
||||
open: &["running"],
|
||||
closed_as: "failed",
|
||||
},
|
||||
OrphanRule {
|
||||
collection: "pentest_sessions",
|
||||
open: &["running", "paused"],
|
||||
closed_as: "failed",
|
||||
},
|
||||
];
|
||||
|
||||
/// Close every run a previous agent process left open, in every tenant.
|
||||
///
|
||||
/// Call once at startup, before the scheduler and servers start, so no run
|
||||
/// this process creates can be caught. A tenant whose update fails is logged
|
||||
/// and skipped, so one bad database cannot leave the others' runs open.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// How many records were closed across all tenants.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error only if the tenant databases cannot be listed.
|
||||
pub async fn recover_orphaned_runs(
|
||||
pool: &DatabasePool,
|
||||
now: DateTime<Utc>,
|
||||
) -> Result<u64, AgentError> {
|
||||
let mut closed = 0;
|
||||
for db in pool.existing_tenant_dbs().await? {
|
||||
match close_open_runs(&db, now).await {
|
||||
Ok(count) => closed += count,
|
||||
Err(e) => tracing::error!(
|
||||
database = db.inner().name(),
|
||||
"closing runs left open by the previous agent failed: {e}"
|
||||
),
|
||||
}
|
||||
}
|
||||
Ok(closed)
|
||||
}
|
||||
|
||||
/// Apply every [`ORPHAN_RULES`] entry to one tenant database.
|
||||
async fn close_open_runs(db: &Database, now: DateTime<Utc>) -> Result<u64, AgentError> {
|
||||
let completed_at = BsonDateTime::from_chrono(now);
|
||||
let mut closed = 0;
|
||||
for rule in &ORPHAN_RULES {
|
||||
let result = db
|
||||
.raw_collection(rule.collection)
|
||||
.update_many(
|
||||
doc! { "status": { "$in": rule.open.to_vec() } },
|
||||
doc! { "$set": {
|
||||
"status": rule.closed_as,
|
||||
"error_message": INTERRUPTED_MESSAGE,
|
||||
"error_code": mongodb::bson::to_bson(&RunErrorCode::Interrupted)
|
||||
.unwrap_or_default(),
|
||||
"completed_at": completed_at,
|
||||
} },
|
||||
)
|
||||
.await?;
|
||||
if result.modified_count > 0 {
|
||||
tracing::warn!(
|
||||
database = db.inner().name(),
|
||||
collection = rule.collection,
|
||||
count = result.modified_count,
|
||||
status = rule.closed_as,
|
||||
"closed runs left open by the previous agent process"
|
||||
);
|
||||
}
|
||||
closed += result.modified_count;
|
||||
}
|
||||
Ok(closed)
|
||||
}
|
||||
|
||||
/// Sweep expired Werkbank leases in every tenant (see
|
||||
/// [`JobQueue::sweep_expired`]). A tenant whose sweep fails is logged and
|
||||
/// skipped.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error only if the tenant databases cannot be listed.
|
||||
pub async fn sweep_werkbank_leases(
|
||||
pool: &DatabasePool,
|
||||
now: DateTime<Utc>,
|
||||
max_attempts: u32,
|
||||
) -> Result<SweepOutcome, AgentError> {
|
||||
let mut total = SweepOutcome::default();
|
||||
for db in pool.existing_tenant_dbs().await? {
|
||||
match JobQueue::new(&db).sweep_expired(now, max_attempts).await {
|
||||
Ok(outcome) => {
|
||||
total.requeued += outcome.requeued;
|
||||
total.expired += outcome.expired;
|
||||
}
|
||||
Err(e) => tracing::error!(
|
||||
database = db.inner().name(),
|
||||
"Werkbank lease sweep failed: {e}"
|
||||
),
|
||||
}
|
||||
}
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
/// Sweep expired Werkbank leases every [`WERKBANK_SWEEP_INTERVAL`] until
|
||||
/// `shutdown` fires. The first sweep runs immediately, which also picks up
|
||||
/// leases that expired while the agent was down.
|
||||
pub async fn run_werkbank_sweeper(pool: DatabasePool, shutdown: Shutdown) {
|
||||
let mut ticks = tokio::time::interval(WERKBANK_SWEEP_INTERVAL);
|
||||
// After a stall, wait a full interval rather than sweeping in a burst.
|
||||
ticks.set_missed_tick_behavior(MissedTickBehavior::Delay);
|
||||
let stop = shutdown.wait();
|
||||
// `select!` polls this one future again on every loop turn, which Rust
|
||||
// only allows once the future is pinned (fixed at one memory address).
|
||||
tokio::pin!(stop);
|
||||
loop {
|
||||
tokio::select! {
|
||||
() = &mut stop => return,
|
||||
_ = ticks.tick() => {}
|
||||
}
|
||||
match sweep_werkbank_leases(&pool, Utc::now(), WERKBANK_MAX_ATTEMPTS).await {
|
||||
Ok(outcome) if outcome != SweepOutcome::default() => tracing::info!(
|
||||
requeued = outcome.requeued,
|
||||
expired = outcome.expired,
|
||||
"swept expired Werkbank leases"
|
||||
),
|
||||
Ok(_) => {}
|
||||
Err(e) => tracing::error!("Werkbank lease sweep failed: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
use compliance_core::models::dast::DastScanStatus;
|
||||
use compliance_core::models::embedding::EmbeddingBuildStatus;
|
||||
use compliance_core::models::graph::GraphBuildStatus;
|
||||
use compliance_core::models::pentest::PentestStatus;
|
||||
use compliance_core::models::ScanRunStatus;
|
||||
|
||||
/// Parse a status literal the way Mongo documents are read back.
|
||||
fn parse<T: serde::de::DeserializeOwned>(status: &str) -> T {
|
||||
serde_json::from_value(serde_json::Value::String(status.to_string()))
|
||||
.expect("status literal matches the enum's serde name")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rule_statuses_match_the_model_enums() {
|
||||
// The rules use literals so they can be a `const`; this keeps them in
|
||||
// step with the serde names of the enums the models read back.
|
||||
for rule in &ORPHAN_RULES {
|
||||
for status in rule.open.iter().chain([&rule.closed_as]) {
|
||||
match rule.collection {
|
||||
"scan_runs" => {
|
||||
parse::<ScanRunStatus>(status);
|
||||
}
|
||||
"graph_builds" => {
|
||||
parse::<GraphBuildStatus>(status);
|
||||
}
|
||||
"embedding_builds" => {
|
||||
parse::<EmbeddingBuildStatus>(status);
|
||||
}
|
||||
"dast_scan_runs" => {
|
||||
parse::<DastScanStatus>(status);
|
||||
}
|
||||
"pentest_sessions" => {
|
||||
parse::<PentestStatus>(status);
|
||||
}
|
||||
other => panic!("no status enum registered for {other}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_scans_are_interrupted_not_failed() {
|
||||
let scan_rule = ORPHAN_RULES
|
||||
.iter()
|
||||
.find(|r| r.collection == "scan_runs")
|
||||
.expect("scan_runs rule");
|
||||
assert_eq!(
|
||||
parse::<ScanRunStatus>(scan_rule.closed_as),
|
||||
ScanRunStatus::Interrupted
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -216,7 +216,45 @@ impl LlmClient {
|
||||
}
|
||||
|
||||
// Otherwise return content
|
||||
let content = choice.message.content.clone().unwrap_or_default();
|
||||
Ok(LlmResponse::Content(content))
|
||||
let content = choice.message.content.as_deref().unwrap_or_default();
|
||||
Ok(LlmResponse::Content(without_reasoning(content)))
|
||||
}
|
||||
}
|
||||
|
||||
/// `content` without a reasoning model's `<think>…</think>` blocks, which some
|
||||
/// gateways return inline ahead of the answer; the callers parse the answer as
|
||||
/// JSON. An unterminated block (the model ran out of tokens while thinking)
|
||||
/// leaves nothing to parse, so it becomes empty.
|
||||
fn without_reasoning(content: &str) -> String {
|
||||
let mut rest = content;
|
||||
let mut out = String::with_capacity(content.len());
|
||||
while let Some(start) = rest.find("<think>") {
|
||||
out.push_str(&rest[..start]);
|
||||
match rest[start..].find("</think>") {
|
||||
Some(end) => rest = &rest[start + end + "</think>".len()..],
|
||||
None => {
|
||||
rest = "";
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(rest);
|
||||
out.trim().to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod reasoning_tests {
|
||||
use super::without_reasoning;
|
||||
|
||||
#[test]
|
||||
fn a_reasoning_models_thinking_is_not_part_of_the_answer() {
|
||||
assert_eq!(
|
||||
without_reasoning(
|
||||
"<think>the finding is in a test file</think>\n[{\"action\":\"dismiss\"}]"
|
||||
),
|
||||
"[{\"action\":\"dismiss\"}]"
|
||||
);
|
||||
assert_eq!(without_reasoning("[1, 2]"), "[1, 2]");
|
||||
assert_eq!(without_reasoning("<think>still going"), "");
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,8 @@ struct EmbeddingData {
|
||||
/// array (bge-multilingual-gemma2 rejects >25 with "batch size overflow"), so we
|
||||
/// chunk larger corpora — a whole control catalog (~1.8k) would otherwise 500.
|
||||
const EMBED_BATCH_SIZE: usize = 16;
|
||||
// The bge backend takes at most 25 inputs per request.
|
||||
const _: () = assert!(EMBED_BATCH_SIZE <= 25);
|
||||
|
||||
// ── Embedding implementation ───────────────────────────────────
|
||||
|
||||
@@ -111,12 +113,4 @@ mod tests {
|
||||
let out = client().embed(Vec::new()).await.unwrap();
|
||||
assert!(out.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_size_is_within_backend_cap() {
|
||||
assert!(
|
||||
EMBED_BATCH_SIZE <= 25,
|
||||
"must stay under the bge 25-input cap"
|
||||
);
|
||||
}
|
||||
}
|
||||
+244
-135
@@ -49,26 +49,37 @@ Confidence scoring (0-10):
|
||||
Respond with a JSON array, one entry per finding in the same order presented (no markdown fences):
|
||||
[{"id": "<fingerprint>", "action": "confirm|downgrade|upgrade|dismiss", "confidence": 0-10, "rationale": "1-2 sentences", "remediation": "optional fix"}, ...]"#;
|
||||
|
||||
pub async fn triage_findings(
|
||||
llm: &Arc<LlmClient>,
|
||||
findings: &mut Vec<Finding>,
|
||||
/// Most findings one scan sends to the LLM triage, the most severe first.
|
||||
/// A large tree can yield thousands (12,000 on an RTOS reference project); the
|
||||
/// rest stay open, untriaged, which is where they would be without an LLM.
|
||||
const TRIAGE_MAX_FINDINGS: usize = 600;
|
||||
/// Triage calls in flight at once.
|
||||
const TRIAGE_CONCURRENCY: usize = 4;
|
||||
|
||||
/// The findings the LLM triage looks at, by index: the most severe first, at
|
||||
/// most [`TRIAGE_MAX_FINDINGS`].
|
||||
fn triage_selection(findings: &[Finding]) -> Vec<usize> {
|
||||
let mut selected: Vec<usize> = (0..findings.len()).collect();
|
||||
// Stable, so equally severe findings keep their scan order.
|
||||
selected.sort_by(|a, b| findings[*b].severity.cmp(&findings[*a].severity));
|
||||
selected.truncate(TRIAGE_MAX_FINDINGS);
|
||||
selected
|
||||
}
|
||||
|
||||
/// The model's answer for one chunk: its verdicts in chunk order, or `None`
|
||||
/// when the call failed or its answer could not be read.
|
||||
async fn triage_chunk(
|
||||
llm: &LlmClient,
|
||||
chunk: &[&Finding],
|
||||
graph_context: Option<&GraphContext>,
|
||||
) -> usize {
|
||||
let mut passed = 0;
|
||||
chunk_start: usize,
|
||||
) -> Option<Vec<TriageResult>> {
|
||||
let mut user_prompt = String::new();
|
||||
|
||||
// Process findings in chunks to avoid overflowing the LLM context window.
|
||||
for chunk_start in (0..findings.len()).step_by(TRIAGE_CHUNK_SIZE) {
|
||||
let chunk_end = (chunk_start + TRIAGE_CHUNK_SIZE).min(findings.len());
|
||||
let chunk = &mut findings[chunk_start..chunk_end];
|
||||
for (i, finding) in chunk.iter().enumerate() {
|
||||
let file_classification = classify_file_path(finding.file_path.as_deref());
|
||||
|
||||
// Build a combined prompt for the entire chunk.
|
||||
let mut user_prompt = String::new();
|
||||
let mut file_classifications: Vec<String> = Vec::new();
|
||||
|
||||
for (i, finding) in chunk.iter().enumerate() {
|
||||
let file_classification = classify_file_path(finding.file_path.as_deref());
|
||||
|
||||
user_prompt.push_str(&format!(
|
||||
user_prompt.push_str(&format!(
|
||||
"\n--- Finding {} (id: {}) ---\nScanner: {}\nRule: {}\nSeverity: {}\nTitle: {}\nDescription: {}\nFile: {}\nLine: {}\nCode: {}\nFile classification: {}",
|
||||
i + 1,
|
||||
finding.fingerprint,
|
||||
@@ -83,144 +94,180 @@ pub async fn triage_findings(
|
||||
file_classification,
|
||||
));
|
||||
|
||||
// Enrich with surrounding code context if possible
|
||||
if let Some(context) = read_surrounding_context(finding) {
|
||||
user_prompt.push_str(&format!(
|
||||
"\n\n--- Surrounding Code (50 lines) ---\n{context}"
|
||||
));
|
||||
}
|
||||
// Enrich with surrounding code context if possible
|
||||
if let Some(context) = read_surrounding_context(finding) {
|
||||
user_prompt.push_str(&format!(
|
||||
"\n\n--- Surrounding Code (50 lines) ---\n{context}"
|
||||
));
|
||||
}
|
||||
|
||||
// Enrich with graph context if available
|
||||
if let Some(ctx) = graph_context {
|
||||
if let Some(impact) = ctx
|
||||
.impacts
|
||||
.iter()
|
||||
.find(|im| im.finding_id == finding.fingerprint)
|
||||
{
|
||||
user_prompt.push_str(&format!(
|
||||
"\n\n--- Code Graph Context ---\n\
|
||||
// Enrich with graph context if available
|
||||
if let Some(ctx) = graph_context {
|
||||
if let Some(impact) = ctx
|
||||
.impacts
|
||||
.iter()
|
||||
.find(|im| im.finding_id == finding.fingerprint)
|
||||
{
|
||||
user_prompt.push_str(&format!(
|
||||
"\n\n--- Code Graph Context ---\n\
|
||||
Blast radius: {} nodes affected\n\
|
||||
Entry points affected: {}\n\
|
||||
Direct callers: {}\n\
|
||||
Communities affected: {}\n\
|
||||
Call chains: {}",
|
||||
impact.blast_radius,
|
||||
if impact.affected_entry_points.is_empty() {
|
||||
"none".to_string()
|
||||
} else {
|
||||
impact.affected_entry_points.join(", ")
|
||||
},
|
||||
if impact.direct_callers.is_empty() {
|
||||
"none".to_string()
|
||||
} else {
|
||||
impact.direct_callers.join(", ")
|
||||
},
|
||||
impact.affected_communities.len(),
|
||||
impact.call_chains.len(),
|
||||
));
|
||||
}
|
||||
impact.blast_radius,
|
||||
if impact.affected_entry_points.is_empty() {
|
||||
"none".to_string()
|
||||
} else {
|
||||
impact.affected_entry_points.join(", ")
|
||||
},
|
||||
if impact.direct_callers.is_empty() {
|
||||
"none".to_string()
|
||||
} else {
|
||||
impact.direct_callers.join(", ")
|
||||
},
|
||||
impact.affected_communities.len(),
|
||||
impact.call_chains.len(),
|
||||
));
|
||||
}
|
||||
|
||||
user_prompt.push('\n');
|
||||
file_classifications.push(file_classification);
|
||||
}
|
||||
|
||||
// Send the batch to the LLM.
|
||||
match llm
|
||||
.chat(TRIAGE_SYSTEM_PROMPT, &user_prompt, Some(0.1))
|
||||
.await
|
||||
{
|
||||
Ok(response) => {
|
||||
let cleaned = response.trim();
|
||||
let cleaned = if cleaned.starts_with("```") {
|
||||
cleaned
|
||||
.trim_start_matches("```json")
|
||||
.trim_start_matches("```")
|
||||
.trim_end_matches("```")
|
||||
.trim()
|
||||
} else {
|
||||
cleaned
|
||||
};
|
||||
user_prompt.push('\n');
|
||||
}
|
||||
|
||||
match serde_json::from_str::<Vec<TriageResult>>(cleaned) {
|
||||
Ok(results) => {
|
||||
for (idx, finding) in chunk.iter_mut().enumerate() {
|
||||
// Match result by position; fall back to keeping the finding.
|
||||
let Some(result) = results.get(idx) else {
|
||||
finding.status = FindingStatus::Triaged;
|
||||
passed += 1;
|
||||
continue;
|
||||
};
|
||||
let response = match llm
|
||||
.chat(TRIAGE_SYSTEM_PROMPT, &user_prompt, Some(0.1))
|
||||
.await
|
||||
{
|
||||
Ok(response) => response,
|
||||
Err(e) => {
|
||||
tracing::warn!("LLM batch triage failed for chunk starting at {chunk_start}: {e}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let cleaned = response.trim();
|
||||
let cleaned = if cleaned.starts_with("```") {
|
||||
cleaned
|
||||
.trim_start_matches("```json")
|
||||
.trim_start_matches("```")
|
||||
.trim_end_matches("```")
|
||||
.trim()
|
||||
} else {
|
||||
cleaned
|
||||
};
|
||||
match serde_json::from_str::<Vec<TriageResult>>(cleaned) {
|
||||
Ok(results) => Some(results),
|
||||
Err(_) => {
|
||||
tracing::warn!(
|
||||
"Failed to parse batch triage response for chunk starting at {chunk_start}: {cleaned}"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let file_classification = file_classifications
|
||||
.get(idx)
|
||||
.map(|s| s.as_str())
|
||||
.unwrap_or("unknown");
|
||||
/// Triage `findings` with the LLM, in chunks: confirm, re-rate or flag each
|
||||
/// one. Nothing is removed; a flagged finding is kept as "needs review". The
|
||||
/// most severe findings go first, at most [`TRIAGE_MAX_FINDINGS`], and
|
||||
/// [`TRIAGE_CONCURRENCY`] chunks are triaged at a time.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// How many findings passed triage (confirmed or re-rated).
|
||||
pub async fn triage_findings(
|
||||
llm: &Arc<LlmClient>,
|
||||
findings: &mut [Finding],
|
||||
graph_context: Option<&GraphContext>,
|
||||
) -> usize {
|
||||
let selected = triage_selection(findings);
|
||||
if selected.len() < findings.len() {
|
||||
tracing::info!(
|
||||
"LLM triage: the {} most severe of {} findings; the rest stay open",
|
||||
selected.len(),
|
||||
findings.len()
|
||||
);
|
||||
}
|
||||
|
||||
let adjusted_confidence =
|
||||
adjust_confidence(result.confidence, file_classification);
|
||||
finding.confidence = Some(adjusted_confidence);
|
||||
finding.triage_action = Some(result.action.clone());
|
||||
finding.triage_rationale = Some(result.rationale.clone());
|
||||
// Ask for every chunk first (read-only), a few at a time, then apply the
|
||||
// answers.
|
||||
let chunks: Vec<&[usize]> = selected.chunks(TRIAGE_CHUNK_SIZE).collect();
|
||||
let mut answers: Vec<Option<Vec<TriageResult>>> = Vec::with_capacity(chunks.len());
|
||||
{
|
||||
let read: &[Finding] = findings;
|
||||
for (group_no, group) in chunks.chunks(TRIAGE_CONCURRENCY).enumerate() {
|
||||
let batches: Vec<Vec<&Finding>> = group
|
||||
.iter()
|
||||
.map(|indices| indices.iter().map(|&i| &read[i]).collect())
|
||||
.collect();
|
||||
let calls = batches.iter().enumerate().map(|(k, batch)| {
|
||||
let start = (group_no * TRIAGE_CONCURRENCY + k) * TRIAGE_CHUNK_SIZE;
|
||||
triage_chunk(llm, batch, graph_context, start)
|
||||
});
|
||||
answers.extend(futures_util::future::join_all(calls).await);
|
||||
}
|
||||
}
|
||||
let answers = chunks.into_iter().zip(answers);
|
||||
|
||||
if let Some(ref remediation) = result.remediation {
|
||||
finding.remediation = Some(remediation.clone());
|
||||
}
|
||||
|
||||
match result.action.as_str() {
|
||||
"dismiss" => {
|
||||
finding.status = FindingStatus::FalsePositive;
|
||||
}
|
||||
"downgrade" => {
|
||||
finding.severity = downgrade_severity(&finding.severity);
|
||||
finding.status = FindingStatus::Triaged;
|
||||
passed += 1;
|
||||
}
|
||||
"upgrade" => {
|
||||
finding.severity = upgrade_severity(&finding.severity);
|
||||
finding.status = FindingStatus::Triaged;
|
||||
passed += 1;
|
||||
}
|
||||
_ => {
|
||||
// "confirm" or unknown — keep as-is
|
||||
if adjusted_confidence >= 3.0 {
|
||||
finding.status = FindingStatus::Triaged;
|
||||
passed += 1;
|
||||
} else {
|
||||
finding.status = FindingStatus::FalsePositive;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
// Batch parse failure — keep all findings in the chunk.
|
||||
tracing::warn!(
|
||||
"Failed to parse batch triage response for chunk starting at {chunk_start}: {cleaned}"
|
||||
);
|
||||
for finding in chunk.iter_mut() {
|
||||
finding.status = FindingStatus::Triaged;
|
||||
passed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut passed = 0;
|
||||
for (indices, answer) in answers {
|
||||
for (pos, &i) in indices.iter().enumerate() {
|
||||
let finding = &mut findings[i];
|
||||
// No usable answer for the chunk, or none for this finding: keep
|
||||
// it as reported.
|
||||
let Some(result) = answer.as_ref().and_then(|results| results.get(pos)) else {
|
||||
finding.status = FindingStatus::Triaged;
|
||||
passed += 1;
|
||||
continue;
|
||||
};
|
||||
let file_classification = classify_file_path(finding.file_path.as_deref());
|
||||
let adjusted_confidence = adjust_confidence(result.confidence, &file_classification);
|
||||
finding.confidence = Some(adjusted_confidence);
|
||||
finding.triage_action = Some(result.action.clone());
|
||||
finding.triage_rationale = Some(result.rationale.clone());
|
||||
if let Some(ref remediation) = result.remediation {
|
||||
finding.remediation = Some(remediation.clone());
|
||||
}
|
||||
Err(e) => {
|
||||
// On LLM error, keep all findings in the chunk.
|
||||
tracing::warn!("LLM batch triage failed for chunk starting at {chunk_start}: {e}");
|
||||
for finding in chunk.iter_mut() {
|
||||
finding.status = FindingStatus::Triaged;
|
||||
passed += 1;
|
||||
}
|
||||
if apply_action(finding, &result.action, adjusted_confidence) {
|
||||
passed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove false positives
|
||||
findings.retain(|f| f.status != FindingStatus::FalsePositive);
|
||||
passed
|
||||
}
|
||||
|
||||
/// Apply the model's `action` to `finding`; `true` when it passed triage.
|
||||
///
|
||||
/// A dismissed or low-confidence finding is kept as
|
||||
/// [`FindingStatus::NeedsReview`], never deleted: the model's rationale goes
|
||||
/// with it, and a person decides.
|
||||
fn apply_action(finding: &mut Finding, action: &str, adjusted_confidence: f64) -> bool {
|
||||
match action {
|
||||
"dismiss" => {
|
||||
finding.status = FindingStatus::NeedsReview;
|
||||
false
|
||||
}
|
||||
"downgrade" => {
|
||||
finding.severity = downgrade_severity(&finding.severity);
|
||||
finding.status = FindingStatus::Triaged;
|
||||
true
|
||||
}
|
||||
"upgrade" => {
|
||||
finding.severity = upgrade_severity(&finding.severity);
|
||||
finding.status = FindingStatus::Triaged;
|
||||
true
|
||||
}
|
||||
// "confirm" or unknown: kept as reported when the model is confident.
|
||||
_ if adjusted_confidence >= 3.0 => {
|
||||
finding.status = FindingStatus::Triaged;
|
||||
true
|
||||
}
|
||||
_ => {
|
||||
finding.status = FindingStatus::NeedsReview;
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read ~50 lines of surrounding code from the file at the finding's location
|
||||
fn read_surrounding_context(finding: &Finding) -> Option<String> {
|
||||
let file_path = finding.file_path.as_deref()?;
|
||||
@@ -347,7 +394,69 @@ fn default_action() -> String {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
#[test]
|
||||
fn the_triage_takes_the_most_severe_findings_first_and_stops_at_the_cap() {
|
||||
use compliance_core::models::{ScanType, Severity};
|
||||
let finding = |severity| {
|
||||
Finding::new(
|
||||
"t".into(),
|
||||
"f".into(),
|
||||
"semgrep".into(),
|
||||
ScanType::Sast,
|
||||
"x".into(),
|
||||
"d".into(),
|
||||
severity,
|
||||
)
|
||||
};
|
||||
let findings = vec![
|
||||
finding(Severity::Low),
|
||||
finding(Severity::Critical),
|
||||
finding(Severity::Medium),
|
||||
];
|
||||
assert_eq!(triage_selection(&findings), [1, 2, 0]);
|
||||
|
||||
let many: Vec<Finding> = (0..TRIAGE_MAX_FINDINGS + 10)
|
||||
.map(|_| finding(Severity::Info))
|
||||
.collect();
|
||||
assert_eq!(triage_selection(&many).len(), TRIAGE_MAX_FINDINGS);
|
||||
}
|
||||
use super::*;
|
||||
use compliance_core::models::scan::ScanType;
|
||||
|
||||
fn finding() -> Finding {
|
||||
Finding::new(
|
||||
"repo".into(),
|
||||
"fp".into(),
|
||||
"semgrep".into(),
|
||||
ScanType::Sast,
|
||||
"strcpy into a fixed buffer".into(),
|
||||
"desc".into(),
|
||||
Severity::High,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dismissed_finding_is_kept_for_review() {
|
||||
let mut f = finding();
|
||||
assert!(!apply_action(&mut f, "dismiss", 9.0));
|
||||
assert_eq!(f.status, FindingStatus::NeedsReview);
|
||||
|
||||
let mut unsure = finding();
|
||||
assert!(!apply_action(&mut unsure, "confirm", 2.0));
|
||||
assert_eq!(unsure.status, FindingStatus::NeedsReview);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confirmed_and_rerated_findings_pass() {
|
||||
let mut f = finding();
|
||||
assert!(apply_action(&mut f, "confirm", 7.0));
|
||||
assert_eq!(f.status, FindingStatus::Triaged);
|
||||
|
||||
let mut lower = finding();
|
||||
assert!(apply_action(&mut lower, "downgrade", 7.0));
|
||||
assert_eq!(lower.severity, Severity::Medium);
|
||||
}
|
||||
use compliance_core::models::Severity;
|
||||
|
||||
// ── classify_file_path ───────────────────────────────────────
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use compliance_agent::{agent, api, config, database, scheduler, ssh, webhooks};
|
||||
use compliance_agent::{agent, api, config, database, lifecycle, scheduler, secrets, webhooks};
|
||||
use compliance_core::shutdown;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
@@ -13,17 +14,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tracing::info!(
|
||||
chrome_ws_url = std::env::var("CHROME_WS_URL").ok().as_deref(),
|
||||
pentest_email = std::env::var("PENTEST_VERIFICATION_EMAIL").ok().as_deref(),
|
||||
encryption_key_set = std::env::var("PENTEST_ENCRYPTION_KEY").is_ok(),
|
||||
secrets_key_set = std::env::var("SECRETS_ENCRYPTION_KEY").is_ok(),
|
||||
"Loading configuration..."
|
||||
);
|
||||
let config = config::load_config()?;
|
||||
|
||||
// Ensure SSH key pair exists for cloning private repos
|
||||
match ssh::ensure_ssh_key(&config.ssh_key_path) {
|
||||
Ok(pubkey) => tracing::info!("SSH public key: {}", pubkey.trim()),
|
||||
Err(e) => tracing::warn!("SSH key generation skipped: {e}"),
|
||||
}
|
||||
|
||||
tracing::info!("Connecting to MongoDB...");
|
||||
// Per-tenant pool only — the agent has no shared "default" database
|
||||
// after M7.2-D. `mongodb_database` is now the db-name prefix used
|
||||
@@ -33,6 +28,29 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
let agent = agent::ComplianceAgent::new(config.clone(), db_pool);
|
||||
|
||||
// Before anything can start a new run, close the runs the previous agent
|
||||
// process left open when it stopped.
|
||||
match lifecycle::recover_orphaned_runs(&agent.db_pool, chrono::Utc::now()).await {
|
||||
Ok(0) => {}
|
||||
Ok(closed) => tracing::warn!(closed, "closed runs left open by the previous agent"),
|
||||
Err(e) => tracing::error!("closing runs left open by the previous agent failed: {e}"),
|
||||
}
|
||||
|
||||
// Credentials stored before sealing existed are sealed now, before any
|
||||
// handler can read one back.
|
||||
match secrets::seal_stored_credentials(&agent.db_pool, &agent.secrets).await {
|
||||
Ok(0) => {}
|
||||
Ok(sealed) => tracing::info!(targets = sealed, "sealed stored credentials"),
|
||||
Err(e) => tracing::error!("sealing stored credentials failed: {e}"),
|
||||
}
|
||||
|
||||
// SIGTERM or Ctrl+C fires `stop`; each server then drains on its own.
|
||||
let (trigger, stop) = shutdown::channel();
|
||||
tokio::spawn(async move {
|
||||
shutdown::signal().await;
|
||||
trigger.fire();
|
||||
});
|
||||
|
||||
tracing::info!("Starting scheduler...");
|
||||
let scheduler_agent = agent.clone();
|
||||
let scheduler_handle = tokio::spawn(async move {
|
||||
@@ -41,17 +59,28 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
});
|
||||
|
||||
tracing::info!("Starting webhook server...");
|
||||
let sweeper_handle = tokio::spawn(lifecycle::run_werkbank_sweeper(
|
||||
agent.db_pool.clone(),
|
||||
stop.clone(),
|
||||
));
|
||||
|
||||
tracing::info!("Starting webhook server on port {}...", config.webhook_port);
|
||||
let webhook_agent = agent.clone();
|
||||
let webhook_stop = stop.clone();
|
||||
let webhook_handle = tokio::spawn(async move {
|
||||
if let Err(e) = webhooks::start_webhook_server(&webhook_agent).await {
|
||||
if let Err(e) = webhooks::start_webhook_server(&webhook_agent, webhook_stop).await {
|
||||
tracing::error!("Webhook server error: {e}");
|
||||
}
|
||||
});
|
||||
|
||||
tracing::info!("Starting REST API on port {}...", config.agent_port);
|
||||
api::start_api_server(agent, config.agent_port).await?;
|
||||
api::start_api_server(agent, config.agent_port, stop).await?;
|
||||
|
||||
let _ = tokio::join!(scheduler_handle, webhook_handle);
|
||||
// The API has drained; the webhook server and sweeper saw the same signal
|
||||
// and finish within the same grace period. Scans still running are cut
|
||||
// off here and closed as `interrupted` at the next start.
|
||||
let _ = tokio::join!(webhook_handle, sweeper_handle);
|
||||
scheduler_handle.abort();
|
||||
tracing::info!("Agent stopped");
|
||||
Ok(())
|
||||
}
|
||||
@@ -306,45 +306,13 @@ mod tests {
|
||||
use secrecy::SecretString;
|
||||
|
||||
fn make_config_no_keycloak() -> AgentConfig {
|
||||
// Dev defaults: no Keycloak, so `cleanup_test_user` takes the
|
||||
// "identity provider not configured" path.
|
||||
AgentConfig {
|
||||
mongodb_uri: String::new(),
|
||||
mongodb_database: String::new(),
|
||||
litellm_url: String::new(),
|
||||
litellm_api_key: SecretString::from(String::new()),
|
||||
litellm_model: String::new(),
|
||||
litellm_embed_model: String::new(),
|
||||
github_token: None,
|
||||
github_webhook_secret: None,
|
||||
gitlab_url: None,
|
||||
gitlab_token: None,
|
||||
gitlab_webhook_secret: None,
|
||||
jira_url: None,
|
||||
jira_email: None,
|
||||
jira_api_token: None,
|
||||
jira_project_key: None,
|
||||
searxng_url: None,
|
||||
nvd_api_key: None,
|
||||
agent_port: 3001,
|
||||
scan_schedule: String::new(),
|
||||
cve_monitor_schedule: String::new(),
|
||||
git_clone_base_path: String::new(),
|
||||
artifact_store_base_path: String::new(),
|
||||
ssh_key_path: String::new(),
|
||||
keycloak_url: None,
|
||||
keycloak_realm: None,
|
||||
keycloak_admin_username: None,
|
||||
keycloak_admin_password: None,
|
||||
pentest_verification_email: None,
|
||||
pentest_imap_host: None,
|
||||
pentest_imap_port: None,
|
||||
pentest_imap_tls: true,
|
||||
pentest_imap_username: None,
|
||||
pentest_imap_password: None,
|
||||
admin_api_token: None,
|
||||
tenant_registry_url: None,
|
||||
plc_runtime: compliance_core::PlcRuntimeConfig::default(),
|
||||
werkbank_runner_token: None,
|
||||
breakpilot: compliance_core::config::BreakpilotConfig::default(),
|
||||
keycloak_audience: None,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
use aes_gcm::aead::AeadCore;
|
||||
use aes_gcm::{
|
||||
aead::{Aead, KeyInit, OsRng},
|
||||
Aes256Gcm, Nonce,
|
||||
};
|
||||
use base64::Engine;
|
||||
|
||||
/// Load the 32-byte encryption key from PENTEST_ENCRYPTION_KEY env var.
|
||||
/// Returns None if not set or invalid length.
|
||||
pub fn load_encryption_key() -> Option<[u8; 32]> {
|
||||
let hex_key = std::env::var("PENTEST_ENCRYPTION_KEY").ok()?;
|
||||
let bytes = hex::decode(hex_key).ok()?;
|
||||
if bytes.len() != 32 {
|
||||
return None;
|
||||
}
|
||||
let mut key = [0u8; 32];
|
||||
key.copy_from_slice(&bytes);
|
||||
Some(key)
|
||||
}
|
||||
|
||||
/// Encrypt a plaintext string. Returns base64-encoded nonce+ciphertext.
|
||||
/// Returns the original string if no encryption key is available.
|
||||
pub fn encrypt(plaintext: &str) -> String {
|
||||
let Some(key_bytes) = load_encryption_key() else {
|
||||
return plaintext.to_string();
|
||||
};
|
||||
let Ok(cipher) = Aes256Gcm::new_from_slice(&key_bytes) else {
|
||||
return plaintext.to_string();
|
||||
};
|
||||
let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
|
||||
let Ok(ciphertext) = cipher.encrypt(&nonce, plaintext.as_bytes()) else {
|
||||
return plaintext.to_string();
|
||||
};
|
||||
let mut combined = nonce.to_vec();
|
||||
combined.extend_from_slice(&ciphertext);
|
||||
base64::engine::general_purpose::STANDARD.encode(&combined)
|
||||
}
|
||||
|
||||
/// Decrypt a base64-encoded nonce+ciphertext string.
|
||||
/// Returns None if decryption fails.
|
||||
pub fn decrypt(encrypted: &str) -> Option<String> {
|
||||
let key_bytes = load_encryption_key()?;
|
||||
let cipher = Aes256Gcm::new_from_slice(&key_bytes).ok()?;
|
||||
let combined = base64::engine::general_purpose::STANDARD
|
||||
.decode(encrypted)
|
||||
.ok()?;
|
||||
if combined.len() < 12 {
|
||||
return None;
|
||||
}
|
||||
let (nonce_bytes, ciphertext) = combined.split_at(12);
|
||||
let nonce = Nonce::from_slice(nonce_bytes);
|
||||
let plaintext = cipher.decrypt(nonce, ciphertext).ok()?;
|
||||
String::from_utf8(plaintext).ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Mutex;
|
||||
|
||||
// Guard to serialize tests that touch env vars
|
||||
static ENV_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
fn with_key<F: FnOnce()>(hex_key: &str, f: F) {
|
||||
let _guard = ENV_LOCK.lock();
|
||||
unsafe { std::env::set_var("PENTEST_ENCRYPTION_KEY", hex_key) };
|
||||
f();
|
||||
unsafe { std::env::remove_var("PENTEST_ENCRYPTION_KEY") };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip() {
|
||||
let key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
with_key(key, || {
|
||||
let plaintext = "my_secret_password";
|
||||
let encrypted = encrypt(plaintext);
|
||||
assert_ne!(encrypted, plaintext);
|
||||
let decrypted = decrypt(&encrypted);
|
||||
assert_eq!(decrypted, Some(plaintext.to_string()));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_key_fails() {
|
||||
let _guard = ENV_LOCK.lock();
|
||||
let key1 = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
let key2 = "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789";
|
||||
let encrypted = {
|
||||
unsafe { std::env::set_var("PENTEST_ENCRYPTION_KEY", key1) };
|
||||
let e = encrypt("secret");
|
||||
unsafe { std::env::remove_var("PENTEST_ENCRYPTION_KEY") };
|
||||
e
|
||||
};
|
||||
unsafe { std::env::set_var("PENTEST_ENCRYPTION_KEY", key2) };
|
||||
assert!(decrypt(&encrypted).is_none());
|
||||
unsafe { std::env::remove_var("PENTEST_ENCRYPTION_KEY") };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_key_passthrough() {
|
||||
let _guard = ENV_LOCK.lock();
|
||||
unsafe { std::env::remove_var("PENTEST_ENCRYPTION_KEY") };
|
||||
let result = encrypt("plain");
|
||||
assert_eq!(result, "plain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupted_ciphertext() {
|
||||
let key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
with_key(key, || {
|
||||
assert!(decrypt("not-valid-base64!!!").is_none());
|
||||
// Valid base64 but wrong content
|
||||
let garbage = base64::engine::general_purpose::STANDARD.encode(b"tooshort");
|
||||
assert!(decrypt(&garbage).is_none());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
pub mod cleanup;
|
||||
mod context;
|
||||
pub mod crypto;
|
||||
pub mod orchestrator;
|
||||
mod prompt_builder;
|
||||
pub mod report;
|
||||
|
||||
@@ -7,6 +7,7 @@ use tokio::sync::{broadcast, watch};
|
||||
use compliance_core::models::dast::DastTarget;
|
||||
use compliance_core::models::pentest::*;
|
||||
use compliance_core::traits::pentest_tool::PentestToolContext;
|
||||
use compliance_core::NetGuard;
|
||||
use compliance_dast::ToolRegistry;
|
||||
|
||||
use crate::database::Database;
|
||||
@@ -33,9 +34,10 @@ impl PentestOrchestrator {
|
||||
db: Database,
|
||||
event_tx: broadcast::Sender<PentestEvent>,
|
||||
pause_rx: Option<watch::Receiver<bool>>,
|
||||
net_guard: NetGuard,
|
||||
) -> Self {
|
||||
Self {
|
||||
tool_registry: ToolRegistry::new(),
|
||||
tool_registry: ToolRegistry::new(net_guard),
|
||||
llm,
|
||||
db,
|
||||
event_tx,
|
||||
|
||||
@@ -5,12 +5,6 @@ use compliance_core::models::sbom::SbomEntry;
|
||||
|
||||
use super::orchestrator::PentestOrchestrator;
|
||||
|
||||
/// Attempt to decrypt a field; if decryption fails, return the original value
|
||||
/// (which may be plaintext from before encryption was enabled).
|
||||
fn decrypt_field(value: &str) -> String {
|
||||
super::crypto::decrypt(value).unwrap_or_else(|| value.to_string())
|
||||
}
|
||||
|
||||
/// Build additional prompt sections from PentestConfig when present.
|
||||
fn build_config_sections(config: &PentestConfig) -> String {
|
||||
let mut sections = String::new();
|
||||
@@ -20,13 +14,12 @@ fn build_config_sections(config: &PentestConfig) -> String {
|
||||
AuthMode::Manual => {
|
||||
sections.push_str("\n## Authentication\n");
|
||||
sections.push_str("- **Mode**: Manual credentials\n");
|
||||
// Callers hand in opened credentials (`SecretBox::open_in_place`).
|
||||
if let Some(ref u) = config.auth.username {
|
||||
let decrypted = decrypt_field(u);
|
||||
sections.push_str(&format!("- **Username**: {decrypted}\n"));
|
||||
sections.push_str(&format!("- **Username**: {u}\n"));
|
||||
}
|
||||
if let Some(ref p) = config.auth.password {
|
||||
let decrypted = decrypt_field(p);
|
||||
sections.push_str(&format!("- **Password**: {decrypted}\n"));
|
||||
sections.push_str(&format!("- **Password**: {p}\n"));
|
||||
}
|
||||
sections.push_str(
|
||||
"Use these credentials to log in before testing authenticated endpoints.\n",
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
//! C and C++ static analysis with cppcheck.
|
||||
//!
|
||||
//! semgrep matches patterns; cppcheck follows values through the code, which is
|
||||
//! what finds the defects that matter in firmware: out-of-bounds writes,
|
||||
//! uninitialised reads, null dereferences, leaks. It parses and never runs the
|
||||
//! code, so it is safe on a tenant's tree.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use compliance_core::models::{Finding, ScanType, Severity};
|
||||
use compliance_core::traits::{ScanOutput, Scanner};
|
||||
use compliance_core::CoreError;
|
||||
|
||||
use crate::pipeline::dedup;
|
||||
use crate::pipeline::source_text::{read_lines, relative_path};
|
||||
use crate::pipeline::vendor::walk_outside;
|
||||
|
||||
/// Compilation units cppcheck analyses; headers are read through them.
|
||||
const SOURCE_EXTENSIONS: &[&str] = &["c", "cc", "cpp", "cxx"];
|
||||
|
||||
/// Include directories passed as `-I`, at most. They only help cppcheck
|
||||
/// resolve macros such as array sizes; beyond this the parse gets slow.
|
||||
const MAX_INCLUDE_DIRS: usize = 64;
|
||||
|
||||
/// Checks that report on the analysis itself, not on the code.
|
||||
const ANALYSIS_NOTES: &[&str] = &[
|
||||
"missingInclude",
|
||||
"missingIncludeSystem",
|
||||
"toomanyconfigs",
|
||||
"checkersReport",
|
||||
"unmatchedSuppression",
|
||||
"normalCheckLevelMaxBranches",
|
||||
"noValidConfiguration",
|
||||
"syntaxError",
|
||||
"internalAstError",
|
||||
"unknownMacro",
|
||||
"preprocessorErrorDirective",
|
||||
];
|
||||
|
||||
/// cppcheck over the C/C++ sources of a tree, skipping vendor directories.
|
||||
///
|
||||
/// The files are listed explicitly rather than excluded with `-i`: cppcheck
|
||||
/// matches `-i Drivers` against any path component, which would also skip a
|
||||
/// customer's own `app/Drivers/`.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct CppcheckScanner {
|
||||
/// Compilation units to analyse, relative to the tree.
|
||||
sources: Vec<String>,
|
||||
/// Include directories (relative to the tree), for macro resolution.
|
||||
include: Vec<String>,
|
||||
}
|
||||
|
||||
impl CppcheckScanner {
|
||||
/// Prepare a scan of `root` that skips the `excluded` directories (see
|
||||
/// [`crate::pipeline::vendor`]). `None` when the tree has no C or C++
|
||||
/// outside them. Walks the tree, so call it off the async runtime.
|
||||
pub fn for_tree(root: &Path, excluded: &[String]) -> Option<Self> {
|
||||
let mut sources: Vec<String> = walk_outside(root, excluded)
|
||||
.filter(|e| e.file_type().is_file() && is_compilation_unit(e.path()))
|
||||
.filter_map(|e| {
|
||||
e.path()
|
||||
.strip_prefix(root)
|
||||
.ok()
|
||||
.map(|p| p.to_string_lossy().replace('\\', "/"))
|
||||
})
|
||||
.collect();
|
||||
sources.sort();
|
||||
(!sources.is_empty()).then(|| Self {
|
||||
include: include_dirs(root),
|
||||
sources,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Scanner for CppcheckScanner {
|
||||
fn name(&self) -> &str {
|
||||
"cppcheck"
|
||||
}
|
||||
|
||||
fn scan_type(&self) -> ScanType {
|
||||
ScanType::Sast
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all)]
|
||||
async fn scan(&self, repo_path: &Path, repo_id: &str) -> Result<ScanOutput, CoreError> {
|
||||
let mut cmd = crate::pipeline::tool_cmd::tool("cppcheck", &[]);
|
||||
cmd.args([
|
||||
"--xml",
|
||||
"--xml-version=2",
|
||||
"--enable=warning,portability",
|
||||
"--inconclusive",
|
||||
"--max-configs=1",
|
||||
"-j2",
|
||||
"--quiet",
|
||||
]);
|
||||
for check in [
|
||||
"missingInclude",
|
||||
"missingIncludeSystem",
|
||||
"unmatchedSuppression",
|
||||
] {
|
||||
cmd.arg(format!("--suppress={check}"));
|
||||
}
|
||||
for dir in &self.include {
|
||||
cmd.arg(format!("-I{dir}"));
|
||||
}
|
||||
let list = FileList::write(&self.sources).map_err(|e| CoreError::Scanner {
|
||||
scanner: "cppcheck".to_string(),
|
||||
source: Box::new(e),
|
||||
})?;
|
||||
// Relative to the tree, so reported paths are too.
|
||||
cmd.arg(format!("--file-list={}", list.path().display()))
|
||||
.current_dir(repo_path);
|
||||
|
||||
let output = tokio::time::timeout(std::time::Duration::from_secs(900), cmd.output())
|
||||
.await
|
||||
.map_err(|_| CoreError::Scanner {
|
||||
scanner: "cppcheck".to_string(),
|
||||
source: "timed out after 15 minutes".into(),
|
||||
})?
|
||||
.map_err(|e| CoreError::Scanner {
|
||||
scanner: "cppcheck".to_string(),
|
||||
source: Box::new(e),
|
||||
})?;
|
||||
|
||||
// The XML report goes to stderr.
|
||||
let report = String::from_utf8_lossy(&output.stderr);
|
||||
let issues = parse_report(&report).map_err(|e| CoreError::Scanner {
|
||||
scanner: "cppcheck".to_string(),
|
||||
source: format!("unreadable report (exit {}): {e}", output.status).into(),
|
||||
})?;
|
||||
let findings = issues
|
||||
.into_iter()
|
||||
.map(|issue| issue.into_finding(repo_path, repo_id))
|
||||
.collect();
|
||||
Ok(ScanOutput {
|
||||
findings,
|
||||
sbom_entries: Vec::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// One defect cppcheck reported.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
struct Issue {
|
||||
id: String,
|
||||
severity: String,
|
||||
msg: String,
|
||||
verbose: String,
|
||||
cwe: Option<u32>,
|
||||
file: String,
|
||||
line: u32,
|
||||
}
|
||||
|
||||
impl Issue {
|
||||
fn into_finding(self, root: &Path, repo_id: &str) -> Finding {
|
||||
let file = relative_path(root, &self.file);
|
||||
let fingerprint = dedup::compute_fingerprint(&[
|
||||
repo_id,
|
||||
"cppcheck",
|
||||
&self.id,
|
||||
&file,
|
||||
&self.line.to_string(),
|
||||
]);
|
||||
let mut finding = Finding::new(
|
||||
repo_id.to_string(),
|
||||
fingerprint,
|
||||
"cppcheck".to_string(),
|
||||
ScanType::Sast,
|
||||
self.msg,
|
||||
self.verbose,
|
||||
map_severity(&self.severity),
|
||||
);
|
||||
finding.code_snippet = read_lines(root, &file, self.line, self.line);
|
||||
finding.rule_id = Some(self.id);
|
||||
finding.cwe = self.cwe.map(|n| format!("CWE-{n}"));
|
||||
finding.line_number = Some(self.line);
|
||||
finding.file_path = Some(file);
|
||||
finding
|
||||
}
|
||||
}
|
||||
|
||||
/// cppcheck's severity levels, as ours.
|
||||
fn map_severity(level: &str) -> Severity {
|
||||
match level {
|
||||
"error" => Severity::High,
|
||||
"warning" => Severity::Medium,
|
||||
"portability" | "performance" | "style" => Severity::Low,
|
||||
_ => Severity::Info,
|
||||
}
|
||||
}
|
||||
|
||||
/// The defects in a cppcheck XML v2 report. Analysis notes (missing includes,
|
||||
/// configuration limits, parse failures) and entries without a location are
|
||||
/// left out: they say nothing about the customer's code.
|
||||
fn parse_report(xml: &str) -> Result<Vec<Issue>, roxmltree::Error> {
|
||||
let start = xml.find("<?xml").unwrap_or(0);
|
||||
let doc = roxmltree::Document::parse(&xml[start..])?;
|
||||
let issues = doc
|
||||
.descendants()
|
||||
.filter(|n| n.has_tag_name("error"))
|
||||
.filter_map(|n| {
|
||||
let id = n.attribute("id")?;
|
||||
let severity = n.attribute("severity").unwrap_or_default();
|
||||
if ANALYSIS_NOTES.contains(&id) || matches!(severity, "information" | "debug") {
|
||||
return None;
|
||||
}
|
||||
let location = n.children().find(|c| c.has_tag_name("location"))?;
|
||||
Some(Issue {
|
||||
id: id.to_string(),
|
||||
severity: severity.to_string(),
|
||||
msg: n.attribute("msg").unwrap_or(id).to_string(),
|
||||
verbose: n
|
||||
.attribute("verbose")
|
||||
.or(n.attribute("msg"))
|
||||
.unwrap_or(id)
|
||||
.to_string(),
|
||||
cwe: n
|
||||
.attribute("cwe")
|
||||
.and_then(|c| c.parse().ok())
|
||||
.filter(|c| *c > 0),
|
||||
file: location.attribute("file")?.to_string(),
|
||||
line: location.attribute("line")?.parse().ok()?,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Ok(issues)
|
||||
}
|
||||
|
||||
/// Directories named `inc` or `include` (any case), vendor ones included:
|
||||
/// their headers define the macros the customer's code uses.
|
||||
fn include_dirs(root: &Path) -> Vec<String> {
|
||||
let mut dirs: Vec<String> = walk_outside(root, &[])
|
||||
.filter(|e| e.file_type().is_dir())
|
||||
.filter(|e| {
|
||||
let name = e.file_name().to_string_lossy();
|
||||
name.eq_ignore_ascii_case("inc") || name.eq_ignore_ascii_case("include")
|
||||
})
|
||||
.filter_map(|e| {
|
||||
e.path()
|
||||
.strip_prefix(root)
|
||||
.ok()
|
||||
.map(|p| p.to_string_lossy().replace('\\', "/"))
|
||||
})
|
||||
.collect();
|
||||
dirs.sort();
|
||||
dirs.truncate(MAX_INCLUDE_DIRS);
|
||||
dirs
|
||||
}
|
||||
|
||||
fn is_compilation_unit(path: &Path) -> bool {
|
||||
path.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.is_some_and(|e| SOURCE_EXTENSIONS.contains(&e.to_ascii_lowercase().as_str()))
|
||||
}
|
||||
|
||||
/// The list of files handed to cppcheck, in a temporary file removed on drop.
|
||||
struct FileList(std::path::PathBuf);
|
||||
|
||||
impl FileList {
|
||||
fn write(sources: &[String]) -> std::io::Result<Self> {
|
||||
let path = std::env::temp_dir().join(format!("cs-cppcheck-{}.lst", uuid::Uuid::new_v4()));
|
||||
std::fs::write(&path, sources.join("\n"))?;
|
||||
Ok(Self(path))
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FileList {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const REPORT: &str = r#"Checking ...
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<results version="2">
|
||||
<cppcheck version="2.10"/>
|
||||
<errors>
|
||||
<error id="arrayIndexOutOfBounds" severity="error" msg="Array 'readings[8]' accessed at index 8, which is out of bounds." verbose="Array 'readings[8]' accessed at index 8, which is out of bounds." cwe="788" file0="Core/Src/sensors.c">
|
||||
<location file="Core/Src/sensors.c" line="15" column="17" info="Array index out of bounds"/>
|
||||
<location file="Core/Src/sensors.c" line="14" column="23" info="Assuming that condition 'i<=8' is not redundant"/>
|
||||
</error>
|
||||
<error id="uninitvar" severity="error" msg="Uninitialized variable: limit" verbose="Uninitialized variable: limit" cwe="457" file0="Core/Src/sensors.c">
|
||||
<location file="Core/Src/sensors.c" line="19" column="15"/>
|
||||
</error>
|
||||
<error id="missingIncludeSystem" severity="information" msg="Include file not found"/>
|
||||
<error id="checkersReport" severity="information" msg="Active checkers: 106/592"/>
|
||||
</errors>
|
||||
</results>"#;
|
||||
|
||||
#[test]
|
||||
fn a_report_yields_defects_not_analysis_notes() {
|
||||
let issues = parse_report(REPORT).expect("parse");
|
||||
let ids: Vec<_> = issues.iter().map(|i| i.id.as_str()).collect();
|
||||
assert_eq!(ids, ["arrayIndexOutOfBounds", "uninitvar"]);
|
||||
// The first location is where the defect is.
|
||||
assert_eq!(issues[0].line, 15);
|
||||
assert_eq!(issues[0].cwe, Some(788));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_defect_becomes_a_finding_with_cwe_and_a_relative_location() {
|
||||
let issue = parse_report(REPORT).expect("parse").remove(1);
|
||||
let finding = issue.into_finding(Path::new("/work/t/a"), "target-1");
|
||||
assert_eq!(finding.scanner, "cppcheck");
|
||||
assert_eq!(finding.rule_id.as_deref(), Some("uninitvar"));
|
||||
assert_eq!(finding.cwe.as_deref(), Some("CWE-457"));
|
||||
assert_eq!(finding.file_path.as_deref(), Some("Core/Src/sensors.c"));
|
||||
assert_eq!(finding.line_number, Some(19));
|
||||
assert_eq!(finding.severity, Severity::High);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_or_garbled_report_is_an_error_or_empty() {
|
||||
assert!(parse_report("<results version=\"2\"><errors/></results>")
|
||||
.expect("parse")
|
||||
.is_empty());
|
||||
assert!(parse_report("not xml at all").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vendor_directories_are_left_out() {
|
||||
let root = std::env::temp_dir().join(format!("cs-cppcheck-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(root.join("Drivers/HAL/Src")).expect("mkdir");
|
||||
std::fs::create_dir_all(root.join("Core/Inc")).expect("mkdir");
|
||||
std::fs::write(root.join("Drivers/HAL/Src/hal.c"), "int x;").expect("write");
|
||||
|
||||
let vendor = vec!["Drivers".to_string()];
|
||||
assert!(
|
||||
CppcheckScanner::for_tree(&root, &vendor).is_none(),
|
||||
"only vendor C code: nothing to check"
|
||||
);
|
||||
|
||||
std::fs::write(root.join("Core/main.c"), "int main(void){return 0;}").expect("write");
|
||||
// A customer's own directory that happens to be called Drivers stays in.
|
||||
std::fs::create_dir_all(root.join("app/Drivers")).expect("mkdir");
|
||||
std::fs::write(root.join("app/Drivers/uart.c"), "int y;").expect("write");
|
||||
let scanner = CppcheckScanner::for_tree(&root, &vendor).expect("customer C code");
|
||||
assert_eq!(scanner.sources, ["Core/main.c", "app/Drivers/uart.c"]);
|
||||
assert_eq!(scanner.include, ["Core/Inc"]);
|
||||
std::fs::remove_dir_all(&root).ok();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,15 @@
|
||||
use compliance_core::models::{CveAlert, CveSource, SbomEntry, VulnRef};
|
||||
use compliance_core::CoreError;
|
||||
|
||||
use crate::pipeline::embedded_versions::{self, EMBEDDED_MANAGER};
|
||||
use crate::pipeline::nvd_cpe::{self, NvdCve, NvdProduct};
|
||||
|
||||
/// Every CODESYS product: advisories key off the runtime's version.
|
||||
const CODESYS: NvdProduct = NvdProduct {
|
||||
match_string: "cpe:2.3:a:codesys",
|
||||
marker: ":codesys:",
|
||||
};
|
||||
|
||||
pub struct CveScanner {
|
||||
http: reqwest::Client,
|
||||
#[allow(dead_code)]
|
||||
@@ -212,43 +221,90 @@ impl CveScanner {
|
||||
/// the internal `Cmp*`/`Sys*` library names OSV-by-purl would look up. So we
|
||||
/// find the runtime SBOM entry, pull every `cpe:2.3:a:codesys:*` CVE from NVD,
|
||||
/// and keep the ones whose affected-version range covers our runtime version.
|
||||
/// Best-effort: returns empty without an NVD key, on a network error, or when
|
||||
/// no CODESYS runtime component is present.
|
||||
pub async fn scan_codesys(&self, repo_id: &str, entries: &mut [SbomEntry]) -> Vec<CveAlert> {
|
||||
/// Nothing is looked up when no CODESYS runtime component is present; a
|
||||
/// lookup that fails is reported in [`CveLookup::unchecked`].
|
||||
pub async fn scan_codesys(&self, repo_id: &str, entries: &mut [SbomEntry]) -> CveLookup {
|
||||
let Some((name, version)) = codesys_runtime(entries) else {
|
||||
return Vec::new();
|
||||
return CveLookup::default();
|
||||
};
|
||||
let url = "https://services.nvd.nist.gov/rest/json/cves/2.0\
|
||||
?virtualMatchString=cpe:2.3:a:codesys";
|
||||
let mut req = self.http.get(url);
|
||||
if let Some(key) = &self.nvd_api_key {
|
||||
req = req.header("apiKey", key.as_str());
|
||||
}
|
||||
let body: serde_json::Value = match req.send().await {
|
||||
Ok(r) if r.status().is_success() => match r.json().await {
|
||||
Ok(b) => b,
|
||||
Err(e) => {
|
||||
tracing::warn!("CODESYS NVD parse failed: {e}");
|
||||
return Vec::new();
|
||||
match nvd_cpe::product_cves(&self.http, self.nvd_api_key.as_deref(), CODESYS, &version)
|
||||
.await
|
||||
{
|
||||
Ok(matched) => {
|
||||
let alerts = record_nvd(repo_id, entries, &name, &version, matched);
|
||||
tracing::info!(runtime = %name, version = %version, cves = alerts.len(), "CODESYS CVE match");
|
||||
CveLookup {
|
||||
alerts,
|
||||
unchecked: Vec::new(),
|
||||
}
|
||||
},
|
||||
Ok(r) => {
|
||||
tracing::warn!("CODESYS NVD returned {}", r.status());
|
||||
return Vec::new();
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("CODESYS NVD request failed: {e}");
|
||||
return Vec::new();
|
||||
tracing::warn!("CODESYS NVD lookup failed: {e}");
|
||||
CveLookup {
|
||||
alerts: Vec::new(),
|
||||
unchecked: vec![format!("{name} {version}")],
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
let matched = parse_codesys_nvd(&body, &version);
|
||||
let mut alerts = Vec::new();
|
||||
for cve in matched {
|
||||
if let Some(e) = entries
|
||||
.iter_mut()
|
||||
.find(|e| e.name == name && e.version == version)
|
||||
/// Match the libraries found by their headers (FreeRTOS, lwIP, mbedTLS,
|
||||
/// wolfSSL; see [`embedded_versions`]) against NVD by CPE: copied into a
|
||||
/// firmware tree, they have no purl OSV could look up. A library whose
|
||||
/// lookup fails is reported in [`CveLookup::unchecked`]; the others are
|
||||
/// still matched.
|
||||
pub async fn scan_embedded(&self, repo_id: &str, entries: &mut [SbomEntry]) -> CveLookup {
|
||||
let found: Vec<(String, String, NvdProduct)> = entries
|
||||
.iter()
|
||||
.filter(|e| e.package_manager == EMBEDDED_MANAGER)
|
||||
.filter_map(|e| {
|
||||
embedded_versions::nvd_product(&e.name)
|
||||
.map(|p| (e.name.clone(), e.version.clone(), p))
|
||||
})
|
||||
.collect();
|
||||
let mut lookup = CveLookup::default();
|
||||
for (name, version, product) in found {
|
||||
match nvd_cpe::product_cves(&self.http, self.nvd_api_key.as_deref(), product, &version)
|
||||
.await
|
||||
{
|
||||
Ok(cves) => lookup
|
||||
.alerts
|
||||
.extend(record_nvd(repo_id, entries, &name, &version, cves)),
|
||||
Err(e) => {
|
||||
tracing::warn!(library = %name, "NVD lookup failed: {e}");
|
||||
lookup.unchecked.push(format!("{name} {version}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
lookup
|
||||
}
|
||||
}
|
||||
|
||||
/// What an NVD lookup found, and what it could not check.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct CveLookup {
|
||||
/// The CVEs that affect the components in use.
|
||||
pub alerts: Vec<CveAlert>,
|
||||
/// Components whose lookup failed (`"lwIP 2.1.2"`): not known to be free
|
||||
/// of CVEs, only unchecked.
|
||||
pub unchecked: Vec<String>,
|
||||
}
|
||||
|
||||
/// Attach NVD `cves` to the SBOM entry `name@version` and make an alert for
|
||||
/// each.
|
||||
fn record_nvd(
|
||||
repo_id: &str,
|
||||
entries: &mut [SbomEntry],
|
||||
name: &str,
|
||||
version: &str,
|
||||
cves: Vec<NvdCve>,
|
||||
) -> Vec<CveAlert> {
|
||||
let mut entry = entries
|
||||
.iter_mut()
|
||||
.find(|e| e.name == name && e.version == version);
|
||||
cves.into_iter()
|
||||
.map(|cve| {
|
||||
if let Some(e) = entry.as_deref_mut() {
|
||||
e.known_vulnerabilities.push(VulnRef {
|
||||
id: cve.id.clone(),
|
||||
source: "nvd".to_string(),
|
||||
@@ -259,17 +315,15 @@ impl CveScanner {
|
||||
let mut alert = CveAlert::new(
|
||||
cve.id,
|
||||
repo_id.to_string(),
|
||||
name.clone(),
|
||||
version.clone(),
|
||||
name.to_string(),
|
||||
version.to_string(),
|
||||
CveSource::Nvd,
|
||||
);
|
||||
alert.summary = cve.summary;
|
||||
alert.cvss_score = cve.cvss;
|
||||
alerts.push(alert);
|
||||
}
|
||||
tracing::info!(runtime = %name, version = %version, cves = alerts.len(), "CODESYS CVE match");
|
||||
alerts
|
||||
}
|
||||
alert
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The CODESYS runtime component (name + version) from an SBOM, if present. The
|
||||
@@ -282,126 +336,6 @@ fn codesys_runtime(entries: &[SbomEntry]) -> Option<(String, String)> {
|
||||
.map(|e| (e.name.clone(), e.version.clone()))
|
||||
}
|
||||
|
||||
/// A parsed NVD CVE that affects the CODESYS runtime.
|
||||
struct CodesysCve {
|
||||
id: String,
|
||||
summary: Option<String>,
|
||||
cvss: Option<f64>,
|
||||
}
|
||||
|
||||
/// Version constraints from an NVD `cpeMatch` node.
|
||||
#[derive(Default)]
|
||||
struct CpeRange {
|
||||
exact: Option<String>,
|
||||
start_incl: Option<String>,
|
||||
start_excl: Option<String>,
|
||||
end_incl: Option<String>,
|
||||
end_excl: Option<String>,
|
||||
}
|
||||
|
||||
/// Parse an NVD CVE-list response and keep the CVEs whose CODESYS CPE match covers
|
||||
/// `runtime_version`.
|
||||
fn parse_codesys_nvd(body: &serde_json::Value, runtime_version: &str) -> Vec<CodesysCve> {
|
||||
let mut out = Vec::new();
|
||||
let Some(vulns) = body["vulnerabilities"].as_array() else {
|
||||
return out;
|
||||
};
|
||||
for v in vulns {
|
||||
let cve = &v["cve"];
|
||||
let Some(id) = cve["id"].as_str() else {
|
||||
continue;
|
||||
};
|
||||
let covered = cve["configurations"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flat_map(|c| c["nodes"].as_array().into_iter().flatten())
|
||||
.flat_map(|n| n["cpeMatch"].as_array().into_iter().flatten())
|
||||
.any(|cm| {
|
||||
cm["vulnerable"].as_bool() == Some(true)
|
||||
&& cm["criteria"]
|
||||
.as_str()
|
||||
.is_some_and(|c| c.contains(":codesys:"))
|
||||
&& version_matches(runtime_version, &cpe_range(cm))
|
||||
});
|
||||
if covered {
|
||||
let summary = cve["descriptions"]
|
||||
.as_array()
|
||||
.and_then(|d| d.iter().find(|x| x["lang"].as_str() == Some("en")))
|
||||
.and_then(|x| x["value"].as_str())
|
||||
.map(String::from);
|
||||
let cvss = cve["metrics"]["cvssMetricV31"]
|
||||
.as_array()
|
||||
.and_then(|m| m.first())
|
||||
.and_then(|m| m["cvssData"]["baseScore"].as_f64());
|
||||
out.push(CodesysCve {
|
||||
id: id.to_string(),
|
||||
summary,
|
||||
cvss,
|
||||
});
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Build a [`CpeRange`] from an NVD `cpeMatch` object.
|
||||
fn cpe_range(cm: &serde_json::Value) -> CpeRange {
|
||||
let exact = cm["criteria"]
|
||||
.as_str()
|
||||
.and_then(cpe_version)
|
||||
.filter(|v| v != "*" && v != "-" && !v.is_empty());
|
||||
CpeRange {
|
||||
exact,
|
||||
start_incl: cm["versionStartIncluding"].as_str().map(String::from),
|
||||
start_excl: cm["versionStartExcluding"].as_str().map(String::from),
|
||||
end_incl: cm["versionEndIncluding"].as_str().map(String::from),
|
||||
end_excl: cm["versionEndExcluding"].as_str().map(String::from),
|
||||
}
|
||||
}
|
||||
|
||||
/// The version field (6th component) of a CPE 2.3 string.
|
||||
fn cpe_version(criteria: &str) -> Option<String> {
|
||||
criteria.split(':').nth(5).map(String::from)
|
||||
}
|
||||
|
||||
/// Whether `v` satisfies a CPE version range.
|
||||
fn version_matches(v: &str, r: &CpeRange) -> bool {
|
||||
use std::cmp::Ordering::{Equal, Greater, Less};
|
||||
if let Some(exact) = &r.exact {
|
||||
return cmp_dotted(v, exact) == Equal;
|
||||
}
|
||||
let mut ok = true;
|
||||
if let Some(s) = &r.start_incl {
|
||||
ok &= cmp_dotted(v, s) != Less;
|
||||
}
|
||||
if let Some(s) = &r.start_excl {
|
||||
ok &= cmp_dotted(v, s) == Greater;
|
||||
}
|
||||
if let Some(e) = &r.end_incl {
|
||||
ok &= cmp_dotted(v, e) != Greater;
|
||||
}
|
||||
if let Some(e) = &r.end_excl {
|
||||
ok &= cmp_dotted(v, e) == Less;
|
||||
}
|
||||
ok
|
||||
}
|
||||
|
||||
/// Compare two dotted numeric versions (`4.17.0.0` vs `4.9.0.0`); missing
|
||||
/// components count as 0, non-numeric components as 0.
|
||||
fn cmp_dotted(a: &str, b: &str) -> std::cmp::Ordering {
|
||||
let pa: Vec<u64> = a.split('.').map(|x| x.parse().unwrap_or(0)).collect();
|
||||
let pb: Vec<u64> = b.split('.').map(|x| x.parse().unwrap_or(0)).collect();
|
||||
for i in 0..pa.len().max(pb.len()) {
|
||||
let x = pa.get(i).copied().unwrap_or(0);
|
||||
let y = pb.get(i).copied().unwrap_or(0);
|
||||
match x.cmp(&y) {
|
||||
std::cmp::Ordering::Equal => continue,
|
||||
other => return other,
|
||||
}
|
||||
}
|
||||
std::cmp::Ordering::Equal
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct OsvBatchResponse {
|
||||
results: Vec<OsvBatchResult>,
|
||||
@@ -428,7 +362,6 @@ struct OsvVuln {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cmp::Ordering::{Equal, Greater, Less};
|
||||
|
||||
fn entry(name: &str, ver: &str, pm: &str) -> SbomEntry {
|
||||
SbomEntry::new("t".into(), name.into(), ver.into(), pm.into())
|
||||
@@ -447,67 +380,4 @@ mod tests {
|
||||
// Internal library components are not the runtime.
|
||||
assert!(codesys_runtime(&[entry("Util", "3.5.21.0", "codesys")]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dotted_version_comparison() {
|
||||
assert_eq!(cmp_dotted("4.17.0.0", "4.9.0.0"), Greater);
|
||||
assert_eq!(cmp_dotted("4.9.0.0", "4.17.0.0"), Less);
|
||||
assert_eq!(cmp_dotted("3.5.18.0", "3.5.18.0"), Equal);
|
||||
assert_eq!(cmp_dotted("4.2", "4.2.0.0"), Equal); // missing components = 0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_range_matching() {
|
||||
let end_excl = CpeRange {
|
||||
end_excl: Some("4.9.0.0".into()),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!version_matches("4.17.0.0", &end_excl)); // patched
|
||||
assert!(version_matches("4.5.0.0", &end_excl)); // affected
|
||||
|
||||
let exact = CpeRange {
|
||||
exact: Some("3.5.16.0".into()),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(version_matches("3.5.16.0", &exact));
|
||||
assert!(!version_matches("3.5.17.0", &exact));
|
||||
|
||||
let span = CpeRange {
|
||||
start_incl: Some("3.0.0.0".into()),
|
||||
end_incl: Some("3.5.16.0".into()),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(version_matches("3.5.16.0", &span));
|
||||
assert!(!version_matches("3.5.17.0", &span));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_nvd_and_matches_by_runtime_version() {
|
||||
// Two CODESYS CVEs: one affects < 4.9 (our 4.17 is patched), one affects
|
||||
// <= 4.20 (our 4.17 is affected). Only the latter should match.
|
||||
let body = serde_json::json!({
|
||||
"vulnerabilities": [
|
||||
{"cve": {"id":"CVE-2023-0001",
|
||||
"descriptions":[{"lang":"en","value":"old CmpBlkDrvTcp bug"}],
|
||||
"metrics":{"cvssMetricV31":[{"cvssData":{"baseScore":7.5}}]},
|
||||
"configurations":[{"nodes":[{"cpeMatch":[
|
||||
{"vulnerable":true,
|
||||
"criteria":"cpe:2.3:a:codesys:control_for_linux_sl:*:*:*:*:*:*:*:*",
|
||||
"versionEndExcluding":"4.9.0.0"}
|
||||
]}]}]}},
|
||||
{"cve": {"id":"CVE-2024-0002",
|
||||
"descriptions":[{"lang":"en","value":"recent runtime bug"}],
|
||||
"metrics":{"cvssMetricV31":[{"cvssData":{"baseScore":9.8}}]},
|
||||
"configurations":[{"nodes":[{"cpeMatch":[
|
||||
{"vulnerable":true,
|
||||
"criteria":"cpe:2.3:a:codesys:control_for_linux_sl:*:*:*:*:*:*:*:*",
|
||||
"versionEndIncluding":"4.20.0.0"}
|
||||
]}]}]}}
|
||||
]
|
||||
});
|
||||
let matched = parse_codesys_nvd(&body, "4.17.0.0");
|
||||
let ids: Vec<&str> = matched.iter().map(|c| c.id.as_str()).collect();
|
||||
assert_eq!(ids, vec!["CVE-2024-0002"]);
|
||||
assert_eq!(matched[0].cvss, Some(9.8));
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ pub fn compute_dast_fingerprint(f: &DastFinding) -> String {
|
||||
/// Canonicalize a DAST finding title for dedup purposes.
|
||||
///
|
||||
/// 1. Lowercase
|
||||
/// 2. Strip domain names / URLs (e.g. "for comp-dev.meghsakha.com")
|
||||
/// 2. Strip domain names / URLs (e.g. "for comp-dev.breakpilot.com")
|
||||
/// 3. Resolve known header synonyms (hsts ↔ strict-transport-security, etc.)
|
||||
/// 4. Strip extra whitespace
|
||||
fn canonicalize_dast_title(title: &str) -> String {
|
||||
@@ -275,7 +275,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn canonicalize_strips_domain_suffix() {
|
||||
let canon = canonicalize_dast_title("Missing HSTS header for comp-dev.meghsakha.com");
|
||||
let canon = canonicalize_dast_title("Missing HSTS header for comp-dev.breakpilot.com");
|
||||
assert!(!canon.contains("meghsakha"), "domain should be stripped");
|
||||
assert!(
|
||||
canon.contains("strict-transport-security"),
|
||||
|
||||
@@ -0,0 +1,355 @@
|
||||
//! Embedded libraries copied into a firmware tree, and their versions.
|
||||
//!
|
||||
//! Microcontroller projects vendor their RTOS, TCP/IP stack and TLS library as
|
||||
//! source: no manifest names them, so no package SBOM sees them, yet they are
|
||||
//! where the published CVEs are. Each one states its version in a header, and
|
||||
//! that is where it is read from: FreeRTOS and its TCP/IP stack, lwIP, Mbed
|
||||
//! TLS, wolfSSL and FatFs. The entries are matched against NVD by CPE
|
||||
//! (see [`crate::pipeline::nvd_cpe`]).
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use compliance_core::models::SbomEntry;
|
||||
|
||||
use crate::pipeline::nvd_cpe::NvdProduct;
|
||||
|
||||
/// The `package_manager` of entries found here.
|
||||
pub const EMBEDDED_MANAGER: &str = "embedded";
|
||||
|
||||
/// Headers larger than this are not a version header.
|
||||
const MAX_HEADER_BYTES: u64 = 512 * 1024;
|
||||
|
||||
/// A library recognised by one of its headers.
|
||||
struct Library {
|
||||
/// The name the SBOM shows.
|
||||
name: &'static str,
|
||||
/// The header that states the version, and the directory it sits in.
|
||||
header: &'static str,
|
||||
parent: Option<&'static str>,
|
||||
/// Reads the version from the header's text.
|
||||
read: fn(&str) -> Option<String>,
|
||||
license: &'static str,
|
||||
product: NvdProduct,
|
||||
}
|
||||
|
||||
const LIBRARIES: [Library; 7] = [
|
||||
Library {
|
||||
name: "FreeRTOS",
|
||||
header: "task.h",
|
||||
parent: None,
|
||||
read: freertos_version,
|
||||
license: "MIT",
|
||||
product: NvdProduct {
|
||||
match_string: "cpe:2.3:*:amazon:freertos",
|
||||
marker: ":amazon:freertos:",
|
||||
},
|
||||
},
|
||||
Library {
|
||||
name: "lwIP",
|
||||
header: "init.h",
|
||||
parent: Some("lwip"),
|
||||
read: lwip_version,
|
||||
license: "BSD-3-Clause",
|
||||
product: NvdProduct {
|
||||
match_string: "cpe:2.3:*:lwip_project:lwip",
|
||||
marker: ":lwip_project:lwip:",
|
||||
},
|
||||
},
|
||||
// NVD files the TCP/IP stack's own CVEs (4.x) under this product; those
|
||||
// of the 2018 AMNESIA-era releases are under the kernel's.
|
||||
Library {
|
||||
name: "FreeRTOS+TCP",
|
||||
header: "FreeRTOS_IP.h",
|
||||
parent: None,
|
||||
read: freertos_tcp_version,
|
||||
license: "MIT",
|
||||
product: NvdProduct {
|
||||
match_string: "cpe:2.3:*:amazon:freertos-plus-tcp",
|
||||
marker: ":amazon:freertos-plus-tcp:",
|
||||
},
|
||||
},
|
||||
Library {
|
||||
name: "FatFs",
|
||||
header: "ff.h",
|
||||
parent: None,
|
||||
read: fatfs_version,
|
||||
license: "BSD-1-Clause",
|
||||
product: NvdProduct {
|
||||
match_string: "cpe:2.3:*:elm-chan:fatfs",
|
||||
marker: ":elm-chan:fatfs:",
|
||||
},
|
||||
},
|
||||
// Mbed TLS 3.x states it in build_info.h, 2.x in version.h.
|
||||
Library {
|
||||
name: "Mbed TLS",
|
||||
header: "build_info.h",
|
||||
parent: Some("mbedtls"),
|
||||
read: mbedtls_version,
|
||||
license: "Apache-2.0",
|
||||
product: MBEDTLS,
|
||||
},
|
||||
Library {
|
||||
name: "Mbed TLS",
|
||||
header: "version.h",
|
||||
parent: Some("mbedtls"),
|
||||
read: mbedtls_version,
|
||||
license: "Apache-2.0",
|
||||
product: MBEDTLS,
|
||||
},
|
||||
Library {
|
||||
name: "wolfSSL",
|
||||
header: "version.h",
|
||||
parent: Some("wolfssl"),
|
||||
read: wolfssl_version,
|
||||
license: "GPL-2.0-or-later",
|
||||
product: NvdProduct {
|
||||
match_string: "cpe:2.3:*:wolfssl:wolfssl",
|
||||
marker: ":wolfssl:wolfssl:",
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const MBEDTLS: NvdProduct = NvdProduct {
|
||||
match_string: "cpe:2.3:*:arm:mbed_tls",
|
||||
marker: ":arm:mbed_tls:",
|
||||
};
|
||||
|
||||
/// The NVD product of a library found here, by its SBOM name.
|
||||
pub fn nvd_product(name: &str) -> Option<NvdProduct> {
|
||||
LIBRARIES.iter().find(|l| l.name == name).map(|l| l.product)
|
||||
}
|
||||
|
||||
/// Every known library under `root`, one entry per library and version.
|
||||
/// Walks the whole tree, vendor directories included: that is where these
|
||||
/// libraries live. Blocking; call it from `spawn_blocking`.
|
||||
pub fn detect(root: &Path, repo_id: &str) -> Vec<SbomEntry> {
|
||||
let mut found: Vec<(&'static Library, String)> = Vec::new();
|
||||
let mut walker = walkdir::WalkDir::new(root).into_iter();
|
||||
while let Some(entry) = walker.next() {
|
||||
// An unreadable entry is skipped; it must not end the walk.
|
||||
let Ok(entry) = entry else {
|
||||
continue;
|
||||
};
|
||||
if entry.file_type().is_dir() {
|
||||
if entry.file_name() == ".git" {
|
||||
walker.skip_current_dir();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let file_name = entry.file_name().to_string_lossy();
|
||||
let parent = entry
|
||||
.path()
|
||||
.parent()
|
||||
.and_then(Path::file_name)
|
||||
.map(|p| p.to_string_lossy().to_ascii_lowercase());
|
||||
for library in LIBRARIES.iter().filter(|l| {
|
||||
l.header == file_name && l.parent.is_none_or(|p| parent.as_deref() == Some(p))
|
||||
}) {
|
||||
let small = entry.metadata().is_ok_and(|m| m.len() <= MAX_HEADER_BYTES);
|
||||
let Some(text) = small
|
||||
.then(|| std::fs::read_to_string(entry.path()).ok())
|
||||
.flatten()
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if let Some(version) = (library.read)(&text) {
|
||||
if !found
|
||||
.iter()
|
||||
.any(|(l, v)| l.name == library.name && *v == version)
|
||||
{
|
||||
found.push((library, version));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
found
|
||||
.into_iter()
|
||||
.map(|(library, version)| {
|
||||
let mut entry = SbomEntry::new(
|
||||
repo_id.to_string(),
|
||||
library.name.to_string(),
|
||||
version,
|
||||
EMBEDDED_MANAGER.to_string(),
|
||||
);
|
||||
entry.license = Some(library.license.to_string());
|
||||
entry
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The value of `#define NAME value` in `text`, quotes and a trailing `U`
|
||||
/// removed.
|
||||
fn define(text: &str, name: &str) -> Option<String> {
|
||||
text.lines().find_map(|line| {
|
||||
let rest = line.trim_start().strip_prefix("#define")?.trim_start();
|
||||
let value = rest.strip_prefix(name)?;
|
||||
// `NAME_SUFFIX` is another macro, not this one.
|
||||
if !value.starts_with(char::is_whitespace) {
|
||||
return None;
|
||||
}
|
||||
let value = value.split("/*").next()?.split("//").next()?.trim();
|
||||
let value = value.trim_matches('"').trim_end_matches(['U', 'u']).trim();
|
||||
(!value.is_empty()).then(|| value.to_string())
|
||||
})
|
||||
}
|
||||
|
||||
/// A plain dotted version (`10.4.6`), nothing else.
|
||||
fn dotted(version: &str) -> Option<String> {
|
||||
let ok = !version.is_empty()
|
||||
&& version
|
||||
.split('.')
|
||||
.all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()));
|
||||
ok.then(|| version.to_string())
|
||||
}
|
||||
|
||||
/// `#define tskKERNEL_VERSION_NUMBER "V10.4.6"`.
|
||||
fn freertos_version(text: &str) -> Option<String> {
|
||||
let raw = define(text, "tskKERNEL_VERSION_NUMBER")?;
|
||||
dotted(raw.trim_start_matches(['V', 'v']))
|
||||
}
|
||||
|
||||
/// `LWIP_VERSION_MAJOR`, `_MINOR` and `_REVISION`.
|
||||
fn lwip_version(text: &str) -> Option<String> {
|
||||
let part = |name| define(text, name).and_then(|v| dotted(&v));
|
||||
dotted(&format!(
|
||||
"{}.{}.{}",
|
||||
part("LWIP_VERSION_MAJOR")?,
|
||||
part("LWIP_VERSION_MINOR")?,
|
||||
part("LWIP_VERSION_REVISION")?
|
||||
))
|
||||
}
|
||||
|
||||
/// `#define ipFR_TCP_VERSION_NUMBER "V4.1.0"`.
|
||||
fn freertos_tcp_version(text: &str) -> Option<String> {
|
||||
let raw = define(text, "ipFR_TCP_VERSION_NUMBER")?;
|
||||
dotted(raw.trim_start_matches(['V', 'v']))
|
||||
}
|
||||
|
||||
/// The revision in ff.h's banner (`FatFs - Generic FAT Filesystem module
|
||||
/// R0.14b`), as NVD writes it: `r0.14b`. The header has no version macro
|
||||
/// (`FF_DEFINED` is a revision id).
|
||||
fn fatfs_version(text: &str) -> Option<String> {
|
||||
let banner = text.lines().take(10).find(|l| l.contains("FatFs"))?;
|
||||
banner.split_whitespace().find_map(|word| {
|
||||
let rest = word.strip_prefix(['R', 'r'])?;
|
||||
let (major, minor) = rest.split_once('.')?;
|
||||
let digits = minor.trim_end_matches(|c: char| c.is_ascii_lowercase());
|
||||
let ok = !major.is_empty()
|
||||
&& major.chars().all(|c| c.is_ascii_digit())
|
||||
&& !digits.is_empty()
|
||||
&& digits.chars().all(|c| c.is_ascii_digit());
|
||||
ok.then(|| format!("r{}", rest.to_ascii_lowercase()))
|
||||
})
|
||||
}
|
||||
|
||||
/// `#define MBEDTLS_VERSION_STRING "3.4.0"`.
|
||||
fn mbedtls_version(text: &str) -> Option<String> {
|
||||
dotted(&define(text, "MBEDTLS_VERSION_STRING")?)
|
||||
}
|
||||
|
||||
/// `#define LIBWOLFSSL_VERSION_STRING "5.6.3"`.
|
||||
fn wolfssl_version(text: &str) -> Option<String> {
|
||||
dotted(&define(text, "LIBWOLFSSL_VERSION_STRING")?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn versions_are_read_from_each_header() {
|
||||
assert_eq!(
|
||||
freertos_version("#define tskKERNEL_VERSION_NUMBER \"V10.4.6\"\n").as_deref(),
|
||||
Some("10.4.6")
|
||||
);
|
||||
let lwip = "#define LWIP_VERSION_MAJOR 2\n#define LWIP_VERSION_MINOR 1\n\
|
||||
#define LWIP_VERSION_REVISION 3U /* comment */\n#define LWIP_VERSION_RC 255\n";
|
||||
assert_eq!(lwip_version(lwip).as_deref(), Some("2.1.3"));
|
||||
assert_eq!(
|
||||
mbedtls_version("#define MBEDTLS_VERSION_STRING \"2.28.1\"").as_deref(),
|
||||
Some("2.28.1")
|
||||
);
|
||||
assert_eq!(
|
||||
wolfssl_version("#define LIBWOLFSSL_VERSION_STRING \"5.6.3\"").as_deref(),
|
||||
Some("5.6.3")
|
||||
);
|
||||
assert_eq!(
|
||||
freertos_tcp_version("#define ipFR_TCP_VERSION_NUMBER \"V4.1.0\"").as_deref(),
|
||||
Some("4.1.0")
|
||||
);
|
||||
let fatfs = "/*----------------------------------------------------------------------------/\n\
|
||||
/ FatFs - Generic FAT Filesystem module R0.14b /\n";
|
||||
assert_eq!(fatfs_version(fatfs).as_deref(), Some("r0.14b"));
|
||||
// Another ff.h: no FatFs banner, no version.
|
||||
assert_eq!(fatfs_version("/* ffmpeg helpers R1.2 */"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_similar_macro_or_a_placeholder_is_not_a_version() {
|
||||
// `..._NUMBER_X` is another macro; a template value is no version.
|
||||
assert_eq!(
|
||||
freertos_version("#define tskKERNEL_VERSION_NUMBER_X \"V1.0\""),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
freertos_version("#define tskKERNEL_VERSION_NUMBER \"V@VERSION@\""),
|
||||
None
|
||||
);
|
||||
assert_eq!(lwip_version("#define LWIP_VERSION_MAJOR 2"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn libraries_are_found_where_projects_keep_them() {
|
||||
let root = std::env::temp_dir().join(format!("cs-embedded-{}", uuid::Uuid::new_v4()));
|
||||
let write = |rel: &str, text: &str| {
|
||||
let path = root.join(rel);
|
||||
std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
|
||||
std::fs::write(path, text).expect("write");
|
||||
};
|
||||
write(
|
||||
"Middlewares/Third_Party/FreeRTOS/Source/include/task.h",
|
||||
"#define tskKERNEL_VERSION_NUMBER \"V10.3.1\"\n",
|
||||
);
|
||||
write(
|
||||
"Middlewares/Third_Party/LwIP/src/include/lwip/init.h",
|
||||
"#define LWIP_VERSION_MAJOR 2\n#define LWIP_VERSION_MINOR 1\n#define LWIP_VERSION_REVISION 2\n",
|
||||
);
|
||||
write(
|
||||
"lib/mbedtls/include/mbedtls/build_info.h",
|
||||
"#define MBEDTLS_VERSION_STRING \"3.4.0\"\n",
|
||||
);
|
||||
write(
|
||||
"Middlewares/Third_Party/FreeRTOS-Plus-TCP/source/include/FreeRTOS_IP.h",
|
||||
"#define ipFR_TCP_VERSION_NUMBER \"V4.1.0\"\n",
|
||||
);
|
||||
write(
|
||||
"Middlewares/Third_Party/FatFs/src/ff.h",
|
||||
"/ FatFs - Generic FAT Filesystem module R0.14b /\n",
|
||||
);
|
||||
// An unrelated `init.h` and a second copy of the same FreeRTOS.
|
||||
write("Core/Inc/init.h", "#define LWIP_VERSION_MAJOR 9\n");
|
||||
write(
|
||||
"backup/task.h",
|
||||
"#define tskKERNEL_VERSION_NUMBER \"V10.3.1\"\n",
|
||||
);
|
||||
|
||||
let mut found: Vec<(String, String)> = detect(&root, "t")
|
||||
.into_iter()
|
||||
.map(|e| (e.name, e.version))
|
||||
.collect();
|
||||
found.sort();
|
||||
assert_eq!(
|
||||
found,
|
||||
[
|
||||
("FatFs".to_string(), "r0.14b".to_string()),
|
||||
("FreeRTOS".to_string(), "10.3.1".to_string()),
|
||||
("FreeRTOS+TCP".to_string(), "4.1.0".to_string()),
|
||||
("Mbed TLS".to_string(), "3.4.0".to_string()),
|
||||
("lwIP".to_string(), "2.1.2".to_string()),
|
||||
]
|
||||
);
|
||||
assert!(nvd_product("Mbed TLS").is_some());
|
||||
std::fs::remove_dir_all(&root).ok();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
//! Findings saved as a scan finds them (#372).
|
||||
//!
|
||||
//! Each scanner stage saves its first-seen findings at once, so the dashboard
|
||||
//! shows them while the scan is still running. The triage stages that follow
|
||||
//! change them (severity, status, rationale, control refs);
|
||||
//! [`RunFindings::write_back`] stores those changes on the rows already saved,
|
||||
//! without undoing a status a person set in the meantime.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use futures_util::TryStreamExt;
|
||||
use mongodb::bson::{doc, oid::ObjectId, to_bson, Bson, Document};
|
||||
|
||||
use compliance_core::models::{Finding, FindingStatus};
|
||||
|
||||
use crate::database::Database;
|
||||
use crate::error::AgentError;
|
||||
|
||||
/// The findings one scan run has saved so far, by fingerprint.
|
||||
pub struct RunFindings {
|
||||
scan_run_id: String,
|
||||
/// First seen in this run, and saved: fingerprint → row id.
|
||||
inserted: HashMap<String, ObjectId>,
|
||||
/// Already stored by an earlier run; never saved again.
|
||||
earlier: HashSet<String>,
|
||||
}
|
||||
|
||||
impl RunFindings {
|
||||
/// Nothing saved yet for the run `scan_run_id`.
|
||||
pub fn new(scan_run_id: &str) -> Self {
|
||||
Self {
|
||||
scan_run_id: scan_run_id.to_string(),
|
||||
inserted: HashMap::new(),
|
||||
earlier: HashSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// How many findings this run saw first.
|
||||
pub fn new_count(&self) -> u32 {
|
||||
u32::try_from(self.inserted.len()).unwrap_or(u32::MAX)
|
||||
}
|
||||
|
||||
/// Save the findings in `findings` that no run has stored yet, in one
|
||||
/// query and one insert, and count them on the scan run. Findings handled
|
||||
/// by an earlier call are skipped; those this run saved get their row id.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// How many findings were saved by this call.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// A database error, as the pipeline's final save used to return.
|
||||
pub async fn save_new(
|
||||
&mut self,
|
||||
db: &Database,
|
||||
findings: &mut [Finding],
|
||||
) -> Result<u32, AgentError> {
|
||||
let unknown: HashSet<String> = findings
|
||||
.iter()
|
||||
.map(|f| f.fingerprint.as_str())
|
||||
.filter(|fp| !self.inserted.contains_key(*fp) && !self.earlier.contains(*fp))
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
if unknown.is_empty() {
|
||||
self.stamp_ids(findings);
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
// Which of them an earlier run already stored (fingerprints only).
|
||||
let stored: HashSet<String> = db
|
||||
.findings()
|
||||
.clone_with_type::<Document>()
|
||||
.find(doc! { "fingerprint": { "$in": unknown.iter().collect::<Vec<_>>() } })
|
||||
.projection(doc! { "fingerprint": 1 })
|
||||
.await?
|
||||
.try_collect::<Vec<Document>>()
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter_map(|d| d.get_str("fingerprint").ok().map(str::to_owned))
|
||||
.collect();
|
||||
|
||||
// The first finding of each new fingerprint (a scan can report the
|
||||
// same one twice).
|
||||
let mut batch: Vec<Finding> = Vec::new();
|
||||
let mut queued: HashSet<&str> = HashSet::new();
|
||||
for finding in findings.iter() {
|
||||
let fp = finding.fingerprint.as_str();
|
||||
if unknown.contains(fp) && !stored.contains(fp) && queued.insert(fp) {
|
||||
let mut row = finding.clone();
|
||||
row.scan_run_id = Some(self.scan_run_id.clone());
|
||||
batch.push(row);
|
||||
}
|
||||
}
|
||||
self.earlier.extend(stored);
|
||||
|
||||
let saved = if batch.is_empty() {
|
||||
0
|
||||
} else {
|
||||
let result = db.findings().insert_many(&batch).await?;
|
||||
for (index, id) in result.inserted_ids {
|
||||
if let (Some(row), Bson::ObjectId(id)) = (batch.get(index), id) {
|
||||
self.inserted.insert(row.fingerprint.clone(), id);
|
||||
}
|
||||
}
|
||||
batch.len()
|
||||
};
|
||||
self.stamp_ids(findings);
|
||||
|
||||
let saved = u32::try_from(saved).unwrap_or(u32::MAX);
|
||||
if saved > 0 {
|
||||
if let Ok(run) = ObjectId::parse_str(&self.scan_run_id) {
|
||||
db.scan_runs()
|
||||
.update_one(
|
||||
doc! { "_id": run },
|
||||
doc! { "$inc": { "new_findings_count": i64::from(saved) } },
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
Ok(saved)
|
||||
}
|
||||
|
||||
/// Store what triage changed on the findings this run saved, and the
|
||||
/// control refs of findings an earlier run stored. Findings no stage has
|
||||
/// saved yet (the grounded surface checks) are saved first.
|
||||
///
|
||||
/// A status is written only onto a row still `open`: a person who marked
|
||||
/// a finding while the scan ran keeps their choice.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// This run's new findings in their final state, once each (for issue
|
||||
/// creation).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// A database error.
|
||||
pub async fn write_back(
|
||||
&mut self,
|
||||
db: &Database,
|
||||
findings: &mut [Finding],
|
||||
) -> Result<Vec<Finding>, AgentError> {
|
||||
self.save_new(db, findings).await?;
|
||||
|
||||
let mut new_findings = Vec::new();
|
||||
let mut written: HashSet<&str> = HashSet::new();
|
||||
let mut refreshed = 0_u32;
|
||||
for finding in findings.iter() {
|
||||
if !written.insert(finding.fingerprint.as_str()) {
|
||||
continue;
|
||||
}
|
||||
match self.inserted.get(&finding.fingerprint) {
|
||||
Some(id) => {
|
||||
db.findings()
|
||||
.update_one(doc! { "_id": id }, triage_update(finding)?)
|
||||
.await?;
|
||||
if finding.status != FindingStatus::Open {
|
||||
db.findings()
|
||||
.update_one(
|
||||
doc! { "_id": id, "status": "open" },
|
||||
doc! { "$set": { "status": bson_of(&finding.status)? } },
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
new_findings.push(finding.clone());
|
||||
}
|
||||
// A mapping pass (newly enabled or tuned) computed refs for a
|
||||
// finding first stored before it ran.
|
||||
None if !finding.control_refs.is_empty() => {
|
||||
db.findings()
|
||||
.update_one(
|
||||
doc! { "fingerprint": &finding.fingerprint },
|
||||
doc! { "$set": { "control_refs": finding.control_refs.clone() } },
|
||||
)
|
||||
.await?;
|
||||
refreshed += 1;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
if refreshed > 0 {
|
||||
tracing::info!(
|
||||
scan_run_id = %self.scan_run_id,
|
||||
"refreshed control_refs on {refreshed} existing findings"
|
||||
);
|
||||
}
|
||||
Ok(new_findings)
|
||||
}
|
||||
|
||||
/// Give each finding this run saved its row id.
|
||||
fn stamp_ids(&self, findings: &mut [Finding]) {
|
||||
for finding in findings.iter_mut() {
|
||||
if let Some(id) = self.inserted.get(&finding.fingerprint) {
|
||||
finding.id = Some(*id);
|
||||
finding.scan_run_id = Some(self.scan_run_id.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `value` as BSON.
|
||||
fn bson_of<T: serde::Serialize>(value: &T) -> Result<Bson, AgentError> {
|
||||
to_bson(value).map_err(|e| AgentError::Other(format!("encode finding field: {e}")))
|
||||
}
|
||||
|
||||
/// The fields the triage stages set, as an update.
|
||||
fn triage_update(finding: &Finding) -> Result<Document, AgentError> {
|
||||
Ok(doc! { "$set": {
|
||||
"severity": bson_of(&finding.severity)?,
|
||||
"confidence": finding.confidence,
|
||||
"triage_action": finding.triage_action.clone(),
|
||||
"triage_rationale": finding.triage_rationale.clone(),
|
||||
"remediation": finding.remediation.clone(),
|
||||
"control_refs": finding.control_refs.clone(),
|
||||
"updated_at": mongodb::bson::DateTime::now(),
|
||||
} })
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
//! Firmware SBOM via tramiton.
|
||||
//! Firmware SBOM via Firmwerk.
|
||||
//!
|
||||
//! Phase 2 (full, the default): drive a **reproducible build** with tramiton's
|
||||
//! Phase 2 (full, the default): drive a **reproducible build** with Firmwerk's
|
||||
//! `NixBackend` — `analyze` → `seal_and_build` → a sealed lock whose libraries
|
||||
//! are pinned and whose firmware artifact carries a content hash — then render
|
||||
//! the SBOM from the lock plus deep binary SCA of pre-compiled inputs. This is
|
||||
//! the complete bill of materials (toolchain + every fetched library + the
|
||||
//! firmware image), the same one `tramiton sbom` produces.
|
||||
//! firmware image), the same one `firmwerk sbom` produces.
|
||||
//!
|
||||
//! Phase 1 fallback (analysis-only): when no nix backend is available or the
|
||||
//! build fails, fall back to the resolvable libraries + toolchain from the build
|
||||
@@ -14,9 +14,18 @@
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use compliance_core::models::{SbomEntry, TargetType};
|
||||
use tramiton_repro::ReproBackend;
|
||||
use tramiton_sbom::ComponentKind;
|
||||
use compliance_core::models::{SbomEntry, SkipCode, SkippedStage, TargetType};
|
||||
use compliance_core::ExecPolicy;
|
||||
use firmwerk_repro::ReproBackend;
|
||||
use firmwerk_sbom::ComponentKind;
|
||||
|
||||
/// The `package_manager` values firmware SBOM entries use. The firmware step
|
||||
/// replaces exactly these, and the SBOM stage leaves them alone, so neither
|
||||
/// wipes the other's entries.
|
||||
pub const FIRMWARE_MANAGERS: [&str; 3] = ["firmware", "library", "toolchain"];
|
||||
|
||||
/// The scan run's stage id for the firmware SBOM.
|
||||
const STAGE: &str = "firmware_sbom";
|
||||
|
||||
/// Whether firmware SBOM applies to this target family.
|
||||
pub fn is_firmware_target(target_type: TargetType) -> bool {
|
||||
@@ -27,46 +36,92 @@ pub fn is_firmware_target(target_type: TargetType) -> bool {
|
||||
}
|
||||
|
||||
/// Build SBOM entries for a firmware target from its source tree. Prefers a full
|
||||
/// reproducible build (sealed lock); falls back to analysis-only. Returns an
|
||||
/// empty vector when tramiton cannot even form a build plan.
|
||||
pub async fn firmware_sbom_entries(path: &Path, repo_id: &str) -> Vec<SbomEntry> {
|
||||
/// reproducible build (sealed lock); falls back to analysis-only.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Why no firmware SBOM could be formed (no supported build system, a failed
|
||||
/// analysis, a timeout), as the skipped stage to record on the scan run
|
||||
/// instead of completing as if the firmware simply had no components.
|
||||
pub async fn firmware_sbom_entries(
|
||||
path: &Path,
|
||||
repo_id: &str,
|
||||
exec: ExecPolicy,
|
||||
) -> Result<Vec<SbomEntry>, SkippedStage> {
|
||||
let p = path.to_path_buf();
|
||||
let repo = repo_id.to_string();
|
||||
let allow_build = exec.untrusted_code_allowed();
|
||||
// The whole analyze → seal → build → render sequence is blocking (it shells
|
||||
// out to nix), so keep it off the async runtime. Bound it: a firmware build
|
||||
// that hangs must not wedge the scan (the orphaned task is abandoned).
|
||||
let handle = tokio::task::spawn_blocking(move || build_sbom_blocking(&p, &repo));
|
||||
let handle = tokio::task::spawn_blocking(move || build_sbom_blocking(&p, &repo, allow_build));
|
||||
match tokio::time::timeout(std::time::Duration::from_secs(900), handle).await {
|
||||
Ok(Ok(entries)) => entries,
|
||||
Ok(Ok(result)) => result,
|
||||
Ok(Err(e)) => {
|
||||
tracing::warn!(repo_id, error = %e, "Firmware SBOM: task join error");
|
||||
Vec::new()
|
||||
Err(gap(
|
||||
SkipCode::FirmwareSbomFailed,
|
||||
"firmware analysis stopped unexpectedly",
|
||||
))
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::warn!(repo_id, "Firmware SBOM: build exceeded 15m; skipping");
|
||||
Vec::new()
|
||||
Err(gap(
|
||||
SkipCode::FirmwareSbomFailed,
|
||||
"firmware analysis took longer than 15 minutes",
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn build_sbom_blocking(path: &Path, repo_id: &str) -> Vec<SbomEntry> {
|
||||
let repo = tramiton_core::Repo::new(path);
|
||||
let plan = match tramiton_core::provider::analyze(&repo) {
|
||||
/// A firmware SBOM that could not be formed, as the scan run records it.
|
||||
fn gap(code: SkipCode, reason: &str) -> SkippedStage {
|
||||
SkippedStage::new(STAGE, code, reason)
|
||||
}
|
||||
|
||||
fn build_sbom_blocking(
|
||||
path: &Path,
|
||||
repo_id: &str,
|
||||
allow_build: bool,
|
||||
) -> Result<Vec<SbomEntry>, SkippedStage> {
|
||||
let repo = firmwerk_core::Repo::new(path);
|
||||
let plan = match firmwerk_core::provider::analyze(&repo) {
|
||||
Ok(Some(bp)) => bp,
|
||||
Ok(None) => return Vec::new(),
|
||||
Ok(None) => {
|
||||
return Err(gap(
|
||||
SkipCode::FirmwareBuildUnknown,
|
||||
"no supported firmware build system found (Make, CMake, Zephyr, ESP-IDF, \
|
||||
PlatformIO, Arduino, embedded Rust, or recognisable SDK headers)",
|
||||
))
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(repo_id, error = %e, "Firmware SBOM: tramiton analyze failed");
|
||||
return Vec::new();
|
||||
tracing::warn!(repo_id, error = %e, "Firmware SBOM: firmwerk analyze failed");
|
||||
return Err(gap(
|
||||
SkipCode::FirmwareSbomFailed,
|
||||
"firmware analysis failed",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
// Phase 2: reproducible build → sealed lock → complete SBOM.
|
||||
if let Some(backend) = tramiton_repro::NixBackend::detect() {
|
||||
match tramiton_repro::seal_and_build(&backend, &plan, path) {
|
||||
//
|
||||
// The build runs the repository's own build system through Nix with
|
||||
// `sandbox = false`, i.e. arbitrary tenant code inside the agent. Where that
|
||||
// is not allowed we stop at analysis-only; the complete firmware SBOM comes
|
||||
// from an imported Firmwerk bundle instead, which is built on the
|
||||
// customer's side.
|
||||
if !allow_build {
|
||||
tracing::info!(
|
||||
repo_id,
|
||||
"Firmware SBOM: reproducible build skipped (it executes the repository's build \
|
||||
system); import a Firmwerk bundle for a complete firmware SBOM"
|
||||
);
|
||||
} else if let Some(backend) = firmwerk_repro::NixBackend::detect() {
|
||||
match firmwerk_repro::seal_and_build(&backend, &plan, path) {
|
||||
Ok(lock) => {
|
||||
let mut sbom = tramiton_sbom::Sbom::from_lock(&lock, repo_id);
|
||||
let mut sbom = firmwerk_sbom::Sbom::from_lock(&lock, repo_id);
|
||||
// Deep binary SCA of any pre-compiled inputs in the tree.
|
||||
sbom.components.extend(tramiton_sbom::binary::scan(path));
|
||||
sbom.components.extend(firmwerk_sbom::binary::scan(path));
|
||||
let entries = sbom_to_entries(&sbom, repo_id);
|
||||
tracing::info!(
|
||||
repo_id,
|
||||
@@ -74,7 +129,7 @@ fn build_sbom_blocking(path: &Path, repo_id: &str) -> Vec<SbomEntry> {
|
||||
count = entries.len(),
|
||||
"Firmware SBOM: sealed reproducible build"
|
||||
);
|
||||
return entries;
|
||||
return Ok(entries);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(repo_id, error = %e, "Firmware SBOM: reproducible build failed; falling back to analysis-only")
|
||||
@@ -88,13 +143,26 @@ fn build_sbom_blocking(path: &Path, repo_id: &str) -> Vec<SbomEntry> {
|
||||
}
|
||||
|
||||
// Phase 1 fallback: analysis-only (toolchain + resolvable libraries).
|
||||
analysis_entries(&plan, repo_id)
|
||||
let entries = analysis_entries(&plan, repo_id);
|
||||
if entries.is_empty() {
|
||||
// Detection worked but nothing resolved without a build: say so, so an
|
||||
// empty SBOM is not read as "this firmware has no components".
|
||||
return Err(gap(
|
||||
SkipCode::FirmwareUnresolved,
|
||||
&format!(
|
||||
"{} build detected, but no components could be resolved without building it",
|
||||
plan.provider
|
||||
),
|
||||
)
|
||||
.about(plan.provider.to_string()));
|
||||
}
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
/// Map a rendered [`tramiton_sbom::Sbom`] (primary firmware + components) into
|
||||
/// Map a rendered [`firmwerk_sbom::Sbom`] (primary firmware + components) into
|
||||
/// our [`SbomEntry`] rows. Source-file (`File`) components are dropped — they are
|
||||
/// build inputs, not a dependency inventory.
|
||||
fn sbom_to_entries(sbom: &tramiton_sbom::Sbom, repo_id: &str) -> Vec<SbomEntry> {
|
||||
fn sbom_to_entries(sbom: &firmwerk_sbom::Sbom, repo_id: &str) -> Vec<SbomEntry> {
|
||||
let mut entries = Vec::new();
|
||||
if let Some(primary) = &sbom.primary {
|
||||
entries.push(component_to_entry(primary, repo_id));
|
||||
@@ -108,7 +176,7 @@ fn sbom_to_entries(sbom: &tramiton_sbom::Sbom, repo_id: &str) -> Vec<SbomEntry>
|
||||
entries
|
||||
}
|
||||
|
||||
fn component_to_entry(c: &tramiton_sbom::Component, repo_id: &str) -> SbomEntry {
|
||||
fn component_to_entry(c: &firmwerk_sbom::Component, repo_id: &str) -> SbomEntry {
|
||||
let manager = match c.kind {
|
||||
ComponentKind::Firmware => "firmware",
|
||||
ComponentKind::Library => "library",
|
||||
@@ -121,32 +189,92 @@ fn component_to_entry(c: &tramiton_sbom::Component, repo_id: &str) -> SbomEntry
|
||||
c.version.clone().unwrap_or_default(),
|
||||
manager.to_string(),
|
||||
);
|
||||
entry.purl = c.source.clone();
|
||||
entry.purl = c.purl.clone().or_else(|| c.source.clone());
|
||||
// A manifest that declares a range pins no version; carrying the requirement keeps the row
|
||||
// honest instead of showing an empty version with no reason.
|
||||
entry.version_requirement = c.declared.as_ref().and_then(|d| d.requirement.clone());
|
||||
entry
|
||||
}
|
||||
|
||||
/// Analysis-only components from the build plan: the cross-toolchain plus the
|
||||
/// resolvable fetched libraries, without a build.
|
||||
fn analysis_entries(bp: &tramiton_core::BuildPlan, repo_id: &str) -> Vec<SbomEntry> {
|
||||
let mut entries = Vec::new();
|
||||
if let Some(id) = bp.toolchain.id.clone() {
|
||||
let version = bp.toolchain.version.clone().unwrap_or_default();
|
||||
entries.push(SbomEntry::new(
|
||||
repo_id.to_string(),
|
||||
id,
|
||||
version,
|
||||
"toolchain".to_string(),
|
||||
));
|
||||
/// Analysis-only components from the build plan, without a build: the cross-toolchain, the
|
||||
/// dependencies the project's manifests declare, and the libraries detection identified in the
|
||||
/// source. Firmwerk renders it into the same model as a sealed build, so both read the same way.
|
||||
fn analysis_entries(bp: &firmwerk_core::BuildPlan, repo_id: &str) -> Vec<SbomEntry> {
|
||||
sbom_to_entries(&firmwerk_sbom::Sbom::from_plan(bp, repo_id), repo_id)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn fixture(name: &str) -> std::path::PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../fixtures/nightly/firmware")
|
||||
.join(name)
|
||||
}
|
||||
for lib in tramiton_repro::lock::libraries_from_inputs(&bp.inputs) {
|
||||
let mut entry = SbomEntry::new(
|
||||
repo_id.to_string(),
|
||||
lib.name,
|
||||
lib.revision,
|
||||
"library".to_string(),
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_tree_without_a_supported_build_system_says_why() {
|
||||
let Err(skipped) =
|
||||
firmware_sbom_entries(&fixture("yocto-layer"), "t", ExecPolicy::default()).await
|
||||
else {
|
||||
panic!("a Yocto layer forms no build plan");
|
||||
};
|
||||
assert_eq!(skipped.code, Some(SkipCode::FirmwareBuildUnknown));
|
||||
assert!(
|
||||
skipped
|
||||
.reason
|
||||
.contains("no supported firmware build system"),
|
||||
"{}",
|
||||
skipped.reason
|
||||
);
|
||||
entry.purl = lib.source;
|
||||
entries.push(entry);
|
||||
}
|
||||
entries
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_zephyr_app_lists_what_its_west_manifest_declares() {
|
||||
let entries = firmware_sbom_entries(&fixture("zephyr-pinned"), "t", ExecPolicy::default())
|
||||
.await
|
||||
.expect("a west manifest forms a build plan");
|
||||
let find = |name: &str| entries.iter().find(|e| e.name == name);
|
||||
let zephyr = find("zephyr").expect("zephyr itself is a component");
|
||||
assert_eq!(zephyr.version, "v3.6.0");
|
||||
assert_eq!(
|
||||
zephyr.purl.as_deref(),
|
||||
Some("pkg:github/zephyrproject-rtos/zephyr@v3.6.0")
|
||||
);
|
||||
// An imported module is named even though its revision lives in zephyr's own manifest.
|
||||
assert!(find("cmsis").is_some(), "{entries:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_declared_range_is_a_requirement_not_a_version() {
|
||||
let entries = firmware_sbom_entries(&fixture("espidf"), "t", ExecPolicy::default())
|
||||
.await
|
||||
.expect("an esp-idf project forms a build plan");
|
||||
let mdns = entries
|
||||
.iter()
|
||||
.find(|e| e.name == "espressif/mdns")
|
||||
.expect("a declared component");
|
||||
assert_eq!(mdns.version, "");
|
||||
assert_eq!(mdns.version_requirement.as_deref(), Some("^1.2.0"));
|
||||
// A pinned one carries its version.
|
||||
let led = entries
|
||||
.iter()
|
||||
.find(|e| e.name == "espressif/led_strip")
|
||||
.expect("a pinned component");
|
||||
assert_eq!(led.version, "2.5.3");
|
||||
assert_eq!(led.version_requirement, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_make_project_yields_its_toolchain() {
|
||||
let entries = firmware_sbom_entries(&fixture("make"), "t", ExecPolicy::default())
|
||||
.await
|
||||
.expect("make forms a build plan");
|
||||
assert!(
|
||||
entries.iter().any(|e| e.package_manager == "toolchain"),
|
||||
"{entries:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,58 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use git2::{Cred, FetchOptions, RemoteCallbacks, Repository};
|
||||
use git2::{Cred, FetchOptions, RemoteCallbacks, RemoteRedirect, Repository};
|
||||
|
||||
use compliance_core::NetGuard;
|
||||
|
||||
use crate::error::AgentError;
|
||||
use crate::tenant_path::{name_segment, tenant_segment};
|
||||
|
||||
/// Credentials for accessing a private repository
|
||||
/// The directory a tenant's checkout of `repo_name` lives in.
|
||||
///
|
||||
/// **The single clone-path convention.** Every producer and every consumer of a
|
||||
/// checkout path goes through here — the orchestrator, PR review, ingest, the
|
||||
/// graph build, the chat embedding build and the file-content reader. A second
|
||||
/// convention is how two tenants end up sharing one checkout: before this, both
|
||||
/// resolved to `<base>/<name>`, so the second tenant to scan a target with the
|
||||
/// same name fetched the first tenant's `origin` instead of cloning its own.
|
||||
///
|
||||
/// Both segments are collapsed to one safe path component, so traversal in
|
||||
/// either the tenant id or the target name cannot escape `base`.
|
||||
pub fn clone_dir(base: &Path, tenant_id: &str, repo_name: &str) -> PathBuf {
|
||||
base.join(tenant_segment(tenant_id))
|
||||
.join(name_segment(repo_name))
|
||||
}
|
||||
|
||||
/// Reject a git URL that would authenticate with an SSH key.
|
||||
///
|
||||
/// At MVP the agent holds no git SSH key at all: it used to authenticate every
|
||||
/// tenant's clone with one shared deploy key, which is a cross-tenant read
|
||||
/// primitive (tenant A adds the agent's key to a repo, tenant B names that repo
|
||||
/// and the agent happily clones it). Per-tenant key management is R1; until
|
||||
/// then git access is HTTPS-with-a-token only, and an SSH URL fails loudly
|
||||
/// rather than silently borrowing somebody else's credential.
|
||||
pub fn reject_ssh_url(git_url: &str) -> Result<(), AgentError> {
|
||||
let url = git_url.trim();
|
||||
let is_ssh = url.starts_with("ssh://")
|
||||
|| url.starts_with("git+ssh://")
|
||||
// scp-style `git@host:org/repo.git` (no scheme, user before a `:`).
|
||||
|| url
|
||||
.split_once('@')
|
||||
.is_some_and(|(user, rest)| !user.contains("://") && rest.contains(':'));
|
||||
if is_ssh {
|
||||
return Err(AgentError::Other(format!(
|
||||
"SSH git URLs are not supported: '{git_url}'. Use an HTTPS clone URL \
|
||||
(https://host/org/repo.git) with a personal access token or deploy \
|
||||
token in the target's credentials."
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Credentials for accessing a private repository. HTTPS token only — see
|
||||
/// [`reject_ssh_url`].
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct RepoCredentials {
|
||||
/// Path to the SSH private key (for SSH URLs)
|
||||
pub ssh_key_path: Option<String>,
|
||||
/// Auth token / password (for HTTPS URLs)
|
||||
pub auth_token: Option<String>,
|
||||
/// Username for HTTPS auth (defaults to "x-access-token")
|
||||
@@ -18,23 +62,12 @@ pub struct RepoCredentials {
|
||||
impl RepoCredentials {
|
||||
pub(crate) fn make_callbacks(&self) -> RemoteCallbacks<'_> {
|
||||
let mut callbacks = RemoteCallbacks::new();
|
||||
let ssh_key = self.ssh_key_path.clone();
|
||||
let token = self.auth_token.clone();
|
||||
let username = self.auth_username.clone();
|
||||
|
||||
callbacks.credentials(move |_url, username_from_url, allowed_types| {
|
||||
// SSH key authentication
|
||||
if allowed_types.contains(git2::CredentialType::SSH_KEY) {
|
||||
if let Some(ref key_path) = ssh_key {
|
||||
let key = Path::new(key_path);
|
||||
if key.exists() {
|
||||
let user = username_from_url.unwrap_or("git");
|
||||
return Cred::ssh_key(user, None, key, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// HTTPS userpass authentication
|
||||
callbacks.credentials(move |_url, _username_from_url, allowed_types| {
|
||||
// HTTPS userpass authentication. There is deliberately no SSH branch:
|
||||
// the agent has no key to offer.
|
||||
if allowed_types.contains(git2::CredentialType::USER_PASS_PLAINTEXT) {
|
||||
if let Some(ref tok) = token {
|
||||
let user = username.as_deref().unwrap_or("x-access-token");
|
||||
@@ -48,8 +81,10 @@ impl RepoCredentials {
|
||||
callbacks
|
||||
}
|
||||
|
||||
fn fetch_options(&self) -> FetchOptions<'_> {
|
||||
pub(crate) fn fetch_options(&self) -> FetchOptions<'_> {
|
||||
let mut fetch_opts = FetchOptions::new();
|
||||
// A redirect could lead anywhere, past the check in `GitOps::check_remote`.
|
||||
fetch_opts.follow_redirects(RemoteRedirect::None);
|
||||
if self.has_credentials() {
|
||||
fetch_opts.remote_callbacks(self.make_callbacks());
|
||||
}
|
||||
@@ -57,38 +92,83 @@ impl RepoCredentials {
|
||||
}
|
||||
|
||||
fn has_credentials(&self) -> bool {
|
||||
self.ssh_key_path
|
||||
.as_ref()
|
||||
.map(|p| Path::new(p).exists())
|
||||
.unwrap_or(false)
|
||||
|| self.auth_token.is_some()
|
||||
self.auth_token.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GitOps {
|
||||
base_path: PathBuf,
|
||||
/// The tenant every checkout this instance makes belongs to.
|
||||
tenant_id: String,
|
||||
credentials: RepoCredentials,
|
||||
/// Where a clone or fetch may connect (#256, #294).
|
||||
net_guard: NetGuard,
|
||||
}
|
||||
|
||||
impl GitOps {
|
||||
pub fn new(base_path: &str, credentials: RepoCredentials) -> Self {
|
||||
pub fn new(
|
||||
base_path: &str,
|
||||
tenant_id: &str,
|
||||
credentials: RepoCredentials,
|
||||
net_guard: NetGuard,
|
||||
) -> Self {
|
||||
Self {
|
||||
base_path: PathBuf::from(base_path),
|
||||
tenant_id: tenant_id.to_string(),
|
||||
credentials,
|
||||
net_guard,
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(repo_name = %repo_name))]
|
||||
/// Refuse a remote whose host is internal or resolves to a non-public
|
||||
/// address, right before connecting to it.
|
||||
///
|
||||
/// libgit2 resolves the host itself and cannot be given a pinned address,
|
||||
/// so a name that changes its answer between this check and libgit2's own
|
||||
/// lookup (DNS rebinding at near-zero TTL) is not covered; redirects are
|
||||
/// off, so the connection cannot be sent anywhere else. Checked on every
|
||||
/// fetch too, because a remote's DNS can change after the clone.
|
||||
pub(crate) fn check_remote(&self, git_url: &str) -> Result<(), AgentError> {
|
||||
let remote = self
|
||||
.net_guard
|
||||
.check_git_url(git_url)
|
||||
.map_err(|e| AgentError::Other(e.to_string()))?;
|
||||
let port = remote
|
||||
.port
|
||||
.unwrap_or(if remote.scheme == "http" { 80 } else { 443 });
|
||||
self.net_guard
|
||||
.check_resolved(&remote.host, port)
|
||||
.map_err(|e| AgentError::Other(e.to_string()))
|
||||
}
|
||||
|
||||
/// The host of a git URL, if it is one this deployment may reach.
|
||||
pub(crate) fn remote_host(&self, git_url: &str) -> Option<String> {
|
||||
self.net_guard.check_git_url(git_url).ok().map(|r| r.host)
|
||||
}
|
||||
|
||||
/// The credentials this instance clones with.
|
||||
pub(crate) fn credentials(&self) -> &RepoCredentials {
|
||||
&self.credentials
|
||||
}
|
||||
|
||||
/// Where this instance's tenant keeps its checkout of `repo_name`.
|
||||
pub fn clone_path(&self, repo_name: &str) -> PathBuf {
|
||||
clone_dir(&self.base_path, &self.tenant_id, repo_name)
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(tenant = %self.tenant_id, repo_name = %repo_name))]
|
||||
pub fn clone_or_fetch(&self, git_url: &str, repo_name: &str) -> Result<PathBuf, AgentError> {
|
||||
// Names can contain slashes or other path-hostile characters (a target
|
||||
// named after a repo path, say); collapse to one safe directory segment
|
||||
// so the clone path never nests or breaks.
|
||||
let repo_path = self.base_path.join(sanitize_repo_dir(repo_name));
|
||||
reject_ssh_url(git_url)?;
|
||||
// Per tenant: two tenants with the same target name get two checkouts.
|
||||
let repo_path = self.clone_path(repo_name);
|
||||
|
||||
if repo_path.exists() {
|
||||
tracing::info!("fetching updates for existing repo");
|
||||
self.fetch(&repo_path)?;
|
||||
} else {
|
||||
// Before creating the directory: a refused remote must not leave
|
||||
// an empty checkout behind for the next run to try to fetch.
|
||||
self.check_remote(git_url)?;
|
||||
std::fs::create_dir_all(&repo_path)?;
|
||||
self.clone_repo(git_url, &repo_path)?;
|
||||
tracing::info!("Cloned {git_url} to {}", repo_path.display());
|
||||
@@ -110,6 +190,7 @@ impl GitOps {
|
||||
fn fetch(&self, repo_path: &Path) -> Result<(), AgentError> {
|
||||
let repo = Repository::open(repo_path)?;
|
||||
let mut remote = repo.find_remote("origin")?;
|
||||
self.check_remote(remote.url().unwrap_or_default())?;
|
||||
let mut fetch_opts = self.credentials.fetch_options();
|
||||
remote.fetch(&[] as &[&str], Some(&mut fetch_opts), None)?;
|
||||
|
||||
@@ -126,22 +207,10 @@ impl GitOps {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Test that we can access a remote repository (used during add validation)
|
||||
pub fn test_access(git_url: &str, credentials: &RepoCredentials) -> Result<(), AgentError> {
|
||||
let mut remote = git2::Remote::create_detached(git_url)?;
|
||||
let callbacks = credentials.make_callbacks();
|
||||
remote.connect_auth(git2::Direction::Fetch, Some(callbacks), None)?;
|
||||
remote.disconnect()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Build credentials from agent config + per-repo overrides
|
||||
pub fn make_repo_credentials(
|
||||
config: &compliance_core::AgentConfig,
|
||||
repo: &crate::pipeline::repo_view::RepoView,
|
||||
) -> RepoCredentials {
|
||||
/// Build credentials from a repo view's own HTTPS token. There is no
|
||||
/// agent-wide fallback credential any more — see [`reject_ssh_url`].
|
||||
pub fn make_repo_credentials(repo: &crate::pipeline::repo_view::RepoView) -> RepoCredentials {
|
||||
RepoCredentials {
|
||||
ssh_key_path: Some(config.ssh_key_path.clone()),
|
||||
auth_token: repo.auth_token.clone(),
|
||||
auth_username: repo.auth_username.clone(),
|
||||
}
|
||||
@@ -257,45 +326,137 @@ pub struct DiffFile {
|
||||
pub hunks: String,
|
||||
}
|
||||
|
||||
/// Collapse a repository name into a single filesystem-safe directory segment.
|
||||
/// Names may carry slashes or other path-hostile characters (a target named
|
||||
/// after a repo path, for instance); those would otherwise nest or break the
|
||||
/// clone path, so map anything outside `[A-Za-z0-9._-]` to `_`.
|
||||
fn sanitize_repo_dir(name: &str) -> String {
|
||||
let mapped: String = name
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' {
|
||||
c
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let trimmed = mapped.trim_matches(|c| c == '.' || c == '_');
|
||||
if trimmed.is_empty() {
|
||||
"repo".to_string()
|
||||
} else {
|
||||
trimmed.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::sanitize_repo_dir;
|
||||
use super::{clone_dir, reject_ssh_url, GitOps, RepoCredentials};
|
||||
use compliance_core::NetGuard;
|
||||
use std::path::Path;
|
||||
|
||||
const BASE: &str = "/data/repos";
|
||||
|
||||
#[test]
|
||||
fn sanitizes_path_hostile_names() {
|
||||
fn same_target_name_in_two_tenants_gets_two_directories() {
|
||||
let a = clone_dir(Path::new(BASE), "tenant-a", "acme-firmware");
|
||||
let b = clone_dir(Path::new(BASE), "tenant-b", "acme-firmware");
|
||||
assert_ne!(a, b, "two tenants must not share a checkout");
|
||||
assert_eq!(a, Path::new("/data/repos/tenant-a/acme-firmware"));
|
||||
assert_eq!(b, Path::new("/data/repos/tenant-b/acme-firmware"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clone_dir_is_stable_for_the_same_tenant_and_name() {
|
||||
assert_eq!(
|
||||
sanitize_repo_dir("zephyr-example-app"),
|
||||
"zephyr-example-app"
|
||||
clone_dir(Path::new(BASE), "t1", "repo"),
|
||||
clone_dir(Path::new(BASE), "t1", "repo")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clone_dir_sanitises_traversal_in_the_target_name() {
|
||||
let p = clone_dir(Path::new(BASE), "t1", "../../etc/passwd");
|
||||
assert_eq!(p, Path::new("/data/repos/t1/etc_passwd"));
|
||||
assert!(p.starts_with("/data/repos/t1"));
|
||||
assert_eq!(
|
||||
sanitize_repo_dir("ChristianRinn/bare_metal_stm32f411xe"),
|
||||
"ChristianRinn_bare_metal_stm32f411xe"
|
||||
clone_dir(
|
||||
Path::new(BASE),
|
||||
"t1",
|
||||
"ChristianRinn/bare_metal_stm32f411xe"
|
||||
),
|
||||
Path::new("/data/repos/t1/ChristianRinn_bare_metal_stm32f411xe")
|
||||
);
|
||||
assert_eq!(sanitize_repo_dir("../../etc/passwd"), "etc_passwd");
|
||||
assert_eq!(sanitize_repo_dir("a b:c"), "a_b_c");
|
||||
assert_eq!(sanitize_repo_dir("///"), "repo");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clone_dir_sanitises_traversal_in_the_tenant_id() {
|
||||
let p = clone_dir(Path::new(BASE), "../../../etc", "repo");
|
||||
assert!(
|
||||
p.starts_with("/data/repos"),
|
||||
"{} escaped the clone base",
|
||||
p.display()
|
||||
);
|
||||
// Exactly base + two components: nothing nested, nothing climbed.
|
||||
assert_eq!(
|
||||
p.components().count(),
|
||||
Path::new(BASE).components().count() + 2
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ssh_urls_are_rejected_with_an_https_hint() {
|
||||
for url in [
|
||||
"ssh://git@github.com/org/repo.git",
|
||||
"git@github.com:org/repo.git",
|
||||
"git+ssh://git@git.example.com/org/repo.git",
|
||||
" git@gitlab.com:org/repo.git ",
|
||||
] {
|
||||
let msg = match reject_ssh_url(url) {
|
||||
Err(e) => e.to_string(),
|
||||
Ok(()) => panic!("{url} should be rejected"),
|
||||
};
|
||||
assert!(msg.contains("HTTPS"), "{url}: {msg}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn https_urls_are_accepted() {
|
||||
for url in [
|
||||
"https://github.com/org/repo.git",
|
||||
"https://x-access-token:tok@github.com/org/repo.git",
|
||||
"http://internal.example.com/org/repo.git",
|
||||
] {
|
||||
assert!(reject_ssh_url(url).is_ok(), "{url} should be accepted");
|
||||
}
|
||||
}
|
||||
|
||||
/// A scratch clone base, removed on drop.
|
||||
struct Scratch(std::path::PathBuf);
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn git_ops(base: &Path) -> GitOps {
|
||||
GitOps::new(
|
||||
&base.to_string_lossy(),
|
||||
"tenant-a",
|
||||
RepoCredentials::default(),
|
||||
NetGuard::public_only(),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_remote_on_a_private_address_is_refused_before_connecting() {
|
||||
let scratch =
|
||||
Scratch(std::env::temp_dir().join(format!("cs-git-{}", uuid::Uuid::new_v4())));
|
||||
let ops = git_ops(&scratch.0);
|
||||
let err = ops
|
||||
.clone_or_fetch("http://169.254.169.254/latest/x.git", "metadata")
|
||||
.expect_err("metadata address must be refused");
|
||||
assert!(err.to_string().contains("not a public address"), "{err}");
|
||||
assert!(
|
||||
!ops.clone_path("metadata").exists(),
|
||||
"a refused clone leaves no checkout behind"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fetch_rechecks_the_stored_remote() {
|
||||
// An existing checkout whose `origin` now points somewhere private (a
|
||||
// remote's DNS or config can change after the clone): the fetch must
|
||||
// be refused, not trusted because the clone once passed.
|
||||
let scratch =
|
||||
Scratch(std::env::temp_dir().join(format!("cs-git-{}", uuid::Uuid::new_v4())));
|
||||
let ops = git_ops(&scratch.0);
|
||||
let path = ops.clone_path("existing");
|
||||
let repo = git2::Repository::init(&path).expect("init");
|
||||
repo.remote("origin", "http://10.0.0.5/internal.git")
|
||||
.expect("set origin");
|
||||
|
||||
let err = ops
|
||||
.clone_or_fetch("https://example.com/org/repo.git", "existing")
|
||||
.expect_err("private origin must be refused");
|
||||
assert!(err.to_string().contains("10.0.0.5"), "{err}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
//! Git submodules of a scanned repository.
|
||||
//!
|
||||
//! Firmware repositories pull their HAL, RTOS or protocol stack in as
|
||||
//! submodules; without them the scan misses code the product ships. Each
|
||||
//! submodule URL passes the same checks as the main remote (HTTPS only, a
|
||||
//! public host, no redirects), and the repository's token is offered only to
|
||||
//! the main remote's own host. A submodule that is refused or cannot be
|
||||
//! fetched is left out and reported, so the scan says what it did not see.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use git2::{Repository, Submodule, SubmoduleUpdateOptions};
|
||||
|
||||
use crate::error::AgentError;
|
||||
use crate::pipeline::git::{reject_ssh_url, GitOps, RepoCredentials};
|
||||
|
||||
/// Most levels of nested submodules that are checked out.
|
||||
const MAX_DEPTH: usize = 3;
|
||||
|
||||
impl GitOps {
|
||||
/// Check out the submodules of the checkout at `repo_path` (whose remote is
|
||||
/// `origin_url`), and theirs, up to [`MAX_DEPTH`] levels.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// One line per submodule that was left out, naming it and saying why;
|
||||
/// empty when there were none or all were checked out.
|
||||
pub fn update_submodules(&self, repo_path: &Path, origin_url: &str) -> Vec<String> {
|
||||
let main_host = self.remote_host(origin_url);
|
||||
let mut skipped = Vec::new();
|
||||
self.update_level(repo_path, origin_url, main_host.as_deref(), 0, &mut skipped);
|
||||
skipped
|
||||
}
|
||||
|
||||
fn update_level(
|
||||
&self,
|
||||
repo_path: &Path,
|
||||
parent_url: &str,
|
||||
main_host: Option<&str>,
|
||||
depth: usize,
|
||||
skipped: &mut Vec<String>,
|
||||
) {
|
||||
let Ok(repo) = Repository::open(repo_path) else {
|
||||
return;
|
||||
};
|
||||
let Ok(submodules) = repo.submodules() else {
|
||||
return;
|
||||
};
|
||||
for mut submodule in submodules {
|
||||
let name = submodule.name().unwrap_or("?").to_string();
|
||||
let Some(url) = submodule.url().and_then(|raw| resolve_url(parent_url, raw)) else {
|
||||
skipped.push(format!("{name}: no usable URL in .gitmodules"));
|
||||
continue;
|
||||
};
|
||||
if let Err(e) = self.fetch_one(&repo, &mut submodule, &name, &url, main_host) {
|
||||
skipped.push(format!("{name} ({url}): {e}"));
|
||||
continue;
|
||||
}
|
||||
if depth + 1 < MAX_DEPTH {
|
||||
let nested = repo_path.join(submodule.path());
|
||||
self.update_level(&nested, &url, main_host, depth + 1, skipped);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Check `url`, point the submodule at exactly that URL, and check it out.
|
||||
fn fetch_one(
|
||||
&self,
|
||||
repo: &Repository,
|
||||
submodule: &mut Submodule<'_>,
|
||||
name: &str,
|
||||
url: &str,
|
||||
main_host: Option<&str>,
|
||||
) -> Result<(), AgentError> {
|
||||
reject_ssh_url(url)?;
|
||||
self.check_remote(url)?;
|
||||
// The URL that was checked is the one fetched: set it in the local
|
||||
// config, where the update reads it, rather than trusting what
|
||||
// libgit2 would resolve on its own.
|
||||
submodule.init(true)?;
|
||||
repo.config()?
|
||||
.set_str(&format!("submodule.{name}.url"), url)?;
|
||||
let mut submodule = repo.find_submodule(name)?;
|
||||
|
||||
// The repository's token belongs to its own host; a submodule on
|
||||
// another host gets no credentials.
|
||||
let same_host = main_host.is_some() && self.remote_host(url).as_deref() == main_host;
|
||||
let anonymous = RepoCredentials::default();
|
||||
let credentials = if same_host {
|
||||
self.credentials()
|
||||
} else {
|
||||
&anonymous
|
||||
};
|
||||
let mut options = SubmoduleUpdateOptions::new();
|
||||
options.fetch(credentials.fetch_options());
|
||||
submodule.update(true, Some(&mut options))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A submodule URL made absolute. Relative URLs (`../lib.git`, `./sub.git`)
|
||||
/// are relative to the parent's remote as if it were a directory, as git
|
||||
/// resolves them. `None` when it would climb above the host.
|
||||
fn resolve_url(parent: &str, raw: &str) -> Option<String> {
|
||||
let raw = raw.trim();
|
||||
if !(raw.starts_with("./") || raw.starts_with("../")) {
|
||||
return (!raw.is_empty()).then(|| raw.to_string());
|
||||
}
|
||||
let (scheme, rest) = parent.trim_end_matches('/').split_once("://")?;
|
||||
let mut segments: Vec<&str> = rest.split('/').collect();
|
||||
let mut remainder = raw;
|
||||
loop {
|
||||
if let Some(r) = remainder.strip_prefix("./") {
|
||||
remainder = r;
|
||||
} else if let Some(r) = remainder.strip_prefix("../") {
|
||||
// The host is the first segment and cannot be climbed past.
|
||||
if segments.len() <= 1 {
|
||||
return None;
|
||||
}
|
||||
segments.pop();
|
||||
remainder = r;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Some(format!("{scheme}://{}/{remainder}", segments.join("/")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::NetGuard;
|
||||
|
||||
#[test]
|
||||
fn relative_urls_resolve_like_git() {
|
||||
let parent = "https://git.example.com/acme/firmware.git";
|
||||
assert_eq!(
|
||||
resolve_url(parent, "../hal.git").as_deref(),
|
||||
Some("https://git.example.com/acme/hal.git")
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_url(parent, "./vendor.git").as_deref(),
|
||||
Some("https://git.example.com/acme/firmware.git/vendor.git")
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_url(parent, "../../other/lib.git").as_deref(),
|
||||
Some("https://git.example.com/other/lib.git")
|
||||
);
|
||||
assert_eq!(resolve_url(parent, "../../../../x.git"), None);
|
||||
assert_eq!(
|
||||
resolve_url(parent, "https://github.com/FreeRTOS/FreeRTOS-Kernel.git").as_deref(),
|
||||
Some("https://github.com/FreeRTOS/FreeRTOS-Kernel.git")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_submodules_are_reported_and_not_fetched() {
|
||||
let base = std::env::temp_dir().join(format!("cs-sub-{}", uuid::Uuid::new_v4()));
|
||||
let ops = GitOps::new(
|
||||
&base.to_string_lossy(),
|
||||
"tenant-a",
|
||||
RepoCredentials::default(),
|
||||
NetGuard::public_only(),
|
||||
);
|
||||
let path = ops.clone_path("fw");
|
||||
let repo = Repository::init(&path).expect("init");
|
||||
// `submodule()` only records the entry; nothing is fetched here.
|
||||
repo.submodule("git@github.com:acme/hal.git", Path::new("hal"), true)
|
||||
.expect("ssh submodule");
|
||||
repo.submodule("http://10.0.0.5/rtos.git", Path::new("rtos"), true)
|
||||
.expect("private submodule");
|
||||
|
||||
let skipped = ops.update_submodules(&path, "https://git.example.com/acme/fw.git");
|
||||
|
||||
assert_eq!(skipped.len(), 2, "{skipped:?}");
|
||||
assert!(skipped
|
||||
.iter()
|
||||
.any(|s| s.starts_with("hal") && s.contains("HTTPS")));
|
||||
assert!(skipped
|
||||
.iter()
|
||||
.any(|s| s.starts_with("rtos") && s.contains("10.0.0.5")));
|
||||
// Nothing was checked out: the submodule has no commit in its workdir.
|
||||
let rtos = repo.find_submodule("rtos").expect("rtos entry");
|
||||
assert!(rtos.workdir_id().is_none(), "rtos must not be fetched");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,18 @@ use crate::pipeline::dedup;
|
||||
|
||||
pub struct GitleaksScanner;
|
||||
|
||||
/// How to point gitleaks at a tree. `detect` walks a git checkout's history;
|
||||
/// on a directory that is not a checkout it scans **nothing** and reports no
|
||||
/// leaks — a silent miss — so a plain tree (an uploaded source archive) is
|
||||
/// scanned with `dir` instead.
|
||||
fn source_args(repo_path: &Path) -> &'static [&'static str] {
|
||||
if repo_path.join(".git").exists() {
|
||||
&["detect", "--source", "."]
|
||||
} else {
|
||||
&["dir", "."]
|
||||
}
|
||||
}
|
||||
|
||||
impl Scanner for GitleaksScanner {
|
||||
fn name(&self) -> &str {
|
||||
"gitleaks"
|
||||
@@ -21,11 +33,9 @@ impl Scanner for GitleaksScanner {
|
||||
async fn scan(&self, repo_path: &Path, repo_id: &str) -> Result<ScanOutput, CoreError> {
|
||||
let output = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(300),
|
||||
tokio::process::Command::new("gitleaks")
|
||||
crate::pipeline::tool_cmd::tool("gitleaks", &[])
|
||||
.args(source_args(repo_path))
|
||||
.args([
|
||||
"detect",
|
||||
"--source",
|
||||
".",
|
||||
"--report-format",
|
||||
"json",
|
||||
"--report-path",
|
||||
@@ -223,6 +233,17 @@ mod tests {
|
||||
assert_eq!(results[0].rule_id, "generic-secret");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_tree_is_scanned_as_a_directory() {
|
||||
let dir = std::env::temp_dir().join(format!("cs-gitleaks-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&dir).expect("mkdir");
|
||||
// An uploaded archive is not a checkout: `detect` would scan nothing there.
|
||||
assert_eq!(source_args(&dir), ["dir", "."]);
|
||||
std::fs::create_dir_all(dir.join(".git")).expect("mkdir .git");
|
||||
assert_eq!(source_args(&dir), ["detect", "--source", "."]);
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn severity_mapping_private_key() {
|
||||
// Verify the severity logic from the scan method
|
||||
|
||||
@@ -66,6 +66,15 @@ impl PipelineOrchestrator {
|
||||
pub(super) async fn maybe_trigger_dast(&self, repo_id: &str, scan_run_id: &str) {
|
||||
use futures_util::TryStreamExt;
|
||||
|
||||
if self.source_only() {
|
||||
self.skip_stage(
|
||||
scan_run_id,
|
||||
compliance_core::models::SkippedStage::feature_disabled("dast"),
|
||||
)
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
|
||||
let filter = mongodb::bson::doc! { "repo_id": repo_id };
|
||||
let targets: Vec<compliance_core::models::DastTarget> =
|
||||
match self.db.dast_targets().find(filter).await {
|
||||
@@ -81,8 +90,9 @@ impl PipelineOrchestrator {
|
||||
for target in targets {
|
||||
let db = self.db.clone();
|
||||
let scan_run_id = scan_run_id.to_string();
|
||||
let net_guard = self.net_guard;
|
||||
tokio::spawn(async move {
|
||||
let orchestrator = compliance_dast::DastOrchestrator::new(100);
|
||||
let orchestrator = compliance_dast::DastOrchestrator::new(100, net_guard);
|
||||
match orchestrator.run_scan(&target, Vec::new()).await {
|
||||
Ok((mut scan_run, findings)) => {
|
||||
scan_run.sast_scan_run_id = Some(scan_run_id);
|
||||
|
||||
@@ -52,9 +52,13 @@ impl PipelineOrchestrator {
|
||||
let token = repo.tracker_token.clone()?;
|
||||
let base_url = extract_base_url(&repo.git_url)?;
|
||||
let secret = secrecy::SecretString::from(token);
|
||||
Some(TrackerDispatch::Gitea(trackers::gitea::GiteaTracker::new(
|
||||
base_url, secret,
|
||||
)))
|
||||
match trackers::gitea::GiteaTracker::new(base_url, secret, self.net_guard) {
|
||||
Ok(t) => Some(TrackerDispatch::Gitea(t)),
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to build Gitea tracker: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
TrackerType::Jira => {
|
||||
let base_url = self.config.jira_url.clone()?;
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
//! Which source languages a tree holds, outside vendor code.
|
||||
//!
|
||||
//! Recorded on the scan run so the CRA status only claims "no violation
|
||||
//! found" for a control when one of its rules covers the code that was
|
||||
//! actually scanned (#368).
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::Path;
|
||||
|
||||
use super::vendor::walk_outside;
|
||||
|
||||
/// The language a file extension belongs to, by the names the control map's
|
||||
/// bindings use. Headers count as C: a C++ project also has `.cpp` files.
|
||||
fn language_of(extension: &str) -> Option<&'static str> {
|
||||
Some(match extension {
|
||||
"c" | "h" => "c",
|
||||
"cc" | "cpp" | "cxx" | "hh" | "hpp" | "hxx" => "cpp",
|
||||
"py" => "python",
|
||||
"js" | "jsx" | "mjs" | "cjs" => "javascript",
|
||||
"ts" | "tsx" | "mts" | "cts" => "typescript",
|
||||
"go" => "go",
|
||||
"java" => "java",
|
||||
"kt" | "kts" => "kotlin",
|
||||
"rb" => "ruby",
|
||||
"php" => "php",
|
||||
"rs" => "rust",
|
||||
"cs" => "csharp",
|
||||
"swift" => "swift",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The source languages of the files under `root`, skipping `.git` and the
|
||||
/// `excluded` (vendor) directories, sorted.
|
||||
pub fn source_languages(root: &Path, excluded: &[String]) -> Vec<String> {
|
||||
walk_outside(root, excluded)
|
||||
.filter(|e| e.file_type().is_file())
|
||||
.filter_map(|e| {
|
||||
let ext = e.path().extension()?.to_str()?.to_ascii_lowercase();
|
||||
language_of(&ext)
|
||||
})
|
||||
.collect::<BTreeSet<_>>()
|
||||
.into_iter()
|
||||
.map(str::to_owned)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn languages_come_from_the_code_outside_vendor_directories() {
|
||||
let dir = std::env::temp_dir().join(format!("cs-languages-{}", uuid::Uuid::new_v4()));
|
||||
let root = dir.as_path();
|
||||
for (path, body) in [
|
||||
("Core/Src/main.c", "int main(void) { return 0; }"),
|
||||
("Core/Inc/main.h", "#pragma once"),
|
||||
("tools/flash.py", "print('flash')"),
|
||||
("Middlewares/Third_Party/lib/x.cpp", "int x;"),
|
||||
("README.md", "# readme"),
|
||||
] {
|
||||
let file = root.join(path);
|
||||
std::fs::create_dir_all(file.parent().expect("parent")).expect("mkdir");
|
||||
std::fs::write(file, body).expect("write");
|
||||
}
|
||||
|
||||
let vendor = vec!["Middlewares/Third_Party".to_string()];
|
||||
|
||||
assert_eq!(source_languages(root, &vendor), ["c", "python"]);
|
||||
assert_eq!(source_languages(root, &[]), ["c", "cpp", "python"]);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -2,31 +2,34 @@ use std::path::Path;
|
||||
|
||||
use compliance_core::models::{Finding, ScanType, Severity};
|
||||
use compliance_core::CoreError;
|
||||
use tokio::process::Command;
|
||||
|
||||
use crate::pipeline::dedup;
|
||||
|
||||
use super::run_with_timeout;
|
||||
|
||||
pub(super) async fn run_clippy(repo_path: &Path, repo_id: &str) -> Result<Vec<Finding>, CoreError> {
|
||||
let child = Command::new("cargo")
|
||||
.args([
|
||||
"clippy",
|
||||
"--message-format=json",
|
||||
"--quiet",
|
||||
"--",
|
||||
"-W",
|
||||
"clippy::all",
|
||||
])
|
||||
.current_dir(repo_path)
|
||||
.env("RUSTC_WRAPPER", "")
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|e| CoreError::Scanner {
|
||||
scanner: "clippy".to_string(),
|
||||
source: Box::new(e),
|
||||
})?;
|
||||
let child = crate::pipeline::tool_cmd::tool_in(
|
||||
"cargo",
|
||||
repo_path,
|
||||
crate::pipeline::tool_cmd::CARGO_ENV,
|
||||
)
|
||||
.args([
|
||||
"clippy",
|
||||
"--message-format=json",
|
||||
"--quiet",
|
||||
"--",
|
||||
"-W",
|
||||
"clippy::all",
|
||||
])
|
||||
.current_dir(repo_path)
|
||||
.env("RUSTC_WRAPPER", "")
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|e| CoreError::Scanner {
|
||||
scanner: "clippy".to_string(),
|
||||
source: Box::new(e),
|
||||
})?;
|
||||
|
||||
let output = run_with_timeout(child, "clippy").await?;
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
|
||||
@@ -2,7 +2,6 @@ use std::path::Path;
|
||||
|
||||
use compliance_core::models::{Finding, ScanType, Severity};
|
||||
use compliance_core::CoreError;
|
||||
use tokio::process::Command;
|
||||
|
||||
use crate::pipeline::dedup;
|
||||
|
||||
@@ -11,16 +10,20 @@ use super::run_with_timeout;
|
||||
pub(super) async fn run_eslint(repo_path: &Path, repo_id: &str) -> Result<Vec<Finding>, CoreError> {
|
||||
// Use the project-local eslint binary directly, not npx (which can hang downloading)
|
||||
let eslint_bin = repo_path.join("node_modules/.bin/eslint");
|
||||
let child = Command::new(eslint_bin)
|
||||
.args([".", "--format", "json", "--no-error-on-unmatched-pattern"])
|
||||
.current_dir(repo_path)
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|e| CoreError::Scanner {
|
||||
scanner: "eslint".to_string(),
|
||||
source: Box::new(e),
|
||||
})?;
|
||||
let child = crate::pipeline::tool_cmd::tool_in(
|
||||
eslint_bin,
|
||||
repo_path,
|
||||
crate::pipeline::tool_cmd::NPM_ENV,
|
||||
)
|
||||
.args([".", "--format", "json", "--no-error-on-unmatched-pattern"])
|
||||
.current_dir(repo_path)
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|e| CoreError::Scanner {
|
||||
scanner: "eslint".to_string(),
|
||||
source: Box::new(e),
|
||||
})?;
|
||||
|
||||
let output = run_with_timeout(child, "eslint").await?;
|
||||
|
||||
@@ -32,6 +35,7 @@ pub(super) async fn run_eslint(repo_path: &Path, repo_id: &str) -> Result<Vec<Fi
|
||||
|
||||
let mut findings = Vec::new();
|
||||
for file_result in results {
|
||||
let file = super::repo_relative(repo_path, &file_result.file_path);
|
||||
for msg in file_result.messages {
|
||||
let severity = match msg.severity {
|
||||
2 => Severity::Medium,
|
||||
@@ -43,7 +47,7 @@ pub(super) async fn run_eslint(repo_path: &Path, repo_id: &str) -> Result<Vec<Fi
|
||||
repo_id,
|
||||
"eslint",
|
||||
&rule_id,
|
||||
&file_result.file_path,
|
||||
&file,
|
||||
&msg.line.to_string(),
|
||||
]);
|
||||
|
||||
@@ -57,7 +61,7 @@ pub(super) async fn run_eslint(repo_path: &Path, repo_id: &str) -> Result<Vec<Fi
|
||||
severity,
|
||||
);
|
||||
finding.rule_id = Some(rule_id);
|
||||
finding.file_path = Some(file_result.file_path.clone());
|
||||
finding.file_path = Some(file.clone());
|
||||
finding.line_number = Some(msg.line);
|
||||
findings.push(finding);
|
||||
}
|
||||
|
||||
@@ -7,12 +7,24 @@ use std::time::Duration;
|
||||
|
||||
use compliance_core::models::ScanType;
|
||||
use compliance_core::traits::{ScanOutput, Scanner};
|
||||
use compliance_core::CoreError;
|
||||
use compliance_core::{CoreError, ExecPolicy};
|
||||
|
||||
/// Timeout for each individual lint command
|
||||
pub(crate) const LINT_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
|
||||
pub struct LintScanner;
|
||||
/// Language linters. Two of the three run code from the repository itself —
|
||||
/// clippy compiles it (`build.rs`, proc macros) and ESLint is the repo's own
|
||||
/// binary with JavaScript config — so they are gated on [`ExecPolicy`]. Ruff
|
||||
/// only parses, and always runs.
|
||||
pub struct LintScanner {
|
||||
exec: ExecPolicy,
|
||||
}
|
||||
|
||||
impl LintScanner {
|
||||
pub fn new(exec: ExecPolicy) -> Self {
|
||||
Self { exec }
|
||||
}
|
||||
}
|
||||
|
||||
impl Scanner for LintScanner {
|
||||
fn name(&self) -> &str {
|
||||
@@ -29,16 +41,24 @@ impl Scanner for LintScanner {
|
||||
|
||||
// Detect which languages are present and run appropriate linters
|
||||
if has_rust_project(repo_path) {
|
||||
match clippy::run_clippy(repo_path, repo_id).await {
|
||||
Ok(findings) => all_findings.extend(findings),
|
||||
Err(e) => tracing::warn!("Clippy failed: {e}"),
|
||||
if self.exec.untrusted_code_allowed() {
|
||||
match clippy::run_clippy(repo_path, repo_id).await {
|
||||
Ok(findings) => all_findings.extend(findings),
|
||||
Err(e) => tracing::warn!("Clippy failed: {e}"),
|
||||
}
|
||||
} else {
|
||||
tracing::info!("{}", self.exec.skip_reason("cargo clippy"));
|
||||
}
|
||||
}
|
||||
|
||||
if has_js_project(repo_path) {
|
||||
match eslint::run_eslint(repo_path, repo_id).await {
|
||||
Ok(findings) => all_findings.extend(findings),
|
||||
Err(e) => tracing::warn!("ESLint failed: {e}"),
|
||||
if self.exec.untrusted_code_allowed() {
|
||||
match eslint::run_eslint(repo_path, repo_id).await {
|
||||
Ok(findings) => all_findings.extend(findings),
|
||||
Err(e) => tracing::warn!("ESLint failed: {e}"),
|
||||
}
|
||||
} else {
|
||||
tracing::info!("{}", self.exec.skip_reason("ESLint"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,6 +91,30 @@ fn has_python_project(repo_path: &Path) -> bool {
|
||||
|| repo_path.join("requirements.txt").exists()
|
||||
}
|
||||
|
||||
/// A linter's file path relative to the scanned tree.
|
||||
///
|
||||
/// ruff and eslint report absolute paths, and the tree lives in a per-scan
|
||||
/// work directory: kept as-is, the path would show the server's layout to the
|
||||
/// customer and change every finding's fingerprint on every scan. Paths
|
||||
/// outside the tree are kept unchanged.
|
||||
pub(super) fn repo_relative(repo_path: &Path, file: &str) -> String {
|
||||
let file_path = Path::new(file);
|
||||
if let Ok(rel) = file_path.strip_prefix(repo_path) {
|
||||
return rel.to_string_lossy().into_owned();
|
||||
}
|
||||
// The tool may resolve symlinks (e.g. a temp dir) that `repo_path` keeps.
|
||||
repo_path
|
||||
.canonicalize()
|
||||
.ok()
|
||||
.and_then(|root| {
|
||||
file_path
|
||||
.strip_prefix(root)
|
||||
.ok()
|
||||
.map(|rel| rel.to_string_lossy().into_owned())
|
||||
})
|
||||
.unwrap_or_else(|| file.to_string())
|
||||
}
|
||||
|
||||
/// Run a command with a timeout, returning its output or an error
|
||||
pub(crate) async fn run_with_timeout(
|
||||
child: tokio::process::Child,
|
||||
@@ -95,3 +139,52 @@ pub(crate) async fn run_with_timeout(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{has_js_project, has_rust_project, repo_relative, LintScanner};
|
||||
|
||||
#[test]
|
||||
fn linter_paths_are_relative_to_the_scanned_tree() {
|
||||
let root = std::path::Path::new("/data/work/t1/a1");
|
||||
assert_eq!(
|
||||
repo_relative(root, "/data/work/t1/a1/src/app.py"),
|
||||
"src/app.py"
|
||||
);
|
||||
assert_eq!(repo_relative(root, "src/app.py"), "src/app.py");
|
||||
assert_eq!(
|
||||
repo_relative(root, "/elsewhere/app.py"),
|
||||
"/elsewhere/app.py"
|
||||
);
|
||||
}
|
||||
use compliance_core::traits::Scanner;
|
||||
use compliance_core::ExecPolicy;
|
||||
|
||||
/// A repo that would trigger both code-executing linters. The scan must
|
||||
/// come back empty — and, more to the point, must not have compiled
|
||||
/// anything — when the policy forbids executing tenant code.
|
||||
#[tokio::test]
|
||||
async fn code_executing_linters_are_skipped_without_the_policy() {
|
||||
let dir = std::env::temp_dir().join(format!("cs-lint-gate-{}", std::process::id()));
|
||||
let bin = dir.join("node_modules/.bin");
|
||||
std::fs::create_dir_all(&bin).expect("mkdir");
|
||||
std::fs::write(dir.join("Cargo.toml"), "[package]\nname=\"x\"\n").expect("cargo.toml");
|
||||
std::fs::write(dir.join("package.json"), "{}").expect("package.json");
|
||||
// A "linter" that would fail the test if it ever ran.
|
||||
std::fs::write(bin.join("eslint"), "#!/bin/sh\nexit 3\n").expect("eslint stub");
|
||||
|
||||
assert!(has_rust_project(&dir) && has_js_project(&dir), "fixture");
|
||||
|
||||
let out = LintScanner::new(ExecPolicy::trusted_only())
|
||||
.scan(&dir, "repo-1")
|
||||
.await
|
||||
.expect("scan");
|
||||
assert!(
|
||||
out.findings.is_empty(),
|
||||
"clippy and eslint must not run: {:?}",
|
||||
out.findings
|
||||
);
|
||||
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
}
|
||||
@@ -2,14 +2,13 @@ use std::path::Path;
|
||||
|
||||
use compliance_core::models::{Finding, ScanType, Severity};
|
||||
use compliance_core::CoreError;
|
||||
use tokio::process::Command;
|
||||
|
||||
use crate::pipeline::dedup;
|
||||
|
||||
use super::run_with_timeout;
|
||||
|
||||
pub(super) async fn run_ruff(repo_path: &Path, repo_id: &str) -> Result<Vec<Finding>, CoreError> {
|
||||
let child = Command::new("ruff")
|
||||
let child = crate::pipeline::tool_cmd::tool_in("ruff", repo_path, &[])
|
||||
.args(["check", ".", "--output-format", "json", "--exit-zero"])
|
||||
.current_dir(repo_path)
|
||||
.stdout(std::process::Stdio::piped())
|
||||
@@ -31,6 +30,7 @@ pub(super) async fn run_ruff(repo_path: &Path, repo_id: &str) -> Result<Vec<Find
|
||||
let findings = results
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let file = super::repo_relative(repo_path, &r.filename);
|
||||
let severity = if r.code.starts_with('E') || r.code.starts_with('F') {
|
||||
Severity::Medium
|
||||
} else {
|
||||
@@ -41,7 +41,7 @@ pub(super) async fn run_ruff(repo_path: &Path, repo_id: &str) -> Result<Vec<Find
|
||||
repo_id,
|
||||
"ruff",
|
||||
&r.code,
|
||||
&r.filename,
|
||||
&file,
|
||||
&r.location.row.to_string(),
|
||||
]);
|
||||
|
||||
@@ -55,7 +55,7 @@ pub(super) async fn run_ruff(repo_path: &Path, repo_id: &str) -> Result<Vec<Find
|
||||
severity,
|
||||
);
|
||||
finding.rule_id = Some(r.code);
|
||||
finding.file_path = Some(r.filename);
|
||||
finding.file_path = Some(file);
|
||||
finding.line_number = Some(r.location.row);
|
||||
finding
|
||||
})
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
pub mod code_review;
|
||||
pub mod cppcheck;
|
||||
pub mod cve;
|
||||
pub mod dedup;
|
||||
pub mod embedded_versions;
|
||||
pub mod finding_store;
|
||||
pub mod firmware_sbom;
|
||||
pub mod git;
|
||||
pub mod git_submodules;
|
||||
pub mod gitleaks;
|
||||
mod graph_build;
|
||||
mod issue_creation;
|
||||
pub mod languages;
|
||||
pub mod lint;
|
||||
pub mod nvd_cpe;
|
||||
pub mod orchestrator;
|
||||
pub mod patterns;
|
||||
pub mod plan;
|
||||
@@ -15,4 +21,7 @@ mod pr_review;
|
||||
pub mod repo_view;
|
||||
pub mod sbom;
|
||||
pub mod semgrep;
|
||||
pub mod source_text;
|
||||
pub mod tool_cmd;
|
||||
mod tracker_dispatch;
|
||||
pub mod vendor;
|
||||
@@ -0,0 +1,483 @@
|
||||
//! Known vulnerabilities of a product that is not in a package ecosystem.
|
||||
//!
|
||||
//! A CODESYS runtime, FreeRTOS or mbedTLS copied into a firmware tree has no
|
||||
//! purl OSV could look up. NVD indexes their CVEs by CPE, with the affected
|
||||
//! versions as ranges. So every CVE of the product is fetched once, and the
|
||||
//! ranges are matched here against the version in use.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// A product as NVD names it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct NvdProduct {
|
||||
/// The CPE prefix NVD is asked for. `cpe:2.3:*:amazon:freertos` covers
|
||||
/// both parts NVD files FreeRTOS under: `a` (its TCP/IP stack) and `o`
|
||||
/// (the kernel).
|
||||
pub match_string: &'static str,
|
||||
/// What a vulnerable CPE's criteria must contain to count
|
||||
/// (`:amazon:freertos:`), so a CVE listing several products only matches
|
||||
/// through this one.
|
||||
pub marker: &'static str,
|
||||
}
|
||||
|
||||
/// A CVE that affects the version in use.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct NvdCve {
|
||||
pub id: String,
|
||||
pub summary: Option<String>,
|
||||
pub cvss: Option<f64>,
|
||||
}
|
||||
|
||||
/// NVD's CVE API.
|
||||
const NVD_CVES_URL: &str = "https://services.nvd.nist.gov/rest/json/cves/2.0";
|
||||
|
||||
/// Waits before each retry of a failed NVD request. NVD asks for about six
|
||||
/// seconds between requests, and answers 403/429 when a key's budget is
|
||||
/// spent; three retries ride out a short limit without stalling a scan.
|
||||
const RETRY_DELAYS: [Duration; 3] = [
|
||||
Duration::from_secs(6),
|
||||
Duration::from_secs(12),
|
||||
Duration::from_secs(24),
|
||||
];
|
||||
|
||||
/// How long an NVD answer for a product is reused. CVEs are published daily,
|
||||
/// and repeated scans (a nightly corpus, several targets with the same
|
||||
/// FreeRTOS) must not spend the rate budget on the same question again.
|
||||
const CACHE_TTL: Duration = Duration::from_secs(6 * 60 * 60);
|
||||
|
||||
/// NVD answers by product match string, with when they were fetched.
|
||||
type Cache = Mutex<HashMap<String, (Instant, Arc<serde_json::Value>)>>;
|
||||
|
||||
fn cache() -> &'static Cache {
|
||||
static CACHE: OnceLock<Cache> = OnceLock::new();
|
||||
CACHE.get_or_init(Cache::default)
|
||||
}
|
||||
|
||||
/// The CVEs of `product` whose affected range covers `version`.
|
||||
///
|
||||
/// NVD is asked once per product and [`CACHE_TTL`]; a rate-limited or failed
|
||||
/// request is retried after [`RETRY_DELAYS`].
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Why NVD could not be asked (network, status, body) after the retries. The
|
||||
/// caller records it on the scan run: a lookup that failed must not read as a
|
||||
/// product without CVEs.
|
||||
pub async fn product_cves(
|
||||
http: &reqwest::Client,
|
||||
api_key: Option<&str>,
|
||||
product: NvdProduct,
|
||||
version: &str,
|
||||
) -> Result<Vec<NvdCve>, String> {
|
||||
let body = product_body(
|
||||
http,
|
||||
NVD_CVES_URL,
|
||||
api_key,
|
||||
product.match_string,
|
||||
&RETRY_DELAYS,
|
||||
)
|
||||
.await?;
|
||||
Ok(parse(&body, product.marker, version))
|
||||
}
|
||||
|
||||
/// NVD's answer for `match_string`: cached, or fetched from `base_url` with
|
||||
/// a retry after each of `delays`.
|
||||
async fn product_body(
|
||||
http: &reqwest::Client,
|
||||
base_url: &str,
|
||||
api_key: Option<&str>,
|
||||
match_string: &str,
|
||||
delays: &[Duration],
|
||||
) -> Result<Arc<serde_json::Value>, String> {
|
||||
if let Some(body) = cached(match_string) {
|
||||
return Ok(body);
|
||||
}
|
||||
let mut last_error = String::new();
|
||||
for attempt in 0..=delays.len() {
|
||||
if let Some(wait) = attempt.checked_sub(1).and_then(|i| delays.get(i)) {
|
||||
tracing::info!(
|
||||
match_string,
|
||||
attempt,
|
||||
"retrying NVD after {wait:?}: {last_error}"
|
||||
);
|
||||
tokio::time::sleep(*wait).await;
|
||||
}
|
||||
let mut req = http
|
||||
.get(base_url)
|
||||
.query(&[("virtualMatchString", match_string)]);
|
||||
if let Some(key) = api_key {
|
||||
req = req.header("apiKey", key);
|
||||
}
|
||||
match req.send().await {
|
||||
Ok(resp) if resp.status().is_success() => {
|
||||
let body: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?;
|
||||
let body = Arc::new(body);
|
||||
if let Ok(mut c) = cache().lock() {
|
||||
c.insert(
|
||||
match_string.to_string(),
|
||||
(Instant::now(), Arc::clone(&body)),
|
||||
);
|
||||
}
|
||||
return Ok(body);
|
||||
}
|
||||
Ok(resp) if is_transient(resp.status()) => {
|
||||
last_error = format!("NVD returned {}", resp.status());
|
||||
}
|
||||
Ok(resp) => return Err(format!("NVD returned {}", resp.status())),
|
||||
Err(e) => last_error = e.to_string(),
|
||||
}
|
||||
}
|
||||
Err(last_error)
|
||||
}
|
||||
|
||||
/// A fresh cached answer for `match_string`, if there is one.
|
||||
fn cached(match_string: &str) -> Option<Arc<serde_json::Value>> {
|
||||
let cache = cache().lock().ok()?;
|
||||
let (at, body) = cache.get(match_string)?;
|
||||
(at.elapsed() < CACHE_TTL).then(|| Arc::clone(body))
|
||||
}
|
||||
|
||||
/// Whether NVD may answer differently when asked again: a spent rate budget
|
||||
/// (403, 429) or a server error.
|
||||
fn is_transient(status: reqwest::StatusCode) -> bool {
|
||||
matches!(status.as_u16(), 403 | 429 | 500 | 502 | 503 | 504)
|
||||
}
|
||||
|
||||
/// The CVEs in an NVD response with a vulnerable CPE containing `marker`
|
||||
/// whose range covers `version`.
|
||||
pub fn parse(body: &serde_json::Value, marker: &str, version: &str) -> Vec<NvdCve> {
|
||||
let Some(vulns) = body["vulnerabilities"].as_array() else {
|
||||
return Vec::new();
|
||||
};
|
||||
vulns
|
||||
.iter()
|
||||
.filter_map(|v| {
|
||||
let cve = &v["cve"];
|
||||
let id = cve["id"].as_str()?;
|
||||
let covered = cve["configurations"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flat_map(|c| c["nodes"].as_array().into_iter().flatten())
|
||||
.flat_map(|n| n["cpeMatch"].as_array().into_iter().flatten())
|
||||
.any(|cm| {
|
||||
cm["vulnerable"].as_bool() == Some(true)
|
||||
&& cm["criteria"].as_str().is_some_and(|c| c.contains(marker))
|
||||
&& version_matches(version, &cpe_range(cm))
|
||||
});
|
||||
covered.then(|| NvdCve {
|
||||
id: id.to_string(),
|
||||
summary: cve["descriptions"]
|
||||
.as_array()
|
||||
.and_then(|d| d.iter().find(|x| x["lang"].as_str() == Some("en")))
|
||||
.and_then(|x| x["value"].as_str())
|
||||
.map(String::from),
|
||||
cvss: cve["metrics"]["cvssMetricV31"]
|
||||
.as_array()
|
||||
.and_then(|m| m.first())
|
||||
.and_then(|m| m["cvssData"]["baseScore"].as_f64()),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Version constraints from an NVD `cpeMatch` node.
|
||||
#[derive(Default)]
|
||||
struct CpeRange {
|
||||
exact: Option<String>,
|
||||
start_incl: Option<String>,
|
||||
start_excl: Option<String>,
|
||||
end_incl: Option<String>,
|
||||
end_excl: Option<String>,
|
||||
}
|
||||
|
||||
/// Build a [`CpeRange`] from an NVD `cpeMatch` object.
|
||||
fn cpe_range(cm: &serde_json::Value) -> CpeRange {
|
||||
let exact = cm["criteria"]
|
||||
.as_str()
|
||||
.and_then(cpe_version)
|
||||
.filter(|v| v != "*" && v != "-" && !v.is_empty());
|
||||
CpeRange {
|
||||
exact,
|
||||
start_incl: cm["versionStartIncluding"].as_str().map(String::from),
|
||||
start_excl: cm["versionStartExcluding"].as_str().map(String::from),
|
||||
end_incl: cm["versionEndIncluding"].as_str().map(String::from),
|
||||
end_excl: cm["versionEndExcluding"].as_str().map(String::from),
|
||||
}
|
||||
}
|
||||
|
||||
/// The version field (6th component) of a CPE 2.3 string.
|
||||
fn cpe_version(criteria: &str) -> Option<String> {
|
||||
criteria.split(':').nth(5).map(String::from)
|
||||
}
|
||||
|
||||
/// Whether `v` satisfies a CPE version range.
|
||||
fn version_matches(v: &str, r: &CpeRange) -> bool {
|
||||
use std::cmp::Ordering::{Equal, Greater, Less};
|
||||
if let Some(exact) = &r.exact {
|
||||
return cmp_dotted(v, exact) == Equal;
|
||||
}
|
||||
let mut ok = true;
|
||||
if let Some(s) = &r.start_incl {
|
||||
ok &= cmp_dotted(v, s) != Less;
|
||||
}
|
||||
if let Some(s) = &r.start_excl {
|
||||
ok &= cmp_dotted(v, s) == Greater;
|
||||
}
|
||||
if let Some(e) = &r.end_incl {
|
||||
ok &= cmp_dotted(v, e) != Greater;
|
||||
}
|
||||
if let Some(e) = &r.end_excl {
|
||||
ok &= cmp_dotted(v, e) == Less;
|
||||
}
|
||||
ok
|
||||
}
|
||||
|
||||
/// Compare two dotted versions (`4.17.0.0` vs `4.9.0.0`); a missing
|
||||
/// component counts as 0.
|
||||
///
|
||||
/// A leading `r`/`v` is ignored (FatFs `r0.14b`, `V10.4.6`), and a component
|
||||
/// is its number then any letter suffix, so `14` < `14b` < `15`.
|
||||
fn cmp_dotted(a: &str, b: &str) -> std::cmp::Ordering {
|
||||
let parts = |v: &str| -> Vec<(u64, String)> {
|
||||
v.trim_start_matches(['r', 'R', 'v', 'V'])
|
||||
.split('.')
|
||||
.map(|part| {
|
||||
let digits =
|
||||
part.len() - part.trim_start_matches(|c: char| c.is_ascii_digit()).len();
|
||||
(
|
||||
part[..digits].parse().unwrap_or(0),
|
||||
part[digits..].to_ascii_lowercase(),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let (pa, pb) = (parts(a), parts(b));
|
||||
let zero = (0, String::new());
|
||||
for i in 0..pa.len().max(pb.len()) {
|
||||
match pa.get(i).unwrap_or(&zero).cmp(pb.get(i).unwrap_or(&zero)) {
|
||||
std::cmp::Ordering::Equal => continue,
|
||||
other => return other,
|
||||
}
|
||||
}
|
||||
std::cmp::Ordering::Equal
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cmp::Ordering::{Equal, Greater, Less};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
/// A stand-in for NVD answering `fail` times with `status`, then 200; it
|
||||
/// counts the requests.
|
||||
async fn fake_nvd(fail: usize, status: u16) -> (String, Arc<AtomicUsize>) {
|
||||
let hits = Arc::new(AtomicUsize::new(0));
|
||||
let counter = Arc::clone(&hits);
|
||||
let app = axum::Router::new().route(
|
||||
"/",
|
||||
axum::routing::get(move || {
|
||||
let counter = Arc::clone(&counter);
|
||||
async move {
|
||||
let n = counter.fetch_add(1, Ordering::SeqCst);
|
||||
if n < fail {
|
||||
(
|
||||
axum::http::StatusCode::from_u16(status)
|
||||
.unwrap_or(axum::http::StatusCode::FORBIDDEN),
|
||||
String::new(),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
axum::http::StatusCode::OK,
|
||||
r#"{"vulnerabilities":[]}"#.to_string(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("bind: {e}"));
|
||||
let url = format!(
|
||||
"http://{}/",
|
||||
listener
|
||||
.local_addr()
|
||||
.unwrap_or_else(|e| panic!("addr: {e}"))
|
||||
);
|
||||
tokio::spawn(async move {
|
||||
let _ = axum::serve(listener, app).await;
|
||||
});
|
||||
(url, hits)
|
||||
}
|
||||
|
||||
const NO_WAIT: [Duration; 3] = [Duration::ZERO; 3];
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_rate_limited_lookup_is_retried_and_then_cached() {
|
||||
let (url, hits) = fake_nvd(2, 403).await;
|
||||
let http = reqwest::Client::new();
|
||||
|
||||
let first = product_body(&http, &url, None, "cpe:test:retry", &NO_WAIT).await;
|
||||
let again = product_body(&http, &url, None, "cpe:test:retry", &NO_WAIT).await;
|
||||
|
||||
assert!(first.is_ok(), "{first:?}");
|
||||
assert!(again.is_ok());
|
||||
// Two refusals, one answer, and the second ask came from the cache.
|
||||
assert_eq!(hits.load(Ordering::SeqCst), 3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_lasting_limit_is_an_error_not_an_empty_answer() {
|
||||
let (url, hits) = fake_nvd(usize::MAX, 429).await;
|
||||
let http = reqwest::Client::new();
|
||||
|
||||
let result = product_body(&http, &url, None, "cpe:test:limited", &NO_WAIT).await;
|
||||
|
||||
assert_eq!(
|
||||
result.err().as_deref(),
|
||||
Some("NVD returned 429 Too Many Requests")
|
||||
);
|
||||
assert_eq!(
|
||||
hits.load(Ordering::SeqCst),
|
||||
4,
|
||||
"the first try and three retries"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_request_nvd_refuses_for_good_is_not_retried() {
|
||||
let (url, hits) = fake_nvd(usize::MAX, 404).await;
|
||||
let http = reqwest::Client::new();
|
||||
|
||||
assert!(
|
||||
product_body(&http, &url, None, "cpe:test:missing", &NO_WAIT)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(hits.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fatfs_revisions_match_nvds_ranges() {
|
||||
// The shape of CVE-2026-6682: FatFs R0.16 and earlier.
|
||||
let body = serde_json::json!({ "vulnerabilities": [{ "cve": {
|
||||
"id": "CVE-2026-6682",
|
||||
"configurations": [{ "nodes": [{ "cpeMatch": [{
|
||||
"vulnerable": true,
|
||||
"criteria": "cpe:2.3:a:elm-chan:fatfs:*:*:*:*:*:*:*:*",
|
||||
"versionEndIncluding": "r0.16"
|
||||
}]}]}]
|
||||
}}]});
|
||||
assert_eq!(parse(&body, ":elm-chan:fatfs:", "r0.14b").len(), 1);
|
||||
assert!(parse(&body, ":elm-chan:fatfs:", "r0.16a").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dotted_version_comparison() {
|
||||
assert_eq!(cmp_dotted("4.17.0.0", "4.9.0.0"), Greater);
|
||||
assert_eq!(cmp_dotted("4.9.0.0", "4.17.0.0"), Less);
|
||||
assert_eq!(cmp_dotted("3.5.18.0", "3.5.18.0"), Equal);
|
||||
assert_eq!(cmp_dotted("4.2", "4.2.0.0"), Equal); // missing components = 0
|
||||
// FatFs revisions, as NVD writes them.
|
||||
assert_eq!(cmp_dotted("r0.14b", "r0.16"), Less);
|
||||
assert_eq!(cmp_dotted("r0.14b", "r0.14"), Greater);
|
||||
assert_eq!(cmp_dotted("R0.14B", "r0.14b"), Equal);
|
||||
assert_eq!(cmp_dotted("V4.1.0", "4.1.1"), Less);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_range_matching() {
|
||||
let end_excl = CpeRange {
|
||||
end_excl: Some("4.9.0.0".into()),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!version_matches("4.17.0.0", &end_excl)); // patched
|
||||
assert!(version_matches("4.5.0.0", &end_excl)); // affected
|
||||
|
||||
let exact = CpeRange {
|
||||
exact: Some("3.5.16.0".into()),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(version_matches("3.5.16.0", &exact));
|
||||
assert!(!version_matches("3.5.17.0", &exact));
|
||||
|
||||
let span = CpeRange {
|
||||
start_incl: Some("3.0.0.0".into()),
|
||||
end_incl: Some("3.5.16.0".into()),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(version_matches("3.5.16.0", &span));
|
||||
assert!(!version_matches("3.5.17.0", &span));
|
||||
}
|
||||
|
||||
/// An NVD response with one CVE fixed before `fixed_below` and one that
|
||||
/// still affects everything up to `affected_up_to`.
|
||||
fn two_cves(criteria: &str, fixed_below: &str, affected_up_to: &str) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"vulnerabilities": [
|
||||
{"cve": {"id":"CVE-2023-0001",
|
||||
"descriptions":[{"lang":"en","value":"old bug"}],
|
||||
"metrics":{"cvssMetricV31":[{"cvssData":{"baseScore":7.5}}]},
|
||||
"configurations":[{"nodes":[{"cpeMatch":[
|
||||
{"vulnerable":true, "criteria": criteria, "versionEndExcluding": fixed_below}
|
||||
]}]}]}},
|
||||
{"cve": {"id":"CVE-2024-0002",
|
||||
"descriptions":[{"lang":"en","value":"recent bug"}],
|
||||
"metrics":{"cvssMetricV31":[{"cvssData":{"baseScore":9.8}}]},
|
||||
"configurations":[{"nodes":[{"cpeMatch":[
|
||||
{"vulnerable":true, "criteria": criteria, "versionEndIncluding": affected_up_to}
|
||||
]}]}]}}
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_cves_covering_the_version_match() {
|
||||
let body = two_cves(
|
||||
"cpe:2.3:a:codesys:control_for_linux_sl:*:*:*:*:*:*:*:*",
|
||||
"4.9.0.0",
|
||||
"4.20.0.0",
|
||||
);
|
||||
let matched = parse(&body, ":codesys:", "4.17.0.0");
|
||||
let ids: Vec<&str> = matched.iter().map(|c| c.id.as_str()).collect();
|
||||
assert_eq!(ids, vec!["CVE-2024-0002"]);
|
||||
assert_eq!(matched[0].cvss, Some(9.8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cve_of_another_product_does_not_match() {
|
||||
let body = two_cves(
|
||||
"cpe:2.3:a:amazon:freertos:*:*:*:*:*:*:*:*",
|
||||
"10.4.3",
|
||||
"10.6.0",
|
||||
);
|
||||
assert_eq!(parse(&body, ":amazon:freertos:", "10.4.1").len(), 2);
|
||||
assert!(parse(&body, ":arm:mbed_tls:", "10.4.1").is_empty());
|
||||
}
|
||||
|
||||
/// A real NVD excerpt: the 2018 TCP/IP stack CVEs (up to 10.0.1, filed
|
||||
/// under the application CPE) and two kernel CVEs (filed under the
|
||||
/// operating-system CPE), fixed in 10.4.3 and 10.6.2.
|
||||
#[test]
|
||||
fn real_freertos_ranges_match_by_version() {
|
||||
let body: serde_json::Value =
|
||||
serde_json::from_str(include_str!("testdata/nvd_freertos.json")).unwrap_or_default();
|
||||
let ids = |version: &str| -> Vec<String> {
|
||||
let mut ids: Vec<String> = parse(&body, ":amazon:freertos:", version)
|
||||
.into_iter()
|
||||
.map(|c| c.id)
|
||||
.collect();
|
||||
ids.sort();
|
||||
ids
|
||||
};
|
||||
assert_eq!(
|
||||
ids("10.0.1"),
|
||||
["CVE-2018-16523", "CVE-2021-31571", "CVE-2024-28115"]
|
||||
);
|
||||
assert_eq!(ids("10.3.1"), ["CVE-2021-31571", "CVE-2024-28115"]);
|
||||
assert_eq!(ids("10.5.1"), ["CVE-2024-28115"]);
|
||||
assert!(ids("10.6.2").is_empty());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -22,11 +22,24 @@ pub struct ScanStep {
|
||||
pub artifact_id: String,
|
||||
}
|
||||
|
||||
/// A scan this target carries the artifact for, which no pipeline stage runs
|
||||
/// yet. Recorded on the scan run as a skipped stage, so an artifact nothing
|
||||
/// looked at is visible instead of silently ignored.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct UnavailableScan {
|
||||
/// The scan that is not implemented.
|
||||
pub scan_type: ScanType,
|
||||
/// What covers the ground instead.
|
||||
pub reason: &'static str,
|
||||
}
|
||||
|
||||
/// The ordered set of scans to run for a target.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct ScanPlan {
|
||||
/// The scans, in matrix order.
|
||||
pub steps: Vec<ScanStep>,
|
||||
/// Scans whose artifact is attached but which nothing runs yet.
|
||||
pub unavailable: Vec<UnavailableScan>,
|
||||
}
|
||||
|
||||
impl ScanPlan {
|
||||
@@ -49,7 +62,22 @@ pub fn build_scan_plan(target: &OnboardedTarget) -> ScanPlan {
|
||||
let disabled = &target.scan_config.disabled_scans;
|
||||
|
||||
let mut steps = Vec::new();
|
||||
let mut unavailable = Vec::new();
|
||||
for option in applicable_scans(target) {
|
||||
// Nothing runs this scan yet. When the target carries the artifact it
|
||||
// would consume, the run says so rather than passing over it.
|
||||
if let Some(reason) = option.unavailable_with_artifact() {
|
||||
if !disabled.contains(&option.scan) {
|
||||
unavailable.push(UnavailableScan {
|
||||
scan_type: option.scan,
|
||||
reason,
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if option.unavailable.is_some() {
|
||||
continue;
|
||||
}
|
||||
// Required artifact missing → not runnable.
|
||||
if option.blocked_reason.is_some() {
|
||||
continue;
|
||||
@@ -71,7 +99,10 @@ pub fn build_scan_plan(target: &OnboardedTarget) -> ScanPlan {
|
||||
artifact_id: artifact.id.clone(),
|
||||
});
|
||||
}
|
||||
ScanPlan { steps }
|
||||
// A scan another rule does run (the firmware SBOM off the sources, say) is
|
||||
// not reported as unavailable because its image-bound rule is.
|
||||
unavailable.retain(|u| !steps.iter().any(|s| s.scan_type == u.scan_type));
|
||||
ScanPlan { steps, unavailable }
|
||||
}
|
||||
|
||||
/// Resolve the artifact a scan consumes. A "code" requirement (represented by
|
||||
@@ -101,7 +132,9 @@ fn phase_for(scan: ScanType) -> ScanPhase {
|
||||
ScanType::Lint => ScanPhase::LintScanning,
|
||||
ScanType::CodeReview => ScanPhase::CodeReview,
|
||||
ScanType::Graph => ScanPhase::GraphBuilding,
|
||||
ScanType::Dast => ScanPhase::DastScanning,
|
||||
// A penetration test is done by a person and never planned here; its
|
||||
// findings are entered or imported, so it borrows the dynamic phase.
|
||||
ScanType::Dast | ScanType::Pentest => ScanPhase::DastScanning,
|
||||
ScanType::FirmwareStatic => ScanPhase::FirmwareStatic,
|
||||
ScanType::PlcControlLogic => ScanPhase::PlcAnalysis,
|
||||
ScanType::MobileStatic => ScanPhase::MobileStatic,
|
||||
@@ -122,7 +155,7 @@ mod tests {
|
||||
t
|
||||
}
|
||||
|
||||
fn step_for<'a>(plan: &'a ScanPlan, scan: ScanType) -> Option<&'a ScanStep> {
|
||||
fn step_for(plan: &ScanPlan, scan: ScanType) -> Option<&ScanStep> {
|
||||
plan.steps.iter().find(|s| s.scan_type == scan)
|
||||
}
|
||||
|
||||
@@ -159,18 +192,68 @@ mod tests {
|
||||
assert_eq!(sast.artifact_id, arc_id);
|
||||
}
|
||||
|
||||
fn unavailable_for(plan: &ScanPlan, scan: ScanType) -> Option<&UnavailableScan> {
|
||||
plan.unavailable.iter().find(|u| u.scan_type == scan)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn firmware_sbom_and_cve_bind_to_the_firmware_image() {
|
||||
let fw = Artifact::firmware_image("fw.bin");
|
||||
let fw_id = fw.id.clone();
|
||||
let t = target(TargetType::FirmwareBareMetal, vec![fw]);
|
||||
fn a_firmware_image_plans_nothing_and_is_recorded_as_unanalysed() {
|
||||
let t = target(
|
||||
TargetType::FirmwareBareMetal,
|
||||
vec![Artifact::firmware_image("fw.bin")],
|
||||
);
|
||||
let plan = build_scan_plan(&t);
|
||||
let sbom = step_for(&plan, ScanType::Sbom).expect("sbom planned");
|
||||
assert_eq!(sbom.artifact_id, fw_id);
|
||||
assert!(step_for(&plan, ScanType::FirmwareStatic).is_some());
|
||||
// Nothing runs on the image, so no step claims to.
|
||||
assert!(plan.steps.is_empty(), "{:?}", plan.steps);
|
||||
for scan in [ScanType::FirmwareStatic, ScanType::Sbom, ScanType::Cve] {
|
||||
assert!(unavailable_for(&plan, scan).is_some(), "{scan} recorded");
|
||||
}
|
||||
assert!(!plan.has(ScanType::Dast));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scan_that_runs_off_the_sources_is_not_reported_unavailable() {
|
||||
// Firmware sources plus an image: the SBOM runs off the sources, so only
|
||||
// the image-only scans are recorded as unanalysed.
|
||||
let t = target(
|
||||
TargetType::FirmwareRtos,
|
||||
vec![
|
||||
Artifact::git_repo("https://git/fw", "main"),
|
||||
Artifact::firmware_image("fw.bin"),
|
||||
],
|
||||
);
|
||||
let plan = build_scan_plan(&t);
|
||||
assert!(plan.has(ScanType::Sbom));
|
||||
assert!(unavailable_for(&plan, ScanType::Sbom).is_none());
|
||||
assert!(unavailable_for(&plan, ScanType::Cve).is_none());
|
||||
assert!(unavailable_for(&plan, ScanType::FirmwareStatic).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_container_image_is_recorded_as_unscanned() {
|
||||
let t = target(
|
||||
TargetType::BackendService,
|
||||
vec![
|
||||
Artifact::git_repo("https://git/x", "main"),
|
||||
Artifact::container_image("registry/app:1.2.3"),
|
||||
],
|
||||
);
|
||||
let plan = build_scan_plan(&t);
|
||||
assert!(plan.has(ScanType::Sast));
|
||||
assert!(unavailable_for(&plan, ScanType::ContainerScan).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_explicitly_disabled_unavailable_scan_is_not_recorded() {
|
||||
let mut t = target(
|
||||
TargetType::AndroidApp,
|
||||
vec![Artifact::mobile_package("app.apk")],
|
||||
);
|
||||
t.scan_config.disabled_scans.push(ScanType::MobileStatic);
|
||||
let plan = build_scan_plan(&t);
|
||||
assert!(unavailable_for(&plan, ScanType::MobileStatic).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plc_plans_only_control_logic() {
|
||||
let plc = Artifact::plc_project("p.xml", PlcFormat::PlcopenXml);
|
||||
|
||||
@@ -51,6 +51,18 @@ pub fn collect_sbom(artifact_file: &Path, working_path: &Path, repo_id: &str) ->
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `archive` opens as a zip, i.e. could be a CODESYS project archive.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The reason it cannot be read, for recording on the scan run.
|
||||
pub fn check_archive(archive: &Path) -> Result<(), String> {
|
||||
let file = std::fs::File::open(archive).map_err(|e| e.to_string())?;
|
||||
zip::ZipArchive::new(file)
|
||||
.map(drop)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Extract CODESYS library + runtime components from a `.projectarchive` (a zip).
|
||||
/// Best-effort: returns empty if the file is not a readable zip (e.g. a bare
|
||||
/// `.st`/`.xml` project, which carries no library manifest).
|
||||
@@ -64,7 +76,9 @@ pub fn projectarchive_sbom(archive: &Path, repo_id: &str) -> Vec<SbomEntry> {
|
||||
let mut seen: BTreeSet<(String, String)> = BTreeSet::new();
|
||||
let mut entries = Vec::new();
|
||||
for i in 0..zip.len() {
|
||||
let Ok(entry) = zip.by_index(i) else {
|
||||
// Only the entry names are read, and a zip never encrypts those: the
|
||||
// raw entry lists a password-protected archive's components too.
|
||||
let Ok(entry) = zip.by_index_raw(i) else {
|
||||
continue;
|
||||
};
|
||||
// Entry paths use `\` (Windows-authored) and/or `/` separators; the
|
||||
@@ -174,6 +188,17 @@ mod tests {
|
||||
zip.finish().expect("finish");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_corrupt_archive_is_reported_not_silently_empty() {
|
||||
let tmp = std::env::temp_dir().join(format!("cs-plc-bad-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&tmp).expect("mkdir");
|
||||
let bad = tmp.join("Broken.projectarchive");
|
||||
std::fs::write(&bad, b"PK\x03\x04 not a real archive").expect("write");
|
||||
assert!(check_archive(&bad).is_err());
|
||||
assert!(check_archive(&synthetic_archive(&tmp)).is_ok());
|
||||
let _ = std::fs::remove_dir_all(&tmp);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extracts_libraries_and_runtime_from_projectarchive() {
|
||||
let tmp = std::env::temp_dir().join(format!("cs-plc-sbom-{}", uuid::Uuid::new_v4()));
|
||||
|
||||
Loaded 100 of 446 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user