diff --git a/CMakeLists.txt b/CMakeLists.txt index 242c1e0..52b25c8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -64,6 +64,7 @@ add_library(VoidBuild_Core STATIC src/Provenance/Sbom.cpp src/Provenance/Signing.cpp src/Provenance/Verification.cpp + src/Provenance/TrustedKeys.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 99e7963..4280f21 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] [--sbom FILE] [--sbom-format spdx|cyclonedx] [--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] [--trusted-public-key HEX]... [--trusted-key-file FILE]... [--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 0cf6e61..6b97b76 100644 --- a/build.cpp +++ b/build.cpp @@ -52,6 +52,7 @@ void build(Void::Build::Project &project) { "src/Provenance/Sbom.cpp", "src/Provenance/Signing.cpp", "src/Provenance/Verification.cpp", + "src/Provenance/TrustedKeys.cpp", "recipes/VoidLibrary/VoidLibraryRecipe.cpp", "recipes/SelfHost/VbsSelfHostRecipe.cpp", }) diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index ec419c1..19241a0 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -93,9 +93,13 @@ Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B - Extracted the CLI's dependency resolution/materialization pipeline into the reusable library API `Package::resolve_and_materialize_dependencies` (`include/Void/Build/Package/Resolver.hpp`, `src/Package/Resolver.cpp`) with explicit `ResolveOptions` (project/build root, pinned lock, offline/upgrade, trusted keys, registry URL/auth); `src/Main.cpp` is now a thin adapter over it. - The daemon `build` request now loads TOML dependency manifests, merges declared dependencies, resolves and materializes them (pinned lock + registry environment), imports native/CMake/Meson/Conan provider targets, and lowers the graph with those imported interfaces before executing. Responses report `dependencies`. Added `Daemon.build_materializes_path_dependency` (path dependency materialized, imported, linked, and built over the socket). +- **Wave 19 (Track D3 Trusted-Key Distribution)**: + - Added `Void::Build::Provenance::load_trusted_keys` / `normalize_public_key` (`include/Void/Build/Provenance/TrustedKeys.hpp`, `src/Provenance/TrustedKeys.cpp`): keys are loaded from explicit `--trusted-key-file` files, an implicit project `vbs.keys` ring, and `VBS_TRUSTED_PUBLIC_KEYS` (comma/whitespace separated), validated as 64-hex, lowercased, and deduplicated. Malformed keys and unreadable files fail explicitly with `file:line` context. + - `vbs build|test` combines inline `--trusted-public-key` values with file/env sources; the daemon build request loads `vbs.keys` + the environment variable before resolving dependencies. `SignatureEnforcement` now has 5 cases. + ## 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, Ed25519 primitives, trusted-key enforcement, the #52 built-in-backend capability probe, and the VoidLibrary pin bump to `0002e74` done; binary-variant signing and key distribution remain), Track E3 (daemon core, bounded `describe`, build-serving, and dependency materialization done; 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, Ed25519 primitives, trusted-key enforcement and distribution, the #52 built-in-backend capability probe, and the VoidLibrary pin bump to `0002e74` done; binary-variant signing remains), Track E3 (daemon core, bounded `describe`, build-serving, and dependency materialization done; 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 bb89729..75bb389 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -25,4 +25,5 @@ Base HEAD: `fe0d1a6` | Wave 16 (Track E3 daemon build serving) | In-process daemon `build` request reusing graph lowering + `Execution::execute_graph` against the warm `StateStore`; bounded `profile`/`targets`/`jobs`; `vbs daemon build` CLI; cache-reuse test | COMPLETE & VERIFIED (GCC 16.2; Daemon suite 7/7) | `src/Daemon/Daemon.cpp`, `include/Void/Build/Daemon/Daemon.hpp`, `src/Main.cpp`, `tests/DaemonTests.cpp`, `tests/CliContracts.cmake`, docs | | Wave 17 (VoidLibrary #52 follow-up + pin bump) | `signing_available()` probes the real Ed25519 capability instead of `has_openssl_backend()`; VoidLibrary pin bumped to `0002e74a7da94a756f55a4a5574d20b77736c185` (contains #52) and pin assertions updated | COMPLETE & VERIFIED (GCC 16.2, fresh remote fetch of the pin, no OpenSSL: Signing 4/4 crypto path, SignatureEnforcement 3/3, full CTest 8/8) | `CMakeLists.txt`, `build.cpp`, `src/Provenance/Signing.cpp`, `include/Void/Build/Provenance/Signing.hpp`, `tests/{SigningTests.cpp,ExampleContexts.cpp,DescribeContracts.cmake}`, docs | | Wave 18 (Track E3 daemon dependency materialization) | Extracted `Package::resolve_and_materialize_dependencies` (`Resolver.hpp/.cpp`) from the CLI; daemon `build` now merges TOML deps, resolves/materializes with the pinned lock, imports provider targets, lowers with imported interfaces, and reports `dependencies` | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Daemon 8/8, full CTest 8/8) | `include/Void/Build/Package/Resolver.hpp`, `src/Package/Resolver.cpp`, `src/Main.cpp`, `src/Daemon/Daemon.cpp`, `tests/DaemonTests.cpp`, build lists, docs | +| Wave 19 (Track D3 trusted-key distribution) | `Provenance::load_trusted_keys` over `--trusted-key-file`, project `vbs.keys`, and `VBS_TRUSTED_PUBLIC_KEYS`; 64-hex validation/lowercasing/dedup with `file:line` errors; wired into CLI builds and daemon dependency resolution | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; SignatureEnforcement 5/5, Daemon 8/8, full CTest 8/8) | `include/Void/Build/Provenance/TrustedKeys.hpp`, `src/Provenance/TrustedKeys.cpp`, `src/Main.cpp`, `src/Daemon/Daemon.cpp`, `tests/SignatureEnforcementTests.cpp`, build lists, docs | | Future (Plan 20 Slice 3 / Tracks C, D3 binary signing, E3 editor plugins, E4, live `conan`) | Live `conan` CLI verification; macOS/Windows/cross-compile; binary-variant signing and key distribution; daemon-side dependency materialization and editor plugins; `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 d0711ba..33d6327 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -370,6 +370,23 @@ dev cpp-gcc -c ctest --test-dir build/pinned --output-on-failure `src/Package/Resolver.cpp`, `include/Void/Build/Package/Resolver.hpp`, and `tests/DaemonTests.cpp`. +## Track D3 Trusted-Key Distribution (GCC 16.2, pin `0002e74`) + +```sh +dev cpp-gcc -c cmake --build build/pinned --parallel 8 +dev cpp-gcc -c build/pinned/bin/vbs_v1_tests --suite SignatureEnforcement --no-color +dev cpp-gcc -c ctest --test-dir build/pinned --output-on-failure +``` + +- Build: exit 0. `SignatureEnforcement`: **5 / 5 passed** in 90 ms, including + `trusted_key_sources_are_loaded_and_deduplicated` (explicit file with comments/blank lines and a + duplicate, implicit `vbs.keys`, and a comma-separated environment value deduplicate to + `[a, b, c, d]`; a missing file and a malformed `invalid.keys:2` entry are explicit errors) and + `normalize_public_key_validates_and_lowercases`. +- Daemon suite: **8 / 8 passed** (13.21 s). +- Full CTest: **8 / 8 passed** in 209.27 s. +- `clang-format --dry-run --Werror` passes on all changed/new C++ files. + ## 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 e86118c..5e61443 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, Ed25519 signing primitives, and trusted-key enforcement implemented; OpenSSL or the built-in Ed25519 backend)* | 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; package signature/public-key metadata persisted in `vbs.lock` and registry releases; `vbs publish --signing-key FILE`; `vbs build\|test --trusted-public-key HEX` enforced before extraction via `Provenance::verify_trusted_package_signature` (`include/Void/Build/Provenance/Verification.hpp`). | SBOM is deterministic and valid JSON; signing primitives pass round-trip/tamper/malformed tests (`tests/SigningTests.cpp`); trusted-key policy tests pass with and without OpenSSL (`tests/SignatureEnforcementTests.cpp`); a signed publish -> deps update -> `--locked` trusted build succeeds and an untrusted/unsigned package fails closed before extraction (`RegistryTests.cpp`). | +| **D3 — Supply-Chain Provenance & Signed Packages** *(SBOM, Ed25519 signing primitives, and trusted-key enforcement implemented; OpenSSL or the built-in Ed25519 backend)* | 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; package signature/public-key metadata persisted in `vbs.lock` and registry releases; `vbs publish --signing-key FILE`; `vbs build\|test --trusted-public-key HEX` enforced before extraction via `Provenance::verify_trusted_package_signature` (`include/Void/Build/Provenance/Verification.hpp`); trusted keys can also come from `--trusted-key-file`, a project `vbs.keys` ring, or `VBS_TRUSTED_PUBLIC_KEYS` (`Provenance::load_trusted_keys`). | SBOM is deterministic and valid JSON; signing primitives pass round-trip/tamper/malformed tests (`tests/SigningTests.cpp`); trusted-key policy tests pass with and without OpenSSL (`tests/SignatureEnforcementTests.cpp`); a signed publish -> deps update -> `--locked` trusted build succeeds and an untrusted/unsigned package fails closed before extraction (`RegistryTests.cpp`). | --- diff --git a/include/Void/Build/Provenance/TrustedKeys.hpp b/include/Void/Build/Provenance/TrustedKeys.hpp new file mode 100644 index 0000000..c01fe3e --- /dev/null +++ b/include/Void/Build/Provenance/TrustedKeys.hpp @@ -0,0 +1,30 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace Void::Build::Provenance { + +// Validates a 64-hex-character Ed25519 public key and returns it lowercase. +[[nodiscard]] Void::Result::Result +normalize_public_key(std::string_view hex); + +// Loads and validates trusted Ed25519 public keys for signed-package enforcement from: +// - each explicit key file (one key per line, '#' comments, blank lines ignored), +// - `/vbs.keys` when it exists (implicit project key ring), +// - an optional comma/whitespace separated environment value. +// Duplicates are removed preserving first-seen order. Explicit files must exist; malformed +// keys or unreadable files are explicit errors (never silently ignored). +[[nodiscard]] Void::Result::Result, Void::Result::Error> +load_trusted_keys(std::span explicit_files, + const std::filesystem::path &project_root, + std::optional environment_value); + +} // namespace Void::Build::Provenance diff --git a/recipes/SelfHost/VbsSelfHostRecipe.cpp b/recipes/SelfHost/VbsSelfHostRecipe.cpp index 717c4c6..565fc06 100644 --- a/recipes/SelfHost/VbsSelfHostRecipe.cpp +++ b/recipes/SelfHost/VbsSelfHostRecipe.cpp @@ -105,6 +105,7 @@ add_vbs_selfhost_native(Project &project, const VbsSelfHostConfig &config) { "src/Provenance/Sbom.cpp", "src/Provenance/Signing.cpp", "src/Provenance/Verification.cpp", + "src/Provenance/TrustedKeys.cpp", "recipes/VoidLibrary/VoidLibraryRecipe.cpp", "recipes/SelfHost/VbsSelfHostRecipe.cpp", }; diff --git a/src/Daemon/Daemon.cpp b/src/Daemon/Daemon.cpp index 37835af..003bb3c 100644 --- a/src/Daemon/Daemon.cpp +++ b/src/Daemon/Daemon.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -440,6 +441,18 @@ Void::Result::Result materialize_project_dependencies( resolve_options.default_registry_url = Void::Configuration::get_env_or("VBS_REGISTRY_URL", ""); resolve_options.registry_auth = Package::RegistryAuth{Void::Configuration::get_env_or("VBS_REGISTRY_TOKEN", "")}; + const std::string trusted_environment = + Void::Configuration::get_env_or("VBS_TRUSTED_PUBLIC_KEYS", ""); + std::optional trusted_environment_value; + if (!trusted_environment.empty()) { + trusted_environment_value = trusted_environment; + } + auto trusted_keys = + Provenance::load_trusted_keys({}, options.project_root, trusted_environment_value); + if (!trusted_keys) { + return std::unexpected{std::format("build: {}", trusted_keys.error().format())}; + } + resolve_options.trusted_public_keys = std::move(*trusted_keys); auto resolved = Package::resolve_and_materialize_dependencies(evaluated.context, *merged, resolve_options); if (!resolved) { diff --git a/src/Main.cpp b/src/Main.cpp index 8ed7451..ee9b354 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -282,6 +283,33 @@ Void::Result::Result resolve_an return Package::resolve_and_materialize_dependencies(ctx, merged_deps, options); } +Void::Result::Result, Void::Result::Error> +combine_trusted_keys(const std::vector &inline_keys, + const std::vector &key_files, + const std::filesystem::path &project_root) { + std::vector files; + files.reserve(key_files.size()); + for (const auto &file : key_files) { + files.emplace_back(file); + } + const std::string environment = Void::Configuration::get_env_or("VBS_TRUSTED_PUBLIC_KEYS", ""); + std::optional environment_value; + if (!environment.empty()) { + environment_value = environment; + } + auto loaded = Provenance::load_trusted_keys(files, project_root, environment_value); + if (!loaded) { + return std::unexpected{loaded.error()}; + } + std::vector combined = inline_keys; + for (auto &key : *loaded) { + if (std::ranges::find(combined, key) == combined.end()) { + combined.push_back(std::move(key)); + } + } + return combined; +} + struct BuildCmdOptions { std::string project_arg; std::optional build_arg; @@ -300,6 +328,7 @@ struct BuildCmdOptions { std::optional lock_root; std::optional state_dir; std::vector trusted_public_keys; + std::vector trusted_key_files; bool publish_editor_selection{true}; bool no_cache{false}; bool locked{false}; @@ -333,6 +362,12 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { const std::filesystem::path project_root{opts.project_arg}; const std::filesystem::path build_root = opts.build_arg ? std::filesystem::path{*opts.build_arg} : (project_root / "build"); + auto trusted_keys = + combine_trusted_keys(opts.trusted_public_keys, opts.trusted_key_files, project_root); + if (!trusted_keys) { + std::cerr << cmd_name << ": " << trusted_keys.error().message() << '\n'; + return 1; + } std::vector extra_build_sources; for (const auto &s : opts.extra_build_sources) { extra_build_sources.emplace_back(s); @@ -492,9 +527,9 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { return 1; } - auto resolved = resolve_and_materialize_deps(ctx, *merged_deps, project_root, - build_root, *pinned_lock, opts.offline, - false, opts.trusted_public_keys); + auto resolved = + resolve_and_materialize_deps(ctx, *merged_deps, project_root, build_root, + *pinned_lock, opts.offline, false, *trusted_keys); if (!resolved) { std::cerr << "vbs: " << resolved.error().message() << '\n'; return 1; @@ -2151,7 +2186,10 @@ int main(int argc, char **argv) { build_opts.native_foreign) .option_many("--trusted-public-key", "", "Trusted Ed25519 package public key (hex; repeatable)", - build_opts.trusted_public_keys); + build_opts.trusted_public_keys) + .option_many("--trusted-key-file", "", + "File with trusted Ed25519 public keys (repeatable)", + build_opts.trusted_key_files); add_log_flags(p); }; diff --git a/src/Provenance/TrustedKeys.cpp b/src/Provenance/TrustedKeys.cpp new file mode 100644 index 0000000..16c0ed4 --- /dev/null +++ b/src/Provenance/TrustedKeys.cpp @@ -0,0 +1,145 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Build::Provenance { +namespace { + +using Void::Result::Error; +using Void::Result::ErrorKind; +using Void::Result::Result; + +constexpr std::size_t PublicKeyHexLength = 64; + +Error make_error(ErrorKind kind, std::string message) { return Error{kind, std::move(message)}; } + +std::string_view trim_ascii(std::string_view text) { + while (!text.empty() && std::isspace(static_cast(text.front())) != 0) { + text.remove_prefix(1); + } + while (!text.empty() && std::isspace(static_cast(text.back())) != 0) { + text.remove_suffix(1); + } + return text; +} + +bool is_hex_digit(char c) noexcept { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); +} + +Result add_key(std::string_view raw, std::string_view origin, + std::vector &keys, std::set &seen) { + const std::string_view trimmed = trim_ascii(raw); + if (trimmed.empty()) { + return {}; + } + if (trimmed.size() != PublicKeyHexLength || !std::ranges::all_of(trimmed, is_hex_digit)) { + return std::unexpected{make_error( + ErrorKind::invalid_argument, + std::format("{}: trusted public key must be exactly {} hex characters, got '{}'", + origin, PublicKeyHexLength, trimmed))}; + } + std::string normalized{trimmed}; + std::ranges::transform(normalized, normalized.begin(), [](char c) { + return static_cast(std::tolower(static_cast(c))); + }); + if (seen.insert(normalized).second) { + keys.push_back(std::move(normalized)); + } + return {}; +} + +Result add_key_file(const std::filesystem::path &path, std::vector &keys, + std::set &seen) { + std::ifstream stream{path}; + if (!stream) { + return std::unexpected{make_error( + ErrorKind::io, std::format("cannot open trusted key file '{}'", path.string()))}; + } + std::string line; + std::size_t line_number = 0; + while (std::getline(stream, line)) { + ++line_number; + const auto comment = line.find('#'); + if (comment != std::string::npos) { + line.resize(comment); + } + if (auto added = + add_key(line, std::format("{}:{}", path.string(), line_number), keys, seen); + !added) { + return added; + } + } + if (!stream.eof()) { + return std::unexpected{make_error( + ErrorKind::io, std::format("cannot read trusted key file '{}'", path.string()))}; + } + return {}; +} + +} // namespace + +Result normalize_public_key(std::string_view hex) { + const std::string_view trimmed = trim_ascii(hex); + if (trimmed.size() != PublicKeyHexLength || !std::ranges::all_of(trimmed, is_hex_digit)) { + return std::unexpected{ + make_error(ErrorKind::invalid_argument, + std::format("trusted public key must be exactly {} hex characters", + PublicKeyHexLength))}; + } + std::string normalized{trimmed}; + std::ranges::transform(normalized, normalized.begin(), [](char c) { + return static_cast(std::tolower(static_cast(c))); + }); + return normalized; +} + +Result, Error> +load_trusted_keys(std::span explicit_files, + const std::filesystem::path &project_root, + std::optional environment_value) { + std::vector keys; + std::set seen; + + for (const auto &file : explicit_files) { + if (auto added = add_key_file(file, keys, seen); !added) { + return std::unexpected{added.error()}; + } + } + + const auto project_key_file = project_root / "vbs.keys"; + std::error_code ec; + if (std::filesystem::is_regular_file(project_key_file, ec)) { + if (auto added = add_key_file(project_key_file, keys, seen); !added) { + return std::unexpected{added.error()}; + } + } + + if (environment_value) { + std::string_view text = *environment_value; + while (!text.empty()) { + const auto separator = text.find_first_of(", \t\r\n"); + const std::string_view token = + separator == std::string_view::npos ? text : text.substr(0, separator); + if (auto added = add_key(token, "VBS_TRUSTED_PUBLIC_KEYS", keys, seen); !added) { + return std::unexpected{added.error()}; + } + if (separator == std::string_view::npos) { + break; + } + text.remove_prefix(separator + 1); + } + } + + return keys; +} + +} // namespace Void::Build::Provenance diff --git a/tests/SignatureEnforcementTests.cpp b/tests/SignatureEnforcementTests.cpp index 280f106..9c3bd17 100644 --- a/tests/SignatureEnforcementTests.cpp +++ b/tests/SignatureEnforcementTests.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -120,6 +121,61 @@ VOID_TEST(SignatureEnforcement, trust_policy_decisions_without_crypto) { } } +VOID_TEST(SignatureEnforcement, trusted_key_sources_are_loaded_and_deduplicated) { + namespace Provenance = Void::Build::Provenance; + auto temp = make_temp_dir(); + const std::string key_c(64, 'c'); + const std::string key_d(64, 'd'); + + const auto explicit_file = temp.path() / "keys.txt"; + { + std::ofstream out{explicit_file}; + out << "# trusted maintainers\n" << kKeyA << "\n\n" << kKeyB << "\n" << kKeyA << "\n"; + } + { + std::ofstream out{temp.path() / "vbs.keys"}; + out << kKeyB << "\n" << key_c << "\n"; + } + + std::vector files{explicit_file}; + const std::string environment = key_d + "," + kKeyA; + auto loaded = Provenance::load_trusted_keys(files, temp.path(), std::string_view{environment}); + Void::Testing::require(loaded.has_value()); + Void::Testing::expect_eq(loaded->size(), std::size_t{4}); + if (loaded->size() == 4) { + Void::Testing::expect((*loaded)[0] == kKeyA); + Void::Testing::expect((*loaded)[1] == kKeyB); + Void::Testing::expect((*loaded)[2] == key_c); + Void::Testing::expect((*loaded)[3] == key_d); + } + + std::vector missing{temp.path() / "missing.keys"}; + Void::Testing::expect( + !Provenance::load_trusted_keys(missing, temp.path(), std::nullopt).has_value()); + + const auto invalid_file = temp.path() / "invalid.keys"; + { + std::ofstream out{invalid_file}; + out << kKeyA << "\nnot-a-key\n"; + } + std::vector invalid{invalid_file}; + auto invalid_result = Provenance::load_trusted_keys(invalid, temp.path(), std::nullopt); + Void::Testing::expect(!invalid_result.has_value()); + if (!invalid_result) { + Void::Testing::expect(invalid_result.error().message().find("invalid.keys:2") != + std::string::npos); + } +} + +VOID_TEST(SignatureEnforcement, normalize_public_key_validates_and_lowercases) { + namespace Provenance = Void::Build::Provenance; + auto valid = Provenance::normalize_public_key(std::string(64, 'A')); + Void::Testing::require(valid.has_value()); + Void::Testing::expect(*valid == std::string(64, 'a')); + Void::Testing::expect(!Provenance::normalize_public_key("abc").has_value()); + Void::Testing::expect(!Provenance::normalize_public_key(std::string(64, 'z')).has_value()); +} + VOID_TEST(SignatureEnforcement, trusted_key_accepts_valid_and_rejects_tampered_signature) { using Void::Build::Provenance::PackageSignature; if (!signing_available()) {