#include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace Void::Build::Package { namespace { Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg) { return Void::System::make_system_error(code, redact_secrets(msg)); } std::string sanitize_key(std::string_view text) { std::string out; for (const char c : text) { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-') { out.push_back(c); } else { out.push_back('_'); } } return out; } std::string trim(std::string_view s) { return std::string{Void::Str::trim_right_ascii(s)}; } } // namespace std::string redact_secrets(std::string_view text) { std::string out{text}; // Redact scheme://user:pass@host -> scheme://@host std::size_t pos = 0; while ((pos = out.find("://", pos)) != std::string::npos) { const auto after = pos + 3; const auto slash = out.find('/', after); const auto space = out.find_first_of(" \t\r\n\"'", after); const auto bound = std::min(slash, space); const auto at = out.find('@', after); if (at != std::string::npos && at < bound) { out.replace(after, at - after, ""); pos = after + 10; } else { pos = after; } } // Redact Bearer tokens. pos = 0; while ((pos = out.find("Bearer ", pos)) != std::string::npos) { const auto start = pos + 7; const auto end = out.find_first_of(" \t\r\n\"',;}", start); const auto len = (end == std::string::npos) ? (out.size() - start) : (end - start); out.replace(start, len, ""); pos = start + 10; } return out; } std::string BinaryCompatibilityKey::compute_key_hash() const { Util::Sha256Hasher h; h.update_length_prefixed("vbs-bin-abi-v1"); h.update_length_prefixed(os); h.update_length_prefixed(architecture); h.update_length_prefixed(compiler_family); h.update_length_prefixed(compiler_abi); h.update_length_prefixed(stdlib_abi); h.update_length_prefixed(linkage); h.update_length_prefixed(cpu_features); h.update_length_prefixed(sanitizers_key); h.update_length_prefixed(lto_mode); h.update_length_prefixed(dependency_closure_hash); return h.finalize_hex(); } bool BinaryCompatibilityKey::matches(const BinaryVariantMeta &candidate) const noexcept { return candidate.os == os && candidate.architecture == architecture && candidate.compiler_family == compiler_family && candidate.compiler_abi == compiler_abi && candidate.stdlib_abi == stdlib_abi && candidate.linkage == linkage && candidate.cpu_features == cpu_features && candidate.sanitizers_key == sanitizers_key && candidate.lto_mode == lto_mode && candidate.dependency_closure_hash == dependency_closure_hash; } BinaryCompatibilityKey make_binary_compatibility_key(const ProfileContext &profile, const Toolchain::ToolchainCapabilities &toolchain, std::string_view linkage, std::string_view dependency_closure_hash) { BinaryCompatibilityKey key; key.os = profile.os; key.architecture = profile.architecture; key.compiler_family = std::string{compiler_name(profile.compiler)}; key.compiler_abi = toolchain.version_banner + "|" + toolchain.target_triple; key.stdlib_abi = (profile.compiler == CompilerFamily::Gcc) ? "libstdc++" : "libstdc++/libc++"; for (const auto &opt : profile.compile_options) { if (opt == "-stdlib=libc++") { key.stdlib_abi = "libc++"; } else if (opt == "-stdlib=libstdc++") { key.stdlib_abi = "libstdc++"; } else if (opt.starts_with("-march=") || opt.starts_with("-mcpu=")) { if (!key.cpu_features.empty()) { key.cpu_features += ","; } key.cpu_features += opt; } } key.linkage = std::string{linkage}; key.lto_mode = std::string{lto_mode_name(profile.lto)}; std::vector sans; for (const auto s : profile.sanitizers) { sans.emplace_back(sanitizer_name(s)); } std::ranges::sort(sans); for (std::size_t i = 0; i < sans.size(); ++i) { if (i > 0) { key.sanitizers_key += "+"; } key.sanitizers_key += sans[i]; } key.dependency_closure_hash = std::string{dependency_closure_hash}; return key; } std::optional select_compatible_binary(const BinaryCompatibilityKey &key, const std::vector &available) { for (const auto &v : available) { if (key.matches(v)) { return v; } } return std::nullopt; } Void::Result::Result select_compatible_signed_binary(const BinaryCompatibilityKey &key, const std::vector &available, const std::vector &trusted_public_keys_hex) { const auto selected = select_compatible_binary(key, available); if (!selected) { return std::unexpected{make_error(Void::System::SystemErrorCode::not_found, "no ABI-compatible binary variant is available")}; } if (trusted_public_keys_hex.empty()) { return *selected; } auto decision = Provenance::verify_trusted_binary_signature( Provenance::BinarySignature{selected->variant_id, selected->sha256, selected->signature.value_or(std::string{}), selected->public_key.value_or(std::string{})}, trusted_public_keys_hex); if (!decision) { return std::unexpected{decision.error()}; } if (*decision != Provenance::TrustDecision::Verified) { return std::unexpected{make_error( Void::System::SystemErrorCode::permission_denied, std::format("binary variant '{}' is not signed by a trusted key ({})", selected->variant_id, Provenance::trust_decision_name(*decision)))}; } return *selected; } Void::Result::Result materialize_binary_variant(const BinaryCompatibilityKey &key, const std::vector &available, const BinaryFetchOptions &options) { auto selected = select_compatible_signed_binary(key, available, options.trusted_public_keys); if (!selected) { return std::unexpected{selected.error()}; } const auto destination = options.cache_dir / "binaries" / selected->sha256; std::error_code ec; if (std::filesystem::is_regular_file(destination, ec)) { auto cached_digest = Util::sha256_file_hex(destination); if (cached_digest && *cached_digest == selected->sha256) { return *selected; } } std::filesystem::create_directories(destination.parent_path(), ec); auto downloaded = download_binary_artifact(selected->download_url, selected->sha256, destination); if (!downloaded) { return std::unexpected{downloaded.error()}; } return *selected; } Void::Result::Result materialize_dependency_source(const DependencyRecord &dep, const FetchOptions &options) { std::error_code ec; std::filesystem::create_directories(options.cache_dir, ec); // 1. Local path source: compute content hash without mutating the external checkout. if (dep.source_kind == DependencySourceKind::Path) { const std::filesystem::path raw{dep.location}; const auto abs = raw.is_absolute() ? raw : (options.project_root / raw); const auto canon = std::filesystem::weakly_canonical(abs, ec); if (ec || !std::filesystem::is_directory(canon)) { return std::unexpected{ make_error(Void::System::SystemErrorCode::not_found, std::format("local path dependency '{}' at '{}' does not exist", dep.name, dep.location))}; } Snapshot::SnapshotOptions sopts; sopts.project_root = canon; sopts.snapshot_store_dir = options.cache_dir / "path-snapshots"; sopts.materialize = false; // Generated editor metadata is never a build input and may be an out-of-tree symlink. sopts.excluded_names.push_back("compile_commands.json"); auto snap = Snapshot::capture_snapshot(sopts, {}, {canon}); if (!snap) { return std::unexpected{snap.error()}; } MaterializedSource out; out.alias = dep.name; out.source_dir = canon; out.content_identity_hash = snap->snapshot_id; out.from_cache = true; return out; } // 2. Checksummed archive source (local file:// or verified cached tar). if (dep.source_kind == DependencySourceKind::Archive) { const auto extract_dir = options.cache_dir / "archives" / dep.sha256; const auto marker = extract_dir / ".vbs_verified"; const auto lock_path = options.cache_dir / "locks" / (dep.sha256 + ".lock"); auto lock = Platform::FileLock::acquire(lock_path, Platform::LockMode::Exclusive); if (!lock) { return std::unexpected{lock.error()}; } if (std::filesystem::is_regular_file(marker, ec)) { MaterializedSource out; out.alias = dep.name; out.source_dir = extract_dir; out.content_identity_hash = dep.sha256; out.from_cache = true; return out; } const auto downloaded_tar = options.cache_dir / "downloads" / (dep.sha256 + ".tar"); std::filesystem::create_directories(downloaded_tar.parent_path(), ec); if (!std::filesystem::is_regular_file(downloaded_tar, ec)) { if (dep.location.starts_with("file://")) { const std::filesystem::path src_file{dep.location.substr(7)}; auto copied = Platform::copy_isolated(src_file, downloaded_tar); if (!copied) { return std::unexpected{copied.error()}; } } else if (std::filesystem::is_regular_file(dep.location, ec)) { auto copied = Platform::copy_isolated(dep.location, downloaded_tar); if (!copied) { return std::unexpected{copied.error()}; } } else { if (options.offline) { return std::unexpected{make_error( Void::System::SystemErrorCode::not_found, std::format("offline mode: archive '{}' (sha256={}) is not cached", dep.location, dep.sha256))}; } auto curl = Platform::resolve_executable("curl"); if (!curl) { return std::unexpected{make_error( Void::System::SystemErrorCode::not_found, "cannot fetch remote archive: neither curl nor Void::Net is available")}; } const auto tmp_dl = downloaded_tar.string() + ".part"; Platform::ProcessRequest req; req.executable = *curl; req.arguments = {"--fail", "--silent", "--show-error", "--location", "--proto", "=https,http", "--output", tmp_dl, dep.location}; req.timeout = std::chrono::seconds{120}; auto proc = Platform::run_supervised(req); if (!proc || !proc->succeeded()) { std::filesystem::remove(tmp_dl, ec); return std::unexpected{ make_error(Void::System::SystemErrorCode::io_error, std::format("failed fetching archive '{}': {}", dep.location, proc ? proc->stderr_data : proc.error().message()))}; } std::filesystem::rename(tmp_dl, downloaded_tar, ec); } } // Verify SHA-256 BEFORE extracting! auto actual_sha = Util::sha256_file_hex(downloaded_tar); if (!actual_sha) { return std::unexpected{actual_sha.error()}; } if (*actual_sha != dep.sha256) { std::filesystem::remove(downloaded_tar, ec); return std::unexpected{ make_error(Void::System::SystemErrorCode::invalid_argument, std::format("SHA-256 mismatch for archive '{}': expected {}, got {}", dep.location, dep.sha256, *actual_sha))}; } auto extracted = extract_safe_tar(downloaded_tar, extract_dir, options.archive_limits); if (!extracted) { return std::unexpected{extracted.error()}; } (void)Platform::atomic_write_file(marker, dep.sha256 + "\n", true); MaterializedSource out; out.alias = dep.name; out.source_dir = extract_dir; out.content_identity_hash = dep.sha256; out.from_cache = false; return out; } // 3. Exact pinned Git revision source. if (dep.source_kind == DependencySourceKind::Git) { if (dep.name == "VoidLibrary") { if (auto override_dir = Void::Configuration::get_env("VBS_VOID_SOURCE_DIR"); override_dir && !override_dir->empty()) { const std::filesystem::path raw{*override_dir}; const auto abs = raw.is_absolute() ? raw : (options.project_root / raw); const auto canon = std::filesystem::weakly_canonical(abs, ec); if (!ec && std::filesystem::is_directory(canon)) { Void::Log::info("Fetch", "Using VBS_VOID_SOURCE_DIR override for 'VoidLibrary': {}", canon.string()); MaterializedSource out; out.alias = dep.name; out.source_dir = canon; out.content_identity_hash = dep.revision + "-local"; out.from_cache = true; return out; } } } const auto git_dir = options.cache_dir / "git" / (sanitize_key(dep.name) + "_" + dep.revision); const auto marker = git_dir / ".vbs_verified_rev"; const auto lock_path = options.cache_dir / "locks" / ("git_" + dep.revision + ".lock"); auto lock = Platform::FileLock::acquire(lock_path, Platform::LockMode::Exclusive); if (!lock) { return std::unexpected{lock.error()}; } if (std::filesystem::is_regular_file(marker, ec)) { Void::Log::info("Fetch", "Using cached git dependency '{}' @ {}", dep.name, dep.revision.substr(0, 12)); MaterializedSource out; out.alias = dep.name; out.source_dir = git_dir; out.content_identity_hash = dep.revision; out.from_cache = true; return out; } Void::Log::info("Fetch", "Fetching git dependency '{}' from {} @ {}...", dep.name, redact_secrets(dep.location), dep.revision.substr(0, 12)); const bool is_local_repo = dep.location.starts_with("file://") || dep.location.starts_with("/") || std::filesystem::is_directory(dep.location, ec); if (options.offline && !is_local_repo) { return std::unexpected{ make_error(Void::System::SystemErrorCode::not_found, std::format("offline mode: git dependency '{}' ({}@{}) is not cached", dep.name, dep.location, dep.revision))}; } auto git_bin = Platform::resolve_executable("git"); if (!git_bin) { return std::unexpected{ make_error(Void::System::SystemErrorCode::not_found, "'git' not found in PATH")}; } const auto stage = git_dir.parent_path() / (git_dir.filename().string() + ".stage"); std::filesystem::remove_all(stage, ec); std::filesystem::create_directories(stage.parent_path(), ec); auto stage_cleanup = Void::Scope::on_exit([&] { std::filesystem::remove_all(stage, ec); }); auto run_git = [&](std::vector args, std::optional cwd = std::nullopt) -> Void::Result::Result { Platform::ProcessRequest req; req.executable = *git_bin; req.arguments = std::move(args); req.working_directory = cwd; req.environment.set_vars["GIT_TERMINAL_PROMPT"] = "0"; req.timeout = std::chrono::seconds{180}; auto p = Platform::run_supervised(req); if (!p || !p->succeeded()) { return std::unexpected{ make_error(Void::System::SystemErrorCode::io_error, std::format("git failed for '{}': {}", dep.location, p ? p->stderr_data : p.error().message()))}; } return p->stdout_data; }; if (auto r = run_git({"clone", "--no-checkout", dep.location, stage.string()}); !r) { return std::unexpected{r.error()}; } if (auto r = run_git({"checkout", "--detach", dep.revision}, stage); !r) { return std::unexpected{r.error()}; } auto head = run_git({"rev-parse", "HEAD"}, stage); if (!head || trim(*head) != dep.revision) { return std::unexpected{ make_error(Void::System::SystemErrorCode::invalid_argument, std::format("git checkout HEAD mismatch for '{}': expected {}", dep.name, dep.revision))}; } (void)Platform::atomic_write_file(stage / ".vbs_verified_rev", dep.revision + "\n", true); if (std::filesystem::exists(git_dir, ec)) { std::filesystem::remove_all(git_dir, ec); } std::filesystem::rename(stage, git_dir, ec); if (ec) { return std::unexpected{make_error(Void::System::SystemErrorCode::io_error, "failed publishing git checkout")}; } stage_cleanup.dismiss(); MaterializedSource out; out.alias = dep.name; out.source_dir = git_dir; out.content_identity_hash = dep.revision; out.from_cache = false; return out; } return std::unexpected{make_error( Void::System::SystemErrorCode::invalid_argument, std::format("dependency '{}' requires package/registry resolution before source fetch", dep.name))}; } } // namespace Void::Build::Package