diff --git a/.cargo/config.toml b/.cargo/config.toml index 54e07b717..5edc7bacd 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,3 +1,5 @@ [alias] patchable = ["run", "--bin", "patchable", "--"] boil = ["run", "--bin", "boil", "--"] +# Release build, it parses a few hundred megabytes of JSON. +sbom-quality = ["run", "--release", "--bin", "sbom-quality", "--"] diff --git a/.github/workflows/sbom_quality.yaml b/.github/workflows/sbom_quality.yaml new file mode 100644 index 000000000..aad8dcd68 --- /dev/null +++ b/.github/workflows/sbom_quality.yaml @@ -0,0 +1,83 @@ +--- +# Checks the SBOMs attested to the 0.0.0-dev images, see rust/sbom-quality/README.md. +# +# The run fails if there is at least one error finding (or if the check itself fails), so the +# status of the latest run is the status of our SBOMs. It does not notify anyone by itself. +name: SBOM quality + +on: + schedule: + - cron: 30 7 * * * # https://crontab.guru/#30_7_*_*_* + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }} + cancel-in-progress: false + +env: + RUST_TOOLCHAIN_VERSION: 1.99.0 + # renovate: datasource=github-releases packageName=google/go-containerregistry + CRANE_VERSION: v0.21.6 + +jobs: + check: + name: Check SBOMs + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Setup Rust Toolchain + run: rustup toolchain install "${RUST_TOOLCHAIN_VERSION}" + + - name: Set up cosign + uses: sigstore/cosign-installer@6f9f17788090df1f26f669e9d70d6ae9567deba6 # v4.1.2 + + # Built from source with the Go toolchain of the runner, which verifies the module against + # the Go checksum database. + - name: Set up crane + run: | + set -euo pipefail + go install "github.com/google/go-containerregistry/cmd/crane@${CRANE_VERSION}" + echo "$(go env GOPATH)/bin" >> "$GITHUB_PATH" + + - name: Build sbom-quality + run: cargo build --release --package sbom-quality + + - name: Check SBOMs + run: | + set -uo pipefail + + # The summary per check, in the log and on the summary page of the run. + ./target/release/sbom-quality --cache-dir "$RUNNER_TEMP/sboms" | tee "$RUNNER_TEMP/report.txt" + status=${PIPESTATUS[0]} + + { + echo "## SBOM quality" + echo + case "$status" in + 0) echo "All SBOMs fulfil the expectations." ;; + 1) echo "Some SBOMs do not fulfil the expectations." ;; + *) echo "The check itself failed (exit code $status), see the log." ;; + esac + echo + echo '```text' + cat "$RUNNER_TEMP/report.txt" + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + + # Every finding and every affected image. The attestations are cached by now, so this + # takes seconds. + if [ "$status" -ne 0 ]; then + echo "::group::Every finding" + ./target/release/sbom-quality --cache-dir "$RUNNER_TEMP/sboms" --verbose + echo "::endgroup::" + fi + + exit "$status" diff --git a/Cargo.lock b/Cargo.lock index 7ea70b45c..af2924163 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -53,7 +53,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -64,7 +64,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -79,6 +79,12 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + [[package]] name = "aws-lc-rs" version = "1.18.1" @@ -102,6 +108,12 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "base64" version = "0.23.1" @@ -141,6 +153,12 @@ dependencies = [ "url", ] +[[package]] +name = "borrow-or-share" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0b364ead1874514c8c2855ab558056ebfeb775653e7ae45ff72f28f8f3166c" + [[package]] name = "bumpalo" version = "3.20.3" @@ -167,7 +185,7 @@ dependencies = [ "maybe-owned", "rustix", "rustix-linux-procfs", - "windows-sys 0.60.2", + "windows-sys 0.61.2", "winx", ] @@ -378,6 +396,41 @@ dependencies = [ "libc", ] +[[package]] +name = "cyclonedx-bom" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f8e9344d60bee3c88033b26d7b233815ae12855bdce5370b66368ae13ac8ac" +dependencies = [ + "base64 0.22.1", + "cyclonedx-bom-macros", + "fluent-uri", + "indexmap", + "once_cell", + "ordered-float", + "purl", + "regex", + "serde", + "serde_json", + "spdx", + "strum 0.28.0", + "thiserror", + "time", + "uuid", + "xml-rs", +] + +[[package]] +name = "cyclonedx-bom-macros" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c50341f21df64b412b4f917e34b7aa786c092d64f3f905f478cb76950c7e980c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "darling" version = "0.20.11" @@ -500,7 +553,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -515,6 +568,17 @@ version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" +[[package]] +name = "fluent-uri" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc74ac4d8359ae70623506d512209619e5cf8f347124910440dbc221714b328e" +dependencies = [ + "borrow-or-share", + "ref-cast", + "serde", +] + [[package]] name = "fnv" version = "1.0.7" @@ -523,9 +587,9 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -682,6 +746,12 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + [[package]] name = "http" version = "1.5.0" @@ -772,7 +842,7 @@ version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ - "base64", + "base64 0.23.1", "bytes", "futures-channel", "futures-util", @@ -1099,9 +1169,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.31" +version = "1.1.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff20308ecabd635a2dc1dd5834a86c462cca20efba1d5d3ddab1f8aea3455cb2" +checksum = "fee3f59f4321dab0c78d828942e7aa09d0bd8ad6e78a501977e6bf3d02938045" dependencies = [ "cc", "libc", @@ -1183,7 +1253,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -1192,6 +1262,15 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + [[package]] name = "oci-spec" version = "0.10.0" @@ -1245,6 +1324,15 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "ordered-float" +version = "5.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab" +dependencies = [ + "num-traits", +] + [[package]] name = "patchable" version = "0.1.0" @@ -1329,6 +1417,17 @@ dependencies = [ "unicase", ] +[[package]] +name = "purl" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60ebe4262ae91ddd28c8721111a0a6e9e58860e211fc92116c4bb85c98fd96ad" +dependencies = [ + "hex", + "percent-encoding", + "thiserror", +] + [[package]] name = "quinn" version = "0.11.12" @@ -1383,7 +1482,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -1427,6 +1526,26 @@ dependencies = [ "rand_core", ] +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.8", +] + [[package]] name = "regex" version = "1.13.1" @@ -1468,7 +1587,7 @@ version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" dependencies = [ - "base64", + "base64 0.23.1", "bytes", "encoding_rs", "futures-core", @@ -1570,7 +1689,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -1637,7 +1756,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -1673,6 +1792,27 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "sbom-quality" +version = "0.1.0" +dependencies = [ + "base64 0.23.1", + "clap", + "cyclonedx-bom", + "glob", + "oci-spec", + "purl", + "regex", + "rstest", + "serde", + "serde_json", + "snafu", + "spdx", + "tempfile", + "time", + "toml", +] + [[package]] name = "schannel" version = "0.1.29" @@ -1859,7 +1999,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", +] + +[[package]] +name = "spdx" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "646c5a367da914e3babcb9cd8e91c37ccaac42325b8f86f036513ad103f2a716" +dependencies = [ + "smallvec", ] [[package]] @@ -1992,7 +2141,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2334,9 +2483,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", @@ -2357,6 +2506,17 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "uuid" +version = "1.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "wasm-bindgen", +] + [[package]] name = "valuable" version = "0.1.1" @@ -2506,7 +2666,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2734,6 +2894,12 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +[[package]] +name = "xml-rs" +version = "0.8.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" + [[package]] name = "yoke" version = "0.8.3" diff --git a/Cargo.toml b/Cargo.toml index 200c5750d..aac8def66 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,14 +8,17 @@ authors = ["Stackable "] license = "Apache-2.0" [workspace.dependencies] +base64 = "0.23" cap-std = "4.0" clap = { version = "4.6", features = ["derive"] } clap_complete = "4.6" clap_complete_nushell = "4.6" +cyclonedx-bom = "0.9" git2 = { version = "0.21", features = ["cred", "ssh", "https"] } glob = "0.3" humansize = "2.1" oci-spec = "0.10" +purl = { version = "0.1.6", default-features = false } reqwest = { version = "0.13", features = ["json"] } rstest = "0.27" secrecy = "0.10" @@ -24,6 +27,7 @@ semver = "1.0" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" snafu = "0.9" +spdx = "0.13" strum = { version = "0.28", features = ["derive"] } tempfile = "3.27" time = { version = "0.3", features = ["parsing", "formatting"] } diff --git a/deny.toml b/deny.toml index f446cc193..ba377c43b 100644 --- a/deny.toml +++ b/deny.toml @@ -104,6 +104,12 @@ license-files = [ { path = "LICENSE", hash = 0x001c7e6c }, ] +# MIT-0 is MIT without the attribution requirement. borrow-or-share is a dependency of fluent-uri, +# which cyclonedx-bom (used by sbom-quality) requires. +[[licenses.exceptions]] +name = "borrow-or-share" +allow = ["MIT-0"] + [sources] unknown-registry = "deny" unknown-git = "deny" diff --git a/rust/sbom-quality/Cargo.toml b/rust/sbom-quality/Cargo.toml new file mode 100644 index 000000000..59acc3642 --- /dev/null +++ b/rust/sbom-quality/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "sbom-quality" +version = "0.1.0" +authors.workspace = true +edition = "2024" +license.workspace = true +publish = false +repository.workspace = true +description = "Checks the quality of the SBOMs that are attested to the published images" + +[dependencies] +base64.workspace = true +clap.workspace = true +cyclonedx-bom.workspace = true +glob.workspace = true +oci-spec.workspace = true +purl.workspace = true +regex.workspace = true +serde.workspace = true +serde_json.workspace = true +snafu.workspace = true +spdx.workspace = true +time.workspace = true +toml.workspace = true + +[dev-dependencies] +rstest.workspace = true +tempfile.workspace = true + +[lints] +workspace = true diff --git a/rust/sbom-quality/README.md b/rust/sbom-quality/README.md new file mode 100644 index 000000000..765a75799 --- /dev/null +++ b/rust/sbom-quality/README.md @@ -0,0 +1,124 @@ +# SBOM quality check + +`sbom-quality` checks the SBOMs that are attested to our published images: every product version +and every operator, both architectures, CycloneDX and SPDX. It is meant to run daily against the +`0.0.0-dev` images, so that a change that makes the SBOMs worse is noticed within a day instead +of at the next manual audit. + +The SBOMs are produced when an image is published, by syft and mergebom in the `publish-image` +action of [stackabletech/actions](https://github.com/stackabletech/actions), from the image +contents and from the SBOMs that the product builds embed into the image. A Dockerfile change, a +new product version, a syft update or a failing attestation step can all break them without +breaking the build. + +## Usage + +Run it from the root of the repository: + +```shell +cargo sbom-quality # everything in expectations.toml +cargo sbom-quality kafka opa=1.20.2 # some products, versions or operators +cargo sbom-quality --arch amd64 --verbose # one architecture, every finding and image +cargo sbom-quality --format json # for a machine +cargo sbom-quality --cache-dir /tmp/sboms # keep the attestations between runs +``` + +It needs `crane` and `cosign` on the `PATH` and no registry credentials. A full run fetches +about 300 attestations and takes a few minutes. Attestations are immutable per image +digest, so with `--cache-dir` a second run takes seconds. + +The exit code is 1 if there is at least one error, warnings do not change it. It is 2 if the +check itself fails, for example on an invalid expectations file. + +Two local files can be checked instead of the registry, for example the output of mergebom +before it is published: + +```shell +cargo sbom-quality kafka=4.3.1 --arch amd64 \ + --cyclonedx sbom.cdx.json --spdx sbom.spdx.json --digest sha256:... +``` + +## Daily run + +The [SBOM quality](../../.github/workflows/sbom_quality.yaml) workflow runs the check every day +at 07:30 UTC, after the scheduled image builds, and can be started by hand. A run fails if there +is at least one error finding, so the status of the latest run is the status of our SBOMs. It +does not notify anyone, something outside has to watch it. + +A failed run shows the summary per check on its summary page and in the log. The log also has +every finding with every affected image, in the collapsed group "Every finding". + +## What is checked + +Invariants, the same for every image. Most of them are defects we had at some point. + +| Check | What it guards | +| --- | --- | +| `image-missing` | The tag exists and has an image for every architecture. | +| `attestation-cyclonedx`, `attestation-spdxjson` | The attestation exists and cosign verifies it against our GitHub workflows. | +| `cdx-format`, `spdx-format` | Format versions, our own SPDX namespace. | +| `cdx-schema` | The document is valid CycloneDX according to the [cyclonedx-bom](https://crates.io/crates/cyclonedx-bom) crate: serial number, SPDX license IDs and expressions, purls, hashes, enum values, unique bom-refs, no dangling dependencies. One finding per field, not per component. | +| `cdx-root-identity`, `spdx-root` | The SBOM describes exactly this image: name, tag, architecture and digest. | +| `cdx-root-metadata`, `cdx-document-metadata`, `spdx-creation-info` | Supplier, manufacturer, license, description, authors, lifecycle, syft and mergebom as tools. | +| `cdx-component-identity`, `cdx-component-version`, `cdx-purl`, `spdx-packages` | Components have a name, a bom-ref, a version and a purl. | +| `cdx-duplicate-purls` | mergebom merged the components that syft reports twice. | +| `cdx-rpm-versions` | No RPM in two versions, which is what scanning all layers instead of the final filesystem produces. | +| `cdx-file-components`, `cdx-syft-properties`, `cdx-size` (warning) | Nothing that only bloats the document. Rekor rejects attestations that get too large. | +| `cdx-operating-system` | One operating system component, and installed RPMs carry its namespace and the `distro` qualifier. | +| `cdx-dependency-graph`, `spdx-relationships` | Every component is reachable from the image, and SPDX relationships point to existing packages. | +| `spdx-supplier` | We are the supplier of the image, not of the packages in it. | +| `spdx-license-refs` | Every `LicenseRef-` is declared. Strict SPDX parsers reject the document otherwise. | +| `spdx-license-expressions` | Every license is a valid SPDX expression according to the [spdx](https://crates.io/crates/spdx) crate. | +| `spdx-matches-cyclonedx` | Both documents list the same packages. | +| `architectures-agree` | amd64 and arm64 list the same components (names, not versions). | +| `image-age` (warning) | The image is not older than the scheduled builds allow. | + +Expectations per product, from `expectations.toml`. These notice what the invariants cannot: an +SBOM without the Python packages of Airflow is still a valid SBOM. + +| Check | What it guards | +| --- | --- | +| `main-component` | The product itself is listed, in the version the image is tagged with. | +| `embedded-sbom` | Components come from each build-time SBOM that the image is supposed to contain. | +| `component-count` | At least so many components in total, per ecosystem (`maven`) and per ecosystem from build-time SBOMs (`embedded-maven`). | +| `license-coverage` | At least this share of the components has a license. | +| `expectations` | Every product that boil builds is listed, and no expectation is left for a removed version. | + +Licenses are checked as strictly as mergebom writes them, in both documents: deprecated SPDX IDs +like `BSD-2-Clause-FreeBSD` are valid, since they are still on the license list. IDs have to be +spelled as on the license list. SPDX itself matches them case-insensitively, but the spdx crate +and cyclonedx-bom do not, so mergebom fixes the case. + +The counts from build-time SBOMs are separate because syft finds most jars and Python packages +on its own as well. If the build-time SBOM of Kafka is lost, the number of Maven components +hardly changes, but the purls get worse and everything shaded disappears. + +## Expectations + +`expectations.toml` documents its own format at the top. The component floors are generated: + +```shell +cargo sbom-quality --suggest-floors # all products +cargo sbom-quality --suggest-floors airflow # one product +``` + +This prints tables to paste, with the smallest count over all versions and architectures minus +20%. It also suggests `embedded-sboms`, but review that list: mergebom keeps one location per +merged component, so a small build-time SBOM that overlaps with a bigger one may have no +component left that points to it. + +When a check fails: + +- Something broke: fix the image or the pipeline. +- A count dropped for a good reason (a dependency cleanup, a new major version): lower the floor. + If only one version differs, use `[products..versions.""]`. +- A deviation is known and accepted: add the check ID to `ignore` of the product, with a comment. + +A new product needs a `[products.]` table (or an entry in `unchecked`), the check fails +until it has one. A new version of an existing product needs nothing. + +## Tests + +```shell +cargo test -p sbom-quality +``` diff --git a/rust/sbom-quality/expectations.toml b/rust/sbom-quality/expectations.toml new file mode 100644 index 000000000..b97b7c46a --- /dev/null +++ b/rust/sbom-quality/expectations.toml @@ -0,0 +1,419 @@ +# What sbom-quality expects from the SBOMs of our images. See README.md. +# +# The settings below apply to every image. [operators] and each [products.] can override +# them and add: +# +# main-component purl of the product itself, which has to be listed in the version of +# the image. "{version}" also matches "{version}-stackable0.0.0-dev". +# embedded-sboms build-time SBOMs in the image that components have to come from. +# min-components smallest allowed number of components: `total`, per purl type +# (`maven`) and per purl type from build-time SBOMs (`embedded-maven`). +# min-license-coverage smallest allowed share of components with a license. +# ignore IDs of checks whose findings are accepted. Say why in a comment. +# versions."" any of the above for one version that differs from the others. +# +# {version}, {release} and {image} are replaced in main-component and embedded-sboms. +# +# The numbers were generated with `cargo sbom-quality --suggest-floors` (20% below the smallest +# count of any version and architecture). Lower one when a count dropped for a good reason, and +# raise them now and then, a floor far below reality catches nothing. + +registry = "oci.stackable.tech/sdp" +release = "0.0.0-dev" +architectures = ["amd64", "arm64"] + +# What publish-image writes once stackabletech/actions#153 and #154 are in use. +cyclonedx-spec-version = "1.7" + +# The dev images are rebuilt every two days. An older image means the build is failing, and +# then its SBOM does not describe what main would produce either. +max-image-age-days = 7 + +# Purl namespace of the installed RPMs and name of the operating-system component. +operating-system = "redhat" + +# Share of components that may lack a purl or a version. A few really have neither, like the +# launcher stubs that pip ships or the jars of a JDK. +max-without-purl = 0.05 +max-without-version = 0.05 + +# Directories with a boil-config.toml that are not checked: intermediate images and optional +# test images, which SDP customers do not use. Every other one needs a [products.] table, +# so a new product cannot be forgotten here. +unchecked = [ + "java-base", + "java-devel", + "jdk-base", + "kafka-testing-tools", + "krb5", + "spark-connect-client", + "stackable-base", + "stackable-devel", + "testing-tools", + "tools", + "trino-cli", + "vector", +] + +[operators] +images = [ + "airflow-operator", + "commons-operator", + "druid-operator", + "hbase-operator", + "hdfs-operator", + "hive-operator", + "kafka-operator", + "listener-operator", + "nifi-operator", + "opa-operator", + "opensearch-operator", + "secret-operator", + "spark-k8s-operator", + "superset-operator", + "trino-operator", + "zookeeper-operator", +] +main-component = "pkg:cargo/stackable-{image}@{release}" +min-license-coverage = 0.95 +embedded-sboms = [ + "/usr/local/bin/stackable-{image}_bin.cdx.xml", +] + +[operators.min-components] +total = 350 +rpm = 84 +cargo = 270 +embedded-cargo = 270 + +[products.airflow] +main-component = "pkg:pypi/apache-airflow@{version}" +min-license-coverage = 0.88 +embedded-sboms = [ + "/stackable/app/airflow-ui-{version}.cdx.json", + "/stackable/app/airflow-{version}.cdx.json", + "/stackable/cert-tools_bin.cdx.xml", + "/stackable/config-utils.cdx.xml", + "/stackable/containerdebug_bin.cdx.xml", + "/stackable/statsd_exporter-*.cdx.json", + "/usr/local/bin/vector_bin.cdx.xml", +] + +[products.airflow.min-components] +total = 1900 +rpm = 170 +cargo = 890 +golang = 38 +npm = 300 +pypi = 520 +embedded-cargo = 890 +embedded-golang = 23 +embedded-npm = 290 +embedded-pypi = 510 + +[products.druid] +main-component = "pkg:maven/org.apache.druid/druid-server@{version}" +min-license-coverage = 0.8 +embedded-sboms = [ + "/stackable/apache-druid-{version}-stackable{release}/apache-druid-{version}-stackable{release}.cdx.json", + "/stackable/apache-druid-{version}-stackable{release}/druid-web-console-{version}-stackable{release}.cdx.json", + "/stackable/cert-tools_bin.cdx.xml", + "/stackable/config-utils.cdx.xml", + "/stackable/containerdebug_bin.cdx.xml", + "/usr/local/bin/vector_bin.cdx.xml", +] + +[products.druid.min-components] +total = 1600 +rpm = 110 +cargo = 890 +maven = 490 +npm = 140 +embedded-cargo = 890 +embedded-maven = 190 +embedded-npm = 140 + +[products.hadoop] +main-component = [ + "pkg:maven/org.apache.hadoop/hadoop-common@{version}", + "pkg:maven/org.apache.hadoop/hadoop-hdfs@{version}", +] +min-license-coverage = 0.89 +embedded-sboms = [ + "/stackable/cert-tools_bin.cdx.xml", + "/stackable/config-utils.cdx.xml", + "/stackable/containerdebug_bin.cdx.xml", + "/stackable/hadoop-{version}-stackable{release}/hadoop-webapps-{version}-stackable{release}.cdx.json", + "/stackable/hadoop-{version}-stackable{release}/hadoop-{version}-stackable{release}.cdx.json", + "/usr/local/bin/vector_bin.cdx.xml", +] + +[products.hadoop.min-components] +total = 1200 +rpm = 110 +cargo = 890 +maven = 230 +embedded-cargo = 890 +embedded-maven = 110 + +[products.hadoop.versions."3.3.6"] +min-license-coverage = 0.73 + +[products.hbase] +main-component = "pkg:maven/org.apache.hbase/hbase-server@{version}" +min-license-coverage = 0.7 +embedded-sboms = [ + "/stackable/cert-tools_bin.cdx.xml", + "/stackable/config-utils.cdx.xml", + "/stackable/containerdebug_bin.cdx.xml", + "/stackable/hbase-operator-tools-*/hbase-operator-tools-*-hbase{version}-stackable{release}.cdx.json", + "/stackable/hbase-{version}-stackable{release}/hbase-webapps-{version}-stackable{release}.cdx.json", + "/stackable/hbase-{version}-stackable{release}/hbase-{version}-stackable{release}.cdx.json", + "/usr/local/bin/vector_bin.cdx.xml", +] + +[products.hbase.min-components] +total = 1700 +rpm = 120 +cargo = 890 +maven = 660 +npm = 76 +embedded-cargo = 890 +embedded-maven = 170 +embedded-npm = 76 + +[products.hive] +main-component = "pkg:maven/org.apache.hive/hive-standalone-metastore-server@{version}" +min-license-coverage = 0.69 +embedded-sboms = [ + "/stackable/apache-hive-metastore-{version}-stackable{release}-bin/*.cdx.json", + "/stackable/cert-tools_bin.cdx.xml", + "/stackable/config-utils.cdx.xml", + "/stackable/containerdebug_bin.cdx.xml", + "/stackable/hadoop-*/hadoop-*.cdx.json", + "/usr/local/bin/vector_bin.cdx.xml", +] + +[products.hive.min-components] +total = 1500 +rpm = 110 +cargo = 890 +maven = 570 +embedded-cargo = 890 +embedded-maven = 190 + +[products.hive.versions."3.1.3"] +main-component = "pkg:maven/org.apache.hive/hive-standalone-metastore@{version}" + +[products.kafka] +main-component = "pkg:maven/org.apache.kafka/kafka-clients@{version}" +min-license-coverage = 0.9 +embedded-sboms = [ + "/stackable/cert-tools_bin.cdx.xml", + "/stackable/config-utils.cdx.xml", + "/stackable/containerdebug_bin.cdx.xml", + "/stackable/kafka_2.13-{version}-stackable{release}/kafka_2.13-{version}-stackable{release}.cdx.json", + "/usr/local/bin/vector_bin.cdx.xml", +] + +[products.kafka.min-components] +total = 1100 +rpm = 110 +cargo = 890 +maven = 130 +embedded-cargo = 890 +embedded-maven = 91 + +[products.nifi] +main-component = "pkg:maven/org.apache.nifi/nifi-runtime@{version}" +min-license-coverage = 0.76 +embedded-sboms = [ + "/stackable/cert-tools_bin.cdx.xml", + "/stackable/config-utils.cdx.xml", + "/stackable/containerdebug_bin.cdx.xml", + "/stackable/nifi-{version}-stackable{release}/nifi-framework-nar.cdx.json", + "/stackable/nifi-{version}-stackable{release}/nifi-frontend-{version}-stackable{release}.cdx.json", + "/stackable/nifi-{version}-stackable{release}/nifi-standard-nar.cdx.json", + "/stackable/nifi-{version}-stackable{release}/nifi-{version}-stackable{release}.cdx.json", + "/usr/local/bin/vector_bin.cdx.xml", +] + +[products.nifi.min-components] +total = 2900 +rpm = 180 +cargo = 890 +golang = 12 +maven = 1700 +npm = 110 +embedded-cargo = 890 +embedded-maven = 1100 +embedded-npm = 110 + +[products.omid] +main-component = "pkg:maven/org.apache.omid/omid-tso-server@{version}" +min-license-coverage = 0.91 +embedded-sboms = [ + "/stackable/cert-tools_bin.cdx.xml", + "/stackable/config-utils.cdx.xml", + "/stackable/containerdebug_bin.cdx.xml", + "/stackable/omid-examples-{version}-stackable{release}/omid-examples-{version}-stackable{release}.cdx.json", + "/stackable/omid-tso-server-{version}-stackable{release}/omid-tso-server-{version}-stackable{release}.cdx.json", + "/usr/local/bin/vector_bin.cdx.xml", +] + +[products.omid.min-components] +total = 1100 +rpm = 110 +cargo = 890 +maven = 140 +embedded-cargo = 890 +embedded-maven = 97 + +[products.opa] +main-component = "pkg:golang/github.com/open-policy-agent/opa@v{version}" +min-license-coverage = 0.94 +embedded-sboms = [ + "/stackable/cert-tools_bin.cdx.xml", + "/stackable/config-utils.cdx.xml", + "/stackable/containerdebug_bin.cdx.xml", + "/stackable/opa/opa_{version}-stackable{release}.cdx.json", + "/usr/local/bin/vector_bin.cdx.xml", +] + +[products.opa.min-components] +total = 1000 +rpm = 92 +cargo = 890 +golang = 79 +embedded-cargo = 890 +embedded-golang = 76 + +[products.opensearch] +main-component = "pkg:maven/org.opensearch/opensearch@{version}" +min-license-coverage = 0.81 +embedded-sboms = [ + "/stackable/cert-tools_bin.cdx.xml", + "/stackable/config-utils.cdx.xml", + "/stackable/containerdebug_bin.cdx.xml", + "/stackable/opensearch-prometheus-exporter-{version}.0-stackable{release}.cdx.json", + "/stackable/opensearch-security-{version}.0-stackable{release}.cdx.json", + "/stackable/opensearch-{version}-stackable{release}.cdx.json", + "/usr/local/bin/vector_bin.cdx.xml", +] + +[products.opensearch.min-components] +total = 1500 +rpm = 110 +cargo = 890 +maven = 570 +embedded-cargo = 890 +embedded-maven = 250 + +[products.opensearch-dashboards] +main-component = "pkg:npm/opensearch-dashboards@{version}" +min-license-coverage = 0.9 +embedded-sboms = [ + "/stackable/cert-tools_bin.cdx.xml", + "/stackable/config-utils.cdx.xml", + "/stackable/containerdebug_bin.cdx.xml", + "/stackable/opensearch-dashboards-{version}-stackable{release}.cdx.json", + "/usr/local/bin/vector_bin.cdx.xml", +] + +[products.opensearch-dashboards.min-components] +total = 2100 +rpm = 90 +cargo = 890 +npm = 1100 +embedded-cargo = 890 +embedded-npm = 1000 + +[products.spark-k8s] +main-component = "pkg:maven/org.apache.spark/spark-core_2.13@{version}" +min-license-coverage = 0.65 +embedded-sboms = [ + "/stackable/cert-tools_bin.cdx.xml", + "/stackable/config-utils.cdx.xml", + "/stackable/containerdebug_bin.cdx.xml", + "/stackable/spark/spark-web-ui-{version}-stackable{release}.cdx.json", + "/stackable/spark/spark-{version}-stackable{release}.cdx.json", + "/usr/local/bin/vector_bin.cdx.xml", +] + +[products.spark-k8s.min-components] +total = 1900 +rpm = 120 +cargo = 890 +maven = 900 +embedded-cargo = 890 +embedded-maven = 250 + +[products.superset] +main-component = "pkg:pypi/apache-superset@{version}" +min-license-coverage = 0.9 +embedded-sboms = [ + "/stackable/app/superset-frontend-{version}.cdx.json", + "/stackable/app/superset-{version}.cdx.json", + "/stackable/cert-tools_bin.cdx.xml", + "/stackable/config-utils.cdx.xml", + "/stackable/containerdebug_bin.cdx.xml", + "/stackable/statsd_exporter-*.cdx.json", + "/usr/local/bin/vector_bin.cdx.xml", +] + +[products.superset.min-components] +total = 2100 +rpm = 120 +cargo = 890 +golang = 24 +npm = 940 +pypi = 150 +embedded-cargo = 890 +embedded-golang = 23 +embedded-npm = 940 +embedded-pypi = 140 + +[products.superset.versions."4.1.4"] +min-license-coverage = 0.49 + +[products.trino] +main-component = "pkg:maven/io.trino/trino-server@{version}" +min-license-coverage = 0.78 +embedded-sboms = [ + "/stackable/cert-tools_bin.cdx.xml", + "/stackable/config-utils.cdx.xml", + "/stackable/containerdebug_bin.cdx.xml", + "/stackable/trino-server-{version}-stackable{release}/trino-server-{version}-stackable{release}.cdx.json", + "/stackable/trino-server-{version}-stackable{release}/trino-web-ui-vendor-{version}-stackable{release}.cdx.json", + "/stackable/trino-server-{version}-stackable{release}/trino-web-ui-{version}-stackable{release}.cdx.json", + "/usr/local/bin/vector_bin.cdx.xml", +] + +[products.trino.min-components] +total = 2000 +rpm = 120 +cargo = 890 +maven = 860 +npm = 170 +embedded-cargo = 890 +embedded-maven = 550 +embedded-npm = 170 + +[products.zookeeper] +main-component = "pkg:maven/org.apache.zookeeper/zookeeper@{version}" +min-license-coverage = 0.93 +embedded-sboms = [ + "/stackable/apache-zookeeper-{version}-stackable{release}-bin/apache-zookeeper-{version}-stackable{release}.cdx.json", + "/stackable/cert-tools_bin.cdx.xml", + "/stackable/config-utils.cdx.xml", + "/stackable/containerdebug_bin.cdx.xml", + "/usr/local/bin/vector_bin.cdx.xml", +] + +[products.zookeeper.min-components] +total = 1000 +rpm = 110 +cargo = 890 +maven = 48 +embedded-cargo = 890 +embedded-maven = 33 diff --git a/rust/sbom-quality/src/check/cyclonedx.rs b/rust/sbom-quality/src/check/cyclonedx.rs new file mode 100644 index 000000000..f8ba2cd32 --- /dev/null +++ b/rust/sbom-quality/src/check/cyclonedx.rs @@ -0,0 +1,849 @@ +//! Checks of the CycloneDX SBOM. + +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::LazyLock, +}; + +use cyclonedx_bom::{ + models::bom::Bom, + validation::{Validate, ValidationErrorsKind, ValidationResult}, +}; +use regex::Regex; +use serde_json::Value; +use time::OffsetDateTime; + +use super::{ + ImageResult, ORGANIZATION, describe, duplicates, examples, expected_image_purl, + is_valid_license, matches_version, occurrences, parse_timestamp, percent, share, substitute, +}; +use crate::{ + expectations::Expectations, + purl::{Purl, percent_decode}, + sbom::{Component, CycloneDx, Metadata}, +}; + +const EMBEDDED_SBOM_CATALOGER: &str = "sbom-cataloger"; +const RPM_DATABASE_CATALOGER: &str = "rpm-db-cataloger"; +const IMAGE_LABEL_PREFIX: &str = "syft:image:labels:"; + +/// Rekor rejected the attestation of a 20 MB SBOM, so an SBOM that grows towards that is worth a +/// warning before the attestation step starts to fail. +const MAX_SBOM_BYTES: usize = 12 * 1024 * 1024; + +/// RPMs that are legitimately installed in several versions. +const MULTI_VERSION_RPMS: [&str; 4] = ["gpg-pubkey", "kernel", "kernel-core", "kernel-modules"]; + +/// A license of a component in the paths of cyclonedx-bom's validation errors. +static LICENSE_PATH: LazyLock = LazyLock::new(|| { + Regex::new( + r"^(?:components\[(?P\d+)\]|metadata\.component)\.licenses\[(?P\d+)\]\.(?:expression|license\.license_identifier\.SpdxId)$", + ) + .expect("static string must be a valid regular expression") +}); + +static INDEX_IN_PATH: LazyLock = LazyLock::new(|| { + Regex::new(r"\[\d+\]").expect("static string must be a valid regular expression") +}); + +/// The only syft properties mergebom keeps on a component. Everything else is bookkeeping that +/// bloats the document. +static KEPT_SYFT_PROPERTY: LazyLock = LazyLock::new(|| { + Regex::new(r"^syft:(package:foundBy|metadata:virtualPath|location:\d+:path)$") + .expect("static string must be a valid regular expression") +}); + +static LOCATION_PROPERTY: LazyLock = LazyLock::new(|| { + Regex::new(r"^syft:location:\d+:path$") + .expect("static string must be a valid regular expression") +}); + +static INDEX: LazyLock = LazyLock::new(|| { + Regex::new(r":\d+:").expect("static string must be a valid regular expression") +}); + +/// Validates the SBOM with the cyclonedx-bom crate, against its own specification version. +/// +/// This catches what the other checks do not look at: invalid SPDX license IDs and expressions, +/// malformed purls and hashes, unknown enum values, duplicate bom-refs and dependencies that +/// point to no component. The crate reads the document strictly, so unlike the other checks it +/// cannot say anything about a document it fails to read. +pub fn check_schema(result: &mut ImageResult, json: &str, lenient: &CycloneDx) { + let bom = match Bom::parse_from_json(json.as_bytes()) { + Ok(bom) => bom, + Err(error) => { + result.error( + "cdx-schema", + format!("the SBOM is not valid CycloneDX: {error}"), + ); + return; + } + }; + + let mut errors = Vec::new(); + flatten_validation(bom.validate_version(bom.spec_version), "", &mut errors); + // cyclonedx-bom also rejects deprecated SPDX IDs. The SPDX check accepts them, so this one + // does as well, see `is_valid_license`. + errors.retain(|(path, _)| !license_at(lenient, path).is_some_and(is_valid_license)); + + // One finding per field, not per component: an invalid license of every RPM is one problem. + let mut by_field = BTreeMap::>::new(); + for (path, message) in errors { + let field = INDEX_IN_PATH.replace_all(&path, "[N]").into_owned(); + by_field.entry(field).or_default().push(message); + } + for (field, messages) in by_field { + result.error( + "cdx-schema", + format!( + "{field}: {count} errors, e.g. {examples}", + count = messages.len(), + examples = examples(&messages), + ), + ); + } +} + +/// The license that a validation error path like `components[3].licenses[0].expression` points +/// to. +fn license_at<'a>(bom: &'a CycloneDx, path: &str) -> Option<&'a str> { + let captures = LICENSE_PATH.captures(path)?; + let component = match captures.name("component") { + Some(index) => bom.components.get(index.as_str().parse::().ok()?)?, + None => bom.metadata.component.as_ref()?, + }; + let license = component + .licenses + .get(captures.name("license")?.as_str().parse::().ok()?)?; + license + .get("expression") + .or_else(|| license.pointer("/license/id"))? + .as_str() +} + +/// Turns the nested validation result into (path, message) pairs, like +/// `components[3].licenses[0].expression`. +fn flatten_validation(result: ValidationResult, path: &str, errors: &mut Vec<(String, String)>) { + for (name, kind) in result.errors() { + // Wrappers like `Components` nest their content under `inner`. + let path = match name.as_str() { + "" | "inner" => path.to_owned(), + name if path.is_empty() => name.to_owned(), + name => format!("{path}.{name}"), + }; + let path_or_document = || { + if path.is_empty() { + "document".to_owned() + } else { + path.clone() + } + }; + match kind { + ValidationErrorsKind::Struct(nested) => flatten_validation(nested, &path, errors), + ValidationErrorsKind::List(items) => { + for (index, nested) in items { + flatten_validation(nested, &format!("{path}[{index}]"), errors); + } + } + ValidationErrorsKind::Field(list) | ValidationErrorsKind::Custom(list) => errors + .extend( + list.into_iter() + .map(|error| (path_or_document(), error.message)), + ), + ValidationErrorsKind::Enum(error) => errors.push((path_or_document(), error.message)), + } + } +} + +/// Runs every check on the CycloneDX SBOM. Returns the purls of its components. +pub fn check( + result: &mut ImageResult, + bom: &CycloneDx, + size: usize, + expectations: &Expectations, +) -> BTreeSet { + let missing_root = Component::default(); + let root = bom.metadata.component.as_ref().unwrap_or(&missing_root); + + check_format(result, bom, size, expectations); + check_root(result, root, &expectations.registry); + check_document_metadata(result, &bom.metadata, expectations); + + if bom.components.is_empty() { + result.error("cdx-components", "the SBOM lists no components"); + return BTreeSet::new(); + } + + let purls = check_components(result, &bom.components, expectations); + check_operating_system(result, &bom.components, expectations); + check_dependency_graph(result, bom, root); + check_component_counts(result, expectations); + check_main_component(result, &purls, expectations); + + purls.into_iter().collect() +} + +fn check_format( + result: &mut ImageResult, + bom: &CycloneDx, + size: usize, + expectations: &Expectations, +) { + if bom.bom_format.as_deref() != Some("CycloneDX") { + result.error( + "cdx-format", + format!( + "bomFormat is {format}", + format = describe(bom.bom_format.as_deref()) + ), + ); + } + + let expected = &expectations.cyclonedx_spec_version; + if bom.spec_version.as_ref() != Some(expected) { + result.error( + "cdx-format", + format!( + "specVersion is {version}, expected {expected}", + version = bom.spec_version.as_deref().unwrap_or("missing") + ), + ); + } + + result.stats.bytes = Some(size); + if size > MAX_SBOM_BYTES { + result.warning( + "cdx-size", + format!( + "the SBOM has {size:.1} MB, Rekor rejects attestations that get much larger \ + (limit for this warning: {limit} MB)", + size = size as f64 / 1024.0 / 1024.0, + limit = MAX_SBOM_BYTES / 1024 / 1024, + ), + ); + } +} + +/// The root component has to identify exactly the image the SBOM is attested to. +/// +/// A wrong digest means the SBOM belongs to a different build, which is the one thing a consumer +/// cannot detect from the SBOM alone. +fn check_root(result: &mut ImageResult, root: &Component, registry: &str) { + let target = result.target.clone(); + + if root.component_type.as_deref() != Some("container") { + result.error( + "cdx-root-identity", + format!( + "root component type is {component_type}", + component_type = describe(root.component_type.as_deref()) + ), + ); + } + if root.name.as_deref() != Some(target.image.as_str()) { + result.error( + "cdx-root-identity", + format!( + "root component name is {name}, expected {expected:?}", + name = describe(root.name.as_deref()), + expected = target.image + ), + ); + } + if root.version.as_deref() != Some(target.canonical_tag().as_str()) { + result.error( + "cdx-root-identity", + format!( + "root component version is {version}, expected {expected:?}", + version = describe(root.version.as_deref()), + expected = target.canonical_tag() + ), + ); + } + if let Some(digest) = result.digest.clone() { + let purl = expected_image_purl(registry, &target, &digest); + if root.purl.as_ref() != Some(&purl) { + result.error( + "cdx-root-identity", + format!( + "root component purl is {actual}, expected {purl:?}", + actual = describe(root.purl.as_deref()) + ), + ); + } + } + if root.bom_ref.is_none() { + result.error("cdx-root-identity", "root component has no bom-ref"); + } + + for (role, entity) in [ + ("supplier", &root.supplier), + ("manufacturer", &root.manufacturer), + ] { + let is_ours = entity.as_ref().is_some_and(|entity| { + entity.name.as_deref() == Some(ORGANIZATION) && !entity.url.is_empty() + }); + if !is_ours { + result.error( + "cdx-root-metadata", + format!("root component {role} is not {ORGANIZATION} with a URL"), + ); + } + } + if root.description.as_deref().is_none_or(str::is_empty) { + result.error("cdx-root-metadata", "root component has no description"); + } + if root.licenses.is_empty() { + result.error("cdx-root-metadata", "root component has no license"); + } +} + +fn check_document_metadata( + result: &mut ImageResult, + metadata: &Metadata, + expectations: &Expectations, +) { + if parse_timestamp(metadata.timestamp.as_deref()).is_none() { + result.error( + "cdx-document-metadata", + "metadata.timestamp is missing or invalid", + ); + } + + if !metadata + .authors + .iter() + .any(|author| author.name.as_deref() == Some(ORGANIZATION)) + { + result.error( + "cdx-document-metadata", + format!("metadata.authors does not name {ORGANIZATION}"), + ); + } + + if !metadata + .lifecycles + .iter() + .any(|lifecycle| lifecycle.phase.as_deref() == Some("post-build")) + { + result.error( + "cdx-document-metadata", + "metadata.lifecycles does not say post-build", + ); + } + + let tools: BTreeMap<&str, &str> = metadata + .tools + .get("components") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|tool| Some((tool.get("name")?.as_str()?, tool.get("version")?.as_str()?))) + .collect(); + for tool in ["syft", "mergebom"] { + if tools.get(tool).is_none_or(|version| version.is_empty()) { + result.error( + "cdx-document-metadata", + format!("metadata.tools does not list {tool} with a version"), + ); + } + } + + // The image labels end up in the SBOM, so the age of the image needs no registry access. + let created = metadata + .properties + .iter() + .find(|property| { + property.name.as_deref() + == Some(&format!( + "{IMAGE_LABEL_PREFIX}org.opencontainers.image.created" + )) + }) + .and_then(|property| parse_timestamp(property.value.as_deref())); + let max_age = expectations.max_image_age_days; + if let Some(created) = created + && (OffsetDateTime::now_utc() - created).whole_days() > max_age + { + result.warning( + "image-age", + format!( + "the image was built on {date}, more than {max_age} days ago. The scheduled \ + build is probably failing", + date = created.date(), + ), + ); + } +} + +/// Every component needs what a scanner or a human needs to identify it. Returns the purls. +fn check_components( + result: &mut ImageResult, + components: &[Component], + expectations: &Expectations, +) -> Vec { + let unnamed = components + .iter() + .filter(|component| component.name.as_deref().is_none_or(str::is_empty)) + .count(); + if unnamed > 0 { + result.error( + "cdx-component-identity", + format!("{unnamed} components have no name"), + ); + } + + // CycloneDX allows components without a bom-ref, but then nothing can depend on them. + // Duplicate bom-refs are reported by the schema check. + let missing_bom_refs = components + .iter() + .filter(|component| component.bom_ref.is_none()) + .count(); + if missing_bom_refs > 0 { + result.error( + "cdx-component-identity", + format!("{missing_bom_refs} components have no bom-ref"), + ); + } + + let files = components + .iter() + .filter(|component| component.component_type.as_deref() == Some("file")) + .count(); + if files > 0 { + result.error( + "cdx-file-components", + format!( + "{files} components of type file. The file catalogers of syft are meant to be \ + off, they multiply the size of the SBOM" + ), + ); + } + + let packages: Vec<&Component> = components + .iter() + .filter(|component| component.component_type.as_deref() != Some("operating-system")) + .collect(); + let name = |component: &&Component| component.name.clone().unwrap_or_default(); + + // A few components really have no package identity, like the Windows launcher stubs that + // pip ships. More than a few means a cataloger lost it. + let without_purl: Vec<&Component> = packages + .iter() + .copied() + .filter(|component| component.purl.as_deref().is_none_or(str::is_empty)) + .collect(); + let allowed = expectations.max_without_purl; + if share(without_purl.len(), packages.len()) > allowed { + result.error( + "cdx-purl", + format!( + "{count} of {total} components have no purl (allowed: {allowed}), e.g. \ + {examples}", + count = without_purl.len(), + total = packages.len(), + allowed = percent(allowed), + examples = examples(without_purl.iter().map(name)), + ), + ); + } + + let purls: Vec<&str> = packages + .iter() + .filter_map(|component| component.purl.as_deref()) + .filter(|purl| !purl.is_empty()) + .collect(); + let without_version: Vec<&Component> = packages + .iter() + .copied() + .filter(|component| { + component + .version + .as_deref() + .is_none_or(|version| version.is_empty() || version == "UNKNOWN") + }) + .collect(); + let allowed = expectations.max_without_version; + if share(without_version.len(), packages.len()) > allowed { + result.error( + "cdx-component-version", + format!( + "{count} of {total} components have no version (allowed: {allowed}), e.g. \ + {examples}", + count = without_version.len(), + total = packages.len(), + allowed = percent(allowed), + examples = examples(without_version.iter().map(name)), + ), + ); + } + + // mergebom merges components with the same purl, so a duplicate means it did not run or + // regressed. + let duplicate_purls = duplicates(&occurrences(purls.iter().copied())); + if !duplicate_purls.is_empty() { + result.error( + "cdx-duplicate-purls", + format!( + "{count} purls are listed more than once, e.g. {examples}", + count = duplicate_purls.len(), + examples = examples(duplicate_purls), + ), + ); + } + + check_rpm_versions(result, &packages); + + // The number of components per syft property, with the index in its name replaced. + let bloat = components + .iter() + .flat_map(|component| &component.properties) + .filter_map(|property| property.name.as_deref()) + .filter(|name| name.starts_with("syft:") && !KEPT_SYFT_PROPERTY.is_match(name)) + .fold(BTreeMap::::new(), |mut bloat, name| { + *bloat + .entry(INDEX.replace_all(name, ":N:").into_owned()) + .or_default() += 1; + bloat + }); + if !bloat.is_empty() { + result.error( + "cdx-syft-properties", + format!( + "{count} syft bookkeeping properties were not removed, e.g. {examples}", + count = bloat.values().sum::(), + examples = examples(bloat.keys()), + ), + ); + } + + let with_license = packages + .iter() + .filter(|component| !component.licenses.is_empty()) + .count(); + result.stats.license_coverage = Some(share(with_license, packages.len())); + result.stats.components = component_counts(components); + result.stats.embedded_sboms = embedded_sboms(components); + + purls.into_iter().map(ToOwned::to_owned).collect() +} + +/// Scanning all layers instead of the squashed filesystem reports every RPM that a later layer +/// updated twice, and the outdated one produces false vulnerability findings. +/// +/// Only the RPM database counts: Python wheels vendor libraries of other distributions and say so +/// in an SBOM of their own, which legitimately adds a second version of an RPM. +fn check_rpm_versions(result: &mut ImageResult, packages: &[&Component]) { + let mut rpm_versions = BTreeMap::<(String, Option), BTreeSet>>::new(); + for component in packages { + if component.found_by() != Some(RPM_DATABASE_CATALOGER) { + continue; + } + let Some(purl) = component.purl.as_deref().and_then(Purl::parse) else { + continue; + }; + if purl.package_type() == "rpm" { + rpm_versions + .entry(( + purl.short_name().to_owned(), + purl.qualifier("arch").map(ToOwned::to_owned), + )) + .or_default() + .insert(purl.version().map(ToOwned::to_owned)); + } + } + + let superseded: BTreeSet<&str> = rpm_versions + .iter() + .filter(|((name, _), versions)| { + versions.len() > 1 && !MULTI_VERSION_RPMS.contains(&name.as_str()) + }) + .map(|((name, _), _)| name.as_str()) + .collect(); + if !superseded.is_empty() { + result.error( + "cdx-rpm-versions", + format!( + "{count} RPMs are listed in more than one version, e.g. {examples}. Is syft \ + scanning all layers?", + count = superseded.len(), + examples = examples(&superseded), + ), + ); + } +} + +/// Component counts: `total`, one per purl type (`maven`), and one per purl type for the +/// components that come from a build-time SBOM embedded in the image (`embedded-maven`). +/// +/// The embedded ones are counted separately because syft finds most jars and Python packages on +/// its own as well. Without the build-time SBOM the plain count hardly moves, although the purls +/// get worse and everything that is shaded or bundled disappears. +fn component_counts(components: &[Component]) -> BTreeMap { + let mut counts = BTreeMap::::new(); + for component in components { + *counts.entry("total".to_owned()).or_default() += 1; + let Some(purl) = component.purl.as_deref().and_then(Purl::parse) else { + continue; + }; + if component.found_by() == Some(EMBEDDED_SBOM_CATALOGER) { + *counts + .entry(format!("embedded-{kind}", kind = purl.package_type())) + .or_default() += 1; + } + *counts.entry(purl.package_type().to_owned()).or_default() += 1; + } + counts +} + +/// The build-time SBOMs in the image, as path and number of components taken from it. +fn embedded_sboms(components: &[Component]) -> BTreeMap { + let mut paths = BTreeMap::::new(); + for component in components { + if component.found_by() != Some(EMBEDDED_SBOM_CATALOGER) { + continue; + } + for property in &component.properties { + if let (Some(name), Some(path)) = (property.name.as_deref(), property.value.as_deref()) + && LOCATION_PROPERTY.is_match(name) + { + *paths.entry(path.to_owned()).or_default() += 1; + } + } + } + paths +} + +/// Scanners need the distribution to match RPMs against the right advisories. +fn check_operating_system( + result: &mut ImageResult, + components: &[Component], + expectations: &Expectations, +) { + let expected = &expectations.operating_system; + let systems: Vec<&Component> = components + .iter() + .filter(|component| component.component_type.as_deref() == Some("operating-system")) + .collect(); + if systems.len() != 1 { + result.error( + "cdx-operating-system", + format!( + "{count} operating-system components, expected 1", + count = systems.len() + ), + ); + } + for system in systems { + // For RHEL and UBI, mergebom renames syft's "rhel" to the purl namespace "redhat". + if system.name.as_ref() != Some(expected) + || system.version.as_deref().is_none_or(str::is_empty) + { + result.error( + "cdx-operating-system", + format!( + "operating system is {name} {version}, expected {expected:?} with a version", + name = describe(system.name.as_deref()), + version = describe(system.version.as_deref()), + ), + ); + } + } + + let rpms: Vec<&str> = components + .iter() + .filter(|component| component.found_by() == Some(RPM_DATABASE_CATALOGER)) + .map(|component| component.purl.as_deref().unwrap_or_default()) + .collect(); + if rpms.is_empty() { + result.error( + "cdx-operating-system", + "no components from the RPM database", + ); + } + let namespace = format!("pkg:rpm/{expected}/"); + let wrong: Vec<&str> = rpms + .iter() + .copied() + .filter(|purl| { + !purl.starts_with(&namespace) + || Purl::parse(purl).is_none_or(|purl| purl.qualifier("distro").is_none()) + }) + .collect(); + if !wrong.is_empty() { + result.error( + "cdx-operating-system", + format!( + "{count} of {total} installed RPMs lack the purl namespace {expected} or the \ + distro qualifier, e.g. {examples}", + count = wrong.len(), + total = rpms.len(), + examples = examples(wrong), + ), + ); + } +} + +/// Every component has to be reachable from the image, otherwise a consumer that walks the graph +/// (and the SPDX document, which is built from it) loses components. +fn check_dependency_graph(result: &mut ImageResult, bom: &CycloneDx, root: &Component) { + if bom.dependencies.is_empty() { + result.error("cdx-dependency-graph", "the SBOM has no dependencies"); + return; + } + + let known: BTreeSet<&str> = bom + .components + .iter() + .filter_map(|component| component.bom_ref.as_deref()) + .collect(); + let root_bom_ref = root.bom_ref.as_deref(); + + let mut graph = BTreeMap::<&str, BTreeSet<&str>>::new(); + for dependency in &bom.dependencies { + if let Some(reference) = dependency.reference.as_deref() { + graph + .entry(reference) + .or_default() + .extend(dependency.depends_on.iter().map(String::as_str)); + } + } + + // Dependencies that point to no component are reported by the schema check. + let Some((root_bom_ref, root_dependencies)) = root_bom_ref + .and_then(|root_bom_ref| Some((root_bom_ref, graph.get(root_bom_ref)?))) + .filter(|(_, dependencies)| !dependencies.is_empty()) + else { + result.error( + "cdx-dependency-graph", + "the root component has no dependencies", + ); + return; + }; + result.stats.direct_dependencies = Some(root_dependencies.len()); + + let mut reachable = BTreeSet::new(); + let mut pending = vec![root_bom_ref]; + while let Some(reference) = pending.pop() { + if reachable.insert(reference) { + pending.extend(graph.get(reference).into_iter().flatten()); + } + } + + let orphans: BTreeSet<&str> = known.difference(&reachable).copied().collect(); + if !orphans.is_empty() { + result.error( + "cdx-dependency-graph", + format!( + "{count} of {total} components are not reachable from the root, e.g. {examples}", + count = orphans.len(), + total = known.len(), + examples = examples(&orphans), + ), + ); + } +} + +/// Compares the component counts with the floors in the expectations. +/// +/// This is the check for everything that the invariants cannot see: an SBOM without the Python +/// packages of Airflow is still a perfectly valid SBOM. +fn check_component_counts(result: &mut ImageResult, expectations: &Expectations) { + let mut findings = Vec::new(); + + for (kind, minimum) in &expectations.min_components { + let actual = result + .stats + .components + .get(kind) + .copied() + .unwrap_or_default(); + if actual < *minimum { + let what = if kind == "total" { + "components in total".to_owned() + } else if let Some(package_type) = kind.strip_prefix("embedded-") { + format!("{package_type} components from build-time SBOMs") + } else { + format!("{kind} components") + }; + findings.push(( + "component-count", + format!("{actual} {what}, expected at least {minimum}"), + )); + } + } + + if let (Some(minimum), Some(actual)) = ( + expectations.min_license_coverage, + result.stats.license_coverage, + ) && actual < minimum + { + findings.push(( + "license-coverage", + format!( + "{actual} of the components have a license, expected at least {minimum}", + actual = percent(actual), + minimum = percent(minimum) + ), + )); + } + + // The floors above have a margin and several build-time SBOMs feed the same count, so a small + // one can get lost unnoticed. This cannot happen to the ones listed by path. + for pattern in &expectations.embedded_sboms { + let path = substitute(pattern, &result.target, &expectations.release); + let found = glob::Pattern::new(&path).is_ok_and(|pattern| { + result + .stats + .embedded_sboms + .keys() + .any(|found| pattern.matches(found)) + }); + if !found { + findings.push(( + "embedded-sbom", + format!("no component from the build-time SBOM {path}"), + )); + } + } + + for (check, message) in findings { + result.error(check, message); + } +} + +/// The product itself has to be in the SBOM, in the version the image is tagged with. +fn check_main_component(result: &mut ImageResult, purls: &[String], expectations: &Expectations) { + let without_qualifiers: Vec<&str> = purls + .iter() + .map(|purl| purl.split_once('?').map_or(purl.as_str(), |(purl, _)| purl)) + .collect(); + + for pattern in &expectations.main_components { + let expected = substitute(pattern, &result.target, &expectations.release); + let (name, version) = match expected.rsplit_once('@') { + Some((name, version)) => (name, Some(version).filter(|version| !version.is_empty())), + None => (expected.as_str(), None), + }; + + let found: Vec<&str> = without_qualifiers + .iter() + .filter_map(|purl| purl.rsplit_once('@')) + .filter(|(purl_name, _)| *purl_name == name) + .map(|(_, purl_version)| purl_version) + .collect(); + if !found.iter().any(|actual| matches_version(actual, version)) { + let other = if found.is_empty() { + "not listed at all".to_owned() + } else { + examples(found.iter().map(|version| percent_decode(version))) + }; + result.error( + "main-component", + format!( + "no component {name} in version {version} (found: {other})", + version = version.unwrap_or("any"), + ), + ); + } + } +} diff --git a/rust/sbom-quality/src/check/mod.rs b/rust/sbom-quality/src/check/mod.rs new file mode 100644 index 000000000..80fdb99c4 --- /dev/null +++ b/rust/sbom-quality/src/check/mod.rs @@ -0,0 +1,398 @@ +//! The checks, their findings and what the checks of both formats share. + +mod cyclonedx; +mod spdx; +#[cfg(test)] +mod tests; + +use std::collections::{BTreeMap, BTreeSet}; + +use serde::{Serialize, de::DeserializeOwned}; +use serde_json::Value; +use time::{OffsetDateTime, format_description::well_known::Rfc3339}; + +use crate::{ + expectations::{Expectations, Target}, + purl::{Purl, percent_decode, percent_encode}, + sbom::{CycloneDx, Spdx, remove_nulls}, +}; + +pub const ORGANIZATION: &str = "Stackable GmbH"; + +/// Share of components that may differ between the architectures of an image. +const MAX_ARCHITECTURE_DIFFERENCE: f64 = 0.05; + +/// The components of an image as (purl type, name), which is the same on every architecture. +/// +/// Not the version: the architectures are built by separate jobs, and an RPM update that is +/// released in between ends up in only one of them. +pub type Identity = BTreeSet<(String, String)>; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Severity { + Error, + Warning, +} + +#[derive(Debug, Serialize)] +pub struct Finding { + pub severity: Severity, + + /// ID of the check, which `ignore` in the expectations refers to. + pub check: &'static str, + + pub message: String, +} + +/// Numbers collected while checking, for `--suggest-floors` and the JSON output. +#[derive(Debug, Default, Serialize)] +#[serde(rename_all = "kebab-case")] +pub struct Stats { + pub bytes: Option, + pub license_coverage: Option, + pub components: BTreeMap, + + /// Paths of the build-time SBOMs and the number of components taken from each. + pub embedded_sboms: BTreeMap, + + pub direct_dependencies: Option, +} + +/// The outcome of checking one image architecture. +#[derive(Debug)] +pub struct ImageResult { + pub target: Target, + pub digest: Option, + pub findings: Vec, + pub stats: Stats, + + /// The number of findings dropped because the expectations ignore their check. + pub ignored: usize, +} + +impl ImageResult { + pub fn new(target: Target, digest: Option) -> Self { + Self { + target, + digest, + findings: Vec::new(), + stats: Stats::default(), + ignored: 0, + } + } + + pub fn error(&mut self, check: &'static str, message: impl Into) { + self.findings.push(Finding { + severity: Severity::Error, + check, + message: message.into(), + }); + } + + pub fn warning(&mut self, check: &'static str, message: impl Into) { + self.findings.push(Finding { + severity: Severity::Warning, + check, + message: message.into(), + }); + } + + pub fn has_errors(&self) -> bool { + self.findings + .iter() + .any(|finding| finding.severity == Severity::Error) + } +} + +/// Runs every check on the SBOMs of one image architecture, given as JSON. A missing SBOM is +/// skipped, the caller reports why it is missing. +pub fn check_sboms( + result: &mut ImageResult, + cyclonedx: Option<&str>, + spdx: Option<&str>, + expectations: &Expectations, +) -> Identity { + let cyclonedx_purls = cyclonedx.and_then(|json| { + let (bom, size) = parse::(result, "cdx-format", "CycloneDX", json)?; + cyclonedx::check_schema(result, json, &bom); + Some(cyclonedx::check(result, &bom, size, expectations)) + }); + let spdx_purls = spdx + .and_then(|json| parse::(result, "spdx-format", "SPDX", json)) + .map(|(document, _)| spdx::check(result, &document, &expectations.registry)); + + if let (Some(cyclonedx_purls), Some(spdx_purls)) = (&cyclonedx_purls, &spdx_purls) + && !cyclonedx_purls.is_empty() + && !spdx_purls.is_empty() + { + check_formats_agree(result, cyclonedx_purls, spdx_purls); + } + + cyclonedx_purls + .iter() + .flatten() + .filter_map(|purl| Purl::parse(purl)) + .map(|purl| (purl.package_type().to_owned(), purl.name().to_owned())) + .collect() +} + +/// Parses an SBOM. Returns it with its size as compact JSON, or reports why it is unreadable. +fn parse( + result: &mut ImageResult, + check: &'static str, + format: &str, + json: &str, +) -> Option<(T, usize)> { + let mut value: Value = match serde_json::from_str(json) { + Ok(value) => value, + Err(error) => { + result.error( + check, + format!("the {format} SBOM is not valid JSON: {error}"), + ); + return None; + } + }; + let size = serde_json::to_string(&value).map_or(json.len(), |compact| compact.len()); + + remove_nulls(&mut value); + match serde_json::from_value(value) { + Ok(document) => Some((document, size)), + Err(error) => { + result.error( + check, + format!("the {format} SBOM does not have the expected structure: {error}"), + ); + None + } + } +} + +/// Both documents are written from the same data, so they have to list the same packages. +fn check_formats_agree( + result: &mut ImageResult, + cyclonedx_purls: &BTreeSet, + spdx_purls: &BTreeSet, +) { + let only_cyclonedx: Vec<&String> = cyclonedx_purls.difference(spdx_purls).collect(); + let only_spdx: Vec<&String> = spdx_purls.difference(cyclonedx_purls).collect(); + if !only_cyclonedx.is_empty() { + result.error( + "spdx-matches-cyclonedx", + format!( + "{count} purls are only in the CycloneDX SBOM, e.g. {examples}", + count = only_cyclonedx.len(), + examples = examples(only_cyclonedx), + ), + ); + } + if !only_spdx.is_empty() { + result.error( + "spdx-matches-cyclonedx", + format!( + "{count} purls are only in the SPDX SBOM, e.g. {examples}", + count = only_spdx.len(), + examples = examples(only_spdx), + ), + ); + } +} + +/// The architectures of an image are built from the same sources. +/// +/// A build-time SBOM that is lost on one architecture only easily stays above the component +/// floors, but not below this. +pub fn check_architectures_agree( + results: &mut [ImageResult], + identities: &BTreeMap, +) { + let mut by_tag = BTreeMap::<(String, String), Vec>::new(); + for (index, result) in results.iter().enumerate() { + if identities.contains_key(&result.target) { + by_tag + .entry((result.target.image.clone(), result.target.tag.clone())) + .or_default() + .push(index); + } + } + + for group in by_tag.values() { + let Some((first, others)) = group.split_first() else { + continue; + }; + let (Some(first_result), Some(mine)) = ( + results.get(*first), + results + .get(*first) + .and_then(|result| identities.get(&result.target)), + ) else { + continue; + }; + let first_architecture = first_result.target.architecture.clone(); + + for other in others { + let Some(theirs) = results + .get(*other) + .and_then(|result| identities.get(&result.target)) + else { + continue; + }; + let union = mine.union(theirs).count(); + let difference = share(mine.symmetric_difference(theirs).count(), union); + if difference <= MAX_ARCHITECTURE_DIFFERENCE { + continue; + } + + let describe = |components: Vec<&(String, String)>| { + if components.is_empty() { + "nothing".to_owned() + } else { + examples( + components + .iter() + .map(|(kind, name)| format!("{kind}:{name}")), + ) + } + }; + let message = format!( + "{difference} of the components differ from {first_architecture} (allowed: \ + {allowed}). Only here: {only_here}. Only {first_architecture}: {only_first}", + difference = percent(difference), + allowed = percent(MAX_ARCHITECTURE_DIFFERENCE), + only_here = describe(theirs.difference(mine).collect()), + only_first = describe(mine.difference(theirs).collect()), + ); + if let Some(result) = results.get_mut(*other) { + result.error("architectures-agree", message); + } + } + } +} + +/// Drops the findings of the checks the expectations ignore. +pub fn apply_ignores(result: &mut ImageResult, expectations: &Expectations) { + let before = result.findings.len(); + result + .findings + .retain(|finding| !expectations.ignore.contains(finding.check)); + result.ignored = before - result.findings.len(); +} + +/// Replaces `{version}`, `{release}` and `{image}` in a purl or path from the expectations. +pub fn substitute(pattern: &str, target: &Target, release: &str) -> String { + pattern + .replace("{version}", target.version.as_deref().unwrap_or_default()) + .replace("{release}", release) + .replace("{image}", &target.image) +} + +/// The purl the publish-image action gives the image. +pub fn expected_image_purl(registry: &str, target: &Target, digest: &str) -> String { + format!( + "pkg:oci/{image}@{digest}?arch={architecture}&repository_url={repository}", + image = target.image, + digest = percent_encode(digest), + architecture = target.architecture, + repository = percent_encode(&format!("{registry}/{image}", image = target.image)), + ) +} + +/// Whether a component version is the expected version, with or without a suffix like +/// `-stackable0.0.0-dev` or `+dirty`. Without an expected version, every version matches. +pub fn matches_version(actual: &str, expected: Option<&str>) -> bool { + let Some(expected) = expected else { + return true; + }; + let actual = percent_decode(actual); + actual == expected + || actual + .strip_prefix(expected) + .and_then(|rest| rest.chars().next()) + .is_some_and(|separator| "-+_".contains(separator)) +} + +/// Whether a license is a valid SPDX expression, `LicenseRef-`s included. +/// +/// Deprecated IDs like `BSD-2-Clause-FreeBSD` are valid: they are still on the SPDX license list, +/// and mergebom keeps them on purpose when it has no replacement for them. +pub fn is_valid_license(expression: &str) -> bool { + let mode = ::spdx::ParseMode { + allow_deprecated: true, + ..::spdx::ParseMode::STRICT + }; + ::spdx::Expression::parse_mode(expression, mode).is_ok() +} + +pub fn parse_timestamp(value: Option<&str>) -> Option { + value.and_then(|value| OffsetDateTime::parse(value, &Rfc3339).ok()) +} + +/// A value from a document for a message: quoted, or `missing`. +pub fn describe(value: Option<&str>) -> String { + value.map_or_else(|| "missing".to_owned(), |value| format!("{value:?}")) +} + +/// A short, stable sample of a collection for a message. +pub fn examples(items: I) -> String +where + I: IntoIterator, + S: AsRef, +{ + const LIMIT: usize = 3; + const MAX_LENGTH: usize = 90; + + let items: BTreeSet = items + .into_iter() + .map(|item| { + let item = item.as_ref(); + if item.chars().count() <= MAX_LENGTH { + item.to_owned() + } else { + format!( + "{truncated}...", + truncated = item.chars().take(MAX_LENGTH).collect::() + ) + } + }) + .collect(); + let shown = items + .iter() + .take(LIMIT) + .map(String::as_str) + .collect::>() + .join(", "); + if items.len() <= LIMIT { + shown + } else { + format!("{shown} and {more} more", more = items.len() - LIMIT) + } +} + +/// How often each item occurs. +pub fn occurrences<'a>(items: impl IntoIterator) -> BTreeMap<&'a str, usize> { + items.into_iter().fold(BTreeMap::new(), |mut counts, item| { + *counts.entry(item).or_default() += 1; + counts + }) +} + +/// Returns the keys of a map where the value (signifying a count) is greater than 1. +pub fn duplicates<'a>(map: &BTreeMap<&'a str, usize>) -> Vec<&'a str> { + map.iter() + .filter(|(_, value)| **value > 1) + .map(|(key, _)| *key) + .collect() +} + +pub fn share(part: usize, total: usize) -> f64 { + if total == 0 { + 0.0 + } else { + part as f64 / total as f64 + } +} + +pub fn percent(value: f64) -> String { + format!("{percentage:.1}%", percentage = value * 100.0) +} diff --git a/rust/sbom-quality/src/check/spdx.rs b/rust/sbom-quality/src/check/spdx.rs new file mode 100644 index 000000000..e3a9a232a --- /dev/null +++ b/rust/sbom-quality/src/check/spdx.rs @@ -0,0 +1,426 @@ +//! Checks of the SPDX SBOM. + +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::LazyLock, +}; + +use regex::Regex; + +use super::{ + ImageResult, ORGANIZATION, describe, duplicates, examples, expected_image_purl, + is_valid_license, occurrences, parse_timestamp, share, +}; +use crate::sbom::{Package, Relationship, Spdx}; + +const DOCUMENT_ID: &str = "SPDXRef-DOCUMENT"; + +/// The share of third-party packages in the image that may name Stackable as their supplier. +/// +/// Stackable is the supplier of the image itself, not of the packages in it, which come from other +/// suppliers. The limit is not zero, so that a few packages are tolerated. It is there to catch the +/// supplier being set on (nearly) every package, which `syft convert` once did. +const MAX_SHARE_STACKABLE_SUPPLIER: f64 = 0.05; + +static SPDX_ID: LazyLock = LazyLock::new(|| { + Regex::new(r"^SPDXRef-[A-Za-z0-9.-]+$") + .expect("static string must be a valid regular expression") +}); + +static LICENSE_REF: LazyLock = LazyLock::new(|| { + Regex::new(r"LicenseRef-[A-Za-z0-9.-]+") + .expect("static string must be a valid regular expression") +}); + +static OUR_CREATOR: LazyLock = LazyLock::new(|| { + Regex::new(&format!(r"^Organization: {ORGANIZATION} \(.+@.+\)")) + .expect("static string must be a valid regular expression") +}); + +/// Runs every check on the SPDX SBOM. Returns the purls of its packages, without the image. +pub fn check(result: &mut ImageResult, document: &Spdx, registry: &str) -> BTreeSet { + check_format(result, document); + + if document.packages.is_empty() { + result.error("spdx-packages", "the document lists no packages"); + return BTreeSet::new(); + } + check_packages(result, &document.packages); + + let by_id: BTreeMap<&str, &Package> = document + .packages + .iter() + .filter_map(|package| Some((package.spdx_id.as_deref()?, package))) + .collect(); + + let described: BTreeSet<&str> = document + .relationships + .iter() + .filter(|relationship| { + relationship.relationship_type.as_deref() == Some("DESCRIBES") + && relationship.spdx_element_id.as_deref() == Some(DOCUMENT_ID) + }) + .filter_map(|relationship| relationship.related_spdx_element.as_deref()) + .chain(document.document_describes.iter().map(String::as_str)) + .collect(); + let root = match described.first() { + Some(root_id) if described.len() == 1 => by_id.get(root_id).copied(), + _ => None, + }; + let (Some(root), Some(root_id)) = (root, described.first().copied()) else { + result.error( + "spdx-root", + format!( + "the document describes {count} packages, expected 1", + count = described.len() + ), + ); + return BTreeSet::new(); + }; + + let others: Vec<&Package> = document + .packages + .iter() + .filter(|package| package.spdx_id.as_deref() != Some(root_id)) + .collect(); + + check_root(result, root, registry); + check_suppliers(result, &others); + check_license_refs(result, document); + check_license_expressions(result, &document.packages); + check_relationships(result, &document.relationships, &by_id, root_id); + + others + .iter() + .flat_map(|package| package.purls()) + .map(ToOwned::to_owned) + .collect() +} + +fn check_format(result: &mut ImageResult, document: &Spdx) { + if document.spdx_version.as_deref() != Some("SPDX-2.3") { + result.error( + "spdx-format", + format!( + "spdxVersion is {version}", + version = describe(document.spdx_version.as_deref()) + ), + ); + } + if document.data_license.as_deref() != Some("CC0-1.0") { + result.error( + "spdx-format", + format!( + "dataLicense is {license}", + license = describe(document.data_license.as_deref()) + ), + ); + } + if document.spdx_id.as_deref() != Some(DOCUMENT_ID) { + result.error( + "spdx-format", + format!("SPDXID is {id}", id = describe(document.spdx_id.as_deref())), + ); + } + // The namespace itself is not printed, it is different in every document. + if !document + .document_namespace + .as_deref() + .is_some_and(|namespace| namespace.starts_with("https://stackable.tech/")) + { + result.error( + "spdx-format", + "documentNamespace is not below https://stackable.tech/", + ); + } + + let creation = &document.creation_info; + if parse_timestamp(creation.created.as_deref()).is_none() { + result.error( + "spdx-creation-info", + "creationInfo.created is missing or invalid", + ); + } + if !creation + .creators + .iter() + .any(|creator| OUR_CREATOR.is_match(creator)) + { + result.error( + "spdx-creation-info", + format!("creationInfo.creators does not name {ORGANIZATION} with an email address"), + ); + } + for tool in ["syft", "mergebom"] { + if !creation + .creators + .iter() + .any(|creator| creator.starts_with(&format!("Tool: {tool}-"))) + { + result.error( + "spdx-creation-info", + format!("creationInfo.creators does not list {tool}"), + ); + } + } +} + +fn check_packages(result: &mut ImageResult, packages: &[Package]) { + let ids = occurrences( + packages + .iter() + .map(|package| package.spdx_id.as_deref().unwrap_or("missing")), + ); + + let invalid: Vec<&str> = ids + .keys() + .copied() + .filter(|spdx_id| !SPDX_ID.is_match(spdx_id)) + .collect(); + if !invalid.is_empty() { + result.error( + "spdx-packages", + format!( + "{count} invalid SPDXIDs, e.g. {examples}", + count = invalid.len(), + examples = examples(&invalid), + ), + ); + } + + let duplicate = duplicates(&ids); + if !duplicate.is_empty() { + result.error( + "spdx-packages", + format!( + "{count} SPDXIDs are used more than once, e.g. {examples}", + count = duplicate.len(), + examples = examples(&duplicate), + ), + ); + } + + let incomplete = packages + .iter() + .filter(|package| { + package.name.as_deref().is_none_or(str::is_empty) + || package + .download_location + .as_deref() + .is_none_or(str::is_empty) + }) + .count(); + if incomplete > 0 { + result.error( + "spdx-packages", + format!("{incomplete} packages lack a name or a downloadLocation"), + ); + } +} + +fn check_root(result: &mut ImageResult, root: &Package, registry: &str) { + let target = result.target.clone(); + + if root.primary_package_purpose.as_deref() != Some("CONTAINER") { + result.error( + "spdx-root", + format!( + "primaryPackagePurpose of the image is {purpose}", + purpose = describe(root.primary_package_purpose.as_deref()) + ), + ); + } + if root.name.as_deref() != Some(target.image.as_str()) + || root.version_info.as_deref() != Some(target.canonical_tag().as_str()) + { + result.error( + "spdx-root", + format!( + "the image package is {name} {version}, expected {image:?} {tag:?}", + name = describe(root.name.as_deref()), + version = describe(root.version_info.as_deref()), + image = target.image, + tag = target.canonical_tag(), + ), + ); + } + if let Some(digest) = result.digest.clone() { + let purl = expected_image_purl(registry, &target, &digest); + if root.purls() != [purl.as_str()] { + result.error( + "spdx-root", + format!( + "the image package purl is {actual:?}, expected {purl:?}", + actual = root.purls() + ), + ); + } + } + let supplier = format!("Organization: {ORGANIZATION}"); + if root.supplier.as_ref() != Some(&supplier) { + result.error( + "spdx-root", + format!( + "supplier of the image is {supplier}", + supplier = describe(root.supplier.as_deref()) + ), + ); + } + if root + .license_declared + .as_deref() + .is_none_or(|license| ["", "NOASSERTION", "NONE"].contains(&license)) + { + result.error("spdx-root", "the image package declares no license"); + } +} + +/// We are the supplier of the image, not of the packages in it. +fn check_suppliers(result: &mut ImageResult, others: &[&Package]) { + let ours = others + .iter() + .filter(|package| { + package + .supplier + .as_deref() + .is_some_and(|supplier| supplier.contains(ORGANIZATION)) + }) + .count(); + if share(ours, others.len()) > MAX_SHARE_STACKABLE_SUPPLIER { + result.error( + "spdx-supplier", + format!( + "{ours} of {total} third-party packages name {ORGANIZATION} as supplier", + total = others.len() + ), + ); + } +} + +/// A LicenseRef that is not declared makes the document invalid for strict parsers. +fn check_license_refs(result: &mut ImageResult, document: &Spdx) { + let declared = occurrences( + document + .has_extracted_licensing_infos + .iter() + .map(|license| license.license_id.as_deref().unwrap_or("missing")), + ); + let duplicate = duplicates(&declared); + if !duplicate.is_empty() { + result.error( + "spdx-license-refs", + format!( + "{count} LicenseRefs are declared more than once, e.g. {examples}", + count = duplicate.len(), + examples = examples(&duplicate), + ), + ); + } + + let undeclared: BTreeSet<&str> = document + .packages + .iter() + .flat_map(|package| [&package.license_declared, &package.license_concluded]) + .filter_map(|license| license.as_deref()) + .flat_map(|license| LICENSE_REF.find_iter(license).map(|found| found.as_str())) + .filter(|license_ref| !declared.contains_key(license_ref)) + .collect(); + if !undeclared.is_empty() { + result.error( + "spdx-license-refs", + format!( + "{count} LicenseRefs are used but not declared in hasExtractedLicensingInfos, \ + e.g. {examples}", + count = undeclared.len(), + examples = examples(&undeclared), + ), + ); + } +} + +/// A license that is not a valid SPDX expression makes the document invalid for strict parsers, +/// and license scanners cannot use it. +fn check_license_expressions(result: &mut ImageResult, packages: &[Package]) { + let licenses: BTreeSet<&str> = packages + .iter() + .flat_map(|package| [&package.license_declared, &package.license_concluded]) + .filter_map(|license| license.as_deref()) + .filter(|license| !["NOASSERTION", "NONE"].contains(license)) + .collect(); + let invalid: Vec<&str> = licenses + .into_iter() + .filter(|license| !is_valid_license(license)) + .collect(); + if !invalid.is_empty() { + result.error( + "spdx-license-expressions", + format!( + "{count} licenses are not valid SPDX expressions, e.g. {examples}", + count = invalid.len(), + examples = examples(&invalid), + ), + ); + } +} + +fn check_relationships( + result: &mut ImageResult, + relationships: &[Relationship], + by_id: &BTreeMap<&str, &Package>, + root_id: &str, +) { + let mut graph = BTreeMap::<&str, BTreeSet<&str>>::new(); + let mut dangling = BTreeSet::new(); + for relationship in relationships { + let source = relationship.spdx_element_id.as_deref().unwrap_or("missing"); + let related = relationship + .related_spdx_element + .as_deref() + .unwrap_or("missing"); + for element in [source, related] { + if element != DOCUMENT_ID && !by_id.contains_key(element) { + dangling.insert(element); + } + } + if matches!( + relationship.relationship_type.as_deref(), + Some("CONTAINS" | "DEPENDS_ON") + ) { + graph.entry(source).or_default().insert(related); + } + } + if !dangling.is_empty() { + result.error( + "spdx-relationships", + format!( + "{count} relationship elements do not exist, e.g. {examples}", + count = dangling.len(), + examples = examples(&dangling), + ), + ); + } + + let mut reachable = BTreeSet::new(); + let mut pending = vec![root_id]; + while let Some(spdx_id) = pending.pop() { + if reachable.insert(spdx_id) { + pending.extend(graph.get(spdx_id).into_iter().flatten()); + } + } + let orphans: BTreeSet<&str> = by_id + .keys() + .copied() + .filter(|spdx_id| !reachable.contains(spdx_id)) + .collect(); + if !orphans.is_empty() { + result.error( + "spdx-relationships", + format!( + "{count} of {total} packages are not reachable from the image, e.g. {examples}", + count = orphans.len(), + total = by_id.len(), + examples = examples(&orphans), + ), + ); + } +} diff --git a/rust/sbom-quality/src/check/tests.rs b/rust/sbom-quality/src/check/tests.rs new file mode 100644 index 000000000..b8b251622 --- /dev/null +++ b/rust/sbom-quality/src/check/tests.rs @@ -0,0 +1,587 @@ +//! Every check is tested the same way: a small pair of SBOMs that passes all of them is broken in +//! one place, and exactly that check has to notice. + +use std::collections::BTreeMap; + +use rstest::{fixture, rstest}; +use serde_json::{Value, json}; + +use super::*; + +const DIGEST: &str = "sha256:abababababababababababababababababababababababababababababababab"; +const IMAGE_PURL: &str = "pkg:oci/kafka@sha256%3Aabababababababababababababababababababababababababababababababab?arch=amd64&repository_url=oci.stackable.tech%2Fsdp%2Fkafka"; +const OTHER_IMAGE_PURL: &str = "pkg:oci/kafka@sha256%3Acdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd?arch=amd64&repository_url=oci.stackable.tech%2Fsdp%2Fkafka"; +const GLIBC: &str = "pkg:rpm/redhat/glibc@2.34-1.el9?arch=x86_64&distro=rhel-9.9"; +const BASH: &str = "pkg:rpm/redhat/bash@5.1.8-1.el9?arch=x86_64&distro=rhel-9.9"; +const KAFKA: &str = "pkg:maven/org.apache.kafka/kafka-clients@4.3.1-stackable0.0.0-dev"; +const EMBEDDED_SBOM: &str = "/stackable/kafka_2.13-4.3.1-stackable0.0.0-dev/kafka.cdx.json"; + +fn target(architecture: &str) -> Target { + Target { + image: "kafka".to_owned(), + version: Some("4.3.1".to_owned()), + tag: "4.3.1-stackable0.0.0-dev".to_owned(), + architecture: architecture.to_owned(), + } +} + +#[fixture] +fn expectations() -> Expectations { + Expectations { + registry: "oci.stackable.tech/sdp".to_owned(), + release: "0.0.0-dev".to_owned(), + cyclonedx_spec_version: "1.7".to_owned(), + max_image_age_days: 7, + operating_system: "redhat".to_owned(), + max_without_purl: 0.05, + max_without_version: 0.05, + main_components: vec!["pkg:maven/org.apache.kafka/kafka-clients@{version}".to_owned()], + embedded_sboms: vec![ + "/stackable/kafka_2.13-{version}-stackable{release}/*.cdx.json".to_owned(), + ], + min_components: BTreeMap::from([ + ("total".to_owned(), 4), + ("rpm".to_owned(), 2), + ("embedded-maven".to_owned(), 1), + ]), + min_license_coverage: Some(0.6), + ignore: BTreeSet::new(), + } +} + +fn component(purl: &str, name: &str, version: &str, cataloger: &str, path: &str) -> Value { + json!({ + "type": "library", + "bom-ref": format!("{purl}&package-id=1"), + "name": name, + "version": version, + "purl": purl, + "licenses": [{ "license": { "id": "Apache-2.0" } }], + "properties": [ + { "name": "syft:package:foundBy", "value": cataloger }, + { "name": "syft:location:0:path", "value": path }, + ], + }) +} + +/// A CycloneDX SBOM as mergebom writes it, cut down to what the checks look at. +#[fixture] +fn cyclonedx() -> Value { + let organization = json!({ "name": "Stackable GmbH", "url": ["https://stackable.tech/"] }); + let components = vec![ + json!({ "type": "operating-system", "bom-ref": "os", "name": "redhat", "version": "9.9" }), + component( + GLIBC, + "glibc", + "2.34-1.el9", + "rpm-db-cataloger", + "/var/lib/rpm/db", + ), + component( + BASH, + "bash", + "5.1.8-1.el9", + "rpm-db-cataloger", + "/var/lib/rpm/db", + ), + component( + KAFKA, + "kafka-clients", + "4.3.1-stackable0.0.0-dev", + "sbom-cataloger", + EMBEDDED_SBOM, + ), + ]; + let bom_ref = |index: usize| components[index]["bom-ref"].clone(); + json!({ + "bomFormat": "CycloneDX", + "specVersion": "1.7", + "serialNumber": "urn:uuid:972ce3e9-363b-4fb5-80c4-ba546dfc50e0", + "version": 1, + "metadata": { + "timestamp": "2026-11-16T01:12:24Z", + "authors": [{ "name": "Stackable GmbH", "email": "info@stackable.tech" }], + "lifecycles": [{ "phase": "post-build" }], + "tools": { + "components": [ + { "type": "application", "name": "syft", "version": "1.44.0" }, + { "type": "application", "name": "mergebom", "version": "0.1.0" }, + ] + }, + "component": { + "type": "container", + "bom-ref": "root", + "name": "kafka", + "version": "4.3.1-stackable0.0.0-dev-amd64", + "purl": IMAGE_PURL, + "supplier": organization, + "manufacturer": organization, + "description": "Apache Kafka.", + "licenses": [{ "license": { "id": "Apache-2.0" } }], + }, + }, + "dependencies": [ + { "ref": "root", "dependsOn": [bom_ref(0), bom_ref(1), bom_ref(2)] }, + { "ref": bom_ref(1), "dependsOn": [bom_ref(3)] }, + ], + "components": components, + }) +} + +/// The SPDX document that belongs to the CycloneDX SBOM. +#[fixture] +fn spdx() -> Value { + let package = |spdx_id: &str, name: &str, purl: &str, supplier: &str| { + json!({ + "SPDXID": spdx_id, + "name": name, + "versionInfo": "1", + "supplier": supplier, + "downloadLocation": "NOASSERTION", + "licenseDeclared": "Apache-2.0 AND LicenseRef-Fedora-Public-Domain", + "externalRefs": [{ "referenceType": "purl", "referenceLocator": purl }], + }) + }; + let relationship = |source: &str, kind: &str, related: &str| json!({ "spdxElementId": source, "relationshipType": kind, "relatedSpdxElement": related }); + + let mut root = package( + "SPDXRef-Image", + "kafka", + IMAGE_PURL, + "Organization: Stackable GmbH", + ); + root["versionInfo"] = json!("4.3.1-stackable0.0.0-dev-amd64"); + root["primaryPackagePurpose"] = json!("CONTAINER"); + json!({ + "spdxVersion": "SPDX-2.3", + "dataLicense": "CC0-1.0", + "SPDXID": "SPDXRef-DOCUMENT", + "documentNamespace": "https://stackable.tech/spdxdocs/kafka-1", + "documentDescribes": null, + "creationInfo": { + "created": "2026-11-16T01:12:24Z", + "creators": [ + "Organization: Stackable GmbH (info@stackable.tech)", + "Tool: mergebom-0.1.0", + "Tool: syft-1.44.0", + ], + }, + "packages": [ + root, + package("SPDXRef-glibc", "glibc", GLIBC, "Organization: Red Hat, Inc."), + package("SPDXRef-bash", "bash", BASH, "Organization: Red Hat, Inc."), + package("SPDXRef-kafka-clients", "kafka-clients", KAFKA, "NOASSERTION"), + ], + "relationships": [ + relationship("SPDXRef-DOCUMENT", "DESCRIBES", "SPDXRef-Image"), + relationship("SPDXRef-Image", "CONTAINS", "SPDXRef-glibc"), + relationship("SPDXRef-Image", "CONTAINS", "SPDXRef-bash"), + relationship("SPDXRef-glibc", "DEPENDS_ON", "SPDXRef-kafka-clients"), + ], + "hasExtractedLicensingInfos": [ + { "licenseId": "LicenseRef-Fedora-Public-Domain", "extractedText": "x" } + ], + }) +} + +fn run_checks( + cyclonedx: Option<&Value>, + spdx: Option<&Value>, + expectations: &Expectations, +) -> ImageResult { + let mut result = ImageResult::new(target("amd64"), Some(DIGEST.to_owned())); + check_sboms( + &mut result, + cyclonedx.map(Value::to_string).as_deref(), + spdx.map(Value::to_string).as_deref(), + expectations, + ); + result +} + +fn checks(result: &ImageResult) -> BTreeSet<&'static str> { + result + .findings + .iter() + .map(|finding| finding.check) + .collect() +} + +fn array(value: &mut Value) -> &mut Vec { + value.as_array_mut().expect("the value should be an array") +} + +#[rstest] +fn good_sboms_have_no_findings(cyclonedx: Value, spdx: Value, expectations: Expectations) { + let result = run_checks(Some(&cyclonedx), Some(&spdx), &expectations); + let messages: Vec<&str> = result + .findings + .iter() + .map(|finding| finding.message.as_str()) + .collect(); + assert_eq!(messages, Vec::<&str>::new()); +} + +#[rstest] +#[case::old_spec_version(|bom: &mut Value| bom["specVersion"] = json!("1.5"), "cdx-format")] +#[case::not_an_sbom(|bom: &mut Value| *bom = json!({ "components": "none" }), "cdx-format")] +#[case::sbom_of_another_digest( + |bom: &mut Value| bom["metadata"]["component"]["purl"] = json!(OTHER_IMAGE_PURL), + "cdx-root-identity" +)] +#[case::sbom_of_another_architecture( + |bom: &mut Value| bom["metadata"]["component"]["version"] = json!("4.3.1-stackable0.0.0-dev-arm64"), + "cdx-root-identity" +)] +#[case::no_supplier(|bom: &mut Value| bom["metadata"]["component"]["supplier"] = Value::Null, "cdx-root-metadata")] +#[case::no_license_on_the_image( + |bom: &mut Value| bom["metadata"]["component"]["licenses"] = json!([]), + "cdx-root-metadata" +)] +#[case::mergebom_did_not_run( + |bom: &mut Value| { array(&mut bom["metadata"]["tools"]["components"]).pop(); }, + "cdx-document-metadata" +)] +#[case::no_components(|bom: &mut Value| bom["components"] = json!([]), "cdx-components")] +#[case::duplicate_bom_ref( + |bom: &mut Value| bom["components"][2]["bom-ref"] = bom["components"][1]["bom-ref"].clone(), + "cdx-schema" +)] +#[case::component_without_bom_ref( + |bom: &mut Value| { bom["components"][2].as_object_mut().expect("the component should be an object").remove("bom-ref"); }, + "cdx-component-identity" +)] +#[case::file_components( + |bom: &mut Value| array(&mut bom["components"]).push(json!({ "type": "file", "bom-ref": "f" })), + "cdx-file-components" +)] +#[case::component_without_purl(|bom: &mut Value| bom["components"][1]["purl"] = Value::Null, "cdx-purl")] +#[case::malformed_purl(|bom: &mut Value| bom["components"][3]["purl"] = json!("maven:kafka-clients"), "cdx-schema")] +#[case::purl_with_duplicate_qualifier( + |bom: &mut Value| bom["components"][1]["purl"] = json!(format!("{GLIBC}&arch=aarch64")), + "cdx-schema" +)] +#[case::invalid_serial_number(|bom: &mut Value| bom["serialNumber"] = json!("nope"), "cdx-schema")] +#[case::invalid_license_id( + |bom: &mut Value| bom["components"][1]["licenses"] = json!([{ "license": { "id": "Apache 2.0" } }]), + "cdx-schema" +)] +#[case::invalid_license_expression( + |bom: &mut Value| bom["components"][1]["licenses"] = json!([{ "expression": "Apache-2.0 ORR MIT" }]), + "cdx-schema" +)] +#[case::wrong_case_in_license_exception( + |bom: &mut Value| bom["components"][1]["licenses"] = json!([{ "expression": "Apache-2.0 WITH LLVM-Exception" }]), + "cdx-schema" +)] +#[case::invalid_license_on_the_image( + |bom: &mut Value| bom["metadata"]["component"]["licenses"] = json!([{ "expression": "Apache 2.0" }]), + "cdx-schema" +)] +#[case::malformed_hash( + |bom: &mut Value| bom["components"][1]["hashes"] = json!([{ "alg": "SHA-256", "content": "xyz" }]), + "cdx-schema" +)] +#[case::unknown_component_type(|bom: &mut Value| bom["components"][1]["type"] = json!("banana"), "cdx-schema")] +#[case::component_without_version( + |bom: &mut Value| bom["components"][1]["version"] = json!("UNKNOWN"), + "cdx-component-version" +)] +#[case::duplicate_purl( + |bom: &mut Value| { + let mut duplicate = bom["components"][3].clone(); + duplicate["bom-ref"] = json!("other"); + array(&mut bom["components"]).push(duplicate); + }, + "cdx-duplicate-purls" +)] +#[case::superseded_rpm_from_a_lower_layer( + |bom: &mut Value| { + let mut old = component( + &GLIBC.replace("2.34-1", "2.34-0"), + "glibc", + "2.34-0.el9", + "rpm-db-cataloger", + "/var/lib/rpm/db", + ); + old["bom-ref"] = json!("old-glibc"); + array(&mut bom["components"]).push(old); + }, + "cdx-rpm-versions" +)] +#[case::syft_bookkeeping_left_in( + |bom: &mut Value| array(&mut bom["components"][1]["properties"]) + .push(json!({ "name": "syft:location:0:layerID", "value": "sha256:1" })), + "cdx-syft-properties" +)] +#[case::no_operating_system(|bom: &mut Value| { array(&mut bom["components"]).remove(0); }, "cdx-operating-system")] +#[case::rpm_without_distro( + |bom: &mut Value| bom["components"][1]["purl"] = json!("pkg:rpm/redhat/glibc@2.34-1.el9?arch=x86_64"), + "cdx-operating-system" +)] +#[case::no_dependencies(|bom: &mut Value| bom["dependencies"] = json!([]), "cdx-dependency-graph")] +#[case::dangling_dependency( + |bom: &mut Value| array(&mut bom["dependencies"][0]["dependsOn"]).push(json!("gone")), + "cdx-schema" +)] +#[case::component_outside_the_graph( + |bom: &mut Value| { array(&mut bom["dependencies"]).pop(); }, + "cdx-dependency-graph" +)] +#[case::wrong_product_version( + |bom: &mut Value| bom["components"][3]["purl"] = json!(KAFKA.replace("4.3.1", "4.3.10")), + "main-component" +)] +#[case::build_time_sbom_lost(|bom: &mut Value| bom["components"][3]["properties"] = json!([]), "embedded-sbom")] +#[case::few_licenses( + |bom: &mut Value| array(&mut bom["components"]).iter_mut().for_each(|component| component["licenses"] = json!([])), + "license-coverage" +)] +fn cyclonedx_defects( + mut cyclonedx: Value, + expectations: Expectations, + #[case] damage: fn(&mut Value), + #[case] check: &str, +) { + damage(&mut cyclonedx); + let result = run_checks(Some(&cyclonedx), None, &expectations); + assert!( + checks(&result).contains(check), + "{check} should report {findings:?}", + findings = result.findings + ); +} + +#[rstest] +#[case::syft_namespace(|document: &mut Value| document["documentNamespace"] = json!("https://anchore.com/syft/x"), "spdx-format")] +#[case::creator_without_email( + |document: &mut Value| document["creationInfo"]["creators"][0] = json!("Organization: Stackable GmbH"), + "spdx-creation-info" +)] +#[case::duplicate_spdx_id(|document: &mut Value| document["packages"][2]["SPDXID"] = json!("SPDXRef-glibc"), "spdx-packages")] +#[case::nothing_described(|document: &mut Value| { array(&mut document["relationships"]).remove(0); }, "spdx-root")] +#[case::image_of_another_digest( + |document: &mut Value| document["packages"][0]["externalRefs"][0]["referenceLocator"] = json!(OTHER_IMAGE_PURL), + "spdx-root" +)] +#[case::stackable_as_supplier_of_everything( + |document: &mut Value| array(&mut document["packages"]) + .iter_mut() + .for_each(|package| package["supplier"] = json!("Organization: Stackable GmbH")), + "spdx-supplier" +)] +#[case::invalid_license_expression( + |document: &mut Value| document["packages"][1]["licenseDeclared"] = json!("Apache 2.0"), + "spdx-license-expressions" +)] +#[case::wrong_case_in_license_exception( + |document: &mut Value| document["packages"][1]["licenseDeclared"] = json!("Apache-2.0 WITH LLVM-Exception"), + "spdx-license-expressions" +)] +#[case::undeclared_license_ref(|document: &mut Value| document["hasExtractedLicensingInfos"] = json!([]), "spdx-license-refs")] +#[case::package_outside_the_graph(|document: &mut Value| { array(&mut document["relationships"]).pop(); }, "spdx-relationships")] +#[case::package_missing( + |document: &mut Value| { + array(&mut document["packages"]).pop(); + array(&mut document["relationships"]).pop(); + }, + "spdx-matches-cyclonedx" +)] +fn spdx_defects( + cyclonedx: Value, + mut spdx: Value, + expectations: Expectations, + #[case] damage: fn(&mut Value), + #[case] check: &str, +) { + damage(&mut spdx); + let result = run_checks(Some(&cyclonedx), Some(&spdx), &expectations); + assert!( + checks(&result).contains(check), + "{check} should report {findings:?}", + findings = result.findings + ); +} + +/// An invalid license on every RPM is one problem and should read as one finding. +#[rstest] +fn schema_errors_are_grouped_by_field(mut cyclonedx: Value, expectations: Expectations) { + for index in [1, 2] { + cyclonedx["components"][index]["licenses"] = json!([{ "license": { "id": "Apache 2.0" } }]); + } + let result = run_checks(Some(&cyclonedx), None, &expectations); + + let fields: Vec<&str> = result + .findings + .iter() + .filter(|finding| finding.check == "cdx-schema") + .filter_map(|finding| finding.message.split_once(": 2 errors, e.g. ")) + .map(|(field, _)| field) + .collect(); + assert_eq!( + fields, + ["components[N].licenses[N].license.license_identifier.SpdxId"] + ); +} + +/// Deprecated IDs are still on the SPDX license list, mergebom keeps them on purpose. +#[rstest] +fn deprecated_license_ids_are_fine( + mut cyclonedx: Value, + mut spdx: Value, + expectations: Expectations, +) { + cyclonedx["components"][1]["licenses"] = + json!([{ "expression": "MIT AND BSD-2-Clause-FreeBSD" }]); + cyclonedx["components"][2]["licenses"] = json!([{ "license": { "id": "GPL-2.0" } }]); + spdx["packages"][1]["licenseDeclared"] = json!("MIT AND BSD-2-Clause-FreeBSD"); + + let result = run_checks(Some(&cyclonedx), Some(&spdx), &expectations); + assert_eq!(checks(&result), BTreeSet::new()); +} + +#[rstest] +fn component_floors(cyclonedx: Value, mut expectations: Expectations) { + expectations.min_components = BTreeMap::from([ + ("total".to_owned(), 5), + ("embedded-maven".to_owned(), 2), + ("pypi".to_owned(), 1), + ]); + let result = run_checks(Some(&cyclonedx), None, &expectations); + + let messages: Vec<&str> = result + .findings + .iter() + .filter(|finding| finding.check == "component-count") + .map(|finding| finding.message.as_str()) + .collect(); + assert_eq!( + messages, + [ + "1 maven components from build-time SBOMs, expected at least 2", + "0 pypi components, expected at least 1", + "4 components in total, expected at least 5", + ] + ); +} + +#[rstest] +fn vendored_rpms_of_another_distribution_are_fine( + mut cyclonedx: Value, + expectations: Expectations, +) { + // A Python wheel that bundles AlmaLinux libraries and says so in its own SBOM. + let vendored = component( + "pkg:rpm/almalinux/glibc@2.28-1.el8", + "glibc", + "2.28-1.el8", + "sbom-cataloger", + "/stackable/app/x.dist-info/sboms/auditwheel.cdx.json", + ); + array(&mut cyclonedx["dependencies"][0]["dependsOn"]).push(vendored["bom-ref"].clone()); + array(&mut cyclonedx["components"]).push(vendored); + + let result = run_checks(Some(&cyclonedx), None, &expectations); + assert_eq!(checks(&result), BTreeSet::new()); +} + +#[rstest] +fn other_operating_system(cyclonedx: Value, mut expectations: Expectations) { + expectations.operating_system = "rocky".to_owned(); + let result = run_checks(Some(&cyclonedx), None, &expectations); + assert_eq!(checks(&result), BTreeSet::from(["cdx-operating-system"])); +} + +#[rstest] +fn old_image_is_a_warning(mut cyclonedx: Value, expectations: Expectations) { + cyclonedx["metadata"]["properties"] = json!([{ + "name": "syft:image:labels:org.opencontainers.image.created", + "value": "2020-01-01T00:00:00.123456789Z", + }]); + let result = run_checks(Some(&cyclonedx), None, &expectations); + + let findings: Vec<(Severity, &str)> = result + .findings + .iter() + .map(|finding| (finding.severity, finding.check)) + .collect(); + assert_eq!(findings, [(Severity::Warning, "image-age")]); +} + +#[rstest] +fn ignore_findings(mut cyclonedx: Value, mut expectations: Expectations) { + cyclonedx["specVersion"] = json!("1.5"); + let mut result = run_checks(Some(&cyclonedx), None, &expectations); + + expectations.ignore.insert("cdx-format".to_owned()); + apply_ignores(&mut result, &expectations); + + assert_eq!((result.findings.len(), result.ignored), (0, 1)); +} + +#[rstest] +#[case::same_components_in_other_versions( + &[GLIBC, KAFKA], + &["pkg:rpm/redhat/glibc@2.34-2.el9?arch=aarch64&distro=rhel-9.9", KAFKA], + false +)] +#[case::half_the_components_missing( + &["pkg:maven/a/a@1", "pkg:maven/b/b@1", "pkg:maven/c/c@1", "pkg:maven/d/d@1"], + &["pkg:maven/a/a@1", "pkg:maven/b/b@1"], + true +)] +fn compare_architectures(#[case] amd64: &[&str], #[case] arm64: &[&str], #[case] differ: bool) { + let identity = |purls: &[&str]| -> Identity { + purls + .iter() + .filter_map(|purl| Purl::parse(purl)) + .map(|purl| (purl.package_type().to_owned(), purl.name().to_owned())) + .collect() + }; + let mut results = vec![ + ImageResult::new(target("amd64"), None), + ImageResult::new(target("arm64"), None), + ]; + let identities = BTreeMap::from([ + (target("amd64"), identity(amd64)), + (target("arm64"), identity(arm64)), + ]); + + check_architectures_agree(&mut results, &identities); + + let reported: Vec> = results.iter().map(checks).collect(); + let expected = if differ { + BTreeSet::from(["architectures-agree"]) + } else { + BTreeSet::new() + }; + assert_eq!(reported, [BTreeSet::new(), expected]); +} + +#[rstest] +#[case("4.3.1", Some("4.3.1"), true)] +#[case("4.3.1-stackable0.0.0-dev", Some("4.3.1"), true)] +#[case("v1.20.2-stackable0.0.0-dev%2Bdirty", Some("v1.20.2"), true)] +#[case("4.3.10", Some("4.3.1"), false)] +#[case("4.3.1.1", Some("4.3.1"), false)] +#[case("4.3.0", Some("4.3.1"), false)] +#[case("21.0.13.0.0.9-1", None, true)] +fn match_versions(#[case] actual: &str, #[case] expected: Option<&str>, #[case] matches: bool) { + assert_eq!(matches_version(actual, expected), matches); +} + +#[rstest] +fn build_expected_image_purl() { + assert_eq!( + expected_image_purl("oci.stackable.tech/sdp", &target("amd64"), DIGEST), + IMAGE_PURL + ); +} + +#[rstest] +#[case::few(&["b", "a"], "a, b")] +#[case::many(&["a", "b", "c", "d", "e"], "a, b, c and 2 more")] +#[case::duplicates(&["a", "a"], "a")] +fn sample_examples(#[case] items: &[&str], #[case] sample: &str) { + assert_eq!(examples(items), sample); +} diff --git a/rust/sbom-quality/src/expectations.rs b/rust/sbom-quality/src/expectations.rs new file mode 100644 index 000000000..dfab0b0d1 --- /dev/null +++ b/rust/sbom-quality/src/expectations.rs @@ -0,0 +1,654 @@ +//! The expectations file and the list of images to check. + +use std::{ + collections::{BTreeMap, BTreeSet}, + fmt, + path::{Path, PathBuf}, + str::FromStr, +}; + +use serde::{Deserialize, Serialize}; +use snafu::{ResultExt, Snafu, ensure}; + +/// Where the expectations file is, relative to the docker-images repository. +pub const DEFAULT_PATH: &str = "rust/sbom-quality/expectations.toml"; + +#[derive(Debug, Snafu)] +pub enum Error { + #[snafu(display("failed to read the expectations file {path:?}"))] + ReadExpectations { + source: std::io::Error, + path: PathBuf, + }, + + #[snafu(display("failed to parse the expectations file {path:?}"))] + ParseExpectations { + source: toml::de::Error, + path: PathBuf, + }, + + #[snafu(display("{table:?} has `images`, which only [operators] may have"))] + ImagesOutsideOperators { table: String }, + + #[snafu(display("{table:?} has `versions`, which only a product may have"))] + UnexpectedVersions { table: String }, + + #[snafu(display("{table:?} has the invalid embedded SBOM pattern {pattern:?}"))] + InvalidPattern { + source: glob::PatternError, + table: String, + pattern: String, + }, + + #[snafu(display("failed to read the boil configuration {path:?}"))] + ReadBoilConfig { + source: std::io::Error, + path: PathBuf, + }, + + #[snafu(display("failed to parse the boil configuration {path:?}"))] + ParseBoilConfig { + source: toml::de::Error, + path: PathBuf, + }, + + #[snafu(display("{name:?} is neither a product nor an operator in the expectations"))] + UnknownImage { name: String }, + + #[snafu(display("{product:?} has no version {version:?} in its boil-config.toml"))] + UnknownVersion { product: String, version: String }, +} + +#[derive(Debug, Snafu)] +pub enum ParseSelectorError { + #[snafu(display("the name must not be empty, expected NAME[=VERSION]"))] + EmptyName, + + #[snafu(display("the version must not be empty, expected NAME[=VERSION]"))] + EmptyVersion, +} + +/// Narrows the check down to a product, a product version or an operator: `kafka`, +/// `kafka=4.3.1`, `kafka-operator`. +#[derive(Debug, Clone)] +pub struct Selector { + name: String, + version: Option, +} + +impl FromStr for Selector { + type Err = ParseSelectorError; + + fn from_str(input: &str) -> Result { + let (name, version) = match input.split_once('=') { + Some((name, version)) => { + ensure!(!version.is_empty(), EmptyVersionSnafu); + (name, Some(version.to_owned())) + } + None => (input, None), + }; + ensure!(!name.is_empty(), EmptyNameSnafu); + Ok(Self { + name: name.to_owned(), + version, + }) + } +} + +/// The expectations file. Its top-level settings apply to every image. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "kebab-case")] +pub struct ExpectationsFile { + pub registry: String, + pub release: String, + pub architectures: Vec, + + #[serde(default = "default_certificate_identity_regexp")] + pub certificate_identity_regexp: String, + + #[serde(default = "default_certificate_oidc_issuer")] + pub certificate_oidc_issuer: String, + + pub cyclonedx_spec_version: String, + pub max_image_age_days: i64, + pub operating_system: String, + pub max_without_purl: f64, + pub max_without_version: f64, + + #[serde(default)] + pub ignore: Vec, + + /// Directories with a boil-config.toml whose images are not published. + #[serde(default)] + pub unchecked: Vec, + + #[serde(default)] + pub operators: Layer, + + #[serde(default)] + pub products: BTreeMap, +} + +fn default_certificate_identity_regexp() -> String { + r"^https://github.com/stackabletech/.+/.github/workflows/.+@.+".to_owned() +} + +fn default_certificate_oidc_issuer() -> String { + "https://token.actions.githubusercontent.com".to_owned() +} + +/// Expectations of `[operators]`, a `[products.]` or one of their versions. Each one +/// overrides the layer below it. +#[derive(Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields, rename_all = "kebab-case")] +pub struct Layer { + /// The operator images, only in `[operators]`. + pub images: Vec, + + pub main_component: Option, + pub embedded_sboms: Option>, + + /// Merged with the floors of the layer below, key by key. + pub min_components: BTreeMap, + + pub min_license_coverage: Option, + pub operating_system: Option, + pub max_without_purl: Option, + pub max_without_version: Option, + + /// Added to the ignored checks of the layer below. + pub ignore: Vec, + + /// Layers for single product versions, only in `[products.]`. + pub versions: BTreeMap, +} + +#[derive(Debug, Deserialize)] +#[serde(untagged)] +pub enum OneOrMany { + One(String), + Many(Vec), +} + +impl OneOrMany { + fn to_vec(&self) -> Vec { + match self { + Self::One(item) => vec![item.clone()], + Self::Many(items) => items.clone(), + } + } +} + +/// Everything that is expected from the SBOMs of one image. +#[derive(Debug, Clone)] +pub struct Expectations { + pub registry: String, + pub release: String, + pub cyclonedx_spec_version: String, + pub max_image_age_days: i64, + pub operating_system: String, + pub max_without_purl: f64, + pub max_without_version: f64, + + /// Purls of the product, see [`crate::check::substitute`] for the placeholders. + pub main_components: Vec, + + /// Paths of build-time SBOMs, with placeholders and `*` wildcards. + pub embedded_sboms: Vec, + + pub min_components: BTreeMap, + pub min_license_coverage: Option, + pub ignore: BTreeSet, +} + +impl Expectations { + fn apply(&mut self, layer: &Layer) { + if let Some(main_component) = &layer.main_component { + self.main_components = main_component.to_vec(); + } + if let Some(embedded_sboms) = &layer.embedded_sboms { + self.embedded_sboms.clone_from(embedded_sboms); + } + if let Some(operating_system) = &layer.operating_system { + self.operating_system.clone_from(operating_system); + } + self.min_components.extend( + layer + .min_components + .iter() + .map(|(kind, minimum)| (kind.clone(), *minimum)), + ); + self.min_license_coverage = layer.min_license_coverage.or(self.min_license_coverage); + self.max_without_purl = layer.max_without_purl.unwrap_or(self.max_without_purl); + self.max_without_version = layer + .max_without_version + .unwrap_or(self.max_without_version); + self.ignore.extend(layer.ignore.iter().cloned()); + } +} + +/// One architecture of one image tag. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)] +pub struct Target { + pub image: String, + + /// The product version, `None` for images that are only tagged with the release (operators). + pub version: Option, + + pub tag: String, + pub architecture: String, +} + +impl Target { + pub fn canonical_tag(&self) -> String { + format!( + "{tag}-{architecture}", + tag = self.tag, + architecture = self.architecture + ) + } +} + +impl fmt::Display for Target { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + formatter, + "{image}:{tag}", + image = self.image, + tag = self.canonical_tag() + ) + } +} + +impl ExpectationsFile { + pub fn load(path: &Path) -> Result { + let content = std::fs::read_to_string(path).context(ReadExpectationsSnafu { path })?; + let file: Self = toml::from_str(&content).context(ParseExpectationsSnafu { path })?; + file.validate()?; + Ok(file) + } + + /// Rejects what the format allows but what makes no sense, so it is not silently ignored. + fn validate(&self) -> Result<(), Error> { + let mut layers = vec![("operators".to_owned(), &self.operators)]; + ensure!( + self.operators.versions.is_empty(), + UnexpectedVersionsSnafu { table: "operators" } + ); + + for (product, layer) in &self.products { + let table = format!("products.{product}"); + ensure!( + layer.images.is_empty(), + ImagesOutsideOperatorsSnafu { table: &table } + ); + for (version, version_layer) in &layer.versions { + let version_table = format!("{table}.versions.{version}"); + ensure!( + version_layer.images.is_empty(), + ImagesOutsideOperatorsSnafu { + table: &version_table + } + ); + ensure!( + version_layer.versions.is_empty(), + UnexpectedVersionsSnafu { + table: &version_table + } + ); + layers.push((version_table, version_layer)); + } + layers.push((table, layer)); + } + + for (table, layer) in layers { + for pattern in layer.embedded_sboms.iter().flatten() { + glob::Pattern::new(pattern).context(InvalidPatternSnafu { + table: &table, + pattern, + })?; + } + } + Ok(()) + } + + /// The expectations for one image: the top-level settings, overridden by the ones of the + /// product or of the operators, overridden by the ones of the product version. + pub fn for_image(&self, image: &str, version: Option<&str>) -> Expectations { + let layer = self.products.get(image).unwrap_or(&self.operators); + let version_layer = version.and_then(|version| layer.versions.get(version)); + + let mut expectations = Expectations { + registry: self.registry.clone(), + release: self.release.clone(), + cyclonedx_spec_version: self.cyclonedx_spec_version.clone(), + max_image_age_days: self.max_image_age_days, + operating_system: self.operating_system.clone(), + max_without_purl: self.max_without_purl, + max_without_version: self.max_without_version, + main_components: Vec::new(), + embedded_sboms: Vec::new(), + min_components: BTreeMap::new(), + min_license_coverage: None, + ignore: self.ignore.iter().cloned().collect(), + }; + for layer in std::iter::once(layer).chain(version_layer) { + expectations.apply(layer); + } + expectations + } + + /// Every image architecture to check, optionally narrowed down by `name` or `name=version` + /// selectors. Also returns the problems with the expectations found along the way. + pub fn select_targets( + &self, + repository: &Path, + selectors: &[Selector], + architectures: &[String], + ) -> Result<(Vec, Vec), Error> { + let mut wanted = BTreeMap::<&str, BTreeSet>>::new(); + for selector in selectors { + let name = selector.name.as_str(); + let version = selector.version.as_deref(); + ensure!( + self.products.contains_key(name) + || self.operators.images.iter().any(|image| image == name), + UnknownImageSnafu { name } + ); + wanted.entry(name).or_default().insert(version); + } + let is_wanted = |name: &str, version: Option<&str>| { + selectors.is_empty() + || wanted + .get(name) + .is_some_and(|versions| versions.contains(&None) || versions.contains(&version)) + }; + + let mut problems = Vec::new(); + let mut tags = Vec::new(); + for (product, layer) in &self.products { + if !selectors.is_empty() && !wanted.contains_key(product.as_str()) { + continue; + } + + let versions = product_versions(repository, product)?; + for version in &versions { + if is_wanted(product, Some(version)) { + let tag = format!("{version}-stackable{release}", release = self.release); + tags.push((product.clone(), Some(version.clone()), tag)); + } + } + + for version in wanted.get(product.as_str()).into_iter().flatten().flatten() { + ensure!( + versions.iter().any(|known| known == version), + UnknownVersionSnafu { + product, + version: *version + } + ); + } + + // Expectations for a removed version are dead weight that nobody cleans up. + for version in layer.versions.keys() { + if !versions.contains(version) { + problems.push(format!( + "[products.{product}.versions] has expectations for {version}, which \ + boil does not build" + )); + } + } + } + for operator in &self.operators.images { + if is_wanted(operator, None) { + tags.push((operator.clone(), None, self.release.clone())); + } + } + + if selectors.is_empty() { + problems.extend(self.unknown_products(repository)?); + } + + let targets = tags + .into_iter() + .flat_map(|(image, version, tag)| { + architectures.iter().map(move |architecture| Target { + image: image.clone(), + version: version.clone(), + tag: tag.clone(), + architecture: architecture.clone(), + }) + }) + .collect(); + Ok((targets, problems)) + } + + /// A new product must not slip through because nobody added it to the expectations. + fn unknown_products(&self, repository: &Path) -> Result, Error> { + let entries = + std::fs::read_dir(repository).context(ReadBoilConfigSnafu { path: repository })?; + let mut built = BTreeSet::new(); + for entry in entries { + let entry = entry.context(ReadBoilConfigSnafu { path: repository })?; + if entry.path().join("boil-config.toml").is_file() { + built.insert(entry.file_name().to_string_lossy().into_owned()); + } + } + + Ok(built + .into_iter() + .filter(|name| !self.products.contains_key(name) && !self.unchecked.contains(name)) + .map(|name| { + format!("{name} is built by boil but is neither in [products] nor in `unchecked`") + }) + .collect()) + } +} + +/// The versions of a product that boil builds. +fn product_versions(repository: &Path, product: &str) -> Result, Error> { + let path = repository.join(product).join("boil-config.toml"); + let content = std::fs::read_to_string(&path).context(ReadBoilConfigSnafu { path: &path })?; + let config: toml::Table = + toml::from_str(&content).context(ParseBoilConfigSnafu { path: &path })?; + Ok(config + .get("versions") + .and_then(toml::Value::as_table) + .map(|versions| versions.keys().cloned().collect()) + .unwrap_or_default()) +} + +#[cfg(test)] +mod tests { + use rstest::{fixture, rstest}; + + use super::*; + + const EXPECTATIONS: &str = r#" + registry = "oci.stackable.tech/sdp" + release = "0.0.0-dev" + architectures = ["amd64", "arm64"] + cyclonedx-spec-version = "1.7" + max-image-age-days = 7 + operating-system = "redhat" + max-without-purl = 0.05 + max-without-version = 0.05 + unchecked = ["stackable-devel"] + + [operators] + images = ["kafka-operator"] + min-components = { total = 300 } + + [products.kafka] + ignore = ["cdx-size"] + min-license-coverage = 0.9 + min-components = { total = 1000, maven = 100 } + + [products.kafka.versions."3.9.2"] + min-license-coverage = 0.5 + min-components = { maven = 50 } + "#; + + #[fixture] + fn expectations() -> ExpectationsFile { + let file: ExpectationsFile = + toml::from_str(EXPECTATIONS).expect("the expectations should parse"); + file.validate().expect("the expectations should be valid"); + file + } + + fn parse(selector: &str) -> Selector { + selector.parse().expect("the selector should be valid") + } + + #[rstest] + #[case::name("kafka", "kafka", None)] + #[case::name_and_version("kafka=1.2.3", "kafka", Some("1.2.3"))] + fn parse_selectors(#[case] input: &str, #[case] name: &str, #[case] version: Option<&str>) { + let selector = parse(input); + assert_eq!(selector.name, name); + assert_eq!(selector.version.as_deref(), version); + } + + #[rstest] + #[case::empty("")] + #[case::empty_name("=4.3.1")] + #[case::empty_version("kafka=")] + fn reject_malformed_selectors(#[case] selector: &str) { + assert!( + selector.parse::().is_err(), + "{selector:?} should be rejected" + ); + } + + /// A docker-images checkout with the given products and their versions. + fn repository(products: &[(&str, &[&str])]) -> tempfile::TempDir { + let directory = tempfile::tempdir().expect("a temporary directory should be created"); + for (product, versions) in products { + let path = directory.path().join(product); + std::fs::create_dir(&path).expect("the product directory should be created"); + let tables: String = versions + .iter() + .map(|version| format!("[versions.\"{version}\"]\n")) + .collect(); + std::fs::write(path.join("boil-config.toml"), tables) + .expect("the boil configuration should be written"); + } + directory + } + + #[rstest] + fn layers_override_each_other(expectations: ExpectationsFile) { + let product = expectations.for_image("kafka", Some("4.3.1")); + let version = expectations.for_image("kafka", Some("3.9.2")); + let operator = expectations.for_image("kafka-operator", None); + + assert_eq!( + product.min_components, + BTreeMap::from([("maven".to_owned(), 100), ("total".to_owned(), 1000)]) + ); + assert_eq!( + version.min_components, + BTreeMap::from([("maven".to_owned(), 50), ("total".to_owned(), 1000)]) + ); + assert_eq!(product.min_license_coverage, Some(0.9)); + assert_eq!(version.min_license_coverage, Some(0.5)); + assert_eq!(version.ignore, BTreeSet::from(["cdx-size".to_owned()])); + assert_eq!( + operator.min_components, + BTreeMap::from([("total".to_owned(), 300)]) + ); + assert_eq!(operator.operating_system, "redhat"); + } + + #[rstest] + #[case::unknown_key("[products.kafka]\nmin-component = 1")] + #[case::images_in_product("[products.kafka]\nimages = [\"a\"]")] + #[case::nested_versions("[products.kafka.versions.\"1\".versions.\"2\"]")] + #[case::invalid_pattern("[products.kafka]\nembedded-sboms = [\"/a/[b\"]")] + fn reject_invalid_expectations(#[case] addition: &str) { + let content = format!("{EXPECTATIONS}\n{addition}"); + let parsed = toml::from_str::(&content) + .map_err(|error| error.to_string()) + .and_then(|file| file.validate().map_err(|error| error.to_string())); + assert!(parsed.is_err(), "{addition:?} should be rejected"); + } + + #[rstest] + #[case::everything( + &[], + &[ + "kafka:3.9.2-stackable0.0.0-dev-amd64", + "kafka:3.9.2-stackable0.0.0-dev-arm64", + "kafka:4.3.1-stackable0.0.0-dev-amd64", + "kafka:4.3.1-stackable0.0.0-dev-arm64", + "kafka-operator:0.0.0-dev-amd64", + "kafka-operator:0.0.0-dev-arm64", + ] + )] + #[case::product( + &["kafka"], + &[ + "kafka:3.9.2-stackable0.0.0-dev-amd64", + "kafka:3.9.2-stackable0.0.0-dev-arm64", + "kafka:4.3.1-stackable0.0.0-dev-amd64", + "kafka:4.3.1-stackable0.0.0-dev-arm64", + ] + )] + #[case::version_and_operator( + &["kafka=4.3.1", "kafka-operator"], + &[ + "kafka:4.3.1-stackable0.0.0-dev-amd64", + "kafka:4.3.1-stackable0.0.0-dev-arm64", + "kafka-operator:0.0.0-dev-amd64", + "kafka-operator:0.0.0-dev-arm64", + ] + )] + fn select_targets( + expectations: ExpectationsFile, + #[case] selectors: &[&str], + #[case] expected: &[&str], + ) { + let repository = repository(&[("kafka", &["3.9.2", "4.3.1"]), ("stackable-devel", &["1"])]); + let selectors: Vec = selectors.iter().map(|selector| parse(selector)).collect(); + let architectures = ["amd64".to_owned(), "arm64".to_owned()]; + + let (targets, problems) = expectations + .select_targets(repository.path(), &selectors, &architectures) + .expect("the targets should be selected"); + + let targets: Vec = targets.iter().map(ToString::to_string).collect(); + assert_eq!(targets, expected); + assert_eq!(problems, Vec::::new()); + } + + #[rstest] + #[case::unknown_image("zookeeper")] + #[case::unknown_version("kafka=1.0.0")] + fn reject_unknown_selectors(expectations: ExpectationsFile, #[case] selector: &str) { + let repository = repository(&[("kafka", &["3.9.2", "4.3.1"])]); + let result = expectations.select_targets( + repository.path(), + &[parse(selector)], + &["amd64".to_owned()], + ); + assert!(result.is_err(), "{selector:?} should be rejected"); + } + + #[rstest] + fn report_new_product_and_removed_version(expectations: ExpectationsFile) { + let repository = repository(&[("kafka", &["4.3.1"]), ("new-product", &["1.0.0"])]); + + let (_, problems) = expectations + .select_targets(repository.path(), &[], &["amd64".to_owned()]) + .expect("the targets should be selected"); + + assert_eq!( + problems, + [ + "[products.kafka.versions] has expectations for 3.9.2, which boil does not build", + "new-product is built by boil but is neither in [products] nor in `unchecked`", + ] + ); + } +} diff --git a/rust/sbom-quality/src/main.rs b/rust/sbom-quality/src/main.rs new file mode 100644 index 000000000..c6a8d7bbc --- /dev/null +++ b/rust/sbom-quality/src/main.rs @@ -0,0 +1,367 @@ +//! Checks the quality of the SBOMs that are attested to our published images. +//! +//! See the README for what is checked and why. + +use std::{ + collections::{BTreeMap, BTreeSet}, + path::{Path, PathBuf}, + process::ExitCode, + sync::{ + Mutex, PoisonError, + atomic::{AtomicUsize, Ordering}, + }, +}; + +use clap::{Parser, ValueEnum}; +use snafu::{ResultExt, Snafu, ensure}; + +use crate::{ + check::{Identity, ImageResult}, + expectations::{DEFAULT_PATH, ExpectationsFile, Selector, Target}, + registry::Attestation, +}; + +mod check; +mod expectations; +mod purl; +mod registry; +mod report; +mod sbom; + +#[derive(Debug, Snafu)] +enum Error { + #[snafu(display("failed to load the expectations"))] + LoadExpectations { source: expectations::Error }, + + #[snafu(display("failed to select the images to check"))] + SelectTargets { source: expectations::Error }, + + #[snafu(display( + "local SBOM files need exactly one image (name=version or an operator, and --arch), got {count}" + ))] + LocalFilesNeedOneImage { count: usize }, + + #[snafu(display("failed to read the SBOM file {path:?}"))] + ReadSbom { + source: std::io::Error, + path: PathBuf, + }, + + #[snafu(display("failed to serialize the results as JSON"))] + SerializeJson { source: serde_json::Error }, +} + +/// Checks the SBOMs attested to the images in the expectations, every architecture, CycloneDX +/// and SPDX. +/// +/// Needs `crane` and `cosign` on the PATH. Exits with 1 if there is an error finding and with 2 if +/// the check itself fails. +#[derive(Debug, Parser)] +#[command(version)] +struct Cli { + /// Only check these products, product versions or operators: `kafka`, `kafka=4.3.1`. + #[arg(value_name = "NAME[=VERSION]")] + selectors: Vec, + + /// The docker-images checkout, for the versions in the boil-config.toml files. + #[arg(long, default_value = ".")] + repository: PathBuf, + + /// The expectations file. Defaults to the one in the repository. + #[arg(long)] + expectations: Option, + + /// Only check this architecture. Can be given more than once. + #[arg(long = "arch")] + architectures: Vec, + + /// Keep fetched attestations in this directory. They are immutable per image digest. + #[arg(long)] + cache_dir: Option, + + /// How many images are fetched and checked at the same time. + #[arg(long, default_value_t = 8)] + jobs: usize, + + #[arg(long, value_enum, default_value_t = Format::Text)] + format: Format, + + /// List every finding and every image instead of a summary per check. + #[arg(long)] + verbose: bool, + + /// Print floors for the expectations from the current SBOMs instead of the findings. + #[arg(long)] + suggest_floors: bool, + + /// How far below the smallest current count the suggested floors are. + #[arg(long, default_value_t = 0.2)] + margin: f64, + + /// Check this CycloneDX file instead of the attestation in the registry. + #[arg(long)] + cyclonedx: Option, + + /// Check this SPDX file instead of the attestation in the registry. + #[arg(long)] + spdx: Option, + + /// The digest of the image the local files belong to. + #[arg(long)] + digest: Option, +} + +#[derive(Debug, Clone, Copy, ValueEnum)] +enum Format { + Text, + Json, +} + +fn main() -> ExitCode { + match run(Cli::parse()) { + Ok(exit_code) => exit_code, + Err(error) => { + eprintln!("{report}", report = snafu::Report::from_error(error)); + ExitCode::from(2) + } + } +} + +fn run(cli: Cli) -> Result { + let expectations_path = cli + .expectations + .clone() + .unwrap_or_else(|| cli.repository.join(DEFAULT_PATH)); + let expectations = ExpectationsFile::load(&expectations_path).context(LoadExpectationsSnafu)?; + let architectures = if cli.architectures.is_empty() { + expectations.architectures.clone() + } else { + cli.architectures.clone() + }; + let (targets, problems) = expectations + .select_targets(&cli.repository, &cli.selectors, &architectures) + .context(SelectTargetsSnafu)?; + + let results = if cli.cyclonedx.is_some() || cli.spdx.is_some() { + vec![check_local_files(&cli, &expectations, targets)?] + } else { + check_registry(&expectations, &targets, cli.cache_dir.as_deref(), cli.jobs) + }; + + if cli.suggest_floors { + print!( + "{floors}", + floors = report::SuggestedFloors::new(&expectations, &results, cli.margin) + ); + return Ok(ExitCode::SUCCESS); + } + + match cli.format { + Format::Text => print!( + "{report}", + report = report::TextReport::new(&results, &problems, cli.verbose) + ), + Format::Json => println!( + "{json}", + json = report::to_json(&results, &problems).context(SerializeJsonSnafu)? + ), + } + + if problems.is_empty() && !results.iter().any(ImageResult::has_errors) { + Ok(ExitCode::SUCCESS) + } else { + Ok(ExitCode::FAILURE) + } +} + +fn check_local_files( + cli: &Cli, + expectations: &ExpectationsFile, + targets: Vec, +) -> Result { + ensure!( + targets.len() == 1, + LocalFilesNeedOneImageSnafu { + count: targets.len() + } + ); + let read = |path: &Option| { + path.as_ref() + .map(|path| std::fs::read_to_string(path).context(ReadSbomSnafu { path })) + .transpose() + }; + let cyclonedx = read(&cli.cyclonedx)?; + let spdx = read(&cli.spdx)?; + + let Some(target) = targets.into_iter().next() else { + return LocalFilesNeedOneImageSnafu { count: 0_usize }.fail(); + }; + let image_expectations = expectations.for_image(&target.image, target.version.as_deref()); + let mut result = ImageResult::new(target, cli.digest.clone()); + check::check_sboms( + &mut result, + cyclonedx.as_deref(), + spdx.as_deref(), + &image_expectations, + ); + check::apply_ignores(&mut result, &image_expectations); + Ok(result) +} + +fn check_registry( + expectations: &ExpectationsFile, + targets: &[Target], + cache_dir: Option<&Path>, + jobs: usize, +) -> Vec { + let tags: Vec<(String, String)> = targets + .iter() + .map(|target| (target.image.clone(), target.tag.clone())) + .collect::>() + .into_iter() + .collect(); + let digests: BTreeMap<&(String, String), _> = tags + .iter() + .zip(parallel_map(&tags, jobs, |(image, tag)| { + registry::resolve_digests(&expectations.registry, image, tag) + })) + .collect(); + + let checked = parallel_map(targets, jobs, |target| { + let key = (target.image.clone(), target.tag.clone()); + check_target(expectations, target, digests.get(&key), cache_dir) + }); + + let mut identities = BTreeMap::new(); + let mut results = Vec::with_capacity(checked.len()); + for (result, identity) in checked { + if let Some(identity) = identity { + identities.insert(result.target.clone(), identity); + } + results.push(result); + } + + check::check_architectures_agree(&mut results, &identities); + for result in &mut results { + let image_expectations = + expectations.for_image(&result.target.image, result.target.version.as_deref()); + check::apply_ignores(result, &image_expectations); + } + results +} + +/// Checks one image architecture. Also returns its components for comparing the architectures, +/// if it has any. +fn check_target( + expectations: &ExpectationsFile, + target: &Target, + digests: Option<&Result, registry::Error>>, + cache_dir: Option<&Path>, +) -> (ImageResult, Option) { + let mut result = ImageResult::new(target.clone(), None); + let image_expectations = expectations.for_image(&target.image, target.version.as_deref()); + + let digests = match digests { + Some(Ok(digests)) => digests, + Some(Err(error)) => { + result.error( + "image-missing", + format!( + "cannot resolve {image}:{tag}: {error}", + image = target.image, + tag = target.tag, + error = error_chain(error), + ), + ); + return (result, None); + } + None => return (result, None), + }; + let Some(digest) = digests.get(&target.architecture) else { + result.error( + "image-missing", + format!( + "{image}:{tag} has no {architecture} image", + image = target.image, + tag = target.tag, + architecture = target.architecture, + ), + ); + return (result, None); + }; + result.digest = Some(digest.clone()); + + let mut fetch = |attestation: Attestation| match registry::fetch_sbom( + expectations, + &target.image, + digest, + attestation, + cache_dir, + ) { + Ok(sbom) => Some(sbom), + Err(error) => { + result.error( + attestation.check(), + format!( + "no verified {kind} attestation: {error}", + kind = attestation.cosign_type(), + error = error_chain(&error) + ), + ); + None + } + }; + let cyclonedx = fetch(Attestation::CycloneDx); + let spdx = fetch(Attestation::Spdx); + + let identity = check::check_sboms( + &mut result, + cyclonedx.as_deref(), + spdx.as_deref(), + &image_expectations, + ); + ( + result, + Some(identity).filter(|identity| !identity.is_empty()), + ) +} + +/// An error and its sources on one line, for a finding. +fn error_chain(error: &dyn std::error::Error) -> String { + std::iter::successors(Some(error), |error| error.source()) + .map(ToString::to_string) + .collect::>() + .join(": ") +} + +/// Maps the items on `jobs` threads, keeping their order. +fn parallel_map(items: &[T], jobs: usize, function: F) -> Vec +where + T: Sync, + R: Send, + F: Fn(&T) -> R + Sync, +{ + let next = AtomicUsize::new(0); + let results = Mutex::new(Vec::with_capacity(items.len())); + std::thread::scope(|scope| { + for _ in 0..jobs.clamp(1, items.len().max(1)) { + scope.spawn(|| { + loop { + let index = next.fetch_add(1, Ordering::Relaxed); + let Some(item) = items.get(index) else { + break; + }; + let result = function(item); + results + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push((index, result)); + } + }); + } + }); + + let mut results = results.into_inner().unwrap_or_else(PoisonError::into_inner); + results.sort_by_key(|(index, _)| *index); + results.into_iter().map(|(_, result)| result).collect() +} diff --git a/rust/sbom-quality/src/purl.rs b/rust/sbom-quality/src/purl.rs new file mode 100644 index 000000000..65c835f70 --- /dev/null +++ b/rust/sbom-quality/src/purl.rs @@ -0,0 +1,170 @@ +//! Package URLs, parsed with the purl crate that mergebom validates them with as well. + +use std::{collections::BTreeMap, str::FromStr}; + +use purl::GenericPurl; + +/// A valid purl. [`Purl::parse`] is the only way to create one. +#[derive(Debug, PartialEq, Eq)] +pub struct Purl { + package_type: String, + name: String, + version: Option, + qualifiers: BTreeMap, +} + +impl Purl { + /// Parses a purl, or returns `None` for a string that does not conform to the Package URL + /// specification. Type-specific rules are not applied, like in mergebom. + pub fn parse(purl: &str) -> Option { + let purl = GenericPurl::::from_str(purl).ok()?; + let name = match purl.namespace() { + Some(namespace) => format!("{namespace}/{name}", name = purl.name()), + None => purl.name().to_owned(), + }; + + Some(Self { + package_type: purl.package_type().to_lowercase(), + name, + version: purl + .version() + .filter(|version| !version.is_empty()) + .map(ToOwned::to_owned), + qualifiers: purl + .qualifiers() + .iter() + .map(|(key, value)| (key.as_ref().to_owned(), value.to_owned())) + .collect(), + }) + } + + /// The package type in lower case, for example `rpm`. + pub fn package_type(&self) -> &str { + &self.package_type + } + + /// The name including the namespace, for example `redhat/glibc`. + pub fn name(&self) -> &str { + &self.name + } + + /// The version, `None` if it is missing or empty. + pub fn version(&self) -> Option<&str> { + self.version.as_deref() + } + + pub fn qualifier(&self, key: &str) -> Option<&str> { + self.qualifiers.get(key).map(String::as_str) + } + + /// The last segment of the name, without the namespace. + pub fn short_name(&self) -> &str { + self.name + .rsplit_once('/') + .map_or(self.name.as_str(), |(_, name)| name) + } +} + +/// Decodes `%XX` escapes. Invalid escapes are kept as they are, and bytes that do not form valid +/// UTF-8 are replaced by U+FFFD. +pub fn percent_decode(input: &str) -> String { + let bytes = input.as_bytes(); + let mut decoded = Vec::with_capacity(bytes.len()); + let mut index = 0; + while let Some(&byte) = bytes.get(index) { + let escaped = bytes + .get(index + 1..index + 3) + .filter(|hex| byte == b'%' && hex.iter().all(u8::is_ascii_hexdigit)) + .and_then(|hex| std::str::from_utf8(hex).ok()) + .and_then(|hex| u8::from_str_radix(hex, 16).ok()); + match escaped { + Some(escaped) => { + decoded.push(escaped); + index += 3; + } + None => { + decoded.push(byte); + index += 1; + } + } + } + String::from_utf8_lossy(&decoded).into_owned() +} + +/// Escapes everything except unreserved characters, as purl qualifier values need it. +pub fn percent_encode(input: &str) -> String { + input + .bytes() + .map(|byte| { + if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) { + char::from(byte).to_string() + } else { + format!("%{byte:02X}") + } + }) + .collect() +} + +#[cfg(test)] +mod tests { + use rstest::rstest; + + use super::*; + + #[rstest] + fn parse_purl_with_qualifiers() { + let purl = Purl::parse("pkg:rpm/redhat/glibc@2.34?arch=x86_64&distro=rhel-9.9") + .expect("the purl should be valid"); + + assert_eq!( + purl, + Purl { + package_type: "rpm".to_owned(), + name: "redhat/glibc".to_owned(), + version: Some("2.34".to_owned()), + qualifiers: BTreeMap::from([ + ("arch".to_owned(), "x86_64".to_owned()), + ("distro".to_owned(), "rhel-9.9".to_owned()), + ]), + } + ); + assert_eq!(purl.short_name(), "glibc"); + } + + #[rstest] + #[case::with_version("pkg:maven/org.example/lib@1.0", Some("1.0"))] + #[case::without_version("pkg:golang/k8s.io/api", None)] + #[case::empty_version("pkg:golang/k8s.io/api@", None)] + #[case::encoded_version("pkg:golang/opa@v1.2%2Bdirty", Some("v1.2+dirty"))] + fn parse_purl_version(#[case] purl: &str, #[case] version: Option<&str>) { + let purl = Purl::parse(purl).expect("the purl should be valid"); + assert_eq!(purl.version(), version); + } + + #[rstest] + #[case::empty("")] + #[case::no_scheme("glibc@2.34")] + #[case::no_name("pkg:rpm")] + #[case::empty_name("pkg:rpm/@1")] + fn parse_malformed_purl(#[case] purl: &str) { + assert_eq!(Purl::parse(purl), None); + } + + #[rstest] + #[case("sha256%3Aab", "sha256:ab")] + #[case("100%", "100%")] + #[case("%zz", "%zz")] + #[case("%2B%2b", "++")] + #[case::invalid_utf8("a%FFb", "a\u{FFFD}b")] + fn decode_percent_escapes(#[case] input: &str, #[case] decoded: &str) { + assert_eq!(percent_decode(input), decoded); + } + + #[rstest] + #[case("sha256:ab", "sha256%3Aab")] + #[case("oci.stackable.tech/sdp/kafka", "oci.stackable.tech%2Fsdp%2Fkafka")] + #[case("a-b_c.d~e", "a-b_c.d~e")] + fn encode_percent_escapes(#[case] input: &str, #[case] encoded: &str) { + assert_eq!(percent_encode(input), encoded); + } +} diff --git a/rust/sbom-quality/src/registry.rs b/rust/sbom-quality/src/registry.rs new file mode 100644 index 000000000..f1f970d3c --- /dev/null +++ b/rust/sbom-quality/src/registry.rs @@ -0,0 +1,231 @@ +//! Fetches image digests with crane and verified SBOM attestations with cosign. + +use std::{ + collections::BTreeMap, + path::{Path, PathBuf}, + process::{Command, Output}, +}; + +use base64::{Engine, engine::general_purpose::STANDARD as BASE64}; +use oci_spec::image::ImageIndex; +use serde_json::Value; +use snafu::{OptionExt, ResultExt, Snafu, ensure}; + +use crate::expectations::ExpectationsFile; + +#[derive(Debug, Snafu)] +pub enum Error { + #[snafu(display("failed to run {program}"))] + Run { + source: std::io::Error, + program: &'static str, + }, + + #[snafu(display("failed to fetch the image index: {message}"))] + FetchIndex { message: String }, + + #[snafu(display("failed to parse the image index"))] + ParseIndex { source: serde_json::Error }, + + #[snafu(display("the tag is not a multi-arch image index"))] + NotAnIndex, + + #[snafu(display("failed to verify the attestation: {message}"))] + VerifyAttestation { message: String }, + + #[snafu(display("failed to parse the output of cosign"))] + ParseAttestation { source: serde_json::Error }, + + #[snafu(display("the attestation has no payload"))] + MissingPayload, + + #[snafu(display("failed to decode the payload of the attestation"))] + DecodePayload { source: base64::DecodeError }, + + #[snafu(display("failed to parse the statement of the attestation"))] + ParseStatement { source: serde_json::Error }, + + #[snafu(display("the attestation has no predicate"))] + MissingPredicate, + + #[snafu(display("cosign returned no attestation"))] + NoAttestation, + + #[snafu(display("failed to serialize the SBOM"))] + SerializeSbom { source: serde_json::Error }, + + #[snafu(display("failed to read the cached SBOM {path:?}"))] + ReadCache { + source: std::io::Error, + path: PathBuf, + }, +} + +/// The kinds of SBOM attestations, named as cosign names their predicate types. +#[derive(Debug, Clone, Copy)] +pub enum Attestation { + CycloneDx, + Spdx, +} + +impl Attestation { + pub fn cosign_type(self) -> &'static str { + match self { + Self::CycloneDx => "cyclonedx", + Self::Spdx => "spdxjson", + } + } + + /// The ID of the check that reports a missing attestation. + pub fn check(self) -> &'static str { + match self { + Self::CycloneDx => "attestation-cyclonedx", + Self::Spdx => "attestation-spdxjson", + } + } +} + +/// The digest of every architecture of a multi-arch image. +pub fn resolve_digests( + registry: &str, + image: &str, + tag: &str, +) -> Result, Error> { + let output = run("crane", &["manifest", &format!("{registry}/{image}:{tag}")])?; + ensure!( + output.status.success(), + FetchIndexSnafu { + message: last_line(&output.stderr).unwrap_or_else(|| "no output".to_owned()) + } + ); + + // A single-architecture image fails here, its manifest has no `manifests`. + let index: ImageIndex = serde_json::from_slice(&output.stdout).context(ParseIndexSnafu)?; + let digests: BTreeMap = index + .manifests() + .iter() + .filter_map(|manifest| { + Some(( + manifest.platform().as_ref()?.architecture().to_string(), + manifest.digest().to_string(), + )) + }) + .collect(); + ensure!(!digests.is_empty(), NotAnIndexSnafu); + Ok(digests) +} + +/// Fetches and verifies one attestation, and returns the SBOM in it as compact JSON. +/// +/// cosign checks the signature against the identity of our GitHub workflows, and that the +/// attestation is for exactly this digest. Attestations are immutable per digest, so they are +/// cached by it. +pub fn fetch_sbom( + expectations: &ExpectationsFile, + image: &str, + digest: &str, + attestation: Attestation, + cache_dir: Option<&Path>, +) -> Result { + let cache = cache_dir.map(|cache_dir| { + cache_dir.join(image).join(format!( + "{digest}.{kind}.json", + digest = digest.replace(':', "-"), + kind = attestation.cosign_type(), + )) + }); + if let Some(cache) = &cache + && cache.exists() + { + return std::fs::read_to_string(cache).context(ReadCacheSnafu { path: cache }); + } + + let reference = format!( + "{registry}/{image}@{digest}", + registry = expectations.registry + ); + let arguments = [ + "verify-attestation", + "--type", + attestation.cosign_type(), + "--certificate-identity-regexp", + &expectations.certificate_identity_regexp, + "--certificate-oidc-issuer", + &expectations.certificate_oidc_issuer, + &reference, + ]; + // One retry, so a hiccup of the registry or of the network does not raise an alert. + let mut output = run("cosign", &arguments)?; + if !output.status.success() { + output = run("cosign", &arguments)?; + } + ensure!( + output.status.success(), + VerifyAttestationSnafu { + message: last_line(&output.stderr).unwrap_or_else(|| "no output".to_owned()) + } + ); + + let mut sboms = Vec::new(); + for line in String::from_utf8_lossy(&output.stdout).lines() { + if line.trim().is_empty() { + continue; + } + let envelope: Value = serde_json::from_str(line).context(ParseAttestationSnafu)?; + let payload = envelope + .get("payload") + .and_then(Value::as_str) + .context(MissingPayloadSnafu)?; + let statement = BASE64.decode(payload).context(DecodePayloadSnafu)?; + let mut statement: Value = + serde_json::from_slice(&statement).context(ParseStatementSnafu)?; + let sbom = statement + .get_mut("predicate") + .map(Value::take) + .context(MissingPredicateSnafu)?; + sboms.push(sbom); + } + + // A digest that was published twice has two attestations, the newest one counts. + let sbom = sboms + .into_iter() + .max_by_key(|sbom| timestamp(sbom).to_owned()) + .context(NoAttestationSnafu)?; + let json = serde_json::to_string(&sbom).context(SerializeSbomSnafu)?; + + if let Some(cache) = &cache { + // The cache only saves time, so failing to write it is not worth a finding. + let written = cache + .parent() + .map_or(Ok(()), std::fs::create_dir_all) + .and_then(|()| std::fs::write(cache, &json)); + if let Err(error) = written { + eprintln!("warning: failed to write the cache file {cache:?}: {error}"); + } + } + Ok(json) +} + +fn timestamp(sbom: &Value) -> &str { + sbom.pointer("/metadata/timestamp") + .or_else(|| sbom.pointer("/creationInfo/created")) + .and_then(Value::as_str) + .unwrap_or_default() +} + +fn run(program: &'static str, arguments: &[&str]) -> Result { + Command::new(program) + .args(arguments) + .output() + .context(RunSnafu { program }) +} + +/// The last non-empty line a tool printed, which is where crane and cosign put the reason they +/// failed. +fn last_line(output: &[u8]) -> Option { + String::from_utf8_lossy(output) + .lines() + .rev() + .find(|line| !line.trim().is_empty()) + .map(ToOwned::to_owned) +} diff --git a/rust/sbom-quality/src/report.rs b/rust/sbom-quality/src/report.rs new file mode 100644 index 000000000..ace4edf8c --- /dev/null +++ b/rust/sbom-quality/src/report.rs @@ -0,0 +1,398 @@ +//! Prints the results: as text for humans, as JSON for machines, or as floors to paste into the +//! expectations. + +use std::{ + collections::{BTreeMap, BTreeSet}, + fmt, + sync::LazyLock, +}; + +use regex::Regex; +use serde::Serialize; + +use crate::{ + check::{ImageResult, Severity, Stats}, + expectations::{ExpectationsFile, Target}, +}; + +/// The maximum number of build-time SBOMs that `--suggest-floors` suggests for `embedded-sboms`. +/// The ones with the most components are listed first. +/// +/// Some images have a build-time SBOM per plugin (NiFi has one per NAR, around a hundred), and +/// listing every one of them would bloat the expectations. The ones that are cut off are still +/// covered in aggregate by the `embedded-` floors in `min-components`. +// +// Raise it when the suggested list of a product is regularly cut off and build-time SBOMs that +// should be checked by path have to be added to the expectations by hand. Lower it when the review +// regularly drops most of the suggested paths again. +const MAX_LISTED_SBOMS: usize = 12; + +static NUMBER: LazyLock = + LazyLock::new(|| Regex::new(r"\d+").expect("static string must be a valid regular expression")); + +/// The findings as text, grouped by check and by kind of message, because a regression in the +/// pipeline hits every image at once and should read as one finding, not as two hundred. +pub struct TextReport<'a> { + results: &'a [ImageResult], + problems: &'a [String], + verbose: bool, +} + +impl<'a> TextReport<'a> { + pub fn new(results: &'a [ImageResult], problems: &'a [String], verbose: bool) -> Self { + Self { + results, + problems, + verbose, + } + } +} + +impl fmt::Display for TextReport<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (results, problems, verbose) = (self.results, self.problems, self.verbose); + type Found<'a> = Vec<(&'a Target, &'a str)>; + let mut grouped = BTreeMap::<(Severity, &str), BTreeMap>>::new(); + for result in results { + for finding in &result.findings { + // Messages that only differ in their numbers are the same kind of finding. + let kind = if verbose { + finding.message.clone() + } else { + NUMBER.replace_all(&finding.message, "N").into_owned() + }; + grouped + .entry((finding.severity, finding.check)) + .or_default() + .entry(kind) + .or_default() + .push((&result.target, &finding.message)); + } + } + + for problem in problems { + writeln!(f, "ERROR expectations\n {problem}\n")?; + } + + for ((severity, check), kinds) in &grouped { + let affected: BTreeSet<&Target> = kinds + .values() + .flatten() + .map(|(target, _)| *target) + .collect(); + let label = match severity { + Severity::Error => "ERROR ", + Severity::Warning => "WARNING", + }; + writeln!( + f, + "{label} {check} ({affected} of {total} images)", + affected = affected.len(), + total = results.len() + )?; + + let mut shown: Vec<&Found<'_>> = kinds.values().collect(); + shown.sort_by_key(|found| { + ( + std::cmp::Reverse(found.len()), + found.first().map(|(_, message)| *message), + ) + }); + let limit = if verbose { shown.len() } else { 4 }; + for found in shown.iter().take(limit) { + let names: Vec = + found.iter().map(|(target, _)| target.to_string()).collect(); + let mut location = if verbose { + names.join(", ") + } else { + names.iter().take(2).cloned().collect::>().join(", ") + }; + if !verbose && names.len() > 2 { + location.push_str(&format!(" and {more} more", more = names.len() - 2)); + } + let message = found + .first() + .map(|(_, message)| *message) + .unwrap_or_default(); + writeln!(f, " {message}\n {location}")?; + } + if shown.len() > limit { + writeln!( + f, + " ... and {more} more kinds, see --verbose", + more = shown.len() - limit + )?; + } + writeln!(f)?; + } + + let count = |severity| { + results + .iter() + .flat_map(|result| &result.findings) + .filter(|finding| finding.severity == severity) + .count() + }; + let clean = results + .iter() + .filter(|result| result.findings.is_empty()) + .count(); + let ignored: usize = results.iter().map(|result| result.ignored).sum(); + let mut summary = format!( + "{total} images checked: {clean} clean, {errors} errors, {warnings} warnings", + total = results.len(), + errors = count(Severity::Error) + problems.len(), + warnings = count(Severity::Warning), + ); + if ignored > 0 { + summary.push_str(&format!(", {ignored} findings ignored")); + } + writeln!(f, "{summary}") + } +} + +#[derive(Serialize)] +struct JsonOutput<'a> { + problems: &'a [String], + images: Vec>, +} + +#[derive(Serialize)] +struct JsonImage<'a> { + image: &'a str, + version: Option<&'a str>, + tag: String, + architecture: &'a str, + digest: Option<&'a str>, + stats: &'a Stats, + ignored: usize, + findings: &'a [crate::check::Finding], +} + +/// The findings and stats of every image as JSON. +pub fn to_json(results: &[ImageResult], problems: &[String]) -> Result { + let output = JsonOutput { + problems, + images: results + .iter() + .map(|result| JsonImage { + image: &result.target.image, + version: result.target.version.as_deref(), + tag: result.target.canonical_tag(), + architecture: &result.target.architecture, + digest: result.digest.as_deref(), + stats: &result.stats, + ignored: result.ignored, + findings: &result.findings, + }) + .collect(), + }; + serde_json::to_string_pretty(&output) +} + +/// Rounds down to two significant digits, so the floors do not pretend to be exact. +pub fn round_down(value: f64) -> u64 { + let whole = value.max(0.0) as u64; + if whole < 100 { + return whole; + } + let magnitude = 10_u64.pow(whole.to_string().len() as u32 - 2); + whole / magnitude * magnitude +} + +/// A path of an image as a pattern for `embedded-sboms`. +fn path_pattern(path: &str, target: &Target, release: &str) -> String { + let path = match target.version.as_deref() { + // Short versions like the 11 of java-base would also replace parts of other numbers. + Some(version) if version.len() > 2 => path.replace(version, "{version}"), + Some(_) => path.to_owned(), + None => path.replace(&target.image, "{image}"), + }; + path.replace(release, "{release}") +} + +/// Floors for the expectations from what is published right now: the smallest count over all +/// versions and architectures of a product, minus a margin. +/// +/// Review them before pasting. A product whose versions differ a lot is better served by +/// `versions."".min-components`. +pub struct SuggestedFloors<'a> { + expectations: &'a ExpectationsFile, + results: &'a [ImageResult], + margin: f64, +} + +impl<'a> SuggestedFloors<'a> { + pub fn new( + expectations: &'a ExpectationsFile, + results: &'a [ImageResult], + margin: f64, + ) -> Self { + Self { + expectations, + results, + margin, + } + } +} + +impl fmt::Display for SuggestedFloors<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (expectations, results, margin) = (self.expectations, self.results, self.margin); + + let mut by_group = BTreeMap::, Vec<&ImageResult>>::new(); + for result in results { + if result.stats.components.is_empty() { + continue; + } + let image = result.target.image.as_str(); + let group = expectations.products.contains_key(image).then_some(image); + by_group.entry(group).or_default().push(result); + } + + for (group, members) in &by_group { + let table = group.map_or_else( + || "operators".to_owned(), + |product| format!("products.{product}"), + ); + + let coverage = members + .iter() + .filter_map(|member| member.stats.license_coverage) + .fold(1.0_f64, f64::min); + writeln!(f, "[{table}]")?; + writeln!( + f, + "min-license-coverage = {minimum}", + minimum = ((coverage - 0.05) * 100.0).floor().max(0.0) / 100.0 + )?; + + // The build-time SBOMs that every version and architecture has, biggest first. An image + // with a hundred of them (NiFi has one per NAR) is not listed completely. + let patterns: Vec> = members + .iter() + .map(|member| { + member + .stats + .embedded_sboms + .iter() + .map(|(path, count)| { + ( + path_pattern(path, &member.target, &expectations.release), + *count, + ) + }) + .collect() + }) + .collect(); + let mut common: Vec<(&String, u64)> = patterns + .first() + .into_iter() + .flat_map(BTreeMap::keys) + .filter(|path| patterns.iter().all(|pattern| pattern.contains_key(*path))) + .map(|path| { + let smallest = patterns + .iter() + .filter_map(|pattern| pattern.get(path)) + .min() + .copied() + .unwrap_or_default(); + (path, smallest) + }) + .collect(); + common.sort_by_key(|(path, smallest)| (std::cmp::Reverse(*smallest), *path)); + let mut listed: Vec<&String> = common + .into_iter() + .take(MAX_LISTED_SBOMS) + .map(|(path, _)| path) + .collect(); + listed.sort(); + if !listed.is_empty() { + writeln!(f, "embedded-sboms = [")?; + for path in listed { + writeln!(f, " \"{path}\",")?; + } + writeln!(f, "]")?; + } + + writeln!(f, "\n[{table}.min-components]")?; + let mut kinds: Vec<&String> = members + .first() + .into_iter() + .flat_map(|member| member.stats.components.keys()) + .filter(|kind| { + members + .iter() + .all(|member| member.stats.components.contains_key(*kind)) + }) + .collect(); + kinds.sort_by_key(|kind| (*kind != "total", kind.starts_with("embedded-"), *kind)); + for kind in kinds { + let counts = members + .iter() + .filter_map(|member| member.stats.components.get(kind).copied()); + let smallest = counts.clone().min().unwrap_or_default(); + let largest = counts.max().unwrap_or_default(); + let floor = round_down(smallest as f64 * (1.0 - margin)); + // A handful of components of some type is noise, not something to guard. + if floor >= 10 { + writeln!(f, "{kind} = {floor} # observed: {smallest} to {largest}")?; + } + } + writeln!(f)?; + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use rstest::rstest; + + use super::*; + + #[rstest] + #[case(7.9, 7)] + #[case(99.0, 99)] + #[case(112.0, 110)] + #[case(1149.6, 1100)] + #[case(-3.0, 0)] + fn round_floors_down(#[case] value: f64, #[case] floor: u64) { + assert_eq!(round_down(value), floor); + } + + #[rstest] + #[case::product( + "/stackable/kafka_2.13-4.3.1-stackable0.0.0-dev/kafka.cdx.json", + Some("4.3.1"), + "/stackable/kafka_2.13-{version}-stackable{release}/kafka.cdx.json" + )] + #[case::short_version( + "/stackable/jdk-11/sbom.cdx.json", + Some("11"), + "/stackable/jdk-11/sbom.cdx.json" + )] + #[case::operator( + "/usr/local/bin/stackable-kafka-operator_bin.cdx.xml", + None, + "/usr/local/bin/stackable-{image}_bin.cdx.xml" + )] + fn turn_paths_into_patterns( + #[case] path: &str, + #[case] version: Option<&str>, + #[case] pattern: &str, + ) { + let target = Target { + image: if version.is_some() { + "kafka" + } else { + "kafka-operator" + } + .to_owned(), + version: version.map(ToOwned::to_owned), + tag: "tag".to_owned(), + architecture: "amd64".to_owned(), + }; + assert_eq!(path_pattern(path, &target, "0.0.0-dev"), pattern); + } +} diff --git a/rust/sbom-quality/src/sbom.rs b/rust/sbom-quality/src/sbom.rs new file mode 100644 index 000000000..b10140699 --- /dev/null +++ b/rust/sbom-quality/src/sbom.rs @@ -0,0 +1,190 @@ +//! The parts of CycloneDX and SPDX documents that the checks look at. +//! +//! Every field is optional, so that a missing field produces a finding of the check that needs +//! it instead of failing the whole document. Only a field of the wrong type makes a document +//! unreadable. + +use serde::Deserialize; +use serde_json::Value; + +/// Removes every `null` from objects, recursively. +/// +/// A field that is `null` means the same as a missing one, but serde only applies the default of +/// a field that is missing. mergebom writes `"documentDescribes": null`, for example. +pub fn remove_nulls(value: &mut Value) { + match value { + Value::Object(object) => { + object.retain(|_, value| !value.is_null()); + object.values_mut().for_each(remove_nulls); + } + Value::Array(items) => items.iter_mut().for_each(remove_nulls), + _ => {} + } +} + +#[derive(Debug, Default, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct CycloneDx { + pub bom_format: Option, + pub spec_version: Option, + pub serial_number: Option, + pub metadata: Metadata, + pub components: Vec, + pub dependencies: Vec, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +pub struct Metadata { + pub timestamp: Option, + pub authors: Vec, + pub lifecycles: Vec, + + /// Either an object with `components` or the deprecated list form, so it is kept as JSON. + pub tools: Value, + + pub component: Option, + pub properties: Vec, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +pub struct Component { + #[serde(rename = "type")] + pub component_type: Option, + + #[serde(rename = "bom-ref")] + pub bom_ref: Option, + + pub name: Option, + pub version: Option, + pub purl: Option, + pub description: Option, + + /// Only checked for presence, so the license choices are kept as JSON. + pub licenses: Vec, + + pub supplier: Option, + pub manufacturer: Option, + pub properties: Vec, +} + +impl Component { + pub fn property(&self, name: &str) -> Option<&str> { + self.properties + .iter() + .find(|property| property.name.as_deref() == Some(name)) + .and_then(|property| property.value.as_deref()) + } + + /// The syft cataloger that found the component. + pub fn found_by(&self) -> Option<&str> { + self.property("syft:package:foundBy") + } +} + +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +pub struct Entity { + pub name: Option, + pub url: Vec, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +pub struct Contact { + pub name: Option, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +pub struct Lifecycle { + pub phase: Option, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +pub struct Property { + pub name: Option, + pub value: Option, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct Dependency { + #[serde(rename = "ref")] + pub reference: Option, + + pub depends_on: Vec, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct Spdx { + pub spdx_version: Option, + pub data_license: Option, + + #[serde(rename = "SPDXID")] + pub spdx_id: Option, + + pub document_namespace: Option, + pub creation_info: CreationInfo, + pub document_describes: Vec, + pub packages: Vec, + pub relationships: Vec, + pub has_extracted_licensing_infos: Vec, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +pub struct CreationInfo { + pub created: Option, + pub creators: Vec, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct Package { + #[serde(rename = "SPDXID")] + pub spdx_id: Option, + + pub name: Option, + pub version_info: Option, + pub supplier: Option, + pub download_location: Option, + pub license_declared: Option, + pub license_concluded: Option, + pub primary_package_purpose: Option, + pub external_refs: Vec, +} + +impl Package { + pub fn purls(&self) -> Vec<&str> { + self.external_refs + .iter() + .filter(|reference| reference.reference_type.as_deref() == Some("purl")) + .filter_map(|reference| reference.reference_locator.as_deref()) + .collect() + } +} + +#[derive(Debug, Default, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct ExternalReference { + pub reference_type: Option, + pub reference_locator: Option, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct Relationship { + pub spdx_element_id: Option, + pub relationship_type: Option, + pub related_spdx_element: Option, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct ExtractedLicense { + pub license_id: Option, +}