Files
Build-System/src/Package/RegistryClient.cpp
T
faumaray 452b2e315d
VoidBuildSystem CI / sanitizers-gcc16 (push) Failing after 3s
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 4s
VoidBuildSystem CI / signing-openssl-gcc16 (push) Failing after 32s
VoidBuildSystem CI / wine-windows-gcc16 (push) Failing after 52s
feat(worker): lease queued actions in vbs worker
2026-12-05 11:36:17 +03:00

1153 lines
50 KiB
C++

#include <Void/Build/Package/RegistryClient.hpp>
#include <Void/Build/Package/Fetch.hpp>
#include <Void/Build/Platform/FileOps.hpp>
#include <Void/Build/Platform/ProcessSupervisor.hpp>
#include <Void/Build/Provenance/Signing.hpp>
#include <Void/Build/Provenance/Verification.hpp>
#include <Void/Build/Util/Sha256.hpp>
#include <Void/Core/Scope.hpp>
#include <Void/Data/StrictJson.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Types.hpp>
#include <Void/Text/Semver.hpp>
#include <Void/Text/Str.hpp>
#include <Void/Text/Url.hpp>
#if defined(VBS_HAS_VOID_NET)
#include <Void/Net/Http.hpp>
#endif
#include <algorithm>
#include <arpa/inet.h>
#include <array>
#include <cerrno>
#include <cstring>
#include <format>
#include <map>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
namespace Void::Build::Package {
namespace {
using JsonVal = Void::Json::Strict::Value;
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg) {
return Void::System::make_system_error(code, redact_secrets(msg));
}
struct ParsedHttpUrl {
std::string scheme;
std::string host;
std::uint16_t port{80};
std::string base_path;
};
Void::Result::Result<ParsedHttpUrl, Void::Result::Error> parse_registry_url(std::string_view url) {
url = Void::Str::trim_ascii(url);
const auto sep = url.find("://");
if (sep == std::string_view::npos) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"registry URL must include http:// or https:// scheme")};
}
ParsedHttpUrl out;
out.scheme = Void::Str::to_lower_ascii(url.substr(0, sep));
if (out.scheme != "http" && out.scheme != "https") {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"unsupported registry URL scheme (expected http/https)")};
}
const auto rest = url.substr(sep + 3);
const auto slash = rest.find('/');
const auto authority = slash == std::string_view::npos ? rest : rest.substr(0, slash);
out.base_path =
slash == std::string_view::npos ? std::string{} : std::string{rest.substr(slash)};
while (!out.base_path.empty() && out.base_path.back() == '/') {
out.base_path.pop_back();
}
const auto colon = authority.rfind(':');
if (colon != std::string_view::npos) {
out.host = std::string{authority.substr(0, colon)};
int p = 0;
if (!Void::Str::to_int(authority.substr(colon + 1), p) || p <= 0 || p > 65535) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"invalid port in registry URL")};
}
out.port = static_cast<std::uint16_t>(p);
} else {
out.host = std::string{authority};
out.port = (out.scheme == "https") ? 443 : 80;
}
if (out.host.empty()) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"empty host in registry URL")};
}
return out;
}
struct RawHttpReply {
std::uint16_t status{0};
std::map<std::string, std::string, std::less<>> headers;
std::string body;
};
bool send_all(int fd, std::string_view data) {
std::size_t off = 0;
while (off < data.size()) {
const ssize_t n = ::send(fd, data.data() + off, data.size() - off, MSG_NOSIGNAL);
if (n < 0) {
if (errno == EINTR) {
continue;
}
return false;
}
off += static_cast<std::size_t>(n);
}
return true;
}
Void::Result::Result<RawHttpReply, Void::Result::Error>
send_http_request(const ParsedHttpUrl &parsed, std::string_view method, std::string_view path,
const std::map<std::string, std::string, std::less<>> &headers,
std::string_view body) {
const std::string full_path = parsed.base_path + std::string{path};
#if defined(VBS_HAS_VOID_NET)
// Track E4: Void::Net transport handles both http:// and verified TLS https://.
Void::Net::Request request;
if (method == "GET") {
request.method = Void::Net::Method::Get;
} else if (method == "PUT") {
request.method = Void::Net::Method::Put;
} else if (method == "POST") {
request.method = Void::Net::Method::Post;
} else if (method == "DELETE") {
request.method = Void::Net::Method::Delete;
} else {
request.method = Void::Net::Method::Get;
}
request.url = std::format("{}://{}:{}{}", parsed.scheme, parsed.host, parsed.port, full_path);
for (const auto &[name, value] : headers) {
request.headers.push_back(Void::Net::Header{name, value});
}
if (!body.empty()) {
request.body = std::string{body};
}
request.timeout = std::chrono::seconds{30};
const Void::Net::HttpClient net_client = Void::Net::HttpClient::secure();
auto net_response = net_client.send(request);
if (!net_response) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::io_error,
std::format("registry client: Void::Net request failed: {}",
net_response.error().message()))};
}
RawHttpReply net_reply;
net_reply.status = net_response->status;
for (const auto &header : net_response->headers) {
net_reply.headers[Void::Str::to_lower_ascii(header.name)] = header.value;
}
net_reply.body = std::move(net_response->body);
return net_reply;
#else
// Plain TCP HTTP/1.1 client for http:// (loopback/local registry without external deps).
if (parsed.scheme == "http") {
struct addrinfo hints{};
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
struct addrinfo *res = nullptr;
const std::string port_s = std::to_string(parsed.port);
if (::getaddrinfo(parsed.host.c_str(), port_s.c_str(), &hints, &res) != 0 || !res) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::io_error,
std::format("registry client: failed resolving host '{}'", parsed.host))};
}
auto free_ai = Void::Scope::on_exit([&] { ::freeaddrinfo(res); });
const int fd = ::socket(res->ai_family, res->ai_socktype | SOCK_CLOEXEC, res->ai_protocol);
if (fd < 0) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"registry client: socket() failed")};
}
Void::System::OwnedFd guard{fd};
struct timeval tv{30, 0};
(void)::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
(void)::setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
if (::connect(fd, res->ai_addr, res->ai_addrlen) != 0) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::io_error,
std::format("registry client: connect to {}:{} failed", parsed.host, parsed.port))};
}
std::string req = std::format("{} {} HTTP/1.1\r\nHost: {}:{}\r\nConnection: close\r\n"
"Content-Length: {}\r\n",
method, full_path, parsed.host, parsed.port, body.size());
for (const auto &[k, v] : headers) {
req += k + ": " + v + "\r\n";
}
req += "\r\n";
req += body;
if (!send_all(fd, req)) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"registry client: send() failed")};
}
std::string raw;
std::array<char, 16384> buf{};
for (;;) {
const ssize_t n = ::recv(fd, buf.data(), buf.size(), 0);
if (n > 0) {
raw.append(buf.data(), static_cast<std::size_t>(n));
} else if (n == 0) {
break;
} else if (errno != EINTR) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"registry client: recv() failed")};
}
}
const auto hdr_end = raw.find("\r\n\r\n");
if (hdr_end == std::string::npos) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"registry client: malformed HTTP response")};
}
RawHttpReply reply;
const std::string_view hdr_block{raw.data(), hdr_end};
const auto first_crlf = hdr_block.find("\r\n");
const auto status_line = hdr_block.substr(0, first_crlf);
const auto sp1 = status_line.find(' ');
if (sp1 != std::string_view::npos) {
int code = 0;
if (Void::Str::to_int(status_line.substr(sp1 + 1, 3), code)) {
reply.status = static_cast<std::uint16_t>(code);
}
}
if (first_crlf != std::string_view::npos) {
std::size_t pos = first_crlf + 2;
while (pos < hdr_block.size()) {
const auto next = hdr_block.find("\r\n", pos);
const auto line = hdr_block.substr(
pos, next == std::string_view::npos ? std::string_view::npos : next - pos);
const auto colon = line.find(':');
if (colon != std::string_view::npos) {
reply.headers[Void::Str::to_lower_ascii(
Void::Str::trim_ascii(line.substr(0, colon)))] =
std::string{Void::Str::trim_ascii(line.substr(colon + 1))};
}
if (next == std::string_view::npos) {
break;
}
pos = next + 2;
}
}
reply.body = raw.substr(hdr_end + 4);
return reply;
}
// HTTPS fallback via curl (preserves TLS certificate verification; never disables TLS!).
auto curl = Platform::resolve_executable("curl");
if (!curl) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::not_found,
"HTTPS registry operations require curl (OpenSSL/Void::Net not linked)")};
}
const std::string full_url =
std::format("https://{}:{}{}", parsed.host, parsed.port, full_path);
Platform::ProcessRequest req;
req.executable = *curl;
req.arguments = {"--silent", "--show-error", "--proto", "=https",
"-X", std::string{method}, "-w", "\n%{http_code}"};
for (const auto &[k, v] : headers) {
req.arguments.push_back("-H");
req.arguments.push_back(k + ": " + v);
}
if (!body.empty()) {
req.arguments.push_back("--data-binary");
req.arguments.push_back("@-");
req.stdin_data = std::string{body};
}
req.arguments.push_back(full_url);
req.timeout = std::chrono::seconds{120};
auto proc = Platform::run_supervised(req);
if (!proc || !proc->succeeded()) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::io_error,
std::format("HTTPS request failed: {}",
proc ? proc->stderr_data : proc.error().message()))};
}
const auto nl = proc->stdout_data.rfind('\n');
RawHttpReply reply;
if (nl != std::string::npos) {
int code = 0;
if (Void::Str::to_int(Void::Str::trim_ascii(proc->stdout_data.substr(nl + 1)), code)) {
reply.status = static_cast<std::uint16_t>(code);
}
reply.body = proc->stdout_data.substr(0, nl);
}
return reply;
#endif
}
std::string get_str(const JsonVal::Object &obj, const std::string &k) {
const auto it = obj.find(k);
if (it == obj.end()) {
return {};
}
const auto *s = std::get_if<std::string>(&it->second.value);
return s ? *s : std::string{};
}
bool get_bool(const JsonVal::Object &obj, const std::string &k, bool def = false) {
const auto it = obj.find(k);
if (it == obj.end()) {
return def;
}
const auto *b = std::get_if<bool>(&it->second.value);
return b ? *b : def;
}
std::int64_t get_i64(const JsonVal::Object &obj, const std::string &k, std::int64_t def = 0) {
const auto it = obj.find(k);
if (it == obj.end()) {
return def;
}
const auto *i = std::get_if<std::int64_t>(&it->second.value);
return i ? *i : def;
}
} // namespace
Void::Result::Result<std::vector<ReleaseRecord>, Void::Result::Error>
fetch_package_releases(std::string_view registry_url, std::string_view package_name,
const RegistryAuth &auth) {
auto parsed_url = parse_registry_url(registry_url);
if (!parsed_url) {
return std::unexpected{parsed_url.error()};
}
std::map<std::string, std::string, std::less<>> headers;
if (!auth.bearer_token.empty()) {
headers["Authorization"] = "Bearer " + auth.bearer_token;
}
const std::string path = "/api/v1/packages/" + Void::Encoding::Url::encode(package_name);
auto reply = send_http_request(*parsed_url, "GET", path, headers, {});
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status != 200) {
return std::unexpected{make_error(reply->status == 404
? Void::System::SystemErrorCode::not_found
: Void::System::SystemErrorCode::permission_denied,
std::format("registry GET {} failed with HTTP {}: {}",
path, reply->status, reply->body))};
}
auto json = Void::Json::Strict::parse(reply->body);
if (!json) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"invalid JSON returned by registry package endpoint")};
}
const auto *root = std::get_if<JsonVal::Object>(&json->value);
if (!root) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"registry response root must be a JSON object")};
}
std::vector<ReleaseRecord> releases;
const auto rit = root->find("releases");
if (rit != root->end()) {
if (const auto *rarr = std::get_if<JsonVal::Array>(&rit->second.value)) {
for (const auto &rv : *rarr) {
const auto *ro = std::get_if<JsonVal::Object>(&rv.value);
if (!ro) {
continue;
}
const auto ver_str = get_str(*ro, "version");
auto ver = Void::Semver::parse_strict(ver_str);
if (!ver) {
continue;
}
ReleaseRecord rec;
rec.id = PackageId{std::string{registry_url}, std::string{package_name}};
rec.version = *ver;
rec.yanked = get_bool(*ro, "yanked", false);
rec.source_sha256 = get_str(*ro, "sha256");
if (const auto sig = get_str(*ro, "signature"); !sig.empty()) {
rec.signature = sig;
}
if (const auto key = get_str(*ro, "public_key"); !key.empty()) {
rec.public_key = key;
}
rec.source_url = std::string{registry_url} + "/api/v1/packages/" +
Void::Encoding::Url::encode(package_name) + "/" +
Void::Encoding::Url::encode(ver_str) + "/download";
releases.push_back(std::move(rec));
}
}
}
return releases;
}
Void::Result::Result<std::filesystem::path, Void::Result::Error>
download_release_archive(std::string_view registry_url, std::string_view package_name,
std::string_view version, std::string_view expected_sha256,
const std::filesystem::path &dest_file, const RegistryAuth &auth) {
auto parsed_url = parse_registry_url(registry_url);
if (!parsed_url) {
return std::unexpected{parsed_url.error()};
}
std::map<std::string, std::string, std::less<>> headers;
if (!auth.bearer_token.empty()) {
headers["Authorization"] = "Bearer " + auth.bearer_token;
}
const std::string path = "/api/v1/packages/" + Void::Encoding::Url::encode(package_name) + "/" +
Void::Encoding::Url::encode(version) + "/download";
auto reply = send_http_request(*parsed_url, "GET", path, headers, {});
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status != 200) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
std::format("registry download {}@{} failed with HTTP {}",
package_name, version, reply->status))};
}
const std::string actual_sha = Util::sha256_hex(reply->body);
if (!expected_sha256.empty() && actual_sha != expected_sha256) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::invalid_argument,
std::format("registry archive SHA-256 mismatch for {}@{}: expected {}, got {}",
package_name, version, expected_sha256, actual_sha))};
}
auto wrote = Platform::atomic_write_file(dest_file, reply->body, true);
if (!wrote) {
return std::unexpected{wrote.error()};
}
return dest_file;
}
Void::Result::Result<BinaryReleaseInfo, Void::Result::Error>
fetch_binary_detail(std::string_view registry_url, std::string_view package_name,
std::string_view version, std::string_view variant_id,
const RegistryAuth &auth) {
auto parsed_url = parse_registry_url(registry_url);
if (!parsed_url) {
return std::unexpected{parsed_url.error()};
}
std::map<std::string, std::string, std::less<>> headers;
if (!auth.bearer_token.empty()) {
headers["Authorization"] = "Bearer " + auth.bearer_token;
}
const std::string path = "/api/v1/packages/" + Void::Encoding::Url::encode(package_name) + "/" +
Void::Encoding::Url::encode(version) + "/binaries/" +
Void::Encoding::Url::encode(variant_id);
auto reply = send_http_request(*parsed_url, "GET", path, headers, {});
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status != 200) {
return std::unexpected{
make_error(reply->status == 404 ? Void::System::SystemErrorCode::not_found
: reply->status == 401 || reply->status == 403
? Void::System::SystemErrorCode::permission_denied
: Void::System::SystemErrorCode::io_error,
std::format("registry GET {} failed with HTTP {}", path, reply->status))};
}
auto json = Void::Json::Strict::parse(reply->body);
if (!json) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"invalid JSON returned by registry binary endpoint")};
}
const auto *object = std::get_if<JsonVal::Object>(&json->value);
if (!object) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"registry binary response must be a JSON object")};
}
BinaryReleaseInfo info;
info.variant_id = get_str(*object, "variant_id");
info.sha256 = get_str(*object, "sha256");
info.size_bytes = static_cast<std::uint64_t>(get_i64(*object, "size_bytes", 0));
info.yanked = get_bool(*object, "yanked", false);
if (const auto sig = get_str(*object, "signature"); !sig.empty()) {
info.signature = sig;
}
if (const auto key = get_str(*object, "public_key"); !key.empty()) {
info.public_key = key;
}
if (info.variant_id.empty()) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"registry binary response is missing variant_id")};
}
return info;
}
Void::Result::Result<std::string, Void::Result::Error>
publish_binary_variant(const BinaryPublishOptions &options) {
if (!Void::Semver::parse_strict(options.version)) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"binary variant version must be strict SemVer")};
}
if (options.variant_id.empty()) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"binary variant id must not be empty")};
}
auto parsed_url = parse_registry_url(options.registry_url);
if (!parsed_url) {
return std::unexpected{parsed_url.error()};
}
auto bytes = Void::FileSystem::read_file(options.artifact_path);
if (!bytes) {
return std::unexpected{bytes.error()};
}
const std::string sha = Util::sha256_hex(*bytes);
std::map<std::string, std::string, std::less<>> headers;
headers["X-Content-SHA256"] = sha;
if (!options.auth.bearer_token.empty()) {
headers["Authorization"] = "Bearer " + options.auth.bearer_token;
}
if (options.signing_seed_path) {
const std::string message = Provenance::canonical_binary_message(options.variant_id, sha);
auto signature = Provenance::sign_message(
std::as_bytes(std::span<const char>{message.data(), message.size()}),
*options.signing_seed_path);
if (!signature) {
return std::unexpected{signature.error()};
}
auto public_key = Provenance::public_key_from_seed(*options.signing_seed_path);
if (!public_key) {
return std::unexpected{public_key.error()};
}
headers["X-Binary-Signature"] = *signature;
headers["X-Binary-Public-Key"] = *public_key;
}
const std::string path = "/api/v1/packages/" +
Void::Encoding::Url::encode(options.package_name) + "/" +
Void::Encoding::Url::encode(options.version) + "/binaries/" +
Void::Encoding::Url::encode(options.variant_id);
auto reply = send_http_request(*parsed_url, "PUT", path, headers, *bytes);
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status != 200 && reply->status != 201) {
return std::unexpected{make_error(
reply->status == 409 ? Void::System::SystemErrorCode::already_exists
: Void::System::SystemErrorCode::permission_denied,
std::format("registry binary publish {}@{}/{} failed with HTTP {}",
options.package_name, options.version, options.variant_id, reply->status))};
}
return sha;
}
Void::Result::Result<std::vector<BinaryReleaseInfo>, Void::Result::Error>
fetch_binary_variants(std::string_view registry_url, std::string_view package_name,
std::string_view version, const RegistryAuth &auth, bool include_yanked) {
auto parsed_url = parse_registry_url(registry_url);
if (!parsed_url) {
return std::unexpected{parsed_url.error()};
}
std::map<std::string, std::string, std::less<>> headers;
if (!auth.bearer_token.empty()) {
headers["Authorization"] = "Bearer " + auth.bearer_token;
}
const std::string path = "/api/v1/packages/" + Void::Encoding::Url::encode(package_name) + "/" +
Void::Encoding::Url::encode(version) + "/binaries";
auto reply = send_http_request(*parsed_url, "GET", path, headers, {});
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status != 200) {
return std::unexpected{
make_error(reply->status == 404 ? Void::System::SystemErrorCode::not_found
: Void::System::SystemErrorCode::io_error,
std::format("registry GET {} failed with HTTP {}", path, reply->status))};
}
auto json = Void::Json::Strict::parse(reply->body);
if (!json) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"invalid JSON returned by registry binaries endpoint")};
}
const auto *root = std::get_if<JsonVal::Object>(&json->value);
if (!root) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"registry response root must be a JSON object")};
}
std::vector<BinaryReleaseInfo> variants;
const auto bit = root->find("binaries");
if (bit == root->end()) {
return variants;
}
const auto *binaries = std::get_if<JsonVal::Array>(&bit->second.value);
if (!binaries) {
return variants;
}
for (const auto &bv : *binaries) {
const auto *bo = std::get_if<JsonVal::Object>(&bv.value);
if (!bo) {
continue;
}
BinaryReleaseInfo info;
info.variant_id = get_str(*bo, "variant_id");
info.sha256 = get_str(*bo, "sha256");
info.size_bytes = static_cast<std::uint64_t>(get_i64(*bo, "size_bytes", 0));
info.yanked = get_bool(*bo, "yanked", false);
if (const auto sig = get_str(*bo, "signature"); !sig.empty()) {
info.signature = sig;
}
if (const auto key = get_str(*bo, "public_key"); !key.empty()) {
info.public_key = key;
}
// Yanked variants are hidden by default so they are never selected for
// materialization; listing callers can opt in for inspection.
if (!info.variant_id.empty() && (include_yanked || !info.yanked)) {
variants.push_back(std::move(info));
}
}
return variants;
}
Void::Result::Result<ReleaseInfo, Void::Result::Error>
fetch_release_detail(std::string_view registry_url, std::string_view package_name,
std::string_view version, const RegistryAuth &auth) {
auto parsed_url = parse_registry_url(registry_url);
if (!parsed_url) {
return std::unexpected{parsed_url.error()};
}
std::map<std::string, std::string, std::less<>> headers;
if (!auth.bearer_token.empty()) {
headers["Authorization"] = "Bearer " + auth.bearer_token;
}
const std::string path = "/api/v1/packages/" + Void::Encoding::Url::encode(package_name) + "/" +
Void::Encoding::Url::encode(version);
auto reply = send_http_request(*parsed_url, "GET", path, headers, {});
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status != 200) {
auto code = Void::System::SystemErrorCode::io_error;
if (reply->status == 404) {
code = Void::System::SystemErrorCode::not_found;
} else if (reply->status == 401 || reply->status == 403) {
code = Void::System::SystemErrorCode::permission_denied;
}
return std::unexpected{
make_error(code, std::format("registry GET {} failed with HTTP {}: {}", path,
reply->status, reply->body))};
}
auto json = Void::Json::Strict::parse(reply->body);
if (!json) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"invalid JSON returned by registry release endpoint")};
}
const auto *root = std::get_if<JsonVal::Object>(&json->value);
if (!root) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"registry response root must be a JSON object")};
}
ReleaseInfo info;
info.name = get_str(*root, "name");
info.version = get_str(*root, "version");
info.sha256 = get_str(*root, "sha256");
info.size_bytes = static_cast<std::uint64_t>(get_i64(*root, "size_bytes", 0));
info.yanked = get_bool(*root, "yanked", false);
if (const auto sig = get_str(*root, "signature"); !sig.empty()) {
info.signature = sig;
}
if (const auto key = get_str(*root, "public_key"); !key.empty()) {
info.public_key = key;
}
const auto bit = root->find("binaries");
if (bit != root->end()) {
if (const auto *binaries = std::get_if<JsonVal::Array>(&bit->second.value)) {
info.binary_count = binaries->size();
}
}
return info;
}
Void::Result::Result<std::vector<std::string>, Void::Result::Error>
fetch_package_owners(std::string_view registry_url, std::string_view package_name,
const RegistryAuth &auth) {
auto parsed_url = parse_registry_url(registry_url);
if (!parsed_url) {
return std::unexpected{parsed_url.error()};
}
std::map<std::string, std::string, std::less<>> headers;
if (!auth.bearer_token.empty()) {
headers["Authorization"] = "Bearer " + auth.bearer_token;
}
const std::string path =
"/api/v1/packages/" + Void::Encoding::Url::encode(package_name) + "/owners";
auto reply = send_http_request(*parsed_url, "GET", path, headers, {});
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status != 200) {
auto code = Void::System::SystemErrorCode::io_error;
if (reply->status == 404) {
code = Void::System::SystemErrorCode::not_found;
} else if (reply->status == 401 || reply->status == 403) {
code = Void::System::SystemErrorCode::permission_denied;
}
return std::unexpected{
make_error(code, std::format("registry GET {} failed with HTTP {}: {}", path,
reply->status, reply->body))};
}
auto json = Void::Json::Strict::parse(reply->body);
if (!json) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"invalid JSON returned by registry owners endpoint")};
}
const auto *root = std::get_if<JsonVal::Object>(&json->value);
if (!root) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"registry response root must be a JSON object")};
}
std::vector<std::string> owners;
const auto oit = root->find("owners");
if (oit == root->end()) {
return owners;
}
const auto *array = std::get_if<JsonVal::Array>(&oit->second.value);
if (!array) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"registry owners field must be a JSON array")};
}
owners.reserve(array->size());
for (const auto &entry : *array) {
if (const auto *name = std::get_if<std::string>(&entry.value); name && !name->empty()) {
owners.push_back(*name);
}
}
return owners;
}
Void::Result::Result<std::vector<TokenInfo>, Void::Result::Error>
fetch_tokens(std::string_view registry_url, const RegistryAuth &auth) {
auto parsed_url = parse_registry_url(registry_url);
if (!parsed_url) {
return std::unexpected{parsed_url.error()};
}
std::map<std::string, std::string, std::less<>> headers;
if (!auth.bearer_token.empty()) {
headers["Authorization"] = "Bearer " + auth.bearer_token;
}
auto reply = send_http_request(*parsed_url, "GET", "/api/v1/tokens", headers, {});
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status != 200) {
return std::unexpected{make_error(
reply->status == 401 || reply->status == 403
? Void::System::SystemErrorCode::permission_denied
: Void::System::SystemErrorCode::io_error,
std::format("registry GET /api/v1/tokens failed with HTTP {}", reply->status))};
}
auto json = Void::Json::Strict::parse(reply->body);
if (!json) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"invalid JSON returned by registry tokens endpoint")};
}
const auto *root = std::get_if<JsonVal::Object>(&json->value);
if (!root) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"registry response root must be a JSON object")};
}
std::vector<TokenInfo> tokens;
const auto tit = root->find("tokens");
if (tit == root->end()) {
return tokens;
}
const auto *array = std::get_if<JsonVal::Array>(&tit->second.value);
if (!array) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"registry tokens field must be a JSON array")};
}
for (const auto &entry : *array) {
const auto *object = std::get_if<JsonVal::Object>(&entry.value);
if (!object) {
continue;
}
TokenInfo info;
info.token_id = get_str(*object, "token_id");
info.username = get_str(*object, "username");
info.label = get_str(*object, "label");
info.revoked = get_bool(*object, "revoked", false);
if (const auto sit = object->find("scopes"); sit != object->end()) {
if (const auto *scopes = std::get_if<JsonVal::Array>(&sit->second.value)) {
for (const auto &scope : *scopes) {
if (const auto *text = std::get_if<std::string>(&scope.value)) {
info.scopes.push_back(*text);
}
}
}
}
if (!info.token_id.empty()) {
tokens.push_back(std::move(info));
}
}
return tokens;
}
namespace {
std::string json_quote_of(std::string_view text) {
std::string out{"\""};
for (const char c : text) {
if (c == '"' || c == '\\') {
out.push_back('\\');
out.push_back(c);
} else if (c == '\n') {
out += "\\n";
} else {
out.push_back(c);
}
}
out.push_back('"');
return out;
}
std::map<std::string, std::string, std::less<>> bearer_headers(const RegistryAuth &auth) {
std::map<std::string, std::string, std::less<>> headers;
headers["Content-Type"] = "application/json";
if (!auth.bearer_token.empty()) {
headers["Authorization"] = "Bearer " + auth.bearer_token;
}
return headers;
}
} // namespace
Void::Result::Result<WorkerRegistration, Void::Result::Error>
register_worker(std::string_view registry_url, std::string_view platform,
const RegistryAuth &auth) {
auto parsed_url = parse_registry_url(registry_url);
if (!parsed_url) {
return std::unexpected{parsed_url.error()};
}
const std::string body = std::format("{{\"platform\":{}}}", json_quote_of(platform));
auto reply =
send_http_request(*parsed_url, "POST", "/api/v1/workers", bearer_headers(auth), body);
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status != 201) {
return std::unexpected{
make_error(reply->status == 401 || reply->status == 403
? Void::System::SystemErrorCode::permission_denied
: Void::System::SystemErrorCode::io_error,
std::format("worker registration failed with HTTP {}", reply->status))};
}
auto json = Void::Json::Strict::parse(reply->body);
const auto *object = json ? std::get_if<JsonVal::Object>(&json->value) : nullptr;
if (!object) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"invalid worker registration response")};
}
WorkerRegistration registration;
registration.worker_id = get_str(*object, "worker_id");
registration.registered_epoch = get_i64(*object, "registered_epoch", 0);
if (registration.worker_id.empty()) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"worker registration response has no worker_id")};
}
return registration;
}
Void::Result::Result<LeasedAction, Void::Result::Error>
lease_action(std::string_view registry_url, std::string_view action_key, std::string_view worker_id,
std::int64_t lease_seconds, const RegistryAuth &auth) {
auto parsed_url = parse_registry_url(registry_url);
if (!parsed_url) {
return std::unexpected{parsed_url.error()};
}
const std::string body =
std::format("{{\"action_key\":{},\"worker_id\":{},\"lease_seconds\":{}}}",
json_quote_of(action_key), json_quote_of(worker_id), lease_seconds);
auto reply =
send_http_request(*parsed_url, "POST", "/api/v1/actions/lease", bearer_headers(auth), body);
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status != 200) {
return std::unexpected{make_error(
reply->status == 404 ? Void::System::SystemErrorCode::not_found
: reply->status == 409 ? Void::System::SystemErrorCode::busy
: reply->status == 401 || reply->status == 403
? Void::System::SystemErrorCode::permission_denied
: Void::System::SystemErrorCode::io_error,
std::format("action lease failed with HTTP {}: {}", reply->status, reply->body))};
}
auto json = Void::Json::Strict::parse(reply->body);
const auto *object = json ? std::get_if<JsonVal::Object>(&json->value) : nullptr;
if (!object) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::io_error, "invalid action lease response")};
}
LeasedAction leased;
leased.action_key = get_str(*object, "action_key");
leased.worker_id = get_str(*object, "worker_id");
leased.lease_token = get_str(*object, "lease_token");
leased.expires_epoch = get_i64(*object, "expires_epoch", 0);
if (const auto it = object->find("record"); it != object->end()) {
auto serialized = Void::Json::Strict::serialize(it->second);
if (!serialized) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"cannot serialize leased record")};
}
leased.record_json = *serialized;
}
if (leased.lease_token.empty()) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"action lease response has no lease_token")};
}
return leased;
}
Void::Result::Result<LeasedAction, Void::Result::Error>
lease_queued_action(std::string_view registry_url, std::string_view worker_id,
std::int64_t lease_seconds, const RegistryAuth &auth) {
auto parsed_url = parse_registry_url(registry_url);
if (!parsed_url) {
return std::unexpected{parsed_url.error()};
}
const std::string body = std::format("{{\"worker_id\":{},\"lease_seconds\":{}}}",
json_quote_of(worker_id), lease_seconds);
auto reply =
send_http_request(*parsed_url, "POST", "/api/v1/queue/lease", bearer_headers(auth), body);
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status != 200) {
return std::unexpected{make_error(
reply->status == 404 ? Void::System::SystemErrorCode::not_found
: reply->status == 401 || reply->status == 403
? Void::System::SystemErrorCode::permission_denied
: Void::System::SystemErrorCode::io_error,
std::format("queue lease failed with HTTP {}: {}", reply->status, reply->body))};
}
auto json = Void::Json::Strict::parse(reply->body);
const auto *object = json ? std::get_if<JsonVal::Object>(&json->value) : nullptr;
if (!object) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::io_error, "invalid queue lease response")};
}
LeasedAction leased;
leased.action_key = get_str(*object, "action_key");
leased.worker_id = get_str(*object, "worker_id");
leased.lease_token = get_str(*object, "lease_token");
leased.expires_epoch = get_i64(*object, "expires_epoch", 0);
if (leased.action_key.empty() || leased.lease_token.empty()) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"queue lease response is incomplete")};
}
return leased;
}
Void::Result::Result<void, Void::Result::Error> submit_action_result(std::string_view registry_url,
std::string_view action_key,
std::string_view lease_token,
std::string_view record_json,
const RegistryAuth &auth) {
auto parsed_url = parse_registry_url(registry_url);
if (!parsed_url) {
return std::unexpected{parsed_url.error()};
}
const std::string path =
"/api/v1/actions/" + Void::Encoding::Url::encode(action_key) + "/result";
const std::string body = std::format("{{\"lease_token\":{},\"record\":{}}}",
json_quote_of(lease_token), record_json);
auto reply = send_http_request(*parsed_url, "POST", path, bearer_headers(auth), body);
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status != 200) {
return std::unexpected{
make_error(reply->status == 409 ? Void::System::SystemErrorCode::busy
: reply->status == 403 ? Void::System::SystemErrorCode::permission_denied
: reply->status == 400 ? Void::System::SystemErrorCode::invalid_argument
: Void::System::SystemErrorCode::io_error,
std::format("action result upload failed with HTTP {}: {}", reply->status,
reply->body))};
}
return {};
}
Void::Result::Result<bool, Void::Result::Error>
set_release_yanked(std::string_view registry_url, std::string_view package_name,
std::string_view version, bool yanked, const RegistryAuth &auth) {
auto parsed_url = parse_registry_url(registry_url);
if (!parsed_url) {
return std::unexpected{parsed_url.error()};
}
std::map<std::string, std::string, std::less<>> headers;
headers["Content-Type"] = "application/json";
if (!auth.bearer_token.empty()) {
headers["Authorization"] = "Bearer " + auth.bearer_token;
}
const std::string path = "/api/v1/packages/" + Void::Encoding::Url::encode(package_name) + "/" +
Void::Encoding::Url::encode(version) + "/yank";
const std::string body = std::format("{{\"yanked\":{}}}", yanked ? "true" : "false");
auto reply = send_http_request(*parsed_url, "POST", path, headers, body);
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status != 200) {
return std::unexpected{make_error(reply->status == 404
? Void::System::SystemErrorCode::not_found
: reply->status == 401 || reply->status == 403
? Void::System::SystemErrorCode::permission_denied
: Void::System::SystemErrorCode::io_error,
std::format("registry POST {} failed with HTTP {}: {}",
path, reply->status, reply->body))};
}
auto json = Void::Json::Strict::parse(reply->body);
if (!json) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"invalid JSON returned by registry yank endpoint")};
}
const auto *object = std::get_if<JsonVal::Object>(&json->value);
if (!object) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"registry yank response must be a JSON object")};
}
const auto it = object->find("yanked");
if (it == object->end()) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"registry yank response is missing 'yanked'")};
}
const auto *flag = std::get_if<bool>(&it->second.value);
if (!flag) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"registry yank 'yanked' must be a boolean")};
}
return *flag;
}
Void::Result::Result<void, Void::Result::Error>
revoke_token(std::string_view registry_url, std::string_view token_id, const RegistryAuth &auth) {
auto parsed_url = parse_registry_url(registry_url);
if (!parsed_url) {
return std::unexpected{parsed_url.error()};
}
std::map<std::string, std::string, std::less<>> headers;
if (!auth.bearer_token.empty()) {
headers["Authorization"] = "Bearer " + auth.bearer_token;
}
const std::string path = "/api/v1/tokens/" + Void::Encoding::Url::encode(token_id);
auto reply = send_http_request(*parsed_url, "DELETE", path, headers, {});
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status != 200) {
return std::unexpected{
make_error(reply->status == 404 ? Void::System::SystemErrorCode::not_found
: reply->status == 401 || reply->status == 403
? Void::System::SystemErrorCode::permission_denied
: Void::System::SystemErrorCode::io_error,
std::format("registry DELETE {} failed with HTTP {}", path, reply->status))};
}
return {};
}
Void::Result::Result<std::filesystem::path, Void::Result::Error>
download_binary_artifact(std::string_view url, std::string_view expected_sha256,
const std::filesystem::path &dest_file, const RegistryAuth &auth) {
auto parsed_url = parse_registry_url(url);
if (!parsed_url) {
return std::unexpected{parsed_url.error()};
}
std::map<std::string, std::string, std::less<>> headers;
if (!auth.bearer_token.empty()) {
headers["Authorization"] = "Bearer " + auth.bearer_token;
}
auto reply = send_http_request(*parsed_url, "GET", "", headers, {});
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status != 200) {
return std::unexpected{make_error(
reply->status == 404 ? Void::System::SystemErrorCode::not_found
: Void::System::SystemErrorCode::io_error,
std::format("binary artifact GET {} failed with HTTP {}", url, reply->status))};
}
const std::string actual_sha = Util::sha256_hex(reply->body);
if (!expected_sha256.empty() && actual_sha != expected_sha256) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::invalid_argument,
std::format("binary artifact SHA-256 mismatch: expected {}, got {}",
expected_sha256, actual_sha))};
}
auto wrote = Platform::atomic_write_file(dest_file, reply->body, true);
if (!wrote) {
return std::unexpected{wrote.error()};
}
return dest_file;
}
Void::Result::Result<PublishReceipt, Void::Result::Error>
publish_package_archive(const PublishOptions &options) {
if (!Void::Semver::parse_strict(options.version)) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"publish version must be strict SemVer (X.Y.Z)")};
}
auto parsed_url = parse_registry_url(options.registry_url);
if (!parsed_url) {
return std::unexpected{parsed_url.error()};
}
auto bytes = Void::FileSystem::read_file(options.archive_path);
if (!bytes) {
return std::unexpected{bytes.error()};
}
const std::string sha = Util::sha256_hex(*bytes);
std::map<std::string, std::string, std::less<>> headers;
headers["X-Content-SHA256"] = sha;
if (options.signing_seed_path) {
auto signature = Provenance::sign_package(options.package_name, options.version, sha,
*options.signing_seed_path);
if (!signature) {
return std::unexpected{signature.error()};
}
auto public_key = Provenance::public_key_from_seed(*options.signing_seed_path);
if (!public_key) {
return std::unexpected{public_key.error()};
}
headers["X-Package-Signature"] = *signature;
headers["X-Package-Public-Key"] = *public_key;
}
if (!options.auth.bearer_token.empty()) {
headers["Authorization"] = "Bearer " + options.auth.bearer_token;
}
if (options.is_private) {
headers["X-Package-Private"] = "true";
}
if (!options.description.empty()) {
headers["X-Package-Description"] = options.description;
}
const std::string path = "/api/v1/packages/" +
Void::Encoding::Url::encode(options.package_name) + "/" +
Void::Encoding::Url::encode(options.version);
auto reply = send_http_request(*parsed_url, "PUT", path, headers, *bytes);
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status != 200 && reply->status != 201) {
return std::unexpected{make_error(
reply->status == 409 ? Void::System::SystemErrorCode::already_exists
: Void::System::SystemErrorCode::permission_denied,
std::format("registry publish {}@{} failed with HTTP {}: {}", options.package_name,
options.version, reply->status, reply->body))};
}
return PublishReceipt{sha, reply->status == 200};
}
} // namespace Void::Build::Package