From e3b8b5d546f85018616a8e7e2e5aa25838ad62a2 Mon Sep 17 00:00:00 2001 From: Danathar Date: Fri, 11 Sep 2026 21:55:48 +0000 Subject: [PATCH 1/3] supply-chain: attest GNOME versions and final repository policy Closes #21. - Strengthen RPM contract verification in scripts/verify-rpm-contract.py: - Assert GNOME contract packages match required major versions (GNOME 51 core desktop packages) and expected factory/Hummingbird release identity (.hum1.bfin / .hum), failing closed if Fedora disttags are present. - Assert Bluefin parity packages expected from factory rebuilds carry the .bfin release identity, preventing silent fallback to Hummingbird base or foreign repositories. - Enforce the runtime repository allowlist on /etc/yum.repos.d and package manager status, failing closed on Fedora or unapproved repositories. - Record the resolved package-origin/NEVRA report with build provenance at /usr/share/utah/package-provenance.json (mirrored as nevra-report.json and package-origins.json). - Declare GNOME major versions, factory packages, and repository allowlist in packages/utah.toml. - Document the supply-chain contract, repository allowlist, and provenance report retention in docs/skills/package-contract.md. - Add unit test suite in tests/unit/test_verify_rpm_contract.py and wire test discovery into Justfile check recipe. Signed-off-by: Danathar --- Justfile | 1 + docs/skills/package-contract.md | 42 ++- packages/utah.toml | 88 ++++++ scripts/verify-rpm-contract.py | 382 ++++++++++++++++++++++++- tests/__init__.py | 0 tests/unit/__init__.py | 0 tests/unit/test_verify_rpm_contract.py | 230 +++++++++++++++ 7 files changed, 735 insertions(+), 8 deletions(-) create mode 100644 tests/__init__.py create mode 100644 tests/unit/__init__.py create mode 100644 tests/unit/test_verify_rpm_contract.py diff --git a/Justfile b/Justfile index 6706129f..7218a8a2 100644 --- a/Justfile +++ b/Justfile @@ -66,6 +66,7 @@ check: python3 -m py_compile scripts/check-repo-availability.py python3 scripts/install-packages.py --check packages/bluefin.toml python3 scripts/verify-rpm-contract.py --check packages/bluefin.toml + python3 -m unittest discover -s tests grep -qE 'reusable-build\.yml@(v1|[0-9a-f]{40} # v1)$' .github/workflows/build.yml test -f Containerfile.kernel bash -n scripts/install-ogc-kernel.sh diff --git a/docs/skills/package-contract.md b/docs/skills/package-contract.md index d19d53f3..703c8460 100644 --- a/docs/skills/package-contract.md +++ b/docs/skills/package-contract.md @@ -1,7 +1,7 @@ --- name: package-contract version: "1.0" -last_updated: "2026-09-05" +last_updated: "2026-09-11" id: package-contract one_line_purpose: Maintain Bluefin package parity and Utah's overlay manifest. entry_point: docs/skills/package-contract.md @@ -37,10 +37,15 @@ policy for changing them. addition to* or *instead of* the contract lives here. The full rules are in the header comment of that file (cite it; do not move or copy it): - - `[gnome]` — GNOME 51 desktop contract Hummingbird does not ship. + - `[gnome]` — GNOME 51 desktop contract Hummingbird does not ship, with + major version assertions (`[gnome.major_versions]`). - `[build]` — toolchain needed to build the pinned GNOME extensions (`scripts/build-gnome-extensions.sh`). - `[services]` — desktop services Bluefin adds on top of the server base. + - `[factory]` — Bluefin parity packages expected from the Utah package factory + rebuilds (`.hum1.bfin`). + - `[repositories]` — explicitly allowed runtime RPM repositories. + - `[supply_chain]` — provenance report path and release identity patterns. - `[unavailable]` — Bluefin contract packages none of Utah's repositories provide. @@ -83,6 +88,15 @@ The pinned package image is an RPM repository, not a runtime dependency: its contents are copied into the image so the package transaction is reproducible and does not depend on a mutable mirror (`Containerfile` L41-44). +An explicit repository allowlist (`[repositories].allowlist`) in +`packages/utah.toml` restricts runtime repositories strictly to: +- `utah-packages` +- `public-hummingbird-x86_64-rpms` +- `nvidia-container-toolkit` (for nvidia flavors) + +Any unapproved repository or any repository resolving from Fedora causes the +build contract check (`scripts/verify-rpm-contract.py`) to fail closed. + ## Supply-chain download verification Every executable release asset fetched during image or ISO composition is @@ -91,6 +105,30 @@ before extraction or execution. `scripts/check-download-integrity.py` runs in `just check` and pre-commit to statically enforce that no build recipe resolves a mutable latest release or downloads unverified executables. +## Supply-chain contract and provenance attestation + +Beyond package name presence, `scripts/verify-rpm-contract.py` enforces full +supply-chain integrity and NEVRA identity: + +1. **GNOME 51 major version & release identity**: Core GNOME desktop contract + packages (`gnome-shell`, `mutter`, `gnome-control-center`, `gnome-session`, + `gnome-settings-daemon`, `gsettings-desktop-schemas`, `xdg-desktop-portal-gnome`) + must match required major version 51 (`[gnome.major_versions]`) and carry + factory/Hummingbird release identity (`.hum1.bfin` / `.hum`), failing if + any Fedora disttag (`.fc`) is detected. +2. **Factory parity package origin**: Bluefin parity packages expected from + factory rebuilds (`[factory].packages`) must carry the factory release + identity (`.bfin`, e.g. `.hum1.bfin`) and cannot silently resolve from + Hummingbird base or any other repository. +3. **Runtime repository allowlist**: The final image is verified to expose only + the explicitly allowed runtime RPM repositories; any enabled Fedora or + unapproved repository fails the build. +4. **Build provenance & NEVRA report retention**: A complete resolved + package-origin/NEVRA report is written to + `/usr/share/utah/package-provenance.json` (also linked to `package-origins.json` + and `nevra-report.json`) recording package NEVRAs, source RPMs, vendor, + repository origin classification, and attestation status. + ## Install and verify cannot disagree `scripts/install-packages.py` records exactly what its run resolved to diff --git a/packages/utah.toml b/packages/utah.toml index dbc79677..e3676860 100644 --- a/packages/utah.toml +++ b/packages/utah.toml @@ -8,6 +8,10 @@ # Sections: # [gnome] GNOME 51 desktop contract Hummingbird does not ship # [build] toolchain needed to build the pinned GNOME extensions +# [services] desktop services Bluefin adds on top of the server base +# [factory] Bluefin parity packages expected from the Utah package factory +# [repositories] explicitly allowed runtime RPM repositories +# [supply_chain] provenance and release identity policies # [unavailable] Bluefin contract packages none of Utah's repositories provide # # On [multimedia_overrides], which Utah deliberately does not install: @@ -48,6 +52,19 @@ packages = [ "xdg-desktop-portal-gnome", ] +[gnome.major_versions] +gnome-control-center = "51" +gnome-session = "51" +gnome-settings-daemon = "51" +gnome-shell = "51" +gsettings-desktop-schemas = "51" +mutter = "51" +xdg-desktop-portal-gnome = "51" +gtk4 = "4" +libadwaita = "1" +xdg-desktop-portal = "1" + + [build] # Build dependencies for scripts/build-gnome-extensions.sh. # @@ -82,6 +99,77 @@ packages = [ "tailscale", ] +[factory] +# Bluefin parity packages expected to be built and provided by the Utah package factory. +# These packages must carry the factory release identity (.hum1.bfin) and cannot silently +# resolve from Hummingbird or another repository. +packages = [ + "adw-gtk3-theme", + "adwaita-fonts-all", + "alsa-firmware", + "alsa-tools-firmware", + "anaconda-live", + "containerd", + "ddcutil", + "distrobox", + "evtest", + "fastfetch", + "flatpak-spawn", + "fzf", + "gnome-ponytail-daemon", + "gnome-tweaks", + "google-noto-sans-cjk-vf-fonts", + "gum", + "gvfs-nfs", + "ibus-mozc", + "ibus-unikey", + "igt-gpu-tools", + "input-remapper", + "isomd5sum", + "just", + "libappindicator-gtk3", + "libayatana-appindicator-gtk3", + "libblockdev-btrfs", + "libblockdev-dm", + "libblockdev-lvm", + "libblockdev-mpath", + "libcamera-gstreamer", + "libcamera-tools", + "libratbag-ratbagd", + "libva-utils", + "livesys-scripts", + "make", + "mesa-libGLU", + "mozc", + "nautilus-gsconnect", + "openrgb-udev-rules", + "python3-gnome-ponytail-daemon", + "slitherer", + "squashfs-tools", + "switcheroo-control", + "waypipe", + "wireguard-tools", + "wl-clipboard", + "xdg-terminal-exec", + "xorriso", + "zenity", +] + +[repositories] +# Runtime RPM repositories explicitly allowed in the composed image. +# Fedora or any unapproved repository enabled at runtime will fail verification. +allowlist = [ + "utah-packages", + "public-hummingbird-x86_64-rpms", + "nvidia-container-toolkit", +] + +[supply_chain] +report_path = "/usr/share/utah/package-provenance.json" +factory_release_pattern = '.*\.hum\d*\.bfin.*' +hummingbird_release_pattern = '.*\.hum\d*.*' + + [unavailable] # Packages Bluefin ships that none of Utah's repositories provide. Each entry # MUST carry a tracking issue: this list is the documented parity debt, not a diff --git a/scripts/verify-rpm-contract.py b/scripts/verify-rpm-contract.py index 08fb22ff..fdc0042a 100644 --- a/scripts/verify-rpm-contract.py +++ b/scripts/verify-rpm-contract.py @@ -3,16 +3,25 @@ Mirrors assert_packages_present from projectbluefin/bluefin's build_files/shared/package-lib.sh: name every missing package, once. +In addition, validates GNOME 51 major versions, verifies factory rebuild release +identity (.hum1.bfin) preventing silent fallbacks to base repositories, enforces +the final runtime repository allowlist, and records a resolved package-origin/NEVRA +report with build provenance under /usr/share/utah/package-provenance.json. """ from __future__ import annotations import argparse +import json import os +import re +import shutil import subprocess import sys import tomllib +from datetime import datetime, timezone from pathlib import Path +from typing import Any # The NVIDIA userspace no longer arrives as RPMs. UBlue's akmods bundle used to # supply nvidia-driver, nvidia-driver-cuda and nvidia-container-toolkit, but it @@ -27,6 +36,28 @@ # was one source, not the only one. NVIDIA_PACKAGES: tuple[str, ...] = ("nvidia-container-toolkit",) +# Approved runtime repository IDs explicitly permitted in composed Utah images. +# Fedora repositories or unapproved third-party repositories must fail verification. +DEFAULT_ALLOWED_REPOS: tuple[str, ...] = ( + "utah-packages", + "public-hummingbird-x86_64-rpms", + "nvidia-container-toolkit", +) + +# Expected major versions for GNOME contract packages. +DEFAULT_GNOME_MAJORS: dict[str, str] = { + "gnome-control-center": "51", + "gnome-session": "51", + "gnome-settings-daemon": "51", + "gnome-shell": "51", + "gsettings-desktop-schemas": "51", + "mutter": "51", + "xdg-desktop-portal-gnome": "51", + "gtk4": "4", + "libadwaita": "1", + "xdg-desktop-portal": "1", +} + def section(path: Path, name: str) -> list[str]: data = tomllib.loads(path.read_text()) @@ -39,6 +70,270 @@ def is_installed(pkg: str) -> bool: ).returncode == 0 +def query_package_nevras(packages: list[str]) -> dict[str, dict[str, str]]: + """Query NEVRAs and provenance attributes for installed packages in batch.""" + if not packages: + return {} + qf = "%{NAME}|%|EPOCH?{%{EPOCH}}:{0}||%{VERSION}|%{RELEASE}|%{ARCH}|%{SOURCERPM}|%|VENDOR?{%{VENDOR}}:{(none)}|\n" + res = subprocess.run( + ["rpm", "-q", f"--queryformat={qf}", *packages], + capture_output=True, + text=True, + check=False, + ) + pkg_map: dict[str, dict[str, str]] = {} + for line in res.stdout.splitlines(): + line = line.strip() + if not line or "|" not in line: + continue + parts = line.split("|") + if len(parts) >= 7: + name, epoch, version, release, arch, sourcerpm, vendor = parts[:7] + pkg_map[name] = { + "name": name, + "epoch": epoch, + "version": version, + "release": release, + "arch": arch, + "sourcerpm": sourcerpm, + "vendor": vendor, + "nevra": f"{name}-{epoch}:{version}-{release}.{arch}", + } + return pkg_map + + +def verify_gnome_packages( + gnome_pkgs: list[str], + pkg_map: dict[str, dict[str, str]], + expected_majors: dict[str, str], +) -> list[str]: + """Verify GNOME contract packages for required major version and release identity.""" + errors: list[str] = [] + for pkg in gnome_pkgs: + info = pkg_map.get(pkg) + if not info: + continue + ver = info["version"] + rel = info["release"] + exp_maj = expected_majors.get(pkg) + if exp_maj: + m = re.match(r"^(\d+)", ver) + actual_maj = m.group(1) if m else "" + if actual_maj != str(exp_maj): + errors.append( + f"GNOME package '{pkg}' version '{ver}' does not match required major version '{exp_maj}'" + ) + # Release identity must match factory (.hum1.bfin) or Hummingbird (.hum) + if not re.search(r"\.hum\d*(\.bfin)?", rel): + errors.append( + f"GNOME package '{pkg}' release '{rel}' does not match expected factory/Hummingbird release identity" + ) + if ".fc" in rel: + errors.append( + f"GNOME package '{pkg}' release '{rel}' carries unapproved Fedora release identity" + ) + return errors + + +def verify_factory_packages( + factory_pkgs: list[str], + pkg_map: dict[str, dict[str, str]], +) -> list[str]: + """Ensure Bluefin parity packages expected from factory carry .bfin and did not silently resolve from base repos.""" + errors: list[str] = [] + for pkg in factory_pkgs: + info = pkg_map.get(pkg) + if not info: + continue + rel = info["release"] + if not re.search(r"\.bfin", rel): + errors.append( + f"Bluefin parity package '{pkg}' expected from factory (.bfin), but resolved with release '{rel}' (silent repository fallback)" + ) + if ".fc" in rel: + errors.append( + f"Bluefin parity package '{pkg}' carries unapproved Fedora release identity '{rel}'" + ) + return errors + + +def verify_repository_allowlist( + allowlist: set[str], + repos_dir: Path = Path("/etc/yum.repos.d"), +) -> tuple[list[str], list[str]]: + """Enforce repository allowlist on /etc/yum.repos.d and package manager status.""" + errors: list[str] = [] + enabled_repos: set[str] = set() + + if repos_dir.is_dir(): + for repo_file in sorted(repos_dir.glob("*.repo")): + try: + content = repo_file.read_text() + except OSError: + continue + current_section: str | None = None + section_enabled = True + is_fedora = False + for line in content.splitlines(): + line = line.strip() + if not line or line.startswith("#") or line.startswith(";"): + continue + sec_match = re.match(r"^\[([^\]]+)\]", line) + if sec_match: + if current_section is not None and section_enabled: + enabled_repos.add(current_section) + if is_fedora: + errors.append( + f"Repository allowlist failure: Fedora repository '{current_section}' is enabled in {repo_file.name}" + ) + elif current_section not in allowlist: + errors.append( + f"Repository allowlist failure: unapproved repository '{current_section}' is enabled in {repo_file.name} (allowlist: {sorted(allowlist)})" + ) + current_section = sec_match.group(1).strip() + section_enabled = True + is_fedora = "fedora" in current_section.lower() or "rawhide" in current_section.lower() + elif "=" in line: + k, v = line.split("=", 1) + k = k.strip().lower() + v = v.strip().lower() + if k == "enabled": + section_enabled = v in ("1", "true", "yes") + elif k in ("baseurl", "metalink", "mirrorlist"): + if "fedoraproject.org" in v or "fedora" in v: + is_fedora = True + + if current_section is not None and section_enabled: + enabled_repos.add(current_section) + if is_fedora: + errors.append( + f"Repository allowlist failure: Fedora repository '{current_section}' is enabled in {repo_file.name}" + ) + elif current_section not in allowlist: + errors.append( + f"Repository allowlist failure: unapproved repository '{current_section}' is enabled in {repo_file.name} (allowlist: {sorted(allowlist)})" + ) + + dnf_bin = shutil.which("dnf5") or shutil.which("dnf") + if dnf_bin: + res = subprocess.run( + [dnf_bin, "repolist", "--enabled"], + capture_output=True, + text=True, + check=False, + ) + if res.returncode == 0: + for line in res.stdout.splitlines(): + line = line.strip() + if not line or line.startswith("repo id") or line.startswith("Loaded plugins") or line.startswith("Updating and loading"): + continue + parts = line.split() + if parts: + repo_id = parts[0] + enabled_repos.add(repo_id) + if "fedora" in repo_id.lower() or "rawhide" in repo_id.lower(): + msg = f"Repository allowlist failure: Fedora repository '{repo_id}' reported enabled by package manager" + if msg not in errors: + errors.append(msg) + elif repo_id not in allowlist: + msg = f"Repository allowlist failure: unapproved repository '{repo_id}' reported enabled by package manager (allowlist: {sorted(allowlist)})" + if msg not in errors: + errors.append(msg) + + return errors, sorted(enabled_repos) + + +def retain_provenance_report( + pkg_map: dict[str, dict[str, str]], + expected_categories: dict[str, str], + factory_pkgs: set[str], + gnome_majors: dict[str, str], + enabled_repos: list[str], + allowlist: set[str], + flavor: str, + output_path: Path = Path("/usr/share/utah/package-provenance.json"), +) -> None: + """Retain the resolved package-origin/NEVRA report with build provenance.""" + packages_list = [] + summary_counts = { + "total_contract_packages": len(pkg_map), + "factory_packages": 0, + "hummingbird_packages": 0, + "nvidia_packages": 0, + "other_packages": 0, + } + + for name, info in sorted(pkg_map.items()): + rel = info["release"] + vendor = info.get("vendor", "") + if ".bfin" in rel: + origin = "factory" + summary_counts["factory_packages"] += 1 + elif ".hum" in rel: + origin = "hummingbird" + summary_counts["hummingbird_packages"] += 1 + elif "nvidia" in name.lower() or "nvidia" in vendor.lower() or "nvidia" in rel.lower(): + origin = "nvidia" + summary_counts["nvidia_packages"] += 1 + elif ".fc" in rel: + origin = "fedora" + summary_counts["other_packages"] += 1 + else: + origin = "other" + summary_counts["other_packages"] += 1 + + sec = expected_categories.get(name, "contract") + entry: dict[str, Any] = { + "name": name, + "epoch": info["epoch"], + "version": info["version"], + "release": info["release"], + "arch": info["arch"], + "nevra": info["nevra"], + "sourcerpm": info["sourcerpm"], + "vendor": info["vendor"], + "contract_section": sec, + "origin": origin, + "expected_factory": name in factory_pkgs, + } + if name in gnome_majors: + entry["expected_gnome_major"] = gnome_majors[name] + packages_list.append(entry) + + report = { + "report_version": "1.0", + "timestamp": datetime.now(timezone.utc).isoformat(), + "image_flavor": flavor, + "summary": summary_counts, + "repositories": { + "allowlist": sorted(allowlist), + "enabled": enabled_repos, + "allowlist_verified": True, + }, + "packages": packages_list, + } + + try: + output_path.parent.mkdir(parents=True, exist_ok=True) + report_json = json.dumps(report, indent=2) + "\n" + output_path.write_text(report_json) + for alias in ("package-origins.json", "nevra-report.json"): + alias_path = output_path.with_name(alias) + try: + alias_path.write_text(report_json) + except OSError: + pass + print( + f"Retained resolved package-origin/NEVRA report at {output_path} " + f"({len(packages_list)} packages: {summary_counts['factory_packages']} factory rebuilds, " + f"{summary_counts['hummingbird_packages']} Hummingbird)", + flush=True, + ) + except OSError as exc: + print(f"WARNING: Could not write package provenance report to {output_path}: {exc}", file=sys.stderr) + + + def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--check", action="store_true") @@ -48,7 +343,8 @@ def main() -> int: overlay = args.overlay or args.manifest.with_name("utah.toml") flavor = os.environ.get("IMAGE_FLAVOR", "main") - unavailable = set(section(overlay, "unavailable")) + overlay_data = tomllib.loads(overlay.read_text()) if overlay.exists() else {} + unavailable = set(overlay_data.get("unavailable", {}).get("packages", [])) # Prefer the set install-packages.py actually resolved. Recomputing it here # is what let the two drift once: install added [fedora_v] for the @@ -60,18 +356,27 @@ def main() -> int: resolved = Path("/usr/share/utah/contract.txt") if resolved.exists(): contract = [line for line in resolved.read_text().split() if line] - gnome_names = set(section(overlay, "gnome")) - service_names = set(section(overlay, "services")) + gnome_names = set(overlay_data.get("gnome", {}).get("packages", [])) + service_names = set(overlay_data.get("services", {}).get("packages", [])) bluefin = [p for p in contract if p not in gnome_names and p not in service_names] gnome = [p for p in contract if p in gnome_names] services = [p for p in contract if p in service_names] else: - bluefin = [p for p in section(args.manifest, "fedora") if p not in unavailable] - gnome = section(overlay, "gnome") - services = section(overlay, "services") + manifest_data = tomllib.loads(args.manifest.read_text()) if args.manifest.exists() else {} + bluefin = [p for p in manifest_data.get("fedora", {}).get("packages", []) if p not in unavailable] + gnome = list(overlay_data.get("gnome", {}).get("packages", [])) + services = list(overlay_data.get("services", {}).get("packages", [])) + nvidia = list(NVIDIA_PACKAGES) if "nvidia" in flavor else [] expected = [*bluefin, *gnome, *services, *nvidia] + factory_pkgs = list(overlay_data.get("factory", {}).get("packages", [])) + configured_majors = dict(overlay_data.get("gnome", {}).get("major_versions", {})) + expected_gnome_majors = {**DEFAULT_GNOME_MAJORS, **configured_majors} + + raw_allowlist = overlay_data.get("repositories", {}).get("allowlist", DEFAULT_ALLOWED_REPOS) + repo_allowlist = set(raw_allowlist) + print( f"Verifying {len(bluefin)} Bluefin packages, {len(gnome)} GNOME desktop packages," f" {len(services)} desktop service packages, and {len(nvidia)} NVIDIA packages", @@ -79,6 +384,18 @@ def main() -> int: ) if args.check: assert len(set(expected)) == len(expected), "RPM contract contains duplicate package names" + if factory_pkgs: + assert len(set(factory_pkgs)) == len(factory_pkgs), "Factory package list contains duplicates" + overlap = set(factory_pkgs) & unavailable + assert not overlap, f"Factory packages overlap with unavailable: {overlap}" + assert not any("fedora" in r.lower() for r in repo_allowlist), "Fedora repository in allowlist" + assert "utah-packages" in repo_allowlist, "utah-packages missing from repository allowlist" + assert "public-hummingbird-x86_64-rpms" in repo_allowlist, "public-hummingbird missing from repository allowlist" + print( + f"RPM contract syntax and supply-chain policy is valid: " + f"{len(gnome)} GNOME desktop packages, {len(factory_pkgs)} factory rebuilds, " + f"repository allowlist: {', '.join(sorted(repo_allowlist))}" + ) return 0 missing = [pkg for pkg in expected if not is_installed(pkg)] @@ -92,6 +409,59 @@ def main() -> int: return 1 print(f"All {len(expected)} contract packages are present.") + # Query installed package NEVRAs and provenance attributes + pkg_map = query_package_nevras(expected) + + # Acceptance Criterion 1: GNOME contract package version & release identity + validation_errors: list[str] = [] + gnome_errors = verify_gnome_packages(gnome, pkg_map, expected_gnome_majors) + validation_errors.extend(gnome_errors) + + # Acceptance Criterion 2: Bluefin parity packages expected from factory cannot silently resolve elsewhere + factory_errors = verify_factory_packages(factory_pkgs, pkg_map) + validation_errors.extend(factory_errors) + + # Acceptance Criterion 3: Final repository allowlist fails on Fedora or unapproved repos + repo_errors, enabled_repos = verify_repository_allowlist(repo_allowlist) + validation_errors.extend(repo_errors) + + if validation_errors: + print(f"ERROR: {len(validation_errors)} supply-chain contract verification failures:", file=sys.stderr) + for err in validation_errors: + print(f" - {err}", file=sys.stderr) + return 1 + + print( + f"Supply-chain attestation passed: GNOME {len(gnome)} packages verified for version and release identity; " + f"{len(factory_pkgs)} factory parity packages confirmed; " + f"repository allowlist confirmed ({len(enabled_repos)} enabled repositories)." + ) + + # Acceptance Criterion 4: Retain resolved package-origin/NEVRA report with build provenance + category_map: dict[str, str] = {} + for p in bluefin: + category_map[p] = "bluefin" + for p in gnome: + category_map[p] = "gnome" + for p in services: + category_map[p] = "services" + for p in nvidia: + category_map[p] = "nvidia" + + report_path_str = overlay_data.get("supply_chain", {}).get( + "report_path", "/usr/share/utah/package-provenance.json" + ) + retain_provenance_report( + pkg_map=pkg_map, + expected_categories=category_map, + factory_pkgs=set(factory_pkgs), + gnome_majors=expected_gnome_majors, + enabled_repos=enabled_repos, + allowlist=repo_allowlist, + flavor=flavor, + output_path=Path(report_path_str), + ) + if "nvidia" not in flavor: return 0 diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/unit/test_verify_rpm_contract.py b/tests/unit/test_verify_rpm_contract.py new file mode 100644 index 00000000..0f7c193d --- /dev/null +++ b/tests/unit/test_verify_rpm_contract.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Unit tests for scripts/verify-rpm-contract.py supply-chain assertions.""" + +import importlib.util +import json +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent.parent +SCRIPT_PATH = REPO_ROOT / "scripts" / "verify-rpm-contract.py" + +spec = importlib.util.spec_from_file_location("verify_rpm_contract", SCRIPT_PATH) +mod = importlib.util.module_from_spec(spec) +spec.loader.exec_module(mod) + + +class TestVerifyRpmContract(unittest.TestCase): + def test_verify_gnome_packages_success(self): + gnome_pkgs = ["gnome-shell", "gtk4"] + pkg_map = { + "gnome-shell": { + "name": "gnome-shell", + "epoch": "0", + "version": "51~beta", + "release": "1.hum1.bfin", + "arch": "x86_64", + "sourcerpm": "gnome-shell-51~beta-1.hum1.bfin.src.rpm", + "vendor": "projectbluefin", + "nevra": "gnome-shell-0:51~beta-1.hum1.bfin.x86_64", + }, + "gtk4": { + "name": "gtk4", + "epoch": "0", + "version": "4.23.3", + "release": "1.hum1.bfin", + "arch": "x86_64", + "sourcerpm": "gtk4-4.23.3-1.hum1.bfin.src.rpm", + "vendor": "projectbluefin", + "nevra": "gtk4-0:4.23.3-1.hum1.bfin.x86_64", + }, + } + majors = {"gnome-shell": "51", "gtk4": "4"} + errors = mod.verify_gnome_packages(gnome_pkgs, pkg_map, majors) + self.assertEqual(errors, []) + + def test_verify_gnome_packages_version_mismatch(self): + gnome_pkgs = ["gnome-shell"] + pkg_map = { + "gnome-shell": { + "name": "gnome-shell", + "epoch": "0", + "version": "50.1", + "release": "1.hum1.bfin", + "arch": "x86_64", + "sourcerpm": "gnome-shell-50.1-1.hum1.bfin.src.rpm", + "vendor": "projectbluefin", + "nevra": "gnome-shell-0:50.1-1.hum1.bfin.x86_64", + } + } + majors = {"gnome-shell": "51"} + errors = mod.verify_gnome_packages(gnome_pkgs, pkg_map, majors) + self.assertEqual(len(errors), 1) + self.assertIn("does not match required major version '51'", errors[0]) + + def test_verify_gnome_packages_unapproved_release(self): + gnome_pkgs = ["gnome-shell"] + pkg_map = { + "gnome-shell": { + "name": "gnome-shell", + "epoch": "0", + "version": "51~beta", + "release": "1.fc44", + "arch": "x86_64", + "sourcerpm": "gnome-shell-51~beta-1.fc44.src.rpm", + "vendor": "Fedora Project", + "nevra": "gnome-shell-0:51~beta-1.fc44.x86_64", + } + } + majors = {"gnome-shell": "51"} + errors = mod.verify_gnome_packages(gnome_pkgs, pkg_map, majors) + self.assertTrue(any("Fedora release identity" in err for err in errors)) + + def test_verify_factory_packages_success(self): + factory_pkgs = ["fastfetch", "just"] + pkg_map = { + "fastfetch": { + "name": "fastfetch", + "epoch": "0", + "version": "2.21.3", + "release": "1.hum1.bfin", + "arch": "x86_64", + "sourcerpm": "fastfetch-2.21.3-1.hum1.bfin.src.rpm", + "vendor": "projectbluefin", + "nevra": "fastfetch-0:2.21.3-1.hum1.bfin.x86_64", + }, + "just": { + "name": "just", + "epoch": "0", + "version": "1.35.0", + "release": "1.hum1.bfin", + "arch": "x86_64", + "sourcerpm": "just-1.35.0-1.hum1.bfin.src.rpm", + "vendor": "projectbluefin", + "nevra": "just-0:1.35.0-1.hum1.bfin.x86_64", + }, + } + errors = mod.verify_factory_packages(factory_pkgs, pkg_map) + self.assertEqual(errors, []) + + def test_verify_factory_packages_silent_fallback(self): + factory_pkgs = ["fastfetch"] + # Package resolved from Hummingbird base without .bfin rebuild + pkg_map = { + "fastfetch": { + "name": "fastfetch", + "epoch": "0", + "version": "2.20.0", + "release": "1.hum1", + "arch": "x86_64", + "sourcerpm": "fastfetch-2.20.0-1.hum1.src.rpm", + "vendor": "Red Hat", + "nevra": "fastfetch-0:2.20.0-1.hum1.x86_64", + } + } + errors = mod.verify_factory_packages(factory_pkgs, pkg_map) + self.assertEqual(len(errors), 1) + self.assertIn("silent repository fallback", errors[0]) + + def test_verify_repository_allowlist_allowed(self): + with tempfile.TemporaryDirectory() as tmpdir: + repos_dir = Path(tmpdir) + (repos_dir / "hummingbird.repo").write_text( + "[public-hummingbird-x86_64-rpms]\nname=hummingbird\nenabled=1\n" + ) + (repos_dir / "utah-packages.repo").write_text( + "[utah-packages]\nname=factory\nenabled=1\n" + ) + (repos_dir / "fedora.repo").write_text( + "[fedora]\nname=fedora\nenabled=0\n" + ) + allowlist = {"utah-packages", "public-hummingbird-x86_64-rpms", "nvidia-container-toolkit"} + errors, enabled = mod.verify_repository_allowlist(allowlist, repos_dir=repos_dir) + self.assertEqual(errors, []) + self.assertEqual(sorted(enabled), ["public-hummingbird-x86_64-rpms", "utah-packages"]) + + def test_verify_repository_allowlist_fedora_enabled(self): + with tempfile.TemporaryDirectory() as tmpdir: + repos_dir = Path(tmpdir) + (repos_dir / "fedora.repo").write_text( + "[fedora]\nname=fedora\nenabled=1\n" + ) + allowlist = {"utah-packages", "public-hummingbird-x86_64-rpms"} + errors, enabled = mod.verify_repository_allowlist(allowlist, repos_dir=repos_dir) + self.assertEqual(len(errors), 1) + self.assertIn("Fedora repository 'fedora' is enabled", errors[0]) + + def test_verify_repository_allowlist_unapproved_enabled(self): + with tempfile.TemporaryDirectory() as tmpdir: + repos_dir = Path(tmpdir) + (repos_dir / "random.repo").write_text( + "[unapproved-custom-repo]\nname=random\nenabled=1\n" + ) + allowlist = {"utah-packages", "public-hummingbird-x86_64-rpms"} + errors, enabled = mod.verify_repository_allowlist(allowlist, repos_dir=repos_dir) + self.assertEqual(len(errors), 1) + self.assertIn("unapproved repository 'unapproved-custom-repo' is enabled", errors[0]) + + def test_retain_provenance_report(self): + with tempfile.TemporaryDirectory() as tmpdir: + out_file = Path(tmpdir) / "usr" / "share" / "utah" / "package-provenance.json" + pkg_map = { + "gnome-shell": { + "name": "gnome-shell", + "epoch": "0", + "version": "51~beta", + "release": "1.hum1.bfin", + "arch": "x86_64", + "sourcerpm": "gnome-shell-51~beta-1.hum1.bfin.src.rpm", + "vendor": "projectbluefin", + "nevra": "gnome-shell-0:51~beta-1.hum1.bfin.x86_64", + }, + "bootc": { + "name": "bootc", + "epoch": "0", + "version": "1.1.0", + "release": "1.hum1", + "arch": "x86_64", + "sourcerpm": "bootc-1.1.0-1.hum1.src.rpm", + "vendor": "Red Hat", + "nevra": "bootc-0:1.1.0-1.hum1.x86_64", + }, + } + mod.retain_provenance_report( + pkg_map=pkg_map, + expected_categories={"gnome-shell": "gnome", "bootc": "bluefin"}, + factory_pkgs={"gnome-shell"}, + gnome_majors={"gnome-shell": "51"}, + enabled_repos=["utah-packages", "public-hummingbird-x86_64-rpms"], + allowlist={"utah-packages", "public-hummingbird-x86_64-rpms"}, + flavor="main", + output_path=out_file, + ) + self.assertTrue(out_file.exists()) + data = json.loads(out_file.read_text()) + self.assertEqual(data["report_version"], "1.0") + self.assertEqual(data["image_flavor"], "main") + self.assertEqual(data["summary"]["total_contract_packages"], 2) + self.assertEqual(data["summary"]["factory_packages"], 1) + self.assertEqual(data["summary"]["hummingbird_packages"], 1) + self.assertEqual(len(data["packages"]), 2) + origins = {p["name"]: p["origin"] for p in data["packages"]} + self.assertEqual(origins["gnome-shell"], "factory") + self.assertEqual(origins["bootc"], "hummingbird") + + def test_cli_check_mode(self): + res = subprocess.run( + [sys.executable, str(SCRIPT_PATH), "--check", str(REPO_ROOT / "packages" / "bluefin.toml")], + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(res.returncode, 0, f"CLI check failed: {res.stderr}") + self.assertIn("RPM contract syntax and supply-chain policy is valid", res.stdout) + + +if __name__ == "__main__": + unittest.main() From 8b2b4b9991f40b78cc99dc39b75dd0996a0c1ff6 Mon Sep 17 00:00:00 2001 From: Danathar Date: Sat, 12 Sep 2026 00:12:28 +0000 Subject: [PATCH 2/3] supply-chain: wire release-identity patterns from toml, drop dead provenance mirrors Review feedback on #68: - factory_release_pattern/hummingbird_release_pattern already existed in packages/utah.toml's [supply_chain] section but verify-rpm-contract.py never read them -- the regexes were hardcoded in Python instead. Now verify_gnome_packages/verify_factory_packages take the patterns as parameters (defaulting to the prior hardcoded values for existing callers/tests) and main() passes through what utah.toml declares, so a dist-tag convention change on either repo is a data edit. - The provenance report was mirrored to package-origins.json and nevra-report.json with no consumer anywhere in the repo for either name. Dropped the mirrors; package-provenance.json is canonical. - Documented the utah.toml [factory] list as a cross-repo contract with utah-packages in docs/skills/package-contract.md, since nothing currently signals a break on the utah-packages side. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01LNgJ8VMdoqzGequbxsP2Kc --- docs/skills/package-contract.md | 20 +++++++++++++++++--- packages/utah.toml | 5 +++++ scripts/verify-rpm-contract.py | 32 ++++++++++++++++++++++---------- 3 files changed, 44 insertions(+), 13 deletions(-) diff --git a/docs/skills/package-contract.md b/docs/skills/package-contract.md index 703c8460..897f9154 100644 --- a/docs/skills/package-contract.md +++ b/docs/skills/package-contract.md @@ -120,14 +120,28 @@ supply-chain integrity and NEVRA identity: factory rebuilds (`[factory].packages`) must carry the factory release identity (`.bfin`, e.g. `.hum1.bfin`) and cannot silently resolve from Hummingbird base or any other repository. + + `[factory].packages` is a contract with the `utah-packages` factory repo, + not just this one: every name listed is a promise that `utah-packages` + rebuilds and publishes it. There is no shared CI between the two repos, so + if a package is dropped or renamed on the factory side, this check is the + only thing that will notice -- and it notices here, not there. Keep the + list in sync with what the factory actually ships, and link the tracking + issue for keeping the two repos' release-identity conventions in sync + once one exists. + + The `.hum1.bfin` / `.hum` release-identity patterns themselves are not + hardcoded in the script -- they live in `[supply_chain].factory_release_pattern` + and `[supply_chain].hummingbird_release_pattern` in `packages/utah.toml`, + so a dist-tag convention change on either repo is a one-line data edit + there, not a code change here. 3. **Runtime repository allowlist**: The final image is verified to expose only the explicitly allowed runtime RPM repositories; any enabled Fedora or unapproved repository fails the build. 4. **Build provenance & NEVRA report retention**: A complete resolved package-origin/NEVRA report is written to - `/usr/share/utah/package-provenance.json` (also linked to `package-origins.json` - and `nevra-report.json`) recording package NEVRAs, source RPMs, vendor, - repository origin classification, and attestation status. + `/usr/share/utah/package-provenance.json` recording package NEVRAs, source + RPMs, vendor, repository origin classification, and attestation status. ## Install and verify cannot disagree diff --git a/packages/utah.toml b/packages/utah.toml index e3676860..051d1488 100644 --- a/packages/utah.toml +++ b/packages/utah.toml @@ -166,6 +166,11 @@ allowlist = [ [supply_chain] report_path = "/usr/share/utah/package-provenance.json" +# These patterns encode the *current* dist-tag convention on each side. If +# utah-packages or Hummingbird ever change how they tag releases, update the +# pattern here rather than in scripts/verify-rpm-contract.py -- the two repos' +# release-identity conventions must move together, and this is the one place +# that should need editing when they do. factory_release_pattern = '.*\.hum\d*\.bfin.*' hummingbird_release_pattern = '.*\.hum\d*.*' diff --git a/scripts/verify-rpm-contract.py b/scripts/verify-rpm-contract.py index fdc0042a..7e71a7cf 100644 --- a/scripts/verify-rpm-contract.py +++ b/scripts/verify-rpm-contract.py @@ -44,6 +44,12 @@ "nvidia-container-toolkit", ) +# Release-identity patterns for the factory (.hum1.bfin) and Hummingbird +# (.hum) rebuild conventions. Overridable via [supply_chain] in utah.toml so a +# dist-tag convention change on either side is a data edit, not a code change. +DEFAULT_FACTORY_RELEASE_PATTERN = r"\.bfin" +DEFAULT_HUMMINGBIRD_RELEASE_PATTERN = r"\.hum\d*(\.bfin)?" + # Expected major versions for GNOME contract packages. DEFAULT_GNOME_MAJORS: dict[str, str] = { "gnome-control-center": "51", @@ -106,6 +112,7 @@ def verify_gnome_packages( gnome_pkgs: list[str], pkg_map: dict[str, dict[str, str]], expected_majors: dict[str, str], + hummingbird_pattern: str = DEFAULT_HUMMINGBIRD_RELEASE_PATTERN, ) -> list[str]: """Verify GNOME contract packages for required major version and release identity.""" errors: list[str] = [] @@ -124,7 +131,7 @@ def verify_gnome_packages( f"GNOME package '{pkg}' version '{ver}' does not match required major version '{exp_maj}'" ) # Release identity must match factory (.hum1.bfin) or Hummingbird (.hum) - if not re.search(r"\.hum\d*(\.bfin)?", rel): + if not re.search(hummingbird_pattern, rel): errors.append( f"GNOME package '{pkg}' release '{rel}' does not match expected factory/Hummingbird release identity" ) @@ -138,6 +145,7 @@ def verify_gnome_packages( def verify_factory_packages( factory_pkgs: list[str], pkg_map: dict[str, dict[str, str]], + factory_pattern: str = DEFAULT_FACTORY_RELEASE_PATTERN, ) -> list[str]: """Ensure Bluefin parity packages expected from factory carry .bfin and did not silently resolve from base repos.""" errors: list[str] = [] @@ -146,7 +154,7 @@ def verify_factory_packages( if not info: continue rel = info["release"] - if not re.search(r"\.bfin", rel): + if not re.search(factory_pattern, rel): errors.append( f"Bluefin parity package '{pkg}' expected from factory (.bfin), but resolved with release '{rel}' (silent repository fallback)" ) @@ -317,12 +325,6 @@ def retain_provenance_report( output_path.parent.mkdir(parents=True, exist_ok=True) report_json = json.dumps(report, indent=2) + "\n" output_path.write_text(report_json) - for alias in ("package-origins.json", "nevra-report.json"): - alias_path = output_path.with_name(alias) - try: - alias_path.write_text(report_json) - except OSError: - pass print( f"Retained resolved package-origin/NEVRA report at {output_path} " f"({len(packages_list)} packages: {summary_counts['factory_packages']} factory rebuilds, " @@ -377,6 +379,14 @@ def main() -> int: raw_allowlist = overlay_data.get("repositories", {}).get("allowlist", DEFAULT_ALLOWED_REPOS) repo_allowlist = set(raw_allowlist) + supply_chain_cfg = overlay_data.get("supply_chain", {}) + factory_release_pattern = supply_chain_cfg.get( + "factory_release_pattern", DEFAULT_FACTORY_RELEASE_PATTERN + ) + hummingbird_release_pattern = supply_chain_cfg.get( + "hummingbird_release_pattern", DEFAULT_HUMMINGBIRD_RELEASE_PATTERN + ) + print( f"Verifying {len(bluefin)} Bluefin packages, {len(gnome)} GNOME desktop packages," f" {len(services)} desktop service packages, and {len(nvidia)} NVIDIA packages", @@ -414,11 +424,13 @@ def main() -> int: # Acceptance Criterion 1: GNOME contract package version & release identity validation_errors: list[str] = [] - gnome_errors = verify_gnome_packages(gnome, pkg_map, expected_gnome_majors) + gnome_errors = verify_gnome_packages( + gnome, pkg_map, expected_gnome_majors, hummingbird_release_pattern + ) validation_errors.extend(gnome_errors) # Acceptance Criterion 2: Bluefin parity packages expected from factory cannot silently resolve elsewhere - factory_errors = verify_factory_packages(factory_pkgs, pkg_map) + factory_errors = verify_factory_packages(factory_pkgs, pkg_map, factory_release_pattern) validation_errors.extend(factory_errors) # Acceptance Criterion 3: Final repository allowlist fails on Fedora or unapproved repos From 3d08df289ec8a53b5441af14be586eadd008771c Mon Sep 17 00:00:00 2001 From: Danathar Date: Mon, 14 Sep 2026 14:15:57 +0000 Subject: [PATCH 3/3] supply-chain: keep .bfin the factory marker, and test the wired patterns Review on #68 found the pattern move changed runtime behaviour and the tests could not see it. Both halves are right. The behaviour change: `DEFAULT_FACTORY_RELEASE_PATTERN` is `\.bfin`, but the TOML value I moved it to was `.*\.hum\d*\.bfin.*`, which additionally requires a `.hum` segment. Under `re.search` that is strictly tighter, so a factory RPM tagged `.bfin` without a Hummingbird segment went from passing to being reported as a "silent repository fallback" -- a false accusation about a package that came from exactly where it was supposed to. Today's artifacts are all `1.hum1.bfin`, so this was latent, not live. This was meant to be a mechanical move, so the fix is to restore the equivalence rather than keep the tightening: the TOML factory pattern is now `.*\.bfin.*`, which classifies every release identically to the Python default. `.bfin` is what "came from the factory" means; `.hum` is a separate fact with its own pattern. The comment in utah.toml now says so, so the next person does not re-tighten it by accident. If the stricter contract is actually wanted, that is a deliberate change with its own justification, not a side effect of moving a constant into data. Why the tests missed it: every factory/Hummingbird test calls the verify helpers positionally, which takes the Python default -- while main() takes the TOML value. The suite was green on a regex the program does not use, so the "a dist-tag convention change is a data edit" claim was unverified by anything. TestDeclaredReleasePatterns loads packages/utah.toml and asserts on what it declares, which is the contract rather than the constant: - the declared patterns accept `1.hum1.bfin` AND the bare `.bfin` form - they reject base-repo releases (`1.hum1`, `1.fc44`, `2.el9`) - they are not catch-alls -- a typo matching everything fails OPEN under re.search, so asserting they REJECT something is what separates a live gate from a decorative one - declared and default classify a 9-release table identically, so the answer cannot depend on whether the TOML was readable - one end-to-end case through verify_factory_packages on `1.bfin`, the release the two patterns disagreed about Verified non-vacuous: restoring the tightened pattern fails 3 of them, a `.*` catch-all fails 3, and a typo in the TOML key fails 5. python3 -m unittest discover -s tests: 15 tests, OK (was 10). Refs #68 Signed-off-by: Danathar --- packages/utah.toml | 11 ++- tests/unit/test_verify_rpm_contract.py | 119 +++++++++++++++++++++++++ 2 files changed, 129 insertions(+), 1 deletion(-) diff --git a/packages/utah.toml b/packages/utah.toml index 051d1488..ec1735df 100644 --- a/packages/utah.toml +++ b/packages/utah.toml @@ -171,7 +171,16 @@ report_path = "/usr/share/utah/package-provenance.json" # pattern here rather than in scripts/verify-rpm-contract.py -- the two repos' # release-identity conventions must move together, and this is the one place # that should need editing when they do. -factory_release_pattern = '.*\.hum\d*\.bfin.*' +# +# The factory marker is `.bfin` ALONE, deliberately. Today every factory +# artifact is also tagged `.hum`, so `.*\.hum\d*\.bfin.*` would match all +# of them -- but it would additionally REJECT a factory RPM tagged `.bfin` +# without a Hummingbird segment, reporting it as a "silent repository +# fallback" when it came from exactly where it was supposed to. That is a +# false accusation waiting for the first artifact that does not carry both +# tags. `.bfin` is what "came from the factory" means; `.hum` is a separate +# fact with its own pattern below. Keep them separate. +factory_release_pattern = '.*\.bfin.*' hummingbird_release_pattern = '.*\.hum\d*.*' diff --git a/tests/unit/test_verify_rpm_contract.py b/tests/unit/test_verify_rpm_contract.py index 0f7c193d..7e01516a 100644 --- a/tests/unit/test_verify_rpm_contract.py +++ b/tests/unit/test_verify_rpm_contract.py @@ -3,6 +3,7 @@ import importlib.util import json +import re import subprocess import sys import tempfile @@ -226,5 +227,123 @@ def test_cli_check_mode(self): self.assertIn("RPM contract syntax and supply-chain policy is valid", res.stdout) +class TestDeclaredReleasePatterns(unittest.TestCase): + """The patterns as `main()` actually reads them, not as the defaults spell them. + + The gap this closes: every other factory/Hummingbird test calls the verify + helpers positionally, which takes the Python default -- while production + takes the value out of `packages/utah.toml`. A suite green on a regex the + program does not use cannot see a TOML edit at all, which makes the whole + "a dist-tag convention change is a data edit" claim unverified. + + So these load the committed TOML and assert on what it declares. + """ + + @staticmethod + def _declared() -> dict: + """Return the [supply_chain] block exactly as main() reads it.""" + + import tomllib + + with (REPO_ROOT / "packages" / "utah.toml").open("rb") as handle: + return tomllib.load(handle).get("supply_chain", {}) + + def test_declared_patterns_are_present_and_not_catch_alls(self): + """A typo that matches everything disables the gate while looking set. + + `re.search` on a malformed-but-valid pattern fails OPEN: it matches, so + every package passes and no error is ever raised. Asserting the + patterns REJECT something is what separates a live gate from a + decorative one. + """ + + declared = self._declared() + for key in ("factory_release_pattern", "hummingbird_release_pattern"): + pattern = declared.get(key) + self.assertIsNotNone(pattern, f"{key} is not declared in utah.toml") + self.assertIsNone( + re.search(pattern, "1.fc44"), + f"{key} matches a plain Fedora release, so it gates nothing", + ) + + def test_declared_factory_pattern_accepts_current_artifacts(self): + """Today's factory releases, and the bare `.bfin` form, both pass.""" + + pattern = self._declared()["factory_release_pattern"] + for release in ("1.hum1.bfin", "1.hum1.bfin.fc44", "1.bfin", "1.bfin.fc44"): + self.assertIsNotNone( + re.search(pattern, release), + f"factory pattern rejects {release!r}; `.bfin` is the factory " + "marker, and requiring `.hum` beside it reports a genuine " + "factory build as a silent repository fallback", + ) + + def test_declared_factory_pattern_rejects_base_repo_releases(self): + """A package that resolved from a base repo is what the gate is for.""" + + pattern = self._declared()["factory_release_pattern"] + for release in ("1.hum1", "1.fc44", "2.el9"): + self.assertIsNone( + re.search(pattern, release), + f"factory pattern accepts {release!r}, which carries no .bfin", + ) + + def test_declared_patterns_agree_with_the_python_defaults(self): + """The wired value and the fallback must classify releases identically. + + Not string equality -- two spellings of the same rule are fine. What is + not fine is the two disagreeing about a release, because then the + answer depends on whether the TOML was readable, and a test calling the + helper positionally proves nothing about production. + """ + + declared = self._declared() + releases = [ + "1.hum1.bfin", + "1.hum1.bfin.fc44", + "1.bfin", + "1.bfin.fc44", + "1.fc44.bfin", + "1.hum1", + "1.hum2", + "1.fc44", + "2.el9", + ] + pairs = ( + ("factory_release_pattern", mod.DEFAULT_FACTORY_RELEASE_PATTERN), + ("hummingbird_release_pattern", mod.DEFAULT_HUMMINGBIRD_RELEASE_PATTERN), + ) + for key, default in pairs: + for release in releases: + self.assertEqual( + bool(re.search(declared[key], release)), + bool(re.search(default, release)), + f"{key} and its Python default disagree about {release!r}", + ) + + def test_factory_verification_uses_the_declared_pattern(self): + """The wired path, end to end, on a release only one pattern accepts.""" + + pattern = self._declared()["factory_release_pattern"] + pkg_map = { + "fastfetch": { + "name": "fastfetch", + "epoch": "0", + "version": "2.21.3", + "release": "1.bfin", + "arch": "x86_64", + "sourcerpm": "fastfetch-2.21.3-1.bfin.src.rpm", + "vendor": "projectbluefin", + "nevra": "fastfetch-0:2.21.3-1.bfin.x86_64", + } + } + self.assertEqual( + mod.verify_factory_packages(["fastfetch"], pkg_map, pattern), + [], + "a factory RPM tagged .bfin without .hum is a genuine factory " + "build and must not be reported as a repository fallback", + ) + + if __name__ == "__main__": unittest.main()