Files
Library/tests/standalone/System/SystemHardening.cpp
T

297 lines
12 KiB
C++

#include <Void/System/Metrics.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Process.hpp>
#include <Void/System/Query.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/System/TempFile.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cerrno>
#include <chrono>
#include <csignal>
#include <filesystem>
#include <fstream>
#include <stop_token>
#include <string>
#include <vector>
namespace
{
using Void::Testing::expect;
using Void::Testing::expect_eq;
using Void::Testing::require;
} // namespace
Void::Testing::Test system_spawn_distinguishes_exec_failure_and_hygiene()
{
// 1. spawn() returns exec_failed distinct from a child exiting 127.
Void::Process::SpawnOptions missing_opts;
missing_opts.executable = "/nonexistent/void/missing_binary";
missing_opts.search_path = false;
auto missing_res = Void::Process::spawn(missing_opts);
require(!missing_res.has_value());
expect_eq(missing_res.error().code().domain, Void::Result::kSystemErrorDomain);
expect_eq(missing_res.error().code().value,
static_cast<std::int32_t>(Void::System::SystemErrorCode::exec_failed));
Void::Process::SpawnOptions exit127_opts;
exit127_opts.executable = VOID_PROCESS_HELPER_PATH;
exit127_opts.arguments = {"exit", "127"};
auto exit127_child = Void::Process::spawn(exit127_opts);
require(exit127_child.has_value());
auto exit127_res = Void::Process::communicate_blocking(*exit127_child);
require(exit127_res.has_value());
expect(exit127_res->status.exited);
expect_eq(exit127_res->status.code, 127);
// 2. Non-CLOEXEC inherited fds in parent are never leaked across spawn().
int dummy_pipe[2]{-1, -1};
require(::pipe(dummy_pipe) == 0);
Void::System::OwnedFd leak0{dummy_pipe[0]};
Void::System::OwnedFd leak1{dummy_pipe[1]};
Void::Process::SpawnOptions fd_opts;
fd_opts.executable = VOID_PROCESS_HELPER_PATH;
fd_opts.arguments = {"check-fds"};
auto fd_child = Void::Process::spawn(fd_opts);
require(fd_child.has_value());
auto fd_res = Void::Process::communicate_blocking(*fd_child);
require(fd_res.has_value());
expect_eq(fd_res->out, std::string{"clean\n"});
// 3. EnvironmentPolicy allowlist & explicit_only + working_directory.
Void::FileSystem::TempDir tmp{"void_sys_cwd_"};
Void::Process::SpawnOptions env_opts;
env_opts.executable = VOID_PROCESS_HELPER_PATH;
env_opts.arguments = {"env-dump"};
env_opts.environment.mode = Void::Process::EnvMode::explicit_only;
env_opts.environment.set_vars = {{"VOID_Z", "two"}, {"VOID_A", "one"}};
auto env_child = Void::Process::spawn(env_opts);
require(env_child.has_value());
auto env_res = Void::Process::communicate_blocking(*env_child);
require(env_res.has_value());
expect_eq(env_res->out, std::string{"VOID_A=one\nVOID_Z=two\n"});
Void::Process::SpawnOptions cwd_opts;
cwd_opts.executable = VOID_PROCESS_HELPER_PATH;
cwd_opts.arguments = {"cwd"};
cwd_opts.working_directory = tmp.path();
auto cwd_child = Void::Process::spawn(cwd_opts);
require(cwd_child.has_value());
auto cwd_res = Void::Process::communicate_blocking(*cwd_child);
require(cwd_res.has_value());
expect_eq(cwd_res->out, std::filesystem::canonical(tmp.path()).string() + "\n");
// 4. argv+env limit rejected cleanly before fork().
Void::Process::SpawnOptions big_opts;
big_opts.executable = VOID_PROCESS_HELPER_PATH;
big_opts.arguments = {std::string(Void::Process::kMaxSpawnInputBytes + 64, 'x')};
auto big_res = Void::Process::spawn(big_opts);
require(!big_res.has_value());
expect_eq(big_res.error().code().value,
static_cast<std::int32_t>(Void::System::SystemErrorCode::limit_exceeded));
}
Void::Testing::Test system_communicate_duplex_limits_escalation_and_cancel()
{
// 1. Full-duplex simultaneous 256 KiB stdin + stdout + stderr without deadlock.
const std::size_t payload_bytes = 256ULL * 1024ULL;
const std::string big_in(payload_bytes, 'i');
Void::Process::SpawnOptions sim_opts;
sim_opts.executable = VOID_PROCESS_HELPER_PATH;
sim_opts.arguments = {"simultaneous-io", std::to_string(payload_bytes)};
auto sim_child = Void::Process::spawn(sim_opts);
require(sim_child.has_value());
Void::Process::CaptureLimits sim_lim;
sim_lim.max_line_bytes = 512ULL * 1024ULL;
auto sim_res = Void::Process::communicate_blocking(
*sim_child,
big_in,
sim_lim,
std::chrono::milliseconds{0}); // explicit zero-timeout completes normally
require(sim_res.has_value());
expect(!sim_res->timed_out);
expect_eq(sim_res->status.code, 0);
expect_eq(sim_res->out.size(), payload_bytes);
expect_eq(sim_res->err.size(), payload_bytes);
// 2. Capture limit fail_and_terminate vs drain_and_truncate, plus line_limit.
{
Void::Process::SpawnOptions flood_opts;
flood_opts.executable = VOID_PROCESS_HELPER_PATH;
flood_opts.arguments = {"flood", "4096", "0"};
auto ch = Void::Process::spawn(flood_opts);
require(ch.has_value());
Void::Process::CaptureLimits lim;
lim.max_stdout_bytes = 512;
lim.overflow_policy = Void::Process::OverflowPolicy::fail_and_terminate;
auto res = Void::Process::communicate_blocking(*ch, {}, lim);
require(!res.has_value());
expect_eq(res.error().code().value,
static_cast<std::int32_t>(Void::System::SystemErrorCode::output_limit));
}
{
Void::Process::SpawnOptions flood_opts;
flood_opts.executable = VOID_PROCESS_HELPER_PATH;
flood_opts.arguments = {"flood", "4096", "256"};
auto ch = Void::Process::spawn(flood_opts);
require(ch.has_value());
Void::Process::CaptureLimits lim;
lim.max_stdout_bytes = 512;
lim.overflow_policy = Void::Process::OverflowPolicy::drain_and_truncate;
auto res = Void::Process::communicate_blocking(*ch, {}, lim);
require(res.has_value());
expect(res->overflowed);
expect(res->stdout_truncated);
expect_eq(res->out.size(), std::size_t{512});
expect_eq(res->err.size(), std::size_t{256});
}
{
Void::Process::SpawnOptions long_opts;
long_opts.executable = VOID_PROCESS_HELPER_PATH;
long_opts.arguments = {"long-line", "2048"};
auto ch = Void::Process::spawn(long_opts);
require(ch.has_value());
Void::Process::CaptureLimits lim;
lim.max_line_bytes = 128;
lim.overflow_policy = Void::Process::OverflowPolicy::fail_and_terminate;
auto res = Void::Process::communicate_blocking(*ch, {}, lim);
require(!res.has_value());
expect_eq(res.error().code().value,
static_cast<std::int32_t>(Void::System::SystemErrorCode::line_limit));
}
// 3. SIGTERM-ignoring child escalates to SIGKILL within short kill_grace.
{
Void::Process::SpawnOptions sig_opts;
sig_opts.executable = VOID_PROCESS_HELPER_PATH;
sig_opts.arguments = {"ignore-sigterm", "10000"};
sig_opts.kill_grace = std::chrono::milliseconds{40};
auto ch = Void::Process::spawn(sig_opts);
require(ch.has_value());
auto res = Void::Process::communicate_blocking(
*ch, {}, Void::Process::CaptureLimits{}, std::chrono::milliseconds{80});
require(res.has_value());
expect(res->timed_out);
expect(!res->status.exited);
expect_eq(res->status.signal, SIGKILL);
}
// 4. Stop token cancels child cleanly.
{
Void::Process::SpawnOptions wait_opts;
wait_opts.executable = VOID_PROCESS_HELPER_PATH;
wait_opts.arguments = {"ignore-sigterm", "10000"};
wait_opts.kill_grace = std::chrono::milliseconds{20};
auto ch = Void::Process::spawn(wait_opts);
require(ch.has_value());
std::stop_source ss;
ss.request_stop();
auto res = ch->wait_blocking(
std::chrono::milliseconds{5000},
ss.get_token(),
std::chrono::milliseconds{20});
require(!res.has_value());
expect_eq(res.error().code().value,
static_cast<std::int32_t>(Void::System::SystemErrorCode::cancelled));
}
}
Void::Testing::Test system_replace_file_temp_ownership_and_metrics()
{
Void::FileSystem::TempDir tmp{"void_sys_fs_"};
struct stat tmp_st {};
require(::lstat(tmp.path().c_str(), &tmp_st) == 0);
expect_eq(static_cast<unsigned>(tmp_st.st_mode & 0777), 0700U);
const auto target = tmp / "state.cfg";
require(Void::FileSystem::replace_file(target, "initial").has_value());
expect_eq(Void::FileSystem::read_file(target).value(), std::string{"initial"});
// Fault during write/sync/rename removes ONLY owned temp and leaves target intact.
for (auto phase : {Void::FileSystem::ReplacePhase::write_stage,
Void::FileSystem::ReplacePhase::sync_stage,
Void::FileSystem::ReplacePhase::rename}) {
Void::FileSystem::ReplaceOptions opts;
opts.fault_hook = [phase](Void::FileSystem::ReplacePhase p)
-> std::optional<int> {
return (p == phase) ? std::optional<int>{EIO} : std::nullopt;
};
auto fail_res = Void::FileSystem::replace_file(target, "bad", opts);
require(!fail_res.has_value());
expect(!fail_res.error().visible_on_disk);
expect(!fail_res.error().durability_unknown);
expect_eq(Void::FileSystem::read_file(target).value(),
std::string{"initial"});
}
// Post-rename parent sync failure reports visible_on_disk + durability_unknown.
{
Void::FileSystem::ReplaceOptions opts;
opts.fault_hook = [](Void::FileSystem::ReplacePhase p)
-> std::optional<int> {
return (p == Void::FileSystem::ReplacePhase::sync_parent)
? std::optional<int>{EIO}
: std::nullopt;
};
auto sync_res = Void::FileSystem::replace_file(target, "committed", opts);
require(!sync_res.has_value());
expect(sync_res.error().visible_on_disk);
expect(sync_res.error().durability_unknown);
expect_eq(Void::FileSystem::read_file(target).value(),
std::string{"committed"});
}
// Bounded read_file & list_directory.
auto small_read = Void::FileSystem::read_file_bounded(
target, Void::FileSystem::ReadFileOptions{.max_bytes = 4});
require(!small_read.has_value());
expect_eq(small_read.error().code().value,
static_cast<std::int32_t>(Void::System::SystemErrorCode::limit_exceeded));
(void)Void::FileSystem::write_file(tmp / "extra1.txt", "1");
(void)Void::FileSystem::write_file(tmp / "extra2.txt", "2");
auto bounded_list = Void::FileSystem::list_directory_bounded(
tmp.path(), Void::FileSystem::ListDirectoryOptions{.max_entries = 1});
require(!bounded_list.has_value());
expect_eq(bounded_list.error().code().value,
static_cast<std::int32_t>(Void::System::SystemErrorCode::limit_exceeded));
// TempFile 0600 mode & symlink-swap refusal (destructor must not delete swap target).
const auto victim = tmp / "victim.txt";
require(Void::FileSystem::write_file(victim, "keep_me").has_value());
std::filesystem::path tf_path;
{
auto tf = Void::FileSystem::TempFile::open_in(tmp.path(), "tf_");
require(tf.has_value());
tf_path = tf->path();
struct stat tf_st {};
require(::lstat(tf_path.c_str(), &tf_st) == 0);
expect_eq(static_cast<unsigned>(tf_st.st_mode & 0777), 0600U);
// Replace tf_path with symlink to victim; ~TempFile must NOT unlink it!
std::filesystem::remove(tf_path);
std::filesystem::create_symlink(victim, tf_path);
}
expect(std::filesystem::exists(victim));
expect(std::filesystem::is_symlink(tf_path));
std::filesystem::remove(tf_path);
// CpuSampler::sample with injected ManualClock distinguishes valid vs zero interval.
Void::Time::ManualClock clock;
Void::SystemInfo::CpuSampler sampler{&clock};
expect(!sampler.sample().valid); // zero elapsed delta on ManualClock
(void)clock.advance(std::chrono::seconds{1});
const auto sample = sampler.sample();
expect(sample.valid);
expect(sample.ratio >= 0.0);
}