Files
Library/tests/standalone/Plugin/PluginHardening.cpp

316 lines
11 KiB
C++

#include <Void/Plugin/CAbi.h>
#include <Void/Plugin/CAbiAdapter.hpp>
#include <Void/Plugin/Host.hpp>
#include <Void/Plugin/Manager.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <chrono>
#include <cstring>
#include <filesystem>
#include <memory>
#include <stdexcept>
#include <stop_token>
#include <string>
#include <thread>
#include <vector>
namespace
{
using namespace Void::Plugin;
struct CabiCalcTable {
uint32_t (*version)(void_module_handle* h);
int32_t (*accumulate)(void_module_handle* h, int32_t delta);
};
const void_interface_id_v1 kCalcIfaceId{
{0x76, 0x6f, 0x69, 0x64, 0x63, 0x61, 0x6c, 0x63, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01}};
std::vector<std::uint8_t> encode_i32_le(std::int32_t v)
{
std::vector<std::uint8_t> out(4);
std::memcpy(out.data(), &v, 4);
return out;
}
std::int32_t decode_i32_le(const std::vector<std::uint8_t>& b)
{
std::int32_t v = 0;
if (b.size() >= 4) {
std::memcpy(&v, b.data(), 4);
}
return v;
}
} // namespace
#if defined(VOID_CABI_V1_PATH) && defined(VOID_CABI_V2_PATH) && \
__has_include(<dlfcn.h>)
Void::Testing::Test plugin_cabi_v1_to_v2_stateful_quiesce_and_reload()
{
PluginHostLimits limits{};
limits.allow_safe_dlclose = true;
CModuleHost host{limits};
auto id = host.load(VOID_CABI_V1_PATH);
Void::Testing::require(id.has_value());
Void::Testing::expect_eq(*id, std::string{"cabi.calc"});
auto g1 = host.acquire("cabi.calc");
Void::Testing::require(static_cast<bool>(g1));
const auto gen1 = g1.generation();
auto iface1 = g1.query_interface(kCalcIfaceId, 1, sizeof(CabiCalcTable));
Void::Testing::require(iface1.has_value());
const auto* t1 = iface1->table<CabiCalcTable>();
Void::Testing::require(t1 != nullptr);
Void::Testing::expect_eq(t1->version(nullptr), std::uint32_t{1});
// Run async op on V1 (kind=3 pins activity via host API, kind=2 sync).
auto op_sync = g1.run_async(2u, encode_i32_le(15));
Void::Testing::require(op_sync.has_value());
Void::Testing::expect_eq(decode_i32_le(*op_sync), 15);
auto op_async = g1.run_async(3u, encode_i32_le(25));
Void::Testing::require(op_async.has_value());
Void::Testing::expect_eq(decode_i32_le(*op_async), 40);
// Reload V1 -> V2 while g1 + iface1 are still pinned!
auto gen2_res =
host.replace("cabi.calc", VOID_CABI_V2_PATH, {}, gen1);
Void::Testing::require(gen2_res.has_value());
Void::Testing::expect(*gen2_res > gen1);
// Old generation stays mapped & live until both leases drop.
auto retained_mid = host.retained_generations("cabi.calc");
Void::Testing::expect_eq(retained_mid.size(), std::size_t{2});
// Acquire V2 interface and confirm checkpoint migrated 40 -> V2.
auto g2 = host.acquire("cabi.calc");
Void::Testing::require(static_cast<bool>(g2));
auto iface2 = g2.query_interface(kCalcIfaceId, 1, sizeof(CabiCalcTable));
Void::Testing::require(iface2.has_value());
const auto* t2 = iface2->table<CabiCalcTable>();
Void::Testing::expect_eq(t2->version(nullptr), std::uint32_t{2});
auto op2 = g2.run_async(1u, encode_i32_le(5));
// V2 does not implement async ops -> UNSUPPORTED mapped to abi_mismatch.
Void::Testing::expect(!op2.has_value());
// Old iface1/g1 still pinned; V1 sees quiesced mutation return -1.
Void::Testing::expect_eq(t1->version(nullptr), std::uint32_t{1});
// Drop all pins to gen1 and verify host retirement thread dlcloses gen1.
iface1 = InterfaceLease{};
g1 = GenerationLease{};
for (int i = 0; i < 100; ++i) {
if (host.retained_generations("cabi.calc").size() == 1) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds{5});
}
Void::Testing::expect_eq(host.retained_generations("cabi.calc").size(),
std::size_t{1});
}
Void::Testing::Test plugin_cabi_async_cancel_and_safe_dlclose_wait()
{
PluginHostLimits limits{};
limits.allow_safe_dlclose = true;
CModuleHost host{limits};
Void::Testing::require(host.load(VOID_CABI_V1_PATH).has_value());
auto lease = host.acquire("cabi.calc");
ActivityPin extra_pin = lease.acquire_activity_pin();
std::stop_source ss;
std::thread canceller([&] {
std::this_thread::sleep_for(std::chrono::milliseconds{2});
ss.request_stop();
});
Void::Async::OperationOptions opts;
opts.stop = ss.get_token();
auto res = lease.run_async(1u, encode_i32_le(1), opts);
canceller.join();
Void::Testing::expect(!res.has_value());
Void::Testing::expect_eq(
res.error().code().value,
static_cast<std::int32_t>(PluginErrorCode::cancelled));
// Unload while extra_pin + lease still exist -> cannot destroy/dlclose yet.
Void::Testing::require(host.unload("cabi.calc").has_value());
lease = GenerationLease{};
std::this_thread::sleep_for(std::chrono::milliseconds{10});
extra_pin = ActivityPin{};
host.close_and_join();
}
Void::Testing::Test plugin_cabi_bad_abi_oversized_ckpt_and_resume_degraded()
{
CModuleHost host{PluginHostLimits{.allow_safe_dlclose = true}};
for (const char* bad_path :
{VOID_CABI_BAD_TRUNC_PATH, VOID_CABI_BAD_MAJOR_PATH,
VOID_CABI_BAD_RESERVED_PATH}) {
auto r = host.load(bad_path);
Void::Testing::expect(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(PluginErrorCode::abi_mismatch));
}
// Prepublication V2 readiness failure resumes V1 cleanly.
Void::Testing::require(host.load(VOID_CABI_V1_PATH).has_value());
auto fail_v2 =
host.replace("cabi.calc", VOID_CABI_V2_PATH, "not_ready");
Void::Testing::expect(!fail_v2.has_value());
auto after = host.acquire("cabi.calc");
Void::Testing::expect(after.health() == GenerationHealth::Healthy);
Void::Testing::expect_eq(after.version(), std::string_view{"1.0.0"});
// Reload into V1 with quiesce_fail_resume_fail -> failed reload leaves old
// generation marked Degraded.
Void::Testing::require(
host.replace("cabi.calc", VOID_CABI_V1_PATH,
"quiesce_fail_resume_fail")
.has_value());
auto deg_attempt = host.replace("cabi.calc", VOID_CABI_V2_PATH);
Void::Testing::expect(!deg_attempt.has_value());
Void::Testing::expect_eq(
deg_attempt.error().code().value,
static_cast<std::int32_t>(PluginErrorCode::resume_degraded));
Void::Testing::expect(host.acquire("cabi.calc").health() ==
GenerationHealth::Degraded);
Void::Testing::require(host.unload("cabi.calc").has_value());
// Oversized checkpoint rejected without crashing or leaking.
Void::Testing::require(
host.load(VOID_CABI_V1_PATH, "ckpt_oversized").has_value());
auto ov = host.replace("cabi.calc", VOID_CABI_V2_PATH);
Void::Testing::expect(!ov.has_value());
Void::Testing::expect_eq(
ov.error().code().value,
static_cast<std::int32_t>(PluginErrorCode::budget_exceeded));
}
Void::Testing::Test plugin_cabi_retention_byte_budget_and_dep_batch()
{
// 4-generation retention cap + byte budget.
PluginHostLimits limits{};
limits.allow_safe_dlclose = true;
limits.max_retained_generations = 4;
CModuleHost host{limits};
Void::Testing::require(host.load(VOID_CABI_V1_PATH).has_value());
std::vector<GenerationLease> pins;
for (int i = 0; i < 3; ++i) {
pins.push_back(host.acquire("cabi.calc"));
auto next = host.replace("cabi.calc", VOID_CABI_V1_PATH);
Void::Testing::require(next.has_value());
}
pins.push_back(host.acquire("cabi.calc"));
// Now 4 distinct generations are pinned -> 5th replace fails retention_limit.
auto cap_fail = host.replace("cabi.calc", VOID_CABI_V2_PATH);
Void::Testing::expect(!cap_fail.has_value());
Void::Testing::expect_eq(
cap_fail.error().code().value,
static_cast<std::int32_t>(PluginErrorCode::retention_limit));
Void::Testing::expect(host.mapped_bytes("cabi.calc") > 0);
pins.clear();
// Byte budget rejection.
PluginHostLimits tiny_mem{};
tiny_mem.max_mapped_bytes_per_module = 1024;
CModuleHost tight{tiny_mem};
auto too_big = tight.load(VOID_CABI_V1_PATH);
Void::Testing::expect(!too_big.has_value());
Void::Testing::expect_eq(
too_big.error().code().value,
static_cast<std::int32_t>(PluginErrorCode::budget_exceeded));
// Dependency batch: B depends on A (supplied out of order) -> A sorted first.
CModuleHost batch_host;
auto batch_ok = batch_host.load_batch(
{{.path = VOID_CABI_DEP_B_PATH}, {.path = VOID_CABI_DEP_A_PATH}});
Void::Testing::require(batch_ok.has_value());
Void::Testing::expect_eq(batch_ok->size(), std::size_t{2});
Void::Testing::expect_eq((*batch_ok)[0], std::string{"cabi.dep.a"});
Void::Testing::expect_eq((*batch_ok)[1], std::string{"cabi.dep.b"});
// RestartRequired policy refuses live upgrade.
auto rr = batch_host.replace("cabi.dep.a", VOID_CABI_DEP_A_PATH);
Void::Testing::expect(!rr.has_value());
Void::Testing::expect_eq(
rr.error().code().value,
static_cast<std::int32_t>(PluginErrorCode::restart_required));
// Cycle in batch rejected before activating anything.
CModuleHost cyc_host;
auto cyc_res = cyc_host.load_batch(
{{.path = VOID_CABI_CYC_A_PATH}, {.path = VOID_CABI_CYC_B_PATH}});
Void::Testing::expect(!cyc_res.has_value());
Void::Testing::expect_eq(
cyc_res.error().code().value,
static_cast<std::int32_t>(PluginErrorCode::cycle_detected));
}
Void::Testing::Test plugin_cpp_adapter_contains_exceptions_and_manager_unlocks()
{
struct ThrowingModule final : Void::Plugin::IModule {
std::string_view name() const noexcept override { return "throw"; }
Void::Result::Result<void> activate(Void::Plugin::ModuleHost&) override
{
throw std::runtime_error("boom");
}
Void::Json::Value checkpoint() const override
{
throw std::runtime_error("ckpt-boom");
}
};
Void::Plugin::CModuleAdapterBox box{.module = std::make_unique<ThrowingModule>()};
void_error_detail_v1 err{};
err.struct_size = sizeof(err);
Void::Testing::expect_eq(Void::Plugin::adapt_activate(&box, &err),
static_cast<std::int32_t>(VOID_STATUS_INTERNAL));
if (err.release != nullptr && err.message != nullptr) {
Void::Testing::expect_eq(std::string_view{err.message},
std::string_view{"boom"});
err.release(err.release_ctx, err.message);
}
void_owned_bytes_v1 ck{};
void_error_detail_v1 err2{};
err2.struct_size = sizeof(err2);
Void::Testing::expect_eq(Void::Plugin::adapt_checkpoint(&box, &ck, &err2),
static_cast<std::int32_t>(VOID_STATUS_INTERNAL));
if (err2.release != nullptr && err2.message != nullptr) {
err2.release(err2.release_ctx, err2.message);
}
// Reentrant candidate/instance validator in PluginManager must NOT deadlock
// on m_mutex.
#if defined(VOID_STATEFUL_V1_PATH) && defined(VOID_STATEFUL_V2_PATH)
PluginManager* mgr_ptr = nullptr;
PluginManager mgr{{
.instance_validator = [&](IPlugin&, const PluginInfo&) {
auto current = mgr_ptr->acquire("StatefulPlugin");
auto all_names = mgr_ptr->names();
return all_names.empty() || static_cast<bool>(current);
},
.candidate_validator = [&](const PluginHandle&) {
auto current = mgr_ptr->acquire("StatefulPlugin");
return static_cast<bool>(current) || mgr_ptr->names().empty();
},
}};
mgr_ptr = &mgr;
Void::Testing::require(mgr.load(VOID_STATEFUL_V1_PATH).has_value());
Void::Testing::require(
mgr.replace("StatefulPlugin", VOID_STATEFUL_V2_PATH).has_value());
#endif
}
#endif // C ABI fixtures available