Files
Library/tests/standalone/Update/UpdateHardening.cpp

457 lines
16 KiB
C++

#include <Void/Archive/Archive.hpp>
#include <Void/Crypto/Crypto.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Text/Base64.hpp>
#include <Void/Text/Hex.hpp>
#include <Void/Time/Clock.hpp>
#include <Void/Update/Update.hpp>
#include <array>
#include <chrono>
#include <cstddef>
#include <filesystem>
#include <format>
#include <fstream>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
namespace
{
using namespace Void::Update;
std::span<const std::byte> as_bytes(std::string_view s)
{
return std::as_bytes(std::span{s.data(), s.size()});
}
std::vector<std::byte> to_vec(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 sign_b64url(std::string_view payload,
const Void::Crypto::Ed25519PrivateKey& key)
{
auto sig = Void::Crypto::sign_ed25519(as_bytes(payload), key);
Void::Testing::require(sig.has_value());
return Void::Encoding::Base64::encode_url(
std::string_view{reinterpret_cast<const char*>(sig->bytes.data()),
sig->bytes.size()});
}
std::string make_feed_payload(std::string_view version,
std::uint64_t sequence, std::string_view url,
std::uint64_t size, std::string_view sha256)
{
return std::format(
R"json({{
"schemaVersion": 1,
"feedId": "vendor-main",
"sequence": {},
"generatedAt": "2026-01-01T00:00:00Z",
"expiresAt": "2099-01-01T00:00:00Z",
"releases": [{{
"component": "service",
"artifactId": "main",
"channel": "stable",
"version": "{}",
"cohort": "linux-abi-2",
"platform": "linux",
"arch": "x86_64",
"url": "{}",
"size": {},
"sha256": "{}",
"packageType": "tar.zst",
"compatibility": {{
"versionContracts": {{}},
"exactContracts": {{}}
}},
"releaseManifestSha256": "2222222222222222222222222222222222222222222222222222222222222222"
}}]
}})json",
sequence, version, url, size, sha256);
}
std::string make_envelope_v1(std::string_view key_id,
std::string_view payload,
const Void::Crypto::Ed25519PrivateKey& key)
{
return std::format(
R"json({{"schemaVersion":1,"keyId":"{}","payload":"{}","signature":"{}"}})json",
key_id, Void::Encoding::Base64::encode_url(payload),
sign_b64url(payload, key));
}
struct BuiltPackage {
std::filesystem::path path{};
std::uint64_t size{0};
std::string sha256{};
};
BuiltPackage build_test_package(const std::filesystem::path& dir,
std::string_view version)
{
const auto pkg_path = dir / std::format("service-{}.tar.zst", version);
const std::array<Void::Archive::CreateEntry, 1> entries{{
Void::Archive::CreateEntry{
.path = "version.txt",
.type = Void::Archive::EntryType::RegularFile,
.executable = false,
.content = to_vec(version),
},
}};
Void::Testing::require(
Void::Archive::create_archive(pkg_path, entries).has_value());
auto digest = Void::Crypto::sha256File(pkg_path);
Void::Testing::require(digest.has_value());
return BuiltPackage{
.path = pkg_path,
.size = std::filesystem::file_size(pkg_path),
.sha256 = Void::Encoding::Hex::encode(*digest),
};
}
} // namespace
Void::Testing::Test update_schema3_verify_before_parse_and_strict_json_profile()
{
auto priv = Void::Crypto::Ed25519PrivateKey::generate();
Void::Testing::require(priv.has_value());
auto pub = priv->public_key();
Void::Testing::require(pub.has_value());
Keyring keys{{"k1", pub->bytes}};
// 1. Schema-3 envelope with INVALID signature AND MALFORMED non-JSON
// payload must fail at signature verification (NOT JSON parse / mirror
// mismatch!).
{
constexpr std::string_view corrupt_payload = "{not valid json!!!";
const std::array<std::byte, 64> bad_sig{};
const std::string env = std::format(
R"json({{"schemaVersion":3,"keyId":"k1","document":{{"ok":1}},"signedPayload":"{}","signature":"{}"}})json",
Void::Encoding::Base64::encode_url(corrupt_payload),
Void::Encoding::Base64::encode_url(std::string_view{
reinterpret_cast<const char*>(bad_sig.data()),
bad_sig.size()}));
auto res = verifyEnvelope(env, keys);
Void::Testing::require(!res.has_value());
Void::Testing::expect_eq(
res.error().code().value,
static_cast<std::int32_t>(UpdateErrorCode::signature_failed));
}
// 2. Schema-3 envelope with VALID signature and mismatched display mirror
// fails with mirror_mismatch AFTER signature passes.
{
constexpr std::string_view signed_doc = R"json({"ok":1})json";
const std::string env = std::format(
R"json({{"schemaVersion":3,"keyId":"k1","document":{{"ok":2}},"signedPayload":"{}","signature":"{}"}})json",
Void::Encoding::Base64::encode_url(signed_doc),
sign_b64url(signed_doc, *priv));
auto res = verifyEnvelope(env, keys);
Void::Testing::require(!res.has_value());
Void::Testing::expect_eq(
res.error().code().value,
static_cast<std::int32_t>(UpdateErrorCode::mirror_mismatch));
}
// 3. Mutating whitespace of signed bytes breaks signature verification.
{
constexpr std::string_view signed_doc = R"json({"ok":1})json";
constexpr std::string_view mutated_doc = R"json({ "ok": 1 })json";
const std::string env = std::format(
R"json({{"schemaVersion":1,"keyId":"k1","payload":"{}","signature":"{}"}})json",
Void::Encoding::Base64::encode_url(mutated_doc),
sign_b64url(signed_doc, *priv));
auto res = verifyEnvelope(env, keys);
Void::Testing::require(!res.has_value());
Void::Testing::expect_eq(
res.error().code().value,
static_cast<std::int32_t>(UpdateErrorCode::signature_failed));
}
// 4. SchemaParsePolicy::StrictJsonProfile rejects duplicate keys and
// decimals while LegacyGeneralJson retains legacy acceptance.
{
constexpr std::string_view dup_payload =
R"json({"a":1,"a":2})json";
const std::string env = make_envelope_v1("k1", dup_payload, *priv);
VerificationPolicy legacy{};
legacy.parsePolicy = SchemaParsePolicy::LegacyGeneralJson;
Void::Testing::expect(verifyEnvelope(env, keys, legacy).has_value());
VerificationPolicy strict{};
strict.parsePolicy = SchemaParsePolicy::StrictJsonProfile;
auto strict_res = verifyEnvelope(env, keys, strict);
Void::Testing::require(!strict_res.has_value());
Void::Testing::expect_eq(
strict_res.error().code().value,
static_cast<std::int32_t>(UpdateErrorCode::schema_error));
}
}
Void::Testing::Test update_replay_floor_and_trust_store_rotation_revocation()
{
Void::FileSystem::TempDir tmp{"void_update_floor_"};
const auto floor_path = tmp / "replay_floor.json";
// 1. Durable monotonic floor survives restart & rejects replay.
{
ReplayFloorStore store{floor_path};
Void::Testing::require(store.load().has_value());
Void::Testing::require(store.advance("vendor-main", "stable", 10).has_value());
Void::Testing::expect_eq(
store.floor("vendor-main", "stable").value_or(0), 10ULL);
}
{
ReplayFloorStore reloaded{floor_path};
Void::Testing::require(reloaded.load().has_value());
Void::Testing::expect_eq(
reloaded.floor("vendor-main", "stable").value_or(0), 10ULL);
auto replay = reloaded.advance("vendor-main", "stable", 9);
Void::Testing::require(!replay.has_value());
Void::Testing::expect_eq(
replay.error().code().value,
static_cast<std::int32_t>(UpdateErrorCode::replay_rejected));
Void::Testing::require(
reloaded.advance("vendor-main", "stable", 11).has_value());
}
// Corrupt floor file triggers RecoveryRequired (never resets to 0).
{
std::ofstream corrupt{floor_path, std::ios::binary | std::ios::trunc};
corrupt << R"({"schemaVersion":1,"sha256":"0000","payload":"{}"})";
}
{
ReplayFloorStore broken{floor_path};
auto r = broken.load();
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(UpdateErrorCode::recovery_required));
}
// 2. TrustStore bootstrap, authenticated rotation, and revocation.
auto k1 = Void::Crypto::Ed25519PrivateKey::generate();
auto k2 = Void::Crypto::Ed25519PrivateKey::generate();
Void::Testing::require(k1.has_value() && k2.has_value());
auto pub1 = k1->public_key();
auto pub2 = k2->public_key();
Void::Testing::require(pub1.has_value() && pub2.has_value());
TrustStore trust;
Void::Testing::require(trust.bootstrap({{"k1", pub1->bytes}}).has_value());
const std::string stmt = TrustStore::rotation_statement("k2", pub2->bytes);
auto rot_sig = Void::Crypto::sign_ed25519(as_bytes(stmt), *k1);
Void::Testing::require(rot_sig.has_value());
// Bad signature rejected.
auto bad_sig = *rot_sig;
bad_sig.bytes[0] ^= std::byte{0xFF};
Void::Testing::expect(!trust
.rotate_key_authenticated("k2", pub2->bytes,
bad_sig.view(), "k1")
.has_value());
// Valid authenticated rotation succeeds.
Void::Testing::require(
trust
.rotate_key_authenticated("k2", pub2->bytes, rot_sig->view(), "k1")
.has_value());
Void::Testing::expect(trust.snapshot().contains("k2"));
// Revoking k1 removes it and forbids silent re-admission.
Void::Testing::require(trust.revoke_key("k1").has_value());
Void::Testing::expect(trust.is_revoked("k1"));
Void::Testing::expect(!trust.snapshot().contains("k1"));
Void::Testing::expect(
!trust.rotate_key_operator("k1", pub1->bytes).has_value());
}
Void::Testing::Test update_coordinator_install_rollback_pins_cleanup_pending_and_reconcile()
{
Void::FileSystem::TempDir tmp{"void_update_coord_"};
const auto pkg_dir = tmp / "packages";
const auto store_dir = tmp / "store";
const auto floor_path = tmp / "floor.json";
std::filesystem::create_directories(pkg_dir);
auto priv = Void::Crypto::Ed25519PrivateKey::generate();
Void::Testing::require(priv.has_value());
auto pub = priv->public_key();
Void::Testing::require(pub.has_value());
Keyring keys{{"k1", pub->bytes}};
auto transport = std::make_shared<LocalFileArtifactTransport>();
VersionStore vstore{store_dir};
ReplayFloorStore floors{floor_path};
Void::Testing::require(floors.load().has_value());
const SelectionRequest sel_req{
.component = "service",
.artifactId = "main",
.channel = "stable",
.environment = {.platform = "linux", .architecture = "x86_64"},
};
auto make_verified_pkg = [&](std::string_view ver, std::uint64_t seq) {
auto pkg = build_test_package(pkg_dir, ver);
const std::string url =
std::format("https://updates.invalid/service-{}.tar.zst", ver);
transport->map_url(url, pkg.path);
const std::string payload =
make_feed_payload(ver, seq, url, pkg.size, pkg.sha256);
const std::string env = make_envelope_v1("k1", payload, *priv);
auto sel = verify_and_select_release(env, keys, sel_req);
Void::Testing::require(sel.has_value());
return *sel;
};
// 1. Install v1.0.0 cleanly (internal activation + 3 consecutive probes).
std::size_t probe_calls = 0;
bool fail_cleanup = false;
std::vector<Void::Semver::Version> pinned;
LifecycleHooks hooks{
.health_probe = [&](const Void::Semver::Version&,
const std::filesystem::path&) {
++probe_calls;
return Void::Result::Result<bool>{true};
},
.live_pinned_versions = [&]() { return pinned; },
.post_commit_cleanup_hook = [&]() -> Void::Result::Result<void> {
if (fail_cleanup) {
return std::unexpected{make_update_error(
UpdateErrorCode::cleanup_pending,
"injected post-commit cleanup failure")};
}
return {};
},
};
InstallCoordinator coord{vstore, floors, transport, hooks};
Void::Time::ManualClock mono;
InstallOptions iopts{};
iopts.health_probe_interval = std::chrono::milliseconds{0};
iopts.consecutive_healthy_required = 3;
iopts.retained_previous_versions = 1;
iopts.monotonic_clock = &mono;
auto sel_100 = make_verified_pkg("1.0.0", 1);
auto r1 = coord.install(sel_100, iopts);
Void::Testing::require(r1.has_value());
Void::Testing::expect_eq(static_cast<int>(r1->state),
static_cast<int>(InstallState::HealthyCommitted));
Void::Testing::expect_eq(probe_calls, 3U);
auto cur = vstore.currentVersion();
Void::Testing::require(cur.has_value() && cur->has_value());
Void::Testing::expect_eq((*cur)->to_string(), std::string{"1.0.0"});
// 2. Truncated / bad-digest download fails before activation, leaving 1.0.0
// active.
auto sel_110 = make_verified_pkg("1.1.0", 2);
transport->set_truncate_bytes(4);
auto bad_dl = coord.install(sel_110, iopts);
transport->set_truncate_bytes(std::nullopt);
Void::Testing::require(!bad_dl.has_value());
Void::Testing::expect_eq(
bad_dl.error().code().value,
static_cast<std::int32_t>(UpdateErrorCode::size_mismatch));
cur = vstore.currentVersion();
Void::Testing::require(cur.has_value() && cur->has_value());
Void::Testing::expect_eq((*cur)->to_string(), std::string{"1.0.0"});
// 3. Unhealthy candidate rolls back cleanly via VersionStore.
bool stopped_candidate = false;
{
LifecycleHooks unhealthy_hooks{
.health_probe = [](const Void::Semver::Version&,
const std::filesystem::path&) {
return Void::Result::Result<bool>{false};
},
.stop_candidate = [&](const Void::Semver::Version&) {
stopped_candidate = true;
},
};
InstallCoordinator bad_coord{vstore, floors, transport, unhealthy_hooks};
auto rb = bad_coord.install(sel_110, iopts);
Void::Testing::require(rb.has_value());
Void::Testing::expect_eq(static_cast<int>(rb->state),
static_cast<int>(InstallState::RolledBack));
Void::Testing::expect(stopped_candidate);
cur = vstore.currentVersion();
Void::Testing::require(cur.has_value() && cur->has_value());
Void::Testing::expect_eq((*cur)->to_string(), std::string{"1.0.0"});
}
// 4. Post-commit cleanup failure reports CleanupPending WITHOUT rolling
// back committed candidate, and retry_cleanup resolves it.
auto sel_120 = make_verified_pkg("1.2.0", 3);
fail_cleanup = true;
auto cp = coord.install(sel_120, iopts);
Void::Testing::require(cp.has_value());
Void::Testing::expect_eq(static_cast<int>(cp->state),
static_cast<int>(InstallState::CleanupPending));
Void::Testing::expect(cp->cleanup_retryable);
cur = vstore.currentVersion();
Void::Testing::require(cur.has_value() && cur->has_value());
Void::Testing::expect_eq((*cur)->to_string(), std::string{"1.2.0"});
// Reconcile is idempotent and preserves CleanupPending until retried.
auto rec1 = coord.reconcile();
auto rec2 = coord.reconcile();
Void::Testing::require(rec1.has_value() && rec2.has_value());
Void::Testing::expect_eq(static_cast<int>(rec1->state),
static_cast<int>(InstallState::CleanupPending));
Void::Testing::expect_eq(static_cast<int>(rec2->state),
static_cast<int>(InstallState::CleanupPending));
fail_cleanup = false;
auto retried = coord.retry_cleanup(iopts);
Void::Testing::require(retried.has_value());
Void::Testing::expect_eq(static_cast<int>(retried->state),
static_cast<int>(InstallState::HealthyCommitted));
// 5. Pin-aware pruning protects pinned live generation 1.0.0 while pruning
// unpinned old versions.
auto v100 = Void::Semver::parse_strict("1.0.0");
Void::Testing::require(v100.has_value());
pinned = {*v100};
auto sel_130 = make_verified_pkg("1.3.0", 4);
auto r3 = coord.install(sel_130, iopts);
Void::Testing::require(r3.has_value());
Void::Testing::expect_eq(static_cast<int>(r3->state),
static_cast<int>(InstallState::HealthyCommitted));
Void::Testing::expect(std::filesystem::exists(vstore.versionPath(*v100)));
auto prune_rep = vstore.pruneWithPins(1, pinned, 16);
Void::Testing::require(prune_rep.has_value());
Void::Testing::expect_eq(prune_rep->skipped_due_to_pins.size(), 1U);
Void::Testing::expect_eq(prune_rep->skipped_due_to_pins[0].to_string(),
std::string{"1.0.0"});
// 6. Corrupt operation journal halts reconcile with RecoveryRequired
// without deleting the journal file.
{
std::ofstream bad_j{coord.operation_journal_path(),
std::ios::binary | std::ios::trunc};
bad_j << R"({"schemaVersion":99,"sha256":"dead","payload":"{}"})";
}
auto rec_err = coord.reconcile();
Void::Testing::require(!rec_err.has_value());
Void::Testing::expect_eq(
rec_err.error().code().value,
static_cast<std::int32_t>(UpdateErrorCode::recovery_required));
Void::Testing::expect(
std::filesystem::exists(coord.operation_journal_path()));
}