From e2d24effdaf5818710f06e318212e69872700c7e Mon Sep 17 00:00:00 2001 From: OpenClaw Bot Date: Sun, 29 Nov 2026 03:30:43 +0000 Subject: [PATCH 1/3] ci: align release and security SBOM contracts Generate, enrich, validate, and score the same CycloneDX 1.6 SBOM set in Security CI and tagged releases. Add conservative deny-gated license and crates.io distribution metadata, release archive verification, and policy tests without synthetic CPE or completeness claims. Agent: Thoth Model: gpt-5.6-sol Thinking: high Bot-Owner: @llunved --- .github/workflows/release-publish.yml | 48 ++++-- .github/workflows/security.yml | 39 +++-- README.md | 4 +- RELEASING.md | 35 ++++- docs/WORKFLOW_SECURITY.md | 46 ++++-- docs/user/usage.md | 20 ++- scripts/collect_workspace_sboms.py | 28 +++- scripts/generate-sboms.sh | 82 +++++++++++ scripts/install-cyclonedx-cli.sh | 29 ++++ scripts/sbom_postprocess.py | 200 +++++++++++++++++-------- scripts/verify_sbom_release.py | 201 ++++++++++++++++++++++++++ tests/fixtures/sbom/minimal.cdx.json | 2 +- tests/test_collect_workspace_sboms.py | 31 +++- tests/test_sbom_postprocess.py | 184 ++++++++++++++++++++--- tests/test_security_workflow.py | 102 +++++++++++-- tests/test_verify_sbom_release.py | 154 ++++++++++++++++++++ 16 files changed, 1053 insertions(+), 152 deletions(-) create mode 100755 scripts/generate-sboms.sh create mode 100755 scripts/install-cyclonedx-cli.sh create mode 100755 scripts/verify_sbom_release.py create mode 100644 tests/test_verify_sbom_release.py diff --git a/.github/workflows/release-publish.yml b/.github/workflows/release-publish.yml index f0db1203..72e81420 100644 --- a/.github/workflows/release-publish.yml +++ b/.github/workflows/release-publish.yml @@ -12,7 +12,13 @@ permissions: env: CARGO_TERM_COLOR: always CARGO_NET_GIT_FETCH_WITH_CLI: "true" - CARGO_CYCLONEDX_VERSION: "0.5.9" + CARGO_CYCLONEDX_VERSION: "0.5.10" + CARGO_DENY_VERSION: "0.20.2" + CYCLONEDX_CLI_VERSION: "0.33.1" + CYCLONEDX_CLI_LINUX_X64_SHA256: "bfc8b2538da86fe239bc53658bbb63c1c8c510a293c1e6891aa5bea5d3c58746" + CYCLONEDX_CLI_LINUX_ARM64_SHA256: "b2e9fdf9665ef49868a2ec012171c6e785dcd69745bc5869e53e4f4bfb096a5f" + SBOMQS_VERSION: "v2.1.4" + SBOM_QUALITY_THRESHOLD: "8.3" jobs: validate: @@ -312,25 +318,37 @@ jobs: with: rust-version: stable components: rustfmt - cache-key: cargo-release-sbom-${{ runner.os }}-${{ runner.arch }}-stable-${{ env.CARGO_CYCLONEDX_VERSION }}-${{ hashFiles('**/Cargo.lock') }} + cache-key: cargo-release-sbom-${{ runner.os }}-${{ runner.arch }}-stable-${{ env.CARGO_CYCLONEDX_VERSION }}-${{ env.CARGO_DENY_VERSION }}-${{ hashFiles('**/Cargo.lock') }} - name: Install pinned cargo-cyclonedx run: cargo install cargo-cyclonedx --version "${CARGO_CYCLONEDX_VERSION}" --locked - - name: Generate and upload SBOMs + - name: Install pinned cargo-deny license gate + run: cargo install cargo-deny --version "${CARGO_DENY_VERSION}" --locked + - name: Install checksum-pinned CycloneDX schema validator + run: | + ./scripts/install-cyclonedx-cli.sh "${RUNNER_TEMP}/cyclonedx-cli" + echo "${RUNNER_TEMP}/cyclonedx-cli" >> "${GITHUB_PATH}" + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version: stable + - name: Install pinned sbomqs + run: | + go install github.com/interlynk-io/sbomqs/v2@${SBOMQS_VERSION} + echo "$(go env GOPATH)/bin" >> "$GITHUB_PATH" + - name: Generate, enrich, validate, and score the complete SBOM set + run: ./scripts/generate-sboms.sh sbom-artifacts sbom-artifacts/sbomqs-results.json + - name: Package and verify exact scored SBOM evidence + run: | + (cd sbom-artifacts && tar czf ../rust-gvm-api-sbom.tar.gz -- *.cdx.json *.cdx.xml sbomqs-results.json) + sha256sum rust-gvm-api-sbom.tar.gz > rust-gvm-api-sbom.tar.gz.sha256 + python3 -B scripts/verify_sbom_release.py \ + --threshold "${SBOM_QUALITY_THRESHOLD}" \ + rust-gvm-api-sbom.tar.gz \ + rust-gvm-api-sbom.tar.gz.sha256 + - name: Upload verified SBOM archive and checksum env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} RELEASE_TAG: ${{ needs.validate.outputs.tag }} - run: | - cargo metadata --locked --all-features --format-version 1 > /dev/null - cargo cyclonedx --format json --all --all-features --target all --spec-version 1.5 - cargo cyclonedx --format xml --all --all-features --target all --spec-version 1.5 - mkdir -p sbom-artifacts - python3 scripts/collect_workspace_sboms.py \ - --format json \ - --format xml \ - sbom-artifacts - cd sbom-artifacts && tar czf ../rust-gvm-api-sbom.tar.gz -- *.cdx.* && cd .. - sha256sum rust-gvm-api-sbom.tar.gz > rust-gvm-api-sbom.tar.gz.sha256 - gh release upload "${RELEASE_TAG}" rust-gvm-api-sbom.tar.gz rust-gvm-api-sbom.tar.gz.sha256 --clobber + run: gh release upload "${RELEASE_TAG}" rust-gvm-api-sbom.tar.gz rust-gvm-api-sbom.tar.gz.sha256 --clobber collect: name: Release complete diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 19d5e987..67b941b0 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -23,11 +23,15 @@ permissions: env: CARGO_AUDIT_VERSION: "0.22.2" - CARGO_CYCLONEDX_VERSION: "0.5.9" + CARGO_CYCLONEDX_VERSION: "0.5.10" + CARGO_DENY_VERSION: "0.20.2" CARGO_GEIGER_VERSION: "0.13.0" CARGO_MACHETE_VERSION: "0.9.2" CARGO_VET_VERSION: "0.10.2" - SBOMQS_VERSION: "v2.0.5" + CYCLONEDX_CLI_VERSION: "0.33.1" + CYCLONEDX_CLI_LINUX_X64_SHA256: "bfc8b2538da86fe239bc53658bbb63c1c8c510a293c1e6891aa5bea5d3c58746" + CYCLONEDX_CLI_LINUX_ARM64_SHA256: "b2e9fdf9665ef49868a2ec012171c6e785dcd69745bc5869e53e4f4bfb096a5f" + SBOMQS_VERSION: "v2.1.4" SBOM_QUALITY_THRESHOLD: "8.3" jobs: @@ -115,6 +119,7 @@ jobs: python3 -B -m unittest tests.test_sbom_postprocess tests.test_sbom_quality + tests.test_verify_sbom_release tests.test_workspace_security tests.test_security_workflow -q @@ -134,22 +139,15 @@ jobs: with: rust-version: stable components: rustfmt - cache-key: cargo-security-sbom-${{ runner.os }}-${{ runner.arch }}-stable-${{ env.CARGO_CYCLONEDX_VERSION }}-${{ hashFiles('**/Cargo.lock') }} + cache-key: cargo-security-sbom-${{ runner.os }}-${{ runner.arch }}-stable-${{ env.CARGO_CYCLONEDX_VERSION }}-${{ env.CARGO_DENY_VERSION }}-${{ hashFiles('**/Cargo.lock') }} - name: Install pinned cargo-cyclonedx run: cargo install cargo-cyclonedx --version "${CARGO_CYCLONEDX_VERSION}" --locked - - name: Verify the locked all-feature workspace - run: cargo metadata --locked --all-features --format-version 1 > /dev/null - - name: Generate complete workspace CycloneDX JSON - run: >- - cargo cyclonedx --format json --all --all-features --target all - --spec-version 1.5 - - name: Collect and post-process every workspace SBOM + - name: Install pinned cargo-deny license gate + run: cargo install cargo-deny --version "${CARGO_DENY_VERSION}" --locked + - name: Install checksum-pinned CycloneDX schema validator run: | - python3 scripts/collect_workspace_sboms.py sbom-artifacts - python3 scripts/sbom_postprocess.py \ - --cargo-toml Cargo.toml \ - --declare-dependency-complete \ - sbom-artifacts/*.cdx.json + ./scripts/install-cyclonedx-cli.sh "${RUNNER_TEMP}/cyclonedx-cli" + echo "${RUNNER_TEMP}/cyclonedx-cli" >> "${GITHUB_PATH}" - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: go-version: stable @@ -157,12 +155,8 @@ jobs: run: | go install github.com/interlynk-io/sbomqs/v2@${SBOMQS_VERSION} echo "$(go env GOPATH)/bin" >> "$GITHUB_PATH" - - name: Enforce SBOM quality floor - run: | - sbomqs score --json sbom-artifacts/*.cdx.json > sbomqs-results.json - python3 scripts/check_sbom_quality.py \ - --threshold "$SBOM_QUALITY_THRESHOLD" \ - sbomqs-results.json + - name: Generate, enrich, validate, and score the complete SBOM set + run: ./scripts/generate-sboms.sh sbom-artifacts sbom-artifacts/sbomqs-results.json - name: Upload machine-readable SBOM evidence if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v4 @@ -170,7 +164,8 @@ jobs: name: sbom-quality-evidence path: | sbom-artifacts/*.cdx.json - sbomqs-results.json + sbom-artifacts/*.cdx.xml + sbom-artifacts/sbomqs-results.json if-no-files-found: error retention-days: 14 diff --git a/README.md b/README.md index ed9e50ae..692a1361 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,9 @@ > workflow with the target version, label the generated PR `release`, and merge > it. The tag workflow creates `v` from the merge commit, and the > publish workflow builds Debian, Arch Linux, OCI, user-documentation, and SBOM -> release artifacts. +> release artifacts. The SBOM archive contains schema-validated CycloneDX 1.6 +> JSON and XML plus the sbomqs quality report; see [Releasing](RELEASING.md) for +> its checksum and verification contract. REST gateway API for [Greenbone Vulnerability Management (GVM)](https://greenbone.github.io/docs/latest/), built on top of [rust-gvm](https://github.com/greenbone-hive/rust-gvm). REST is the implemented public gateway surface on `main`; MCP remains a planned peer adapter over the same shared core. diff --git a/RELEASING.md b/RELEASING.md index 4a8a4942..dc76c1f7 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -41,7 +41,35 @@ after a release. - `gvm-gateway` Arch Linux packages (`.pkg.tar.zst`) - `gvm-gateway` OCI image archives (`.oci.tar`) - matching `.sha256` checksum files -- SBOM archives +- `rust-gvm-api-sbom.tar.gz`, containing CycloneDX 1.6 JSON and XML for all + seven inventoried workspace packages plus `sbomqs-results.json` +- `rust-gvm-api-sbom.tar.gz.sha256` + +The release SBOM job runs the same `scripts/generate-sboms.sh` contract as +Security CI: cargo-cyclonedx 0.5.10 generation, a successful pinned cargo-deny +license check, conservative JSON enrichment, CycloneDX 1.6 schema validation, +and sbomqs 2.1.4 scoring with an inclusive 8.3 floor. The exact transformed +JSON files that are scored are the files placed in the archive. XML remains +generator-native but is schema-validated before packaging. + +Before upload, `scripts/verify_sbom_release.py` verifies the archive checksum, +the exact seven JSON/XML pairs from the committed workspace inventory, release +version metadata, and one at-or-above-floor score for every archived JSON file. +It also rejects unexpected members. For local verification of downloaded +release evidence, run: + +```bash +python3 -B scripts/verify_sbom_release.py \ + rust-gvm-api-sbom.tar.gz \ + rust-gvm-api-sbom.tar.gz.sha256 +``` + +The archive deliberately contains no synthesized CPEs, dependency-completeness +claims, embedded CycloneDX signatures, or external release attestations. The +`.sha256` file authenticates archive bytes only; it is not an embedded SBOM +signature. License conclusions are limited to sole, simple SPDX identifiers +allowed by `deny.toml`, and exact crates.io distribution references are limited +to unqualified Cargo PURLs. ## Retry and Recovery @@ -75,6 +103,11 @@ For local testing without releasing: ```bash cargo build --locked --release -p gvm-gateway cargo test +python3 -B -m unittest \ + tests.test_sbom_postprocess \ + tests.test_sbom_quality \ + tests.test_verify_sbom_release \ + tests.test_security_workflow -q ./scripts/build-binary-archive.sh --version "$(./scripts/workspace-version.sh)" --architecture amd64 ./scripts/binary-archive-smoke.sh \ --archive "dist/binaries/gvm-gateway_$(./scripts/workspace-version.sh)_linux_amd64.tar.gz" \ diff --git a/docs/WORKFLOW_SECURITY.md b/docs/WORKFLOW_SECURITY.md index 441db1f7..0e079ab5 100644 --- a/docs/WORKFLOW_SECURITY.md +++ b/docs/WORKFLOW_SECURITY.md @@ -51,20 +51,37 @@ For a dependency update: ## SBOM policy -Security installs the pinned `cargo-cyclonedx` release, verifies `Cargo.lock` -through `cargo metadata --locked --all-features`, and generates CycloneDX 1.5 -JSON for every member of `supply-chain/workspace-packages.toml`. -`collect_workspace_sboms.py` fails unless exactly one generated document exists -for every inventoried package. `sbom_postprocess.py` adds deterministic document -licensing, build-lifecycle, supplier, repository, and completeness metadata; -`check_sbom_quality.py` fails if the machine-readable `sbomqs` result is absent, -malformed, or below 8.3 for any file. The generated SBOMs and score report are -uploaded as workflow evidence. - -When updating `cargo-cyclonedx` or `sbomqs`, review release notes, update the -pinned version in Security (and the matching release-workflow pin for -`cargo-cyclonedx`), run the helper unit tests, generate the complete workspace -SBOM set, and confirm every score remains at least 8.3. +Security and tagged releases both call `scripts/generate-sboms.sh`; workflow +policy tests reject either lane reimplementing or bypassing that command +contract. The script verifies `Cargo.lock` through +`cargo metadata --locked --all-features`, then uses pinned `cargo-cyclonedx` +0.5.10 to generate CycloneDX 1.6 JSON and XML for every member of +`supply-chain/workspace-packages.toml`. `collect_workspace_sboms.py` fails unless +exactly one document of each format exists for every inventoried package. The +checksum-pinned CycloneDX CLI validates every post-processed JSON and +generator-native XML document against the 1.6 schemas. + +License conclusions are opt-in and occur only after pinned `cargo-deny` 0.20.2 +successfully checks `deny.toml` in the same script. A sole, simple Cargo SPDX +identifier in `[licenses].allow` becomes matching declared and concluded +license objects. Composite expressions, `LicenseRef` or custom values, +malformed or disallowed entries, non-Cargo components, and existing conclusions +remain untouched. Exact unqualified `pkg:cargo/name@version` PURLs receive a +URL-encoded crates.io distribution reference; qualified, fragmented, local, +and non-Cargo PURLs do not. + +The transform also adds deterministic document licensing, build lifecycle, +supplier, and repository metadata. It deliberately does not synthesize CPEs, +CycloneDX signatures, or completeness claims. XML remains generator-native. +Pinned `sbomqs` 2.1.4 scores the exact transformed JSON files, and +`check_sbom_quality.py` fails if its machine-readable report is absent, +malformed, incomplete, or below 8.3 for any file. Security uploads both formats +and the report as workflow evidence. + +When updating any SBOM tool, review its release notes and atomically update the +matching pins in Security and release publication. Run the helper and workflow +policy tests, generate all seven JSON/XML pairs, validate both formats, and +confirm every JSON score remains at least 8.3. ## First-party unsafe-code policy @@ -88,6 +105,7 @@ Run the deterministic helper suite with: python3 -B -m unittest \ tests.test_sbom_postprocess \ tests.test_sbom_quality \ + tests.test_verify_sbom_release \ tests.test_workspace_security \ tests.test_security_workflow -q cargo vet --locked diff --git a/docs/user/usage.md b/docs/user/usage.md index 1da47def..c233b336 100644 --- a/docs/user/usage.md +++ b/docs/user/usage.md @@ -3,8 +3,24 @@ ## Release artifacts Current releases publish Debian packages, Arch Linux packages, an OCI image -archive, and this user documentation package with the matching OpenAPI -specification. +archive, this user documentation package with the matching OpenAPI +specification, and `rust-gvm-api-sbom.tar.gz` with its `.sha256` checksum. The +SBOM archive contains CycloneDX 1.6 JSON and XML for all seven workspace +packages plus a machine-readable `sbomqs-results.json`; every JSON score is at +least 8.3 under sbomqs 2.1.4. + +Verify the checksum with `sha256sum --check rust-gvm-api-sbom.tar.gz.sha256`. +Maintainers and source users can additionally run this from a matching checkout: + +```bash +python3 -B scripts/verify_sbom_release.py \ + rust-gvm-api-sbom.tar.gz \ + rust-gvm-api-sbom.tar.gz.sha256 +``` + +The archive does not claim dependency completeness, synthesize CPEs, or contain +embedded CycloneDX signatures or external attestations; the separate checksum +is not an embedded signature. Choose the package or container form that matches your environment. diff --git a/scripts/collect_workspace_sboms.py b/scripts/collect_workspace_sboms.py index 3ca8a09c..d3443d1d 100644 --- a/scripts/collect_workspace_sboms.py +++ b/scripts/collect_workspace_sboms.py @@ -17,10 +17,13 @@ SUPPORTED_FORMATS = ("json", "xml") -def collect(destination: Path, formats: tuple[str, ...] = ("json",)) -> list[Path]: +def collect( + destination: Path, + formats: tuple[str, ...] = ("json",), + remove_sources: bool = False, +) -> list[Path]: destination = destination.resolve() - destination.mkdir(parents=True, exist_ok=True) - collected = [] + sources: list[Path] = [] for package in validated_inventory(): package_dir = (ROOT / package.manifest).parent for document_format in formats: @@ -30,9 +33,17 @@ def collect(destination: Path, formats: tuple[str, ...] = ("json",)) -> list[Pat f"expected one {document_format.upper()} SBOM for {package.name} " f"beside {package.manifest}" ) - target = destination / source.name + sources.append(source) + + destination.mkdir(parents=True, exist_ok=True) + collected = [] + for source in sources: + target = destination / source.name + if remove_sources: + shutil.move(source, target) + else: shutil.copyfile(source, target) - collected.append(target) + collected.append(target) return collected @@ -45,11 +56,16 @@ def main(argv: list[str]) -> int: dest="formats", help="document format to collect; repeat for multiple formats (default: json)", ) + parser.add_argument( + "--remove-sources", + action="store_true", + help="move generated package-adjacent documents into the destination", + ) parser.add_argument("destination", type=Path) args = parser.parse_args(argv) try: formats = tuple(dict.fromkeys(args.formats or ("json",))) - collected = collect(args.destination, formats) + collected = collect(args.destination, formats, args.remove_sources) except (OSError, ValueError) as error: print(f"error: {error}", file=sys.stderr) return 2 diff --git a/scripts/generate-sboms.sh b/scripts/generate-sboms.sh new file mode 100755 index 00000000..61ab6ac6 --- /dev/null +++ b/scripts/generate-sboms.sh @@ -0,0 +1,82 @@ +#!/usr/bin/env bash +# Generate, conservatively enrich, validate, and score the complete SBOM set. +set -euo pipefail +export PYTHONDONTWRITEBYTECODE=1 + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +OUTPUT_DIR="${1:-${ROOT_DIR}/sbom-artifacts}" +QUALITY_REPORT="${2:-${OUTPUT_DIR}/sbomqs-results.json}" +QUALITY_THRESHOLD="${SBOM_QUALITY_THRESHOLD:-8.3}" +CARGO_CYCLONEDX_VERSION="${CARGO_CYCLONEDX_VERSION:?CARGO_CYCLONEDX_VERSION must be set}" +CARGO_DENY_VERSION="${CARGO_DENY_VERSION:?CARGO_DENY_VERSION must be set}" +CYCLONEDX_CLI_VERSION="${CYCLONEDX_CLI_VERSION:?CYCLONEDX_CLI_VERSION must be set}" +SBOMQS_VERSION="${SBOMQS_VERSION:?SBOMQS_VERSION must be set}" + +if [[ -e "${OUTPUT_DIR}" ]]; then + echo "SBOM output path already exists: ${OUTPUT_DIR}" >&2 + exit 2 +fi + +for tool in cargo cargo-cyclonedx cargo-deny cyclonedx sbomqs; do + if ! command -v "${tool}" >/dev/null 2>&1; then + echo "Required SBOM tool is not installed: ${tool}" >&2 + exit 2 + fi +done + +if [[ "$(cargo cyclonedx --version)" != *" ${CARGO_CYCLONEDX_VERSION}" ]]; then + echo "cargo-cyclonedx does not match pinned version ${CARGO_CYCLONEDX_VERSION}" >&2 + exit 2 +fi +if [[ "$(cargo deny --version)" != "cargo-deny ${CARGO_DENY_VERSION}" ]]; then + echo "cargo-deny does not match pinned version ${CARGO_DENY_VERSION}" >&2 + exit 2 +fi +if [[ "$(cyclonedx --version)" != "${CYCLONEDX_CLI_VERSION}"+* ]]; then + echo "CycloneDX CLI does not match pinned version ${CYCLONEDX_CLI_VERSION}" >&2 + exit 2 +fi +if ! sbomqs version | grep -Fq "GitVersion: ${SBOMQS_VERSION}"; then + echo "sbomqs does not match pinned version ${SBOMQS_VERSION}" >&2 + exit 2 +fi + +cd "${ROOT_DIR}" +cargo metadata --locked --all-features --format-version 1 >/dev/null +cargo cyclonedx --format json --all --all-features --target all --spec-version 1.6 +cargo cyclonedx --format xml --all --all-features --target all --spec-version 1.6 + +python3 scripts/collect_workspace_sboms.py \ + --format json \ + --format xml \ + --remove-sources \ + "${OUTPUT_DIR}" + +# License conclusions are enabled only after this pinned tool has successfully +# enforced the same deny.toml allowlist consumed by the postprocessor. +cargo deny --config deny.toml --locked check licenses +python3 scripts/sbom_postprocess.py \ + --cargo-toml Cargo.toml \ + --conclude-allowed-cargo-licenses \ + --deny-policy deny.toml \ + "${OUTPUT_DIR}"/*.cdx.json + +for sbom in "${OUTPUT_DIR}"/*.cdx.json; do + cyclonedx validate \ + --input-file "${sbom}" \ + --input-format json \ + --input-version v1_6 \ + --fail-on-errors +done +for sbom in "${OUTPUT_DIR}"/*.cdx.xml; do + cyclonedx validate \ + --input-file "${sbom}" \ + --input-format xml \ + --input-version v1_6 \ + --fail-on-errors +done + +sbomqs score --json "${OUTPUT_DIR}"/*.cdx.json > "${QUALITY_REPORT}" +python3 scripts/check_sbom_quality.py \ + --threshold "${QUALITY_THRESHOLD}" \ + "${QUALITY_REPORT}" diff --git a/scripts/install-cyclonedx-cli.sh b/scripts/install-cyclonedx-cli.sh new file mode 100755 index 00000000..f0b0d8e3 --- /dev/null +++ b/scripts/install-cyclonedx-cli.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Install a checksum-verified CycloneDX CLI release for schema validation. +set -euo pipefail + +VERSION="${CYCLONEDX_CLI_VERSION:?CYCLONEDX_CLI_VERSION must be set}" +DESTINATION="${1:?usage: install-cyclonedx-cli.sh DESTINATION_DIRECTORY}" + +case "$(uname -m)" in + x86_64) + ASSET="cyclonedx-linux-x64" + EXPECTED_SHA256="${CYCLONEDX_CLI_LINUX_X64_SHA256:?CYCLONEDX_CLI_LINUX_X64_SHA256 must be set}" + ;; + aarch64|arm64) + ASSET="cyclonedx-linux-arm64" + EXPECTED_SHA256="${CYCLONEDX_CLI_LINUX_ARM64_SHA256:?CYCLONEDX_CLI_LINUX_ARM64_SHA256 must be set}" + ;; + *) + echo "Unsupported CycloneDX CLI architecture: $(uname -m)" >&2 + exit 2 + ;; +esac + +mkdir -p "${DESTINATION}" +TARGET="${DESTINATION}/cyclonedx" +curl --fail --location --proto '=https' --tlsv1.2 \ + --output "${TARGET}" \ + "https://github.com/CycloneDX/cyclonedx-cli/releases/download/v${VERSION}/${ASSET}" +printf '%s %s\n' "${EXPECTED_SHA256}" "${TARGET}" | sha256sum --check --strict +chmod 0755 "${TARGET}" diff --git a/scripts/sbom_postprocess.py b/scripts/sbom_postprocess.py index c3df93f2..8872fed5 100644 --- a/scripts/sbom_postprocess.py +++ b/scripts/sbom_postprocess.py @@ -10,16 +10,26 @@ import sys import tomllib from pathlib import Path -from typing import Any +from typing import AbstractSet, Any +from urllib.parse import quote, unquote CC0_LICENSE = {"license": {"id": "CC0-1.0"}} BUILD_LIFECYCLE = {"phase": "build"} SUPPLIER_FALLBACK = "greenbone-hive" +REGISTRY_SUPPLIER = "crates.io" +CRATES_IO_DOWNLOAD_BASE = "https://crates.io/api/v1/crates" +CARGO_PURL = re.compile(r"^pkg:cargo/[^@/?#]+@[^/?#]+(?:\?[^#]+)?(?:#.+)?$") +EXACT_CARGO_PURL = re.compile( + r"^pkg:cargo/(?P[^@/?#]+)@(?P[^/?#]+)$" +) +SIMPLE_SPDX_IDENTIFIER = re.compile(r"^[A-Za-z0-9][A-Za-z0-9.-]*\+?$") def workspace_metadata(cargo_toml: Path) -> tuple[str, str, list[Any]]: - workspace = tomllib.loads(cargo_toml.read_text(encoding="utf-8")).get("workspace", {}) + workspace = tomllib.loads(cargo_toml.read_text(encoding="utf-8")).get( + "workspace", {} + ) package = workspace.get("package", {}) if isinstance(workspace, dict) else {} repository = str(package.get("repository", "")) match = re.search(r"github\.com/([^/]+)/", repository) @@ -33,8 +43,26 @@ def normalize_spec_version(value: Any) -> str: try: major, minor = [int(part) for part in str(value).split(".")[:2]] except (TypeError, ValueError): - return "1.5" - return "1.5" if (major, minor) < (1, 5) else f"{major}.{minor}" + return "1.6" + return "1.6" if (major, minor) < (1, 6) else f"{major}.{minor}" + + +def load_allowed_spdx_identifiers(deny_policy: Path) -> frozenset[str]: + try: + policy = tomllib.loads(deny_policy.read_text(encoding="utf-8")) + except (OSError, tomllib.TOMLDecodeError) as error: + raise ValueError(f"cannot load deny policy {deny_policy}: {error}") from error + licenses = policy.get("licenses") + allowed = licenses.get("allow") if isinstance(licenses, dict) else None + if ( + not isinstance(allowed, list) + or not allowed + or any(not isinstance(identifier, str) or not identifier for identifier in allowed) + ): + raise ValueError( + f"deny policy {deny_policy} must define a non-empty [licenses].allow list" + ) + return frozenset(allowed) def ensure_list_entry(container: dict[str, Any], key: str, value: dict[str, Any]) -> None: @@ -72,7 +100,7 @@ def is_first_party(component: dict[str, Any], repository: str) -> bool: if bom_ref.startswith("path+file://") or "download_url=file://" in purl: return True references = component.get("externalReferences", []) - return any( + return isinstance(references, list) and any( isinstance(item, dict) and item.get("type") == "vcs" and item.get("url") == repository @@ -80,66 +108,90 @@ def is_first_party(component: dict[str, Any], repository: str) -> bool: ) -def enrich_component( - component: dict[str, Any], supplier: str, repository: str, licenses: list[Any] -) -> None: - first_party = is_first_party(component, repository) - if not component.get("supplier"): - purl = str(component.get("purl", "")) - if first_party: - component["supplier"] = {"name": supplier} - elif purl.startswith("pkg:cargo/"): - component["supplier"] = {"name": "crates.io"} - if not first_party: +def cargo_download_url(purl: Any) -> str | None: + if not isinstance(purl, str): + return None + match = EXACT_CARGO_PURL.fullmatch(purl) + if match is None: + return None + name = quote(unquote(match.group("name")), safe="") + version = quote(unquote(match.group("version")), safe="") + return f"{CRATES_IO_DOWNLOAD_BASE}/{name}/{version}/download" + + +def ensure_cargo_distribution_reference(component: dict[str, Any]) -> None: + url = cargo_download_url(component.get("purl")) + if url is None: return - if licenses and not component.get("licenses"): - component["licenses"] = copy.deepcopy(licenses) references = component.get("externalReferences") - if not isinstance(references, list): + if references is None: references = [] component["externalReferences"] = references - vcs = {"type": "vcs", "url": repository} - if repository and vcs not in references: - references.append(vcs) + elif not isinstance(references, list): + return + reference = {"type": "distribution", "url": url} + if reference not in references: + references.append(reference) -def declare_complete(document: dict[str, Any]) -> None: - dependencies = document.get("dependencies") - if not isinstance(dependencies, list): +def conclude_allowed_cargo_license( + component: dict[str, Any], allowed_spdx_identifiers: AbstractSet[str] +) -> None: + purl = component.get("purl") + if not isinstance(purl, str) or CARGO_PURL.fullmatch(purl) is None: return - refs = list( - dict.fromkeys( - str(item.get("ref")) - for item in dependencies - if isinstance(item, dict) - and item.get("ref") - and isinstance(item.get("dependsOn"), list) - ) - ) - if not refs: + licenses = component.get("licenses") + if not isinstance(licenses, list) or len(licenses) != 1: return - compositions = document.setdefault("compositions", []) - if not isinstance(compositions, list): - raise ValueError("SBOM compositions must be a JSON array") - complete = next( - ( - item - for item in compositions - if isinstance(item, dict) and item.get("aggregate") == "complete" - ), - None, - ) - if complete is None: - compositions.append({"aggregate": "complete", "dependencies": refs}) - else: - existing = complete.get("dependencies", []) - complete["dependencies"] = list( - dict.fromkeys([item for item in existing if isinstance(item, str)] + refs) - ) + entry = licenses[0] + if not isinstance(entry, dict) or set(entry) != {"expression"}: + return + identifier = entry.get("expression") + if ( + not isinstance(identifier, str) + or identifier not in allowed_spdx_identifiers + or SIMPLE_SPDX_IDENTIFIER.fullmatch(identifier) is None + or identifier.startswith(("LicenseRef-", "DocumentRef-")) + ): + return + component["licenses"] = [ + {"license": {"id": identifier, "acknowledgement": "declared"}}, + {"license": {"id": identifier, "acknowledgement": "concluded"}}, + ] + + +def enrich_component( + component: dict[str, Any], + supplier: str, + repository: str, + workspace_licenses: list[Any], + allowed_spdx_identifiers: AbstractSet[str] | None, +) -> None: + first_party = is_first_party(component, repository) + if not component.get("supplier"): + if first_party: + component["supplier"] = {"name": supplier} + elif str(component.get("purl", "")).startswith("pkg:cargo/"): + component["supplier"] = {"name": REGISTRY_SUPPLIER} + if first_party: + if workspace_licenses and not component.get("licenses"): + component["licenses"] = copy.deepcopy(workspace_licenses) + references = component.get("externalReferences") + if not isinstance(references, list): + references = [] + component["externalReferences"] = references + vcs = {"type": "vcs", "url": repository} + if repository and vcs not in references: + references.append(vcs) + ensure_cargo_distribution_reference(component) + if allowed_spdx_identifiers is not None: + conclude_allowed_cargo_license(component, allowed_spdx_identifiers) def transform( - document: dict[str, Any], cargo_toml: Path, dependency_complete: bool + document: dict[str, Any], + cargo_toml: Path, + allowed_spdx_identifiers: AbstractSet[str] | None = None, ) -> dict[str, Any]: supplier, repository, licenses = workspace_metadata(cargo_toml) document["specVersion"] = normalize_spec_version(document.get("specVersion")) @@ -153,23 +205,51 @@ def transform( if not metadata.get("supplier"): metadata["supplier"] = {"name": supplier} for component in iter_components(document): - enrich_component(component, supplier, repository, licenses) - if dependency_complete: - declare_complete(document) + enrich_component( + component, + supplier, + repository, + licenses, + allowed_spdx_identifiers, + ) return document -def main(argv: list[str]) -> int: +def parse_args(argv: list[str]) -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("sbom", nargs="+", type=Path) parser.add_argument("--cargo-toml", type=Path, default=Path("Cargo.toml")) - parser.add_argument("--declare-dependency-complete", action="store_true") + parser.add_argument( + "--conclude-allowed-cargo-licenses", + action="store_true", + help=( + "represent a sole allowed Cargo SPDX identifier as matching declared " + "and concluded license objects" + ), + ) + parser.add_argument( + "--deny-policy", + type=Path, + help="deny.toml whose [licenses].allow list gates license conclusions", + ) args = parser.parse_args(argv) + if args.conclude_allowed_cargo_licenses and args.deny_policy is None: + parser.error("--conclude-allowed-cargo-licenses requires --deny-policy") + return args + + +def main(argv: list[str]) -> int: + args = parse_args(argv) + allowed = ( + load_allowed_spdx_identifiers(args.deny_policy) + if args.conclude_allowed_cargo_licenses + else None + ) for path in args.sbom: document = json.loads(path.read_text(encoding="utf-8")) if not isinstance(document, dict): raise ValueError(f"SBOM must be a JSON object: {path}") - transformed = transform(document, args.cargo_toml, args.declare_dependency_complete) + transformed = transform(document, args.cargo_toml, allowed) path.write_text(json.dumps(transformed, indent=2) + "\n", encoding="utf-8") return 0 diff --git a/scripts/verify_sbom_release.py b/scripts/verify_sbom_release.py new file mode 100755 index 00000000..e16b3e69 --- /dev/null +++ b/scripts/verify_sbom_release.py @@ -0,0 +1,201 @@ +#!/usr/bin/env python3 +"""Verify the release SBOM archive, checksum, inventory, formats, and score floor.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import re +import sys +import tarfile +import tomllib +import xml.etree.ElementTree as ET +from pathlib import Path +from typing import Any + +try: + from scripts.check_sbom_quality import check_report, entry_path + from scripts.workspace_inventory import load_inventory +except ModuleNotFoundError: # Direct execution adds scripts/ to sys.path. + from check_sbom_quality import check_report, entry_path + from workspace_inventory import load_inventory + + +CYCLONEDX_XML_NAMESPACE = "http://cyclonedx.org/schema/bom/1.6" +QUALITY_REPORT_NAME = "sbomqs-results.json" +SHA256_LINE = re.compile(r"^(?P[0-9a-f]{64}) [ *](?P[^/]+)$") + + +class VerificationError(ValueError): + """Release SBOM evidence violates the publication contract.""" + + +def expected_members(package_names: list[str]) -> set[str]: + documents = { + f"{name}.cdx.{document_format}" + for name in package_names + for document_format in ("json", "xml") + } + return documents | {QUALITY_REPORT_NAME} + + +def verify_checksum(archive: Path, checksum: Path) -> None: + lines = checksum.read_text(encoding="utf-8").splitlines() + match = SHA256_LINE.fullmatch(lines[0]) if len(lines) == 1 else None + if match is None or match.group("name") != archive.name: + raise VerificationError("checksum must contain one SHA-256 entry for the archive") + actual = hashlib.sha256(archive.read_bytes()).hexdigest() + if actual != match.group("digest"): + raise VerificationError("SBOM archive checksum does not match") + + +def read_regular_members(archive: Path) -> dict[str, bytes]: + with tarfile.open(archive, "r:gz") as bundle: + members = bundle.getmembers() + if any(not member.isfile() or Path(member.name).name != member.name for member in members): + raise VerificationError("SBOM archive must contain only flat regular files") + if len({member.name for member in members}) != len(members): + raise VerificationError("SBOM archive contains duplicate member names") + result = {} + for member in members: + stream = bundle.extractfile(member) + if stream is None: + raise VerificationError(f"cannot read archive member: {member.name}") + result[member.name] = stream.read() + return result + + +def verify_json_sbom(name: str, payload: bytes, version: str) -> None: + try: + document = json.loads(payload) + except (UnicodeDecodeError, json.JSONDecodeError) as error: + raise VerificationError(f"{name} is not valid JSON: {error}") from error + if not isinstance(document, dict): + raise VerificationError(f"{name} must contain a JSON object") + if document.get("bomFormat") != "CycloneDX" or document.get("specVersion") != "1.6": + raise VerificationError(f"{name} is not CycloneDX 1.6 JSON") + metadata = document.get("metadata") + component = metadata.get("component") if isinstance(metadata, dict) else None + if not isinstance(component, dict) or component.get("version") != version: + raise VerificationError(f"{name} does not identify release version {version}") + if "signature" in document: + raise VerificationError(f"{name} must not contain an embedded signature") + compositions = document.get("compositions", []) + if isinstance(compositions, list) and any( + isinstance(composition, dict) and composition.get("aggregate") == "complete" + for composition in compositions + ): + raise VerificationError(f"{name} must not claim complete composition coverage") + + +def verify_xml_sbom(name: str, payload: bytes, version: str) -> None: + if b" None: + try: + report = json.loads(payload) + except (UnicodeDecodeError, json.JSONDecodeError) as error: + raise VerificationError(f"quality report is invalid JSON: {error}") from error + if not isinstance(report, dict): + raise VerificationError("quality report must be a JSON object") + try: + failures = check_report(report, threshold) + except ValueError as error: + raise VerificationError(f"quality report is malformed: {error}") from error + if failures: + raise VerificationError(f"quality report contains scores below {threshold:.1f}") + entries = report.get("files", []) + scored = [Path(entry_path(entry)).name for entry in entries if isinstance(entry, dict)] + if len(scored) != len(set(scored)) or set(scored) != expected_json: + raise VerificationError("quality report must score every archived JSON SBOM exactly once") + + +def verify_archive( + archive: Path, + checksum: Path, + package_names: list[str], + version: str, + threshold: float, +) -> None: + if not math.isfinite(threshold) or not 0.0 <= threshold <= 10.0: + raise VerificationError("quality threshold must be between 0 and 10") + verify_checksum(archive, checksum) + members = read_regular_members(archive) + expected = expected_members(package_names) + if set(members) != expected: + missing = sorted(expected - set(members)) + unexpected = sorted(set(members) - expected) + raise VerificationError( + f"SBOM archive inventory mismatch; missing={missing}; unexpected={unexpected}" + ) + for name, payload in members.items(): + if name.endswith(".cdx.json"): + verify_json_sbom(name, payload, version) + elif name.endswith(".cdx.xml"): + verify_xml_sbom(name, payload, version) + verify_quality_report( + members[QUALITY_REPORT_NAME], + {name for name in expected if name.endswith(".cdx.json")}, + threshold, + ) + + +def workspace_version(cargo_toml: Path) -> str: + document: dict[str, Any] = tomllib.loads(cargo_toml.read_text(encoding="utf-8")) + return str(document["workspace"]["package"]["version"]) + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("archive", type=Path) + parser.add_argument("checksum", type=Path) + parser.add_argument("--threshold", type=float, default=8.3) + parser.add_argument("--cargo-toml", type=Path, default=Path("Cargo.toml")) + parser.add_argument( + "--inventory", + type=Path, + default=Path("supply-chain/workspace-packages.toml"), + ) + args = parser.parse_args(argv) + try: + packages = load_inventory(args.inventory) + verify_archive( + args.archive, + args.checksum, + [package.name for package in packages], + workspace_version(args.cargo_toml), + args.threshold, + ) + except (OSError, KeyError, tomllib.TOMLDecodeError, VerificationError) as error: + print(f"error: {error}", file=sys.stderr) + return 2 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/tests/fixtures/sbom/minimal.cdx.json b/tests/fixtures/sbom/minimal.cdx.json index a86f7aaf..9ae31170 100644 --- a/tests/fixtures/sbom/minimal.cdx.json +++ b/tests/fixtures/sbom/minimal.cdx.json @@ -1,6 +1,6 @@ { "bomFormat": "CycloneDX", - "specVersion": "1.3", + "specVersion": "1.6", "version": 1, "metadata": { "component": { diff --git a/tests/test_collect_workspace_sboms.py b/tests/test_collect_workspace_sboms.py index a0f4fded..7c337cc4 100644 --- a/tests/test_collect_workspace_sboms.py +++ b/tests/test_collect_workspace_sboms.py @@ -62,7 +62,36 @@ def test_missing_inventory_document_fails_closed(self) -> None: ), self.assertRaisesRegex(ValueError, "expected one XML SBOM"), ): - collect(self.root / "collected", ("json", "xml")) + collect( + self.root / "collected", + ("json", "xml"), + remove_sources=True, + ) + + self.assertTrue((self.package_dir / "gateway.cdx.json").is_file()) + self.assertFalse((self.root / "collected").exists()) + + def test_shared_contract_can_move_generated_documents_out_of_source_tree(self) -> None: + # Real generation writes beside Cargo.toml; moving the complete pair + # prevents local policy runs from leaving untracked release evidence. + for document_format in ("json", "xml"): + (self.package_dir / f"gateway.cdx.{document_format}").write_text( + document_format, + encoding="utf-8", + ) + with ( + patch("scripts.collect_workspace_sboms.ROOT", self.root), + patch( + "scripts.collect_workspace_sboms.validated_inventory", + return_value=(self.package,), + ), + ): + collect(self.root / "collected", ("json", "xml"), remove_sources=True) + + self.assertFalse((self.package_dir / "gateway.cdx.json").exists()) + self.assertFalse((self.package_dir / "gateway.cdx.xml").exists()) + self.assertTrue((self.root / "collected" / "gateway.cdx.json").is_file()) + self.assertTrue((self.root / "collected" / "gateway.cdx.xml").is_file()) if __name__ == "__main__": diff --git a/tests/test_sbom_postprocess.py b/tests/test_sbom_postprocess.py index eca8636d..8d5df570 100644 --- a/tests/test_sbom_postprocess.py +++ b/tests/test_sbom_postprocess.py @@ -1,14 +1,19 @@ -"""Contract tests for deterministic CycloneDX metadata enrichment.""" +"""Contract tests for conservative, deterministic CycloneDX enrichment.""" import json import tempfile import unittest +from contextlib import redirect_stderr +from io import StringIO from pathlib import Path from scripts.sbom_postprocess import ( - CC0_LICENSE, BUILD_LIFECYCLE, - declare_complete, + CC0_LICENSE, + cargo_download_url, + conclude_allowed_cargo_license, + ensure_cargo_distribution_reference, + load_allowed_spdx_identifiers, main, normalize_spec_version, transform, @@ -20,12 +25,14 @@ class SbomPostprocessTests(unittest.TestCase): - def test_enrichment_adds_quality_metadata_without_hiding_dependencies(self) -> None: + def test_enrichment_adds_evidence_backed_metadata_without_completeness_claim(self) -> None: + # The quality transform may improve known metadata, but it must not claim + # that cargo-cyclonedx discovered every possible dependency or component. document = json.loads(FIXTURE.read_text(encoding="utf-8")) - transformed = transform(document, ROOT / "Cargo.toml", True) + transformed = transform(document, ROOT / "Cargo.toml") metadata = transformed["metadata"] - self.assertEqual(transformed["specVersion"], "1.5") + self.assertEqual(transformed["specVersion"], "1.6") self.assertIn(CC0_LICENSE, metadata["licenses"]) self.assertIn(BUILD_LIFECYCLE, metadata["lifecycles"]) self.assertEqual(metadata["supplier"], {"name": "greenbone-hive"}) @@ -34,20 +41,153 @@ def test_enrichment_adds_quality_metadata_without_hiding_dependencies(self) -> N [{"type": "vcs", "url": "https://github.com/greenbone-hive/rust-gvm-api"}], ) self.assertEqual(transformed["components"][0]["supplier"], {"name": "crates.io"}) - self.assertEqual(transformed["compositions"][0]["aggregate"], "complete") + self.assertNotIn("compositions", transformed) - def test_invalid_versions_and_compositions_fail_or_normalize(self) -> None: - self.assertEqual(normalize_spec_version(None), "1.5") + def test_old_or_invalid_spec_versions_are_normalized_to_cyclonedx_1_6(self) -> None: + # Post-processing must never regress a generated document below the + # schema version required by both Security and release workflows. + self.assertEqual(normalize_spec_version(None), "1.6") + self.assertEqual(normalize_spec_version("1.5"), "1.6") self.assertEqual(normalize_spec_version("1.6"), "1.6") - with self.assertRaisesRegex(ValueError, "compositions"): - declare_complete( + + def test_license_conclusions_require_an_explicit_deny_allowlist(self) -> None: + # A caller cannot accidentally conclude licenses without naming the + # exact policy that the preceding cargo-deny check enforced. + with redirect_stderr(StringIO()), self.assertRaises(SystemExit): + main(["--conclude-allowed-cargo-licenses", str(FIXTURE)]) + + def test_deny_policy_allowlist_loading_fails_closed(self) -> None: + # Missing or malformed allowlists must block conclusions instead of + # silently turning arbitrary Cargo metadata into asserted conclusions. + directory = tempfile.TemporaryDirectory(prefix="sbom-deny-policy-") + self.addCleanup(directory.cleanup) + policy = Path(directory.name) / "deny.toml" + policy.write_text('[licenses]\nallow = ["MIT", "Apache-2.0"]\n', encoding="utf-8") + self.assertEqual( + load_allowed_spdx_identifiers(policy), + frozenset({"MIT", "Apache-2.0"}), + ) + + policy.write_text('[licenses]\nallow = "MIT"\n', encoding="utf-8") + with self.assertRaisesRegex(ValueError, r"\[licenses\]\.allow"): + load_allowed_spdx_identifiers(policy) + with self.assertRaisesRegex(ValueError, "cannot load deny policy"): + load_allowed_spdx_identifiers(Path(directory.name) / "missing.toml") + + def test_sole_simple_allowed_cargo_license_gets_matching_conclusion(self) -> None: + # This is the only license shape for which cargo-deny and deny.toml give + # enough evidence to emit identical declared and concluded identifiers. + component = { + "purl": "pkg:cargo/example@1.0.0?download_url=file://.", + "licenses": [{"expression": "MIT"}], + } + conclude_allowed_cargo_license(component, {"MIT", "Apache-2.0"}) + self.assertEqual( + component["licenses"], + [ + {"license": {"id": "MIT", "acknowledgement": "declared"}}, + {"license": {"id": "MIT", "acknowledgement": "concluded"}}, + ], + ) + + def test_ambiguous_custom_disallowed_and_non_cargo_licenses_are_preserved(self) -> None: + # Expressions, LicenseRefs, malformed entries, non-Cargo components, + # disallowed identifiers, and existing conclusions are not simplified. + components = [ + { + "purl": "pkg:cargo/composite@1.0.0", + "licenses": [{"expression": "MIT OR Apache-2.0"}], + }, + { + "purl": "pkg:cargo/exception@1.0.0", + "licenses": [{"expression": "GPL-2.0-only WITH Classpath-exception-2.0"}], + }, + { + "purl": "pkg:cargo/custom@1.0.0", + "licenses": [{"expression": "LicenseRef-Proprietary"}], + }, + { + "purl": "pkg:generic/non-cargo@1.0.0", + "licenses": [{"expression": "MIT"}], + }, + { + "purl": "pkg:cargo/disallowed@1.0.0", + "licenses": [{"expression": "BSD-3-Clause"}], + }, + { + "purl": "pkg:cargo/malformed@1.0.0", + "licenses": [{"expression": "MIT", "unexpected": True}], + }, + { + "purl": "pkg:cargo/existing@1.0.0", + "licenses": [ + {"license": {"id": "MIT", "acknowledgement": "declared"}}, + {"license": {"id": "MIT", "acknowledgement": "concluded"}}, + ], + }, + ] + original = json.loads(json.dumps(components)) + misleading_allowlist = { + "MIT", + "MIT OR Apache-2.0", + "GPL-2.0-only WITH Classpath-exception-2.0", + "LicenseRef-Proprietary", + } + for component in components: + conclude_allowed_cargo_license(component, misleading_allowlist) + self.assertEqual(components, original) + + def test_license_conversion_is_idempotent(self) -> None: + # Re-running the shared contract must not duplicate or rewrite the two + # acknowledgement-bearing license objects produced on the first run. + component = { + "purl": "pkg:cargo/example@1.0.0", + "licenses": [{"expression": "MIT"}], + } + conclude_allowed_cargo_license(component, {"MIT"}) + after_first = json.loads(json.dumps(component)) + conclude_allowed_cargo_license(component, {"MIT"}) + self.assertEqual(component, after_first) + + def test_distribution_reference_requires_exact_unqualified_cargo_purl(self) -> None: + # Only a registry-shaped Cargo identity maps exactly to crates.io; + # qualifiers and fragments can describe local or alternate sources. + exact = { + "purl": "pkg:cargo/example%20crate@1.0.0%2Bbuild", + "externalReferences": [], + } + ensure_cargo_distribution_reference(exact) + ensure_cargo_distribution_reference(exact) + self.assertEqual( + exact["externalReferences"], + [ { - "dependencies": [{"ref": "a", "dependsOn": []}], - "compositions": {}, + "type": "distribution", + "url": ( + "https://crates.io/api/v1/crates/" + "example%20crate/1.0.0%2Bbuild/download" + ), } - ) + ], + ) + + ineligible = [ + "pkg:cargo/local@1.0.0?download_url=file://.", + "pkg:cargo/qualified@1.0.0?repository_url=https://example.test", + "pkg:cargo/fragmented@1.0.0#target", + "pkg:npm/example@1.0.0", + "not-a-purl", + ] + for purl in ineligible: + with self.subTest(purl=purl): + component = {"purl": purl} + ensure_cargo_distribution_reference(component) + self.assertNotIn("externalReferences", component) + self.assertIsNone(cargo_download_url(purl)) - def test_cli_rewrites_the_document(self) -> None: + def test_cli_rewrites_with_allowlist_gated_conclusions(self) -> None: + # The workflow-facing CLI must apply the same policy to files in place + # after cargo-deny has successfully checked the named deny.toml. directory = tempfile.TemporaryDirectory(prefix="sbom-postprocess-") self.addCleanup(directory.cleanup) path = Path(directory.name) / "input.cdx.json" @@ -56,12 +196,22 @@ def test_cli_rewrites_the_document(self) -> None: [ "--cargo-toml", str(ROOT / "Cargo.toml"), - "--declare-dependency-complete", + "--conclude-allowed-cargo-licenses", + "--deny-policy", + str(ROOT / "deny.toml"), str(path), ] ) + transformed = json.loads(path.read_text(encoding="utf-8")) self.assertEqual(result, 0) - self.assertEqual(json.loads(path.read_text())["specVersion"], "1.5") + self.assertEqual(transformed["specVersion"], "1.6") + self.assertEqual( + transformed["metadata"]["component"]["licenses"][1]["license"][ + "acknowledgement" + ], + "concluded", + ) + self.assertNotIn("compositions", transformed) if __name__ == "__main__": diff --git a/tests/test_security_workflow.py b/tests/test_security_workflow.py index 22dc855b..5ef77c07 100644 --- a/tests/test_security_workflow.py +++ b/tests/test_security_workflow.py @@ -10,6 +10,7 @@ WORKFLOW_DIR = ROOT / ".github" / "workflows" WORKFLOW = ROOT / ".github" / "workflows" / "security.yml" RELEASE_WORKFLOW = ROOT / ".github" / "workflows" / "release-publish.yml" +SBOM_CONTRACT = ROOT / "scripts" / "generate-sboms.sh" SETUP_RUST_ACTION = ( "greenbone/actions/setup-rust@d6d4c9500cb4e83f8a516ec1d40b04bcc720bd22" ) @@ -115,9 +116,11 @@ def test_external_actions_and_cargo_tools_are_pinned(self) -> None: 'cargo install cargo-machete --version "${CARGO_MACHETE_VERSION}" --locked', 'cargo install cargo-vet --version "${CARGO_VET_VERSION}" --locked', 'cargo install cargo-cyclonedx --version "${CARGO_CYCLONEDX_VERSION}" --locked', + 'cargo install cargo-deny --version "${CARGO_DENY_VERSION}" --locked', 'cargo install cargo-geiger --version "${CARGO_GEIGER_VERSION}" --locked', 'cargo install cargo-geiger --version "${CARGO_GEIGER_VERSION}" --locked', 'cargo install cargo-cyclonedx --version "${CARGO_CYCLONEDX_VERSION}" --locked', + 'cargo install cargo-deny --version "${CARGO_DENY_VERSION}" --locked', ) installs = re.findall(r"(?m)^\s+run: (cargo install .+)$", all_workflows) self.assertCountEqual(installs, expected_installs) @@ -131,11 +134,14 @@ def test_external_actions_and_cargo_tools_are_pinned(self) -> None: workflow = source() for value in ( 'CARGO_AUDIT_VERSION: "0.22.2"', - 'CARGO_CYCLONEDX_VERSION: "0.5.9"', + 'CARGO_CYCLONEDX_VERSION: "0.5.10"', + 'CARGO_DENY_VERSION: "0.20.2"', 'CARGO_GEIGER_VERSION: "0.13.0"', 'CARGO_MACHETE_VERSION: "0.9.2"', 'CARGO_VET_VERSION: "0.10.2"', - 'SBOMQS_VERSION: "v2.0.5"', + 'CYCLONEDX_CLI_VERSION: "0.33.1"', + 'SBOMQS_VERSION: "v2.1.4"', + 'SBOM_QUALITY_THRESHOLD: "8.3"', "semgrep/semgrep:1.176.1@sha256:", ): self.assertIn(value, workflow) @@ -146,23 +152,95 @@ def test_external_actions_and_cargo_tools_are_pinned(self) -> None: self.assertIn("RUSTUP_TOOLCHAIN: ${{ matrix.rust }}", ci) self.assertIn('RUSTUP_TOOLCHAIN: "1.89.0"', ci) release = RELEASE_WORKFLOW.read_text(encoding="utf-8") - self.assertIn('CARGO_CYCLONEDX_VERSION: "0.5.9"', release) + self.assertIn('CARGO_CYCLONEDX_VERSION: "0.5.10"', release) + self.assertIn('CARGO_DENY_VERSION: "0.20.2"', release) + self.assertIn('CYCLONEDX_CLI_VERSION: "0.33.1"', release) + self.assertIn('SBOMQS_VERSION: "v2.1.4"', release) + self.assertIn('SBOM_QUALITY_THRESHOLD: "8.3"', release) self.assertIn( 'cargo install cargo-cyclonedx --version "${CARGO_CYCLONEDX_VERSION}" --locked', release, ) - def test_release_sbom_collection_is_scoped_to_workspace_inventory(self) -> None: - # Release evidence must be selected from the committed package inventory; - # repository-wide discovery can accidentally publish test fixtures. + def test_security_and_release_execute_the_same_sbom_contract(self) -> None: + # Keeping the complete command sequence in one script prevents a tagged + # release from silently bypassing Security's enrichment or score floor. + security = source() release = RELEASE_WORKFLOW.read_text(encoding="utf-8") - self.assertIn( - "python3 scripts/collect_workspace_sboms.py \\", - release, + command = ( + "./scripts/generate-sboms.sh sbom-artifacts " + "sbom-artifacts/sbomqs-results.json" + ) + self.assertEqual(security.count(command), 1) + self.assertEqual(release.count(command), 1) + for workflow in (security, release): + workflow_name = "security" if workflow == security else "release" + with self.subTest(workflow=workflow_name): + self.assertNotIn("cargo cyclonedx --format", workflow) + self.assertNotIn("scripts/sbom_postprocess.py", workflow) + self.assertNotIn("sbomqs score", workflow) + + def test_shared_sbom_contract_is_fail_closed_and_inventory_scoped(self) -> None: + # Generation must use locked all-feature inputs, both 1.6 formats, the + # committed inventory, deny-gated conclusions, schema checks, and 8.3 scoring. + contract = SBOM_CONTRACT.read_text(encoding="utf-8") + required = ( + "cargo metadata --locked --all-features", + "cargo cyclonedx --format json --all --all-features --target all --spec-version 1.6", + "cargo cyclonedx --format xml --all --all-features --target all --spec-version 1.6", + "scripts/collect_workspace_sboms.py", + "--format json", + "--format xml", + "--remove-sources", + "cargo deny --config deny.toml --locked check licenses", + "--conclude-allowed-cargo-licenses", + "--deny-policy deny.toml", + "--input-version v1_6", + "--fail-on-errors", + "sbomqs score --json", + "scripts/check_sbom_quality.py", + "cargo-cyclonedx does not match pinned version", + "cargo-deny does not match pinned version", + "CycloneDX CLI does not match pinned version", + "sbomqs does not match pinned version", ) - self.assertIn("--format json", release) - self.assertIn("--format xml", release) - self.assertNotIn("find . -name '*.cdx.", release) + for fragment in required: + with self.subTest(fragment=fragment): + self.assertIn(fragment, contract) + self.assertLess( + contract.index("cargo deny --config deny.toml --locked check licenses"), + contract.index("python3 scripts/sbom_postprocess.py"), + ) + self.assertNotIn("--declare-dependency-complete", contract) + self.assertNotIn("find ", contract) + + def test_schema_validator_download_is_version_and_checksum_pinned(self) -> None: + # Schema validation is a release gate, so changing either official CLI + # binary requires an explicit version-and-digest policy update in both lanes. + security = source() + release = RELEASE_WORKFLOW.read_text(encoding="utf-8") + pins = ( + 'CYCLONEDX_CLI_VERSION: "0.33.1"', + 'CYCLONEDX_CLI_LINUX_X64_SHA256: "bfc8b2538da86fe239bc53658bbb63c1c8c510a293c1e6891aa5bea5d3c58746"', + 'CYCLONEDX_CLI_LINUX_ARM64_SHA256: "b2e9fdf9665ef49868a2ec012171c6e785dcd69745bc5869e53e4f4bfb096a5f"', + ) + for workflow in (security, release): + for pin in pins: + with self.subTest(pin=pin): + self.assertIn(pin, workflow) + self.assertIn("./scripts/install-cyclonedx-cli.sh", workflow) + + def test_release_packages_and_verifies_the_exact_scored_documents(self) -> None: + # The quality report and all validated JSON/XML files enter one checked + # archive before the archive and its checksum can be uploaded. + release = RELEASE_WORKFLOW.read_text(encoding="utf-8") + package = release.index("tar czf ../rust-gvm-api-sbom.tar.gz") + verify = release.index("python3 -B scripts/verify_sbom_release.py") + upload = release.index('gh release upload "${RELEASE_TAG}" rust-gvm-api-sbom.tar.gz') + self.assertLess(package, verify) + self.assertLess(verify, upload) + self.assertIn("*.cdx.json *.cdx.xml sbomqs-results.json", release) + self.assertIn("sha256sum rust-gvm-api-sbom.tar.gz", release) def test_shadow_evidence_write_permission_is_confined_to_trusted_persistence_job(self) -> None: # Durable evidence needs one branch writer, but untrusted PR and merge diff --git a/tests/test_verify_sbom_release.py b/tests/test_verify_sbom_release.py new file mode 100644 index 00000000..e7bc90a2 --- /dev/null +++ b/tests/test_verify_sbom_release.py @@ -0,0 +1,154 @@ +"""Release-verifier tests for the published SBOM evidence contract.""" + +import hashlib +import io +import json +import tarfile +import tempfile +import unittest +from pathlib import Path + +from scripts.verify_sbom_release import VerificationError, verify_archive + + +class VerifySbomReleaseTests(unittest.TestCase): + def setUp(self) -> None: + directory = tempfile.TemporaryDirectory(prefix="verify-sbom-release-") + self.addCleanup(directory.cleanup) + self.root = Path(directory.name) + self.archive = self.root / "rust-gvm-api-sbom.tar.gz" + self.checksum = self.root / "rust-gvm-api-sbom.tar.gz.sha256" + self.packages = ["one", "two"] + self.members = self.valid_members() + + def json_sbom(self, version: str = "1.6") -> bytes: + return json.dumps( + { + "bomFormat": "CycloneDX", + "specVersion": version, + "metadata": {"component": {"version": "0.8.2"}}, + } + ).encode() + + def xml_sbom(self, version: str = "1.6") -> bytes: + return ( + f'' + "0.8.2" + ).encode() + + def valid_members(self) -> dict[str, bytes]: + members = {} + for package in self.packages: + members[f"{package}.cdx.json"] = self.json_sbom() + members[f"{package}.cdx.xml"] = self.xml_sbom() + members["sbomqs-results.json"] = json.dumps( + { + "files": [ + { + "file_name": f"sbom-artifacts/{package}.cdx.json", + "sbom_quality_score": 8.3, + } + for package in self.packages + ] + } + ).encode() + return members + + def write_bundle(self) -> None: + with tarfile.open(self.archive, "w:gz") as bundle: + for name, payload in self.members.items(): + info = tarfile.TarInfo(name) + info.size = len(payload) + bundle.addfile(info, io.BytesIO(payload)) + digest = hashlib.sha256(self.archive.read_bytes()).hexdigest() + self.checksum.write_text(f"{digest} {self.archive.name}\n", encoding="utf-8") + + def verify(self) -> None: + self.write_bundle() + verify_archive(self.archive, self.checksum, self.packages, "0.8.2", 8.3) + + def test_complete_archive_and_checksum_satisfy_release_contract(self) -> None: + # A release is publishable only with every inventoried JSON/XML pair, + # the complete score report, and a checksum naming the archive. + self.verify() + + def test_missing_format_or_unexpected_file_fails_closed(self) -> None: + # Partial document sets and unrelated files must not be mistaken for a + # complete release SBOM or smuggle test fixtures into the archive. + del self.members["two.cdx.xml"] + self.members["untracked.cdx.xml"] = self.xml_sbom() + with self.assertRaisesRegex(VerificationError, "inventory mismatch"): + self.verify() + + def test_every_json_document_must_be_cyclonedx_1_6(self) -> None: + # The postprocessed JSON shipped to users cannot silently remain on the + # old schema while the workflow advertises a 1.6 toolchain. + self.members["one.cdx.json"] = self.json_sbom("1.5") + with self.assertRaisesRegex(VerificationError, "not CycloneDX 1.6 JSON"): + self.verify() + + def test_every_xml_document_must_be_cyclonedx_1_6(self) -> None: + # Generator-native XML remains supported for compatibility, but every + # archived document must identify the required 1.6 namespace. + self.members["one.cdx.xml"] = self.xml_sbom("1.5") + with self.assertRaisesRegex(VerificationError, "not CycloneDX 1.6 XML"): + self.verify() + + def test_quality_report_must_cover_exact_json_set_at_score_floor(self) -> None: + # Scoring one file twice or accepting a below-floor file would let the + # archive diverge from the JSON set that passed Security CI. + self.members["sbomqs-results.json"] = json.dumps( + { + "files": [ + {"file_name": "one.cdx.json", "sbom_quality_score": 8.29}, + {"file_name": "one.cdx.json", "sbom_quality_score": 9.0}, + ] + } + ).encode() + with self.assertRaisesRegex(VerificationError, "below 8.3"): + self.verify() + + def test_embedded_signature_and_complete_composition_claim_are_rejected(self) -> None: + # Release checksums and external attestations are distinct evidence; the + # SBOM must not invent an embedded signature or overstate completeness. + cases = ( + ( + "signature", + {"algorithm": "RS256", "value": "not-evidence"}, + "embedded signature", + ), + ("compositions", [{"aggregate": "complete"}], "complete composition"), + ) + for field, value, message in cases: + with self.subTest(field=field): + self.members = self.valid_members() + document = json.loads(self.members["one.cdx.json"]) + document[field] = value + self.members["one.cdx.json"] = json.dumps(document).encode() + with self.assertRaisesRegex(VerificationError, message): + self.verify() + + def test_checksum_mismatch_blocks_publication(self) -> None: + # The separately published checksum must authenticate the exact archive + # that the verifier inspected and the release job subsequently uploads. + self.write_bundle() + self.checksum.write_text(f"{'0' * 64} {self.archive.name}\n", encoding="utf-8") + with self.assertRaisesRegex(VerificationError, "does not match"): + verify_archive(self.archive, self.checksum, self.packages, "0.8.2", 8.3) + + def test_invalid_score_threshold_cannot_disable_release_gate(self) -> None: + # NaN compares false to every score, so it must be rejected explicitly + # instead of accidentally allowing every below-policy document. + self.write_bundle() + with self.assertRaisesRegex(VerificationError, "between 0 and 10"): + verify_archive( + self.archive, + self.checksum, + self.packages, + "0.8.2", + float("nan"), + ) + + +if __name__ == "__main__": + unittest.main() From 933ca59abaaf31b205505a4e37cce27c595e2fdd Mon Sep 17 00:00:00 2001 From: OpenClaw Bot Date: Sun, 29 Nov 2026 03:41:42 +0000 Subject: [PATCH 2/3] Harden XML release verification boundary Bound archive members before XML parsing and document why the standard-library parser remains safe without an unpinned runtime dependency. Agent: Thoth Model: openai/gpt-5.6-sol Thinking: high Bot-Owner: @llunved --- scripts/verify_sbom_release.py | 10 +++++++++- tests/test_verify_sbom_release.py | 9 +++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/scripts/verify_sbom_release.py b/scripts/verify_sbom_release.py index e16b3e69..fe85afe9 100755 --- a/scripts/verify_sbom_release.py +++ b/scripts/verify_sbom_release.py @@ -11,7 +11,10 @@ import sys import tarfile import tomllib -import xml.etree.ElementTree as ET +# XML inputs are size-bounded below and DTD/entity declarations are rejected +# before parsing. Keep the standard-library parser so release verification has +# no unpinned runtime dependency. +import xml.etree.ElementTree as ET # nosemgrep: python.lang.security.use-defused-xml.use-defused-xml from pathlib import Path from typing import Any @@ -25,6 +28,7 @@ CYCLONEDX_XML_NAMESPACE = "http://cyclonedx.org/schema/bom/1.6" QUALITY_REPORT_NAME = "sbomqs-results.json" +MAX_ARCHIVE_MEMBER_BYTES = 16 * 1024 * 1024 SHA256_LINE = re.compile(r"^(?P[0-9a-f]{64}) [ *](?P[^/]+)$") @@ -58,6 +62,10 @@ def read_regular_members(archive: Path) -> dict[str, bytes]: raise VerificationError("SBOM archive must contain only flat regular files") if len({member.name for member in members}) != len(members): raise VerificationError("SBOM archive contains duplicate member names") + if any(member.size > MAX_ARCHIVE_MEMBER_BYTES for member in members): + raise VerificationError( + f"SBOM archive members must not exceed {MAX_ARCHIVE_MEMBER_BYTES} bytes" + ) result = {} for member in members: stream = bundle.extractfile(member) diff --git a/tests/test_verify_sbom_release.py b/tests/test_verify_sbom_release.py index e7bc90a2..5e80a127 100644 --- a/tests/test_verify_sbom_release.py +++ b/tests/test_verify_sbom_release.py @@ -7,6 +7,7 @@ import tempfile import unittest from pathlib import Path +from unittest.mock import patch from scripts.verify_sbom_release import VerificationError, verify_archive @@ -80,6 +81,14 @@ def test_missing_format_or_unexpected_file_fails_closed(self) -> None: with self.assertRaisesRegex(VerificationError, "inventory mismatch"): self.verify() + def test_oversized_archive_member_is_rejected_before_xml_parsing(self) -> None: + # Bounding every member limits parser resource use even when a release + # archive is malicious or corrupted before verification. + self.members["one.cdx.xml"] = self.xml_sbom() + b" " * 64 + with patch("scripts.verify_sbom_release.MAX_ARCHIVE_MEMBER_BYTES", 64): + with self.assertRaisesRegex(VerificationError, "must not exceed 64 bytes"): + self.verify() + def test_every_json_document_must_be_cyclonedx_1_6(self) -> None: # The postprocessed JSON shipped to users cannot silently remain on the # old schema while the workflow advertises a 1.6 toolchain. From 29875dc1014feec9ed7b58ee4b1fe95347b3bdeb Mon Sep 17 00:00:00 2001 From: OpenClaw Bot Date: Sun, 29 Nov 2026 03:51:51 +0000 Subject: [PATCH 3/3] Use hash-pinned safe XML parser Parse release SBOM XML with defusedxml and install the exact hashed wheel before Security policy tests and tagged-release verification. This removes the code-scanning finding instead of suppressing it. Agent: Thoth Model: openai/gpt-5.6-sol Thinking: high Bot-Owner: @llunved --- .github/workflows/release-publish.yml | 2 ++ .github/workflows/security.yml | 2 ++ requirements-security.txt | 3 +++ scripts/verify_sbom_release.py | 16 +++++++++------ tests/test_security_workflow.py | 28 +++++++++++++++++++++++++++ 5 files changed, 45 insertions(+), 6 deletions(-) create mode 100644 requirements-security.txt diff --git a/.github/workflows/release-publish.yml b/.github/workflows/release-publish.yml index 72e81420..3b31e139 100644 --- a/.github/workflows/release-publish.yml +++ b/.github/workflows/release-publish.yml @@ -323,6 +323,8 @@ jobs: run: cargo install cargo-cyclonedx --version "${CARGO_CYCLONEDX_VERSION}" --locked - name: Install pinned cargo-deny license gate run: cargo install cargo-deny --version "${CARGO_DENY_VERSION}" --locked + - name: Install hash-pinned Python security dependencies + run: python3 -m pip install --require-hashes --no-deps -r requirements-security.txt - name: Install checksum-pinned CycloneDX schema validator run: | ./scripts/install-cyclonedx-cli.sh "${RUNNER_TEMP}/cyclonedx-cli" diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 67b941b0..07069fd1 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -114,6 +114,8 @@ jobs: rust-version: stable components: rustfmt cache-key: cargo-security-policy-${{ runner.os }}-${{ runner.arch }}-stable-${{ hashFiles('**/Cargo.lock') }} + - name: Install hash-pinned Python security dependencies + run: python3 -m pip install --require-hashes --no-deps -r requirements-security.txt - name: Test fail-closed security helpers and workflow policy run: >- python3 -B -m unittest diff --git a/requirements-security.txt b/requirements-security.txt new file mode 100644 index 00000000..f942091c --- /dev/null +++ b/requirements-security.txt @@ -0,0 +1,3 @@ +# Safe XML parsing for release evidence. The hash pins the universal PyPI wheel. +defusedxml==0.7.1 \ + --hash=sha256:a352e7e428770286cc899e2542b6cdaedb2b4953ff269a210103ec58f6198a61 diff --git a/scripts/verify_sbom_release.py b/scripts/verify_sbom_release.py index fe85afe9..b648cde5 100755 --- a/scripts/verify_sbom_release.py +++ b/scripts/verify_sbom_release.py @@ -11,13 +11,12 @@ import sys import tarfile import tomllib -# XML inputs are size-bounded below and DTD/entity declarations are rejected -# before parsing. Keep the standard-library parser so release verification has -# no unpinned runtime dependency. -import xml.etree.ElementTree as ET # nosemgrep: python.lang.security.use-defused-xml.use-defused-xml from pathlib import Path from typing import Any +from defusedxml import ElementTree as ET +from defusedxml.common import DefusedXmlException + try: from scripts.check_sbom_quality import check_report, entry_path from scripts.workspace_inventory import load_inventory @@ -102,8 +101,13 @@ def verify_xml_sbom(name: str, payload: bytes, version: str) -> None: if b" None: self.assertIn("*.cdx.json *.cdx.xml sbomqs-results.json", release) self.assertIn("sha256sum rust-gvm-api-sbom.tar.gz", release) + def test_xml_parser_dependency_is_hash_pinned_before_each_verifier_use(self) -> None: + # Both the policy tests and tagged-release verifier parse untrusted XML; + # they must install the same immutable defusedxml wheel first. + requirements = PYTHON_SECURITY_REQUIREMENTS.read_text(encoding="utf-8") + self.assertEqual( + requirements.strip(), + "# Safe XML parsing for release evidence. The hash pins the universal " + "PyPI wheel.\n" + "defusedxml==0.7.1 \\\n" + " --hash=sha256:" + "a352e7e428770286cc899e2542b6cdaedb2b4953ff269a210103ec58f6198a61", + ) + install = ( + "python3 -m pip install --require-hashes --no-deps " + "-r requirements-security.txt" + ) + security = source() + release = RELEASE_WORKFLOW.read_text(encoding="utf-8") + self.assertLess( + security.index(install), + security.index("tests.test_verify_sbom_release"), + ) + self.assertLess( + release.index(install), + release.index("python3 -B scripts/verify_sbom_release.py"), + ) + def test_shadow_evidence_write_permission_is_confined_to_trusted_persistence_job(self) -> None: # Durable evidence needs one branch writer, but untrusted PR and merge # executions must never inherit that permission or enter its condition.