Files
Library/tests/standalone/Archive/ArchiveHardening.cpp

393 lines
14 KiB
C++

#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
}