Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
860d1a78bf | ||
|
|
a3735b12b7 | ||
|
|
db515486a4 | ||
|
|
d9f5ad85dc | ||
|
|
64f5a810dd | ||
|
|
57b5aaeb97 | ||
|
|
ba499d14e4 | ||
|
|
42b25719ec | ||
|
|
8d6be32c83 | ||
|
|
ac50880b25 | ||
|
|
e382746cfb | ||
|
|
7e3856db31 | ||
|
|
750f1d7308 | ||
|
|
528c9d4f7f | ||
|
|
cc5b667870 | ||
|
|
11e3b98c99 | ||
|
|
dcf78b8e66 | ||
|
|
6f1172589e | ||
|
|
7f2b128efd | ||
|
|
2c2fea6222 | ||
|
|
44b2f38841 | ||
|
|
69a4c2084a | ||
|
|
2ca73acabf | ||
|
|
2c5b2eb003 | ||
|
|
e396141490 |
No files matched your search
@@ -27,6 +27,9 @@ SEARXNG_URL=http://localhost:8888
|
||||
|
||||
# NVD
|
||||
NVD_API_KEY=
|
||||
# The CVE monitor re-checks components only NVD knows (Yocto recipes, embedded
|
||||
# libraries, CODESYS runtime) by NVD's changed CVEs; on by default.
|
||||
# NVD_MONITOR=off
|
||||
|
||||
# Agent
|
||||
AGENT_PORT=3001
|
||||
@@ -50,6 +53,14 @@ CVE_MONITOR_SCHEDULE=0 0 0 * * *
|
||||
# FINDING_GROUP_THRESHOLD=5
|
||||
# FINDING_GROUP_SCANNERS=mobsfscan=5,gitleaks=off
|
||||
# FINDING_GROUP_SEVERITIES=low,info
|
||||
# Issue catch-up (Gitea only): after a scan's own issues, open medium+ findings
|
||||
# that never got an issue are linked to their existing issue or get a new one,
|
||||
# at most 20 new per target and scan. off (default) | dry_run (log counts only) | on
|
||||
# ISSUE_CATCHUP=off
|
||||
# Closing CVE issues a VEX statement settles (not_affected or fixed), with a
|
||||
# comment, at most 20 per target and scan; no new issue is opened for such a
|
||||
# CVE either way. off (default) | dry_run (log counts per VEX status) | on
|
||||
# ISSUE_AUTOCLOSE=off
|
||||
GIT_CLONE_BASE_PATH=/tmp/compliance-scanner/repos
|
||||
# NuGet licenses (#467): look up licenses the tree's .nuspec files do not give
|
||||
# on api.nuget.org (package id and version only; never for ids a nuget.config
|
||||
|
||||
@@ -176,9 +176,11 @@ jobs:
|
||||
echo "Changed files:"
|
||||
echo "$CHANGED"
|
||||
|
||||
# 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
|
||||
# Agent: core libs and the crates the agent links (werkbank-exec,
|
||||
# control-map), agent code, agent Dockerfile and the helper scripts
|
||||
# it copies from docker/, 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/|werkbank-exec/|control-map/|docker/|Dockerfile\.agent|Cargo\.(toml|lock)|docs/|README\.md)'; then
|
||||
echo "agent=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "agent=false" >> "$GITHUB_OUTPUT"
|
||||
|
||||
@@ -7,3 +7,6 @@
|
||||
.playwright-mcp/
|
||||
report-preview-full.png
|
||||
compliance-dashboard/attack-chain-final.html
|
||||
|
||||
# Python bytecode (the agent image helpers)
|
||||
__pycache__/
|
||||
Generated
+26
-318
@@ -150,20 +150,6 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-tungstenite"
|
||||
version = "0.27.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c5359381fd414fbdb272c48f2111c16cb0bb3447bfacd59311ff3736da9f6664"
|
||||
dependencies = [
|
||||
"futures-io",
|
||||
"futures-util",
|
||||
"log",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
"tungstenite 0.23.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-tungstenite"
|
||||
version = "0.31.0"
|
||||
@@ -349,50 +335,6 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bollard"
|
||||
version = "0.18.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "97ccca1260af6a459d75994ad5acc1651bcabcbdbc41467cc9786519ab854c30"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bollard-stubs",
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"hex",
|
||||
"http",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-named-pipe",
|
||||
"hyper-util",
|
||||
"hyperlocal",
|
||||
"log",
|
||||
"pin-project-lite",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"serde_repr",
|
||||
"serde_urlencoded",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tower-service",
|
||||
"url",
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bollard-stubs"
|
||||
version = "1.47.1-rc.27.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f179cfbddb6e77a5472703d4b30436bff32929c0aa8a9008ecf23d1d3cdd0da"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_repr",
|
||||
"serde_with",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bon"
|
||||
version = "3.9.0"
|
||||
@@ -437,7 +379,7 @@ dependencies = [
|
||||
"getrandom 0.2.17",
|
||||
"getrandom 0.3.4",
|
||||
"hex",
|
||||
"indexmap 2.13.0",
|
||||
"indexmap",
|
||||
"js-sys",
|
||||
"once_cell",
|
||||
"rand 0.9.2",
|
||||
@@ -562,72 +504,6 @@ dependencies = [
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chromiumoxide"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8380ce7721cc895fe8a184c49d615fe755b0c9a3d7986355cee847439fff907f"
|
||||
dependencies = [
|
||||
"async-tungstenite 0.27.0",
|
||||
"base64",
|
||||
"cfg-if",
|
||||
"chromiumoxide_cdp",
|
||||
"chromiumoxide_types",
|
||||
"dunce",
|
||||
"fnv",
|
||||
"futures",
|
||||
"futures-timer",
|
||||
"pin-project-lite",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 1.0.69",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"url",
|
||||
"which",
|
||||
"winreg 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chromiumoxide_cdp"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cadbfb52fa0aeca43626f6c42ca04184b108b786f8e45198dc41a42aedcf2e50"
|
||||
dependencies = [
|
||||
"chromiumoxide_pdl",
|
||||
"chromiumoxide_types",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chromiumoxide_pdl"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c197aeb42872c5d4c923e7d8ad46d99a58fd0fec37f6491554ff677a6791d3c9"
|
||||
dependencies = [
|
||||
"chromiumoxide_types",
|
||||
"either",
|
||||
"heck 0.4.1",
|
||||
"once_cell",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"regex",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chromiumoxide_types"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "923486888790528d55ac37ec2f7483ed19eb8ccbb44701878e5856d1ceadf5d8"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chrono"
|
||||
version = "0.4.44"
|
||||
@@ -706,12 +582,10 @@ dependencies = [
|
||||
"firmwerk-repro",
|
||||
"firmwerk-sbom",
|
||||
"flate2",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"git2",
|
||||
"hex",
|
||||
"hmac",
|
||||
"jsonwebtoken",
|
||||
"mongodb",
|
||||
"object",
|
||||
"octocrab",
|
||||
@@ -739,6 +613,7 @@ dependencies = [
|
||||
"uuid",
|
||||
"walkdir",
|
||||
"werkbank-exec",
|
||||
"yaml-rust2",
|
||||
"zip",
|
||||
]
|
||||
|
||||
@@ -780,7 +655,6 @@ dependencies = [
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64",
|
||||
"bson",
|
||||
"chrono",
|
||||
"compliance-core",
|
||||
"dioxus",
|
||||
@@ -796,7 +670,6 @@ dependencies = [
|
||||
"pulldown-cmark",
|
||||
"rand 0.9.2",
|
||||
"reqwest",
|
||||
"secrecy",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
@@ -818,19 +691,13 @@ name = "compliance-dast"
|
||||
version = "0.4.6"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bollard",
|
||||
"bson",
|
||||
"chromiumoxide",
|
||||
"chrono",
|
||||
"compliance-core",
|
||||
"futures-util",
|
||||
"mongodb",
|
||||
"native-tls",
|
||||
"reqwest",
|
||||
"scraper",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tokio-native-tls",
|
||||
"tokio-tungstenite 0.26.2",
|
||||
@@ -850,9 +717,7 @@ dependencies = [
|
||||
"mongodb",
|
||||
"petgraph",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tantivy",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tree-sitter",
|
||||
@@ -860,7 +725,6 @@ dependencies = [
|
||||
"tree-sitter-python",
|
||||
"tree-sitter-rust",
|
||||
"tree-sitter-typescript",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -876,13 +740,12 @@ dependencies = [
|
||||
"hex",
|
||||
"mongodb",
|
||||
"rmcp",
|
||||
"schemars 1.2.1",
|
||||
"schemars",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tower-http",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
]
|
||||
@@ -893,7 +756,6 @@ version = "0.4.6"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"compliance-core",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
@@ -1606,7 +1468,7 @@ checksum = "7db1f8b70338072ec408b48d09c96559cf071f87847465d8161294197504c498"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-stream",
|
||||
"async-tungstenite 0.31.0",
|
||||
"async-tungstenite",
|
||||
"axum",
|
||||
"axum-core",
|
||||
"axum-extra",
|
||||
@@ -2130,7 +1992,7 @@ version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
@@ -2348,7 +2210,7 @@ version = "0.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8640e34b88f7652208ce9e88b1a37a2ae95227d84abec377ccd3c5cfeb141ed4"
|
||||
dependencies = [
|
||||
"rustix 1.1.4",
|
||||
"rustix",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
@@ -2439,12 +2301,6 @@ version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
|
||||
|
||||
[[package]]
|
||||
name = "futures-timer"
|
||||
version = "3.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24"
|
||||
|
||||
[[package]]
|
||||
name = "futures-util"
|
||||
version = "0.3.32"
|
||||
@@ -2621,7 +2477,7 @@ dependencies = [
|
||||
"futures-core",
|
||||
"futures-sink",
|
||||
"http",
|
||||
"indexmap 2.13.0",
|
||||
"indexmap",
|
||||
"slab",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
@@ -2639,12 +2495,6 @@ dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.12.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.14.5"
|
||||
@@ -2715,12 +2565,6 @@ dependencies = [
|
||||
"http",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.5.0"
|
||||
@@ -2788,15 +2632,6 @@ dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "home"
|
||||
version = "0.5.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "html5ever"
|
||||
version = "0.36.1"
|
||||
@@ -2887,21 +2722,6 @@ dependencies = [
|
||||
"want",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper-named-pipe"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73b7d8abf35697b81a825e386fc151e0d503e8cb5fcb93cc8669c376dfd6f278"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper-rustls"
|
||||
version = "0.27.7"
|
||||
@@ -2960,21 +2780,6 @@ dependencies = [
|
||||
"windows-registry",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyperlocal"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "986c5ce3b994526b3cd75578e62554abd09f0899d6206de48b3e96ab34ccc8c7"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyperloglogplus"
|
||||
version = "0.4.1"
|
||||
@@ -3122,17 +2927,6 @@ dependencies = [
|
||||
"icu_properties",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "1.9.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
"hashbrown 0.12.3",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.13.0"
|
||||
@@ -3181,7 +2975,7 @@ dependencies = [
|
||||
"socket2 0.5.10",
|
||||
"widestring",
|
||||
"windows-sys 0.48.0",
|
||||
"winreg 0.50.0",
|
||||
"winreg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3394,12 +3188,6 @@ dependencies = [
|
||||
"vcpkg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.4.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.12.1"
|
||||
@@ -3652,7 +3440,7 @@ version = "0.6.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ad38eb12aea514a0466ea40a80fd8cc83637065948eb4a426e4aa46261175227"
|
||||
dependencies = [
|
||||
"rustix 1.1.4",
|
||||
"rustix",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4301,7 +4089,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3672b37090dbd86368a4145bc067582552b29c27377cad4e0a306c97f9bd7772"
|
||||
dependencies = [
|
||||
"fixedbitset",
|
||||
"indexmap 2.13.0",
|
||||
"indexmap",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4884,7 +4672,7 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
"rand 0.10.0",
|
||||
"rmcp-macros",
|
||||
"schemars 1.2.1",
|
||||
"schemars",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sse-stream",
|
||||
@@ -4957,19 +4745,6 @@ dependencies = [
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "0.38.44"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.4.15",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.4"
|
||||
@@ -4979,7 +4754,7 @@ dependencies = [
|
||||
"bitflags",
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.12.1",
|
||||
"linux-raw-sys",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
@@ -5061,18 +4836,6 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "schemars"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f"
|
||||
dependencies = [
|
||||
"dyn-clone",
|
||||
"ref-cast",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "schemars"
|
||||
version = "1.2.1"
|
||||
@@ -5255,7 +5018,7 @@ version = "1.0.149"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
|
||||
dependencies = [
|
||||
"indexmap 2.13.0",
|
||||
"indexmap",
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
@@ -5323,17 +5086,8 @@ version = "3.17.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "381b283ce7bc6b476d903296fb59d0d36633652b633b27f64db4fb46dcbfc3b9"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"chrono",
|
||||
"hex",
|
||||
"indexmap 1.9.3",
|
||||
"indexmap 2.13.0",
|
||||
"schemars 0.9.0",
|
||||
"schemars 1.2.1",
|
||||
"serde_core",
|
||||
"serde_json",
|
||||
"serde_with_macros",
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5509,7 +5263,7 @@ version = "0.8.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c1c97747dbf44bb1ca44a561ece23508e99cb592e862f22222dcf42f51d1e451"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
@@ -5877,7 +5631,7 @@ dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.4.1",
|
||||
"once_cell",
|
||||
"rustix 1.1.4",
|
||||
"rustix",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
@@ -6172,7 +5926,7 @@ version = "0.22.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
|
||||
dependencies = [
|
||||
"indexmap 2.13.0",
|
||||
"indexmap",
|
||||
"serde",
|
||||
"serde_spanned",
|
||||
"toml_datetime 0.6.11",
|
||||
@@ -6186,7 +5940,7 @@ version = "0.23.10+spec-1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "84c8b9f757e028cee9fa244aea147aab2a9ec09d5325a9b01e0a49730c2b5269"
|
||||
dependencies = [
|
||||
"indexmap 2.13.0",
|
||||
"indexmap",
|
||||
"toml_datetime 0.7.5+spec-1.1.0",
|
||||
"toml_parser",
|
||||
"winnow",
|
||||
@@ -6505,24 +6259,6 @@ version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
||||
|
||||
[[package]]
|
||||
name = "tungstenite"
|
||||
version = "0.23.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e2e2ce1e47ed2994fd43b04c8f618008d4cabdd5ee34027cf14f9d918edd9c8"
|
||||
dependencies = [
|
||||
"byteorder",
|
||||
"bytes",
|
||||
"data-encoding",
|
||||
"http",
|
||||
"httparse",
|
||||
"log",
|
||||
"rand 0.8.5",
|
||||
"sha1",
|
||||
"thiserror 1.0.69",
|
||||
"utf-8",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tungstenite"
|
||||
version = "0.26.2"
|
||||
@@ -6895,7 +6631,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"indexmap 2.13.0",
|
||||
"indexmap",
|
||||
"wasm-encoder",
|
||||
"wasmparser",
|
||||
]
|
||||
@@ -6921,7 +6657,7 @@ checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"hashbrown 0.15.5",
|
||||
"indexmap 2.13.0",
|
||||
"indexmap",
|
||||
"semver",
|
||||
]
|
||||
|
||||
@@ -6995,18 +6731,6 @@ dependencies = [
|
||||
"walkdir",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "which"
|
||||
version = "6.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4ee928febd44d98f2f459a4a79bd4d928591333a494a10a868418ac1b39cf1f"
|
||||
dependencies = [
|
||||
"either",
|
||||
"home",
|
||||
"rustix 0.38.44",
|
||||
"winsafe",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "widestring"
|
||||
version = "1.2.1"
|
||||
@@ -7430,22 +7154,6 @@ dependencies = [
|
||||
"windows-sys 0.48.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winreg"
|
||||
version = "0.52.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a277a57398d4bfa075df44f501a17cfdf8542d224f0d36095a2adc7aee4ef0a5"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"windows-sys 0.48.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winsafe"
|
||||
version = "0.0.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.51.0"
|
||||
@@ -7462,7 +7170,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"heck 0.5.0",
|
||||
"heck",
|
||||
"wit-parser",
|
||||
]
|
||||
|
||||
@@ -7473,8 +7181,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"heck 0.5.0",
|
||||
"indexmap 2.13.0",
|
||||
"heck",
|
||||
"indexmap",
|
||||
"prettyplease",
|
||||
"syn",
|
||||
"wasm-metadata",
|
||||
@@ -7505,7 +7213,7 @@ checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bitflags",
|
||||
"indexmap 2.13.0",
|
||||
"indexmap",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
@@ -7524,7 +7232,7 @@ checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"id-arena",
|
||||
"indexmap 2.13.0",
|
||||
"indexmap",
|
||||
"log",
|
||||
"semver",
|
||||
"serde",
|
||||
@@ -7556,7 +7264,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rustix 1.1.4",
|
||||
"rustix",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7718,7 +7426,7 @@ dependencies = [
|
||||
"flate2",
|
||||
"getrandom 0.3.4",
|
||||
"hmac",
|
||||
"indexmap 2.13.0",
|
||||
"indexmap",
|
||||
"lzma-rs",
|
||||
"memchr",
|
||||
"pbkdf2",
|
||||
|
||||
+19
-2
@@ -16,6 +16,10 @@ ARG RUFF_VERSION=0.16.8
|
||||
# mobsfscan pins an older semgrep; it is installed without its dependencies so
|
||||
# it runs on the semgrep above, and its other dependencies are pinned here.
|
||||
ARG MOBSFSCAN_VERSION=1.0.1
|
||||
# Yocto recipe lint (BSD-2-Clause): only its security rules run.
|
||||
ARG OELINT_ADV_VERSION=9.11.2
|
||||
# The recipe inventory reads the recipes with the same oelint-parser.
|
||||
ARG OELINT_PARSER_VERSION=8.13.2
|
||||
# DevSkim (MIT) is published as a .NET tool on nuget.org, not as a release
|
||||
# binary: the package is pinned by checksum and run on the .NET runtime (MIT).
|
||||
ARG DEVSKIM_VERSION=1.0.100
|
||||
@@ -63,6 +67,8 @@ ARG SBOMQS_SHA256
|
||||
ARG SEMGREP_VERSION
|
||||
ARG RUFF_VERSION
|
||||
ARG MOBSFSCAN_VERSION
|
||||
ARG OELINT_ADV_VERSION
|
||||
ARG OELINT_PARSER_VERSION
|
||||
ARG DEVSKIM_VERSION
|
||||
ARG DEVSKIM_SHA256
|
||||
ARG DOTNET_RUNTIME_VERSION
|
||||
@@ -117,6 +123,16 @@ RUN pip3 install --break-system-packages --no-cache-dir --no-deps \
|
||||
"tabulate==0.10.0" "xmltodict==1.0.4"
|
||||
COPY docker/pruefwerk_mobsfscan.py /opt/pruefwerk/pruefwerk_mobsfscan.py
|
||||
|
||||
# Yocto recipe lint and recipe inventory; see
|
||||
# compliance-agent/src/pipeline/recipe_lint/oelint.rs and yocto_inventory.rs.
|
||||
# Its dependencies are pinned with it (oelint-parser reads the recipes;
|
||||
# deprecated's wrapt is the 1.x semgrep's OpenTelemetry already installed).
|
||||
RUN pip3 install --break-system-packages --no-cache-dir \
|
||||
"oelint-adv==${OELINT_ADV_VERSION}" "oelint-parser==${OELINT_PARSER_VERSION}" "oelint-data==1.5.23" \
|
||||
"anytree==2.13.0" "argcomplete==3.7.2" "urllib3==2.8.0" "regex==2026.9.29" \
|
||||
"deprecated==1.3.1"
|
||||
COPY docker/pruefwerk_yocto_recipes.py /opt/pruefwerk/pruefwerk_yocto_recipes.py
|
||||
|
||||
# .NET SAST without a build (#494): DevSkim on C#, VB.NET and .config files.
|
||||
# The .NET runtime only (no SDK), with invariant globalisation so it needs no
|
||||
# ICU; of DevSkim's bundled native libraries only the linux-x64 ones are kept.
|
||||
@@ -139,10 +155,11 @@ RUN curl -sSfL -o /tmp/dotnet.tar.gz \
|
||||
COPY --chmod=0755 docker/devskim.sh /usr/local/bin/devskim
|
||||
|
||||
RUN mkdir -p /opt/pruefwerk \
|
||||
&& printf '{"rust":"%s","cargo-audit":"%s","syft":"%s","betterleaks":"%s","semgrep":"%s","ruff":"%s","cppcheck":"%s","mobsfscan":"%s","sbomqs":"%s","devskim":"%s","dotnet-runtime":"%s"}\n' \
|
||||
&& printf '{"rust":"%s","cargo-audit":"%s","syft":"%s","betterleaks":"%s","semgrep":"%s","ruff":"%s","cppcheck":"%s","mobsfscan":"%s","oelint-adv":"%s","oelint-parser":"%s","sbomqs":"%s","devskim":"%s","dotnet-runtime":"%s"}\n' \
|
||||
"${RUST_VERSION}" "${CARGO_AUDIT_VERSION}" "${SYFT_VERSION}" "${BETTERLEAKS_VERSION}" \
|
||||
"${SEMGREP_VERSION}" "${RUFF_VERSION}" "$(cppcheck --version | cut -d' ' -f2)" \
|
||||
"${MOBSFSCAN_VERSION}" "${SBOMQS_VERSION}" "${DEVSKIM_VERSION}" "${DOTNET_RUNTIME_VERSION}" \
|
||||
"${MOBSFSCAN_VERSION}" "${OELINT_ADV_VERSION}" "${OELINT_PARSER_VERSION}" "${SBOMQS_VERSION}" "${DEVSKIM_VERSION}" \
|
||||
"${DOTNET_RUNTIME_VERSION}" \
|
||||
> /opt/pruefwerk/tool-versions.json
|
||||
|
||||
# The agent runs unprivileged. It writes only to its home (tool caches), the
|
||||
|
||||
@@ -55,15 +55,15 @@ walkdir = "2"
|
||||
toml = "0.8"
|
||||
# Read-only XML tree parsing for PLCopen project files (POU extraction).
|
||||
roxmltree = "0.20"
|
||||
# kas project files (Yocto layer pins); already in the tree through firmwerk-core.
|
||||
yaml-rust2 = { version = "0.13", default-features = false }
|
||||
base64 = "0.22"
|
||||
urlencoding = "2"
|
||||
futures-util = "0.3"
|
||||
jsonwebtoken = "9"
|
||||
zip = { 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 }
|
||||
tokio-stream = { workspace = true }
|
||||
rand = { workspace = true }
|
||||
|
||||
@@ -146,7 +146,8 @@ impl ComplianceAgent {
|
||||
/// 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
|
||||
/// or it is dropped if a follow-up is already pending. A scheduled scan
|
||||
/// first waits a random [`crate::scan_gate::start_delay`]. Every trigger
|
||||
/// (click, webhook, scheduler, demo seed) comes through here.
|
||||
///
|
||||
/// # Errors
|
||||
@@ -158,6 +159,17 @@ impl ComplianceAgent {
|
||||
target_id: &str,
|
||||
trigger: compliance_core::models::ScanTrigger,
|
||||
) -> Result<(), crate::error::AgentError> {
|
||||
// Scheduled scans spread out before they take a slot or the target.
|
||||
let delay = crate::scan_gate::start_delay(&trigger);
|
||||
if !delay.is_zero() {
|
||||
tracing::debug!(
|
||||
tenant_id,
|
||||
target_id,
|
||||
delay_ms = delay.as_millis(),
|
||||
"scheduled scan waits"
|
||||
);
|
||||
tokio::time::sleep(delay).await;
|
||||
}
|
||||
let key = ScanGate::key(tenant_id, target_id);
|
||||
match self.scan_gate.admit(&key, trigger.clone()) {
|
||||
Admission::Run => {}
|
||||
|
||||
@@ -226,6 +226,10 @@ pub struct SbomFilter {
|
||||
pub has_vulns: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub license: Option<String>,
|
||||
/// Only components an image is known to contain (`true`), or only the
|
||||
/// others (`false`); see [`compliance_core::models::InImage`].
|
||||
#[serde(default)]
|
||||
pub in_image: Option<bool>,
|
||||
#[serde(default = "default_page", deserialize_with = "de_page")]
|
||||
pub page: u64,
|
||||
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
||||
|
||||
@@ -95,6 +95,7 @@ fn state_counts(controls: &[crate::evidence::compliance::ControlStatus]) -> serd
|
||||
"not_satisfied": count(ControlState::NotSatisfied),
|
||||
"no_violation_found": count(ControlState::NoViolationFound),
|
||||
"not_assessed": count(ControlState::NotAssessed),
|
||||
"partial": count(ControlState::Partial),
|
||||
"not_code_checkable": count(ControlState::NotCodeCheckable),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -99,7 +99,12 @@ pub async fn stats_overview(
|
||||
.limit(10)
|
||||
.await
|
||||
{
|
||||
Ok(cursor) => collect_cursor_async(cursor).await,
|
||||
Ok(cursor) => {
|
||||
let mut runs: Vec<ScanRun> = collect_cursor_async(cursor).await;
|
||||
// Runs recorded before notes existed list them among their skips.
|
||||
runs.iter_mut().for_each(ScanRun::split_notes);
|
||||
runs
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to fetch recent scans: {e}");
|
||||
Vec::new()
|
||||
|
||||
@@ -13,7 +13,7 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
use compliance_core::models::{
|
||||
ArtifactKind, ComplianceProfile, Credentials, DetectedFact, Finding, OnboardedTarget,
|
||||
PlcFormat, ScanRun, TargetType,
|
||||
PlcFormat, ScanRun, TargetType, WebhookDelivery, DELIVERIES_SHOWN,
|
||||
};
|
||||
use compliance_core::scan_matrix::{applicable_scans, supports_pentest};
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
@@ -96,6 +96,7 @@ pub async fn list_targets(
|
||||
let targets = match db
|
||||
.onboarded_targets()
|
||||
.find(query)
|
||||
.sort(TargetFilter::sort())
|
||||
.skip(skip)
|
||||
.limit(params.limit)
|
||||
.await
|
||||
@@ -169,6 +170,13 @@ impl TargetFilter {
|
||||
None => doc! {},
|
||||
}
|
||||
}
|
||||
|
||||
/// The list's order: oldest first by id (creation order, what the list
|
||||
/// showed before it paged). Ids are unique, so the order is total and a
|
||||
/// page never repeats or skips a target.
|
||||
pub fn sort() -> mongodb::bson::Document {
|
||||
doc! { "_id": 1 }
|
||||
}
|
||||
}
|
||||
|
||||
/// The newest scan run of each target in `target_ids`, in one query.
|
||||
@@ -192,7 +200,9 @@ pub(crate) async fn latest_scan_runs(
|
||||
cursor
|
||||
.filter_map(|row| async move {
|
||||
let run = row.ok()?.get_document("run").ok()?.clone();
|
||||
let run: ScanRun = mongodb::bson::from_document(run).ok()?;
|
||||
let mut run: ScanRun = mongodb::bson::from_document(run).ok()?;
|
||||
// Runs recorded before notes existed list them among their skips.
|
||||
run.split_notes();
|
||||
Some((run.repo_id.clone(), run))
|
||||
})
|
||||
.collect()
|
||||
@@ -300,6 +310,42 @@ pub async fn get_target(
|
||||
}))
|
||||
}
|
||||
|
||||
/// GET /api/v1/targets/{id}/webhook-deliveries — the target's newest
|
||||
/// webhook deliveries, refused and failed ones included; for a managed
|
||||
/// target also those of its repository from before the target existed.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn list_webhook_deliveries(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<Json<ApiResponse<Vec<WebhookDelivery>>>, StatusCode> {
|
||||
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 filter = crate::webhooks::deliveries::target_filter(&id, target.source_repo.as_ref());
|
||||
let cursor = db
|
||||
.webhook_deliveries()
|
||||
.find(filter)
|
||||
.sort(doc! { "received_at": -1 })
|
||||
.limit(DELIVERIES_SHOWN)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::warn!("Failed to list webhook deliveries: {e}");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
let deliveries = collect_cursor_async(cursor).await;
|
||||
Ok(Json(ApiResponse {
|
||||
total: Some(deliveries.len() as u64),
|
||||
data: deliveries,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// PATCH /api/v1/targets/{id} — update mutable fields.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn update_target(
|
||||
@@ -1018,4 +1064,17 @@ mod filter_tests {
|
||||
};
|
||||
assert_eq!(blank.to_query(), doc! {});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_list_pages_in_a_total_order_with_the_filter_beside_it() {
|
||||
// `?project=p1&page=2&limit=1` feeds both extractors of the handler.
|
||||
let uri: axum::http::Uri = "/api/v1/targets?project=p1&page=2&limit=1"
|
||||
.parse()
|
||||
.expect("uri");
|
||||
let Query(params) = Query::<PaginationParams>::try_from_uri(&uri).expect("params");
|
||||
let Query(filter) = Query::<TargetFilter>::try_from_uri(&uri).expect("filter");
|
||||
assert_eq!((params.page, params.limit, params.skip()), (2, 1, 1));
|
||||
assert_eq!(filter.to_query(), doc! { "project_ids": "p1" });
|
||||
assert_eq!(TargetFilter::sort(), doc! { "_id": 1 });
|
||||
}
|
||||
}
|
||||
@@ -16,25 +16,6 @@ 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",
|
||||
"GPL-2.0-or-later",
|
||||
"GPL-3.0",
|
||||
"GPL-3.0-only",
|
||||
"GPL-3.0-or-later",
|
||||
"AGPL-3.0",
|
||||
"AGPL-3.0-only",
|
||||
"AGPL-3.0-or-later",
|
||||
"LGPL-2.1",
|
||||
"LGPL-2.1-only",
|
||||
"LGPL-2.1-or-later",
|
||||
"LGPL-3.0",
|
||||
"LGPL-3.0-only",
|
||||
"LGPL-3.0-or-later",
|
||||
"MPL-2.0",
|
||||
];
|
||||
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn sbom_filters(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -103,6 +84,9 @@ pub async fn list_sbom(
|
||||
if let Some(license) = &filter.license {
|
||||
query.insert("license", license);
|
||||
}
|
||||
if let Some(in_image) = filter.in_image {
|
||||
query.insert("in_image", doc! { "$exists": in_image });
|
||||
}
|
||||
|
||||
let skip = filter.skip();
|
||||
let total = db
|
||||
@@ -114,7 +98,7 @@ pub async fn list_sbom(
|
||||
let entries = match db
|
||||
.sbom_entries()
|
||||
.find(query)
|
||||
.sort(doc! { "name": 1 })
|
||||
.sort(list_order())
|
||||
.skip(skip)
|
||||
.limit(filter.limit)
|
||||
.await
|
||||
@@ -133,6 +117,12 @@ pub async fn list_sbom(
|
||||
}))
|
||||
}
|
||||
|
||||
/// The order of the SBOM list: the components an image contains first (a
|
||||
/// missing `in_image` sorts as null, below any value), then by name.
|
||||
fn list_order() -> mongodb::bson::Document {
|
||||
doc! { "in_image.basis": -1, "name": 1 }
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn export_sbom(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -278,11 +268,8 @@ pub async fn license_summary(
|
||||
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())),
|
||||
is_copyleft: compliance_core::spdx_license::is_copyleft(&row.license),
|
||||
license: row.license,
|
||||
count: u64::try_from(row.count).unwrap_or(0),
|
||||
packages: row.packages,
|
||||
|
||||
@@ -51,7 +51,12 @@ pub async fn list_scan_runs(
|
||||
.limit(params.limit)
|
||||
.await
|
||||
{
|
||||
Ok(cursor) => collect_cursor_async(cursor).await,
|
||||
Ok(cursor) => {
|
||||
let mut runs: Vec<ScanRun> = collect_cursor_async(cursor).await;
|
||||
// Runs recorded before notes existed list them among their skips.
|
||||
runs.iter_mut().for_each(ScanRun::split_notes);
|
||||
runs
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to fetch scan runs: {e}");
|
||||
Vec::new()
|
||||
|
||||
@@ -55,6 +55,10 @@ pub fn build_router() -> Router {
|
||||
"/api/v1/targets/{id}/artifacts",
|
||||
post(handlers::onboarding::add_artifact),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/webhook-deliveries",
|
||||
get(handlers::onboarding::list_webhook_deliveries),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/artifacts/upload",
|
||||
// The one route that takes large bodies — and it streams them to
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Heuristic target-type classification from artifact kinds and source markers.
|
||||
//!
|
||||
//! Complements the Firmwerk firmware detector: this handles web / backend /
|
||||
//! mobile / desktop / PLC by sniffing manifest files and file extensions in the
|
||||
//! mobile / desktop / PLC / Yocto 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).
|
||||
|
||||
@@ -40,6 +40,7 @@ const LOCATED_FILES: &[&str] = &[
|
||||
"androidmanifest.xml",
|
||||
"build.gradle",
|
||||
"build.gradle.kts",
|
||||
"layer.conf",
|
||||
"projectversion.txt",
|
||||
"pubspec.yaml",
|
||||
"web.config",
|
||||
@@ -280,6 +281,74 @@ fn package_json_is_frontend(root: &Path) -> bool {
|
||||
.any(|f| c.contains(f))
|
||||
}
|
||||
|
||||
/// The markers of a Yocto / OpenEmbedded layer tree.
|
||||
#[derive(Default)]
|
||||
struct YoctoShape {
|
||||
/// The layers: directories holding a `conf/layer.conf` (`.` for the root).
|
||||
layers: Vec<String>,
|
||||
/// BitBake recipes, appends or includes (`.bb`, `.bbappend`, `.inc`
|
||||
/// beside a `recipes-*` directory).
|
||||
recipes: bool,
|
||||
/// A kas project file (`kas*.yml`, or YAML beside a `kas/` directory).
|
||||
kas: bool,
|
||||
/// A build directory's `bblayers.conf` / `local.conf`, or poky's
|
||||
/// `oe-init-build-env`.
|
||||
build_setup: bool,
|
||||
/// `meta-*` layer directories or distro configurations: common enough
|
||||
/// elsewhere (`META-INF`) to only back up another signal.
|
||||
corroborated: bool,
|
||||
}
|
||||
|
||||
impl YoctoShape {
|
||||
/// The confidence that the tree is a Yocto layer tree: a layer with its
|
||||
/// recipes is as clear as an Android manifest; a kas file or a build
|
||||
/// directory's configuration alone is weaker. `None` without any signal.
|
||||
fn confidence(&self) -> Option<f32> {
|
||||
let layer = !self.layers.is_empty();
|
||||
let base = if layer && self.recipes {
|
||||
return Some(0.8);
|
||||
} else if layer || self.recipes {
|
||||
0.65
|
||||
} else if self.kas {
|
||||
0.6
|
||||
} else if self.build_setup {
|
||||
0.5
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
Some(if self.corroborated { base + 0.05 } else { base })
|
||||
}
|
||||
}
|
||||
|
||||
/// What of a Yocto layer tree the markers show.
|
||||
fn yocto_shape(m: &Markers) -> YoctoShape {
|
||||
const LAYER_CONF: &str = "conf/layer.conf";
|
||||
let is_yaml = |name: &str| name.ends_with(".yml") || name.ends_with(".yaml");
|
||||
YoctoShape {
|
||||
layers: m
|
||||
.located_ending(LAYER_CONF)
|
||||
.filter_map(|p| p.get(..p.len().saturating_sub(LAYER_CONF.len())))
|
||||
.map(|dir| match dir.trim_end_matches('/') {
|
||||
"" => ".".to_string(),
|
||||
dir => dir.to_string(),
|
||||
})
|
||||
.collect(),
|
||||
recipes: m.has_ext("bb")
|
||||
|| m.has_ext("bbappend")
|
||||
|| (m.has_ext("inc") && m.dirs.iter().any(|d| d.starts_with("recipes-"))),
|
||||
kas: m.files.iter().any(|f| f.starts_with("kas") && is_yaml(f))
|
||||
|| (m.dirs.contains("kas") && (m.has_ext("yml") || m.has_ext("yaml"))),
|
||||
build_setup: ["bblayers.conf", "local.conf", "oe-init-build-env"]
|
||||
.iter()
|
||||
.any(|f| m.has_file(f)),
|
||||
corroborated: m
|
||||
.dirs
|
||||
.iter()
|
||||
.any(|d| d.starts_with("meta-") && d != "meta-inf")
|
||||
|| (m.dirs.contains("distro") && m.has_ext("conf")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The heuristic classifier: artifact-kind priors + source-tree markers.
|
||||
pub struct HeuristicClassifier;
|
||||
|
||||
@@ -519,6 +588,28 @@ impl HeuristicClassifier {
|
||||
));
|
||||
}
|
||||
}
|
||||
// Yocto / OpenEmbedded. The C sources a recipe carries in
|
||||
// `files/` do not make it firmware: a layer with its recipes
|
||||
// outranks Firmwerk's guess from loose sources (0.3).
|
||||
let yocto = yocto_shape(&m);
|
||||
if let Some(confidence) = yocto.confidence() {
|
||||
let mut facts = facts_lang("bitbake");
|
||||
facts.push(DetectedFact::new("build_system", "bitbake", "heuristic"));
|
||||
// Each layer, for the stages that read the recipes.
|
||||
facts.extend(
|
||||
yocto
|
||||
.layers
|
||||
.iter()
|
||||
.take(10)
|
||||
.map(|layer| DetectedFact::new("yocto_layer", layer, "heuristic")),
|
||||
);
|
||||
out.push(verdict(
|
||||
TargetType::EmbeddedLinuxYocto,
|
||||
confidence,
|
||||
"Yocto layer / BitBake recipes / kas project",
|
||||
facts,
|
||||
));
|
||||
}
|
||||
// Container-only.
|
||||
if m.has_file("dockerfile") && out.is_empty() {
|
||||
out.push(verdict(
|
||||
@@ -902,6 +993,114 @@ mod tests {
|
||||
assert!(!v.iter().any(|x| x.target_type == TargetType::AndroidApp));
|
||||
}
|
||||
|
||||
/// Assert the Yocto verdict's confidence (`None`: no Yocto verdict).
|
||||
fn assert_yocto(verdicts: &[ClassifierVerdict], want: Option<f32>) {
|
||||
let got = verdicts
|
||||
.iter()
|
||||
.find(|v| v.target_type == TargetType::EmbeddedLinuxYocto)
|
||||
.map(|v| v.confidence);
|
||||
match (got, want) {
|
||||
(Some(got), Some(want)) => assert!((got - want).abs() < 1e-6, "{got} != {want}"),
|
||||
_ => assert_eq!(got.is_some(), want.is_some(), "{got:?} != {want:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_layer_with_recipes_is_confidently_yocto_and_names_its_layers() {
|
||||
let v = classify_tree(|root| {
|
||||
write_all(
|
||||
root,
|
||||
&[
|
||||
(
|
||||
"meta-pump/conf/layer.conf",
|
||||
"BBFILE_COLLECTIONS += \"pump\"",
|
||||
),
|
||||
(
|
||||
"meta-pump/recipes-app/pump/pump_1.0.bb",
|
||||
"LICENSE = \"CLOSED\"",
|
||||
),
|
||||
(
|
||||
"meta-pump/recipes-app/pump/files/pump.c",
|
||||
"int main(void){}",
|
||||
),
|
||||
(
|
||||
"meta-pump/recipes-app/pump/files/Makefile",
|
||||
"all:\n\tcc pump.c",
|
||||
),
|
||||
("meta-pump/recipes-core/images/pump-image.bbappend", ""),
|
||||
("conf/layer.conf", ""),
|
||||
("recipes-x/x/x_1.0.bb", ""),
|
||||
],
|
||||
);
|
||||
})
|
||||
.await;
|
||||
assert_eq!(top(&v), TargetType::EmbeddedLinuxYocto);
|
||||
assert_yocto(&v, Some(0.8));
|
||||
let facts = &v
|
||||
.iter()
|
||||
.find(|x| x.target_type == TargetType::EmbeddedLinuxYocto)
|
||||
.expect("yocto verdict")
|
||||
.facts;
|
||||
let value = |key: &str| -> Vec<&str> {
|
||||
facts
|
||||
.iter()
|
||||
.filter(|f| f.key == key)
|
||||
.map(|f| f.value.as_str())
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(value("build_system"), ["bitbake"]);
|
||||
assert_eq!(value("yocto_layer"), [".", "meta-pump"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn weaker_yocto_signals_give_a_lower_confidence() {
|
||||
let kas = classify_tree(|root| {
|
||||
write_all(root, &[("kas-pump.yml", "header:\n version: 14\n")]);
|
||||
})
|
||||
.await;
|
||||
assert_yocto(&kas, Some(0.6));
|
||||
|
||||
let kas_dir = classify_tree(|root| {
|
||||
write_all(root, &[("kas/pump.yaml", "header:\n version: 14\n")]);
|
||||
})
|
||||
.await;
|
||||
assert_yocto(&kas_dir, Some(0.6));
|
||||
|
||||
// A poky checkout: the build environment script and meta-* layers.
|
||||
let poky = classify_tree(|root| {
|
||||
write_all(
|
||||
root,
|
||||
&[("oe-init-build-env", "#!/bin/sh"), ("meta-poky/README", "")],
|
||||
);
|
||||
})
|
||||
.await;
|
||||
assert_yocto(&poky, Some(0.55));
|
||||
|
||||
let recipes_only = classify_tree(|root| {
|
||||
write_all(root, &[("recipes-app/pump/pump_1.0.bb", "")]);
|
||||
})
|
||||
.await;
|
||||
assert_yocto(&recipes_only, Some(0.65));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn meta_inf_and_loose_conf_files_are_not_yocto() {
|
||||
let v = classify_tree(|root| {
|
||||
write_all(
|
||||
root,
|
||||
&[
|
||||
("app/src/main/resources/META-INF/MANIFEST.MF", ""),
|
||||
("pom.xml", "<project/>"),
|
||||
("etc/distro/default.conf", ""),
|
||||
("lib/defs.inc", ""),
|
||||
],
|
||||
);
|
||||
})
|
||||
.await;
|
||||
assert_yocto(&v, None);
|
||||
assert_eq!(top(&v), TargetType::BackendService);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn structured_text_is_plc() {
|
||||
let v = classify_tree(|root| {
|
||||
|
||||
@@ -260,6 +260,108 @@ mod tests {
|
||||
assert_eq!(target.detected_type(&c), Some(TargetType::PlcSps));
|
||||
}
|
||||
|
||||
/// What Firmwerk reports for loose C sources, or for a Makefile.
|
||||
fn firmwerk_found(provider: &str, confidence: &str) -> MockFirmwareDetector {
|
||||
MockFirmwareDetector {
|
||||
detection: Some(FirmwareDetection {
|
||||
provider: provider.to_string(),
|
||||
confidence: confidence.to_string(),
|
||||
build_system: provider.to_string(),
|
||||
framework: Some("bare-metal".to_string()),
|
||||
target: FirmwareTarget::default(),
|
||||
gaps: vec![],
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Classify the tree `files` (relative path, content) as one source
|
||||
/// archive, with `detector` standing in for Firmwerk.
|
||||
async fn classify_files(
|
||||
files: &[(&str, &str)],
|
||||
detector: &MockFirmwareDetector,
|
||||
) -> Classification {
|
||||
let scratch = Scratch::new();
|
||||
for (rel, content) in files {
|
||||
let path = scratch.0.join(rel);
|
||||
fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
|
||||
fs::write(path, content).expect("write");
|
||||
}
|
||||
let artifact = Artifact::source_archive("upload.zip");
|
||||
let mut wp = HashMap::new();
|
||||
wp.insert(artifact.id.clone(), scratch.0.clone());
|
||||
let mut target = OnboardedTarget::new("t".to_string(), TargetType::BackendService);
|
||||
target.artifacts.push(artifact);
|
||||
classify_target(&target, &wp, detector)
|
||||
.await
|
||||
.expect("classify")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_nightly_yocto_fixture_is_typed_yocto() {
|
||||
let fixture =
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../fixtures/nightly/firmware/yocto-layer");
|
||||
let artifact = Artifact::source_archive("yocto-layer.zip");
|
||||
let mut wp = HashMap::new();
|
||||
wp.insert(artifact.id.clone(), fixture);
|
||||
let mut target = OnboardedTarget::new("y".to_string(), TargetType::BackendService);
|
||||
target.artifacts.push(artifact);
|
||||
let c = classify_target(&target, &wp, &no_firmware())
|
||||
.await
|
||||
.expect("classify");
|
||||
assert_eq!(c.suggested, TargetType::EmbeddedLinuxYocto);
|
||||
assert!(c
|
||||
.facts
|
||||
.iter()
|
||||
.any(|f| f.key == "build_system" && f.value == "bitbake"));
|
||||
assert!(c
|
||||
.facts
|
||||
.iter()
|
||||
.any(|f| f.key == "yocto_layer" && f.value == "."));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_plain_c_firmware_repo_stays_bare_metal() {
|
||||
let c = classify_files(
|
||||
&[
|
||||
("Makefile", "CC=arm-none-eabi-gcc\nCFLAGS=-mcpu=cortex-m4"),
|
||||
("Core/Src/main.c", "int main(void){}"),
|
||||
// A config file in `conf/` is not a layer.
|
||||
("conf/board.conf", "BOARD=nucleo"),
|
||||
],
|
||||
&firmwerk_found("make", "medium"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(c.suggested, TargetType::FirmwareBareMetal);
|
||||
assert!(!c
|
||||
.candidates
|
||||
.iter()
|
||||
.any(|x| x.target_type == TargetType::EmbeddedLinuxYocto));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_layer_shipping_c_sources_is_yocto_not_bare_metal() {
|
||||
// Firmwerk's source archaeology fires on the recipe's C sources.
|
||||
let c = classify_files(
|
||||
&[
|
||||
("conf/layer.conf", "BBFILE_COLLECTIONS += \"pump\""),
|
||||
(
|
||||
"recipes-app/pump/pump_1.0.bb",
|
||||
"SRC_URI = \"file://pump.c\"",
|
||||
),
|
||||
("recipes-app/pump/files/pump.c", "int main(void){}"),
|
||||
("recipes-app/pump/files/pump.h", "#pragma once"),
|
||||
],
|
||||
&firmwerk_found("source-archaeology", "low"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(c.suggested, TargetType::EmbeddedLinuxYocto);
|
||||
// The firmware reading stays a lower candidate.
|
||||
assert!(c
|
||||
.candidates
|
||||
.iter()
|
||||
.any(|x| x.target_type == TargetType::FirmwareBareMetal));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn no_signal_falls_back_to_declared_type() {
|
||||
let scratch = Scratch::new();
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use compliance_core::config::{AppEnv, BreakpilotConfig, Features, PlcRuntimeConfig};
|
||||
use compliance_core::config::{
|
||||
AppEnv, BreakpilotConfig, Features, IssueAutoclose, IssueCatchup, PlcRuntimeConfig,
|
||||
};
|
||||
use compliance_core::AgentConfig;
|
||||
use secrecy::SecretString;
|
||||
|
||||
@@ -127,6 +129,24 @@ fn build_config(app_env: AppEnv) -> Result<AgentConfig, AgentError> {
|
||||
},
|
||||
features: Features::parse(&env_var_opt("PW_FEATURES").unwrap_or_default()),
|
||||
app_env,
|
||||
issue_catchup: load_issue_catchup(),
|
||||
issue_autoclose: load_issue_autoclose(),
|
||||
})
|
||||
}
|
||||
|
||||
/// `ISSUE_AUTOCLOSE`; an unknown value is logged and leaves closing off.
|
||||
fn load_issue_autoclose() -> IssueAutoclose {
|
||||
IssueAutoclose::parse(&env_var_opt("ISSUE_AUTOCLOSE").unwrap_or_default()).unwrap_or_else(|e| {
|
||||
tracing::warn!("{e}; CVE issues settled by VEX stay open");
|
||||
IssueAutoclose::Off
|
||||
})
|
||||
}
|
||||
|
||||
/// `ISSUE_CATCHUP`; an unknown value is logged and leaves the catch-up off.
|
||||
fn load_issue_catchup() -> IssueCatchup {
|
||||
IssueCatchup::parse(&env_var_opt("ISSUE_CATCHUP").unwrap_or_default()).unwrap_or_else(|e| {
|
||||
tracing::warn!("{e}; the issue catch-up stays off");
|
||||
IssueCatchup::Off
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use dashmap::DashMap;
|
||||
use futures_util::StreamExt;
|
||||
use mongodb::bson::doc;
|
||||
use mongodb::options::IndexOptions;
|
||||
use mongodb::{Client, Collection, IndexModel};
|
||||
@@ -25,6 +26,22 @@ const HASH_HEX_LEN: usize = 32;
|
||||
/// fits in the 63-byte cap: `prefix + "_" + 32 hex chars`.
|
||||
const MAX_PREFIX_LEN: usize = MAX_DB_NAME_LEN - 1 - HASH_HEX_LEN;
|
||||
|
||||
/// The collection of [`Database::webhook_deliveries`].
|
||||
const WEBHOOK_DELIVERIES: &str = "webhook_deliveries";
|
||||
|
||||
/// Deliveries kept per tenant: the target page shows the newest
|
||||
/// [`DELIVERIES_SHOWN`] of a target, so this keeps them for 50 busy targets.
|
||||
const WEBHOOK_DELIVERIES_MAX: u64 = 1_000;
|
||||
|
||||
/// The byte cap the capped collection needs as well; a delivery is well
|
||||
/// under 1 KiB, so the document cap is the one that bites.
|
||||
const WEBHOOK_DELIVERIES_BYTES: u64 = 2 * 1024 * 1024;
|
||||
|
||||
/// `create_collection` on a name that exists (Mongo error code 48).
|
||||
fn is_namespace_exists(e: &mongodb::error::Error) -> bool {
|
||||
matches!(&*e.kind, mongodb::error::ErrorKind::Command(c) if c.code == 48)
|
||||
}
|
||||
|
||||
/// Per-tenant Mongo connection broker (M7.2 isolation model).
|
||||
///
|
||||
/// Holds one [`Client`] and hands out [`Database`] handles physically
|
||||
@@ -552,10 +569,71 @@ impl Database {
|
||||
)
|
||||
.await?;
|
||||
|
||||
// webhook_deliveries: capped, then the target page's two lookups
|
||||
self.ensure_capped(
|
||||
WEBHOOK_DELIVERIES,
|
||||
WEBHOOK_DELIVERIES_BYTES,
|
||||
WEBHOOK_DELIVERIES_MAX,
|
||||
)
|
||||
.await?;
|
||||
self.webhook_deliveries()
|
||||
.create_index(
|
||||
IndexModel::builder()
|
||||
.keys(doc! { "target_id": 1, "received_at": -1 })
|
||||
.build(),
|
||||
)
|
||||
.await?;
|
||||
self.webhook_deliveries()
|
||||
.create_index(
|
||||
IndexModel::builder()
|
||||
.keys(doc! {
|
||||
"source_repo.base_url": 1,
|
||||
"source_repo.repo_id": 1,
|
||||
"received_at": -1,
|
||||
})
|
||||
.build(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
tracing::info!("Database indexes ensured");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Make `name` a capped collection of at most `bytes` and `max` documents,
|
||||
/// so Mongo drops the oldest itself. An existing plain collection (written
|
||||
/// before this ran) is converted; `convertToCapped` takes no document cap,
|
||||
/// so that one is bounded by size only.
|
||||
async fn ensure_capped(&self, name: &str, bytes: u64, max: u64) -> Result<(), AgentError> {
|
||||
let created = self
|
||||
.inner
|
||||
.create_collection(name)
|
||||
.capped(true)
|
||||
.size(bytes)
|
||||
.max(max)
|
||||
.await;
|
||||
match created {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) if is_namespace_exists(&e) => {}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
let mut specs = self
|
||||
.inner
|
||||
.list_collections()
|
||||
.filter(doc! { "name": name })
|
||||
.await?;
|
||||
let capped = match specs.next().await {
|
||||
Some(spec) => spec?.options.capped.unwrap_or(false),
|
||||
None => false,
|
||||
};
|
||||
if !capped {
|
||||
self.inner
|
||||
.run_command(doc! { "convertToCapped": name, "size": bytes as i64 })
|
||||
.await?;
|
||||
tracing::info!(collection = name, "converted to a capped collection");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn findings(&self) -> Collection<Finding> {
|
||||
self.inner.collection("findings")
|
||||
}
|
||||
@@ -661,6 +739,12 @@ impl Database {
|
||||
self.inner.collection("pentest_messages")
|
||||
}
|
||||
|
||||
/// The tenant's recent webhook deliveries: a capped collection (see
|
||||
/// [`Self::ensure_capped`]), newest per target shown on the target page.
|
||||
pub fn webhook_deliveries(&self) -> Collection<WebhookDelivery> {
|
||||
self.inner.collection(WEBHOOK_DELIVERIES)
|
||||
}
|
||||
|
||||
/// The Werkbank job queue (WB-02): declarative dynamic-execution jobs the
|
||||
/// control plane enqueues and runners lease.
|
||||
pub fn werkbank_jobs(&self) -> Collection<compliance_core::models::werkbank::JobRecord> {
|
||||
|
||||
@@ -21,6 +21,9 @@ pub enum ControlState {
|
||||
/// 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,
|
||||
/// Assessed on part of what the control covers only: a Yocto target's
|
||||
/// components come from its recipe inventory, not from the image's SBOM.
|
||||
Partial,
|
||||
/// A design property no code scan can decide (breakpilot-compliance).
|
||||
NotCodeCheckable,
|
||||
}
|
||||
@@ -48,6 +51,11 @@ pub enum NotAssessedReason {
|
||||
/// `manifests` declare could not be listed (no lockfile, or one no tool
|
||||
/// reads), so the SBOM is incomplete.
|
||||
DependenciesUnresolved { manifests: Vec<String> },
|
||||
/// The control is checked on the target's components, and they are the
|
||||
/// Yocto recipe inventory only, not the image's SBOM: every recipe in the
|
||||
/// layer tree, not what the image contains (the reason of
|
||||
/// [`ControlState::Partial`]).
|
||||
RecipeInventoryOnly,
|
||||
}
|
||||
|
||||
/// How far the target's SBOM speaks for its components.
|
||||
@@ -59,10 +67,18 @@ pub enum SbomCoverage {
|
||||
Empty,
|
||||
/// The dependencies these manifests declare could not be listed.
|
||||
Unresolved(Vec<String>),
|
||||
/// The components are a Yocto recipe inventory; no image SBOM exists.
|
||||
RecipeInventoryOnly,
|
||||
}
|
||||
|
||||
/// The tools that check a target's components rather than its code.
|
||||
const COMPONENT_TOOLS: [&str; 4] = ["syft", "osv", "dotnet-lifecycle", "build-lifecycle"];
|
||||
const COMPONENT_TOOLS: [&str; 5] = [
|
||||
"syft",
|
||||
"osv",
|
||||
"dotnet-lifecycle",
|
||||
"build-lifecycle",
|
||||
"yocto-release",
|
||||
];
|
||||
|
||||
/// The tool a skipped stage of a scan run stands for, when that stage is one
|
||||
/// a control's binding relies on.
|
||||
@@ -72,6 +88,7 @@ pub fn tool_of_stage(stage: &str) -> Option<&'static str> {
|
||||
"sast_c_cpp" => Some("cppcheck"),
|
||||
"sast_mobile" => Some("mobsfscan"),
|
||||
"sast_dotnet" => Some("devskim"),
|
||||
"recipe_lint" => Some("oelint-adv"),
|
||||
"cve_lookup" => Some("osv"),
|
||||
"sbom" => Some("syft"),
|
||||
_ => None,
|
||||
@@ -96,7 +113,8 @@ pub struct ControlStatus {
|
||||
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.
|
||||
/// Why a checkable control was not assessed, or assessed only in part;
|
||||
/// set only in those states.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub reason: Option<NotAssessedReason>,
|
||||
/// How severe a violation is, as the catalog rates it.
|
||||
@@ -163,7 +181,18 @@ pub fn control_statuses(
|
||||
let (state, reason) = if !against.is_empty() {
|
||||
(ControlState::NotSatisfied, None)
|
||||
} else {
|
||||
match (entry.status, scanned_languages) {
|
||||
// A control otherwise outside static scans is assessed where
|
||||
// one of its bindings checks the scanned code (cra-ai-2's
|
||||
// recipe lint on a Yocto layer tree).
|
||||
let status = match entry.status {
|
||||
Coverage::NotCodeCheckable
|
||||
if scanned_languages.is_some_and(|l| entry.checked_for(l)) =>
|
||||
{
|
||||
Coverage::Covered
|
||||
}
|
||||
status => status,
|
||||
};
|
||||
match (status, scanned_languages) {
|
||||
(Coverage::NotCodeCheckable, _) => (ControlState::NotCodeCheckable, None),
|
||||
(Coverage::NeedsTooling, _) => {
|
||||
(ControlState::NotAssessed, Some(NotAssessedReason::NoTool))
|
||||
@@ -200,6 +229,10 @@ pub fn control_statuses(
|
||||
ControlState::NotAssessed,
|
||||
Some(NotAssessedReason::NoComponents),
|
||||
),
|
||||
SbomCoverage::RecipeInventoryOnly => (
|
||||
ControlState::Partial,
|
||||
Some(NotAssessedReason::RecipeInventoryOnly),
|
||||
),
|
||||
SbomCoverage::Unresolved(manifests) => (
|
||||
ControlState::NotAssessed,
|
||||
Some(NotAssessedReason::DependenciesUnresolved {
|
||||
@@ -278,6 +311,34 @@ mod tests {
|
||||
status_of(statuses, control).state
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attack_surface_is_assessed_on_a_yocto_tree_only() {
|
||||
let map = ControlMap::cra().expect("map");
|
||||
let yocto = vec!["bitbake".to_string(), "c".to_string()];
|
||||
let none = SbomCoverage::Complete;
|
||||
let statuses = control_statuses(&map, &[], Some(&yocto), &[], &none);
|
||||
assert_eq!(
|
||||
state_of(&statuses, "cra-ai-2"),
|
||||
ControlState::NoViolationFound
|
||||
);
|
||||
// Elsewhere it stays outside static scans.
|
||||
for languages in [Some(python()), Some(c_only()), None] {
|
||||
let statuses = control_statuses(&map, &[], languages.as_deref(), &[], &none);
|
||||
assert_eq!(
|
||||
state_of(&statuses, "cra-ai-2"),
|
||||
ControlState::NotCodeCheckable
|
||||
);
|
||||
}
|
||||
// oelint-adv did not complete: not assessed.
|
||||
let statuses = control_statuses(&map, &[], Some(&yocto), &["oelint-adv"], &none);
|
||||
assert_eq!(state_of(&statuses, "cra-ai-2"), ControlState::NotAssessed);
|
||||
// A finding bound to it counts against it.
|
||||
let mut network = finding("cra-ai-2", FindingStatus::Open);
|
||||
network.scanner = "oelint-adv".into();
|
||||
let statuses = control_statuses(&map, &[network], Some(&yocto), &[], &none);
|
||||
assert_eq!(state_of(&statuses, "cra-ai-2"), ControlState::NotSatisfied);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_control_gets_exactly_one_state() {
|
||||
let map = ControlMap::cra().expect("map");
|
||||
@@ -411,6 +472,27 @@ mod tests {
|
||||
assert_eq!(state_of(&with, "cra-ai-23"), ControlState::NoViolationFound);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recipe_inventory_assesses_the_component_controls_only_in_part() {
|
||||
let map = ControlMap::cra().expect("map");
|
||||
let statuses = control_statuses(
|
||||
&map,
|
||||
&[],
|
||||
Some(&c_only()),
|
||||
&[],
|
||||
&SbomCoverage::RecipeInventoryOnly,
|
||||
);
|
||||
for control in ["cra-ai-22", "cra-ai-23", "cra-ai-33"] {
|
||||
let status = status_of(&statuses, control);
|
||||
assert_eq!(status.state, ControlState::Partial, "{control}");
|
||||
assert_eq!(status.reason, Some(NotAssessedReason::RecipeInventoryOnly));
|
||||
}
|
||||
assert_eq!(
|
||||
state_of(&statuses, "cra-ai-20"),
|
||||
ControlState::NoViolationFound
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unresolved_dependencies_claim_nothing_about_components() {
|
||||
let map = ControlMap::cra().expect("map");
|
||||
@@ -456,6 +538,7 @@ mod tests {
|
||||
assert_eq!(tool_of_stage("cve_lookup"), Some("osv"));
|
||||
assert_eq!(tool_of_stage("sast_mobile"), Some("mobsfscan"));
|
||||
assert_eq!(tool_of_stage("sast_dotnet"), Some("devskim"));
|
||||
assert_eq!(tool_of_stage("recipe_lint"), Some("oelint-adv"));
|
||||
assert_eq!(tool_of_stage("sast_vendor_code"), None);
|
||||
}
|
||||
|
||||
|
||||
@@ -158,12 +158,16 @@ pub fn build_pack(
|
||||
"type": inputs.target.target_type.to_string(),
|
||||
}),
|
||||
last_scan_run: inputs.last_run.as_ref().map(|run| {
|
||||
// A run recorded before notes existed lists them among its skips.
|
||||
let mut run = run.clone();
|
||||
run.split_notes();
|
||||
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,
|
||||
"notes": run.notes,
|
||||
})
|
||||
}),
|
||||
tool_versions: std::fs::read(TOOL_VERSIONS_PATH)
|
||||
@@ -215,12 +219,13 @@ pub fn scanned_languages(inputs: &EvidenceInputs) -> Option<&[String]> {
|
||||
}
|
||||
|
||||
/// The tools that did not complete in the target's last scan (a skipped
|
||||
/// stage a control relies on: semgrep, cppcheck, the CVE lookup).
|
||||
/// stage a control relies on: semgrep, cppcheck, the CVE lookup). Notes never
|
||||
/// count: the stage they inform about ran.
|
||||
pub fn failed_tools(inputs: &EvidenceInputs) -> Vec<&'static str> {
|
||||
inputs
|
||||
.last_run
|
||||
.iter()
|
||||
.flat_map(|run| &run.skipped_stages)
|
||||
.flat_map(ScanRun::skips)
|
||||
.filter_map(|s| compliance::tool_of_stage(&s.stage))
|
||||
.collect()
|
||||
}
|
||||
@@ -232,7 +237,7 @@ pub fn sbom_coverage(inputs: &EvidenceInputs) -> compliance::SbomCoverage {
|
||||
let unresolved: Vec<String> = inputs
|
||||
.last_run
|
||||
.iter()
|
||||
.flat_map(|run| &run.skipped_stages)
|
||||
.flat_map(ScanRun::skips)
|
||||
.filter(|s| s.code == Some(SkipCode::DependenciesUnlocked))
|
||||
.filter_map(|s| s.subject.clone())
|
||||
.collect();
|
||||
@@ -240,6 +245,15 @@ pub fn sbom_coverage(inputs: &EvidenceInputs) -> compliance::SbomCoverage {
|
||||
compliance::SbomCoverage::Unresolved(unresolved)
|
||||
} else if inputs.sbom.is_empty() {
|
||||
compliance::SbomCoverage::Empty
|
||||
} else if inputs
|
||||
.sbom
|
||||
.iter()
|
||||
.any(|e| e.package_manager == compliance_core::models::YOCTO_RECIPE_MANAGER)
|
||||
{
|
||||
// No image SBOM can be imported yet (Yocto tier 2), so a recipe
|
||||
// inventory is all there is: it lists the layer tree's recipes, not
|
||||
// what the image contains.
|
||||
compliance::SbomCoverage::RecipeInventoryOnly
|
||||
} else {
|
||||
compliance::SbomCoverage::Complete
|
||||
}
|
||||
@@ -334,7 +348,7 @@ fn csv_cell(value: &str) -> String {
|
||||
#[allow(clippy::expect_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::{ScanType, Severity, TargetType};
|
||||
use compliance_core::models::{ScanType, Severity, SkippedStage, TargetType};
|
||||
use std::io::Read;
|
||||
|
||||
fn inputs() -> EvidenceInputs {
|
||||
@@ -367,6 +381,22 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recipe_inventory_is_not_a_complete_sbom() {
|
||||
let mut with = inputs();
|
||||
assert_eq!(sbom_coverage(&with), compliance::SbomCoverage::Complete);
|
||||
with.sbom.push(SbomEntry::new(
|
||||
"t1".into(),
|
||||
"busybox".into(),
|
||||
"1.35.0".into(),
|
||||
compliance_core::models::YOCTO_RECIPE_MANAGER.into(),
|
||||
));
|
||||
assert_eq!(
|
||||
sbom_coverage(&with),
|
||||
compliance::SbomCoverage::RecipeInventoryOnly
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_actively_exploited_vulnerability_adds_its_draft_notification() {
|
||||
let mut with_kev = inputs();
|
||||
@@ -391,6 +421,63 @@ mod tests {
|
||||
assert!(listed.iter().all(|f| f.name != "enisa-drafts.json"));
|
||||
}
|
||||
|
||||
/// The last run of `inputs()` with these skipped stages and notes, as a
|
||||
/// completed run.
|
||||
fn with_run(skipped: Vec<SkippedStage>, notes: Vec<SkippedStage>) -> EvidenceInputs {
|
||||
let mut run = ScanRun::new("t1".into(), compliance_core::models::ScanTrigger::Manual);
|
||||
run.completed_at = Some(Utc::now());
|
||||
run.languages = vec!["c".into()];
|
||||
run.skipped_stages = skipped;
|
||||
run.notes = notes;
|
||||
EvidenceInputs {
|
||||
last_run: Some(run),
|
||||
..inputs()
|
||||
}
|
||||
}
|
||||
|
||||
fn vendor_note() -> SkippedStage {
|
||||
SkippedStage::new("sast_vendor_code", SkipCode::VendorCode, "vendor").about("Drivers")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notes_leave_the_control_status_alone() {
|
||||
let without = with_run(Vec::new(), Vec::new());
|
||||
let noted = with_run(Vec::new(), vec![vendor_note()]);
|
||||
// A run recorded before notes existed, the note among its skips.
|
||||
let mut old_note = vendor_note();
|
||||
old_note.status = SkippedStage::SKIPPED.to_string();
|
||||
let old = with_run(vec![old_note], Vec::new());
|
||||
assert!(failed_tools(¬ed).is_empty());
|
||||
assert!(failed_tools(&old).is_empty());
|
||||
assert_eq!(compliance_of(¬ed), compliance_of(&without));
|
||||
assert_eq!(compliance_of(&old), compliance_of(&without));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_manifest_lists_the_last_runs_notes_apart_from_its_skips() {
|
||||
let mut old_note = vendor_note();
|
||||
old_note.status = SkippedStage::SKIPPED.to_string();
|
||||
let semgrep = SkippedStage::new("sast", SkipCode::ToolFailed, "semgrep did not complete");
|
||||
let pack = with_run(vec![old_note, semgrep], Vec::new());
|
||||
assert_eq!(failed_tools(&pack), ["semgrep"]);
|
||||
|
||||
let (zip_bytes, _) = build_pack(&pack, Utc::now()).expect("pack");
|
||||
let mut archive =
|
||||
zip::ZipArchive::new(std::io::Cursor::new(zip_bytes)).expect("a valid zip");
|
||||
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");
|
||||
let run = &manifest["last_scan_run"];
|
||||
assert_eq!(run["skipped_stages"].as_array().map(Vec::len), Some(1));
|
||||
assert_eq!(run["skipped_stages"][0]["stage"], "sast");
|
||||
assert_eq!(run["notes"][0]["stage"], "sast_vendor_code");
|
||||
assert_eq!(run["notes"][0]["status"], "note");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pack_holds_every_file_and_the_manifest_hashes_match() {
|
||||
let (zip_bytes, listed) = build_pack(&inputs(), Utc::now()).expect("pack");
|
||||
|
||||
@@ -16,6 +16,16 @@ pub enum SourceAction {
|
||||
Ignore(&'static str),
|
||||
}
|
||||
|
||||
impl SourceAction {
|
||||
/// The repository the action is about; `None` for [`Self::Ignore`].
|
||||
pub fn repo(&self) -> Option<&GiteaRepo> {
|
||||
match self {
|
||||
Self::Created(repo) | Self::Deleted(repo) | Self::Push(repo) => Some(repo),
|
||||
Self::Ignore(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A branch deletion pushes this as the new head.
|
||||
const ZERO_SHA: &str = "0000000000000000000000000000000000000000";
|
||||
|
||||
@@ -73,6 +83,16 @@ mod tests {
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_action_names_its_repository_unless_ignored() {
|
||||
let p = json!({ "action": "created", "repository": repository("kunde") });
|
||||
assert_eq!(
|
||||
route_event("repository", &p, "kunde").repo().map(|r| r.id),
|
||||
Some(42)
|
||||
);
|
||||
assert!(SourceAction::Ignore("x").repo().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn created_and_deleted() {
|
||||
let p = json!({ "action": "created", "repository": repository("kunde") });
|
||||
|
||||
@@ -112,6 +112,11 @@ impl RepoLister for SourceClient {
|
||||
self.base_url,
|
||||
urlencoding::encode(org)
|
||||
);
|
||||
// One of the instance's two request slots, shared with the issue
|
||||
// tracker, held until the page has been read.
|
||||
let _permit = crate::trackers::gitea_limit::acquire(&self.base_url)
|
||||
.await
|
||||
.map_err(|e| AgentError::Other(format!("Gitea request slot: {e}")))?;
|
||||
let resp = self
|
||||
.http
|
||||
.get(&url)
|
||||
|
||||
@@ -45,9 +45,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
Err(e) => tracing::error!("migrating stored findings failed: {e}"),
|
||||
}
|
||||
// Open CVE alerts stored before purls were recorded (#532) get their
|
||||
// component's purl, before a scan can resolve them.
|
||||
// component's purl, before a scan can resolve them. Logged with 0 too, so
|
||||
// "ran, nothing to do" is told apart from "did not run".
|
||||
match pipeline::vex_lifecycle::backfill_purls_everywhere(&agent.db_pool).await {
|
||||
Ok(0) => {}
|
||||
Ok(alerts) => tracing::info!(alerts, "CVE alerts got their component's purl"),
|
||||
Err(e) => tracing::error!("backfilling CVE alert purls failed: {e}"),
|
||||
}
|
||||
|
||||
@@ -381,6 +381,7 @@ mod tests {
|
||||
severity: None,
|
||||
url: None,
|
||||
exploitation: None,
|
||||
aliases: Vec::new(),
|
||||
})
|
||||
.collect();
|
||||
entry
|
||||
|
||||
@@ -189,7 +189,7 @@ fn check_adt_project(root: &Path, dir: &Path) -> Vec<Hit> {
|
||||
),
|
||||
remediation: "Raise the target and minimum API level to a supported Android \
|
||||
release (after migrating the build to Gradle) and test on it.",
|
||||
severity: Severity::Medium,
|
||||
severity: Severity::High,
|
||||
cwe: "CWE-1104",
|
||||
path,
|
||||
line: Some(line),
|
||||
@@ -270,7 +270,7 @@ fn check_xcode_project(root: &Path, file: &Path) -> Vec<Hit> {
|
||||
remediation: "Migrate the code to Swift 5 or later (Xcode migrates Swift 4 \
|
||||
code; older code through an Xcode release that still reads it) \
|
||||
and set SWIFT_VERSION accordingly.",
|
||||
severity: Severity::Medium,
|
||||
severity: Severity::High,
|
||||
cwe: "CWE-1104",
|
||||
path,
|
||||
line: Some(line),
|
||||
@@ -415,7 +415,7 @@ fn check_unity_project(root: &Path, project: &Path) -> Vec<Hit> {
|
||||
relative(root, project)
|
||||
),
|
||||
remediation: "Upgrade the project to a supported Unity LTS release.",
|
||||
severity: Severity::Medium,
|
||||
severity: Severity::High,
|
||||
cwe: "CWE-1104",
|
||||
path,
|
||||
line: Some(1),
|
||||
@@ -466,8 +466,24 @@ mod tests {
|
||||
Tree(dir)
|
||||
}
|
||||
|
||||
/// The hits as `rule path:line`; every end-of-support hit is high, like
|
||||
/// every other end-of-life finding, except the minimum OS an app still
|
||||
/// installs on, which stays low until that severity is decided.
|
||||
fn hits(t: &Tree) -> Vec<String> {
|
||||
check_tree(&t.0)
|
||||
let found = check_tree(&t.0);
|
||||
for hit in found
|
||||
.iter()
|
||||
.filter(|h| h.rule_id.ends_with("-end-of-support"))
|
||||
{
|
||||
let expected = match hit.rule_id {
|
||||
"ios-deployment-target-end-of-support" | "android-min-sdk-end-of-support" => {
|
||||
Severity::Low
|
||||
}
|
||||
_ => Severity::High,
|
||||
};
|
||||
assert_eq!(hit.severity, expected, "{}", hit.rule_id);
|
||||
}
|
||||
found
|
||||
.into_iter()
|
||||
.map(|h| format!("{} {}:{}", h.rule_id, h.path, h.line.unwrap_or(0)))
|
||||
.collect()
|
||||
|
||||
@@ -69,6 +69,18 @@ pub enum ClamavError {
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
|
||||
impl ClamavError {
|
||||
/// True when the clamd service itself is down (unreachable or silent),
|
||||
/// as opposed to a problem with one file or the tree. Logged as an error
|
||||
/// so the "ERROR/FATAL logs" alert fires: nothing else restarts clamd.
|
||||
pub fn service_down(&self) -> bool {
|
||||
match self {
|
||||
Self::Unreachable(..) | Self::Timeout => true,
|
||||
Self::Refused(_) | Self::Io(_) => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A clamd service.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Clamd {
|
||||
@@ -397,6 +409,16 @@ fn finding(root: &Path, repo_id: &str, file: &Path, hash: &str, signature: &str)
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_an_unreachable_or_silent_clamd_is_down() {
|
||||
let refused = std::io::Error::from(std::io::ErrorKind::ConnectionRefused);
|
||||
assert!(ClamavError::Unreachable("clamav:3310".into(), refused).service_down());
|
||||
assert!(ClamavError::Timeout.service_down());
|
||||
assert!(!ClamavError::Refused("INSTREAM size limit exceeded".into()).service_down());
|
||||
let unreadable = std::io::Error::from(std::io::ErrorKind::PermissionDenied);
|
||||
assert!(!ClamavError::Io(unreadable).service_down());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clamd_answers_are_read() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
//! At most two clones or fetches against one git host at a time.
|
||||
//!
|
||||
//! Every target of a tenant usually lives on the same git host. When scans of
|
||||
//! several of them start together (a git sync creating targets, scans resumed
|
||||
//! after a restart), they would all clone from that host at once; a small
|
||||
//! self-hosted Gitea answers that with an OOM kill and `502`s. The limit is
|
||||
//! held only around the clone or fetch itself, not the rest of the scan, and
|
||||
//! another host's clones go ahead meanwhile.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Condvar, LazyLock, Mutex, PoisonError};
|
||||
|
||||
/// How many clones or fetches may run against one git host at once.
|
||||
pub const CLONES_PER_HOST: usize = 2;
|
||||
|
||||
/// The limiter every clone and fetch of this process goes through.
|
||||
pub static CLONE_SLOTS: LazyLock<HostLimiter> = LazyLock::new(|| HostLimiter::new(CLONES_PER_HOST));
|
||||
|
||||
/// A counting semaphore per git host, for blocking (non-async) callers.
|
||||
#[derive(Debug)]
|
||||
pub struct HostLimiter {
|
||||
per_host: usize,
|
||||
hosts: Mutex<HashMap<String, Arc<HostSlots>>>,
|
||||
}
|
||||
|
||||
/// The slots of one host: how many are taken, and a wake-up for waiters.
|
||||
#[derive(Debug, Default)]
|
||||
struct HostSlots {
|
||||
taken: Mutex<usize>,
|
||||
freed: Condvar,
|
||||
}
|
||||
|
||||
/// One taken slot of a host; dropping it frees the slot.
|
||||
#[derive(Debug)]
|
||||
pub struct HostPermit {
|
||||
slots: Arc<HostSlots>,
|
||||
}
|
||||
|
||||
impl HostLimiter {
|
||||
/// A limiter allowing `per_host` operations per host at once (at least one).
|
||||
pub fn new(per_host: usize) -> Self {
|
||||
Self {
|
||||
per_host: per_host.max(1),
|
||||
hosts: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait until `host` has a free slot and take it.
|
||||
///
|
||||
/// Blocks the calling thread. On the async runtime's worker threads it
|
||||
/// hands the worker's other tasks to another worker first.
|
||||
pub fn acquire(&self, host: &str) -> HostPermit {
|
||||
// The map lock is held only for the lookup, never while waiting.
|
||||
let slots = {
|
||||
let mut hosts = self.hosts.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
Arc::clone(hosts.entry(host.to_ascii_lowercase()).or_default())
|
||||
};
|
||||
let taken = slots.taken.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut taken = if *taken < self.per_host {
|
||||
taken
|
||||
} else {
|
||||
tracing::info!(host, "waiting for a free clone slot on this git host");
|
||||
off_the_runtime(|| {
|
||||
slots
|
||||
.freed
|
||||
.wait_while(taken, |taken| *taken >= self.per_host)
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
})
|
||||
};
|
||||
*taken += 1;
|
||||
drop(taken);
|
||||
HostPermit { slots }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for HostPermit {
|
||||
fn drop(&mut self) {
|
||||
let mut taken = self
|
||||
.slots
|
||||
.taken
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
*taken = taken.saturating_sub(1);
|
||||
self.slots.freed.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
/// Run blocking `work` without stalling the async runtime: on a multi-thread
|
||||
/// runtime's worker, `block_in_place` moves the worker's other tasks first.
|
||||
pub(crate) fn off_the_runtime<R>(work: impl FnOnce() -> R) -> R {
|
||||
let on_multi_thread_runtime = tokio::runtime::Handle::try_current()
|
||||
.is_ok_and(|h| h.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread);
|
||||
if on_multi_thread_runtime {
|
||||
tokio::task::block_in_place(work)
|
||||
} else {
|
||||
work()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::HostLimiter;
|
||||
use std::sync::{mpsc, Arc};
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn a_host_runs_at_most_two_while_another_host_proceeds() {
|
||||
let limiter = Arc::new(HostLimiter::new(2));
|
||||
let first = limiter.acquire("git.example.com");
|
||||
let _second = limiter.acquire("git.example.com");
|
||||
|
||||
// A third clone from the same host waits.
|
||||
let (sent, received) = mpsc::channel();
|
||||
let waiting = Arc::clone(&limiter);
|
||||
let third = std::thread::spawn(move || {
|
||||
let permit = waiting.acquire("GIT.example.com");
|
||||
sent.send(()).expect("send");
|
||||
drop(permit);
|
||||
});
|
||||
assert!(received.recv_timeout(Duration::from_millis(100)).is_err());
|
||||
|
||||
// Another host is not held up by the full one.
|
||||
let _other = limiter.acquire("gitlab.example.org");
|
||||
|
||||
// A freed slot lets the waiting clone go ahead.
|
||||
drop(first);
|
||||
received
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.expect("the third clone runs once a slot is free");
|
||||
third.join().expect("join");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_permit_frees_its_slot() {
|
||||
let limiter = HostLimiter::new(1);
|
||||
drop(limiter.acquire("git.example.com"));
|
||||
// Would block forever if the slot had not been freed.
|
||||
let _again = limiter.acquire("git.example.com");
|
||||
}
|
||||
}
|
||||
@@ -192,6 +192,7 @@ pub(crate) fn apply(
|
||||
severity: hit.vulnerability.severity.clone(),
|
||||
url: hit.advisory.url.clone(),
|
||||
exploitation: None,
|
||||
aliases: Vec::new(),
|
||||
});
|
||||
}
|
||||
let fixed = hit.advisory.fixed_versions(hit.vulnerability, &entry.name);
|
||||
@@ -333,6 +334,7 @@ mod tests {
|
||||
severity: None,
|
||||
url: None,
|
||||
exploitation: None,
|
||||
aliases: Vec::new(),
|
||||
});
|
||||
let mut nvd = CveAlert::new(
|
||||
"CVE-2026-90001".into(),
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
|
||||
use compliance_core::models::{CveAlert, CveSource, SbomEntry, VulnRef};
|
||||
use compliance_core::models::{CveAlert, CveSource, SbomEntry, VulnRef, YOCTO_RECIPE_MANAGER};
|
||||
use compliance_core::net_guard::NetGuard;
|
||||
use compliance_core::CoreError;
|
||||
|
||||
use crate::pipeline::embedded_versions::{self, EMBEDDED_MANAGER};
|
||||
use crate::pipeline::nvd_cpe::{self, NvdCve, NvdProduct};
|
||||
use crate::pipeline::public_http::{read_body, read_json, PublicHttp};
|
||||
use crate::pipeline::yocto_inventory::NvdQuery;
|
||||
|
||||
/// OSV's API.
|
||||
const OSV_API: &str = "https://api.osv.dev";
|
||||
|
||||
/// Every CODESYS product: advisories key off the runtime's version.
|
||||
const CODESYS: NvdProduct = NvdProduct {
|
||||
pub(crate) const CODESYS: NvdProduct = NvdProduct {
|
||||
match_string: "cpe:2.3:a:codesys",
|
||||
marker: ":codesys:",
|
||||
};
|
||||
@@ -79,6 +80,7 @@ impl CveScanner {
|
||||
severity: vuln.severity,
|
||||
url: Some(format!("https://osv.dev/vulnerability/{}", vuln.id)),
|
||||
exploitation: None,
|
||||
aliases: Vec::new(),
|
||||
});
|
||||
let mut alert = CveAlert::new(
|
||||
vuln.id,
|
||||
@@ -116,6 +118,7 @@ impl CveScanner {
|
||||
for vuln in &mut entry.known_vulnerabilities {
|
||||
if let Some(detail) = details.get(&vuln.id) {
|
||||
vuln.severity = detail.severity.clone().or(vuln.severity.take());
|
||||
vuln.aliases.clone_from(&detail.aliases);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -155,10 +158,13 @@ impl CveScanner {
|
||||
let mut refused = Vec::new();
|
||||
// Each query keeps the index of its entry: an entry without a purl is
|
||||
// not asked about, and must not shift the answers onto its neighbours.
|
||||
// Yocto recipes are matched by CPE in NVD instead ([`Self::scan_yocto`]).
|
||||
let queries: Vec<(usize, &str)> = entries
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, e)| !without_osv_advisories(e))
|
||||
.filter(|(_, e)| {
|
||||
!without_osv_advisories(e) && e.package_manager != YOCTO_RECIPE_MANAGER
|
||||
})
|
||||
.filter_map(|(i, e)| e.purl.as_deref().map(|purl| (i, purl)))
|
||||
.collect();
|
||||
|
||||
@@ -349,6 +355,82 @@ impl CveScanner {
|
||||
}
|
||||
}
|
||||
|
||||
impl CveScanner {
|
||||
/// Match the components of a Yocto recipe inventory against NVD by CPE
|
||||
/// (`queries`, see [`crate::pipeline::yocto_inventory::nvd_queries`]),
|
||||
/// one product after the other, within `budget`. A recipe whose lookup
|
||||
/// fails, or that the budget leaves unasked, is reported in
|
||||
/// [`CveLookup::unchecked`]; the others are still matched.
|
||||
///
|
||||
/// NVD answers about 5 requests per 30 seconds without an API key and 50
|
||||
/// with one (`NVD_API_KEY`, sent as the `apiKey` header): the requests are
|
||||
/// paced to that ([`nvd_cpe::request_interval`]), a cached answer costs
|
||||
/// none, and a layer tree can name hundreds of products: the budget keeps
|
||||
/// the scan bounded, and the 6-hour cache lets the next scan of the same
|
||||
/// products go further.
|
||||
pub async fn scan_yocto(
|
||||
&self,
|
||||
repo_id: &str,
|
||||
entries: &mut [SbomEntry],
|
||||
queries: &[NvdQuery],
|
||||
budget: std::time::Duration,
|
||||
) -> CveLookup {
|
||||
let deadline = tokio::time::Instant::now() + budget;
|
||||
let interval = nvd_cpe::request_interval(self.nvd_api_key.is_some());
|
||||
let mut next_request = tokio::time::Instant::now();
|
||||
let mut lookup = CveLookup::default();
|
||||
for query in queries {
|
||||
let mut found: Vec<NvdCve> = Vec::new();
|
||||
let mut checked = true;
|
||||
for product in &query.products {
|
||||
let (match_string, marker) = (product.match_string(), product.marker());
|
||||
if !nvd_cpe::is_cached(&match_string) {
|
||||
if next_request >= deadline {
|
||||
checked = false;
|
||||
continue;
|
||||
}
|
||||
tokio::time::sleep_until(next_request).await;
|
||||
next_request = tokio::time::Instant::now() + interval;
|
||||
}
|
||||
let lookup = nvd_cpe::match_cves(
|
||||
&self.http,
|
||||
self.nvd_api_key.as_deref(),
|
||||
&match_string,
|
||||
&marker,
|
||||
&query.cve_version,
|
||||
);
|
||||
match tokio::time::timeout_at(deadline, lookup).await {
|
||||
Ok(Ok(cves)) => {
|
||||
for cve in cves {
|
||||
if !found.iter().any(|f| f.id == cve.id) {
|
||||
found.push(cve);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
tracing::warn!(recipe = %query.name, "NVD lookup failed: {e}");
|
||||
checked = false;
|
||||
}
|
||||
Err(_) => checked = false,
|
||||
}
|
||||
}
|
||||
if !checked {
|
||||
lookup
|
||||
.unchecked
|
||||
.push(format!("{} {}", query.name, query.version));
|
||||
}
|
||||
lookup.alerts.extend(record_nvd(
|
||||
repo_id,
|
||||
entries,
|
||||
&query.name,
|
||||
&query.version,
|
||||
found,
|
||||
));
|
||||
}
|
||||
lookup
|
||||
}
|
||||
}
|
||||
|
||||
/// What a CVE lookup found, and what it could not check.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct CveLookup {
|
||||
@@ -359,9 +441,10 @@ pub struct CveLookup {
|
||||
pub unchecked: Vec<String>,
|
||||
}
|
||||
|
||||
/// Attach NVD `cves` to the SBOM entry `name@version` and make an alert for
|
||||
/// each.
|
||||
fn record_nvd(
|
||||
/// Attach NVD `cves` to the SBOM entry `name@version` (once per CVE: an
|
||||
/// entry read back from the database may carry it already) and make an alert
|
||||
/// for each.
|
||||
pub(crate) fn record_nvd(
|
||||
repo_id: &str,
|
||||
entries: &mut [SbomEntry],
|
||||
name: &str,
|
||||
@@ -374,13 +457,17 @@ fn record_nvd(
|
||||
let purl = entry.as_ref().and_then(|e| e.purl.clone());
|
||||
cves.into_iter()
|
||||
.map(|cve| {
|
||||
if let Some(e) = entry.as_deref_mut() {
|
||||
if let Some(e) = entry
|
||||
.as_deref_mut()
|
||||
.filter(|e| !e.known_vulnerabilities.iter().any(|v| v.id == cve.id))
|
||||
{
|
||||
e.known_vulnerabilities.push(VulnRef {
|
||||
id: cve.id.clone(),
|
||||
source: "nvd".to_string(),
|
||||
severity: None,
|
||||
url: Some(format!("https://nvd.nist.gov/vuln/detail/{}", cve.id)),
|
||||
exploitation: None,
|
||||
aliases: Vec::new(),
|
||||
});
|
||||
}
|
||||
let mut alert = CveAlert::new(
|
||||
@@ -487,7 +574,7 @@ fn without_osv_advisories(entry: &SbomEntry) -> bool {
|
||||
/// The CODESYS runtime component (name + version) from an SBOM, if present. The
|
||||
/// runtime carries the version CODESYS advisories key off; the internal library
|
||||
/// components do not.
|
||||
fn codesys_runtime(entries: &[SbomEntry]) -> Option<(String, String)> {
|
||||
pub(crate) fn codesys_runtime(entries: &[SbomEntry]) -> Option<(String, String)> {
|
||||
entries
|
||||
.iter()
|
||||
.find(|e| e.package_manager == "codesys" && e.name.starts_with("CODESYS Control"))
|
||||
@@ -600,6 +687,23 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn yocto_recipes_are_left_to_nvd_not_asked_of_osv() {
|
||||
let (url, hits) = fake_osv().await;
|
||||
let scanner = CveScanner::new(NetGuard::allow_private(), None)
|
||||
.unwrap()
|
||||
.with_osv_api(url);
|
||||
let mut recipe = with_purl("busybox", "pkg:generic/busybox@1.35.0");
|
||||
recipe.package_manager = YOCTO_RECIPE_MANAGER.into();
|
||||
let mut entries = vec![recipe];
|
||||
|
||||
let lookup = scanner.scan_dependencies("t", &mut entries).await.unwrap();
|
||||
|
||||
assert_eq!(hits.load(Ordering::SeqCst), 0, "OSV was asked");
|
||||
assert!(lookup.alerts.is_empty());
|
||||
assert!(lookup.unchecked.is_empty(), "NVD checks it, not OSV");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_nvd_alert_keeps_the_purl_of_its_component() {
|
||||
let mut entries = vec![
|
||||
@@ -615,6 +719,10 @@ mod tests {
|
||||
let without = record_nvd("t", &mut entries, "FreeRTOS", "1.0.0", vec![cve("CVE-2")]);
|
||||
assert_eq!(with[0].purl.as_deref(), Some("pkg:generic/lwip@1.0.0"));
|
||||
assert_eq!(without[0].purl, None);
|
||||
// Recorded again (the monitor re-reads stored entries), the
|
||||
// component lists the CVE once.
|
||||
record_nvd("t", &mut entries, "lwIP", "1.0.0", vec![cve("CVE-1")]);
|
||||
assert_eq!(entries[0].known_vulnerabilities.len(), 1);
|
||||
}
|
||||
|
||||
fn entry(name: &str, ver: &str, pm: &str) -> SbomEntry {
|
||||
|
||||
@@ -28,7 +28,7 @@ use std::collections::{BTreeSet, HashMap};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use compliance_core::models::{CveAlert, EpssScore, Exploitation, KevEntry, SbomEntry};
|
||||
use compliance_core::models::{is_cve, CveAlert, EpssScore, Exploitation, KevEntry, SbomEntry};
|
||||
use compliance_core::net_guard::NetGuard;
|
||||
use compliance_core::CoreError;
|
||||
use futures_util::future::BoxFuture;
|
||||
@@ -194,7 +194,7 @@ impl CveEnricher {
|
||||
let cves: BTreeSet<String> = alerts
|
||||
.iter()
|
||||
.map(|a| a.cve().to_string())
|
||||
.filter(|id| is_cve_id(id))
|
||||
.filter(|id| is_cve(id))
|
||||
.collect();
|
||||
let mut counts = EnrichCounts {
|
||||
cves: cves.len(),
|
||||
@@ -446,22 +446,10 @@ impl CveEnricher {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `id` is a CVE id (`CVE-2021-44228`).
|
||||
fn is_cve_id(id: &str) -> bool {
|
||||
let mut parts = id.splitn(3, '-');
|
||||
parts.next() == Some("CVE")
|
||||
&& parts
|
||||
.next()
|
||||
.is_some_and(|y| y.len() == 4 && y.bytes().all(|b| b.is_ascii_digit()))
|
||||
&& parts
|
||||
.next()
|
||||
.is_some_and(|n| n.len() >= 4 && n.bytes().all(|b| b.is_ascii_digit()))
|
||||
}
|
||||
|
||||
/// Where Vulnrichment keeps the record of `cve`: `<year>/<thousands>xxx/<cve>.json`
|
||||
/// (`CVE-2021-44228` → `2021/44xxx/CVE-2021-44228.json`).
|
||||
fn vulnrichment_path(cve: &str) -> Option<String> {
|
||||
if !is_cve_id(cve) {
|
||||
if !is_cve(cve) {
|
||||
return None;
|
||||
}
|
||||
let mut parts = cve.splitn(3, '-').skip(1);
|
||||
@@ -930,6 +918,7 @@ mod tests {
|
||||
severity: None,
|
||||
url: None,
|
||||
exploitation: None,
|
||||
aliases: Vec::new(),
|
||||
});
|
||||
e
|
||||
}
|
||||
@@ -977,7 +966,7 @@ mod tests {
|
||||
"CVE-2021-../x",
|
||||
"RUSTSEC-2021-0001",
|
||||
] {
|
||||
assert!(!is_cve_id(id), "{id}");
|
||||
assert!(!is_cve(id), "{id}");
|
||||
assert_eq!(vulnrichment_path(id), None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,13 @@
|
||||
//! updated or removed), the issue is closed with a comment; when it comes back,
|
||||
//! it is reopened.
|
||||
//!
|
||||
//! A CVE a VEX statement settles (`not_affected` or `fixed`, by a person, the
|
||||
//! scan or an imported VEX document) gets no issue. Its open issue is closed
|
||||
//! with a comment naming the status and the reason when `ISSUE_AUTOCLOSE` is
|
||||
//! `on` (at most [`AUTOCLOSE_PER_SCAN`] per target and scan), only counted
|
||||
//! with `dry_run`, and left open with `off`, the default. When the statement
|
||||
//! is withdrawn, the issue is reopened (or opened) as for a CVE found again.
|
||||
//!
|
||||
//! What is known about a CVE's exploitation (#493) moves the threshold: a CVE
|
||||
//! in CISA's KEV catalog always gets an issue, rated at least high, and one
|
||||
//! whose EPSS percentile reaches [`epss_percentile`] is rated one step higher
|
||||
@@ -16,8 +23,9 @@ use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
use mongodb::bson::doc;
|
||||
|
||||
use compliance_core::config::IssueAutoclose;
|
||||
use compliance_core::models::notification::{parse_severity, NotificationSeverity};
|
||||
use compliance_core::models::{CveAlert, IssueStatus, TrackerIssue};
|
||||
use compliance_core::models::{CveAlert, IssueStatus, TrackerIssue, VexAssessment, VexStatus};
|
||||
|
||||
use crate::database::Database;
|
||||
use crate::error::AgentError;
|
||||
@@ -30,6 +38,8 @@ const CVE_CONTROLS: [&str; 2] = ["cra-ai-22", "cra-ai-33"];
|
||||
/// Where the issues of one target go.
|
||||
pub(crate) struct CveIssueTarget<'a> {
|
||||
pub db: &'a Database,
|
||||
/// The tenant, for the log lines.
|
||||
pub tenant_id: &'a str,
|
||||
pub tracker: &'a TrackerDispatch,
|
||||
pub owner: &'a str,
|
||||
pub repo: &'a str,
|
||||
@@ -40,6 +50,9 @@ pub(crate) struct CveIssueTarget<'a> {
|
||||
/// From this EPSS percentile (0 to 1) on a CVE is rated one step higher;
|
||||
/// `None` leaves EPSS out (see [`epss_percentile`]).
|
||||
pub epss_percentile: Option<f64>,
|
||||
/// Whether open issues a VEX statement settles are closed
|
||||
/// (`ISSUE_AUTOCLOSE`).
|
||||
pub autoclose: IssueAutoclose,
|
||||
}
|
||||
|
||||
/// The EPSS percentile from which a CVE is rated one step higher.
|
||||
@@ -136,7 +149,9 @@ fn issue_worthy(alert: &CveAlert, epss_percentile: Option<f64>) -> bool {
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `target` - where the issues go
|
||||
/// * `alerts` - every CVE the scan found in the target's components
|
||||
/// * `alerts` - every CVE the scan found in the target's components, with
|
||||
/// its stored VEX statement
|
||||
/// ([`crate::pipeline::vex_lifecycle::attach_stored_vex`])
|
||||
/// * `complete` - whether every component was matched; only then is a CVE
|
||||
/// that is missing from `alerts` known to be gone, and its issue closed
|
||||
///
|
||||
@@ -171,7 +186,7 @@ pub(crate) async fn sync_cve_issues(
|
||||
|
||||
for (key, alert) in present
|
||||
.iter()
|
||||
.filter(|(_, a)| issue_worthy(a, target.epss_percentile))
|
||||
.filter(|(_, a)| !a.is_resolved_by_vex() && issue_worthy(a, target.epss_percentile))
|
||||
{
|
||||
match existing.get(key) {
|
||||
Some(issue) if is_closed(&issue.status) => {
|
||||
@@ -190,6 +205,17 @@ pub(crate) async fn sync_cve_issues(
|
||||
}
|
||||
}
|
||||
|
||||
// A VEX statement settles the CVE whether or not the scan was complete.
|
||||
let settled: Vec<(&TrackerIssue, &VexAssessment)> = present
|
||||
.iter()
|
||||
.filter_map(|(key, alert)| {
|
||||
let vex = alert.vex.as_ref().filter(|_| alert.is_resolved_by_vex())?;
|
||||
let issue = existing.get(key).filter(|i| !is_closed(&i.status))?;
|
||||
Some((issue, vex))
|
||||
})
|
||||
.collect();
|
||||
counts.closed += autoclose(target, &settled).await?;
|
||||
|
||||
if complete {
|
||||
for (key, issue) in &existing {
|
||||
if present.contains_key(key) || is_closed(&issue.status) {
|
||||
@@ -205,6 +231,86 @@ pub(crate) async fn sync_cve_issues(
|
||||
Ok(counts)
|
||||
}
|
||||
|
||||
/// Open issues closed per target and scan because a VEX statement settles
|
||||
/// their CVE; the rest follow in the next scans.
|
||||
const AUTOCLOSE_PER_SCAN: usize = 20;
|
||||
|
||||
/// Close the open issues in `settled` (each with the VEX statement that
|
||||
/// settles its CVE) as `ISSUE_AUTOCLOSE` says: not at all, only counted, or
|
||||
/// at most [`AUTOCLOSE_PER_SCAN`] with a comment. Every Gitea request waits
|
||||
/// for its instance's slot ([`crate::trackers::gitea_limit`]). Unless off,
|
||||
/// logs one line per target and scan with counts only, also when there is
|
||||
/// nothing to close, so "ran, nothing to close" shows in the log.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// How many issues were closed.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// A database error.
|
||||
async fn autoclose(
|
||||
target: &CveIssueTarget<'_>,
|
||||
settled: &[(&TrackerIssue, &VexAssessment)],
|
||||
) -> Result<u32, AgentError> {
|
||||
let tenant_id = target.tenant_id;
|
||||
let target_id = target.target_id;
|
||||
match target.autoclose {
|
||||
IssueAutoclose::Off => Ok(0),
|
||||
IssueAutoclose::DryRun => {
|
||||
let not_affected = settled
|
||||
.iter()
|
||||
.filter(|(_, vex)| vex.status == VexStatus::NotAffected)
|
||||
.count();
|
||||
tracing::info!(
|
||||
tenant_id,
|
||||
target_id,
|
||||
would_close = settled.len(),
|
||||
not_affected,
|
||||
fixed = settled.len() - not_affected,
|
||||
"CVE issues settled by VEX (dry run, nothing changed)"
|
||||
);
|
||||
Ok(0)
|
||||
}
|
||||
IssueAutoclose::On => {
|
||||
let (mut closed, mut failed) = (0u32, 0u32);
|
||||
for (issue, vex) in settled.iter().take(AUTOCLOSE_PER_SCAN) {
|
||||
if set_state(target, issue, &vex_comment(vex), "closed").await {
|
||||
record(target.db, issue, IssueStatus::Closed).await?;
|
||||
closed += 1;
|
||||
} else {
|
||||
failed += 1;
|
||||
}
|
||||
}
|
||||
tracing::info!(
|
||||
tenant_id,
|
||||
target_id,
|
||||
closed,
|
||||
deferred = settled.len().saturating_sub(AUTOCLOSE_PER_SCAN),
|
||||
failed,
|
||||
"CVE issues settled by VEX closed"
|
||||
);
|
||||
Ok(closed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The comment an issue is closed with when a VEX statement settles its CVE:
|
||||
/// the status and the justification, or the reason in words.
|
||||
fn vex_comment(vex: &VexAssessment) -> String {
|
||||
let reason = match (vex.justification, vex.impact_statement.as_deref()) {
|
||||
(Some(justification), _) => format!(" ({})", justification.as_str()),
|
||||
(None, Some(statement)) if !statement.trim().is_empty() => {
|
||||
format!(": {}", statement.trim())
|
||||
}
|
||||
(None, _) => String::new(),
|
||||
};
|
||||
let status = vex.status.as_str();
|
||||
format!(
|
||||
"**Prüfwerk:** VEX-Status `{status}`{reason}. Geschlossen, solange diese Aussage gilt.\n\nVEX status `{status}`{reason}. Closed while this statement stands."
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether an issue is closed.
|
||||
fn is_closed(status: &IssueStatus) -> bool {
|
||||
matches!(status, IssueStatus::Closed | IssueStatus::Resolved)
|
||||
@@ -411,7 +517,7 @@ mod tests {
|
||||
use axum::extract::{Path, State};
|
||||
use axum::routing::{get, patch, post};
|
||||
use axum::{Json, Router};
|
||||
use compliance_core::models::CveSource;
|
||||
use compliance_core::models::{CveSource, VexJustification, VexStatus};
|
||||
use compliance_core::NetGuard;
|
||||
use secrecy::SecretString;
|
||||
|
||||
@@ -420,14 +526,22 @@ mod tests {
|
||||
/// The calls a fake Gitea received.
|
||||
type Calls = Arc<Mutex<Vec<String>>>;
|
||||
|
||||
async fn fake_gitea(calls: Calls) -> String {
|
||||
async fn labels() -> Json<serde_json::Value> {
|
||||
Json(serde_json::json!(pruefwerk_labels()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, l)| serde_json::json!({ "id": i as i64 + 1, "name": l.name, "color": "fff" }))
|
||||
.collect::<Vec<_>>()))
|
||||
/// The Prüfwerk labels, all present.
|
||||
async fn labels(
|
||||
axum::extract::Query(page): axum::extract::Query<std::collections::HashMap<String, String>>,
|
||||
) -> Json<serde_json::Value> {
|
||||
// One page of labels: a later page is empty, as Gitea ends a list.
|
||||
if page.get("page").map(String::as_str) != Some("1") {
|
||||
return Json(serde_json::json!([]));
|
||||
}
|
||||
Json(serde_json::json!(pruefwerk_labels()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, l)| serde_json::json!({ "id": i as i64 + 1, "name": l.name, "color": "fff" }))
|
||||
.collect::<Vec<_>>()))
|
||||
}
|
||||
|
||||
async fn fake_gitea(calls: Calls) -> String {
|
||||
async fn create(
|
||||
State(calls): State<Calls>,
|
||||
Json(body): Json<serde_json::Value>,
|
||||
@@ -453,8 +567,12 @@ mod tests {
|
||||
async fn comment(
|
||||
State(calls): State<Calls>,
|
||||
Path((_o, _r, n)): Path<(String, String, String)>,
|
||||
Json(body): Json<serde_json::Value>,
|
||||
) -> axum::http::StatusCode {
|
||||
calls.lock().unwrap().push(format!("comment {n}"));
|
||||
calls.lock().unwrap().push(format!(
|
||||
"comment {n}: {}",
|
||||
body["body"].as_str().unwrap_or_default()
|
||||
));
|
||||
axum::http::StatusCode::CREATED
|
||||
}
|
||||
async fn state(
|
||||
@@ -480,6 +598,27 @@ mod tests {
|
||||
format!("http://{addr}")
|
||||
}
|
||||
|
||||
/// A Gitea that lists its labels and refuses (and records) every other
|
||||
/// call: a dry run must not write.
|
||||
async fn read_only_gitea(calls: Calls) -> String {
|
||||
async fn refuse(
|
||||
State(calls): State<Calls>,
|
||||
method: axum::http::Method,
|
||||
uri: axum::http::Uri,
|
||||
) -> axum::http::StatusCode {
|
||||
calls.lock().unwrap().push(format!("{method} {uri}"));
|
||||
axum::http::StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
let app = Router::new()
|
||||
.route("/api/v1/repos/{o}/{r}/labels", get(labels))
|
||||
.fallback(refuse)
|
||||
.with_state(calls);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
format!("http://{addr}")
|
||||
}
|
||||
|
||||
fn exploited(kev: bool, percentile: Option<f64>) -> compliance_core::models::Exploitation {
|
||||
compliance_core::models::Exploitation {
|
||||
kev: kev.then(|| compliance_core::models::KevEntry {
|
||||
@@ -585,12 +724,14 @@ mod tests {
|
||||
let tracker = TrackerDispatch::Gitea(gitea);
|
||||
let target = CveIssueTarget {
|
||||
db: &db,
|
||||
tenant_id: "cve-issues",
|
||||
tracker: &tracker,
|
||||
owner: "kunde",
|
||||
repo: "app",
|
||||
target_id: "target-1",
|
||||
dashboard: "https://pruefwerk.example",
|
||||
epss_percentile: Some(0.95),
|
||||
autoclose: IssueAutoclose::Off,
|
||||
};
|
||||
let okhttp = alert("okhttp", "3.12.0", "GHSA-3cqm-mf7h-prrj", "HIGH");
|
||||
let minor = alert("gson", "2.8.8", "GHSA-4jrv-ppp4-jm57", "MODERATE");
|
||||
@@ -653,4 +794,303 @@ mod tests {
|
||||
|
||||
pool.drop_tenant("cve-issues").await.ok();
|
||||
}
|
||||
|
||||
fn vex(status: VexStatus) -> VexAssessment {
|
||||
VexAssessment {
|
||||
status,
|
||||
justification: (status == VexStatus::NotAffected)
|
||||
.then_some(VexJustification::VulnerableCodeNotInExecutePath),
|
||||
impact_statement: None,
|
||||
action_statement: None,
|
||||
by: "u1".into(),
|
||||
by_name: None,
|
||||
at: chrono::Utc::now(),
|
||||
by_scan: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_vex_comment_names_the_status_and_the_reason() {
|
||||
let comment = vex_comment(&vex(VexStatus::NotAffected));
|
||||
assert!(
|
||||
comment.contains("VEX status `not_affected` (vulnerable_code_not_in_execute_path)."),
|
||||
"{comment}"
|
||||
);
|
||||
let mut stated = vex(VexStatus::NotAffected);
|
||||
stated.justification = None;
|
||||
stated.impact_statement = Some(" The parser is not built. ".into());
|
||||
assert!(vex_comment(&stated).contains("`not_affected`: The parser is not built."));
|
||||
assert!(vex_comment(&vex(VexStatus::Fixed)).contains("VEX status `fixed`. Closed"));
|
||||
}
|
||||
|
||||
/// A tenant database for one test, or `None` (the test skips) without
|
||||
/// MongoDB.
|
||||
async fn test_db(tenant: &str) -> Option<(crate::database::DatabasePool, Database)> {
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let prefix = format!(
|
||||
"cvevex_{}",
|
||||
&uuid::Uuid::new_v4().simple().to_string()[..10]
|
||||
);
|
||||
let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else {
|
||||
eprintln!("SKIP cve_issues: no MongoDB reachable at {uri}");
|
||||
return None;
|
||||
};
|
||||
let db = pool.for_tenant_id(tenant).await.unwrap();
|
||||
Some((pool, db))
|
||||
}
|
||||
|
||||
fn tracker_at(base: String) -> TrackerDispatch {
|
||||
TrackerDispatch::Gitea(
|
||||
GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
fn vex_target<'a>(
|
||||
db: &'a Database,
|
||||
tracker: &'a TrackerDispatch,
|
||||
autoclose: IssueAutoclose,
|
||||
) -> CveIssueTarget<'a> {
|
||||
CveIssueTarget {
|
||||
db,
|
||||
tenant_id: "cve-issues-vex",
|
||||
tracker,
|
||||
owner: "kunde",
|
||||
repo: "app",
|
||||
target_id: "target-1",
|
||||
dashboard: "",
|
||||
epss_percentile: None,
|
||||
autoclose,
|
||||
}
|
||||
}
|
||||
|
||||
fn closed(n: u32) -> CveIssueCounts {
|
||||
CveIssueCounts {
|
||||
closed: n,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_vex_not_affected_or_fixed_closes_the_issue_until_it_is_withdrawn() {
|
||||
let Some((pool, db)) = test_db("cve-issues-vex").await else {
|
||||
return;
|
||||
};
|
||||
let calls: Calls = Arc::default();
|
||||
let tracker = tracker_at(fake_gitea(calls.clone()).await);
|
||||
let target = vex_target(&db, &tracker, IssueAutoclose::On);
|
||||
let mut okhttp = alert("okhttp", "3.12.0", "GHSA-3cqm-mf7h-prrj", "HIGH");
|
||||
let mut settled = alert("log4j-core", "2.14.1", "GHSA-jfh8-c2jp-5v3q", "CRITICAL");
|
||||
settled.aliases = vec!["CVE-2021-44228".into()];
|
||||
settled.vex = Some(vex(VexStatus::Fixed));
|
||||
|
||||
// A settled CVE opens no issue; the unsettled one opens one.
|
||||
let counts = sync_cve_issues(&target, &[okhttp.clone(), settled.clone()], true)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
counts,
|
||||
CveIssueCounts {
|
||||
created: 1,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
assert!(calls.lock().unwrap()[0].contains("okhttp@3.12.0"));
|
||||
|
||||
// Stated not_affected: closed with the status and the reason, even
|
||||
// after an incomplete scan, and only once.
|
||||
okhttp.vex = Some(vex(VexStatus::NotAffected));
|
||||
let both = [okhttp.clone(), settled.clone()];
|
||||
assert_eq!(
|
||||
sync_cve_issues(&target, &both, false).await.unwrap(),
|
||||
closed(1)
|
||||
);
|
||||
{
|
||||
let calls = calls.lock().unwrap();
|
||||
let comment = &calls[calls.len() - 2];
|
||||
assert!(comment.starts_with("comment 100: "), "{comment}");
|
||||
assert!(
|
||||
comment.contains("`not_affected` (vulnerable_code_not_in_execute_path)"),
|
||||
"{comment}"
|
||||
);
|
||||
assert_eq!(calls.last().unwrap(), "state 100: \"closed\"");
|
||||
}
|
||||
assert_eq!(
|
||||
sync_cve_issues(&target, &both, true).await.unwrap(),
|
||||
CveIssueCounts::default()
|
||||
);
|
||||
|
||||
// Withdrawn (back under investigation): the same issue is reopened,
|
||||
// not opened twice.
|
||||
okhttp.vex = Some(vex(VexStatus::UnderInvestigation));
|
||||
assert_eq!(
|
||||
sync_cve_issues(&target, &[okhttp.clone(), settled], true)
|
||||
.await
|
||||
.unwrap(),
|
||||
CveIssueCounts {
|
||||
reopened: 1,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
assert_eq!(calls.lock().unwrap().last().unwrap(), "state 100: \"open\"");
|
||||
assert_eq!(
|
||||
db.tracker_issues().count_documents(doc! {}).await.unwrap(),
|
||||
1
|
||||
);
|
||||
|
||||
pool.drop_tenant("cve-issues-vex").await.ok();
|
||||
}
|
||||
|
||||
/// Log lines written while the returned guard lives (on this thread; a
|
||||
/// `#[tokio::test]` runs on one).
|
||||
fn capture_logs() -> (Arc<Mutex<Vec<u8>>>, tracing::subscriber::DefaultGuard) {
|
||||
let buffer: Arc<Mutex<Vec<u8>>> = Arc::default();
|
||||
let writer = buffer.clone();
|
||||
let subscriber = tracing_subscriber::fmt()
|
||||
.with_ansi(false)
|
||||
.with_max_level(tracing::Level::INFO)
|
||||
.with_writer(move || LogWriter(writer.clone()))
|
||||
.finish();
|
||||
(buffer, tracing::subscriber::set_default(subscriber))
|
||||
}
|
||||
|
||||
struct LogWriter(Arc<Mutex<Vec<u8>>>);
|
||||
|
||||
impl std::io::Write for LogWriter {
|
||||
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||
self.0.lock().unwrap().extend_from_slice(bytes);
|
||||
Ok(bytes.len())
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The autoclose summary lines logged into `logs`.
|
||||
fn summaries(logs: &Mutex<Vec<u8>>) -> Vec<String> {
|
||||
String::from_utf8_lossy(&logs.lock().unwrap())
|
||||
.lines()
|
||||
.filter(|l| l.contains("CVE issues settled by VEX"))
|
||||
.map(str::to_owned)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn autoclose_off_and_dry_run_leave_the_issue_open() {
|
||||
let Some((pool, db)) = test_db("cve-issues-vex-off").await else {
|
||||
return;
|
||||
};
|
||||
let (logs, _guard) = capture_logs();
|
||||
let calls: Calls = Arc::default();
|
||||
let tracker = tracker_at(fake_gitea(calls.clone()).await);
|
||||
let mut okhttp = alert("okhttp", "3.12.0", "GHSA-3cqm-mf7h-prrj", "HIGH");
|
||||
let open = vex_target(&db, &tracker, IssueAutoclose::Off);
|
||||
assert_eq!(
|
||||
sync_cve_issues(&open, std::slice::from_ref(&okhttp), true)
|
||||
.await
|
||||
.unwrap()
|
||||
.created,
|
||||
1
|
||||
);
|
||||
let before = calls.lock().unwrap().len();
|
||||
|
||||
// Off: the settled CVE's issue stays open, nothing is called.
|
||||
okhttp.vex = Some(vex(VexStatus::Fixed));
|
||||
let found = std::slice::from_ref(&okhttp);
|
||||
assert_eq!(
|
||||
sync_cve_issues(&open, found, true).await.unwrap(),
|
||||
CveIssueCounts::default()
|
||||
);
|
||||
assert_eq!(calls.lock().unwrap().len(), before);
|
||||
// Off logs no summary.
|
||||
assert!(summaries(&logs).is_empty());
|
||||
|
||||
// Dry run, against a Gitea that refuses every write: only counted,
|
||||
// and a target with nothing to close says so too.
|
||||
let writes: Calls = Arc::default();
|
||||
let read_only = tracker_at(read_only_gitea(writes.clone()).await);
|
||||
let dry = vex_target(&db, &read_only, IssueAutoclose::DryRun);
|
||||
assert_eq!(
|
||||
sync_cve_issues(&dry, found, true).await.unwrap(),
|
||||
CveIssueCounts::default()
|
||||
);
|
||||
assert!(writes.lock().unwrap().is_empty(), "{:?}", writes.lock());
|
||||
let other = CveIssueTarget {
|
||||
target_id: "target-2",
|
||||
..vex_target(&db, &read_only, IssueAutoclose::DryRun)
|
||||
};
|
||||
sync_cve_issues(&other, &[], true).await.unwrap();
|
||||
let lines = summaries(&logs);
|
||||
assert_eq!(lines.len(), 2, "{lines:?}");
|
||||
assert!(
|
||||
lines[0].contains("tenant_id=\"cve-issues-vex\"")
|
||||
&& lines[0].contains("target_id=\"target-1\"")
|
||||
&& lines[0].contains("would_close=1 not_affected=0 fixed=1"),
|
||||
"{}",
|
||||
lines[0]
|
||||
);
|
||||
assert!(
|
||||
lines[1].contains("target_id=\"target-2\"") && lines[1].contains("would_close=0"),
|
||||
"{}",
|
||||
lines[1]
|
||||
);
|
||||
// No title or path in the line.
|
||||
assert!(!lines[0].contains("okhttp"), "{}", lines[0]);
|
||||
assert_eq!(
|
||||
db.tracker_issues()
|
||||
.count_documents(doc! { "status": "open" })
|
||||
.await
|
||||
.unwrap(),
|
||||
1
|
||||
);
|
||||
|
||||
pool.drop_tenant("cve-issues-vex-off").await.ok();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn autoclose_closes_at_most_twenty_per_scan() {
|
||||
let Some((pool, db)) = test_db("cve-issues-vex-many").await else {
|
||||
return;
|
||||
};
|
||||
let calls: Calls = Arc::default();
|
||||
let tracker = tracker_at(fake_gitea(calls.clone()).await);
|
||||
let target = vex_target(&db, &tracker, IssueAutoclose::On);
|
||||
let mut alerts: Vec<CveAlert> = (0..22)
|
||||
.map(|i| {
|
||||
let mut a = alert(
|
||||
&format!("lib{i:02}"),
|
||||
"1.0",
|
||||
&format!("CVE-2026-{i:04}"),
|
||||
"HIGH",
|
||||
);
|
||||
a.aliases.clear();
|
||||
a
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
sync_cve_issues(&target, &alerts, true)
|
||||
.await
|
||||
.unwrap()
|
||||
.created,
|
||||
22
|
||||
);
|
||||
|
||||
for a in &mut alerts {
|
||||
a.vex = Some(vex(VexStatus::NotAffected));
|
||||
}
|
||||
assert_eq!(
|
||||
sync_cve_issues(&target, &alerts, true).await.unwrap(),
|
||||
closed(20)
|
||||
);
|
||||
assert_eq!(
|
||||
sync_cve_issues(&target, &alerts, true).await.unwrap(),
|
||||
closed(2)
|
||||
);
|
||||
assert_eq!(
|
||||
sync_cve_issues(&target, &alerts, true).await.unwrap(),
|
||||
CveIssueCounts::default()
|
||||
);
|
||||
|
||||
pool.drop_tenant("cve-issues-vex-many").await.ok();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
//! A notification for every CVE a target's components newly carry, shared by
|
||||
//! the scans (every SBOM source: source, firmware, CODESYS libraries and
|
||||
//! runtime) and the hourly CVE monitor.
|
||||
//!
|
||||
//! One notification per CVE, target, package and version. An alert a VEX
|
||||
//! statement settles (`not_affected` or `fixed`, see
|
||||
//! [`CveAlert::is_resolved_by_vex`]) raises none; once the statement is
|
||||
//! withdrawn, the next scan or monitor run raises it as for any new CVE.
|
||||
|
||||
use mongodb::bson::doc;
|
||||
|
||||
use compliance_core::models::notification::{parse_severity, CveNotification};
|
||||
use compliance_core::models::CveAlert;
|
||||
|
||||
use crate::database::Database;
|
||||
|
||||
/// Create the notifications `alerts` of the target `repo_id` (named
|
||||
/// `repo_name`) do not have yet. The alerts carry their stored VEX statement
|
||||
/// ([`crate::pipeline::vex_lifecycle::attach_stored_vex`]).
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// How many notifications were created. A notification that cannot be stored
|
||||
/// is logged and skipped.
|
||||
pub async fn notify_new_cves(
|
||||
db: &Database,
|
||||
repo_id: &str,
|
||||
repo_name: &str,
|
||||
alerts: &[CveAlert],
|
||||
) -> u32 {
|
||||
let mut created = 0;
|
||||
for alert in alerts.iter().filter(|a| !a.is_resolved_by_vex()) {
|
||||
let filter = doc! {
|
||||
"cve_id": &alert.cve_id,
|
||||
"repo_id": &alert.repo_id,
|
||||
"package_name": &alert.affected_package,
|
||||
"package_version": &alert.affected_version,
|
||||
};
|
||||
let severity = parse_severity(alert.severity.as_deref(), alert.cvss_score);
|
||||
let mut notification = CveNotification::new(
|
||||
alert.cve_id.clone(),
|
||||
repo_id.to_string(),
|
||||
repo_name.to_string(),
|
||||
alert.affected_package.clone(),
|
||||
alert.affected_version.clone(),
|
||||
severity,
|
||||
);
|
||||
notification.cvss_score = alert.cvss_score;
|
||||
notification.summary = alert.summary.clone();
|
||||
notification.url = Some(format!("https://osv.dev/vulnerability/{}", alert.cve_id));
|
||||
let notification = match mongodb::bson::to_bson(¬ification) {
|
||||
Ok(n) => n,
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
cve = alert.cve_id,
|
||||
"could not encode the CVE notification: {e}"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
// Inserted only when missing (`$setOnInsert`), so a notification
|
||||
// that was read or dismissed stays as it is.
|
||||
match db
|
||||
.cve_notifications()
|
||||
.update_one(filter, doc! { "$setOnInsert": notification })
|
||||
.upsert(true)
|
||||
.await
|
||||
{
|
||||
Ok(result) if result.upserted_id.is_some() => created += 1,
|
||||
Ok(_) => {}
|
||||
Err(e) => tracing::warn!(
|
||||
cve = alert.cve_id,
|
||||
"could not store the CVE notification: {e}"
|
||||
),
|
||||
}
|
||||
}
|
||||
created
|
||||
}
|
||||
@@ -494,7 +494,7 @@ fn check_frameworks(root: &Path, today: chrono::NaiveDate) -> Vec<Hit> {
|
||||
),
|
||||
remediation: "Retarget the project to a supported version (.NET Framework \
|
||||
4.8/4.8.1, or a supported .NET release) and test it there.",
|
||||
severity: Severity::Medium,
|
||||
severity: Severity::High,
|
||||
cwe: "CWE-1104",
|
||||
path: project.path.clone(),
|
||||
line: Some(tf.line),
|
||||
@@ -677,6 +677,8 @@ mod tests {
|
||||
["dotnet-framework-end-of-support Legacy/Legacy.csproj:3"]
|
||||
);
|
||||
assert_eq!(hits[0].cwe, "CWE-1104");
|
||||
// End of life is high, like every other end-of-life finding.
|
||||
assert_eq!(hits[0].severity, Severity::High);
|
||||
assert!(
|
||||
hits[0].title.contains(".NET Framework 4.5"),
|
||||
"{}",
|
||||
|
||||
@@ -5,6 +5,7 @@ use git2::{Cred, FetchOptions, RemoteCallbacks, RemoteRedirect, Repository};
|
||||
use compliance_core::NetGuard;
|
||||
|
||||
use crate::error::AgentError;
|
||||
use crate::pipeline::git_retry::Backoff;
|
||||
use crate::tenant_path::{name_segment, tenant_segment};
|
||||
|
||||
/// The directory a tenant's checkout of `repo_name` lives in.
|
||||
@@ -173,6 +174,8 @@ pub struct GitOps {
|
||||
net_guard: NetGuard,
|
||||
/// How long and how large a clone or fetch may be.
|
||||
limits: CloneLimits,
|
||||
/// When a clone or fetch the host failed briefly is tried again.
|
||||
backoff: Backoff,
|
||||
}
|
||||
|
||||
impl GitOps {
|
||||
@@ -188,6 +191,7 @@ impl GitOps {
|
||||
credentials,
|
||||
net_guard,
|
||||
limits: CloneLimits::from_env(),
|
||||
backoff: Backoff::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,6 +202,18 @@ impl GitOps {
|
||||
self
|
||||
}
|
||||
|
||||
/// The same operations with another retry schedule (tests).
|
||||
#[cfg(test)]
|
||||
fn with_backoff(mut self, backoff: Backoff) -> Self {
|
||||
self.backoff = backoff;
|
||||
self
|
||||
}
|
||||
|
||||
/// When this instance tries a failed clone or fetch again.
|
||||
pub(crate) fn backoff(&self) -> &Backoff {
|
||||
&self.backoff
|
||||
}
|
||||
|
||||
/// Fetch options for one bounded transfer: the credentials, no
|
||||
/// redirects, and a progress check that stops the transfer once it
|
||||
/// exceeds [`CloneLimits`], leaving the reason in `stopped`.
|
||||
@@ -282,6 +298,11 @@ impl GitOps {
|
||||
#[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> {
|
||||
reject_ssh_url(git_url)?;
|
||||
// At most two clones or fetches per git host, held to the end of this
|
||||
// one; a refused remote has no host and fails below anyway.
|
||||
let _host_slot = self
|
||||
.remote_host(git_url)
|
||||
.map(|host| crate::pipeline::clone_limit::CLONE_SLOTS.acquire(&host));
|
||||
// Per tenant: two tenants with the same target name get two checkouts.
|
||||
let repo_path = self.clone_path(repo_name);
|
||||
|
||||
@@ -290,7 +311,8 @@ impl GitOps {
|
||||
// every scan after it (#486).
|
||||
if repo_path.exists() && prepare_entry(&repo_path) {
|
||||
tracing::info!("fetching updates for existing repo");
|
||||
match self.fetch(&repo_path) {
|
||||
// A 502 is retried before it can be taken for a broken entry.
|
||||
match self.backoff.retry("fetch", || self.fetch(&repo_path)) {
|
||||
Ok(()) => return Ok(repo_path),
|
||||
Err(AgentError::Git(e)) if is_corruption(&e) => {
|
||||
tracing::warn!(
|
||||
@@ -315,7 +337,8 @@ impl GitOps {
|
||||
// Before creating anything: a refused remote must not leave an entry
|
||||
// behind for the next run to try to fetch.
|
||||
self.check_remote(git_url)?;
|
||||
self.clone_atomically(git_url, &repo_path)?;
|
||||
self.backoff
|
||||
.retry("clone", || self.clone_atomically(git_url, &repo_path))?;
|
||||
tracing::info!("Cloned {git_url} to {}", repo_path.display());
|
||||
Ok(repo_path)
|
||||
}
|
||||
@@ -833,6 +856,44 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clone_the_host_answers_with_502_is_tried_four_times() {
|
||||
// A git host that answers every request with 502, counting them.
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
|
||||
let port = listener.local_addr().expect("addr").port();
|
||||
let requests = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let counted = std::sync::Arc::clone(&requests);
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming() {
|
||||
let Ok(mut stream) = stream else { break };
|
||||
counted.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
let mut buf = [0u8; 4096];
|
||||
let _ = std::io::Read::read(&mut stream, &mut buf);
|
||||
let _ = std::io::Write::write_all(
|
||||
&mut stream,
|
||||
b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
|
||||
);
|
||||
}
|
||||
});
|
||||
let scratch =
|
||||
Scratch(std::env::temp_dir().join(format!("cs-git-{}", uuid::Uuid::new_v4())));
|
||||
let ops = GitOps::new(
|
||||
&scratch.0.to_string_lossy(),
|
||||
"tenant-a",
|
||||
RepoCredentials::default(),
|
||||
NetGuard::allow_private(),
|
||||
)
|
||||
.with_backoff(crate::pipeline::git_retry::Backoff::immediate());
|
||||
|
||||
let err = ops
|
||||
.clone_or_fetch(&format!("http://127.0.0.1:{port}/org/repo.git"), "flaky")
|
||||
.expect_err("the host never recovers");
|
||||
|
||||
assert!(err.to_string().contains("502"), "{err}");
|
||||
assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 4);
|
||||
assert!(!ops.clone_path("flaky").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fetch_rechecks_the_stored_remote() {
|
||||
// An existing checkout whose `origin` now points somewhere private (a
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
//! Retrying a clone or fetch the git host failed for a passing reason.
|
||||
//!
|
||||
//! A git host that restarts (an OOM kill, a redeploy) answers `502` or
|
||||
//! refuses connections for a few seconds; every scan that clones in that
|
||||
//! window would fail. A clone or fetch that fails with a 5xx status or a
|
||||
//! network error is tried again after 5, 15 and 30 seconds. One that fails
|
||||
//! for a reason another try cannot change (authentication, 403, 404, a
|
||||
//! missing reference, a download limit) fails at once.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use git2::{ErrorClass, ErrorCode};
|
||||
|
||||
use crate::error::AgentError;
|
||||
|
||||
/// The waits between the tries of one clone or fetch: one retry per entry.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Backoff {
|
||||
schedule: [Duration; 3],
|
||||
}
|
||||
|
||||
impl Default for Backoff {
|
||||
/// Three retries, after 5, 15 and 30 seconds.
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
schedule: [5, 15, 30].map(Duration::from_secs),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Backoff {
|
||||
/// The same number of retries without waiting (tests).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn immediate() -> Self {
|
||||
Self {
|
||||
schedule: [Duration::ZERO; 3],
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `op`, and run it again after each wait of the schedule while it
|
||||
/// fails with a [transient](is_transient) error.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `what` - What `op` does, for the log (`"clone"`, `"fetch"`).
|
||||
/// * `op` - The clone or fetch; it must be safe to run again after it failed.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The first error that is not transient, or the last one once the
|
||||
/// schedule is used up.
|
||||
pub fn retry<T>(
|
||||
&self,
|
||||
what: &str,
|
||||
mut op: impl FnMut() -> Result<T, AgentError>,
|
||||
) -> Result<T, AgentError> {
|
||||
// `iter()` yields `&Duration`, one wait per retry, in order.
|
||||
let mut waits = self.schedule.iter();
|
||||
let mut attempt = 1;
|
||||
loop {
|
||||
match op() {
|
||||
Ok(value) => return Ok(value),
|
||||
Err(error) => {
|
||||
let Some(wait) = waits.next().filter(|_| is_retryable(&error)) else {
|
||||
return Err(error);
|
||||
};
|
||||
tracing::warn!(
|
||||
attempt,
|
||||
wait_secs = wait.as_secs(),
|
||||
error = %error,
|
||||
"git {what} failed for a passing reason; trying again"
|
||||
);
|
||||
sleep(*wait);
|
||||
attempt += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `error` is a git error another try may not see.
|
||||
fn is_retryable(error: &AgentError) -> bool {
|
||||
matches!(error, AgentError::Git(e) if is_transient(e))
|
||||
}
|
||||
|
||||
/// Whether a git error comes from the host or the network being briefly
|
||||
/// unavailable: a 5xx status, a timeout, or a connection that failed.
|
||||
pub fn is_transient(error: &git2::Error) -> bool {
|
||||
if error.code() == ErrorCode::Auth {
|
||||
return false;
|
||||
}
|
||||
if error.code() == ErrorCode::Timeout {
|
||||
return true;
|
||||
}
|
||||
match error.class() {
|
||||
// libgit2: "unexpected http status code: 502".
|
||||
ErrorClass::Http => error
|
||||
.message()
|
||||
.strip_prefix("unexpected http status code: ")
|
||||
.and_then(|status| status.trim().parse::<u16>().ok())
|
||||
.is_some_and(|status| (500..=599).contains(&status)),
|
||||
// Every network error libgit2 raises is a failed connection, read or
|
||||
// write, except these three about the URL itself.
|
||||
ErrorClass::Net => !["invalid url", "invalid scp-style path", "cannot redirect"]
|
||||
.iter()
|
||||
.any(|prefix| error.message().starts_with(prefix)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait `duration` on this thread, without stalling the async runtime's
|
||||
/// other tasks (clones run on its worker threads).
|
||||
fn sleep(duration: Duration) {
|
||||
if !duration.is_zero() {
|
||||
crate::pipeline::clone_limit::off_the_runtime(|| std::thread::sleep(duration));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::{is_transient, Backoff};
|
||||
use crate::error::AgentError;
|
||||
use git2::{ErrorClass, ErrorCode};
|
||||
|
||||
fn git_error(code: ErrorCode, class: ErrorClass, message: &str) -> git2::Error {
|
||||
git2::Error::new(code, class, message)
|
||||
}
|
||||
|
||||
fn http_status(status: u16) -> git2::Error {
|
||||
git_error(
|
||||
ErrorCode::GenericError,
|
||||
ErrorClass::Http,
|
||||
&format!("unexpected http status code: {status}"),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_5xx_status_is_transient() {
|
||||
assert!(is_transient(&http_status(502)));
|
||||
assert!(is_transient(&http_status(503)));
|
||||
assert!(is_transient(&http_status(500)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_connection_or_timeout_is_transient() {
|
||||
let refused = git_error(
|
||||
ErrorCode::GenericError,
|
||||
ErrorClass::Net,
|
||||
"failed to connect to git.example.com: Connection refused",
|
||||
);
|
||||
let timeout = git_error(
|
||||
ErrorCode::Timeout,
|
||||
ErrorClass::Net,
|
||||
"could not read from socket: timed out",
|
||||
);
|
||||
let unresolved = git_error(
|
||||
ErrorCode::GenericError,
|
||||
ErrorClass::Net,
|
||||
"failed to resolve address for git.example.com: Name or service not known",
|
||||
);
|
||||
assert!(is_transient(&refused));
|
||||
assert!(is_transient(&timeout));
|
||||
assert!(is_transient(&unresolved));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auth_not_found_and_bad_refs_are_not_transient() {
|
||||
let unauthorized = git_error(
|
||||
ErrorCode::Auth,
|
||||
ErrorClass::Http,
|
||||
"unexpected authentication failure",
|
||||
);
|
||||
let missing_ref = git_error(
|
||||
ErrorCode::NotFound,
|
||||
ErrorClass::Reference,
|
||||
"reference 'refs/heads/nope' not found",
|
||||
);
|
||||
let bad_url = git_error(ErrorCode::GenericError, ErrorClass::Net, "invalid url: x");
|
||||
let redirect = git_error(
|
||||
ErrorCode::GenericError,
|
||||
ErrorClass::Net,
|
||||
"cannot redirect from 'a' to 'b'",
|
||||
);
|
||||
assert!(!is_transient(&unauthorized));
|
||||
assert!(!is_transient(&http_status(401)));
|
||||
assert!(!is_transient(&http_status(403)));
|
||||
assert!(!is_transient(&http_status(404)));
|
||||
assert!(!is_transient(&missing_ref));
|
||||
assert!(!is_transient(&bad_url));
|
||||
assert!(!is_transient(&redirect));
|
||||
}
|
||||
|
||||
/// An operation that fails with `error` its first `failures` runs, and
|
||||
/// how often it ran.
|
||||
fn run_failing(failures: usize, error: fn() -> AgentError) -> (Result<u8, AgentError>, usize) {
|
||||
let mut runs = 0;
|
||||
let result = Backoff::immediate().retry("fetch", || {
|
||||
runs += 1;
|
||||
if runs <= failures {
|
||||
Err(error())
|
||||
} else {
|
||||
Ok(7)
|
||||
}
|
||||
});
|
||||
(result, runs)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_502s_then_success_succeeds_on_the_third_try() {
|
||||
let (result, runs) = run_failing(2, || AgentError::Git(http_status(502)));
|
||||
assert_eq!(result.unwrap(), 7);
|
||||
assert_eq!(runs, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn four_502s_fail_after_three_retries() {
|
||||
let (result, runs) = run_failing(4, || AgentError::Git(http_status(502)));
|
||||
assert!(matches!(result, Err(AgentError::Git(e)) if e.message().contains("502")));
|
||||
assert_eq!(runs, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_permanent_error_is_not_retried() {
|
||||
let (result, runs) = run_failing(4, || AgentError::Git(http_status(404)));
|
||||
assert!(result.is_err());
|
||||
assert_eq!(runs, 1);
|
||||
let (limit, runs) = run_failing(4, || AgentError::Other("download limit".to_string()));
|
||||
assert!(limit.is_err());
|
||||
assert_eq!(runs, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_schedule_waits_5_15_and_30_seconds() {
|
||||
let secs = Backoff::default().schedule.map(|d| d.as_secs());
|
||||
assert_eq!(secs, [5, 15, 30]);
|
||||
}
|
||||
}
|
||||
@@ -91,10 +91,12 @@ impl GitOps {
|
||||
} else {
|
||||
&anonymous
|
||||
};
|
||||
let mut options = SubmoduleUpdateOptions::new();
|
||||
options.fetch(credentials.fetch_options());
|
||||
submodule.update(true, Some(&mut options))?;
|
||||
Ok(())
|
||||
self.backoff().retry("submodule fetch", || {
|
||||
let mut options = SubmoduleUpdateOptions::new();
|
||||
options.fetch(credentials.fetch_options());
|
||||
submodule.update(true, Some(&mut options))?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,563 @@
|
||||
//! The issue catch-up (`ISSUE_CATCHUP`).
|
||||
//!
|
||||
//! A scan opens issues only for the findings it stores new, so a finding
|
||||
//! whose issue could not be opened (a failed listing, a refused create)
|
||||
//! never got one later. After a scan's own issues, the catch-up goes through
|
||||
//! the target's open medium+ findings without an issue: one that has an issue
|
||||
//! already (by fingerprint marker, then title, as in
|
||||
//! [`super::issue_creation`]) is linked to it, the others get a new one, at
|
||||
//! most [`MAX_NEW_ISSUES`] per scan, highest severity and oldest first. The
|
||||
//! rest wait for the next scans. Gitea only: it matches against the listing
|
||||
//! the scan made anyway; the other trackers would need a search per finding.
|
||||
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
use compliance_core::config::IssueCatchup;
|
||||
use compliance_core::models::{Finding, Severity};
|
||||
use futures_util::TryStreamExt;
|
||||
use mongodb::bson::doc;
|
||||
|
||||
use super::issue_creation::{
|
||||
issue_title, wants_issue, ExistingIssues, IssueSink, KnownIssue, ISSUE_SEVERITIES,
|
||||
ISSUE_STATUSES,
|
||||
};
|
||||
use crate::error::AgentError;
|
||||
|
||||
/// New issues the catch-up opens per target and scan; links are not counted.
|
||||
pub(super) const MAX_NEW_ISSUES: usize = 20;
|
||||
|
||||
/// A count per severity, highest first when shown.
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub(super) struct SeverityCounts(BTreeMap<Severity, u32>);
|
||||
|
||||
impl SeverityCounts {
|
||||
/// Count one finding of `severity`.
|
||||
fn add(&mut self, severity: &Severity) {
|
||||
*self.0.entry(severity.clone()).or_default() += 1;
|
||||
}
|
||||
|
||||
/// All counted.
|
||||
pub(super) fn total(&self) -> u32 {
|
||||
self.0.values().sum()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for SeverityCounts {
|
||||
/// `critical=1 high=3`, or `-` when nothing was counted.
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
if self.0.is_empty() {
|
||||
return f.write_str("-");
|
||||
}
|
||||
let parts: Vec<String> = self
|
||||
.0
|
||||
.iter()
|
||||
.rev()
|
||||
.map(|(severity, n)| format!("{severity}={n}"))
|
||||
.collect();
|
||||
f.write_str(&parts.join(" "))
|
||||
}
|
||||
}
|
||||
|
||||
/// What a catch-up does, decided before any request.
|
||||
#[derive(Debug, Default)]
|
||||
struct CatchupPlan<'a> {
|
||||
/// Findings whose issue exists, with it.
|
||||
link: Vec<(&'a Finding, &'a KnownIssue)>,
|
||||
/// Findings that get a new issue, at most the cap.
|
||||
create: Vec<&'a Finding>,
|
||||
/// Findings past the cap: their issues wait for the next scans.
|
||||
deferred: SeverityCounts,
|
||||
}
|
||||
|
||||
/// What a catch-up did on one target (in a dry run: would do).
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub(super) struct CatchupSummary {
|
||||
pub(super) mode: IssueCatchup,
|
||||
pub(super) created: SeverityCounts,
|
||||
pub(super) linked: SeverityCounts,
|
||||
pub(super) deferred: SeverityCounts,
|
||||
/// Issues the tracker refused.
|
||||
pub(super) failed: u32,
|
||||
}
|
||||
|
||||
impl CatchupSummary {
|
||||
/// Log the one line per target: counts and severities, never a title or
|
||||
/// a path.
|
||||
pub(super) fn log(&self, tenant_id: &str, target_id: &str) {
|
||||
let what = match self.mode {
|
||||
IssueCatchup::DryRun => "issue catch-up (dry run, nothing changed)",
|
||||
IssueCatchup::Off | IssueCatchup::On => "issue catch-up",
|
||||
};
|
||||
tracing::info!(
|
||||
tenant_id,
|
||||
target_id,
|
||||
mode = self.mode.as_str(),
|
||||
created = self.created.total(),
|
||||
created_severities = %self.created,
|
||||
linked = self.linked.total(),
|
||||
linked_severities = %self.linked,
|
||||
deferred = self.deferred.total(),
|
||||
deferred_severities = %self.deferred,
|
||||
failed = self.failed,
|
||||
"{what}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the catch-up for the target of `sink` against `index`, the listing
|
||||
/// of its repository's issues (with the scan's new issues added).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The target's findings cannot be read.
|
||||
pub(super) async fn catch_up(
|
||||
sink: &IssueSink<'_>,
|
||||
index: &ExistingIssues,
|
||||
mode: IssueCatchup,
|
||||
) -> Result<CatchupSummary, AgentError> {
|
||||
let candidates = select(load_candidates(sink).await?);
|
||||
Ok(run(sink, &candidates, index, mode).await)
|
||||
}
|
||||
|
||||
/// The target's open medium+ findings without an issue, as stored.
|
||||
async fn load_candidates(sink: &IssueSink<'_>) -> Result<Vec<Finding>, AgentError> {
|
||||
let severities: Vec<String> = ISSUE_SEVERITIES.iter().map(Severity::to_string).collect();
|
||||
let statuses: Vec<String> = ISSUE_STATUSES.iter().map(ToString::to_string).collect();
|
||||
// `tracker_issue_url: null` matches a missing field too.
|
||||
let findings = sink
|
||||
.db
|
||||
.findings()
|
||||
.find(doc! {
|
||||
"repo_id": sink.repo_id,
|
||||
"tracker_issue_url": null,
|
||||
"severity": { "$in": severities },
|
||||
"status": { "$in": statuses },
|
||||
})
|
||||
.await?
|
||||
.try_collect()
|
||||
.await?;
|
||||
Ok(findings)
|
||||
}
|
||||
|
||||
/// The findings that want an issue and have none, highest severity first,
|
||||
/// then oldest first.
|
||||
fn select(findings: Vec<Finding>) -> Vec<Finding> {
|
||||
let mut candidates: Vec<Finding> = findings
|
||||
.into_iter()
|
||||
.filter(|f| wants_issue(f) && f.tracker_issue_url.is_none())
|
||||
.collect();
|
||||
candidates.sort_by(|a, b| {
|
||||
b.severity
|
||||
.cmp(&a.severity)
|
||||
.then(a.created_at.cmp(&b.created_at))
|
||||
});
|
||||
candidates
|
||||
}
|
||||
|
||||
/// Decide for each of `candidates` (in order): link it to its issue in
|
||||
/// `index`, give it a new one while fewer than `cap` are planned, or defer
|
||||
/// it. A single finding with the title of an issue planned here is left for
|
||||
/// the next scan, which links it to that issue (as the scan's own issue
|
||||
/// creation never opens two issues of one title).
|
||||
fn plan<'a>(candidates: &'a [Finding], index: &'a ExistingIssues, cap: usize) -> CatchupPlan<'a> {
|
||||
let mut plan = CatchupPlan::default();
|
||||
let mut planned_titles = HashSet::new();
|
||||
for finding in candidates {
|
||||
let title = issue_title(finding);
|
||||
if let Some(known) = index.find(finding, &title) {
|
||||
plan.link.push((finding, known));
|
||||
} else if finding.occurrences.is_empty() && planned_titles.contains(&title) {
|
||||
continue;
|
||||
} else if plan.create.len() < cap {
|
||||
planned_titles.insert(title);
|
||||
plan.create.push(finding);
|
||||
} else {
|
||||
plan.deferred.add(&finding.severity);
|
||||
}
|
||||
}
|
||||
plan
|
||||
}
|
||||
|
||||
/// Plan the catch-up of `candidates` and, when `mode` is on, carry it out.
|
||||
async fn run(
|
||||
sink: &IssueSink<'_>,
|
||||
candidates: &[Finding],
|
||||
index: &ExistingIssues,
|
||||
mode: IssueCatchup,
|
||||
) -> CatchupSummary {
|
||||
let plan = plan(candidates, index, MAX_NEW_ISSUES);
|
||||
let mut summary = CatchupSummary {
|
||||
mode,
|
||||
deferred: plan.deferred,
|
||||
..CatchupSummary::default()
|
||||
};
|
||||
match mode {
|
||||
IssueCatchup::Off => {}
|
||||
IssueCatchup::DryRun => {
|
||||
plan.link
|
||||
.iter()
|
||||
.for_each(|(f, _)| summary.linked.add(&f.severity));
|
||||
plan.create
|
||||
.iter()
|
||||
.for_each(|f| summary.created.add(&f.severity));
|
||||
}
|
||||
IssueCatchup::On => {
|
||||
for (finding, known) in plan.link {
|
||||
sink.link(finding, &issue_title(finding), known).await;
|
||||
summary.linked.add(&finding.severity);
|
||||
}
|
||||
for finding in plan.create {
|
||||
match sink.open(finding, &issue_title(finding)).await {
|
||||
Ok(_) => summary.created.add(&finding.severity),
|
||||
Err(e) => {
|
||||
summary.failed += 1;
|
||||
tracing::warn!(
|
||||
"[{}] Catch-up issue for {} not created: {e}",
|
||||
sink.repo_id,
|
||||
finding.fingerprint
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
summary
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use axum::extract::State;
|
||||
use axum::routing::get;
|
||||
use axum::{Json, Router};
|
||||
use chrono::{Duration, Utc};
|
||||
use compliance_core::models::{FindingStatus, ScanType, TrackerIssue};
|
||||
use compliance_core::NetGuard;
|
||||
use secrecy::SecretString;
|
||||
|
||||
use super::*;
|
||||
use crate::database::Database;
|
||||
use crate::pipeline::issue_creation::format_issue_body;
|
||||
use crate::pipeline::tracker_dispatch::TrackerDispatch;
|
||||
use crate::trackers::gitea::{GiteaIssue, GiteaTracker};
|
||||
|
||||
/// A finding of `severity`, `age_days` old.
|
||||
fn finding(fingerprint: &str, severity: Severity, age_days: i64) -> Finding {
|
||||
let mut f = Finding::new(
|
||||
"target-1".into(),
|
||||
fingerprint.into(),
|
||||
"semgrep".into(),
|
||||
ScanType::Sast,
|
||||
format!("rule {fingerprint}"),
|
||||
"desc".into(),
|
||||
severity,
|
||||
);
|
||||
f.created_at = Utc::now() - Duration::days(age_days);
|
||||
f
|
||||
}
|
||||
|
||||
fn fingerprints(findings: &[&Finding]) -> Vec<String> {
|
||||
findings.iter().map(|f| f.fingerprint.clone()).collect()
|
||||
}
|
||||
|
||||
/// A listed issue whose body carries `finding`'s fingerprint marker.
|
||||
fn issue_of(number: i64, finding: &Finding) -> GiteaIssue {
|
||||
GiteaIssue {
|
||||
number,
|
||||
title: "renamed since".into(),
|
||||
body: Some(format_issue_body(finding)),
|
||||
html_url: format!("https://gitea.invalid/o/r/issues/{number}"),
|
||||
state: "open".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_undecided_medium_and_above_without_an_issue_are_caught_up() {
|
||||
let mut linked = finding("linked", Severity::High, 1);
|
||||
linked.tracker_issue_url = Some("https://gitea.invalid/o/r/issues/1".into());
|
||||
let mut decided = finding("decided", Severity::Critical, 1);
|
||||
decided.status = FindingStatus::AcceptedRisk;
|
||||
let mut triaged = finding("triaged", Severity::Medium, 1);
|
||||
triaged.status = FindingStatus::Triaged;
|
||||
let selected = select(vec![
|
||||
finding("low", Severity::Low, 1),
|
||||
finding("info", Severity::Info, 1),
|
||||
linked,
|
||||
decided,
|
||||
triaged,
|
||||
finding("open", Severity::High, 1),
|
||||
]);
|
||||
let names: Vec<&str> = selected.iter().map(|f| f.fingerprint.as_str()).collect();
|
||||
assert_eq!(names, ["open", "triaged"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn highest_severity_first_then_oldest() {
|
||||
let selected = select(vec![
|
||||
finding("medium-old", Severity::Medium, 30),
|
||||
finding("high-new", Severity::High, 1),
|
||||
finding("critical-new", Severity::Critical, 1),
|
||||
finding("high-old", Severity::High, 10),
|
||||
finding("critical-old", Severity::Critical, 5),
|
||||
]);
|
||||
let names: Vec<&str> = selected.iter().map(|f| f.fingerprint.as_str()).collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
"critical-old",
|
||||
"critical-new",
|
||||
"high-old",
|
||||
"high-new",
|
||||
"medium-old"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn at_most_twenty_new_issues_and_the_rest_are_deferred() {
|
||||
let mut all: Vec<Finding> = (0..22)
|
||||
.map(|i| finding(&format!("high-{i}"), Severity::High, 100 - i))
|
||||
.collect();
|
||||
all.extend((0..3).map(|i| finding(&format!("medium-{i}"), Severity::Medium, 1)));
|
||||
let candidates = select(all);
|
||||
let index = ExistingIssues::default();
|
||||
|
||||
let plan = plan(&candidates, &index, MAX_NEW_ISSUES);
|
||||
|
||||
assert_eq!(plan.create.len(), 20);
|
||||
assert!(plan.link.is_empty());
|
||||
// The oldest highs first; two highs and the mediums wait.
|
||||
assert_eq!(plan.create[0].fingerprint, "high-0");
|
||||
assert_eq!(plan.create[19].fingerprint, "high-19");
|
||||
assert_eq!(plan.deferred.total(), 5);
|
||||
assert_eq!(plan.deferred.to_string(), "high=2 medium=3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finding_with_an_issue_is_linked_and_not_counted() {
|
||||
let candidates = select(
|
||||
(0..21)
|
||||
.map(|i| finding(&format!("fp-{i}"), Severity::High, 50 - i))
|
||||
.collect(),
|
||||
);
|
||||
// fp-0 has its issue (found by its marker, under another title).
|
||||
let index = ExistingIssues::new(&[issue_of(7, &candidates[0])]);
|
||||
|
||||
let plan = plan(&candidates, &index, MAX_NEW_ISSUES);
|
||||
|
||||
assert_eq!(plan.link.len(), 1);
|
||||
assert_eq!(plan.link[0].0.fingerprint, "fp-0");
|
||||
assert_eq!(plan.link[0].1.url, "https://gitea.invalid/o/r/issues/7");
|
||||
assert_eq!(plan.create.len(), 20, "the link does not use the cap");
|
||||
assert!(!fingerprints(&plan.create).contains(&"fp-0".to_string()));
|
||||
assert_eq!(plan.deferred.total(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_new_issue_per_title() {
|
||||
let first = finding("fp-a", Severity::High, 2);
|
||||
let mut second = finding("fp-b", Severity::High, 1);
|
||||
second.title = first.title.clone();
|
||||
let candidates = select(vec![first, second]);
|
||||
let index = ExistingIssues::default();
|
||||
let plan = plan(&candidates, &index, MAX_NEW_ISSUES);
|
||||
assert_eq!(fingerprints(&plan.create), ["fp-a"]);
|
||||
assert_eq!(plan.deferred.total(), 0);
|
||||
}
|
||||
|
||||
/// Requests a fake Gitea saw, as `METHOD path`.
|
||||
type Seen = Arc<Mutex<Vec<String>>>;
|
||||
|
||||
/// A fake Gitea whose repository has `issues`; a created issue gets
|
||||
/// number 100 and up.
|
||||
async fn fake_gitea(issues: Vec<GiteaIssue>, seen: Seen) -> String {
|
||||
async fn list(
|
||||
State((issues, seen)): State<(Arc<Vec<serde_json::Value>>, Seen)>,
|
||||
axum::extract::Query(params): axum::extract::Query<
|
||||
std::collections::HashMap<String, String>,
|
||||
>,
|
||||
) -> Json<serde_json::Value> {
|
||||
seen.lock().unwrap().push("GET issues".into());
|
||||
if params.get("page").map(String::as_str) != Some("1") {
|
||||
return Json(serde_json::json!([]));
|
||||
}
|
||||
Json(serde_json::json!(*issues))
|
||||
}
|
||||
async fn create(
|
||||
State((_, seen)): State<(Arc<Vec<serde_json::Value>>, Seen)>,
|
||||
) -> (axum::http::StatusCode, Json<serde_json::Value>) {
|
||||
let mut seen = seen.lock().unwrap();
|
||||
seen.push("POST issues".into());
|
||||
let number = 99 + seen.iter().filter(|s| s.starts_with("POST")).count();
|
||||
(
|
||||
axum::http::StatusCode::CREATED,
|
||||
Json(serde_json::json!({
|
||||
"number": number,
|
||||
"html_url": format!("https://gitea.invalid/o/r/issues/{number}"),
|
||||
})),
|
||||
)
|
||||
}
|
||||
let issues: Vec<serde_json::Value> = issues
|
||||
.iter()
|
||||
.map(|i| {
|
||||
serde_json::json!({
|
||||
"number": i.number,
|
||||
"title": i.title,
|
||||
"body": i.body,
|
||||
"html_url": i.html_url,
|
||||
"state": i.state,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let app = Router::new()
|
||||
.route("/api/v1/repos/{o}/{r}/issues", get(list).post(create))
|
||||
.with_state((Arc::new(issues), seen));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
format!("http://{addr}")
|
||||
}
|
||||
|
||||
fn sink<'a>(db: &'a Database, tracker: &'a TrackerDispatch, repo_id: &'a str) -> IssueSink<'a> {
|
||||
IssueSink {
|
||||
db,
|
||||
tracker,
|
||||
owner: "kunde",
|
||||
repo: "fw",
|
||||
repo_id,
|
||||
managed: false,
|
||||
dashboard: String::new(),
|
||||
labels: tokio::sync::OnceCell::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn posts(seen: &Seen) -> usize {
|
||||
seen.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|s| s.starts_with("POST"))
|
||||
.count()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_dry_run_counts_but_creates_and_links_nothing() {
|
||||
let seen: Seen = Arc::default();
|
||||
let with_issue = finding("fp-old", Severity::High, 9);
|
||||
let index = ExistingIssues::new(&[issue_of(7, &with_issue)]);
|
||||
let base = fake_gitea(Vec::new(), seen.clone()).await;
|
||||
let tracker = TrackerDispatch::Gitea(
|
||||
GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap(),
|
||||
);
|
||||
// Never reached: a dry run writes nothing (the client connects lazily).
|
||||
let client =
|
||||
mongodb::Client::with_uri_str("mongodb://127.0.0.1:1/?serverSelectionTimeoutMS=100")
|
||||
.await
|
||||
.unwrap();
|
||||
let db = Database::from_database(client.database("unused"));
|
||||
let sink = sink(&db, &tracker, "target-1");
|
||||
let candidates = select(vec![
|
||||
with_issue,
|
||||
finding("fp-new", Severity::Critical, 1),
|
||||
finding("fp-medium", Severity::Medium, 1),
|
||||
]);
|
||||
|
||||
let summary = run(&sink, &candidates, &index, IssueCatchup::DryRun).await;
|
||||
|
||||
assert_eq!(summary.created.to_string(), "critical=1 medium=1");
|
||||
assert_eq!(summary.linked.to_string(), "high=1");
|
||||
assert_eq!(summary.deferred.total(), 0);
|
||||
assert!(seen.lock().unwrap().is_empty(), "no request to Gitea");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn on_links_by_marker_and_opens_the_others() {
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let prefix = format!(
|
||||
"catchup_{}",
|
||||
&uuid::Uuid::new_v4().simple().to_string()[..10]
|
||||
);
|
||||
let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else {
|
||||
eprintln!("SKIP issue_catchup: no MongoDB reachable at {uri}");
|
||||
return;
|
||||
};
|
||||
let db = pool.for_tenant_id("issue-catchup").await.unwrap();
|
||||
|
||||
// Arrange: one finding whose issue exists (#7, matched by its
|
||||
// marker), one without, one already linked, and a low one.
|
||||
let old = finding("fp-old", Severity::High, 9);
|
||||
let fresh = finding("fp-new", Severity::Critical, 1);
|
||||
let mut linked = finding("fp-linked", Severity::High, 3);
|
||||
linked.tracker_issue_url = Some("https://gitea.invalid/o/r/issues/2".into());
|
||||
let low = finding("fp-low", Severity::Low, 3);
|
||||
let seen: Seen = Arc::default();
|
||||
let base = fake_gitea(vec![issue_of(7, &old)], seen.clone()).await;
|
||||
let gitea =
|
||||
GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap();
|
||||
db.findings()
|
||||
.insert_many([&old, &fresh, &linked, &low])
|
||||
.await
|
||||
.unwrap();
|
||||
let index = ExistingIssues::new(&gitea.list_issues("kunde", "fw").await.unwrap());
|
||||
let tracker = TrackerDispatch::Gitea(gitea);
|
||||
let sink = sink(&db, &tracker, "target-1");
|
||||
let url_of = |fp: &'static str| {
|
||||
let db = db.clone();
|
||||
async move {
|
||||
db.findings()
|
||||
.find_one(doc! { "fingerprint": fp })
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.tracker_issue_url
|
||||
}
|
||||
};
|
||||
|
||||
// A dry run changes nothing.
|
||||
let dry = catch_up(&sink, &index, IssueCatchup::DryRun).await.unwrap();
|
||||
assert_eq!((dry.created.total(), dry.linked.total()), (1, 1));
|
||||
assert_eq!(posts(&seen), 0);
|
||||
assert_eq!(url_of("fp-old").await, None);
|
||||
|
||||
// On: the old finding is linked to #7 without a request, the new
|
||||
// one gets an issue, the others are left alone.
|
||||
let done = catch_up(&sink, &index, IssueCatchup::On).await.unwrap();
|
||||
|
||||
assert_eq!(done.linked.to_string(), "high=1");
|
||||
assert_eq!(done.created.to_string(), "critical=1");
|
||||
assert_eq!(done.failed, 0);
|
||||
assert_eq!(posts(&seen), 1, "one create, for the new finding only");
|
||||
assert_eq!(
|
||||
url_of("fp-old").await.as_deref(),
|
||||
Some("https://gitea.invalid/o/r/issues/7")
|
||||
);
|
||||
assert_eq!(
|
||||
url_of("fp-new").await.as_deref(),
|
||||
Some("https://gitea.invalid/o/r/issues/100")
|
||||
);
|
||||
assert_eq!(url_of("fp-low").await, None);
|
||||
let old_id = db
|
||||
.findings()
|
||||
.find_one(doc! { "fingerprint": "fp-old" })
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.id
|
||||
.unwrap();
|
||||
let record: TrackerIssue = db
|
||||
.tracker_issues()
|
||||
.find_one(doc! { "finding_id": old_id.to_hex() })
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("the link is recorded for the status sync");
|
||||
assert_eq!(record.external_id, "7");
|
||||
|
||||
// The next scan finds nothing left to do.
|
||||
let again = catch_up(&sink, &index, IssueCatchup::On).await.unwrap();
|
||||
assert_eq!((again.created.total(), again.linked.total()), (0, 0));
|
||||
assert_eq!(posts(&seen), 1);
|
||||
pool.drop_tenant("issue-catchup").await.ok();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,12 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use mongodb::bson::doc;
|
||||
|
||||
use crate::database::Database;
|
||||
use crate::pipeline::repo_view::RepoView;
|
||||
use crate::trackers::gitea::GiteaIssue;
|
||||
use compliance_core::config::IssueCatchup;
|
||||
use compliance_core::error::CoreError;
|
||||
use compliance_core::models::*;
|
||||
|
||||
use super::orchestrator::{extract_base_url, PipelineOrchestrator};
|
||||
@@ -24,41 +30,20 @@ impl PipelineOrchestrator {
|
||||
alerts: &[CveAlert],
|
||||
complete: bool,
|
||||
) -> Result<(), AgentError> {
|
||||
if !repo.managed {
|
||||
return Ok(());
|
||||
}
|
||||
let (Some(tracker), Some(owner), Some(name)) = (
|
||||
self.build_tracker(repo),
|
||||
repo.tracker_owner.as_deref(),
|
||||
repo.tracker_repo.as_deref(),
|
||||
) else {
|
||||
return Ok(());
|
||||
};
|
||||
let dashboard = std::env::var("DASHBOARD_PUBLIC_URL").unwrap_or_default();
|
||||
let target = crate::pipeline::cve_issues::CveIssueTarget {
|
||||
let sync = CveIssueSync {
|
||||
config: &self.config,
|
||||
net_guard: self.net_guard,
|
||||
db: &self.db,
|
||||
tracker: &tracker,
|
||||
owner,
|
||||
repo: name,
|
||||
target_id: repo_id,
|
||||
dashboard: &dashboard,
|
||||
epss_percentile: crate::pipeline::cve_issues::epss_percentile(
|
||||
std::env::var("CVE_ISSUE_EPSS_PERCENTILE").ok().as_deref(),
|
||||
),
|
||||
tenant_id: &self.tenant_id,
|
||||
};
|
||||
let counts =
|
||||
crate::pipeline::cve_issues::sync_cve_issues(&target, alerts, complete).await?;
|
||||
tracing::info!(
|
||||
"[{repo_id}] CVE issues: {} opened, {} reopened, {} closed",
|
||||
counts.created,
|
||||
counts.reopened,
|
||||
counts.closed
|
||||
);
|
||||
Ok(())
|
||||
sync.sync(repo, repo_id, alerts, complete).await
|
||||
}
|
||||
|
||||
/// Create tracker issues for new findings (severity >= Medium).
|
||||
/// Checks for duplicates via fingerprint search before creating.
|
||||
/// Skips a finding whose issue exists (by fingerprint, then title): on
|
||||
/// Gitea matched against one listing of the repository's issues, on other
|
||||
/// trackers by a search per finding. On Gitea the issue catch-up
|
||||
/// ([`crate::pipeline::issue_catchup`]) follows, on the same listing.
|
||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||
pub(super) async fn create_tracker_issues(
|
||||
&self,
|
||||
@@ -89,144 +74,72 @@ impl PipelineOrchestrator {
|
||||
}
|
||||
};
|
||||
|
||||
// Only create issues for medium+ severity findings nobody has decided
|
||||
// about (a group can take over its places' decision, #483).
|
||||
let actionable: Vec<&Finding> = new_findings
|
||||
.iter()
|
||||
.filter(|f| {
|
||||
matches!(
|
||||
f.severity,
|
||||
Severity::Medium | Severity::High | Severity::Critical
|
||||
) && matches!(
|
||||
f.status,
|
||||
FindingStatus::Open | FindingStatus::Triaged | FindingStatus::NeedsReview
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let actionable: Vec<&Finding> = new_findings.iter().filter(|f| wants_issue(f)).collect();
|
||||
// Only Gitea has the listing the catch-up matches against.
|
||||
let catchup = match &tracker {
|
||||
TrackerDispatch::Gitea(_) => self.config.issue_catchup,
|
||||
_ => IssueCatchup::Off,
|
||||
};
|
||||
|
||||
if actionable.is_empty() {
|
||||
if actionable.is_empty() && catchup == IssueCatchup::Off {
|
||||
tracing::info!("[{repo_id}] No medium+ findings, skipping issue creation");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
tracing::info!(
|
||||
"[{repo_id}] Creating issues for {} findings via {}",
|
||||
actionable.len(),
|
||||
tracker.name()
|
||||
);
|
||||
|
||||
// A managed repository (#439) gets its labels created once per run
|
||||
// and attached by id. If that fails (no permission), the issues are
|
||||
// still opened, with the label names in the body as before.
|
||||
let managed_labels = match (&tracker, repo.managed) {
|
||||
(TrackerDispatch::Gitea(gitea), true) => match gitea
|
||||
.ensure_labels(
|
||||
owner,
|
||||
tracker_repo_name,
|
||||
&trackers::gitea::pruefwerk_labels(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(ids) => Some(ids),
|
||||
Err(e) => {
|
||||
tracing::warn!("[{repo_id}] Could not ensure the Prüfwerk labels: {e}");
|
||||
None
|
||||
}
|
||||
},
|
||||
// A Gitea lists its issues once and the findings are matched here, not
|
||||
// searched one by one (a burst of searches took a small instance
|
||||
// down). A listing that fails stops the sync for this repository,
|
||||
// the catch-up included; the next scan tries again.
|
||||
let mut existing = match &tracker {
|
||||
TrackerDispatch::Gitea(gitea) => {
|
||||
let issues = gitea.list_issues(owner, tracker_repo_name).await?;
|
||||
Some(ExistingIssues::new(&issues))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let dashboard = std::env::var("DASHBOARD_PUBLIC_URL").unwrap_or_default();
|
||||
|
||||
let sink = IssueSink {
|
||||
db: &self.db,
|
||||
tracker: &tracker,
|
||||
owner,
|
||||
repo: tracker_repo_name,
|
||||
repo_id,
|
||||
managed: repo.managed,
|
||||
dashboard: std::env::var("DASHBOARD_PUBLIC_URL").unwrap_or_default(),
|
||||
labels: tokio::sync::OnceCell::new(),
|
||||
};
|
||||
|
||||
if !actionable.is_empty() {
|
||||
tracing::info!(
|
||||
"[{repo_id}] Creating issues for {} findings via {}",
|
||||
actionable.len(),
|
||||
tracker.name()
|
||||
);
|
||||
}
|
||||
let mut created = 0u32;
|
||||
for finding in actionable {
|
||||
let title = issue_title(finding);
|
||||
|
||||
// Check if an issue already exists by fingerprint first, then by title
|
||||
let mut found_existing = false;
|
||||
for search_term in issue_search_terms(finding, &title) {
|
||||
match tracker
|
||||
.find_existing_issue(owner, tracker_repo_name, search_term)
|
||||
let found_existing = match &existing {
|
||||
Some(index) => index.find(finding, &title).map(|known| known.url.clone()),
|
||||
None => search_existing(&tracker, owner, tracker_repo_name, finding, &title)
|
||||
.await
|
||||
{
|
||||
Ok(Some(existing)) => {
|
||||
tracing::debug!(
|
||||
"[{repo_id}] Issue already exists for '{}': {}",
|
||||
search_term,
|
||||
existing.external_url
|
||||
);
|
||||
found_existing = true;
|
||||
break;
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
tracing::warn!("[{repo_id}] Failed to search for existing issue: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
if found_existing {
|
||||
.map(|issue| issue.external_url),
|
||||
};
|
||||
if let Some(url) = found_existing {
|
||||
tracing::debug!(
|
||||
"[{repo_id}] Issue already exists for '{}': {url}",
|
||||
finding.fingerprint
|
||||
);
|
||||
continue;
|
||||
}
|
||||
let mut body = format_issue_body(finding);
|
||||
if repo.managed {
|
||||
if let Some(link) = finding_link(&dashboard, repo_id) {
|
||||
body.push_str(&format!(
|
||||
"\n[Open in Prüfwerk / In Prüfwerk öffnen]({link})"
|
||||
));
|
||||
}
|
||||
}
|
||||
let labels = vec![
|
||||
format!("severity:{}", finding.severity),
|
||||
format!("scanner:{}", finding.scanner),
|
||||
"compliance-scanner".to_string(),
|
||||
];
|
||||
|
||||
let result = match (&tracker, &managed_labels) {
|
||||
(TrackerDispatch::Gitea(gitea), Some(ids)) => {
|
||||
let label_ids = label_ids(
|
||||
ids,
|
||||
&trackers::gitea::issue_label_names(&finding.severity.to_string()),
|
||||
);
|
||||
gitea
|
||||
.create_issue_with_label_ids(
|
||||
owner,
|
||||
tracker_repo_name,
|
||||
&title,
|
||||
&body,
|
||||
&label_ids,
|
||||
)
|
||||
.await
|
||||
}
|
||||
_ => {
|
||||
tracker
|
||||
.create_issue(owner, tracker_repo_name, &title, &body, &labels)
|
||||
.await
|
||||
}
|
||||
};
|
||||
match result {
|
||||
Ok(mut issue) => {
|
||||
issue.finding_id = finding
|
||||
.id
|
||||
.as_ref()
|
||||
.map(|id| id.to_hex())
|
||||
.unwrap_or_default();
|
||||
|
||||
// Update the finding with the issue URL
|
||||
if let Some(finding_id) = &finding.id {
|
||||
let _ = self
|
||||
.db
|
||||
.findings()
|
||||
.update_one(
|
||||
doc! { "_id": finding_id },
|
||||
doc! { "$set": { "tracker_issue_url": &issue.external_url } },
|
||||
)
|
||||
.await;
|
||||
match sink.open(finding, &title).await {
|
||||
Ok(issue) => {
|
||||
// Later findings of this run with the same title find it.
|
||||
if let Some(index) = existing.as_mut() {
|
||||
index.insert(&finding.fingerprint, &title, &issue);
|
||||
}
|
||||
|
||||
// Store the tracker issue record
|
||||
if let Err(e) = self.db.tracker_issues().insert_one(&issue).await {
|
||||
tracing::warn!("[{repo_id}] Failed to store tracker issue: {e}");
|
||||
}
|
||||
|
||||
created += 1;
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -237,8 +150,75 @@ impl PipelineOrchestrator {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tracing::info!("[{repo_id}] Created {created} tracker issues");
|
||||
|
||||
if let (Some(index), IssueCatchup::DryRun | IssueCatchup::On) = (&existing, catchup) {
|
||||
let summary = crate::pipeline::issue_catchup::catch_up(&sink, index, catchup).await?;
|
||||
summary.log(&self.tenant_id, repo_id);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// What opening, reopening and closing a target's CVE issues needs: the
|
||||
/// tracker configuration, where tracker calls may connect, and the tenant's
|
||||
/// database. Shared by the scans and the CVE monitor.
|
||||
pub(crate) struct CveIssueSync<'a> {
|
||||
pub config: &'a compliance_core::AgentConfig,
|
||||
pub net_guard: compliance_core::NetGuard,
|
||||
pub db: &'a Database,
|
||||
/// The tenant, for the log lines.
|
||||
pub tenant_id: &'a str,
|
||||
}
|
||||
|
||||
impl CveIssueSync<'_> {
|
||||
/// Open, reopen and close the CVE issues of the managed repository
|
||||
/// `repo` (target `repo_id`) to match `alerts` (see
|
||||
/// [`crate::pipeline::cve_issues::sync_cve_issues`] for `complete`);
|
||||
/// other targets, and one without a tracker, get none.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// A database error.
|
||||
pub(crate) async fn sync(
|
||||
&self,
|
||||
repo: &RepoView,
|
||||
repo_id: &str,
|
||||
alerts: &[CveAlert],
|
||||
complete: bool,
|
||||
) -> Result<(), AgentError> {
|
||||
if !repo.managed {
|
||||
return Ok(());
|
||||
}
|
||||
let (Some(tracker), Some(owner), Some(name)) = (
|
||||
build_tracker(self.config, self.net_guard, repo),
|
||||
repo.tracker_owner.as_deref(),
|
||||
repo.tracker_repo.as_deref(),
|
||||
) else {
|
||||
return Ok(());
|
||||
};
|
||||
let dashboard = std::env::var("DASHBOARD_PUBLIC_URL").unwrap_or_default();
|
||||
let target = crate::pipeline::cve_issues::CveIssueTarget {
|
||||
db: self.db,
|
||||
tenant_id: self.tenant_id,
|
||||
tracker: &tracker,
|
||||
owner,
|
||||
repo: name,
|
||||
target_id: repo_id,
|
||||
dashboard: &dashboard,
|
||||
epss_percentile: crate::pipeline::cve_issues::epss_percentile(
|
||||
std::env::var("CVE_ISSUE_EPSS_PERCENTILE").ok().as_deref(),
|
||||
),
|
||||
autoclose: self.config.issue_autoclose,
|
||||
};
|
||||
let counts =
|
||||
crate::pipeline::cve_issues::sync_cve_issues(&target, alerts, complete).await?;
|
||||
tracing::info!(
|
||||
"[{repo_id}] CVE issues: {} opened, {} reopened, {} closed",
|
||||
counts.created,
|
||||
counts.reopened,
|
||||
counts.closed
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -324,6 +304,272 @@ pub(crate) fn build_tracker(
|
||||
}
|
||||
}
|
||||
|
||||
/// Search the tracker for a finding's issue, one search per term of
|
||||
/// [`issue_search_terms`] (trackers other than Gitea). A failed search is
|
||||
/// logged and counts as not found.
|
||||
async fn search_existing(
|
||||
tracker: &TrackerDispatch,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
finding: &Finding,
|
||||
title: &str,
|
||||
) -> Option<TrackerIssue> {
|
||||
for search_term in issue_search_terms(finding, title) {
|
||||
match tracker.find_existing_issue(owner, repo, search_term).await {
|
||||
Ok(Some(existing)) => return Some(existing),
|
||||
Ok(None) => {}
|
||||
Err(e) => tracing::warn!("Failed to search for existing issue: {e}"),
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The marker a finding issue's body carries its fingerprint in, right
|
||||
/// before the fingerprint and its closing backtick.
|
||||
const FINGERPRINT_MARKER: &str = "*Fingerprint:* `";
|
||||
|
||||
/// The fingerprint in an issue body written by [`format_issue_body`].
|
||||
fn body_fingerprint(body: &str) -> Option<&str> {
|
||||
let start = body.find(FINGERPRINT_MARKER)? + FINGERPRINT_MARKER.len();
|
||||
let rest = &body[start..];
|
||||
rest.find('`')
|
||||
.map(|end| &rest[..end])
|
||||
.filter(|fp| !fp.is_empty())
|
||||
}
|
||||
|
||||
/// An issue of the repository: what a finding linked to it records.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(super) struct KnownIssue {
|
||||
/// The issue number.
|
||||
pub(super) external_id: String,
|
||||
pub(super) url: String,
|
||||
/// Closed on the tracker.
|
||||
pub(super) closed: bool,
|
||||
}
|
||||
|
||||
/// The issues a repository already has, by fingerprint and by title, built
|
||||
/// from one listing so each finding is matched without a request.
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct ExistingIssues {
|
||||
/// Fingerprint (from the body's marker) to issue.
|
||||
by_fingerprint: HashMap<String, KnownIssue>,
|
||||
/// Exact title to issue.
|
||||
by_title: HashMap<String, KnownIssue>,
|
||||
}
|
||||
|
||||
impl ExistingIssues {
|
||||
/// Index `issues`; where two share a fingerprint or title, the first
|
||||
/// listed (Gitea lists the newest first) wins.
|
||||
pub(super) fn new(issues: &[GiteaIssue]) -> Self {
|
||||
let mut index = Self::default();
|
||||
for issue in issues {
|
||||
let known = KnownIssue {
|
||||
external_id: issue.number.to_string(),
|
||||
url: issue.html_url.clone(),
|
||||
closed: issue.state == "closed",
|
||||
};
|
||||
if let Some(fp) = issue.body.as_deref().and_then(body_fingerprint) {
|
||||
index
|
||||
.by_fingerprint
|
||||
.entry(fp.to_string())
|
||||
.or_insert_with(|| known.clone());
|
||||
}
|
||||
index.by_title.entry(issue.title.clone()).or_insert(known);
|
||||
}
|
||||
index
|
||||
}
|
||||
|
||||
/// `finding`'s issue: by fingerprint, then by `title` (not for a group,
|
||||
/// see [`issue_search_terms`]).
|
||||
pub(super) fn find(&self, finding: &Finding, title: &str) -> Option<&KnownIssue> {
|
||||
self.by_fingerprint.get(&finding.fingerprint).or_else(|| {
|
||||
finding
|
||||
.occurrences
|
||||
.is_empty()
|
||||
.then(|| self.by_title.get(title))
|
||||
.flatten()
|
||||
})
|
||||
}
|
||||
|
||||
/// Add an issue opened during this run.
|
||||
fn insert(&mut self, fingerprint: &str, title: &str, issue: &TrackerIssue) {
|
||||
let known = KnownIssue {
|
||||
external_id: issue.external_id.clone(),
|
||||
url: issue.external_url.clone(),
|
||||
closed: false,
|
||||
};
|
||||
self.by_fingerprint
|
||||
.entry(fingerprint.to_string())
|
||||
.or_insert_with(|| known.clone());
|
||||
self.by_title.entry(title.to_string()).or_insert(known);
|
||||
}
|
||||
}
|
||||
|
||||
/// The severities a finding gets an issue at.
|
||||
pub(super) const ISSUE_SEVERITIES: [Severity; 3] =
|
||||
[Severity::Medium, Severity::High, Severity::Critical];
|
||||
|
||||
/// The statuses of findings nobody has decided about (a group can take over
|
||||
/// its places' decision, #483): only those get an issue.
|
||||
pub(super) const ISSUE_STATUSES: [FindingStatus; 3] = [
|
||||
FindingStatus::Open,
|
||||
FindingStatus::Triaged,
|
||||
FindingStatus::NeedsReview,
|
||||
];
|
||||
|
||||
/// Whether `finding` should have an issue: medium or above and undecided.
|
||||
pub(super) fn wants_issue(finding: &Finding) -> bool {
|
||||
ISSUE_SEVERITIES.contains(&finding.severity) && ISSUE_STATUSES.contains(&finding.status)
|
||||
}
|
||||
|
||||
/// Where a target's finding issues are opened, and what each one gets.
|
||||
pub(super) struct IssueSink<'a> {
|
||||
pub(super) db: &'a Database,
|
||||
pub(super) tracker: &'a TrackerDispatch,
|
||||
pub(super) owner: &'a str,
|
||||
pub(super) repo: &'a str,
|
||||
/// The target the findings belong to.
|
||||
pub(super) repo_id: &'a str,
|
||||
/// From a managed git source (#439): its issues get the Prüfwerk labels
|
||||
/// and a link into Prüfwerk.
|
||||
pub(super) managed: bool,
|
||||
/// The dashboard's public origin (`DASHBOARD_PUBLIC_URL`).
|
||||
pub(super) dashboard: String,
|
||||
/// The ids of the Prüfwerk labels, ensured once, when the first issue
|
||||
/// is opened (`None` inside: they could not be ensured). A `OnceCell`
|
||||
/// runs its async initialiser at most once, like a cached property.
|
||||
pub(super) labels: tokio::sync::OnceCell<Option<HashMap<String, i64>>>,
|
||||
}
|
||||
|
||||
impl IssueSink<'_> {
|
||||
/// The label ids of a managed Gitea repository, ensured on first use.
|
||||
/// If that fails (no permission), issues are still opened, with the
|
||||
/// label names in the body as before.
|
||||
async fn label_ids(&self) -> Option<&HashMap<String, i64>> {
|
||||
let TrackerDispatch::Gitea(gitea) = self.tracker else {
|
||||
return None;
|
||||
};
|
||||
if !self.managed {
|
||||
return None;
|
||||
}
|
||||
self.labels
|
||||
.get_or_init(|| async {
|
||||
match gitea
|
||||
.ensure_labels(self.owner, self.repo, &trackers::gitea::pruefwerk_labels())
|
||||
.await
|
||||
{
|
||||
Ok(ids) => Some(ids),
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
"[{}] Could not ensure the Prüfwerk labels: {e}",
|
||||
self.repo_id
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
/// Open the issue of `finding`, titled `title`, and record it.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The tracker refused the issue; nothing is recorded then.
|
||||
pub(super) async fn open(
|
||||
&self,
|
||||
finding: &Finding,
|
||||
title: &str,
|
||||
) -> Result<TrackerIssue, CoreError> {
|
||||
let mut body = format_issue_body(finding);
|
||||
if self.managed {
|
||||
if let Some(link) = finding_link(&self.dashboard, self.repo_id) {
|
||||
body.push_str(&format!(
|
||||
"\n[Open in Prüfwerk / In Prüfwerk öffnen]({link})"
|
||||
));
|
||||
}
|
||||
}
|
||||
let mut issue = match (self.tracker, self.label_ids().await) {
|
||||
(TrackerDispatch::Gitea(gitea), Some(ids)) => {
|
||||
let label_ids = label_ids(
|
||||
ids,
|
||||
&trackers::gitea::issue_label_names(&finding.severity.to_string()),
|
||||
);
|
||||
gitea
|
||||
.create_issue_with_label_ids(self.owner, self.repo, title, &body, &label_ids)
|
||||
.await?
|
||||
}
|
||||
_ => {
|
||||
let labels = [
|
||||
format!("severity:{}", finding.severity),
|
||||
format!("scanner:{}", finding.scanner),
|
||||
"compliance-scanner".to_string(),
|
||||
];
|
||||
self.tracker
|
||||
.create_issue(self.owner, self.repo, title, &body, &labels)
|
||||
.await?
|
||||
}
|
||||
};
|
||||
issue.finding_id = finding
|
||||
.id
|
||||
.as_ref()
|
||||
.map(|id| id.to_hex())
|
||||
.unwrap_or_default();
|
||||
self.record(finding, &issue).await;
|
||||
Ok(issue)
|
||||
}
|
||||
|
||||
/// Link `finding` to its Gitea issue `known`, which exists already.
|
||||
pub(super) async fn link(&self, finding: &Finding, title: &str, known: &KnownIssue) {
|
||||
let mut issue = TrackerIssue::new(
|
||||
finding
|
||||
.id
|
||||
.as_ref()
|
||||
.map(|id| id.to_hex())
|
||||
.unwrap_or_default(),
|
||||
TrackerType::Gitea,
|
||||
known.external_id.clone(),
|
||||
known.url.clone(),
|
||||
title.to_string(),
|
||||
);
|
||||
if known.closed {
|
||||
issue.status = IssueStatus::Closed;
|
||||
}
|
||||
self.record(finding, &issue).await;
|
||||
}
|
||||
|
||||
/// Put the issue's URL on the finding and store the issue record (one
|
||||
/// per finding, replacing an older one), which the status sync
|
||||
/// ([`crate::pipeline::issue_sync`]) finds the issue by. A failed write
|
||||
/// is logged: the issue exists either way.
|
||||
async fn record(&self, finding: &Finding, issue: &TrackerIssue) {
|
||||
let Some(finding_id) = &finding.id else {
|
||||
return;
|
||||
};
|
||||
if let Err(e) = self
|
||||
.db
|
||||
.findings()
|
||||
.update_one(
|
||||
doc! { "_id": finding_id },
|
||||
doc! { "$set": { "tracker_issue_url": &issue.external_url } },
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!("[{}] Failed to link the issue: {e}", self.repo_id);
|
||||
}
|
||||
if let Err(e) = self
|
||||
.db
|
||||
.tracker_issues()
|
||||
.replace_one(doc! { "finding_id": &issue.finding_id }, issue)
|
||||
.upsert(true)
|
||||
.await
|
||||
{
|
||||
tracing::warn!("[{}] Failed to store tracker issue: {e}", self.repo_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What to search the tracker for to find a finding's issue: its
|
||||
/// fingerprint, then its title. A group (#464) only by fingerprint: it has
|
||||
/// the title of its rule's single findings, whose issues are being closed as
|
||||
@@ -339,7 +585,7 @@ fn issue_search_terms<'a>(finding: &'a Finding, title: &'a str) -> Vec<&'a str>
|
||||
/// A finding's issue title: severity, scanner, the app variant when there
|
||||
/// are several (the same flaw in the phone and the tablet app is two
|
||||
/// issues, and the title is what an issue is found by), and its title.
|
||||
fn issue_title(finding: &Finding) -> String {
|
||||
pub(super) fn issue_title(finding: &Finding) -> String {
|
||||
match &finding.variant {
|
||||
Some(variant) => format!(
|
||||
"[{}] {} ({variant}): {}",
|
||||
@@ -403,7 +649,7 @@ pub(super) fn format_issue_body(finding: &Finding) -> String {
|
||||
}
|
||||
|
||||
body.push_str(&format!(
|
||||
"\n---\n*Fingerprint:* `{}`\n*Generated by compliance-scanner*",
|
||||
"\n---\n{FINGERPRINT_MARKER}{}`\n*Generated by compliance-scanner*",
|
||||
finding.fingerprint
|
||||
));
|
||||
|
||||
@@ -442,7 +688,7 @@ fn finding_link(dashboard: &str, target_id: &str) -> Option<String> {
|
||||
|
||||
/// The ids of `names` among the ensured labels; a name without an id is left
|
||||
/// out.
|
||||
fn label_ids(ids: &std::collections::HashMap<String, i64>, names: &[String]) -> Vec<i64> {
|
||||
fn label_ids(ids: &HashMap<String, i64>, names: &[String]) -> Vec<i64> {
|
||||
names.iter().filter_map(|n| ids.get(n).copied()).collect()
|
||||
}
|
||||
|
||||
@@ -531,6 +777,103 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
fn listed(number: i64, title: &str, body: Option<&str>) -> GiteaIssue {
|
||||
GiteaIssue {
|
||||
number,
|
||||
title: title.into(),
|
||||
body: body.map(str::to_string),
|
||||
html_url: format!("https://gitea.invalid/o/r/issues/{number}"),
|
||||
state: "open".into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The URL of `finding`'s issue in `index`.
|
||||
fn url<'a>(index: &'a ExistingIssues, finding: &Finding, title: &str) -> Option<&'a str> {
|
||||
index.find(finding, title).map(|known| known.url.as_str())
|
||||
}
|
||||
|
||||
fn high(fingerprint: &str, title: &str) -> Finding {
|
||||
Finding::new(
|
||||
"r".into(),
|
||||
fingerprint.into(),
|
||||
"semgrep".into(),
|
||||
ScanType::Sast,
|
||||
title.into(),
|
||||
"desc".into(),
|
||||
Severity::High,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fingerprint_is_read_back_from_the_body() {
|
||||
let body = format_issue_body(&high("fp-abc", "SQL injection"));
|
||||
assert_eq!(body_fingerprint(&body), Some("fp-abc"));
|
||||
assert_eq!(body_fingerprint("no marker"), None);
|
||||
assert_eq!(body_fingerprint("*Fingerprint:* `"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_issue_is_matched_by_its_fingerprint_marker() {
|
||||
let finding = high("fp-1", "SQL injection");
|
||||
let body = format_issue_body(&finding);
|
||||
// Another title: the scanner renamed the rule since.
|
||||
let index = ExistingIssues::new(&[
|
||||
listed(3, "something else", Some("text")),
|
||||
listed(7, "[high] semgrep: old name", Some(&body)),
|
||||
]);
|
||||
assert_eq!(
|
||||
url(&index, &finding, &issue_title(&finding)),
|
||||
Some("https://gitea.invalid/o/r/issues/7")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_issue_without_the_marker_is_matched_by_title_unless_grouped() {
|
||||
let finding = high("fp-2", "SQL injection");
|
||||
let title = issue_title(&finding);
|
||||
let index = ExistingIssues::new(&[listed(4, &title, None)]);
|
||||
assert_eq!(
|
||||
url(&index, &finding, &title),
|
||||
Some("https://gitea.invalid/o/r/issues/4")
|
||||
);
|
||||
// A group is found by its fingerprint only.
|
||||
let mut group = finding.clone();
|
||||
group.occurrences = (1..=2)
|
||||
.map(|line| Occurrence {
|
||||
file: "a.rs".into(),
|
||||
line: Some(line),
|
||||
variant: None,
|
||||
decision: None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(url(&index, &group, &title), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_match_means_a_new_issue_and_it_is_found_afterwards() {
|
||||
let first = high("fp-3", "Hardcoded key");
|
||||
let title = issue_title(&first);
|
||||
let mut index = ExistingIssues::new(&[listed(1, "[high] semgrep: other", Some("x"))]);
|
||||
assert_eq!(url(&index, &first, &title), None);
|
||||
|
||||
// Opened during this run: the next finding with that title (or the
|
||||
// same fingerprint) is not opened twice.
|
||||
let opened = TrackerIssue::new(
|
||||
String::new(),
|
||||
TrackerType::Gitea,
|
||||
"9".into(),
|
||||
"https://gitea.invalid/o/r/issues/9".into(),
|
||||
title.clone(),
|
||||
);
|
||||
index.insert(&first.fingerprint, &title, &opened);
|
||||
let same_title = high("fp-4", "Hardcoded key");
|
||||
assert_eq!(
|
||||
url(&index, &same_title, &title),
|
||||
Some("https://gitea.invalid/o/r/issues/9")
|
||||
);
|
||||
assert!(index.find(&first, "another title").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_variant_is_in_the_title_and_the_body() {
|
||||
let mut finding = Finding::new(
|
||||
|
||||
@@ -7,6 +7,9 @@
|
||||
//! reopens its issue. The sync reads each finding's status when it runs, so a
|
||||
//! change made in between is the one carried over.
|
||||
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use mongodb::bson::{doc, oid::ObjectId};
|
||||
|
||||
use compliance_core::models::{
|
||||
@@ -78,8 +81,9 @@ impl IssueSync {
|
||||
return;
|
||||
}
|
||||
tokio::spawn(async move {
|
||||
let mut risk_labels = RiskLabels::new();
|
||||
for id in ids {
|
||||
if let Err(e) = self.sync_one(id).await {
|
||||
if let Err(e) = self.sync_one(id, &mut risk_labels).await {
|
||||
tracing::warn!(finding = %id, error = %e, "issue status not synced");
|
||||
}
|
||||
}
|
||||
@@ -87,7 +91,10 @@ impl IssueSync {
|
||||
}
|
||||
|
||||
/// Carry the status of finding `id` over to its issue, if it has one.
|
||||
async fn sync_one(&self, id: ObjectId) -> Result<(), String> {
|
||||
/// `risk_labels` keeps the `risk:accepted` label id of each target this
|
||||
/// run has resolved, so the labels are listed once per target, not once
|
||||
/// per issue.
|
||||
async fn sync_one(&self, id: ObjectId, risk_labels: &mut RiskLabels) -> Result<(), String> {
|
||||
let Some(issue) = self
|
||||
.db
|
||||
.tracker_issues()
|
||||
@@ -138,7 +145,14 @@ impl IssueSync {
|
||||
accepted_risk: true,
|
||||
} = action
|
||||
{
|
||||
label_accepted_risk(&tracker, owner, name, number).await;
|
||||
label_accepted_risk(
|
||||
&tracker,
|
||||
owner,
|
||||
name,
|
||||
number,
|
||||
risk_labels.entry(finding.repo_id.clone()),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let (state, status) = match action {
|
||||
IssueAction::Close { .. } => ("closed", IssueStatus::Closed),
|
||||
@@ -169,17 +183,34 @@ impl IssueSync {
|
||||
}
|
||||
}
|
||||
|
||||
/// The `risk:accepted` label id per target (`Finding::repo_id`), once
|
||||
/// resolved; `None` for a target whose repository has no such label.
|
||||
type RiskLabels = HashMap<String, Option<i64>>;
|
||||
|
||||
/// Put the `risk:accepted` label on a Gitea issue. Other trackers keep only
|
||||
/// the comment; a label that cannot be set does not stop the close.
|
||||
async fn label_accepted_risk(tracker: &TrackerDispatch, owner: &str, repo: &str, number: &str) {
|
||||
/// the comment; a label that cannot be set does not stop the close. The
|
||||
/// label id is resolved once per target and kept in `cached`.
|
||||
async fn label_accepted_risk(
|
||||
tracker: &TrackerDispatch,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
number: &str,
|
||||
cached: Entry<'_, String, Option<i64>>,
|
||||
) {
|
||||
let TrackerDispatch::Gitea(gitea) = tracker else {
|
||||
return;
|
||||
};
|
||||
let labelled = async {
|
||||
let ids = gitea
|
||||
.ensure_labels(owner, repo, &pruefwerk_labels())
|
||||
.await?;
|
||||
let label: Vec<i64> = ids.get(LABEL_ACCEPTED_RISK).copied().into_iter().collect();
|
||||
let label = match cached {
|
||||
Entry::Occupied(known) => *known.get(),
|
||||
Entry::Vacant(slot) => {
|
||||
let ids = gitea
|
||||
.ensure_labels(owner, repo, &pruefwerk_labels())
|
||||
.await?;
|
||||
*slot.insert(ids.get(LABEL_ACCEPTED_RISK).copied())
|
||||
}
|
||||
};
|
||||
let label: Vec<i64> = label.into_iter().collect();
|
||||
gitea.add_labels(owner, repo, number, &label).await
|
||||
};
|
||||
if let Err(e) = labelled.await {
|
||||
@@ -261,7 +292,17 @@ mod tests {
|
||||
type Calls = Arc<Mutex<Vec<String>>>;
|
||||
|
||||
async fn fake_gitea(calls: Calls) -> String {
|
||||
async fn labels() -> Json<serde_json::Value> {
|
||||
async fn labels(
|
||||
State(calls): State<Calls>,
|
||||
axum::extract::Query(page): axum::extract::Query<
|
||||
std::collections::HashMap<String, String>,
|
||||
>,
|
||||
) -> Json<serde_json::Value> {
|
||||
// One page of labels: a later page is empty, as Gitea ends a list.
|
||||
if page.get("page").map(String::as_str) != Some("1") {
|
||||
return Json(serde_json::json!([]));
|
||||
}
|
||||
calls.lock().unwrap().push("list labels".into());
|
||||
// Every Prüfwerk label exists already; risk:accepted is id 42.
|
||||
Json(serde_json::json!(pruefwerk_labels()
|
||||
.iter()
|
||||
@@ -395,7 +436,9 @@ mod tests {
|
||||
};
|
||||
|
||||
// Act + assert: the scan closed it, so the issue closes with a comment.
|
||||
sync.sync_one(finding_id).await.unwrap();
|
||||
sync.sync_one(finding_id, &mut RiskLabels::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(issue_status().await, IssueStatus::Closed);
|
||||
{
|
||||
let calls = calls.lock().unwrap();
|
||||
@@ -405,7 +448,9 @@ mod tests {
|
||||
}
|
||||
|
||||
// Synced again with no change: nothing more is sent.
|
||||
sync.sync_one(finding_id).await.unwrap();
|
||||
sync.sync_one(finding_id, &mut RiskLabels::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(calls.lock().unwrap().len(), 2);
|
||||
|
||||
// It comes back: the issue reopens.
|
||||
@@ -416,7 +461,9 @@ mod tests {
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
sync.sync_one(finding_id).await.unwrap();
|
||||
sync.sync_one(finding_id, &mut RiskLabels::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(issue_status().await, IssueStatus::Open);
|
||||
assert_eq!(calls.lock().unwrap().last().unwrap(), "state 12: \"open\"");
|
||||
|
||||
@@ -428,7 +475,9 @@ mod tests {
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
sync.sync_one(finding_id).await.unwrap();
|
||||
sync.sync_one(finding_id, &mut RiskLabels::new())
|
||||
.await
|
||||
.unwrap();
|
||||
{
|
||||
let calls = calls.lock().unwrap();
|
||||
let tail: Vec<&str> = calls.iter().rev().take(2).map(String::as_str).collect();
|
||||
@@ -438,6 +487,33 @@ mod tests {
|
||||
pool.drop_tenant("issue-sync").await.ok();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_risk_label_is_resolved_once_per_target() {
|
||||
let calls: Calls = Arc::default();
|
||||
let base = fake_gitea(calls.clone()).await;
|
||||
let tracker = TrackerDispatch::Gitea(
|
||||
crate::trackers::gitea::GiteaTracker::new(
|
||||
base,
|
||||
secrecy::SecretString::from("t"),
|
||||
NetGuard::allow_private(),
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
let mut cache = RiskLabels::new();
|
||||
|
||||
for number in ["5", "6"] {
|
||||
label_accepted_risk(&tracker, "kunde", "fw", number, cache.entry("t1".into())).await;
|
||||
}
|
||||
|
||||
let calls = calls.lock().unwrap();
|
||||
assert_eq!(
|
||||
*calls,
|
||||
["list labels", "labels 5: [42]", "labels 6: [42]"],
|
||||
"the labels are listed once"
|
||||
);
|
||||
assert_eq!(cache["t1"], Some(42));
|
||||
}
|
||||
|
||||
fn by_scan(status: FindingStatus, kind: ScanChangeKind) -> StatusChange {
|
||||
StatusChange::by_scan(status, kind, "run-1")
|
||||
}
|
||||
|
||||
@@ -30,6 +30,8 @@ fn language_of(extension: &str) -> Option<&'static str> {
|
||||
// Objective-C; `.m` is also MATLAB's extension, which only means
|
||||
// mobsfscan looks at a tree it finds nothing in.
|
||||
"m" | "mm" => "objc",
|
||||
// Yocto / OpenEmbedded recipes, appends and classes.
|
||||
"bb" | "bbappend" | "bbclass" => "bitbake",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -64,6 +66,10 @@ mod tests {
|
||||
("tools/flash.py", "print('flash')"),
|
||||
("Middlewares/Third_Party/lib/x.cpp", "int x;"),
|
||||
("README.md", "# readme"),
|
||||
(
|
||||
"meta-pump/recipes-app/pump/pump_1.0.bb",
|
||||
"LICENSE = \"CLOSED\"",
|
||||
),
|
||||
] {
|
||||
let file = root.join(path);
|
||||
std::fs::create_dir_all(file.parent().expect("parent")).expect("mkdir");
|
||||
@@ -72,8 +78,11 @@ mod tests {
|
||||
|
||||
let vendor = vec!["Middlewares/Third_Party".to_string()];
|
||||
|
||||
assert_eq!(source_languages(root, &vendor), ["c", "python"]);
|
||||
assert_eq!(source_languages(root, &[]), ["c", "cpp", "python"]);
|
||||
assert_eq!(source_languages(root, &vendor), ["bitbake", "c", "python"]);
|
||||
assert_eq!(
|
||||
source_languages(root, &[]),
|
||||
["bitbake", "c", "cpp", "python"]
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ pub mod binary_depth;
|
||||
pub mod build_lifecycle;
|
||||
pub mod change;
|
||||
pub mod clamav;
|
||||
pub mod clone_limit;
|
||||
pub mod code_review;
|
||||
pub mod cppcheck;
|
||||
pub(crate) mod csaf_feed;
|
||||
@@ -10,6 +11,7 @@ pub(crate) mod csaf_match;
|
||||
pub mod cve;
|
||||
pub(crate) mod cve_enrichment;
|
||||
pub(crate) mod cve_issues;
|
||||
pub mod cve_notify;
|
||||
pub mod dedup;
|
||||
pub mod devskim;
|
||||
pub mod dotnet;
|
||||
@@ -17,23 +19,27 @@ pub mod embedded_versions;
|
||||
pub mod finding_store;
|
||||
pub mod firmware_sbom;
|
||||
pub mod git;
|
||||
pub mod git_retry;
|
||||
pub mod git_submodules;
|
||||
pub mod gitleaks;
|
||||
mod graph_build;
|
||||
pub mod grouping;
|
||||
pub mod ios_config;
|
||||
mod issue_creation;
|
||||
mod issue_catchup;
|
||||
pub(crate) mod issue_creation;
|
||||
pub(crate) mod issue_sync;
|
||||
pub mod languages;
|
||||
pub mod lint;
|
||||
pub mod mobsfscan;
|
||||
pub mod nvd_cpe;
|
||||
pub(crate) mod nvd_monitor;
|
||||
pub mod orchestrator;
|
||||
pub mod patterns;
|
||||
pub mod plan;
|
||||
pub mod plc;
|
||||
mod pr_review;
|
||||
mod public_http;
|
||||
pub mod recipe_lint;
|
||||
pub mod repo_view;
|
||||
pub mod sbom;
|
||||
pub mod sbom_quality;
|
||||
@@ -45,3 +51,5 @@ pub(crate) mod unity_settings;
|
||||
pub mod variants;
|
||||
pub mod vendor;
|
||||
pub mod vex_lifecycle;
|
||||
pub mod yocto_inventory;
|
||||
pub mod yocto_pins;
|
||||
@@ -40,7 +40,7 @@ pub(crate) const NVD_CVES_URL: &str = "https://services.nvd.nist.gov/rest/json/c
|
||||
/// 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] = [
|
||||
pub(crate) const RETRY_DELAYS: [Duration; 3] = [
|
||||
Duration::from_secs(6),
|
||||
Duration::from_secs(12),
|
||||
Duration::from_secs(24),
|
||||
@@ -80,15 +80,25 @@ pub(crate) async fn product_cves(
|
||||
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))
|
||||
match_cves(http, api_key, product.match_string, product.marker, version).await
|
||||
}
|
||||
|
||||
/// [`product_cves`] for a product named at run time (a Yocto recipe's
|
||||
/// CVE_PRODUCT): the CVEs NVD lists for `match_string` whose vulnerable CPE
|
||||
/// contains `marker` and whose range covers `version`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Why NVD could not be asked, as for [`product_cves`].
|
||||
pub(crate) async fn match_cves(
|
||||
http: &PublicHttp,
|
||||
api_key: Option<&str>,
|
||||
match_string: &str,
|
||||
marker: &str,
|
||||
version: &str,
|
||||
) -> Result<Vec<NvdCve>, String> {
|
||||
let body = product_body(http, NVD_CVES_URL, api_key, match_string, &RETRY_DELAYS).await?;
|
||||
Ok(parse(&body, marker, version))
|
||||
}
|
||||
|
||||
/// NVD's answer for `match_string`: cached, or fetched from `base_url` with
|
||||
@@ -103,36 +113,48 @@ async fn product_body(
|
||||
if let Some(body) = cached(match_string) {
|
||||
return Ok(body);
|
||||
}
|
||||
let query = [("virtualMatchString", match_string.to_string())];
|
||||
let body = Arc::new(fetch(http, base_url, api_key, &query, delays).await?);
|
||||
if let Ok(mut c) = cache().lock() {
|
||||
c.insert(
|
||||
match_string.to_string(),
|
||||
(Instant::now(), Arc::clone(&body)),
|
||||
);
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
/// NVD's answer to `query` at `base_url`, asked again after each of `delays`
|
||||
/// while NVD's answer is transient ([`is_transient`]) or the request fails.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Why NVD could not be asked (net guard, network, status, body) after the
|
||||
/// retries; a status NVD gives for good (404 for a query it refuses) and a
|
||||
/// URL the net guard refuses are not retried.
|
||||
pub(crate) async fn fetch(
|
||||
http: &PublicHttp,
|
||||
base_url: &str,
|
||||
api_key: Option<&str>,
|
||||
query: &[(&str, String)],
|
||||
delays: &[Duration],
|
||||
) -> Result<serde_json::Value, String> {
|
||||
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}"
|
||||
);
|
||||
tracing::info!(attempt, "retrying NVD after {wait:?}: {last_error}");
|
||||
tokio::time::sleep(*wait).await;
|
||||
}
|
||||
// A URL the net guard refuses is refused for good: not retried.
|
||||
let mut req = http
|
||||
.get(base_url)?
|
||||
.query(&[("virtualMatchString", match_string)])
|
||||
.query(query)
|
||||
.timeout(NVD_REQUEST_TIMEOUT);
|
||||
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 = read_json(resp).await?;
|
||||
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 resp.status().is_success() => return read_json(resp).await,
|
||||
Ok(resp) if is_transient(resp.status()) => {
|
||||
last_error = format!("NVD returned {}", resp.status());
|
||||
}
|
||||
@@ -143,6 +165,22 @@ async fn product_body(
|
||||
Err(last_error)
|
||||
}
|
||||
|
||||
/// Whether a fresh answer for `match_string` is cached, so asking costs no
|
||||
/// request against NVD's rate limit.
|
||||
pub(crate) fn is_cached(match_string: &str) -> bool {
|
||||
cached(match_string).is_some()
|
||||
}
|
||||
|
||||
/// The pause between two requests that keeps within NVD's rate limit: 50
|
||||
/// requests per 30 seconds with an API key, 5 without.
|
||||
pub(crate) fn request_interval(with_key: bool) -> Duration {
|
||||
if with_key {
|
||||
Duration::from_millis(600)
|
||||
} else {
|
||||
Duration::from_secs(6)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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()?;
|
||||
@@ -164,36 +202,59 @@ pub fn parse(body: &serde_json::Value, marker: &str, version: &str) -> Vec<NvdCv
|
||||
};
|
||||
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()),
|
||||
})
|
||||
})
|
||||
.filter_map(|v| parse_cve(v, marker, version))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One entry of an NVD response's `vulnerabilities`, when a vulnerable CPE
|
||||
/// of it contains `marker` and its range covers `version`.
|
||||
pub(crate) fn parse_cve(v: &serde_json::Value, marker: &str, version: &str) -> Option<NvdCve> {
|
||||
let cve = &v["cve"];
|
||||
let id = cve["id"].as_str()?;
|
||||
let covered = cpe_matches(v).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()),
|
||||
})
|
||||
}
|
||||
|
||||
/// Every `cpeMatch` object of one entry of an NVD response's
|
||||
/// `vulnerabilities`.
|
||||
pub(crate) fn cpe_matches(v: &serde_json::Value) -> impl Iterator<Item = &serde_json::Value> {
|
||||
v["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())
|
||||
}
|
||||
|
||||
/// Whether the CPE `criteria` is one NVD returns for the match string
|
||||
/// `match_string` (`virtualMatchString`): each component the match string
|
||||
/// names (part, vendor, product, ...) is `*` there or equal in `criteria`.
|
||||
/// `cpe:2.3:a:codesys` matches every CODESYS application CPE,
|
||||
/// `cpe:2.3:*:amazon:freertos` FreeRTOS as application and operating system.
|
||||
pub(crate) fn matches_virtual(match_string: &str, criteria: &str) -> bool {
|
||||
let mut wanted = match_string.split(':');
|
||||
let mut have = criteria.split(':');
|
||||
wanted.all(|w| {
|
||||
have.next()
|
||||
.is_some_and(|h| w == "*" || w.eq_ignore_ascii_case(h))
|
||||
})
|
||||
}
|
||||
|
||||
/// Version constraints from an NVD `cpeMatch` node.
|
||||
#[derive(Default)]
|
||||
struct CpeRange {
|
||||
@@ -249,6 +310,12 @@ fn version_matches(v: &str, r: &CpeRange) -> bool {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_api_key_allows_ten_times_the_requests() {
|
||||
assert_eq!(request_interval(false), Duration::from_secs(6));
|
||||
assert_eq!(request_interval(true) * 10, request_interval(false));
|
||||
}
|
||||
use std::cmp::Ordering::{Equal, Greater, Less};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
@@ -359,6 +426,23 @@ mod tests {
|
||||
assert_eq!(hits.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_match_string_matches_cpes_as_nvd_lists_them() {
|
||||
let criteria = "cpe:2.3:o:amazon:freertos:*:*:*:*:*:*:*:*";
|
||||
assert!(matches_virtual("cpe:2.3:*:amazon:freertos", criteria));
|
||||
assert!(matches_virtual("cpe:2.3:*:*:freertos", criteria));
|
||||
assert!(!matches_virtual("cpe:2.3:a:amazon:freertos", criteria));
|
||||
assert!(!matches_virtual(
|
||||
"cpe:2.3:*:amazon:freertos-plus-tcp",
|
||||
criteria
|
||||
));
|
||||
assert!(matches_virtual(
|
||||
"cpe:2.3:a:codesys",
|
||||
"cpe:2.3:a:codesys:control_for_linux_sl:*:*:*:*:*:*:*:*"
|
||||
));
|
||||
assert!(!matches_virtual("cpe:2.3:a:codesys", "cpe:2.3:a"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fatfs_revisions_match_nvds_ranges() {
|
||||
// The shape of CVE-2026-6682: FatFs R0.16 and earlier.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -24,6 +24,7 @@ use crate::pipeline::plan::build_scan_plan;
|
||||
use crate::pipeline::repo_view::RepoView;
|
||||
use crate::pipeline::sbom::{LicenseCache, NugetRegistry, SbomScanner};
|
||||
use crate::pipeline::semgrep::SemgrepScanner;
|
||||
use crate::pipeline::yocto_inventory::{self, Inventory};
|
||||
use crate::secrets::SecretBox;
|
||||
|
||||
/// Context from graph analysis passed to LLM triage for enhanced filtering
|
||||
@@ -379,6 +380,26 @@ impl PipelineOrchestrator {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Yocto layers: oelint-adv's security rules and our own over the
|
||||
// recipes and the image configuration.
|
||||
let (findings, completed) = self
|
||||
.lint_recipes(&repo_path, &repo_id, scan_run_id, &languages, &vendor)
|
||||
.instrument(tracing::info_span!("stage_recipe_lint"))
|
||||
.await;
|
||||
for scanner in completed {
|
||||
run_findings.completed(scanner);
|
||||
}
|
||||
all_findings.extend(findings);
|
||||
// Yocto layers: what they pin, and whether their release is supported.
|
||||
if repo.yocto_layers {
|
||||
if let Some(found) = self
|
||||
.check_yocto_release(&repo_path, repo, scan_run_id, &vendor)
|
||||
.await
|
||||
{
|
||||
run_findings.completed(crate::pipeline::yocto_pins::release::SCANNER);
|
||||
all_findings.extend(found);
|
||||
}
|
||||
}
|
||||
run_findings.label(&mut all_findings);
|
||||
group_repetitive(&mut all_findings, &grouping);
|
||||
run_findings.save_new(&self.db, &mut all_findings).await?;
|
||||
@@ -487,7 +508,35 @@ impl PipelineOrchestrator {
|
||||
})
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
for entry in embedded.into_iter().chain(codesys) {
|
||||
// A Yocto layer tree: its recipes, read without a build and labelled
|
||||
// as the recipe inventory (not the image SBOM).
|
||||
let yocto = if repo.yocto_layers {
|
||||
self.yocto_recipes(&repo_path, scan_run_id).await
|
||||
} else {
|
||||
Inventory::default()
|
||||
};
|
||||
// The recipes the image recipes name are marked as in the image
|
||||
// (declared); what an image names that is not in the tree is listed.
|
||||
let declarations = yocto_inventory::declared_in_images(&yocto);
|
||||
if !declarations.unresolved.is_empty() {
|
||||
let names: Vec<String> = declarations.unresolved.iter().cloned().collect();
|
||||
self.skip_stage(
|
||||
scan_run_id,
|
||||
SkippedStage::new(
|
||||
yocto_inventory::IMAGE_STAGE,
|
||||
SkipCode::NotInTree,
|
||||
format!(
|
||||
"named by an image but not a recipe or package group in the tree: {}",
|
||||
component_list(&names)
|
||||
),
|
||||
)
|
||||
.about(component_list(&names)),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let yocto_entries = yocto_inventory::entries(&yocto.recipes, &declarations, &repo_id);
|
||||
let yocto_recipes = yocto.recipes;
|
||||
for entry in embedded.into_iter().chain(codesys).chain(yocto_entries) {
|
||||
let known = sbom_entries
|
||||
.iter()
|
||||
.any(|e| e.name.eq_ignore_ascii_case(&entry.name) && e.version == entry.version);
|
||||
@@ -614,6 +663,32 @@ impl PipelineOrchestrator {
|
||||
}
|
||||
}
|
||||
|
||||
// A Yocto recipe inventory's components: NVD by CPE, within a budget
|
||||
// of their own (a layer tree can name hundreds of products).
|
||||
if !yocto_recipes.is_empty() {
|
||||
let (queries, unversioned) = yocto_inventory::nvd_queries(&yocto_recipes);
|
||||
let lookup = cve_scanner
|
||||
.scan_yocto(
|
||||
&repo_id,
|
||||
&mut sbom_entries,
|
||||
&queries,
|
||||
yocto_inventory::NVD_BUDGET,
|
||||
)
|
||||
.await;
|
||||
cve_alerts.extend(lookup.alerts);
|
||||
let unchecked: Vec<String> = unversioned.into_iter().chain(lookup.unchecked).collect();
|
||||
if !unchecked.is_empty() {
|
||||
cve_complete = false;
|
||||
self.record_cve_gap(
|
||||
scan_run_id,
|
||||
&format!("NVD (Yocto recipes): {}", component_list(&unchecked)),
|
||||
"these recipes were not matched in NVD: they have no release version, or \
|
||||
the lookup failed or did not fit in the time NVD's rate limit allows",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
self.match_advisories(&repo_id, &mut sbom_entries, &mut cve_alerts)
|
||||
.await;
|
||||
|
||||
@@ -900,9 +975,27 @@ impl PipelineOrchestrator {
|
||||
.await?;
|
||||
}
|
||||
|
||||
// Persist CVE alerts and create notifications (shared with the PLC path).
|
||||
// Persist CVE alerts (shared with the PLC path).
|
||||
self.persist_cve_alerts(&cve_alerts).await?;
|
||||
// What the recipes say about their CVEs (CVE_STATUS, `CVE:` patches),
|
||||
// stated again after the alerts were stored, never over a person's,
|
||||
// and before the notifications, which a `not_affected` or `fixed`
|
||||
// suppresses.
|
||||
let statements = yocto_inventory::vex_statements(&yocto_recipes, &cve_alerts);
|
||||
if !statements.is_empty() {
|
||||
match crate::pipeline::vex_lifecycle::apply_scan_statements(
|
||||
&self.db,
|
||||
&repo_id,
|
||||
&statements,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(set) => tracing::info!("[{repo_id}] {set} VEX statement(s) from Yocto recipes"),
|
||||
Err(e) => tracing::warn!("[{repo_id}] VEX statements from Yocto recipes: {e}"),
|
||||
}
|
||||
}
|
||||
let new_notif_count = self
|
||||
.persist_cve_alerts(&repo_id, &repo.name, &cve_alerts)
|
||||
.notify_cves(&repo_id, &repo.name, &mut cve_alerts)
|
||||
.await?;
|
||||
if new_notif_count > 0 {
|
||||
tracing::info!("[{repo_id}] Created {new_notif_count} CVE notification(s)");
|
||||
@@ -1128,9 +1221,12 @@ impl PipelineOrchestrator {
|
||||
|
||||
// Ingest + classify (Firmwerk for firmware) and store the detected type.
|
||||
// The ingested paths are where an uploaded archive was unpacked.
|
||||
let working_paths = self
|
||||
let (working_paths, classified_yocto) = self
|
||||
.classify_and_store(target, &target_id, scan_run_id)
|
||||
.await;
|
||||
// The recipe inventory runs on a tree classified as a Yocto layer
|
||||
// tree, and on any target the plan gives it to (a Yocto target).
|
||||
let yocto_layers = classified_yocto || plan.has(ScanType::RecipeInventory);
|
||||
// Provision a DAST target from a LiveUrl artifact so DAST fires for
|
||||
// wizard-created targets, not just migrated ones.
|
||||
self.ensure_dast_target(target, &plan).await;
|
||||
@@ -1207,7 +1303,8 @@ impl PipelineOrchestrator {
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let repo = RepoView::from_target(target, code, &self.secrets);
|
||||
let mut repo = RepoView::from_target(target, code, &self.secrets);
|
||||
repo.yocto_layers = yocto_layers;
|
||||
let n = self.run_pipeline(&repo, scan_run_id, trigger).await?;
|
||||
self.finalize_target(target, &repo, n).await?;
|
||||
new_count += n;
|
||||
@@ -1221,7 +1318,8 @@ impl PipelineOrchestrator {
|
||||
// run scans what was uploaded.
|
||||
match working_paths.get(&code.id) {
|
||||
Some(tree) => {
|
||||
let repo = RepoView::from_target(target, code, &self.secrets);
|
||||
let mut repo = RepoView::from_target(target, code, &self.secrets);
|
||||
repo.yocto_layers = yocto_layers;
|
||||
let upload = crate::pipeline::plc::sbom::uploaded_archive(code);
|
||||
let n = self.scan_tree(tree, upload, &repo, scan_run_id).await?;
|
||||
self.finalize_target(target, &repo, n).await?;
|
||||
@@ -1652,8 +1750,9 @@ impl PipelineOrchestrator {
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
self.persist_cve_alerts(&alerts).await?;
|
||||
let new_notifs = self
|
||||
.persist_cve_alerts(target_id, &target.name, &alerts)
|
||||
.notify_cves(target_id, &target.name, &mut alerts)
|
||||
.await?;
|
||||
// What the code pipeline does at its end: a complete lookup resolves
|
||||
// the alerts it no longer reports, and a managed repository's CVE
|
||||
@@ -1704,57 +1803,32 @@ impl PipelineOrchestrator {
|
||||
}
|
||||
}
|
||||
|
||||
/// Upsert CVE alerts for a target and create dedup'd CVE notifications;
|
||||
/// returns the number of newly-created notifications. Shared by the SAST
|
||||
/// pipeline and the PLC control-app SBOM path, so every SBOM source (source,
|
||||
/// firmware, CODESYS libraries/runtime) raises the same notifications.
|
||||
async fn persist_cve_alerts(
|
||||
/// Store the CVE alerts a scan of a target found. Shared by the SAST
|
||||
/// pipeline and the PLC control-app SBOM path.
|
||||
async fn persist_cve_alerts(&self, alerts: &[CveAlert]) -> Result<(), AgentError> {
|
||||
for alert in alerts {
|
||||
crate::pipeline::vex_lifecycle::upsert_reported(&self.db, alert).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Give the stored alerts' VEX statements to `alerts` and create the CVE
|
||||
/// notifications that are new (none for an alert `not_affected` or
|
||||
/// `fixed`); returns how many were created. Run after
|
||||
/// [`Self::persist_cve_alerts`] and the scan's own VEX statements, so
|
||||
/// every SBOM source (source, firmware, CODESYS libraries/runtime) raises
|
||||
/// the same notifications and the issue sync sees the statements.
|
||||
async fn notify_cves(
|
||||
&self,
|
||||
repo_id: &str,
|
||||
repo_name: &str,
|
||||
alerts: &[CveAlert],
|
||||
alerts: &mut [CveAlert],
|
||||
) -> Result<u32, AgentError> {
|
||||
use compliance_core::models::notification::{parse_severity, CveNotification};
|
||||
|
||||
let mut new_notif = 0u32;
|
||||
for alert in alerts {
|
||||
crate::pipeline::vex_lifecycle::upsert_reported(&self.db, alert).await?;
|
||||
|
||||
// Dedup notifications by cve + repo + package + version.
|
||||
let notif_filter = doc! {
|
||||
"cve_id": &alert.cve_id,
|
||||
"repo_id": &alert.repo_id,
|
||||
"package_name": &alert.affected_package,
|
||||
"package_version": &alert.affected_version,
|
||||
};
|
||||
let severity = parse_severity(alert.severity.as_deref(), alert.cvss_score);
|
||||
let mut notification = CveNotification::new(
|
||||
alert.cve_id.clone(),
|
||||
repo_id.to_string(),
|
||||
repo_name.to_string(),
|
||||
alert.affected_package.clone(),
|
||||
alert.affected_version.clone(),
|
||||
severity,
|
||||
);
|
||||
notification.cvss_score = alert.cvss_score;
|
||||
notification.summary = alert.summary.clone();
|
||||
notification.url = Some(format!("https://osv.dev/vulnerability/{}", alert.cve_id));
|
||||
let notif_update = doc! {
|
||||
"$setOnInsert": mongodb::bson::to_bson(¬ification).unwrap_or_default()
|
||||
};
|
||||
if let Ok(result) = self
|
||||
.db
|
||||
.cve_notifications()
|
||||
.update_one(notif_filter, notif_update)
|
||||
.upsert(true)
|
||||
.await
|
||||
{
|
||||
if result.upserted_id.is_some() {
|
||||
new_notif += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(new_notif)
|
||||
crate::pipeline::vex_lifecycle::attach_stored_vex(&self.db, repo_id, alerts).await?;
|
||||
Ok(
|
||||
crate::pipeline::cve_notify::notify_new_cves(&self.db, repo_id, repo_name, alerts)
|
||||
.await,
|
||||
)
|
||||
}
|
||||
|
||||
/// Ingest the target's artifacts, classify (Firmwerk for firmware/RTOS/Yocto,
|
||||
@@ -1767,7 +1841,7 @@ impl PipelineOrchestrator {
|
||||
target: &OnboardedTarget,
|
||||
target_id: &str,
|
||||
scan_run_id: &str,
|
||||
) -> std::collections::HashMap<String, std::path::PathBuf> {
|
||||
) -> (std::collections::HashMap<String, std::path::PathBuf>, bool) {
|
||||
self.update_phase(scan_run_id, ScanPhase::Classification)
|
||||
.await;
|
||||
let ingest_set = self.ingest_with_steps(target, target_id, scan_run_id).await;
|
||||
@@ -1781,6 +1855,8 @@ impl PipelineOrchestrator {
|
||||
let working_paths = ingest_set.working_paths();
|
||||
self.record_upload_hashes(target, &ingest_set).await;
|
||||
let mut detected_firmware = false;
|
||||
// Without a classification the declared type decides.
|
||||
let mut yocto = target.target_type == TargetType::EmbeddedLinuxYocto;
|
||||
self.update_step(scan_run_id, ScanStep::DetectProjectType)
|
||||
.await;
|
||||
match crate::classify::classify_target(
|
||||
@@ -1798,6 +1874,7 @@ impl PipelineOrchestrator {
|
||||
);
|
||||
detected_firmware =
|
||||
crate::pipeline::firmware_sbom::is_firmware_target(classification.suggested);
|
||||
yocto = classification.suggested == TargetType::EmbeddedLinuxYocto;
|
||||
if let (Some(oid), Ok(bson)) = (target.id, mongodb::bson::to_bson(&classification))
|
||||
{
|
||||
let mut set = doc! { "classification": bson };
|
||||
@@ -1834,12 +1911,25 @@ impl PipelineOrchestrator {
|
||||
// Analysis-based firmware SBOM: for embedded targets, derive components
|
||||
// (resolved libraries + cross-toolchain) from Firmwerk's build-plan
|
||||
// analysis over the already-ingested source — no build, no binary
|
||||
// upload. When no build plan forms (e.g. a Yocto layer), the run says
|
||||
// so rather than completing as if the firmware had no components.
|
||||
// upload. When no build plan forms, the run says so rather than
|
||||
// completing as if the firmware had no components.
|
||||
// What the code is decides, not only the type picked at onboarding: an
|
||||
// STM32 project onboarded as "backend service" still gets its SBOM.
|
||||
if detected_firmware
|
||||
|| crate::pipeline::firmware_sbom::is_firmware_target(target.target_type)
|
||||
// A Yocto layer tree is not a firmware build: Firmwerk would read the
|
||||
// C sources a recipe ships in `files/` as a bare-metal project.
|
||||
if yocto && target.code_artifact().is_some() {
|
||||
self.skip_stage(
|
||||
scan_run_id,
|
||||
SkippedStage::new(
|
||||
"firmware_sbom",
|
||||
SkipCode::NotAnalysedYet,
|
||||
compliance_core::scan_matrix::YOCTO_BUILD_PLANNED,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
} else if !yocto
|
||||
&& (detected_firmware
|
||||
|| crate::pipeline::firmware_sbom::is_firmware_target(target.target_type))
|
||||
{
|
||||
if let Some(code) = target.code_artifact() {
|
||||
if let Some(path) = working_paths.get(&code.id) {
|
||||
@@ -1896,7 +1986,7 @@ impl PipelineOrchestrator {
|
||||
}
|
||||
}
|
||||
}
|
||||
working_paths
|
||||
(working_paths, yocto)
|
||||
}
|
||||
|
||||
/// Store on each upload that has none the sha256 ingest computed, so the
|
||||
@@ -2117,7 +2207,11 @@ impl PipelineOrchestrator {
|
||||
findings.extend(scan.findings);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("[{repo_id}] ClamAV did not complete: {e}");
|
||||
if e.service_down() {
|
||||
tracing::error!("[{repo_id}] ClamAV did not complete: {e}");
|
||||
} else {
|
||||
tracing::warn!("[{repo_id}] ClamAV did not complete: {e}");
|
||||
}
|
||||
self.skip_stage(
|
||||
scan_run_id,
|
||||
SkippedStage::new(
|
||||
@@ -2135,13 +2229,20 @@ impl PipelineOrchestrator {
|
||||
|
||||
/// Record a stage the pipeline deliberately did not run. A skipped stage is
|
||||
/// not an error: the scan completes, and the dashboard shows it as skipped
|
||||
/// rather than failed.
|
||||
/// rather than failed. An informational entry (a stage that ran, with
|
||||
/// context) goes to the run's notes instead.
|
||||
pub(super) async fn skip_stage(&self, scan_run_id: &str, skipped: SkippedStage) {
|
||||
let field = if skipped.is_note() {
|
||||
"notes"
|
||||
} else {
|
||||
"skipped_stages"
|
||||
};
|
||||
tracing::info!(
|
||||
scan_run_id,
|
||||
stage = %skipped.stage,
|
||||
reason = %skipped.reason,
|
||||
"pipeline stage skipped"
|
||||
field,
|
||||
"pipeline stage skipped or noted"
|
||||
);
|
||||
let Ok(oid) = mongodb::bson::oid::ObjectId::parse_str(scan_run_id) else {
|
||||
return;
|
||||
@@ -2152,11 +2253,93 @@ impl PipelineOrchestrator {
|
||||
let _ = self
|
||||
.db
|
||||
.scan_runs()
|
||||
.update_one(
|
||||
doc! { "_id": oid },
|
||||
doc! { "$push": { "skipped_stages": entry } },
|
||||
.update_one(doc! { "_id": oid }, doc! { "$push": { field: entry } })
|
||||
.await;
|
||||
}
|
||||
|
||||
/// The recipe lint of a tree whose `languages` include BitBake, outside
|
||||
/// the `vendor` directories: the findings, and the scanners that
|
||||
/// completed. Upstream layers left out and findings suppressed in the
|
||||
/// recipes are recorded as notes, an oelint-adv run that did not complete
|
||||
/// as a skipped stage.
|
||||
async fn lint_recipes(
|
||||
&self,
|
||||
tree: &std::path::Path,
|
||||
repo_id: &str,
|
||||
scan_run_id: &str,
|
||||
languages: &[String],
|
||||
vendor: &[String],
|
||||
) -> (Vec<Finding>, Vec<&'static str>) {
|
||||
use crate::pipeline::recipe_lint::{self, oelint, rules, RecipeLint};
|
||||
let (root, id) = (tree.to_path_buf(), repo_id.to_string());
|
||||
let (languages, vendor) = (languages.to_vec(), vendor.to_vec());
|
||||
let prepared = tokio::task::spawn_blocking(move || {
|
||||
RecipeLint::for_tree(&root, &languages, &vendor).map(|lint| {
|
||||
let findings = lint.config_findings(&root, &id);
|
||||
(lint, findings)
|
||||
})
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten();
|
||||
let Some((lint, mut findings)) = prepared else {
|
||||
return (Vec::new(), Vec::new());
|
||||
};
|
||||
let mut completed = vec![rules::SCANNER];
|
||||
let upstream = lint.upstream_layers().join(", ");
|
||||
if !upstream.is_empty() {
|
||||
self.skip_stage(
|
||||
scan_run_id,
|
||||
SkippedStage::new(
|
||||
recipe_lint::UPSTREAM_STAGE,
|
||||
SkipCode::VendorCode,
|
||||
format!("upstream Yocto layers are left out of the recipe lint: {upstream}"),
|
||||
)
|
||||
.about(upstream),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
match lint.oelint_findings(tree, repo_id).await {
|
||||
Ok(found) => {
|
||||
completed.push(oelint::SCANNER);
|
||||
findings.extend(found.findings);
|
||||
// Suppressed findings are not shown, so the run says how many.
|
||||
if found.suppressed > 0 {
|
||||
tracing::info!(
|
||||
repo_id,
|
||||
suppressed = found.suppressed,
|
||||
"recipe comments (# nooelint) suppressed oelint-adv findings"
|
||||
);
|
||||
self.skip_stage(
|
||||
scan_run_id,
|
||||
SkippedStage::new(
|
||||
recipe_lint::SUPPRESSED_STAGE,
|
||||
SkipCode::SuppressedInSource,
|
||||
format!(
|
||||
"{} findings suppressed by recipe comments (# nooelint)",
|
||||
found.suppressed
|
||||
),
|
||||
)
|
||||
.about(found.suppressed.to_string()),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("[{repo_id}] oelint-adv failed: {e}");
|
||||
self.skip_stage(
|
||||
scan_run_id,
|
||||
SkippedStage::new(
|
||||
recipe_lint::STAGE,
|
||||
SkipCode::ToolFailed,
|
||||
"oelint-adv did not complete",
|
||||
)
|
||||
.about(oelint::SCANNER),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
(findings, completed)
|
||||
}
|
||||
|
||||
/// Record that `phase` started. Typed, so a phase the model cannot read
|
||||
@@ -2199,6 +2382,103 @@ impl PipelineOrchestrator {
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Read the layer pins of the Yocto layer tree at `tree` and store them on
|
||||
/// the target. The support-status finding of its release, `None` when the
|
||||
/// release is unknown (recorded on the run as a skipped stage).
|
||||
async fn check_yocto_release(
|
||||
&self,
|
||||
tree: &std::path::Path,
|
||||
repo: &RepoView,
|
||||
scan_run_id: &str,
|
||||
vendor: &[String],
|
||||
) -> Option<Vec<Finding>> {
|
||||
use crate::pipeline::yocto_pins::{self, release};
|
||||
let (root, excluded) = (tree.to_path_buf(), vendor.to_vec());
|
||||
let pins = tokio::task::spawn_blocking(move || yocto_pins::read(&root, &excluded))
|
||||
.await
|
||||
.ok()?;
|
||||
if let (Some(oid), Ok(stored)) = (repo.id, mongodb::bson::to_bson(&pins)) {
|
||||
if let Err(e) = self
|
||||
.db
|
||||
.onboarded_targets()
|
||||
.update_one(
|
||||
doc! { "_id": oid },
|
||||
doc! { "$set": { "layer_pins": stored } },
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(target_id = %oid, "layer pins not stored: {e}");
|
||||
}
|
||||
}
|
||||
let Some(found) = &pins.release else {
|
||||
self.skip_stage(
|
||||
scan_run_id,
|
||||
SkippedStage::new(
|
||||
yocto_pins::STAGE,
|
||||
SkipCode::ReleaseUnknown,
|
||||
"the Yocto release could not be read from the layer pins (kas, repo \
|
||||
manifest, submodules) or LAYERSERIES_COMPAT, so its support period was \
|
||||
not checked",
|
||||
),
|
||||
)
|
||||
.await;
|
||||
return None;
|
||||
};
|
||||
let repo_id = repo.id.map(|id| id.to_hex()).unwrap_or_default();
|
||||
let today = chrono::Utc::now().date_naive();
|
||||
Some(
|
||||
release::finding(&repo_id, found, today)
|
||||
.into_iter()
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The recipes, images and package groups of a Yocto layer tree. A parser
|
||||
/// that failed, a tree with no layer, or recipes the parser could not read
|
||||
/// are recorded on the run.
|
||||
async fn yocto_recipes(&self, tree: &std::path::Path, scan_run_id: &str) -> Inventory {
|
||||
match yocto_inventory::read(tree).await {
|
||||
Ok(inventory) if inventory.recipes.is_empty() && inventory.errors.is_empty() => {
|
||||
self.skip_stage(
|
||||
scan_run_id,
|
||||
SkippedStage::new(
|
||||
yocto_inventory::STAGE,
|
||||
SkipCode::NotAnalysedYet,
|
||||
"no BitBake recipe of a product component was found in the tree \
|
||||
(a layer has conf/layer.conf and .bb recipes)",
|
||||
),
|
||||
)
|
||||
.await;
|
||||
Inventory::default()
|
||||
}
|
||||
Ok(inventory) => {
|
||||
if !inventory.errors.is_empty() {
|
||||
let files: Vec<String> =
|
||||
inventory.errors.iter().map(|e| e.file.clone()).collect();
|
||||
self.skip_stage(
|
||||
scan_run_id,
|
||||
SkippedStage::new(
|
||||
yocto_inventory::STAGE,
|
||||
SkipCode::ToolFailed,
|
||||
format!(
|
||||
"these recipes could not be parsed and are not in the recipe \
|
||||
inventory: {}",
|
||||
component_list(&files)
|
||||
),
|
||||
)
|
||||
.about("oelint-parser"),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
inventory
|
||||
}
|
||||
Err(skipped) => {
|
||||
self.skip_stage(scan_run_id, skipped).await;
|
||||
Inventory::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Record that CVE matching is incomplete for this run, and why: a lookup
|
||||
/// that failed must not read as components without CVEs.
|
||||
async fn record_cve_gap(&self, scan_run_id: &str, lookup: &str, reason: &str) {
|
||||
|
||||
@@ -124,8 +124,8 @@ fn resolve_artifact(target: &OnboardedTarget, required: Option<ArtifactKind>) ->
|
||||
/// The pipeline phase reported while a given scan runs.
|
||||
fn phase_for(scan: ScanType) -> ScanPhase {
|
||||
match scan {
|
||||
ScanType::Sast => ScanPhase::Sast,
|
||||
ScanType::Sbom => ScanPhase::SbomGeneration,
|
||||
ScanType::Sast | ScanType::RecipeLint => ScanPhase::Sast,
|
||||
ScanType::Sbom | ScanType::RecipeInventory => ScanPhase::SbomGeneration,
|
||||
ScanType::Cve => ScanPhase::CveScanning,
|
||||
ScanType::Gdpr | ScanType::OAuth => ScanPhase::PatternScanning,
|
||||
ScanType::SecretDetection => ScanPhase::SecretDetection,
|
||||
@@ -175,6 +175,27 @@ mod tests {
|
||||
assert_eq!(dast.artifact_id, url_id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_yocto_layer_tree_runs_its_source_scans_recipe_inventory_and_lint() {
|
||||
let t = target(
|
||||
TargetType::EmbeddedLinuxYocto,
|
||||
vec![Artifact::source_archive("meta-pump.zip")],
|
||||
);
|
||||
let plan = build_scan_plan(&t);
|
||||
assert!(plan.has(ScanType::Sast) && plan.has(ScanType::Sbom));
|
||||
assert!(plan.has(ScanType::RecipeLint));
|
||||
assert_eq!(
|
||||
step_for(&plan, ScanType::RecipeLint).map(|s| &s.phase),
|
||||
Some(&ScanPhase::Sast)
|
||||
);
|
||||
assert!(plan.has(ScanType::RecipeInventory));
|
||||
assert!(!plan.has(ScanType::Dast));
|
||||
assert!(
|
||||
plan.unavailable.is_empty(),
|
||||
"nothing is recorded as not run: no image is attached"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn webapp_without_url_omits_dast() {
|
||||
let t = target(TargetType::WebApp, vec![Artifact::git_repo("u", "main")]);
|
||||
|
||||
@@ -61,18 +61,27 @@ impl PublicHttp {
|
||||
}
|
||||
}
|
||||
|
||||
/// How the error of a body over [`MAX_BODY_BYTES`] begins.
|
||||
const TOO_LARGE: &str = "response larger than";
|
||||
|
||||
/// Whether `error` (from [`read_body`] or [`read_json`]) says the body
|
||||
/// exceeded [`MAX_BODY_BYTES`], so a smaller page could still be read.
|
||||
pub(crate) fn is_too_large(error: &str) -> bool {
|
||||
error.starts_with(TOO_LARGE)
|
||||
}
|
||||
|
||||
/// The body of `resp`, refused once it exceeds [`MAX_BODY_BYTES`].
|
||||
pub(crate) async fn read_body(mut resp: reqwest::Response) -> Result<Vec<u8>, String> {
|
||||
if resp
|
||||
.content_length()
|
||||
.is_some_and(|n| n > MAX_BODY_BYTES as u64)
|
||||
{
|
||||
return Err(format!("response larger than {MAX_BODY_BYTES} bytes"));
|
||||
return Err(format!("{TOO_LARGE} {MAX_BODY_BYTES} bytes"));
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
while let Some(chunk) = resp.chunk().await.map_err(|e| e.to_string())? {
|
||||
if body.len() + chunk.len() > MAX_BODY_BYTES {
|
||||
return Err(format!("response larger than {MAX_BODY_BYTES} bytes"));
|
||||
return Err(format!("{TOO_LARGE} {MAX_BODY_BYTES} bytes"));
|
||||
}
|
||||
body.extend_from_slice(&chunk);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,544 @@
|
||||
//! Recipe lint of a Yocto / OpenEmbedded layer tree (tier 1, no build).
|
||||
//!
|
||||
//! Two scanners read the layers' recipes and configuration:
|
||||
//!
|
||||
//! - **oelint-adv** (BSD-2-Clause, [`oelint`]) with only its security rules:
|
||||
//! debug and empty-password image features, missing checksums, `AUTOREV`,
|
||||
//! `tag=` fetches, network access in tasks and skipped QA checks;
|
||||
//! - **our own rules** (`yocto-config`, [`rules`]): password hashes in
|
||||
//! `EXTRA_USERS_PARAMS`, `http://` fetches, a shipped `sshd_config` that
|
||||
//! allows root or password logins, certificates shipped with a recipe, and a
|
||||
//! distro without `security_flags.inc`.
|
||||
//!
|
||||
//! Upstream layers (Poky, OpenEmbedded, the BSP vendors' layers) are not the
|
||||
//! customer's to fix, so neither scanner reads them; the run names them, as it
|
||||
//! names vendor code.
|
||||
|
||||
pub mod oelint;
|
||||
pub mod rules;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
|
||||
use compliance_core::models::{Finding, ScanType, Severity};
|
||||
|
||||
use crate::pipeline::dedup;
|
||||
use crate::pipeline::source_text::{read_lines, read_text};
|
||||
|
||||
/// The stage id a failed oelint-adv run is recorded under.
|
||||
pub const STAGE: &str = "recipe_lint";
|
||||
/// The stage id the upstream layers left out are recorded under.
|
||||
pub const UPSTREAM_STAGE: &str = "recipe_lint_upstream";
|
||||
/// The stage id the findings suppressed by `# nooelint` comments are
|
||||
/// recorded under.
|
||||
pub const SUPPRESSED_STAGE: &str = "recipe_lint_suppressed";
|
||||
|
||||
/// Directories never walked: version control and a build directory's output.
|
||||
const SKIPPED_DIRS: &[&str] = &[".git", "build", "downloads", "sstate-cache"];
|
||||
|
||||
/// `BBFILE_COLLECTIONS` of upstream layers: OpenEmbedded-Core and Poky, the
|
||||
/// meta-openembedded layers, and widely used security, virtualisation and
|
||||
/// BSP layers. Their findings are upstream's, like vendor SDK code.
|
||||
const UPSTREAM_COLLECTIONS: &[&str] = &[
|
||||
"core",
|
||||
"yocto",
|
||||
"yoctobsp",
|
||||
"selftest",
|
||||
"skeleton",
|
||||
"openembedded-layer",
|
||||
"meta-python",
|
||||
"networking-layer",
|
||||
"multimedia-layer",
|
||||
"filesystems-layer",
|
||||
"webserver",
|
||||
"gnome-layer",
|
||||
"xfce-layer",
|
||||
"perl-layer",
|
||||
"meta-initramfs",
|
||||
"security",
|
||||
"virtualization-layer",
|
||||
"arm",
|
||||
"arm-bsp",
|
||||
"arm-toolchain",
|
||||
"intel",
|
||||
"freescale-layer",
|
||||
"raspberrypi",
|
||||
"clang-layer",
|
||||
"qt6-layer",
|
||||
];
|
||||
|
||||
/// The Yocto releases oelint-adv 9.11 knows, oldest first (its `--release`
|
||||
/// choices, without `latest`).
|
||||
const RELEASES: &[&str] = &[
|
||||
"inky",
|
||||
"clyde",
|
||||
"blinky",
|
||||
"pinky",
|
||||
"purple",
|
||||
"green",
|
||||
"laverne",
|
||||
"bernard",
|
||||
"edison",
|
||||
"denzil",
|
||||
"danny",
|
||||
"dylan",
|
||||
"dora",
|
||||
"daisy",
|
||||
"dizzy",
|
||||
"fido",
|
||||
"jethro",
|
||||
"krogoth",
|
||||
"morty",
|
||||
"pyro",
|
||||
"rocko",
|
||||
"sumo",
|
||||
"thud",
|
||||
"warrior",
|
||||
"zeus",
|
||||
"dunfell",
|
||||
"gatesgarth",
|
||||
"hardknott",
|
||||
"honister",
|
||||
"kirkstone",
|
||||
"langdale",
|
||||
"mickledore",
|
||||
"nanbield",
|
||||
"scarthgap",
|
||||
"styhead",
|
||||
"walnascar",
|
||||
"whinlatter",
|
||||
"wrynose",
|
||||
"blacksail",
|
||||
];
|
||||
|
||||
/// The CRA Annex I requirement a rule's finding is about. The control it is
|
||||
/// evidence for comes from the control map, by rule id.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Cra {
|
||||
/// Part I (2)(b): made available with a secure by default configuration.
|
||||
SecureByDefault,
|
||||
/// Part I (2)(j): designed to limit attack surfaces.
|
||||
AttackSurface,
|
||||
/// Part I (2)(f): the integrity of the software, here of what the image
|
||||
/// is built from.
|
||||
Integrity,
|
||||
/// Informational, not a requirement on its own.
|
||||
None,
|
||||
}
|
||||
|
||||
impl Cra {
|
||||
/// The requirement in words, for the finding's description.
|
||||
fn text(self) -> Option<&'static str> {
|
||||
match self {
|
||||
Self::SecureByDefault => Some(
|
||||
"CRA Annex I Part I (2)(b): products are made available with a secure by \
|
||||
default configuration.",
|
||||
),
|
||||
Self::AttackSurface => {
|
||||
Some("CRA Annex I Part I (2)(j): products are designed to limit attack surfaces.")
|
||||
}
|
||||
Self::Integrity => Some(
|
||||
"CRA Annex I Part I (2)(f): the integrity of the software is protected; an \
|
||||
image built from unverified or moving sources cannot be traced to them.",
|
||||
),
|
||||
Self::None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a rule reports: its scanner and id, title, severity, CWE, the CRA
|
||||
/// requirement and the fix.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RuleInfo {
|
||||
/// The scanner name findings carry.
|
||||
pub scanner: &'static str,
|
||||
/// The rule id findings carry.
|
||||
pub id: &'static str,
|
||||
/// The finding's title.
|
||||
pub title: &'static str,
|
||||
/// The finding's severity.
|
||||
pub severity: Severity,
|
||||
/// The weakness, as `CWE-<n>`.
|
||||
pub cwe: Option<&'static str>,
|
||||
/// The CRA requirement.
|
||||
pub cra: Cra,
|
||||
/// How to fix it.
|
||||
pub remediation: &'static str,
|
||||
}
|
||||
|
||||
/// A rule matching at a place, before it becomes a [`Finding`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct Hit {
|
||||
pub rule: &'static RuleInfo,
|
||||
/// The file, relative to the tree.
|
||||
pub path: String,
|
||||
/// The line, 1-based.
|
||||
pub line: u32,
|
||||
/// What the rule saw there, for the description; may be empty.
|
||||
pub detail: String,
|
||||
/// The snippet to show instead of the line (with a secret hidden).
|
||||
pub snippet: Option<String>,
|
||||
}
|
||||
|
||||
impl Hit {
|
||||
fn new(rule: &'static RuleInfo, path: &str, line: u32, detail: String) -> Self {
|
||||
Self {
|
||||
rule,
|
||||
path: path.to_string(),
|
||||
line,
|
||||
detail,
|
||||
snippet: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The finding of `repo_id` for this hit in the tree under `root`.
|
||||
fn into_finding(self, root: &Path, repo_id: &str) -> Finding {
|
||||
let rule = self.rule;
|
||||
let line = self.line.to_string();
|
||||
let fingerprint =
|
||||
dedup::compute_fingerprint(&[repo_id, rule.scanner, rule.id, &self.path, &line]);
|
||||
let description = [Some(self.detail.as_str()), rule.cra.text()]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|part| !part.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n\n");
|
||||
let mut finding = Finding::new(
|
||||
repo_id.to_string(),
|
||||
fingerprint,
|
||||
rule.scanner.to_string(),
|
||||
ScanType::RecipeLint,
|
||||
rule.title.to_string(),
|
||||
description,
|
||||
rule.severity.clone(),
|
||||
);
|
||||
finding.rule_id = Some(rule.id.to_string());
|
||||
finding.cwe = rule.cwe.map(str::to_string);
|
||||
finding.remediation = Some(rule.remediation.to_string());
|
||||
finding.code_snippet = self
|
||||
.snippet
|
||||
.or_else(|| read_lines(root, &self.path, self.line, self.line));
|
||||
finding.line_number = Some(self.line);
|
||||
finding.file_path = Some(self.path);
|
||||
finding
|
||||
}
|
||||
}
|
||||
|
||||
/// One layer of the tree and the files the recipe lint reads in it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct Layer {
|
||||
/// The layer's directory relative to the tree, `.` for the root.
|
||||
pub dir: String,
|
||||
/// The oldest release its `LAYERSERIES_COMPAT` names: the recipes are
|
||||
/// read with that release's syntax and rules.
|
||||
pub release: Option<&'static str>,
|
||||
/// An upstream layer, which is not linted.
|
||||
pub upstream: bool,
|
||||
/// The collections its `layer.conf` declares (`BBFILE_COLLECTIONS`).
|
||||
pub collections: Vec<String>,
|
||||
/// Every release its `LAYERSERIES_COMPAT_*` names, as written.
|
||||
pub compat: Vec<String>,
|
||||
/// Its files relative to the tree; a nested layer's files are its own.
|
||||
pub files: Vec<String>,
|
||||
}
|
||||
|
||||
impl Layer {
|
||||
/// `file` (relative to the tree) relative to the layer.
|
||||
fn inner<'a>(&self, file: &'a str) -> &'a str {
|
||||
if self.dir == "." {
|
||||
file
|
||||
} else {
|
||||
file.get(self.dir.len() + 1..).unwrap_or(file)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The recipe lint of one tree.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RecipeLint {
|
||||
layers: Vec<Layer>,
|
||||
}
|
||||
|
||||
impl RecipeLint {
|
||||
/// The recipe lint for a tree whose source `languages` include BitBake,
|
||||
/// skipping the `excluded` vendor directories; `None` otherwise.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `root` - the tree
|
||||
/// * `languages` - the source languages found outside vendor code
|
||||
/// * `excluded` - vendor directories relative to the tree
|
||||
pub fn for_tree(root: &Path, languages: &[String], excluded: &[String]) -> Option<Self> {
|
||||
languages.iter().any(|l| l == "bitbake").then(|| Self {
|
||||
layers: layers(root, excluded),
|
||||
})
|
||||
}
|
||||
|
||||
/// The upstream layers left out, relative to the tree.
|
||||
pub fn upstream_layers(&self) -> Vec<&str> {
|
||||
self.layers
|
||||
.iter()
|
||||
.filter(|l| l.upstream)
|
||||
.map(|l| l.dir.as_str())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What our own rules ([`rules`]) find in the customer's layers under
|
||||
/// `root`. They read files only, so they always complete.
|
||||
pub fn config_findings(&self, root: &Path, repo_id: &str) -> Vec<Finding> {
|
||||
self.config_hits(root)
|
||||
.into_iter()
|
||||
.map(|hit| hit.into_finding(root, repo_id))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The customer's layers: those the lint reads.
|
||||
fn own_layers(&self) -> impl Iterator<Item = &Layer> {
|
||||
self.layers.iter().filter(|l| !l.upstream)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the recipe lint reads `inner` (a path relative to its layer):
|
||||
/// recipes, appends, includes, classes, the layer's configuration, and what
|
||||
/// recipes ship in their `files/` (sshd configurations, certificates).
|
||||
fn is_read(inner: &str) -> bool {
|
||||
let name = inner.rsplit('/').next().unwrap_or(inner);
|
||||
let ext = name.rsplit_once('.').map_or("", |(_, ext)| ext);
|
||||
match ext {
|
||||
"bb" | "bbappend" | "bbclass" | "inc" => true,
|
||||
"conf" => inner.starts_with("conf/"),
|
||||
"sample" => name == "local.conf.sample",
|
||||
_ => rules::is_shipped_file(inner, name),
|
||||
}
|
||||
}
|
||||
|
||||
/// The layers of the tree under `root`, outside the `excluded` directories:
|
||||
/// each directory holding a `conf/layer.conf`. A tree without one (loose
|
||||
/// recipes) is read as a single layer.
|
||||
pub(crate) fn layers(root: &Path, excluded: &[String]) -> Vec<Layer> {
|
||||
let files: Vec<String> = walkdir::WalkDir::new(root)
|
||||
.min_depth(1)
|
||||
.into_iter()
|
||||
.filter_entry(|e| {
|
||||
let rel = rel_path(root, e.path());
|
||||
!(e.file_type().is_dir()
|
||||
&& (SKIPPED_DIRS.contains(&e.file_name().to_string_lossy().as_ref())
|
||||
|| excluded.contains(&rel)))
|
||||
})
|
||||
.filter_map(Result::ok)
|
||||
.filter(|e| e.file_type().is_file())
|
||||
.map(|e| rel_path(root, e.path()))
|
||||
.collect();
|
||||
let mut dirs: Vec<String> = files
|
||||
.iter()
|
||||
.filter_map(|f| match f.strip_suffix("conf/layer.conf") {
|
||||
Some("") => Some(".".to_string()),
|
||||
Some(dir) => dir.strip_suffix('/').map(str::to_string),
|
||||
None => None,
|
||||
})
|
||||
.collect();
|
||||
if dirs.is_empty() {
|
||||
dirs.push(".".to_string());
|
||||
}
|
||||
// Deepest first, so a file belongs to the innermost layer holding it.
|
||||
dirs.sort_by_key(|d| std::cmp::Reverse(d.len()));
|
||||
let mut by_dir: BTreeMap<String, Vec<String>> = BTreeMap::new();
|
||||
for file in files {
|
||||
let owner = dirs
|
||||
.iter()
|
||||
.find(|d| d.as_str() == "." || file.starts_with(&format!("{d}/")));
|
||||
if let Some(owner) = owner {
|
||||
by_dir.entry(owner.clone()).or_default().push(file);
|
||||
}
|
||||
}
|
||||
dirs.sort();
|
||||
dirs.into_iter()
|
||||
.map(|dir| {
|
||||
let conf = if dir == "." {
|
||||
"conf/layer.conf".to_string()
|
||||
} else {
|
||||
format!("{dir}/conf/layer.conf")
|
||||
};
|
||||
let (collections, compat) = read_text(root, &conf)
|
||||
.map(|text| layer_conf(&text))
|
||||
.unwrap_or_default();
|
||||
let mut layer = Layer {
|
||||
upstream: collections
|
||||
.iter()
|
||||
.any(|c| UPSTREAM_COLLECTIONS.contains(&c.as_str())),
|
||||
release: oldest_release(&compat),
|
||||
files: Vec::new(),
|
||||
dir,
|
||||
collections,
|
||||
compat,
|
||||
};
|
||||
let mut files = by_dir.remove(&layer.dir).unwrap_or_default();
|
||||
files.retain(|f| is_read(layer.inner(f)));
|
||||
files.sort();
|
||||
layer.files = files;
|
||||
layer
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `path` relative to `root`, `/`-separated.
|
||||
pub(crate) fn rel_path(root: &Path, path: &Path) -> String {
|
||||
path.strip_prefix(root)
|
||||
.unwrap_or(path)
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/")
|
||||
}
|
||||
|
||||
/// The collections a `layer.conf` declares and the releases it is compatible
|
||||
/// with (`BBFILE_COLLECTIONS`, `LAYERSERIES_COMPAT_*`).
|
||||
fn layer_conf(text: &str) -> (Vec<String>, Vec<String>) {
|
||||
let mut collections = Vec::new();
|
||||
let mut compat = Vec::new();
|
||||
for assignment in rules::assignments(text) {
|
||||
let words = assignment
|
||||
.value
|
||||
.split_whitespace()
|
||||
.map(str::to_string)
|
||||
.collect::<Vec<_>>();
|
||||
if assignment.var == "BBFILE_COLLECTIONS" {
|
||||
collections.extend(words);
|
||||
} else if assignment.var.starts_with("LAYERSERIES_COMPAT_") {
|
||||
compat.extend(words);
|
||||
}
|
||||
}
|
||||
(collections, compat)
|
||||
}
|
||||
|
||||
/// The oldest of `releases` oelint-adv knows.
|
||||
fn oldest_release(releases: &[String]) -> Option<&'static str> {
|
||||
RELEASES
|
||||
.iter()
|
||||
.find(|known| releases.iter().any(|r| r == *known))
|
||||
.copied()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A scratch tree holding `files`, removed on drop.
|
||||
pub(crate) struct Tree(pub PathBuf);
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn tree(files: &[(&str, &str)]) -> Tree {
|
||||
let dir = std::env::temp_dir().join(format!("cs-recipe-lint-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&dir).expect("mkdir");
|
||||
for (path, content) in files {
|
||||
let full = dir.join(path);
|
||||
std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir");
|
||||
std::fs::write(full, content).expect("write");
|
||||
}
|
||||
Tree(dir)
|
||||
}
|
||||
|
||||
const POKY_META: &str =
|
||||
"BBFILE_COLLECTIONS += \"core\"\nLAYERSERIES_COMPAT_core = \"scarthgap\"\n";
|
||||
const OWN: &str =
|
||||
"BBFILE_COLLECTIONS += \"pump\"\nLAYERSERIES_COMPAT_pump = \"scarthgap kirkstone\"\n";
|
||||
|
||||
#[test]
|
||||
fn layers_are_found_with_their_release_and_upstream_ones_marked() {
|
||||
let t = tree(&[
|
||||
("poky/meta/conf/layer.conf", POKY_META),
|
||||
("poky/meta/recipes-core/busybox/busybox_1.36.bb", ""),
|
||||
("meta-pump/conf/layer.conf", OWN),
|
||||
("meta-pump/conf/distro/pump.conf", ""),
|
||||
("meta-pump/recipes-app/pump/pump_1.0.bb", ""),
|
||||
("meta-pump/recipes-app/pump/files/pump.c", ""),
|
||||
("meta-pump/recipes-app/pump/files/server.pem", ""),
|
||||
("meta-pump/README.md", ""),
|
||||
("build/conf/local.conf", ""),
|
||||
]);
|
||||
let lint = RecipeLint::for_tree(&t.0, &["bitbake".to_string()], &[]).expect("bitbake");
|
||||
assert_eq!(lint.upstream_layers(), ["poky/meta"]);
|
||||
let own: Vec<&Layer> = lint.own_layers().collect();
|
||||
assert_eq!(own.len(), 1);
|
||||
assert_eq!(own[0].dir, "meta-pump");
|
||||
// The oldest compatible release.
|
||||
assert_eq!(own[0].release, Some("kirkstone"));
|
||||
assert_eq!(
|
||||
own[0].files,
|
||||
[
|
||||
"meta-pump/conf/distro/pump.conf",
|
||||
"meta-pump/conf/layer.conf",
|
||||
"meta-pump/recipes-app/pump/files/server.pem",
|
||||
"meta-pump/recipes-app/pump/pump_1.0.bb",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loose_recipes_are_one_layer_and_other_trees_are_not_linted() {
|
||||
let t = tree(&[("recipes-app/pump/pump_1.0.bb", "")]);
|
||||
let lint = RecipeLint::for_tree(&t.0, &["bitbake".to_string()], &[]).expect("bitbake");
|
||||
let own: Vec<&Layer> = lint.own_layers().collect();
|
||||
assert_eq!(own[0].dir, ".");
|
||||
assert_eq!(own[0].release, None);
|
||||
assert!(RecipeLint::for_tree(&t.0, &["c".to_string()], &[]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vendor_directories_are_not_read() {
|
||||
let t = tree(&[
|
||||
("conf/layer.conf", OWN),
|
||||
("vendor/recipes-x/x/x_1.0.bb", ""),
|
||||
("recipes-app/pump/pump_1.0.bb", ""),
|
||||
]);
|
||||
let lint = RecipeLint::for_tree(&t.0, &["bitbake".to_string()], &["vendor".to_string()])
|
||||
.expect("bitbake");
|
||||
assert_eq!(
|
||||
lint.layers[0].files,
|
||||
["conf/layer.conf", "recipes-app/pump/pump_1.0.bb"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_rule_with_a_cra_requirement_is_bound_in_the_control_map() {
|
||||
let map = control_map::ControlMap::cra().expect("map");
|
||||
let all = oelint::RULES.iter().chain(rules::RULES.iter().copied());
|
||||
for rule in all {
|
||||
let bound = !map
|
||||
.controls_for_finding(rule.scanner, None, Some(rule.id))
|
||||
.is_empty();
|
||||
assert_eq!(bound, rule.cra != Cra::None, "{}", rule.id);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hit_becomes_a_recipe_lint_finding_with_its_cra_requirement() {
|
||||
let t = tree(&[("recipes-app/x/x.bb", "SRC_URI = \"http://x/y.tgz\"\n")]);
|
||||
let rule = &rules::RULES[1];
|
||||
let finding = Hit::new(rule, "recipes-app/x/x.bb", 1, "Fetched without TLS".into())
|
||||
.into_finding(&t.0, "t");
|
||||
assert_eq!(finding.scanner, "yocto-config");
|
||||
assert_eq!(finding.scan_type, ScanType::RecipeLint);
|
||||
assert_eq!(finding.rule_id.as_deref(), Some("yocto-src-uri-http"));
|
||||
assert!(finding
|
||||
.description
|
||||
.starts_with("Fetched without TLS\n\nCRA Annex I"));
|
||||
assert_eq!(
|
||||
finding.code_snippet.as_deref(),
|
||||
Some("SRC_URI = \"http://x/y.tgz\"")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_releases_are_ignored() {
|
||||
assert_eq!(oldest_release(&["future".to_string()]), None);
|
||||
assert_eq!(
|
||||
oldest_release(&["wrynose".to_string(), "dunfell".to_string()]),
|
||||
Some("dunfell")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,617 @@
|
||||
//! oelint-adv (BSD-2-Clause, used unchanged) with only its security rules.
|
||||
//!
|
||||
//! oelint-adv is mostly a style linter for the OpenEmbedded style guide; the
|
||||
//! rule file passed with `--rulefile` loads only the rules in [`RULES`], so
|
||||
//! none of the style rules run. Two of its defaults are not safe for a
|
||||
//! customer's tree:
|
||||
//!
|
||||
//! - it reads a `.oelint.cfg` from the working directory, which would let the
|
||||
//! repository switch rules off: `OELINT_SKIP_CONFIG` turns that off;
|
||||
//! - it caches results under the home directory only with `--cached`, which
|
||||
//! is never passed.
|
||||
//!
|
||||
//! Each layer is read with the oldest release its `LAYERSERIES_COMPAT` names
|
||||
//! (`--release`): the syntax (`_append` before Kirkstone) and which rules
|
||||
//! apply depend on it. `oelint.vars.srcurigittag`, for one, only applies up
|
||||
//! to Walnascar; later BitBake checks the tag itself.
|
||||
//!
|
||||
//! A `# nooelint: <rule>` comment in a recipe suppresses a finding there, as
|
||||
//! oelint-adv intends. oelint-adv drops suppressed findings without a trace,
|
||||
//! so they are counted: the suppressions of our rules in the recipes, less
|
||||
//! those oelint-adv reports as not needed (`oelint.file.inlinesuppress_na`).
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use compliance_core::models::{Finding, Severity};
|
||||
use compliance_core::CoreError;
|
||||
|
||||
use super::{Cra, Hit, RecipeLint, RuleInfo};
|
||||
|
||||
/// The scanner name of oelint-adv's findings.
|
||||
pub const SCANNER: &str = "oelint-adv";
|
||||
|
||||
/// oelint-adv's report of a `# nooelint` comment that suppressed nothing.
|
||||
const UNUSED_SUPPRESSION: &str = "oelint.file.inlinesuppress_na";
|
||||
|
||||
/// The id of every image-feature rule at once, as a suppression may name it.
|
||||
const IMAGE_FEATURES: &str = "oelint.var.badimagefeature";
|
||||
|
||||
/// How long one run may take before it is stopped and recorded as failed.
|
||||
const TIMEOUT: Duration = Duration::from_secs(600);
|
||||
|
||||
/// Files per run, so a tree with many recipes stays under the argument
|
||||
/// limit. A recipe and its appends are in the same layer, and a layer's files
|
||||
/// are sorted, so they mostly stay in one run.
|
||||
const FILES_PER_RUN: usize = 1000;
|
||||
|
||||
/// A security rule of oelint-adv and what it means.
|
||||
const fn rule(
|
||||
id: &'static str,
|
||||
title: &'static str,
|
||||
severity: Severity,
|
||||
cwe: Option<&'static str>,
|
||||
cra: Cra,
|
||||
remediation: &'static str,
|
||||
) -> RuleInfo {
|
||||
RuleInfo {
|
||||
scanner: SCANNER,
|
||||
id,
|
||||
title,
|
||||
severity,
|
||||
cwe,
|
||||
cra,
|
||||
remediation,
|
||||
}
|
||||
}
|
||||
|
||||
/// Removing a debug or development image feature.
|
||||
const DROP_FEATURE: &str = "Remove the feature from IMAGE_FEATURES / EXTRA_IMAGE_FEATURES of \
|
||||
the product image; keep it in a separate development image.";
|
||||
|
||||
/// The rules that run, by their id in oelint-adv 9.11.
|
||||
pub static RULES: [RuleInfo; 13] = [
|
||||
rule(
|
||||
"oelint.var.badimagefeature.debug-tweaks",
|
||||
"Image feature debug-tweaks (empty root password, root login)",
|
||||
Severity::High,
|
||||
Some("CWE-258"),
|
||||
Cra::SecureByDefault,
|
||||
DROP_FEATURE,
|
||||
),
|
||||
rule(
|
||||
"oelint.var.badimagefeature.allow-empty-password",
|
||||
"Image feature allow-empty-password",
|
||||
Severity::High,
|
||||
Some("CWE-258"),
|
||||
Cra::SecureByDefault,
|
||||
DROP_FEATURE,
|
||||
),
|
||||
rule(
|
||||
"oelint.var.badimagefeature.empty-root-password",
|
||||
"Image feature empty-root-password",
|
||||
Severity::High,
|
||||
Some("CWE-258"),
|
||||
Cra::SecureByDefault,
|
||||
DROP_FEATURE,
|
||||
),
|
||||
rule(
|
||||
"oelint.var.badimagefeature.serial-autologin-root",
|
||||
"Image feature serial-autologin-root",
|
||||
Severity::High,
|
||||
Some("CWE-306"),
|
||||
Cra::SecureByDefault,
|
||||
DROP_FEATURE,
|
||||
),
|
||||
rule(
|
||||
"oelint.var.badimagefeature.allow-root-login",
|
||||
"Image feature allow-root-login",
|
||||
Severity::Medium,
|
||||
Some("CWE-1188"),
|
||||
Cra::SecureByDefault,
|
||||
DROP_FEATURE,
|
||||
),
|
||||
rule(
|
||||
"oelint.var.badimagefeature.tools-debug",
|
||||
"Image feature tools-debug (debugging tools on the device)",
|
||||
Severity::Low,
|
||||
Some("CWE-489"),
|
||||
Cra::SecureByDefault,
|
||||
DROP_FEATURE,
|
||||
),
|
||||
rule(
|
||||
"oelint.var.badimagefeature.dbg-pkgs",
|
||||
"Image feature dbg-pkgs (debug symbols on the device)",
|
||||
Severity::Low,
|
||||
Some("CWE-489"),
|
||||
Cra::SecureByDefault,
|
||||
DROP_FEATURE,
|
||||
),
|
||||
rule(
|
||||
"oelint.var.badimagefeature.dev-pkgs",
|
||||
"Image feature dev-pkgs (development files on the device)",
|
||||
Severity::Low,
|
||||
Some("CWE-489"),
|
||||
Cra::SecureByDefault,
|
||||
DROP_FEATURE,
|
||||
),
|
||||
rule(
|
||||
"oelint.vars.srcurichecksum",
|
||||
"Fetched source without a checksum",
|
||||
Severity::Medium,
|
||||
Some("CWE-494"),
|
||||
Cra::Integrity,
|
||||
"Add SRC_URI[sha256sum] for every downloaded file, so a changed or swapped download \
|
||||
fails the build.",
|
||||
),
|
||||
rule(
|
||||
"oelint.vars.autorev",
|
||||
"SRCREV follows the branch head (AUTOREV)",
|
||||
Severity::Medium,
|
||||
Some("CWE-494"),
|
||||
Cra::Integrity,
|
||||
"Pin SRCREV to a commit: with AUTOREV every build takes whatever the branch holds, \
|
||||
and the image cannot be rebuilt or traced to its sources.",
|
||||
),
|
||||
rule(
|
||||
"oelint.vars.srcurigittag",
|
||||
"Git source pinned by a tag instead of a commit",
|
||||
Severity::Low,
|
||||
Some("CWE-494"),
|
||||
Cra::Integrity,
|
||||
"Pin SRCREV to a commit: a tag can be moved.",
|
||||
),
|
||||
rule(
|
||||
"oelint.task.network",
|
||||
"Task with network access",
|
||||
Severity::Medium,
|
||||
Some("CWE-494"),
|
||||
Cra::AttackSurface,
|
||||
"Fetch in do_fetch through SRC_URI, with checksums, instead of giving a build task \
|
||||
network access.",
|
||||
),
|
||||
rule(
|
||||
"oelint.vars.insaneskip",
|
||||
"QA checks skipped (INSANE_SKIP)",
|
||||
Severity::Low,
|
||||
None,
|
||||
Cra::None,
|
||||
"Fix what the QA check reports instead of skipping it; some (ldflags, \
|
||||
already-stripped, textrel) guard the binaries' hardening.",
|
||||
),
|
||||
];
|
||||
|
||||
/// The rule file passed with `--rulefile`: only [`RULES`] are loaded, and
|
||||
/// the report of suppressions that suppressed nothing. An empty severity keeps
|
||||
/// oelint-adv's own; ours come from [`RULES`].
|
||||
fn rulefile() -> String {
|
||||
let entries: serde_json::Map<String, serde_json::Value> = RULES
|
||||
.iter()
|
||||
.map(|r| r.id)
|
||||
.chain([UNUSED_SUPPRESSION])
|
||||
.map(|id| (id.to_string(), serde_json::Value::String(String::new())))
|
||||
.collect();
|
||||
serde_json::Value::Object(entries).to_string()
|
||||
}
|
||||
|
||||
/// One issue of oelint-adv's `gitlab-codequality` report.
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
struct Issue {
|
||||
check_name: String,
|
||||
description: String,
|
||||
location: Location,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
struct Location {
|
||||
path: String,
|
||||
lines: Lines,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
struct Lines {
|
||||
begin: u32,
|
||||
}
|
||||
|
||||
/// What one oelint-adv run reported.
|
||||
#[derive(Debug, Default)]
|
||||
struct Report {
|
||||
hits: Vec<Hit>,
|
||||
/// `# nooelint` suppressions of our rules that suppressed nothing.
|
||||
unused_suppressions: usize,
|
||||
}
|
||||
|
||||
/// The hits in a `gitlab-codequality` `report`. An issue is reported once per
|
||||
/// place, though oelint-adv repeats it for each configuration it tries; a
|
||||
/// rule we did not ask for is dropped.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns the parse error when `report` is not that format.
|
||||
fn parse_report(report: &str) -> Result<Report, serde_json::Error> {
|
||||
let issues: Vec<Issue> = serde_json::from_str(report)?;
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut unused = BTreeSet::new();
|
||||
let mut hits = Vec::new();
|
||||
for issue in issues {
|
||||
let path = issue
|
||||
.location
|
||||
.path
|
||||
.strip_prefix("./")
|
||||
.unwrap_or(&issue.location.path)
|
||||
.to_string();
|
||||
let line = issue.location.lines.begin.max(1);
|
||||
if issue.check_name == UNUSED_SUPPRESSION {
|
||||
// "Inline suppression for '<id>' is not needed"
|
||||
if let Some(id) = issue.description.split('\'').nth(1) {
|
||||
if is_ours(id) {
|
||||
unused.insert((path, line, id.to_string()));
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some(rule) = RULES.iter().find(|r| r.id == issue.check_name) else {
|
||||
continue;
|
||||
};
|
||||
if !seen.insert((rule.id, path.clone(), line)) {
|
||||
continue;
|
||||
}
|
||||
// `[branch:true]` names the configuration oelint-adv tried.
|
||||
let detail = match issue.description.rsplit_once(" [") {
|
||||
Some((text, matrix)) if matrix.ends_with(']') => text,
|
||||
_ => issue.description.as_str(),
|
||||
};
|
||||
hits.push(Hit::new(rule, &path, line, detail.to_string()));
|
||||
}
|
||||
Ok(Report {
|
||||
hits,
|
||||
unused_suppressions: unused.len(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a suppression naming `id` can suppress one of our rules.
|
||||
fn is_ours(id: &str) -> bool {
|
||||
id == IMAGE_FEATURES || RULES.iter().any(|r| r.id == id)
|
||||
}
|
||||
|
||||
/// How many suppressions of our rules the `# nooelint:` comments in `text`
|
||||
/// name, read as oelint-adv reads them.
|
||||
fn suppressions(text: &str) -> usize {
|
||||
text.lines()
|
||||
.filter_map(|line| {
|
||||
let rest = line.trim_start().strip_prefix('#')?;
|
||||
// `#\s+nooelint:\s+<ids>`, as oelint-adv matches it.
|
||||
let ids = rest.trim_start().strip_prefix("nooelint:").filter(|ids| {
|
||||
rest.starts_with(char::is_whitespace) && ids.starts_with(char::is_whitespace)
|
||||
})?;
|
||||
Some(
|
||||
ids.split(|c: char| c == ',' || c.is_whitespace())
|
||||
.filter(|id| is_ours(id))
|
||||
.count(),
|
||||
)
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// oelint-adv's findings, and how many it did not report because a
|
||||
/// `# nooelint` comment suppressed them.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct OelintOutput {
|
||||
/// The findings.
|
||||
pub findings: Vec<Finding>,
|
||||
/// Suppressions of our rules in the recipes that took effect.
|
||||
pub suppressed: usize,
|
||||
}
|
||||
|
||||
/// A scanner error with `source` as its cause.
|
||||
fn failed(source: Box<dyn std::error::Error + Send + Sync>) -> CoreError {
|
||||
CoreError::Scanner {
|
||||
scanner: SCANNER.to_string(),
|
||||
source,
|
||||
}
|
||||
}
|
||||
|
||||
impl RecipeLint {
|
||||
/// oelint-adv's findings in the customer's layers under `root`, and the
|
||||
/// findings suppressed by comments there.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `CoreError::Scanner` when oelint-adv cannot start, times out,
|
||||
/// exits with an error, or writes a report that cannot be read.
|
||||
pub async fn oelint_findings(
|
||||
&self,
|
||||
root: &Path,
|
||||
repo_id: &str,
|
||||
) -> Result<OelintOutput, CoreError> {
|
||||
let work = WorkDir::new().map_err(|e| failed(Box::new(e)))?;
|
||||
let mut hits = Vec::new();
|
||||
let mut unused = 0;
|
||||
let mut named = 0;
|
||||
for layer in self.own_layers() {
|
||||
// Includes are read through the recipes, so their comments count.
|
||||
named += layer
|
||||
.files
|
||||
.iter()
|
||||
.filter(|f| {
|
||||
let inner = layer.inner(f);
|
||||
is_bitbake(inner) || inner.ends_with(".inc")
|
||||
})
|
||||
.filter_map(|f| super::read_text(root, f))
|
||||
.map(|text| suppressions(&text))
|
||||
.sum::<usize>();
|
||||
let files: Vec<&String> = layer
|
||||
.files
|
||||
.iter()
|
||||
.filter(|f| is_bitbake(layer.inner(f)))
|
||||
.collect();
|
||||
for chunk in files.chunks(FILES_PER_RUN) {
|
||||
let report = parse_report(&run(root, layer.release, chunk, &work).await?)?;
|
||||
hits.extend(report.hits);
|
||||
unused += report.unused_suppressions;
|
||||
}
|
||||
}
|
||||
Ok(OelintOutput {
|
||||
findings: hits
|
||||
.into_iter()
|
||||
.map(|hit| hit.into_finding(root, repo_id))
|
||||
.collect(),
|
||||
suppressed: named.saturating_sub(unused),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether oelint-adv reads `inner` (relative to its layer): recipes,
|
||||
/// appends, classes and the layer's configuration. Includes are read through
|
||||
/// the recipes that require them.
|
||||
fn is_bitbake(inner: &str) -> bool {
|
||||
let ext = inner.rsplit_once('.').map_or("", |(_, ext)| ext);
|
||||
matches!(ext, "bb" | "bbappend" | "bbclass") || (ext == "conf" && inner.starts_with("conf/"))
|
||||
}
|
||||
|
||||
/// One oelint-adv run over `files` (relative to `root`) read as `release`.
|
||||
async fn run(
|
||||
root: &Path,
|
||||
release: Option<&str>,
|
||||
files: &[&String],
|
||||
work: &WorkDir,
|
||||
) -> Result<String, CoreError> {
|
||||
let mut cmd = crate::pipeline::tool_cmd::tool_in(SCANNER, root, &[]);
|
||||
cmd.env("OELINT_SKIP_CONFIG", "1")
|
||||
.args(["--quiet", "--exit-zero", "--relpaths", "--jobs", "2"])
|
||||
.args([
|
||||
"--outputformat",
|
||||
"gitlab-codequality",
|
||||
"--messageformat",
|
||||
"{msg}",
|
||||
])
|
||||
.arg("--rulefile")
|
||||
.arg(work.rulefile())
|
||||
.arg("--output")
|
||||
.arg(work.report());
|
||||
if let Some(release) = release {
|
||||
cmd.args(["--release", release]);
|
||||
}
|
||||
cmd.args(files.iter().map(|f| f.as_str()));
|
||||
let output = crate::pipeline::tool_cmd::run_bounded_for(&mut cmd, SCANNER, TIMEOUT)
|
||||
.await
|
||||
.map_err(|e| failed(Box::new(e)))?;
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let tail: String = stderr.lines().rev().take(3).collect::<Vec<_>>().join(" / ");
|
||||
return Err(failed(
|
||||
format!("exited with {}: {tail}", output.status).into(),
|
||||
));
|
||||
}
|
||||
let report = std::fs::read_to_string(work.report()).map_err(|e| failed(Box::new(e)))?;
|
||||
// The report is rewritten by every run.
|
||||
let _ = std::fs::remove_file(work.report());
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// The rule file and report of the runs, in a temporary directory removed on
|
||||
/// drop.
|
||||
struct WorkDir(PathBuf);
|
||||
|
||||
impl WorkDir {
|
||||
fn new() -> std::io::Result<Self> {
|
||||
let dir = std::env::temp_dir().join(format!("cs-oelint-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
let work = Self(dir);
|
||||
std::fs::write(work.rulefile(), rulefile())?;
|
||||
Ok(work)
|
||||
}
|
||||
|
||||
fn rulefile(&self) -> PathBuf {
|
||||
self.0.join("rules.json")
|
||||
}
|
||||
|
||||
fn report(&self) -> PathBuf {
|
||||
self.0.join("report.json")
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WorkDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const REPORT: &str = r#"[
|
||||
{"description": "EXTRA_IMAGE_FEATURES contains 'debug-tweaks', that is a security risk. Allows limitless access without authentication [branch:true]",
|
||||
"check_name": "oelint.var.badimagefeature.debug-tweaks",
|
||||
"fingerprint": "a", "location": {"path": "recipes-core/images/pump-image.bb", "lines": {"begin": 8}},
|
||||
"severity": "minor"},
|
||||
{"description": "EXTRA_IMAGE_FEATURES contains 'debug-tweaks', that is a security risk. Allows limitless access without authentication [branch:false]",
|
||||
"check_name": "oelint.var.badimagefeature.debug-tweaks",
|
||||
"fingerprint": "b", "location": {"path": "recipes-core/images/pump-image.bb", "lines": {"begin": 8}},
|
||||
"severity": "minor"},
|
||||
{"description": "Variable 'HOMEPAGE' should be set [branch:true]",
|
||||
"check_name": "oelint.var.mandatoryvar.HOMEPAGE",
|
||||
"fingerprint": "c", "location": {"path": "recipes-app/x/x.bb", "lines": {"begin": 1}},
|
||||
"severity": "critical"},
|
||||
{"description": "SRC_URI[sha256sum] is needed",
|
||||
"check_name": "oelint.vars.srcurichecksum",
|
||||
"fingerprint": "d", "location": {"path": "./recipes-app/web/web_2.1.bb", "lines": {"begin": 0}},
|
||||
"severity": "critical"},
|
||||
{"description": "Inline suppression for 'oelint.vars.autorev' is not needed",
|
||||
"check_name": "oelint.file.inlinesuppress_na",
|
||||
"fingerprint": "e", "location": {"path": "recipes-app/web/web_2.1.bb", "lines": {"begin": 9}},
|
||||
"severity": "info"},
|
||||
{"description": "Inline suppression for 'oelint.vars.autorev' is not needed",
|
||||
"check_name": "oelint.file.inlinesuppress_na",
|
||||
"fingerprint": "f", "location": {"path": "recipes-app/web/web_2.1.bb", "lines": {"begin": 9}},
|
||||
"severity": "info"},
|
||||
{"description": "Inline suppression for 'oelint.var.order.PV' is not needed",
|
||||
"check_name": "oelint.file.inlinesuppress_na",
|
||||
"fingerprint": "g", "location": {"path": "recipes-app/web/web_2.1.bb", "lines": {"begin": 3}},
|
||||
"severity": "info"}
|
||||
]"#;
|
||||
|
||||
#[test]
|
||||
fn the_report_becomes_one_hit_per_rule_and_place() {
|
||||
let report = parse_report(REPORT).expect("report");
|
||||
assert_eq!(report.unused_suppressions, 1);
|
||||
let hits = report.hits;
|
||||
let got: Vec<(&str, &str, u32, Severity)> = hits
|
||||
.iter()
|
||||
.map(|h| (h.rule.id, h.path.as_str(), h.line, h.rule.severity.clone()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
got,
|
||||
[
|
||||
(
|
||||
"oelint.var.badimagefeature.debug-tweaks",
|
||||
"recipes-core/images/pump-image.bb",
|
||||
8,
|
||||
Severity::High
|
||||
),
|
||||
(
|
||||
"oelint.vars.srcurichecksum",
|
||||
"recipes-app/web/web_2.1.bb",
|
||||
1,
|
||||
Severity::Medium
|
||||
),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
hits[0].detail,
|
||||
"EXTRA_IMAGE_FEATURES contains 'debug-tweaks', that is a security risk. Allows \
|
||||
limitless access without authentication"
|
||||
);
|
||||
assert!(parse_report("not json").is_err());
|
||||
assert!(parse_report("[]").expect("empty").hits.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rule_file_lists_only_the_security_rules() {
|
||||
let file: serde_json::Map<String, serde_json::Value> =
|
||||
serde_json::from_str(&rulefile()).expect("json");
|
||||
assert_eq!(file.len(), RULES.len() + 1);
|
||||
assert!(file.contains_key(UNUSED_SUPPRESSION));
|
||||
assert!(file.keys().all(|id| id.starts_with("oelint.")));
|
||||
assert!(!file.contains_key("oelint.var.badimagefeature"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suppressions_of_our_rules_are_counted_as_oelint_adv_reads_them() {
|
||||
let text = "# nooelint: oelint.vars.autorev, oelint.var.order.PV\n\
|
||||
SRCREV = \"${AUTOREV}\"\n\
|
||||
# nooelint: oelint.var.badimagefeature oelint.task.network\n\
|
||||
#nooelint: oelint.vars.insaneskip\n\
|
||||
# nooelint:oelint.vars.insaneskip\n\
|
||||
# a note about nooelint: oelint.vars.autorev\n";
|
||||
// One of the two on the first comment and both on the second; the
|
||||
// third lacks the space oelint-adv requires, the last is prose.
|
||||
assert_eq!(suppressions(text), 3);
|
||||
assert_eq!(suppressions("SRC_URI = \"x\"\n"), 0);
|
||||
}
|
||||
|
||||
/// The fixture with `# nooelint` comments: one that suppresses a
|
||||
/// finding and one in the wrong place.
|
||||
#[tokio::test]
|
||||
async fn suppressed_findings_are_counted() {
|
||||
if !installed() {
|
||||
return;
|
||||
}
|
||||
let fixture =
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../fixtures/nightly/firmware/yocto-layer");
|
||||
let read = |rel: &str| std::fs::read_to_string(fixture.join(rel)).expect("fixture");
|
||||
let fw = read("recipes-app/pump-fw/pump-fw_git.bb")
|
||||
.replace("SRCREV = ", "# nooelint: oelint.vars.autorev\nSRCREV = ");
|
||||
let web = read("recipes-app/pump-web/pump-web_2.1.bb").replace(
|
||||
"do_compile() {",
|
||||
"# nooelint: oelint.task.network\ndo_compile() {",
|
||||
);
|
||||
let t = super::super::tests::tree(&[
|
||||
("conf/layer.conf", &read("conf/layer.conf")),
|
||||
("recipes-app/pump-fw/pump-fw_git.bb", &fw),
|
||||
("recipes-app/pump-web/pump-web_2.1.bb", &web),
|
||||
]);
|
||||
let lint = RecipeLint::for_tree(&t.0, &["bitbake".to_string()], &[]).expect("lint");
|
||||
let out = lint.oelint_findings(&t.0, "t").await.expect("oelint-adv");
|
||||
let rules: Vec<&str> = out
|
||||
.findings
|
||||
.iter()
|
||||
.filter_map(|f| f.rule_id.as_deref())
|
||||
.collect();
|
||||
assert!(!rules.contains(&"oelint.vars.autorev"));
|
||||
assert!(rules.contains(&"oelint.task.network"));
|
||||
assert_eq!(out.suppressed, 1);
|
||||
}
|
||||
|
||||
/// Whether oelint-adv is on the PATH (the agent image has it).
|
||||
fn installed() -> bool {
|
||||
let found = std::process::Command::new(SCANNER)
|
||||
.arg("--version")
|
||||
.output()
|
||||
.is_ok_and(|o| o.status.success());
|
||||
if !found {
|
||||
eprintln!("oelint-adv is not installed; skipping");
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// Runs the real oelint-adv over the nightly fixture when it is on the
|
||||
/// PATH (the agent image has it); passes without it.
|
||||
#[tokio::test]
|
||||
async fn the_fixture_layer_yields_the_security_findings() {
|
||||
if !installed() {
|
||||
return;
|
||||
}
|
||||
let root =
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../fixtures/nightly/firmware/yocto-layer");
|
||||
let lint = RecipeLint::for_tree(&root, &["bitbake".to_string()], &[]).expect("lint");
|
||||
let out = lint.oelint_findings(&root, "t").await.expect("oelint-adv");
|
||||
assert_eq!(out.suppressed, 0);
|
||||
let mut got: Vec<String> = out
|
||||
.findings
|
||||
.iter()
|
||||
.map(|f| {
|
||||
format!(
|
||||
"{} {}:{}",
|
||||
f.rule_id.as_deref().unwrap_or_default(),
|
||||
f.file_path.as_deref().unwrap_or_default(),
|
||||
f.line_number.unwrap_or(0)
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
got.sort();
|
||||
assert_eq!(
|
||||
got,
|
||||
[
|
||||
"oelint.task.network recipes-app/pump-web/pump-web_2.1.bb:8",
|
||||
"oelint.var.badimagefeature.allow-empty-password recipes-core/images/pump-image.bb:7",
|
||||
"oelint.var.badimagefeature.debug-tweaks recipes-core/images/pump-image.bb:8",
|
||||
"oelint.vars.autorev recipes-app/pump-fw/pump-fw_git.bb:6",
|
||||
"oelint.vars.srcurichecksum recipes-app/pump-web/pump-web_2.1.bb:6",
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,620 @@
|
||||
//! Our own secure-by-default rules for Yocto layers (`yocto-config`).
|
||||
//!
|
||||
//! What oelint-adv does not check, read from the layer files without running
|
||||
//! BitBake:
|
||||
//!
|
||||
//! - a password (hash or clear text) in `EXTRA_USERS_PARAMS`: every device
|
||||
//! gets the same one;
|
||||
//! - an `http://` fetch in `SRC_URI`;
|
||||
//! - a shipped `sshd_config` with `PermitRootLogin yes` or
|
||||
//! `PasswordAuthentication yes`;
|
||||
//! - a certificate shipped with a recipe (informational: which trust anchors
|
||||
//! the image carries). Private keys are the secret scanner's (gitleaks
|
||||
//! reports PEM keys anywhere in the tree), so they are not reported twice;
|
||||
//! - a distro configuration, or a `local.conf.sample` without a distro, that
|
||||
//! does not pull in `security_flags.inc` (stack protector, FORTIFY_SOURCE,
|
||||
//! PIE, RELRO).
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::Path;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use compliance_core::models::Severity;
|
||||
use regex::Regex;
|
||||
|
||||
use super::{Cra, Hit, Layer, RecipeLint, RuleInfo};
|
||||
use crate::pipeline::source_text::read_text;
|
||||
|
||||
/// The scanner name of these rules' findings.
|
||||
pub const SCANNER: &str = "yocto-config";
|
||||
|
||||
/// Extensions of certificate files a recipe may ship.
|
||||
const CERTIFICATE_EXTENSIONS: &[&str] = &["pem", "crt", "cer", "cert"];
|
||||
|
||||
/// Values of `-p` that lock an account instead of setting a password.
|
||||
const LOCKED: &[&str] = &["*", "!", "!!", "!*", "x"];
|
||||
|
||||
const EXTRAUSERS_PASSWORD: RuleInfo = RuleInfo {
|
||||
scanner: SCANNER,
|
||||
id: "yocto-extrausers-password",
|
||||
title: "Password set in EXTRA_USERS_PARAMS",
|
||||
severity: Severity::High,
|
||||
cwe: Some("CWE-798"),
|
||||
cra: Cra::SecureByDefault,
|
||||
remediation: "Do not bake a password or password hash into the image: every device \
|
||||
ships with the same credential. Lock the account (usermod -p '*'), use key \
|
||||
authentication, or set a per-device password at provisioning.",
|
||||
};
|
||||
|
||||
const SRC_URI_HTTP: RuleInfo = RuleInfo {
|
||||
scanner: SCANNER,
|
||||
id: "yocto-src-uri-http",
|
||||
title: "Source fetched over unencrypted http",
|
||||
severity: Severity::Medium,
|
||||
cwe: Some("CWE-319"),
|
||||
cra: Cra::AttackSurface,
|
||||
remediation: "Fetch over https (or git with protocol=https) and keep the checksum or \
|
||||
SRCREV pinned.",
|
||||
};
|
||||
|
||||
const SSHD_ROOT_LOGIN: RuleInfo = RuleInfo {
|
||||
scanner: SCANNER,
|
||||
id: "yocto-sshd-root-login",
|
||||
title: "Shipped sshd_config allows root login",
|
||||
severity: Severity::High,
|
||||
cwe: Some("CWE-1188"),
|
||||
cra: Cra::SecureByDefault,
|
||||
remediation: "Set PermitRootLogin no (or prohibit-password with key authentication) in \
|
||||
the sshd_config the image ships.",
|
||||
};
|
||||
|
||||
const SSHD_PASSWORD_AUTH: RuleInfo = RuleInfo {
|
||||
scanner: SCANNER,
|
||||
id: "yocto-sshd-password-auth",
|
||||
title: "Shipped sshd_config allows password logins",
|
||||
severity: Severity::Medium,
|
||||
cwe: Some("CWE-1188"),
|
||||
cra: Cra::SecureByDefault,
|
||||
remediation: "Set PasswordAuthentication no and use key authentication.",
|
||||
};
|
||||
|
||||
const SHIPPED_CERTIFICATE: RuleInfo = RuleInfo {
|
||||
scanner: SCANNER,
|
||||
id: "yocto-files-certificate",
|
||||
title: "Certificate shipped with a recipe",
|
||||
severity: Severity::Info,
|
||||
cwe: None,
|
||||
cra: Cra::None,
|
||||
remediation: "Check that the certificate is meant to be on every device (a trust anchor, \
|
||||
not a device identity) and that it is renewed before it expires.",
|
||||
};
|
||||
|
||||
const DISTRO_NO_SECURITY_FLAGS: RuleInfo = RuleInfo {
|
||||
scanner: SCANNER,
|
||||
id: "yocto-distro-no-security-flags",
|
||||
title: "Distro does not include security_flags.inc",
|
||||
severity: Severity::Medium,
|
||||
cwe: Some("CWE-693"),
|
||||
cra: Cra::SecureByDefault,
|
||||
remediation: "Add require conf/distro/include/security_flags.inc to the distro \
|
||||
configuration, so every package is built with the stack protector, \
|
||||
FORTIFY_SOURCE, PIE and full RELRO.",
|
||||
};
|
||||
|
||||
const LOCAL_CONF_NO_SECURITY_FLAGS: RuleInfo = RuleInfo {
|
||||
scanner: SCANNER,
|
||||
id: "yocto-local-conf-no-security-flags",
|
||||
title: "local.conf.sample builds without a distro or security_flags.inc",
|
||||
severity: Severity::Info,
|
||||
cwe: Some("CWE-693"),
|
||||
cra: Cra::SecureByDefault,
|
||||
remediation: "Set DISTRO to a distro that includes security_flags.inc, or require it in \
|
||||
the template.",
|
||||
};
|
||||
|
||||
/// Every rule of this scanner.
|
||||
pub const RULES: [&RuleInfo; 7] = [
|
||||
&EXTRAUSERS_PASSWORD,
|
||||
&SRC_URI_HTTP,
|
||||
&SSHD_ROOT_LOGIN,
|
||||
&SSHD_PASSWORD_AUTH,
|
||||
&SHIPPED_CERTIFICATE,
|
||||
&DISTRO_NO_SECURITY_FLAGS,
|
||||
&LOCAL_CONF_NO_SECURITY_FLAGS,
|
||||
];
|
||||
|
||||
/// The start of a BitBake assignment: the variable (with its overrides), the
|
||||
/// operator and the opening quote.
|
||||
static ASSIGNMENT: LazyLock<Option<Regex>> = LazyLock::new(|| {
|
||||
Regex::new(
|
||||
r#"^\s*(?:export\s+)?([A-Za-z0-9_${}.+/-]+(?::[A-Za-z0-9_${}.+/-]+)*)\s*(?:\?\?=|\?=|:=|\+=|=\+|\.=|=\.|=)\s*(["'])"#,
|
||||
)
|
||||
.ok()
|
||||
});
|
||||
|
||||
/// A password option of `useradd` / `usermod` and its value.
|
||||
static PASSWORD_OPTION: LazyLock<Option<Regex>> = LazyLock::new(|| {
|
||||
Regex::new(
|
||||
r#"\b(?:useradd|usermod)\b[^;]*?\s(?:-p|-P|--password)\s+('[^']*'|\\?"[^"]*\\?"|[^\s;]+)"#,
|
||||
)
|
||||
.ok()
|
||||
});
|
||||
|
||||
/// A `require` or `include` and the file it names.
|
||||
static INCLUDE: LazyLock<Option<Regex>> =
|
||||
LazyLock::new(|| Regex::new(r"^\s*(?:require|include)\s+(\S+)").ok());
|
||||
|
||||
/// One assignment in a BitBake file.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct Assignment {
|
||||
/// The variable without its overrides (`SRC_URI` for `SRC_URI:append`).
|
||||
pub var: String,
|
||||
/// The value between the quotes; continued lines are joined by `\n`.
|
||||
pub value: String,
|
||||
/// The line the assignment starts on, 1-based.
|
||||
pub line: u32,
|
||||
}
|
||||
|
||||
impl Assignment {
|
||||
/// The line of byte `offset` in the value.
|
||||
fn line_at(&self, offset: usize) -> u32 {
|
||||
let newlines = self.value.get(..offset).unwrap_or("").matches('\n').count();
|
||||
self.line + u32::try_from(newlines).unwrap_or(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// The assignments in BitBake `text`, in order. Flags (`SRC_URI[sha256sum]`)
|
||||
/// and comments are not assignments.
|
||||
pub(crate) fn assignments(text: &str) -> Vec<Assignment> {
|
||||
let Some(start) = ASSIGNMENT.as_ref() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
let mut lines = text.lines().enumerate();
|
||||
while let Some((index, line)) = lines.next() {
|
||||
let Some(caps) = start.captures(line) else {
|
||||
continue;
|
||||
};
|
||||
let (Some(name), Some(quote), Some(all)) = (caps.get(1), caps.get(2), caps.get(0)) else {
|
||||
continue;
|
||||
};
|
||||
let quote = quote.as_str();
|
||||
let mut value = String::new();
|
||||
let mut rest = &line[all.end()..];
|
||||
loop {
|
||||
if let Some(end) = rest.find(quote) {
|
||||
value.push_str(&rest[..end]);
|
||||
break;
|
||||
}
|
||||
match rest.trim_end().strip_suffix('\\') {
|
||||
Some(continued) => {
|
||||
value.push_str(continued);
|
||||
value.push('\n');
|
||||
match lines.next() {
|
||||
Some((_, next)) => rest = next,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
None => {
|
||||
value.push_str(rest);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(Assignment {
|
||||
var: name
|
||||
.as_str()
|
||||
.split(':')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.to_string(),
|
||||
value,
|
||||
line: u32::try_from(index + 1).unwrap_or(u32::MAX),
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `inner` (relative to its layer, file `name`) is a file a recipe
|
||||
/// ships that these rules read: an sshd configuration or a certificate in a
|
||||
/// `recipes-*` directory.
|
||||
pub(crate) fn is_shipped_file(inner: &str, name: &str) -> bool {
|
||||
if !inner.starts_with("recipes-") {
|
||||
return false;
|
||||
}
|
||||
let ext = name.rsplit_once('.').map_or("", |(_, ext)| ext);
|
||||
name.starts_with("sshd_config") || CERTIFICATE_EXTENSIONS.contains(&ext)
|
||||
}
|
||||
|
||||
impl RecipeLint {
|
||||
/// What our own rules find in the customer's layers under `root`.
|
||||
pub(crate) fn config_hits(&self, root: &Path) -> Vec<Hit> {
|
||||
let index = ConfIndex::new(root, &self.layers);
|
||||
let mut hits = Vec::new();
|
||||
for layer in self.own_layers() {
|
||||
for file in &layer.files {
|
||||
let Some(text) = read_text(root, file) else {
|
||||
continue;
|
||||
};
|
||||
let inner = layer.inner(file);
|
||||
let name = inner.rsplit('/').next().unwrap_or(inner);
|
||||
if name.starts_with("sshd_config") {
|
||||
hits.extend(sshd_hits(file, &text));
|
||||
} else if is_shipped_file(inner, name) {
|
||||
hits.extend(certificate_hit(file, &text));
|
||||
} else {
|
||||
let found = assignments(&text);
|
||||
hits.extend(extrausers_hits(file, &found));
|
||||
hits.extend(http_hits(file, &found));
|
||||
if is_distro_conf(inner) && !index.hardened(file, &text) {
|
||||
hits.push(Hit::new(&DISTRO_NO_SECURITY_FLAGS, file, 1, String::new()));
|
||||
} else if name == "local.conf.sample"
|
||||
&& without_distro(&found)
|
||||
&& !index.hardened(file, &text)
|
||||
{
|
||||
hits.push(Hit::new(
|
||||
&LOCAL_CONF_NO_SECURITY_FLAGS,
|
||||
file,
|
||||
1,
|
||||
String::new(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
hits
|
||||
}
|
||||
}
|
||||
|
||||
/// Passwords set by `useradd` / `usermod` in `EXTRA_USERS_PARAMS`. The
|
||||
/// snippet hides the value.
|
||||
fn extrausers_hits(file: &str, found: &[Assignment]) -> Vec<Hit> {
|
||||
let Some(option) = PASSWORD_OPTION.as_ref() else {
|
||||
return Vec::new();
|
||||
};
|
||||
found
|
||||
.iter()
|
||||
.filter(|a| a.var == "EXTRA_USERS_PARAMS")
|
||||
.flat_map(|a| {
|
||||
option.captures_iter(&a.value).filter_map(|caps| {
|
||||
let value = caps.get(1)?;
|
||||
let bare = value
|
||||
.as_str()
|
||||
.trim_matches(|c| matches!(c, '\'' | '"' | '\\'));
|
||||
let reference = bare.starts_with("${") && bare.ends_with('}');
|
||||
if LOCKED.contains(&bare) || reference {
|
||||
return None;
|
||||
}
|
||||
let whole = caps.get(0)?;
|
||||
let command = a
|
||||
.value
|
||||
.get(whole.start()..value.start())
|
||||
.unwrap_or_default();
|
||||
let shown = format!("{}<hidden>", command.trim_start());
|
||||
let mut hit = Hit::new(
|
||||
&EXTRAUSERS_PASSWORD,
|
||||
file,
|
||||
a.line_at(value.start()),
|
||||
if bare.is_empty() {
|
||||
"The account is given an empty password.".to_string()
|
||||
} else {
|
||||
"The image sets a fixed password for the account.".to_string()
|
||||
},
|
||||
);
|
||||
hit.snippet = Some(shown);
|
||||
Some(hit)
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `http://` fetches and `protocol=http` in `SRC_URI`.
|
||||
fn http_hits(file: &str, found: &[Assignment]) -> Vec<Hit> {
|
||||
found
|
||||
.iter()
|
||||
.filter(|a| a.var == "SRC_URI")
|
||||
.flat_map(|a| {
|
||||
a.value
|
||||
.split_whitespace()
|
||||
.filter(|uri| {
|
||||
uri.starts_with("http://")
|
||||
|| uri.split(';').skip(1).any(|o| o == "protocol=http")
|
||||
})
|
||||
.filter_map(|uri| {
|
||||
let offset = a.value.find(uri)?;
|
||||
Some(Hit::new(
|
||||
&SRC_URI_HTTP,
|
||||
file,
|
||||
a.line_at(offset),
|
||||
format!("Fetched without TLS: {uri}"),
|
||||
))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `PermitRootLogin yes` and `PasswordAuthentication yes` in an sshd
|
||||
/// configuration; comments are the stock template's defaults, not settings.
|
||||
fn sshd_hits(file: &str, text: &str) -> Vec<Hit> {
|
||||
text.lines()
|
||||
.enumerate()
|
||||
.filter_map(|(index, line)| {
|
||||
let mut words = line.split_whitespace();
|
||||
let key = words.next()?.to_ascii_lowercase();
|
||||
let value = words.next()?.to_ascii_lowercase();
|
||||
let rule = match (key.as_str(), value.as_str()) {
|
||||
("permitrootlogin", "yes") => &SSHD_ROOT_LOGIN,
|
||||
("passwordauthentication", "yes") => &SSHD_PASSWORD_AUTH,
|
||||
_ => return None,
|
||||
};
|
||||
let line_number = u32::try_from(index + 1).ok()?;
|
||||
Some(Hit::new(rule, file, line_number, String::new()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The first certificate in a shipped file.
|
||||
fn certificate_hit(file: &str, text: &str) -> Option<Hit> {
|
||||
let index = text
|
||||
.lines()
|
||||
.position(|l| l.contains("-----BEGIN CERTIFICATE-----"))?;
|
||||
let line = u32::try_from(index + 1).ok()?;
|
||||
Some(Hit::new(&SHIPPED_CERTIFICATE, file, line, String::new()))
|
||||
}
|
||||
|
||||
/// Whether `inner` is a distro configuration (`conf/distro/<name>.conf`).
|
||||
fn is_distro_conf(inner: &str) -> bool {
|
||||
inner
|
||||
.strip_prefix("conf/distro/")
|
||||
.is_some_and(|name| !name.contains('/') && name.ends_with(".conf"))
|
||||
}
|
||||
|
||||
/// Whether a `local.conf.sample` builds without a distro (`DISTRO` unset or
|
||||
/// `nodistro`), which OpenEmbedded-Core builds without the security flags. A
|
||||
/// named distro is checked on its own when it is in the tree, and is not
|
||||
/// known otherwise.
|
||||
fn without_distro(found: &[Assignment]) -> bool {
|
||||
found
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|a| a.var == "DISTRO")
|
||||
.is_none_or(|a| a.value.trim() == "nodistro")
|
||||
}
|
||||
|
||||
/// The configuration files of every layer (upstream included), by their path
|
||||
/// inside the layer, to follow `require` and `include`.
|
||||
struct ConfIndex<'a> {
|
||||
root: &'a Path,
|
||||
by_inner: BTreeMap<&'a str, &'a str>,
|
||||
}
|
||||
|
||||
impl<'a> ConfIndex<'a> {
|
||||
fn new(root: &'a Path, layers: &'a [Layer]) -> Self {
|
||||
let by_inner = layers
|
||||
.iter()
|
||||
.flat_map(|l| l.files.iter().map(move |f| (l.inner(f), f.as_str())))
|
||||
.filter(|(inner, _)| inner.starts_with("conf/"))
|
||||
.collect();
|
||||
Self { root, by_inner }
|
||||
}
|
||||
|
||||
/// Whether the configuration `text` of `file` may pull in
|
||||
/// `security_flags.inc`, itself or through what it requires. An include
|
||||
/// that is not in the tree (Poky's distros, a BSP layer kas fetches) or
|
||||
/// goes through a variable cannot be followed and counts as hardened, so
|
||||
/// nothing is claimed that is not known.
|
||||
fn hardened(&self, file: &str, text: &str) -> bool {
|
||||
let mut seen = BTreeSet::from([file.to_string()]);
|
||||
self.follows(text, &mut seen)
|
||||
}
|
||||
|
||||
fn follows(&self, text: &str, seen: &mut BTreeSet<String>) -> bool {
|
||||
let Some(include) = INCLUDE.as_ref() else {
|
||||
return true;
|
||||
};
|
||||
text.lines()
|
||||
.filter_map(|line| include.captures(line)?.get(1))
|
||||
.map(|target| target.as_str())
|
||||
.any(|target| {
|
||||
let name = target.rsplit('/').next().unwrap_or(target);
|
||||
if name == "security_flags.inc" || target.contains("${") {
|
||||
return true;
|
||||
}
|
||||
let Some(file) = self.by_inner.get(target) else {
|
||||
return true;
|
||||
};
|
||||
if !seen.insert((*file).to_string()) {
|
||||
return false;
|
||||
}
|
||||
read_text(self.root, file).is_some_and(|text| self.follows(&text, seen))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::super::tests::tree;
|
||||
use super::*;
|
||||
|
||||
fn rule_lines(lint_root: &Path) -> Vec<String> {
|
||||
let lint = RecipeLint::for_tree(lint_root, &["bitbake".to_string()], &[]).expect("lint");
|
||||
let mut out: Vec<String> = lint
|
||||
.config_hits(lint_root)
|
||||
.into_iter()
|
||||
.map(|h| format!("{} {}:{}", h.rule.id, h.path, h.line))
|
||||
.collect();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
const LAYER: &str = "BBFILE_COLLECTIONS += \"pump\"\nLAYERSERIES_COMPAT_pump = \"scarthgap\"\n";
|
||||
|
||||
#[test]
|
||||
fn assignments_join_continued_lines_and_skip_flags() {
|
||||
let text = "SRC_URI = \"git://x;protocol=https \\\n file://a.patch \\\n\"\n\
|
||||
SRC_URI[sha256sum] = \"abc\"\n# SRC_URI = \"http://commented\"\n\
|
||||
SRC_URI:append:arm = \" http://y/z.tgz\"\n";
|
||||
let found = assignments(text);
|
||||
assert_eq!(found.len(), 2);
|
||||
assert_eq!(found[0].var, "SRC_URI");
|
||||
assert_eq!(found[0].line, 1);
|
||||
assert!(found[0].value.contains("file://a.patch"));
|
||||
assert_eq!(found[1].var, "SRC_URI");
|
||||
assert_eq!(found[1].line, 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_password_in_extra_users_params_is_reported_with_its_value_hidden() {
|
||||
let text = "EXTRA_USERS_PARAMS = \"\\\n useradd -m -p '$6$salt$hash' pump; \\\n \
|
||||
usermod -p '*' root; \\\n usermod -P secret operator; \\\n \
|
||||
usermod -p '${ROOT_HASH}' service; \\\n\"\n";
|
||||
let hits = extrausers_hits("image.bb", &assignments(text));
|
||||
let lines: Vec<u32> = hits.iter().map(|h| h.line).collect();
|
||||
// The locked root account and the hash from a variable are not.
|
||||
assert_eq!(lines, [2, 4]);
|
||||
let snippet = hits[0].snippet.as_deref().expect("snippet");
|
||||
assert!(snippet.starts_with("useradd -m -p"));
|
||||
assert!(snippet.ends_with("<hidden>"));
|
||||
assert!(!hits.iter().any(|h| h
|
||||
.snippet
|
||||
.as_deref()
|
||||
.is_some_and(|s| s.contains("secret") || s.contains("$6$"))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_http_fetches_are_reported_and_https_ones_are_not() {
|
||||
let text = "SRC_URI = \"http://a/b.tgz \\\n https://c/d.tgz \\\n \
|
||||
git://e/f.git;protocol=http;branch=main \\\n \
|
||||
git://g/h.git;protocol=https;branch=main\"\n";
|
||||
let hits = http_hits("x.bb", &assignments(text));
|
||||
let lines: Vec<u32> = hits.iter().map(|h| h.line).collect();
|
||||
assert_eq!(lines, [1, 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sshd_settings_count_only_when_set() {
|
||||
let text = "#PermitRootLogin yes\nPermitRootLogin yes\nPasswordAuthentication no\n\
|
||||
passwordauthentication YES\nPermitRootLogin prohibit-password\n";
|
||||
let lines: Vec<(&str, u32)> = sshd_hits("sshd_config", text)
|
||||
.iter()
|
||||
.map(|h| (h.rule.id, h.line))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
lines,
|
||||
[
|
||||
("yocto-sshd-root-login", 2),
|
||||
("yocto-sshd-password-auth", 4)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tree_reports_each_rule_once_where_it_applies() {
|
||||
let t = tree(&[
|
||||
("conf/layer.conf", LAYER),
|
||||
// Requires a distro that includes the flags: hardened.
|
||||
(
|
||||
"conf/distro/pump.conf",
|
||||
"require conf/distro/include/pump-base.inc\nDISTRO = \"pump\"\n",
|
||||
),
|
||||
(
|
||||
"conf/distro/include/pump-base.inc",
|
||||
"require conf/distro/include/security_flags.inc\n",
|
||||
),
|
||||
// Poky's distro, or a BSP include kas fetches: not in the tree,
|
||||
// so not known.
|
||||
(
|
||||
"conf/distro/pump-poky.conf",
|
||||
"require conf/distro/poky.conf\n",
|
||||
),
|
||||
(
|
||||
"conf/distro/pump-imx.conf",
|
||||
"require conf/distro/include/fsl-imx-base.inc\n",
|
||||
),
|
||||
// An include in the tree without the flags is followed.
|
||||
(
|
||||
"conf/distro/pump-lite.conf",
|
||||
"include conf/distro/include/pump-lite.inc\n",
|
||||
),
|
||||
(
|
||||
"conf/distro/include/pump-lite.inc",
|
||||
"DISTRO_FEATURES = \"\"\n",
|
||||
),
|
||||
("conf/distro/bare.conf", "DISTRO = \"bare\"\n"),
|
||||
(
|
||||
"conf/templates/default/local.conf.sample",
|
||||
"MACHINE ?= \"qemux86-64\"\n",
|
||||
),
|
||||
(
|
||||
"recipes-connectivity/openssh/files/sshd_config",
|
||||
"PermitRootLogin yes\n",
|
||||
),
|
||||
// Not shipped with a recipe: not read.
|
||||
("docs/sshd_config", "PermitRootLogin yes\n"),
|
||||
(
|
||||
"recipes-core/ca/files/ca.pem",
|
||||
"# root CA\n-----BEGIN CERTIFICATE-----\nMII\n-----END CERTIFICATE-----\n",
|
||||
),
|
||||
(
|
||||
"recipes-core/ca/files/notes.pem",
|
||||
"-----BEGIN PUBLIC KEY-----\n",
|
||||
),
|
||||
]);
|
||||
assert_eq!(
|
||||
rule_lines(&t.0),
|
||||
[
|
||||
"yocto-distro-no-security-flags conf/distro/bare.conf:1",
|
||||
"yocto-distro-no-security-flags conf/distro/pump-lite.conf:1",
|
||||
"yocto-files-certificate recipes-core/ca/files/ca.pem:2",
|
||||
"yocto-local-conf-no-security-flags conf/templates/default/local.conf.sample:1",
|
||||
"yocto-sshd-root-login recipes-connectivity/openssh/files/sshd_config:1",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_local_conf_with_a_distro_or_flags_is_not_reported() {
|
||||
let t = tree(&[
|
||||
("conf/layer.conf", LAYER),
|
||||
("conf/local.conf.sample", "DISTRO ?= \"poky\"\n"),
|
||||
(
|
||||
"conf/templates/hardened/local.conf.sample",
|
||||
"require conf/distro/include/security_flags.inc\n",
|
||||
),
|
||||
]);
|
||||
assert!(rule_lines(&t.0).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fixture_layer_yields_the_nightly_baseline() {
|
||||
let root =
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../fixtures/nightly/firmware/yocto-layer");
|
||||
assert_eq!(
|
||||
rule_lines(&root),
|
||||
[
|
||||
"yocto-distro-no-security-flags conf/distro/pump-distro.conf:1",
|
||||
"yocto-extrausers-password recipes-core/images/pump-image.bb:13",
|
||||
"yocto-src-uri-http recipes-app/pump-web/pump-web_2.1.bb:6",
|
||||
"yocto-sshd-root-login recipes-connectivity/openssh/files/sshd_config:3",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upstream_layers_are_not_checked() {
|
||||
let t = tree(&[
|
||||
(
|
||||
"poky/meta/conf/layer.conf",
|
||||
"BBFILE_COLLECTIONS += \"core\"\n",
|
||||
),
|
||||
("poky/meta/conf/distro/defaultsetup.conf", "DISTRO = \"\"\n"),
|
||||
(
|
||||
"poky/meta/recipes-x/x/x.bb",
|
||||
"SRC_URI = \"http://x/y.tgz\"\n",
|
||||
),
|
||||
]);
|
||||
assert!(rule_lines(&t.0).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,10 @@ pub struct RepoView {
|
||||
/// Whether the target's uploaded files let a scheduled scan without new
|
||||
/// commits be skipped ([`crate::pipeline::change::uploads_allow_git_skip`]).
|
||||
pub uploads_allow_skip: bool,
|
||||
/// Whether the tree is read as Yocto layers (its recipe inventory): it
|
||||
/// was classified as one, or the target is a Yocto target. Set by the
|
||||
/// caller after classification; `false` from [`Self::from_target`].
|
||||
pub yocto_layers: bool,
|
||||
}
|
||||
|
||||
impl RepoView {
|
||||
@@ -74,6 +78,7 @@ impl RepoView {
|
||||
findings_count: target.findings_count,
|
||||
managed: target.source_repo.is_some(),
|
||||
uploads_allow_skip: crate::pipeline::change::uploads_allow_git_skip(target),
|
||||
yocto_layers: false,
|
||||
};
|
||||
if let Some(git) = &code.git {
|
||||
view.default_branch = git.default_branch.clone();
|
||||
|
||||
@@ -488,6 +488,7 @@ fn merge_audit_vulns(entries: &mut [SbomEntry], vulns: Vec<cargo_audit::AuditVul
|
||||
severity: None,
|
||||
url: Some(vuln.url),
|
||||
exploitation: None,
|
||||
aliases: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -475,54 +475,12 @@ pub(super) fn license_from_url(url: &str) -> Option<String> {
|
||||
{
|
||||
return Some(expression);
|
||||
}
|
||||
let page = bare
|
||||
.trim_end_matches(".php")
|
||||
.trim_end_matches(".html")
|
||||
.trim_end_matches(".txt")
|
||||
.trim_end_matches(".md");
|
||||
let known = WELL_KNOWN_URLS
|
||||
.iter()
|
||||
.find(|(prefix, _)| page == *prefix)
|
||||
.map(|(_, spdx)| (*spdx).to_string());
|
||||
Some(known.unwrap_or_else(|| url.to_string()))
|
||||
Some(
|
||||
compliance_core::spdx_license::spdx_of_url(url)
|
||||
.map_or_else(|| url.to_string(), str::to_string),
|
||||
)
|
||||
}
|
||||
|
||||
/// License pages (lowercase, without scheme, `www.`, trailing slash and
|
||||
/// `.html`/`.php`/`.txt`) and the SPDX id they stand for.
|
||||
const WELL_KNOWN_URLS: &[(&str, &str)] = &[
|
||||
("opensource.org/licenses/mit", "MIT"),
|
||||
("opensource.org/licenses/mit-license", "MIT"),
|
||||
("opensource.org/license/mit", "MIT"),
|
||||
("choosealicense.com/licenses/mit", "MIT"),
|
||||
("opensource.org/licenses/apache-2.0", "Apache-2.0"),
|
||||
("opensource.org/license/apache-2-0", "Apache-2.0"),
|
||||
("apache.org/licenses/license-2.0", "Apache-2.0"),
|
||||
("choosealicense.com/licenses/apache-2.0", "Apache-2.0"),
|
||||
("opensource.org/licenses/bsd-license", "BSD-3-Clause"),
|
||||
("opensource.org/licenses/bsd-3-clause", "BSD-3-Clause"),
|
||||
("opensource.org/licenses/bsd-2-clause", "BSD-2-Clause"),
|
||||
("opensource.org/licenses/ms-pl", "MS-PL"),
|
||||
("opensource.org/licenses/ms-rl", "MS-RL"),
|
||||
("microsoft.com/opensource/licenses.mspx#ms-pl", "MS-PL"),
|
||||
("opensource.org/licenses/mpl-2.0", "MPL-2.0"),
|
||||
("mozilla.org/mpl/2.0", "MPL-2.0"),
|
||||
("opensource.org/licenses/isc", "ISC"),
|
||||
("opensource.org/licenses/zlib", "Zlib"),
|
||||
("opensource.org/licenses/lgpl-2.1", "LGPL-2.1-only"),
|
||||
("opensource.org/licenses/lgpl-3.0", "LGPL-3.0-only"),
|
||||
("gnu.org/licenses/lgpl-2.1", "LGPL-2.1-only"),
|
||||
("gnu.org/licenses/old-licenses/lgpl-2.1", "LGPL-2.1-only"),
|
||||
("gnu.org/licenses/lgpl-3.0", "LGPL-3.0-only"),
|
||||
("gnu.org/licenses/lgpl", "LGPL-3.0-or-later"),
|
||||
("gnu.org/licenses/gpl-2.0", "GPL-2.0-only"),
|
||||
("gnu.org/licenses/old-licenses/gpl-2.0", "GPL-2.0-only"),
|
||||
("gnu.org/licenses/gpl-3.0", "GPL-3.0-only"),
|
||||
("gnu.org/licenses/gpl", "GPL-3.0-or-later"),
|
||||
("gnu.org/licenses/agpl-3.0", "AGPL-3.0-only"),
|
||||
("gnu.org/licenses/agpl", "AGPL-3.0-or-later"),
|
||||
("unlicense.org", "Unlicense"),
|
||||
];
|
||||
|
||||
/// `%XX` escapes decoded (the expressions nuget.org puts in a URL path).
|
||||
fn percent_decode(s: &str) -> String {
|
||||
let bytes = s.as_bytes();
|
||||
|
||||
@@ -762,7 +762,8 @@ fn pom_license(text: &str) -> PomLicense {
|
||||
let name = child(license, "name");
|
||||
let url = child(license, "url");
|
||||
name.as_deref()
|
||||
.and_then(spdx_of_name)
|
||||
.and_then(compliance_core::spdx_license::spdx_of_name)
|
||||
.map(str::to_string)
|
||||
.or_else(|| {
|
||||
url.as_deref()
|
||||
.and_then(license_from_url)
|
||||
@@ -790,31 +791,6 @@ fn pom_license(text: &str) -> PomLicense {
|
||||
}
|
||||
}
|
||||
|
||||
/// The SPDX id of a license as POMs commonly name it.
|
||||
fn spdx_of_name(name: &str) -> Option<String> {
|
||||
let n = name.to_ascii_lowercase();
|
||||
let id = if n.contains("apache") && n.contains("2") {
|
||||
"Apache-2.0"
|
||||
} else if n == "mit" || n.contains("mit license") {
|
||||
"MIT"
|
||||
} else if n.contains("bsd") && (n.contains("3") || n.contains("new") || n.contains("revised")) {
|
||||
"BSD-3-Clause"
|
||||
} else if n.contains("bsd") && (n.contains("2") || n.contains("simplified")) {
|
||||
"BSD-2-Clause"
|
||||
} else if n.contains("eclipse public license") && n.contains("2") {
|
||||
"EPL-2.0"
|
||||
} else if n.contains("eclipse public license") && n.contains("1") {
|
||||
"EPL-1.0"
|
||||
} else if n.contains("eclipse distribution license") {
|
||||
"BSD-3-Clause"
|
||||
} else if n.contains("mozilla public license") && n.contains("2") {
|
||||
"MPL-2.0"
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
Some(id.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
|
||||
@@ -5,7 +5,10 @@
|
||||
//! complete lookup no longer reports it (the component removed or updated
|
||||
//! past the fix), it is marked resolved, and one nobody assessed, or
|
||||
//! assessed as affected, gets the VEX status `fixed` from the scan. A
|
||||
//! person's `not_affected` or `fixed` is never changed by a scan. The first
|
||||
//! person's `not_affected` or `fixed` is never changed by a scan. What a
|
||||
//! scan states from the target's own data (a Yocto recipe's CVE_STATUS or
|
||||
//! `CVE:` patch) is stated again on every scan, and likewise never replaces
|
||||
//! a person's statement. The first
|
||||
//! scan that finds it actively exploited records when (`exploited_seen_at`),
|
||||
//! the start of the CRA's reporting deadlines.
|
||||
//!
|
||||
@@ -148,15 +151,149 @@ pub async fn upsert_reported(db: &Database, alert: &CveAlert) -> Result<(), Agen
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
let mut scan_fixed = filter;
|
||||
scan_fixed.insert("vex.by_scan", true);
|
||||
scan_fixed.insert("vex.status", "fixed");
|
||||
// Reported again, the scan's own statement is withdrawn: a `fixed`
|
||||
// because the component was gone, or what a recipe said last time
|
||||
// ([`apply_scan_statements`] states it again if it still does).
|
||||
let mut by_scan = filter;
|
||||
by_scan.insert("vex.by_scan", true);
|
||||
db.cve_alerts()
|
||||
.update_one(scan_fixed, doc! { "$unset": { "vex": "" } })
|
||||
.update_one(by_scan, doc! { "$unset": { "vex": "" } })
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Store `alert` as found by the CVE monitor between scans: inserted when
|
||||
/// the target has no alert for the CVE yet (the scan's key, CVE and target),
|
||||
/// otherwise only its exploitation is refreshed and, when it has none, given
|
||||
/// the component's purl (same package and version). Unlike
|
||||
/// [`upsert_reported`] it leaves the rest alone: the VEX statements a scan
|
||||
/// made from the target's own data (a recipe's `CVE_STATUS`) and whether the
|
||||
/// alert is resolved are the scan's to change.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Whether the alert was new.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// A database or encoding error.
|
||||
pub async fn store_monitored(db: &Database, alert: &CveAlert) -> Result<bool, AgentError> {
|
||||
let filter = doc! { "cve_id": &alert.cve_id, "repo_id": &alert.repo_id };
|
||||
let mut insert = mongodb::bson::to_document(alert)
|
||||
.map_err(|e| AgentError::Other(format!("encode CVE alert: {e}")))?;
|
||||
let exploitation = insert.remove("exploitation");
|
||||
let mut update = doc! { "$setOnInsert": insert };
|
||||
if let Some(exploitation) = exploitation {
|
||||
update.insert("$set", doc! { "exploitation": exploitation });
|
||||
}
|
||||
let inserted = db
|
||||
.cve_alerts()
|
||||
.update_one(filter.clone(), update)
|
||||
.upsert(true)
|
||||
.await?
|
||||
.upserted_id
|
||||
.is_some();
|
||||
// An alert stored before purls were recorded gets its component's purl
|
||||
// (only for the same package and version).
|
||||
if let Some(purl) = &alert.purl {
|
||||
let mut without_purl = filter;
|
||||
without_purl.insert("affected_package", &alert.affected_package);
|
||||
without_purl.insert("affected_version", &alert.affected_version);
|
||||
without_purl.insert("purl", doc! { "$exists": false });
|
||||
db.cve_alerts()
|
||||
.update_one(without_purl, doc! { "$set": { "purl": purl } })
|
||||
.await?;
|
||||
}
|
||||
Ok(inserted)
|
||||
}
|
||||
|
||||
/// Set the VEX statements this scan makes on `repo_id`'s alerts (a Yocto
|
||||
/// recipe's CVE_STATUS or `CVE:` patch, see
|
||||
/// [`crate::pipeline::yocto_inventory::vex_statements`]), each as
|
||||
/// `(cve_id, statement)`. Only an alert nobody assessed, or one whose
|
||||
/// statement a scan made, gets it: a person's statement is never replaced.
|
||||
/// Run after [`upsert_reported`], which withdraws the scan's last statements.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// How many alerts got a statement.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// A database error.
|
||||
pub async fn apply_scan_statements(
|
||||
db: &Database,
|
||||
repo_id: &str,
|
||||
statements: &[(String, VexAssessment)],
|
||||
) -> Result<u64, AgentError> {
|
||||
let mut set = 0;
|
||||
for (cve_id, statement) in statements {
|
||||
let vex = mongodb::bson::to_bson(statement)
|
||||
.map_err(|e| AgentError::Other(format!("encode VEX: {e}")))?;
|
||||
let result = db
|
||||
.cve_alerts()
|
||||
.update_one(
|
||||
scan_may_state(repo_id, cve_id),
|
||||
doc! { "$set": { "vex": vex } },
|
||||
)
|
||||
.await?;
|
||||
set += result.modified_count;
|
||||
}
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
/// The alert `cve_id` of `repo_id`, while no person has assessed it.
|
||||
fn scan_may_state(repo_id: &str, cve_id: &str) -> mongodb::bson::Document {
|
||||
doc! {
|
||||
"repo_id": repo_id,
|
||||
"cve_id": cve_id,
|
||||
"$or": [
|
||||
{ "vex": { "$exists": false } },
|
||||
{ "vex.by_scan": true },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/// Give the alerts a scan found (which carry no VEX statement) the statement
|
||||
/// stored on `repo_id`'s alert of the same CVE, or none, so that
|
||||
/// [`CveAlert::is_resolved_by_vex`] tells whether they notify and keep an
|
||||
/// issue. Run after the alerts were stored and the scan's own statements set
|
||||
/// ([`upsert_reported`], [`apply_scan_statements`]).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// A database error.
|
||||
pub async fn attach_stored_vex(
|
||||
db: &Database,
|
||||
repo_id: &str,
|
||||
alerts: &mut [CveAlert],
|
||||
) -> Result<(), AgentError> {
|
||||
if alerts.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let ids: Vec<&str> = alerts.iter().map(|a| a.cve_id.as_str()).collect();
|
||||
let stored: Vec<CveAlert> = db
|
||||
.cve_alerts()
|
||||
.find(doc! {
|
||||
"repo_id": repo_id,
|
||||
"cve_id": { "$in": ids },
|
||||
"vex": { "$exists": true },
|
||||
})
|
||||
.await?
|
||||
.try_collect()
|
||||
.await?;
|
||||
let statements: std::collections::HashMap<String, VexAssessment> = stored
|
||||
.into_iter()
|
||||
.filter_map(|alert| Some((alert.cve_id, alert.vex?)))
|
||||
.collect();
|
||||
for alert in alerts {
|
||||
// Cloned, not taken: one CVE can be listed for two versions of a
|
||||
// package.
|
||||
alert.vex = statements.get(&alert.cve_id).cloned();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Mark resolved the stored alerts of `repo_id` a complete lookup
|
||||
/// (`complete`) no longer reports in `current`.
|
||||
///
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,177 @@
|
||||
//! Git submodules as layer pins: `.gitmodules` names each submodule's path,
|
||||
//! URL and branch, and the tree's HEAD commit records the commit each
|
||||
//! submodule is pinned to (its gitlink). An uploaded archive has no `.git`,
|
||||
//! so its submodules have no commit.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use compliance_core::models::{LayerPin, PinSource};
|
||||
use git2::Repository;
|
||||
|
||||
use super::{clean_ref, read_small};
|
||||
|
||||
/// The file submodules are declared in.
|
||||
pub(crate) const GITMODULES: &str = ".gitmodules";
|
||||
|
||||
/// The git file mode of a gitlink: a commit of another repository.
|
||||
const GITLINK_MODE: i32 = 0o160000;
|
||||
|
||||
/// One `[submodule "<name>"]` section.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub(crate) struct Submodule {
|
||||
pub name: String,
|
||||
pub path: Option<String>,
|
||||
pub url: Option<String>,
|
||||
pub branch: Option<String>,
|
||||
}
|
||||
|
||||
/// The submodules a `.gitmodules` text declares, in order.
|
||||
pub(crate) fn parse(text: &str) -> Vec<Submodule> {
|
||||
let mut out: Vec<Submodule> = Vec::new();
|
||||
// Only keys inside a `[submodule "…"]` section count.
|
||||
let mut in_submodule = false;
|
||||
for line in text.lines().map(str::trim) {
|
||||
if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
|
||||
continue;
|
||||
}
|
||||
if let Some(section) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
|
||||
let name = section
|
||||
.trim()
|
||||
.strip_prefix("submodule")
|
||||
.map(|rest| rest.trim().trim_matches('"').to_string());
|
||||
in_submodule = name.is_some();
|
||||
if let Some(name) = name {
|
||||
out.push(Submodule {
|
||||
name,
|
||||
..Submodule::default()
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let (Some(current), true) = (out.last_mut(), in_submodule) else {
|
||||
continue;
|
||||
};
|
||||
let Some((key, value)) = line.split_once('=') else {
|
||||
continue;
|
||||
};
|
||||
let value = value.trim().trim_matches('"').to_string();
|
||||
match key.trim().to_ascii_lowercase().as_str() {
|
||||
"path" => current.path = Some(value),
|
||||
"url" => current.url = Some(value),
|
||||
"branch" => current.branch = Some(value),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The commit the HEAD tree of the repository at `root` records at `path`,
|
||||
/// when `root` is a git checkout and `path` a gitlink there.
|
||||
fn gitlink(repo: &Repository, path: &str) -> Option<String> {
|
||||
let tree = repo.head().ok()?.peel_to_tree().ok()?;
|
||||
let entry = tree.get_path(Path::new(path)).ok()?;
|
||||
(entry.filemode() == GITLINK_MODE).then(|| entry.id().to_string())
|
||||
}
|
||||
|
||||
/// The submodules of the tree under `root` as pins, and their paths (whose
|
||||
/// own kas files and manifests are another repository's, not the tree's).
|
||||
pub(crate) fn pins(root: &Path) -> (Vec<LayerPin>, Vec<String>) {
|
||||
let Some(text) = read_small(&root.join(GITMODULES)) else {
|
||||
return (Vec::new(), Vec::new());
|
||||
};
|
||||
// `open`, not `discover`: only a checkout rooted at the tree counts.
|
||||
let repo = Repository::open(root).ok();
|
||||
let submodules = parse(&text);
|
||||
let paths = submodules.iter().filter_map(|s| s.path.clone()).collect();
|
||||
let pins = submodules
|
||||
.into_iter()
|
||||
.map(|s| LayerPin {
|
||||
commit: repo
|
||||
.as_ref()
|
||||
.zip(s.path.as_deref())
|
||||
.and_then(|(repo, path)| gitlink(repo, path)),
|
||||
branch: s.branch.as_deref().and_then(clean_ref),
|
||||
url: s.url,
|
||||
name: s.name,
|
||||
source: PinSource::GitSubmodule,
|
||||
file: GITMODULES.to_string(),
|
||||
})
|
||||
.collect();
|
||||
(pins, paths)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::pipeline::recipe_lint::tests::tree;
|
||||
|
||||
const GITMODULES_TEXT: &str = "# layers\n[submodule \"poky\"]\n\tpath = layers/poky\n\t\
|
||||
url = https://git.yoctoproject.org/poky\n\tbranch = kirkstone\n\
|
||||
[core]\n\tpath = not-a-submodule\n\
|
||||
[submodule \"meta-oe\"]\n\tpath = layers/meta-openembedded\n\t\
|
||||
url = \"https://github.com/openembedded/meta-openembedded.git\"\n";
|
||||
|
||||
#[test]
|
||||
fn gitmodules_sections_are_read() {
|
||||
let found = parse(GITMODULES_TEXT);
|
||||
assert_eq!(found.len(), 2);
|
||||
assert_eq!(found[0].name, "poky");
|
||||
assert_eq!(found[0].path.as_deref(), Some("layers/poky"));
|
||||
assert_eq!(found[0].branch.as_deref(), Some("kirkstone"));
|
||||
assert_eq!(found[1].name, "meta-oe");
|
||||
assert_eq!(
|
||||
found[1].url.as_deref(),
|
||||
Some("https://github.com/openembedded/meta-openembedded.git")
|
||||
);
|
||||
assert_eq!(found[1].branch, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_archive_has_submodules_without_commits() {
|
||||
let t = tree(&[(GITMODULES, GITMODULES_TEXT)]);
|
||||
let (pins, paths) = pins(&t.0);
|
||||
assert_eq!(paths, ["layers/poky", "layers/meta-openembedded"]);
|
||||
assert_eq!(pins[0].source, PinSource::GitSubmodule);
|
||||
assert_eq!(pins[0].file, ".gitmodules");
|
||||
assert_eq!(pins[0].commit, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_checkout_pins_each_submodule_to_its_gitlink_commit() {
|
||||
let t = tree(&[(GITMODULES, GITMODULES_TEXT), ("README", "x")]);
|
||||
let repo = Repository::init(&t.0).expect("init");
|
||||
let sig = git2::Signature::now("t", "t@example.com").expect("sig");
|
||||
// A commit of the layer repository the gitlink points at.
|
||||
let pinned = git2::Oid::from_str("0123456789abcdef0123456789abcdef01234567").expect("oid");
|
||||
let mut index = repo.index().expect("index");
|
||||
index.add_path(Path::new(GITMODULES)).expect("add");
|
||||
index.add_path(Path::new("README")).expect("add");
|
||||
index
|
||||
.add(&git2::IndexEntry {
|
||||
ctime: git2::IndexTime::new(0, 0),
|
||||
mtime: git2::IndexTime::new(0, 0),
|
||||
dev: 0,
|
||||
ino: 0,
|
||||
mode: 0o160000,
|
||||
uid: 0,
|
||||
gid: 0,
|
||||
file_size: 0,
|
||||
id: pinned,
|
||||
flags: 0,
|
||||
flags_extended: 0,
|
||||
path: b"layers/poky".to_vec(),
|
||||
})
|
||||
.expect("gitlink");
|
||||
let tree_id = index.write_tree().expect("tree");
|
||||
let commit_tree = repo.find_tree(tree_id).expect("tree");
|
||||
repo.commit(Some("HEAD"), &sig, &sig, "layers", &commit_tree, &[])
|
||||
.expect("commit");
|
||||
|
||||
let (pins, _) = pins(&t.0);
|
||||
assert_eq!(pins[0].commit.as_deref(), Some(pinned.to_string().as_str()));
|
||||
assert_eq!(pins[0].branch.as_deref(), Some("kirkstone"));
|
||||
// meta-oe has no gitlink in HEAD.
|
||||
assert_eq!(pins[1].commit, None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,493 @@
|
||||
//! kas project files as layer pins.
|
||||
//!
|
||||
//! A kas file (`kas*.yml`, `kas/*.yml`) lists the repositories a build
|
||||
//! fetches under `repos:`, each with its `url`, `branch`, `tag`, `commit` or
|
||||
//! the older `refspec`. `header.includes` merges other kas files in before the
|
||||
//! file's own settings; only local includes are read: an include from another
|
||||
//! repository (`repo:` / `file:`) or a URL is named, never fetched. A lock
|
||||
//! file beside a kas file (`kas.lock.yml`) pins commits under
|
||||
//! `overrides.repos`.
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::path::Path;
|
||||
|
||||
use compliance_core::models::{LayerPin, PinSource};
|
||||
use yaml_rust2::parser::{Event, Parser};
|
||||
use yaml_rust2::{Yaml, YamlLoader};
|
||||
|
||||
use super::{clean_ref, is_commit, local_include, read_small};
|
||||
|
||||
/// Most YAML nodes a kas file may expand to, aliases included: a file of
|
||||
/// nested aliases ("billion laughs") is refused instead of expanded.
|
||||
const MAX_NODES: usize = 100_000;
|
||||
|
||||
/// Whether `rel` (relative to the tree) names a kas project file: `kas*.yml`
|
||||
/// anywhere, or any YAML file in a `kas/` directory. Lock files are read with
|
||||
/// the file they lock, not on their own.
|
||||
pub(crate) fn is_kas_file(rel: &str) -> bool {
|
||||
let name = rel.rsplit('/').next().unwrap_or(rel);
|
||||
let yaml = name.ends_with(".yml") || name.ends_with(".yaml");
|
||||
let in_kas_dir = rel.split('/').rev().nth(1) == Some("kas");
|
||||
yaml && !is_lock_file(name) && (name.starts_with("kas") || in_kas_dir)
|
||||
}
|
||||
|
||||
fn is_lock_file(name: &str) -> bool {
|
||||
name.ends_with(".lock.yml") || name.ends_with(".lock.yaml")
|
||||
}
|
||||
|
||||
/// The lock file kas reads beside `rel` (`x.yml` -> `x.lock.yml`).
|
||||
fn lock_file(rel: &str) -> Option<String> {
|
||||
let (stem, ext) = rel.rsplit_once('.')?;
|
||||
Some(format!("{stem}.lock.{ext}"))
|
||||
}
|
||||
|
||||
/// How many nodes the YAML `text` expands to with its aliases resolved;
|
||||
/// `None` past [`MAX_NODES`] or when it does not parse.
|
||||
fn expanded_nodes(text: &str) -> Option<usize> {
|
||||
let mut parser = Parser::new_from_str(text);
|
||||
// Open collections: (anchor id, nodes so far).
|
||||
let mut open: Vec<(usize, usize)> = Vec::new();
|
||||
let mut anchors: HashMap<usize, usize> = HashMap::new();
|
||||
let mut total = 0usize;
|
||||
loop {
|
||||
let (event, _) = parser.next_token().ok()?;
|
||||
let done = match event {
|
||||
Event::StreamEnd => break,
|
||||
Event::SequenceStart(anchor, _) | Event::MappingStart(anchor, _) => {
|
||||
open.push((anchor, 1));
|
||||
None
|
||||
}
|
||||
Event::SequenceEnd | Event::MappingEnd => {
|
||||
let (anchor, nodes) = open.pop()?;
|
||||
if anchor > 0 {
|
||||
anchors.insert(anchor, nodes);
|
||||
}
|
||||
Some(nodes)
|
||||
}
|
||||
Event::Scalar(_, _, anchor, _) => {
|
||||
if anchor > 0 {
|
||||
anchors.insert(anchor, 1);
|
||||
}
|
||||
Some(1)
|
||||
}
|
||||
Event::Alias(anchor) => Some(anchors.get(&anchor).copied().unwrap_or(1)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(nodes) = done {
|
||||
match open.last_mut() {
|
||||
Some((_, parent)) => *parent = parent.saturating_add(nodes),
|
||||
None => total = total.saturating_add(nodes),
|
||||
}
|
||||
let pending: usize = open.iter().map(|(_, n)| *n).sum();
|
||||
if total.saturating_add(pending) > MAX_NODES {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(total)
|
||||
}
|
||||
|
||||
/// The kas file `rel` under `root` as YAML: `None` when it is missing, too
|
||||
/// large, not YAML, expands too far, or has no `header` (not a kas file).
|
||||
fn load(root: &Path, rel: &str) -> Option<Yaml> {
|
||||
let text = read_small(&root.join(rel))?;
|
||||
expanded_nodes(&text)?;
|
||||
let doc = YamlLoader::load_from_str(&text).ok()?.into_iter().next()?;
|
||||
(!doc["header"].is_badvalue()).then_some(doc)
|
||||
}
|
||||
|
||||
/// A repository entry as the merged kas files describe it.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
struct Repo {
|
||||
url: Option<String>,
|
||||
branch: Option<String>,
|
||||
tag: Option<String>,
|
||||
refspec: Option<String>,
|
||||
commit: Option<String>,
|
||||
/// The last file that set any of it.
|
||||
file: String,
|
||||
}
|
||||
|
||||
/// The repositories of one kas configuration, in the order they first
|
||||
/// appear, and the default branch.
|
||||
#[derive(Debug, Default)]
|
||||
struct Merged {
|
||||
repos: Vec<(String, Repo)>,
|
||||
default_branch: Option<String>,
|
||||
}
|
||||
|
||||
impl Merged {
|
||||
fn repo(&mut self, name: &str) -> &mut Repo {
|
||||
let index = match self.repos.iter().position(|(n, _)| n == name) {
|
||||
Some(index) => index,
|
||||
None => {
|
||||
self.repos.push((name.to_string(), Repo::default()));
|
||||
self.repos.len() - 1
|
||||
}
|
||||
};
|
||||
&mut self.repos[index].1
|
||||
}
|
||||
|
||||
/// Lay `doc` (the kas file `file`) over what is merged so far: its
|
||||
/// settings override the included files'.
|
||||
fn apply(&mut self, doc: &Yaml, file: &str) {
|
||||
let text = |y: &Yaml| match y {
|
||||
Yaml::String(s) => Some(s.clone()),
|
||||
Yaml::Integer(i) => Some(i.to_string()),
|
||||
Yaml::Real(r) => Some(r.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let defaults = &doc["defaults"]["repos"];
|
||||
if let Some(branch) = text(&defaults["branch"]).or_else(|| text(&defaults["refspec"])) {
|
||||
self.default_branch = Some(branch);
|
||||
}
|
||||
if let Some(repos) = doc["repos"].as_hash() {
|
||||
for (key, value) in repos {
|
||||
let Some(name) = text(key) else { continue };
|
||||
let repo = self.repo(&name);
|
||||
repo.file = file.to_string();
|
||||
for (field, slot) in [
|
||||
("url", &mut repo.url),
|
||||
("branch", &mut repo.branch),
|
||||
("tag", &mut repo.tag),
|
||||
("refspec", &mut repo.refspec),
|
||||
("commit", &mut repo.commit),
|
||||
] {
|
||||
if let Some(v) = text(&value[field]) {
|
||||
*slot = Some(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(overrides) = doc["overrides"]["repos"].as_hash() {
|
||||
for (key, value) in overrides {
|
||||
let (Some(name), Some(commit)) = (text(key), text(&value["commit"])) else {
|
||||
continue;
|
||||
};
|
||||
let repo = self.repo(&name);
|
||||
repo.commit = Some(commit);
|
||||
repo.file = file.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pins of the repositories fetched from elsewhere (with a `url`).
|
||||
fn pins(self) -> Vec<LayerPin> {
|
||||
let default_branch = self.default_branch;
|
||||
self.repos
|
||||
.into_iter()
|
||||
.filter_map(|(name, repo)| {
|
||||
let url = repo.url?;
|
||||
// A refspec may be a commit (old kas files) or a branch.
|
||||
let refspec_commit = repo.refspec.clone().filter(|r| is_commit(r));
|
||||
let named = repo
|
||||
.branch
|
||||
.or(repo.tag)
|
||||
.or(repo.refspec.filter(|r| !is_commit(r)))
|
||||
.or(default_branch.clone());
|
||||
Some(LayerPin {
|
||||
name,
|
||||
source: PinSource::Kas,
|
||||
file: repo.file,
|
||||
url: Some(url),
|
||||
branch: named.as_deref().and_then(clean_ref),
|
||||
commit: repo.commit.or(refspec_commit),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// What the kas files of a tree pin.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct KasPins {
|
||||
pub pins: Vec<LayerPin>,
|
||||
/// Includes that were not read (remote ones, missing ones), as written.
|
||||
pub unread_includes: BTreeSet<String>,
|
||||
}
|
||||
|
||||
/// Reads kas files and their includes, each file once.
|
||||
struct Reader<'a> {
|
||||
root: &'a Path,
|
||||
docs: HashMap<String, Option<Yaml>>,
|
||||
unread: BTreeSet<String>,
|
||||
/// Every file merged into a configuration so far.
|
||||
visited: BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl Reader<'_> {
|
||||
fn doc(&mut self, rel: &str) -> Option<Yaml> {
|
||||
let root = self.root;
|
||||
self.docs
|
||||
.entry(rel.to_string())
|
||||
.or_insert_with(|| load(root, rel))
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// The local files `doc` (the kas file `rel`) includes, in order; remote
|
||||
/// and unresolvable ones are recorded as unread.
|
||||
fn includes(&mut self, rel: &str, doc: &Yaml) -> Vec<String> {
|
||||
let Some(list) = doc["header"]["includes"].as_vec() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for include in list {
|
||||
match include {
|
||||
Yaml::String(path) if path.contains("://") => {
|
||||
self.unread.insert(path.clone());
|
||||
}
|
||||
Yaml::String(path) => match local_include(self.root, rel, path) {
|
||||
Some(found) => out.push(found),
|
||||
None => {
|
||||
self.unread.insert(path.clone());
|
||||
}
|
||||
},
|
||||
// `repo:` + `file:`: a file in another repository.
|
||||
Yaml::Hash(_) => {
|
||||
let repo = include["repo"].as_str().unwrap_or("?");
|
||||
let file = include["file"].as_str().unwrap_or("?");
|
||||
self.unread.insert(format!("{repo}:{file}"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Merge `rel` with everything it includes into `merged`; `stack` holds
|
||||
/// the files being read, so an include cycle ends.
|
||||
fn merge(&mut self, rel: &str, merged: &mut Merged, stack: &mut Vec<String>) {
|
||||
if stack.iter().any(|s| s == rel) {
|
||||
return;
|
||||
}
|
||||
let Some(doc) = self.doc(rel) else {
|
||||
return;
|
||||
};
|
||||
stack.push(rel.to_string());
|
||||
self.visited.insert(rel.to_string());
|
||||
for include in self.includes(rel, &doc) {
|
||||
if self.doc(&include).is_some() {
|
||||
self.merge(&include, merged, stack);
|
||||
} else if !stack.contains(&include) {
|
||||
self.unread.insert(include);
|
||||
}
|
||||
}
|
||||
merged.apply(&doc, rel);
|
||||
stack.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/// The pins of the kas files `files` (relative to `root`). Each file no other
|
||||
/// one includes is a configuration of its own; a pin several of them share
|
||||
/// is listed once.
|
||||
pub(crate) fn read(root: &Path, files: &[String]) -> KasPins {
|
||||
let mut reader = Reader {
|
||||
root,
|
||||
docs: HashMap::new(),
|
||||
unread: BTreeSet::new(),
|
||||
visited: BTreeSet::new(),
|
||||
};
|
||||
let mut included: BTreeSet<String> = BTreeSet::new();
|
||||
for file in files {
|
||||
if let Some(doc) = reader.doc(file) {
|
||||
included.extend(reader.includes(file, &doc));
|
||||
}
|
||||
}
|
||||
let mut pins: Vec<LayerPin> = Vec::new();
|
||||
// The files no other one includes first; then any left unread, which only
|
||||
// an include cycle leaves.
|
||||
let order = files
|
||||
.iter()
|
||||
.filter(|f| !included.contains(*f))
|
||||
.chain(files.iter().filter(|f| included.contains(*f)));
|
||||
for file in order {
|
||||
if reader.visited.contains(file) || reader.doc(file).is_none() {
|
||||
continue;
|
||||
}
|
||||
let mut merged = Merged::default();
|
||||
reader.merge(file, &mut merged, &mut Vec::new());
|
||||
if let Some(lock) = lock_file(file).filter(|l| root.join(l).is_file()) {
|
||||
if let Some(doc) = load(root, &lock) {
|
||||
merged.apply(&doc, &lock);
|
||||
}
|
||||
}
|
||||
for pin in merged.pins() {
|
||||
if !pins.contains(&pin) {
|
||||
pins.push(pin);
|
||||
}
|
||||
}
|
||||
}
|
||||
KasPins {
|
||||
pins,
|
||||
unread_includes: reader.unread,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::pipeline::recipe_lint::tests::tree;
|
||||
|
||||
const SHA: &str = "4a2d3b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a";
|
||||
|
||||
#[test]
|
||||
fn kas_files_are_recognised_by_name_and_directory() {
|
||||
assert!(is_kas_file("kas.yml"));
|
||||
assert!(is_kas_file("kas-pump.yaml"));
|
||||
assert!(is_kas_file("ci/kas/machine.yml"));
|
||||
assert!(!is_kas_file("kas.lock.yml"));
|
||||
assert!(!is_kas_file("docker-compose.yml"));
|
||||
assert!(!is_kas_file("kas/readme.md"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn includes_are_merged_and_the_including_file_wins() {
|
||||
let t = tree(&[
|
||||
(
|
||||
"kas.yml",
|
||||
&format!(
|
||||
"header:\n version: 14\n includes:\n - kas/common.yml\n \
|
||||
- repo: meta-vendor\n file: kas/vendor.yml\n \
|
||||
- https://example.com/remote.yml\n - kas/missing.yml\n\
|
||||
repos:\n poky:\n commit: {SHA}\n meta-pump:\n"
|
||||
),
|
||||
),
|
||||
(
|
||||
"kas/common.yml",
|
||||
"header:\n version: 14\ndefaults:\n repos:\n branch: kirkstone\n\
|
||||
repos:\n poky:\n url: https://git.yoctoproject.org/poky\n \
|
||||
branch: dunfell\n meta-openembedded:\n \
|
||||
url: https://github.com/openembedded/meta-openembedded\n",
|
||||
),
|
||||
]);
|
||||
let files = vec!["kas.yml".to_string(), "kas/common.yml".to_string()];
|
||||
let read = read(&t.0, &files);
|
||||
assert_eq!(read.pins.len(), 2, "{:?}", read.pins);
|
||||
let poky = &read.pins[0];
|
||||
assert_eq!(poky.name, "poky");
|
||||
assert_eq!(
|
||||
poky.url.as_deref(),
|
||||
Some("https://git.yoctoproject.org/poky")
|
||||
);
|
||||
assert_eq!(poky.branch.as_deref(), Some("dunfell"));
|
||||
assert_eq!(poky.commit.as_deref(), Some(SHA));
|
||||
assert_eq!(poky.file, "kas.yml");
|
||||
// The default branch fills in, and the tree's own layer (no url) is
|
||||
// not a pin.
|
||||
assert_eq!(read.pins[1].branch.as_deref(), Some("kirkstone"));
|
||||
assert_eq!(read.pins[1].file, "kas/common.yml");
|
||||
assert_eq!(
|
||||
read.unread_includes.iter().collect::<Vec<_>>(),
|
||||
[
|
||||
"https://example.com/remote.yml",
|
||||
"kas/missing.yml",
|
||||
"meta-vendor:kas/vendor.yml"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_include_cycle_ends() {
|
||||
let t = tree(&[
|
||||
(
|
||||
"kas/a.yml",
|
||||
"header:\n version: 14\n includes:\n - kas/b.yml\n\
|
||||
repos:\n poky:\n url: https://git.yoctoproject.org/poky\n",
|
||||
),
|
||||
(
|
||||
"kas/b.yml",
|
||||
"header:\n version: 14\n includes:\n - kas/a.yml\n\
|
||||
repos:\n poky:\n branch: scarthgap\n",
|
||||
),
|
||||
(
|
||||
"kas-top.yml",
|
||||
"header:\n version: 14\n includes:\n - kas/a.yml\n",
|
||||
),
|
||||
]);
|
||||
let files: Vec<String> = ["kas-top.yml", "kas/a.yml", "kas/b.yml"]
|
||||
.map(String::from)
|
||||
.to_vec();
|
||||
let read = read(&t.0, &files);
|
||||
assert_eq!(read.pins.len(), 1);
|
||||
assert_eq!(read.pins[0].branch.as_deref(), Some("scarthgap"));
|
||||
assert!(read.unread_includes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_that_only_include_each_other_are_still_read_once() {
|
||||
let t = tree(&[
|
||||
(
|
||||
"kas/a.yml",
|
||||
"header:\n version: 14\n includes:\n - kas/b.yml\n\
|
||||
repos:\n poky:\n url: https://git.yoctoproject.org/poky\n",
|
||||
),
|
||||
(
|
||||
"kas/b.yml",
|
||||
"header:\n version: 14\n includes:\n - kas/a.yml\n",
|
||||
),
|
||||
]);
|
||||
let files: Vec<String> = ["kas/a.yml", "kas/b.yml"].map(String::from).to_vec();
|
||||
assert_eq!(read(&t.0, &files).pins.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_include_leaving_the_tree_is_not_read() {
|
||||
let t = tree(&[(
|
||||
"kas.yml",
|
||||
"header:\n version: 14\n includes:\n - ../../etc/kas.yml\n",
|
||||
)]);
|
||||
let read = read(&t.0, &["kas.yml".to_string()]);
|
||||
assert!(read.pins.is_empty());
|
||||
assert!(read.unread_includes.contains("../../etc/kas.yml"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lock_file_pins_the_commits_and_a_refspec_may_be_one() {
|
||||
let t = tree(&[
|
||||
(
|
||||
"kas.yml",
|
||||
&format!(
|
||||
"header:\n version: 8\nrepos:\n poky:\n \
|
||||
url: https://git.yoctoproject.org/poky\n refspec: refs/heads/kirkstone\n \
|
||||
meta-oe:\n url: https://github.com/openembedded/meta-openembedded\n \
|
||||
refspec: {SHA}\n"
|
||||
),
|
||||
),
|
||||
(
|
||||
"kas.lock.yml",
|
||||
&format!("header:\n version: 14\noverrides:\n repos:\n poky:\n commit: {SHA}\n"),
|
||||
),
|
||||
]);
|
||||
let read = read(&t.0, &["kas.yml".to_string()]);
|
||||
assert_eq!(read.pins[0].branch.as_deref(), Some("kirkstone"));
|
||||
assert_eq!(read.pins[0].commit.as_deref(), Some(SHA));
|
||||
assert_eq!(read.pins[0].file, "kas.lock.yml");
|
||||
assert_eq!(read.pins[1].branch, None);
|
||||
assert_eq!(read.pins[1].commit.as_deref(), Some(SHA));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn yaml_without_a_header_or_with_an_alias_bomb_is_not_read() {
|
||||
let mut bomb =
|
||||
String::from("header:\n version: 14\na: &a [x, x, x, x, x, x, x, x, x, x]\n");
|
||||
let mut previous = 'a';
|
||||
for name in ['b', 'c', 'd', 'e', 'f', 'g'] {
|
||||
bomb.push_str(&format!(
|
||||
"{name}: &{name} [*{previous}, *{previous}, *{previous}, *{previous}, \
|
||||
*{previous}, *{previous}, *{previous}, *{previous}, *{previous}, *{previous}]\n"
|
||||
));
|
||||
previous = name;
|
||||
}
|
||||
let t = tree(&[
|
||||
("kas.yml", bomb.as_str()),
|
||||
(
|
||||
"kas-plain.yml",
|
||||
"repos:\n poky:\n url: https://x/poky\n",
|
||||
),
|
||||
]);
|
||||
assert!(load(&t.0, "kas.yml").is_none());
|
||||
assert!(load(&t.0, "kas-plain.yml").is_none());
|
||||
assert_eq!(expanded_nodes("a: &a [1, 2]\nb: *a\n"), Some(9));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
//! `repo` tool manifests as layer pins.
|
||||
//!
|
||||
//! A manifest (`default.xml` and the files it includes) names remotes
|
||||
//! (`<remote name fetch revision>`), a default (`<default remote revision>`)
|
||||
//! and the projects to check out (`<project name path remote revision
|
||||
//! upstream>`). A project's URL is its remote's `fetch` and its name; its
|
||||
//! revision is its own, else the remote's, else the default's. A revision may
|
||||
//! be a commit, then `upstream` (or `dest-branch`) names the branch.
|
||||
//! `<include name>` is read from the manifest's own directory, never fetched.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::Path;
|
||||
|
||||
use compliance_core::models::{LayerPin, PinSource};
|
||||
|
||||
use super::{clean_ref, is_commit, local_include, read_small};
|
||||
|
||||
/// Most manifest files one configuration may include.
|
||||
const MAX_FILES: usize = 32;
|
||||
|
||||
/// Whether `text` is a `repo` manifest: a `<manifest>` root with projects or
|
||||
/// includes (an Android app manifest is a `<manifest>` without either).
|
||||
fn is_manifest(doc: &roxmltree::Document<'_>) -> bool {
|
||||
let root = doc.root_element();
|
||||
root.has_tag_name("manifest")
|
||||
&& root
|
||||
.children()
|
||||
.any(|c| c.has_tag_name("project") || c.has_tag_name("include"))
|
||||
}
|
||||
|
||||
/// One `<project>`, with what it inherits not yet filled in.
|
||||
#[derive(Debug, Clone)]
|
||||
struct Project {
|
||||
name: String,
|
||||
remote: Option<String>,
|
||||
revision: Option<String>,
|
||||
upstream: Option<String>,
|
||||
file: String,
|
||||
}
|
||||
|
||||
/// Everything one manifest configuration declares, includes merged in
|
||||
/// document order.
|
||||
#[derive(Debug, Default)]
|
||||
struct Declared {
|
||||
/// name -> (fetch, revision)
|
||||
remotes: Vec<(String, String, Option<String>)>,
|
||||
default_remote: Option<String>,
|
||||
default_revision: Option<String>,
|
||||
projects: Vec<Project>,
|
||||
/// The files read, includes too.
|
||||
files: Vec<String>,
|
||||
}
|
||||
|
||||
/// Read the manifest `rel` under `root` and the files it includes into
|
||||
/// `declared`; `stack` ends include cycles, `unread` collects includes that
|
||||
/// could not be read.
|
||||
fn declare(
|
||||
root: &Path,
|
||||
rel: &str,
|
||||
declared: &mut Declared,
|
||||
stack: &mut Vec<String>,
|
||||
unread: &mut BTreeSet<String>,
|
||||
) {
|
||||
if stack.iter().any(|s| s == rel) || declared.files.len() >= MAX_FILES {
|
||||
return;
|
||||
}
|
||||
let Some(text) = read_small(&root.join(rel)) else {
|
||||
unread.insert(rel.to_string());
|
||||
return;
|
||||
};
|
||||
// roxmltree refuses a DTD by default, so no entity can expand.
|
||||
let Ok(doc) = roxmltree::Document::parse(&text) else {
|
||||
unread.insert(rel.to_string());
|
||||
return;
|
||||
};
|
||||
declared.files.push(rel.to_string());
|
||||
stack.push(rel.to_string());
|
||||
let attr = |n: &roxmltree::Node<'_, '_>, a: &str| n.attribute(a).map(str::to_string);
|
||||
for node in doc.root_element().children().filter(|n| n.is_element()) {
|
||||
match node.tag_name().name() {
|
||||
"remote" => {
|
||||
if let (Some(name), Some(fetch)) = (attr(&node, "name"), attr(&node, "fetch")) {
|
||||
declared
|
||||
.remotes
|
||||
.push((name, fetch, attr(&node, "revision")));
|
||||
}
|
||||
}
|
||||
"default" => {
|
||||
declared.default_remote = attr(&node, "remote").or(declared.default_remote.take());
|
||||
declared.default_revision =
|
||||
attr(&node, "revision").or(declared.default_revision.take());
|
||||
}
|
||||
"project" => {
|
||||
if let Some(name) = attr(&node, "name") {
|
||||
declared.projects.push(Project {
|
||||
name,
|
||||
remote: attr(&node, "remote"),
|
||||
revision: attr(&node, "revision"),
|
||||
upstream: attr(&node, "upstream").or_else(|| attr(&node, "dest-branch")),
|
||||
file: rel.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
"extend-project" => {
|
||||
let name = attr(&node, "name");
|
||||
for project in declared
|
||||
.projects
|
||||
.iter_mut()
|
||||
.filter(|p| Some(&p.name) == name.as_ref())
|
||||
{
|
||||
if let Some(revision) = attr(&node, "revision") {
|
||||
project.revision = Some(revision);
|
||||
project.file = rel.to_string();
|
||||
}
|
||||
if let Some(remote) = attr(&node, "remote") {
|
||||
project.remote = Some(remote);
|
||||
}
|
||||
}
|
||||
}
|
||||
"remove-project" => {
|
||||
let name = attr(&node, "name");
|
||||
declared.projects.retain(|p| Some(&p.name) != name.as_ref());
|
||||
}
|
||||
"include" => {
|
||||
let Some(name) = attr(&node, "name") else {
|
||||
continue;
|
||||
};
|
||||
match local_include(root, rel, &name) {
|
||||
Some(found) => declare(root, &found, declared, stack, unread),
|
||||
None => {
|
||||
unread.insert(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
stack.pop();
|
||||
}
|
||||
|
||||
impl Declared {
|
||||
fn pins(self) -> Vec<LayerPin> {
|
||||
let remote = |name: Option<&String>| {
|
||||
name.and_then(|n| self.remotes.iter().rev().find(|(r, _, _)| r == n))
|
||||
};
|
||||
self.projects
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let remote = remote(p.remote.as_ref().or(self.default_remote.as_ref()));
|
||||
let revision = p
|
||||
.revision
|
||||
.clone()
|
||||
.or_else(|| remote.and_then(|(_, _, r)| r.clone()))
|
||||
.or_else(|| self.default_revision.clone());
|
||||
let (branch, commit) = match revision {
|
||||
Some(r) if is_commit(&r) => (p.upstream.clone(), Some(r)),
|
||||
other => (other, None),
|
||||
};
|
||||
LayerPin {
|
||||
name: p.name.clone(),
|
||||
source: PinSource::RepoManifest,
|
||||
file: p.file.clone(),
|
||||
url: remote
|
||||
.map(|(_, fetch, _)| format!("{}/{}", fetch.trim_end_matches('/'), p.name)),
|
||||
branch: branch.as_deref().and_then(clean_ref),
|
||||
commit,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// What the manifests among `files` (XML files relative to `root`) pin, and
|
||||
/// the includes that were not read. A manifest another one includes is read
|
||||
/// with it, not on its own.
|
||||
pub(crate) fn read(root: &Path, files: &[String]) -> (Vec<LayerPin>, BTreeSet<String>) {
|
||||
let mut manifests: Vec<String> = Vec::new();
|
||||
let mut included: BTreeSet<String> = BTreeSet::new();
|
||||
for file in files {
|
||||
let Some(text) = read_small(&root.join(file)) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(doc) = roxmltree::Document::parse(&text) else {
|
||||
continue;
|
||||
};
|
||||
if !is_manifest(&doc) {
|
||||
continue;
|
||||
}
|
||||
manifests.push(file.clone());
|
||||
included.extend(
|
||||
doc.root_element()
|
||||
.children()
|
||||
.filter(|n| n.has_tag_name("include"))
|
||||
.filter_map(|n| n.attribute("name"))
|
||||
.filter_map(|name| local_include(root, file, name)),
|
||||
);
|
||||
}
|
||||
let mut pins: Vec<LayerPin> = Vec::new();
|
||||
let mut unread = BTreeSet::new();
|
||||
let mut visited: BTreeSet<String> = BTreeSet::new();
|
||||
// The manifests no other one includes first; then any left unread,
|
||||
// which only an include cycle leaves.
|
||||
let order = manifests
|
||||
.iter()
|
||||
.filter(|m| !included.contains(*m))
|
||||
.chain(manifests.iter().filter(|m| included.contains(*m)));
|
||||
for manifest in order {
|
||||
if visited.contains(manifest) {
|
||||
continue;
|
||||
}
|
||||
let mut declared = Declared::default();
|
||||
declare(root, manifest, &mut declared, &mut Vec::new(), &mut unread);
|
||||
visited.extend(declared.files.iter().cloned());
|
||||
for pin in declared.pins() {
|
||||
if !pins.contains(&pin) {
|
||||
pins.push(pin);
|
||||
}
|
||||
}
|
||||
}
|
||||
(pins, unread)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::pipeline::recipe_lint::tests::tree;
|
||||
|
||||
const SHA: &str = "4a2d3b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a";
|
||||
|
||||
#[test]
|
||||
fn projects_inherit_remote_and_revision_and_includes_are_read() {
|
||||
let t = tree(&[
|
||||
(
|
||||
"manifests/default.xml",
|
||||
&format!(
|
||||
"<?xml version=\"1.0\"?>\n<manifest>\n\
|
||||
<remote name=\"yocto\" fetch=\"https://git.yoctoproject.org/\"/>\n\
|
||||
<remote name=\"oe\" fetch=\"https://github.com/openembedded\" \
|
||||
revision=\"refs/heads/scarthgap\"/>\n\
|
||||
<default remote=\"yocto\" revision=\"kirkstone\"/>\n\
|
||||
<project name=\"poky\" path=\"layers/poky\" revision=\"{SHA}\" \
|
||||
upstream=\"refs/heads/kirkstone\"/>\n\
|
||||
<project name=\"meta-openembedded\" remote=\"oe\"/>\n\
|
||||
<project name=\"meta-old\"/>\n\
|
||||
<remove-project name=\"meta-old\"/>\n\
|
||||
<include name=\"bsp.xml\"/>\n\
|
||||
<include name=\"missing.xml\"/>\n</manifest>\n"
|
||||
),
|
||||
),
|
||||
(
|
||||
"manifests/bsp.xml",
|
||||
"<manifest>\n<project name=\"meta-arm\" revision=\"refs/tags/yocto-4.0.3\"/>\n\
|
||||
<include name=\"default.xml\"/>\n</manifest>\n",
|
||||
),
|
||||
(
|
||||
"app/AndroidManifest.xml",
|
||||
"<manifest package=\"x\"><application/></manifest>",
|
||||
),
|
||||
]);
|
||||
let files: Vec<String> = [
|
||||
"manifests/default.xml",
|
||||
"manifests/bsp.xml",
|
||||
"app/AndroidManifest.xml",
|
||||
]
|
||||
.map(String::from)
|
||||
.to_vec();
|
||||
let (pins, unread) = read(&t.0, &files);
|
||||
let names: Vec<&str> = pins.iter().map(|p| p.name.as_str()).collect();
|
||||
assert_eq!(names, ["poky", "meta-openembedded", "meta-arm"]);
|
||||
assert_eq!(
|
||||
pins[0].url.as_deref(),
|
||||
Some("https://git.yoctoproject.org/poky")
|
||||
);
|
||||
assert_eq!(pins[0].commit.as_deref(), Some(SHA));
|
||||
assert_eq!(pins[0].branch.as_deref(), Some("kirkstone"));
|
||||
assert_eq!(pins[0].source, PinSource::RepoManifest);
|
||||
assert_eq!(
|
||||
pins[1].url.as_deref(),
|
||||
Some("https://github.com/openembedded/meta-openembedded")
|
||||
);
|
||||
assert_eq!(pins[1].branch.as_deref(), Some("scarthgap"));
|
||||
assert_eq!(pins[2].branch.as_deref(), Some("yocto-4.0.3"));
|
||||
assert_eq!(pins[2].file, "manifests/bsp.xml");
|
||||
assert_eq!(unread.into_iter().collect::<Vec<_>>(), ["missing.xml"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_manifest_with_a_dtd_is_not_read() {
|
||||
let t = tree(&[(
|
||||
"default.xml",
|
||||
"<?xml version=\"1.0\"?>\n<!DOCTYPE manifest [<!ENTITY a \"aaaa\">]>\n\
|
||||
<manifest><project name=\"&a;\"/></manifest>\n",
|
||||
)]);
|
||||
let (pins, _) = read(&t.0, &["default.xml".to_string()]);
|
||||
assert!(pins.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
//! Layer pins of a Yocto / OpenEmbedded layer tree and the release they make
|
||||
//! up (tier 1: nothing is fetched, nothing is built).
|
||||
//!
|
||||
//! The layers a build uses are pinned in one of three ways, all read here:
|
||||
//!
|
||||
//! - **kas** project files ([`kas`]), with their local includes;
|
||||
//! - **`repo` manifests** ([`manifest`]), with their local includes;
|
||||
//! - **git submodules** ([`gitmodules`]), with the commit the tree records.
|
||||
//!
|
||||
//! From the pins, or else from `LAYERSERIES_COMPAT`, [`release`] reads the
|
||||
//! Yocto release and reports when its support has ended or ends soon. The
|
||||
//! pins are stored on the target, where tier 2 (fetching the upstream layers
|
||||
//! at their pins, importing the build's SPDX) will start from.
|
||||
|
||||
pub mod gitmodules;
|
||||
pub mod kas;
|
||||
pub mod manifest;
|
||||
pub mod release;
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
use compliance_core::models::LayerPins;
|
||||
|
||||
use crate::pipeline::recipe_lint;
|
||||
|
||||
/// The stage id an unknown release is recorded under.
|
||||
pub const STAGE: &str = "yocto_release";
|
||||
|
||||
/// The largest kas file, manifest or `.gitmodules` that is read.
|
||||
const MAX_FILE_BYTES: u64 = 1 << 20;
|
||||
|
||||
/// How deep kas files and manifests are looked for.
|
||||
const MAX_DEPTH: usize = 4;
|
||||
|
||||
/// Directories never searched: version control, build output, downloads.
|
||||
const SKIPPED_DIRS: &[&str] = &[".git", "build", "downloads", "sstate-cache", "node_modules"];
|
||||
|
||||
/// The text of the regular file at `path` (not a symlink), when it is at
|
||||
/// most [`MAX_FILE_BYTES`].
|
||||
pub(crate) fn read_small(path: &Path) -> Option<String> {
|
||||
let meta = std::fs::symlink_metadata(path).ok()?;
|
||||
if !meta.is_file() || meta.len() > MAX_FILE_BYTES {
|
||||
return None;
|
||||
}
|
||||
std::fs::read_to_string(path).ok()
|
||||
}
|
||||
|
||||
/// Whether `value` is a full git commit id (SHA-1 or SHA-256).
|
||||
pub(crate) fn is_commit(value: &str) -> bool {
|
||||
matches!(value.len(), 40 | 64) && value.bytes().all(|b| b.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
/// A branch or tag as shown: `refs/heads/` and `refs/tags/` dropped, `None`
|
||||
/// when empty.
|
||||
pub(crate) fn clean_ref(reference: &str) -> Option<String> {
|
||||
let trimmed = reference.trim();
|
||||
let name = trimmed
|
||||
.strip_prefix("refs/heads/")
|
||||
.or_else(|| trimmed.strip_prefix("refs/tags/"))
|
||||
.unwrap_or(trimmed);
|
||||
(!name.is_empty()).then(|| name.to_string())
|
||||
}
|
||||
|
||||
/// `path` joined to `base` (relative to the tree) without leaving it;
|
||||
/// `None` when a `..` climbs out.
|
||||
fn inside(base: &Path, path: &str) -> Option<PathBuf> {
|
||||
let mut out = PathBuf::new();
|
||||
for part in base.join(path).components() {
|
||||
match part {
|
||||
Component::Normal(p) => out.push(p),
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir => {
|
||||
if !out.pop() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Component::RootDir | Component::Prefix(_) => return None,
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The local file an include `path` in `including` (both relative to the
|
||||
/// tree under `root`) names: relative to the including file's directory,
|
||||
/// else to the tree. `None` for a URL, a path leaving the tree, a symlink or
|
||||
/// a missing file.
|
||||
pub(crate) fn local_include(root: &Path, including: &str, path: &str) -> Option<String> {
|
||||
if path.contains("://") || path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let dir = Path::new(including).parent().unwrap_or(Path::new(""));
|
||||
[dir, Path::new("")]
|
||||
.into_iter()
|
||||
.filter_map(|base| inside(base, path))
|
||||
.find(|rel| std::fs::symlink_metadata(root.join(rel)).is_ok_and(|m| m.is_file()))
|
||||
.map(|rel| rel.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
|
||||
/// The layer pins of the tree under `root` and the release they make up,
|
||||
/// outside the `excluded` vendor directories. A submodule's own kas files
|
||||
/// and manifests are its repository's, not the tree's, and are not read.
|
||||
pub fn read(root: &Path, excluded: &[String]) -> LayerPins {
|
||||
let (submodule_pins, submodule_paths) = gitmodules::pins(root);
|
||||
let mut kas_files = Vec::new();
|
||||
let mut xml_files = Vec::new();
|
||||
let walk = walkdir::WalkDir::new(root)
|
||||
.min_depth(1)
|
||||
.max_depth(MAX_DEPTH)
|
||||
.sort_by_file_name()
|
||||
.into_iter()
|
||||
.filter_entry(|e| {
|
||||
let rel = recipe_lint::rel_path(root, e.path());
|
||||
!(e.file_type().is_dir()
|
||||
&& (SKIPPED_DIRS.contains(&e.file_name().to_string_lossy().as_ref())
|
||||
|| excluded.contains(&rel)
|
||||
|| submodule_paths.contains(&rel)))
|
||||
})
|
||||
.filter_map(Result::ok)
|
||||
.filter(|e| e.file_type().is_file());
|
||||
for entry in walk {
|
||||
let rel = recipe_lint::rel_path(root, entry.path());
|
||||
if kas::is_kas_file(&rel) {
|
||||
kas_files.push(rel);
|
||||
} else if rel.ends_with(".xml") {
|
||||
xml_files.push(rel);
|
||||
}
|
||||
}
|
||||
let kas = kas::read(root, &kas_files);
|
||||
let (manifest_pins, manifest_unread) = manifest::read(root, &xml_files);
|
||||
let pins: Vec<_> = kas
|
||||
.pins
|
||||
.into_iter()
|
||||
.chain(manifest_pins)
|
||||
.chain(submodule_pins)
|
||||
.collect();
|
||||
let layers = recipe_lint::layers(root, excluded);
|
||||
let unread: BTreeSet<String> = kas
|
||||
.unread_includes
|
||||
.into_iter()
|
||||
.chain(manifest_unread)
|
||||
.collect();
|
||||
LayerPins {
|
||||
release: release::derive(&pins, &layers),
|
||||
pins,
|
||||
unread_includes: unread.into_iter().collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::pipeline::recipe_lint::tests::tree;
|
||||
use compliance_core::models::{PinSource, ReleaseBasis};
|
||||
|
||||
#[test]
|
||||
fn refs_and_commits_are_recognised() {
|
||||
assert_eq!(
|
||||
clean_ref("refs/heads/kirkstone").as_deref(),
|
||||
Some("kirkstone")
|
||||
);
|
||||
assert_eq!(
|
||||
clean_ref("refs/tags/yocto-5.0.3").as_deref(),
|
||||
Some("yocto-5.0.3")
|
||||
);
|
||||
assert_eq!(clean_ref(" "), None);
|
||||
assert!(is_commit("4a2d3b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a"));
|
||||
assert!(!is_commit("kirkstone"));
|
||||
assert!(!is_commit("4a2d3b5"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn includes_resolve_beside_the_file_then_from_the_root_and_never_outside() {
|
||||
let t = tree(&[("kas/a.yml", ""), ("kas/b.yml", ""), ("common.yml", "")]);
|
||||
assert_eq!(
|
||||
local_include(&t.0, "kas/a.yml", "b.yml").as_deref(),
|
||||
Some("kas/b.yml")
|
||||
);
|
||||
assert_eq!(
|
||||
local_include(&t.0, "kas/a.yml", "kas/b.yml").as_deref(),
|
||||
Some("kas/b.yml")
|
||||
);
|
||||
assert_eq!(
|
||||
local_include(&t.0, "kas/a.yml", "../common.yml").as_deref(),
|
||||
Some("common.yml")
|
||||
);
|
||||
assert_eq!(local_include(&t.0, "kas/a.yml", "../../x.yml"), None);
|
||||
assert_eq!(local_include(&t.0, "kas/a.yml", "/etc/passwd"), None);
|
||||
assert_eq!(local_include(&t.0, "kas/a.yml", "https://x/y.yml"), None);
|
||||
assert_eq!(local_include(&t.0, "kas/a.yml", "missing.yml"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tree_pins_its_layers_and_the_pins_name_the_release() {
|
||||
let t = tree(&[
|
||||
(
|
||||
"kas.yml",
|
||||
"header:\n version: 14\nrepos:\n poky:\n \
|
||||
url: https://git.yoctoproject.org/poky\n branch: dunfell\n \
|
||||
commit: 4a2d3b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a\n",
|
||||
),
|
||||
(
|
||||
".gitmodules",
|
||||
"[submodule \"meta-vendor\"]\n\tpath = layers/meta-vendor\n\t\
|
||||
url = https://git.example.com/meta-vendor.git\n",
|
||||
),
|
||||
// A submodule's own kas files are not the tree's.
|
||||
(
|
||||
"layers/meta-vendor/kas.yml",
|
||||
"header:\n version: 14\nrepos:\n x:\n url: https://x/x\n",
|
||||
),
|
||||
(
|
||||
"conf/layer.conf",
|
||||
"BBFILE_COLLECTIONS += \"pump\"\nLAYERSERIES_COMPAT_pump = \"scarthgap\"\n",
|
||||
),
|
||||
("recipes-app/pump/pump_1.0.bb", ""),
|
||||
]);
|
||||
let read = read(&t.0, &[]);
|
||||
let names: Vec<(&str, PinSource)> = read
|
||||
.pins
|
||||
.iter()
|
||||
.map(|p| (p.name.as_str(), p.source))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
("poky", PinSource::Kas),
|
||||
("meta-vendor", PinSource::GitSubmodule)
|
||||
]
|
||||
);
|
||||
let release = read.release.expect("release");
|
||||
// The pin wins over the layer's LAYERSERIES_COMPAT.
|
||||
assert_eq!(release.codename, "dunfell");
|
||||
assert!(matches!(release.basis, ReleaseBasis::Pin { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_nightly_fixture_pins_dunfell_and_is_end_of_life() {
|
||||
let root =
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../fixtures/nightly/firmware/yocto-layer");
|
||||
let read = read(&root, &[]);
|
||||
let pins: Vec<String> = read
|
||||
.pins
|
||||
.iter()
|
||||
.map(|p| {
|
||||
format!(
|
||||
"{:?} {} {}@{}",
|
||||
p.source,
|
||||
p.name,
|
||||
p.branch.as_deref().unwrap_or("-"),
|
||||
p.commit.as_deref().unwrap_or("-")
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
pins,
|
||||
[
|
||||
// Included files' repositories come first, as kas merges them.
|
||||
"Kas meta-openembedded dunfell@-",
|
||||
"Kas poky dunfell@0b1f2c3d4e5f60718293a4b5c6d7e8f901234567",
|
||||
"GitSubmodule meta-security dunfell@-",
|
||||
]
|
||||
);
|
||||
assert_eq!(read.unread_includes, ["meta-vendor:kas/vendor.yml"]);
|
||||
let release = read.release.expect("release");
|
||||
assert_eq!(release.codename, "dunfell");
|
||||
let today = chrono::NaiveDate::from_ymd_opt(2026, 10, 9).expect("date");
|
||||
let finding = release::finding("t", &release, today).expect("finding");
|
||||
assert_eq!(finding.rule_id.as_deref(), Some(release::RULE_EOL));
|
||||
assert_eq!(finding.file_path.as_deref(), Some("kas.yml"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tree_without_pins_or_compat_has_no_release() {
|
||||
let t = tree(&[("recipes-app/pump/pump_1.0.bb", "")]);
|
||||
let read = read(&t.0, &[]);
|
||||
assert!(read.pins.is_empty());
|
||||
assert_eq!(read.release, None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,547 @@
|
||||
//! The Yocto release a layer tree builds, its support period, and a finding
|
||||
//! when that period is over or ends soon.
|
||||
|
||||
use chrono::NaiveDate;
|
||||
use compliance_core::models::{
|
||||
display_codename, soon_window, Finding, LayerPin, ReleaseBasis, ScanType, Severity, Support,
|
||||
YoctoRelease,
|
||||
};
|
||||
|
||||
use crate::pipeline::dedup;
|
||||
use crate::pipeline::recipe_lint::Layer;
|
||||
|
||||
/// The scanner name of the support-status findings.
|
||||
pub const SCANNER: &str = "yocto-release";
|
||||
/// The rule of a release past its end of life.
|
||||
pub const RULE_EOL: &str = "yocto-release-eol";
|
||||
/// The rule of a release whose end of life is near: within six months for an
|
||||
/// LTS release, two for any other ([`soon_window`]).
|
||||
pub const RULE_EOL_SOON: &str = "yocto-release-eol-soon";
|
||||
/// Where the support periods come from.
|
||||
pub const SOURCE_URL: &str = "https://wiki.yoctoproject.org/wiki/Releases";
|
||||
/// When [`RELEASES`] was checked against its sources.
|
||||
pub const CHECKED_ON: &str = "2026-10-09";
|
||||
|
||||
/// One Yocto Project release.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct ReleaseInfo {
|
||||
/// The codename, lower case.
|
||||
pub codename: &'static str,
|
||||
/// The Yocto Project version.
|
||||
pub version: &'static str,
|
||||
/// A long term support release.
|
||||
pub lts: bool,
|
||||
/// Its release day.
|
||||
pub released: NaiveDate,
|
||||
/// The day its support ends (or ended).
|
||||
pub end_of_life: NaiveDate,
|
||||
}
|
||||
|
||||
/// A day of the table; every date in it is valid, a test checks them.
|
||||
const fn day(y: i32, m: u32, d: u32) -> NaiveDate {
|
||||
match NaiveDate::from_ymd_opt(y, m, d) {
|
||||
Some(date) => date,
|
||||
None => NaiveDate::MIN,
|
||||
}
|
||||
}
|
||||
|
||||
const fn release(
|
||||
codename: &'static str,
|
||||
version: &'static str,
|
||||
lts: bool,
|
||||
released: NaiveDate,
|
||||
end_of_life: NaiveDate,
|
||||
) -> ReleaseInfo {
|
||||
ReleaseInfo {
|
||||
codename,
|
||||
version,
|
||||
lts,
|
||||
released,
|
||||
end_of_life,
|
||||
}
|
||||
}
|
||||
|
||||
/// The Yocto Project releases, oldest first.
|
||||
///
|
||||
/// Source: the Yocto Project releases wiki, <https://wiki.yoctoproject.org/wiki/Releases>
|
||||
/// (page last updated 2026-09-10), checked on 2026-10-09: codename, version,
|
||||
/// LTS and support status. The wiki gives months only; the exact release and
|
||||
/// end-of-life days are endoflife.date's (<https://endoflife.date/yocto>,
|
||||
/// checked the same day), which agree with the wiki's months except
|
||||
/// Walnascar (wiki: "EOL since November 2025", endoflife.date: 2025-12-07).
|
||||
/// For Thud and older, which endoflife.date does not list, the end of life
|
||||
/// is the last day of the month of the release's last point release (wiki),
|
||||
/// and the release day the first of its month. Blacksail (6.1, due October
|
||||
/// 2026) is not released yet and not listed: a newer branch reads as an
|
||||
/// unknown release.
|
||||
pub const RELEASES: &[ReleaseInfo] = &[
|
||||
release("jethro", "2.0", false, day(2015, 11, 1), day(2017, 1, 31)),
|
||||
release("krogoth", "2.1", false, day(2016, 4, 1), day(2017, 7, 31)),
|
||||
release("morty", "2.2", false, day(2016, 11, 1), day(2018, 7, 31)),
|
||||
release("pyro", "2.3", false, day(2017, 5, 1), day(2018, 7, 31)),
|
||||
release("rocko", "2.4", false, day(2017, 10, 1), day(2018, 11, 30)),
|
||||
release("sumo", "2.5", false, day(2018, 4, 1), day(2019, 4, 30)),
|
||||
release("thud", "2.6", false, day(2018, 11, 1), day(2019, 10, 31)),
|
||||
release("warrior", "2.7", false, day(2019, 5, 1), day(2020, 6, 1)),
|
||||
release("zeus", "3.0", false, day(2019, 10, 22), day(2020, 8, 1)),
|
||||
release("dunfell", "3.1", true, day(2020, 4, 21), day(2024, 4, 30)),
|
||||
release(
|
||||
"gatesgarth",
|
||||
"3.2",
|
||||
false,
|
||||
day(2020, 11, 3),
|
||||
day(2021, 5, 1),
|
||||
),
|
||||
release(
|
||||
"hardknott",
|
||||
"3.3",
|
||||
false,
|
||||
day(2021, 4, 19),
|
||||
day(2022, 4, 20),
|
||||
),
|
||||
release("honister", "3.4", false, day(2021, 10, 25), day(2022, 5, 1)),
|
||||
release("kirkstone", "4.0", true, day(2022, 4, 25), day(2026, 4, 27)),
|
||||
release(
|
||||
"langdale",
|
||||
"4.1",
|
||||
false,
|
||||
day(2022, 10, 23),
|
||||
day(2023, 5, 27),
|
||||
),
|
||||
release(
|
||||
"mickledore",
|
||||
"4.2",
|
||||
false,
|
||||
day(2023, 5, 3),
|
||||
day(2023, 11, 5),
|
||||
),
|
||||
release("nanbield", "4.3", false, day(2023, 11, 9), day(2024, 6, 9)),
|
||||
release("scarthgap", "5.0", true, day(2024, 4, 29), day(2028, 4, 30)),
|
||||
release("styhead", "5.1", false, day(2024, 10, 16), day(2025, 5, 16)),
|
||||
release("walnascar", "5.2", false, day(2025, 5, 7), day(2025, 12, 7)),
|
||||
release(
|
||||
"whinlatter",
|
||||
"5.3",
|
||||
false,
|
||||
day(2025, 12, 15),
|
||||
day(2026, 6, 15),
|
||||
),
|
||||
release("wrynose", "6.0", true, day(2026, 5, 13), day(2030, 4, 30)),
|
||||
];
|
||||
|
||||
/// The repositories whose branch names the release, most telling first.
|
||||
const RELEASE_REPOS: &[&str] = &["poky", "openembedded-core", "meta-openembedded"];
|
||||
|
||||
fn by_codename(codename: &str) -> Option<&'static ReleaseInfo> {
|
||||
RELEASES.iter().find(|r| r.codename == codename)
|
||||
}
|
||||
|
||||
/// The release a branch or tag names: a codename as one of its words
|
||||
/// (`scarthgap`, `scarthgap-5.0.3`, `kirkstone-4.0.15`, `dunfell-23.0.10`),
|
||||
/// or a `yocto-<version>` tag (`yocto-5.0.3`). `master` names none.
|
||||
pub(crate) fn from_reference(reference: &str) -> Option<&'static ReleaseInfo> {
|
||||
let lower = reference.to_ascii_lowercase();
|
||||
if let Some(found) = lower
|
||||
.split(|c: char| !c.is_ascii_alphanumeric())
|
||||
.find_map(by_codename)
|
||||
{
|
||||
return Some(found);
|
||||
}
|
||||
let version = lower.rsplit('/').next()?.strip_prefix("yocto-")?;
|
||||
let mut parts = version.split('.');
|
||||
let major_minor = format!("{}.{}", parts.next()?, parts.next()?);
|
||||
RELEASES.iter().find(|r| r.version == major_minor)
|
||||
}
|
||||
|
||||
/// The newest of `codenames` the table knows.
|
||||
fn newest<'a>(codenames: impl IntoIterator<Item = &'a String>) -> Option<&'static ReleaseInfo> {
|
||||
codenames
|
||||
.into_iter()
|
||||
.filter_map(|c| by_codename(c))
|
||||
.max_by_key(|r| r.released)
|
||||
}
|
||||
|
||||
/// Whether `pin` is the repository `repo` (by its URL's last segment, else
|
||||
/// its name).
|
||||
fn pin_is(pin: &LayerPin, repo: &str) -> bool {
|
||||
let tail = pin.url.as_deref().and_then(|url| {
|
||||
url.trim_end_matches('/')
|
||||
.rsplit(['/', ':'])
|
||||
.next()
|
||||
.map(|t| t.trim_end_matches(".git"))
|
||||
});
|
||||
tail.unwrap_or(&pin.name) == repo || pin.name == repo
|
||||
}
|
||||
|
||||
/// The configuration file of `layer`, relative to the tree.
|
||||
fn conf_of(layer: &Layer) -> String {
|
||||
if layer.dir == "." {
|
||||
"conf/layer.conf".to_string()
|
||||
} else {
|
||||
format!("{}/conf/layer.conf", layer.dir)
|
||||
}
|
||||
}
|
||||
|
||||
/// The release the tree builds, from the first of:
|
||||
///
|
||||
/// 1. the branch or tag of a Poky, OpenEmbedded-Core or meta-openembedded pin
|
||||
/// (in that order): what the build fetches;
|
||||
/// 2. `LAYERSERIES_COMPAT_core` of an OpenEmbedded-Core layer in the tree;
|
||||
/// 3. the newest release every customer layer declares compatible in
|
||||
/// `LAYERSERIES_COMPAT_*`: the build can use no newer one, and a layer
|
||||
/// that also names older releases is not built on those for it (the
|
||||
/// recipe lint reads the oldest instead, for the syntax it must accept).
|
||||
///
|
||||
/// `None` when none of them names a release the table knows.
|
||||
pub(crate) fn derive(pins: &[LayerPin], layers: &[Layer]) -> Option<YoctoRelease> {
|
||||
let make = |info: &ReleaseInfo, basis: ReleaseBasis, file: String| YoctoRelease {
|
||||
codename: info.codename.to_string(),
|
||||
version: info.version.to_string(),
|
||||
lts: info.lts,
|
||||
end_of_life: info.end_of_life,
|
||||
basis,
|
||||
file,
|
||||
};
|
||||
for repo in RELEASE_REPOS {
|
||||
for pin in pins.iter().filter(|p| pin_is(p, repo)) {
|
||||
let Some(branch) = &pin.branch else { continue };
|
||||
if let Some(info) = from_reference(branch) {
|
||||
let basis = ReleaseBasis::Pin {
|
||||
name: pin.name.clone(),
|
||||
branch: branch.clone(),
|
||||
};
|
||||
return Some(make(info, basis, pin.file.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let core = layers
|
||||
.iter()
|
||||
.filter(|l| l.collections.iter().any(|c| c == "core"))
|
||||
.find_map(|l| newest(&l.compat).map(|info| (info, conf_of(l))));
|
||||
if let Some((info, file)) = core {
|
||||
return Some(make(info, ReleaseBasis::CoreLayer, file));
|
||||
}
|
||||
let own: Vec<&Layer> = layers
|
||||
.iter()
|
||||
.filter(|l| !l.upstream && !l.compat.is_empty())
|
||||
.collect();
|
||||
let first = own.first()?;
|
||||
let common = first
|
||||
.compat
|
||||
.iter()
|
||||
.filter(|c| own.iter().all(|l| l.compat.contains(c)));
|
||||
newest(common).map(|info| make(info, ReleaseBasis::LayerCompat, conf_of(first)))
|
||||
}
|
||||
|
||||
/// The newest LTS release on `today` whose end of life is not yet soon.
|
||||
fn current_lts(today: NaiveDate) -> Option<&'static ReleaseInfo> {
|
||||
let horizon = today.checked_add_months(soon_window(true))?;
|
||||
RELEASES
|
||||
.iter()
|
||||
.filter(|r| r.lts && r.released <= today && r.end_of_life > horizon)
|
||||
.max_by_key(|r| r.released)
|
||||
}
|
||||
|
||||
/// What `basis` (in `file`) is, in words.
|
||||
fn basis_text(basis: &ReleaseBasis, file: &str) -> String {
|
||||
match basis {
|
||||
ReleaseBasis::Pin { name, branch } => {
|
||||
format!("the branch or tag \"{branch}\" that {file} pins {name} to")
|
||||
}
|
||||
ReleaseBasis::CoreLayer => {
|
||||
format!("LAYERSERIES_COMPAT_core of the OpenEmbedded-Core layer ({file})")
|
||||
}
|
||||
ReleaseBasis::LayerCompat => format!(
|
||||
"LAYERSERIES_COMPAT of your layers ({file}): the newest release they all declare"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The support-status finding of `repo_id` for `release` on `today`;
|
||||
/// `None` while its end of life is not yet soon ([`soon_window`]).
|
||||
pub(crate) fn finding(repo_id: &str, release: &YoctoRelease, today: NaiveDate) -> Option<Finding> {
|
||||
let (rule, severity, title, status) = match release.support(today) {
|
||||
Support::Supported => return None,
|
||||
Support::Ended => (
|
||||
RULE_EOL,
|
||||
Severity::High,
|
||||
"is end of life since",
|
||||
"ended its support on",
|
||||
),
|
||||
Support::EndsSoon => (
|
||||
RULE_EOL_SOON,
|
||||
Severity::Medium,
|
||||
"reaches end of life on",
|
||||
"ends its support on",
|
||||
),
|
||||
};
|
||||
let name = display_codename(&release.codename);
|
||||
let lts = if release.lts { " LTS" } else { "" };
|
||||
let eol = release.end_of_life;
|
||||
let description = format!(
|
||||
"The layers build Yocto {name} ({version}{lts}), read from {basis}. The Yocto Project \
|
||||
{status} {eol} (source: {SOURCE_URL}, checked {CHECKED_ON}). After that, no security \
|
||||
fixes are published for its recipes, so vulnerabilities in the image's components \
|
||||
stay open unless every fix is backported by hand.\n\nCRA Annex I Part I (2)(c): \
|
||||
vulnerabilities can be addressed through security updates; Annex I Part II (2): \
|
||||
vulnerabilities are remediated without delay, including by security updates, over \
|
||||
the product's support period.",
|
||||
version = release.version,
|
||||
basis = basis_text(&release.basis, &release.file),
|
||||
);
|
||||
let remediation = match current_lts(today) {
|
||||
Some(lts) if lts.codename != release.codename => format!(
|
||||
"Move the layers to the current long term support release, Yocto {} ({}), \
|
||||
supported until {}: update the pins of Poky / OpenEmbedded-Core and the other \
|
||||
layers to its branch, and LAYERSERIES_COMPAT of your layers. Until then, \
|
||||
backport the security fixes the product needs and record them (CVE_STATUS, \
|
||||
patches).",
|
||||
display_codename(lts.codename),
|
||||
lts.version,
|
||||
lts.end_of_life
|
||||
),
|
||||
_ => "Move the layers to a Yocto release that is supported for the product's support \
|
||||
period, and backport security fixes until then."
|
||||
.to_string(),
|
||||
};
|
||||
let fingerprint =
|
||||
dedup::compute_fingerprint(&[repo_id, SCANNER, rule, &release.file, &release.codename]);
|
||||
let mut finding = Finding::new(
|
||||
repo_id.to_string(),
|
||||
fingerprint,
|
||||
SCANNER.to_string(),
|
||||
ScanType::Sbom,
|
||||
format!("Yocto {name} ({}) {title} {eol}", release.version),
|
||||
description,
|
||||
severity,
|
||||
);
|
||||
finding.rule_id = Some(rule.to_string());
|
||||
finding.cwe = Some("CWE-1104".to_string());
|
||||
finding.remediation = Some(remediation);
|
||||
finding.file_path = Some(release.file.clone());
|
||||
Some(finding)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::PinSource;
|
||||
|
||||
fn date(y: i32, m: u32, d: u32) -> NaiveDate {
|
||||
NaiveDate::from_ymd_opt(y, m, d).expect("date")
|
||||
}
|
||||
|
||||
fn pin(name: &str, url: &str, branch: Option<&str>) -> LayerPin {
|
||||
LayerPin {
|
||||
name: name.into(),
|
||||
source: PinSource::Kas,
|
||||
file: "kas.yml".into(),
|
||||
url: Some(url.into()),
|
||||
branch: branch.map(str::to_string),
|
||||
commit: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn layer(dir: &str, collections: &[&str], compat: &[&str], upstream: bool) -> Layer {
|
||||
Layer {
|
||||
dir: dir.into(),
|
||||
release: None,
|
||||
upstream,
|
||||
collections: collections.iter().map(|c| c.to_string()).collect(),
|
||||
compat: compat.iter().map(|c| c.to_string()).collect(),
|
||||
files: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_table_is_ordered_and_names_the_required_releases() {
|
||||
assert!(RELEASES.iter().all(|r| r.released != NaiveDate::MIN
|
||||
&& r.end_of_life != NaiveDate::MIN
|
||||
&& r.released < r.end_of_life));
|
||||
assert!(RELEASES.windows(2).all(|w| w[0].released < w[1].released));
|
||||
for codename in [
|
||||
"dunfell",
|
||||
"kirkstone",
|
||||
"mickledore",
|
||||
"nanbield",
|
||||
"scarthgap",
|
||||
"styhead",
|
||||
"walnascar",
|
||||
"whinlatter",
|
||||
"wrynose",
|
||||
] {
|
||||
assert!(by_codename(codename).is_some(), "{codename}");
|
||||
}
|
||||
assert_eq!(date(2026, 10, 9).to_string(), CHECKED_ON);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn branches_and_tags_name_their_release() {
|
||||
let codename = |r: &str| from_reference(r).map(|i| i.codename);
|
||||
assert_eq!(codename("scarthgap"), Some("scarthgap"));
|
||||
assert_eq!(codename("scarthgap-5.0.3"), Some("scarthgap"));
|
||||
assert_eq!(codename("yocto-5.0.3"), Some("scarthgap"));
|
||||
assert_eq!(codename("refs/tags/yocto-4.0.15"), Some("kirkstone"));
|
||||
assert_eq!(codename("kirkstone-4.0.15"), Some("kirkstone"));
|
||||
assert_eq!(codename("dunfell-23.0.10"), Some("dunfell"));
|
||||
assert_eq!(codename("Mickledore"), Some("mickledore"));
|
||||
assert_eq!(codename("master"), None);
|
||||
assert_eq!(codename("main"), None);
|
||||
assert_eq!(codename("yocto-9.9"), None);
|
||||
assert_eq!(codename("blacksail"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn poky_pins_win_over_meta_openembedded_and_layer_compat() {
|
||||
let pins = [
|
||||
pin(
|
||||
"meta-oe",
|
||||
"https://github.com/openembedded/meta-openembedded.git",
|
||||
Some("scarthgap"),
|
||||
),
|
||||
pin("poky", "https://git.yoctoproject.org/poky", Some("dunfell")),
|
||||
];
|
||||
let layers = [layer(".", &["pump"], &["scarthgap"], false)];
|
||||
let release = derive(&pins, &layers).expect("release");
|
||||
assert_eq!(release.codename, "dunfell");
|
||||
assert_eq!(
|
||||
release.basis,
|
||||
ReleaseBasis::Pin {
|
||||
name: "poky".into(),
|
||||
branch: "dunfell".into()
|
||||
}
|
||||
);
|
||||
assert_eq!(release.file, "kas.yml");
|
||||
// meta-openembedded speaks when poky names no release.
|
||||
let pins = [
|
||||
pin("poky", "https://git.yoctoproject.org/poky", None),
|
||||
pin(
|
||||
"meta-oe",
|
||||
"git@github.com:openembedded/meta-openembedded.git",
|
||||
Some("kirkstone"),
|
||||
),
|
||||
];
|
||||
assert_eq!(
|
||||
derive(&pins, &layers).expect("release").codename,
|
||||
"kirkstone"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_pins_the_core_layer_then_the_customer_layers_decide() {
|
||||
let core = layer("poky/meta", &["core"], &["nanbield"], true);
|
||||
let own = layer("meta-pump", &["pump"], &["kirkstone", "scarthgap"], false);
|
||||
let release = derive(&[], &[core, own.clone()]).expect("release");
|
||||
assert_eq!(release.codename, "nanbield");
|
||||
assert_eq!(release.basis, ReleaseBasis::CoreLayer);
|
||||
assert_eq!(release.file, "poky/meta/conf/layer.conf");
|
||||
// The newest release every own layer declares.
|
||||
let other = layer(
|
||||
"meta-ui",
|
||||
&["ui"],
|
||||
&["kirkstone", "scarthgap", "wrynose"],
|
||||
false,
|
||||
);
|
||||
let release = derive(&[], &[own.clone(), other]).expect("release");
|
||||
assert_eq!(release.codename, "scarthgap");
|
||||
assert_eq!(release.basis, ReleaseBasis::LayerCompat);
|
||||
assert_eq!(release.file, "meta-pump/conf/layer.conf");
|
||||
// Layers with nothing in common, or no compat at all: unknown.
|
||||
let apart = layer("meta-ui", &["ui"], &["wrynose"], false);
|
||||
assert_eq!(derive(&[], &[own, apart]), None);
|
||||
assert_eq!(derive(&[], &[layer(".", &["x"], &[], false)]), None);
|
||||
}
|
||||
|
||||
fn release_of(codename: &str) -> YoctoRelease {
|
||||
let info = by_codename(codename).expect("known");
|
||||
YoctoRelease {
|
||||
codename: codename.into(),
|
||||
version: info.version.into(),
|
||||
lts: info.lts,
|
||||
end_of_life: info.end_of_life,
|
||||
basis: ReleaseBasis::Pin {
|
||||
name: "poky".into(),
|
||||
branch: codename.into(),
|
||||
},
|
||||
file: "kas.yml".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ended_release_is_a_high_finding_naming_the_date_source_and_current_lts() {
|
||||
let today = date(2026, 10, 9);
|
||||
let f = finding("t1", &release_of("dunfell"), today).expect("finding");
|
||||
assert_eq!(f.scanner, SCANNER);
|
||||
assert_eq!(f.rule_id.as_deref(), Some(RULE_EOL));
|
||||
assert_eq!(f.severity, Severity::High);
|
||||
assert_eq!(f.scan_type, ScanType::Sbom);
|
||||
assert_eq!(
|
||||
f.title,
|
||||
"Yocto Dunfell (3.1) is end of life since 2024-04-30"
|
||||
);
|
||||
assert!(f.description.contains("Yocto Dunfell (3.1 LTS)"));
|
||||
assert!(f
|
||||
.description
|
||||
.contains("\"dunfell\" that kas.yml pins poky to"));
|
||||
assert!(f.description.contains(SOURCE_URL));
|
||||
assert!(f.description.contains("Annex I Part I (2)(c)"));
|
||||
assert!(f.description.contains("Part II"));
|
||||
assert_eq!(f.file_path.as_deref(), Some("kas.yml"));
|
||||
assert_eq!(f.cwe.as_deref(), Some("CWE-1104"));
|
||||
// Wrynose is the newest LTS released by then.
|
||||
assert!(f
|
||||
.remediation
|
||||
.as_deref()
|
||||
.expect("remediation")
|
||||
.contains("Yocto Wrynose (6.0), supported until 2030-04-30"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_release_ending_soon_is_medium_and_a_supported_one_none() {
|
||||
let today = date(2026, 3, 1);
|
||||
let f = finding("t1", &release_of("kirkstone"), today).expect("finding");
|
||||
assert_eq!(f.rule_id.as_deref(), Some(RULE_EOL_SOON));
|
||||
assert_eq!(f.severity, Severity::Medium);
|
||||
assert_eq!(
|
||||
f.title,
|
||||
"Yocto Kirkstone (4.0) reaches end of life on 2026-04-27"
|
||||
);
|
||||
// Wrynose is not out yet: Scarthgap is the current LTS.
|
||||
assert!(f
|
||||
.remediation
|
||||
.as_deref()
|
||||
.expect("r")
|
||||
.contains("Yocto Scarthgap (5.0)"));
|
||||
assert!(finding("t1", &release_of("scarthgap"), today).is_none());
|
||||
// A different release is a different finding.
|
||||
let other = finding("t1", &release_of("mickledore"), today).expect("finding");
|
||||
assert_ne!(other.fingerprint, f.fingerprint);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_release_without_lts_warns_two_months_ahead() {
|
||||
// Whinlatter (5.3) ends on 2026-06-15.
|
||||
let whinlatter = release_of("whinlatter");
|
||||
assert!(finding("t1", &whinlatter, date(2026, 4, 14)).is_none());
|
||||
let soon = finding("t1", &whinlatter, date(2026, 4, 15)).expect("finding");
|
||||
assert_eq!(soon.rule_id.as_deref(), Some(RULE_EOL_SOON));
|
||||
assert_eq!(soon.severity, Severity::Medium);
|
||||
let ended = finding("t1", &whinlatter, date(2026, 6, 16)).expect("finding");
|
||||
assert_eq!(ended.rule_id.as_deref(), Some(RULE_EOL));
|
||||
assert_eq!(ended.severity, Severity::High);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rules_are_bound_in_the_control_map() {
|
||||
let map = control_map::ControlMap::cra().expect("map");
|
||||
for rule in [RULE_EOL, RULE_EOL_SOON] {
|
||||
let controls: Vec<String> = map
|
||||
.controls_for_finding(SCANNER, Some("CWE-1104"), Some(rule))
|
||||
.into_iter()
|
||||
.map(|c| c.control.clone())
|
||||
.collect();
|
||||
assert_eq!(controls, ["cra-ai-22"], "{rule}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,10 @@ use compliance_core::AgentConfig;
|
||||
pub const ENTITLEMENT_TTL: Duration = Duration::from_secs(60);
|
||||
/// Refresh the service token this long before it expires.
|
||||
const TOKEN_MARGIN: Duration = Duration::from_secs(30);
|
||||
/// Upper bound for one registry or Keycloak token request. Without it a hung
|
||||
/// Keycloak holds the token lock, and every caller behind it, for the shared
|
||||
/// client's 30 s.
|
||||
const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
/// The registry's `reason` for a member blocked in the tenant.
|
||||
pub const MEMBER_BLOCKED: &str = "member_blocked";
|
||||
@@ -230,6 +234,7 @@ impl RegistryClient {
|
||||
let resp = self
|
||||
.http
|
||||
.post(url)
|
||||
.timeout(REQUEST_TIMEOUT)
|
||||
.form(&[
|
||||
("grant_type", "client_credentials"),
|
||||
("client_id", id.as_str()),
|
||||
@@ -261,7 +266,7 @@ impl RegistryClient {
|
||||
let mut rb = self
|
||||
.http
|
||||
.request(method, format!("{}{path}", self.base_url))
|
||||
.timeout(Duration::from_secs(5));
|
||||
.timeout(REQUEST_TIMEOUT);
|
||||
if let Some(tok) = self.bearer().await? {
|
||||
rb = rb.bearer_auth(tok);
|
||||
}
|
||||
@@ -542,4 +547,43 @@ mod tests {
|
||||
assert!(!scheduler_runs_for(s), "{s} should be skipped");
|
||||
}
|
||||
}
|
||||
|
||||
/// A Keycloak that accepts the connection and never answers costs one
|
||||
/// [`REQUEST_TIMEOUT`], not the shared client's 30 s.
|
||||
#[tokio::test]
|
||||
async fn a_hung_token_endpoint_gives_up_after_the_request_timeout() {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move {
|
||||
let mut held = Vec::new();
|
||||
while let Ok((socket, _)) = listener.accept().await {
|
||||
held.push(socket);
|
||||
}
|
||||
});
|
||||
let http = reqwest::Client::builder()
|
||||
.timeout(Duration::from_secs(30))
|
||||
.build()
|
||||
.unwrap();
|
||||
let client = RegistryClient {
|
||||
base_url: format!("http://{addr}"),
|
||||
product: "pruefwerk".into(),
|
||||
http,
|
||||
token_url: Some(format!("http://{addr}/token")),
|
||||
client_id: Some("svc".into()),
|
||||
client_secret: Some("secret".into()),
|
||||
token: Mutex::new(None),
|
||||
cache: DashMap::new(),
|
||||
projects: DashMap::new(),
|
||||
};
|
||||
|
||||
let started = Instant::now();
|
||||
let result = client.bearer().await;
|
||||
|
||||
assert!(result.is_err(), "{result:?}");
|
||||
assert!(
|
||||
started.elapsed() < REQUEST_TIMEOUT * 2,
|
||||
"{:?}",
|
||||
started.elapsed()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -14,15 +14,34 @@
|
||||
//! scan will pick up the latest code anyway. Ten pushes during a long scan
|
||||
//! therefore cost two scans, not ten. Dropped requests are never billed: only
|
||||
//! a scan that actually ran emits usage.
|
||||
//!
|
||||
//! A scheduled scan also starts after a random delay of up to
|
||||
//! [`SCHEDULED_SCAN_JITTER`], so the scans of a tenant's repositories (often
|
||||
//! all on one git host) do not start in the same second.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use dashmap::mapref::entry::Entry;
|
||||
use dashmap::DashMap;
|
||||
use rand::Rng;
|
||||
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
|
||||
|
||||
use compliance_core::models::ScanTrigger;
|
||||
|
||||
/// The longest a scheduled scan waits before it starts.
|
||||
pub const SCHEDULED_SCAN_JITTER: Duration = Duration::from_secs(30);
|
||||
|
||||
/// How long a scan with `trigger` waits before it starts: a random delay of
|
||||
/// up to [`SCHEDULED_SCAN_JITTER`] for a scheduled scan, none for a scan a
|
||||
/// webhook or a person started.
|
||||
pub fn start_delay(trigger: &ScanTrigger) -> Duration {
|
||||
match trigger {
|
||||
ScanTrigger::Scheduled => rand::rng().random_range(Duration::ZERO..=SCHEDULED_SCAN_JITTER),
|
||||
ScanTrigger::Webhook | ScanTrigger::Manual | ScanTrigger::Support => Duration::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
/// What happened to a scan request.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Admission {
|
||||
@@ -153,8 +172,30 @@ impl Drop for HeldTarget<'_> {
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::{Admission, HeldTarget, ScanGate};
|
||||
use super::{start_delay, Admission, HeldTarget, ScanGate, SCHEDULED_SCAN_JITTER};
|
||||
use compliance_core::models::ScanTrigger;
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn a_scheduled_scan_waits_within_the_jitter() {
|
||||
let delays: Vec<Duration> = (0..1000)
|
||||
.map(|_| start_delay(&ScanTrigger::Scheduled))
|
||||
.collect();
|
||||
assert!(delays.iter().all(|d| *d <= SCHEDULED_SCAN_JITTER));
|
||||
// Spread out, not one fixed delay.
|
||||
assert!(delays.iter().any(|d| *d != delays[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn webhook_manual_and_support_scans_start_at_once() {
|
||||
for trigger in [
|
||||
ScanTrigger::Webhook,
|
||||
ScanTrigger::Manual,
|
||||
ScanTrigger::Support,
|
||||
] {
|
||||
assert_eq!(start_delay(&trigger), Duration::ZERO);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_burst_coalesces_into_one_run_and_one_follow_up() {
|
||||
|
||||
@@ -54,8 +54,13 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError>
|
||||
tenant_count = tenants.len(),
|
||||
"CVE monitor: tenants resolved"
|
||||
);
|
||||
for tenant_id in tenants {
|
||||
monitor_cves(&agent, &tenant_id).await;
|
||||
for tenant_id in &tenants {
|
||||
monitor_cves(&agent, tenant_id).await;
|
||||
}
|
||||
// Components only NVD knows (by CPE), incrementally; `NVD_MONITOR=off`
|
||||
// turns it off.
|
||||
if crate::pipeline::nvd_monitor::enabled(std::env::var("NVD_MONITOR").ok().as_deref()) {
|
||||
crate::pipeline::nvd_monitor::run(&agent, &tenants).await;
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -242,7 +247,6 @@ async fn scan_all_repos(agent: &ComplianceAgent, tenant_id: &str) {
|
||||
}
|
||||
|
||||
async fn monitor_cves(agent: &ComplianceAgent, tenant_id: &str) {
|
||||
use compliance_core::models::notification::{parse_severity, CveNotification};
|
||||
use compliance_core::models::SbomEntry;
|
||||
use futures_util::StreamExt;
|
||||
|
||||
@@ -334,32 +338,14 @@ async fn monitor_cves(agent: &ComplianceAgent, tenant_id: &str) {
|
||||
enricher.enrich(&mut alerts, &mut repo_entries).await;
|
||||
}
|
||||
|
||||
// Upsert CVE alerts (existing logic); an existing alert's
|
||||
// exploitation is refreshed.
|
||||
// New alerts are stored; an existing alert's exploitation is
|
||||
// refreshed.
|
||||
for alert in &alerts {
|
||||
let filter = doc! { "cve_id": &alert.cve_id, "repo_id": &alert.repo_id };
|
||||
let mut insert = mongodb::bson::to_document(alert).unwrap_or_default();
|
||||
let exploitation = insert.remove("exploitation");
|
||||
let mut update = doc! { "$setOnInsert": insert };
|
||||
if let Some(exploitation) = exploitation {
|
||||
update.insert("$set", doc! { "exploitation": exploitation });
|
||||
}
|
||||
let _ = db
|
||||
.cve_alerts()
|
||||
.update_one(filter.clone(), update)
|
||||
.upsert(true)
|
||||
.await;
|
||||
// An alert stored before purls were recorded gets its
|
||||
// component's purl (only for the same package and version).
|
||||
if let Some(purl) = &alert.purl {
|
||||
let mut without_purl = filter;
|
||||
without_purl.insert("affected_package", &alert.affected_package);
|
||||
without_purl.insert("affected_version", &alert.affected_version);
|
||||
without_purl.insert("purl", doc! { "$exists": false });
|
||||
let _ = db
|
||||
.cve_alerts()
|
||||
.update_one(without_purl, doc! { "$set": { "purl": purl } })
|
||||
.await;
|
||||
if let Err(e) = crate::pipeline::vex_lifecycle::store_monitored(&db, alert).await {
|
||||
tracing::warn!(
|
||||
cve = alert.cve_id,
|
||||
"CVE monitor: storing the alert failed: {e}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -382,46 +368,15 @@ async fn monitor_cves(agent: &ComplianceAgent, tenant_id: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
// Create notifications for NEW CVEs (dedup against existing notifications)
|
||||
for alert in &alerts {
|
||||
let filter = doc! {
|
||||
"cve_id": &alert.cve_id,
|
||||
"repo_id": &alert.repo_id,
|
||||
"package_name": &alert.affected_package,
|
||||
"package_version": &alert.affected_version,
|
||||
};
|
||||
// Only insert if not already exists (upsert with $setOnInsert)
|
||||
let severity = parse_severity(alert.severity.as_deref(), alert.cvss_score);
|
||||
let mut notification = CveNotification::new(
|
||||
alert.cve_id.clone(),
|
||||
repo_id.clone(),
|
||||
repo_name.clone(),
|
||||
alert.affected_package.clone(),
|
||||
alert.affected_version.clone(),
|
||||
severity,
|
||||
);
|
||||
notification.cvss_score = alert.cvss_score;
|
||||
notification.summary = alert.summary.clone();
|
||||
notification.url = Some(format!("https://osv.dev/vulnerability/{}", alert.cve_id));
|
||||
|
||||
let update = doc! {
|
||||
"$setOnInsert": mongodb::bson::to_bson(¬ification).unwrap_or_default()
|
||||
};
|
||||
match db
|
||||
.cve_notifications()
|
||||
.update_one(filter, update)
|
||||
.upsert(true)
|
||||
.await
|
||||
{
|
||||
Ok(result) if result.upserted_id.is_some() => {
|
||||
new_notifications += 1;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("CVE monitor: failed to create notification: {e}");
|
||||
}
|
||||
_ => {} // Already exists
|
||||
}
|
||||
// Notifications for new CVEs, none for one a VEX statement settles.
|
||||
if let Err(e) =
|
||||
crate::pipeline::vex_lifecycle::attach_stored_vex(&db, &repo_id, &mut alerts).await
|
||||
{
|
||||
tracing::warn!("CVE monitor: failed to read the VEX statements of {repo_name}: {e}");
|
||||
continue;
|
||||
}
|
||||
new_notifications +=
|
||||
crate::pipeline::cve_notify::notify_new_cves(&db, &repo_id, &repo_name, &alerts).await;
|
||||
}
|
||||
|
||||
if new_notifications > 0 {
|
||||
|
||||
@@ -5,7 +5,11 @@ use compliance_core::guarded_net::guarded_client_builder;
|
||||
use compliance_core::models::{TrackerIssue, TrackerType};
|
||||
use compliance_core::traits::issue_tracker::{IssueTracker, ReviewComment};
|
||||
use compliance_core::NetGuard;
|
||||
use reqwest::StatusCode;
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use crate::trackers::gitea_limit;
|
||||
|
||||
pub struct GiteaTracker {
|
||||
base_url: String,
|
||||
@@ -42,6 +46,104 @@ impl GiteaTracker {
|
||||
format!("token {}", self.token.expose_secret())
|
||||
}
|
||||
|
||||
/// Send `request` with the bot token once the instance has a free slot
|
||||
/// (see [`gitea_limit`]), and read the whole answer before giving the slot
|
||||
/// back: Gitea is still working while it streams the body.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`CoreError::IssueTracker`] naming `what` if Gitea cannot be reached.
|
||||
/// An error status is returned as the status, not as an error.
|
||||
async fn send_raw(
|
||||
&self,
|
||||
what: &str,
|
||||
request: reqwest::RequestBuilder,
|
||||
) -> Result<(StatusCode, String), CoreError> {
|
||||
let _permit = gitea_limit::acquire(&self.base_url)
|
||||
.await
|
||||
.map_err(|e| CoreError::IssueTracker(format!("Gitea {what}: {e}")))?;
|
||||
let resp = request
|
||||
.header("Authorization", self.auth())
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| CoreError::IssueTracker(format!("Gitea {what} failed: {e}")))?;
|
||||
let status = resp.status();
|
||||
let text = resp
|
||||
.text()
|
||||
.await
|
||||
.map_err(|e| CoreError::IssueTracker(format!("Gitea {what} failed: {e}")))?;
|
||||
Ok((status, text))
|
||||
}
|
||||
|
||||
/// [`Self::send_raw`], with an error status turned into an error.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`CoreError::IssueTracker`] if Gitea cannot be reached or answers with
|
||||
/// an error status.
|
||||
async fn send(
|
||||
&self,
|
||||
what: &str,
|
||||
request: reqwest::RequestBuilder,
|
||||
) -> Result<String, CoreError> {
|
||||
let (status, text) = self.send_raw(what, request).await?;
|
||||
if status.is_success() {
|
||||
Ok(text)
|
||||
} else {
|
||||
Err(CoreError::IssueTracker(format!(
|
||||
"Gitea {what} returned {status}: {text}"
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::send`], with the answer parsed as JSON.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// As [`Self::send`], and [`CoreError::IssueTracker`] if the answer is not
|
||||
/// the expected JSON.
|
||||
async fn send_json<T: DeserializeOwned>(
|
||||
&self,
|
||||
what: &str,
|
||||
request: reqwest::RequestBuilder,
|
||||
) -> Result<T, CoreError> {
|
||||
let text = self.send(what, request).await?;
|
||||
serde_json::from_str(&text)
|
||||
.map_err(|e| CoreError::IssueTracker(format!("Failed to parse Gitea {what}: {e}")))
|
||||
}
|
||||
|
||||
/// Every page of a list endpoint, `path` being the URL without `page` and
|
||||
/// `limit`. Only an empty page ends the list: an instance may cap the page
|
||||
/// size below ours (`[api] MAX_RESPONSE_ITEMS`).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`CoreError::IssueTracker`] if a page cannot be fetched or parsed, or
|
||||
/// the list has more than `max_pages` pages (a partial list would let a
|
||||
/// caller take a missing entry for an absent one).
|
||||
async fn list_all<T: DeserializeOwned>(
|
||||
&self,
|
||||
what: &str,
|
||||
path: &str,
|
||||
max_pages: usize,
|
||||
) -> Result<Vec<T>, CoreError> {
|
||||
let separator = if path.contains('?') { '&' } else { '?' };
|
||||
let mut all = Vec::new();
|
||||
for page in 1..=max_pages {
|
||||
let url = self.api_url(&format!(
|
||||
"{path}{separator}page={page}&limit={LIST_PAGE_SIZE}"
|
||||
));
|
||||
let batch: Vec<T> = self.send_json(what, self.http.get(&url)).await?;
|
||||
if batch.is_empty() {
|
||||
return Ok(all);
|
||||
}
|
||||
all.extend(batch);
|
||||
}
|
||||
Err(CoreError::IssueTracker(format!(
|
||||
"Gitea {what}: more than {max_pages} pages"
|
||||
)))
|
||||
}
|
||||
|
||||
/// Every label of a repository, all pages.
|
||||
///
|
||||
/// # Errors
|
||||
@@ -49,35 +151,29 @@ impl GiteaTracker {
|
||||
/// [`CoreError::IssueTracker`] if Gitea cannot be asked or answers with an
|
||||
/// error.
|
||||
pub async fn list_labels(&self, owner: &str, repo: &str) -> Result<Vec<GiteaLabel>, CoreError> {
|
||||
let mut labels = Vec::new();
|
||||
for page in 1..=MAX_LABEL_PAGES {
|
||||
let url = self.api_url(&format!(
|
||||
"/repos/{owner}/{repo}/labels?page={page}&limit={LABEL_PAGE_SIZE}"
|
||||
));
|
||||
let resp = self
|
||||
.http
|
||||
.get(&url)
|
||||
.header("Authorization", self.auth())
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| CoreError::IssueTracker(format!("Gitea list labels failed: {e}")))?;
|
||||
if !resp.status().is_success() {
|
||||
let status = resp.status();
|
||||
return Err(CoreError::IssueTracker(format!(
|
||||
"Gitea list labels returned {status}"
|
||||
)));
|
||||
}
|
||||
let batch: Vec<GiteaLabel> = resp.json().await.map_err(|e| {
|
||||
CoreError::IssueTracker(format!("Failed to parse Gitea labels: {e}"))
|
||||
})?;
|
||||
// Only an empty page ends the list (the instance may cap the
|
||||
// page size below ours).
|
||||
if batch.is_empty() {
|
||||
break;
|
||||
}
|
||||
labels.extend(batch);
|
||||
}
|
||||
Ok(labels)
|
||||
self.list_all(
|
||||
"list labels",
|
||||
&format!("/repos/{owner}/{repo}/labels"),
|
||||
MAX_LABEL_PAGES,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Every issue of a repository, open and closed, all pages: one listing
|
||||
/// per sync, matched locally, instead of a search per finding.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`CoreError::IssueTracker`] if any page cannot be fetched (the caller
|
||||
/// must not take a failed listing for an empty one) or the repository has
|
||||
/// more than `MAX_ISSUE_PAGES` pages of issues.
|
||||
pub async fn list_issues(&self, owner: &str, repo: &str) -> Result<Vec<GiteaIssue>, CoreError> {
|
||||
self.list_all(
|
||||
"list issues",
|
||||
&format!("/repos/{owner}/{repo}/issues?type=issues&state=all"),
|
||||
MAX_ISSUE_PAGES,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Make sure the repository has every label in `wanted`, creating the
|
||||
@@ -99,29 +195,16 @@ impl GiteaTracker {
|
||||
existing.iter().map(|l| (l.name.clone(), l.id)).collect();
|
||||
for spec in missing_labels(&existing, wanted) {
|
||||
let url = self.api_url(&format!("/repos/{owner}/{repo}/labels"));
|
||||
let resp = self
|
||||
.http
|
||||
.post(&url)
|
||||
.header("Authorization", self.auth())
|
||||
.json(&serde_json::json!({
|
||||
"name": spec.name,
|
||||
"color": spec.color,
|
||||
"description": spec.description,
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| CoreError::IssueTracker(format!("Gitea create label failed: {e}")))?;
|
||||
if !resp.status().is_success() {
|
||||
let status = resp.status();
|
||||
return Err(CoreError::IssueTracker(format!(
|
||||
"Gitea create label '{}' returned {status}",
|
||||
spec.name
|
||||
)));
|
||||
}
|
||||
let label: GiteaLabel = resp.json().await.map_err(|e| {
|
||||
CoreError::IssueTracker(format!("Failed to parse Gitea label: {e}"))
|
||||
})?;
|
||||
let request = self.http.post(&url).json(&serde_json::json!({
|
||||
"name": spec.name,
|
||||
"color": spec.color,
|
||||
"description": spec.description,
|
||||
}));
|
||||
let label: GiteaLabel = self
|
||||
.send_json(&format!("create label '{}'", spec.name), request)
|
||||
.await?;
|
||||
ids.insert(label.name, label.id);
|
||||
tokio::time::sleep(gitea_limit::CREATE_PAUSE).await;
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
@@ -141,21 +224,14 @@ impl GiteaTracker {
|
||||
let url = self.api_url(&format!(
|
||||
"/repos/{owner}/{repo}/issues/{external_id}/labels"
|
||||
));
|
||||
let resp = self
|
||||
.http
|
||||
.post(&url)
|
||||
.header("Authorization", self.auth())
|
||||
.json(&serde_json::json!({ "labels": label_ids }))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| CoreError::IssueTracker(format!("Gitea add labels failed: {e}")))?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(CoreError::IssueTracker(format!(
|
||||
"Gitea add labels returned {}",
|
||||
resp.status()
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
self.send(
|
||||
"add labels",
|
||||
self.http
|
||||
.post(&url)
|
||||
.json(&serde_json::json!({ "labels": label_ids })),
|
||||
)
|
||||
.await
|
||||
.map(drop)
|
||||
}
|
||||
|
||||
/// Create an issue with the given labels attached by id (see
|
||||
@@ -181,6 +257,8 @@ impl GiteaTracker {
|
||||
.await
|
||||
}
|
||||
|
||||
/// Create an issue from `payload`, then pause for
|
||||
/// [`gitea_limit::CREATE_PAUSE`] (after giving the request slot back).
|
||||
async fn post_issue(
|
||||
&self,
|
||||
owner: &str,
|
||||
@@ -189,28 +267,10 @@ impl GiteaTracker {
|
||||
payload: serde_json::Value,
|
||||
) -> Result<TrackerIssue, CoreError> {
|
||||
let url = self.api_url(&format!("/repos/{owner}/{repo}/issues"));
|
||||
let resp = self
|
||||
.http
|
||||
.post(&url)
|
||||
.header("Authorization", self.auth())
|
||||
.json(&payload)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| CoreError::IssueTracker(format!("Gitea create issue failed: {e}")))?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
let status = resp.status();
|
||||
let text = resp.text().await.unwrap_or_default();
|
||||
return Err(CoreError::IssueTracker(format!(
|
||||
"Gitea returned {status}: {text}"
|
||||
)));
|
||||
}
|
||||
|
||||
let issue: serde_json::Value = resp
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| CoreError::IssueTracker(format!("Failed to parse Gitea response: {e}")))?;
|
||||
|
||||
let issue: serde_json::Value = self
|
||||
.send_json("create issue", self.http.post(&url).json(&payload))
|
||||
.await?;
|
||||
tokio::time::sleep(gitea_limit::CREATE_PAUSE).await;
|
||||
Ok(TrackerIssue::new(
|
||||
String::new(),
|
||||
TrackerType::Gitea,
|
||||
@@ -221,10 +281,27 @@ impl GiteaTracker {
|
||||
}
|
||||
}
|
||||
|
||||
/// Labels per page when listing a repository's labels.
|
||||
const LABEL_PAGE_SIZE: usize = 50;
|
||||
/// Entries per page when listing labels or issues.
|
||||
const LIST_PAGE_SIZE: usize = 50;
|
||||
/// Upper bound on label pages, so a misbehaving server cannot loop us.
|
||||
const MAX_LABEL_PAGES: usize = 20;
|
||||
/// Upper bound on issue pages (10 000 issues).
|
||||
const MAX_ISSUE_PAGES: usize = 200;
|
||||
|
||||
/// An issue as Gitea lists it, with what an issue is matched by.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
|
||||
pub struct GiteaIssue {
|
||||
pub number: i64,
|
||||
pub title: String,
|
||||
/// Gitea sends `null` or leaves it out for an issue without text.
|
||||
#[serde(default)]
|
||||
pub body: Option<String>,
|
||||
#[serde(default)]
|
||||
pub html_url: String,
|
||||
/// `open` or `closed`.
|
||||
#[serde(default)]
|
||||
pub state: String,
|
||||
}
|
||||
|
||||
/// A repository label as Gitea returns it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
|
||||
@@ -355,33 +432,18 @@ impl IssueTracker for GiteaTracker {
|
||||
status: &str,
|
||||
) -> Result<(), CoreError> {
|
||||
let url = self.api_url(&format!("/repos/{owner}/{repo}/issues/{external_id}"));
|
||||
|
||||
let state = match status {
|
||||
"closed" | "resolved" => "closed",
|
||||
_ => "open",
|
||||
};
|
||||
|
||||
let resp = self
|
||||
.http
|
||||
.patch(&url)
|
||||
.header(
|
||||
"Authorization",
|
||||
format!("token {}", self.token.expose_secret()),
|
||||
)
|
||||
.json(&serde_json::json!({ "state": state }))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| CoreError::IssueTracker(format!("Gitea update issue failed: {e}")))?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
let status = resp.status();
|
||||
let text = resp.text().await.unwrap_or_default();
|
||||
return Err(CoreError::IssueTracker(format!(
|
||||
"Gitea update issue returned {status}: {text}"
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
self.send(
|
||||
"update issue",
|
||||
self.http
|
||||
.patch(&url)
|
||||
.json(&serde_json::json!({ "state": state })),
|
||||
)
|
||||
.await
|
||||
.map(drop)
|
||||
}
|
||||
|
||||
async fn add_comment(
|
||||
@@ -394,28 +456,14 @@ impl IssueTracker for GiteaTracker {
|
||||
let url = self.api_url(&format!(
|
||||
"/repos/{owner}/{repo}/issues/{external_id}/comments"
|
||||
));
|
||||
|
||||
let resp = self
|
||||
.http
|
||||
.post(&url)
|
||||
.header(
|
||||
"Authorization",
|
||||
format!("token {}", self.token.expose_secret()),
|
||||
)
|
||||
.json(&serde_json::json!({ "body": body }))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| CoreError::IssueTracker(format!("Gitea add comment failed: {e}")))?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
let status = resp.status();
|
||||
let text = resp.text().await.unwrap_or_default();
|
||||
return Err(CoreError::IssueTracker(format!(
|
||||
"Gitea add comment returned {status}: {text}"
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
self.send(
|
||||
"add comment",
|
||||
self.http
|
||||
.post(&url)
|
||||
.json(&serde_json::json!({ "body": body })),
|
||||
)
|
||||
.await
|
||||
.map(drop)
|
||||
}
|
||||
|
||||
async fn create_pr_review(
|
||||
@@ -439,65 +487,40 @@ impl IssueTracker for GiteaTracker {
|
||||
})
|
||||
.collect();
|
||||
|
||||
let resp = self
|
||||
.http
|
||||
.post(&url)
|
||||
.header(
|
||||
"Authorization",
|
||||
format!("token {}", self.token.expose_secret()),
|
||||
let (status, text) = self
|
||||
.send_raw(
|
||||
"PR review",
|
||||
self.http.post(&url).json(&serde_json::json!({
|
||||
"body": body,
|
||||
"event": "COMMENT",
|
||||
"comments": review_comments,
|
||||
})),
|
||||
)
|
||||
.json(&serde_json::json!({
|
||||
"body": body,
|
||||
"event": "COMMENT",
|
||||
"comments": review_comments,
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| CoreError::IssueTracker(format!("Gitea PR review failed: {e}")))?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
let status = resp.status();
|
||||
let text = resp.text().await.unwrap_or_default();
|
||||
|
||||
// If inline comments caused the failure, retry with just the summary body
|
||||
if !comments.is_empty() {
|
||||
tracing::warn!(
|
||||
"Gitea PR review with inline comments failed ({status}): {text}, retrying as plain comment"
|
||||
);
|
||||
let fallback_url = self.api_url(&format!(
|
||||
"/repos/{owner}/{repo}/issues/{pr_number}/comments"
|
||||
));
|
||||
let fallback_resp = self
|
||||
.http
|
||||
.post(&fallback_url)
|
||||
.header(
|
||||
"Authorization",
|
||||
format!("token {}", self.token.expose_secret()),
|
||||
)
|
||||
.json(&serde_json::json!({ "body": body }))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
CoreError::IssueTracker(format!("Gitea PR comment fallback failed: {e}"))
|
||||
})?;
|
||||
|
||||
if !fallback_resp.status().is_success() {
|
||||
let fb_status = fallback_resp.status();
|
||||
let fb_text = fallback_resp.text().await.unwrap_or_default();
|
||||
return Err(CoreError::IssueTracker(format!(
|
||||
"Gitea PR comment fallback returned {fb_status}: {fb_text}"
|
||||
)));
|
||||
}
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
.await?;
|
||||
if status.is_success() {
|
||||
return Ok(());
|
||||
}
|
||||
if comments.is_empty() {
|
||||
return Err(CoreError::IssueTracker(format!(
|
||||
"Gitea PR review returned {status}: {text}"
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
// If inline comments caused the failure, retry with just the summary body
|
||||
tracing::warn!(
|
||||
"Gitea PR review with inline comments failed ({status}): {text}, retrying as plain comment"
|
||||
);
|
||||
let fallback_url = self.api_url(&format!(
|
||||
"/repos/{owner}/{repo}/issues/{pr_number}/comments"
|
||||
));
|
||||
self.send(
|
||||
"PR comment fallback",
|
||||
self.http
|
||||
.post(&fallback_url)
|
||||
.json(&serde_json::json!({ "body": body })),
|
||||
)
|
||||
.await
|
||||
.map(drop)
|
||||
}
|
||||
|
||||
async fn find_existing_issue(
|
||||
@@ -506,33 +529,23 @@ impl IssueTracker for GiteaTracker {
|
||||
repo: &str,
|
||||
fingerprint: &str,
|
||||
) -> Result<Option<TrackerIssue>, CoreError> {
|
||||
let url = self.api_url(&format!(
|
||||
"/repos/{owner}/{repo}/issues?type=issues&state=all&q={fingerprint}"
|
||||
));
|
||||
|
||||
let resp = self
|
||||
.http
|
||||
.get(&url)
|
||||
.header(
|
||||
"Authorization",
|
||||
format!("token {}", self.token.expose_secret()),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| CoreError::IssueTracker(format!("Gitea search failed: {e}")))?;
|
||||
|
||||
let issues: Vec<serde_json::Value> = resp.json().await.unwrap_or_default();
|
||||
if let Some(issue) = issues.first() {
|
||||
Ok(Some(TrackerIssue::new(
|
||||
// The finding issues are matched against `list_issues` instead; this
|
||||
// search stays for the trait.
|
||||
let url = self.api_url(&format!("/repos/{owner}/{repo}/issues"));
|
||||
let request =
|
||||
self.http
|
||||
.get(&url)
|
||||
.query(&[("type", "issues"), ("state", "all"), ("q", fingerprint)]);
|
||||
let issues: Vec<GiteaIssue> = self.send_json("search issues", request).await?;
|
||||
Ok(issues.into_iter().next().map(|issue| {
|
||||
TrackerIssue::new(
|
||||
String::new(),
|
||||
TrackerType::Gitea,
|
||||
issue["number"].to_string(),
|
||||
issue["html_url"].as_str().unwrap_or("").to_string(),
|
||||
issue["title"].as_str().unwrap_or("").to_string(),
|
||||
)))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
issue.number.to_string(),
|
||||
issue.html_url,
|
||||
issue.title,
|
||||
)
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -597,7 +610,14 @@ mod tests {
|
||||
async fn list(
|
||||
State(labels): State<Labels>,
|
||||
Path((_o, _r)): Path<(String, String)>,
|
||||
axum::extract::Query(page): axum::extract::Query<
|
||||
std::collections::HashMap<String, String>,
|
||||
>,
|
||||
) -> Json<serde_json::Value> {
|
||||
// One page of labels: a later page is empty, as Gitea ends a list.
|
||||
if page.get("page").map(String::as_str) != Some("1") {
|
||||
return Json(serde_json::json!([]));
|
||||
}
|
||||
let all = labels.lock().unwrap().clone();
|
||||
Json(serde_json::json!(all
|
||||
.iter()
|
||||
@@ -649,4 +669,130 @@ mod tests {
|
||||
assert_eq!(again, ids);
|
||||
assert_eq!(labels.lock().unwrap().len(), 8);
|
||||
}
|
||||
|
||||
/// The query strings a fake Gitea saw.
|
||||
type Seen = Arc<Mutex<Vec<String>>>;
|
||||
|
||||
/// A fake Gitea whose repository has `total` issues, served in pages of
|
||||
/// at most `cap` (an instance may cap the page size below ours).
|
||||
async fn fake_issues(total: i64, cap: i64, seen: Seen) -> String {
|
||||
async fn list(
|
||||
State((total, cap, seen)): State<(i64, i64, Seen)>,
|
||||
Path((_o, _r)): Path<(String, String)>,
|
||||
axum::extract::RawQuery(query): axum::extract::RawQuery,
|
||||
axum::extract::Query(params): axum::extract::Query<HashMap<String, String>>,
|
||||
) -> Json<serde_json::Value> {
|
||||
seen.lock().unwrap().push(query.unwrap_or_default());
|
||||
let page: i64 = params["page"].parse().unwrap();
|
||||
let limit: i64 = params["limit"].parse::<i64>().unwrap().min(cap);
|
||||
let first = (page - 1) * limit + 1;
|
||||
Json(serde_json::json!((first..=(first + limit - 1).min(total))
|
||||
.map(|n| serde_json::json!({
|
||||
"number": n,
|
||||
"title": format!("issue {n}"),
|
||||
"body": if n % 2 == 0 { serde_json::Value::Null } else { format!("body {n}").into() },
|
||||
"html_url": format!("https://gitea.invalid/o/r/issues/{n}"),
|
||||
}))
|
||||
.collect::<Vec<_>>()))
|
||||
}
|
||||
let app = Router::new()
|
||||
.route("/api/v1/repos/{owner}/{repo}/issues", get(list))
|
||||
.with_state((total, cap, seen));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
format!("http://{addr}")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_issues_reads_every_page_of_open_and_closed_issues() {
|
||||
let seen: Seen = Arc::default();
|
||||
let base = fake_issues(103, 50, seen.clone()).await;
|
||||
let tracker =
|
||||
GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap();
|
||||
|
||||
let issues = tracker.list_issues("kunde", "fw").await.unwrap();
|
||||
|
||||
assert_eq!(issues.len(), 103);
|
||||
assert_eq!(issues[0].body.as_deref(), Some("body 1"));
|
||||
assert_eq!(issues[1].body, None);
|
||||
assert_eq!(issues[102].number, 103);
|
||||
let seen = seen.lock().unwrap();
|
||||
assert_eq!(seen.len(), 4, "three pages and the empty one: {seen:?}");
|
||||
assert_eq!(seen[0], "type=issues&state=all&page=1&limit=50");
|
||||
assert_eq!(seen[3], "type=issues&state=all&page=4&limit=50");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_issues_does_not_stop_at_a_capped_page() {
|
||||
let seen: Seen = Arc::default();
|
||||
let base = fake_issues(45, 20, seen.clone()).await;
|
||||
let tracker =
|
||||
GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap();
|
||||
assert_eq!(tracker.list_issues("kunde", "fw").await.unwrap().len(), 45);
|
||||
assert_eq!(seen.lock().unwrap().len(), 4);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_listing_is_an_error_not_an_empty_list() {
|
||||
let app = Router::new().route(
|
||||
"/api/v1/repos/{owner}/{repo}/issues",
|
||||
get(|| async { axum::http::StatusCode::INTERNAL_SERVER_ERROR }),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
let tracker = GiteaTracker::new(
|
||||
format!("http://{addr}"),
|
||||
SecretString::from("t"),
|
||||
NetGuard::allow_private(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(tracker.list_issues("kunde", "fw").await.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn never_more_than_two_requests_in_flight_per_instance() {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
/// Requests being served now, and the most at any one time.
|
||||
type Gauge = Arc<(AtomicUsize, AtomicUsize)>;
|
||||
async fn slow(State(gauge): State<Gauge>) -> Json<serde_json::Value> {
|
||||
let now = gauge.0.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
gauge.1.fetch_max(now, Ordering::SeqCst);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(40)).await;
|
||||
gauge.0.fetch_sub(1, Ordering::SeqCst);
|
||||
Json(serde_json::json!([]))
|
||||
}
|
||||
let gauge: Gauge = Arc::default();
|
||||
let app = Router::new()
|
||||
.route("/api/v1/repos/{owner}/{repo}/labels", get(slow))
|
||||
.with_state(gauge.clone());
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
let base = format!("http://{addr}");
|
||||
// Two trackers of the same instance, as two scans would build them.
|
||||
let trackers: Vec<GiteaTracker> = (0..2)
|
||||
.map(|_| {
|
||||
GiteaTracker::new(
|
||||
base.clone(),
|
||||
SecretString::from("t"),
|
||||
NetGuard::allow_private(),
|
||||
)
|
||||
.unwrap()
|
||||
})
|
||||
.collect();
|
||||
|
||||
let calls = (0..10).map(|i| trackers[i % 2].list_labels("kunde", "fw"));
|
||||
let results = futures_util::future::join_all(calls).await;
|
||||
|
||||
assert!(results.iter().all(Result::is_ok));
|
||||
let most = gauge.1.load(Ordering::SeqCst);
|
||||
assert_eq!(
|
||||
most,
|
||||
gitea_limit::MAX_IN_FLIGHT,
|
||||
"at most two, and two did run at once"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
//! At most [`MAX_IN_FLIGHT`] requests in flight per Gitea instance.
|
||||
//!
|
||||
//! A managed Gitea is often small (one with 1 GiB was OOM-killed by a burst
|
||||
//! of issue searches, K-00001). Every request the agent makes to a Gitea, from
|
||||
//! the issue tracker and from the managed git source alike, first takes a
|
||||
//! permit of its instance here, so all scans of one instance in this process
|
||||
//! share the same two slots.
|
||||
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use std::time::Duration;
|
||||
|
||||
use dashmap::DashMap;
|
||||
use tokio::sync::{AcquireError, OwnedSemaphorePermit, Semaphore};
|
||||
|
||||
/// Requests one Gitea instance gets from this process at the same time.
|
||||
pub const MAX_IN_FLIGHT: usize = 2;
|
||||
|
||||
/// The pause after creating something (an issue, a label), so a sync that
|
||||
/// opens many issues does not hit the instance back to back.
|
||||
pub const CREATE_PAUSE: Duration = Duration::from_millis(250);
|
||||
|
||||
/// One semaphore per instance, keyed by [`instance_key`]. A `LazyLock` is
|
||||
/// initialised on first use, like a module-level singleton in Python.
|
||||
static LIMITERS: LazyLock<DashMap<String, Arc<Semaphore>>> = LazyLock::new(DashMap::new);
|
||||
|
||||
/// The instance a base URL points at: `host:port`, lower case, so
|
||||
/// `https://Git.example.com` and `https://git.example.com:443/sub` share one
|
||||
/// limit while two instances on one host with different ports do not. A URL
|
||||
/// that cannot be parsed is its own key.
|
||||
pub fn instance_key(base_url: &str) -> String {
|
||||
match reqwest::Url::parse(base_url) {
|
||||
Ok(url) => match url.host_str() {
|
||||
Some(host) => format!(
|
||||
"{}:{}",
|
||||
host.to_ascii_lowercase(),
|
||||
url.port_or_known_default().unwrap_or_default()
|
||||
),
|
||||
None => base_url.to_ascii_lowercase(),
|
||||
},
|
||||
Err(_) => base_url.trim_end_matches('/').to_ascii_lowercase(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait for a request slot at the instance of `base_url`. Hold the permit
|
||||
/// until the response body has been read; dropping it frees the slot.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`AcquireError`] only if the semaphore was closed, which this module never
|
||||
/// does.
|
||||
pub async fn acquire(base_url: &str) -> Result<OwnedSemaphorePermit, AcquireError> {
|
||||
// Clone the `Arc` out of the map first: the map's entry guard must not be
|
||||
// held across the `.await` below.
|
||||
let semaphore = LIMITERS
|
||||
.entry(instance_key(base_url))
|
||||
.or_insert_with(|| Arc::new(Semaphore::new(MAX_IN_FLIGHT)))
|
||||
.clone();
|
||||
semaphore.acquire_owned().await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn one_key_per_host_and_port() {
|
||||
assert_eq!(
|
||||
instance_key("https://Git.Example.com"),
|
||||
"git.example.com:443"
|
||||
);
|
||||
assert_eq!(
|
||||
instance_key("https://git.example.com:443/sub/"),
|
||||
"git.example.com:443"
|
||||
);
|
||||
assert_eq!(instance_key("http://127.0.0.1:3000"), "127.0.0.1:3000");
|
||||
assert_ne!(
|
||||
instance_key("http://127.0.0.1:3000"),
|
||||
instance_key("http://127.0.0.1:3001")
|
||||
);
|
||||
assert_eq!(instance_key("not a url/"), "not a url");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_third_permit_waits_for_one_of_the_first_two() {
|
||||
let base = "https://limit-test.invalid";
|
||||
let first = acquire(base).await.unwrap();
|
||||
let _second = acquire(base).await.unwrap();
|
||||
let third = tokio::time::timeout(Duration::from_millis(50), acquire(base)).await;
|
||||
assert!(third.is_err(), "a third request must wait");
|
||||
drop(first);
|
||||
let third = tokio::time::timeout(Duration::from_millis(50), acquire(base)).await;
|
||||
assert!(third.is_ok(), "a freed slot is taken");
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod gitea;
|
||||
pub mod gitea_limit;
|
||||
pub mod github;
|
||||
pub mod gitlab;
|
||||
pub mod jira;
|
||||
@@ -0,0 +1,101 @@
|
||||
//! Recording webhook deliveries for the target page (see
|
||||
//! [`compliance_core::models::webhook_delivery`]).
|
||||
//!
|
||||
//! Deliveries live in a capped per-tenant collection: one insert per delivery,
|
||||
//! Mongo drops the oldest, and a delivery refused before its target exists
|
||||
//! needs no target to be stored. The target page finds its deliveries by
|
||||
//! target id or, for a managed repository, by the repository.
|
||||
|
||||
use compliance_core::models::{DeliveryResult, SourceRepo, WebhookDelivery};
|
||||
use mongodb::bson::{doc, Document};
|
||||
|
||||
use crate::agent::ComplianceAgent;
|
||||
|
||||
/// Store `delivery` in the tenant's database. Never fails the webhook: an
|
||||
/// error is logged and the delivery is lost.
|
||||
pub async fn record(agent: &ComplianceAgent, tenant_id: &str, delivery: &WebhookDelivery) {
|
||||
let db = match agent.db_pool.for_tenant_id(tenant_id).await {
|
||||
Ok(db) => db,
|
||||
Err(e) => {
|
||||
tracing::warn!(tenant_id, "webhook delivery not recorded: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Err(e) = db.webhook_deliveries().insert_one(delivery).await {
|
||||
tracing::warn!(tenant_id, "webhook delivery not recorded: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// [`record`] in the background, so the sender's answer does not wait for it.
|
||||
pub fn spawn_record(agent: &ComplianceAgent, tenant_id: &str, delivery: WebhookDelivery) {
|
||||
let (agent, tenant_id) = (agent.clone(), tenant_id.to_string());
|
||||
tokio::spawn(async move { record(&agent, &tenant_id, &delivery).await });
|
||||
}
|
||||
|
||||
/// A per-target webhook (`receiver`) queued work (`detail`) for `target_id`.
|
||||
/// The scan or review itself shows in the scan runs; this shows that the
|
||||
/// delivery arrived and was accepted.
|
||||
pub fn queued(receiver: &str, event: &str, target_id: &str, detail: &str) -> WebhookDelivery {
|
||||
let mut delivery = WebhookDelivery::new(receiver, event, DeliveryResult::Handled, detail);
|
||||
delivery.target_id = Some(target_id.to_string());
|
||||
delivery
|
||||
}
|
||||
|
||||
/// The filter for the deliveries of target `target_id`: its own, and for a
|
||||
/// managed target also those of its repository (a delivery refused before the
|
||||
/// target was created carries only the repository).
|
||||
pub fn target_filter(target_id: &str, source_repo: Option<&SourceRepo>) -> Document {
|
||||
let mut any = vec![doc! { "target_id": target_id }];
|
||||
if let Some(repo) = source_repo {
|
||||
any.push(doc! {
|
||||
"source_repo.base_url": &repo.base_url,
|
||||
"source_repo.repo_id": repo.repo_id,
|
||||
});
|
||||
}
|
||||
doc! { "$or": any }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_queued_delivery_is_handled_for_its_target() {
|
||||
let d = queued("github", "push", "abc", "scan queued");
|
||||
assert_eq!(d.result, DeliveryResult::Handled);
|
||||
assert_eq!(d.target_id.as_deref(), Some("abc"));
|
||||
assert_eq!((d.source.as_str(), d.event.as_str()), ("github", "push"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_target_matches_by_id_only() {
|
||||
let f = target_filter("abc", None);
|
||||
let any = f.get_array("$or").unwrap();
|
||||
assert_eq!(any.len(), 1);
|
||||
assert_eq!(
|
||||
any[0].as_document().unwrap().get_str("target_id").unwrap(),
|
||||
"abc"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_managed_target_also_matches_its_repository() {
|
||||
let repo = SourceRepo {
|
||||
base_url: "https://git.example".into(),
|
||||
repo_id: 42,
|
||||
full_name: "kunde/fw".into(),
|
||||
};
|
||||
let f = target_filter("abc", Some(&repo));
|
||||
let any = f.get_array("$or").unwrap();
|
||||
assert_eq!(any.len(), 2);
|
||||
let by_repo = any[1].as_document().unwrap();
|
||||
assert_eq!(
|
||||
by_repo.get_str("source_repo.base_url").unwrap(),
|
||||
"https://git.example"
|
||||
);
|
||||
assert_eq!(by_repo.get_i64("source_repo.repo_id").unwrap(), 42);
|
||||
// the name changes on a rename; the id does not
|
||||
assert!(by_repo.get("source_repo.full_name").is_none());
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,11 @@ pub async fn handle_gitea_webhook(
|
||||
|
||||
match event {
|
||||
"push" => {
|
||||
super::deliveries::spawn_record(
|
||||
&agent,
|
||||
&tenant_id,
|
||||
super::deliveries::queued("gitea", "push", &repo_id, "scan queued"),
|
||||
);
|
||||
let agent_clone = (*agent).clone();
|
||||
let repo_id = repo_id.clone();
|
||||
let tenant_id = tenant_id.clone();
|
||||
@@ -117,6 +122,16 @@ async fn handle_pull_request(
|
||||
return StatusCode::BAD_REQUEST;
|
||||
}
|
||||
|
||||
super::deliveries::spawn_record(
|
||||
&agent,
|
||||
tenant_id,
|
||||
super::deliveries::queued(
|
||||
"gitea",
|
||||
"pull_request",
|
||||
repo_id,
|
||||
"pull request review queued",
|
||||
),
|
||||
);
|
||||
let repo_id = repo_id.to_string();
|
||||
let tenant_id = tenant_id.to_string();
|
||||
let head_sha = head_sha.to_string();
|
||||
|
||||
@@ -4,23 +4,59 @@
|
||||
//! Authenticated by `X-Gitea-Signature`: HMAC-SHA256 of the body under the
|
||||
//! source's webhook secret. Until that is verified nothing is created: the
|
||||
//! source is read through a handle that cannot conjure a tenant database.
|
||||
//!
|
||||
//! A verified delivery that asks for work is answered `202 Accepted` at once;
|
||||
//! the entitlement check, the target and the scan follow in the background,
|
||||
//! so a slow registry or Keycloak never runs into Gitea's delivery timeout.
|
||||
//! What became of it (handled, refused, failed) is recorded for the target
|
||||
//! page, since Gitea's delivery log only ever sees the `202`.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use axum::body::Bytes;
|
||||
use axum::extract::{Extension, Path};
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use compliance_core::models::{DeliveryResult, GitSource, SourceRepo, WebhookDelivery};
|
||||
|
||||
use super::deliveries;
|
||||
use crate::agent::ComplianceAgent;
|
||||
use crate::git_source::{self, events};
|
||||
use crate::git_source::{self, events, Outcome};
|
||||
|
||||
/// This receiver's name in the delivery records.
|
||||
const SOURCE: &str = "gitea-source";
|
||||
|
||||
/// Answer one delivery and log how long the answer took.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `202` when work was handed to the background, `200` when the event needs
|
||||
/// none, `401`/`404`/`400`/`500` when the delivery is refused or unreadable.
|
||||
pub async fn handle_gitea_source_webhook(
|
||||
Extension(agent): Extension<Arc<ComplianceAgent>>,
|
||||
Path(tenant_id): Path<String>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> StatusCode {
|
||||
let probe = agent.db_pool.for_existing_tenant_id(&tenant_id);
|
||||
let started = Instant::now();
|
||||
let status = answer(agent, &tenant_id, &headers, &body).await;
|
||||
tracing::info!(
|
||||
tenant_id,
|
||||
status = status.as_u16(),
|
||||
elapsed_ms = started.elapsed().as_millis() as u64,
|
||||
"Gitea source webhook answered"
|
||||
);
|
||||
status
|
||||
}
|
||||
|
||||
/// Verify and route a delivery; hand any work to [`process`] in the background.
|
||||
async fn answer(
|
||||
agent: Arc<ComplianceAgent>,
|
||||
tenant_id: &str,
|
||||
headers: &HeaderMap,
|
||||
body: &[u8],
|
||||
) -> StatusCode {
|
||||
let probe = agent.db_pool.for_existing_tenant_id(tenant_id);
|
||||
let source = match git_source::load_source(&probe).await {
|
||||
Ok(Some(source)) if source.enabled => source,
|
||||
Ok(_) => {
|
||||
@@ -43,14 +79,14 @@ pub async fn handle_gitea_source_webhook(
|
||||
);
|
||||
return StatusCode::UNAUTHORIZED;
|
||||
};
|
||||
let signature = header(&headers, "x-gitea-signature");
|
||||
if !super::gitea::verify_signature(&secret, &body, signature) {
|
||||
let signature = header(headers, "x-gitea-signature");
|
||||
if !super::gitea::verify_signature(&secret, body, signature) {
|
||||
tracing::warn!("Gitea source webhook: invalid signature for tenant '{tenant_id}'");
|
||||
return StatusCode::UNAUTHORIZED;
|
||||
}
|
||||
|
||||
let event = header(&headers, "x-gitea-event");
|
||||
let payload: serde_json::Value = match serde_json::from_slice(&body) {
|
||||
let event = header(headers, "x-gitea-event");
|
||||
let payload: serde_json::Value = match serde_json::from_slice(body) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
tracing::warn!("Gitea source webhook: invalid JSON: {e}");
|
||||
@@ -63,29 +99,113 @@ pub async fn handle_gitea_source_webhook(
|
||||
return StatusCode::OK;
|
||||
}
|
||||
|
||||
// Automated work follows the same entitlement and ladder rules as the
|
||||
// scheduler. Refused visibly, so the delivery log in Gitea shows it.
|
||||
if let Err(why) = git_source::automation_allowed(&agent, &tenant_id).await {
|
||||
tracing::info!(tenant_id, "Gitea source webhook refused: {why}");
|
||||
return StatusCode::FORBIDDEN;
|
||||
}
|
||||
let db = match agent.db_pool.for_tenant_id(&tenant_id).await {
|
||||
Ok(db) => db,
|
||||
Err(e) => {
|
||||
tracing::error!("Gitea source webhook: tenant database: {e}");
|
||||
return StatusCode::INTERNAL_SERVER_ERROR;
|
||||
let tenant_id = tenant_id.to_string();
|
||||
let event = event.to_string();
|
||||
tokio::spawn(async move {
|
||||
let (received_at, started) = (chrono::Utc::now(), Instant::now());
|
||||
let repo = action.repo().map(|repo| SourceRepo {
|
||||
base_url: source.base_url.clone(),
|
||||
repo_id: repo.id,
|
||||
full_name: repo.full_name.clone(),
|
||||
});
|
||||
let result = process(&agent, &tenant_id, &source, action).await;
|
||||
let elapsed_ms = started.elapsed().as_millis() as u64;
|
||||
match &result {
|
||||
Ok(outcome) => tracing::info!(
|
||||
tenant_id,
|
||||
event,
|
||||
elapsed_ms,
|
||||
?outcome,
|
||||
"Gitea source webhook handled"
|
||||
),
|
||||
Err(why) => tracing::warn!(
|
||||
tenant_id,
|
||||
event,
|
||||
elapsed_ms,
|
||||
"Gitea source webhook not handled: {why}"
|
||||
),
|
||||
}
|
||||
let mut delivery = delivery_of(&event, &result);
|
||||
delivery.received_at = received_at;
|
||||
delivery.elapsed_ms = elapsed_ms;
|
||||
delivery.source_repo = repo;
|
||||
deliveries::record(&agent, &tenant_id, &delivery).await;
|
||||
});
|
||||
StatusCode::ACCEPTED
|
||||
}
|
||||
|
||||
/// Why a verified delivery did no work.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
enum NotHandled {
|
||||
/// Automation refused for the tenant: entitlement, read-only.
|
||||
Refused(String),
|
||||
/// The tenant database or the action failed.
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for NotHandled {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Refused(why) => write!(f, "refused: {why}"),
|
||||
Self::Failed(why) => write!(f, "{why}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The work a verified delivery asks for: entitlement, target, scan.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// What was done.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Why nothing was done: automation refused for the tenant (same entitlement
|
||||
/// and ladder rules as the scheduler), or the tenant database or the action
|
||||
/// failed.
|
||||
async fn process(
|
||||
agent: &ComplianceAgent,
|
||||
tenant_id: &str,
|
||||
source: &GitSource,
|
||||
action: events::SourceAction,
|
||||
) -> Result<Outcome, NotHandled> {
|
||||
git_source::automation_allowed(agent, tenant_id)
|
||||
.await
|
||||
.map_err(NotHandled::Refused)?;
|
||||
let db = agent
|
||||
.db_pool
|
||||
.for_tenant_id(tenant_id)
|
||||
.await
|
||||
.map_err(|e| NotHandled::Failed(format!("tenant database: {e}")))?;
|
||||
git_source::apply_action(agent, &db, tenant_id, source, action)
|
||||
.await
|
||||
.map_err(|e| NotHandled::Failed(e.to_string()))
|
||||
}
|
||||
|
||||
/// The record of a delivery of `event` that came to `result`; the target is
|
||||
/// set when the delivery created or found one.
|
||||
fn delivery_of(event: &str, result: &Result<Outcome, NotHandled>) -> WebhookDelivery {
|
||||
let (outcome, detail, target_id) = match result {
|
||||
Ok(Outcome::Ensured { target_id, scan }) => (
|
||||
DeliveryResult::Handled,
|
||||
if *scan {
|
||||
"scan queued"
|
||||
} else {
|
||||
"target ready, nothing to scan yet"
|
||||
},
|
||||
Some(target_id.clone()),
|
||||
),
|
||||
Ok(Outcome::Archived(true)) => (DeliveryResult::Handled, "target archived", None),
|
||||
Ok(Outcome::Archived(false)) => {
|
||||
(DeliveryResult::Handled, "no active target to archive", None)
|
||||
}
|
||||
Ok(Outcome::Ignored(why)) => (DeliveryResult::Handled, *why, None),
|
||||
Err(NotHandled::Refused(why)) => (DeliveryResult::Refused, why.as_str(), None),
|
||||
Err(NotHandled::Failed(why)) => (DeliveryResult::Failed, why.as_str(), None),
|
||||
};
|
||||
match git_source::apply_action(&agent, &db, &tenant_id, &source, action).await {
|
||||
Ok(outcome) => {
|
||||
tracing::info!(tenant_id, event, ?outcome, "Gitea source webhook handled");
|
||||
StatusCode::OK
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!(tenant_id, event, "Gitea source webhook failed: {e}");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
}
|
||||
let mut delivery = WebhookDelivery::new(SOURCE, event, outcome, detail);
|
||||
delivery.target_id = target_id;
|
||||
delivery
|
||||
}
|
||||
|
||||
fn header<'a>(headers: &'a HeaderMap, name: &str) -> &'a str {
|
||||
@@ -101,8 +221,59 @@ mod tests {
|
||||
use hmac::{Hmac, Mac};
|
||||
use sha2::Sha256;
|
||||
|
||||
use super::*;
|
||||
use crate::webhooks::gitea::verify_signature;
|
||||
|
||||
#[test]
|
||||
fn a_refusal_is_recorded_with_its_reason_and_no_target() {
|
||||
let d = delivery_of(
|
||||
"push",
|
||||
&Err(NotHandled::Refused("not entitled: no licence".into())),
|
||||
);
|
||||
assert_eq!(d.result, DeliveryResult::Refused);
|
||||
assert_eq!(d.detail, "not entitled: no licence");
|
||||
assert_eq!((d.source.as_str(), d.event.as_str()), (SOURCE, "push"));
|
||||
assert!(d.target_id.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failure_and_the_handled_outcomes_are_recorded() {
|
||||
let d = delivery_of("push", &Err(NotHandled::Failed("db down".into())));
|
||||
assert_eq!(
|
||||
(d.result, d.detail.as_str()),
|
||||
(DeliveryResult::Failed, "db down")
|
||||
);
|
||||
|
||||
let ensured = |scan| Outcome::Ensured {
|
||||
target_id: "t1".into(),
|
||||
scan,
|
||||
};
|
||||
let d = delivery_of("push", &Ok(ensured(true)));
|
||||
assert_eq!(
|
||||
(d.result, d.detail.as_str()),
|
||||
(DeliveryResult::Handled, "scan queued")
|
||||
);
|
||||
assert_eq!(d.target_id.as_deref(), Some("t1"));
|
||||
let d = delivery_of("repository", &Ok(ensured(false)));
|
||||
assert_eq!(d.detail, "target ready, nothing to scan yet");
|
||||
|
||||
let d = delivery_of("repository", &Ok(Outcome::Archived(true)));
|
||||
assert_eq!(
|
||||
(d.result, d.detail.as_str()),
|
||||
(DeliveryResult::Handled, "target archived")
|
||||
);
|
||||
assert!(d.target_id.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refusal_reads_as_one_in_the_log() {
|
||||
assert_eq!(
|
||||
NotHandled::Refused("read-only".into()).to_string(),
|
||||
"refused: read-only"
|
||||
);
|
||||
assert_eq!(NotHandled::Failed("db".into()).to_string(), "db");
|
||||
}
|
||||
|
||||
fn sign(secret: &str, body: &[u8]) -> String {
|
||||
let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).unwrap();
|
||||
mac.update(body);
|
||||
|
||||
@@ -69,6 +69,11 @@ pub async fn handle_github_webhook(
|
||||
|
||||
match event {
|
||||
"push" => {
|
||||
super::deliveries::spawn_record(
|
||||
&agent,
|
||||
&tenant_id,
|
||||
super::deliveries::queued("github", "push", &repo_id, "scan queued"),
|
||||
);
|
||||
let agent_clone = (*agent).clone();
|
||||
let repo_id = repo_id.clone();
|
||||
let tenant_id = tenant_id.clone();
|
||||
@@ -116,6 +121,16 @@ async fn handle_pull_request(
|
||||
return StatusCode::BAD_REQUEST;
|
||||
}
|
||||
|
||||
super::deliveries::spawn_record(
|
||||
&agent,
|
||||
tenant_id,
|
||||
super::deliveries::queued(
|
||||
"github",
|
||||
"pull_request",
|
||||
repo_id,
|
||||
"pull request review queued",
|
||||
),
|
||||
);
|
||||
let repo_id = repo_id.to_string();
|
||||
let tenant_id = tenant_id.to_string();
|
||||
let head_sha = head_sha.to_string();
|
||||
|
||||
@@ -64,6 +64,11 @@ pub async fn handle_gitlab_webhook(
|
||||
|
||||
match event_type {
|
||||
"push" => {
|
||||
super::deliveries::spawn_record(
|
||||
&agent,
|
||||
&tenant_id,
|
||||
super::deliveries::queued("gitlab", "push", &repo_id, "scan queued"),
|
||||
);
|
||||
let agent_clone = (*agent).clone();
|
||||
let repo_id = repo_id.clone();
|
||||
let tenant_id = tenant_id.clone();
|
||||
@@ -114,6 +119,16 @@ async fn handle_merge_request(
|
||||
return StatusCode::BAD_REQUEST;
|
||||
}
|
||||
|
||||
super::deliveries::spawn_record(
|
||||
&agent,
|
||||
tenant_id,
|
||||
super::deliveries::queued(
|
||||
"gitlab",
|
||||
"merge_request",
|
||||
repo_id,
|
||||
"merge request review queued",
|
||||
),
|
||||
);
|
||||
let repo_id = repo_id.to_string();
|
||||
let tenant_id = tenant_id.to_string();
|
||||
let head_sha = head_sha.to_string();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod deliveries;
|
||||
pub mod gitea;
|
||||
pub mod gitea_source;
|
||||
pub mod github;
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! Managed git source (#439) against a live Mongo: the platform API stores the
|
||||
//! source sealed and hands out the webhook secret once, the org webhook is
|
||||
//! HMAC-checked and creates exactly one target per repository however often
|
||||
//! (or concurrently) it is delivered, deletion archives, and the sync diffs a
|
||||
//! mocked Gitea listing. Skips cleanly when no Mongo is reachable.
|
||||
//! HMAC-checked, answers 202 and creates exactly one target per repository in
|
||||
//! the background however often (or concurrently) it is delivered, deletion
|
||||
//! archives, every handled delivery is recorded for the target page, and the
|
||||
//! sync diffs a mocked Gitea listing. Skips cleanly when no Mongo is reachable.
|
||||
//!
|
||||
//! Every repository here is empty, so no scan (and no clone) is started.
|
||||
|
||||
@@ -14,6 +15,7 @@ use std::sync::Arc;
|
||||
|
||||
use axum::routing::{get, post};
|
||||
use axum::{Extension, Router};
|
||||
use futures_util::TryStreamExt;
|
||||
use hmac::{Hmac, Mac};
|
||||
use mongodb::bson::doc;
|
||||
use sha2::Sha256;
|
||||
@@ -24,6 +26,7 @@ use compliance_agent::database::{Database, DatabasePool};
|
||||
use compliance_agent::error::AgentError;
|
||||
use compliance_agent::git_source::gitea::{GiteaRepo, RepoLister};
|
||||
use compliance_agent::webhooks::gitea_source::handle_gitea_source_webhook;
|
||||
use compliance_core::models::{DeliveryResult, OnboardedTarget, WebhookDelivery};
|
||||
|
||||
use common::dev_config;
|
||||
|
||||
@@ -126,6 +129,29 @@ impl Harness {
|
||||
req.body(bytes).send().await.unwrap().status().as_u16()
|
||||
}
|
||||
|
||||
/// Poll `check` until it holds: the webhook's work runs after its answer.
|
||||
async fn eventually<F, Fut>(what: &str, mut check: F)
|
||||
where
|
||||
F: FnMut() -> Fut,
|
||||
Fut: std::future::Future<Output = bool>,
|
||||
{
|
||||
for _ in 0..100 {
|
||||
if check().await {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
}
|
||||
panic!("{what} did not happen within 5 s");
|
||||
}
|
||||
|
||||
async fn target(&self, repo_id: i64) -> Option<OnboardedTarget> {
|
||||
self.db
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "source_repo.repo_id": repo_id })
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn managed_count(&self, repo_id: i64) -> u64 {
|
||||
self.db
|
||||
.onboarded_targets()
|
||||
@@ -255,25 +281,28 @@ async fn platform_api_webhook_and_sync() {
|
||||
);
|
||||
assert_eq!(h.managed_count(11).await, 0);
|
||||
|
||||
// Twice at once and once more: one target.
|
||||
// Twice at once and once more: accepted at once, one target.
|
||||
let sig = sign(&secret, &body);
|
||||
let (a, b) = tokio::join!(
|
||||
h.deliver(TENANT, "repository", &created_evt, Some(sig.clone())),
|
||||
h.deliver(TENANT, "repository", &created_evt, Some(sig.clone())),
|
||||
);
|
||||
assert_eq!((a, b), (200, 200));
|
||||
assert_eq!((a, b), (202, 202));
|
||||
Harness::eventually("the first target", || async {
|
||||
h.target(11)
|
||||
.await
|
||||
.is_some_and(|t| t.classification.is_some())
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
h.deliver(TENANT, "repository", &created_evt, Some(sig))
|
||||
.await,
|
||||
200
|
||||
202
|
||||
);
|
||||
// Let the third delivery's refresh finish before the deletion below.
|
||||
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
|
||||
assert_eq!(h.managed_count(11).await, 1);
|
||||
let target =
|
||||
h.db.onboarded_targets()
|
||||
.find_one(doc! { "source_repo.repo_id": 11_i64 })
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let target = h.target(11).await.unwrap();
|
||||
assert_eq!(target.name, "kunde/fw");
|
||||
assert_eq!(
|
||||
target.code_artifact().unwrap().source_ref,
|
||||
@@ -281,7 +310,56 @@ async fn platform_api_webhook_and_sync() {
|
||||
);
|
||||
assert!(target.classification.is_some(), "detection ran");
|
||||
|
||||
// Another organisation's repository is ignored.
|
||||
// Each of the three deliveries is recorded for the target page, in a
|
||||
// capped collection.
|
||||
let target_id = target.id.unwrap().to_hex();
|
||||
let for_target = compliance_agent::webhooks::deliveries::target_filter(
|
||||
&target_id,
|
||||
target.source_repo.as_ref(),
|
||||
);
|
||||
Harness::eventually("three recorded deliveries", || async {
|
||||
h.db.webhook_deliveries()
|
||||
.count_documents(for_target.clone())
|
||||
.await
|
||||
.unwrap()
|
||||
== 3
|
||||
})
|
||||
.await;
|
||||
let recorded: Vec<WebhookDelivery> =
|
||||
h.db.webhook_deliveries()
|
||||
.find(for_target.clone())
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect()
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(recorded.iter().all(|d| d.result == DeliveryResult::Handled
|
||||
&& d.source == "gitea-source"
|
||||
&& d.event == "repository"
|
||||
&& d.target_id.as_deref() == Some(target_id.as_str())));
|
||||
assert_eq!(
|
||||
recorded
|
||||
.iter()
|
||||
.filter(|d| d.detail == "target ready, nothing to scan yet")
|
||||
.count(),
|
||||
3,
|
||||
"an empty repository is not scanned"
|
||||
);
|
||||
let spec = h
|
||||
.pool
|
||||
.client()
|
||||
.database(&h.pool.tenant_db_name(TENANT))
|
||||
.list_collections()
|
||||
.filter(doc! { "name": "webhook_deliveries" })
|
||||
.await
|
||||
.unwrap()
|
||||
.try_next()
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(spec.options.capped, Some(true));
|
||||
|
||||
// Another organisation's repository is ignored, and said so at once.
|
||||
let other =
|
||||
serde_json::json!({ "action": "created", "repository": repo_json(12, "andere", "x") });
|
||||
let ob = serde_json::to_vec(&other).unwrap();
|
||||
@@ -299,15 +377,21 @@ async fn platform_api_webhook_and_sync() {
|
||||
assert_eq!(
|
||||
h.deliver(TENANT, "repository", &deleted, Some(sign(&secret, &db_)))
|
||||
.await,
|
||||
200
|
||||
202
|
||||
);
|
||||
let target =
|
||||
h.db.onboarded_targets()
|
||||
.find_one(doc! { "source_repo.repo_id": 11_i64 })
|
||||
Harness::eventually("the archive", || async {
|
||||
h.target(11).await.is_some_and(|t| t.archived_at.is_some())
|
||||
})
|
||||
.await;
|
||||
// The deletion carries no target id; it is the target's by repository.
|
||||
Harness::eventually("the recorded deletion", || async {
|
||||
h.db.webhook_deliveries()
|
||||
.count_documents(for_target.clone())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(target.archived_at.is_some());
|
||||
== 4
|
||||
})
|
||||
.await;
|
||||
|
||||
// ── sync against a mocked listing ───────────────────────────────────
|
||||
struct Listing(Vec<GiteaRepo>);
|
||||
@@ -398,3 +482,42 @@ async fn platform_api_webhook_and_sync() {
|
||||
|
||||
h.pool.drop_tenant(TENANT).await.ok();
|
||||
}
|
||||
|
||||
/// A deliveries collection written before the indexes were ensured (a plain
|
||||
/// one) is converted to a capped one.
|
||||
#[tokio::test]
|
||||
async fn a_plain_deliveries_collection_becomes_capped() {
|
||||
let Some(h) = start().await else { return };
|
||||
const PLAIN: &str = "gitsrc-plain";
|
||||
let early = WebhookDelivery::new("gitea", "push", DeliveryResult::Handled, "scan queued");
|
||||
h.pool
|
||||
.for_existing_tenant_id(PLAIN)
|
||||
.webhook_deliveries()
|
||||
.insert_one(&early)
|
||||
.await
|
||||
.unwrap();
|
||||
let db = h.pool.for_tenant_id(PLAIN).await.expect("ensured");
|
||||
let spec = h
|
||||
.pool
|
||||
.client()
|
||||
.database(&h.pool.tenant_db_name(PLAIN))
|
||||
.list_collections()
|
||||
.filter(doc! { "name": "webhook_deliveries" })
|
||||
.await
|
||||
.unwrap()
|
||||
.try_next()
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(spec.options.capped, Some(true));
|
||||
assert_eq!(
|
||||
db.webhook_deliveries()
|
||||
.count_documents(doc! {})
|
||||
.await
|
||||
.unwrap(),
|
||||
1,
|
||||
"the early delivery is kept"
|
||||
);
|
||||
h.pool.drop_tenant(PLAIN).await.ok();
|
||||
h.pool.drop_tenant(TENANT).await.ok();
|
||||
}
|
||||
@@ -3,4 +3,5 @@ mod dast;
|
||||
mod findings;
|
||||
mod health;
|
||||
mod onboarding;
|
||||
mod sbom;
|
||||
mod stats;
|
||||
@@ -222,3 +222,68 @@ async fn a_rejected_upload_leaves_no_file_behind() {
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_list_pages_with_a_total_after_the_project_filter() {
|
||||
let server = TestServer::start().await;
|
||||
let mut ids = Vec::new();
|
||||
for name in ["page-a", "page-b", "page-c"] {
|
||||
ids.push(firmware_target(&server, name).await);
|
||||
}
|
||||
// Projects are registry-owned, so put two targets in one directly.
|
||||
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
|
||||
let targets = client
|
||||
.database(&format!("{}_dev", server.db_name()))
|
||||
.collection::<mongodb::bson::Document>("onboarded_targets");
|
||||
for id in &ids[1..] {
|
||||
let oid = mongodb::bson::oid::ObjectId::parse_str(id).unwrap();
|
||||
let updated = targets
|
||||
.update_one(
|
||||
mongodb::bson::doc! { "_id": oid },
|
||||
mongodb::bson::doc! { "$set": { "project_ids": ["p1"] } },
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(updated.matched_count, 1);
|
||||
}
|
||||
|
||||
let names = |body: &serde_json::Value| -> Vec<String> {
|
||||
body["data"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|t| t["name"].as_str().unwrap().to_string())
|
||||
.collect()
|
||||
};
|
||||
let page = |query: &'static str| {
|
||||
let server = &server;
|
||||
async move {
|
||||
let resp = server.get(&format!("/api/v1/targets?{query}")).await;
|
||||
assert_eq!(resp.status(), 200);
|
||||
resp.json::<serde_json::Value>().await.unwrap()
|
||||
}
|
||||
};
|
||||
|
||||
// Creation order, two to a page, the total over every page.
|
||||
let first = page("limit=2&page=1").await;
|
||||
assert_eq!(names(&first), ["page-a", "page-b"]);
|
||||
assert_eq!(first["total"], 3);
|
||||
assert_eq!(first["page"], 1);
|
||||
let second = page("limit=2&page=2").await;
|
||||
assert_eq!(names(&second), ["page-c"]);
|
||||
assert_eq!(second["total"], 3);
|
||||
|
||||
// The filter applies before paging: the total counts the project only.
|
||||
let in_project = page("project=p1&limit=1&page=2").await;
|
||||
assert_eq!(names(&in_project), ["page-c"]);
|
||||
assert_eq!(in_project["total"], 2);
|
||||
|
||||
// A page past the end is empty but still knows the total.
|
||||
let past = page("limit=2&page=9").await;
|
||||
assert!(names(&past).is_empty());
|
||||
assert_eq!(past["total"], 3);
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
use crate::common::TestServer;
|
||||
use compliance_core::models::{InImage, InImageBasis, SbomEntry, YOCTO_RECIPE_MANAGER};
|
||||
|
||||
/// A Yocto recipe component, in `pump-image` when `in_image`.
|
||||
fn recipe(name: &str, in_image: bool) -> SbomEntry {
|
||||
let mut entry = SbomEntry::new(
|
||||
"yocto-target".into(),
|
||||
name.into(),
|
||||
"1.0".into(),
|
||||
YOCTO_RECIPE_MANAGER.into(),
|
||||
);
|
||||
entry.purl = Some(format!("pkg:generic/{name}@1.0"));
|
||||
entry.in_image = in_image.then(|| InImage {
|
||||
basis: InImageBasis::Declared,
|
||||
images: vec!["pump-image".into()],
|
||||
});
|
||||
entry
|
||||
}
|
||||
|
||||
/// The names of the components a list request returns, in its order.
|
||||
async fn names(server: &TestServer, query: &str) -> Vec<String> {
|
||||
let resp = server
|
||||
.get(&format!("/api/v1/sbom?repo_id=yocto-target{query}"))
|
||||
.await;
|
||||
assert_eq!(resp.status(), 200);
|
||||
let body: serde_json::Value = resp.json().await.unwrap();
|
||||
body["data"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|e| e["name"].as_str().unwrap().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_sbom_lists_components_in_the_image_first_and_filters_by_it() {
|
||||
let server = TestServer::start().await;
|
||||
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
|
||||
// The dev tenant's database, which the API reads.
|
||||
let db = client.database(&format!("{}_dev", server.db_name()));
|
||||
let entries = [
|
||||
recipe("aaa-tools", false),
|
||||
recipe("busybox", true),
|
||||
recipe("pump-fw", false),
|
||||
recipe("zlib", true),
|
||||
];
|
||||
db.collection::<SbomEntry>("sbom_entries")
|
||||
.insert_many(&entries)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
names(&server, "").await,
|
||||
["busybox", "zlib", "aaa-tools", "pump-fw"],
|
||||
"nothing is dropped; the image's components come first"
|
||||
);
|
||||
assert_eq!(names(&server, "&in_image=true").await, ["busybox", "zlib"]);
|
||||
assert_eq!(
|
||||
names(&server, "&in_image=false").await,
|
||||
["aaa-tools", "pump-fw"]
|
||||
);
|
||||
|
||||
let resp = server
|
||||
.get("/api/v1/sbom/export?repo_id=yocto-target&format=cyclonedx")
|
||||
.await;
|
||||
assert_eq!(resp.status(), 200);
|
||||
let cdx: serde_json::Value = resp.json().await.unwrap();
|
||||
let busybox = cdx["components"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|c| c["name"] == "busybox")
|
||||
.expect("busybox");
|
||||
assert!(busybox["properties"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(
|
||||
|p| p["name"] == "pruefwerk:component:in_image" && p["value"] == "declared: pump-image"
|
||||
));
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
@@ -331,12 +331,24 @@ struct Snapshot {
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
error: String,
|
||||
skipped_stages: BTreeSet<String>,
|
||||
/// `package_manager:name@version`, compared exactly.
|
||||
/// The stages the run's notes are about (code left out by design,
|
||||
/// suppressed findings), compared exactly.
|
||||
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
|
||||
notes: BTreeSet<String>,
|
||||
/// `package_manager:name@version`, with ` [in image: <images>]` for a
|
||||
/// component an image declares, compared exactly.
|
||||
sbom: BTreeSet<String>,
|
||||
/// Deterministic findings as `scanner:rule file:line`, compared exactly.
|
||||
findings: BTreeSet<String>,
|
||||
/// CVE and advisory ids; the run must contain at least these.
|
||||
cves: BTreeSet<String>,
|
||||
/// A Yocto target's layer pins as `source name branch@commit` (`-` for
|
||||
/// what is not pinned), compared exactly.
|
||||
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
|
||||
layer_pins: BTreeSet<String>,
|
||||
/// The Yocto release read from them, compared exactly.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
yocto_release: String,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
@@ -376,9 +388,17 @@ impl Snapshot {
|
||||
&self.skipped_stages,
|
||||
&baseline.skipped_stages,
|
||||
));
|
||||
out.extend(exact("note", &self.notes, &baseline.notes));
|
||||
out.extend(exact("SBOM component", &self.sbom, &baseline.sbom));
|
||||
out.extend(exact("finding", &self.findings, &baseline.findings));
|
||||
out.extend(at_least("CVE", &self.cves, &baseline.cves));
|
||||
out.extend(exact("layer pin", &self.layer_pins, &baseline.layer_pins));
|
||||
if self.yocto_release != baseline.yocto_release {
|
||||
out.push(format!(
|
||||
"Yocto release \"{}\", blessed \"{}\"",
|
||||
self.yocto_release, baseline.yocto_release
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -403,6 +423,16 @@ struct Collected {
|
||||
observed: Observed,
|
||||
}
|
||||
|
||||
/// The `stage` of every entry of a run's `skipped_stages` or `notes`.
|
||||
fn stages(entries: &Value) -> BTreeSet<String> {
|
||||
entries
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|s| text(s, "stage"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn collect(agent: &Agent, target_id: &str, run: &Value) -> Collected {
|
||||
let findings = agent
|
||||
.all(&format!("/api/v1/findings?repo_id={target_id}"))
|
||||
@@ -420,12 +450,8 @@ async fn collect(agent: &Agent, target_id: &str, run: &Value) -> Collected {
|
||||
let mut snapshot = Snapshot {
|
||||
scan_status: text(run, "status"),
|
||||
error: text(run, "error_message"),
|
||||
skipped_stages: run["skipped_stages"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|s| text(s, "stage"))
|
||||
.collect(),
|
||||
skipped_stages: stages(&run["skipped_stages"]),
|
||||
notes: stages(&run["notes"]),
|
||||
..Default::default()
|
||||
};
|
||||
let mut observed = Observed {
|
||||
@@ -477,8 +503,15 @@ async fn collect(agent: &Agent, target_id: &str, run: &Value) -> Collected {
|
||||
}
|
||||
}
|
||||
for e in &sbom {
|
||||
let in_image = e["in_image"]["images"]
|
||||
.as_array()
|
||||
.map(|images| {
|
||||
let names: Vec<&str> = images.iter().filter_map(Value::as_str).collect();
|
||||
format!(" [in image: {}]", names.join(", "))
|
||||
})
|
||||
.unwrap_or_default();
|
||||
snapshot.sbom.insert(format!(
|
||||
"{}:{}@{}",
|
||||
"{}:{}@{}{in_image}",
|
||||
text(e, "package_manager"),
|
||||
text(e, "name"),
|
||||
text(e, "version")
|
||||
@@ -488,6 +521,19 @@ async fn collect(agent: &Agent, target_id: &str, run: &Value) -> Collected {
|
||||
}
|
||||
}
|
||||
|
||||
let pins = &target["layer_pins"];
|
||||
for pin in pins["pins"].as_array().into_iter().flatten() {
|
||||
let or_dash = |key: &str| pin[key].as_str().unwrap_or("-").to_string();
|
||||
snapshot.layer_pins.insert(format!(
|
||||
"{} {} {}@{}",
|
||||
text(pin, "source"),
|
||||
text(pin, "name"),
|
||||
or_dash("branch"),
|
||||
or_dash("commit")
|
||||
));
|
||||
}
|
||||
snapshot.yocto_release = text(&pins["release"], "codename");
|
||||
|
||||
let facts = target["classification"]["facts"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
@@ -730,9 +776,11 @@ mod unit {
|
||||
scan_status: "completed".into(),
|
||||
error: String::new(),
|
||||
skipped_stages: set(&["dast"]),
|
||||
notes: set(&["sast_vendor_code"]),
|
||||
sbom: set(&["cargo:itoa@1.0.15"]),
|
||||
findings: set(&["gitleaks:aws-key a.py:3"]),
|
||||
cves: set(&["CVE-2020-1", "GHSA-xxxx-yyyy-zzzz"]),
|
||||
..Default::default()
|
||||
};
|
||||
let mut run = blessed.clone();
|
||||
assert!(run.diff(&blessed).is_empty());
|
||||
@@ -741,9 +789,14 @@ mod unit {
|
||||
// A new CVE is fine, a lost one is not.
|
||||
run.cves = set(&["CVE-2020-1", "CVE-2026-9"]);
|
||||
run.scan_status = "failed".into();
|
||||
run.notes = set(&["recipe_lint_suppressed"]);
|
||||
run.layer_pins = set(&["kas poky dunfell@-"]);
|
||||
let diff = run.diff(&blessed);
|
||||
for needle in [
|
||||
"unexpected layer pin: kas poky dunfell@-",
|
||||
"scan status failed, blessed completed",
|
||||
"missing note: sast_vendor_code",
|
||||
"unexpected note: recipe_lint_suppressed",
|
||||
"missing SBOM component: cargo:itoa@1.0.15",
|
||||
"unexpected SBOM component: cargo:itoa@1.0.16",
|
||||
"missing CVE: GHSA-xxxx-yyyy-zzzz",
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
//! #498: a CVE alert's VEX status follows the scans. Gone after a complete
|
||||
//! lookup, an unassessed or affected alert is `fixed` by the scan, a
|
||||
//! person's `not_affected` stays; reported again, the scan's `fixed` is
|
||||
//! withdrawn. A stored alert gets its component's purl on a later scan.
|
||||
//! withdrawn. A stored alert gets its component's purl on a later scan. An
|
||||
//! alert `not_affected` or `fixed` raises no notification until the
|
||||
//! statement is withdrawn.
|
||||
//! Runs against a live Mongo (`TEST_MONGODB_URI`) and skips
|
||||
//! cleanly without one.
|
||||
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
use compliance_agent::database::{Database, DatabasePool};
|
||||
use compliance_agent::pipeline::vex_lifecycle::{backfill_purls, resolve_gone, upsert_reported};
|
||||
use compliance_agent::pipeline::cve_notify::notify_new_cves;
|
||||
use compliance_agent::pipeline::vex_lifecycle::{
|
||||
apply_scan_statements, attach_stored_vex, backfill_purls, resolve_gone, upsert_reported,
|
||||
};
|
||||
use compliance_agent::pipeline::yocto_inventory::{self, CveStatus, Patch, Recipe};
|
||||
use compliance_core::models::{
|
||||
CveAlert, CveSource, SbomEntry, VexAssessment, VexJustification, VexStatus,
|
||||
};
|
||||
@@ -240,3 +246,225 @@ async fn an_alert_from_before_keeps_its_purl_after_the_component_is_gone() {
|
||||
|
||||
pool.drop_tenant(tenant).await.ok();
|
||||
}
|
||||
|
||||
/// A Yocto recipe's CVE_STATUS and `CVE:` patch become the alerts' VEX
|
||||
/// statements on every scan, reach the exports, are withdrawn when the recipe
|
||||
/// stops saying so, and never replace a person's statement.
|
||||
#[tokio::test]
|
||||
async fn a_recipe_states_vex_each_scan_but_never_over_a_person() {
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let prefix = format!(
|
||||
"vexyocto_{}",
|
||||
&uuid::Uuid::new_v4().simple().to_string()[..10]
|
||||
);
|
||||
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
|
||||
eprintln!("SKIP vex_lifecycle: no MongoDB reachable at {uri}");
|
||||
return;
|
||||
};
|
||||
let tenant = "vex-yocto";
|
||||
let Ok(db) = pool.for_tenant_id(tenant).await else {
|
||||
eprintln!("SKIP vex_lifecycle: MongoDB at {uri} not usable");
|
||||
return;
|
||||
};
|
||||
|
||||
// Arrange: busybox's recipe assesses one CVE and patches another; a
|
||||
// person assessed a third one the recipe also names.
|
||||
let mut recipe = Recipe {
|
||||
file: "recipes-core/busybox/busybox_1.35.0.bb".into(),
|
||||
pn: "busybox".into(),
|
||||
bpn: "busybox".into(),
|
||||
pv: Some("1.35.0".into()),
|
||||
cve_status: vec![
|
||||
CveStatus {
|
||||
cve: "CVE-2022-28391".into(),
|
||||
status: "not-applicable-config".into(),
|
||||
detail: "netstat is disabled".into(),
|
||||
},
|
||||
CveStatus {
|
||||
cve: "CVE-2022-48174".into(),
|
||||
status: "ignored".into(),
|
||||
detail: String::new(),
|
||||
},
|
||||
],
|
||||
patches: vec![Patch {
|
||||
file: "recipes-core/busybox/busybox/fix.patch".into(),
|
||||
cves: vec!["CVE-2022-30065".into()],
|
||||
}],
|
||||
..Recipe::default()
|
||||
};
|
||||
let busybox = |id: &str| {
|
||||
CveAlert::new(
|
||||
id.into(),
|
||||
TARGET.into(),
|
||||
"busybox".into(),
|
||||
"1.35.0".into(),
|
||||
CveSource::Nvd,
|
||||
)
|
||||
};
|
||||
let alerts: Vec<CveAlert> = ["CVE-2022-28391", "CVE-2022-30065", "CVE-2022-48174"]
|
||||
.into_iter()
|
||||
.map(busybox)
|
||||
.collect();
|
||||
for alert in &alerts {
|
||||
upsert_reported(&db, alert).await.unwrap();
|
||||
}
|
||||
let person = mongodb::bson::to_bson(&by_person(VexStatus::Affected)).unwrap();
|
||||
db.cve_alerts()
|
||||
.update_one(
|
||||
doc! { "cve_id": "CVE-2022-48174" },
|
||||
doc! { "$set": { "vex": person } },
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Act: the scan states what the recipe says.
|
||||
let statements = yocto_inventory::vex_statements(std::slice::from_ref(&recipe), &alerts);
|
||||
assert_eq!(statements.len(), 3);
|
||||
assert_eq!(
|
||||
apply_scan_statements(&db, TARGET, &statements)
|
||||
.await
|
||||
.unwrap(),
|
||||
2
|
||||
);
|
||||
|
||||
// Assert: not_affected and fixed by the scan; the person's stays.
|
||||
let status = stored(&db, "CVE-2022-28391").await.vex.unwrap();
|
||||
assert_eq!(
|
||||
(status.status, status.justification, status.by_scan),
|
||||
(
|
||||
VexStatus::NotAffected,
|
||||
Some(VexJustification::VulnerableCodeNotPresent),
|
||||
true
|
||||
)
|
||||
);
|
||||
let patched = stored(&db, "CVE-2022-30065").await.vex.unwrap();
|
||||
assert_eq!(patched.status, VexStatus::Fixed);
|
||||
let kept = stored(&db, "CVE-2022-48174").await.vex.unwrap();
|
||||
assert_eq!((kept.status, kept.by_scan), (VexStatus::Affected, false));
|
||||
|
||||
// The exports carry the recipe's reason.
|
||||
let current = vec![stored(&db, "CVE-2022-28391").await];
|
||||
let input = vex_docs::VexInput {
|
||||
subject: "pump",
|
||||
author: "ws",
|
||||
tooling: "Prüfwerk test",
|
||||
alerts: ¤t,
|
||||
sbom: &[],
|
||||
now: chrono::Utc::now(),
|
||||
};
|
||||
let openvex = vex_docs::openvex(&input).to_string();
|
||||
assert!(openvex.contains("not_affected"), "{openvex}");
|
||||
assert!(openvex.contains("netstat is disabled"), "{openvex}");
|
||||
|
||||
// The next scan: the recipe no longer assesses CVE-2022-28391, so its
|
||||
// statement is withdrawn; the patch still fixes CVE-2022-30065.
|
||||
recipe.cve_status.remove(0);
|
||||
for alert in &alerts {
|
||||
upsert_reported(&db, alert).await.unwrap();
|
||||
}
|
||||
let statements = yocto_inventory::vex_statements(std::slice::from_ref(&recipe), &alerts);
|
||||
apply_scan_statements(&db, TARGET, &statements)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(stored(&db, "CVE-2022-28391").await.vex.is_none());
|
||||
assert_eq!(
|
||||
stored(&db, "CVE-2022-30065").await.vex.map(|v| v.status),
|
||||
Some(VexStatus::Fixed)
|
||||
);
|
||||
assert_eq!(
|
||||
stored(&db, "CVE-2022-48174").await.vex.map(|v| v.status),
|
||||
Some(VexStatus::Affected)
|
||||
);
|
||||
|
||||
pool.drop_tenant(tenant).await.ok();
|
||||
}
|
||||
|
||||
/// What a scan does: store the alerts, set its own statements, then give the
|
||||
/// alerts their stored statements and notify.
|
||||
async fn scan_and_notify(
|
||||
db: &Database,
|
||||
found: &[CveAlert],
|
||||
statements: &[(String, VexAssessment)],
|
||||
) -> u32 {
|
||||
for alert in found {
|
||||
upsert_reported(db, alert).await.unwrap();
|
||||
}
|
||||
apply_scan_statements(db, TARGET, statements).await.unwrap();
|
||||
let mut found = found.to_vec();
|
||||
attach_stored_vex(db, TARGET, &mut found).await.unwrap();
|
||||
notify_new_cves(db, TARGET, "app", &found).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn not_affected_and_fixed_raise_no_notification_until_withdrawn() {
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let prefix = format!(
|
||||
"vexnotif_{}",
|
||||
&uuid::Uuid::new_v4().simple().to_string()[..10]
|
||||
);
|
||||
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
|
||||
eprintln!("SKIP vex_lifecycle: no MongoDB reachable at {uri}");
|
||||
return;
|
||||
};
|
||||
let tenant = "vex-notifications";
|
||||
let Ok(db) = pool.for_tenant_id(tenant).await else {
|
||||
eprintln!("SKIP vex_lifecycle: MongoDB at {uri} not usable");
|
||||
return;
|
||||
};
|
||||
let found: Vec<CveAlert> = ["CVE-1", "CVE-2", "CVE-3", "CVE-4", "CVE-5"]
|
||||
.into_iter()
|
||||
.map(alert)
|
||||
.collect();
|
||||
for alert in &found {
|
||||
upsert_reported(&db, alert).await.unwrap();
|
||||
}
|
||||
// A person settles CVE-2 and CVE-3 and confirms CVE-4; a recipe says
|
||||
// CVE-5 is not affected.
|
||||
for (id, status) in [
|
||||
("CVE-2", VexStatus::NotAffected),
|
||||
("CVE-3", VexStatus::Fixed),
|
||||
("CVE-4", VexStatus::Affected),
|
||||
] {
|
||||
let vex = mongodb::bson::to_bson(&by_person(status)).unwrap();
|
||||
db.cve_alerts()
|
||||
.update_one(doc! { "cve_id": id }, doc! { "$set": { "vex": vex } })
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let mut recipe_says = by_person(VexStatus::NotAffected);
|
||||
recipe_says.by_scan = true;
|
||||
let recipe = vec![("CVE-5".to_string(), recipe_says)];
|
||||
|
||||
// Only the unsettled CVEs notify, and only once.
|
||||
assert_eq!(scan_and_notify(&db, &found, &recipe).await, 2);
|
||||
assert_eq!(scan_and_notify(&db, &found, &recipe).await, 0);
|
||||
let mut notified: Vec<String> = db
|
||||
.cve_notifications()
|
||||
.distinct("cve_id", doc! {})
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.filter_map(|id| id.as_str().map(str::to_owned))
|
||||
.collect();
|
||||
notified.sort();
|
||||
assert_eq!(notified, ["CVE-1", "CVE-4"]);
|
||||
|
||||
// The person withdraws CVE-2's statement and the recipe no longer
|
||||
// assesses CVE-5: both notify now; CVE-3 stays fixed and silent.
|
||||
db.cve_alerts()
|
||||
.update_one(doc! { "cve_id": "CVE-2" }, doc! { "$unset": { "vex": "" } })
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(scan_and_notify(&db, &found, &[]).await, 2);
|
||||
assert_eq!(
|
||||
db.cve_notifications()
|
||||
.count_documents(doc! { "cve_id": "CVE-3" })
|
||||
.await
|
||||
.unwrap(),
|
||||
0
|
||||
);
|
||||
|
||||
pool.drop_tenant(tenant).await.ok();
|
||||
}
|
||||
@@ -95,6 +95,98 @@ pub struct AgentConfig {
|
||||
/// below stop being optional and a missing one fails startup instead of
|
||||
/// silently disabling the check.
|
||||
pub app_env: AppEnv,
|
||||
/// Whether a scan files the missing Gitea issues of a target's older
|
||||
/// open findings (`ISSUE_CATCHUP`, default off).
|
||||
pub issue_catchup: IssueCatchup,
|
||||
/// Whether a scan closes the open CVE issues a VEX statement settles
|
||||
/// (`ISSUE_AUTOCLOSE`, default off).
|
||||
pub issue_autoclose: IssueAutoclose,
|
||||
}
|
||||
|
||||
/// Closing open CVE issues whose CVE a VEX statement settles
|
||||
/// (`ISSUE_AUTOCLOSE`): `not_affected` or `fixed`. Opening no new issue for
|
||||
/// such a CVE does not depend on it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum IssueAutoclose {
|
||||
/// Leave the open issues open.
|
||||
#[default]
|
||||
Off,
|
||||
/// Count the issues it would close, per VEX status; change nothing.
|
||||
DryRun,
|
||||
/// Close them with a comment, a few per target and scan.
|
||||
On,
|
||||
}
|
||||
|
||||
impl IssueAutoclose {
|
||||
/// Parse `ISSUE_AUTOCLOSE`: `off`, `dry_run` or `on`, any case. Empty is
|
||||
/// [`IssueAutoclose::Off`].
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Any other value, with a message naming it (the caller falls back to
|
||||
/// off).
|
||||
pub fn parse(raw: &str) -> Result<Self, String> {
|
||||
match raw.trim().to_ascii_lowercase().as_str() {
|
||||
"" | "off" => Ok(Self::Off),
|
||||
"dry_run" => Ok(Self::DryRun),
|
||||
"on" => Ok(Self::On),
|
||||
other => Err(format!(
|
||||
"unknown ISSUE_AUTOCLOSE '{other}' (expected off, dry_run or on)"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The value as `ISSUE_AUTOCLOSE` spells it.
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Off => "off",
|
||||
Self::DryRun => "dry_run",
|
||||
Self::On => "on",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The issue catch-up (`ISSUE_CATCHUP`): after a scan's own issues, a Gitea
|
||||
/// target's open medium+ findings without an issue get one (or are linked to
|
||||
/// the one that exists), at most a few new issues per scan.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum IssueCatchup {
|
||||
/// No catch-up.
|
||||
#[default]
|
||||
Off,
|
||||
/// Count what the catch-up would create and link, change nothing.
|
||||
DryRun,
|
||||
/// Create and link.
|
||||
On,
|
||||
}
|
||||
|
||||
impl IssueCatchup {
|
||||
/// Parse `ISSUE_CATCHUP`: `off`, `dry_run` or `on`, any case. Empty is
|
||||
/// [`IssueCatchup::Off`].
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Any other value, with a message naming it (the caller falls back to
|
||||
/// off).
|
||||
pub fn parse(raw: &str) -> Result<Self, String> {
|
||||
match raw.trim().to_ascii_lowercase().as_str() {
|
||||
"" | "off" => Ok(Self::Off),
|
||||
"dry_run" => Ok(Self::DryRun),
|
||||
"on" => Ok(Self::On),
|
||||
other => Err(format!(
|
||||
"unknown ISSUE_CATCHUP '{other}' (expected off, dry_run or on)"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The value as `ISSUE_CATCHUP` spells it.
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Off => "off",
|
||||
Self::DryRun => "dry_run",
|
||||
Self::On => "on",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Deployment environment (`APP_ENV`).
|
||||
@@ -274,6 +366,8 @@ impl Default for AgentConfig {
|
||||
platform_allowed_clients: Vec::new(),
|
||||
features: Features::default(),
|
||||
app_env: AppEnv::Dev,
|
||||
issue_catchup: IssueCatchup::Off,
|
||||
issue_autoclose: IssueAutoclose::Off,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -294,6 +388,38 @@ mod app_env_tests {
|
||||
assert!(AppEnv::Production.is_hardened());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn issue_catchup_is_off_unless_named() {
|
||||
use super::IssueCatchup;
|
||||
assert_eq!(IssueCatchup::parse("").unwrap(), IssueCatchup::Off);
|
||||
assert_eq!(IssueCatchup::parse("off").unwrap(), IssueCatchup::Off);
|
||||
assert_eq!(
|
||||
IssueCatchup::parse(" DRY_RUN ").unwrap(),
|
||||
IssueCatchup::DryRun
|
||||
);
|
||||
assert_eq!(IssueCatchup::parse("On").unwrap(), IssueCatchup::On);
|
||||
assert!(IssueCatchup::parse("yes").is_err());
|
||||
assert!(IssueCatchup::parse("dry-run").is_err());
|
||||
assert_eq!(AgentConfig::default().issue_catchup, IssueCatchup::Off);
|
||||
assert_eq!(IssueCatchup::DryRun.as_str(), "dry_run");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn issue_autoclose_is_off_unless_named() {
|
||||
use super::IssueAutoclose;
|
||||
assert_eq!(IssueAutoclose::parse("").unwrap(), IssueAutoclose::Off);
|
||||
assert_eq!(IssueAutoclose::parse("OFF").unwrap(), IssueAutoclose::Off);
|
||||
assert_eq!(
|
||||
IssueAutoclose::parse(" dry_run ").unwrap(),
|
||||
IssueAutoclose::DryRun
|
||||
);
|
||||
assert_eq!(IssueAutoclose::parse("on").unwrap(), IssueAutoclose::On);
|
||||
assert!(IssueAutoclose::parse("true").is_err());
|
||||
assert!(IssueAutoclose::parse("dry-run").is_err());
|
||||
assert_eq!(AgentConfig::default().issue_autoclose, IssueAutoclose::Off);
|
||||
assert_eq!(IssueAutoclose::DryRun.as_str(), "dry_run");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dev_needs_nothing() {
|
||||
assert!(AgentConfig::default().validate_deployment().is_ok());
|
||||
|
||||
@@ -11,9 +11,9 @@
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
use crate::models::{CveAlert, VexStatus};
|
||||
use crate::models::{advisory_source, is_cve, VexStatus};
|
||||
use crate::sbom_docs::product_ref;
|
||||
use crate::vex_docs::{component_id, rfc3339, status_of, VexInput};
|
||||
use crate::vex_docs::{component_id, rfc3339, statements, status_of, Statement, VexInput};
|
||||
|
||||
/// The note every draft carries.
|
||||
pub const DRAFT_NOTE: &str = "Draft, not published: check publisher and statements before release.";
|
||||
@@ -74,40 +74,6 @@ pub fn filename(tracking_id: &str) -> String {
|
||||
format!("{name}.json")
|
||||
}
|
||||
|
||||
/// Whether `id` is a CVE id, which CSAF keeps in its own field.
|
||||
fn is_cve(id: &str) -> bool {
|
||||
id.strip_prefix("CVE-")
|
||||
.and_then(|rest| rest.split_once('-'))
|
||||
.is_some_and(|(year, number)| {
|
||||
year.len() == 4
|
||||
&& number.len() >= 4
|
||||
&& year
|
||||
.bytes()
|
||||
.chain(number.bytes())
|
||||
.all(|b| b.is_ascii_digit())
|
||||
})
|
||||
}
|
||||
|
||||
/// The id CSAF lists a vulnerability under: the alert's CVE, or the CVE
|
||||
/// among its aliases, else its own id. Alerts with the same key are one
|
||||
/// vulnerability (CSAF forbids listing a CVE twice).
|
||||
fn vulnerability_key(alert: &CveAlert) -> &str {
|
||||
if is_cve(&alert.cve_id) {
|
||||
return &alert.cve_id;
|
||||
}
|
||||
alert
|
||||
.aliases
|
||||
.iter()
|
||||
.find(|a| is_cve(a))
|
||||
.map_or(alert.cve_id.as_str(), String::as_str)
|
||||
}
|
||||
|
||||
/// The system a non-CVE id belongs to (`GHSA-…` is GitHub's advisory
|
||||
/// database).
|
||||
fn id_system(id: &str) -> &str {
|
||||
id.split_once('-').map_or("OSV", |(prefix, _)| prefix)
|
||||
}
|
||||
|
||||
/// The components the alerts are about, each once: `(id, name, purl)`.
|
||||
fn components(input: &VexInput<'_>) -> Vec<(String, String, String)> {
|
||||
let mut out: Vec<(String, String, String)> = Vec::new();
|
||||
@@ -177,58 +143,62 @@ fn push_product(parent: &mut serde_json::Value, field: &str, key: &str, product:
|
||||
}
|
||||
}
|
||||
|
||||
/// One vulnerability of the advisory, from all alerts listed under `key`.
|
||||
/// One vulnerability of the advisory, from all statements listed under
|
||||
/// `key` (the CVE, or the advisory's id without one): the CVE in its own
|
||||
/// field, the other ids (a GitHub advisory) under `ids`.
|
||||
fn vulnerability(
|
||||
key: &str,
|
||||
alerts: &[&CveAlert],
|
||||
statements: &[&Statement<'_>],
|
||||
components: &[(String, String, String)],
|
||||
input: &VexInput<'_>,
|
||||
) -> serde_json::Value {
|
||||
let mut v = serde_json::json!({ "product_status": {} });
|
||||
let mut ids: Vec<&str> = Vec::new();
|
||||
if is_cve(key) {
|
||||
v["cve"] = serde_json::json!(key);
|
||||
} else {
|
||||
ids.push(key);
|
||||
}
|
||||
let mut ids: Vec<&str> = Vec::new();
|
||||
for alert in alerts {
|
||||
for id in std::iter::once(&alert.cve_id).chain(&alert.aliases) {
|
||||
if !is_cve(id) && !ids.contains(&id.as_str()) {
|
||||
ids.push(id);
|
||||
}
|
||||
for id in statements.iter().flat_map(|st| &st.other_ids) {
|
||||
if !is_cve(id) && !ids.contains(id) {
|
||||
ids.push(id);
|
||||
}
|
||||
}
|
||||
if !ids.is_empty() {
|
||||
v["ids"] = ids
|
||||
.iter()
|
||||
.map(|id| serde_json::json!({ "system_name": id_system(id), "text": id }))
|
||||
.map(|id| serde_json::json!({ "system_name": advisory_source(id).0, "text": id }))
|
||||
.collect();
|
||||
}
|
||||
// The VEX profile requires notes on every vulnerability; without an
|
||||
// advisory summary they say what is affected.
|
||||
let text = alerts
|
||||
let text = input
|
||||
.alerts
|
||||
.iter()
|
||||
.filter(|a| a.cve() == key)
|
||||
.find_map(|a| a.summary.clone())
|
||||
.unwrap_or_else(|| {
|
||||
let packages: Vec<String> = alerts
|
||||
let packages: Vec<String> = statements
|
||||
.iter()
|
||||
.map(|a| format!("{} {}", a.affected_package, a.affected_version))
|
||||
.map(|st| {
|
||||
format!(
|
||||
"{} {}",
|
||||
st.alert.affected_package, st.alert.affected_version
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
format!("{key} in {}.", packages.join(", "))
|
||||
});
|
||||
v["notes"] = serde_json::json!([{ "category": "description", "text": text }]);
|
||||
let (mut flags, mut threats, mut remediations) = (Vec::new(), Vec::new(), Vec::new());
|
||||
for alert in alerts {
|
||||
let purl = component_id(alert, input.sbom);
|
||||
let Some((id, ..)) = components.iter().find(|(.., p)| *p == purl) else {
|
||||
// One statement per component, so each product has one status.
|
||||
for st in statements {
|
||||
let alert = st.alert;
|
||||
let Some((id, ..)) = components.iter().find(|(.., p)| *p == st.component) else {
|
||||
continue;
|
||||
};
|
||||
let product = in_product(id);
|
||||
let status = status_of(alert);
|
||||
let listed = v["product_status"][status_key(status)]
|
||||
.as_array()
|
||||
.is_some_and(|l| l.iter().any(|p| p == product.as_str()));
|
||||
if listed {
|
||||
continue;
|
||||
}
|
||||
push_product(&mut v, "product_status", status_key(status), &product);
|
||||
let Some(vex) = &alert.vex else { continue };
|
||||
match status {
|
||||
@@ -266,7 +236,17 @@ fn vulnerability(
|
||||
"product_ids": [product],
|
||||
}));
|
||||
}
|
||||
VexStatus::UnderInvestigation | VexStatus::Fixed => {}
|
||||
// Why it is under investigation or fixed (a Yocto recipe's
|
||||
// CVE_STATUS or patch), as the impact on these products.
|
||||
VexStatus::UnderInvestigation | VexStatus::Fixed => {
|
||||
if let Some(text) = vex.impact_statement.as_deref() {
|
||||
threats.push(serde_json::json!({
|
||||
"category": "impact",
|
||||
"details": text,
|
||||
"product_ids": [product],
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (field, list) in [
|
||||
@@ -288,22 +268,21 @@ fn vulnerability(
|
||||
pub fn csaf_vex(input: &VexInput<'_>, namespace: &str, lang: &str) -> serde_json::Value {
|
||||
let now = rfc3339(input.now);
|
||||
let components = components(input);
|
||||
let statements = statements(input);
|
||||
// One vulnerability per CVE (CSAF forbids listing a CVE twice), in the
|
||||
// order the statements first name it.
|
||||
let mut keys: Vec<&str> = Vec::new();
|
||||
for alert in input.alerts {
|
||||
let key = vulnerability_key(alert);
|
||||
if !keys.contains(&key) {
|
||||
keys.push(key);
|
||||
for st in &statements {
|
||||
if !keys.contains(&st.id()) {
|
||||
keys.push(st.id());
|
||||
}
|
||||
}
|
||||
let vulnerabilities: Vec<serde_json::Value> = keys
|
||||
.iter()
|
||||
.map(|key| {
|
||||
let alerts: Vec<&CveAlert> = input
|
||||
.alerts
|
||||
.iter()
|
||||
.filter(|a| vulnerability_key(a) == *key)
|
||||
.collect();
|
||||
vulnerability(key, &alerts, &components, input)
|
||||
let of_key: Vec<&Statement<'_>> =
|
||||
statements.iter().filter(|st| st.id() == *key).collect();
|
||||
vulnerability(key, &of_key, &components, input)
|
||||
})
|
||||
.collect();
|
||||
serde_json::json!({
|
||||
@@ -351,13 +330,53 @@ mod tests {
|
||||
assert_eq!(id, "pruefwerk-vex-pump-remote-hmi-20261006");
|
||||
assert_eq!(filename(&id), "pruefwerk-vex-pump-remote-hmi-20261006.json");
|
||||
assert_eq!(filename("ACME_SA:2026/01"), "acme_sa_2026_01.json");
|
||||
assert!(is_cve("CVE-2021-44228"));
|
||||
assert!(!is_cve("GHSA-jfh8-c2jp-5v3q"));
|
||||
assert!(!is_cve("CVE-21-1"));
|
||||
assert_eq!(id_system("GHSA-jfh8-c2jp-5v3q"), "GHSA");
|
||||
assert_eq!(
|
||||
placeholder_namespace("example-pumps"),
|
||||
"https://example.invalid/example-pumps"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scan_note_on_an_open_or_fixed_status_reaches_every_export() {
|
||||
use crate::models::{CveAlert, CveSource, VexAssessment};
|
||||
let mut alert = CveAlert::new(
|
||||
"CVE-2022-48174".into(),
|
||||
"t".into(),
|
||||
"busybox".into(),
|
||||
"1.35.0".into(),
|
||||
CveSource::Nvd,
|
||||
);
|
||||
let note = "Yocto CVE_STATUS \"disputed\" in recipes-core/busybox/busybox_1.35.0.bb";
|
||||
alert.vex = Some(VexAssessment {
|
||||
status: VexStatus::UnderInvestigation,
|
||||
justification: None,
|
||||
impact_statement: Some(note.into()),
|
||||
action_statement: None,
|
||||
by: "pruefwerk-scan".into(),
|
||||
by_name: None,
|
||||
at: Utc::now(),
|
||||
by_scan: true,
|
||||
});
|
||||
let alerts = [alert];
|
||||
let input = VexInput {
|
||||
subject: "pump",
|
||||
author: "ws",
|
||||
tooling: "test",
|
||||
alerts: &alerts,
|
||||
sbom: &[],
|
||||
now: Utc::now(),
|
||||
};
|
||||
|
||||
let openvex = crate::vex_docs::openvex(&input);
|
||||
let statement = &openvex["statements"][0];
|
||||
assert_eq!(statement["status"], "under_investigation");
|
||||
assert_eq!(statement["status_notes"], note);
|
||||
assert!(
|
||||
statement.get("impact_statement").is_none(),
|
||||
"only for not_affected"
|
||||
);
|
||||
|
||||
let csaf = csaf_vex(&input, "https://example.invalid/ws", "en");
|
||||
assert_eq!(csaf["vulnerabilities"][0]["threats"][0]["details"], note);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ pub mod net_guard;
|
||||
pub mod purl;
|
||||
pub mod sbom_docs;
|
||||
pub mod scan_matrix;
|
||||
pub mod spdx_license;
|
||||
#[cfg(feature = "telemetry")]
|
||||
pub mod telemetry;
|
||||
pub mod tenant;
|
||||
|
||||
@@ -139,17 +139,77 @@ pub struct CveAlert {
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// Whether `id` is a CVE id (`CVE-2021-44228`: a four-digit year and at
|
||||
/// least four digits).
|
||||
pub fn is_cve(id: &str) -> bool {
|
||||
id.strip_prefix("CVE-")
|
||||
.and_then(|rest| rest.split_once('-'))
|
||||
.is_some_and(|(year, number)| {
|
||||
year.len() == 4
|
||||
&& number.len() >= 4
|
||||
&& year
|
||||
.bytes()
|
||||
.chain(number.bytes())
|
||||
.all(|b| b.is_ascii_digit())
|
||||
})
|
||||
}
|
||||
|
||||
/// The id a vulnerability known as `id` (with `aliases`) is listed under:
|
||||
/// `id` when it is a CVE, else its first CVE alias, else `id` itself.
|
||||
pub fn primary_id<'a>(id: &'a str, aliases: &'a [String]) -> &'a str {
|
||||
if is_cve(id) {
|
||||
return id;
|
||||
}
|
||||
aliases
|
||||
.iter()
|
||||
.find(|a| is_cve(a))
|
||||
.map_or(id, String::as_str)
|
||||
}
|
||||
|
||||
/// The database an advisory id belongs to and the advisory's page there:
|
||||
/// NVD for a CVE, GitHub's advisory database for a `GHSA-`, else the id's
|
||||
/// prefix (`RUSTSEC`, `PYSEC`; `OSV` without one) and its OSV page.
|
||||
pub fn advisory_source(id: &str) -> (&str, String) {
|
||||
if is_cve(id) {
|
||||
return ("NVD", format!("https://nvd.nist.gov/vuln/detail/{id}"));
|
||||
}
|
||||
if id.starts_with("GHSA-") {
|
||||
return (
|
||||
"GitHub Security Advisories",
|
||||
format!("https://github.com/advisories/{id}"),
|
||||
);
|
||||
}
|
||||
let prefix = id.split_once('-').map_or("OSV", |(prefix, _)| prefix);
|
||||
(prefix, format!("https://osv.dev/vulnerability/{id}"))
|
||||
}
|
||||
|
||||
impl CveAlert {
|
||||
/// The CVE id of the advisory: its own id, or a `CVE-` alias of a GHSA
|
||||
/// or ecosystem advisory; otherwise its own id.
|
||||
/// The CVE id of the advisory: its own id, or a CVE alias of a GHSA or
|
||||
/// ecosystem advisory; otherwise its own id.
|
||||
pub fn cve(&self) -> &str {
|
||||
if self.cve_id.starts_with("CVE-") {
|
||||
return &self.cve_id;
|
||||
primary_id(&self.cve_id, &self.aliases)
|
||||
}
|
||||
|
||||
/// The advisory's ids other than [`Self::cve`], each once: the GHSA of
|
||||
/// an alert listed under its CVE alias, further aliases.
|
||||
pub fn other_ids(&self) -> Vec<&str> {
|
||||
let primary = self.cve();
|
||||
let mut ids: Vec<&str> = Vec::with_capacity(self.aliases.len());
|
||||
for id in std::iter::once(&self.cve_id).chain(&self.aliases) {
|
||||
if id != primary && !ids.contains(&id.as_str()) {
|
||||
ids.push(id);
|
||||
}
|
||||
}
|
||||
self.aliases
|
||||
.iter()
|
||||
.find(|a| a.starts_with("CVE-"))
|
||||
.map_or(self.cve_id.as_str(), String::as_str)
|
||||
ids
|
||||
}
|
||||
|
||||
/// Whether a VEX statement settles the alert: `not_affected` or `fixed`,
|
||||
/// stated by a person, by the scan or in an imported VEX document. Such an
|
||||
/// alert raises no notification and keeps no open tracker issue; once the
|
||||
/// statement is withdrawn (back to `affected`, `under_investigation` or
|
||||
/// none) it counts again.
|
||||
pub fn is_resolved_by_vex(&self) -> bool {
|
||||
self.vex.as_ref().is_some_and(|vex| vex.status.resolves())
|
||||
}
|
||||
|
||||
pub fn new(
|
||||
@@ -183,3 +243,89 @@ impl CveAlert {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn alert(id: &str, aliases: &[&str]) -> CveAlert {
|
||||
let mut a = CveAlert::new(
|
||||
id.into(),
|
||||
"t".into(),
|
||||
"log4j-core".into(),
|
||||
"2.14.1".into(),
|
||||
CveSource::Osv,
|
||||
);
|
||||
a.aliases = aliases.iter().map(|s| s.to_string()).collect();
|
||||
a
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_not_affected_and_fixed_resolve_an_alert() {
|
||||
use crate::models::vex::{VexAssessment, VexStatus};
|
||||
let mut a = alert("CVE-2021-44228", &[]);
|
||||
assert!(!a.is_resolved_by_vex());
|
||||
for (status, resolved) in [
|
||||
(VexStatus::UnderInvestigation, false),
|
||||
(VexStatus::Affected, false),
|
||||
(VexStatus::NotAffected, true),
|
||||
(VexStatus::Fixed, true),
|
||||
] {
|
||||
a.vex = Some(VexAssessment {
|
||||
status,
|
||||
justification: None,
|
||||
impact_statement: None,
|
||||
action_statement: None,
|
||||
by: "u1".into(),
|
||||
by_name: None,
|
||||
at: Utc::now(),
|
||||
by_scan: false,
|
||||
});
|
||||
assert_eq!(a.is_resolved_by_vex(), resolved, "{status:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cve_is_strictly_recognised() {
|
||||
assert!(is_cve("CVE-2021-44228"));
|
||||
assert!(!is_cve("GHSA-jfh8-c2jp-5v3q"));
|
||||
assert!(!is_cve("CVE-21-1"));
|
||||
assert!(!is_cve("CVE-2021-12a4"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cve_is_the_primary_id_and_the_rest_are_other_ids() {
|
||||
// CVE and GHSA: the CVE, whichever of them the alert was found under.
|
||||
let ghsa = alert("GHSA-jfh8-c2jp-5v3q", &["CVE-2021-44228"]);
|
||||
assert_eq!(ghsa.cve(), "CVE-2021-44228");
|
||||
assert_eq!(ghsa.other_ids(), ["GHSA-jfh8-c2jp-5v3q"]);
|
||||
let cve = alert("CVE-2021-44228", &["GHSA-jfh8-c2jp-5v3q", "CVE-2021-44228"]);
|
||||
assert_eq!(cve.cve(), "CVE-2021-44228");
|
||||
assert_eq!(cve.other_ids(), ["GHSA-jfh8-c2jp-5v3q"]);
|
||||
// CVE only.
|
||||
let only_cve = alert("CVE-2021-44228", &[]);
|
||||
assert_eq!(only_cve.cve(), "CVE-2021-44228");
|
||||
assert!(only_cve.other_ids().is_empty());
|
||||
// GHSA only: its own id, as before.
|
||||
let only_ghsa = alert("GHSA-jfh8-c2jp-5v3q", &["A-171980069"]);
|
||||
assert_eq!(only_ghsa.cve(), "GHSA-jfh8-c2jp-5v3q");
|
||||
assert_eq!(only_ghsa.other_ids(), ["A-171980069"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn advisory_ids_name_their_database() {
|
||||
assert_eq!(
|
||||
advisory_source("CVE-2021-44228"),
|
||||
(
|
||||
"NVD",
|
||||
"https://nvd.nist.gov/vuln/detail/CVE-2021-44228".into()
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
advisory_source("GHSA-jfh8-c2jp-5v3q").0,
|
||||
"GitHub Security Advisories"
|
||||
);
|
||||
assert_eq!(advisory_source("RUSTSEC-2021-0001").0, "RUSTSEC");
|
||||
assert_eq!(advisory_source("OSV").0, "OSV");
|
||||
}
|
||||
}
|
||||
@@ -21,12 +21,17 @@ pub mod sbom;
|
||||
pub mod scan;
|
||||
pub(crate) mod serde_helpers;
|
||||
pub mod vex;
|
||||
pub mod webhook_delivery;
|
||||
pub mod werkbank;
|
||||
pub mod yocto;
|
||||
|
||||
pub use auth::{AuthInfo, SupportTenant};
|
||||
pub use chat::{ChatMessage, ChatRequest, ChatResponse, SourceReference};
|
||||
pub use credentials::Credentials;
|
||||
pub use cve::{AdvisoryRef, CveAlert, CveSource, EpssScore, Exploitation, KevEntry};
|
||||
pub use cve::{
|
||||
advisory_source, is_cve, primary_id, AdvisoryRef, CveAlert, CveSource, EpssScore, Exploitation,
|
||||
KevEntry,
|
||||
};
|
||||
pub use dast::{
|
||||
DastAuthConfig, DastEvidence, DastFinding, DastScanPhase, DastScanRun, DastScanStatus,
|
||||
DastTarget, DastTargetType, DastVulnType,
|
||||
@@ -60,14 +65,21 @@ pub use pentest::{
|
||||
pub use project::{Project, ProjectKind};
|
||||
pub use repository::ScanTrigger;
|
||||
pub use sbom::{
|
||||
ComponentHash, SbomEntry, SbomQuality, SbomQualityCheck, SbomQualityProfile, VulnRef,
|
||||
ComponentHash, InImage, InImageBasis, SbomEntry, SbomQuality, SbomQualityCheck,
|
||||
SbomQualityProfile, VulnRef, YOCTO_RECIPE_MANAGER, YOCTO_RECIPE_SOURCE,
|
||||
};
|
||||
pub use scan::{
|
||||
RunErrorCode, ScanPhase, ScanRun, ScanRunStatus, ScanStep, ScanType, SkipCode, SkippedStage,
|
||||
RunErrorCode, RunNote, ScanPhase, ScanRun, ScanRunStatus, ScanStep, ScanType, SkipCode,
|
||||
SkippedStage,
|
||||
};
|
||||
pub use vex::{VexAssessment, VexError, VexJustification, VexStatus};
|
||||
pub use webhook_delivery::{DeliveryResult, WebhookDelivery, DELIVERIES_SHOWN};
|
||||
pub use werkbank::{
|
||||
CompleteRequest, CompleteResponse, DastCollect, Executor, HeartbeatAck, HeartbeatRequest,
|
||||
InputRef, Job, JobCollect, JobRecord, JobResult, JobRuntime, JobStatus, JobType, LeaseRequest,
|
||||
LeasedJob,
|
||||
};
|
||||
pub use yocto::{
|
||||
display_codename, soon_window, LayerPin, LayerPins, PinSource, ReleaseBasis, Support,
|
||||
YoctoRelease,
|
||||
};
|
||||
@@ -643,6 +643,10 @@ pub struct OnboardedTarget {
|
||||
/// target can be skipped (#465).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub last_scan: Option<LastScan>,
|
||||
/// The layers a Yocto layer tree pins and the release they make up, from
|
||||
/// its last scan; `None` for every other target.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub layer_pins: Option<super::yocto::LayerPins>,
|
||||
/// Creation timestamp.
|
||||
#[serde(
|
||||
default = "chrono::Utc::now",
|
||||
@@ -682,6 +686,7 @@ impl OnboardedTarget {
|
||||
type_chosen: false,
|
||||
archived_at: None,
|
||||
last_scan: None,
|
||||
layer_pins: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
|
||||
@@ -10,6 +10,69 @@ pub struct VulnRef {
|
||||
/// Exploitation of the advisory's CVE (KEV, EPSS, SSVC; #493).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub exploitation: Option<super::cve::Exploitation>,
|
||||
/// Other ids of the advisory (a GHSA's `CVE-…`), as OSV lists them.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub aliases: Vec<String>,
|
||||
}
|
||||
|
||||
impl VulnRef {
|
||||
/// The id the vulnerability is listed under: its CVE when one is known
|
||||
/// (see [`super::cve::primary_id`]).
|
||||
pub fn cve(&self) -> &str {
|
||||
super::cve::primary_id(&self.id, &self.aliases)
|
||||
}
|
||||
}
|
||||
|
||||
/// The `package_manager` of a component read from a Yocto/OpenEmbedded recipe
|
||||
/// in a layer tree, without a build.
|
||||
pub const YOCTO_RECIPE_MANAGER: &str = "yocto-recipe";
|
||||
|
||||
/// Where a [`YOCTO_RECIPE_MANAGER`] component comes from, as the SBOM view,
|
||||
/// the exports and the evidence say it. Layer overrides, PACKAGECONFIG and
|
||||
/// what the image installs are not resolved, so the inventory lists more than
|
||||
/// an image contains.
|
||||
pub const YOCTO_RECIPE_SOURCE: &str = "Yocto recipe inventory (not the image SBOM)";
|
||||
|
||||
/// How a component is known to be in the product's image.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum InImageBasis {
|
||||
/// An image recipe names it (IMAGE_INSTALL, a package group it installs),
|
||||
/// read from the recipes without BitBake: what the image declares, not
|
||||
/// what a build resolved.
|
||||
Declared,
|
||||
}
|
||||
|
||||
impl InImageBasis {
|
||||
/// Its stored name (`declared`).
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Declared => "declared",
|
||||
}
|
||||
}
|
||||
|
||||
/// How the exports and the evidence say it.
|
||||
pub fn describe(self) -> &'static str {
|
||||
match self {
|
||||
Self::Declared => "In the image (declared in the recipes, not resolved by bitbake)",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The images a component is in, and how that is known.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct InImage {
|
||||
pub basis: InImageBasis,
|
||||
/// The image recipes (`pump-image`) that install it, or the
|
||||
/// configuration file that does for every image (`conf/local.conf.sample`).
|
||||
pub images: Vec<String>,
|
||||
}
|
||||
|
||||
impl InImage {
|
||||
/// `In the image (declared …): pump-image, rescue-image`.
|
||||
pub fn describe(&self) -> String {
|
||||
format!("{}: {}", self.basis.describe(), self.images.join(", "))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -47,6 +110,15 @@ pub struct SbomEntry {
|
||||
/// TR-03183-2's component creator; #508). A URL only, never a person.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub manufacturer_url: Option<String>,
|
||||
/// The CPE 2.3 name NVD knows the component by, where it has no purl an
|
||||
/// advisory database could look up (a Yocto recipe's CVE_PRODUCT).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub cpe: Option<String>,
|
||||
/// The images the component is in, where that is known (a Yocto recipe
|
||||
/// an image recipe installs); `None` when it is not, and on components
|
||||
/// stored before it was recorded.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub in_image: Option<InImage>,
|
||||
#[serde(with = "super::serde_helpers::bson_datetime")]
|
||||
pub created_at: DateTime<Utc>,
|
||||
#[serde(with = "super::serde_helpers::bson_datetime")]
|
||||
@@ -79,6 +151,8 @@ impl SbomEntry {
|
||||
hashes: Vec::new(),
|
||||
download_url: None,
|
||||
manufacturer_url: None,
|
||||
cpe: None,
|
||||
in_image: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
|
||||
@@ -33,6 +33,12 @@ pub enum ScanType {
|
||||
/// Malware signatures (ClamAV) and the committed binaries of a tree
|
||||
/// (#465).
|
||||
Malware,
|
||||
/// The recipe inventory of a Yocto layer tree: the components its BitBake
|
||||
/// recipes build (SBOM) and their known vulnerabilities.
|
||||
RecipeInventory,
|
||||
/// Security lint of a Yocto layer tree's BitBake recipes and image
|
||||
/// configuration.
|
||||
RecipeLint,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ScanType {
|
||||
@@ -55,6 +61,8 @@ impl std::fmt::Display for ScanType {
|
||||
Self::IcsProbe => write!(f, "ics_probe"),
|
||||
Self::Pentest => write!(f, "pentest"),
|
||||
Self::Malware => write!(f, "malware"),
|
||||
Self::RecipeInventory => write!(f, "recipe_inventory"),
|
||||
Self::RecipeLint => write!(f, "recipe_lint"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -152,9 +160,16 @@ pub struct ScanRun {
|
||||
pub completed_at: Option<DateTime<Utc>>,
|
||||
/// Stages the pipeline deliberately did not run (e.g. a deployment
|
||||
/// feature flag turned them off). Distinct from `error_message`: a
|
||||
/// skipped stage is not a failure.
|
||||
/// skipped stage is not a failure. Runs recorded before `notes` existed
|
||||
/// also hold informational entries here; [`ScanRun::skips`] leaves them
|
||||
/// out.
|
||||
#[serde(default)]
|
||||
pub skipped_stages: Vec<SkippedStage>,
|
||||
/// Informational entries about stages that ran: code left out of the
|
||||
/// analysis by design, findings suppressed in the sources. Never a gap in
|
||||
/// what was checked.
|
||||
#[serde(default)]
|
||||
pub notes: Vec<RunNote>,
|
||||
/// The source languages the static analysis found outside vendor code
|
||||
/// (`"c"`, `"python"`, …). A control counts as checked only if one of its
|
||||
/// rules covers one of them. Empty in runs from before it was recorded.
|
||||
@@ -171,8 +186,9 @@ pub struct ScanRun {
|
||||
pub sbom_quality: Option<super::sbom::SbomQuality>,
|
||||
}
|
||||
|
||||
/// Why a stage was skipped, stable for the dashboard to word in the reader's
|
||||
/// language. The stage's `reason` next to it is English prose for API
|
||||
/// Why a stage was skipped, or what a run note is about
|
||||
/// ([`SkipCode::is_informational`]), stable for the dashboard to word in the
|
||||
/// reader's language. The stage's `reason` next to it is English prose for API
|
||||
/// readers; neither ever carries a server path or a raw error (those go to
|
||||
/// the log).
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
@@ -229,6 +245,49 @@ pub enum SkipCode {
|
||||
UploadUnchanged,
|
||||
/// Files too large for the malware scan; `subject` lists them.
|
||||
TooLargeToScan,
|
||||
/// Findings a rule reported that comments in the scanned files suppress
|
||||
/// (`# nooelint` in a Yocto recipe), so they are not shown; `subject` is
|
||||
/// how many.
|
||||
SuppressedInSource,
|
||||
/// Names an image recipe declares it installs that are not recipes or
|
||||
/// package groups in the scanned tree (they come from layers that are not
|
||||
/// in it, such as Poky's); `subject` lists them.
|
||||
NotInTree,
|
||||
/// The Yocto release a layer tree builds could not be read from its
|
||||
/// layer pins or `LAYERSERIES_COMPAT`, so its support period was not
|
||||
/// checked.
|
||||
ReleaseUnknown,
|
||||
}
|
||||
|
||||
impl SkipCode {
|
||||
/// Whether an entry with this code only informs about a stage that ran
|
||||
/// (a run note) rather than recording something that did not run, failed
|
||||
/// or is not analysed yet (a skipped stage).
|
||||
pub fn is_informational(self) -> bool {
|
||||
// An exhaustive match, so a new code has to be classified here.
|
||||
match self {
|
||||
Self::VendorCode | Self::SuppressedInSource | Self::NotInTree => true,
|
||||
Self::FeatureDisabled
|
||||
| Self::SubmodulesNotFetched
|
||||
| Self::ToolFailed
|
||||
| Self::DependenciesUnlocked
|
||||
| Self::NotAnalysedYet
|
||||
| Self::ArchiveUnreadable
|
||||
| Self::ArtifactNotIngested
|
||||
| Self::ArchivePasswordRequired
|
||||
| Self::ArchivePasswordWrong
|
||||
| Self::FirmwareSbomFailed
|
||||
| Self::FirmwareBuildUnknown
|
||||
| Self::FirmwareUnresolved
|
||||
| Self::CveLookupIncomplete
|
||||
| Self::LfsNotFetched
|
||||
| Self::NoNewCommits
|
||||
| Self::PlatformProjectGenerated
|
||||
| Self::UploadUnchanged
|
||||
| Self::TooLargeToScan
|
||||
| Self::ReleaseUnknown => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a scan run failed, stable for the dashboard to word.
|
||||
@@ -252,7 +311,8 @@ pub enum RunErrorCode {
|
||||
pub struct SkippedStage {
|
||||
/// Stage id (`dast`, `pentest`, `ics_probe`, `plc_runtime`, …).
|
||||
pub stage: String,
|
||||
/// Always `skipped` — present so the entry reads like a stage result.
|
||||
/// `skipped`, or `note` for an informational entry (a [`RunNote`]) —
|
||||
/// present so the entry reads like a stage result.
|
||||
pub status: String,
|
||||
/// Why it was skipped, in English (`feature disabled`, …).
|
||||
pub reason: String,
|
||||
@@ -264,15 +324,29 @@ pub struct SkippedStage {
|
||||
pub subject: Option<String>,
|
||||
}
|
||||
|
||||
/// An informational entry of a scan run: the same shape as a skipped stage,
|
||||
/// with status `note` and an informational [`SkipCode`].
|
||||
pub type RunNote = SkippedStage;
|
||||
|
||||
impl SkippedStage {
|
||||
/// The reason recorded when a deployment feature flag disables a stage.
|
||||
pub const FEATURE_DISABLED: &'static str = "feature disabled";
|
||||
/// The status of a stage that did not run.
|
||||
pub const SKIPPED: &'static str = "skipped";
|
||||
/// The status of an informational entry (a [`RunNote`]).
|
||||
pub const NOTE: &'static str = "note";
|
||||
|
||||
/// A skipped `stage`, why (`code`), and the English `reason`.
|
||||
/// A skipped `stage`, why (`code`), and the English `reason`; a note
|
||||
/// when `code` is informational.
|
||||
pub fn new(stage: impl Into<String>, code: SkipCode, reason: impl Into<String>) -> Self {
|
||||
let status = if code.is_informational() {
|
||||
Self::NOTE
|
||||
} else {
|
||||
Self::SKIPPED
|
||||
};
|
||||
Self {
|
||||
stage: stage.into(),
|
||||
status: "skipped".to_string(),
|
||||
status: status.to_string(),
|
||||
reason: reason.into(),
|
||||
code: Some(code),
|
||||
subject: None,
|
||||
@@ -288,6 +362,12 @@ impl SkippedStage {
|
||||
pub fn feature_disabled(stage: impl Into<String>) -> Self {
|
||||
Self::new(stage, SkipCode::FeatureDisabled, Self::FEATURE_DISABLED)
|
||||
}
|
||||
|
||||
/// Whether this entry is a note: its code is informational. Entries
|
||||
/// without a code predate the informational codes, so they are skips.
|
||||
pub fn is_note(&self) -> bool {
|
||||
self.code.is_some_and(SkipCode::is_informational)
|
||||
}
|
||||
}
|
||||
|
||||
impl ScanRun {
|
||||
@@ -307,6 +387,7 @@ impl ScanRun {
|
||||
started_at: Utc::now(),
|
||||
completed_at: None,
|
||||
skipped_stages: Vec::new(),
|
||||
notes: Vec::new(),
|
||||
languages: Vec::new(),
|
||||
planned_phases: Vec::new(),
|
||||
sbom_quality: None,
|
||||
@@ -314,9 +395,125 @@ impl ScanRun {
|
||||
}
|
||||
}
|
||||
|
||||
impl ScanRun {
|
||||
/// The stages that did not run, without the informational entries older
|
||||
/// runs recorded among them.
|
||||
pub fn skips(&self) -> impl Iterator<Item = &SkippedStage> {
|
||||
self.skipped_stages.iter().filter(|s| !s.is_note())
|
||||
}
|
||||
|
||||
/// The run's notes, including the informational entries older runs
|
||||
/// recorded among the skipped stages.
|
||||
pub fn all_notes(&self) -> impl Iterator<Item = &RunNote> {
|
||||
self.notes
|
||||
.iter()
|
||||
.chain(self.skipped_stages.iter().filter(|s| s.is_note()))
|
||||
}
|
||||
|
||||
/// Move the informational entries older runs recorded among the skipped
|
||||
/// stages into `notes`, as status `note`, so a run read back exports
|
||||
/// both lists the way new runs record them.
|
||||
pub fn split_notes(&mut self) {
|
||||
let (notes, skips) = std::mem::take(&mut self.skipped_stages)
|
||||
.into_iter()
|
||||
.partition::<Vec<_>, _>(SkippedStage::is_note);
|
||||
self.skipped_stages = skips;
|
||||
self.notes.extend(notes.into_iter().map(|mut note| {
|
||||
note.status = SkippedStage::NOTE.to_string();
|
||||
note
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod skipped_stage_tests {
|
||||
use super::{ScanRun, ScanStep, ScanTrigger, SkippedStage};
|
||||
use super::{ScanRun, ScanStep, ScanTrigger, SkipCode, SkippedStage};
|
||||
|
||||
#[test]
|
||||
fn only_code_exclusions_and_suppressions_are_informational() {
|
||||
let notes = [
|
||||
SkipCode::VendorCode,
|
||||
SkipCode::SuppressedInSource,
|
||||
SkipCode::NotInTree,
|
||||
];
|
||||
let skips = [
|
||||
SkipCode::FeatureDisabled,
|
||||
SkipCode::SubmodulesNotFetched,
|
||||
SkipCode::ToolFailed,
|
||||
SkipCode::DependenciesUnlocked,
|
||||
SkipCode::NotAnalysedYet,
|
||||
SkipCode::ArchiveUnreadable,
|
||||
SkipCode::ArtifactNotIngested,
|
||||
SkipCode::ArchivePasswordRequired,
|
||||
SkipCode::ArchivePasswordWrong,
|
||||
SkipCode::FirmwareSbomFailed,
|
||||
SkipCode::FirmwareBuildUnknown,
|
||||
SkipCode::FirmwareUnresolved,
|
||||
SkipCode::CveLookupIncomplete,
|
||||
SkipCode::LfsNotFetched,
|
||||
SkipCode::NoNewCommits,
|
||||
SkipCode::PlatformProjectGenerated,
|
||||
SkipCode::UploadUnchanged,
|
||||
SkipCode::TooLargeToScan,
|
||||
];
|
||||
assert!(notes.iter().all(|c| c.is_informational()));
|
||||
assert!(skips.iter().all(|c| !c.is_informational()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_informational_entry_is_recorded_as_a_note() {
|
||||
let note = SkippedStage::new("sast_vendor_code", SkipCode::VendorCode, "vendor");
|
||||
assert_eq!(note.status, SkippedStage::NOTE);
|
||||
assert!(note.is_note());
|
||||
let skip = SkippedStage::new("sast", SkipCode::ToolFailed, "semgrep did not complete");
|
||||
assert_eq!(skip.status, SkippedStage::SKIPPED);
|
||||
assert!(!skip.is_note());
|
||||
}
|
||||
|
||||
/// A run recorded before notes existed, with an informational entry among
|
||||
/// its skipped stages, lists it as a note and keeps the real skips.
|
||||
#[test]
|
||||
fn an_old_run_lists_its_informational_skips_as_notes() {
|
||||
let mut run = ScanRun::new("repo".into(), ScanTrigger::Manual);
|
||||
let mut old =
|
||||
SkippedStage::new("recipe_lint_suppressed", SkipCode::SuppressedInSource, "2");
|
||||
old.status = SkippedStage::SKIPPED.to_string();
|
||||
run.skipped_stages = vec![
|
||||
SkippedStage::feature_disabled("dast"),
|
||||
old,
|
||||
SkippedStage::new("sast", SkipCode::ToolFailed, "semgrep did not complete"),
|
||||
];
|
||||
let stages = |it: Vec<&SkippedStage>| -> Vec<String> {
|
||||
it.into_iter().map(|s| s.stage.clone()).collect()
|
||||
};
|
||||
assert_eq!(stages(run.skips().collect()), ["dast", "sast"]);
|
||||
assert_eq!(
|
||||
stages(run.all_notes().collect()),
|
||||
["recipe_lint_suppressed"]
|
||||
);
|
||||
|
||||
run.split_notes();
|
||||
assert_eq!(
|
||||
stages(run.skipped_stages.iter().collect()),
|
||||
["dast", "sast"]
|
||||
);
|
||||
assert_eq!(
|
||||
stages(run.notes.iter().collect()),
|
||||
["recipe_lint_suppressed"]
|
||||
);
|
||||
assert_eq!(run.notes[0].status, SkippedStage::NOTE);
|
||||
let j = serde_json::to_value(&run).expect("serialize");
|
||||
assert_eq!(j["notes"][0]["code"], "suppressed_in_source");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_runs_without_notes_deserialize_with_none() {
|
||||
let run = ScanRun::new("repo".into(), ScanTrigger::Manual);
|
||||
let mut j = serde_json::to_value(&run).expect("serialize");
|
||||
j.as_object_mut().expect("object").remove("notes");
|
||||
let back: ScanRun = serde_json::from_value(j).expect("older document");
|
||||
assert!(back.notes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feature_disabled_reads_like_a_stage_result() {
|
||||
|
||||
@@ -24,6 +24,27 @@ pub enum VexStatus {
|
||||
Fixed,
|
||||
}
|
||||
|
||||
impl VexStatus {
|
||||
/// Whether the status settles the vulnerability for the product:
|
||||
/// `not_affected` or `fixed`.
|
||||
pub fn resolves(self) -> bool {
|
||||
match self {
|
||||
Self::NotAffected | Self::Fixed => true,
|
||||
Self::UnderInvestigation | Self::Affected => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The status as OpenVEX names it (`not_affected`).
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::UnderInvestigation => "under_investigation",
|
||||
Self::Affected => "affected",
|
||||
Self::NotAffected => "not_affected",
|
||||
Self::Fixed => "fixed",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the product is not affected (OpenVEX's five justifications).
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
@@ -35,6 +56,21 @@ pub enum VexJustification {
|
||||
InlineMitigationsAlreadyExist,
|
||||
}
|
||||
|
||||
impl VexJustification {
|
||||
/// The justification as OpenVEX names it (`vulnerable_code_not_present`).
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::ComponentNotPresent => "component_not_present",
|
||||
Self::VulnerableCodeNotPresent => "vulnerable_code_not_present",
|
||||
Self::VulnerableCodeNotInExecutePath => "vulnerable_code_not_in_execute_path",
|
||||
Self::VulnerableCodeCannotBeControlledByAdversary => {
|
||||
"vulnerable_code_cannot_be_controlled_by_adversary"
|
||||
}
|
||||
Self::InlineMitigationsAlreadyExist => "inline_mitigations_already_exist",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One VEX statement on an alert: the status, its reasons, and who made it.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct VexAssessment {
|
||||
@@ -133,4 +169,30 @@ mod tests {
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_names_are_openvex_s() {
|
||||
use VexJustification as J;
|
||||
use VexStatus as S;
|
||||
for status in [S::UnderInvestigation, S::Affected, S::NotAffected, S::Fixed] {
|
||||
assert_eq!(
|
||||
serde_json::to_value(status).ok(),
|
||||
Some(serde_json::json!(status.as_str()))
|
||||
);
|
||||
}
|
||||
for justification in [
|
||||
J::ComponentNotPresent,
|
||||
J::VulnerableCodeNotPresent,
|
||||
J::VulnerableCodeNotInExecutePath,
|
||||
J::VulnerableCodeCannotBeControlledByAdversary,
|
||||
J::InlineMitigationsAlreadyExist,
|
||||
] {
|
||||
assert_eq!(
|
||||
serde_json::to_value(justification).ok(),
|
||||
Some(serde_json::json!(justification.as_str()))
|
||||
);
|
||||
}
|
||||
assert!(S::NotAffected.resolves() && S::Fixed.resolves());
|
||||
assert!(!S::Affected.resolves() && !S::UnderInvestigation.resolves());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
//! The recent webhook deliveries of a tenant, as the target page shows them.
|
||||
//!
|
||||
//! A webhook answers its sender before the work is done (the managed Gitea
|
||||
//! source answers `202` and decides about entitlement in the background), so
|
||||
//! the sender's delivery log cannot tell a refused delivery from a handled
|
||||
//! one. Each verified delivery that asks for work is recorded here with what
|
||||
//! became of it.
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::git_source::SourceRepo;
|
||||
|
||||
/// Deliveries shown per target.
|
||||
pub const DELIVERIES_SHOWN: i64 = 20;
|
||||
|
||||
/// The longest `detail` stored, in characters: a refusal reason or an error
|
||||
/// fits, a runaway error message does not bloat the collection.
|
||||
pub const MAX_DETAIL_CHARS: usize = 300;
|
||||
|
||||
/// What became of a delivery.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum DeliveryResult {
|
||||
/// The work was done or queued.
|
||||
Handled,
|
||||
/// Not done on purpose: no entitlement, a read-only tenant.
|
||||
Refused,
|
||||
/// Not done because something broke: the database, the git source.
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// One webhook delivery.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct WebhookDelivery {
|
||||
#[serde(rename = "_id", default, skip_serializing_if = "Option::is_none")]
|
||||
pub id: Option<bson::oid::ObjectId>,
|
||||
/// When the delivery arrived.
|
||||
#[serde(with = "super::serde_helpers::bson_datetime")]
|
||||
pub received_at: DateTime<Utc>,
|
||||
/// The receiver: `gitea-source`, `gitea`, `github` or `gitlab`.
|
||||
pub source: String,
|
||||
/// The sender's event name (`push`, `repository`, `pull_request`, ...).
|
||||
pub event: String,
|
||||
pub result: DeliveryResult,
|
||||
/// What was done, or why not.
|
||||
#[serde(default)]
|
||||
pub detail: String,
|
||||
/// How long the handling took (background work included).
|
||||
#[serde(default)]
|
||||
pub elapsed_ms: u64,
|
||||
/// The target, when it is known.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub target_id: Option<String>,
|
||||
/// The repository of a managed git source. A delivery refused before its
|
||||
/// target exists has only this; the target shows it once it does.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub source_repo: Option<SourceRepo>,
|
||||
}
|
||||
|
||||
impl WebhookDelivery {
|
||||
/// A delivery received now; `detail` is cut to [`MAX_DETAIL_CHARS`].
|
||||
pub fn new(source: &str, event: &str, result: DeliveryResult, detail: &str) -> Self {
|
||||
Self {
|
||||
id: None,
|
||||
received_at: Utc::now(),
|
||||
source: source.to_string(),
|
||||
event: event.to_string(),
|
||||
result,
|
||||
detail: clip(detail, MAX_DETAIL_CHARS),
|
||||
elapsed_ms: 0,
|
||||
target_id: None,
|
||||
source_repo: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` cut to at most `max` characters (never inside a character), with
|
||||
/// an ellipsis when it was cut.
|
||||
fn clip(text: &str, max: usize) -> String {
|
||||
match text.char_indices().nth(max) {
|
||||
// `nth(max)` is the first character past the limit: keep max - 1 and
|
||||
// the ellipsis, so the result is exactly `max` characters.
|
||||
Some(_) => {
|
||||
let keep: String = text.chars().take(max.saturating_sub(1)).collect();
|
||||
format!("{keep}…")
|
||||
}
|
||||
None => text.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_short_detail_is_kept_as_is() {
|
||||
let d = WebhookDelivery::new("gitea", "push", DeliveryResult::Handled, "scan queued");
|
||||
assert_eq!(d.detail, "scan queued");
|
||||
assert_eq!(d.elapsed_ms, 0);
|
||||
assert!(d.target_id.is_none() && d.source_repo.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_detail_is_clipped_on_a_character_boundary() {
|
||||
let long = "ä".repeat(MAX_DETAIL_CHARS + 50);
|
||||
let d = WebhookDelivery::new("gitea", "push", DeliveryResult::Failed, &long);
|
||||
assert_eq!(d.detail.chars().count(), MAX_DETAIL_CHARS);
|
||||
assert!(d.detail.ends_with('…'));
|
||||
// exactly at the limit: nothing cut
|
||||
let exact = "x".repeat(MAX_DETAIL_CHARS);
|
||||
assert_eq!(clip(&exact, MAX_DETAIL_CHARS), exact);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn results_are_snake_case_and_round_trip() {
|
||||
let mut d = WebhookDelivery::new("gitea-source", "push", DeliveryResult::Refused, "no");
|
||||
d.source_repo = Some(SourceRepo {
|
||||
base_url: "https://git.example".into(),
|
||||
repo_id: 7,
|
||||
full_name: "acme/fw".into(),
|
||||
});
|
||||
let json = serde_json::to_value(&d).unwrap();
|
||||
assert_eq!(json["result"], "refused");
|
||||
assert!(json.get("target_id").is_none());
|
||||
let back: WebhookDelivery = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(back.source_repo, d.source_repo);
|
||||
assert_eq!(back.result, DeliveryResult::Refused);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
//! What a Yocto / OpenEmbedded layer tree pins: the layers it builds from
|
||||
//! (kas files, `repo` manifests, git submodules) and the Yocto release they
|
||||
//! make up. Read without fetching anything and without a build (tier 1).
|
||||
|
||||
use chrono::{Months, NaiveDate};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Where a layer pin is declared.
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PinSource {
|
||||
/// A kas project file (`repos:`), with its local includes.
|
||||
Kas,
|
||||
/// A `repo` tool manifest (`<project>`).
|
||||
RepoManifest,
|
||||
/// A git submodule (`.gitmodules`, and the commit the tree records).
|
||||
GitSubmodule,
|
||||
}
|
||||
|
||||
/// One layer repository the tree builds from, as its configuration pins it.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct LayerPin {
|
||||
/// The repository's name in the file (kas repo key, manifest project
|
||||
/// name, submodule name).
|
||||
pub name: String,
|
||||
/// Where it is declared.
|
||||
pub source: PinSource,
|
||||
/// The declaring file, relative to the tree.
|
||||
pub file: String,
|
||||
/// The repository URL; `None` for the tree's own repository (a kas repo
|
||||
/// without `url`).
|
||||
#[serde(default)]
|
||||
pub url: Option<String>,
|
||||
/// The branch, tag or refspec named, as written (`refs/heads/` dropped).
|
||||
#[serde(default)]
|
||||
pub branch: Option<String>,
|
||||
/// The commit it is pinned to.
|
||||
#[serde(default)]
|
||||
pub commit: Option<String>,
|
||||
}
|
||||
|
||||
/// What the Yocto release of the tree was read from.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum ReleaseBasis {
|
||||
/// The branch or tag a pin of Poky, OpenEmbedded-Core or
|
||||
/// meta-openembedded names.
|
||||
Pin {
|
||||
/// The pin's name.
|
||||
name: String,
|
||||
/// The branch or tag it names.
|
||||
branch: String,
|
||||
},
|
||||
/// `LAYERSERIES_COMPAT_core` of the OpenEmbedded-Core layer in the tree.
|
||||
CoreLayer,
|
||||
/// The newest release every one of the customer's layers declares in
|
||||
/// `LAYERSERIES_COMPAT_*`.
|
||||
LayerCompat,
|
||||
}
|
||||
|
||||
/// The Yocto release a tree builds and its support period.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct YoctoRelease {
|
||||
/// The codename, lower case (`scarthgap`).
|
||||
pub codename: String,
|
||||
/// The Yocto Project version (`5.0`).
|
||||
pub version: String,
|
||||
/// A long term support release.
|
||||
pub lts: bool,
|
||||
/// The day its support ends (or ended).
|
||||
pub end_of_life: NaiveDate,
|
||||
/// What it was read from.
|
||||
pub basis: ReleaseBasis,
|
||||
/// The file it was read from, relative to the tree.
|
||||
pub file: String,
|
||||
}
|
||||
|
||||
/// A codename as written in prose: `dunfell` -> `Dunfell`.
|
||||
pub fn display_codename(codename: &str) -> String {
|
||||
let mut chars = codename.chars();
|
||||
chars
|
||||
.next()
|
||||
.map(|c| c.to_uppercase().chain(chars).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// How far ahead the end of life of a release counts as soon: six months for
|
||||
/// a long term support release, two for any other. A non-LTS release is
|
||||
/// supported for about seven months, so a six-month window would warn from
|
||||
/// its first weeks.
|
||||
pub const fn soon_window(lts: bool) -> Months {
|
||||
if lts {
|
||||
Months::new(6)
|
||||
} else {
|
||||
Months::new(2)
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a release's support stands on a day.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Support {
|
||||
/// Supported for longer than its [`soon_window`].
|
||||
Supported,
|
||||
/// Its support ends within its [`soon_window`].
|
||||
EndsSoon,
|
||||
/// Its support has ended (after its last day).
|
||||
Ended,
|
||||
}
|
||||
|
||||
impl YoctoRelease {
|
||||
/// Where its support stands on `today`.
|
||||
pub fn support(&self, today: NaiveDate) -> Support {
|
||||
if self.end_of_life < today {
|
||||
Support::Ended
|
||||
} else if today
|
||||
.checked_add_months(soon_window(self.lts))
|
||||
.is_none_or(|horizon| self.end_of_life <= horizon)
|
||||
{
|
||||
Support::EndsSoon
|
||||
} else {
|
||||
Support::Supported
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The layer pins of a Yocto target and the release they make up, from its
|
||||
/// last scan.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct LayerPins {
|
||||
/// Every pin, in the order the files declare them.
|
||||
#[serde(default)]
|
||||
pub pins: Vec<LayerPin>,
|
||||
/// The release, when one could be read.
|
||||
#[serde(default)]
|
||||
pub release: Option<YoctoRelease>,
|
||||
/// Includes that were not read: remote ones (another repository, a URL)
|
||||
/// and local ones that are missing or leave the tree.
|
||||
#[serde(default)]
|
||||
pub unread_includes: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn release(end_of_life: NaiveDate, lts: bool) -> YoctoRelease {
|
||||
YoctoRelease {
|
||||
codename: "scarthgap".into(),
|
||||
version: "5.0".into(),
|
||||
lts,
|
||||
end_of_life,
|
||||
basis: ReleaseBasis::CoreLayer,
|
||||
file: "conf/layer.conf".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codenames_are_capitalised() {
|
||||
assert_eq!(display_codename("dunfell"), "Dunfell");
|
||||
assert_eq!(display_codename(""), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lts_support_ends_soon_within_six_months_and_ends_after_its_last_day() {
|
||||
let date = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).expect("date");
|
||||
let scarthgap = release(date(2028, 4, 30), true);
|
||||
assert_eq!(scarthgap.support(date(2026, 10, 9)), Support::Supported);
|
||||
assert_eq!(scarthgap.support(date(2027, 10, 29)), Support::Supported);
|
||||
assert_eq!(scarthgap.support(date(2027, 10, 30)), Support::EndsSoon);
|
||||
assert_eq!(scarthgap.support(date(2028, 4, 30)), Support::EndsSoon);
|
||||
assert_eq!(scarthgap.support(date(2028, 5, 1)), Support::Ended);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_releases_end_soon_within_two_months() {
|
||||
let date = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).expect("date");
|
||||
// Whinlatter (5.3): released 2025-12-15, supported until 2026-06-15.
|
||||
let whinlatter = release(date(2026, 6, 15), false);
|
||||
assert_eq!(whinlatter.support(date(2025, 12, 20)), Support::Supported);
|
||||
assert_eq!(whinlatter.support(date(2026, 4, 14)), Support::Supported);
|
||||
assert_eq!(whinlatter.support(date(2026, 4, 15)), Support::EndsSoon);
|
||||
assert_eq!(whinlatter.support(date(2026, 6, 16)), Support::Ended);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_pins_round_trip_through_bson() {
|
||||
let pins = LayerPins {
|
||||
pins: vec![LayerPin {
|
||||
name: "poky".into(),
|
||||
source: PinSource::Kas,
|
||||
file: "kas.yml".into(),
|
||||
url: Some("https://git.yoctoproject.org/poky".into()),
|
||||
branch: Some("dunfell".into()),
|
||||
commit: Some("a".repeat(40)),
|
||||
}],
|
||||
release: Some(YoctoRelease {
|
||||
codename: "dunfell".into(),
|
||||
version: "3.1".into(),
|
||||
lts: true,
|
||||
end_of_life: NaiveDate::from_ymd_opt(2024, 4, 30).expect("date"),
|
||||
basis: ReleaseBasis::Pin {
|
||||
name: "poky".into(),
|
||||
branch: "dunfell".into(),
|
||||
},
|
||||
file: "kas.yml".into(),
|
||||
}),
|
||||
unread_includes: vec!["https://x/y.yml".into()],
|
||||
};
|
||||
let b = bson::to_bson(&pins).expect("serialize");
|
||||
assert_eq!(bson::from_bson::<LayerPins>(b).expect("deserialize"), pins);
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,19 @@ impl Purl {
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` percent-encoded for a purl component or qualifier value: every byte
|
||||
/// but the unreserved ones (`A-Z a-z 0-9 . - _ ~`) as `%XX`.
|
||||
pub fn encode(text: &str) -> String {
|
||||
text.bytes()
|
||||
.map(|b| match b {
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'.' | b'-' | b'_' | b'~' => {
|
||||
(b as char).to_string()
|
||||
}
|
||||
_ => format!("%{b:02X}"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `text` with its `%XX` escapes decoded; an invalid escape is kept as is.
|
||||
fn decode(text: &str) -> String {
|
||||
let bytes = text.as_bytes();
|
||||
@@ -92,6 +105,17 @@ fn decode(text: &str) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_encoded_value_parses_back_to_itself() {
|
||||
let url = "https://busybox.net/downloads/busybox-1.35.0.tar.bz2";
|
||||
let purl = format!("pkg:generic/busybox@1.35.0?download_url={}", encode(url));
|
||||
assert!(!encode(url).contains(['/', ':']));
|
||||
assert_eq!(
|
||||
Purl::parse(&purl).and_then(|p| p.qualifier("download_url").map(String::from)),
|
||||
Some(url.to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parts_are_read_and_decoded() {
|
||||
let p = Purl::parse("pkg:npm/%40angular/core@16.2.0").unwrap();
|
||||
|
||||
@@ -8,8 +8,11 @@
|
||||
//! packages, a dependency graph whose completeness is stated, and licences as
|
||||
//! the suppliers declare them.
|
||||
|
||||
use crate::models::{ComponentHash, SbomEntry};
|
||||
use crate::models::{
|
||||
advisory_source, is_cve, ComponentHash, SbomEntry, YOCTO_RECIPE_MANAGER, YOCTO_RECIPE_SOURCE,
|
||||
};
|
||||
use crate::purl::Purl;
|
||||
use crate::spdx_license;
|
||||
|
||||
/// The `bom-ref` of a component, which a VEX statement refers to: its purl,
|
||||
/// or `<package manager>:<name>@<version>` without one.
|
||||
@@ -23,48 +26,19 @@ pub fn component_ref(entry: &SbomEntry) -> String {
|
||||
/// The identifier of the product (the target) the SBOM and the VEX describe:
|
||||
/// `pkg:generic/<name>`, the name percent-encoded as a purl requires.
|
||||
pub fn product_ref(subject: &str) -> String {
|
||||
let encoded: String = subject
|
||||
.bytes()
|
||||
.map(|b| match b {
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'.' | b'-' | b'_' | b'~' => {
|
||||
(b as char).to_string()
|
||||
}
|
||||
_ => format!("%{b:02X}"),
|
||||
})
|
||||
.collect();
|
||||
format!("pkg:generic/{encoded}")
|
||||
format!("pkg:generic/{}", crate::purl::encode(subject))
|
||||
}
|
||||
|
||||
/// The SPDX license ids CycloneDX accepts as `license.id` (its own copy of
|
||||
/// the SPDX list).
|
||||
fn spdx_ids() -> &'static std::collections::HashSet<String> {
|
||||
static IDS: std::sync::LazyLock<std::collections::HashSet<String>> =
|
||||
std::sync::LazyLock::new(|| {
|
||||
serde_json::from_str::<serde_json::Value>(include_str!("../schemas/spdx.schema.json"))
|
||||
.ok()
|
||||
.and_then(|schema| {
|
||||
schema["enum"].as_array().map(|ids| {
|
||||
ids.iter()
|
||||
.filter_map(|id| id.as_str().map(str::to_string))
|
||||
.collect()
|
||||
})
|
||||
})
|
||||
.unwrap_or_default()
|
||||
});
|
||||
&IDS
|
||||
}
|
||||
|
||||
/// A license as CycloneDX writes it: an SPDX id it knows, an SPDX expression
|
||||
/// (`MIT OR Apache-2.0`), or a named license. It is the license the supplier
|
||||
/// declares (registry or lockfile metadata): Prüfwerk has not concluded it.
|
||||
/// A license as CycloneDX writes it: an SPDX id, an SPDX expression
|
||||
/// (`MIT OR Apache-2.0`), or a named license. A name or URL of a license
|
||||
/// SPDX lists becomes its id ([`spdx_license::normalise`], BSI TR-03183-2).
|
||||
/// It is the license the supplier declares (registry or lockfile metadata):
|
||||
/// Prüfwerk has not concluded it.
|
||||
fn license_choice(license: &str) -> serde_json::Value {
|
||||
let license = license.trim();
|
||||
if spdx_ids().contains(license) {
|
||||
let license = spdx_license::normalise(license);
|
||||
if spdx_license::canonical_id(&license) == Some(&*license) {
|
||||
serde_json::json!([{ "license": { "id": license, "acknowledgement": "declared" } }])
|
||||
} else if [" OR ", " AND ", " WITH "]
|
||||
.iter()
|
||||
.any(|op| license.contains(op))
|
||||
{
|
||||
} else if spdx_license::has_operator(&license) {
|
||||
serde_json::json!([{ "expression": license, "acknowledgement": "declared" }])
|
||||
} else {
|
||||
serde_json::json!([{ "license": { "name": license, "acknowledgement": "declared" } }])
|
||||
@@ -111,6 +85,46 @@ fn bsi_properties(purl: &Purl) -> Option<serde_json::Value> {
|
||||
]))
|
||||
}
|
||||
|
||||
/// The property that says where a component comes from when its source
|
||||
/// limits what it proves: a Yocto recipe is in the layer tree, not
|
||||
/// necessarily in the image.
|
||||
const SOURCE_PROPERTY: &str = "pruefwerk:component:source";
|
||||
|
||||
/// The property naming the images a component is in and how that is known
|
||||
/// (`declared: pump-image`).
|
||||
const IN_IMAGE_PROPERTY: &str = "pruefwerk:component:in_image";
|
||||
|
||||
/// Where `entry` comes from, when the reader must know it to weigh it.
|
||||
fn source_note(entry: &SbomEntry) -> Option<&'static str> {
|
||||
(entry.package_manager == YOCTO_RECIPE_MANAGER).then_some(YOCTO_RECIPE_SOURCE)
|
||||
}
|
||||
|
||||
/// The CycloneDX properties saying where `entry` comes from and which images
|
||||
/// it is in.
|
||||
fn provenance_properties(entry: &SbomEntry) -> Vec<serde_json::Value> {
|
||||
let source = source_note(entry)
|
||||
.map(|source| serde_json::json!({ "name": SOURCE_PROPERTY, "value": source }));
|
||||
let in_image = entry.in_image.as_ref().map(|in_image| {
|
||||
let value = format!(
|
||||
"{}: {}",
|
||||
in_image.basis.as_str(),
|
||||
in_image.images.join(", ")
|
||||
);
|
||||
serde_json::json!({ "name": IN_IMAGE_PROPERTY, "value": value })
|
||||
});
|
||||
source.into_iter().chain(in_image).collect()
|
||||
}
|
||||
|
||||
/// The SPDX package comment saying the same: the source, and the images.
|
||||
fn provenance_comment(entry: &SbomEntry) -> Option<String> {
|
||||
let notes: Vec<String> = source_note(entry)
|
||||
.map(str::to_string)
|
||||
.into_iter()
|
||||
.chain(entry.in_image.as_ref().map(|in_image| in_image.describe()))
|
||||
.collect();
|
||||
(!notes.is_empty()).then(|| notes.join(". "))
|
||||
}
|
||||
|
||||
/// A CycloneDX severity from an advisory's (`HIGH`, `MODERATE`, `critical`).
|
||||
pub fn cdx_severity(severity: &str) -> &'static str {
|
||||
match severity.trim().to_ascii_lowercase().as_str() {
|
||||
@@ -158,6 +172,16 @@ pub fn cdx_components(entries: &[SbomEntry]) -> Vec<serde_json::Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(cpe) = &e.cpe {
|
||||
comp["cpe"] = serde_json::Value::String(cpe.clone());
|
||||
}
|
||||
let provenance = provenance_properties(e);
|
||||
if !provenance.is_empty() {
|
||||
match comp["properties"].as_array_mut() {
|
||||
Some(properties) => properties.extend(provenance),
|
||||
None => comp["properties"] = serde_json::Value::Array(provenance),
|
||||
}
|
||||
}
|
||||
if let Some(license) = e.license.as_deref().filter(|l| !l.trim().is_empty()) {
|
||||
comp["licenses"] = license_choice(license);
|
||||
}
|
||||
@@ -246,56 +270,98 @@ fn cdx_dependencies(doc: &mut serde_json::Value, components: &[serde_json::Value
|
||||
}]);
|
||||
}
|
||||
|
||||
/// The identification of a CycloneDX vulnerability known as `primary` and
|
||||
/// `others`: `id` and `source` of the primary id (NVD for a CVE, else
|
||||
/// `source`, the scanner that found it), the other ids as `references` to
|
||||
/// their databases.
|
||||
pub fn cdx_vulnerability(primary: &str, others: &[&str], source: &str) -> serde_json::Value {
|
||||
let mut v = if is_cve(primary) {
|
||||
let (name, url) = advisory_source(primary);
|
||||
serde_json::json!({ "id": primary, "source": { "name": name, "url": url } })
|
||||
} else {
|
||||
serde_json::json!({ "id": primary, "source": { "name": source } })
|
||||
};
|
||||
if !others.is_empty() {
|
||||
v["references"] = others
|
||||
.iter()
|
||||
.map(|id| {
|
||||
let (name, url) = advisory_source(id);
|
||||
serde_json::json!({ "id": id, "source": { "name": name, "url": url } })
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// One vulnerability of a CycloneDX SBOM: its primary id, its other ids,
|
||||
/// the source and severity it was first found with, and the components it
|
||||
/// affects.
|
||||
struct SbomVulnerability<'a> {
|
||||
id: &'a str,
|
||||
others: Vec<&'a str>,
|
||||
source: &'a str,
|
||||
severity: Option<&'a str>,
|
||||
affects: Vec<String>,
|
||||
}
|
||||
|
||||
/// A CycloneDX 1.6 document for `entries`, named after `subject`. The known
|
||||
/// vulnerabilities of the components are listed at the top level, each
|
||||
/// naming the components it affects by `bom-ref` (CycloneDX keeps them out of
|
||||
/// the components).
|
||||
/// the components). A vulnerability is listed under its CVE when one is
|
||||
/// known, with its GitHub advisory as a reference.
|
||||
pub fn cyclonedx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
|
||||
let mut doc = cdx_frame(subject, entries);
|
||||
let components = cdx_components(entries);
|
||||
cdx_dependencies(&mut doc, &components);
|
||||
doc["components"] = serde_json::Value::Array(components);
|
||||
// One vulnerability per advisory, affecting every component it was
|
||||
// found in.
|
||||
let mut vulns: Vec<(String, String, Option<String>, Vec<String>)> = Vec::new();
|
||||
// One vulnerability per CVE (or advisory without one), affecting every
|
||||
// component it was found in, by whichever scanner and id.
|
||||
let mut vulns: Vec<SbomVulnerability<'_>> = Vec::new();
|
||||
for e in entries {
|
||||
for v in &e.known_vulnerabilities {
|
||||
let reference = component_ref(e);
|
||||
match vulns
|
||||
.iter_mut()
|
||||
.find(|(id, source, ..)| *id == v.id && *source == v.source)
|
||||
{
|
||||
Some((.., refs)) => {
|
||||
if !refs.contains(&reference) {
|
||||
refs.push(reference);
|
||||
}
|
||||
let id = v.cve();
|
||||
let i = match vulns.iter().position(|known| known.id == id) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
vulns.push(SbomVulnerability {
|
||||
id,
|
||||
others: Vec::new(),
|
||||
source: &v.source,
|
||||
severity: None,
|
||||
affects: Vec::new(),
|
||||
});
|
||||
vulns.len() - 1
|
||||
}
|
||||
None => vulns.push((
|
||||
v.id.clone(),
|
||||
v.source.clone(),
|
||||
v.severity.clone(),
|
||||
vec![reference],
|
||||
)),
|
||||
};
|
||||
let known = &mut vulns[i];
|
||||
for other in std::iter::once(&v.id).chain(&v.aliases) {
|
||||
if other != id && !known.others.contains(&other.as_str()) {
|
||||
known.others.push(other);
|
||||
}
|
||||
}
|
||||
known.severity = known.severity.or(v.severity.as_deref());
|
||||
let reference = component_ref(e);
|
||||
if !known.affects.contains(&reference) {
|
||||
known.affects.push(reference);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !vulns.is_empty() {
|
||||
doc["vulnerabilities"] = serde_json::Value::Array(
|
||||
vulns
|
||||
.into_iter()
|
||||
.map(|(id, source, severity, refs)| {
|
||||
let mut v = serde_json::json!({
|
||||
"id": id,
|
||||
"source": { "name": source },
|
||||
"affects": refs.into_iter().map(|r| serde_json::json!({ "ref": r })).collect::<Vec<_>>(),
|
||||
});
|
||||
if let Some(severity) = severity {
|
||||
v["ratings"] = serde_json::json!([{ "severity": cdx_severity(&severity) }]);
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
doc["vulnerabilities"] = vulns
|
||||
.into_iter()
|
||||
.map(|known| {
|
||||
let mut v = cdx_vulnerability(known.id, &known.others, known.source);
|
||||
v["affects"] = known
|
||||
.affects
|
||||
.into_iter()
|
||||
.map(|r| serde_json::json!({ "ref": r }))
|
||||
.collect();
|
||||
if let Some(severity) = known.severity {
|
||||
v["ratings"] = serde_json::json!([{ "severity": cdx_severity(severity) }]);
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
doc
|
||||
}
|
||||
@@ -306,18 +372,45 @@ pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, e)| {
|
||||
serde_json::json!({
|
||||
// The license is what the supplier declares; nothing is
|
||||
// concluded without a license review of our own. SPDX takes only
|
||||
// an expression of listed ids; another license is NOASSERTION,
|
||||
// its text kept as a comment.
|
||||
let raw = e
|
||||
.license
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty());
|
||||
let license = raw
|
||||
.map(spdx_license::normalise)
|
||||
.filter(|l| spdx_license::is_spdx_expression(l));
|
||||
let mut package = serde_json::json!({
|
||||
"SPDXID": format!("SPDXRef-Package-{i}"),
|
||||
"name": e.name,
|
||||
"versionInfo": e.version,
|
||||
"downloadLocation": "NOASSERTION",
|
||||
"licenseConcluded": e.license.as_deref().unwrap_or("NOASSERTION"),
|
||||
"licenseConcluded": "NOASSERTION",
|
||||
"licenseDeclared": 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(),
|
||||
})
|
||||
});
|
||||
if let (Some(raw), None) = (raw, &license) {
|
||||
package["licenseComments"] = serde_json::Value::String(format!("Declared: {raw}"));
|
||||
}
|
||||
if let (Some(cpe), Some(refs)) = (&e.cpe, package["externalRefs"].as_array_mut()) {
|
||||
refs.push(serde_json::json!({
|
||||
"referenceCategory": "SECURITY",
|
||||
"referenceType": "cpe23Type",
|
||||
"referenceLocator": cpe,
|
||||
}));
|
||||
}
|
||||
if let Some(comment) = provenance_comment(e) {
|
||||
package["comment"] = serde_json::Value::String(comment);
|
||||
}
|
||||
package
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -334,6 +427,7 @@ pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::models::{InImage, InImageBasis};
|
||||
|
||||
#[test]
|
||||
fn both_formats_list_every_component() {
|
||||
@@ -349,4 +443,119 @@ mod tests {
|
||||
assert_eq!(spdx["spdxVersion"], "SPDX-2.3");
|
||||
assert_eq!(spdx["packages"][0]["versionInfo"], "2.1.2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_license_names_are_exported_as_spdx_ids() {
|
||||
let entries: Vec<SbomEntry> = [
|
||||
"The Apache Software License, Version 2.0",
|
||||
"https://opensource.org/licenses/MIT",
|
||||
"Custom Pump License",
|
||||
"MIT OR Apache-2.0",
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, license)| {
|
||||
let mut e = SbomEntry::new("t".into(), format!("c{i}"), "1".into(), "maven".into());
|
||||
e.license = Some(license.into());
|
||||
e
|
||||
})
|
||||
.collect();
|
||||
|
||||
let cdx = cyclonedx(&entries, "t");
|
||||
let licenses = |i: usize| &cdx["components"][i]["licenses"][0];
|
||||
assert_eq!(licenses(0)["license"]["id"], "Apache-2.0");
|
||||
assert!(licenses(0)["license"].get("name").is_none());
|
||||
assert_eq!(licenses(1)["license"]["id"], "MIT");
|
||||
assert_eq!(licenses(2)["license"]["name"], "Custom Pump License");
|
||||
assert!(licenses(2)["license"].get("id").is_none());
|
||||
assert_eq!(licenses(3)["expression"], "MIT OR Apache-2.0");
|
||||
|
||||
let spdx = spdx(&entries, "t");
|
||||
let package = |i: usize| &spdx["packages"][i];
|
||||
for i in 0..4 {
|
||||
assert_eq!(package(i)["licenseConcluded"], "NOASSERTION");
|
||||
}
|
||||
assert_eq!(package(0)["licenseDeclared"], "Apache-2.0");
|
||||
assert_eq!(package(1)["licenseDeclared"], "MIT");
|
||||
assert_eq!(package(2)["licenseDeclared"], "NOASSERTION");
|
||||
assert_eq!(
|
||||
package(2)["licenseComments"],
|
||||
"Declared: Custom Pump License"
|
||||
);
|
||||
assert_eq!(package(3)["licenseDeclared"], "MIT OR Apache-2.0");
|
||||
assert!(package(3).get("licenseComments").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_yocto_recipe_says_it_is_not_the_image_sbom_in_both_formats() {
|
||||
let mut recipe = SbomEntry::new(
|
||||
"t".into(),
|
||||
"busybox".into(),
|
||||
"1.35.0".into(),
|
||||
YOCTO_RECIPE_MANAGER.into(),
|
||||
);
|
||||
recipe.purl = Some("pkg:generic/busybox@1.35.0".into());
|
||||
recipe.cpe = Some("cpe:2.3:a:*:busybox:1.35.0:*:*:*:*:*:*:*".into());
|
||||
let other = SbomEntry::new("t".into(), "lwIP".into(), "2.1.2".into(), "embedded".into());
|
||||
let entries = [recipe, other];
|
||||
|
||||
let cdx = cyclonedx(&entries, "t");
|
||||
let component = &cdx["components"][0];
|
||||
assert_eq!(component["cpe"], "cpe:2.3:a:*:busybox:1.35.0:*:*:*:*:*:*:*");
|
||||
assert_eq!(
|
||||
component["properties"],
|
||||
serde_json::json!([{ "name": SOURCE_PROPERTY, "value": YOCTO_RECIPE_SOURCE }])
|
||||
);
|
||||
assert!(cdx["components"][1].get("properties").is_none());
|
||||
|
||||
let spdx = spdx(&entries, "t");
|
||||
let package = &spdx["packages"][0];
|
||||
assert_eq!(package["comment"], YOCTO_RECIPE_SOURCE);
|
||||
assert_eq!(package["externalRefs"][1]["referenceType"], "cpe23Type");
|
||||
assert!(spdx["packages"][1].get("comment").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recipe_an_image_installs_says_so_in_both_formats() {
|
||||
let mut recipe = SbomEntry::new(
|
||||
"t".into(),
|
||||
"busybox".into(),
|
||||
"1.35.0".into(),
|
||||
YOCTO_RECIPE_MANAGER.into(),
|
||||
);
|
||||
recipe.in_image = Some(InImage {
|
||||
basis: InImageBasis::Declared,
|
||||
images: vec!["pump-image".into(), "rescue-image".into()],
|
||||
});
|
||||
let inventory_only = SbomEntry::new(
|
||||
"t".into(),
|
||||
"pump-fw".into(),
|
||||
"1.0".into(),
|
||||
YOCTO_RECIPE_MANAGER.into(),
|
||||
);
|
||||
let entries = [recipe, inventory_only];
|
||||
|
||||
let cdx = cyclonedx(&entries, "t");
|
||||
assert_eq!(
|
||||
cdx["components"][0]["properties"],
|
||||
serde_json::json!([
|
||||
{ "name": SOURCE_PROPERTY, "value": YOCTO_RECIPE_SOURCE },
|
||||
{ "name": IN_IMAGE_PROPERTY, "value": "declared: pump-image, rescue-image" },
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
cdx["components"][1]["properties"],
|
||||
serde_json::json!([{ "name": SOURCE_PROPERTY, "value": YOCTO_RECIPE_SOURCE }])
|
||||
);
|
||||
|
||||
let spdx = spdx(&entries, "t");
|
||||
assert_eq!(
|
||||
spdx["packages"][0]["comment"],
|
||||
format!(
|
||||
"{YOCTO_RECIPE_SOURCE}. In the image (declared in the recipes, not resolved \
|
||||
by bitbake): pump-image, rescue-image"
|
||||
)
|
||||
);
|
||||
assert_eq!(spdx["packages"][1]["comment"], YOCTO_RECIPE_SOURCE);
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,21 @@ const CVE_FROM_IMAGE: &str =
|
||||
"CVE matching needs an SBOM, and none is extracted from a firmware image yet";
|
||||
const CONTAINER_IMAGES: &str =
|
||||
"container images are not scanned yet: only the sources that build them are";
|
||||
/// Why a Yocto image has no SBOM or CVE match yet: that needs the build's
|
||||
/// artefacts (tier 2), not the layer tree.
|
||||
const YOCTO_IMAGE_SBOM: &str = "a Yocto image SBOM needs build artefacts (SPDX/manifest), planned";
|
||||
const YOCTO_IMAGE_CVE: &str =
|
||||
"CVE matching for a Yocto image needs build artefacts (SPDX/manifest), planned";
|
||||
/// Why the firmware SBOM stage passes over a Yocto layer tree: Firmwerk forms
|
||||
/// no build plan from BitBake recipes. The agent records it with this text.
|
||||
pub const YOCTO_BUILD_PLANNED: &str =
|
||||
"Yocto build analysis is planned (tier 2): a layer tree is not a firmware build";
|
||||
|
||||
/// The recipe inventory of a Yocto layer tree (SBOM and CVEs from its BitBake
|
||||
/// recipes): `Some(reason)` while no stage runs it, `None` once one does.
|
||||
const RECIPE_INVENTORY: Option<&str> = None;
|
||||
/// Recipe lint (oelint-adv and our own rules) over a Yocto layer tree, likewise.
|
||||
const RECIPE_LINT: Option<&str> = None;
|
||||
|
||||
/// What an artifact a scan needs in order to run.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -216,7 +231,7 @@ pub fn rules_for(target_type: TargetType) -> Vec<ScanRule> {
|
||||
/// The rules specific to a target type (see [`rules_for`], which adds the rules
|
||||
/// that apply to every target).
|
||||
fn target_rules(target_type: TargetType) -> Vec<ScanRule> {
|
||||
use ArtifactRequirement::{Firmware, HttpUrl, Mobile, Plc, RunningUrl};
|
||||
use ArtifactRequirement::{Code, Firmware, HttpUrl, Mobile, Plc, RunningUrl};
|
||||
match target_type {
|
||||
TargetType::WebApp | TargetType::BackendService => {
|
||||
let mut r = sast_umbrella();
|
||||
@@ -263,6 +278,26 @@ fn target_rules(target_type: TargetType) -> Vec<ScanRule> {
|
||||
}
|
||||
TargetType::EmbeddedLinuxYocto => {
|
||||
let mut r = sast_umbrella();
|
||||
// Tier 1: the layer tree itself. Each turns on by setting its
|
||||
// constant to `None`.
|
||||
r.push(ScanRule {
|
||||
unavailable: RECIPE_INVENTORY,
|
||||
..ScanRule::new(
|
||||
ScanType::RecipeInventory,
|
||||
true,
|
||||
"Recipe inventory (SBOM and CVEs) from the layers' BitBake recipes",
|
||||
Code,
|
||||
)
|
||||
});
|
||||
r.push(ScanRule {
|
||||
unavailable: RECIPE_LINT,
|
||||
..ScanRule::new(
|
||||
ScanType::RecipeLint,
|
||||
true,
|
||||
"Security lint of the BitBake recipes and image configuration",
|
||||
Code,
|
||||
)
|
||||
});
|
||||
r.push(ScanRule::unavailable(
|
||||
ScanType::FirmwareStatic,
|
||||
"EMBA / binwalk static analysis of the image",
|
||||
@@ -271,15 +306,15 @@ fn target_rules(target_type: TargetType) -> Vec<ScanRule> {
|
||||
));
|
||||
r.push(ScanRule::unavailable(
|
||||
ScanType::Sbom,
|
||||
"SBOM from image layers / recipes",
|
||||
"SBOM from the image's build artefacts",
|
||||
Firmware,
|
||||
SBOM_FROM_IMAGE,
|
||||
YOCTO_IMAGE_SBOM,
|
||||
));
|
||||
r.push(ScanRule::unavailable(
|
||||
ScanType::Cve,
|
||||
"Match image components against known CVEs",
|
||||
Firmware,
|
||||
CVE_FROM_IMAGE,
|
||||
YOCTO_IMAGE_CVE,
|
||||
));
|
||||
r.push(ScanRule::new(
|
||||
ScanType::Dast,
|
||||
@@ -348,7 +383,8 @@ fn target_rules(target_type: TargetType) -> Vec<ScanRule> {
|
||||
///
|
||||
/// Pentest runs as its own session (not a [`ScanType`] scan) and needs a
|
||||
/// reachable running target, so it is offered only for the network-reachable
|
||||
/// families.
|
||||
/// families. Not for Embedded Linux / Yocto until an image can be booted in an
|
||||
/// emulation sandbox: a pentest of the customer's device is out of scope.
|
||||
pub fn supports_pentest(target_type: TargetType) -> bool {
|
||||
matches!(
|
||||
target_type,
|
||||
@@ -356,7 +392,6 @@ pub fn supports_pentest(target_type: TargetType) -> bool {
|
||||
| TargetType::BackendService
|
||||
| TargetType::AndroidApp
|
||||
| TargetType::IosApp
|
||||
| TargetType::EmbeddedLinuxYocto
|
||||
// A PLC/SPS device exposes reachable runtime services (WebVisu, OPC UA,
|
||||
// the CODESYS programming protocol), so an active pentest applies.
|
||||
| TargetType::PlcSps
|
||||
@@ -671,13 +706,64 @@ mod tests {
|
||||
fn pentest_support_matches_reachable_families() {
|
||||
assert!(supports_pentest(TargetType::WebApp));
|
||||
assert!(supports_pentest(TargetType::BackendService));
|
||||
assert!(supports_pentest(TargetType::EmbeddedLinuxYocto));
|
||||
assert!(!supports_pentest(TargetType::EmbeddedLinuxYocto));
|
||||
// A PLC/SPS device is network-reachable (WebVisu / OPC UA / 11740).
|
||||
assert!(supports_pentest(TargetType::PlcSps));
|
||||
assert!(!supports_pentest(TargetType::FirmwareBareMetal));
|
||||
assert!(!supports_pentest(TargetType::DesktopApp));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_yocto_layer_tree_runs_its_recipe_inventory_and_lint() {
|
||||
let t = target_with(
|
||||
TargetType::EmbeddedLinuxYocto,
|
||||
vec![Artifact::git_repo("https://git/meta-pump", "main")],
|
||||
);
|
||||
let opts = applicable_scans(&t);
|
||||
let inventory = option(&opts, ScanType::RecipeInventory).expect("listed");
|
||||
assert!(inventory.default_on && inventory.unavailable.is_none());
|
||||
// Recipe lint runs over the layers.
|
||||
let lint = option(&opts, ScanType::RecipeLint).expect("listed");
|
||||
assert!(lint.default_on && lint.unavailable.is_none() && lint.blocked_reason.is_none());
|
||||
// The source scans (secrets, malware, the source SBOM) still run.
|
||||
let sast = option(&opts, ScanType::Sast).expect("sast");
|
||||
assert!(sast.default_on && sast.unavailable.is_none());
|
||||
// DAST stays opt-in and needs a web address.
|
||||
let dast = option(&opts, ScanType::Dast).expect("dast listed");
|
||||
assert!(!dast.default_on && dast.blocked_reason.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_yocto_image_has_no_sbom_until_build_artefacts_can_be_imported() {
|
||||
let t = target_with(
|
||||
TargetType::EmbeddedLinuxYocto,
|
||||
vec![
|
||||
Artifact::firmware_image("core-image.wic"),
|
||||
Artifact::live_url("https://device.local"),
|
||||
],
|
||||
);
|
||||
let opts = applicable_scans(&t);
|
||||
let image_option = |scan: ScanType| {
|
||||
opts.iter().find(|o| {
|
||||
o.scan == scan && o.required_artifact == Some(ArtifactKind::FirmwareImage)
|
||||
})
|
||||
};
|
||||
for (scan, reason) in [
|
||||
(ScanType::Sbom, YOCTO_IMAGE_SBOM),
|
||||
(ScanType::Cve, YOCTO_IMAGE_CVE),
|
||||
] {
|
||||
let opt = image_option(scan).expect("image rule listed");
|
||||
assert!(!opt.default_on);
|
||||
assert_eq!(opt.unavailable_with_artifact(), Some(reason));
|
||||
assert!(reason.contains("build artefacts (SPDX/manifest), planned"));
|
||||
}
|
||||
// With a web address DAST is unblocked but still opt-in; no pentest
|
||||
// until an image boots in an emulation sandbox.
|
||||
let dast = option(&opts, ScanType::Dast).expect("dast listed");
|
||||
assert!(dast.blocked_reason.is_none() && !dast.default_on);
|
||||
assert!(!supports_pentest(t.target_type));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_target_type_has_at_least_one_rule() {
|
||||
for tt in [
|
||||
|
||||
@@ -0,0 +1,533 @@
|
||||
//! Licences as SPDX ids (BSI TR-03183-2): the SPDX license list, and the
|
||||
//! ids of the licences registries and manifests name in prose or by URL.
|
||||
//!
|
||||
//! Maven POMs in particular say "The Apache Software License, Version 2.0" or
|
||||
//! give only `https://www.apache.org/licenses/LICENSE-2.0.txt`; the SBOM
|
||||
//! exports ([`crate::sbom_docs`]) write those as `Apache-2.0`. A name this
|
||||
//! module does not know stays as written: a guessed id would be worse than a
|
||||
//! name.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
/// The SPDX license and exception ids (CycloneDX's copy of the SPDX list),
|
||||
/// keyed by their lowercase form: SPDX ids match case-insensitively.
|
||||
static SPDX_IDS: LazyLock<HashMap<String, String>> = LazyLock::new(|| {
|
||||
serde_json::from_str::<serde_json::Value>(include_str!("../schemas/spdx.schema.json"))
|
||||
.ok()
|
||||
.and_then(|schema| {
|
||||
schema["enum"].as_array().map(|ids| {
|
||||
ids.iter()
|
||||
.filter_map(serde_json::Value::as_str)
|
||||
.map(|id| (id.to_ascii_lowercase(), id.to_string()))
|
||||
.collect()
|
||||
})
|
||||
})
|
||||
.unwrap_or_default()
|
||||
});
|
||||
|
||||
/// The operators of an SPDX license expression.
|
||||
const OPERATORS: [&str; 3] = ["AND", "OR", "WITH"];
|
||||
|
||||
/// The operators as they stand between two terms of an expression.
|
||||
const SPACED_OPERATORS: [&str; 3] = [" AND ", " OR ", " WITH "];
|
||||
|
||||
/// The SPDX id `text` is, in its canonical casing (`apache-2.0` is
|
||||
/// `Apache-2.0`); `None` when it is no SPDX license or exception id.
|
||||
pub fn canonical_id(text: &str) -> Option<&'static str> {
|
||||
SPDX_IDS
|
||||
.get(&text.trim().to_ascii_lowercase())
|
||||
.map(String::as_str)
|
||||
}
|
||||
|
||||
/// Whether `text` is an SPDX license expression of known ids
|
||||
/// (`MIT`, `(MIT OR Apache-2.0)`, `GPL-2.0-only WITH Classpath-exception-2.0`).
|
||||
/// `LicenseRef-` ids are not, as they need a definition beside them.
|
||||
pub fn is_spdx_expression(text: &str) -> bool {
|
||||
let mut tokens = text
|
||||
.split(|c: char| c.is_whitespace() || c == '(' || c == ')')
|
||||
.filter(|t| !t.is_empty())
|
||||
.peekable();
|
||||
tokens.peek().is_some()
|
||||
&& tokens.all(|t| {
|
||||
OPERATORS.contains(&t) || canonical_id(t.strip_suffix('+').unwrap_or(t)).is_some()
|
||||
})
|
||||
}
|
||||
|
||||
/// The licence written as SPDX where it is known: an SPDX id in canonical
|
||||
/// casing, the id of a licence name or licence page URL. An expression or a
|
||||
/// `LicenseRef-` stays as it is, and so does a name or URL this module does
|
||||
/// not know.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use compliance_core::spdx_license::normalise;
|
||||
///
|
||||
/// assert_eq!(normalise("The Apache Software License, Version 2.0"), "Apache-2.0");
|
||||
/// assert_eq!(normalise("https://opensource.org/licenses/MIT"), "MIT");
|
||||
/// assert_eq!(normalise("MIT OR Apache-2.0"), "MIT OR Apache-2.0");
|
||||
/// assert_eq!(normalise("Custom Pump License"), "Custom Pump License");
|
||||
/// ```
|
||||
pub fn normalise(license: &str) -> Cow<'_, str> {
|
||||
let license = license.trim();
|
||||
if let Some(id) = canonical_id(license) {
|
||||
return Cow::Borrowed(id);
|
||||
}
|
||||
let is_expression = license.starts_with("LicenseRef-") || has_operator(license);
|
||||
let known = if is_expression {
|
||||
None
|
||||
} else if is_url(license) {
|
||||
spdx_of_url(license)
|
||||
} else {
|
||||
spdx_of_name(license)
|
||||
};
|
||||
// `Cow` (clone-on-write) lends the input back when nothing changed and
|
||||
// only owns a value when it did; here every known id is a `'static str`.
|
||||
known.map_or(Cow::Borrowed(license), Cow::Borrowed)
|
||||
}
|
||||
|
||||
/// The copyleft licences, as SPDX ids without `-only`/`-or-later`.
|
||||
const COPYLEFT: [&str; 7] = [
|
||||
"GPL-2.0", "GPL-3.0", "AGPL-3.0", "LGPL-2.0", "LGPL-2.1", "LGPL-3.0", "MPL-2.0",
|
||||
];
|
||||
|
||||
/// Whether `license` is or includes a copyleft licence: any term of its SPDX
|
||||
/// form ([`normalise`]), so "GNU Lesser General Public License v2.1" and
|
||||
/// `MIT OR GPL-3.0-only` are. A name this module does not know is copyleft
|
||||
/// when it contains a copyleft id (`GPL-2.0 with exceptions`).
|
||||
pub fn is_copyleft(license: &str) -> bool {
|
||||
let is_copyleft_id = |id: &str| {
|
||||
let base = id.strip_suffix('+').unwrap_or(id);
|
||||
let base = base
|
||||
.strip_suffix("-only")
|
||||
.or_else(|| base.strip_suffix("-or-later"))
|
||||
.unwrap_or(base);
|
||||
COPYLEFT.iter().any(|c| c.eq_ignore_ascii_case(base))
|
||||
};
|
||||
let spdx = normalise(license);
|
||||
let by_term = spdx
|
||||
.split(|c: char| c.is_whitespace() || c == '(' || c == ')')
|
||||
.filter(|t| !t.is_empty() && !OPERATORS.contains(t))
|
||||
.any(is_copyleft_id);
|
||||
let upper = license.to_ascii_uppercase();
|
||||
by_term || COPYLEFT.iter().any(|c| upper.contains(c))
|
||||
}
|
||||
|
||||
/// Whether `text` joins terms with an SPDX operator (`MIT OR Apache-2.0`),
|
||||
/// as an expression does.
|
||||
pub fn has_operator(text: &str) -> bool {
|
||||
SPACED_OPERATORS.iter().any(|op| text.contains(op))
|
||||
}
|
||||
|
||||
/// Whether `text` looks like a URL rather than a licence name.
|
||||
fn is_url(text: &str) -> bool {
|
||||
let lower = text.to_ascii_lowercase();
|
||||
lower.starts_with("http://") || lower.starts_with("https://") || lower.starts_with("www.")
|
||||
}
|
||||
|
||||
/// The SPDX id of a licence page: a well-known page, or an
|
||||
/// `opensource.org/licenses/<id>` or `spdx.org/licenses/<id>` page.
|
||||
pub fn spdx_of_url(url: &str) -> Option<&'static str> {
|
||||
let lower = url.trim().to_ascii_lowercase();
|
||||
let bare = lower
|
||||
.trim_start_matches("https://")
|
||||
.trim_start_matches("http://")
|
||||
.trim_start_matches("www.")
|
||||
.trim_end_matches('/');
|
||||
let page = [".php", ".html", ".htm", ".txt", ".md"]
|
||||
.iter()
|
||||
.find_map(|ext| bare.strip_suffix(ext))
|
||||
.unwrap_or(bare);
|
||||
WELL_KNOWN_URLS
|
||||
.iter()
|
||||
.find(|(known, _)| page == *known)
|
||||
.map(|(_, id)| *id)
|
||||
.or_else(|| {
|
||||
[
|
||||
"opensource.org/licenses/",
|
||||
"opensource.org/license/",
|
||||
"spdx.org/licenses/",
|
||||
]
|
||||
.iter()
|
||||
.find_map(|prefix| page.strip_prefix(prefix))
|
||||
.and_then(canonical_id)
|
||||
})
|
||||
}
|
||||
|
||||
/// License pages (lowercase, without scheme, `www.`, trailing slash and
|
||||
/// `.html`/`.php`/`.txt`) and the SPDX id they stand for.
|
||||
const WELL_KNOWN_URLS: &[(&str, &str)] = &[
|
||||
("opensource.org/licenses/mit-license", "MIT"),
|
||||
("opensource.org/license/mit", "MIT"),
|
||||
("choosealicense.com/licenses/mit", "MIT"),
|
||||
("opensource.org/license/apache-2-0", "Apache-2.0"),
|
||||
("apache.org/licenses/license-2.0", "Apache-2.0"),
|
||||
("choosealicense.com/licenses/apache-2.0", "Apache-2.0"),
|
||||
("opensource.org/licenses/bsd-license", "BSD-3-Clause"),
|
||||
("microsoft.com/opensource/licenses.mspx#ms-pl", "MS-PL"),
|
||||
("mozilla.org/mpl/2.0", "MPL-2.0"),
|
||||
("opensource.org/licenses/lgpl-2.1", "LGPL-2.1-only"),
|
||||
("opensource.org/licenses/lgpl-3.0", "LGPL-3.0-only"),
|
||||
("gnu.org/licenses/lgpl-2.1", "LGPL-2.1-only"),
|
||||
("gnu.org/licenses/old-licenses/lgpl-2.1", "LGPL-2.1-only"),
|
||||
("gnu.org/licenses/lgpl-3.0", "LGPL-3.0-only"),
|
||||
("gnu.org/licenses/lgpl", "LGPL-3.0-or-later"),
|
||||
("opensource.org/licenses/gpl-2.0", "GPL-2.0-only"),
|
||||
("opensource.org/licenses/gpl-3.0", "GPL-3.0-only"),
|
||||
("gnu.org/licenses/gpl-2.0", "GPL-2.0-only"),
|
||||
("gnu.org/licenses/old-licenses/gpl-2.0", "GPL-2.0-only"),
|
||||
("gnu.org/licenses/gpl-3.0", "GPL-3.0-only"),
|
||||
("gnu.org/licenses/gpl", "GPL-3.0-or-later"),
|
||||
("gnu.org/licenses/agpl-3.0", "AGPL-3.0-only"),
|
||||
("gnu.org/licenses/agpl", "AGPL-3.0-or-later"),
|
||||
("eclipse.org/legal/epl-2.0", "EPL-2.0"),
|
||||
("eclipse.org/legal/epl-v20", "EPL-2.0"),
|
||||
("eclipse.org/legal/epl-v10", "EPL-1.0"),
|
||||
("eclipse.org/org/documents/edl-v10", "BSD-3-Clause"),
|
||||
("creativecommons.org/publicdomain/zero/1.0", "CC0-1.0"),
|
||||
(
|
||||
"creativecommons.org/publicdomain/zero/1.0/legalcode",
|
||||
"CC0-1.0",
|
||||
),
|
||||
("boost.org/license_1_0", "BSL-1.0"),
|
||||
("unlicense.org", "Unlicense"),
|
||||
];
|
||||
|
||||
/// The words of a licence name, lowercase: punctuation separates words, and
|
||||
/// so does a letter followed by a digit (`GPLv2` is `gpl 2`, `2.1` is
|
||||
/// `2 1`); a `v` before a version (`v2`, `gplv3`) is dropped.
|
||||
fn words(name: &str) -> Vec<String> {
|
||||
let mut spaced = String::with_capacity(name.len() * 2);
|
||||
let mut previous = ' ';
|
||||
for c in name.chars().map(|c| c.to_ascii_lowercase()) {
|
||||
if c.is_ascii_digit() && previous.is_ascii_alphabetic() {
|
||||
spaced.push(' ');
|
||||
}
|
||||
spaced.push(if c.is_ascii_alphanumeric() { c } else { ' ' });
|
||||
previous = c;
|
||||
}
|
||||
spaced
|
||||
.split_whitespace()
|
||||
.map(|w| match w.strip_suffix('v') {
|
||||
// `gplv` (from `gplv3`) is `gpl`; `v` alone is the version mark.
|
||||
Some(family @ ("gpl" | "lgpl" | "agpl" | "epl" | "mpl" | "")) => family.to_string(),
|
||||
_ => w.to_string(),
|
||||
})
|
||||
.filter(|w| !w.is_empty())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The version a licence name states: the first number and the one after it
|
||||
/// (`2.1` is `(2, Some(1))`, `Version 2` is `(2, None)`).
|
||||
fn version(words: &[String]) -> Option<(u32, Option<u32>)> {
|
||||
let at = words
|
||||
.iter()
|
||||
.position(|w| w.chars().all(|c| c.is_ascii_digit()))?;
|
||||
let major = words[at].parse().ok()?;
|
||||
let minor = words
|
||||
.get(at + 1)
|
||||
.filter(|w| w.chars().all(|c| c.is_ascii_digit()))
|
||||
.and_then(|w| w.parse().ok());
|
||||
Some((major, minor))
|
||||
}
|
||||
|
||||
/// The SPDX id (or, for the GPL with the Classpath exception, expression) of
|
||||
/// a licence as registries and POMs name it: "Apache License, Version 2.0",
|
||||
/// "The MIT License", "GNU Lesser General Public License v2.1", ... Case,
|
||||
/// punctuation, "The" and "Version"/"v" do not matter. A family without the
|
||||
/// version it needs ("GPL", "BSD License") or a name with two licences in it
|
||||
/// is `None`.
|
||||
pub fn spdx_of_name(name: &str) -> Option<&'static str> {
|
||||
let words = words(name);
|
||||
let has = |w: &str| words.iter().any(|x| x == w);
|
||||
// Padded with spaces so that a phrase matches whole words only.
|
||||
let joined = format!(" {} ", words.join(" "));
|
||||
let phrase = |p: &str| joined.contains(&format!(" {p} "));
|
||||
let version = version(&words);
|
||||
let (major, minor) = version.map_or((None, None), |(major, minor)| (Some(major), minor));
|
||||
let later = has("later") || (name.contains('+') && !name.contains(" + "));
|
||||
let gnu =
|
||||
|only: &'static str, or_later: &'static str| Some(if later { or_later } else { only });
|
||||
|
||||
let gpl = has("gpl") || phrase("general public");
|
||||
let lgpl = has("lgpl") || phrase("lesser general public") || phrase("library general public");
|
||||
let agpl = has("agpl") || has("affero");
|
||||
// A dual licence ("CDDL + GPLv2 with classpath exception") is two
|
||||
// licences; its name stays.
|
||||
if gpl && (has("cddl") || has("mit") || has("apache")) {
|
||||
return None;
|
||||
}
|
||||
|
||||
if lgpl {
|
||||
return match (major?, minor) {
|
||||
(2, Some(1)) => gnu("LGPL-2.1-only", "LGPL-2.1-or-later"),
|
||||
(2, None | Some(0)) => gnu("LGPL-2.0-only", "LGPL-2.0-or-later"),
|
||||
(3, None | Some(0)) => gnu("LGPL-3.0-only", "LGPL-3.0-or-later"),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if agpl {
|
||||
return match major? {
|
||||
3 => gnu("AGPL-3.0-only", "AGPL-3.0-or-later"),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if gpl {
|
||||
return match major? {
|
||||
2 if has("classpath") => Some("GPL-2.0-only WITH Classpath-exception-2.0"),
|
||||
1 => gnu("GPL-1.0-only", "GPL-1.0-or-later"),
|
||||
2 => gnu("GPL-2.0-only", "GPL-2.0-or-later"),
|
||||
3 => gnu("GPL-3.0-only", "GPL-3.0-or-later"),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if has("cc0") || phrase("cc 0") || phrase("creative commons zero") {
|
||||
return Some("CC0-1.0");
|
||||
}
|
||||
if has("apache") || has("asl") {
|
||||
return match (major?, minor) {
|
||||
(2, None | Some(0)) => Some("Apache-2.0"),
|
||||
(1, Some(1)) => Some("Apache-1.1"),
|
||||
(1, None | Some(0)) => Some("Apache-1.0"),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if has("mit") {
|
||||
return Some(if has("attribution") { "MIT-0" } else { "MIT" });
|
||||
}
|
||||
if phrase("eclipse distribution") || has("edl") {
|
||||
return (major == Some(1)).then_some("BSD-3-Clause");
|
||||
}
|
||||
if phrase("eclipse public") || has("epl") {
|
||||
return match major? {
|
||||
1 => Some("EPL-1.0"),
|
||||
2 => Some("EPL-2.0"),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if phrase("mozilla public") || has("mpl") {
|
||||
return match (major?, minor) {
|
||||
(2, None | Some(0)) => Some("MPL-2.0"),
|
||||
(1, Some(1)) => Some("MPL-1.1"),
|
||||
(1, None | Some(0)) => Some("MPL-1.0"),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if has("cddl") || phrase("common development and distribution") {
|
||||
return match (major?, minor) {
|
||||
(1, None | Some(0)) => Some("CDDL-1.0"),
|
||||
(1, Some(1)) => Some("CDDL-1.1"),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if has("eupl") || phrase("european union public") {
|
||||
return match (major?, minor) {
|
||||
(1, Some(1)) => Some("EUPL-1.1"),
|
||||
(1, Some(2)) => Some("EUPL-1.2"),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if has("0bsd") || (has("bsd") && phrase("zero clause")) {
|
||||
return Some("0BSD");
|
||||
}
|
||||
if has("bsd") || has("freebsd") {
|
||||
return if major == Some(3) || has("new") || has("revised") {
|
||||
Some("BSD-3-Clause")
|
||||
} else if major == Some(2) || has("simplified") || has("freebsd") {
|
||||
Some("BSD-2-Clause")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
}
|
||||
if phrase("boost software") || has("bsl") {
|
||||
return (major == Some(1)).then_some("BSL-1.0");
|
||||
}
|
||||
if has("artistic") {
|
||||
return (major == Some(2)).then_some("Artistic-2.0");
|
||||
}
|
||||
if phrase("python software foundation") || has("psf") {
|
||||
return Some("PSF-2.0");
|
||||
}
|
||||
if phrase("universal permissive") || has("upl") {
|
||||
return Some("UPL-1.0");
|
||||
}
|
||||
if has("isc") {
|
||||
return Some("ISC");
|
||||
}
|
||||
if has("zlib") {
|
||||
return Some("Zlib");
|
||||
}
|
||||
if has("unlicense") {
|
||||
return Some("Unlicense");
|
||||
}
|
||||
if has("wtfpl") {
|
||||
return Some("WTFPL");
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn copyleft_is_found_in_names_ids_and_expressions() {
|
||||
for license in [
|
||||
"GNU Lesser General Public License v2.1",
|
||||
"GNU General Public License, version 2",
|
||||
"LGPL-2.1-or-later",
|
||||
"gpl-3.0-only",
|
||||
"GPL-2.0+",
|
||||
"MIT OR GPL-3.0-only",
|
||||
"GPL-2.0-only WITH Classpath-exception-2.0",
|
||||
"Mozilla Public License 2.0",
|
||||
"AGPL-3.0",
|
||||
] {
|
||||
assert!(is_copyleft(license), "{license}");
|
||||
}
|
||||
for license in [
|
||||
"Apache License, Version 2.0",
|
||||
"MIT",
|
||||
"BSD-3-Clause",
|
||||
"Custom Pump License",
|
||||
"",
|
||||
] {
|
||||
assert!(!is_copyleft(license), "{license}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Licence names and URLs as Maven POMs, npm and NuGet give them, and
|
||||
/// their SPDX id.
|
||||
const KNOWN: &[(&str, &str)] = &[
|
||||
("Apache 2.0", "Apache-2.0"),
|
||||
("Apache 2", "Apache-2.0"),
|
||||
("Apache License, Version 2.0", "Apache-2.0"),
|
||||
("The Apache Software License, Version 2.0", "Apache-2.0"),
|
||||
("The Apache License, Version 2.0", "Apache-2.0"),
|
||||
("Apache License 2.0", "Apache-2.0"),
|
||||
("Apache Software License - Version 2.0", "Apache-2.0"),
|
||||
("ASL 2.0", "Apache-2.0"),
|
||||
("apache-2.0", "Apache-2.0"),
|
||||
("Apache License, Version 1.1", "Apache-1.1"),
|
||||
("MIT", "MIT"),
|
||||
("MIT License", "MIT"),
|
||||
("The MIT License", "MIT"),
|
||||
("The MIT License (MIT)", "MIT"),
|
||||
("MIT No Attribution", "MIT-0"),
|
||||
("BSD 3-Clause", "BSD-3-Clause"),
|
||||
("BSD-3-Clause License", "BSD-3-Clause"),
|
||||
("New BSD License", "BSD-3-Clause"),
|
||||
("BSD Zero Clause License", "0BSD"),
|
||||
("The BSD 3-Clause License", "BSD-3-Clause"),
|
||||
("BSD 2-Clause \"Simplified\" License", "BSD-2-Clause"),
|
||||
("Eclipse Public License - v 2.0", "EPL-2.0"),
|
||||
("Eclipse Public License v2.0", "EPL-2.0"),
|
||||
("Eclipse Public License - v 1.0", "EPL-1.0"),
|
||||
("EPL 2.0", "EPL-2.0"),
|
||||
("Eclipse Distribution License - v 1.0", "BSD-3-Clause"),
|
||||
("GNU Lesser General Public License v2.1", "LGPL-2.1-only"),
|
||||
(
|
||||
"GNU Lesser General Public License, version 2.1",
|
||||
"LGPL-2.1-only",
|
||||
),
|
||||
("LGPL 2.1", "LGPL-2.1-only"),
|
||||
("LGPLv2.1+", "LGPL-2.1-or-later"),
|
||||
(
|
||||
"GNU Lesser General Public License v3.0 or later",
|
||||
"LGPL-3.0-or-later",
|
||||
),
|
||||
("GNU Library General Public License v2", "LGPL-2.0-only"),
|
||||
("GNU General Public License, version 2", "GPL-2.0-only"),
|
||||
("GPLv3", "GPL-3.0-only"),
|
||||
("GNU Affero General Public License v3", "AGPL-3.0-only"),
|
||||
(
|
||||
"GNU General Public License, version 2 with the GNU Classpath Exception",
|
||||
"GPL-2.0-only WITH Classpath-exception-2.0",
|
||||
),
|
||||
("Mozilla Public License, Version 2.0", "MPL-2.0"),
|
||||
("MPL 1.1", "MPL-1.1"),
|
||||
("CDDL 1.1", "CDDL-1.1"),
|
||||
(
|
||||
"Common Development and Distribution License (CDDL) v1.0",
|
||||
"CDDL-1.0",
|
||||
),
|
||||
("European Union Public License 1.2", "EUPL-1.2"),
|
||||
("CC0 1.0 Universal", "CC0-1.0"),
|
||||
("Public Domain, per Creative Commons CC0", "CC0-1.0"),
|
||||
("Boost Software License 1.0", "BSL-1.0"),
|
||||
("ISC License", "ISC"),
|
||||
("zlib License", "Zlib"),
|
||||
("The Unlicense", "Unlicense"),
|
||||
("Universal Permissive License, Version 1.0", "UPL-1.0"),
|
||||
("https://www.apache.org/licenses/LICENSE-2.0", "Apache-2.0"),
|
||||
(
|
||||
"https://www.apache.org/licenses/LICENSE-2.0.txt",
|
||||
"Apache-2.0",
|
||||
),
|
||||
(
|
||||
"http://www.apache.org/licenses/LICENSE-2.0.html",
|
||||
"Apache-2.0",
|
||||
),
|
||||
("https://opensource.org/licenses/MIT", "MIT"),
|
||||
("http://opensource.org/licenses/mit-license.php", "MIT"),
|
||||
(
|
||||
"https://opensource.org/licenses/BSD-3-Clause",
|
||||
"BSD-3-Clause",
|
||||
),
|
||||
("https://opensource.org/licenses/MS-PL", "MS-PL"),
|
||||
("https://spdx.org/licenses/ISC.html", "ISC"),
|
||||
("https://www.eclipse.org/legal/epl-2.0/", "EPL-2.0"),
|
||||
("http://www.eclipse.org/legal/epl-v10.html", "EPL-1.0"),
|
||||
(
|
||||
"https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html",
|
||||
"LGPL-2.1-only",
|
||||
),
|
||||
(
|
||||
"https://www.gnu.org/licenses/agpl.html",
|
||||
"AGPL-3.0-or-later",
|
||||
),
|
||||
("www.mozilla.org/MPL/2.0/", "MPL-2.0"),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn known_licence_names_and_urls_become_spdx_ids() {
|
||||
for (input, id) in KNOWN {
|
||||
assert_eq!(normalise(input), *id, "{input}");
|
||||
assert!(is_spdx_expression(id), "{id} is no SPDX id");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_names_and_spdx_input_stay_as_written() {
|
||||
for input in [
|
||||
"Custom Pump License",
|
||||
"GPL",
|
||||
"BSD License",
|
||||
"Eclipse Public License",
|
||||
"CDDL + GPLv2 with classpath exception",
|
||||
"Commercial",
|
||||
"https://example.com/our-license.html",
|
||||
"MIT OR Apache-2.0",
|
||||
"(EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0)",
|
||||
"LicenseRef-file",
|
||||
"GPL-2.0",
|
||||
] {
|
||||
assert_eq!(normalise(input), input, "{input}");
|
||||
}
|
||||
// A word that merely contains a family's letters is not that family.
|
||||
assert_eq!(spdx_of_name("Permit to Limit License"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spdx_expressions_are_recognised() {
|
||||
assert!(is_spdx_expression("MIT"));
|
||||
assert!(is_spdx_expression("(MIT OR Apache-2.0)"));
|
||||
assert!(is_spdx_expression("GPL-2.0-or-later"));
|
||||
assert!(is_spdx_expression("GPL-2.0+"));
|
||||
assert!(!is_spdx_expression("Custom Pump License"));
|
||||
assert!(!is_spdx_expression("MIT OR LicenseRef-file"));
|
||||
assert!(!is_spdx_expression(""));
|
||||
}
|
||||
}
|
||||
@@ -15,11 +15,19 @@
|
||||
//! | `vulnerable_code_not_in_execute_path` | `code_not_reachable` |
|
||||
//! | `vulnerable_code_cannot_be_controlled_by_adversary` | `requires_environment` |
|
||||
//! | `inline_mitigations_already_exist` | `protected_by_mitigating_control` |
|
||||
//!
|
||||
//! A vulnerability is named by its CVE when one is known (ENISA and BSI work
|
||||
//! with CVE ids), its GitHub advisory and other ids are aliases (OpenVEX) or
|
||||
//! references (CycloneDX); without a CVE it keeps the advisory's id. Alerts of
|
||||
//! the same CVE in the same component (a GitHub advisory and the CVE it
|
||||
//! aliases, found by different scanners) are one statement.
|
||||
|
||||
use chrono::{DateTime, SecondsFormat, Utc};
|
||||
|
||||
use crate::models::{CveAlert, SbomEntry, VexJustification, VexStatus};
|
||||
use crate::sbom_docs::{cdx_components, cdx_frame, cdx_severity, component_ref, product_ref};
|
||||
use crate::sbom_docs::{
|
||||
cdx_components, cdx_frame, cdx_severity, cdx_vulnerability, component_ref, product_ref,
|
||||
};
|
||||
|
||||
/// What a VEX document is built from.
|
||||
pub struct VexInput<'a> {
|
||||
@@ -74,22 +82,82 @@ pub(crate) fn rfc3339(at: DateTime<Utc>) -> String {
|
||||
at.to_rfc3339_opts(SecondsFormat::Secs, true)
|
||||
}
|
||||
|
||||
/// One statement of a VEX document: a vulnerability in a component, from
|
||||
/// all alerts of its CVE in that component.
|
||||
pub(crate) struct Statement<'a> {
|
||||
/// The alert whose status is stated (see [`statements`]).
|
||||
pub(crate) alert: &'a CveAlert,
|
||||
/// The component's id ([`component_id`]).
|
||||
pub(crate) component: String,
|
||||
/// The vulnerability's ids other than [`CveAlert::cve`] across the
|
||||
/// alerts, each once.
|
||||
pub(crate) other_ids: Vec<&'a str>,
|
||||
}
|
||||
|
||||
impl Statement<'_> {
|
||||
/// The id the vulnerability is listed under: its CVE when one is known.
|
||||
pub(crate) fn id(&self) -> &str {
|
||||
self.alert.cve()
|
||||
}
|
||||
}
|
||||
|
||||
/// How much an alert's status counts when two alerts of the same CVE name
|
||||
/// the same component: an explicit statement (the latest one) over none,
|
||||
/// then an open alert over a resolved one.
|
||||
fn weight(alert: &CveAlert) -> (Option<DateTime<Utc>>, bool) {
|
||||
(
|
||||
alert.vex.as_ref().map(|v| v.at),
|
||||
alert.resolved_at.is_none(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The statements of `input`, one per CVE and component in the order the
|
||||
/// alerts first name them. Of several alerts of one CVE in one component
|
||||
/// the one with the highest [`weight`] states the status (the first on a
|
||||
/// tie).
|
||||
pub(crate) fn statements<'a>(input: &VexInput<'a>) -> Vec<Statement<'a>> {
|
||||
let mut out: Vec<Statement<'a>> = Vec::with_capacity(input.alerts.len());
|
||||
for alert in input.alerts {
|
||||
let component = component_id(alert, input.sbom);
|
||||
let known = out
|
||||
.iter()
|
||||
.position(|s| s.component == component && s.id() == alert.cve());
|
||||
let Some(i) = known else {
|
||||
out.push(Statement {
|
||||
alert,
|
||||
component,
|
||||
other_ids: alert.other_ids(),
|
||||
});
|
||||
continue;
|
||||
};
|
||||
let statement = &mut out[i];
|
||||
for id in alert.other_ids() {
|
||||
if !statement.other_ids.contains(&id) {
|
||||
statement.other_ids.push(id);
|
||||
}
|
||||
}
|
||||
if weight(alert) > weight(statement.alert) {
|
||||
statement.alert = alert;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An OpenVEX 0.2.0 document: one statement per alert, about the product
|
||||
/// with the affected component as its subcomponent.
|
||||
pub fn openvex(input: &VexInput<'_>) -> serde_json::Value {
|
||||
let product = product_ref(input.subject);
|
||||
let statements: Vec<serde_json::Value> = input
|
||||
.alerts
|
||||
.iter()
|
||||
.map(|alert| {
|
||||
let component = component_id(alert, input.sbom);
|
||||
let statements: Vec<serde_json::Value> = statements(input)
|
||||
.into_iter()
|
||||
.map(|st| {
|
||||
let (alert, component) = (st.alert, &st.component);
|
||||
let mut subcomponent = serde_json::json!({ "@id": component });
|
||||
if component.starts_with("pkg:") {
|
||||
subcomponent["identifiers"] = serde_json::json!({ "purl": component });
|
||||
}
|
||||
let mut vulnerability = serde_json::json!({ "name": alert.cve_id });
|
||||
if !alert.aliases.is_empty() {
|
||||
vulnerability["aliases"] = serde_json::json!(alert.aliases);
|
||||
let mut vulnerability = serde_json::json!({ "name": st.id() });
|
||||
if !st.other_ids.is_empty() {
|
||||
vulnerability["aliases"] = serde_json::json!(st.other_ids);
|
||||
}
|
||||
let status = status_of(alert);
|
||||
let mut statement = serde_json::json!({
|
||||
@@ -106,8 +174,15 @@ pub fn openvex(input: &VexInput<'_>) -> serde_json::Value {
|
||||
if let Some(j) = vex.justification {
|
||||
statement["justification"] = serde_json::json!(j);
|
||||
}
|
||||
// OpenVEX's impact statement belongs to `not_affected`; the
|
||||
// reason of another status (a scan's note) is its status note.
|
||||
if let Some(text) = vex.impact_statement.as_deref() {
|
||||
statement["impact_statement"] = serde_json::json!(text);
|
||||
let field = if status == VexStatus::NotAffected {
|
||||
"impact_statement"
|
||||
} else {
|
||||
"status_notes"
|
||||
};
|
||||
statement[field] = serde_json::json!(text);
|
||||
}
|
||||
if let Some(text) = vex.action_statement.as_deref() {
|
||||
statement["action_statement"] = serde_json::json!(text);
|
||||
@@ -152,7 +227,7 @@ fn cdx_justification(justification: VexJustification) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// A CycloneDX 1.6 VEX: the SBOM's components, and every alert as a
|
||||
/// A CycloneDX 1.6 VEX: the SBOM's components, and every statement as a
|
||||
/// vulnerability with its analysis, affecting its component by `bom-ref`.
|
||||
pub fn cyclonedx_vex(input: &VexInput<'_>) -> serde_json::Value {
|
||||
let mut doc = cdx_frame(input.subject, input.sbom);
|
||||
@@ -161,12 +236,11 @@ pub fn cyclonedx_vex(input: &VexInput<'_>) -> serde_json::Value {
|
||||
.iter()
|
||||
.filter_map(|c| c["bom-ref"].as_str().map(str::to_string))
|
||||
.collect();
|
||||
let vulnerabilities: Vec<serde_json::Value> = input
|
||||
.alerts
|
||||
.iter()
|
||||
let vulnerabilities: Vec<serde_json::Value> = statements(input)
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, alert)| {
|
||||
let component = component_id(alert, input.sbom);
|
||||
.map(|(i, st)| {
|
||||
let (alert, component) = (st.alert, &st.component);
|
||||
// A component the SBOM no longer lists (a fixed one) is still
|
||||
// named, so the reference resolves.
|
||||
if refs.insert(component.clone()) {
|
||||
@@ -197,13 +271,11 @@ pub fn cyclonedx_vex(input: &VexInput<'_>) -> serde_json::Value {
|
||||
if status == VexStatus::Affected && !alert.fixed_versions.is_empty() {
|
||||
analysis["response"] = serde_json::json!(["update"]);
|
||||
}
|
||||
let mut v = serde_json::json!({
|
||||
"bom-ref": format!("vex-{i}-{}", alert.cve_id),
|
||||
"id": alert.cve_id,
|
||||
"source": { "name": format!("{:?}", alert.source).to_uppercase() },
|
||||
"analysis": analysis,
|
||||
"affects": [{ "ref": component }],
|
||||
});
|
||||
let source = format!("{:?}", alert.source).to_uppercase();
|
||||
let mut v = cdx_vulnerability(st.id(), &st.other_ids, &source);
|
||||
v["bom-ref"] = serde_json::json!(format!("vex-{i}-{}", st.id()));
|
||||
v["analysis"] = analysis;
|
||||
v["affects"] = serde_json::json!([{ "ref": component }]);
|
||||
if let Some(severity) = alert.severity.as_deref() {
|
||||
v["ratings"] = serde_json::json!([{ "severity": cdx_severity(severity) }]);
|
||||
}
|
||||
|
||||
@@ -78,6 +78,7 @@ fn sbom() -> Vec<SbomEntry> {
|
||||
severity: Some("CRITICAL".into()),
|
||||
url: None,
|
||||
exploitation: None,
|
||||
aliases: Vec::new(),
|
||||
}];
|
||||
let mut lodash = SbomEntry::new("t".into(), "lodash".into(), "4.17.20".into(), "npm".into());
|
||||
lodash.purl = Some("pkg:npm/lodash@4.17.20".into());
|
||||
@@ -335,7 +336,11 @@ fn the_csaf_advisory_is_valid_and_carries_the_statements() {
|
||||
assert_eq!(vulns.len(), 4);
|
||||
let log4shell = &vulns[0];
|
||||
assert_eq!(log4shell["cve"], "CVE-2021-44228");
|
||||
assert_eq!(log4shell["ids"][0]["system_name"], "GHSA");
|
||||
assert_eq!(
|
||||
log4shell["ids"][0]["system_name"],
|
||||
"GitHub Security Advisories"
|
||||
);
|
||||
assert_eq!(log4shell["ids"][0]["text"], "GHSA-jfh8-c2jp-5v3q");
|
||||
let affected = log4shell["product_status"]["known_affected"]
|
||||
.as_array()
|
||||
.unwrap();
|
||||
@@ -461,3 +466,158 @@ fn a_fixed_component_that_left_the_sbom_keeps_its_stored_purl() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cve_is_the_vulnerability_id_and_the_github_advisory_an_alias() {
|
||||
// Arrange: Log4Shell as a CVE alert on log4j-core and as a GitHub
|
||||
// advisory aliasing it on log4j-api; a CVE-only alert; a GitHub advisory
|
||||
// without a CVE.
|
||||
let sbom = sbom();
|
||||
let mut alerts = csaf_alerts();
|
||||
alerts.push(alert("GHSA-xxxx-yyyy-zzzz", "lodash", "4.17.20"));
|
||||
let input = vex_input(&alerts, &sbom);
|
||||
|
||||
// Act
|
||||
let openvex = vex_docs::openvex(&input);
|
||||
let cdx = vex_docs::cyclonedx_vex(&input);
|
||||
let csaf = csaf_docs::csaf_vex(&input, "https://example.invalid/pumps", "en");
|
||||
|
||||
// Assert
|
||||
assert_eq!(openvex_errors(&openvex), Vec::<String>::new());
|
||||
assert_eq!(cyclonedx_errors(&cdx), Vec::<String>::new());
|
||||
assert_eq!(csaf_errors(&csaf), Vec::<String>::new());
|
||||
let statements = openvex["statements"].as_array().unwrap();
|
||||
let vulns = cdx["vulnerabilities"].as_array().unwrap();
|
||||
assert_eq!(statements.len(), 6);
|
||||
assert_eq!(vulns.len(), 6);
|
||||
// CVE only: the CVE, from NVD, nothing else.
|
||||
assert_eq!(statements[0]["vulnerability"]["name"], "CVE-2021-44228");
|
||||
assert!(statements[0]["vulnerability"].get("aliases").is_none());
|
||||
assert_eq!(vulns[0]["id"], "CVE-2021-44228");
|
||||
assert_eq!(vulns[0]["source"]["name"], "NVD");
|
||||
assert!(vulns[0].get("references").is_none());
|
||||
// CVE and GHSA: the CVE, the GHSA as alias and reference.
|
||||
let ghsa = "GHSA-jfh8-c2jp-5v3q";
|
||||
assert_eq!(statements[4]["vulnerability"]["name"], "CVE-2021-44228");
|
||||
assert_eq!(
|
||||
statements[4]["vulnerability"]["aliases"],
|
||||
serde_json::json!([ghsa])
|
||||
);
|
||||
assert_eq!(vulns[4]["id"], "CVE-2021-44228");
|
||||
assert_eq!(
|
||||
vulns[4]["source"]["url"],
|
||||
"https://nvd.nist.gov/vuln/detail/CVE-2021-44228"
|
||||
);
|
||||
assert_eq!(vulns[4]["references"][0]["id"], ghsa);
|
||||
assert_eq!(
|
||||
vulns[4]["references"][0]["source"]["name"],
|
||||
"GitHub Security Advisories"
|
||||
);
|
||||
assert_eq!(csaf["vulnerabilities"][0]["cve"], "CVE-2021-44228");
|
||||
assert_eq!(csaf["vulnerabilities"][0]["ids"][0]["text"], ghsa);
|
||||
// GHSA only: its own id, as the scanner found it.
|
||||
let only = "GHSA-xxxx-yyyy-zzzz";
|
||||
assert_eq!(statements[5]["vulnerability"]["name"], only);
|
||||
assert!(statements[5]["vulnerability"].get("aliases").is_none());
|
||||
assert_eq!(vulns[5]["id"], only);
|
||||
assert_eq!(vulns[5]["source"]["name"], "OSV");
|
||||
assert!(vulns[5].get("references").is_none());
|
||||
let csaf_only = &csaf["vulnerabilities"][4];
|
||||
assert!(csaf_only.get("cve").is_none());
|
||||
assert_eq!(csaf_only["ids"][0]["text"], only);
|
||||
assert_eq!(
|
||||
csaf_only["ids"][0]["system_name"],
|
||||
"GitHub Security Advisories"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cve_found_as_cve_and_as_github_advisory_in_one_component_is_one_statement() {
|
||||
// Arrange: the GHSA alert of Log4Shell on the same log4j-core as the
|
||||
// CVE alert, open; the CVE alert carries the statement.
|
||||
let sbom = sbom();
|
||||
let mut alerts = alerts();
|
||||
let mut ghsa = alert("GHSA-jfh8-c2jp-5v3q", "log4j-core", "2.14.1");
|
||||
ghsa.aliases = vec!["CVE-2021-44228".into()];
|
||||
alerts.insert(0, ghsa);
|
||||
let input = vex_input(&alerts, &sbom);
|
||||
|
||||
// Act
|
||||
let openvex = vex_docs::openvex(&input);
|
||||
let cdx = vex_docs::cyclonedx_vex(&input);
|
||||
let csaf = csaf_docs::csaf_vex(&input, "https://example.invalid/pumps", "en");
|
||||
|
||||
// Assert: four statements, Log4Shell once with the stated status.
|
||||
assert_eq!(openvex_errors(&openvex), Vec::<String>::new());
|
||||
assert_eq!(cyclonedx_errors(&cdx), Vec::<String>::new());
|
||||
assert_eq!(csaf_errors(&csaf), Vec::<String>::new());
|
||||
let statements = openvex["statements"].as_array().unwrap();
|
||||
assert_eq!(statements.len(), 4);
|
||||
let log4shell: Vec<_> = statements
|
||||
.iter()
|
||||
.filter(|s| s["vulnerability"]["name"] == "CVE-2021-44228")
|
||||
.collect();
|
||||
assert_eq!(log4shell.len(), 1);
|
||||
assert_eq!(log4shell[0]["status"], "affected");
|
||||
assert_eq!(
|
||||
log4shell[0]["vulnerability"]["aliases"],
|
||||
serde_json::json!(["GHSA-jfh8-c2jp-5v3q"])
|
||||
);
|
||||
let vulns = cdx["vulnerabilities"].as_array().unwrap();
|
||||
assert_eq!(vulns.len(), 4);
|
||||
assert_eq!(vulns[0]["id"], "CVE-2021-44228");
|
||||
assert_eq!(vulns[0]["analysis"]["state"], "exploitable");
|
||||
let csaf_vulns = csaf["vulnerabilities"].as_array().unwrap();
|
||||
assert_eq!(csaf_vulns.len(), 4);
|
||||
assert_eq!(csaf_vulns[0]["cve"], "CVE-2021-44228");
|
||||
assert!(csaf_vulns[0]["product_status"]
|
||||
.get("under_investigation")
|
||||
.is_none());
|
||||
assert_eq!(
|
||||
csaf_vulns[0]["product_status"]["known_affected"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cyclonedx_sbom_lists_a_vulnerability_under_its_cve_once() {
|
||||
// Arrange: log4j-core's GHSA aliases the CVE NVD also found it under;
|
||||
// lodash has a GHSA without a CVE.
|
||||
let mut sbom = sbom();
|
||||
sbom[0].known_vulnerabilities[0].aliases = vec!["CVE-2021-44228".into()];
|
||||
sbom[0].known_vulnerabilities.push(VulnRef {
|
||||
id: "CVE-2021-44228".into(),
|
||||
source: "nvd".into(),
|
||||
severity: None,
|
||||
url: None,
|
||||
exploitation: None,
|
||||
aliases: Vec::new(),
|
||||
});
|
||||
sbom[1].known_vulnerabilities.push(VulnRef {
|
||||
id: "GHSA-xxxx-yyyy-zzzz".into(),
|
||||
source: "osv".into(),
|
||||
severity: Some("MODERATE".into()),
|
||||
url: None,
|
||||
exploitation: None,
|
||||
aliases: Vec::new(),
|
||||
});
|
||||
|
||||
// Act
|
||||
let doc = sbom_docs::cyclonedx(&sbom, "Pump Remote");
|
||||
|
||||
// Assert
|
||||
assert_eq!(cyclonedx_errors(&doc), Vec::<String>::new());
|
||||
let vulns = doc["vulnerabilities"].as_array().unwrap();
|
||||
assert_eq!(vulns.len(), 2);
|
||||
assert_eq!(vulns[0]["id"], "CVE-2021-44228");
|
||||
assert_eq!(vulns[0]["source"]["name"], "NVD");
|
||||
assert_eq!(vulns[0]["references"][0]["id"], "GHSA-jfh8-c2jp-5v3q");
|
||||
assert_eq!(vulns[0]["affects"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(vulns[0]["ratings"][0]["severity"], "critical");
|
||||
assert_eq!(vulns[1]["id"], "GHSA-xxxx-yyyy-zzzz");
|
||||
assert_eq!(vulns[1]["source"]["name"], "osv");
|
||||
assert!(vulns[1].get("references").is_none());
|
||||
}
|
||||
@@ -24,7 +24,6 @@ server = [
|
||||
"dep:mongodb",
|
||||
"dep:reqwest",
|
||||
"dep:tower-http",
|
||||
"dep:secrecy",
|
||||
"dep:dotenvy",
|
||||
"dep:dioxus-cli-config",
|
||||
"dep:dioxus-fullstack",
|
||||
@@ -36,7 +35,6 @@ server = [
|
||||
"dep:sha2",
|
||||
"dep:base64",
|
||||
"dep:uuid",
|
||||
"dep:bson",
|
||||
"dep:hex",
|
||||
"dep:async-trait",
|
||||
]
|
||||
@@ -67,7 +65,6 @@ gloo-timers = { version = "0.3", features = ["futures"], optional = true }
|
||||
axum = { version = "0.8", optional = true }
|
||||
mongodb = { workspace = true, optional = true }
|
||||
tower-http = { version = "0.6", features = ["cors", "trace", "set-header"], optional = true }
|
||||
secrecy = { workspace = true, optional = true }
|
||||
dotenvy = { version = "0.15", optional = true }
|
||||
tokio = { workspace = true, optional = true }
|
||||
dioxus-cli-config = { version = "=0.7.3", optional = true }
|
||||
@@ -82,4 +79,3 @@ url = { version = "2", optional = true }
|
||||
sha2 = { workspace = true, optional = true }
|
||||
base64 = { version = "0.22", optional = true }
|
||||
uuid = { workspace = true, optional = true }
|
||||
bson = { version = "2", features = ["chrono-0_4"], optional = true }
|
||||
@@ -4447,6 +4447,7 @@ tbody tr:last-child td {
|
||||
|
||||
.cra-violated { background: var(--danger); }
|
||||
.cra-open { background: var(--warning); }
|
||||
.cra-partial { background: var(--info); }
|
||||
.cra-clear { background: var(--success); }
|
||||
.cra-process { background: color-mix(in srgb, var(--accent) 28%, var(--bg-elevated)); }
|
||||
|
||||
@@ -4748,6 +4749,24 @@ tbody tr:last-child td {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* Under the list: how many targets, and how many a page shows. */
|
||||
.targets-pager {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
|
||||
.targets-total {
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.targets-pager .project-filter select {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.targets-row:hover td {
|
||||
background: var(--bg-card-hover);
|
||||
}
|
||||
@@ -4913,11 +4932,52 @@ tbody tr:last-child td {
|
||||
}
|
||||
|
||||
.target-open,
|
||||
.target-pins,
|
||||
.target-vex,
|
||||
.target-manual {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.target-pins-release {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
gap: 6px;
|
||||
margin-bottom: 12px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
/* Wide tables scroll inside the card, never the page. */
|
||||
.target-pins-table {
|
||||
display: block;
|
||||
overflow-x: auto;
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
|
||||
.target-pins-table th,
|
||||
.target-pins-table td {
|
||||
padding: 4px 12px 4px 0;
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.target-pins-table th {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
.target-pins-table code {
|
||||
font-family: var(--font-mono);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.target-findings {
|
||||
list-style: none;
|
||||
}
|
||||
@@ -4986,6 +5046,37 @@ tbody tr:last-child td {
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
/* Webhook deliveries on the target page: one line each, the reason wraps. */
|
||||
.webhook-deliveries {
|
||||
list-style: none;
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
margin-top: 10px;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
|
||||
.webhook-deliveries li {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
gap: 4px 10px;
|
||||
}
|
||||
|
||||
.webhook-deliveries code,
|
||||
.webhook-delivery-time,
|
||||
.webhook-delivery-elapsed {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11.5px;
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
.webhook-delivery-detail {
|
||||
flex: 1 1 200px;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.vex-head {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
|
||||
@@ -9,10 +9,11 @@ use crate::infrastructure::evidence::CraCounts;
|
||||
|
||||
/// The states in reading order: what needs work first, process evidence last.
|
||||
/// Each is (label, CSS modifier, count).
|
||||
fn segments(counts: &CraCounts) -> [(Text, &'static str, u32); 4] {
|
||||
fn segments(counts: &CraCounts) -> [(Text, &'static str, u32); 5] {
|
||||
[
|
||||
(tx::NOT_SATISFIED, "violated", counts.not_satisfied),
|
||||
(tx::NOT_ASSESSED, "open", counts.not_assessed),
|
||||
(tx::PARTIAL, "partial", counts.partial),
|
||||
(tx::NO_VIOLATION, "clear", counts.no_violation_found),
|
||||
(tx::NOT_CODE_CHECKABLE, "process", counts.not_code_checkable),
|
||||
]
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
//! On a Yocto target: the layers its kas files, `repo` manifests and git
|
||||
//! submodules pin, and the Yocto release they make up with its support end.
|
||||
|
||||
use dioxus::prelude::*;
|
||||
|
||||
use compliance_core::models::{
|
||||
display_codename, LayerPins, PinSource, ReleaseBasis, Support, YoctoRelease,
|
||||
};
|
||||
|
||||
use crate::i18n::texts::layer_pins as tx;
|
||||
use crate::i18n::{use_lang, Lang};
|
||||
|
||||
/// How many characters of a commit id are shown (the whole id on hover).
|
||||
const SHORT_COMMIT: usize = 12;
|
||||
|
||||
/// Where a pin is declared, in words.
|
||||
fn source_label(source: PinSource) -> &'static str {
|
||||
match source {
|
||||
PinSource::Kas => "kas",
|
||||
PinSource::RepoManifest => "repo",
|
||||
PinSource::GitSubmodule => "git submodule",
|
||||
}
|
||||
}
|
||||
|
||||
/// The badge class and words of a release's support on `today`.
|
||||
fn support_badge(
|
||||
release: &YoctoRelease,
|
||||
today: chrono::NaiveDate,
|
||||
lang: Lang,
|
||||
) -> (&'static str, &'static str) {
|
||||
match release.support(today) {
|
||||
Support::Ended => ("badge badge-high", tx::ENDED.get(lang)),
|
||||
Support::EndsSoon => ("badge badge-medium", tx::ENDS_SOON.get(lang)),
|
||||
Support::Supported => ("badge badge-success", tx::SUPPORTED.get(lang)),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the release was read from, in words.
|
||||
fn basis_label(basis: &ReleaseBasis, lang: Lang) -> String {
|
||||
match basis {
|
||||
ReleaseBasis::Pin { name, branch } => {
|
||||
format!("{} {name} ({branch})", tx::FROM_PIN.get(lang))
|
||||
}
|
||||
ReleaseBasis::CoreLayer => tx::FROM_CORE.get(lang).to_string(),
|
||||
ReleaseBasis::LayerCompat => tx::FROM_COMPAT.get(lang).to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The "Layer pins" card of a Yocto target.
|
||||
#[component]
|
||||
pub fn LayerPinsCard(pins: LayerPins) -> Element {
|
||||
let lang = use_lang()();
|
||||
let today = chrono::Utc::now().date_naive();
|
||||
rsx! {
|
||||
section { class: "card target-pins",
|
||||
div { class: "target-card-head", h3 { {tx::TITLE.get(lang)} } }
|
||||
div { class: "target-card-body",
|
||||
p { class: "target-pins-release",
|
||||
strong { "{tx::RELEASE.get(lang)}: " }
|
||||
match &pins.release {
|
||||
Some(release) => {
|
||||
let (class, words) = support_badge(release, today, lang);
|
||||
let name = display_codename(&release.codename);
|
||||
let lts = if release.lts { " LTS" } else { "" };
|
||||
rsx! {
|
||||
"{name} {release.version}{lts} "
|
||||
span { class: "{class}", "{words}" }
|
||||
span { class: "target-muted",
|
||||
" {tx::SUPPORT_UNTIL.get(lang)} {release.end_of_life} · {basis_label(&release.basis, lang)}, "
|
||||
code { "{release.file}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
None => rsx! { span { class: "target-muted", {tx::RELEASE_UNKNOWN.get(lang)} } },
|
||||
}
|
||||
}
|
||||
if pins.pins.is_empty() {
|
||||
p { class: "target-muted", {tx::NO_PINS.get(lang)} }
|
||||
} else {
|
||||
table { class: "target-pins-table",
|
||||
thead {
|
||||
tr {
|
||||
th { {tx::LAYER.get(lang)} }
|
||||
th { {tx::BRANCH.get(lang)} }
|
||||
th { {tx::COMMIT.get(lang)} }
|
||||
th { {tx::SOURCE.get(lang)} }
|
||||
}
|
||||
}
|
||||
tbody {
|
||||
for pin in pins.pins.iter() {
|
||||
tr {
|
||||
td { title: pin.url.clone().unwrap_or_default(), "{pin.name}" }
|
||||
td { code { {pin.branch.clone().unwrap_or_else(|| "–".into())} } }
|
||||
td {
|
||||
title: pin.commit.clone().unwrap_or_default(),
|
||||
code { {pin.commit.as_deref().map_or_else(|| "–".into(), short_commit)} }
|
||||
}
|
||||
td { "{source_label(pin.source)} · " code { "{pin.file}" } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !pins.unread_includes.is_empty() {
|
||||
h4 { class: "target-subhead", {tx::UNREAD_INCLUDES.get(lang)} }
|
||||
ul { class: "target-facts",
|
||||
for include in pins.unread_includes.iter() {
|
||||
li { code { "{include}" } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The first [`SHORT_COMMIT`] characters of a commit id.
|
||||
fn short_commit(commit: &str) -> String {
|
||||
commit.chars().take(SHORT_COMMIT).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn commits_are_shortened() {
|
||||
assert_eq!(short_commit("4a2d3b5c6d7e8f9a0b1c"), "4a2d3b5c6d7e");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_release_basis_reads_in_both_languages() {
|
||||
let pin = ReleaseBasis::Pin {
|
||||
name: "poky".into(),
|
||||
branch: "dunfell".into(),
|
||||
};
|
||||
assert_eq!(
|
||||
basis_label(&pin, Lang::De),
|
||||
"aus dem Stand von poky (dunfell)"
|
||||
);
|
||||
assert_eq!(
|
||||
basis_label(&pin, Lang::En),
|
||||
"from the pin of poky (dunfell)"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ pub mod evidence_button;
|
||||
pub mod file_tree;
|
||||
pub mod help_chat;
|
||||
pub mod lang_toggle;
|
||||
pub mod layer_pins;
|
||||
pub mod manual_findings;
|
||||
pub mod markdown;
|
||||
pub mod no_access;
|
||||
@@ -26,3 +27,4 @@ pub mod support;
|
||||
pub mod theme_toggle;
|
||||
pub mod toast;
|
||||
pub mod vex_panel;
|
||||
pub mod webhook_deliveries;
|
||||
Loaded 100 of 154 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user