Files
EchoionStandalone/tests/test_update_service.cpp
T

775 lines
31 KiB
C++

#include "echoion/standalone/UpdateService.hpp"
#include <Void/Crypto/Crypto.hpp>
#include <Void/Data/Json.hpp>
#include <Void/Text/Hex.hpp>
#include <Void/Update/Update.hpp>
#include <filesystem>
#include <format>
#include <fstream>
#include <iostream>
#include <random>
#include <string>
#include <string_view>
namespace
{
class TemporaryTree
{
public:
TemporaryTree()
{
std::random_device random;
path_ =
std::filesystem::temp_directory_path() /
("echoion-update-service-" +
std::to_string(static_cast<unsigned long long>(random())));
std::filesystem::create_directories(path_);
}
~TemporaryTree()
{
std::error_code error;
std::filesystem::remove_all(path_, error);
}
TemporaryTree(const TemporaryTree&) = delete;
TemporaryTree& operator=(const TemporaryTree&) = delete;
[[nodiscard]] const std::filesystem::path& path() const noexcept
{
return path_;
}
private:
std::filesystem::path path_;
};
bool writeFile(const std::filesystem::path& path, std::string_view contents)
{
std::filesystem::create_directories(path.parent_path());
std::ofstream output(path, std::ios::binary);
output.write(contents.data(),
static_cast<std::streamsize>(contents.size()));
return output.good();
}
std::string readFile(const std::filesystem::path& path)
{
std::ifstream input(path, std::ios::binary);
return {std::istreambuf_iterator<char>{input},
std::istreambuf_iterator<char>{}};
}
bool publishHistoricalVersion(const std::filesystem::path& root,
std::string_view versionText,
const std::filesystem::path& filename,
std::string_view contents)
{
const auto version = Void::Semver::parse_strict(versionText);
if (!version) {
return false;
}
Void::Update::VersionStore store(root);
if (auto initialized = store.initialize(); !initialized) {
return false;
}
auto staging = store.prepare(*version);
if (!staging || !writeFile(*staging / filename, contents)) {
return false;
}
if (auto published = store.publish(*version, *staging); !published) {
return false;
}
return store.recordHealthy(*version).has_value();
}
bool activatePublishedVersion(const std::filesystem::path& root,
std::string_view versionText)
{
const auto version = Void::Semver::parse_strict(versionText);
if (!version) {
return false;
}
Void::Update::VersionStore store(root);
if (auto initialized = store.initialize(); !initialized) {
return false;
}
if (auto activated = store.activate(*version); !activated) {
return false;
}
return store.commit().has_value();
}
std::string sha256(std::string_view contents)
{
auto digest = Void::Crypto::sha256(contents);
return digest ? Void::Encoding::Hex::encode(*digest) : std::string{};
}
std::string architecture()
{
#if defined(__x86_64__) || defined(_M_X64)
return "x86_64";
#elif defined(__aarch64__) || defined(_M_ARM64)
return "aarch64";
#elif defined(__i386__) || defined(_M_IX86)
return "x86";
#else
return "unknown";
#endif
}
std::string configDocument(const std::filesystem::path& feed)
{
return R"json({"updates":{"enabled":false,"retainHealthyVersions":1,"sources":{"official":{"url":"file://)json" +
feed.string() +
R"json(","publicKeys":[],"allowUnsigned":true,"bearerTokenEnv":""}},"runtime":{"enabled":false,"source":"official","channel":"stable","autoApply":false},"core":{"enabled":true,"source":"official","channel":"stable","autoApply":false},"plugins":{"enabled":true,"source":"official","channel":"stable","autoApply":false,"managedOnly":true,"overrides":{}}}})json";
}
std::string release(std::string_view component, std::string_view artifactId,
std::string_view version,
const std::filesystem::path& artifact,
std::string_view contents)
{
return std::format(
R"json({{"component":"{}","artifactId":"{}","channel":"stable","version":"{}","cohort":"test","platform":"linux","arch":"{}","url":"file://{}","size":{},"sha256":"{}","packageType":"file","compatibility":{{"versionContracts":{{}},"exactContracts":{{}}}},"releaseManifestSha256":"0000000000000000000000000000000000000000000000000000000000000000"}})json",
component, artifactId, version, architecture(), artifact.string(),
contents.size(), sha256(contents));
}
std::string feedDocument(const std::filesystem::path& coreArtifact,
std::string_view coreContents,
const std::filesystem::path& pluginArtifact,
std::string_view pluginContents,
std::uint64_t sequence = 1)
{
return std::format(
R"json({{"schemaVersion":1,"feedId":"test","sequence":{},"generatedAt":"2026-01-01T00:00:00Z","expiresAt":"2099-01-01T00:00:00Z","releases":[{},{}]}})json",
sequence,
release("core", "", "2.0.0", coreArtifact, coreContents),
release("plugin", "fixture", "4.0.0", pluginArtifact,
pluginContents));
}
const Void::Json::Value*
parseResponse(const Echoion::Api::Result<std::string>& response,
std::optional<Void::Json::Value>& storage)
{
if (!response) {
return nullptr;
}
auto parsed = Void::Json::parse(*response);
if (!parsed) {
return nullptr;
}
storage = std::move(*parsed);
return &*storage;
}
std::string coreCandidateId(const Void::Json::Value& status)
{
const auto* components = status.find("components");
const auto* core = components ? components->find("core") : nullptr;
const auto* candidate = core ? core->find("candidate") : nullptr;
const auto* id = candidate ? candidate->find("id") : nullptr;
return id && id->is_string() ? id->as_string() : std::string{};
}
std::string pluginCandidateId(const Void::Json::Value& status)
{
const auto* plugins = status.find("plugins");
if (!plugins || !plugins->is_array()) {
return {};
}
for (const auto& plugin : plugins->as_array()) {
if (plugin.get_str("id") != "fixture") {
continue;
}
const auto* candidate = plugin.find("candidate");
const auto* id = candidate ? candidate->find("id") : nullptr;
return id && id->is_string() ? id->as_string() : std::string{};
}
return {};
}
std::string componentRollbackVersion(const Void::Json::Value& status,
std::string_view componentId)
{
const auto* components = status.find("components");
const auto* component =
components ? components->find(componentId) : nullptr;
return component ? component->get_str("rollbackVersion")
: std::string{};
}
std::string pluginRollbackVersion(const Void::Json::Value& status,
std::string_view pluginId)
{
const auto* plugins = status.find("plugins");
if (!plugins || !plugins->is_array()) {
return {};
}
for (const auto& plugin : plugins->as_array()) {
if (plugin.get_str("id") == pluginId) {
return plugin.get_str("rollbackVersion");
}
}
return {};
}
std::string confirmationToken(Echoion::Standalone::UpdateService& service,
std::string_view component,
std::string_view pluginId,
std::string_view candidateId,
std::string_view version)
{
const auto request = std::format(
R"json({{"component":"{}","pluginId":"{}","candidateId":"{}","version":"{}","confirmation":"UNSIGNED {}"}})json",
component, pluginId, candidateId, version, version);
auto response = service.handle("updates.confirmUnsigned", request);
if (!response) {
return {};
}
auto parsed = Void::Json::parse(*response);
return parsed ? parsed->get_str("confirmationToken") : std::string{};
}
} // namespace
int main()
{
int failures{};
const auto check = [&failures](bool condition, std::string_view message) {
if (!condition) {
std::cerr << message << '\n';
++failures;
}
};
TemporaryTree tree;
{
auto ownedService =
std::make_shared<Echoion::Standalone::UpdateService>(
Echoion::Standalone::UpdateService::Options{},
Echoion::Standalone::UpdateService::Hooks{});
std::weak_ptr<Echoion::Standalone::UpdateService> observedService =
ownedService;
auto handler = Echoion::Standalone::bindUpdateService(ownedService);
ownedService.reset();
check(!observedService.expired(),
"host control handler did not retain UpdateService");
check(handler("updates.getStatus", "{}").has_value(),
"retained UpdateService handler could not serve status");
handler = {};
check(observedService.expired(),
"cleared host control handler retained UpdateService");
}
const auto startupState = tree.path() / "startup-state";
const auto bundledStartupCore =
tree.path() / "startup-runtime" / "lib" / "Echoion.ts";
check(writeFile(bundledStartupCore, "runtime-core"),
"failed to write startup Core fixture");
const auto startupStore = startupState / "updates" / "components" / "core";
check(publishHistoricalVersion(startupStore, "1.1.0", "Echoion.ts",
"stale-managed-core"),
"failed to publish stale managed Core fixture");
check(activatePublishedVersion(startupStore, "1.1.0"),
"failed to activate stale managed Core fixture");
auto firstRuntimeSelection =
Echoion::Standalone::selectManagedCoreForStartup(
startupState, bundledStartupCore, std::string_view{"2.0.0"});
check(firstRuntimeSelection.has_value(),
"runtime Core baseline selection failed");
if (firstRuntimeSelection) {
check(firstRuntimeSelection->corePath == bundledStartupCore,
"new runtime did not prefer its bundled Core");
check(firstRuntimeSelection->runtimeBaselineChanged,
"new runtime did not report a Core baseline change");
check(firstRuntimeSelection->archivedStore.has_value() &&
std::filesystem::is_regular_file(
*firstRuntimeSelection->archivedStore / "versions" /
"1.1.0" / "Echoion.ts"),
"stale managed Core store was not archived");
}
check(publishHistoricalVersion(startupStore, "1.1.0", "Echoion.ts",
"runtime-core"),
"failed to seed the new runtime Core store");
check(activatePublishedVersion(startupStore, "1.1.0"),
"failed to activate the new runtime Core baseline");
auto sameRuntimeSelection =
Echoion::Standalone::selectManagedCoreForStartup(
startupState, bundledStartupCore, std::string_view{"2.0.0"});
check(sameRuntimeSelection.has_value() &&
sameRuntimeSelection->corePath ==
startupStore / "versions" / "1.1.0" / "Echoion.ts" &&
!sameRuntimeSelection->runtimeBaselineChanged,
"same runtime did not retain its managed Core selection");
auto nextRuntimeSelection =
Echoion::Standalone::selectManagedCoreForStartup(
startupState, bundledStartupCore, std::string_view{"2.1.0"});
check(nextRuntimeSelection.has_value() &&
nextRuntimeSelection->corePath == bundledStartupCore &&
nextRuntimeSelection->runtimeBaselineChanged,
"next runtime did not invalidate the prior managed Core baseline");
const auto state = tree.path() / "state";
const auto incoming = tree.path() / "incoming";
const auto currentCore = tree.path() / "installed" / "Echoion.ts";
const auto currentPlugin = tree.path() / "installed" / "fixture.so";
const auto installRoot = tree.path() / "runtime";
const auto runningExecutable = installRoot / "bin" / "echoiond";
const auto coreArtifact = incoming / "Echoion-2.0.0.ts";
const auto pluginArtifact = incoming / "fixture-4.0.0.so";
const auto feed = incoming / "feed.json";
const auto config = tree.path() / "config.json";
constexpr std::string_view oldCore = "old-core";
constexpr std::string_view newCore = "new-core";
constexpr std::string_view oldPlugin = "old-plugin";
constexpr std::string_view newPlugin = "new-plugin";
check(writeFile(currentCore, oldCore), "failed to write current Core");
check(writeFile(currentPlugin, oldPlugin),
"failed to write current plugin");
check(writeFile(coreArtifact, newCore), "failed to write Core artifact");
check(writeFile(pluginArtifact, newPlugin),
"failed to write plugin artifact");
check(writeFile(feed,
feedDocument(coreArtifact, newCore, pluginArtifact,
newPlugin, 9)),
"failed to write update feed");
check(writeFile(config, configDocument(feed)), "failed to write config");
check(publishHistoricalVersion(state / "updates" / "components" / "core",
"0.9.0", "Echoion.ts", "historical-core"),
"failed to seed a historical Core version");
check(publishHistoricalVersion(state / "plugins" / ".managed" / "fixture",
"1.0.0", "fixture.so", "oldest-plugin"),
"failed to seed the oldest historical plugin version");
check(publishHistoricalVersion(state / "plugins" / ".managed" / "fixture",
"2.0.0", "fixture.so", "historical-plugin"),
"failed to seed a historical plugin version");
check(publishHistoricalVersion(installRoot, "0.8.0", "bin/echoiond",
"previous-runtime"),
"failed to seed a runtime rollback version");
check(publishHistoricalVersion(installRoot, "0.9.0", "bin/not-echoiond",
"invalid-runtime-rollback"),
"failed to seed a runtime rollback decoy");
check(publishHistoricalVersion(installRoot, "1.0.0", "bin/echoiond",
"current-runtime"),
"failed to seed the current runtime version");
check(activatePublishedVersion(installRoot, "1.0.0"),
"failed to activate the current runtime version");
std::string coreVersion = "1.0.0";
std::string pluginVersion = "3.0.0";
std::filesystem::path activatedCore;
std::filesystem::path activatedPlugin;
int coreReplacements{};
int pluginReplacements{};
bool rejectCore{};
Void::Update::VersionStore pluginStore(state / "plugins" / ".managed" /
"fixture");
const auto makeService = [&] {
return Echoion::Standalone::UpdateService(
Echoion::Standalone::UpdateService::Options{
.configPath = config,
.stateDirectory = state,
.installRoot = installRoot,
.runningExecutable = runningExecutable,
.currentCore = currentCore,
.releaseManifestPath = {},
.officialFeedUrl = {},
.officialPublicKeysJson = "[]",
.runtimeVersion = "1.0.0",
.apiVersion = "1.1.0",
.toolchainAbi = "test",
.incomingDirectory = incoming},
Echoion::Standalone::UpdateService::Hooks{
.replaceCore = [&](const std::filesystem::path& path)
-> Echoion::Api::Result<void> {
++coreReplacements;
if (rejectCore) {
return Echoion::Api::fail(
Echoion::Api::ErrorCode::PluginError,
"rejected by test");
}
activatedCore = path;
coreVersion = path.parent_path().filename().string();
return {};
},
.managePlugins = [&](const std::string& request)
-> Echoion::Api::Result<std::string> {
auto parsed = Void::Json::parse(request);
if (!parsed) {
return Echoion::Api::fail(
Echoion::Api::ErrorCode::ParseError,
"invalid test request");
}
if (parsed->get_str("action") == "status") {
return std::format(
R"json({{"plugins":[{{"id":"fixture","name":"Fixture","version":"{}","path":"{}","managed":true}}]}})json",
pluginVersion, currentPlugin.string());
}
if (parsed->get_str("action") != "replace") {
return Echoion::Api::fail(
Echoion::Api::ErrorCode::InvalidArgument,
"unexpected test plugin action");
}
++pluginReplacements;
activatedPlugin = parsed->get_str("path");
pluginVersion = parsed->get_str("version");
return "{}";
},
.manageRuntime = {},
.playbackActive = [] { return false; },
.coreVersion = [&] { return coreVersion; }});
};
auto service = makeService();
check(service.start().has_value(), "UpdateService did not start");
check(service.handle("updates.history", "{}").has_value(),
"dynamic update history RPC was unavailable");
check(!service.handle("updates.preview", "{}").has_value(),
"transaction preview succeeded without a checked catalog");
check(!service
.handle("updates.applyTransaction",
R"({"transactionId":"missing"})")
.has_value(),
"component transaction apply succeeded without a checked catalog");
check(!service
.handle("updates.rollbackGeneration",
R"({"generationId":"missing"})")
.has_value(),
"generation rollback accepted an unadvertised target");
check(!std::filesystem::exists(
pluginStore.versionPath(*Void::Semver::parse("1.0.0"))),
"managed plugin startup retention did not prune the oldest version");
auto checked = service.handle("updates.check", "{}");
std::optional<Void::Json::Value> checkedJson;
const auto* checkedStatus = parseResponse(checked, checkedJson);
check(checkedStatus != nullptr, "manual update check failed");
const auto coreId = checkedStatus ? coreCandidateId(*checkedStatus) : "";
const auto pluginId =
checkedStatus ? pluginCandidateId(*checkedStatus) : "";
if ((coreId.empty() || pluginId.empty()) && checked) {
std::cerr << "update check response: " << *checked << '\n';
}
check(!coreId.empty(), "Core candidate was not selected");
check(!pluginId.empty(), "plugin candidate was not selected");
check(checkedStatus && !checkedStatus->get_bool("checking", true),
"completed manual check was returned as still running");
auto repeatedCheck = service.handle("updates.check", "{}");
std::optional<Void::Json::Value> repeatedJson;
const auto* repeatedStatus = parseResponse(repeatedCheck, repeatedJson);
check(repeatedStatus && coreCandidateId(*repeatedStatus) == coreId &&
pluginCandidateId(*repeatedStatus) == pluginId,
"an unchanged feed sequence was incorrectly treated as a replay");
const auto replacementFeed = incoming / "replacement-feed.json";
check(writeFile(
replacementFeed,
feedDocument(coreArtifact, newCore, pluginArtifact, newPlugin)),
"failed to write replacement update feed");
auto replacementConfig = Void::Json::parse(configDocument(replacementFeed));
const auto* replacementUpdates =
replacementConfig ? replacementConfig->find("updates") : nullptr;
check(replacementUpdates != nullptr,
"failed to construct replacement updater configuration");
bool replacementSaved = false;
if (replacementUpdates) {
replacementSaved =
service
.handle("updates.setConfig",
std::format(R"({{"config":{}}})",
Void::Json::serialize(*replacementUpdates)))
.has_value();
}
check(replacementSaved, "custom source URL could not be saved");
auto replacementCheck = service.handle("updates.check", "{}");
std::optional<Void::Json::Value> replacementJson;
const auto* replacementStatus =
parseResponse(replacementCheck, replacementJson);
check(replacementStatus && coreCandidateId(*replacementStatus) == coreId &&
pluginCandidateId(*replacementStatus) == pluginId,
"changing a custom source URL inherited the old feed replay floor");
const auto rejectedCoreToken =
confirmationToken(service, "core", "", coreId, "2.0.0");
check(!rejectedCoreToken.empty(), "Core unsigned confirmation failed");
rejectCore = true;
auto rejectedCoreApply = service.handle(
"updates.apply",
std::format(
R"json({{"component":"core","candidateId":"{}","version":"2.0.0","confirmationToken":"{}"}})json",
coreId, rejectedCoreToken));
check(rejectedCoreApply.has_value(), "failing Core apply did not queue");
service.processPendingHostActions();
check(coreReplacements == 1,
"failing queued Core replacement did not run exactly once");
auto replayedCoreApply = service.handle(
"updates.apply",
std::format(
R"json({{"component":"core","candidateId":"{}","version":"2.0.0","confirmationToken":"{}"}})json",
coreId, rejectedCoreToken));
check(!replayedCoreApply.has_value(),
"failed unsigned Core apply reused a consumed confirmation token");
const auto coreToken =
confirmationToken(service, "core", "", coreId, "2.0.0");
check(!coreToken.empty(), "fresh Core unsigned confirmation failed");
rejectCore = false;
auto coreApply = service.handle(
"updates.apply",
std::format(
R"json({{"component":"core","candidateId":"{}","version":"2.0.0","confirmationToken":"{}"}})json",
coreId, coreToken));
check(coreApply.has_value(), "Core apply did not queue");
check(coreReplacements == 1,
"Core was replaced synchronously on the RPC call stack");
service.processPendingHostActions();
check(coreReplacements == 2, "queued Core replacement did not run");
check(readFile(activatedCore) == newCore,
"queued Core replacement used the wrong artifact");
Void::Update::VersionStore coreStore(state / "updates" / "components" /
"core");
auto activeCoreVersion = coreStore.currentVersion();
check(activeCoreVersion && activeCoreVersion->has_value() &&
(*activeCoreVersion)->to_string() == "2.0.0",
"Core activation was not committed");
check(readFile(coreStore.versionPath(*Void::Semver::parse("1.0.0")) /
"Echoion.ts") == oldCore,
"initial Core was not seeded for rollback");
check(!std::filesystem::exists(
coreStore.versionPath(*Void::Semver::parse("0.9.0"))),
"Core retention did not remove an excess healthy version");
const auto pluginToken =
confirmationToken(service, "plugins", "fixture", pluginId, "4.0.0");
check(!pluginToken.empty(), "plugin unsigned confirmation failed");
auto pluginApply = service.handle(
"updates.apply",
std::format(
R"json({{"component":"plugins","pluginId":"fixture","candidateId":"{}","version":"4.0.0","confirmationToken":"{}"}})json",
pluginId, pluginToken));
check(pluginApply.has_value(), "plugin apply failed");
check(pluginReplacements == 1 && readFile(activatedPlugin) == newPlugin,
"plugin replacement used the wrong artifact");
check(readFile(pluginStore.versionPath(*Void::Semver::parse("3.0.0")) /
"fixture.so") == oldPlugin,
"initial plugin was not seeded for rollback");
check(!std::filesystem::exists(
pluginStore.versionPath(*Void::Semver::parse("2.0.0"))),
"plugin retention did not remove an excess healthy version");
auto unsafePluginRollback = service.handle(
"updates.rollback",
R"({"component":"plugins","pluginId":"../escape","version":"3.0.0"})");
check(!unsafePluginRollback.has_value(),
"plugin rollback accepted a path-traversal plugin id");
auto pluginRollback = service.handle(
"updates.rollback",
R"({"component":"plugins","pluginId":"fixture","version":"3.0.0"})");
check(pluginRollback.has_value() && pluginReplacements == 2 &&
readFile(activatedPlugin) == oldPlugin,
"plugin rollback did not restore the seeded version");
auto unadvertisedRollback = service.handle(
"updates.rollback", R"({"component":"core","version":"2.0.0"})");
check(!unadvertisedRollback.has_value(),
"Core rollback accepted a version that was not advertised healthy");
auto rollback = service.handle("updates.rollback",
R"({"component":"core","version":"1.0.0"})");
check(rollback.has_value(), "Core rollback did not queue");
check(coreReplacements == 2,
"Core rollback ran synchronously on the RPC call stack");
service.processPendingHostActions();
check(coreReplacements == 3 && readFile(activatedCore) == oldCore,
"queued Core rollback did not restore the seed");
rejectCore = true;
auto failedRollback = service.handle(
"updates.rollback", R"({"component":"core","version":"2.0.0"})");
check(failedRollback.has_value(), "failing Core rollback did not queue");
service.processPendingHostActions();
activeCoreVersion = coreStore.currentVersion();
check(coreReplacements == 4 && activeCoreVersion &&
activeCoreVersion->has_value() &&
(*activeCoreVersion)->to_string() == "1.0.0",
"failed Core replacement did not roll back the VersionStore");
auto finalStatus = service.handle("updates.getStatus", "{}");
check(finalStatus && finalStatus->contains("rejected by test"),
"failed deferred activation was not reported in status/history");
const auto plugin4 = *Void::Semver::parse("4.0.0");
check(pluginStore.activate(plugin4).has_value(),
"could not stage an interrupted plugin activation");
check(Echoion::Standalone::reconcileManagedPluginUpdates(state).has_value(),
"managed plugin startup reconciliation failed");
auto recoveredPluginVersion = pluginStore.currentVersion();
check(recoveredPluginVersion && recoveredPluginVersion->has_value() &&
(*recoveredPluginVersion)->to_string() == "3.0.0",
"startup reconciliation did not roll back the interrupted plugin");
const auto sequenceState = state / "updates" / "sequences.json";
std::filesystem::remove(sequenceState);
std::filesystem::create_directory(sequenceState);
check(!service.handle("updates.check", "{}").has_value(),
"update check ignored a replay-floor persistence failure");
std::filesystem::remove(sequenceState);
service.stop();
auto restarted = makeService();
check(restarted.start().has_value(),
"restarted UpdateService did not start");
auto restartedStatusResponse = restarted.handle("updates.getStatus", "{}");
std::optional<Void::Json::Value> restartedStatusJson;
const auto* restartedStatus =
parseResponse(restartedStatusResponse, restartedStatusJson);
check(restartedStatus != nullptr,
"restarted UpdateService did not return status");
check(restartedStatus &&
componentRollbackVersion(*restartedStatus, "runtime") == "0.8.0",
"runtime rollback metadata was not reconstructed or accepted an "
"invalid payload");
check(restartedStatus &&
componentRollbackVersion(*restartedStatus, "core") == "2.0.0",
"Core rollback metadata was not reconstructed after restart");
check(restartedStatus &&
pluginRollbackVersion(*restartedStatus, "fixture") == "4.0.0",
"plugin rollback metadata was not reconstructed after restart");
check(readFile(coreStore.versionPath(*Void::Semver::parse("2.0.0")) /
"Echoion.ts") == newCore,
"retained Core rollback payload was unavailable after restart");
check(readFile(pluginStore.versionPath(*Void::Semver::parse("4.0.0")) /
"fixture.so") == newPlugin,
"retained plugin rollback payload was unavailable after restart");
Void::Update::VersionStore runtimeStore(installRoot);
check(readFile(runtimeStore.versionPath(*Void::Semver::parse("0.8.0")) /
"bin" / "echoiond") == "previous-runtime",
"retained runtime rollback payload was unavailable after restart");
restarted.stop();
check(writeFile(sequenceState, "{not-json"),
"failed to write corrupt replay-floor fixture");
auto corruptReplayState = makeService();
const auto corruptReplayStart = corruptReplayState.start();
check(
!corruptReplayStart &&
corruptReplayStart.error().message.contains("replay-floor"),
"corrupt replay-floor state silently disabled anti-replay persistence");
std::filesystem::remove(sequenceState);
#ifndef _WIN32
const auto runtimeLock = installRoot / ".update.lock";
const auto runtimeHealth = installRoot / "health.log";
std::filesystem::permissions(runtimeLock, std::filesystem::perms::none,
std::filesystem::perm_options::replace);
std::filesystem::permissions(runtimeHealth, std::filesystem::perms::none,
std::filesystem::perm_options::replace);
std::ifstream unreadableProbe{runtimeLock, std::ios::binary};
if (!unreadableProbe) {
auto legacy = makeService();
check(legacy.start().has_value(),
"unreadable legacy runtime metadata disabled UpdateService");
auto legacyStatusResponse = legacy.handle("updates.getStatus", "{}");
std::optional<Void::Json::Value> legacyStatusJson;
const auto* legacyStatus =
parseResponse(legacyStatusResponse, legacyStatusJson);
check(legacyStatus &&
componentRollbackVersion(*legacyStatus, "runtime").empty(),
"unreadable legacy metadata exposed a runtime rollback");
legacy.stop();
}
const auto readableMetadata = std::filesystem::perms::owner_read |
std::filesystem::perms::owner_write |
std::filesystem::perms::group_read |
std::filesystem::perms::others_read;
std::filesystem::permissions(runtimeLock, readableMetadata,
std::filesystem::perm_options::replace);
std::filesystem::permissions(runtimeHealth, readableMetadata,
std::filesystem::perm_options::replace);
#endif
TemporaryTree freshTree;
const auto freshState = freshTree.path() / "state";
const auto freshIncoming = freshTree.path() / "incoming";
const auto freshFeed = freshIncoming / "feed.json";
const auto freshConfig = freshTree.path() / "config.json";
const auto freshCore = freshTree.path() / "installed" / "Echoion.ts";
const auto freshInstall = freshTree.path() / "runtime";
check(writeFile(freshFeed, "{}"),
"failed to write fresh-install feed fixture");
check(writeFile(freshConfig, configDocument(freshFeed)),
"failed to write fresh-install config fixture");
check(writeFile(freshCore, oldCore),
"failed to write fresh-install Core fixture");
check(writeFile(freshInstall / "versions" / "1.0.0" / "bin" / "echoiond",
"fresh-runtime"),
"failed to write fresh-install runtime fixture");
std::filesystem::create_directory_symlink(
std::filesystem::path{"versions"} / "1.0.0", freshInstall / "current");
Echoion::Standalone::UpdateService freshService(
Echoion::Standalone::UpdateService::Options{
.configPath = freshConfig,
.stateDirectory = freshState,
.installRoot = freshInstall,
.runningExecutable = freshInstall / "bin" / "echoiond",
.currentCore = freshCore,
.releaseManifestPath = {},
.officialFeedUrl = {},
.officialPublicKeysJson = "[]",
.runtimeVersion = "1.0.0",
.apiVersion = "1.1.0",
.toolchainAbi = "test",
.incomingDirectory = freshIncoming},
Echoion::Standalone::UpdateService::Hooks{});
check(freshService.start().has_value(),
"fresh install without VersionStore metadata did not start");
auto freshStatusResponse = freshService.handle("updates.getStatus", "{}");
std::optional<Void::Json::Value> freshStatusJson;
const auto* freshStatus =
parseResponse(freshStatusResponse, freshStatusJson);
check(freshStatus &&
componentRollbackVersion(*freshStatus, "runtime").empty(),
"fresh install synthesized runtime rollback metadata");
freshService.stop();
TemporaryTree blockedTree;
const auto blockedState = blockedTree.path() / "state";
const auto blockedIncoming = blockedTree.path() / "incoming";
const auto blockedFeed = blockedIncoming / "feed.json";
const auto blockedConfig = blockedTree.path() / "config.json";
const auto blockedCore = blockedTree.path() / "installed" / "Echoion.ts";
check(writeFile(blockedFeed, "{}"),
"failed to write blocked-start feed fixture");
check(writeFile(blockedConfig, configDocument(blockedFeed)),
"failed to write blocked-start config fixture");
check(writeFile(blockedCore, oldCore),
"failed to write blocked-start Core fixture");
check(writeFile(blockedState / "updates" / "downloads", "not-a-directory"),
"failed to create blocked updater directory fixture");
Echoion::Standalone::UpdateService blockedService(
Echoion::Standalone::UpdateService::Options{
.configPath = blockedConfig,
.stateDirectory = blockedState,
.installRoot = blockedTree.path() / "runtime",
.runningExecutable =
blockedTree.path() / "runtime" / "bin" / "echoiond",
.currentCore = blockedCore,
.releaseManifestPath = {},
.officialFeedUrl = {},
.officialPublicKeysJson = "[]",
.runtimeVersion = "1.0.0",
.apiVersion = "1.1.0",
.toolchainAbi = "test",
.incomingDirectory = blockedIncoming},
Echoion::Standalone::UpdateService::Hooks{});
const auto blockedStart = blockedService.start();
check(!blockedStart && blockedStart.error().message.contains("downloads"),
"startup masked an earlier updater directory creation failure");
blockedService.stop();
return failures == 0 ? 0 : 1;
}