From 46ff4068cfdcb86b688b6ec29eb90a6d2fe2fdcc Mon Sep 17 00:00:00 2001 From: faumaray Date: Sat, 25 Jul 2026 23:44:48 +0300 Subject: [PATCH] update Signed-off-by: faumaray --- CMakeLists.txt | 82 +- .../standalone/StandaloneClientInterface.hpp | 9 + .../standalone/UpdateBuildDefaults.hpp.in | 17 + include/echoion/standalone/UpdateService.hpp | 83 + src/StandaloneClientInterface.cpp | 23 + src/UpdateService.cpp | 3221 +++++++++++++++++ src/main.cpp | 599 ++- tests/test_stage_release.sh | 28 +- tests/test_update_service.cpp | 691 ++++ 9 files changed, 4657 insertions(+), 96 deletions(-) create mode 100644 include/echoion/standalone/UpdateBuildDefaults.hpp.in create mode 100644 include/echoion/standalone/UpdateService.hpp create mode 100644 src/UpdateService.cpp create mode 100644 tests/test_update_service.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 2a21694..2cd6d53 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,6 +19,44 @@ pkg_check_modules(OPUS REQUIRED IMPORTED_TARGET opus) find_package(Threads REQUIRED) find_package(OpenSSL REQUIRED) +set(ECHOION_UPDATE_FEED_URL "" CACHE STRING + "Build-time default URL for the official signed update feed") +set(ECHOION_UPDATE_PUBLIC_KEYS_JSON "[]" CACHE STRING + "Build-time Ed25519 trust anchors as [{\"id\":...,\"ed25519\":...}]") +set(ECHOION_RUNTIME_VERSION "${PROJECT_VERSION}" CACHE STRING + "Canonical SemVer reported when no installed release manifest is present") +string(LENGTH "${ECHOION_RUNTIME_VERSION}" _runtime_version_length) +if(_runtime_version_length GREATER 64 OR + NOT ECHOION_RUNTIME_VERSION MATCHES + "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)?$") + message(FATAL_ERROR + "ECHOION_RUNTIME_VERSION must be canonical SemVer without build metadata") +endif() +if(ECHOION_RUNTIME_VERSION MATCHES "-([^+]+)$") + set(_runtime_prerelease "${CMAKE_MATCH_1}") + string(REPLACE "." ";" _runtime_prerelease_identifiers + "${_runtime_prerelease}") + foreach(_identifier IN LISTS _runtime_prerelease_identifiers) + if(_identifier MATCHES "^0[0-9]+$") + message(FATAL_ERROR + "ECHOION_RUNTIME_VERSION has a non-canonical numeric prerelease identifier") + endif() + endforeach() +endif() +foreach(_update_default IN ITEMS + ECHOION_UPDATE_FEED_URL ECHOION_UPDATE_PUBLIC_KEYS_JSON + ECHOION_RUNTIME_VERSION) + if("${${_update_default}}" MATCHES "\\)ECHOION_UPDATE\\\"") + message(FATAL_ERROR "${_update_default} contains the generated-header delimiter") + endif() +endforeach() +set(ECHOION_TOOLCHAIN_ABI + "${CMAKE_CXX_COMPILER_ID}-${CMAKE_CXX_COMPILER_VERSION}-${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_PROCESSOR}") +configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/standalone/UpdateBuildDefaults.hpp.in" + "${CMAKE_CURRENT_BINARY_DIR}/generated/echoion/standalone/UpdateBuildDefaults.hpp" + @ONLY) + add_executable(EchoionStandalone src/main.cpp src/StandaloneClientInterface.cpp @@ -27,10 +65,12 @@ add_executable(EchoionStandalone src/ReleaseManifest.cpp src/RuntimePaths.cpp src/EventCallbackGate.cpp + src/UpdateService.cpp ) target_include_directories(EchoionStandalone PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/include" + "${CMAKE_CURRENT_BINARY_DIR}/generated" ) target_link_libraries(EchoionStandalone PRIVATE @@ -47,6 +87,11 @@ target_link_libraries(EchoionStandalone PRIVATE Void::Log Void::System Void::Stacktrace + Void::Archive + Void::Crypto + Void::Net + Void::Plugin + Void::Update Threads::Threads PkgConfig::SWRESAMPLE PkgConfig::OPUS @@ -121,8 +166,37 @@ if(BUILD_TESTS) add_test(NAME echoion_event_callback_gate_tests COMMAND echoion_event_callback_gate_tests) - add_test(NAME echoion_stage_release_tests - COMMAND bash "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_stage_release.sh" - "${CMAKE_SOURCE_DIR}/scripts/stage-release.sh" - $) + add_executable(echoion_update_service_tests + tests/test_update_service.cpp + src/UpdateService.cpp + ) + target_include_directories(echoion_update_service_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/include" + ) + target_compile_features(echoion_update_service_tests PRIVATE cxx_std_26) + target_link_libraries(echoion_update_service_tests PRIVATE + Echoion::ApiBase Echoion::ApiConfig + Void::Archive Void::Crypto Void::Data Void::Log Void::Net Void::Plugin + Void::System Void::Update Threads::Threads) + add_test(NAME echoion_update_service_tests + COMMAND echoion_update_service_tests) + + add_executable(echoion_update_build_defaults_tests + tests/test_update_build_defaults.cpp) + target_include_directories(echoion_update_build_defaults_tests PRIVATE + "${CMAKE_CURRENT_BINARY_DIR}/generated") + target_compile_features(echoion_update_build_defaults_tests PRIVATE + cxx_std_20) + target_compile_definitions(echoion_update_build_defaults_tests PRIVATE + "ECHOION_EXPECTED_RUNTIME_VERSION=\"${ECHOION_RUNTIME_VERSION}\"") + add_test(NAME echoion_update_build_defaults_tests + COMMAND echoion_update_build_defaults_tests) + + if(TARGET EchoionUpdater) + add_test(NAME echoion_stage_release_tests + COMMAND bash "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_stage_release.sh" + "${CMAKE_SOURCE_DIR}/scripts/stage-release.sh" + $ + "${CMAKE_SOURCE_DIR}/packaging/service") + endif() endif() diff --git a/include/echoion/standalone/StandaloneClientInterface.hpp b/include/echoion/standalone/StandaloneClientInterface.hpp index ec1353c..a8a3a7d 100644 --- a/include/echoion/standalone/StandaloneClientInterface.hpp +++ b/include/echoion/standalone/StandaloneClientInterface.hpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -124,6 +125,12 @@ namespace Echoion::Standalone // Events void registerEventCallback(const Api::EventCallback& cb) override; void unregisterEventCallback(const Api::EventCallback& cb) override; + [[nodiscard]] Api::Result + hostControl(const std::string& method, + const std::string& requestJson) override; + using HostControlHandler = std::function( + const std::string&, const std::string&)>; + void setHostControlHandler(HostControlHandler handler); // Prevent new event dispatches, release registered callbacks and // wait until every callback already in flight has returned. The // host must call this before unloading code that owns an event @@ -157,6 +164,8 @@ namespace Echoion::Standalone std::map avatarPaths_; std::vector whisperList_; std::jthread snapshotThread_; + mutable std::mutex hostControlMutex_; + HostControlHandler hostControlHandler_; EventCallbackGate eventCallbacks_; }; diff --git a/include/echoion/standalone/UpdateBuildDefaults.hpp.in b/include/echoion/standalone/UpdateBuildDefaults.hpp.in new file mode 100644 index 0000000..975eeb0 --- /dev/null +++ b/include/echoion/standalone/UpdateBuildDefaults.hpp.in @@ -0,0 +1,17 @@ +#pragma once + +#include + +namespace Echoion::Standalone::UpdateBuildDefaults +{ + inline constexpr std::string_view FeedUrl = + R"ECHOION_UPDATE(@ECHOION_UPDATE_FEED_URL@)ECHOION_UPDATE"; + inline constexpr std::string_view PublicKeysJson = + R"ECHOION_UPDATE(@ECHOION_UPDATE_PUBLIC_KEYS_JSON@)ECHOION_UPDATE"; + inline constexpr std::string_view RuntimeVersion = + R"ECHOION_UPDATE(@ECHOION_RUNTIME_VERSION@)ECHOION_UPDATE"; + inline constexpr std::string_view ApiVersion = + R"ECHOION_UPDATE(@PROJECT_VERSION@)ECHOION_UPDATE"; + inline constexpr std::string_view ToolchainAbi = + R"ECHOION_UPDATE(@ECHOION_TOOLCHAIN_ABI@)ECHOION_UPDATE"; +} diff --git a/include/echoion/standalone/UpdateService.hpp b/include/echoion/standalone/UpdateService.hpp new file mode 100644 index 0000000..76dac97 --- /dev/null +++ b/include/echoion/standalone/UpdateService.hpp @@ -0,0 +1,83 @@ +#pragma once + +#include + +#include +#include +#include +#include + +namespace Echoion::Standalone +{ + // Roll back any uncommitted managed-plugin activation before Core loads and + // discovers plugin `current` links. This must run before PluginHost + // startup. + [[nodiscard]] Api::Result reconcileManagedPluginUpdates( + const std::filesystem::path& stateDirectory); + + // Host-owned update coordinator. Core only forwards authenticated RPC + // requests across the append-only host interface; all trust, download, + // staging and activation decisions remain in the long-lived daemon. + class UpdateService final + { + public: + + struct Options { + std::filesystem::path configPath; + std::filesystem::path stateDirectory; + std::filesystem::path installRoot; + std::filesystem::path runningExecutable; + std::filesystem::path currentCore; + std::filesystem::path releaseManifestPath; + std::string officialFeedUrl; + std::string officialPublicKeysJson = "[]"; + std::string runtimeVersion; + std::string apiVersion; + std::string toolchainAbi; + // Trusted administrator drop directory for file:// + // feeds/artifacts. Empty selects stateDirectory / + // "incoming". + std::filesystem::path incomingDirectory; + }; + + struct Hooks { + std::function( + const std::filesystem::path&)> + replaceCore; + std::function(const std::string&)> + managePlugins; + std::function(const std::string&)> + manageRuntime; + std::function playbackActive; + std::function coreVersion; + }; + + UpdateService(Options options, Hooks hooks); + ~UpdateService(); + + UpdateService(const UpdateService&) = delete; + UpdateService& operator=(const UpdateService&) = delete; + UpdateService(UpdateService&&) noexcept; + UpdateService& operator=(UpdateService&&) noexcept; + + [[nodiscard]] Api::Result start(); + void stop() noexcept; + + // Execute host mutations which must not run on the Core RPC stack. + // The daemon calls this from its polling loop after an RPC has + // returned. + void processPendingHostActions(); + + // Methods are the internal `updates.*` names forwarded by Core. + // Requests and successful responses are JSON documents matching the + // web contract. + [[nodiscard]] Api::Result + handle(const std::string& method, + const std::string& requestJson); + + private: + + class Impl; + std::unique_ptr impl_; + }; +} // namespace Echoion::Standalone diff --git a/src/StandaloneClientInterface.cpp b/src/StandaloneClientInterface.cpp index 915d6be..beb05bf 100644 --- a/src/StandaloneClientInterface.cpp +++ b/src/StandaloneClientInterface.cpp @@ -1225,6 +1225,29 @@ namespace Echoion::Standalone quiesceEventCallbacks(); } + Api::Result + StandaloneClientInterface::hostControl(const std::string& method, + const std::string& requestJson) + { + HostControlHandler handler; + { + std::lock_guard lock(hostControlMutex_); + handler = hostControlHandler_; + } + if (!handler) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "host control plane is not ready"); + } + return handler(method, requestJson); + } + + void StandaloneClientInterface::setHostControlHandler( + HostControlHandler handler) + { + std::lock_guard lock(hostControlMutex_); + hostControlHandler_ = std::move(handler); + } + void StandaloneClientInterface::quiesceEventCallbacks() { eventCallbacks_.quiesce(); diff --git a/src/UpdateService.cpp b/src/UpdateService.cpp new file mode 100644 index 0000000..d3afda3 --- /dev/null +++ b/src/UpdateService.cpp @@ -0,0 +1,3221 @@ +#include "echoion/standalone/UpdateService.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Standalone +{ + namespace + { + using Void::Json::Value; + + constexpr auto kMinimumCheckInterval = std::chrono::minutes{5}; + constexpr auto kMaximumCheckInterval = std::chrono::hours{24 * 30}; + constexpr auto kMaximumRuntimeDeferral = std::chrono::hours{24 * 7}; + constexpr auto kUnsignedConfirmationLifetime = std::chrono::minutes{10}; + constexpr std::uint64_t kMaximumArtifactBytes = + 2ULL * 1024 * 1024 * 1024; + + struct CandidateRecord { + Void::Update::Release release; + std::string id; + std::string source; + bool signedFeed = true; + std::chrono::system_clock::time_point discoveredAt; + std::string confirmationToken; + std::chrono::system_clock::time_point confirmationExpiresAt{}; + bool unsignedAuthorized = false; + bool applying = false; + }; + + struct FetchedFeed { + Void::Update::Feed feed; + bool signedFeed = true; + }; + + struct PluginInventoryEntry { + std::string id; + std::string name; + std::string version; + std::filesystem::path path; + bool managed = false; + }; + + struct PendingCoreAction { + std::string action; + std::string version; + std::string candidateId; + std::filesystem::path path; + std::optional previousVersion; + bool activationPending = true; + bool processing = false; + }; + + struct HistoryEntry { + std::chrono::system_clock::time_point timestamp; + std::string component; + std::string pluginId; + std::string action; + std::string version; + std::string result; + std::string message; + std::string actor; + }; + + [[nodiscard]] std::optional + parseVersion(std::string_view value) + { + if (value.empty()) { + return std::nullopt; + } + return Void::Semver::parse(value); + } + + [[nodiscard]] Void::Semver::Version + versionOrZero(std::string_view value) + { + return parseVersion(value).value_or(Void::Semver::Version{}); + } + + [[nodiscard]] std::string nativePlatform() + { +#if defined(__linux__) + return "linux"; +#elif defined(__APPLE__) + return "macos"; +#elif defined(_WIN32) + return "windows"; +#else + return "unknown"; +#endif + } + + [[nodiscard]] std::string nativeArchitecture() + { +#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 + } + + [[nodiscard]] std::int64_t + unixMilliseconds(std::chrono::system_clock::time_point value) + { + return std::chrono::duration_cast( + value.time_since_epoch()) + .count(); + } + + [[nodiscard]] std::string + candidateId(std::string_view source, + const Void::Update::Release& release) + { + const auto material = std::format( + "{}|{}|{}|{}|{}", source, release.component, release.artifactId, + release.version.to_string(), release.sha256); + auto digest = Void::Crypto::sha256(material); + if (!digest) { + return release.sha256; + } + return Void::Encoding::Hex::encode(*digest); + } + + [[nodiscard]] std::optional + decodePublicKey(std::string_view encoded) + { + std::optional decoded; + if (encoded.size() == Void::Crypto::Ed25519PublicKeySize * 2) { + decoded = Void::Encoding::Hex::decode(encoded); + } + if (!decoded) { + decoded = Void::Encoding::Base64::decode(encoded); + } + if (!decoded) { + decoded = Void::Encoding::Base64::decode_url(encoded); + } + if (!decoded || + decoded->size() != Void::Crypto::Ed25519PublicKeySize) { + return std::nullopt; + } + Void::Update::Ed25519PublicKey key{}; + std::memcpy(key.data(), decoded->data(), decoded->size()); + return key; + } + + [[nodiscard]] Api::Result parseJson(std::string_view json) + { + auto parsed = Void::Json::parse(json); + if (!parsed) { + return Api::fail(Api::ErrorCode::ParseError, + std::format("invalid JSON at {}:{}: {}", + parsed.error().line, + parsed.error().col, + parsed.error().message)); + } + return std::move(*parsed); + } + + [[nodiscard]] bool safeIdentifier(std::string_view value) + { + if (value.empty() || value.size() > 64 || value == "." || + value == "..") { + return false; + } + if (!std::isalnum(static_cast(value.front()))) { + return false; + } + return std::ranges::all_of(value, [](unsigned char character) { + return std::isalnum(character) || character == '.' || + character == '_' || character == '-'; + }); + } + + [[nodiscard]] Void::Result::Result + isRealRegularFile(const std::filesystem::path& path) + { + std::error_code error; + const auto status = std::filesystem::symlink_status(path, error); + if (error == std::errc::no_such_file_or_directory || + status.type() == std::filesystem::file_type::not_found) { + return false; + } + if (error) { + return Void::Result::fail( + std::format("cannot inspect rollback payload '{}': {}", + path.string(), error.message())); + } + return std::filesystem::is_regular_file(status) && + !std::filesystem::is_symlink(status); + } + + [[nodiscard]] + Void::Result::Result> + newestHealthyRollback( + const Void::Update::VersionStore& store, + std::span excludedVersions, + const std::filesystem::path& relativePayload) + { + auto healthy = store.healthyPublishedVersions(); + if (!healthy) { + return std::unexpected{healthy.error()}; + } + for (const auto& version : *healthy) { + if (std::ranges::find(excludedVersions, version) != + excludedVersions.end()) { + continue; + } + auto valid = isRealRegularFile(store.versionPath(version) / + relativePayload); + if (!valid) { + return std::unexpected{valid.error()}; + } + if (*valid) { + return std::optional{version}; + } + } + return std::optional{}; + } + + [[nodiscard]] bool safeEnvironmentName(std::string_view value) + { + if (value.empty()) { + return true; + } + if (!(std::isalpha(static_cast(value.front())) || + value.front() == '_')) { + return false; + } + return std::ranges::all_of( + value.substr(1), [](unsigned char character) { + return std::isalnum(character) || character == '_'; + }); + } + + [[nodiscard]] bool sameHex(std::string_view left, + std::string_view right) noexcept + { + return left.size() == right.size() && + std::ranges::equal( + left, right, [](unsigned char lhs, unsigned char rhs) { + return std::tolower(lhs) == std::tolower(rhs); + }); + } + + [[nodiscard]] bool hasUrlUserInfo(std::string_view value) + { + const auto scheme = value.find("://"); + if (scheme == std::string_view::npos) { + return false; + } + const auto authorityStart = scheme + 3; + const auto authorityEnd = + value.find_first_of("/?#", authorityStart); + return value.substr(authorityStart, authorityEnd - authorityStart) + .contains('@'); + } + + [[nodiscard]] bool pathIsWithin(const std::filesystem::path& candidate, + const std::filesystem::path& root) + { + std::error_code error; + const auto canonicalRoot = + std::filesystem::weakly_canonical(root, error); + if (error) { + return false; + } + const auto canonicalCandidate = + std::filesystem::weakly_canonical(candidate, error); + if (error) { + return false; + } + const auto [rootEnd, candidateEnd] = + std::ranges::mismatch(canonicalRoot, canonicalCandidate); + return rootEnd == canonicalRoot.end() && + canonicalRoot != canonicalCandidate && + candidateEnd != canonicalCandidate.begin(); + } + + [[nodiscard]] bool validMaintenanceStart(std::string_view value) + { + if (value.size() != 5 || value[2] != ':' || + !std::isdigit(static_cast(value[0])) || + !std::isdigit(static_cast(value[1])) || + !std::isdigit(static_cast(value[3])) || + !std::isdigit(static_cast(value[4]))) { + return false; + } + const int hour = (value[0] - '0') * 10 + value[1] - '0'; + const int minute = (value[3] - '0') * 10 + value[4] - '0'; + return hour < 24 && minute < 60; + } + + [[nodiscard]] bool + withinMaintenanceWindow(const Api::UpdateMaintenanceWindow& window, + std::chrono::system_clock::time_point now) + { + const auto time = std::chrono::system_clock::to_time_t(now); + std::tm utc{}; + if (::gmtime_r(&time, &utc) == nullptr) { + return false; + } + const int start = + (window.start[0] - '0') * 600 + (window.start[1] - '0') * 60 + + (window.start[3] - '0') * 10 + (window.start[4] - '0'); + const int current = utc.tm_hour * 60 + utc.tm_min; + const auto duration = + std::chrono::duration_cast( + window.duration) + .count(); + const int end = static_cast((start + duration) % (24 * 60)); + return duration >= 24 * 60 || + (start < end ? current >= start && current < end + : current >= start || current < end); + } + + [[nodiscard]] Api::Result + validateConfig(const Api::UpdatesConfig& config, + const std::filesystem::path& incoming) + { + if (config.checkInterval < kMinimumCheckInterval || + config.checkInterval > kMaximumCheckInterval) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "update checkInterval must be between 5m and 30d"); + } + if (config.jitter < std::chrono::milliseconds::zero() || + config.jitter > config.checkInterval) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "update jitter must be non-negative and no " + "longer than checkInterval"); + } + if (!validMaintenanceStart(config.maintenanceWindowUtc.start) || + config.maintenanceWindowUtc.duration < + std::chrono::minutes{1} || + config.maintenanceWindowUtc.duration > std::chrono::hours{24}) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "maintenanceWindowUtc requires HH:MM and a " + "duration from 1m to 24h"); + } + if (config.maxRuntimeDeferral < std::chrono::milliseconds::zero() || + config.maxRuntimeDeferral > kMaximumRuntimeDeferral) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "maxRuntimeDeferral must be between 0 and 7d"); + } + if (config.retainHealthyVersions < 1 || + config.retainHealthyVersions > 10) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "retainHealthyVersions must be between 1 and 10"); + } + + for (const auto& [id, source] : config.sources) { + if (!safeIdentifier(id)) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + std::format("invalid update source id '{}'", id)); + } + if (!safeEnvironmentName(source.bearerTokenEnv)) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + std::format("source '{}' has an invalid bearer token " + "environment name", + id)); + } + if (source.url.empty() && id != "official") { + return Api::fail( + Api::ErrorCode::InvalidArgument, + std::format("source '{}' requires a feed URL", id)); + } + if (!source.url.empty()) { + if (hasUrlUserInfo(source.url)) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + std::format( + "source '{}' URL must not contain credentials", + id)); + } + if (source.url.starts_with("file://")) { + const auto path = + std::filesystem::path{source.url.substr(7)}; + if (!pathIsWithin(path, incoming)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format( + "source '{}' file URL must be under {}", id, + incoming.string())); + } + } else { + const auto url = Void::Net::Url::parse(source.url); + if (!url || url->scheme != "https" || + url->host.empty()) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + std::format("source '{}' must use an HTTPS URL", + id)); + } + } + } + for (const auto& key : source.publicKeys) { + if (!safeIdentifier(key.id) || key.ed25519.empty()) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + std::format( + "source '{}' contains an invalid public key", + id)); + } + } + } + + const auto validatePolicy = + [&config](std::string_view component, std::string_view source, + std::string_view channel) -> Api::Result { + if (!config.sources.contains(std::string(source))) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + std::format("{} references unknown source '{}'", + component, source)); + } + if (!safeIdentifier(channel)) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + std::format("{} has an invalid channel", component)); + } + return {}; + }; + if (auto result = validatePolicy("runtime", config.runtime.source, + config.runtime.channel); + !result) { + return result; + } + if (auto result = validatePolicy("core", config.core.source, + config.core.channel); + !result) { + return result; + } + if (auto result = validatePolicy("plugins", config.plugins.source, + config.plugins.channel); + !result) { + return result; + } + for (const auto& [plugin, policy] : config.plugins.overrides) { + if (!safeIdentifier(plugin)) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "plugin update override has an invalid id"); + } + if (auto result = + validatePolicy(std::format("plugin {}", plugin), + policy.source, policy.channel); + !result) { + return result; + } + } + return {}; + } + + void add(Value& object, std::string key, Value value) + { + object.as_object().emplace_back(std::move(key), std::move(value)); + } + + [[nodiscard]] const Value* payload(const Value& request, + std::string_view key) + { + if (!request.is_object()) { + return nullptr; + } + if (const auto* nested = request.find(key)) { + return nested; + } + return &request; + } + + [[nodiscard]] std::string stringField(const Value& object, + std::string_view key) + { + const auto* value = object.is_object() ? object.find(key) : nullptr; + return value && value->is_string() ? value->as_string() + : std::string{}; + } + + [[nodiscard]] bool boolField(const Value& object, std::string_view key, + bool fallback = false) + { + const auto* value = object.is_object() ? object.find(key) : nullptr; + return value && value->is_bool() ? value->as_bool() : fallback; + } + + template + [[nodiscard]] Api::Result + invokeHostHook(std::string_view operation, + Function&& function) noexcept + { + try { + return std::forward(function)(); + } catch (const std::exception& error) { + return Api::fail(Api::ErrorCode::UnknownError, + std::format("{} threw an exception: {}", + operation, error.what())); + } catch (...) { + return Api::fail( + Api::ErrorCode::UnknownError, + std::format("{} threw an unknown exception", operation)); + } + } + } // namespace + + class UpdateService::Impl final + { + public: + + Impl(Options options, Hooks hooks) + : options_(std::move(options)), hooks_(std::move(hooks)), + updateDirectory_(options_.stateDirectory / "updates"), + incomingDirectory_(options_.incomingDirectory.empty() + ? options_.stateDirectory / "incoming" + : options_.incomingDirectory) + { + } + + [[nodiscard]] Api::Result start() + { + std::error_code error; + std::filesystem::create_directories(incomingDirectory_, error); + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot create updater directory '{}': {}", + incomingDirectory_.string(), + error.message())); + } + std::filesystem::create_directories( + updateDirectory_ / "downloads", error); + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot create updater directory '{}': {}", + (updateDirectory_ / "downloads").string(), + error.message())); + } + std::filesystem::create_directories(updateDirectory_ / "staged", + error); + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot create updater directory '{}': {}", + (updateDirectory_ / "staged").string(), + error.message())); + } + std::filesystem::create_directories( + updateDirectory_ / "extract", error); + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot create updater directory '{}': {}", + (updateDirectory_ / "extract").string(), + error.message())); + } + if (auto loaded = loadConfig(); !loaded) { + return loaded; + } + if (auto discovered = discoverRuntimeRollback(); !discovered) { + return discovered; + } + const auto sequencePath = updateDirectory_ / "sequences.json"; + error.clear(); + const auto sequenceStatus = + std::filesystem::symlink_status(sequencePath, error); + if (!error && sequenceStatus.type() != + std::filesystem::file_type::not_found) { + if (std::filesystem::is_symlink(sequenceStatus) || + !std::filesystem::is_regular_file(sequenceStatus)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + "update replay-floor state must be a regular file"); + } + auto state = Void::FileSystem::read_file(sequencePath); + if (!state) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format( + "cannot read update replay-floor state: {}", + state.error().message())); + } + auto parsed = parseJson(*state); + if (!parsed) { + return Api::fail( + Api::ErrorCode::ParseError, + std::format("invalid update replay-floor state: {}", + parsed.error().message)); + } + auto values = Void::Json::from_json< + std::map>(*parsed); + if (!values) { + return Api::fail( + Api::ErrorCode::ParseError, + std::format( + "invalid update replay-floor state at '{}': {}", + values.error().field, values.error().message)); + } + std::lock_guard lock(mutex_); + sequences_ = std::move(*values); + } else if (error != std::errc::no_such_file_or_directory && + error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format( + "cannot inspect update replay-floor state: {}", + error.message())); + } + Void::Update::VersionStore coreStore(updateDirectory_ / + "components" / "core"); + if (auto initialized = coreStore.initialize(); !initialized) { + return Api::fail(Api::ErrorCode::UnknownError, + initialized.error().message()); + } + auto interrupted = coreStore.pendingActivation(); + if (!interrupted) { + return Api::fail(Api::ErrorCode::UnknownError, + interrupted.error().message()); + } + if (auto reconciled = coreStore.reconcile(); !reconciled) { + return Api::fail(Api::ErrorCode::UnknownError, + reconciled.error().message()); + } + if (auto seeded = seedCoreStore(coreStore); !seeded) { + return seeded; + } + pruneStoreBestEffort(coreStore, "Core"); + if (auto discovered = discoverCoreRollback(coreStore); + !discovered) { + return discovered; + } + if (auto discovered = reconcileAndDiscoverManagedPlugins(); + !discovered) { + return discovered; + } + if (interrupted->has_value() && + (*interrupted)->previousVersion) { + const auto previous = *(*interrupted)->previousVersion; + std::lock_guard lock(mutex_); + pendingCoreAction_ = PendingCoreAction{ + .action = "reconcile", + .version = previous.to_string(), + .candidateId = {}, + .path = + coreStore.versionPath(previous) / coreFilename(), + .previousVersion = (*interrupted)->candidateVersion, + .activationPending = false}; + coreState_ = "pending-host-action"; + coreMessage_ = + "Restoring Core after an interrupted activation"; + } + { + std::lock_guard lock(mutex_); + if (worker_.joinable()) { + return {}; + } + nextCheck_ = + std::chrono::system_clock::now() + nextDelayLocked(); + worker_ = std::jthread( + [this](std::stop_token token) { scheduler(token); }); + } + return {}; + } + + void stop() noexcept + { + std::jthread worker; + { + std::lock_guard lock(mutex_); + if (!worker_.joinable()) { + return; + } + worker_.request_stop(); + condition_.notify_all(); + worker = std::move(worker_); + } + if (worker.joinable()) { + worker.join(); + } + } + + [[nodiscard]] Api::Result + handle(const std::string& method, + const std::string& requestJson) + { + if (method == "updates.getStatus") { + return statusJson(); + } + if (method == "updates.getConfig") { + return configJson(); + } + if (method == "updates.setConfig") { + return setConfig(requestJson); + } + if (method == "updates.check") { + return checkNow(true); + } + if (method == "updates.apply") { + return apply(requestJson); + } + if (method == "updates.rollback") { + return rollback(requestJson); + } + if (method == "updates.confirmUnsigned") { + return confirmUnsigned(requestJson); + } + return Api::fail( + Api::ErrorCode::NotFound, + std::format("unknown host control method '{}'", method)); + } + + void processPendingHostActions(); + + private: + + [[nodiscard]] std::filesystem::path coreFilename() const + { + return options_.currentCore.filename().empty() + ? std::filesystem::path{"Echoion.ts"} + : options_.currentCore.filename(); + } + + [[nodiscard]] std::size_t retainedPreviousVersions() const + { + std::lock_guard lock(mutex_); + return config_.retainHealthyVersions; + } + + void pruneStoreBestEffort(Void::Update::VersionStore& store, + std::string_view component) const + { + auto pruned = store.prune(retainedPreviousVersions()); + if (!pruned) { + Void::Log::warn("UpdateService", + "could not prune {} versions: {}", + component, pruned.error().message()); + } + } + + [[nodiscard]] Api::Result + seedStoreFromFile(Void::Update::VersionStore& store, + std::string_view versionText, + const std::filesystem::path& source, + const std::filesystem::path& filename); + [[nodiscard]] Api::Result + seedCoreStore(Void::Update::VersionStore& store); + [[nodiscard]] Api::Result + discoverCoreRollback(Void::Update::VersionStore& store); + [[nodiscard]] Api::Result discoverRuntimeRollback(); + [[nodiscard]] Api::Result + reconcileAndDiscoverManagedPlugins(); + [[nodiscard]] Api::Result + publishArtifact(Void::Update::VersionStore& store, + const Void::Semver::Version& version, + const std::filesystem::path& artifact, + const std::filesystem::path& filename, + std::string_view expectedSha256); + + [[nodiscard]] std::string + sourceUrl(std::string_view id, + const Api::UpdateSourceConfig& source) const + { + if (!source.url.empty()) { + return source.url; + } + return id == "official" ? options_.officialFeedUrl + : std::string{}; + } + + [[nodiscard]] std::string + replayFloorKey(std::string_view id, + const Api::UpdateSourceConfig& source) const + { + std::string identity; + auto append = [&identity](std::string_view field) { + identity += std::format("{}:{}|", field.size(), field); + }; + append(sourceUrl(id, source)); + append(source.allowUnsigned ? "unsigned" : "signed"); + for (const auto& key : source.publicKeys) { + append(key.id); + append(key.ed25519); + } + if (id == "official") { + append(options_.officialPublicKeysJson); + } + auto digest = Void::Crypto::sha256(identity); + return digest + ? std::format("{}@{}", id, + Void::Encoding::Hex::encode(*digest)) + : std::string{id}; + } + + [[nodiscard]] Api::Result + keyring(std::string_view sourceId, + const Api::UpdateSourceConfig& source) const + { + std::vector keys = source.publicKeys; + if (sourceId == "official" && + !options_.officialPublicKeysJson.empty()) { + auto defaults = parseJson(options_.officialPublicKeysJson); + if (!defaults) { + return std::unexpected(defaults.error()); + } + if (!defaults->is_array()) { + return Api::fail(Api::ErrorCode::ParseError, + "build-time official update keys must " + "be a JSON array"); + } + for (const auto& value : defaults->as_array()) { + const auto id = stringField(value, "id"); + const auto encoded = stringField(value, "ed25519"); + if (!id.empty() || !encoded.empty()) { + keys.push_back({.id = id, .ed25519 = encoded}); + } + } + } + + Void::Update::Keyring result; + for (const auto& key : keys) { + auto decoded = decodePublicKey(key.ed25519); + if (!safeIdentifier(key.id) || !decoded) { + return Api::fail( + Api::ErrorCode::ParseError, + std::format( + "source '{}' has an invalid Ed25519 key '{}'", + sourceId, key.id)); + } + result.insert_or_assign(key.id, *decoded); + } + return result; + } + + [[nodiscard]] Api::Result + fetchBytes(std::string_view url, + const Api::UpdateSourceConfig& source, + std::uint64_t maximumBytes, + std::string_view credentialOrigin = {}) const + { + if (url.starts_with("file://")) { + auto path = std::filesystem::path{url.substr(7)}; + if (!pathIsWithin(path, incomingDirectory_)) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "local update input must be under the " + "configured incoming directory"); + } + std::error_code error; + const auto size = std::filesystem::file_size(path, error); + if (error || size > maximumBytes) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "local update input is missing or " + "exceeds its size limit"); + } + auto bytes = Void::FileSystem::read_file(path); + if (!bytes) { + return Api::fail( + Api::ErrorCode::NotFound, + std::format("cannot read local update input: {}", + bytes.error().message())); + } + return std::move(*bytes); + } + const auto parsed = Void::Net::Url::parse(url); + if (!parsed || parsed->scheme != "https" || + parsed->host.empty() || hasUrlUserInfo(url)) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "update downloads require a credential-free HTTPS URL"); + } + Void::Net::HttpClient client; + client.set_user_agent("Echoion-Updater/1"); + client.set_verify_tls(true); + client.set_max_redirects(0); + client.set_max_body_size(maximumBytes); + Void::Net::Request request; + request.method = Void::Net::Method::Get; + request.url = std::string(url); + request.timeout = std::chrono::seconds{60}; + const auto origin = Void::Net::Url::parse(credentialOrigin); + const bool sameCredentialOrigin = + origin && origin->scheme == parsed->scheme && + origin->host == parsed->host && + origin->port == parsed->port; + if (sameCredentialOrigin && !source.bearerTokenEnv.empty()) { + if (const char* token = + std::getenv(source.bearerTokenEnv.c_str()); + token && *token != '\0') { + request.headers.push_back( + {"Authorization", std::string{"Bearer "} + token}); + } + } + auto response = client.send(request); + if (!response) { + return Api::fail(Api::ErrorCode::NetworkError, + response.error().message()); + } + if (!response->ok()) { + return Api::fail( + Api::ErrorCode::NetworkError, + std::format("update server returned HTTP {}", + response->status)); + } + if (response->body.size() > maximumBytes) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "update response exceeded its size limit"); + } + return std::move(response->body); + } + + [[nodiscard]] Api::Result + fetchFeed(std::string_view id, + const Api::UpdateSourceConfig& source, + std::optional minimumSequence) const + { + const auto url = sourceUrl(id, source); + if (url.empty()) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + std::format("update source '{}' has no feed URL", id)); + } + auto bytes = fetchBytes(url, source, 5U * 1024U * 1024U, url); + if (!bytes) { + return std::unexpected(bytes.error()); + } + Void::Update::VerificationPolicy policy; + policy.minimumSequence = minimumSequence; + auto keys = keyring(id, source); + if (!keys) { + return std::unexpected(keys.error()); + } + if (!keys->empty()) { + auto verified = + Void::Update::verifyFeedEnvelope(*bytes, *keys, policy); + if (verified) { + return FetchedFeed{.feed = std::move(verified->feed), + .signedFeed = true}; + } + if (!source.allowUnsigned) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format( + "source '{}' signature verification failed: {}", + id, verified.error().message())); + } + } else if (!source.allowUnsigned) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("source '{}' has no trusted signing key", + id)); + } + + // Explicitly configured unsigned sources may present either a + // raw feed payload or an envelope whose payload field is the + // exact JSON text. + std::string payloadBytes = *bytes; + if (auto envelope = parseJson(*bytes); + envelope && envelope->is_object()) { + if (const auto* payloadValue = envelope->find("payload"); + payloadValue && payloadValue->is_string()) { + payloadBytes = payloadValue->as_string(); + } + } + auto parsed = + Void::Update::parseFeedPayload(payloadBytes, policy); + if (!parsed) { + return Api::fail( + Api::ErrorCode::ParseError, + std::format("unsigned source '{}' feed rejected: {}", + id, parsed.error().message())); + } + return FetchedFeed{.feed = std::move(*parsed), + .signedFeed = false}; + } + + [[nodiscard]] Void::Update::Environment environment() const + { + const auto runtime = versionOrZero(options_.runtimeVersion); + const auto core = + versionOrZero(hooks_.coreVersion ? hooks_.coreVersion() + : options_.runtimeVersion); + Void::Update::Environment value; + value.platform = nativePlatform(); + value.architecture = nativeArchitecture(); + value.versionContracts.emplace("echoion.runtime", runtime); + value.versionContracts.emplace("echoion.core", core); + value.versionContracts.emplace( + "echoion.api", versionOrZero(options_.apiVersion)); + value.exactContracts.emplace( + "void.plugin.abi", + std::to_string(Void::Plugin::ABI_VERSION)); + value.exactContracts.emplace("cxx.toolchain.abi", + options_.toolchainAbi); + return value; + } + + [[nodiscard]] std::vector + queryPluginInventory() const + { + if (!hooks_.managePlugins) { + return {}; + } + auto response = + invokeHostHook("plugin inventory hook", [&] { + return hooks_.managePlugins( + R"({"schemaVersion":1,"action":"status"})"); + }); + if (!response) { + Void::Log::warn("UpdateService", "cannot query plugins: {}", + response.error().message); + return {}; + } + auto parsed = parseJson(*response); + if (!parsed) { + return {}; + } + const auto* entries = parsed->find("plugins"); + if (!entries || !entries->is_array()) { + return {}; + } + std::vector result; + for (const auto& entry : entries->as_array()) { + auto id = stringField(entry, "id"); + if (id.empty()) { + continue; + } + result.push_back({.id = std::move(id), + .name = stringField(entry, "name"), + .version = stringField(entry, "version"), + .path = stringField(entry, "path"), + .managed = boolField(entry, "managed")}); + } + return result; + } + + [[nodiscard]] Api::Result loadConfig() + { + auto contents = + Void::FileSystem::read_file(options_.configPath); + if (!contents) { + return Api::fail( + Api::ErrorCode::NotFound, + std::format("cannot read updater configuration: {}", + contents.error().message())); + } + auto root = parseJson(*contents); + if (!root) { + return std::unexpected(root.error()); + } + const auto* value = root->find("updates"); + Api::UpdatesConfig config; + if (value) { + auto parsed = + Void::Json::from_json(*value); + if (!parsed) { + return Api::fail( + Api::ErrorCode::ParseError, + std::format( + "invalid updates configuration at '{}': {}", + parsed.error().field, parsed.error().message)); + } + config = std::move(*parsed); + } + if (!config.sources.contains("official")) { + config.sources.emplace("official", + Api::UpdateSourceConfig{}); + } + if (auto valid = validateConfig(config, incomingDirectory_); + !valid) { + return valid; + } + std::lock_guard lock(mutex_); + config_ = std::move(config); + return {}; + } + + [[nodiscard]] Api::Result configJson() const + { + Api::UpdatesConfig snapshot; + { + std::lock_guard lock(mutex_); + snapshot = config_; + } + auto value = Void::Json::to_json(snapshot); + if (auto* sources = value.find("sources"); + sources && sources->is_object()) { + for (auto& [id, source] : sources->as_object()) { + const auto configured = snapshot.sources.find(id); + if (configured == snapshot.sources.end() || + !source.is_object()) { + continue; + } + const auto& environment = + configured->second.bearerTokenEnv; + const bool present = + !environment.empty() && + std::getenv(environment.c_str()) != nullptr; + add(source, "bearerTokenPresent", Value{present}); + } + } + return Void::Json::serialize(value, {.pretty = true}); + } + + [[nodiscard]] Api::Result + setConfig(std::string_view requestJson) + { + auto request = + parseJson(requestJson.empty() ? "{}" : requestJson); + if (!request) { + return std::unexpected(request.error()); + } + const auto* value = payload(*request, "config"); + if (!value || !value->is_object()) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "setConfig requires a config object"); + } + auto parsed = Void::Json::from_json(*value); + if (!parsed) { + return Api::fail( + Api::ErrorCode::ParseError, + std::format("invalid update config at '{}': {}", + parsed.error().field, + parsed.error().message)); + } + if (!parsed->sources.contains("official")) { + parsed->sources.emplace("official", + Api::UpdateSourceConfig{}); + } + if (auto valid = validateConfig(*parsed, incomingDirectory_); + !valid) { + return std::unexpected(valid.error()); + } + + auto contents = + Void::FileSystem::read_file(options_.configPath); + if (!contents) { + return Api::fail( + Api::ErrorCode::NotFound, + std::format("cannot read configuration: {}", + contents.error().message())); + } + auto root = parseJson(*contents); + if (!root) { + return std::unexpected(root.error()); + } + if (!root->is_object()) { + return Api::fail(Api::ErrorCode::ParseError, + "configuration root must be an object"); + } + bool replaced = false; + for (auto& [key, member] : root->as_object()) { + if (key == "updates") { + member = Void::Json::to_json(*parsed); + replaced = true; + break; + } + } + if (!replaced) { + add(*root, "updates", Void::Json::to_json(*parsed)); + } + const auto serialized = + Void::Json::serialize(*root, {.pretty = true}); + if (auto written = Void::FileSystem::atomic_write( + options_.configPath, serialized); + !written) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot persist update configuration: {}", + written.error().message())); + } + { + std::lock_guard lock(mutex_); + config_ = std::move(*parsed); + nextCheck_ = + std::chrono::system_clock::now() + nextDelayLocked(); + } + condition_.notify_all(); + return configJson(); + } + + [[nodiscard]] std::chrono::milliseconds nextDelayLocked() + { + auto delay = config_.checkInterval; + if (config_.jitter > std::chrono::milliseconds::zero()) { + std::uniform_int_distribution distribution( + 0, config_.jitter.count()); + delay += std::chrono::milliseconds{distribution(random_)}; + } + return delay; + } + + void scheduler(std::stop_token token) + { + std::unique_lock lock(mutex_); + while (!token.stop_requested()) { + if (!config_.enabled) { + condition_.wait(lock, token, + [this] { return config_.enabled; }); + continue; + } + const auto scheduledCheck = nextCheck_; + auto deadline = scheduledCheck; + if (runtimeState_ == "waiting-for-idle" && + runtimeCandidate_) { + deadline = std::min(deadline, + std::chrono::system_clock::now() + + std::chrono::minutes{1}); + } + if (condition_.wait_until( + lock, token, deadline, [this, scheduledCheck] { + return nextCheck_ != scheduledCheck; + })) { + continue; + } + if (token.stop_requested()) { + break; + } + const auto now = std::chrono::system_clock::now(); + if (runtimeState_ == "waiting-for-idle" && + runtimeCandidate_) { + const bool idle = + !hooks_.playbackActive || !hooks_.playbackActive(); + const bool deferred = + now - runtimeCandidate_->discoveredAt >= + config_.maxRuntimeDeferral; + const bool forcedWindow = + deferred && withinMaintenanceWindow( + config_.maintenanceWindowUtc, now); + if (idle || forcedWindow) { + const auto candidate = *runtimeCandidate_; + lock.unlock(); + Value request = Void::Json::object(); + add(request, "component", Value{"runtime"}); + add(request, "candidateId", Value{candidate.id}); + add(request, "version", + Value{candidate.release.version.to_string()}); + if (!candidate.confirmationToken.empty()) { + add(request, "confirmationToken", + Value{candidate.confirmationToken}); + } + if (auto result = + apply(Void::Json::serialize(request)); + !result) { + Void::Log::warn( + "UpdateService", + "deferred runtime apply failed: {}", + result.error().message); + } + lock.lock(); + continue; + } + } + if (now < nextCheck_) { + continue; + } + lock.unlock(); + auto result = checkNow(false); + if (!result) { + Void::Log::warn("UpdateService", + "scheduled check failed: {}", + result.error().message); + } + lock.lock(); + nextCheck_ = + std::chrono::system_clock::now() + nextDelayLocked(); + } + } + + [[nodiscard]] Api::Result statusJson() const; + [[nodiscard]] Api::Result checkNow(bool manual); + [[nodiscard]] Api::Result + downloadArtifact(const CandidateRecord& candidate); + [[nodiscard]] Api::Result + activateCore(const CandidateRecord& candidate); + [[nodiscard]] Api::Result + activatePlugin(std::string_view pluginId, + const CandidateRecord& candidate); + [[nodiscard]] Api::Result + activateRuntime(const CandidateRecord& candidate); + void recordHistory(HistoryEntry entry); + [[nodiscard]] Api::Result + apply(std::string_view requestJson); + [[nodiscard]] Api::Result + rollback(std::string_view requestJson); + [[nodiscard]] Api::Result + confirmUnsigned(std::string_view requestJson); + + Options options_; + Hooks hooks_; + std::filesystem::path updateDirectory_; + std::filesystem::path incomingDirectory_; + mutable std::mutex mutex_; + std::condition_variable_any condition_; + Api::UpdatesConfig config_; + std::jthread worker_; + std::chrono::system_clock::time_point lastCheck_{}; + std::chrono::system_clock::time_point nextCheck_{}; + bool checking_ = false; + std::string message_; + std::optional runtimeCandidate_; + std::optional coreCandidate_; + std::unordered_map pluginCandidates_; + std::vector pluginInventory_; + std::vector history_; + std::map sequences_; + std::string runtimeState_ = "current"; + std::string coreState_ = "current"; + std::string pluginsState_ = "current"; + std::string runtimeMessage_; + std::string coreMessage_; + std::string pluginsMessage_; + std::string runtimeRollbackVersion_; + std::string coreRollbackVersion_; + std::unordered_map + pluginRollbackVersions_; + std::optional pendingCoreAction_; + std::mt19937_64 random_{std::random_device{}()}; + }; + + Api::Result UpdateService::Impl::seedStoreFromFile( + Void::Update::VersionStore& store, std::string_view versionText, + const std::filesystem::path& source, + const std::filesystem::path& filename) + { + auto current = store.currentVersion(); + if (!current) { + return Api::fail(Api::ErrorCode::UnknownError, + current.error().message()); + } + if (current->has_value()) { + return {}; + } + + const auto version = Void::Semver::parse_strict(versionText); + if (!version) { + return Api::fail( + Api::ErrorCode::IncompatibleVersion, + std::format( + "cannot seed update store from non-SemVer version '{}'", + versionText)); + } + std::error_code error; + if (!std::filesystem::is_regular_file(source, error) || error) { + return Api::fail( + Api::ErrorCode::NotFound, + std::format( + "cannot seed update store: '{}' is not a regular file", + source.string())); + } + + const auto publishedFile = store.versionPath(*version) / filename; + const bool versionDirectoryExists = + std::filesystem::exists(store.versionPath(*version), error); + if (error) { + return Api::fail(Api::ErrorCode::PermissionDenied, + std::format("cannot inspect update store seed: {}", + error.message())); + } + if (versionDirectoryExists) { + if (!std::filesystem::is_regular_file(publishedFile, error) || + error) { + return Api::fail( + Api::ErrorCode::ParseError, + std::format("update store version '{}' is missing '{}'", + version->to_string(), filename.string())); + } + } else { + auto staging = store.prepare(*version); + if (!staging) { + return Api::fail(Api::ErrorCode::UnknownError, + staging.error().message()); + } + std::filesystem::copy_file( + source, *staging / filename, + std::filesystem::copy_options::overwrite_existing, error); + if (error) { + std::error_code ignored; + std::filesystem::remove_all(*staging, ignored); + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format( + "cannot copy initial version into update store: {}", + error.message())); + } + if (auto published = store.publish(*version, *staging); + !published) { + std::error_code ignored; + std::filesystem::remove_all(*staging, ignored); + return Api::fail(Api::ErrorCode::UnknownError, + published.error().message()); + } + } + if (auto activated = store.activate(*version); !activated) { + return Api::fail(Api::ErrorCode::UnknownError, + activated.error().message()); + } + if (auto committed = store.commit(); !committed) { + std::ignore = store.rollback(); + return Api::fail(Api::ErrorCode::UnknownError, + committed.error().message()); + } + return {}; + } + + Api::Result + UpdateService::Impl::seedCoreStore(Void::Update::VersionStore& store) + { + const auto version = + hooks_.coreVersion ? hooks_.coreVersion() : options_.runtimeVersion; + return seedStoreFromFile(store, version, options_.currentCore, + coreFilename()); + } + + Api::Result UpdateService::Impl::discoverCoreRollback( + Void::Update::VersionStore& store) + { + auto current = store.currentVersion(); + if (!current) { + return Api::fail(Api::ErrorCode::UnknownError, + current.error().message()); + } + std::vector excluded; + if (*current) { + excluded.push_back(**current); + } + auto rollback = newestHealthyRollback(store, excluded, coreFilename()); + if (!rollback) { + return Api::fail( + Api::ErrorCode::UnknownError, + std::format("cannot discover Core rollback version: {}", + rollback.error().message())); + } + std::lock_guard lock(mutex_); + coreRollbackVersion_ = + *rollback ? (*rollback)->to_string() : std::string{}; + return {}; + } + + Api::Result UpdateService::Impl::discoverRuntimeRollback() + { + const auto clearRollback = [this] { + std::lock_guard lock(mutex_); + runtimeRollbackVersion_.clear(); + }; + const auto versionsRoot = options_.installRoot / "versions"; + std::error_code error; + const auto status = + std::filesystem::symlink_status(versionsRoot, error); + if (error == std::errc::no_such_file_or_directory || + status.type() == std::filesystem::file_type::not_found) { + clearRollback(); + return {}; + } + if (error || !std::filesystem::is_directory(status) || + std::filesystem::is_symlink(status)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + "runtime VersionStore versions root is not a real directory"); + } + for (const auto& metadata : {options_.installRoot / ".update.lock", + options_.installRoot / "health.log"}) { + error.clear(); + const auto metadataStatus = + std::filesystem::symlink_status(metadata, error); + if (error == std::errc::no_such_file_or_directory || + metadataStatus.type() == + std::filesystem::file_type::not_found) { + clearRollback(); + return {}; + } + if (error || !std::filesystem::is_regular_file(metadataStatus) || + std::filesystem::is_symlink(metadataStatus)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("runtime VersionStore metadata '{}' is unsafe", + metadata.string())); + } + std::ifstream readable{metadata, std::ios::binary}; + if (!readable) { + Void::Log::warn( + "UpdateService", + "runtime rollback metadata '{}' is not readable; " + "rollback discovery is disabled until a privileged updater " + "migrates it", + metadata.string()); + clearRollback(); + return {}; + } + } + + Void::Update::VersionStore store(options_.installRoot); + auto current = store.currentVersion(); + if (!current) { + return Api::fail( + Api::ErrorCode::UnknownError, + std::format("cannot inspect the runtime VersionStore: {}", + current.error().message())); + } + std::vector excluded; + if (*current) { + excluded.push_back(**current); + } + if (auto running = parseVersion(options_.runtimeVersion); running) { + excluded.push_back(*running); + } + const auto executable = options_.runningExecutable.filename().empty() + ? std::filesystem::path{"echoiond"} + : options_.runningExecutable.filename(); + auto rollback = newestHealthyRollback( + store, excluded, std::filesystem::path{"bin"} / executable); + if (!rollback) { + return Api::fail( + Api::ErrorCode::UnknownError, + std::format("cannot discover runtime rollback version: {}", + rollback.error().message())); + } + std::lock_guard lock(mutex_); + runtimeRollbackVersion_ = + *rollback ? (*rollback)->to_string() : std::string{}; + return {}; + } + + Api::Result UpdateService::Impl::reconcileAndDiscoverManagedPlugins() + { + std::unordered_map rollbacks; + const auto managed = options_.stateDirectory / "plugins" / ".managed"; + std::error_code error; + const auto status = std::filesystem::symlink_status(managed, error); + if (error == std::errc::no_such_file_or_directory || + status.type() == std::filesystem::file_type::not_found) { + auto inventory = queryPluginInventory(); + std::lock_guard lock(mutex_); + pluginInventory_ = std::move(inventory); + pluginRollbackVersions_.clear(); + return {}; + } + if (error || !std::filesystem::is_directory(status) || + std::filesystem::is_symlink(status)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + "managed plugin update root is not a real directory"); + } + + std::filesystem::directory_iterator iterator{managed, error}; + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot enumerate managed plugin stores: {}", + error.message())); + } + for (const std::filesystem::directory_iterator end; iterator != end; + iterator.increment(error)) { + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot enumerate managed plugin stores: {}", + error.message())); + } + const auto id = iterator->path().filename().string(); + const auto entryStatus = iterator->symlink_status(error); + if (error || !safeIdentifier(id) || + !std::filesystem::is_directory(entryStatus) || + std::filesystem::is_symlink(entryStatus)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("managed plugin update store '{}' is unsafe", + id)); + } + + Void::Update::VersionStore store(iterator->path()); + if (auto initialized = store.initialize(); !initialized) { + return Api::fail(Api::ErrorCode::UnknownError, + initialized.error().message()); + } + if (auto reconciled = store.reconcile(); !reconciled) { + return Api::fail(Api::ErrorCode::UnknownError, + reconciled.error().message()); + } + pruneStoreBestEffort(store, std::format("plugin '{}'", id)); + auto current = store.currentVersion(); + if (!current) { + return Api::fail(Api::ErrorCode::UnknownError, + current.error().message()); + } + std::vector excluded; + if (*current) { + excluded.push_back(**current); + } + auto rollback = newestHealthyRollback( + store, excluded, std::filesystem::path{id + ".so"}); + if (!rollback) { + return Api::fail( + Api::ErrorCode::UnknownError, + std::format( + "cannot discover rollback version for plugin '{}': {}", + id, rollback.error().message())); + } + if (*rollback) { + rollbacks.emplace(id, (*rollback)->to_string()); + } + } + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot enumerate managed plugin stores: {}", + error.message())); + } + + auto inventory = queryPluginInventory(); + std::lock_guard lock(mutex_); + pluginInventory_ = std::move(inventory); + pluginRollbackVersions_ = std::move(rollbacks); + return {}; + } + + Api::Result UpdateService::Impl::publishArtifact( + Void::Update::VersionStore& store, const Void::Semver::Version& version, + const std::filesystem::path& artifact, + const std::filesystem::path& filename, std::string_view expectedSha256) + { + const auto destination = store.versionPath(version) / filename; + std::error_code error; + const bool published = + std::filesystem::exists(store.versionPath(version), error); + if (error) { + return Api::fail(Api::ErrorCode::PermissionDenied, + std::format("cannot inspect published update: {}", + error.message())); + } + if (published) { + if (!std::filesystem::is_regular_file(destination, error) || + error) { + return Api::fail(Api::ErrorCode::ParseError, + "published update version is incomplete"); + } + auto digest = Void::Crypto::sha256File(destination); + if (!digest || !sameHex(Void::Encoding::Hex::encode(*digest), + expectedSha256)) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "published update version does not match the " + "signed artifact"); + } + return destination; + } + + auto staging = store.prepare(version); + if (!staging) { + return Api::fail(Api::ErrorCode::AlreadyExists, + staging.error().message()); + } + std::filesystem::copy_file( + artifact, *staging / filename, + std::filesystem::copy_options::overwrite_existing, error); + if (error) { + std::error_code ignored; + std::filesystem::remove_all(*staging, ignored); + return Api::fail(Api::ErrorCode::PermissionDenied, + std::format("cannot stage update artifact: {}", + error.message())); + } + if (auto result = store.publish(version, *staging); !result) { + std::error_code ignored; + std::filesystem::remove_all(*staging, ignored); + return Api::fail(Api::ErrorCode::UnknownError, + result.error().message()); + } + return destination; + } + + void UpdateService::Impl::processPendingHostActions() + { + PendingCoreAction action; + { + std::lock_guard lock(mutex_); + if (!pendingCoreAction_ || pendingCoreAction_->processing) { + return; + } + pendingCoreAction_->processing = true; + action = *pendingCoreAction_; + coreState_ = "activating"; + coreMessage_ = + action.action == "rollback" + ? "Activating the selected previous Core version" + : "Activating the staged Core outside the RPC callback"; + } + + Api::Result result = + hooks_.replaceCore + ? invokeHostHook( + "Core replacement hook", + [&] { return hooks_.replaceCore(action.path); }) + : Api::fail(Api::ErrorCode::NotSupported, + "this host cannot replace Core"); + Void::Update::VersionStore store(updateDirectory_ / "components" / + "core"); + if (result && action.activationPending) { + if (auto committed = store.commit(); !committed) { + result = Api::fail(Api::ErrorCode::UnknownError, + std::format("Core loaded but its activation " + "could not be committed: {}", + committed.error().message())); + if (auto rolledBack = store.rollback(); !rolledBack) { + result.error().message += + std::format("; store rollback also failed: {}", + rolledBack.error().message()); + } else if (action.previousVersion && hooks_.replaceCore) { + const auto restored = + invokeHostHook("Core restoration hook", [&] { + return hooks_.replaceCore( + store.versionPath(*action.previousVersion) / + coreFilename()); + }); + if (!restored) { + result.error().message += std::format( + "; restoring the previous Core also failed: {}", + restored.error().message); + } + } + } + } else if (!result && action.activationPending) { + if (auto rolledBack = store.rollback(); !rolledBack) { + result.error().message += + std::format("; store rollback also failed: {}", + rolledBack.error().message()); + } + } + pruneStoreBestEffort(store, "Core"); + + const auto now = std::chrono::system_clock::now(); + const auto message = result ? std::string{} : result.error().message; + { + std::lock_guard lock(mutex_); + pendingCoreAction_.reset(); + if (result) { + coreRollbackVersion_ = action.previousVersion + ? action.previousVersion->to_string() + : std::string{}; + coreState_ = "healthy"; + coreMessage_ = + action.action == "rollback" + ? "Previous Core version activated" + : "Core activated without restarting the daemon"; + if (!action.candidateId.empty() && coreCandidate_ && + coreCandidate_->id == action.candidateId) { + coreCandidate_.reset(); + } + } else { + if (coreCandidate_ && + coreCandidate_->id == action.candidateId) { + coreCandidate_->applying = false; + if (!coreCandidate_->signedFeed) { + coreCandidate_->unsignedAuthorized = false; + coreCandidate_->confirmationToken.clear(); + coreCandidate_->confirmationExpiresAt = {}; + } + } + coreState_ = "failed"; + coreMessage_ = message; + } + history_.push_back( + {.timestamp = now, + .component = "core", + .pluginId = {}, + .action = action.action, + .version = action.version, + .result = result ? "success" : "failed", + .message = message, + .actor = action.action == "reconcile" ? "host" : "admin"}); + if (history_.size() > 100) { + history_.erase(history_.begin()); + } + } + } + + Api::Result UpdateService::Impl::statusJson() const + { + const auto coreVersion = + hooks_.coreVersion ? hooks_.coreVersion() : options_.runtimeVersion; + std::lock_guard lock(mutex_); + auto candidateValue = [](const CandidateRecord& record, + std::string_view current) { + Value value = Void::Json::object(); + add(value, "id", Value{record.id}); + add(value, "version", Value{record.release.version.to_string()}); + add(value, "channel", Value{record.release.channel}); + add(value, "source", Value{record.source}); + add(value, "signed", Value{record.signedFeed}); + add(value, "compatible", Value{true}); + const auto installed = parseVersion(current); + add(value, "downgrade", + Value{installed && record.release.version < *installed}); + add(value, "requiresRestart", + Value{record.release.component == "runtime" || + record.release.component == "executable"}); + if (!record.release.cohort.empty()) { + add(value, "cohort", Value{record.release.cohort}); + } + return value; + }; + + auto componentValue = + [&](std::string_view component, std::string_view current, + std::string_view state, std::string_view message, + std::string_view source, std::string_view channel, + const std::optional& candidate, + std::string_view rollbackVersion) { + Value value = Void::Json::object(); + add(value, "component", Value{std::string(component)}); + add(value, "currentVersion", Value{std::string(current)}); + add(value, "state", Value{std::string(state)}); + add(value, "source", Value{std::string(source)}); + add(value, "channel", Value{std::string(channel)}); + if (!message.empty()) { + add(value, "message", Value{std::string(message)}); + } + if (candidate) { + add(value, "candidate", + candidateValue(*candidate, current)); + } + if (!rollbackVersion.empty()) { + add(value, "rollbackVersion", + Value{std::string(rollbackVersion)}); + } + return value; + }; + + Value root = Void::Json::object(); + add(root, "enabled", Value{config_.enabled}); + add(root, "checking", Value{checking_}); + if (lastCheck_ != std::chrono::system_clock::time_point{}) { + add(root, "lastCheckAt", + Value{static_cast(unixMilliseconds(lastCheck_))}); + } + if (nextCheck_ != std::chrono::system_clock::time_point{}) { + add(root, "nextCheckAt", + Value{static_cast(unixMilliseconds(nextCheck_))}); + } + if (!message_.empty()) { + add(root, "message", Value{message_}); + } + + Value components = Void::Json::object(); + add(components, "runtime", + componentValue("runtime", options_.runtimeVersion, runtimeState_, + runtimeMessage_, config_.runtime.source, + config_.runtime.channel, runtimeCandidate_, + runtimeRollbackVersion_)); + add(components, "core", + componentValue("core", coreVersion, coreState_, coreMessage_, + config_.core.source, config_.core.channel, + coreCandidate_, coreRollbackVersion_)); + std::optional anyPlugin; + if (!pluginCandidates_.empty()) { + anyPlugin = pluginCandidates_.begin()->second; + } + add(components, "plugins", + componentValue("plugins", "", pluginsState_, pluginsMessage_, + config_.plugins.source, config_.plugins.channel, + anyPlugin, "")); + add(root, "components", std::move(components)); + + Value plugins = Void::Json::array(); + for (const auto& plugin : pluginInventory_) { + Value item = Void::Json::object(); + add(item, "id", Value{plugin.id}); + add(item, "name", + Value{plugin.name.empty() ? plugin.id : plugin.name}); + add(item, "managed", Value{plugin.managed}); + add(item, "currentVersion", Value{plugin.version}); + const auto override = config_.plugins.overrides.find(plugin.id); + const auto source = override == config_.plugins.overrides.end() + ? config_.plugins.source + : override->second.source; + const auto channel = override == config_.plugins.overrides.end() + ? config_.plugins.channel + : override->second.channel; + add(item, "source", Value{source}); + add(item, "channel", Value{channel}); + const auto candidate = pluginCandidates_.find(plugin.id); + add(item, "state", + Value{candidate == pluginCandidates_.end() + ? std::string{"current"} + : std::string{"available"}}); + if (candidate != pluginCandidates_.end()) { + add(item, "candidate", + candidateValue(candidate->second, plugin.version)); + } + if (const auto previous = pluginRollbackVersions_.find(plugin.id); + previous != pluginRollbackVersions_.end()) { + add(item, "rollbackVersion", Value{previous->second}); + } + plugins.as_array().push_back(std::move(item)); + } + add(root, "plugins", std::move(plugins)); + + Value history = Void::Json::array(); + for (const auto& entry : history_) { + Value item = Void::Json::object(); + add(item, "timestamp", + Value{ + static_cast(unixMilliseconds(entry.timestamp))}); + if (!entry.component.empty()) { + add(item, "component", Value{entry.component}); + } + if (!entry.pluginId.empty()) { + add(item, "pluginId", Value{entry.pluginId}); + } + if (!entry.action.empty()) { + add(item, "action", Value{entry.action}); + } + if (!entry.version.empty()) { + add(item, "version", Value{entry.version}); + } + if (!entry.result.empty()) { + add(item, "result", Value{entry.result}); + } + if (!entry.message.empty()) { + add(item, "message", Value{entry.message}); + } + if (!entry.actor.empty()) { + add(item, "actor", Value{entry.actor}); + } + history.as_array().push_back(std::move(item)); + } + add(root, "history", std::move(history)); + return Void::Json::serialize(root, {.pretty = true}); + } + + Api::Result UpdateService::Impl::checkNow(bool manual) + { + Api::UpdatesConfig config; + std::map sequences; + { + std::lock_guard lock(mutex_); + if (checking_) { + return Api::fail(Api::ErrorCode::AlreadyExists, + "an update check is already running"); + } + checking_ = true; + message_ = "Checking update feeds"; + config = config_; + sequences = sequences_; + } + + struct CheckGuard { + Impl& service; + bool active = true; + void finish() + { + if (!active) { + return; + } + std::lock_guard lock(service.mutex_); + service.checking_ = false; + service.lastCheck_ = std::chrono::system_clock::now(); + service.nextCheck_ = + service.lastCheck_ + service.nextDelayLocked(); + service.condition_.notify_all(); + active = false; + } + ~CheckGuard() { finish(); } + } guard{*this}; + + const auto inventory = queryPluginInventory(); + std::unordered_map feeds; + std::unordered_map feedErrors; + std::vector sourceIds; + auto addSource = [&](std::string_view source) { + if (std::ranges::find(sourceIds, source) == sourceIds.end()) { + sourceIds.emplace_back(source); + } + }; + if (config.runtime.enabled) { + addSource(config.runtime.source); + } + if (config.core.enabled) { + addSource(config.core.source); + } + if (config.plugins.enabled) { + addSource(config.plugins.source); + for (const auto& [id, policy] : config.plugins.overrides) { + (void)id; + addSource(policy.source); + } + } + + for (const auto& id : sourceIds) { + const auto source = config.sources.find(id); + if (source == config.sources.end()) { + feedErrors.emplace(id, "source is not configured"); + continue; + } + const auto floorKey = replayFloorKey(id, source->second); + std::optional minimum; + auto saved = sequences.find(floorKey); + if (saved == sequences.end()) { + // Migrate the pre-source-identity state format on the first + // successful check. The legacy floor remains fail-closed for + // the source identity configured at startup. + saved = sequences.find(id); + } + if (saved != sequences.end()) { + // Routine polling must accept the same immutable feed again + // while still rejecting a sequence rollback. Void's replay + // floor is exclusive, so use the predecessor to admit equality. + if (saved->second > 0) { + minimum = saved->second - 1; + } + } + auto fetched = fetchFeed(id, source->second, minimum); + if (!fetched) { + feedErrors.emplace(id, fetched.error().message); + continue; + } + const auto existing = sequences.find(floorKey); + const auto previous = existing == sequences.end() + ? std::uint64_t{} + : existing->second; + sequences[floorKey] = std::max(previous, fetched->feed.sequence); + if (floorKey != id) { + sequences.erase(id); + } + feeds.emplace(id, std::move(*fetched)); + } + + const auto installedEnvironment = environment(); + auto select = + [&](std::string_view sourceId, std::string_view component, + std::string_view alternateComponent, + std::string_view artifactId, std::string_view channel, + std::string_view current) -> std::optional { + const auto feed = feeds.find(std::string(sourceId)); + if (feed == feeds.end()) { + return std::nullopt; + } + Void::Update::SelectionRequest request; + request.component = std::string(component); + request.artifactId = std::string(artifactId); + request.channel = std::string(channel); + request.environment = installedEnvironment; + request.currentVersion = parseVersion(current); + request.allowDowngrade = true; + auto release = + Void::Update::selectRelease(feed->second.feed, request); + if (!release && !alternateComponent.empty()) { + request.component = std::string(alternateComponent); + release = + Void::Update::selectRelease(feed->second.feed, request); + } + if (!release) { + return std::nullopt; + } + const auto id = candidateId(sourceId, *release); + return CandidateRecord{.release = std::move(*release), + .id = id, + .source = std::string(sourceId), + .signedFeed = feed->second.signedFeed, + .discoveredAt = + std::chrono::system_clock::now(), + .confirmationToken = {}, + .confirmationExpiresAt = {}, + .unsignedAuthorized = false, + .applying = false}; + }; + + const auto coreVersion = + hooks_.coreVersion ? hooks_.coreVersion() : options_.runtimeVersion; + auto runtimeCandidate = + config.runtime.enabled + ? select(config.runtime.source, "runtime", "executable", "", + config.runtime.channel, options_.runtimeVersion) + : std::nullopt; + auto coreCandidate = config.core.enabled + ? select(config.core.source, "core", "", "", + config.core.channel, coreVersion) + : std::nullopt; + std::unordered_map pluginCandidates; + if (config.plugins.enabled) { + for (const auto& plugin : inventory) { + if (config.plugins.managedOnly && !plugin.managed) { + continue; + } + const auto override = config.plugins.overrides.find(plugin.id); + const auto& source = override == config.plugins.overrides.end() + ? config.plugins.source + : override->second.source; + const auto& channel = override == config.plugins.overrides.end() + ? config.plugins.channel + : override->second.channel; + if (auto candidate = + select(source, "plugin", "plugins", plugin.id, channel, + plugin.version)) { + pluginCandidates.emplace(plugin.id, std::move(*candidate)); + } + } + } + if (auto saved = Void::FileSystem::atomic_write( + updateDirectory_ / "sequences.json", + Void::Json::serialize(Void::Json::to_json(sequences), + {.pretty = true})); + !saved) { + const auto message = std::format( + "Update feeds were verified, but the replay floor could not be " + "persisted: {}", + saved.error().message()); + { + std::lock_guard lock(mutex_); + message_ = message; + history_.push_back( + {.timestamp = std::chrono::system_clock::now(), + .component = {}, + .pluginId = {}, + .action = "check", + .version = {}, + .result = "failed", + .message = message, + .actor = manual ? "admin" : "scheduler"}); + if (history_.size() > 100) { + history_.erase(history_.begin()); + } + } + return Api::fail(Api::ErrorCode::PermissionDenied, message); + } + + { + std::lock_guard lock(mutex_); + runtimeCandidate_ = std::move(runtimeCandidate); + coreCandidate_ = std::move(coreCandidate); + pluginCandidates_ = std::move(pluginCandidates); + pluginInventory_ = inventory; + sequences_ = std::move(sequences); + runtimeState_ = runtimeCandidate_ ? "available" : "current"; + coreState_ = coreCandidate_ ? "available" : "current"; + pluginsState_ = pluginCandidates_.empty() ? "current" : "available"; + auto sourceMessage = [&](std::string_view id) { + const auto error = feedErrors.find(std::string(id)); + return error == feedErrors.end() ? std::string{} + : error->second; + }; + runtimeMessage_ = sourceMessage(config.runtime.source); + coreMessage_ = sourceMessage(config.core.source); + pluginsMessage_ = sourceMessage(config.plugins.source); + if (feedErrors.empty()) { + message_ = "Update check completed"; + } else { + message_ = std::format( + "Update check completed with {} source error(s)", + feedErrors.size()); + } + history_.push_back( + {.timestamp = std::chrono::system_clock::now(), + .component = {}, + .pluginId = {}, + .action = "check", + .version = {}, + .result = feedErrors.empty() ? "success" : "partial", + .message = message_, + .actor = manual ? "admin" : "scheduler"}); + if (history_.size() > 100) { + history_.erase(history_.begin()); + } + } + // Auto-activation is intentionally attempted only for signed upgrades. + // Unsigned candidates always require the per-candidate confirmation + // RPC. + if (!manual) { + std::vector> + automatic; + { + std::lock_guard lock(mutex_); + auto collect = + [&](std::string component, std::string plugin, + const std::optional& candidate, + bool enabled) { + if (!enabled || !candidate || !candidate->signedFeed) { + return; + } + const auto current = + component == "runtime" ? options_.runtimeVersion + : component == "core" + ? coreVersion + : [&] { + const auto found = std::ranges::find( + pluginInventory_, plugin, + &PluginInventoryEntry::id); + return found == pluginInventory_.end() + ? std::string{} + : found->version; + }(); + const auto installed = parseVersion(current); + if (installed && + candidate->release.version <= *installed) { + return; + } + automatic.emplace_back(std::move(component), + std::move(plugin), + candidate->id); + }; + collect("runtime", "", runtimeCandidate_, + config.runtime.autoApply); + collect("core", "", coreCandidate_, config.core.autoApply); + for (const auto& [id, candidate] : pluginCandidates_) { + const auto override = config.plugins.overrides.find(id); + const bool autoApply = + override == config.plugins.overrides.end() + ? config.plugins.autoApply + : override->second.autoApply; + collect("plugins", id, std::optional{candidate}, autoApply); + } + } + for (const auto& [component, plugin, id] : automatic) { + Value request = Void::Json::object(); + add(request, "component", Value{component}); + if (!plugin.empty()) { + add(request, "pluginId", Value{plugin}); + } + add(request, "candidateId", Value{id}); + if (auto result = apply(Void::Json::serialize(request)); + !result) { + Void::Log::warn("UpdateService", "auto-apply {} failed: {}", + component, result.error().message); + } + } + } + + guard.finish(); + return statusJson(); + } + + void UpdateService::Impl::recordHistory(HistoryEntry entry) + { + std::lock_guard lock(mutex_); + history_.push_back(std::move(entry)); + if (history_.size() > 100) { + history_.erase(history_.begin()); + } + } + + Api::Result + UpdateService::Impl::downloadArtifact(const CandidateRecord& candidate) + { + if (candidate.release.size == 0 || + candidate.release.size > kMaximumArtifactBytes) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "candidate has an invalid artifact size"); + } + const auto source = [&]() -> std::optional { + std::lock_guard lock(mutex_); + const auto found = config_.sources.find(candidate.source); + return found == config_.sources.end() + ? std::nullopt + : std::optional{found->second}; + }(); + if (!source) { + return Api::fail(Api::ErrorCode::NotFound, + "candidate source is no longer configured"); + } + auto bytes = fetchBytes(candidate.release.url, *source, + candidate.release.size + 1, + sourceUrl(candidate.source, *source)); + if (!bytes) { + return std::unexpected(bytes.error()); + } + if (bytes->size() != candidate.release.size) { + return Api::fail( + Api::ErrorCode::ParseError, + std::format("artifact size mismatch: expected {}, received {}", + candidate.release.size, bytes->size())); + } + auto digest = Void::Crypto::sha256(*bytes); + if (!digest) { + return Api::fail(Api::ErrorCode::UnknownError, + digest.error().message()); + } + if (!sameHex(Void::Encoding::Hex::encode(*digest), + candidate.release.sha256)) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "artifact SHA-256 does not match the signed feed"); + } + const auto destination = + updateDirectory_ / "downloads" / (candidate.id + ".artifact"); + if (auto written = Void::FileSystem::atomic_write(destination, *bytes); + !written) { + return Api::fail(Api::ErrorCode::PermissionDenied, + std::format("cannot store downloaded artifact: {}", + written.error().message())); + } + return destination; + } + + Api::Result + UpdateService::Impl::activateCore(const CandidateRecord& candidate) + { + if (!hooks_.replaceCore) { + return Api::fail(Api::ErrorCode::NotSupported, + "this host cannot replace Core"); + } + if (candidate.release.packageType != "shared-library" && + candidate.release.packageType != "file") { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Core updates require packageType shared-library"); + } + { + std::lock_guard lock(mutex_); + if (pendingCoreAction_) { + return Api::fail(Api::ErrorCode::AlreadyExists, + "another Core host action is pending"); + } + } + auto artifact = downloadArtifact(candidate); + if (!artifact) { + return std::unexpected(artifact.error()); + } + Void::Update::VersionStore store(updateDirectory_ / "components" / + "core"); + if (auto initialized = store.initialize(); !initialized) { + return Api::fail(Api::ErrorCode::UnknownError, + initialized.error().message()); + } + if (auto seeded = seedCoreStore(store); !seeded) { + return seeded; + } + auto previous = store.currentVersion(); + if (!previous) { + return Api::fail(Api::ErrorCode::UnknownError, + previous.error().message()); + } + const auto filename = coreFilename(); + auto corePath = + publishArtifact(store, candidate.release.version, *artifact, + filename, candidate.release.sha256); + if (!corePath) { + return std::unexpected(corePath.error()); + } + if (auto activated = store.activate(candidate.release.version); + !activated) { + return Api::fail(Api::ErrorCode::UnknownError, + activated.error().message()); + } + { + std::lock_guard lock(mutex_); + pendingCoreAction_ = PendingCoreAction{ + .action = "apply", + .version = candidate.release.version.to_string(), + .candidateId = candidate.id, + .path = *corePath, + .previousVersion = *previous}; + coreState_ = "pending-host-action"; + coreMessage_ = + "Core is staged and will activate after this RPC returns"; + } + return {}; + } + + Api::Result + UpdateService::Impl::activatePlugin(std::string_view pluginId, + const CandidateRecord& candidate) + { + if (!hooks_.managePlugins) { + return Api::fail(Api::ErrorCode::NotSupported, + "this Core cannot manage extension plugins"); + } + if (!safeIdentifier(pluginId) || + candidate.release.artifactId != pluginId) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "candidate does not belong to the requested plugin"); + } + if (candidate.release.packageType != "shared-library" && + candidate.release.packageType != "file") { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "plugin updates require packageType shared-library"); + } + auto artifact = downloadArtifact(candidate); + if (!artifact) { + return std::unexpected(artifact.error()); + } + Void::Update::VersionStore store(options_.stateDirectory / "plugins" / + ".managed" / std::string(pluginId)); + if (auto initialized = store.initialize(); !initialized) { + return Api::fail(Api::ErrorCode::UnknownError, + initialized.error().message()); + } + const auto filename = std::string(pluginId) + ".so"; + PluginInventoryEntry installed; + { + std::lock_guard lock(mutex_); + const auto found = std::ranges::find(pluginInventory_, pluginId, + &PluginInventoryEntry::id); + if (found != pluginInventory_.end()) { + installed = *found; + } + } + if (auto seeded = seedStoreFromFile(store, installed.version, + installed.path, filename); + !seeded) { + return Api::fail( + seeded.error().code, + std::format("cannot preserve plugin '{}' for rollback: {}", + pluginId, seeded.error().message)); + } + auto previous = store.currentVersion(); + if (!previous) { + return Api::fail(Api::ErrorCode::UnknownError, + previous.error().message()); + } + auto pluginPath = + publishArtifact(store, candidate.release.version, *artifact, + filename, candidate.release.sha256); + if (!pluginPath) { + return std::unexpected(pluginPath.error()); + } + if (auto activated = store.activate(candidate.release.version); + !activated) { + return Api::fail(Api::ErrorCode::UnknownError, + activated.error().message()); + } + Value request = Void::Json::object(); + add(request, "schemaVersion", Value{1}); + add(request, "action", Value{"replace"}); + add(request, "pluginId", Value{std::string(pluginId)}); + add(request, "version", Value{candidate.release.version.to_string()}); + add(request, "path", Value{pluginPath->string()}); + auto replaced = + invokeHostHook("plugin replacement hook", [&] { + return hooks_.managePlugins(Void::Json::serialize(request)); + }); + if (!replaced) { + auto failure = replaced.error(); + if (auto rolledBack = store.rollback(); !rolledBack) { + failure.message += + std::format("; store rollback also failed: {}", + rolledBack.error().message()); + } + pruneStoreBestEffort(store, std::format("plugin '{}'", pluginId)); + return std::unexpected(std::move(failure)); + } + if (auto committed = store.commit(); !committed) { + std::string message = std::format( + "plugin loaded but its activation could not be committed: {}", + committed.error().message()); + if (auto rolledBack = store.rollback(); !rolledBack) { + message += std::format("; store rollback also failed: {}", + rolledBack.error().message()); + } else if (previous->has_value()) { + Value restore = Void::Json::object(); + add(restore, "schemaVersion", Value{1}); + add(restore, "action", Value{"replace"}); + add(restore, "pluginId", Value{std::string(pluginId)}); + add(restore, "version", Value{previous->value().to_string()}); + add(restore, "path", + Value{(store.versionPath(previous->value()) / filename) + .string()}); + auto restored = + invokeHostHook("plugin restoration hook", [&] { + return hooks_.managePlugins( + Void::Json::serialize(restore)); + }); + if (!restored) { + message += std::format( + "; restoring the previous plugin also failed: {}", + restored.error().message); + } + } + pruneStoreBestEffort(store, std::format("plugin '{}'", pluginId)); + return Api::fail(Api::ErrorCode::UnknownError, message); + } + pruneStoreBestEffort(store, std::format("plugin '{}'", pluginId)); + { + std::lock_guard lock(mutex_); + if (previous->has_value()) { + pluginRollbackVersions_[std::string(pluginId)] = + previous->value().to_string(); + } + pluginCandidates_.erase(std::string(pluginId)); + for (auto& plugin : pluginInventory_) { + if (plugin.id == pluginId) { + plugin.version = candidate.release.version.to_string(); + plugin.managed = true; + } + } + pluginsState_ = pluginCandidates_.empty() ? "healthy" : "available"; + pluginsMessage_ = "Managed plugin activated transactionally"; + } + return {}; + } + + Api::Result + UpdateService::Impl::activateRuntime(const CandidateRecord& candidate) + { + if (!hooks_.manageRuntime) { + return Api::fail( + Api::ErrorCode::NotSupported, + "this installation has no runtime activation helper"); + } + if (candidate.release.packageType != "tar.zst") { + return Api::fail(Api::ErrorCode::InvalidArgument, + "runtime updates require packageType tar.zst"); + } + if (candidate.release.releaseManifestSha256.empty()) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "runtime candidate has no release-manifest digest"); + } + auto artifact = downloadArtifact(candidate); + if (!artifact) { + return std::unexpected(artifact.error()); + } + + const auto extractionRoot = updateDirectory_ / "extract" / candidate.id; + const auto stagedRoot = updateDirectory_ / "staged"; + const auto staged = stagedRoot / candidate.id; + std::error_code error; + std::filesystem::remove_all(extractionRoot, error); + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot clear runtime extraction '{}': {}", + extractionRoot.string(), error.message())); + } + std::filesystem::remove_all(staged, error); + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot clear runtime staging '{}': {}", + staged.string(), error.message())); + } + std::filesystem::create_directories(extractionRoot, error); + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot create runtime extraction '{}': {}", + extractionRoot.string(), error.message())); + } + std::filesystem::create_directories(stagedRoot, error); + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot create runtime staging root '{}': {}", + stagedRoot.string(), error.message())); + } + Void::Archive::ExtractionOptions limits; + limits.maxEntries = 50'000; + limits.maxFileBytes = 1024ULL * 1024 * 1024; + limits.maxTotalBytes = kMaximumArtifactBytes; + auto extracted = + Void::Archive::extract(*artifact, extractionRoot, limits); + if (!extracted) { + return Api::fail(Api::ErrorCode::ParseError, + std::format("runtime archive rejected: {}", + extracted.error().message())); + } + std::vector roots; + for (const auto& entry : + std::filesystem::directory_iterator(extractionRoot, error)) { + if (!error) { + roots.push_back(entry.path()); + } + } + if (error || roots.size() != 1 || + !std::filesystem::is_directory(roots.front())) { + return Api::fail( + Api::ErrorCode::ParseError, + "runtime archive must contain exactly one top-level directory"); + } + std::filesystem::rename(roots.front(), staged, error); + if (error) { + return Api::fail(Api::ErrorCode::PermissionDenied, + std::format("cannot publish runtime staging: {}", + error.message())); + } + std::filesystem::remove_all(extractionRoot, error); + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot remove runtime extraction '{}': {}", + extractionRoot.string(), error.message())); + } + + const auto manifest = staged / "manifest.json"; + auto digest = Void::Crypto::sha256File(manifest); + if (!digest || !sameHex(Void::Encoding::Hex::encode(*digest), + candidate.release.releaseManifestSha256)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + "runtime manifest SHA-256 does not match the signed feed"); + } + Value operation = Void::Json::object(); + add(operation, "action", Value{"activate"}); + add(operation, "stagingId", Value{candidate.id}); + add(operation, "version", Value{candidate.release.version.to_string()}); + add(operation, "manifestSha256", + Value{candidate.release.releaseManifestSha256}); + std::uint32_t retainHealthyVersions{}; + { + std::lock_guard lock(mutex_); + retainHealthyVersions = config_.retainHealthyVersions; + } + add(operation, "retainHealthyVersions", + Value{static_cast(retainHealthyVersions)}); + auto managed = + invokeHostHook("runtime activation hook", [&] { + return hooks_.manageRuntime(Void::Json::serialize(operation)); + }); + if (!managed) { + return std::unexpected(managed.error()); + } + { + std::lock_guard lock(mutex_); + runtimeRollbackVersion_ = options_.runtimeVersion; + runtimeState_ = "pending-restart"; + runtimeMessage_ = + "Runtime activation is queued for the local helper"; + runtimeCandidate_.reset(); + } + return {}; + } + + Api::Result + UpdateService::Impl::apply(std::string_view requestJson) + { + auto request = parseJson(requestJson.empty() ? "{}" : requestJson); + if (!request) { + return std::unexpected(request.error()); + } + const auto component = stringField(*request, "component"); + const auto pluginId = stringField(*request, "pluginId"); + const auto id = stringField(*request, "candidateId"); + const auto requestedVersion = stringField(*request, "version"); + const auto confirmation = stringField(*request, "confirmationToken"); + CandidateRecord candidate; + { + std::lock_guard lock(mutex_); + CandidateRecord* selected = nullptr; + if (component == "runtime" && runtimeCandidate_) { + selected = &*runtimeCandidate_; + } else if (component == "core" && coreCandidate_) { + selected = &*coreCandidate_; + } else if ((component == "plugins" || component == "plugin") && + !pluginId.empty()) { + const auto found = pluginCandidates_.find(pluginId); + if (found != pluginCandidates_.end()) { + selected = &found->second; + } + } + if (!selected) { + return Api::fail( + Api::ErrorCode::NotFound, + "no candidate is available for the requested component"); + } + if (selected->applying) { + return Api::fail( + Api::ErrorCode::AlreadyExists, + "this update candidate is already being applied"); + } + if (id.empty() || selected->id != id || + (!requestedVersion.empty() && + selected->release.version.to_string() != requestedVersion)) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "candidate id/version no longer matches the checked feed"); + } + if (!selected->signedFeed) { + if (!selected->unsignedAuthorized && + (selected->confirmationToken.empty() || + selected->confirmationToken != confirmation || + std::chrono::system_clock::now() >= + selected->confirmationExpiresAt)) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "this unsigned candidate requires a " + "fresh, unexpired confirmation token"); + } + selected->unsignedAuthorized = true; + selected->confirmationToken.clear(); + selected->confirmationExpiresAt = {}; + } + selected->applying = true; + candidate = *selected; + if (component == "runtime") { + runtimeState_ = "staging"; + } else if (component == "core") { + coreState_ = "staging"; + } else { + pluginsState_ = "staging"; + } + } + + Api::Result activated; + if (component == "runtime") { + if (hooks_.playbackActive && hooks_.playbackActive()) { + { + std::lock_guard lock(mutex_); + if (runtimeCandidate_ && + runtimeCandidate_->id == candidate.id) { + runtimeCandidate_->applying = false; + } + runtimeState_ = "waiting-for-idle"; + runtimeMessage_ = + "Runtime update is queued until playback is idle"; + } + return statusJson(); + } + activated = activateRuntime(candidate); + } else if (component == "core") { + activated = activateCore(candidate); + } else if (component == "plugins" || component == "plugin") { + activated = activatePlugin(pluginId, candidate); + } else { + return Api::fail(Api::ErrorCode::InvalidArgument, + "component must be runtime, core, or plugins"); + } + + if (!activated) { + { + std::lock_guard lock(mutex_); + CandidateRecord* selected = nullptr; + if (component == "runtime" && runtimeCandidate_) { + selected = &*runtimeCandidate_; + } else if (component == "core" && coreCandidate_) { + selected = &*coreCandidate_; + } else if (component == "plugins" || component == "plugin") { + const auto found = pluginCandidates_.find(pluginId); + if (found != pluginCandidates_.end()) { + selected = &found->second; + } + } + if (selected && selected->id == candidate.id) { + selected->applying = false; + if (!selected->signedFeed) { + selected->unsignedAuthorized = false; + selected->confirmationToken.clear(); + selected->confirmationExpiresAt = {}; + } + } + if (component == "runtime") { + runtimeState_ = "failed"; + runtimeMessage_ = activated.error().message; + } else if (component == "core") { + coreState_ = "failed"; + coreMessage_ = activated.error().message; + } else { + pluginsState_ = "failed"; + pluginsMessage_ = activated.error().message; + } + } + recordHistory({.timestamp = std::chrono::system_clock::now(), + .component = component, + .pluginId = pluginId, + .action = "apply", + .version = candidate.release.version.to_string(), + .result = "failed", + .message = activated.error().message, + .actor = "admin"}); + return std::unexpected(activated.error()); + } + if (component == "core") { + // Final success/failure is recorded by processPendingHostActions(), + // after the Core-originated RPC has fully unwound. + return statusJson(); + } + recordHistory({.timestamp = std::chrono::system_clock::now(), + .component = component, + .pluginId = pluginId, + .action = "apply", + .version = candidate.release.version.to_string(), + .result = "success", + .message = {}, + .actor = "admin"}); + return statusJson(); + } + + Api::Result + UpdateService::Impl::confirmUnsigned(std::string_view requestJson) + { + auto request = parseJson(requestJson.empty() ? "{}" : requestJson); + if (!request) { + return std::unexpected(request.error()); + } + const auto component = stringField(*request, "component"); + const auto pluginId = stringField(*request, "pluginId"); + const auto id = stringField(*request, "candidateId"); + const auto version = stringField(*request, "version"); + const auto phrase = stringField(*request, "confirmation"); + std::string token; + { + std::lock_guard lock(mutex_); + CandidateRecord* candidate = nullptr; + if (component == "runtime" && runtimeCandidate_) { + candidate = &*runtimeCandidate_; + } else if (component == "core" && coreCandidate_) { + candidate = &*coreCandidate_; + } else if ((component == "plugins" || component == "plugin") && + !pluginId.empty()) { + const auto found = pluginCandidates_.find(pluginId); + if (found != pluginCandidates_.end()) { + candidate = &found->second; + } + } + if (!candidate || candidate->signedFeed || candidate->id != id || + candidate->release.version.to_string() != version) { + return Api::fail( + Api::ErrorCode::NotFound, + "unsigned candidate is missing or has changed"); + } + const auto source = config_.sources.find(candidate->source); + if (source == config_.sources.end() || + !source->second.allowUnsigned) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + "unsigned staging is no longer enabled for this source"); + } + if (phrase != std::format("UNSIGNED {}", version)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + "unsigned confirmation phrase does not match this version"); + } + const auto material = + std::format("{}|{}|{}|{}", id, + unixMilliseconds(std::chrono::system_clock::now()), + random_(), random_()); + auto digest = Void::Crypto::sha256(material); + if (!digest) { + return Api::fail(Api::ErrorCode::UnknownError, + digest.error().message()); + } + token = Void::Encoding::Hex::encode(*digest); + candidate->confirmationToken = token; + candidate->confirmationExpiresAt = + std::chrono::system_clock::now() + + kUnsignedConfirmationLifetime; + candidate->unsignedAuthorized = false; + } + Value response = Void::Json::object(); + add(response, "confirmationToken", Value{token}); + return Void::Json::serialize(response); + } + + Api::Result + UpdateService::Impl::rollback(std::string_view requestJson) + { + auto request = parseJson(requestJson.empty() ? "{}" : requestJson); + if (!request) { + return std::unexpected(request.error()); + } + const auto component = stringField(*request, "component"); + const auto pluginId = stringField(*request, "pluginId"); + const auto versionText = stringField(*request, "version"); + const auto version = parseVersion(versionText); + if (!version) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "rollback requires a semantic version"); + } + if (component != "runtime" && component != "core" && + component != "plugins" && component != "plugin") { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "rollback component must be runtime, core, or a plugin id"); + } + if ((component == "plugins" || component == "plugin") && + !safeIdentifier(pluginId)) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "rollback requires a safe managed plugin id"); + } + + std::string advertisedRollback; + { + std::lock_guard lock(mutex_); + if (component == "runtime") { + advertisedRollback = runtimeRollbackVersion_; + } else if (component == "core") { + advertisedRollback = coreRollbackVersion_; + } else if (component == "plugins" || component == "plugin") { + if (const auto found = pluginRollbackVersions_.find(pluginId); + found != pluginRollbackVersions_.end()) { + advertisedRollback = found->second; + } + } + } + if (advertisedRollback.empty() || advertisedRollback != versionText) { + return Api::fail( + Api::ErrorCode::NotFound, + "requested version is not the advertised healthy rollback"); + } + + Api::Result result; + std::string rollbackPreviousVersion; + if (component == "runtime") { + if (!hooks_.manageRuntime) { + return Api::fail(Api::ErrorCode::NotSupported, + "runtime rollback is unavailable"); + } + Value operation = Void::Json::object(); + add(operation, "action", Value{"rollback"}); + add(operation, "version", Value{versionText}); + std::uint32_t retainHealthyVersions{}; + { + std::lock_guard lock(mutex_); + retainHealthyVersions = config_.retainHealthyVersions; + } + add(operation, "retainHealthyVersions", + Value{static_cast(retainHealthyVersions)}); + auto managed = + invokeHostHook("runtime rollback hook", [&] { + return hooks_.manageRuntime( + Void::Json::serialize(operation)); + }); + if (!managed) { + result = std::unexpected(managed.error()); + } else { + result = {}; + } + } else if (component == "core") { + Void::Update::VersionStore store(updateDirectory_ / "components" / + "core"); + bool pending = false; + { + std::lock_guard lock(mutex_); + pending = pendingCoreAction_.has_value(); + } + if (pending) { + result = Api::fail(Api::ErrorCode::AlreadyExists, + "another Core host action is pending"); + } else if (!hooks_.replaceCore) { + result = Api::fail(Api::ErrorCode::NotSupported, + "Core rollback is unavailable"); + } else if (auto initialized = store.initialize(); !initialized) { + result = Api::fail(Api::ErrorCode::UnknownError, + initialized.error().message()); + } else if (auto seeded = seedCoreStore(store); !seeded) { + result = seeded; + } else if (auto activated = store.activate(*version); !activated) { + result = Api::fail(Api::ErrorCode::NotFound, + activated.error().message()); + } else { + auto activation = store.pendingActivation(); + if (!activation || !activation->has_value()) { + std::ignore = store.rollback(); + result = Api::fail( + Api::ErrorCode::UnknownError, + activation ? "Core activation journal is missing" + : activation.error().message()); + } else { + std::lock_guard lock(mutex_); + pendingCoreAction_ = PendingCoreAction{ + .action = "rollback", + .version = versionText, + .candidateId = {}, + .path = store.versionPath(*version) / coreFilename(), + .previousVersion = (*activation)->previousVersion}; + coreState_ = "pending-host-action"; + coreMessage_ = + "Core rollback will activate after this RPC returns"; + result = {}; + } + } + } else if ((component == "plugins" || component == "plugin") && + !pluginId.empty()) { + Void::Update::VersionStore store(options_.stateDirectory / + "plugins" / ".managed" / pluginId); + const auto pluginComponent = std::format("plugin '{}'", pluginId); + if (auto initialized = store.initialize(); !initialized) { + result = Api::fail(Api::ErrorCode::UnknownError, + initialized.error().message()); + } else if (auto activated = store.activate(*version); !activated) { + result = Api::fail(Api::ErrorCode::NotFound, + activated.error().message()); + } else { + result = [&]() -> Api::Result { + auto activation = store.pendingActivation(); + if (!activation || !activation->has_value()) { + std::ignore = store.rollback(); + pruneStoreBestEffort(store, pluginComponent); + return Api::fail( + Api::ErrorCode::UnknownError, + activation ? "plugin activation journal is missing" + : activation.error().message()); + } + if ((*activation)->previousVersion) { + rollbackPreviousVersion = + (*activation)->previousVersion->to_string(); + } + Value operation = Void::Json::object(); + add(operation, "schemaVersion", Value{1}); + add(operation, "action", Value{"replace"}); + add(operation, "pluginId", Value{pluginId}); + add(operation, "version", Value{versionText}); + add(operation, "path", + Value{(store.versionPath(*version) / (pluginId + ".so")) + .string()}); + auto managed = + hooks_.managePlugins + ? invokeHostHook( + "plugin rollback hook", + [&] { + return hooks_.managePlugins( + Void::Json::serialize(operation)); + }) + : Api::fail(Api::ErrorCode::NotSupported, + "plugin rollback is unavailable"); + if (!managed) { + auto failure = managed.error(); + if (auto rolledBack = store.rollback(); !rolledBack) { + failure.message += + std::format("; store rollback also failed: {}", + rolledBack.error().message()); + } + pruneStoreBestEffort(store, pluginComponent); + return std::unexpected(std::move(failure)); + } + auto committed = store.commit(); + if (committed) { + pruneStoreBestEffort(store, pluginComponent); + return {}; + } + + std::string message = std::format( + "plugin loaded but rollback could not be committed: {}", + committed.error().message()); + if (auto rolledBack = store.rollback(); !rolledBack) { + message += + std::format("; store rollback also failed: {}", + rolledBack.error().message()); + } else if ((*activation)->previousVersion && + hooks_.managePlugins) { + Value restore = Void::Json::object(); + add(restore, "schemaVersion", Value{1}); + add(restore, "action", Value{"replace"}); + add(restore, "pluginId", Value{pluginId}); + add(restore, "version", + Value{(*activation)->previousVersion->to_string()}); + add(restore, "path", + Value{(store.versionPath( + *(*activation)->previousVersion) / + (pluginId + ".so")) + .string()}); + auto restored = invokeHostHook( + "plugin restoration hook", [&] { + return hooks_.managePlugins( + Void::Json::serialize(restore)); + }); + if (!restored) { + message += std::format("; restoring the previous " + "plugin also failed: {}", + restored.error().message); + } + } + pruneStoreBestEffort(store, pluginComponent); + return Api::fail(Api::ErrorCode::UnknownError, message); + }(); + } + } else { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "rollback component must be runtime, core, or a plugin id"); + } + + if (!result) { + recordHistory({.timestamp = std::chrono::system_clock::now(), + .component = component, + .pluginId = pluginId, + .action = "rollback", + .version = versionText, + .result = "failed", + .message = result.error().message, + .actor = "admin"}); + return std::unexpected(result.error()); + } + if (component == "core") { + return statusJson(); + } + if (component == "plugins" || component == "plugin") { + std::lock_guard lock(mutex_); + for (auto& plugin : pluginInventory_) { + if (plugin.id == pluginId) { + plugin.version = versionText; + plugin.managed = true; + plugin.path = options_.stateDirectory / "plugins" / + ".managed" / pluginId / "versions" / + versionText / (pluginId + ".so"); + break; + } + } + if (!rollbackPreviousVersion.empty()) { + pluginRollbackVersions_[pluginId] = rollbackPreviousVersion; + } + pluginsState_ = "healthy"; + pluginsMessage_ = "Managed plugin rollback activated"; + } + recordHistory({.timestamp = std::chrono::system_clock::now(), + .component = component, + .pluginId = pluginId, + .action = "rollback", + .version = versionText, + .result = "success", + .message = {}, + .actor = "admin"}); + return statusJson(); + } + + UpdateService::UpdateService(Options options, Hooks hooks) + : impl_(std::make_unique(std::move(options), std::move(hooks))) + { + } + + UpdateService::~UpdateService() { stop(); } + UpdateService::UpdateService(UpdateService&&) noexcept = default; + UpdateService& UpdateService::operator=(UpdateService&&) noexcept = default; + + Api::Result UpdateService::start() { return impl_->start(); } + void UpdateService::stop() noexcept { impl_->stop(); } + void UpdateService::processPendingHostActions() + { + impl_->processPendingHostActions(); + } + + Api::Result + UpdateService::handle(const std::string& method, + const std::string& requestJson) + { + return impl_->handle(method, requestJson); + } + + Api::Result reconcileManagedPluginUpdates( + const std::filesystem::path& stateDirectory) + { + const auto managed = stateDirectory / "plugins" / ".managed"; + std::error_code error; + const auto status = std::filesystem::symlink_status(managed, error); + if (error == std::errc::no_such_file_or_directory || + status.type() == std::filesystem::file_type::not_found) { + return {}; + } + if (error || !std::filesystem::is_directory(status) || + std::filesystem::is_symlink(status)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + "managed plugin update root is not a real directory"); + } + for (const auto& entry : + std::filesystem::directory_iterator(managed, error)) { + if (error) { + break; + } + const auto id = entry.path().filename().string(); + const auto entryStatus = entry.symlink_status(error); + if (error || !safeIdentifier(id) || + !std::filesystem::is_directory(entryStatus) || + std::filesystem::is_symlink(entryStatus)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("managed plugin update store '{}' is unsafe", + id)); + } + Void::Update::VersionStore store(entry.path()); + if (auto initialized = store.initialize(); !initialized) { + return Api::fail(Api::ErrorCode::UnknownError, + initialized.error().message()); + } + auto pending = store.pendingActivation(); + if (!pending) { + return Api::fail(Api::ErrorCode::ParseError, + pending.error().message()); + } + if (pending->has_value()) { + if (auto reconciled = store.reconcile(); !reconciled) { + return Api::fail(Api::ErrorCode::UnknownError, + reconciled.error().message()); + } + } + } + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot enumerate managed plugin stores: {}", + error.message())); + } + return {}; + } +} // namespace Echoion::Standalone diff --git a/src/main.cpp b/src/main.cpp index 983cc14..b9e4c23 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -5,48 +5,47 @@ #include "echoion/standalone/ReleaseManifest.hpp" #include "echoion/standalone/RuntimePaths.hpp" #include "echoion/standalone/StandaloneClientInterface.hpp" +#include "echoion/standalone/UpdateBuildDefaults.hpp" +#include "echoion/standalone/UpdateService.hpp" #include +#include #include #include #include #include #include +#include #include +#include +#include +#include #include -#include -#include +#include +#include +#include #include #include #include #include #include -#include #include #include #include #include +#include #include +#ifndef _WIN32 +#include +#endif + namespace { - std::atomic g_stop{false}; std::atomic g_updateRequested{false}; - std::condition_variable g_cv; - std::mutex g_mu; - void onSignal(int) - { - g_stop = true; - g_cv.notify_all(); - } - - void requestUpdate() - { - g_updateRequested = true; - g_cv.notify_all(); - } + void requestUpdate() { g_updateRequested = true; } std::optional argumentValue(int argc, char** argv, std::string_view name) @@ -101,6 +100,255 @@ namespace return (error ? path : absolute).lexically_normal(); } + struct RuntimeHandoff { + std::filesystem::path manifestPath; + std::string state; + std::string version; + std::string previousVersion; + std::uint32_t retainHealthyVersions = 2; + }; + + [[nodiscard]] std::optional + retainHealthyVersions(const Void::Json::Value& object) + { + const auto* value = object.find("retainHealthyVersions"); + if (value == nullptr) { + return 2U; + } + if (!value->is_number()) { + return std::nullopt; + } + const double number = value->as_number(); + if (!std::isfinite(number) || std::trunc(number) != number || + number < 1.0 || number > 10.0) { + return std::nullopt; + } + return static_cast(number); + } + + [[nodiscard]] bool pathWithin(const std::filesystem::path& path, + const std::filesystem::path& root) + { + auto pathIterator = path.begin(); + for (auto rootIterator = root.begin(); rootIterator != root.end(); + ++rootIterator, ++pathIterator) { + if (pathIterator == path.end() || *pathIterator != *rootIterator) { + return false; + } + } + return true; + } + + std::optional + readRuntimeHandoff(const std::filesystem::path& handoff, + const std::filesystem::path& installationPrefix) + { + auto contents = Void::FileSystem::read_file(handoff); + if (!contents) { + return std::nullopt; + } + auto parsed = Void::Json::parse(*contents); + if (!parsed || !parsed->is_object()) { + return std::nullopt; + } + const auto stringField = [&parsed](std::string_view name) { + const auto* value = parsed->find(name); + return value && value->is_string() ? value->as_string() + : std::string{}; + }; + const auto manifestValue = stringField("manifestPath"); + const auto state = stringField("state"); + const auto version = stringField("version"); + const auto retention = retainHealthyVersions(*parsed); + if (manifestValue.empty() || state.empty() || version.empty() || + !retention.has_value()) { + return std::nullopt; + } + const std::filesystem::path relativeManifest{manifestValue}; + if (relativeManifest.is_absolute()) { + return std::nullopt; + } + std::error_code error; + const auto manifest = std::filesystem::canonical( + installationPrefix / relativeManifest, error); + if (error) { + return std::nullopt; + } + const auto versions = + std::filesystem::canonical(installationPrefix / "versions", error); + if (error || !std::filesystem::is_regular_file(manifest)) { + return std::nullopt; + } + if (!pathWithin(manifest, versions)) { + return std::nullopt; + } + return RuntimeHandoff{.manifestPath = manifest, + .state = state, + .version = version, + .previousVersion = stringField("previousVersion"), + .retainHealthyVersions = *retention}; + } + + [[nodiscard]] std::filesystem::path + installationPrefix(const std::filesystem::path& installRoot) + { + std::error_code error; + if (installRoot.filename() == "current" && + std::filesystem::is_symlink( + std::filesystem::symlink_status(installRoot, error))) { + return installRoot.parent_path(); + } + return installRoot; + } + + [[nodiscard]] std::filesystem::path + updaterIncomingDirectory(const std::filesystem::path& root, + const std::filesystem::path& stateDirectory) + { + if (const auto configured = environmentPath("ECHOION_INCOMING_DIR")) { + return absolutePath(*configured); + } + if (auto record = + Void::FileSystem::read_file(root / ".echoion-install")) { + constexpr std::string_view prefix{"incoming_dir="}; + std::string_view contents{*record}; + while (!contents.empty()) { + const auto end = contents.find('\n'); + const auto line = contents.substr(0, end); + if (line.starts_with(prefix) && line.size() > prefix.size()) { + std::filesystem::path path{line.substr(prefix.size())}; + return absolutePath(path.is_absolute() ? path + : root / path); + } + if (end == std::string_view::npos) { + break; + } + contents.remove_prefix(end + 1); + } + } + return stateDirectory / "incoming"; + } + + [[nodiscard]] std::optional + runningReleaseManifest(const std::filesystem::path& executable, + const std::filesystem::path& installRoot) + { + const std::array candidates{executable.parent_path().parent_path() / + "manifest.json", + installRoot / "manifest.json"}; + for (const auto& candidate : candidates) { + if (auto manifest = + Echoion::Standalone::ReleaseManifest::load(candidate)) { + return std::move(*manifest); + } + } + return std::nullopt; + } + + [[nodiscard]] std::filesystem::path + reconcileManagedCore(const std::filesystem::path& stateDirectory, + const std::filesystem::path& fallback) + { + Void::Update::VersionStore store(stateDirectory / "updates" / + "components" / "core"); + if (auto initialized = store.initialize(); !initialized) { + Void::Log::warn("main", "Cannot initialize managed Core store: {}", + initialized.error().message()); + return fallback; + } + if (auto reconciled = store.reconcile(); !reconciled) { + Void::Log::warn("main", "Cannot reconcile managed Core store: {}", + reconciled.error().message()); + return fallback; + } + auto current = store.currentVersion(); + if (!current || !*current) { + return fallback; + } + const auto managed = store.versionPath(**current) / fallback.filename(); + return std::filesystem::is_regular_file(managed) ? managed : fallback; + } + + [[nodiscard]] Echoion::Api::Result + invokeRuntimeHelper(const std::filesystem::path& helper, + const std::filesystem::path& root, + std::string_view operationJson) + { + auto operation = Void::Json::parse(operationJson); + if (!operation || !operation->is_object()) { + return Echoion::Api::fail( + Echoion::Api::ErrorCode::ParseError, + "runtime update operation must be a JSON object"); + } + const auto field = [&operation](std::string_view name) { + const auto* value = operation->find(name); + return value && value->is_string() ? value->as_string() + : std::string{}; + }; + const auto action = field("action"); + const auto version = field("version"); + const auto retention = retainHealthyVersions(*operation); + if (!retention.has_value()) { + return Echoion::Api::fail( + Echoion::Api::ErrorCode::InvalidArgument, + "retainHealthyVersions must be an integer from 1 to 10"); + } + std::string command; + std::vector options; + if (action == "activate") { + command = "activate-runtime"; + options = {"--staging", field("stagingId"), + "--version", version, + "--manifest-sha256", field("manifestSha256")}; + } else if (action == "rollback") { + command = "rollback-runtime"; + options = {"--version", version}; + } else if (action == "commit") { + command = "commit-runtime"; + options = {"--version", version}; + } else { + return Echoion::Api::fail(Echoion::Api::ErrorCode::InvalidArgument, + "unknown runtime update operation"); + } + if (version.empty() || + std::ranges::any_of( + options, [](const auto& value) { return value.empty(); })) { + return Echoion::Api::fail( + Echoion::Api::ErrorCode::InvalidArgument, + "runtime update operation is missing required fields"); + } + options.insert(options.end(), {"--retain", std::to_string(*retention)}); + + bool direct = false; +#ifndef _WIN32 + direct = ::access((root / "versions").c_str(), W_OK) == 0; +#endif + std::vector arguments{"--root", root.string()}; + if (!direct) { + arguments.insert(arguments.end(), {"request", command}); + } else { + arguments.push_back(command); + } + arguments.insert(arguments.end(), options.begin(), options.end()); + if (!direct) { + arguments.insert(arguments.end(), {"--origin", "daemon"}); + } + auto result = + Void::Process::run(helper, arguments, {}, std::chrono::seconds{30}); + if (!result) { + return Echoion::Api::fail( + Echoion::Api::ErrorCode::ServiceUnavailable, + result.error().message()); + } + if (result->exit_code != 0) { + return Echoion::Api::fail( + Echoion::Api::ErrorCode::ServiceUnavailable, + result->err.empty() ? "runtime update helper failed" + : result->err); + } + return result->out.empty() ? std::string{"{}"} : std::move(result->out); + } + std::filesystem::path configDir() { if (const char* x = std::getenv("XDG_CONFIG_HOME")) { @@ -298,6 +546,7 @@ int main(int argc, char** argv) } const auto installRoot = Echoion::Standalone::deriveInstallRoot( *runningExecutable, environmentPath("ECHOION_HOME")); + const auto updateRoot = installationPrefix(installRoot); if (hasArgument(argc, argv, "--validate-install")) { const auto requestedRoot = optionalArgumentPath(argc, argv, "--validate-install"); @@ -334,6 +583,13 @@ int main(int argc, char** argv) environmentState.has_value())) { return 2; } + auto signalWatcherResult = Void::Process::SignalWatcher::create(); + if (!signalWatcherResult) { + std::cerr << "Cannot install signal watcher: " + << signalWatcherResult.error().message() << '\n'; + return 2; + } + auto signalWatcher = std::move(*signalWatcherResult); recordInterruptedRelease(stateDirectory); const auto identityPath = absolutePath(std::filesystem::path(envOr( @@ -348,9 +604,26 @@ int main(int argc, char** argv) requestedRestore ? std::optional{absolutePath(*requestedRestore)} : std::nullopt; const auto requestedManifest = environmentPath("ECHOION_RELEASE_MANIFEST"); - const std::optional releaseManifestPath = - requestedManifest ? std::optional{absolutePath(*requestedManifest)} - : std::nullopt; + const auto activationHandoff = + stateDirectory / "updates" / "activated-runtime.json"; + const auto releaseTriggerPath = requestedManifest + ? absolutePath(*requestedManifest) + : activationHandoff; + const bool releaseTriggerIsHandoff = !requestedManifest.has_value(); + const auto runningManifest = + runningReleaseManifest(*runningExecutable, installRoot); + const auto runtimeVersion = + runningManifest + ? runningManifest->version + : std::string{ + Echoion::Standalone::UpdateBuildDefaults::RuntimeVersion}; + if (auto recovered = + Echoion::Standalone::reconcileManagedPluginUpdates(stateDirectory); + !recovered) { + Void::Log::error("main", "cannot recover managed plugin updates: {}", + recovered.error().message); + return 1; + } Echoion::Standalone::StandaloneSettings settings; settings.identityPath = identityPath.string(); @@ -371,8 +644,17 @@ int main(int argc, char** argv) loader.setConfigPath(cfgPath); const auto executableDirectory = runningExecutable->parent_path(); - const auto corePathResolved = Echoion::Standalone::resolveCorePath( - installRoot, executableDirectory, environmentPath("ECHOION_CORE_PATH")); + const auto configuredCoreOverride = environmentPath("ECHOION_CORE_PATH"); + const auto configuredCorePath = Echoion::Standalone::resolveCorePath( + installRoot, executableDirectory, configuredCoreOverride); + const bool customCoreOverride = + configuredCoreOverride && + absolutePath(*configuredCoreOverride) != + absolutePath(installRoot / "lib" / "Echoion.ts"); + const auto corePathResolved = + customCoreOverride + ? configuredCorePath + : reconcileManagedCore(stateDirectory, configuredCorePath); if (const auto workingDirectory = Echoion::Standalone::runtimeWorkingDirectory(installRoot, executableDirectory)) { @@ -423,21 +705,95 @@ int main(int argc, char** argv) } }); - core->triggerAutoConnect(); - std::unique_ptr releaseWatcher; - if (releaseManifestPath) { - releaseWatcher = std::make_unique(); - releaseWatcher->watch( - *releaseManifestPath, - [](const Void::FileSystem::FileWatcher::Event& event) { - if (event.exists) { - requestUpdate(); + const auto updaterExecutable = + runningExecutable->parent_path() / "echoion-updater"; + auto updateService = std::make_unique( + Echoion::Standalone::UpdateService::Options{ + .configPath = cfgPath, + .stateDirectory = stateDirectory, + .installRoot = updateRoot, + .runningExecutable = *runningExecutable, + .currentCore = corePathResolved, + .releaseManifestPath = runningManifest + ? runningManifest->root / "manifest.json" + : std::filesystem::path{}, + .officialFeedUrl = + std::string{Echoion::Standalone::UpdateBuildDefaults::FeedUrl}, + .officialPublicKeysJson = + std::string{ + Echoion::Standalone::UpdateBuildDefaults::PublicKeysJson}, + .runtimeVersion = runtimeVersion, + .apiVersion = Echoion::Api::VERSION_STRING, + .toolchainAbi = + std::string{ + Echoion::Standalone::UpdateBuildDefaults::ToolchainAbi}, + .incomingDirectory = + updaterIncomingDirectory(updateRoot, stateDirectory)}, + Echoion::Standalone::UpdateService::Hooks{ + .replaceCore = + [&loader](const std::filesystem::path& path) { + return loader.hotReload(path); + }, + .managePlugins = [&loader](const std::string& request) + -> Echoion::Api::Result { + if (auto loadedCore = loader.getCore()) { + return loadedCore->managePluginsJson(request); } + return Echoion::Api::fail( + Echoion::Api::ErrorCode::ServiceUnavailable, + "Core is not available"); + }, + .manageRuntime = + [updaterExecutable, updateRoot](const std::string& request) { + return invokeRuntimeHelper(updaterExecutable, updateRoot, + request); + }, + .playbackActive = + [&loader] { + auto loadedCore = loader.getCore(); + if (!loadedCore) { + return false; + } + auto playback = loadedCore->getPlaybackSummary(); + return playback && playback->isPlaying && + playback->currentTrack.has_value(); + }, + .coreVersion = + [&loader] { + if (auto loadedCore = loader.getCore()) { + return loadedCore->getVersion(); + } + return std::string{}; + }}); + if (auto started = updateService->start(); !started) { + Void::Log::error("main", "Updater disabled: {}", + started.error().message); + updateService.reset(); + } else { + interface->setHostControlHandler( + [service = updateService.get()](const std::string& method, + const std::string& request) { + return service->handle(method, request); }); - Void::Log::info("main", "Watching release manifest {}", - releaseManifestPath->string()); - } else if (!std::filesystem::is_regular_file(installRoot / - "manifest.json")) { + } + + core->triggerAutoConnect(); + core.reset(); + auto releaseWatcher = std::make_unique(); + releaseWatcher->watch( + releaseTriggerPath, + [](const Void::FileSystem::FileWatcher::Event& event) { + if (event.exists) { + requestUpdate(); + } + }); + Void::Log::info("main", "Watching runtime update trigger {}", + releaseTriggerPath.string()); + if (std::filesystem::is_regular_file(releaseTriggerPath)) { + requestUpdate(); + } + + if (!std::filesystem::is_regular_file(installRoot / "manifest.json")) { // Compatibility mode for development. Production release bundles use // transactional daemon re-exec instead of replacing Core in isolation. loader.enableAutoReload(); @@ -447,72 +803,143 @@ int main(int argc, char** argv) "Core auto-reload is disabled for an installed release payload"); } - std::signal(SIGINT, onSignal); - std::signal(SIGTERM, onSignal); Void::Log::info("main", "Echoion standalone running. Ctrl-C to stop."); + std::optional healthVersion; if (const char* version = std::getenv("ECHOION_REEXEC_VERSION")) { - std::ignore = Void::FileSystem::atomic_write( - stateDirectory / "release-health", version); - std::ignore = Void::FileSystem::remove_path(stateDirectory / - "release-transaction"); - std::ignore = - Void::FileSystem::remove_path(stateDirectory / "failed-release"); - ::unsetenv("ECHOION_REEXEC_VERSION"); - Void::Log::info("main", "Release {} passed startup health check", - version); + healthVersion = version; + Void::Log::info("main", "Release {} entered its 30 second health check", + *healthVersion); } + auto healthDeadline = + std::chrono::steady_clock::now() + std::chrono::seconds{30}; std::optional pendingRelease; std::filesystem::path checkpointPath; - while (!g_stop.load() && !pendingRelease) { - { - std::unique_lock lock(g_mu); - g_cv.wait(lock, - [] { return g_stop.load() || g_updateRequested.load(); }); + bool stopRequested = false; + while (!stopRequested && !pendingRelease) { + if (updateService) { + updateService->processPendingHostActions(); } - if (g_stop.load() || !releaseManifestPath) { - break; + + if (healthVersion && + std::chrono::steady_clock::now() >= healthDeadline) { + bool committed = true; + const auto handoff = + readRuntimeHandoff(activationHandoff, updateRoot); + if (handoff && handoff->state == "pending" && + handoff->version == *healthVersion) { + Void::Json::Value operation = Void::Json::object(); + operation.as_object().emplace_back("action", + Void::Json::Value{"commit"}); + operation.as_object().emplace_back( + "version", Void::Json::Value{*healthVersion}); + operation.as_object().emplace_back( + "retainHealthyVersions", + Void::Json::Value{static_cast( + handoff->retainHealthyVersions)}); + auto result = + invokeRuntimeHelper(updaterExecutable, updateRoot, + Void::Json::serialize(operation)); + if (!result) { + committed = false; + Void::Log::error("main", + "Cannot confirm runtime {} health: {}", + *healthVersion, result.error().message); + } + } + if (committed) { + std::ignore = Void::FileSystem::atomic_write( + stateDirectory / "release-health", *healthVersion); + std::ignore = Void::FileSystem::remove_path( + stateDirectory / "release-transaction"); + std::ignore = Void::FileSystem::remove_path(stateDirectory / + "failed-release"); + Void::Log::info("main", "Release {} passed its health check", + *healthVersion); + healthVersion.reset(); + ::unsetenv("ECHOION_REEXEC_VERSION"); + } else { + healthDeadline = + std::chrono::steady_clock::now() + std::chrono::seconds{5}; + } } - g_updateRequested = false; - auto manifest = - Echoion::Standalone::ReleaseManifest::load(*releaseManifestPath); - if (!manifest) { - Void::Log::error("main", "release rejected: {}", - manifest.error().message); + + if (g_updateRequested.exchange(false)) { + auto manifestPath = releaseTriggerPath; + if (releaseTriggerIsHandoff) { + auto handoff = + readRuntimeHandoff(releaseTriggerPath, updateRoot); + if (!handoff) { + Void::Log::error("main", + "runtime activation handoff is invalid"); + continue; + } + if (handoff->version == runtimeVersion) { + continue; + } + manifestPath = handoff->manifestPath; + } + auto manifest = + Echoion::Standalone::ReleaseManifest::load(manifestPath); + if (!manifest) { + Void::Log::error("main", "release rejected: {}", + manifest.error().message); + continue; + } + if (manifest->version == runtimeVersion) { + continue; + } + if (auto failed = Void::FileSystem::read_file(stateDirectory / + "failed-release"); + failed && *failed == manifest->version) { + Void::Log::error( + "main", + "Release {} was previously rolled back; publish a new " + "version to retry", + manifest->version); + continue; + } + auto validation = Void::Process::run( + *runningExecutable, + {"--validate-release", manifestPath.string()}, {}, + std::chrono::seconds{30}); + if (!validation || validation->exit_code != 0) { + Void::Log::error("main", "release validation failed: {}", + validation ? validation->err + : validation.error().message()); + continue; + } + checkpointPath = stateDirectory / "restart-state.bin"; + if (auto checkpoint = loader.checkpoint(checkpointPath); + !checkpoint) { + Void::Log::error("main", "release checkpoint failed: {}", + checkpoint.error().message); + continue; + } + pendingRelease = std::move(*manifest); continue; } - if (auto failed = - Void::FileSystem::read_file(stateDirectory / "failed-release"); - failed && *failed == manifest->version) { - Void::Log::error("main", - "Release {} was previously rolled back; publish a " - "new version to retry", - manifest->version); - continue; + + auto observedSignal = + signalWatcher.wait(std::chrono::milliseconds{250}); + if (!observedSignal) { + Void::Log::error("main", "signal watcher failed: {}", + observedSignal.error().message()); + stopRequested = true; + } else if (observedSignal->has_value()) { + stopRequested = true; } - auto validation = Void::Process::run( - *runningExecutable, - {"--validate-release", releaseManifestPath->string()}, {}, - std::chrono::seconds{30}); - if (!validation || validation->exit_code != 0) { - Void::Log::error("main", "release validation failed: {}", - validation ? validation->err - : validation.error().message()); - continue; - } - checkpointPath = stateDirectory / "restart-state.bin"; - if (auto checkpoint = loader.checkpoint(checkpointPath); !checkpoint) { - Void::Log::error("main", "release checkpoint failed: {}", - checkpoint.error().message); - continue; - } - pendingRelease = std::move(*manifest); } releaseWatcher.reset(); Void::Log::info("main", "{}", pendingRelease ? "Applying validated release..." : "Shutting down..."); + interface->setHostControlHandler({}); + if (updateService) { + updateService->stop(); + } + updateService.reset(); loader.disableAutoReload(); (void)interface->disconnectFromServer(); interface->quiesceEventCallbacks(); @@ -529,7 +956,9 @@ int main(int argc, char** argv) } const auto pendingRoot = Echoion::Standalone::deriveInstallRoot(pendingRelease->executable); - const auto pendingRootString = pendingRoot.string(); + const auto pendingHome = + releaseTriggerIsHandoff ? updateRoot / "current" : pendingRoot; + const auto pendingRootString = pendingHome.string(); const auto pendingCoreString = pendingRelease->core.string(); if (::setenv("ECHOION_HOME", pendingRootString.c_str(), 1) != 0 || ::setenv("ECHOION_CORE_PATH", pendingCoreString.c_str(), 1) != 0 || diff --git a/tests/test_stage_release.sh b/tests/test_stage_release.sh index be3c8e2..c57a4d1 100755 --- a/tests/test_stage_release.sh +++ b/tests/test_stage_release.sh @@ -2,8 +2,10 @@ set -euo pipefail stage_script=$1 -validator=$2 +updater=$2 +service_templates=$3 generator=$(dirname -- "$stage_script")/generate-release-manifest.py +manifest_validator=$(dirname -- "$stage_script")/validate-release-manifest.py root=$(mktemp -d) trap 'rm -rf -- "$root"' EXIT @@ -12,31 +14,43 @@ mkdir -p -- \ "$bundle/bin" \ "$bundle/lib" \ "$bundle/service" \ + "$bundle/share/echoion/tools" \ "$bundle/share/echoion/web" -printf '#!/bin/sh\nexit 0\n' > "$bundle/bin/echoiond" +printf '#!/bin/sh\necho "echoiond must not run during release staging" >&2\nexit 97\n' \ + > "$bundle/bin/echoiond" chmod 0755 "$bundle/bin/echoiond" +install -m 0755 -- "$updater" "$bundle/bin/echoion-updater" printf 'test core\n' > "$bundle/lib/Echoion.ts" -printf '[Service]\nExecStart=@ECHOION_EXECUTABLE@\n' \ - > "$bundle/service/echoion.service.in" +install -m 0644 -- \ + "$service_templates/echoion.service.in" \ + "$service_templates/echoion-updater.service.in" \ + "$service_templates/echoion-updater.timer.in" \ + "$bundle/service/" +printf '{"webRoot":"./web"}\n' > "$bundle/share/echoion/config.example.json" +install -m 0755 -- "$manifest_validator" \ + "$bundle/share/echoion/tools/validate-release-manifest.py" printf '\n' > "$bundle/share/echoion/web/index.html" ln -s -- Echoion.ts "$bundle/lib/libEchoionCore.so" python3 "$generator" --root "$bundle" --version 1.2.3 -"$validator" --validate-install "$bundle" +python3 "$manifest_validator" --root "$bundle" --version 1.2.3 bash "$stage_script" "$root/releases" 1.2.3 "$bundle" manifest=$root/releases/pending-release.json test -x "$root/releases/1.2.3/bin/echoiond" +test -x "$root/releases/1.2.3/bin/echoion-updater" test -f "$root/releases/1.2.3/lib/Echoion.ts" test -L "$root/releases/1.2.3/lib/libEchoionCore.so" grep -q '"version": "1.2.3"' "$manifest" grep -q '"executable": "1.2.3/bin/echoiond"' "$manifest" +grep -q '"updater": "1.2.3/bin/echoion-updater"' "$manifest" grep -q '"path": "1.2.3/share/echoion/web/index.html"' "$manifest" -"$validator" --validate-release "$manifest" +python3 "$manifest_validator" --root "$root/releases/1.2.3" --version 1.2.3 printf 'tampered\n' >> "$root/releases/1.2.3/lib/Echoion.ts" -if "$validator" --validate-release "$manifest" >/dev/null 2>&1; then +if python3 "$manifest_validator" --root "$root/releases/1.2.3" --version 1.2.3 \ + >/dev/null 2>&1; then echo "tampered Core artifact was accepted" >&2 exit 1 fi diff --git a/tests/test_update_service.cpp b/tests/test_update_service.cpp new file mode 100644 index 0000000..8ed9f99 --- /dev/null +++ b/tests/test_update_service.cpp @@ -0,0 +1,691 @@ +#include "echoion/standalone/UpdateService.hpp" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + class TemporaryTree + { + public: + + TemporaryTree() + { + std::random_device random; + path_ = + std::filesystem::temp_directory_path() / + ("echoion-update-service-" + + std::to_string(static_cast(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(contents.size())); + return output.good(); + } + + std::string readFile(const std::filesystem::path& path) + { + std::ifstream input(path, std::ios::binary); + return {std::istreambuf_iterator{input}, + std::istreambuf_iterator{}}; + } + + 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& response, + std::optional& 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; + 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 { + ++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 { + 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(!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 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 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 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 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 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 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; +}