feat(provenance,daemon): add Ed25519 signing primitives and bounded daemon describe op
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 3s
VoidBuildSystem CI / signing-openssl-gcc16 (push) Failing after 9s

This commit is contained in:
faumaray committed 2026-12-03 17:30:12 +03:00
1 parent 0bde74f739
commit 21babb8c31
16 files changed
+1232 -20

No files matched your search

+154
View File
@@ -1,10 +1,16 @@
#include <Void/Build/Daemon/Daemon.hpp>
#include <Void/Build.hpp>
#include <Void/Build/BootstrapConfig.hpp>
#include <Void/Build/Config/Frontend.hpp>
#include <Void/Build/Graph/Graph.hpp>
#include <Void/Build/State/StateStore.hpp>
#include <Void/Build/Toolchain/Driver.hpp>
#include <Void/Build/Watch/Watcher.hpp>
#include <Void/Data/StrictJson.hpp>
#include <Void/Functional/Error.hpp>
#include <algorithm>
#include <cerrno>
#include <chrono>
#include <cstddef>
@@ -13,6 +19,7 @@
#include <fcntl.h>
#include <format>
#include <limits>
#include <optional>
#include <poll.h>
#include <string>
#include <string_view>
@@ -23,6 +30,7 @@
#include <unistd.h>
#include <utility>
#include <variant>
#include <vector>
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<std::filesystem::path> 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<CompilerFamily> 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<std::string> 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<std::int64_t>(graph->targets.size())});
object.emplace("actions", JsonValue{static_cast<std::int64_t>(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<std::string>(&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<CompilerFamily> compiler_override;
if (const auto entry = object->find("compiler"); entry != object->end()) {
const auto *value = std::get_if<std::string>(&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};
}
+19 -1
View File
@@ -38,6 +38,7 @@
#include <algorithm>
#include <array>
#include <charconv>
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <filesystem>
@@ -1535,6 +1536,7 @@ struct DaemonCmdOptions {
std::string project_arg;
std::optional<std::string> build_arg;
std::optional<std::string> 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()) {
+374
View File
@@ -0,0 +1,374 @@
#include <Void/Build/Provenance/Signing.hpp>
#include <Void/Crypto/Crypto.hpp>
#include <Void/System/Types.hpp>
#include <Void/Text/Hex.hpp>
#include <algorithm>
#include <array>
#include <cctype>
#include <cstddef>
#include <format>
#include <fstream>
#include <iterator>
#include <span>
#include <string>
#include <string_view>
#include <utility>
#ifndef _WIN32
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#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<void, Error> 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<std::byte>{reinterpret_cast<std::byte *>(secret.data()), secret.size()});
secret.clear();
}
struct SecretWipeGuard {
std::string &secret;
~SecretWipeGuard() { wipe_string(secret); }
};
Result<std::string, Error> 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<std::string, Error> 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<char, 512> 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<std::size_t>(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<char>{stream}, std::istreambuf_iterator<char>{}};
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<Void::Crypto::Ed25519Seed, Error> 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<unsigned char>(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<void, Error> 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<std::size_t>(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<std::streamsize>(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<void, Error> 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<std::string, Error> 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<std::string, Error> 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<const char>{message.data(), message.size()}), *private_key);
if (!signature) {
return std::unexpected{signature.error()};
}
return Void::Encoding::Hex::encode(signature->view());
}
Result<bool, Error> 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<const char>{message.data(), message.size()}), *signature,
*public_key);
}
} // namespace Void::Build::Provenance