#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include 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 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(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> 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(n); } return true; } Void::Result::Result send_http_request(const ParsedHttpUrl &parsed, std::string_view method, std::string_view path, const std::map> &headers, std::string_view body) { const std::string full_path = parsed.base_path + std::string{path}; // 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 buf{}; for (;;) { const ssize_t n = ::recv(fd, buf.data(), buf.size(), 0); if (n > 0) { raw.append(buf.data(), static_cast(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(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(code); } reply.body = proc->stdout_data.substr(0, nl); } return reply; } 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(&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(&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(&it->second.value); return i ? *i : def; } } // namespace Void::Result::Result, 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> 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(&json->value); if (!root) { return std::unexpected{make_error(Void::System::SystemErrorCode::io_error, "registry response root must be a JSON object")}; } std::vector releases; const auto rit = root->find("releases"); if (rit != root->end()) { if (const auto *rarr = std::get_if(&rit->second.value)) { for (const auto &rv : *rarr) { const auto *ro = std::get_if(&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 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> 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 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> 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{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, Void::Result::Error> fetch_binary_variants(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> 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::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 package endpoint")}; } const auto *root = std::get_if(&json->value); if (!root) { return std::unexpected{make_error(Void::System::SystemErrorCode::io_error, "registry response root must be a JSON object")}; } std::vector variants; const auto rit = root->find("releases"); if (rit == root->end()) { return variants; } const auto *releases = std::get_if(&rit->second.value); if (!releases) { return variants; } for (const auto &rv : *releases) { const auto *ro = std::get_if(&rv.value); if (!ro || get_str(*ro, "version") != version) { continue; } const auto bit = ro->find("binaries"); if (bit == ro->end()) { continue; } const auto *binaries = std::get_if(&bit->second.value); if (!binaries) { continue; } for (const auto &bv : *binaries) { const auto *bo = std::get_if(&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(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 stay listed but must never be selected for materialization. if (!info.variant_id.empty() && !info.yanked) { variants.push_back(std::move(info)); } } } return variants; } Void::Result::Result download_binary_artifact(std::string_view url, std::string_view expected_sha256, const std::filesystem::path &dest_file) { auto parsed_url = parse_registry_url(url); if (!parsed_url) { return std::unexpected{parsed_url.error()}; } auto reply = send_http_request(*parsed_url, "GET", "", {}, {}); 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 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> 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