feat(archive): add streaming Reader, atomic StagedTree publication, reproducible creation, and isolated worker

This commit is contained in:
faumaray committed 2026-11-25 20:54:10 +03:00
1 parent 713d2dc656
commit 00d7478335
10 files changed
+3781 -5

No files matched your search

+176 -4
View File
@@ -1,11 +1,19 @@
#pragma once
#include <Void/Archive/Types.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <memory>
#include <optional>
#include <span>
#include <stop_token>
#include <string_view>
#include <vector>
namespace Void::Archive
{
@@ -21,12 +29,176 @@ namespace Void::Archive
std::uint64_t bytes{0};
};
/// Extract a tar/tar.zst archive without invoking an external process.
/// Only regular files and directories are accepted. Absolute/traversal
/// paths, links, special files, duplicates and configured size/count
/// overages fail the whole operation.
/// Extract a tar/tar.zst archive incrementally into `destination` without
/// invoking an external process. Preserved 1.x incremental API; callers
/// requiring all-or-nothing directory visibility should use
/// `extract_staged` + `StagedTree::publish`.
[[nodiscard]] Void::Result::Result<ExtractionResult>
extract(const std::filesystem::path& archivePath,
const std::filesystem::path& destination,
const ExtractionOptions& options = {});
/// Caller-driven bounded tar/tar.zst reader. Maintains one active entry at
/// a time; callers must drain (`read_chunk` returning 0) or call
/// `skip_entry()` before advancing with `next_entry()`.
class Reader
{
public:
~Reader();
Reader(Reader&&) noexcept;
Reader& operator=(Reader&&) noexcept;
Reader(const Reader&) = delete;
Reader& operator=(const Reader&) = delete;
[[nodiscard]] static Void::Result::Result<Reader> open(
ByteSource& source, ReadLimits limits = {},
std::stop_token stop = {},
std::optional<Void::Time::MonotonicClock::time_point> deadline =
std::nullopt,
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance());
[[nodiscard]] static Void::Result::Result<Reader> open_file(
const std::filesystem::path& archive_path,
ReadLimits limits = {}, std::stop_token stop = {},
std::optional<Void::Time::MonotonicClock::time_point> deadline =
std::nullopt,
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance());
/// Advance to the next archive entry. Returns std::nullopt on clean
/// EOF.
[[nodiscard]] Void::Result::Result<std::optional<EntryInfo>>
next_entry();
/// Read up to dst.size() decompressed bytes of the active regular
/// file entry. Returns 0 on entry EOF.
[[nodiscard]] Void::Result::Result<std::size_t>
read_chunk(std::span<std::byte> dst);
/// Drain and discard remaining bytes of the active entry while
/// still accounting decompressed bytes against policy limits.
[[nodiscard]] Void::Result::Result<std::uint64_t> skip_entry();
[[nodiscard]] std::size_t entries_seen() const noexcept;
[[nodiscard]] std::uint64_t total_decompressed_bytes() const noexcept;
[[nodiscard]] std::uint64_t total_compressed_bytes() const noexcept;
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
explicit Reader(std::unique_ptr<Impl> impl) noexcept;
};
/// Bounded metadata listing of archive entries. Normal mode (`forensic =
/// false`) rejects unsafe/duplicate/conflicting entries. Opt-in forensic
/// mode reports rejected entries without writing to disk.
[[nodiscard]] Void::Result::Result<std::vector<EntryInfo>>
list_entries(ByteSource& source, ReadLimits limits = {},
bool forensic = false);
[[nodiscard]] Void::Result::Result<std::vector<EntryInfo>>
list_entries(const std::filesystem::path& archive_path,
ReadLimits limits = {}, bool forensic = false);
/// Move-only handle owning an unpublished private staging directory beneath
/// a pinned parent directory. Unlinks only names under its staging
/// descriptor without following links if destroyed before publication.
class StagedTree
{
public:
StagedTree() noexcept = default;
~StagedTree() noexcept;
StagedTree(StagedTree&&) noexcept;
StagedTree& operator=(StagedTree&&) noexcept;
StagedTree(const StagedTree&) = delete;
StagedTree& operator=(const StagedTree&) = delete;
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool published() const noexcept;
[[nodiscard]] std::string_view staging_id() const noexcept;
[[nodiscard]] const std::filesystem::path&
staging_root() const noexcept;
[[nodiscard]] const std::filesystem::path&
tree_path() const noexcept;
[[nodiscard]] std::size_t entries() const noexcept;
[[nodiscard]] std::uint64_t bytes() const noexcept;
[[nodiscard]] const std::vector<EntryInfo>&
inventory() const noexcept;
/// Publish the staged tree into a previously absent immediate child
/// of the pinned parent directory using atomic no-replace rename
/// (`renameat2(..., RENAME_NOREPLACE)`). Never overwrites existing
/// directories or falls back to a racy existence check.
[[nodiscard]] Void::Result::Result<PublicationReceipt>
publish(std::string_view new_child_name);
/// Explicitly discard an unpublished staging tree.
[[nodiscard]] Void::Result::Result<void> discard();
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
explicit StagedTree(std::unique_ptr<Impl> impl) noexcept;
friend Void::Result::Result<StagedTree>
extract_staged(ByteSource& source,
const std::filesystem::path& parent_directory,
const StagedExtractionOptions& options);
friend Void::Result::Result<StagedTree>
extract_staged_isolated(
const std::filesystem::path& archive_path,
const std::filesystem::path& parent_directory,
const IsolationOptions& options);
};
/// Extract a tar/tar.zst stream into an exclusive 0700 staging directory
/// beneath `parent_directory`, fsync files and directories bottom-up, write
/// a bounded completion inventory, and return an unpublished StagedTree.
[[nodiscard]] Void::Result::Result<StagedTree>
extract_staged(ByteSource& source,
const std::filesystem::path& parent_directory,
const StagedExtractionOptions& options = {});
[[nodiscard]] Void::Result::Result<StagedTree>
extract_staged(const std::filesystem::path& archive_path,
const std::filesystem::path& parent_directory,
const StagedExtractionOptions& options = {});
/// Remove abandoned staging directories under `parent_directory` that carry
/// a valid exclusive operation marker owned by the current user and are at
/// least `min_age` old. Never touches directories without a valid marker.
[[nodiscard]] Void::Result::Result<std::size_t>
cleanup_stale_staging(const std::filesystem::path& parent_directory,
std::chrono::seconds min_age =
std::chrono::seconds{300});
/// Create a bounded, optionally reproducible tar or tar.zst archive from
/// regular file and directory entries. Sorts normalized paths, rejects
/// duplicates/conflicts, and opens source files with O_NOFOLLOW.
[[nodiscard]] Void::Result::Result<void>
create_archive(ByteSink& sink, std::span<const CreateEntry> entries,
const CreationOptions& options = {});
[[nodiscard]] Void::Result::Result<void>
create_archive(const std::filesystem::path& output_path,
std::span<const CreateEntry> entries,
const CreationOptions& options = {});
/// Hardened untrusted-input profile: extracts the archive in an isolated
/// System child process with bounded execution time and RSS checks, then
/// independently verifies the staged tree and inventory in the parent
/// before returning StagedTree.
[[nodiscard]] Void::Result::Result<StagedTree>
extract_staged_isolated(const std::filesystem::path& archive_path,
const std::filesystem::path& parent_directory,
const IsolationOptions& options);
/// Entry point invoked by the isolated archive decoder worker binary.
[[nodiscard]] int run_isolated_worker_main(int argc, char** argv);
} // namespace Void::Archive
+342
View File
@@ -0,0 +1,342 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
#include <string_view>
#include <system_error>
#include <utility>
#include <vector>
namespace Void::Archive
{
enum class ArchiveErrorCode : std::int32_t {
none = 0,
invalid_argument = 1,
unsafe_entry = 2,
unsupported_format = 3,
corrupt_archive = 4,
limit_exceeded = 5,
permission_denied = 6,
no_space = 7,
io_error = 8,
cancelled = 9,
timeout = 10,
unknown_publication = 11,
unsupported_capability = 12,
already_exists = 13,
conflict = 14,
isolation_failed = 15
};
[[nodiscard]] inline Void::Result::Error
make_archive_error(ArchiveErrorCode code, std::string message = {},
std::error_code sys_err = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case ArchiveErrorCode::none:
kind = ErrorKind::internal;
break;
case ArchiveErrorCode::invalid_argument:
case ArchiveErrorCode::unsafe_entry:
kind = ErrorKind::invalid_argument;
break;
case ArchiveErrorCode::unsupported_format:
case ArchiveErrorCode::unsupported_capability:
kind = ErrorKind::unsupported;
break;
case ArchiveErrorCode::corrupt_archive:
kind = ErrorKind::corrupt;
break;
case ArchiveErrorCode::limit_exceeded:
case ArchiveErrorCode::no_space:
kind = ErrorKind::exhausted;
break;
case ArchiveErrorCode::permission_denied:
case ArchiveErrorCode::io_error:
kind = ErrorKind::io;
break;
case ArchiveErrorCode::cancelled:
kind = ErrorKind::cancelled;
break;
case ArchiveErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case ArchiveErrorCode::already_exists:
case ArchiveErrorCode::conflict:
kind = ErrorKind::conflict;
break;
case ArchiveErrorCode::unknown_publication:
case ArchiveErrorCode::isolation_failed:
kind = ErrorKind::internal;
break;
}
const ErrorCode domain_code{Void::Result::kArchiveErrorDomain,
static_cast<std::int32_t>(code)};
return Error{kind, std::move(message), domain_code, sys_err};
}
/// Render an untrusted archive entry path safely for diagnostics: capped at
/// 4 KiB with control characters and newlines escaped.
[[nodiscard]] std::string
sanitize_diagnostic_path(std::string_view raw) noexcept;
struct ReadLimits {
std::size_t max_entries{10'000};
bool allow_zero_entries{false};
std::uint64_t max_file_bytes{512ULL * 1024 * 1024};
std::uint64_t max_total_bytes{2ULL * 1024 * 1024 * 1024};
std::uint64_t max_compressed_bytes{1ULL * 1024 * 1024 * 1024};
std::size_t max_metadata_bytes{8ULL * 1024 * 1024};
std::size_t transfer_buffer_bytes{64ULL * 1024};
std::size_t max_path_bytes{4096};
std::size_t max_component_bytes{255};
std::size_t max_path_components{64};
[[nodiscard]] Void::Result::Result<void> validate() const
{
if ((max_entries == 0 && !allow_zero_entries) ||
max_file_bytes == 0 || max_total_bytes == 0 ||
max_compressed_bytes == 0 || max_metadata_bytes == 0 ||
transfer_buffer_bytes == 0 || max_path_bytes == 0 ||
max_component_bytes == 0 || max_path_components == 0) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::invalid_argument,
"Archive::ReadLimits: limits must be non-zero unless "
"allow_zero_entries is explicitly enabled")};
}
return {};
}
};
enum class EntryType : std::uint8_t {
RegularFile = 0,
Directory,
Symlink,
Hardlink,
Other
};
struct EntryInfo {
std::string path{};
EntryType type{EntryType::RegularFile};
std::uint64_t declared_size{0};
std::uint32_t safe_mode{0644};
bool executable{false};
bool accepted{true};
std::string rejection_reason{};
};
struct ProgressEvent {
std::size_t entries_processed{0};
std::uint64_t bytes_extracted{0};
std::string current_path{};
};
using ProgressCallback = std::function<void(const ProgressEvent&)>;
enum class PublicationOutcome : std::uint8_t {
Published = 0,
NotPublished,
Unknown
};
struct PublicationReceipt {
PublicationOutcome outcome{PublicationOutcome::NotPublished};
std::filesystem::path destination_path{};
std::string staging_id{};
std::size_t entries{0};
std::uint64_t bytes{0};
std::string diagnostic{};
};
struct StagedExtractionOptions {
ReadLimits limits{};
bool preserve_executable_bit{true};
std::stop_token stop{};
std::optional<Void::Time::MonotonicClock::time_point> deadline{};
const Void::Time::MonotonicClock* clock{nullptr};
ProgressCallback on_progress{};
};
enum class ArchiveCompression : std::uint8_t { None = 0, Zstd };
struct CreationOptions {
ArchiveCompression compression{ArchiveCompression::Zstd};
bool reproducible{true};
ReadLimits limits{};
std::stop_token stop{};
};
struct CreateEntry {
std::string path{};
EntryType type{EntryType::RegularFile};
bool executable{false};
std::vector<std::byte> content{};
std::optional<std::filesystem::path> source_file{};
};
struct IsolationOptions {
std::filesystem::path worker_executable{};
std::uint64_t max_rss_bytes{128ULL * 1024 * 1024};
std::chrono::milliseconds timeout{std::chrono::seconds{60}};
StagedExtractionOptions extraction{};
};
/// Synchronous byte source interface borrowed through completion.
class ByteSource
{
public:
virtual ~ByteSource() = default;
/// Read up to dst.size() bytes. Returns 0 on clean EOF.
[[nodiscard]] virtual Void::Result::Result<std::size_t>
read(std::span<std::byte> dst) = 0;
};
/// Synchronous byte sink interface borrowed through completion.
class ByteSink
{
public:
virtual ~ByteSink() = default;
[[nodiscard]] virtual Void::Result::Result<void>
write(std::span<const std::byte> src) = 0;
};
class SpanByteSource final : public ByteSource
{
public:
explicit SpanByteSource(std::span<const std::byte> data) noexcept
: m_data(data)
{
}
[[nodiscard]] Void::Result::Result<std::size_t>
read(std::span<std::byte> dst) override;
private:
std::span<const std::byte> m_data{};
std::size_t m_offset{0};
};
class FileByteSource final : public ByteSource
{
public:
[[nodiscard]] static Void::Result::Result<FileByteSource>
open(const std::filesystem::path& path);
FileByteSource(FileByteSource&&) noexcept;
FileByteSource& operator=(FileByteSource&&) noexcept;
~FileByteSource() override;
FileByteSource(const FileByteSource&) = delete;
FileByteSource& operator=(const FileByteSource&) = delete;
[[nodiscard]] Void::Result::Result<std::size_t>
read(std::span<std::byte> dst) override;
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
explicit FileByteSource(std::unique_ptr<Impl> impl) noexcept;
};
class VectorByteSink final : public ByteSink
{
public:
explicit VectorByteSink(
std::size_t max_bytes = 256ULL * 1024 * 1024) noexcept
: m_max_bytes(max_bytes)
{
}
[[nodiscard]] Void::Result::Result<void>
write(std::span<const std::byte> src) override;
[[nodiscard]] const std::vector<std::byte>& bytes() const noexcept
{
return m_bytes;
}
[[nodiscard]] std::vector<std::byte> take_bytes() noexcept
{
return std::move(m_bytes);
}
private:
std::size_t m_max_bytes{256ULL * 1024 * 1024};
std::vector<std::byte> m_bytes{};
};
class FileByteSink final : public ByteSink
{
public:
[[nodiscard]] static Void::Result::Result<FileByteSink>
create(const std::filesystem::path& path);
FileByteSink(FileByteSink&&) noexcept;
FileByteSink& operator=(FileByteSink&&) noexcept;
~FileByteSink() override;
FileByteSink(const FileByteSink&) = delete;
FileByteSink& operator=(const FileByteSink&) = delete;
[[nodiscard]] Void::Result::Result<void>
write(std::span<const std::byte> src) override;
[[nodiscard]] Void::Result::Result<void> sync_and_close();
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
explicit FileByteSink(std::unique_ptr<Impl> impl) noexcept;
};
enum class FaultPoint : std::uint8_t {
none = 0,
rename_enosys,
post_rename_parent_sync,
staging_cleanup_fail
};
class ScopedFaultGuard
{
public:
explicit ScopedFaultGuard(FaultPoint point) noexcept;
~ScopedFaultGuard() noexcept;
ScopedFaultGuard(const ScopedFaultGuard&) = delete;
ScopedFaultGuard& operator=(const ScopedFaultGuard&) = delete;
ScopedFaultGuard(ScopedFaultGuard&&) = delete;
ScopedFaultGuard& operator=(ScopedFaultGuard&&) = delete;
private:
FaultPoint m_previous{FaultPoint::none};
};
} // namespace Void::Archive
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,4 +1,4 @@
void_add_module(Archive
INTERNAL_DEPS Functional
INTERNAL_DEPS Functional Time System
EXTERNAL_DEPS LibArchive::LibArchive
)
+14
View File
@@ -170,6 +170,20 @@ if(TARGET VoidTests AND (TARGET Void::System OR TARGET Void::IPC))
add_dependencies(VoidTests VoidProcessHelper)
endif()
if(TARGET VoidTests AND TARGET Void::Archive)
add_executable(VoidArchiveWorker
"${CMAKE_CURRENT_SOURCE_DIR}/helpers/ArchiveWorker.cpp")
target_link_libraries(VoidArchiveWorker PRIVATE Void::Archive)
set_target_properties(VoidArchiveWorker PROPERTIES
CXX_STANDARD 26
CXX_STANDARD_REQUIRED ON
CXX_EXTENSIONS OFF
VOID_TESTING_NO_AUTO_SCAN TRUE)
target_compile_definitions(VoidTests PRIVATE
"VOID_ARCHIVE_WORKER_PATH=\"$<TARGET_FILE:VoidArchiveWorker>\"")
add_dependencies(VoidTests VoidArchiveWorker)
endif()
if(TARGET VoidTests AND TARGET Void::Plugin)
set(_test_plugin_src "${CMAKE_CURRENT_SOURCE_DIR}/plugins/TestPlugin.cpp")
if(EXISTS "${_test_plugin_src}")
+6
View File
@@ -0,0 +1,6 @@
#include <Void/Archive/Archive.hpp>
int main(int argc, char** argv)
{
return Void::Archive::run_isolated_worker_main(argc, argv);
}
+11
View File
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 4.0)
project(VoidArchiveOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS Archive)
add_executable(void_archive_only_consumer main.cpp)
target_link_libraries(void_archive_only_consumer PRIVATE Void::Archive)
target_compile_features(void_archive_only_consumer PRIVATE cxx_std_26)
enable_testing()
add_test(NAME ArchiveOnlyConsumer COMMAND void_archive_only_consumer)
+26
View File
@@ -0,0 +1,26 @@
#include <Void/Archive/Archive.hpp>
#include <array>
#include <cstddef>
int main()
{
const std::array<Void::Archive::CreateEntry, 1> entries{{
Void::Archive::CreateEntry{
.path = "hello.txt",
.type = Void::Archive::EntryType::RegularFile,
.content = {std::byte{'h'}, std::byte{'i'}},
},
}};
Void::Archive::VectorByteSink sink;
if (!Void::Archive::create_archive(sink, entries).has_value()) {
return 1;
}
Void::Archive::SpanByteSource src{sink.bytes()};
auto listed = Void::Archive::list_entries(src);
if (!listed.has_value() || listed->size() != 1U ||
(*listed)[0].path != "hello.txt") {
return 2;
}
return 0;
}
+9
View File
@@ -197,6 +197,15 @@ if(_has_security_async)
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
endif()
has_modules(_has_archive Archive System Time Functional)
if(_has_archive)
run_consumer(ArchiveOnly "${install_prefix}" "ArchiveOnly"
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
endif()
# Foundation consumer with Core-formatting bridge and zero external packages.
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
if(_has_foundation)
@@ -0,0 +1,392 @@
#include <Void/Archive/Archive.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <archive.h>
#include <archive_entry.h>
#include <array>
#include <chrono>
#include <cstddef>
#include <filesystem>
#include <fstream>
#include <memory>
#include <stop_token>
#include <string>
#include <string_view>
#include <sys/stat.h>
#include <vector>
namespace
{
using namespace Void::Archive;
std::vector<std::byte> to_bytes(std::string_view s)
{
std::vector<std::byte> out(s.size());
for (std::size_t i = 0; i < s.size(); ++i) {
out[i] = static_cast<std::byte>(static_cast<unsigned char>(s[i]));
}
return out;
}
std::string read_file_str(const std::filesystem::path& p)
{
std::ifstream in{p, std::ios::binary};
Void::Testing::require(in.is_open());
return std::string{std::istreambuf_iterator<char>{in},
std::istreambuf_iterator<char>{}};
}
std::vector<std::byte> make_raw_tar(
std::span<const std::tuple<std::string_view, std::string_view,
unsigned int, std::string_view>>
entries)
{
using W = std::unique_ptr<archive, decltype(&archive_write_free)>;
using E =
std::unique_ptr<archive_entry, decltype(&archive_entry_free)>;
std::vector<std::byte> out;
W writer{archive_write_new(), &archive_write_free};
Void::Testing::require(static_cast<bool>(writer));
Void::Testing::require(archive_write_add_filter_zstd(writer.get()) ==
ARCHIVE_OK);
Void::Testing::require(archive_write_set_format_pax_restricted(
writer.get()) == ARCHIVE_OK);
Void::Testing::require(
archive_write_set_bytes_in_last_block(writer.get(), 1) ==
ARCHIVE_OK);
auto cb = [](archive*, void* data, const void* buf,
std::size_t len) -> la_ssize_t {
auto* vec = static_cast<std::vector<std::byte>*>(data);
const auto* p = static_cast<const std::byte*>(buf);
vec->insert(vec->end(), p, p + len);
return static_cast<la_ssize_t>(len);
};
Void::Testing::require(archive_write_open2(writer.get(), &out, nullptr,
cb, nullptr, nullptr) ==
ARCHIVE_OK);
for (const auto& [path, content, type, link] : entries) {
E ae{archive_entry_new(), &archive_entry_free};
const std::string p{path};
archive_entry_set_pathname(ae.get(), p.c_str());
archive_entry_set_filetype(ae.get(), type);
archive_entry_set_perm(ae.get(), type == AE_IFDIR ? 0755 : 0644);
if (type == AE_IFREG) {
archive_entry_set_size(ae.get(),
static_cast<la_int64_t>(content.size()));
}
if (!link.empty()) {
const std::string l{link};
archive_entry_set_symlink(ae.get(), l.c_str());
}
Void::Testing::require(archive_write_header(writer.get(), ae.get()) ==
ARCHIVE_OK);
if (!content.empty()) {
Void::Testing::require(
archive_write_data(writer.get(), content.data(),
content.size()) ==
static_cast<la_ssize_t>(content.size()));
}
Void::Testing::require(archive_write_finish_entry(writer.get()) ==
ARCHIVE_OK);
}
Void::Testing::require(archive_write_close(writer.get()) == ARCHIVE_OK);
return out;
}
} // namespace
Void::Testing::Test archive_reader_reproducible_skip_and_forensic_listing()
{
// 1. Reproducible creation produces identical bytes regardless of entry
// ordering.
const std::array<CreateEntry, 3> order_a{{
CreateEntry{.path = "bin/run",
.type = EntryType::RegularFile,
.executable = true,
.content = to_bytes("#!/bin/sh\necho hi\n")},
CreateEntry{.path = "docs/readme.txt",
.type = EntryType::RegularFile,
.executable = false,
.content = to_bytes("hello archive")},
CreateEntry{.path = "bin/", .type = EntryType::Directory},
}};
const std::array<CreateEntry, 3> order_b{order_a[2], order_a[1], order_a[0]};
VectorByteSink sink_a;
VectorByteSink sink_b;
CreationOptions copts{.compression = ArchiveCompression::Zstd,
.reproducible = true};
Void::Testing::require(create_archive(sink_a, order_a, copts).has_value());
Void::Testing::require(create_archive(sink_b, order_b, copts).has_value());
Void::Testing::expect_eq(sink_a.bytes(), sink_b.bytes());
// 2. Caller-driven Reader enforces drain/skip before next_entry and
// accounts skipped decompressed bytes against max_total_bytes.
{
SpanByteSource src{sink_a.bytes()};
auto reader = Reader::open(src);
Void::Testing::require(reader.has_value());
auto e1 = reader->next_entry();
Void::Testing::require(e1.has_value() && e1->has_value());
Void::Testing::expect_eq((*e1)->path, std::string{"bin"});
Void::Testing::expect_eq(static_cast<int>((*e1)->type),
static_cast<int>(EntryType::Directory));
auto e2 = reader->next_entry();
Void::Testing::require(e2.has_value() && e2->has_value());
Void::Testing::expect_eq((*e2)->path, std::string{"bin/run"});
Void::Testing::expect((*e2)->executable);
// Calling next_entry before draining/skipping active file fails.
auto premature = reader->next_entry();
Void::Testing::require(!premature.has_value());
}
// Skip accounting catches total limit even when caller skips data!
{
SpanByteSource src{sink_a.bytes()};
ReadLimits tight{};
tight.max_total_bytes = 20; // bin/run (18B) + readme (13B) = 31B > 20B
auto reader = Reader::open(src, tight);
Void::Testing::require(reader.has_value());
Void::Testing::require(reader->next_entry().has_value()); // bin/
Void::Testing::require(reader->next_entry().has_value()); // bin/run
auto skipped = reader->skip_entry();
Void::Testing::require(skipped.has_value());
Void::Testing::expect_eq(*skipped, 18ULL);
auto e3 = reader->next_entry(); // docs/readme.txt declared 13B > 2B rem
Void::Testing::require(!e3.has_value());
Void::Testing::expect_eq(
e3.error().code().value,
static_cast<std::int32_t>(ArchiveErrorCode::limit_exceeded));
}
// 3. Zero limits rejected unless allow_zero_entries is explicitly set.
{
ReadLimits zero_entries{};
zero_entries.max_entries = 0;
Void::Testing::expect(!zero_entries.validate().has_value());
zero_entries.allow_zero_entries = true;
Void::Testing::expect(zero_entries.validate().has_value());
}
// 4. File-as-parent conflict rejected cleanly (both orderings).
{
const std::array<
std::tuple<std::string_view, std::string_view, unsigned int,
std::string_view>,
2>
conflict_entries{{
{"foo", "file-bytes", AE_IFREG, ""},
{"foo/child", "nested", AE_IFREG, ""},
}};
const auto raw = make_raw_tar(conflict_entries);
SpanByteSource src{raw};
auto listed = list_entries(src, {}, false);
Void::Testing::require(!listed.has_value());
Void::Testing::expect_eq(
listed.error().code().value,
static_cast<std::int32_t>(ArchiveErrorCode::unsafe_entry));
}
// 5. Normal vs forensic listing + sanitized diagnostics.
{
const std::array<
std::tuple<std::string_view, std::string_view, unsigned int,
std::string_view>,
3>
mixed{{
{"safe.txt", "ok", AE_IFREG, ""},
{"bad\nlink", "", AE_IFLNK, "/etc/passwd"},
{"../escape", "nope", AE_IFREG, ""},
}};
const auto raw = make_raw_tar(mixed);
SpanByteSource src1{raw};
Void::Testing::expect(!list_entries(src1, {}, false).has_value());
SpanByteSource src2{raw};
auto forensic = list_entries(src2, {}, true);
Void::Testing::require(forensic.has_value());
Void::Testing::expect_eq(forensic->size(), 3U);
Void::Testing::expect((*forensic)[0].accepted);
Void::Testing::expect(!(*forensic)[1].accepted);
Void::Testing::expect((*forensic)[1].path.find('\n') ==
std::string::npos);
Void::Testing::expect(!(*forensic)[2].accepted);
}
// Diagnostic sanitizer caps at 4 KiB and escapes newlines.
const std::string huge_diag(6000, 'a');
Void::Testing::expect_eq(sanitize_diagnostic_path(huge_diag).size(), 4096U);
Void::Testing::expect_eq(sanitize_diagnostic_path("a\nb\rc"),
std::string{"a\\nb\\rc"});
}
Void::Testing::Test archive_staged_extraction_atomic_publish_unknown_and_cleanup()
{
Void::FileSystem::TempDir tmp{"void_archive_staged_"};
const auto archive_path = tmp / "pkg.tar.zst";
const auto parent_dir = tmp / "versions";
std::filesystem::create_directories(parent_dir);
const std::array<CreateEntry, 2> entries{{
CreateEntry{.path = "bin/app",
.type = EntryType::RegularFile,
.executable = true,
.content = to_bytes("binary-payload")},
CreateEntry{.path = "etc/config.txt",
.type = EntryType::RegularFile,
.executable = false,
.content = to_bytes("key=val")},
}};
Void::Testing::require(create_archive(archive_path, entries).has_value());
// 1. Staged extraction + atomic no-replace publication + safe modes.
std::size_t progress_calls = 0;
StagedExtractionOptions sopts{};
sopts.on_progress = [&](const ProgressEvent&) { ++progress_calls; };
auto staged = extract_staged(archive_path, parent_dir, sopts);
Void::Testing::require(staged.has_value());
Void::Testing::expect(staged->valid());
Void::Testing::expect(!staged->published());
Void::Testing::expect_eq(staged->entries(), 2U);
Void::Testing::expect(progress_calls >= 1U);
// Unsupported renameat2 ENOSYS returns unsupported_capability without
// fallback or consuming the staging tree.
{
ScopedFaultGuard fault{FaultPoint::rename_enosys};
auto unsupported = staged->publish("v1");
Void::Testing::require(!unsupported.has_value());
Void::Testing::expect_eq(
unsupported.error().code().value,
static_cast<std::int32_t>(ArchiveErrorCode::unsupported_capability));
Void::Testing::expect(!staged->published());
Void::Testing::expect(!std::filesystem::exists(parent_dir / "v1"));
}
// Atomic publish succeeds.
auto receipt = staged->publish("v1");
Void::Testing::require(receipt.has_value());
Void::Testing::expect_eq(static_cast<int>(receipt->outcome),
static_cast<int>(PublicationOutcome::Published));
Void::Testing::expect(staged->published());
Void::Testing::expect_eq(read_file_str(parent_dir / "v1/bin/app"),
std::string{"binary-payload"});
Void::Testing::expect_eq(read_file_str(parent_dir / "v1/etc/config.txt"),
std::string{"key=val"});
struct stat st_exec{};
struct stat st_reg{};
Void::Testing::require(::stat((parent_dir / "v1/bin/app").c_str(), &st_exec) ==
0);
Void::Testing::require(
::stat((parent_dir / "v1/etc/config.txt").c_str(), &st_reg) == 0);
Void::Testing::expect_eq(st_exec.st_mode & 0777, mode_t{0755});
Void::Testing::expect_eq(st_reg.st_mode & 0777, mode_t{0644});
// 2. Never overwrites an existing child directory.
auto staged2 = extract_staged(archive_path, parent_dir);
Void::Testing::require(staged2.has_value());
auto conflict = staged2->publish("v1");
Void::Testing::require(!conflict.has_value());
Void::Testing::expect_eq(
conflict.error().code().value,
static_cast<std::int32_t>(ArchiveErrorCode::already_exists));
const auto stage2_root = staged2->staging_root();
Void::Testing::expect(std::filesystem::exists(stage2_root));
// Destroying unpublished StagedTree cleans up its staging directory.
staged2 = std::unexpected{make_archive_error(ArchiveErrorCode::none)};
Void::Testing::expect(!std::filesystem::exists(stage2_root));
// 3. Post-rename parent fsync failure reports Unknown outcome with identity
// and does NOT claim rollback.
auto staged3 = extract_staged(archive_path, parent_dir);
Void::Testing::require(staged3.has_value());
{
ScopedFaultGuard fault{FaultPoint::post_rename_parent_sync};
auto unknown = staged3->publish("v2");
Void::Testing::require(unknown.has_value());
Void::Testing::expect_eq(static_cast<int>(unknown->outcome),
static_cast<int>(PublicationOutcome::Unknown));
Void::Testing::expect_eq(unknown->destination_path, parent_dir / "v2");
Void::Testing::expect(!unknown->staging_id.empty());
Void::Testing::expect(std::filesystem::exists(parent_dir / "v2/bin/app"));
}
// 4. Failed extraction with cleanup fault preserves primary error +
// retryable staging_id; cleanup_stale_staging cleans only valid marked dirs.
const auto foreign_dir = parent_dir / ".void-stage-foreign";
std::filesystem::create_directories(foreign_dir);
{
ScopedFaultGuard fault{FaultPoint::staging_cleanup_fail};
StagedExtractionOptions tight{};
tight.limits.max_file_bytes = 4;
auto failed = extract_staged(archive_path, parent_dir, tight);
Void::Testing::require(!failed.has_value());
Void::Testing::expect_eq(
failed.error().code().value,
static_cast<std::int32_t>(ArchiveErrorCode::limit_exceeded));
Void::Testing::expect(failed.error().message().find("staging_id=") !=
std::string::npos);
}
auto cleaned = cleanup_stale_staging(parent_dir, std::chrono::seconds{0});
Void::Testing::require(cleaned.has_value());
Void::Testing::expect_eq(*cleaned, 1U);
Void::Testing::expect(std::filesystem::exists(foreign_dir));
}
Void::Testing::Test archive_isolated_worker_extracts_verifies_and_publishes()
{
#ifdef VOID_ARCHIVE_WORKER_PATH
Void::FileSystem::TempDir tmp{"void_archive_iso_"};
const auto archive_path = tmp / "untrusted.tar.zst";
const auto parent_dir = tmp / "out";
std::filesystem::create_directories(parent_dir);
const std::array<CreateEntry, 2> entries{{
CreateEntry{.path = "bin/tool",
.type = EntryType::RegularFile,
.executable = true,
.content = to_bytes("isolated-ok")},
CreateEntry{.path = "data/info.txt",
.type = EntryType::RegularFile,
.executable = false,
.content = to_bytes("verified-by-parent")},
}};
Void::Testing::require(create_archive(archive_path, entries).has_value());
IsolationOptions iso{};
iso.worker_executable = VOID_ARCHIVE_WORKER_PATH;
iso.timeout = std::chrono::seconds{30};
iso.max_rss_bytes = 256ULL * 1024 * 1024;
auto staged = extract_staged_isolated(archive_path, parent_dir, iso);
Void::Testing::require(staged.has_value());
Void::Testing::expect_eq(staged->entries(), 2U);
auto published = staged->publish("rel-1");
Void::Testing::require(published.has_value());
Void::Testing::expect_eq(static_cast<int>(published->outcome),
static_cast<int>(PublicationOutcome::Published));
Void::Testing::expect_eq(read_file_str(parent_dir / "rel-1/bin/tool"),
std::string{"isolated-ok"});
Void::Testing::expect_eq(read_file_str(parent_dir / "rel-1/data/info.txt"),
std::string{"verified-by-parent"});
// Worker limit violation returns limit_exceeded and cleans staging.
IsolationOptions tight = iso;
tight.extraction.limits.max_file_bytes = 4;
auto failed = extract_staged_isolated(archive_path, parent_dir, tight);
Void::Testing::require(!failed.has_value());
Void::Testing::expect_eq(
failed.error().code().value,
static_cast<std::int32_t>(ArchiveErrorCode::limit_exceeded));
#else
Void::Testing::expect(true);
#endif
}