diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f1f5b8f..c475a2b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,3 +31,26 @@ jobs: benchmarks/*.cpp tests/*.cpp - name: Benchmark smoke run run: build/ci-gcc/bin/vbs_benchmarks 15 + + signing-openssl-gcc16: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Install OpenSSL headers + run: sudo apt-get update && sudo apt-get install -y libssl-dev + - name: Configure (Debug, Ninja, GCC 16 C++26, OpenSSL) + run: | + cmake -S . -B build/ci-openssl -G Ninja \ + -DCMAKE_BUILD_TYPE=Debug \ + -DCMAKE_CXX_COMPILER=g++-16 \ + -DCMAKE_EXPORT_COMPILE_COMMANDS=ON + - name: Build vbs_v1_tests + run: cmake --build build/ci-openssl --target vbs_v1_tests --parallel 4 + - name: Run Signing suite with the OpenSSL backend + run: | + output=$(build/ci-openssl/bin/vbs_v1_tests --suite Signing --no-color) + printf '%s\n' "$output" + if printf '%s\n' "$output" | grep -q 'SKIP'; then + echo "Signing checks were skipped: the OpenSSL backend was not enabled" >&2 + exit 1 + fi diff --git a/CMakeLists.txt b/CMakeLists.txt index 06f2411..a989d9c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -61,12 +61,14 @@ add_library(VoidBuild_Core STATIC src/Modules/ModuleScanner.cpp src/SelfHost/TestRegistryGen.cpp src/Provenance/Sbom.cpp + src/Provenance/Signing.cpp recipes/VoidLibrary/VoidLibraryRecipe.cpp recipes/SelfHost/VbsSelfHostRecipe.cpp) add_library(Void::BuildCore ALIAS VoidBuild_Core) target_include_directories(VoidBuild_Core PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include" "${CMAKE_CURRENT_SOURCE_DIR}/recipes") +target_include_directories(VoidBuild_Core PRIVATE "${PROJECT_BINARY_DIR}/generated") target_link_libraries(VoidBuild_Core PUBLIC Void::BuildSdk Void::Configuration diff --git a/build.cpp b/build.cpp index 466a8c4..206991e 100644 --- a/build.cpp +++ b/build.cpp @@ -49,11 +49,13 @@ void build(Void::Build::Project &project) { "src/Modules/ModuleScanner.cpp", "src/SelfHost/TestRegistryGen.cpp", "src/Provenance/Sbom.cpp", + "src/Provenance/Signing.cpp", "recipes/VoidLibrary/VoidLibraryRecipe.cpp", "recipes/SelfHost/VbsSelfHostRecipe.cpp", }) .include_directory("include", Void::Build::Visibility::Public) .include_directory("recipes", Void::Build::Visibility::Public) + .include_directory("$GEN/include", Void::Build::Visibility::Private) .define("VBS_HAS_VOID_CRYPTO=1", Void::Build::Visibility::Public) .define("VBS_HAS_VOID_ARCHIVE=1", Void::Build::Visibility::Public) .link(sdk, Void::Build::Visibility::Public) @@ -91,6 +93,8 @@ void build(Void::Build::Project &project) { auto bootstrap_cfg = project.custom_action("GenerateBootstrapConfig"); bootstrap_cfg.command({"/bin/sh", "-c", gen_script}) .outputs({"include/Void/Build/BootstrapConfig.hpp"}); + // The generated header is a compile input of the core library. + core.depends_on(bootstrap_cfg); auto cli = project.executable("vbs"); cli.cxx_standard(Void::Build::CxxStandard::Cxx26) @@ -151,7 +155,7 @@ void build(Void::Build::Project &project) { auto v1_tests = project.test("vbs_v1_tests"); v1_tests.cxx_standard(Void::Build::CxxStandard::Cxx26) - .sources({"tests/FullV1Tests.cpp", "tests/DaemonTests.cpp"}) + .sources({"tests/FullV1Tests.cpp", "tests/DaemonTests.cpp", "tests/SigningTests.cpp"}) .depends_on(bootstrap_cfg) .depends_on(cli) .include_directory("$GEN/include", Void::Build::Visibility::Private) diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index be51c54..3fccf3e 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 + Track D3 SBOM (Docker GCC 16) + Track E3 daemon core + Track C1 Linux platform split 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) + Track D3 Ed25519 signing primitives (OpenSSL-gated) + Track E3 daemon core & bounded describe + Track C1 Linux platform split complete ## Completed delivery waves @@ -67,17 +67,17 @@ Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B - **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`. + - Added `include/Void/Build/Provenance/Signing.hpp` + `src/Provenance/Signing.cpp` + `tests/SigningTests.cpp`: Ed25519 detached-signature primitives (owner-only `0600` seed generation, public-key derivation, canonical `vbs-package-v1` message, sign/verify) capability-gated on `Void::Crypto`'s OpenSSL backend. Without OpenSSL every operation fails closed with an explicit unsupported error; signature enforcement in `vbs publish`/`vbs build --locked` and the OpenSSL-backed round-trip run remain planned. - **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. - **Wave 14 (Track E3 Unix-Socket Daemon Core, Track C1 Linux Platform Backend Split, & CMake 4.5 Feature-Carrier Translation Fix)**: - - Implemented `Void::Build::Daemon` in `include/Void/Build/Daemon/Daemon.hpp` and `src/Daemon/Daemon.cpp`: a bounded single-threaded Unix-domain-socket daemon that holds a warm `StateStore` and project `InotifyWatcher`, serves strict newline-delimited JSON requests (`ping`, `status`, `gc`, `recover`, `shutdown`), probes and replaces stale sockets, binds with `0600` permissions, recovers watcher overflow via rescan, and removes only its own socket (device/inode checked). Wired `vbs daemon run|status|stop|gc|recover` into `src/Main.cpp` and added `tests/DaemonTests.cpp` (`VOID_TEST(Daemon, ...)`) plus CLI contracts. + - Implemented `Void::Build::Daemon` in `include/Void/Build/Daemon/Daemon.hpp` and `src/Daemon/Daemon.cpp`: a bounded single-threaded Unix-domain-socket daemon that holds a warm `StateStore` and project `InotifyWatcher`, serves strict newline-delimited JSON requests (`ping`, `status`, `gc`, `recover`, `describe`, `shutdown`) with bounded `describe` graph summaries (`target_names` ≤ 128 entries × 200 bytes, `profile` ≤ 128 bytes, 10 s evaluation timeout), probes and replaces stale sockets, binds with `0600` permissions, recovers watcher overflow via rescan, and removes only its own socket (device/inode checked). Wired `vbs daemon run|status|stop|gc|recover|describe` into `src/Main.cpp` and added `tests/DaemonTests.cpp` (`VOID_TEST(Daemon, ...)`) plus CLI contracts. - Split OS-specific platform implementations into `src/Platform/Linux/` and added `include/Void/Build/Platform/Host.hpp` (`HostOs`, `host_os()`, `host_supported()`); macOS/Windows backends remain planned Track C2/C3 scope. - Fixed bounded CMake translation for CMake 4.5's synthesized `@cmake_cxx_std@(synth_N)` `INTERFACE_LIBRARY` feature carriers in `src/Provider/Translator.cpp`: their standard flag is already lowered from compile groups, so they are skipped instead of reported as untranslated dependency edges. Restored `FullV1Tests.track_b3_foreign_cmake_cxx20_modules_native_translation` on CMake 4.5. ## 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 D3 signing (SBOM done; upstream Ed25519 available in pin but needs an OpenSSL-enabled verification environment), Track E3 (daemon core done; build-serving requests and external editor plugins remain), 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 and Ed25519 primitives done; OpenSSL-backed round-trip verification and `vbs publish`/`vbs build --locked` enforcement remain), Track E3 (daemon core and bounded `describe` done; build-serving requests and external editor plugins remain), 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 c99f426..4a80379 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -19,6 +19,6 @@ 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 | -| 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 | -| Wave 14 (Track E3 daemon core + Track C1 platform split) | Unix-socket `vbs daemon` holding warm `StateStore`/`InotifyWatcher` with `ping/status/gc/recover/shutdown`, CLI + tests; `src/Platform/Linux/` backend split with `HostOs` boundary; CMake 4.5 `@cmake_cxx_std@` feature-carrier translation fix | COMPLETE & VERIFIED (GCC 16.2, pinned VoidLibrary `3e25405`, 8/8 CTest suites) | `include/Void/Build/Daemon/Daemon.hpp`, `src/Daemon/Daemon.cpp`, `tests/DaemonTests.cpp`, `include/Void/Build/Platform/Host.hpp`, `src/Platform/Linux/`, `src/Main.cpp`, `src/Provider/Translator.cpp`, `tests/CliContracts.cmake`, docs | -| Future (Plan 20 Slice 3 / Tracks C, D3 signing, E3 daemon build serving, 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) | +| Wave 13 (Track D3 SBOM + Ed25519 signing primitives) | Deterministic SPDX 2.3 / CycloneDX 1.5 SBOM from `vbs.lock` packages + `BuildGraph` outputs; `vbs build\|test --sbom FILE --sbom-format spdx\|cyclonedx`; Ed25519 detached-signature primitives (`Void::Build::Provenance::Signing`: 0600 seed generation, public-key derivation, canonical package message, sign/verify) capability-gated on `Void::Crypto`'s OpenSSL backend | SBOM COMPLETE & VERIFIED (Docker GCC 16, 8/8 CTest suites); signing primitives IMPLEMENTED & VERIFIED in `dev cpp-gcc` (OpenSSL-gated: 4/4 `SigningTests`; OpenSSL-backed round-trip pending an OpenSSL-enabled environment) | `include/Void/Build/Provenance/Sbom.hpp`, `src/Provenance/Sbom.cpp`, `include/Void/Build/Provenance/Signing.hpp`, `src/Provenance/Signing.cpp`, `tests/SigningTests.cpp`, `src/Main.cpp`, `tests/FullV1Tests.cpp`, docs | +| Wave 14 (Track E3 daemon core + bounded `describe` + Track C1 platform split) | Unix-socket `vbs daemon` holding warm `StateStore`/`InotifyWatcher` with `ping/status/gc/recover/describe/shutdown`, CLI + tests; bounded `describe` graph summary (`target_names` ≤ 128 × 200 bytes, `profile` ≤ 128 bytes, 10 s eval timeout); `src/Platform/Linux/` backend split with `HostOs` boundary; CMake 4.5 `@cmake_cxx_std@` feature-carrier translation fix | COMPLETE & VERIFIED (GCC 16.2, pinned VoidLibrary `3e25405`, 8/8 CTest suites; `Daemon` suite 6/6 under `dev cpp-gcc`; live `vbs daemon describe` CLI round-trip verified in `vbs_cli_contract`) | `include/Void/Build/Daemon/Daemon.hpp`, `src/Daemon/Daemon.cpp`, `tests/DaemonTests.cpp`, `include/Void/Build/Platform/Host.hpp`, `src/Platform/Linux/`, `src/Main.cpp`, `src/Provider/Translator.cpp`, `tests/CliContracts.cmake`, docs | +| Future (Plan 20 Slice 3 / Tracks C, D3 signature enforcement, E3 daemon build serving, E4, live `conan`) | Live `conan` CLI verification; macOS/Windows/cross-compile; `vbs publish`/`vbs build --locked` signature enforcement; daemon build serving; `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 f1de992..9e7cfd1 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -1,6 +1,6 @@ # Verification record -Updated: 2026-11-27 +Updated: 2026-12-03 Working directory: `/home/faumaray/Projects/VoidBuildSystem` All checks below were executed after the final C++ edits and formatting pass. Planned/non-executed items are separated explicitly under **Limits and Unrun Checks**. @@ -187,9 +187,8 @@ inputs are byte-equal. 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. +Ed25519 package/binary signing primitives are now implemented in `Void::Build::Provenance::Signing` +(see the signing verification section below); package/binary signature enforcement remains planned. ## Track E3 Daemon Core & Track C1 Platform Split (2026-12-03, `dev cpp-gcc`) @@ -219,11 +218,60 @@ dev cpp-gcc -c ctest --test-dir build/bootstrap --output-on-failure fix; it failed deterministically before it. - `clang-format --dry-run --Werror` passes on all new/changed C++ files. +## Track D3 Ed25519 Signing Primitives & Track E3 Daemon `describe` (2026-12-03, `dev cpp-gcc`) + +Environment: GCC 16.2.0, CMake 4.5.0, Ninja 1.13.2, VoidLibrary pin +`3e254055e081a104f08df68dde39711bc7813518` exported read-only to `/tmp/opencode/vl-pin`. This +build has `VOID_CRYPTO_HAS_OPENSSL=0`, so `Void::Crypto::has_openssl_backend()` is false. + +```sh +dev cpp-gcc -c cmake -S . -B build/bootstrap -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON +dev cpp-gcc -c cmake --build build/bootstrap -j 8 +build/bootstrap/bin/vbs_v1_tests --suite Signing --no-color +dev cpp-gcc -c build/bootstrap/bin/vbs_v1_tests --suite Daemon --no-color +dev cpp-gcc -c ctest --test-dir build/bootstrap -R vbs_cli_contract --output-on-failure +``` + +- Build: exit 0; all targets including `bin/vbs` and `bin/vbs_v1_tests` compile and link. +- `Signing` suite: **4 / 4 passed** in 0.3 ms (canonical message, seed round-trip/tamper/rejections, + malformed hex/seed files, backend gating). The crypto round-trip case self-skips while + `signing_available() == false`. +- External signing harness (`/tmp/opencode/signing-verify/verify.cpp`, linked against + `libVoidBuild_Core.a`): **0 failures, 4 skipped, exit 0**. The canonical message is deterministic + and changes on a 1-byte archive-digest or version tamper; + `generate_signing_seed`/`public_key_from_seed`/`sign_package`/`verify_package` return + `ErrorKind::unsupported` with `Ed25519 package signing requires the OpenSSL backend of + Void::Crypto` instead of crashing; truncated/oversized signatures and public keys, missing seed + files, and directory seed paths are rejected as errors. Skipped (OpenSSL unavailable): fixed-seed + RFC 8032 round-trip, signature 1-byte tamper, wrong key, non-hex key/signature. +- `Daemon` suite under `dev cpp-gcc`: **6 / 6 passed** in 6.53 s, including + `describe_evaluates_project_graph` (2224.5 ms), `describe_empty_project_reports_zero_targets` + (2080.0 ms), `describe_bounds_target_names_for_large_projects` (2186.1 ms), and + `describe_rejects_workspace_root` (16.4 ms). +- The same `Daemon` suite run outside the dev shell: 3 / 6, because `g++` is absent from `PATH` + (`describe: host compiler 'g++' not found in PATH for compiling build.cpp`). Daemon tests must + run under `dev cpp-gcc`. +- `vbs_cli_contract`: **PASSED** (7.44 s) including the live `vbs daemon run` → `vbs daemon describe` + → `vbs daemon stop` round-trip over the Unix socket. The describe client uses a 15 s timeout + because graph evaluation takes ~2 s; the daemon bounds evaluation at 10 s. +- Full default CTest after integration: **8 / 8 passed** in 211.36 s (`vbs_v1_tests` 87.35 s, + `vbs_selfhost_tests` 93.22 s, `vbs_cli_contract` 7.44 s). +- **OpenSSL-backed signing verification** (separate `build/openssl` configure with + `OPENSSL_ROOT_DIR` pointing at the Nix OpenSSL 3.5.9 dev/lib outputs): build exit 0, and + `build/openssl/bin/vbs_v1_tests --suite Signing --no-color` reports **4 / 4 passed** with the + real Ed25519 backend (seed round-trip, sign/verify, uppercase hex, digest/signature/wrong-key + rejection, malformed hex and seed files). The same suite on the default no-OpenSSL build is + **4 / 4 passed** via the capability-gated path, where the crypto round-trip self-skips and the + explicit unsupported-backend error is asserted. +- Bounds verified by `DaemonTests`: `target_names` capped at 128 entries (project with 140 targets) + and 200 bytes per name; `profile` rejects empty, non-string, and > 128-byte values; `compiler` + rejects non-string and unknown values; workspace roots are rejected. + ## 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). 2. **Conan2 live installation**: `conan` is absent in `dev cpp-gcc`; automated testing verified explicit missing-prerequisite failure (`FullV1Tests.cpp`). Live `conan` container verification (Track B3) remains unrun. 3. **Optional external VoidLibrary modules (`Void::Net`, `Void::Sqlite`)**: `Boost`, `OpenSSL`, and `SQLite3` are not installed in `dev cpp-gcc`, so VBS continues using its pure-C++/POSIX loopback HTTP adapters (`HttpServer`, `RegistryClient`) and journaled atomic CAS store (`StateStore`), while retaining optional `Void::Sqlite` CMake detection. 4. **CI workflow & Web UI browser**: [.github/workflows/ci.yml](../../.github/workflows/ci.yml) has not been executed on remote GitHub Actions runners, and `registry/web/` was verified via HTTP/header/static-serving/API/XSS/CSRF tests without a headless browser runner. -5. **Remaining Post-v1 Roadmap ([21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md) & [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Live `conan` container verification, Track C (Windows/MSVC, macOS/Apple Clang, dual-profile cross-compilation), Track D1/D2 acceptance scenarios (unit/integration suites pass in Docker; see above), Track D3 (SBOM/signatures), Track E2 (`workspace.cpp`), Track E3 (daemon core is done; build-serving requests and external editor plugins remain), and Track E4 (`Void::Net`/`Void::Sqlite` alignment) remain planned scope. -6. **Track D3 signing / Track C ports**: the pinned VoidLibrary exposes Ed25519 in `Void::Crypto`, but it requires the OpenSSL backend, which is not available in `dev cpp-gcc`; macOS/Windows platform backends are also unverified because no such hosts are available. Both remain unrun rather than claimed. +5. **Remaining Post-v1 Roadmap ([21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md) & [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Live `conan` container verification, Track C (Windows/MSVC, macOS/Apple Clang, dual-profile cross-compilation), Track D1/D2 acceptance scenarios (unit/integration suites pass in Docker; see above), Track D3 (SBOM/signatures), Track E2 (`workspace.cpp`), Track E3 (daemon core and bounded `describe` are done; build-serving requests and external editor plugins remain), and Track E4 (`Void::Net`/`Void::Sqlite` alignment) remain planned scope. +6. **Track D3 signing / Track C ports**: the Ed25519 primitives are implemented and pass both the no-OpenSSL gating tests and the OpenSSL-backed round-trip (verified against Nix OpenSSL 3.5.9 in `build/openssl`); `vbs publish`/`vbs build --locked` signature enforcement is not wired yet. macOS/Windows platform backends are unverified because no such hosts are available. These remain unrun rather than claimed. diff --git a/docs/roadmap/21-expansion-roadmap.md b/docs/roadmap/21-expansion-roadmap.md index 31f9759..be447d1 100644 --- a/docs/roadmap/21-expansion-roadmap.md +++ b/docs/roadmap/21-expansion-roadmap.md @@ -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** *(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). | +| **D3 — Supply-Chain Provenance & Signed Packages** *(SBOM implemented; Ed25519 signing primitives implemented, OpenSSL backend required)* | Emit SPDX/CycloneDX SBOM JSON from `vbs.lock` + `BuildGraph` (`vbs build/test --sbom FILE --sbom-format spdx\|cyclonedx`, `src/Provenance/Sbom.cpp`); Ed25519 detached-signature primitives in `Void::Build::Provenance::Signing` (`include/Void/Build/Provenance/Signing.hpp`, `src/Provenance/Signing.cpp`): 0600 seed generation, public-key derivation, canonical `vbs-package-v1` package message, and sign/verify, capability-gated on `Void::Crypto`'s OpenSSL backend; wiring signature enforcement into `vbs publish` and `vbs build --locked` remains planned. | SBOM is deterministic and valid JSON; signing primitives pass round-trip/tamper/malformed tests (`tests/SigningTests.cpp`) and fail closed with an explicit unsupported-backend error without OpenSSL; tampered archive or signature must fail closed before extraction once enforcement is wired. | --- @@ -73,7 +73,7 @@ flowchart LR | --- | --- | --- | | **E1 — Everyday CLI Ergonomics (Implemented in Wave 8)** | `vbs init` project scaffolding, `vbs clean`, `vbs doctor` environment diagnostics, `vbs graph --format dot|json`, and `vbs build --native-foreign`. | End-to-end CLI & integration tests passing in `vbs_cli_contract` and `vbs_v1_tests`. | | **E2 — Multi-Package Workspaces (`workspace.cpp`)** *(verified in Docker GCC 16)* | Shared root `vbs.lock` and `build/.vbs` CAS, `workspace_dependency()` cross-member native linking, and affected-member selection (`vbs build/test --member ` / `--changed-since `). | 3-package workspace fixture (shared library + app + tests) builds/tests with one root lockfile; member selection and `--changed-since` verified in `FullV1Tests.workspace_members_shared_build_and_member_selection`. | -| **E3 — IDE Config/Query & Background Daemon** | `build.cpp`/`build.profiles.cpp`/`build-support/` SDK entries in `compile_commands.json` + `vbs ide generate` (`.clangd`, `.vscode/`, `.zed/`, `.idea/customTargets.xml`) & `vbs ide query` (**Implemented & Verified in Wave 10**); Unix-socket daemon core holding a warm `StateStore` + project `DirectoryWatcher` with `vbs daemon run\|status\|stop\|gc\|recover` (**Implemented & Verified in Wave 14**). Build-serving daemon requests and dedicated editor extensions remain planned. | `vbs ide` & `build.cpp` syntax-check verified in `FullV1Tests.cpp`; daemon lifecycle/status/gc/shutdown verified in `DaemonTests.cpp` and CLI contracts. | +| **E3 — IDE Config/Query & Background Daemon** | `build.cpp`/`build.profiles.cpp`/`build-support/` SDK entries in `compile_commands.json` + `vbs ide generate` (`.clangd`, `.vscode/`, `.zed/`, `.idea/customTargets.xml`) & `vbs ide query` (**Implemented & Verified in Wave 10**); Unix-socket daemon core holding a warm `StateStore` + project `DirectoryWatcher` with `vbs daemon run\|status\|stop\|gc\|recover\|describe` (**Implemented & Verified in Wave 14; bounded `describe` added in the post-v1 daemon follow-up**). `describe` returns a bounded graph summary (`target_names` ≤ 128 entries × 200 bytes, `profile` ≤ 128 bytes, 10 s evaluation timeout). Build-serving daemon requests and dedicated editor extensions remain planned. | `vbs ide` & `build.cpp` syntax-check verified in `FullV1Tests.cpp`; daemon lifecycle/status/gc/shutdown/describe verified in `DaemonTests.cpp` (6/6 under `dev cpp-gcc`); the live `vbs daemon describe` CLI round-trip is verified in `vbs_cli_contract`. | | **E4 — Transport & Storage Upstream Alignment** | Adopt `Void::Net` (`VL-004`/`VL-005`) and `Void::Sqlite` (`VL-011b`) when lightweight/bundled builds become available in minimal Nix toolchains, reducing VBS transport code further. | All `vbs_registry_tests` and `vbs_core_tests` pass on both minimal and full toolchains. | --- diff --git a/include/Void/Build/Provenance/Signing.hpp b/include/Void/Build/Provenance/Signing.hpp new file mode 100644 index 0000000..0e3fc16 --- /dev/null +++ b/include/Void/Build/Provenance/Signing.hpp @@ -0,0 +1,42 @@ +#pragma once + +#include +#include + +#include +#include +#include + +namespace Void::Build::Provenance { + +// Ed25519 package-signing primitives. Every operation fails closed with an +// explicit error when Void::Crypto was built without its OpenSSL backend. +[[nodiscard]] bool signing_available() noexcept; + +// Writes a fresh random 32-byte Ed25519 seed as 64 lowercase hex characters +// plus a trailing newline, creating the file owner read/write only (0600). +[[nodiscard]] Void::Result::Result +generate_signing_seed(const std::filesystem::path &seed_path); + +// Derives the 32-byte Ed25519 public key (64 lowercase hex characters) from a +// seed file holding exactly 64 hex characters plus optional trailing whitespace. +[[nodiscard]] Void::Result::Result +public_key_from_seed(const std::filesystem::path &seed_path); + +// Canonical package message signed by vbs: +// "vbs-package-v1\n@\nsha256:\n" +[[nodiscard]] std::string canonical_package_message(std::string_view name, std::string_view version, + std::string_view sha256_hex); + +// Detached Ed25519 signature (128 lowercase hex characters) over the canonical message. +[[nodiscard]] Void::Result::Result +sign_package(std::string_view name, std::string_view version, std::string_view sha256_hex, + const std::filesystem::path &seed_path); + +// Verifies a detached signature over the canonical message. Well-formed but invalid +// signatures return false; malformed hex, key, or signature sizes return an error. +[[nodiscard]] Void::Result::Result +verify_package(std::string_view name, std::string_view version, std::string_view sha256_hex, + std::string_view signature_hex, std::string_view public_key_hex); + +} // namespace Void::Build::Provenance diff --git a/recipes/SelfHost/VbsSelfHostRecipe.cpp b/recipes/SelfHost/VbsSelfHostRecipe.cpp index 6a201ee..c64ecdc 100644 --- a/recipes/SelfHost/VbsSelfHostRecipe.cpp +++ b/recipes/SelfHost/VbsSelfHostRecipe.cpp @@ -62,6 +62,7 @@ add_vbs_selfhost_native(Project &project, const VbsSelfHostConfig &config) { core.cxx_standard(CxxStandard::Cxx26) .include_directory((root / "include").string(), Visibility::Public) .include_directory((root / "recipes").string(), Visibility::Public) + .include_directory(gen_dir.string(), Visibility::Private) .compile_option("-freflection", Visibility::Public) .define("VBS_HAS_VOID_CRYPTO=1", Visibility::Public) .define("VBS_HAS_VOID_ARCHIVE=1", Visibility::Public) @@ -101,6 +102,7 @@ add_vbs_selfhost_native(Project &project, const VbsSelfHostConfig &config) { "src/Modules/ModuleScanner.cpp", "src/SelfHost/TestRegistryGen.cpp", "src/Provenance/Sbom.cpp", + "src/Provenance/Signing.cpp", "recipes/VoidLibrary/VoidLibraryRecipe.cpp", "recipes/SelfHost/VbsSelfHostRecipe.cpp", }; diff --git a/src/Daemon/Daemon.cpp b/src/Daemon/Daemon.cpp index 5ae7116..e92757c 100644 --- a/src/Daemon/Daemon.cpp +++ b/src/Daemon/Daemon.cpp @@ -1,10 +1,16 @@ #include +#include +#include +#include +#include #include +#include #include #include #include +#include #include #include #include @@ -13,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -23,6 +30,7 @@ #include #include #include +#include namespace Void::Build::Daemon { namespace { @@ -35,6 +43,10 @@ constexpr std::size_t kMaxJsonDepth = 16U; constexpr int kListenBacklog = 8; constexpr auto kClientIoTimeout = std::chrono::milliseconds{2000}; constexpr auto kProbeTimeout = std::chrono::milliseconds{1000}; +constexpr auto kDescribeEvalTimeout = std::chrono::seconds{10}; +constexpr std::size_t kMaxDescribeProfileBytes = 128U; +constexpr std::size_t kMaxDescribeTargetNames = 128U; +constexpr std::size_t kMaxDescribeTargetNameBytes = 200U; Void::Result::Error make_error(Void::Result::ErrorKind kind, std::string message, int system_errno = 0) { @@ -279,6 +291,119 @@ std::string ok_response(std::string_view op) { return serialize_response(JsonValue{std::move(object)}); } +// Mirrors the executable's frontend option construction: SDK include/source roots come from the +// generated BootstrapConfig, and the prebuilt SDK archive is discovered from the running binary +// or the configured binary directory. +Config::FrontendOptions make_frontend_options(const DaemonOptions &options) { + Config::FrontendOptions frontend; + frontend.project_root = options.project_root; + frontend.build_root = options.build_root; + frontend.sdk_include_dir = std::filesystem::path{Bootstrap::sdk_include_dir}; + frontend.sdk_source_dir = std::filesystem::path{Bootstrap::sdk_source_dir}; + frontend.eval_timeout = kDescribeEvalTimeout; + + std::error_code ec; + std::vector sdk_candidates; + if (const auto self_exe = std::filesystem::read_symlink("/proc/self/exe", ec); + !ec && !self_exe.empty()) { + const auto self_root = self_exe.parent_path().parent_path(); + sdk_candidates.push_back(self_root / "libVoidBuildSdk.a"); + sdk_candidates.push_back(self_root / "libVoidBuild_Sdk.a"); + sdk_candidates.push_back(self_root / "lib" / "libVoidBuildSdk.a"); + } + if (!Bootstrap::binary_dir.empty()) { + const auto bin_dir = std::filesystem::path{Bootstrap::binary_dir}; + sdk_candidates.push_back(bin_dir / "libVoidBuild_Sdk.a"); + sdk_candidates.push_back(bin_dir / "out" / "libVoidBuildSdk.a"); + sdk_candidates.push_back(bin_dir / "profiles" / "debug" / "out" / "libVoidBuildSdk.a"); + } + for (const auto &candidate : sdk_candidates) { + if (std::filesystem::is_regular_file(candidate, ec)) { + frontend.sdk_library_path = candidate; + break; + } + } + return frontend; +} + +// Evaluates the project description in-process and lowers it to a bounded graph summary. +// Workspace roots are rejected explicitly: member selection belongs to the CLI. +std::string describe_project(const DaemonOptions &options, std::string_view profile_name, + std::optional compiler_override) { + if (Config::is_workspace_root(options.project_root)) { + return error_response("describe: workspace roots are not supported by the daemon yet"); + } + + const auto frontend = make_frontend_options(options); + auto compiled = Config::compile_descriptor(frontend); + if (!compiled) { + return error_response(std::format("describe: {}", compiled.error().format())); + } + auto profiles = Config::discover_profiles(*compiled, frontend); + if (!profiles) { + return error_response(std::format("describe: {}", profiles.error().format())); + } + + ProfileContext context; + try { + context = profiles->resolve(profile_name, compiler_override, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + } catch (const std::exception &ex) { + return error_response(std::format("describe: {}", ex.what())); + } + + auto description = Config::evaluate_project(*compiled, context, frontend); + if (!description) { + return error_response(std::format("describe: {}", description.error().format())); + } + auto toolchain = Toolchain::discover_and_probe(context, options.build_root / ".vbs" / "probes"); + if (!toolchain) { + return error_response(std::format("describe: {}", toolchain.error().format())); + } + + Graph::GraphLowerOptions lower_options; + lower_options.project_root = options.project_root; + lower_options.build_root = options.build_root; + auto graph = Graph::lower_project_graph(*description, *toolchain, lower_options); + if (!graph) { + return error_response(std::format("describe: {}", graph.error().format())); + } + + std::vector target_names; + target_names.reserve(graph->targets.size()); + for (const auto &target : graph->targets) { + target_names.push_back(target.name); + } + std::ranges::sort(target_names); + + bool truncated = false; + if (target_names.size() > kMaxDescribeTargetNames) { + target_names.resize(kMaxDescribeTargetNames); + truncated = true; + } + JsonValue::Array names_json; + names_json.reserve(target_names.size()); + for (auto &name : target_names) { + if (name.size() > kMaxDescribeTargetNameBytes) { + name.resize(kMaxDescribeTargetNameBytes); + truncated = true; + } + names_json.emplace_back(std::move(name)); + } + + JsonValue::Object object; + object.emplace("ok", JsonValue{true}); + object.emplace("op", JsonValue{std::string{"describe"}}); + object.emplace("profile", JsonValue{context.name}); + object.emplace("targets", JsonValue{static_cast(graph->targets.size())}); + object.emplace("actions", JsonValue{static_cast(graph->actions.size())}); + object.emplace("target_names", JsonValue{std::move(names_json)}); + if (truncated) { + object.emplace("target_names_truncated", JsonValue{true}); + } + return serialize_response(JsonValue{std::move(object)}); +} + } // namespace struct DaemonServer::Impl { @@ -386,6 +511,35 @@ DaemonServer::Impl::DispatchResult DaemonServer::Impl::dispatch(std::string_view if (*name == "status") { return {status_response(), false}; } + if (*name == "describe") { + std::string profile_name{"debug"}; + if (const auto entry = object->find("profile"); entry != object->end()) { + const auto *value = std::get_if(&entry->second.value); + if (value == nullptr) { + return {error_response("\"profile\" must be a string"), false}; + } + if (value->empty()) { + return {error_response("\"profile\" must not be empty"), false}; + } + if (value->size() > kMaxDescribeProfileBytes) { + return {error_response("\"profile\" is too long"), false}; + } + profile_name = *value; + } + std::optional compiler_override; + if (const auto entry = object->find("compiler"); entry != object->end()) { + const auto *value = std::get_if(&entry->second.value); + if (value == nullptr) { + return {error_response("\"compiler\" must be a string"), false}; + } + try { + compiler_override = parse_compiler(*value); + } catch (const std::exception &ex) { + return {error_response(ex.what()), false}; + } + } + return {describe_project(options, profile_name, compiler_override), false}; + } if (*name == "shutdown") { return {ok_response("shutdown"), true}; } diff --git a/src/Main.cpp b/src/Main.cpp index 46a1b35..22674c0 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -38,6 +38,7 @@ #include #include #include +#include #include #include #include @@ -1535,6 +1536,7 @@ struct DaemonCmdOptions { std::string project_arg; std::optional build_arg; std::optional socket_arg; + std::string profile_arg{"debug"}; std::string max_bytes_arg{"0"}; std::string max_requests_arg{"0"}; }; @@ -1607,12 +1609,23 @@ int execute_daemon_command(std::string_view sub, const DaemonCmdOptions &opts) { return 2; } request_json = std::format(R"({{"op":"gc","max_bytes":{}}})", max_bytes); + } else if (sub == "describe") { + if (opts.profile_arg.empty()) { + std::cerr << "vbs daemon describe: --profile must not be empty\n"; + return 2; + } + request_json = + std::format(R"({{"op":"describe","profile":{}}})", Util::json_quote(opts.profile_arg)); } else { std::cerr << "vbs daemon: unknown command '" << sub << "'\n"; return 2; } - auto response = Daemon::request(socket_path, request_json); + // Describe evaluates the whole project graph (descriptor compile, toolchain probe, lowering), + // which can exceed the 2 s default; the daemon bounds evaluation at 10 s. + const auto request_timeout = + sub == "describe" ? std::chrono::milliseconds{15000} : std::chrono::milliseconds{2000}; + auto response = Daemon::request(socket_path, request_json, request_timeout); if (!response) { std::cerr << "vbs daemon: " << response.error().message() << '\n'; return 1; @@ -2534,6 +2547,11 @@ int main(int argc, char **argv) { daemon_gc_cmd.option_default("--max-bytes", "", "Target maximum retained CAS bytes (0=unreferenced only)", daemon_opts.max_bytes_arg, "0"); + auto &daemon_describe_cmd = + daemon_cmd.subcommand("describe", "Describe a project's build graph via the daemon"); + configure_daemon_common(daemon_describe_cmd); + daemon_describe_cmd.option_default("--profile", "-p", "Profile to evaluate", + daemon_opts.profile_arg, "debug"); const auto parsed = root.parse_detailed(argc, argv); if (parsed.is_help()) { diff --git a/src/Provenance/Signing.cpp b/src/Provenance/Signing.cpp new file mode 100644 index 0000000..06cf79a --- /dev/null +++ b/src/Provenance/Signing.cpp @@ -0,0 +1,374 @@ +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef _WIN32 +#include +#include +#include +#endif + +namespace Void::Build::Provenance { +namespace { + +using Void::Result::Error; +using Void::Result::ErrorKind; +using Void::Result::Result; + +constexpr std::size_t SeedHexLength = 64; +constexpr std::size_t PublicKeyHexLength = 64; +constexpr std::size_t SignatureHexLength = 128; +constexpr std::size_t MaxSeedFileBytes = 4096; +constexpr std::string_view OpenSslRequirement = + "Ed25519 package signing requires the OpenSSL backend of Void::Crypto"; + +Error make_error(ErrorKind kind, std::string message) { return Error{kind, std::move(message)}; } + +Result require_openssl_backend() { + if (Void::Crypto::has_openssl_backend()) { + return {}; + } + return std::unexpected{make_error(ErrorKind::unsupported, std::string{OpenSslRequirement})}; +} + +bool is_hex_digit(char c) noexcept { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); +} + +// Best-effort secure wipe of a local secret string. +void wipe_string(std::string &secret) noexcept { + Void::Crypto::secure_wipe( + std::span{reinterpret_cast(secret.data()), secret.size()}); + secret.clear(); +} + +struct SecretWipeGuard { + std::string &secret; + + ~SecretWipeGuard() { wipe_string(secret); } +}; + +Result decode_hex_exact(std::string_view hex, std::size_t expected_chars, + std::string_view description) { + if (hex.size() != expected_chars) { + return std::unexpected{make_error( + ErrorKind::invalid_argument, std::format("{} must be exactly {} hex characters, got {}", + description, expected_chars, hex.size()))}; + } + if (!std::ranges::all_of(hex, is_hex_digit)) { + return std::unexpected{ + make_error(ErrorKind::invalid_argument, + std::format("{} contains a non-hexadecimal character", description))}; + } + auto decoded = Void::Encoding::Hex::decode(hex); + if (!decoded) { + return std::unexpected{make_error(ErrorKind::invalid_argument, + std::format("{} could not be decoded", description))}; + } + return *decoded; +} + +// Reads a bounded regular file without following symlinks. The caller owns +// wiping the returned contents when they are secret. +Result read_bounded_file(const std::filesystem::path &path) { +#ifndef _WIN32 + const int raw_fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW); + if (raw_fd < 0) { + const int error = errno; + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(error), + std::format("cannot open signing seed '{}'", path.string()), error)}; + } + Void::System::OwnedFd fd{raw_fd}; + struct stat status{}; + if (::fstat(fd.get(), &status) != 0) { + const int error = errno; + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(error), + std::format("cannot stat signing seed '{}'", path.string()), error)}; + } + if (!S_ISREG(status.st_mode)) { + return std::unexpected{ + make_error(ErrorKind::invalid_argument, + std::format("signing seed '{}' is not a regular file", path.string()))}; + } + + std::string contents; + std::array buffer{}; + while (true) { + const ssize_t count = ::read(fd.get(), buffer.data(), buffer.size()); + if (count < 0) { + if (errno == EINTR) { + continue; + } + const int error = errno; + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(error), + std::format("cannot read signing seed '{}'", path.string()), error)}; + } + if (count == 0) { + break; + } + contents.append(buffer.data(), static_cast(count)); + if (contents.size() > MaxSeedFileBytes) { + return std::unexpected{make_error(ErrorKind::invalid_argument, + std::format("signing seed '{}' exceeds {} bytes", + path.string(), MaxSeedFileBytes))}; + } + } + return contents; +#else + std::error_code error; + if (!std::filesystem::is_regular_file(path, error)) { + return std::unexpected{ + make_error(ErrorKind::invalid_argument, + std::format("signing seed '{}' is not a regular file", path.string()))}; + } + std::ifstream stream{path, std::ios::binary}; + if (!stream) { + return std::unexpected{ + make_error(ErrorKind::io, std::format("cannot open signing seed '{}'", path.string()))}; + } + std::string contents{std::istreambuf_iterator{stream}, std::istreambuf_iterator{}}; + if (contents.size() > MaxSeedFileBytes) { + return std::unexpected{make_error( + ErrorKind::invalid_argument, + std::format("signing seed '{}' exceeds {} bytes", path.string(), MaxSeedFileBytes))}; + } + return contents; +#endif +} + +// Parses and decodes a seed file. The returned Ed25519Seed wipes itself. +Result read_seed(const std::filesystem::path &seed_path) { + auto contents = read_bounded_file(seed_path); + if (!contents) { + return std::unexpected{contents.error()}; + } + SecretWipeGuard wipe{*contents}; + + if (contents->size() < SeedHexLength) { + return std::unexpected{make_error( + ErrorKind::invalid_argument, + "signing seed must contain exactly 64 hex characters followed only by whitespace")}; + } + const std::string_view hex{contents->data(), SeedHexLength}; + if (!std::ranges::all_of(hex, is_hex_digit)) { + return std::unexpected{make_error(ErrorKind::invalid_argument, + "signing seed contains a non-hexadecimal character")}; + } + for (const char trailing : std::string_view{*contents}.substr(SeedHexLength)) { + if (std::isspace(static_cast(trailing)) == 0) { + return std::unexpected{ + make_error(ErrorKind::invalid_argument, + "signing seed has trailing data after the 64 hex characters")}; + } + } + + auto decoded = Void::Encoding::Hex::decode(hex); + if (!decoded) { + return std::unexpected{ + make_error(ErrorKind::invalid_argument, "signing seed could not be decoded")}; + } + auto seed = Void::Crypto::Ed25519Seed::from_bytes( + std::as_bytes(std::span{decoded->data(), decoded->size()})); + wipe_string(*decoded); + if (!seed) { + return std::unexpected{seed.error()}; + } + return std::move(*seed); +} + +// Creates or truncates path with owner-only permissions (0600). +Result write_private_file(const std::filesystem::path &path, + std::string_view contents) { +#ifndef _WIN32 + const int raw_fd = + ::open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0600); + if (raw_fd < 0) { + const int error = errno; + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(error), + std::format("cannot create signing seed '{}'", path.string()), error)}; + } + Void::System::OwnedFd fd{raw_fd}; + // Tighten an existing file even when the umask or its previous mode was wider. + if (::fchmod(fd.get(), 0600) != 0) { + const int error = errno; + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(error), + std::format("cannot restrict signing seed '{}'", path.string()), error)}; + } + + std::size_t offset = 0; + while (offset < contents.size()) { + const ssize_t count = ::write(fd.get(), contents.data() + offset, contents.size() - offset); + if (count < 0) { + if (errno == EINTR) { + continue; + } + const int error = errno; + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(error), + std::format("cannot write signing seed '{}'", path.string()), error)}; + } + offset += static_cast(count); + } + return fd.close(); +#else + std::ofstream stream{path, std::ios::binary | std::ios::trunc}; + if (!stream) { + return std::unexpected{make_error( + ErrorKind::io, std::format("cannot create signing seed '{}'", path.string()))}; + } + stream.write(contents.data(), static_cast(contents.size())); + stream.close(); + if (!stream) { + return std::unexpected{make_error( + ErrorKind::io, std::format("cannot write signing seed '{}'", path.string()))}; + } + std::error_code error; + std::filesystem::permissions( + path, std::filesystem::perms::owner_read | std::filesystem::perms::owner_write, + std::filesystem::perm_options::replace, error); + if (error) { + return std::unexpected{ + make_error(ErrorKind::io, std::format("cannot restrict signing seed '{}': {}", + path.string(), error.message()))}; + } + return {}; +#endif +} + +} // namespace + +bool signing_available() noexcept { return Void::Crypto::has_openssl_backend(); } + +Result generate_signing_seed(const std::filesystem::path &seed_path) { + if (auto backend = require_openssl_backend(); !backend) { + return backend; + } + + auto private_key = Void::Crypto::Ed25519PrivateKey::generate(); + if (!private_key) { + return std::unexpected{private_key.error()}; + } + auto seed = private_key->export_raw_seed(); + if (!seed) { + return std::unexpected{seed.error()}; + } + + std::string hex = Void::Encoding::Hex::encode(seed->view()); + hex.push_back('\n'); + SecretWipeGuard wipe{hex}; + return write_private_file(seed_path, hex); +} + +Result public_key_from_seed(const std::filesystem::path &seed_path) { + if (auto backend = require_openssl_backend(); !backend) { + return std::unexpected{backend.error()}; + } + + auto seed = read_seed(seed_path); + if (!seed) { + return std::unexpected{seed.error()}; + } + auto private_key = Void::Crypto::Ed25519PrivateKey::from_raw_seed(seed->view()); + if (!private_key) { + return std::unexpected{private_key.error()}; + } + auto public_key = private_key->public_key(); + if (!public_key) { + return std::unexpected{public_key.error()}; + } + return Void::Encoding::Hex::encode(public_key->view()); +} + +std::string canonical_package_message(std::string_view name, std::string_view version, + std::string_view sha256_hex) { + std::string message; + message.reserve(15 + name.size() + 1 + version.size() + 8 + sha256_hex.size() + 1); + message += "vbs-package-v1\n"; + message += name; + message.push_back('@'); + message += version; + message += "\nsha256:"; + message += sha256_hex; + message.push_back('\n'); + return message; +} + +Result sign_package(std::string_view name, std::string_view version, + std::string_view sha256_hex, + const std::filesystem::path &seed_path) { + if (auto backend = require_openssl_backend(); !backend) { + return std::unexpected{backend.error()}; + } + + auto seed = read_seed(seed_path); + if (!seed) { + return std::unexpected{seed.error()}; + } + auto private_key = Void::Crypto::Ed25519PrivateKey::from_raw_seed(seed->view()); + if (!private_key) { + return std::unexpected{private_key.error()}; + } + + const std::string message = canonical_package_message(name, version, sha256_hex); + auto signature = Void::Crypto::sign_ed25519( + std::as_bytes(std::span{message.data(), message.size()}), *private_key); + if (!signature) { + return std::unexpected{signature.error()}; + } + return Void::Encoding::Hex::encode(signature->view()); +} + +Result verify_package(std::string_view name, std::string_view version, + std::string_view sha256_hex, std::string_view signature_hex, + std::string_view public_key_hex) { + if (auto backend = require_openssl_backend(); !backend) { + return std::unexpected{backend.error()}; + } + + auto signature_bytes = decode_hex_exact(signature_hex, SignatureHexLength, "Ed25519 signature"); + if (!signature_bytes) { + return std::unexpected{signature_bytes.error()}; + } + auto public_key_bytes = + decode_hex_exact(public_key_hex, PublicKeyHexLength, "Ed25519 public key"); + if (!public_key_bytes) { + return std::unexpected{public_key_bytes.error()}; + } + + auto signature = Void::Crypto::Ed25519Signature::from_bytes( + std::as_bytes(std::span{signature_bytes->data(), signature_bytes->size()})); + if (!signature) { + return std::unexpected{signature.error()}; + } + auto public_key = Void::Crypto::Ed25519PublicKey::from_bytes( + std::as_bytes(std::span{public_key_bytes->data(), public_key_bytes->size()})); + if (!public_key) { + return std::unexpected{public_key.error()}; + } + + const std::string message = canonical_package_message(name, version, sha256_hex); + return Void::Crypto::verify_ed25519( + std::as_bytes(std::span{message.data(), message.size()}), *signature, + *public_key); +} + +} // namespace Void::Build::Provenance diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index e5e5d6e..bc20d94 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -12,7 +12,7 @@ set_target_properties(vbs_core_tests PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin") add_test(NAME vbs_core_tests COMMAND "$" --no-color) -add_executable(vbs_v1_tests FullV1Tests.cpp DaemonTests.cpp) +add_executable(vbs_v1_tests FullV1Tests.cpp DaemonTests.cpp SigningTests.cpp) target_include_directories(vbs_v1_tests PRIVATE "${PROJECT_BINARY_DIR}/generated") target_link_libraries(vbs_v1_tests PRIVATE Void::BuildCore Void::Testing) set_target_properties(vbs_v1_tests PROPERTIES diff --git a/tests/CliContracts.cmake b/tests/CliContracts.cmake index 464b4b3..2752c0e 100644 --- a/tests/CliContracts.cmake +++ b/tests/CliContracts.cmake @@ -45,9 +45,91 @@ check_process(2 "" "--prefix is required" uninstall) check_process(2 "" "--input and --output-dir are required" gen-tests) check_process(0 "Usage: vbs publish " "" publish --help) check_process(2 "" "--registry, --name, and --version are required" publish) -check_process(0 "Usage: vbs daemon .*Commands:.*run.*status.*stop.*recover.*gc" "" daemon --help) +check_process(0 "Usage: vbs daemon .*Commands:.*run.*status.*stop.*recover.*gc.*describe" "" daemon --help) check_process(0 "Usage: vbs daemon run " "" daemon run --help) +check_process(0 "Usage: vbs daemon describe .*--profile" "" daemon describe --help) check_process(2 "" "missing subcommand for 'vbs daemon'" daemon) + +# Daemon-backed describe contract: start `vbs daemon run`, query the bounded graph summary over +# the Unix socket, then stop it. The daemon is Unix-only, matching the rest of this suite. +set(daemon_contract_root "${CMAKE_CURRENT_BINARY_DIR}/daemon_contract") +file(REMOVE_RECURSE "${daemon_contract_root}") +file(MAKE_DIRECTORY "${daemon_contract_root}/project") +file(WRITE "${daemon_contract_root}/project/build.cpp" [=[#include + +void build(Void::Build::Project &project) { + auto app = project.executable("app"); + app.sources({"main.cpp"}); +} +]=]) +file(WRITE "${daemon_contract_root}/project/main.cpp" "int main() { return 0; }\n") + +set(daemon_contract_script [=[ +set -u +vbs="$1" +project="$2" +build="$3" +out="$4" +log="$5" + +"$vbs" daemon run -C "$project" -B "$build" --max-requests 2 >"$log" 2>&1 & +pid=$! +cleanup() { + kill "$pid" 2>/dev/null || true +} +trap cleanup EXIT + +socket="$build/.vbs/vbs-daemon.sock" +i=0 +while [ ! -S "$socket" ]; do + i=$((i + 1)) + if [ "$i" -gt 400 ]; then + echo "daemon socket did not appear" >&2 + exit 1 + fi + sleep 0.05 +done + +"$vbs" daemon describe -C "$project" -B "$build" >"$out" +status=$? + +"$vbs" daemon stop -C "$project" -B "$build" >/dev/null 2>&1 || true +i=0 +while kill -0 "$pid" 2>/dev/null; do + i=$((i + 1)) + if [ "$i" -gt 100 ]; then + break + fi + sleep 0.05 +done +kill "$pid" 2>/dev/null || true +wait "$pid" 2>/dev/null || true +trap - EXIT +exit "$status" +]=]) + +execute_process( + COMMAND sh -c "${daemon_contract_script}" sh "${VBS}" + "${daemon_contract_root}/project" "${daemon_contract_root}/build" + "${daemon_contract_root}/describe.json" "${daemon_contract_root}/daemon.log" + RESULT_VARIABLE daemon_contract_code + TIMEOUT 180) + +set(daemon_contract_log "") +if(EXISTS "${daemon_contract_root}/daemon.log") + file(READ "${daemon_contract_root}/daemon.log" daemon_contract_log) +endif() +if(NOT "${daemon_contract_code}" STREQUAL "0") + message(FATAL_ERROR "vbs daemon describe failed: exit ${daemon_contract_code}\ndaemon log=[${daemon_contract_log}]") +endif() + +file(READ "${daemon_contract_root}/describe.json" daemon_describe_out) +if(NOT daemon_describe_out MATCHES "\"ok\":true" OR + NOT daemon_describe_out MATCHES "\"op\":\"describe\"" OR + NOT daemon_describe_out MATCHES "\"target_names\":\\[[^]]*\"app\"") + message(FATAL_ERROR "vbs daemon describe: unexpected response [${daemon_describe_out}]") +endif() +message(STATUS "daemon describe response: ${daemon_describe_out}") check_process(0 "Usage: vbs ide .*Commands:.*generate.*query" "" ide --help) check_process(0 "Usage: vbs ide generate " "" ide generate --help) check_process(0 "Usage: vbs ide query " "" ide query --help) @@ -59,4 +141,4 @@ execute_process(COMMAND "${VBS_REGISTRY}" --help if(NOT "${reg_code}" STREQUAL "0" OR NOT reg_out MATCHES "Usage: vbs-registry") message(FATAL_ERROR "vbs-registry --help failed: code=${reg_code}\nstdout=[${reg_out}]\nstderr=[${reg_err}]") endif() -message(STATUS "37 native CLI and auto-generated Argparse help contracts verified") +message(STATUS "CLI and auto-generated Argparse help contracts verified (including daemon describe round-trip)") diff --git a/tests/DaemonTests.cpp b/tests/DaemonTests.cpp index 509a7cf..3cef14f 100644 --- a/tests/DaemonTests.cpp +++ b/tests/DaemonTests.cpp @@ -4,15 +4,18 @@ #include #include +#include #include #include #include +#include #include #include #include #include #include #include +#include namespace { @@ -63,6 +66,42 @@ std::string str_field(const JsonObject &object, std::string_view name) { return text != nullptr ? *text : std::string{}; } +std::optional +request_object(const std::filesystem::path &socket, std::string_view request_json, + std::chrono::milliseconds timeout = std::chrono::seconds{120}) { + auto response = Void::Build::Daemon::request(socket, request_json, timeout); + if (!response) { + return std::nullopt; + } + auto parsed = parse_json(*response); + if (!parsed) { + return std::nullopt; + } + const auto *object = as_object(*parsed); + if (object == nullptr) { + return std::nullopt; + } + return *object; +} + +std::vector string_array_field(const JsonObject &object, std::string_view name) { + std::vector result; + const auto *value = field(object, name); + if (value == nullptr) { + return result; + } + const auto *array = std::get_if(&value->value); + if (array == nullptr) { + return result; + } + for (const auto &entry : *array) { + if (const auto *text = std::get_if(&entry.value)) { + result.push_back(*text); + } + } + return result; +} + bool wait_for_path(const std::filesystem::path &path, std::chrono::milliseconds timeout) { const auto deadline = std::chrono::steady_clock::now() + timeout; while (std::chrono::steady_clock::now() < deadline) { @@ -180,3 +219,220 @@ VOID_TEST(Daemon, second_create_reports_already_running) { Void::Testing::expect(run_result.has_value()); Void::Testing::expect(!std::filesystem::exists(socket)); } + +VOID_TEST(Daemon, describe_evaluates_project_graph) { + auto temp = Void::FileSystem::TempDir::open("vbs_daemon_"); + Void::Testing::require(temp.has_value()); + const auto options = make_options(temp->path()); + + { + std::ofstream descriptor{options.project_root / "build.cpp"}; + descriptor << R"cpp(#include + +void build(Void::Build::Project &project) { + auto app = project.executable("app"); + app.sources({"main.cpp"}); +} +)cpp"; + Void::Testing::require(descriptor.good()); + } + { + std::ofstream source{options.project_root / "main.cpp"}; + source << "int main() { return 0; }\n"; + Void::Testing::require(source.good()); + } + + auto server = Void::Build::Daemon::DaemonServer::create(options); + Void::Testing::require(server.has_value()); + const auto socket = server->socket_path(); + + Void::Result::Result run_result; + std::jthread worker{[&] { run_result = server->run(); }}; + Void::Testing::require(wait_for_path(socket, std::chrono::seconds{5})); + + auto describe = + Void::Build::Daemon::request(socket, R"({"op":"describe"})", std::chrono::seconds{120}); + Void::Testing::require(describe.has_value()); + const auto describe_json = parse_json(*describe); + Void::Testing::require(describe_json.has_value()); + const auto *describe_object = as_object(*describe_json); + Void::Testing::require(describe_object != nullptr); + Void::Testing::expect(bool_field(*describe_object, "ok")); + Void::Testing::expect_eq(str_field(*describe_object, "op"), std::string{"describe"}); + Void::Testing::expect_eq(str_field(*describe_object, "profile"), std::string{"debug"}); + Void::Testing::expect(int_field(*describe_object, "targets") >= 1); + Void::Testing::expect(int_field(*describe_object, "actions") >= 1); + const auto target_names = string_array_field(*describe_object, "target_names"); + Void::Testing::expect(std::ranges::find(target_names, std::string{"app"}) != + target_names.end()); + + auto bad_profile = request_object(socket, R"({"op":"describe","profile":"does-not-exist"})"); + Void::Testing::require(bad_profile.has_value()); + Void::Testing::expect(!bool_field(*bad_profile, "ok", true)); + Void::Testing::expect(field(*bad_profile, "error") != nullptr); + + auto numeric_profile = request_object(socket, R"({"op":"describe","profile":123})"); + Void::Testing::require(numeric_profile.has_value()); + Void::Testing::expect(!bool_field(*numeric_profile, "ok", true)); + Void::Testing::expect(str_field(*numeric_profile, "error").find("must be a string") != + std::string::npos); + + auto empty_profile = request_object(socket, R"({"op":"describe","profile":""})"); + Void::Testing::require(empty_profile.has_value()); + Void::Testing::expect(!bool_field(*empty_profile, "ok", true)); + Void::Testing::expect(str_field(*empty_profile, "error").find("must not be empty") != + std::string::npos); + + const std::string oversized_profile_request{R"({"op":"describe","profile":")" + + std::string(129, 'p') + "\"}"}; + auto oversized_profile = request_object(socket, oversized_profile_request); + Void::Testing::require(oversized_profile.has_value()); + Void::Testing::expect(!bool_field(*oversized_profile, "ok", true)); + Void::Testing::expect(str_field(*oversized_profile, "error").find("too long") != + std::string::npos); + + auto numeric_compiler = request_object(socket, R"({"op":"describe","compiler":5})"); + Void::Testing::require(numeric_compiler.has_value()); + Void::Testing::expect(!bool_field(*numeric_compiler, "ok", true)); + Void::Testing::expect(str_field(*numeric_compiler, "error").find("must be a string") != + std::string::npos); + + auto invalid_compiler = request_object(socket, R"({"op":"describe","compiler":"msvc"})"); + Void::Testing::require(invalid_compiler.has_value()); + Void::Testing::expect(!bool_field(*invalid_compiler, "ok", true)); + Void::Testing::expect(str_field(*invalid_compiler, "error").find("unknown compiler") != + std::string::npos); + + auto shutdown = Void::Build::Daemon::request(socket, R"({"op":"shutdown"})"); + Void::Testing::expect(shutdown.has_value()); + worker.join(); + Void::Testing::expect(run_result.has_value()); + Void::Testing::expect(!std::filesystem::exists(socket)); +} + +VOID_TEST(Daemon, describe_empty_project_reports_zero_targets) { + auto temp = Void::FileSystem::TempDir::open("vbs_daemon_"); + Void::Testing::require(temp.has_value()); + const auto options = make_options(temp->path()); + + { + std::ofstream descriptor{options.project_root / "build.cpp"}; + descriptor << R"cpp(#include + +void build(Void::Build::Project &project) {} +)cpp"; + Void::Testing::require(descriptor.good()); + } + + auto server = Void::Build::Daemon::DaemonServer::create(options); + Void::Testing::require(server.has_value()); + const auto socket = server->socket_path(); + + Void::Result::Result run_result; + std::jthread worker{[&] { run_result = server->run(); }}; + Void::Testing::require(wait_for_path(socket, std::chrono::seconds{5})); + + auto describe = request_object(socket, R"({"op":"describe"})"); + Void::Testing::require(describe.has_value()); + Void::Testing::expect(bool_field(*describe, "ok")); + Void::Testing::expect_eq(int_field(*describe, "targets"), std::int64_t{0}); + Void::Testing::expect_eq(int_field(*describe, "actions"), std::int64_t{0}); + Void::Testing::expect(string_array_field(*describe, "target_names").empty()); + Void::Testing::expect(field(*describe, "target_names_truncated") == nullptr); + + auto shutdown = Void::Build::Daemon::request(socket, R"({"op":"shutdown"})"); + Void::Testing::expect(shutdown.has_value()); + worker.join(); + Void::Testing::expect(run_result.has_value()); + Void::Testing::expect(!std::filesystem::exists(socket)); +} + +VOID_TEST(Daemon, describe_bounds_target_names_for_large_projects) { + auto temp = Void::FileSystem::TempDir::open("vbs_daemon_"); + Void::Testing::require(temp.has_value()); + const auto options = make_options(temp->path()); + + { + std::ofstream descriptor{options.project_root / "build.cpp"}; + descriptor << R"cpp(#include +#include + +void build(Void::Build::Project &project) { + for (int i = 0; i < 140; ++i) { + auto target = project.executable(std::to_string(i) + std::string(240, 'a')); + target.sources({"main.cpp"}); + } +} +)cpp"; + Void::Testing::require(descriptor.good()); + } + { + std::ofstream source{options.project_root / "main.cpp"}; + source << "int main() { return 0; }\n"; + Void::Testing::require(source.good()); + } + + auto server = Void::Build::Daemon::DaemonServer::create(options); + Void::Testing::require(server.has_value()); + const auto socket = server->socket_path(); + + Void::Result::Result run_result; + std::jthread worker{[&] { run_result = server->run(); }}; + Void::Testing::require(wait_for_path(socket, std::chrono::seconds{5})); + + auto raw = + Void::Build::Daemon::request(socket, R"({"op":"describe"})", std::chrono::seconds{120}); + Void::Testing::require(raw.has_value()); + // 128 names x 200 bytes plus JSON overhead stays well under 32 KiB. + Void::Testing::expect(raw->size() < 32U * 1024U); + const auto parsed = parse_json(*raw); + Void::Testing::require(parsed.has_value()); + const auto *object = as_object(*parsed); + Void::Testing::require(object != nullptr); + Void::Testing::expect(bool_field(*object, "ok")); + Void::Testing::expect_eq(int_field(*object, "targets"), std::int64_t{140}); + Void::Testing::expect(int_field(*object, "actions") >= 140); + const auto names = string_array_field(*object, "target_names"); + Void::Testing::expect_eq(names.size(), std::size_t{128}); + for (const auto &name : names) { + Void::Testing::expect(name.size() <= 200U); + } + Void::Testing::expect(bool_field(*object, "target_names_truncated")); + + auto shutdown = Void::Build::Daemon::request(socket, R"({"op":"shutdown"})"); + Void::Testing::expect(shutdown.has_value()); + worker.join(); + Void::Testing::expect(run_result.has_value()); + Void::Testing::expect(!std::filesystem::exists(socket)); +} + +VOID_TEST(Daemon, describe_rejects_workspace_root) { + auto temp = Void::FileSystem::TempDir::open("vbs_daemon_"); + Void::Testing::require(temp.has_value()); + const auto options = make_options(temp->path()); + + { + std::ofstream workspace{options.project_root / "workspace.cpp"}; + workspace << "void workspace(Void::Build::Workspace &workspace) {}\n"; + Void::Testing::require(workspace.good()); + } + + auto server = Void::Build::Daemon::DaemonServer::create(options); + Void::Testing::require(server.has_value()); + const auto socket = server->socket_path(); + + Void::Result::Result run_result; + std::jthread worker{[&] { run_result = server->run(); }}; + Void::Testing::require(wait_for_path(socket, std::chrono::seconds{5})); + + auto describe = request_object(socket, R"({"op":"describe"})"); + Void::Testing::require(describe.has_value()); + Void::Testing::expect(!bool_field(*describe, "ok", true)); + Void::Testing::expect(str_field(*describe, "error").find("workspace") != std::string::npos); + + auto shutdown = Void::Build::Daemon::request(socket, R"({"op":"shutdown"})"); + Void::Testing::expect(shutdown.has_value()); + worker.join(); + Void::Testing::expect(run_result.has_value()); + Void::Testing::expect(!std::filesystem::exists(socket)); +} diff --git a/tests/SigningTests.cpp b/tests/SigningTests.cpp new file mode 100644 index 0000000..2a0213e --- /dev/null +++ b/tests/SigningTests.cpp @@ -0,0 +1,207 @@ +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr std::string_view kDigest = + "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + +std::string read_text(const std::filesystem::path &path) { + std::ifstream stream{path, std::ios::binary}; + return std::string{std::istreambuf_iterator{stream}, std::istreambuf_iterator{}}; +} + +void write_text(const std::filesystem::path &path, std::string_view text) { + std::ofstream stream{path, std::ios::binary | std::ios::trunc}; + stream.write(text.data(), static_cast(text.size())); +} + +bool is_lower_hex(std::string_view text) { + return std::ranges::all_of( + text, [](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); }); +} + +std::string uppercase(std::string value) { + std::ranges::transform(value, value.begin(), [](char c) { + return static_cast(std::toupper(static_cast(c))); + }); + return value; +} + +std::string tampered(std::string value) { + value.front() = value.front() == '0' ? '1' : '0'; + return value; +} + +Void::FileSystem::TempDir make_temp_dir() { + auto temp = Void::FileSystem::TempDir::open("vbs_signing_"); + Void::Testing::require(temp.has_value()); + return std::move(*temp); +} + +} // namespace + +VOID_TEST(Signing, canonical_package_message_is_exact_and_stable) { + using Void::Build::Provenance::canonical_package_message; + const std::string expected = + "vbs-package-v1\nvoid-core@1.2.3\nsha256:" + std::string{kDigest} + "\n"; + Void::Testing::expect_eq(canonical_package_message("void-core", "1.2.3", kDigest), expected); + Void::Testing::expect_eq(canonical_package_message("void-core", "1.2.3", kDigest), expected); +} + +VOID_TEST(Signing, seed_roundtrip_sign_verify_and_rejections) { + namespace Provenance = Void::Build::Provenance; + if (!Provenance::signing_available()) { + return; + } + + auto temp = make_temp_dir(); + const auto seed_path = temp.path() / "signing.seed"; + + auto generated = Provenance::generate_signing_seed(seed_path); + Void::Testing::require(generated.has_value()); + + const std::string contents = read_text(seed_path); + Void::Testing::expect_eq(contents.size(), std::size_t{65}); + if (contents.size() == 65) { + Void::Testing::expect(contents.back() == '\n'); + Void::Testing::expect(is_lower_hex(std::string_view{contents}.substr(0, 64))); + } + + using Perms = std::filesystem::perms; + const auto permissions = std::filesystem::status(seed_path).permissions(); + Void::Testing::expect((permissions & Perms::owner_read) != Perms::none); + Void::Testing::expect((permissions & Perms::owner_write) != Perms::none); + Void::Testing::expect((permissions & (Perms::group_all | Perms::others_all)) == Perms::none); + + auto public_key = Provenance::public_key_from_seed(seed_path); + Void::Testing::require(public_key.has_value()); + Void::Testing::expect_eq(public_key->size(), std::size_t{64}); + + auto signature = Provenance::sign_package("void-core", "1.2.3", kDigest, seed_path); + Void::Testing::require(signature.has_value()); + Void::Testing::expect_eq(signature->size(), std::size_t{128}); + + auto verified = + Provenance::verify_package("void-core", "1.2.3", kDigest, *signature, *public_key); + Void::Testing::require(verified.has_value()); + Void::Testing::expect(*verified); + + // Hex input accepts uppercase as well as lowercase. + auto upper_verified = Provenance::verify_package("void-core", "1.2.3", kDigest, + uppercase(*signature), uppercase(*public_key)); + Void::Testing::require(upper_verified.has_value()); + Void::Testing::expect(*upper_verified); + + std::string other_digest{kDigest}; + other_digest.back() = other_digest.back() == '0' ? '1' : '0'; + auto digest_result = + Provenance::verify_package("void-core", "1.2.3", other_digest, *signature, *public_key); + Void::Testing::require(digest_result.has_value()); + Void::Testing::expect(!*digest_result); + + auto signature_result = Provenance::verify_package("void-core", "1.2.3", kDigest, + tampered(*signature), *public_key); + Void::Testing::require(signature_result.has_value()); + Void::Testing::expect(!*signature_result); + + const auto other_seed_path = temp.path() / "other.seed"; + Void::Testing::require(Provenance::generate_signing_seed(other_seed_path).has_value()); + auto other_public_key = Provenance::public_key_from_seed(other_seed_path); + Void::Testing::require(other_public_key.has_value()); + Void::Testing::expect(*other_public_key != *public_key); + + auto wrong_key_result = + Provenance::verify_package("void-core", "1.2.3", kDigest, *signature, *other_public_key); + Void::Testing::require(wrong_key_result.has_value()); + Void::Testing::expect(!*wrong_key_result); +} + +VOID_TEST(Signing, malformed_hex_and_seed_files_are_rejected) { + namespace Provenance = Void::Build::Provenance; + if (!Provenance::signing_available()) { + return; + } + + auto temp = make_temp_dir(); + const auto seed_path = temp.path() / "signing.seed"; + Void::Testing::require(Provenance::generate_signing_seed(seed_path).has_value()); + auto public_key = Provenance::public_key_from_seed(seed_path); + Void::Testing::require(public_key.has_value()); + auto signature = Provenance::sign_package("void-core", "1.2.3", kDigest, seed_path); + Void::Testing::require(signature.has_value()); + + for (const std::string_view bad_signature : + {std::string_view{}, std::string_view{"00"}, std::string_view{std::string(128, 'z')}}) { + auto result = + Provenance::verify_package("void-core", "1.2.3", kDigest, bad_signature, *public_key); + Void::Testing::expect(!result.has_value()); + } + auto bad_key = + Provenance::verify_package("void-core", "1.2.3", kDigest, *signature, "not-a-key"); + Void::Testing::expect(!bad_key.has_value()); + + const auto bad_seed_path = temp.path() / "bad.seed"; + write_text(bad_seed_path, std::string(63, 'a')); + Void::Testing::expect(!Provenance::public_key_from_seed(bad_seed_path).has_value()); + + write_text(bad_seed_path, std::string(64, 'g')); + Void::Testing::expect(!Provenance::public_key_from_seed(bad_seed_path).has_value()); + + write_text(bad_seed_path, std::string(64, 'a') + "trailing"); + Void::Testing::expect(!Provenance::public_key_from_seed(bad_seed_path).has_value()); + + // Optional trailing whitespace is accepted. + write_text(bad_seed_path, read_text(seed_path) + " \t\r\n"); + auto whitespace_key = Provenance::public_key_from_seed(bad_seed_path); + Void::Testing::require(whitespace_key.has_value()); + Void::Testing::expect_eq(*whitespace_key, *public_key); + + const auto directory_path = temp.path() / "seed-directory"; + std::filesystem::create_directory(directory_path); + Void::Testing::expect(!Provenance::public_key_from_seed(directory_path).has_value()); + Void::Testing::expect( + !Provenance::public_key_from_seed(temp.path() / "missing.seed").has_value()); +} + +VOID_TEST(Signing, backend_gating_reports_openssl_requirement) { + namespace Provenance = Void::Build::Provenance; + if (Provenance::signing_available()) { + return; + } + + auto temp = make_temp_dir(); + const auto seed_path = temp.path() / "signing.seed"; + + auto generated = Provenance::generate_signing_seed(seed_path); + Void::Testing::expect(!generated.has_value()); + if (!generated) { + Void::Testing::expect(generated.error().message().find("OpenSSL") != std::string::npos); + } + + auto signed_result = Provenance::sign_package("void-core", "1.2.3", kDigest, seed_path); + Void::Testing::expect(!signed_result.has_value()); + if (!signed_result) { + Void::Testing::expect(signed_result.error().message().find("OpenSSL") != std::string::npos); + } + + auto verified_result = Provenance::verify_package("void-core", "1.2.3", kDigest, + std::string(128, '0'), std::string(64, '0')); + Void::Testing::expect(!verified_result.has_value()); + if (!verified_result) { + Void::Testing::expect(verified_result.error().message().find("OpenSSL") != + std::string::npos); + } +}