From 55ea30552805a32f8ca5693b453f86b590cec952 Mon Sep 17 00:00:00 2001 From: Aleksei Selikhov Date: Thu, 3 Dec 2026 13:20:31 +0300 Subject: [PATCH] feat(provenance): emit deterministic SPDX and CycloneDX SBOMs - New Provenance::Sbom module generating SPDX 2.3 / CycloneDX 1.5 from lockfile packages + BuildGraph outputs - Wire vbs build|test --sbom FILE --sbom-format spdx|cyclonedx - Register the module in CMake, build.cpp and the self-host recipe - Ed25519 signing requested upstream as Void/Library#36 (VL-014) - Verified in Docker GCC 16: 8/8 CTest suites; deterministic JSON unit test + CLI SBOM assertion --- CMakeLists.txt | 1 + README.md | 2 +- build.cpp | 1 + docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md | 2 + docs/agent-workflow/STATE.md | 10 +- docs/agent-workflow/TASKS.md | 3 +- docs/agent-workflow/VERIFICATION.md | 18 +++ docs/roadmap/21-expansion-roadmap.md | 4 +- include/Void/Build/Provenance/Sbom.hpp | 47 ++++++ recipes/SelfHost/VbsSelfHostRecipe.cpp | 1 + src/Main.cpp | 78 ++++++++++ src/Provenance/Sbom.cpp | 204 +++++++++++++++++++++++++ tests/FullV1Tests.cpp | 40 ++++- 13 files changed, 403 insertions(+), 8 deletions(-) create mode 100644 include/Void/Build/Provenance/Sbom.hpp create mode 100644 src/Provenance/Sbom.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 301e809..59376f7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -59,6 +59,7 @@ add_library(VoidBuild_Core STATIC src/Bridge/CMakeBridge.cpp src/Modules/ModuleScanner.cpp src/SelfHost/TestRegistryGen.cpp + src/Provenance/Sbom.cpp recipes/VoidLibrary/VoidLibraryRecipe.cpp recipes/SelfHost/VbsSelfHostRecipe.cpp) add_library(Void::BuildCore ALIAS VoidBuild_Core) diff --git a/README.md b/README.md index c75c70c..f4e9ff2 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,7 @@ All CLI help text (`vbs --help`, `vbs --help`, `vbs compdb --help`, `v - `vbs [--version] [--verbose] [--quiet] ` - `vbs init [--dir DIR] [--name NAME] [--library] [--with-toml] [--force]` -- `vbs build [--project DIR] [--build-dir DIR] [--profile NAME]... [--target NAME]... [--compiler gcc|clang] [--editor-profile NAME] [--build-source FILE]... [--jobs N] [--member PKG]... [--changed-since REF] [--remote-cache URL] [--remote-cache-token-env VAR] [--locked] [--offline] [--no-cache] [--native-foreign] [--verbose] [--quiet]` +- `vbs build [--project DIR] [--build-dir DIR] [--profile NAME]... [--target NAME]... [--compiler gcc|clang] [--editor-profile NAME] [--build-source FILE]... [--jobs N] [--member PKG]... [--changed-since REF] [--sbom FILE] [--sbom-format spdx|cyclonedx] [--remote-cache URL] [--remote-cache-token-env VAR] [--locked] [--offline] [--no-cache] [--native-foreign] [--verbose] [--quiet]` - `vbs test ...` (same flags as `vbs build`, then runs selected `TargetKind::Test` binaries) - `vbs clean [--build-dir DIR] [--all]` - `vbs doctor` diff --git a/build.cpp b/build.cpp index 3034e3d..558e271 100644 --- a/build.cpp +++ b/build.cpp @@ -47,6 +47,7 @@ void build(Void::Build::Project &project) { "src/Bridge/CMakeBridge.cpp", "src/Modules/ModuleScanner.cpp", "src/SelfHost/TestRegistryGen.cpp", + "src/Provenance/Sbom.cpp", "recipes/VoidLibrary/VoidLibraryRecipe.cpp", "recipes/SelfHost/VbsSelfHostRecipe.cpp", }) diff --git a/docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md b/docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md index 7c1e8aa..c93d15d 100644 --- a/docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md +++ b/docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md @@ -20,6 +20,7 @@ Pinned VoidLibrary revision: `3e254055e081a104f08df68dde39711bc7813518` (merged | `VL-011b` | Optional SQLite3 FetchContent (`Void::Sqlite`) | Implemented (`VOID_FETCH_SQLITE3`) | Opportunistic when system `SQLite3` is installed (`VOID_FETCH_SQLITE3=OFF` to keep offline configures fast); journaled atomic CAS store retained | | `VL-012` | Naming consistency observation | Noted | VBS strictly uses `Void::Build`, `PascalCase` types/enums/paths, `snake_case` functions/methods | | `VL-013` | Shorthand SemVer ranges (`^1.0`, `~1.2`, `>=1.2 <2`) in `Void::Semver::parse_range` | Implemented | **Adopted** (`src/Package/Solver.cpp` delegates directly to `Void::Semver::parse_range`) | +| `VL-014` | Ed25519 sign/verify primitive (`Void::Crypto`) for package/binary provenance | Not implemented upstream ([Void/Library#36](https://git.faumaray.com/Void/Library/issues/36)) | Pending: D3 signature verification waits on this primitive; VBS emits SPDX/CycloneDX SBOM provenance now | --- @@ -41,3 +42,4 @@ Pinned VoidLibrary revision: `3e254055e081a104f08df68dde39711bc7813518` (merged - **`VL-004` / `VL-005` (`Void::Net`)**: `Void::Net` in VoidLibrary still requires external `Boost` + `OpenSSL` (`src/Net/module.cmake`), which are absent in minimal `dev cpp-gcc`. VBS keeps its zero-dependency POSIX loopback `HttpServer` (`registry/service/HttpServer.cpp`) and `RegistryClient` (`src/Package/RegistryClient.cpp`) until a Boost-free/minimal-dependency transport is desired or available in the base toolchain. - **`VL-011b` (`Void::Sqlite`)**: `cmake/VoidDependency.cmake` disables network fetches during CMake configure (`VOID_FETCH_SQLITE3=OFF`) and opportunistically enables `Void::Sqlite` when system `SQLite3` is installed; `src/State/StateStore.cpp` continues providing crash-safe atomic-replace CAS persistence in minimal shells. +- **`VL-014` (Ed25519)**: `Void::Crypto` currently exposes only hashing (SHA-256/BLAKE2b). D3 SBOM emission is implemented in `src/Provenance/Sbom.cpp`, but package/binary signature verification is not faked with a weaker scheme: it waits for the upstream Ed25519 primitive requested in [Void/Library#36](https://git.faumaray.com/Void/Library/issues/36). diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index dc40a24..b03f63f 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -2,7 +2,7 @@ Updated: 2026-12-03 Branch: main -Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B1–B3) + Track E1 + `vbs ide` & `build.cpp` CompDB integration + Track D1/D2 + Track E2 (Docker GCC 16) complete +Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B1–B3) + Track E1 + `vbs ide` & `build.cpp` CompDB integration + Track D1/D2 + Track E2 + Track D3 SBOM (Docker GCC 16) complete ## Completed delivery waves @@ -64,9 +64,15 @@ Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B - Cross-member linking resolves `workspace_dependency("lib").target("core")` to the member's native path provider through `VBS_WORKSPACE_MEMBER_`; `--member ` and `--changed-since ` select affected members. Member builds do not steal the project-root `compile_commands.json` alias, and path-dependency snapshots exclude generated editor metadata. - **Docker verification**: `FullV1Tests.workspace_members_shared_build_and_member_selection` builds a 3-member workspace (shared library + app + test) with a unified root lockfile, runs the app, selects a single member, and selects by changed file; all 8 CTest suites pass. +- **Wave 13 (Track D3 SBOM Provenance)**: + - Added `include/Void/Build/Provenance/Sbom.hpp` + `src/Provenance/Sbom.cpp` with deterministic SPDX 2.3 and CycloneDX 1.5 JSON generation from lockfile packages and `BuildGraph` target outputs (content-derived namespace/serial and epoch timestamp). + - Wired `vbs build|test --sbom FILE --sbom-format spdx|cyclonedx` in `src/Main.cpp`, writing per-profile files when multiple profiles are selected. + - Ed25519 package/binary signing remains blocked on an upstream `Void::Crypto` primitive, filed as [Void/Library#36](https://git.faumaray.com/Void/Library/issues/36) and tracked as `VL-014`. + - **Docker verification**: `FullV1Tests.sbom_spdx_and_cyclonedx_are_deterministic_and_valid_json` plus a CLI `--sbom` assertion in the workspace test; full CTest suite passes. + ## Remaining future scope -- **Post-v1 Expansion Roadmap ([21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md) & [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Live `conan` CLI verification (Track B3), Track C (macOS/Windows ports + dual-profile cross-compilation), Track D1/D2 acceptance scenarios (suites pass; cache-hit/benchmark pending), Track D3 (SBOM/signatures), Track E3 (`vbs daemon` local socket server + external editor plugins), and Track E4 (`Void::Net`/`Void::Sqlite` alignment) remain planned scope. +- **Post-v1 Expansion Roadmap ([21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md) & [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Live `conan` CLI verification (Track B3), Track C (macOS/Windows ports + dual-profile cross-compilation), Track D3 signing (SBOM done; upstream Ed25519 pending), Track E3 (`vbs daemon` local socket server + external editor plugins), and Track E4 (`Void::Net`/`Void::Sqlite` alignment) remain planned scope. ## Environment notes & upstream boundaries diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index 9f7f483..4ee03ed 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -19,4 +19,5 @@ Base HEAD: `fe0d1a6` | Wave 10 (Track B [B1–B3] + First-Class `vbs ide` Integration) | Native C driver (`CStandard`) & mixed C/C++ CMake/Meson translation (`PerFileOption`); bounded `build.ninja` `CUSTOM_COMMAND` translation (`CustomAction`); foreign CMake `CXX_MODULES` `fileSets` & cross-target `module_bmis` + Clang `default_include_dirs`; `build.cpp` SDK CompDB indexing + `vbs ide generate\|query` | COMPLETE & VERIFIED | `include/Void/Build.hpp`, `Driver.{hpp,cpp}`, `ModuleScanner.{hpp,cpp}`, `Graph.{hpp,cpp}`, `CompDb.{hpp,cpp}`, `Provider.cpp`, `Translator.{hpp,cpp}`, `Watcher.cpp`, `Main.cpp`, `tests/{FullV1Tests.cpp,CliContracts.cmake}`, docs | | Wave 11 (Track D1–D2) | Shared HTTP CAS action cache (`/api/v1/cas/{blobs,actions}`, bearer auth, digest verification, portable action keys, `--remote-cache`) + parallel snapshot revalidation hashing | COMPLETE & VERIFIED (Docker GCC 16.0.1, pinned VoidLibrary, 8/8 CTest suites; D1 cross-build-dir 100% cache hit; D2 5,001-file warm no-op 374 ms) | `include/Void/Build/State/RemoteCache.hpp`, `src/State/RemoteCache.cpp`, `StateStore.{hpp,cpp}`, `Scheduler.cpp`, `Snapshot.cpp`, `registry/service/RegistryService.cpp`, `src/Main.cpp`, `tests/RegistryTests.cpp`, docs | | Wave 12 (Track E2 Workspaces) | `workspace.cpp` member declaration/evaluation, shared root `vbs.lock` + `build/.vbs` CAS, `workspace_dependency()` cross-member native linking, `--member` and `--changed-since` selection | COMPLETE & VERIFIED (Docker GCC 16.0.1, 8/8 CTest suites; 3-member fixture with unified lockfile) | `include/Void/Build.hpp`, `src/Build.cpp`, `Config/Frontend.{hpp,cpp}`, `src/Main.cpp`, `src/Package/Fetch.cpp`, `tests/FullV1Tests.cpp`, docs | -| Future (Plan 20 Slice 3 / Tracks C–D, E3 daemon, E4, live `conan`) | Live `conan` CLI verification; macOS/Windows/cross-compile; SBOM/signatures; `vbs daemon`, `Void::Net`/`Void::Sqlite` alignment | PLANNED (unimplemented) | [21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md), [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md) | +| Wave 13 (Track D3 SBOM) | Deterministic SPDX 2.3 / CycloneDX 1.5 SBOM from `vbs.lock` packages + `BuildGraph` outputs; `vbs build\|test --sbom FILE --sbom-format spdx\|cyclonedx`; Ed25519 signing blocked upstream | SBOM COMPLETE & VERIFIED (Docker GCC 16, 8/8 CTest suites); signing pending [Void/Library#36](https://git.faumaray.com/Void/Library/issues/36) | `include/Void/Build/Provenance/Sbom.hpp`, `src/Provenance/Sbom.cpp`, `src/Main.cpp`, `tests/FullV1Tests.cpp`, docs | +| Future (Plan 20 Slice 3 / Tracks C, D3 signing, E3 daemon, E4, live `conan`) | Live `conan` CLI verification; macOS/Windows/cross-compile; signed provenance; `vbs daemon`, `Void::Net`/`Void::Sqlite` alignment | PLANNED (unimplemented) | [21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md), [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md) | diff --git a/docs/agent-workflow/VERIFICATION.md b/docs/agent-workflow/VERIFICATION.md index bc22d6e..6685dac 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -173,6 +173,24 @@ declared by a root `workspace.cpp`: Full suite after the change: **8 / 8 CTest suites passed** in 800.22 s (`vbs_v1_tests` 170.33 s, `vbs_registry_tests` 36.82 s, `vbs_selfhost_tests` 568.05 s). +## Track D3 SBOM Provenance in Docker (2026-12-03) + +`src/Provenance/Sbom.cpp` emits deterministic SPDX 2.3 and CycloneDX 1.5 JSON from lockfile +packages plus `BuildGraph` target outputs, wired as +`vbs build|test --sbom FILE --sbom-format spdx|cyclonedx`. The document namespace/serial is +derived from the input content and the timestamp from the reproducibility epoch, so identical +inputs are byte-equal. + +- `FullV1Tests.sbom_spdx_and_cyclonedx_are_deterministic_and_valid_json`: both formats parse as + strict JSON, contain the package/file entries, and repeated generation is byte-identical. +- The workspace CLI test runs `vbs build --member app --sbom app.cdx.json --sbom-format cyclonedx` + and verifies the emitted file contains CycloneDX. +- Full suite: **8 / 8 CTest suites passed** in 471.56 s. + +Ed25519 package/binary signing is **not** implemented: `Void::Crypto` has no Ed25519 primitive. +It is requested upstream as [Void/Library#36](https://git.faumaray.com/Void/Library/issues/36) +(`VL-014`) rather than faked with a weaker scheme. + ## Limits and Unrun Checks 1. **HTTPS git fetch**: the host shell is proxy-restricted, but the Docker container could clone `https://git.faumaray.com/Void/VoidLibrary.git`; the pinned commit `3e254055e081a104f08df68dde39711bc7813518` was fetched directly for the verification above. A separate configure against the local `/home/faumaray/Projects/Library` checkout via `VBS_VOID_SOURCE_DIR` also succeeded (development-only override, checkout unmodified). diff --git a/docs/roadmap/21-expansion-roadmap.md b/docs/roadmap/21-expansion-roadmap.md index d41b0d8..5972e60 100644 --- a/docs/roadmap/21-expansion-roadmap.md +++ b/docs/roadmap/21-expansion-roadmap.md @@ -1,6 +1,6 @@ # 21 — Post-v1 Expansion Roadmap -Status: Active execution guide (Plans **01–19**, **Plan 20 Slices 1–2C**, **Track A [A1–A3]**, **Track B [B1–B3, except live `conan` CLI container]**, **Track E1**, and **Track E3 IDE config/query tooling** are implemented and verified; **Track D1/D2** are implemented and verified in Docker GCC 16 (D1 cross-build-directory 100% cache hit; D2 5,001-file warm no-op 374 ms); **Track E2 (`workspace.cpp`)** is implemented and verified in Docker GCC 16; **Track C**, **Track D3**, **Track E3 (`vbs daemon`)**, **Track E4**, and live `conan` CLI verification remain planned; see [STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)). +Status: Active execution guide (Plans **01–19**, **Plan 20 Slices 1–2C**, **Track A [A1–A3]**, **Track B [B1–B3, except live `conan` CLI container]**, **Track E1**, and **Track E3 IDE config/query tooling** are implemented and verified; **Track D1/D2** are implemented and verified in Docker GCC 16 (D1 cross-build-directory 100% cache hit; D2 5,001-file warm no-op 374 ms); **Track E2 (`workspace.cpp`)** is implemented and verified in Docker GCC 16; **Track D3** SBOM emission is implemented (Ed25519 signing pending [Void/Library#36](https://git.faumaray.com/Void/Library/issues/36)); **Track C**, **Track E3 (`vbs daemon`)**, **Track E4**, and live `conan` CLI verification remain planned; see [STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)). This roadmap defines five orthogonal expansion tracks for taking VoidBuildSystem from a verified self-hosting Linux C++26 build system into a multi-platform, distributed, daily-driver ecosystem. Each track preserves core architectural invariants: ordinary C++ descriptions, hermetic content-verified snapshots, isolated profiles, immutable CAS publication, and explicit diagnostics over silent approximation. @@ -61,7 +61,7 @@ flowchart LR | --- | --- | --- | | **D1 — Shared HTTP Content-Addressed Action Cache (CAS)** *(verified: cross-build-directory 100% cache hit)* | Push/pull action records and output blobs (`PUT/GET /api/v1/cas/blobs/{sha256}`, `/api/v1/cas/actions/{action_key}`) against `vbs-registry` or any compatible HTTP CAS server with bearer auth and digest verification on every read. Action keys are normalized to be build-directory independent; `vbs build/test --remote-cache URL [--remote-cache-token-env VAR]` (or `VBS_REMOTE_CACHE` / `VBS_REMOTE_CACHE_TOKEN`). | Cold CI build populates remote CAS; second clean machine achieves 100% cache hit with verified SHA-256 outputs. | | **D2 — Fast Hashing & Parallel Snapshot Pipeline** *(verified: 5,001-file warm no-op 374 ms)* | Adopt `Void::Crypto` BLAKE2b / hardware-accelerated SHA-256 (when available) + parallel snapshot hashing across `Void::Concurrency::ThreadPool` + optional `Void::Sqlite` indexed state store for >10k-file monorepos. Snapshot capture revalidation now hashes on a bounded thread pool for trees of 32+ files. | Sub-second warm no-op on 5,000-file synthetic benchmark fixture (`vbs_benchmarks`). | -| **D3 — Supply-Chain Provenance & Signed Packages** | Emit SPDX/CycloneDX SBOM JSON from `vbs.lock` + `BuildGraph`; optional Ed25519 package & binary signature verification in `vbs publish` and `vbs build --locked`. | Tampered archive or signature fails closed before extraction. | +| **D3 — Supply-Chain Provenance & Signed Packages** *(SBOM implemented; signing pending upstream)* | Emit SPDX/CycloneDX SBOM JSON from `vbs.lock` + `BuildGraph` (`vbs build/test --sbom FILE --sbom-format spdx|cyclonedx`, `src/Provenance/Sbom.cpp`); optional Ed25519 package & binary signature verification in `vbs publish` and `vbs build --locked` waits on [Void/Library#36](https://git.faumaray.com/Void/Library/issues/36). | SBOM is deterministic and valid JSON; tampered archive or signature fails closed before extraction (signing gate pending). | --- diff --git a/include/Void/Build/Provenance/Sbom.hpp b/include/Void/Build/Provenance/Sbom.hpp new file mode 100644 index 0000000..5c20529 --- /dev/null +++ b/include/Void/Build/Provenance/Sbom.hpp @@ -0,0 +1,47 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +namespace Void::Build::Provenance { + +enum class SbomFormat { Spdx, CycloneDX }; + +[[nodiscard]] std::string_view sbom_format_name(SbomFormat format) noexcept; +[[nodiscard]] SbomFormat parse_sbom_format(std::string_view name); + +struct SbomPackage { + std::string name; + std::string version; + std::string supplier; // "NOASSERTION" when unknown. + std::string download_location; // "NOASSERTION" when unknown. + std::string sha256; + std::string purl; +}; + +struct SbomFile { + std::string path; + std::string sha256; +}; + +struct SbomInput { + std::string project_name; + std::string project_version{"0.0.0"}; + std::string tool_version; + std::int64_t created_epoch{0}; + // Lockfile-derived dependency packages and BuildGraph-derived output files. + std::vector packages; + std::vector files; +}; + +// Deterministic SPDX 2.3 or CycloneDX 1.5 JSON. The document namespace/serial is derived from +// the input content, and the timestamp from created_epoch, so identical inputs are byte-equal. +[[nodiscard]] Void::Result::Result +generate_sbom(const SbomInput &input, SbomFormat format); + +} // namespace Void::Build::Provenance diff --git a/recipes/SelfHost/VbsSelfHostRecipe.cpp b/recipes/SelfHost/VbsSelfHostRecipe.cpp index 9d0780a..5781887 100644 --- a/recipes/SelfHost/VbsSelfHostRecipe.cpp +++ b/recipes/SelfHost/VbsSelfHostRecipe.cpp @@ -99,6 +99,7 @@ add_vbs_selfhost_native(Project &project, const VbsSelfHostConfig &config) { "src/Bridge/CMakeBridge.cpp", "src/Modules/ModuleScanner.cpp", "src/SelfHost/TestRegistryGen.cpp", + "src/Provenance/Sbom.cpp", "recipes/VoidLibrary/VoidLibraryRecipe.cpp", "recipes/SelfHost/VbsSelfHostRecipe.cpp", }; diff --git a/src/Main.cpp b/src/Main.cpp index 3c2e5cc..4080a34 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -507,6 +508,8 @@ struct BuildCmdOptions { std::optional remote_cache_token_env; std::vector members; std::optional changed_since; + std::optional sbom_arg; + std::optional sbom_format_arg; std::optional lock_root; std::optional state_dir; bool publish_editor_selection{true}; @@ -856,6 +859,78 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { std::cout << "vbs: [" << prof_name << "] built (" << rep->executed_count << " executed, " << rep->cached_count << " cached)\n"; + if (opts.sbom_arg) { + Provenance::SbomInput sbom; + sbom.project_name = project_root.filename().string(); + sbom.tool_version = std::string{Bootstrap::version}; + sbom.created_epoch = ctx.reproducibility_epoch; + const auto sbom_ctx_key = Package::make_lock_context_key(ctx, "target"); + if (pinned_lock && pinned_lock->has_value()) { + const auto &document = (*pinned_lock)->document; + if (const auto it = document.contexts.find(sbom_ctx_key); + it != document.contexts.end()) { + for (const auto &entry : it->second.entries) { + if (entry.version.empty()) { + continue; + } + Provenance::SbomPackage package; + package.name = + entry.package_name.empty() ? entry.alias : entry.package_name; + package.version = entry.version; + package.download_location = entry.registry_authority.empty() + ? entry.location + : entry.registry_authority; + package.sha256 = entry.sha256; + package.purl = "pkg:generic/" + package.name + "@" + package.version; + sbom.packages.push_back(std::move(package)); + } + } + } + for (const auto &target : graph->targets) { + for (const auto &output : target.primary_outputs) { + auto digest = Util::sha256_file_hex(output); + if (!digest) { + continue; + } + Provenance::SbomFile file; + file.path = Platform::path_is_within(project_root, output) + ? output.lexically_relative(project_root).generic_string() + : output.filename().string(); + file.sha256 = std::move(*digest); + sbom.files.push_back(std::move(file)); + } + } + try { + const auto format = opts.sbom_format_arg + ? Provenance::parse_sbom_format(*opts.sbom_format_arg) + : Provenance::SbomFormat::Spdx; + auto generated = Provenance::generate_sbom(sbom, format); + if (!generated) { + std::cerr << "vbs: SBOM generation failed: " << generated.error().message() + << '\n'; + all_ok = false; + continue; + } + std::filesystem::path sbom_path{*opts.sbom_arg}; + if (opts.profiles.size() > 1) { + sbom_path = + sbom_path.parent_path() / (sbom_path.stem().string() + "." + prof_name + + sbom_path.extension().string()); + } + if (auto wrote = Platform::atomic_write_file(sbom_path, *generated, true); !wrote) { + std::cerr << "vbs: failed writing SBOM: " << wrote.error().message() << '\n'; + all_ok = false; + continue; + } + Void::Log::info("Sbom", "[{}] Wrote {} SBOM to {}", prof_name, + Provenance::sbom_format_name(format), sbom_path.string()); + } catch (const std::exception &ex) { + std::cerr << "vbs: " << ex.what() << '\n'; + all_ok = false; + continue; + } + } + if (run_tests) { for (const auto &t : graph->targets) { if (t.kind != TargetKind::Test || t.primary_outputs.empty()) { @@ -2131,6 +2206,9 @@ int main(int argc, char **argv) { .option_many("--member", "", "Workspace member to build/test", build_opts.members) .option("--changed-since", "", "Build/test workspace members changed since a git ref", build_opts.changed_since) + .option("--sbom", "", "Write an SBOM after a successful build", build_opts.sbom_arg) + .option("--sbom-format", "", "SBOM format: spdx (default) or cyclonedx", + build_opts.sbom_format_arg) .option("--remote-cache", "", "Shared HTTP action cache URL (or VBS_REMOTE_CACHE)", build_opts.remote_cache_arg) .option("--remote-cache-token-env", "", diff --git a/src/Provenance/Sbom.cpp b/src/Provenance/Sbom.cpp new file mode 100644 index 0000000..01aac89 --- /dev/null +++ b/src/Provenance/Sbom.cpp @@ -0,0 +1,204 @@ +#include + +#include +#include + +#include +#include +#include +#include +#include + +namespace Void::Build::Provenance { +namespace { + +using Util::json_array; +using Util::json_quote; + +std::string iso8601(std::int64_t epoch) { + const auto time = static_cast(epoch); + std::tm tm{}; + ::gmtime_r(&time, &tm); + char buffer[32]; + (void)std::strftime(buffer, sizeof(buffer), "%Y-%m-%dT%H:%M:%SZ", &tm); + return buffer; +} + +std::string purl_for(const SbomPackage &package) { + if (!package.purl.empty()) { + return package.purl; + } + return "pkg:generic/" + package.name + "@" + package.version; +} + +// Deterministic UUID-shaped serial derived from a hex digest (version 4 nibble). +std::string uuid_from_hex(std::string_view hex) { + const std::string h{hex}; + if (h.size() < 32) { + return "00000000-0000-4000-8000-000000000000"; + } + return std::format("{}-{}-4{}-8{}-{}", h.substr(0, 8), h.substr(8, 4), h.substr(13, 3), + h.substr(17, 3), h.substr(20, 12)); +} + +std::string document_identity(const SbomInput &input) { + Util::Sha256Hasher hasher; + hasher.update_length_prefixed("vbs-sbom-v1"); + hasher.update_length_prefixed(input.project_name); + hasher.update_length_prefixed(input.project_version); + hasher.update_length_prefixed(input.tool_version); + hasher.update_u64(input.packages.size()); + for (const auto &package : input.packages) { + hasher.update_length_prefixed(package.name); + hasher.update_length_prefixed(package.version); + hasher.update_length_prefixed(package.sha256); + hasher.update_length_prefixed(purl_for(package)); + } + hasher.update_u64(input.files.size()); + for (const auto &file : input.files) { + hasher.update_length_prefixed(file.path); + hasher.update_length_prefixed(file.sha256); + } + return hasher.finalize_hex(); +} + +std::string checksum_json(std::string_view sha256, std::string_view algorithm_key, + std::string_view value_key) { + return "{\"" + std::string{algorithm_key} + "\":" + json_quote("SHA256") + ",\"" + + std::string{value_key} + "\":" + json_quote(sha256) + '}'; +} + +std::string spdx(const SbomInput &input, std::string_view identity) { + std::string out = + "{\n \"spdxVersion\": \"SPDX-2.3\",\n \"dataLicense\": \"CC0-1.0\",\n" + " \"SPDXID\": \"SPDXRef-DOCUMENT\",\n \"name\": " + + json_quote(input.project_name + "-sbom") + ",\n \"documentNamespace\": " + + json_quote("https://voidbuild.dev/spdx/" + std::string{identity}) + + ",\n \"creationInfo\": {\"created\": " + json_quote(iso8601(input.created_epoch)) + + ", \"creators\": [" + json_quote("Tool: vbs-" + input.tool_version) + + "]},\n \"packages\": [\n"; + + out += + " {\"SPDXID\": \"SPDXRef-Package-Root\", \"name\": " + json_quote(input.project_name) + + ", \"versionInfo\": " + json_quote(input.project_version) + + ", \"downloadLocation\": \"NOASSERTION\", \"filesAnalyzed\": false, " + "\"supplier\": \"NOASSERTION\", \"licenseConcluded\": \"NOASSERTION\"}"; + + for (std::size_t i = 0; i < input.packages.size(); ++i) { + const auto &package = input.packages[i]; + out += ",\n {\"SPDXID\": " + json_quote(std::format("SPDXRef-Package-{}", i)) + + ", \"name\": " + json_quote(package.name) + + ", \"versionInfo\": " + json_quote(package.version) + ", \"downloadLocation\": " + + json_quote(package.download_location.empty() ? "NOASSERTION" + : package.download_location) + + ", \"filesAnalyzed\": false, \"supplier\": " + + json_quote(package.supplier.empty() ? "NOASSERTION" : package.supplier) + + ", \"licenseConcluded\": \"NOASSERTION\", \"checksums\": [" + + checksum_json(package.sha256, "algorithm", "checksumValue") + + "], \"externalRefs\": [{\"referenceCategory\": \"PACKAGE-MANAGER\", " + "\"referenceType\": \"purl\", \"referenceLocator\": " + + json_quote(purl_for(package)) + "}]}"; + } + out += "\n ],\n \"files\": [\n"; + for (std::size_t i = 0; i < input.files.size(); ++i) { + const auto &file = input.files[i]; + out += " {\"SPDXID\": " + json_quote(std::format("SPDXRef-File-{}", i)) + + ", \"fileName\": " + json_quote(file.path) + ", \"checksums\": [" + + checksum_json(file.sha256, "algorithm", "checksumValue") + "]}"; + if (i + 1 != input.files.size()) { + out += ','; + } + out += '\n'; + } + out += " ],\n \"relationships\": [\n" + " {\"spdxElementId\": \"SPDXRef-DOCUMENT\", \"relationshipType\": \"DESCRIBES\", " + "\"relatedSpdxElement\": \"SPDXRef-Package-Root\"}"; + for (std::size_t i = 0; i < input.packages.size(); ++i) { + out += ",\n {\"spdxElementId\": \"SPDXRef-Package-Root\", \"relationshipType\": " + "\"DEPENDS_ON\", \"relatedSpdxElement\": " + + json_quote(std::format("SPDXRef-Package-{}", i)) + '}'; + } + for (std::size_t i = 0; i < input.files.size(); ++i) { + out += ",\n {\"spdxElementId\": \"SPDXRef-Package-Root\", \"relationshipType\": " + "\"CONTAINS\", \"relatedSpdxElement\": " + + json_quote(std::format("SPDXRef-File-{}", i)) + '}'; + } + out += "\n ]\n}\n"; + return out; +} + +std::string cyclonedx(const SbomInput &input, std::string_view identity) { + std::string out = + "{\n \"bomFormat\": \"CycloneDX\",\n \"specVersion\": \"1.5\",\n \"serialNumber\": " + + json_quote("urn:uuid:" + uuid_from_hex(identity)) + ",\n \"version\": 1,\n" + + " \"metadata\": {\"timestamp\": " + json_quote(iso8601(input.created_epoch)) + + ", \"tools\": {\"components\": [{\"type\": \"application\", \"name\": \"vbs\", " + "\"version\": " + + json_quote(input.tool_version) + + "}]}, \"component\": {\"type\": \"application\", \"name\": " + + json_quote(input.project_name) + ", \"version\": " + json_quote(input.project_version) + + "}},\n \"components\": [\n"; + + for (std::size_t i = 0; i < input.packages.size(); ++i) { + const auto &package = input.packages[i]; + out += " {\"type\": \"library\", \"bom-ref\": " + json_quote(purl_for(package)) + + ", \"name\": " + json_quote(package.name) + + ", \"version\": " + json_quote(package.version) + + ", \"purl\": " + json_quote(purl_for(package)) + ", \"hashes\": [" + + checksum_json(package.sha256, "alg", "content") + "]}"; + if (i + 1 != input.packages.size()) { + out += ','; + } + out += '\n'; + } + out += " ],\n \"dependencies\": [{\"ref\": " + + json_quote( + purl_for(SbomPackage{input.project_name, input.project_version, {}, {}, {}, {}})) + + ", \"dependsOn\": ["; + for (std::size_t i = 0; i < input.packages.size(); ++i) { + if (i != 0) { + out += ", "; + } + out += json_quote(purl_for(input.packages[i])); + } + out += "]}]\n}\n"; + return out; +} + +} // namespace + +std::string_view sbom_format_name(SbomFormat format) noexcept { + switch (format) { + case SbomFormat::Spdx: + return "spdx"; + case SbomFormat::CycloneDX: + return "cyclonedx"; + } + return "spdx"; +} + +SbomFormat parse_sbom_format(std::string_view name) { + if (name == "spdx") { + return SbomFormat::Spdx; + } + if (name == "cyclonedx" || name == "cdx") { + return SbomFormat::CycloneDX; + } + throw std::invalid_argument{"unknown SBOM format '" + std::string{name} + + "' (expected spdx or cyclonedx)"}; +} + +Void::Result::Result generate_sbom(const SbomInput &raw_input, + SbomFormat format) { + SbomInput input = raw_input; + std::ranges::sort(input.packages, [](const SbomPackage &a, const SbomPackage &b) { + return std::tie(a.name, a.version, a.sha256) < std::tie(b.name, b.version, b.sha256); + }); + std::ranges::sort(input.files, [](const SbomFile &a, const SbomFile &b) { + return std::tie(a.path, a.sha256) < std::tie(b.path, b.sha256); + }); + const std::string identity = document_identity(input); + return format == SbomFormat::Spdx ? spdx(input, identity) : cyclonedx(input, identity); +} + +} // namespace Void::Build::Provenance diff --git a/tests/FullV1Tests.cpp b/tests/FullV1Tests.cpp index ab8c77f..1bb4a79 100644 --- a/tests/FullV1Tests.cpp +++ b/tests/FullV1Tests.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -177,9 +178,14 @@ void build(Void::Build::Project &p) { Void::Testing::expect(!std::filesystem::exists(ws / "packages" / "lib" / "vbs.lock", ec)); const auto selected_build = tmp / "build_selected"; - auto selected = run_vbs({"build", "--project", ws.string(), "--build-dir", - selected_build.string(), "--member", "app"}); + const auto sbom_path = tmp / "app.cdx.json"; + auto selected = + run_vbs({"build", "--project", ws.string(), "--build-dir", selected_build.string(), + "--member", "app", "--sbom", sbom_path.string(), "--sbom-format", "cyclonedx"}); Void::Testing::expect(selected.has_value() && selected->succeeded()); + auto sbom_text = Void::FileSystem::read_file(sbom_path); + Void::Testing::expect(sbom_text.has_value() && + sbom_text->find("CycloneDX") != std::string::npos); Void::Testing::expect(std::filesystem::exists(selected_build / "members" / "app" / "profiles" / "debug" / "out" / "bin" / "ws_app")); Void::Testing::expect(!std::filesystem::exists(selected_build / "members" / "tests")); @@ -214,6 +220,36 @@ void build(Void::Build::Project &p) { } } +VOID_TEST(FullV1Tests, sbom_spdx_and_cyclonedx_are_deterministic_and_valid_json) { + Provenance::SbomInput input; + input.project_name = "demo"; + input.project_version = "1.2.3"; + input.tool_version = "0.1.0"; + input.packages.push_back({"zlib", "1.3", "", "https://example.invalid/zlib", + std::string(64, 'a'), "pkg:generic/zlib@1.3"}); + input.files.push_back({"out/bin/demo", std::string(64, 'b')}); + + auto spdx = Provenance::generate_sbom(input, Provenance::SbomFormat::Spdx); + Void::Testing::expect(spdx.has_value()); + if (!spdx) { + return; + } + Void::Testing::expect(Void::Json::Strict::parse(*spdx).has_value()); + Void::Testing::expect(spdx->find("\"SPDX-2.3\"") != std::string::npos); + Void::Testing::expect(spdx->find("zlib") != std::string::npos); + Void::Testing::expect(spdx->find("out/bin/demo") != std::string::npos); + auto spdx_again = Provenance::generate_sbom(input, Provenance::SbomFormat::Spdx); + Void::Testing::expect(spdx_again.has_value() && *spdx_again == *spdx); + + auto cdx = Provenance::generate_sbom(input, Provenance::SbomFormat::CycloneDX); + Void::Testing::expect(cdx.has_value()); + if (cdx) { + Void::Testing::expect(Void::Json::Strict::parse(*cdx).has_value()); + Void::Testing::expect(cdx->find("CycloneDX") != std::string::npos); + Void::Testing::expect(cdx->find("pkg:generic/zlib@1.3") != std::string::npos); + } +} + // === Plan 09: CompDB projection, selection ticket races, user-file preservation, recovery === VOID_TEST(FullV1Tests, compdb_projection_ticket_races_and_user_file_preservation) { Void::FileSystem::TempDir tmp{"vbs_compdb_"};