From 0fd1cef78b3349d50d5bb636668810fb58a48735 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 | 33 + ReleaseTree.cpp | 1562 +++++++++++++++++++++++++++ ReleaseTree.hpp | 61 ++ ReleaseTreeSecurityTests.cpp | 282 +++++ echoion-updater.cpp | 1982 ++++++++++++++++++++++++++++++++++ 5 files changed, 3920 insertions(+) create mode 100644 CMakeLists.txt create mode 100644 ReleaseTree.cpp create mode 100644 ReleaseTree.hpp create mode 100644 ReleaseTreeSecurityTests.cpp create mode 100644 echoion-updater.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..c877518 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,33 @@ +find_package(OpenSSL REQUIRED COMPONENTS Crypto) + +add_executable(EchoionUpdater echoion-updater.cpp ReleaseTree.cpp) +target_link_libraries(EchoionUpdater PRIVATE OpenSSL::Crypto Void::Update) +set_target_properties(EchoionUpdater PROPERTIES + OUTPUT_NAME echoion-updater + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin") + +if(UNIX AND NOT APPLE) + set_target_properties(EchoionUpdater PROPERTIES + INSTALL_RPATH "$ORIGIN/../${CMAKE_INSTALL_LIBDIR}" + INSTALL_RPATH_USE_LINK_PATH FALSE) +endif() + +install(TARGETS EchoionUpdater + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + COMPONENT Runtime) + +if(BUILD_TESTS) + add_executable(EchoionReleaseTreeSecurityTests + ReleaseTreeSecurityTests.cpp + ReleaseTree.cpp) + target_link_libraries(EchoionReleaseTreeSecurityTests PRIVATE OpenSSL::Crypto) + + add_test(NAME EchoionReleaseTreeSecurity + COMMAND EchoionReleaseTreeSecurityTests) + + add_test(NAME EchoionUpdaterLifecycle + COMMAND bash + "${CMAKE_CURRENT_SOURCE_DIR}/../tests/updater_test.sh" + "$" + "${CMAKE_SOURCE_DIR}") +endif() diff --git a/ReleaseTree.cpp b/ReleaseTree.cpp new file mode 100644 index 0000000..f9ea2da --- /dev/null +++ b/ReleaseTree.cpp @@ -0,0 +1,1562 @@ +#include "ReleaseTree.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 + +namespace Echoion::Updater +{ + namespace + { + + namespace fs = std::filesystem; + + constexpr std::size_t kMaximumJsonBytes{16U * 1024U * 1024U}; + constexpr std::size_t kMaximumJsonDepth{64U}; + constexpr std::size_t kMaximumReleaseEntries{50'000U}; + constexpr std::size_t kMaximumManifestEntries{kMaximumReleaseEntries}; + constexpr std::size_t kMaximumSymlinkBytes{4096U}; + constexpr std::size_t kMaximumReleaseDepth{64U}; + constexpr std::size_t kMaximumReleasePathBytes{4096U}; + constexpr std::size_t kMaximumReleaseNameBytes{255U}; + constexpr std::uintmax_t kMaximumReleaseFileBytes{1ULL * 1024ULL * + 1024ULL * 1024ULL}; + constexpr std::uintmax_t kMaximumReleaseBytes{2ULL * 1024ULL * 1024ULL * + 1024ULL}; + + class FileDescriptor final + { + public: + + explicit FileDescriptor(const int descriptor = -1) noexcept + : descriptor_{descriptor} + { + } + + ~FileDescriptor() + { + if (descriptor_ >= 0) { + ::close(descriptor_); + } + } + + FileDescriptor(const FileDescriptor&) = delete; + FileDescriptor& operator=(const FileDescriptor&) = delete; + FileDescriptor(FileDescriptor&& other) noexcept + : descriptor_{std::exchange(other.descriptor_, -1)} + { + } + FileDescriptor& operator=(FileDescriptor&& other) noexcept + { + if (this != &other) { + if (descriptor_ >= 0) { + ::close(descriptor_); + } + descriptor_ = std::exchange(other.descriptor_, -1); + } + return *this; + } + + [[nodiscard]] int get() const noexcept { return descriptor_; } + + private: + + int descriptor_{-1}; + }; + + struct DirectoryCloser { + void operator()(DIR* directory) const noexcept + { + if (directory != nullptr) { + ::closedir(directory); + } + } + }; + + using Directory = std::unique_ptr; + + [[nodiscard]] std::runtime_error + systemError(const std::string_view operation) + { + return std::runtime_error{std::string{operation} + ": " + + std::strerror(errno)}; + } + + struct Json { + using Array = std::vector; + using Object = std::map>; + std::variant + value; + }; + + class JsonParser final + { + public: + + explicit JsonParser(const std::string_view input) + : input_{input} + { + } + + [[nodiscard]] Json parse() + { + skipWhitespace(); + Json result = parseValue(0U); + skipWhitespace(); + if (position_ != input_.size()) { + fail("trailing data"); + } + return result; + } + + private: + + [[noreturn]] void fail(const std::string_view message) const + { + throw std::runtime_error{"invalid JSON at byte " + + std::to_string(position_) + ": " + + std::string{message}}; + } + + void skipWhitespace() + { + while (position_ < input_.size() && + (input_[position_] == ' ' || + input_[position_] == '\t' || + input_[position_] == '\r' || + input_[position_] == '\n')) { + ++position_; + } + } + + [[nodiscard]] char take() + { + if (position_ >= input_.size()) { + fail("unexpected end of input"); + } + return input_[position_++]; + } + + void expect(const char expected) + { + if (take() != expected) { + fail("unexpected character"); + } + } + + void expectLiteral(const std::string_view literal) + { + if (input_.substr(position_, literal.size()) != literal) { + fail("invalid literal"); + } + position_ += literal.size(); + } + + [[nodiscard]] static int hexValue(const char value) + { + if (value >= '0' && value <= '9') { + return value - '0'; + } + if (value >= 'a' && value <= 'f') { + return value - 'a' + 10; + } + if (value >= 'A' && value <= 'F') { + return value - 'A' + 10; + } + return -1; + } + + [[nodiscard]] std::uint32_t unicodeEscape() + { + std::uint32_t value{}; + for (int index{}; index < 4; ++index) { + const int digit = hexValue(take()); + if (digit < 0) { + fail("invalid unicode escape"); + } + value = value * 16U + static_cast(digit); + } + return value; + } + + static void appendUtf8(std::string& output, + const std::uint32_t codepoint) + { + if (codepoint <= 0x7FU) { + output.push_back(static_cast(codepoint)); + } else if (codepoint <= 0x7FFU) { + output.push_back( + static_cast(0xC0U | (codepoint >> 6U))); + output.push_back( + static_cast(0x80U | (codepoint & 0x3FU))); + } else if (codepoint <= 0xFFFFU) { + output.push_back( + static_cast(0xE0U | (codepoint >> 12U))); + output.push_back(static_cast( + 0x80U | ((codepoint >> 6U) & 0x3FU))); + output.push_back( + static_cast(0x80U | (codepoint & 0x3FU))); + } else { + output.push_back( + static_cast(0xF0U | (codepoint >> 18U))); + output.push_back(static_cast( + 0x80U | ((codepoint >> 12U) & 0x3FU))); + output.push_back(static_cast( + 0x80U | ((codepoint >> 6U) & 0x3FU))); + output.push_back( + static_cast(0x80U | (codepoint & 0x3FU))); + } + } + + [[nodiscard]] std::string parseString() + { + expect('"'); + std::string output; + while (true) { + const unsigned char value = + static_cast(take()); + if (value == '"') { + return output; + } + if (value < 0x20U) { + fail("control character in string"); + } + if (value != '\\') { + output.push_back(static_cast(value)); + continue; + } + switch (take()) { + case '"': + output.push_back('"'); + break; + case '\\': + output.push_back('\\'); + break; + case '/': + output.push_back('/'); + break; + case 'b': + output.push_back('\b'); + break; + case 'f': + output.push_back('\f'); + break; + case 'n': + output.push_back('\n'); + break; + case 'r': + output.push_back('\r'); + break; + case 't': + output.push_back('\t'); + break; + case 'u': + { + std::uint32_t codepoint = unicodeEscape(); + if (codepoint >= 0xD800U && + codepoint <= 0xDBFFU) { + if (take() != '\\' || take() != 'u') { + fail("missing low surrogate"); + } + const std::uint32_t low = + unicodeEscape(); + if (low < 0xDC00U || low > 0xDFFFU) { + fail("invalid low surrogate"); + } + codepoint = + 0x10000U + + ((codepoint - 0xD800U) << 10U) + + low - 0xDC00U; + } else if (codepoint >= 0xDC00U && + codepoint <= 0xDFFFU) { + fail("unexpected low surrogate"); + } + appendUtf8(output, codepoint); + break; + } + default: + fail("invalid string escape"); + } + } + } + + [[nodiscard]] Json parseNumber() + { + const std::size_t start = position_; + if (input_[position_] == '-') { + ++position_; + } + if (position_ >= input_.size()) { + fail("incomplete number"); + } + if (input_[position_] == '0') { + ++position_; + } else { + if (input_[position_] < '1' || + input_[position_] > '9') { + fail("invalid number"); + } + while (position_ < input_.size() && + input_[position_] >= '0' && + input_[position_] <= '9') { + ++position_; + } + } + if (position_ < input_.size() && + (input_[position_] == '.' || input_[position_] == 'e' || + input_[position_] == 'E')) { + fail("floating-point numbers are not supported"); + } + std::int64_t value{}; + const auto result = + std::from_chars(input_.data() + start, + input_.data() + position_, value); + if (result.ec != std::errc{} || + result.ptr != input_.data() + position_) { + fail("integer is out of range"); + } + return Json{value}; + } + + [[nodiscard]] Json parseArray(const std::size_t depth) + { + expect('['); + skipWhitespace(); + Json::Array result; + if (position_ < input_.size() && input_[position_] == ']') { + ++position_; + return Json{std::move(result)}; + } + while (true) { + result.push_back(parseValue(depth + 1U)); + skipWhitespace(); + const char separator = take(); + if (separator == ']') { + return Json{std::move(result)}; + } + if (separator != ',') { + fail("array requires comma or closing bracket"); + } + skipWhitespace(); + } + } + + [[nodiscard]] Json parseObject(const std::size_t depth) + { + expect('{'); + skipWhitespace(); + Json::Object result; + if (position_ < input_.size() && input_[position_] == '}') { + ++position_; + return Json{std::move(result)}; + } + while (true) { + if (position_ >= input_.size() || + input_[position_] != '"') { + fail("object key must be a string"); + } + std::string key = parseString(); + skipWhitespace(); + expect(':'); + skipWhitespace(); + auto [iterator, inserted] = result.emplace( + std::move(key), parseValue(depth + 1U)); + static_cast(iterator); + if (!inserted) { + fail("duplicate object key"); + } + skipWhitespace(); + const char separator = take(); + if (separator == '}') { + return Json{std::move(result)}; + } + if (separator != ',') { + fail("object requires comma or closing brace"); + } + skipWhitespace(); + } + } + + [[nodiscard]] Json parseValue(const std::size_t depth) + { + if (depth > kMaximumJsonDepth || + position_ >= input_.size()) { + fail("nesting limit or unexpected end of input"); + } + switch (input_[position_]) { + case '{': + return parseObject(depth); + case '[': + return parseArray(depth); + case '"': + return Json{parseString()}; + case 't': + expectLiteral("true"); + return Json{true}; + case 'f': + expectLiteral("false"); + return Json{false}; + case 'n': + expectLiteral("null"); + return Json{nullptr}; + default: + if (input_[position_] == '-' || + (input_[position_] >= '0' && + input_[position_] <= '9')) { + return parseNumber(); + } + fail("invalid value"); + } + } + + std::string_view input_; + std::size_t position_{}; + }; + + [[nodiscard]] const Json::Object& + object(const Json& value, const std::string_view description) + { + const auto* result = std::get_if(&value.value); + if (result == nullptr) { + throw std::runtime_error{std::string{description} + + " must be an object"}; + } + return *result; + } + + [[nodiscard]] const Json::Array& + array(const Json& value, const std::string_view description) + { + const auto* result = std::get_if(&value.value); + if (result == nullptr) { + throw std::runtime_error{std::string{description} + + " must be an array"}; + } + return *result; + } + + [[nodiscard]] const Json& required(const Json::Object& value, + const std::string_view key) + { + const auto iterator = value.find(key); + if (iterator == value.end()) { + throw std::runtime_error{"missing JSON field: " + + std::string{key}}; + } + return iterator->second; + } + + [[nodiscard]] const std::string& string(const Json::Object& value, + const std::string_view key) + { + const auto* result = + std::get_if(&required(value, key).value); + if (result == nullptr) { + throw std::runtime_error{"JSON field must be a string: " + + std::string{key}}; + } + return *result; + } + + [[nodiscard]] std::int64_t integer(const Json::Object& value, + const std::string_view key) + { + const auto* result = + std::get_if(&required(value, key).value); + if (result == nullptr) { + throw std::runtime_error{"JSON field must be an integer: " + + std::string{key}}; + } + return *result; + } + + [[nodiscard]] std::uint32_t retainedVersions(const Json::Object& value) + { + const auto found = value.find("retainHealthyVersions"); + if (found == value.end()) { + return 2U; + } + const auto* result = + std::get_if(&found->second.value); + if (result == nullptr || *result < 1 || *result > 10) { + throw std::runtime_error{ + "retainHealthyVersions must be an integer from 1 to 10"}; + } + return static_cast(*result); + } + + [[nodiscard]] bool safeIdentifier(const std::string_view value) + { + if (value.empty() || value.size() > 64U || value == "." || + value == "..") { + return false; + } + for (const char rawCharacter : value) { + const auto character = static_cast(rawCharacter); + if (!(character >= 'a' && character <= 'z') && + !(character >= 'A' && character <= 'Z') && + !(character >= '0' && character <= '9') && + character != '.' && character != '_' && character != '-') { + return false; + } + } + return (value.front() >= 'A' && value.front() <= 'Z') || + (value.front() >= 'a' && value.front() <= 'z') || + (value.front() >= '0' && value.front() <= '9'); + } + + [[nodiscard]] bool safeDigest(const std::string_view value) + { + if (value.size() != 64U) { + return false; + } + return std::ranges::all_of(value, [](const char character) { + return (character >= '0' && character <= '9') || + (character >= 'a' && character <= 'f'); + }); + } + + [[nodiscard]] std::string readBounded(const fs::path& path, + const std::size_t maximumBytes) + { + std::error_code error; + const auto status = fs::symlink_status(path, error); + if (error || !fs::is_regular_file(status) || + fs::is_symlink(status)) { + throw std::runtime_error{"not a regular file: " + + path.string()}; + } + const auto size = fs::file_size(path, error); + if (error || size > maximumBytes) { + throw std::runtime_error{"file exceeds size limit: " + + path.string()}; + } + std::ifstream input{path, std::ios::binary}; + if (!input) { + throw std::runtime_error{"cannot read file: " + path.string()}; + } + std::string result(static_cast(size), '\0'); + input.read(result.data(), + static_cast(result.size())); + if (!input || input.peek() != std::char_traits::eof()) { + throw std::runtime_error{"cannot read complete file: " + + path.string()}; + } + return result; + } + + [[nodiscard]] unsigned int mode(const fs::file_status& status) + { + return static_cast(status.permissions()) & 07777U; + } + + void rejectWritable(const fs::path& path, const fs::file_status& status) + { + if ((mode(status) & 0022U) != 0U) { + throw std::runtime_error{ + "immutable path is group/world-writable: " + path.string()}; + } + } + + [[nodiscard]] std::vector + pathParts(const std::string_view path) + { + if (path.empty() || path.front() == '/' || path.back() == '/' || + path.find('\\') != std::string_view::npos) { + throw std::runtime_error{"unsafe manifest path"}; + } + std::vector parts; + std::size_t begin{}; + while (begin < path.size()) { + const std::size_t end = path.find('/', begin); + const std::string_view part = path.substr( + begin, end == std::string_view::npos ? path.size() - begin + : end - begin); + if (part.empty() || part == "." || part == "..") { + throw std::runtime_error{"unsafe manifest path component"}; + } + parts.push_back(part); + if (end == std::string_view::npos) { + break; + } + begin = end + 1U; + } + static const std::set roots{"bin", "lib", + "service", "share"}; + if (parts.empty() || !roots.contains(parts.front())) { + throw std::runtime_error{ + "manifest path is outside immutable roots"}; + } + return parts; + } + + [[nodiscard]] fs::path + joinedPath(const fs::path& root, + const std::vector& parts) + { + fs::path result = root; + for (const auto part : parts) { + result /= std::string{part}; + } + return result; + } + + [[nodiscard]] bool within(const fs::path& path, const fs::path& root) + { + const auto mismatch = std::mismatch(root.begin(), root.end(), + path.begin(), path.end()); + return mismatch.first == root.end(); + } + + [[nodiscard]] unsigned int parseMode(const std::string_view value) + { + if (value.size() != 4U) { + throw std::runtime_error{ + "manifest mode must have four octal digits"}; + } + unsigned int result{}; + for (const char digit : value) { + if (digit < '0' || digit > '7') { + throw std::runtime_error{"manifest mode is not octal"}; + } + result = result * 8U + static_cast(digit - '0'); + } + return result; + } + + struct CopyBudget { + std::size_t entries{}; + std::uintmax_t bytes{}; + + void accountEntry(const std::string_view logicalPath, + const std::size_t depth) + { + if (depth > kMaximumReleaseDepth) { + throw std::runtime_error{ + "staged release exceeds maximum directory depth"}; + } + if (logicalPath.empty() || + logicalPath.size() > kMaximumReleasePathBytes) { + throw std::runtime_error{ + "staged release path exceeds size limit"}; + } + if (entries >= kMaximumReleaseEntries) { + throw std::runtime_error{ + "staged release exceeds entry count limit"}; + } + ++entries; + } + + void accountFile(const struct stat& metadata, + const std::string_view logicalPath) + { + if (metadata.st_size < 0) { + throw std::runtime_error{ + "staged release file has an invalid size: " + + std::string{logicalPath}}; + } + const auto size = + static_cast(metadata.st_size); + if (size > kMaximumReleaseFileBytes) { + throw std::runtime_error{ + "staged release file exceeds size limit: " + + std::string{logicalPath}}; + } + accountBytes(size); + } + + void accountBytes(const std::uintmax_t size) + { + if (size > kMaximumReleaseBytes - bytes) { + throw std::runtime_error{ + "staged release exceeds total size limit"}; + } + bytes += size; + } + }; + + [[nodiscard]] bool sameOpenedNode(const struct stat& before, + const struct stat& after) noexcept + { + return before.st_dev == after.st_dev && + before.st_ino == after.st_ino && + before.st_mode == after.st_mode && + before.st_uid == after.st_uid && + before.st_size == after.st_size && + before.st_mtim.tv_sec == after.st_mtim.tv_sec && + before.st_mtim.tv_nsec == after.st_mtim.tv_nsec && + before.st_ctim.tv_sec == after.st_ctim.tv_sec && + before.st_ctim.tv_nsec == after.st_ctim.tv_nsec; + } + + void requireEntryName(const std::string_view name) + { + if (name.empty() || name == "." || name == ".." || + name.size() > kMaximumReleaseNameBytes || + name.find('\0') != std::string_view::npos || + name.find('/') != std::string_view::npos || + name.find('\\') != std::string_view::npos) { + throw std::runtime_error{ + "staged release contains an unsafe path component"}; + } + } + + [[nodiscard]] std::string + childLogicalPath(const std::string_view parent, + const std::string_view child) + { + requireEntryName(child); + if (parent.size() + 1U + child.size() > kMaximumReleasePathBytes) { + throw std::runtime_error{ + "staged release path exceeds size limit"}; + } + return std::string{parent} + "/" + std::string{child}; + } + + template + void visitDirectoryEntries(const int descriptor, Visitor&& visitor) + { + const int duplicate = ::fcntl(descriptor, F_DUPFD_CLOEXEC, 0); + if (duplicate < 0) { + throw systemError( + "cannot duplicate staged directory descriptor"); + } + Directory directory{::fdopendir(duplicate)}; + if (!directory) { + const int saved = errno; + ::close(duplicate); + errno = saved; + throw systemError("cannot enumerate staged directory"); + } + std::size_t entries{}; + while (true) { + errno = 0; + const dirent* entry = ::readdir(directory.get()); + if (entry == nullptr) { + if (errno != 0) { + throw systemError("cannot enumerate staged directory"); + } + break; + } + const std::string_view name{entry->d_name}; + if (name != "." && name != "..") { + requireEntryName(name); + if (entries >= kMaximumReleaseEntries) { + throw std::runtime_error{"staged release directory " + "exceeds entry count limit"}; + } + ++entries; + visitor(std::string{name}); + } + } + } + + [[nodiscard]] std::vector + directoryEntries(const int descriptor) + { + std::vector result; + visitDirectoryEntries(descriptor, [&](std::string name) { + result.push_back(std::move(name)); + }); + std::ranges::sort(result); + return result; + } + + [[nodiscard]] FileDescriptor + openDirectoryAt(const int parent, const std::string_view name, + const std::string_view description) + { + const std::string ownedName{name}; + FileDescriptor result{ + ::openat(parent, ownedName.c_str(), + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)}; + if (result.get() < 0) { + throw systemError(std::string{"cannot open "} + + std::string{description}); + } + struct stat metadata{}; + if (::fstat(result.get(), &metadata) != 0 || + !S_ISDIR(metadata.st_mode)) { + throw std::runtime_error{std::string{description} + + " is not a real directory"}; + } + return result; + } + + void requireOwnedSource(const struct stat& metadata, const uid_t owner, + const std::string_view logicalPath) + { + if (metadata.st_uid != owner) { + throw std::runtime_error{ + "staged path ownership changes inside release: " + + std::string{logicalPath}}; + } + if (!S_ISLNK(metadata.st_mode) && + (metadata.st_mode & 0022U) != 0U) { + throw std::runtime_error{ + "staged immutable path is group/world-writable: " + + std::string{logicalPath}}; + } + } + + void writeAll(const int descriptor, const char* bytes, + const std::size_t size) + { + std::size_t offset{}; + while (offset < size) { + const auto count = + ::write(descriptor, bytes + offset, size - offset); + if (count < 0) { + if (errno == EINTR) { + continue; + } + throw systemError("cannot write staged release file"); + } + if (count == 0) { + throw std::runtime_error{ + "short write while copying staged release file"}; + } + offset += static_cast(count); + } + } + + void copyRegularAt( + const int sourceParent, const std::string_view name, + const int destinationParent, const std::string_view logicalPath, + const uid_t owner, const std::size_t depth, CopyBudget& budget, + const std::uintmax_t maximumBytes = kMaximumReleaseFileBytes) + { + requireEntryName(name); + const std::string ownedName{name}; + FileDescriptor source{ + ::openat(sourceParent, ownedName.c_str(), + O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)}; + if (source.get() < 0) { + throw systemError("cannot open staged release file"); + } + struct stat before{}; + if (::fstat(source.get(), &before) != 0 || + !S_ISREG(before.st_mode)) { + throw std::runtime_error{ + "staged path changed before it was read: " + + std::string{logicalPath}}; + } + requireOwnedSource(before, owner, logicalPath); + if (before.st_size < 0 || + static_cast(before.st_size) > maximumBytes) { + throw std::runtime_error{ + "staged release file exceeds size limit: " + + std::string{logicalPath}}; + } + budget.accountEntry(logicalPath, depth); + budget.accountFile(before, logicalPath); + + FileDescriptor destination{::openat( + destinationParent, ownedName.c_str(), + O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0600)}; + if (destination.get() < 0) { + throw systemError("cannot create release file"); + } + if (::fchmod(destination.get(), before.st_mode & 07777U) != 0) { + throw systemError("cannot set release file mode"); + } + std::array buffer{}; + const auto expectedBytes = + static_cast(before.st_size); + std::uintmax_t copiedBytes{}; + while (copiedBytes < expectedBytes) { + const auto remaining = expectedBytes - copiedBytes; + const auto requested = static_cast( + std::min(remaining, buffer.size())); + const auto count = + ::read(source.get(), buffer.data(), requested); + if (count < 0) { + if (errno == EINTR) { + continue; + } + throw systemError("cannot read staged release file"); + } + if (count == 0) { + throw std::runtime_error{"staged release file became " + "shorter while it was copied: " + + std::string{logicalPath}}; + } + writeAll(destination.get(), buffer.data(), + static_cast(count)); + copiedBytes += static_cast(count); + } + char extraByte{}; + while (true) { + const auto extra = ::read(source.get(), &extraByte, 1U); + if (extra < 0 && errno == EINTR) { + continue; + } + if (extra < 0) { + throw systemError( + "cannot finish reading staged release file"); + } + if (extra != 0) { + throw std::runtime_error{ + "staged release file grew while it was copied: " + + std::string{logicalPath}}; + } + break; + } + struct stat after{}; + if (::fstat(source.get(), &after) != 0 || + !sameOpenedNode(before, after)) { + throw std::runtime_error{ + "staged release file changed while it was copied: " + + std::string{logicalPath}}; + } + if (::fsync(destination.get()) != 0) { + throw systemError("cannot sync copied release file"); + } + } + + [[nodiscard]] std::string readSymlinkAt(const int parent, + const std::string_view name) + { + const std::string ownedName{name}; + std::vector buffer(kMaximumSymlinkBytes + 1U, '\0'); + const auto count = ::readlinkat(parent, ownedName.c_str(), + buffer.data(), buffer.size()); + if (count < 0) { + throw systemError("cannot read staged release symlink"); + } + if (static_cast(count) >= buffer.size()) { + throw std::runtime_error{"staged release symlink is too long"}; + } + return {buffer.data(), static_cast(count)}; + } + + void copySymlinkAt(const int sourceParent, const std::string_view name, + const int destinationParent, + const std::string_view logicalPath, + const uid_t owner, const std::size_t depth, + CopyBudget& budget) + { + const std::string ownedName{name}; + struct stat before{}; + if (::fstatat(sourceParent, ownedName.c_str(), &before, + AT_SYMLINK_NOFOLLOW) != 0 || + !S_ISLNK(before.st_mode)) { + throw std::runtime_error{ + "staged symlink changed before it was read: " + + std::string{logicalPath}}; + } + requireOwnedSource(before, owner, logicalPath); + budget.accountEntry(logicalPath, depth); + const std::string target = readSymlinkAt(sourceParent, name); + budget.accountBytes(target.size()); + struct stat after{}; + if (::fstatat(sourceParent, ownedName.c_str(), &after, + AT_SYMLINK_NOFOLLOW) != 0 || + !sameOpenedNode(before, after)) { + throw std::runtime_error{ + "staged symlink changed while it was copied: " + + std::string{logicalPath}}; + } + if (::symlinkat(target.c_str(), destinationParent, + ownedName.c_str()) != 0) { + throw systemError("cannot create release symlink"); + } + } + + void copyNodeAt(const int sourceParent, const std::string_view name, + const int destinationParent, + const std::string_view logicalPath, const uid_t owner, + const std::size_t depth, CopyBudget& budget) + { + requireEntryName(name); + const std::string ownedName{name}; + struct stat metadata{}; + if (::fstatat(sourceParent, ownedName.c_str(), &metadata, + AT_SYMLINK_NOFOLLOW) != 0) { + throw systemError("cannot inspect staged release path"); + } + requireOwnedSource(metadata, owner, logicalPath); + if (S_ISDIR(metadata.st_mode)) { + const FileDescriptor source = openDirectoryAt( + sourceParent, name, "staged release directory"); + struct stat opened{}; + if (::fstat(source.get(), &opened) != 0) { + throw systemError( + "cannot inspect staged release directory"); + } + requireOwnedSource(opened, owner, logicalPath); + if (metadata.st_dev != opened.st_dev || + metadata.st_ino != opened.st_ino) { + throw std::runtime_error{ + "staged directory changed before it was opened: " + + std::string{logicalPath}}; + } + budget.accountEntry(logicalPath, depth); + if (::mkdirat(destinationParent, ownedName.c_str(), 0700) != + 0) { + throw systemError("cannot create release directory"); + } + const FileDescriptor destination = openDirectoryAt( + destinationParent, name, "release directory"); + if (::fchmod(destination.get(), opened.st_mode & 07777U) != 0) { + throw systemError("cannot set release directory mode"); + } + visitDirectoryEntries( + source.get(), [&](const std::string& child) { + const std::string childPath = + childLogicalPath(logicalPath, child); + copyNodeAt(source.get(), child, destination.get(), + childPath, owner, depth + 1U, budget); + }); + struct stat after{}; + if (::fstat(source.get(), &after) != 0 || + !sameOpenedNode(opened, after)) { + throw std::runtime_error{ + "staged directory changed while it was copied: " + + std::string{logicalPath}}; + } + if (::fsync(destination.get()) != 0) { + throw systemError("cannot sync copied release directory"); + } + } else if (S_ISREG(metadata.st_mode)) { + copyRegularAt(sourceParent, name, destinationParent, + logicalPath, owner, depth, budget); + } else if (S_ISLNK(metadata.st_mode)) { + copySymlinkAt(sourceParent, name, destinationParent, + logicalPath, owner, depth, budget); + } else { + throw std::runtime_error{"unsupported staged special file: " + + std::string{logicalPath}}; + } + } + + void removeTreeAt(const int parent, const std::string_view name, + const std::size_t depth, std::size_t& entries) + { + requireEntryName(name); + if (depth > kMaximumReleaseDepth + 1U || + entries > kMaximumReleaseEntries + 1U) { + throw std::runtime_error{ + "incomplete release cleanup exceeds traversal limit"}; + } + const std::string ownedName{name}; + struct stat metadata{}; + if (::fstatat(parent, ownedName.c_str(), &metadata, + AT_SYMLINK_NOFOLLOW) != 0) { + if (errno == ENOENT) { + return; + } + throw systemError("cannot inspect incomplete release"); + } + if (S_ISDIR(metadata.st_mode)) { + const FileDescriptor directory = openDirectoryAt( + parent, name, "incomplete release directory"); + const auto children = directoryEntries(directory.get()); + if (children.size() > kMaximumReleaseEntries + 1U - entries) { + throw std::runtime_error{ + "incomplete release cleanup exceeds traversal limit"}; + } + entries += children.size(); + for (const auto& child : children) { + removeTreeAt(directory.get(), child, depth + 1U, entries); + } + if (::unlinkat(parent, ownedName.c_str(), AT_REMOVEDIR) != 0) { + throw systemError( + "cannot remove incomplete release directory"); + } + } else if (::unlinkat(parent, ownedName.c_str(), 0) != 0) { + throw systemError("cannot remove incomplete release path"); + } + } + + void syncTreeAt(const int directoryDescriptor, const std::size_t depth, + std::size_t& entries) + { + if (depth > kMaximumReleaseDepth + 1U || + entries > kMaximumReleaseEntries + 1U) { + throw std::runtime_error{ + "release sync exceeds traversal limit"}; + } + const auto children = directoryEntries(directoryDescriptor); + if (children.size() > kMaximumReleaseEntries + 1U - entries) { + throw std::runtime_error{ + "release sync exceeds traversal limit"}; + } + entries += children.size(); + for (const auto& child : children) { + struct stat metadata{}; + if (::fstatat(directoryDescriptor, child.c_str(), &metadata, + AT_SYMLINK_NOFOLLOW) != 0) { + throw systemError("cannot inspect copied release path"); + } + if (S_ISDIR(metadata.st_mode)) { + const FileDescriptor directory = openDirectoryAt( + directoryDescriptor, child, "copied release directory"); + syncTreeAt(directory.get(), depth + 1U, entries); + } else if (S_ISREG(metadata.st_mode)) { + FileDescriptor file{::openat( + directoryDescriptor, child.c_str(), + O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)}; + struct stat opened{}; + if (file.get() < 0 || ::fstat(file.get(), &opened) != 0 || + !S_ISREG(opened.st_mode) || + opened.st_dev != metadata.st_dev || + opened.st_ino != metadata.st_ino) { + throw std::runtime_error{ + "copied release file changed before sync"}; + } + if (::fsync(file.get()) != 0) { + throw systemError("cannot sync copied release file"); + } + } else if (!S_ISLNK(metadata.st_mode)) { + throw std::runtime_error{ + "copied release contains an unsupported special file"}; + } + } + if (::fsync(directoryDescriptor) != 0) { + throw systemError("cannot sync copied release directory"); + } + } + + } // namespace + + PrivilegedRequest parsePrivilegedRequest(const std::string_view json) + { + if (json.size() > kMaximumJsonBytes) { + throw std::runtime_error{"activation request exceeds size limit"}; + } + const Json requestValue = JsonParser{json}.parse(); + const auto& request = object(requestValue, "privileged request"); + static const std::set allowed{ + "schemaVersion", "id", "createdAt", + "operation", "stagingId", "version", + "manifestSha256", "origin", "retainHealthyVersions"}; + for (const auto& [key, value] : request) { + static_cast(value); + if (!allowed.contains(key)) { + throw std::runtime_error{"unknown activation request field: " + + key}; + } + } + if (integer(request, "schemaVersion") != 1) { + throw std::runtime_error{"unsupported activation request"}; + } + if (!safeIdentifier(string(request, "id")) || + string(request, "createdAt").size() > 64U) { + throw std::runtime_error{"privileged request metadata is invalid"}; + } + if (const auto origin = request.find("origin"); + origin != request.end()) { + const auto* originValue = + std::get_if(&origin->second.value); + if (originValue == nullptr || !safeIdentifier(*originValue)) { + throw std::runtime_error{ + "privileged request origin is invalid"}; + } + } + const std::string& operation = string(request, "operation"); + if (operation == "activate-runtime") { + RuntimeActivation result{ + .stagingId = string(request, "stagingId"), + .version = string(request, "version"), + .manifestSha256 = string(request, "manifestSha256"), + .retainHealthyVersions = retainedVersions(request), + }; + if (!safeIdentifier(result.stagingId) || + !safeIdentifier(result.version) || + !safeDigest(result.manifestSha256)) { + throw std::runtime_error{ + "activation request contains an unsafe value"}; + } + return result; + } + if (operation == "rollback-runtime" || operation == "commit-runtime") { + if (request.contains("stagingId") || + request.contains("manifestSha256")) { + throw std::runtime_error{ + "runtime selection request has activation-only fields"}; + } + const std::string& version = string(request, "version"); + if (!safeIdentifier(version)) { + throw std::runtime_error{ + "runtime selection request contains an unsafe version"}; + } + if (operation == "rollback-runtime") { + return RuntimeRollback{.version = version, + .retainHealthyVersions = + retainedVersions(request)}; + } + return RuntimeCommit{.version = version, + .retainHealthyVersions = + retainedVersions(request)}; + } + throw std::runtime_error{"unsupported privileged request operation"}; + } + + PendingRuntime parsePendingRuntime(const std::string_view json) + { + if (json.size() > kMaximumJsonBytes) { + throw std::runtime_error{ + "pending runtime journal exceeds size limit"}; + } + const Json value = JsonParser{json}.parse(); + const auto& pending = object(value, "pending runtime journal"); + static const std::set allowed{ + "schemaVersion", "candidateId", "version", + "previousVersion", "manifestSha256", "manifestPath", + "activatedAt", "state", "retainHealthyVersions"}; + for (const auto& [key, child] : pending) { + static_cast(child); + if (!allowed.contains(key)) { + throw std::runtime_error{"unknown pending runtime field: " + + key}; + } + } + if (integer(pending, "schemaVersion") != 1 || + string(pending, "state") != "pending") { + throw std::runtime_error{"unsupported pending runtime journal"}; + } + PendingRuntime result{ + .candidateId = string(pending, "candidateId"), + .version = string(pending, "version"), + .previousVersion = string(pending, "previousVersion"), + .manifestSha256 = string(pending, "manifestSha256"), + .activatedAt = string(pending, "activatedAt"), + .retainHealthyVersions = retainedVersions(pending), + }; + if (!safeIdentifier(result.candidateId) || + !safeIdentifier(result.version) || + !safeIdentifier(result.previousVersion) || + !safeDigest(result.manifestSha256) || + result.version == result.previousVersion || + result.activatedAt.empty() || result.activatedAt.size() > 64U || + string(pending, "manifestPath") != + "versions/" + result.version + "/manifest.json") { + throw std::runtime_error{ + "pending runtime journal contains an unsafe value"}; + } + return result; + } + + RuntimeActivation parseActivationRequest(const std::string_view json) + { + PrivilegedRequest request = parsePrivilegedRequest(json); + const auto* activation = std::get_if(&request); + if (activation == nullptr) { + throw std::runtime_error{"request is not a runtime activation"}; + } + return *activation; + } + + std::string sha256File(const fs::path& path) + { + const std::unique_ptr context{ + EVP_MD_CTX_new(), &EVP_MD_CTX_free}; + if (!context || + EVP_DigestInit_ex(context.get(), EVP_sha256(), nullptr) != 1) { + throw std::runtime_error{"cannot initialize SHA-256"}; + } + std::ifstream input{path, std::ios::binary}; + if (!input) { + throw std::runtime_error{"cannot hash file: " + path.string()}; + } + std::array buffer{}; + while (input) { + input.read(buffer.data(), + static_cast(buffer.size())); + const auto count = input.gcount(); + if (count > 0 && + EVP_DigestUpdate(context.get(), buffer.data(), + static_cast(count)) != 1) { + throw std::runtime_error{"cannot update SHA-256"}; + } + } + if (!input.eof()) { + throw std::runtime_error{"cannot read file while hashing: " + + path.string()}; + } + std::array digest{}; + unsigned int length{}; + if (EVP_DigestFinal_ex(context.get(), digest.data(), &length) != 1 || + length != 32U) { + throw std::runtime_error{"cannot finalize SHA-256"}; + } + static constexpr char hex[] = "0123456789abcdef"; + std::string result(length * 2U, '0'); + for (unsigned int index{}; index < length; ++index) { + result[index * 2U] = hex[digest[index] >> 4U]; + result[index * 2U + 1U] = hex[digest[index] & 0x0FU]; + } + return result; + } + + void validateRelease(const fs::path& release, + const std::string& expectedVersion, + const std::string& expectedManifestSha256) + { + const fs::path root = fs::canonical(release); + const auto rootStatus = fs::symlink_status(release); + if (!fs::is_directory(rootStatus) || fs::is_symlink(rootStatus)) { + throw std::runtime_error{"release root is not a real directory"}; + } + rejectWritable(root, rootStatus); + const fs::path manifestPath = root / "manifest.json"; + if (!expectedManifestSha256.empty() && + sha256File(manifestPath) != expectedManifestSha256) { + throw std::runtime_error{"release manifest SHA-256 mismatch"}; + } + const std::string manifestBytes = + readBounded(manifestPath, kMaximumJsonBytes); + const Json manifestValue = JsonParser{manifestBytes}.parse(); + const auto& manifest = object(manifestValue, "release manifest"); + if (integer(manifest, "schemaVersion") != 2 || + string(manifest, "version") != expectedVersion || + string(manifest, "executable") != "bin/echoiond" || + string(manifest, "updater") != "bin/echoion-updater" || + string(manifest, "core") != "lib/Echoion.ts") { + throw std::runtime_error{"release manifest identity is invalid"}; + } + const auto& entries = + array(required(manifest, "files"), "manifest files"); + if (entries.empty() || entries.size() > kMaximumManifestEntries) { + throw std::runtime_error{"release manifest entry count is invalid"}; + } + + std::map declared; + for (const Json& entryValue : entries) { + const auto& entry = object(entryValue, "manifest entry"); + const std::string& relative = string(entry, "path"); + const auto parts = pathParts(relative); + if (!declared.emplace(relative, string(entry, "type")).second) { + throw std::runtime_error{"duplicate manifest path: " + + relative}; + } + const fs::path path = joinedPath(root, parts); + const auto status = fs::symlink_status(path); + if (string(entry, "type") == "file") { + if (!fs::is_regular_file(status) || fs::is_symlink(status)) { + throw std::runtime_error{"manifest file is missing: " + + relative}; + } + rejectWritable(path, status); + const std::int64_t size = integer(entry, "size"); + if (size < 0 || + static_cast(size) != fs::file_size(path) || + !safeDigest(string(entry, "sha256")) || + sha256File(path) != string(entry, "sha256") || + mode(status) != parseMode(string(entry, "mode"))) { + throw std::runtime_error{ + "manifest file verification failed: " + relative}; + } + } else if (string(entry, "type") == "symlink") { + if (!fs::is_symlink(status)) { + throw std::runtime_error{"manifest symlink is missing: " + + relative}; + } + const std::string& target = string(entry, "target"); + static_cast( + pathParts(std::string{parts.front()} + "/" + target)); + if (fs::read_symlink(path).generic_string() != target) { + throw std::runtime_error{ + "manifest symlink target mismatch: " + relative}; + } + const fs::path resolved = fs::canonical(path); + if (!within(resolved, root)) { + throw std::runtime_error{ + "manifest symlink escapes release: " + relative}; + } + } else { + throw std::runtime_error{"invalid manifest entry type"}; + } + } + + std::map actual; + for (const std::string_view rootName : + {"bin", "lib", "service", "share"}) { + const fs::path directory = root / rootName; + const auto status = fs::symlink_status(directory); + if (!fs::is_directory(status) || fs::is_symlink(status)) { + throw std::runtime_error{ + "immutable release directory is missing"}; + } + rejectWritable(directory, status); + for (const auto& entry : + fs::recursive_directory_iterator{directory}) { + const auto entryStatus = entry.symlink_status(); + if (fs::is_directory(entryStatus)) { + rejectWritable(entry.path(), entryStatus); + continue; + } + if (!fs::is_regular_file(entryStatus) && + !fs::is_symlink(entryStatus)) { + throw std::runtime_error{"release contains a special file"}; + } + actual.emplace( + entry.path().lexically_relative(root).generic_string(), + fs::is_symlink(entryStatus) ? "symlink" : "file"); + } + } + if (actual != declared) { + throw std::runtime_error{ + "release manifest does not cover the immutable tree"}; + } + + static const std::map requiredFiles{ + {"bin/echoiond", "file"}, + {"bin/echoion-updater", "file"}, + {"lib/Echoion.ts", "file"}, + {"share/echoion/web/index.html", "file"}, + {"share/echoion/config.example.json", "file"}, + {"share/echoion/tools/validate-release-manifest.py", "file"}, + {"service/echoion.service.in", "file"}, + {"service/echoion-updater.service.in", "file"}, + {"service/echoion-updater.timer.in", "file"}, + }; + for (const auto& [path, type] : requiredFiles) { + if (!declared.contains(path) || declared.at(path) != type) { + throw std::runtime_error{"required release file is missing: " + + path}; + } + } + if (::access((root / "bin/echoiond").c_str(), X_OK) != 0 || + ::access((root / "bin/echoion-updater").c_str(), X_OK) != 0) { + throw std::runtime_error{"release executables are not executable"}; + } + } + + void copyAndValidateRelease(const int sourceDirectoryDescriptor, + const fs::path& destination, + const RuntimeActivation& activation) + { + struct stat sourceMetadata{}; + if (sourceDirectoryDescriptor < 0 || + ::fstat(sourceDirectoryDescriptor, &sourceMetadata) != 0 || + !S_ISDIR(sourceMetadata.st_mode)) { + throw std::runtime_error{ + "staged release descriptor is not a directory"}; + } + requireOwnedSource(sourceMetadata, sourceMetadata.st_uid, "."); + + const fs::path destinationParentPath = destination.parent_path(); + const std::string destinationName = destination.filename().string(); + requireEntryName(destinationName); + if (destinationParentPath.empty() || + destination != destinationParentPath / destinationName) { + throw std::runtime_error{"runtime destination path is invalid"}; + } + FileDescriptor destinationParent{ + ::open(destinationParentPath.c_str(), + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)}; + if (destinationParent.get() < 0) { + throw systemError("cannot open runtime destination directory"); + } + struct stat existing{}; + if (::fstatat(destinationParent.get(), destinationName.c_str(), + &existing, AT_SYMLINK_NOFOLLOW) == 0 || + errno != ENOENT) { + throw std::runtime_error{"runtime destination already exists"}; + } + if (::mkdirat(destinationParent.get(), destinationName.c_str(), 0700) != + 0) { + throw systemError("cannot create private runtime destination"); + } + try { + const FileDescriptor destinationDirectory = + openDirectoryAt(destinationParent.get(), destinationName, + "private runtime destination"); + CopyBudget budget; + copyRegularAt(sourceDirectoryDescriptor, "manifest.json", + destinationDirectory.get(), "manifest.json", + sourceMetadata.st_uid, 1U, budget, kMaximumJsonBytes); + for (const std::string_view root : + {"bin", "lib", "service", "share"}) { + copyNodeAt(sourceDirectoryDescriptor, root, + destinationDirectory.get(), root, + sourceMetadata.st_uid, 1U, budget); + } + struct stat sourceAfter{}; + if (::fstat(sourceDirectoryDescriptor, &sourceAfter) != 0 || + !sameOpenedNode(sourceMetadata, sourceAfter)) { + throw std::runtime_error{ + "staged release root changed while it was copied"}; + } + validateRelease(destination, activation.version, + activation.manifestSha256); + std::size_t syncedEntries{1U}; + syncTreeAt(destinationDirectory.get(), 1U, syncedEntries); + if (::fchmod(destinationDirectory.get(), + sourceMetadata.st_mode & 07777U) != 0) { + throw systemError("cannot publish runtime destination mode"); + } + if (::fsync(destinationDirectory.get()) != 0 || + ::fsync(destinationParent.get()) != 0) { + throw systemError( + "cannot sync runtime destination publication"); + } + } catch (...) { + const std::exception_ptr failure = std::current_exception(); + try { + std::size_t removedEntries{1U}; + removeTreeAt(destinationParent.get(), destinationName, 1U, + removedEntries); + static_cast(::fsync(destinationParent.get())); + } catch (...) { + // Preserve the validation or copy failure that caused cleanup. + } + std::rethrow_exception(failure); + } + } + + void removeReleaseTreeAt(const int parentDirectoryDescriptor, + const std::string_view name) + { + struct stat parentMetadata{}; + if (parentDirectoryDescriptor < 0 || + ::fstat(parentDirectoryDescriptor, &parentMetadata) != 0 || + !S_ISDIR(parentMetadata.st_mode)) { + throw std::runtime_error{ + "release cleanup parent descriptor is not a directory"}; + } + std::size_t removedEntries{1U}; + removeTreeAt(parentDirectoryDescriptor, name, 1U, removedEntries); + if (::fsync(parentDirectoryDescriptor) != 0) { + throw systemError("cannot sync release cleanup directory"); + } + } + + void syncReleaseTree(const fs::path& root) + { + FileDescriptor directory{::open( + root.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)}; + if (directory.get() < 0) { + throw systemError("cannot open release directory for sync"); + } + std::size_t syncedEntries{1U}; + syncTreeAt(directory.get(), 1U, syncedEntries); + } + +} // namespace Echoion::Updater diff --git a/ReleaseTree.hpp b/ReleaseTree.hpp new file mode 100644 index 0000000..1025ff2 --- /dev/null +++ b/ReleaseTree.hpp @@ -0,0 +1,61 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace Echoion::Updater +{ + + struct RuntimeActivation { + std::string stagingId; + std::string version; + std::string manifestSha256; + std::uint32_t retainHealthyVersions = 2; + }; + + struct RuntimeRollback { + std::string version; + std::uint32_t retainHealthyVersions = 2; + }; + + struct RuntimeCommit { + std::string version; + std::uint32_t retainHealthyVersions = 2; + }; + + struct PendingRuntime { + std::string candidateId; + std::string version; + std::string previousVersion; + std::string manifestSha256; + std::string activatedAt; + std::uint32_t retainHealthyVersions = 2; + }; + + using PrivilegedRequest = + std::variant; + + [[nodiscard]] RuntimeActivation + parseActivationRequest(std::string_view json); + [[nodiscard]] PrivilegedRequest + parsePrivilegedRequest(std::string_view json); + [[nodiscard]] PendingRuntime parsePendingRuntime(std::string_view json); + + [[nodiscard]] std::string sha256File(const std::filesystem::path& path); + + void copyAndValidateRelease(int sourceDirectoryDescriptor, + const std::filesystem::path& destination, + const RuntimeActivation& activation); + void removeReleaseTreeAt(int parentDirectoryDescriptor, + std::string_view name); + + void validateRelease(const std::filesystem::path& release, + const std::string& expectedVersion, + const std::string& expectedManifestSha256 = {}); + + void syncReleaseTree(const std::filesystem::path& root); + +} // namespace Echoion::Updater diff --git a/ReleaseTreeSecurityTests.cpp b/ReleaseTreeSecurityTests.cpp new file mode 100644 index 0000000..2fdc185 --- /dev/null +++ b/ReleaseTreeSecurityTests.cpp @@ -0,0 +1,282 @@ +#include "ReleaseTree.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace +{ + namespace fs = std::filesystem; + + class FileDescriptor final + { + public: + + explicit FileDescriptor(const int descriptor) noexcept + : descriptor_{descriptor} + { + } + + ~FileDescriptor() + { + if (descriptor_ >= 0) { + ::close(descriptor_); + } + } + + FileDescriptor(const FileDescriptor&) = delete; + FileDescriptor& operator=(const FileDescriptor&) = delete; + FileDescriptor(FileDescriptor&&) = delete; + FileDescriptor& operator=(FileDescriptor&&) = delete; + + [[nodiscard]] int get() const noexcept { return descriptor_; } + + private: + + int descriptor_; + }; + + class TemporaryDirectory final + { + public: + + TemporaryDirectory() + { + const std::string value = + (fs::temp_directory_path() / "echoion-release-tree.XXXXXX") + .string(); + std::vector pattern{value.begin(), value.end()}; + pattern.push_back('\0'); + if (::mkdtemp(pattern.data()) == nullptr) { + throw std::system_error{ + errno, std::generic_category(), + "cannot create temporary directory"}; + } + path_ = pattern.data(); + } + + ~TemporaryDirectory() + { + std::error_code ignored; + fs::remove_all(path_, ignored); + } + + TemporaryDirectory(const TemporaryDirectory&) = delete; + TemporaryDirectory& operator=(const TemporaryDirectory&) = delete; + TemporaryDirectory(TemporaryDirectory&&) = delete; + TemporaryDirectory& operator=(TemporaryDirectory&&) = delete; + + [[nodiscard]] const fs::path& path() const noexcept + { + return path_; + } + + private: + + fs::path path_; + }; + + void setMode(const fs::path& path, const mode_t mode) + { + if (::chmod(path.c_str(), mode) != 0) { + throw std::system_error{errno, std::generic_category(), + "cannot set test path mode"}; + } + } + + void createDirectory(const fs::path& path) + { + fs::create_directory(path); + setMode(path, 0755); + } + + void createFile(const fs::path& path, const std::string_view bytes) + { + std::ofstream output{path, std::ios::binary | std::ios::trunc}; + output.write(bytes.data(), static_cast(bytes.size())); + if (!output) { + throw std::runtime_error{"cannot create test file"}; + } + output.close(); + setMode(path, 0644); + } + + [[nodiscard]] FileDescriptor openDirectory(const fs::path& path) + { + const int descriptor = ::open( + path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW); + if (descriptor < 0) { + throw std::system_error{errno, std::generic_category(), + "cannot open test directory"}; + } + return FileDescriptor{descriptor}; + } + + void expectFailure(const std::function& operation, + const std::string_view expected) + { + try { + operation(); + } catch (const std::exception& error) { + if (std::string_view{error.what()}.find(expected) == + std::string_view::npos) { + throw std::runtime_error{"unexpected failure: " + + std::string{error.what()}}; + } + return; + } + throw std::runtime_error{"operation unexpectedly succeeded"}; + } + + [[nodiscard]] Echoion::Updater::RuntimeActivation activation() + { + return {.stagingId = "security-test", + .version = "security-test", + .manifestSha256 = {}}; + } + + void testOversizedFileRejectedBeforeCopy() + { + TemporaryDirectory temporary; + const fs::path source = temporary.path() / "source"; + const fs::path versions = temporary.path() / "versions"; + createDirectory(source); + createDirectory(versions); + + const fs::path manifest = source / "manifest.json"; + FileDescriptor file{::open( + manifest.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644)}; + if (file.get() < 0 || + ::ftruncate( + file.get(), + static_cast(3ULL * 1024ULL * 1024ULL * 1024ULL)) != 0) { + throw std::system_error{errno, std::generic_category(), + "cannot create sparse oversized file"}; + } + + const FileDescriptor sourceDescriptor = openDirectory(source); + const fs::path replacement = temporary.path() / "replacement"; + createDirectory(replacement); + createFile(replacement / "manifest.json", "replacement\n"); + fs::rename(source, temporary.path() / "pinned-source"); + fs::create_directory_symlink(replacement, source); + const fs::path destination = versions / ".incoming-oversized"; + expectFailure( + [&] { + Echoion::Updater::copyAndValidateRelease( + sourceDescriptor.get(), destination, activation()); + }, + "file exceeds size limit"); + if (fs::symlink_status(destination).type() != + fs::file_type::not_found) { + throw std::runtime_error{ + "failed oversized copy left a destination tree"}; + } + } + + void testManifestSymlinkIsNeverFollowed() + { + TemporaryDirectory temporary; + const fs::path source = temporary.path() / "source"; + const fs::path versions = temporary.path() / "versions"; + const fs::path secret = temporary.path() / "secret"; + createDirectory(source); + createDirectory(versions); + createFile(secret, "must-not-be-copied\n"); + fs::create_symlink(secret, source / "manifest.json"); + + const FileDescriptor sourceDescriptor = openDirectory(source); + const fs::path destination = versions / ".incoming-symlink"; + expectFailure( + [&] { + Echoion::Updater::copyAndValidateRelease( + sourceDescriptor.get(), destination, activation()); + }, + "cannot open staged release file"); + if (fs::symlink_status(destination).type() != + fs::file_type::not_found) { + throw std::runtime_error{ + "failed symlink copy left a destination tree"}; + } + } + + void testExcessiveDepthRejected() + { + TemporaryDirectory temporary; + const fs::path source = temporary.path() / "source"; + const fs::path versions = temporary.path() / "versions"; + createDirectory(source); + createDirectory(versions); + createFile(source / "manifest.json", "{}\n"); + for (const std::string_view root : {"bin", "lib", "service", "share"}) { + createDirectory(source / root); + } + fs::path nested = source / "bin"; + for (std::size_t depth{}; depth < 70U; ++depth) { + nested /= "d"; + createDirectory(nested); + } + + const FileDescriptor sourceDescriptor = openDirectory(source); + const fs::path destination = versions / ".incoming-deep"; + expectFailure( + [&] { + Echoion::Updater::copyAndValidateRelease( + sourceDescriptor.get(), destination, activation()); + }, + "maximum directory depth"); + if (fs::symlink_status(destination).type() != + fs::file_type::not_found) { + throw std::runtime_error{ + "failed deep copy left a destination tree"}; + } + } + + void testDescriptorRelativeCleanupDoesNotFollowSymlink() + { + TemporaryDirectory temporary; + const fs::path parent = temporary.path() / "parent"; + const fs::path victim = temporary.path() / "victim"; + createDirectory(parent); + createDirectory(victim); + createFile(victim / "sentinel", "unchanged\n"); + fs::create_symlink(victim, parent / "candidate"); + + const FileDescriptor parentDescriptor = openDirectory(parent); + expectFailure( + [&] { + Echoion::Updater::removeReleaseTreeAt(parentDescriptor.get(), + "../victim"); + }, + "unsafe path component"); + Echoion::Updater::removeReleaseTreeAt(parentDescriptor.get(), + "candidate"); + if (fs::symlink_status(parent / "candidate").type() != + fs::file_type::not_found || + !fs::is_regular_file(victim / "sentinel")) { + throw std::runtime_error{ + "descriptor-relative cleanup followed a symlink"}; + } + } + +} // namespace + +int main() +{ + testOversizedFileRejectedBeforeCopy(); + testManifestSymlinkIsNeverFollowed(); + testExcessiveDepthRejected(); + testDescriptorRelativeCleanupDoesNotFollowSymlink(); +} diff --git a/echoion-updater.cpp b/echoion-updater.cpp new file mode 100644 index 0000000..0bc8e31 --- /dev/null +++ b/echoion-updater.cpp @@ -0,0 +1,1982 @@ +#include "ReleaseTree.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 + +namespace +{ + + namespace fs = std::filesystem; + + constexpr std::string_view kProgramName{"echoion-updater"}; + constexpr std::uintmax_t kMaximumRequestBytes{64U * 1024U}; + constexpr std::uint32_t kDefaultRetainedVersions{2U}; + constexpr auto kRuntimeHealthGrace = std::chrono::seconds{60}; + + class UpdateError final : public std::runtime_error + { + public: + + using std::runtime_error::runtime_error; + }; + + class FileDescriptor final + { + public: + + explicit FileDescriptor(const int descriptor = -1) noexcept + : descriptor_{descriptor} + { + } + ~FileDescriptor() + { + if (descriptor_ >= 0) { + ::close(descriptor_); + } + } + + FileDescriptor(const FileDescriptor&) = delete; + FileDescriptor& operator=(const FileDescriptor&) = delete; + FileDescriptor(FileDescriptor&& other) noexcept + : descriptor_{std::exchange(other.descriptor_, -1)} + { + } + FileDescriptor& operator=(FileDescriptor&& other) noexcept + { + if (this != &other) { + if (descriptor_ >= 0) { + ::close(descriptor_); + } + descriptor_ = std::exchange(other.descriptor_, -1); + } + return *this; + } + + [[nodiscard]] int get() const noexcept { return descriptor_; } + + private: + + int descriptor_{-1}; + }; + + struct DirectoryCloser { + void operator()(DIR* directory) const noexcept + { + if (directory != nullptr) { + ::closedir(directory); + } + } + }; + + using Directory = std::unique_ptr; + + [[nodiscard]] std::string systemError(const std::string_view operation) + { + return std::string{operation} + ": " + std::strerror(errno); + } + + [[nodiscard]] bool safeIdentifier(const std::string_view value) + { + static const std::regex pattern{R"(^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$)"}; + return std::regex_match(value.begin(), value.end(), pattern) && + value != "." && value != ".."; + } + + [[nodiscard]] bool safeDigest(const std::string_view value) + { + static const std::regex pattern{R"(^[0-9a-f]{64}$)"}; + return std::regex_match(value.begin(), value.end(), pattern); + } + + [[nodiscard]] std::string jsonEscape(const std::string_view value) + { + std::ostringstream output; + for (const char rawCharacter : value) { + const auto character = static_cast(rawCharacter); + switch (character) { + case '\\': + output << "\\\\"; + break; + case '"': + output << "\\\""; + break; + case '\b': + output << "\\b"; + break; + case '\f': + output << "\\f"; + break; + case '\n': + output << "\\n"; + break; + case '\r': + output << "\\r"; + break; + case '\t': + output << "\\t"; + break; + default: + if (character < 0x20U) { + output << "\\u" << std::hex << std::setw(4) + << std::setfill('0') + << static_cast(character) + << std::dec; + } else { + output << static_cast(character); + } + } + } + return output.str(); + } + + [[nodiscard]] std::string nowUtc() + { + const auto now = std::chrono::system_clock::now(); + const std::time_t value = std::chrono::system_clock::to_time_t(now); + std::tm utc{}; + if (::gmtime_r(&value, &utc) == nullptr) { + throw UpdateError{"cannot format the current time"}; + } + std::ostringstream output; + output << std::put_time(&utc, "%Y-%m-%dT%H:%M:%SZ"); + return output.str(); + } + + [[nodiscard]] std::string requestId() + { + std::random_device random; + std::array words{}; + std::generate(words.begin(), words.end(), + [&random] { return random(); }); + std::ostringstream output; + output << std::hex << std::setfill('0'); + for (const auto word : words) { + output << std::setw(8) << word; + } + return output.str(); + } + + [[nodiscard]] fs::path + canonicalDirectory(const fs::path& path, + const std::string_view description) + { + std::error_code error; + const auto status = fs::symlink_status(path, error); + if (error || !fs::is_directory(status) || fs::is_symlink(status)) { + throw UpdateError{std::string{description} + + " is not a real directory: " + path.string()}; + } + const auto canonical = fs::canonical(path, error); + if (error) { + throw UpdateError{"cannot resolve " + std::string{description} + + ": " + error.message()}; + } + return canonical; + } + + void requireRegularFile(const fs::path& path, + const std::string_view description, + const bool executable = false) + { + std::error_code error; + const auto status = fs::symlink_status(path, error); + if (error || !fs::is_regular_file(status) || fs::is_symlink(status)) { + throw UpdateError{std::string{description} + + " is not a regular file: " + path.string()}; + } + if (executable && (::access(path.c_str(), X_OK) != 0)) { + throw UpdateError{std::string{description} + + " is not executable: " + path.string()}; + } + } + + class PrefixLock final + { + public: + + explicit PrefixLock(const fs::path& root) + : descriptor_{ + ::open(root.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC)} + { + if (descriptor_.get() < 0) { + throw UpdateError{ + systemError("cannot open installation root")}; + } + if (::flock(descriptor_.get(), LOCK_EX | LOCK_NB) != 0) { + throw UpdateError{ + errno == EWOULDBLOCK + ? "another install, uninstall, or update is active" + : systemError("cannot lock installation root")}; + } + } + + private: + + FileDescriptor descriptor_; + }; + + [[nodiscard]] std::map + loadInstallRecord(const fs::path& root) + { + const fs::path path = root / ".echoion-install"; + requireRegularFile(path, "install record"); + std::ifstream input{path}; + if (!input) { + throw UpdateError{"cannot open install record: " + path.string()}; + } + std::map values; + std::string line; + while (std::getline(input, line)) { + const auto separator = line.find('='); + if (separator == std::string::npos || separator == 0U) { + throw UpdateError{"install record contains an invalid line"}; + } + values.emplace(line.substr(0, separator), + line.substr(separator + 1U)); + } + if (values["format"] != "1") { + throw UpdateError{"unsupported install record format"}; + } + return values; + } + + [[nodiscard]] fs::path + resolveRecordedPath(const fs::path& root, + const std::map& record, + const std::string_view key) + { + const auto iterator = record.find(std::string{key}); + if (iterator == record.end() || iterator->second.empty()) { + throw UpdateError{"install record has no " + std::string{key}}; + } + fs::path path{iterator->second}; + if (path.is_relative()) { + path = root / path; + } + return fs::weakly_canonical(path); + } + + [[nodiscard]] std::string currentVersion(const fs::path& root) + { + const fs::path current = root / "current"; + std::error_code error; + const auto status = fs::symlink_status(current, error); + if (error || !fs::is_symlink(status)) { + throw UpdateError{"current release link is missing"}; + } + const fs::path target = fs::read_symlink(current, error); + if (error || target.is_absolute() || + target.parent_path() != "versions" || + !safeIdentifier(target.filename().string())) { + throw UpdateError{"current release link has an unsafe target"}; + } + return target.filename().string(); + } + + [[nodiscard]] fs::path validateRelease(const fs::path& root, + const std::string_view version) + { + if (!safeIdentifier(version)) { + throw UpdateError{"unsafe release version"}; + } + const fs::path versions = + canonicalDirectory(root / "versions", "versions directory"); + const fs::path release = + canonicalDirectory(versions / version, "release directory"); + if (release.parent_path() != versions) { + throw UpdateError{"release directory escapes versions"}; + } + requireRegularFile(release / "manifest.json", "release manifest"); + requireRegularFile(release / "bin/echoiond", "Echoion daemon", true); + requireRegularFile(release / "bin/echoion-updater", "Echoion updater", + true); + requireRegularFile(release / "lib/Echoion.ts", "Echoion Core"); + return release; + } + + [[nodiscard]] std::vector + installedVersions(const fs::path& root) + { + const fs::path versions = + canonicalDirectory(root / "versions", "versions directory"); + std::vector> candidates; + for (const auto& entry : fs::directory_iterator{versions}) { + const std::string name = entry.path().filename().string(); + std::error_code error; + const auto status = entry.symlink_status(error); + if (error || !fs::is_directory(status) || fs::is_symlink(status) || + !safeIdentifier(name)) { + continue; + } + try { + static_cast(validateRelease(root, name)); + candidates.emplace_back(entry.last_write_time(), name); + } catch (const UpdateError&) { + // An incomplete staging directory is not an installed version. + } + } + std::ranges::sort(candidates, std::greater{}); + std::vector result; + result.reserve(candidates.size()); + std::ranges::transform(candidates, std::back_inserter(result), + [](const auto& item) { return item.second; }); + return result; + } + + void syncDirectory(const fs::path& directory) + { + const FileDescriptor descriptor{ + ::open(directory.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC)}; + if (descriptor.get() < 0 || ::fsync(descriptor.get()) != 0) { + throw UpdateError{systemError("cannot sync directory")}; + } + } + + void atomicWrite(const fs::path& destination, const std::string_view bytes, + const mode_t mode = 0600) + { + fs::create_directories(destination.parent_path()); + const fs::path temporary = + destination.parent_path() / + ("." + destination.filename().string() + "." + + std::to_string(::getpid()) + "." + requestId()); + const FileDescriptor descriptor{::open( + temporary.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, mode)}; + if (descriptor.get() < 0) { + throw UpdateError{ + systemError("cannot create temporary updater file")}; + } + if (::fchmod(descriptor.get(), mode) != 0) { + fs::remove(temporary); + throw UpdateError{systemError("cannot set updater file mode")}; + } + std::size_t offset{}; + while (offset < bytes.size()) { + const auto written = ::write( + descriptor.get(), bytes.data() + offset, bytes.size() - offset); + if (written < 0) { + if (errno == EINTR) { + continue; + } + fs::remove(temporary); + throw UpdateError{systemError("cannot write updater file")}; + } + if (written == 0) { + fs::remove(temporary); + throw UpdateError{"short write while publishing updater file"}; + } + offset += static_cast(written); + } + if (::fsync(descriptor.get()) != 0) { + fs::remove(temporary); + throw UpdateError{systemError("cannot sync updater file")}; + } + std::error_code error; + fs::rename(temporary, destination, error); + if (error) { + fs::remove(temporary); + throw UpdateError{"cannot publish updater file: " + + error.message()}; + } + syncDirectory(destination.parent_path()); + } + + [[nodiscard]] std::string + readRegularFileNoFollow(const fs::path& path, + const std::size_t maximumBytes) + { + const FileDescriptor descriptor{ + ::open(path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)}; + if (descriptor.get() < 0) { + throw UpdateError{systemError("cannot open updater request")}; + } + struct stat metadata{}; + if (::fstat(descriptor.get(), &metadata) != 0 || + !S_ISREG(metadata.st_mode) || metadata.st_size < 0 || + static_cast(metadata.st_size) > maximumBytes) { + throw UpdateError{"updater request is not a bounded regular file"}; + } + std::string result(static_cast(metadata.st_size), '\0'); + std::size_t offset{}; + while (offset < result.size()) { + const auto count = ::read(descriptor.get(), result.data() + offset, + result.size() - offset); + if (count < 0) { + if (errno == EINTR) { + continue; + } + throw UpdateError{systemError("cannot read updater request")}; + } + if (count == 0) { + throw UpdateError{ + "updater request ended before its recorded size"}; + } + offset += static_cast(count); + } + char extra{}; + if (::read(descriptor.get(), &extra, 1U) != 0) { + throw UpdateError{"updater request changed while it was read"}; + } + return result; + } + + void requireLeafName(const std::string_view name) + { + if (name.empty() || name == "." || name == ".." || name.contains('/') || + name.contains('\0')) { + throw UpdateError{"unsafe updater state entry name"}; + } + } + + void syncDirectoryDescriptor(const int descriptor, + const std::string_view description) + { + if (::fsync(descriptor) != 0) { + throw UpdateError{systemError(description)}; + } + } + + [[nodiscard]] FileDescriptor + openRealDirectory(const fs::path& path, + const std::string_view description) + { + FileDescriptor descriptor{::open( + path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)}; + struct stat metadata{}; + if (descriptor.get() < 0 || ::fstat(descriptor.get(), &metadata) != 0 || + !S_ISDIR(metadata.st_mode)) { + throw UpdateError{"cannot pin " + std::string{description} + ": " + + (descriptor.get() < 0 ? std::strerror(errno) + : "not a directory")}; + } + return descriptor; + } + + [[nodiscard]] FileDescriptor openDirectoryAt(const int parent, + const std::string_view name, + const mode_t mode = 0750) + { + requireLeafName(name); + const std::string ownedName{name}; + bool created{false}; + if (::mkdirat(parent, ownedName.c_str(), mode) == 0) { + created = true; + } else if (errno != EEXIST) { + throw UpdateError{ + systemError("cannot create updater state directory")}; + } + FileDescriptor descriptor{ + ::openat(parent, ownedName.c_str(), + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)}; + struct stat metadata{}; + if (descriptor.get() < 0 || ::fstat(descriptor.get(), &metadata) != 0 || + !S_ISDIR(metadata.st_mode)) { + throw UpdateError{"updater state entry is not a real directory: " + + ownedName}; + } + if (created) { + struct stat parentMetadata{}; + if (::fstat(parent, &parentMetadata) != 0 || + ::fchown(descriptor.get(), parentMetadata.st_uid, + parentMetadata.st_gid) != 0 || + ::fchmod(descriptor.get(), mode) != 0) { + throw UpdateError{ + systemError("cannot initialize updater state directory")}; + } + syncDirectoryDescriptor(parent, "cannot sync updater state parent"); + } + return descriptor; + } + + class UpdateDirectories final + { + public: + + explicit UpdateDirectories(const fs::path& root) + { + const auto record = loadInstallRecord(root); + const fs::path statePath = + resolveRecordedPath(root, record, "state_dir"); + state_ = openRealDirectory(statePath, "state directory"); + updates_ = openDirectoryAt(state_.get(), "updates"); + privilegedRequests_ = + openDirectoryAt(updates_.get(), "privileged-requests"); + processed_ = openDirectoryAt(updates_.get(), "processed"); + rejected_ = openDirectoryAt(updates_.get(), "rejected"); + staged_ = openDirectoryAt(updates_.get(), "staged"); + path_ = statePath / "updates"; + } + + [[nodiscard]] int updates() const noexcept + { + return updates_.get(); + } + [[nodiscard]] int privilegedRequests() const noexcept + { + return privilegedRequests_.get(); + } + [[nodiscard]] int processed() const noexcept + { + return processed_.get(); + } + [[nodiscard]] int rejected() const noexcept + { + return rejected_.get(); + } + [[nodiscard]] int staged() const noexcept { return staged_.get(); } + [[nodiscard]] const fs::path& path() const noexcept + { + return path_; + } + + private: + + fs::path path_; + FileDescriptor state_; + FileDescriptor updates_; + FileDescriptor privilegedRequests_; + FileDescriptor processed_; + FileDescriptor rejected_; + FileDescriptor staged_; + }; + + void writeAll(const int descriptor, const std::string_view bytes) + { + std::size_t offset{}; + while (offset < bytes.size()) { + const auto written = ::write(descriptor, bytes.data() + offset, + bytes.size() - offset); + if (written < 0) { + if (errno == EINTR) { + continue; + } + throw UpdateError{systemError("cannot write updater state")}; + } + if (written == 0) { + throw UpdateError{"short write while publishing updater state"}; + } + offset += static_cast(written); + } + } + + void atomicWriteAt(const int directory, const std::string_view name, + const std::string_view bytes, const mode_t mode = 0600) + { + requireLeafName(name); + const std::string ownedName{name}; + const std::string temporary = "." + ownedName + "." + + std::to_string(::getpid()) + "." + + requestId(); + FileDescriptor descriptor{::openat( + directory, temporary.c_str(), + O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK, + mode)}; + if (descriptor.get() < 0) { + throw UpdateError{ + systemError("cannot create temporary updater state")}; + } + try { + if (::fchmod(descriptor.get(), mode) != 0) { + throw UpdateError{ + systemError("cannot set updater state file mode")}; + } + writeAll(descriptor.get(), bytes); + if (::fsync(descriptor.get()) != 0) { + throw UpdateError{ + systemError("cannot sync updater state file")}; + } + if (::renameat(directory, temporary.c_str(), directory, + ownedName.c_str()) != 0) { + throw UpdateError{systemError("cannot publish updater state")}; + } + } catch (...) { + static_cast(::unlinkat(directory, temporary.c_str(), 0)); + throw; + } + syncDirectoryDescriptor(directory, + "cannot sync updater state directory"); + } + + [[nodiscard]] bool fileExistsAt(const int directory, + const std::string_view name) + { + requireLeafName(name); + const std::string ownedName{name}; + struct stat metadata{}; + if (::fstatat(directory, ownedName.c_str(), &metadata, + AT_SYMLINK_NOFOLLOW) == 0) { + if (!S_ISREG(metadata.st_mode) || metadata.st_nlink != 1) { + throw UpdateError{ + "updater state entry is not a singly linked regular file"}; + } + return true; + } + if (errno == ENOENT) { + return false; + } + throw UpdateError{systemError("cannot inspect updater state entry")}; + } + + [[nodiscard]] std::string readRegularFileAt(const int directory, + const std::string_view name, + const std::size_t maximumBytes) + { + requireLeafName(name); + const std::string ownedName{name}; + const FileDescriptor descriptor{ + ::openat(directory, ownedName.c_str(), + O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)}; + if (descriptor.get() < 0) { + throw UpdateError{systemError("cannot open updater state entry")}; + } + struct stat before{}; + if (::fstat(descriptor.get(), &before) != 0 || + !S_ISREG(before.st_mode) || before.st_nlink != 1 || + before.st_size < 0 || + static_cast(before.st_size) > maximumBytes) { + throw UpdateError{ + "updater state entry is not a bounded regular file"}; + } + std::string result(static_cast(before.st_size), '\0'); + std::size_t offset{}; + while (offset < result.size()) { + const auto count = ::read(descriptor.get(), result.data() + offset, + result.size() - offset); + if (count < 0) { + if (errno == EINTR) { + continue; + } + throw UpdateError{ + systemError("cannot read updater state entry")}; + } + if (count == 0) { + throw UpdateError{ + "updater state entry ended before its recorded size"}; + } + offset += static_cast(count); + } + char extra{}; + ssize_t extraCount{}; + do { + extraCount = ::read(descriptor.get(), &extra, 1U); + } while (extraCount < 0 && errno == EINTR); + struct stat after{}; + if (extraCount != 0 || ::fstat(descriptor.get(), &after) != 0 || + before.st_dev != after.st_dev || before.st_ino != after.st_ino || + before.st_size != after.st_size || + before.st_mtim.tv_sec != after.st_mtim.tv_sec || + before.st_mtim.tv_nsec != after.st_mtim.tv_nsec || + before.st_ctim.tv_sec != after.st_ctim.tv_sec || + before.st_ctim.tv_nsec != after.st_ctim.tv_nsec) { + throw UpdateError{"updater state entry changed while it was read"}; + } + return result; + } + + void unlinkFileAt(const int directory, const std::string_view name) + { + requireLeafName(name); + const std::string ownedName{name}; + if (::unlinkat(directory, ownedName.c_str(), 0) != 0) { + throw UpdateError{systemError("cannot remove updater state entry")}; + } + syncDirectoryDescriptor(directory, + "cannot sync updater state directory"); + } + + void moveFileAt(const int sourceDirectory, + const std::string_view sourceName, + const int destinationDirectory, + const std::string_view destinationName) + { + requireLeafName(sourceName); + requireLeafName(destinationName); + const std::string ownedSource{sourceName}; + const std::string ownedDestination{destinationName}; + if (::renameat(sourceDirectory, ownedSource.c_str(), + destinationDirectory, ownedDestination.c_str()) != 0) { + throw UpdateError{systemError("cannot move updater state entry")}; + } + syncDirectoryDescriptor(sourceDirectory, + "cannot sync updater source directory"); + if (sourceDirectory != destinationDirectory) { + syncDirectoryDescriptor( + destinationDirectory, + "cannot sync updater destination directory"); + } + } + + [[nodiscard]] std::vector + directoryEntries(const int descriptor, const std::size_t maximumEntries) + { + const int duplicate = ::fcntl(descriptor, F_DUPFD_CLOEXEC, 0); + if (duplicate < 0) { + throw UpdateError{ + systemError("cannot duplicate updater directory")}; + } + Directory directory{::fdopendir(duplicate)}; + if (!directory) { + ::close(duplicate); + throw UpdateError{ + systemError("cannot enumerate updater directory")}; + } + std::vector result; + errno = 0; + while (const dirent* entry = ::readdir(directory.get())) { + const std::string_view name{entry->d_name}; + if (name != "." && name != "..") { + if (result.size() >= maximumEntries) { + throw UpdateError{ + "updater directory contains too many entries"}; + } + result.emplace_back(name); + } + errno = 0; + } + if (errno != 0) { + throw UpdateError{ + systemError("cannot enumerate updater directory")}; + } + return result; + } + + void appendHistory(const UpdateDirectories& directories, + const std::string_view operation, + const std::string_view result, + const std::string_view detail) + { + const FileDescriptor descriptor{::openat( + directories.updates(), "history.jsonl", + O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK, + 0640)}; + if (descriptor.get() < 0) { + throw UpdateError{systemError("cannot open update history")}; + } + struct stat metadata{}; + if (::fstat(descriptor.get(), &metadata) != 0 || + !S_ISREG(metadata.st_mode) || metadata.st_nlink != 1) { + throw UpdateError{ + "update history is not a singly linked regular file"}; + } + if (::fchmod(descriptor.get(), 0640) != 0) { + throw UpdateError{systemError("cannot set update history mode")}; + } + const std::string record = + "{\"time\":\"" + jsonEscape(nowUtc()) + "\",\"operation\":\"" + + jsonEscape(operation) + "\",\"result\":\"" + jsonEscape(result) + + "\",\"detail\":\"" + jsonEscape(detail) + "\"}\n"; + std::size_t offset{}; + while (offset < record.size()) { + const auto written = + ::write(descriptor.get(), record.data() + offset, + record.size() - offset); + if (written < 0) { + if (errno == EINTR) { + continue; + } + throw UpdateError{systemError("cannot write update history")}; + } + if (written == 0) { + throw UpdateError{"short write while appending update history"}; + } + offset += static_cast(written); + } + if (::fsync(descriptor.get()) != 0) { + throw UpdateError{systemError("cannot sync update history")}; + } + } + + struct ParsedArguments { + fs::path root; + std::string command; + std::vector values; + }; + + [[nodiscard]] fs::path inferredRoot(const char* executable) + { + std::error_code error; + const fs::path resolved = fs::canonical(executable, error); + if (error || resolved.parent_path().filename() != "bin") { + throw UpdateError{"--root is required when the updater is not " + "installed under bin/"}; + } + const fs::path release = resolved.parent_path().parent_path(); + if (release.parent_path().filename() != "versions") { + throw UpdateError{ + "--root is required outside a versioned Echoion installation"}; + } + return release.parent_path().parent_path(); + } + + [[nodiscard]] ParsedArguments parseArguments(const int argc, char** argv) + { + ParsedArguments result; + int index{1}; + if (index + 1 < argc && std::string_view{argv[index]} == "--root") { + result.root = argv[index + 1]; + index += 2; + } else { + result.root = inferredRoot(argv[0]); + } + if (index >= argc) { + throw UpdateError{"a command is required"}; + } + result.command = argv[index++]; + for (; index < argc; ++index) { + result.values.emplace_back(argv[index]); + } + result.root = canonicalDirectory(result.root, "installation root"); + return result; + } + + [[nodiscard]] std::optional + optionValue(const std::vector& values, + const std::string_view option) + { + std::optional result; + for (std::size_t index{}; index < values.size(); ++index) { + if (values[index] != option) { + continue; + } + if (index + 1U >= values.size() || result.has_value()) { + throw UpdateError{"option requires one value: " + + std::string{option}}; + } + result = values[index + 1U]; + ++index; + } + return result; + } + + void ensureOnlyOptions(const std::vector& values, + const std::vector& allowed) + { + for (std::size_t index{}; index < values.size();) { + const auto iterator = std::ranges::find(allowed, values[index]); + if (iterator == allowed.end()) { + throw UpdateError{"unknown argument: " + values[index]}; + } + if (index + 1U >= values.size()) { + throw UpdateError{"missing value for argument: " + + values[index]}; + } + index += 2U; + } + } + + void status(const fs::path& root, const bool json) + { + const std::string current = currentVersion(root); + static_cast(validateRelease(root, current)); + const auto versions = installedVersions(root); + if (json) { + std::cout << "{\"schemaVersion\":1,\"root\":\"" + << jsonEscape(root.string()) << "\",\"current\":\"" + << jsonEscape(current) << "\",\"versions\":["; + for (std::size_t index{}; index < versions.size(); ++index) { + if (index != 0U) { + std::cout << ','; + } + std::cout << '"' << jsonEscape(versions[index]) << '"'; + } + std::cout << "]}\n"; + return; + } + std::cout << "Root: " << root << "\nCurrent: " << current + << "\nInstalled:"; + for (const auto& version : versions) { + std::cout << "\n " << version; + } + std::cout << '\n'; + } + + void activateCurrent(const fs::path& root, const std::string_view selected) + { + const fs::path temporary = + root / + (".current." + std::to_string(::getpid()) + "." + requestId()); + std::error_code error; + fs::create_symlink(fs::path{"versions"} / selected, temporary, error); + if (error) { + throw UpdateError{"cannot create replacement current link: " + + error.message()}; + } + fs::rename(temporary, root / "current", error); + if (error) { + fs::remove(temporary); + throw UpdateError{"cannot publish replacement current link: " + + error.message()}; + } + syncDirectory(root); + } + + void updateInstallRecords(const fs::path& root, + const std::string_view version) + { + const fs::path legacyPath = root / ".echoion-install"; + const std::string oldLegacy = + readRegularFileNoFollow(legacyPath, 1024U * 1024U); + std::istringstream input{oldLegacy}; + std::ostringstream legacyOutput; + std::string line; + std::size_t replacements{}; + while (std::getline(input, line)) { + if (line.starts_with("version=")) { + legacyOutput << "version=" << version << '\n'; + ++replacements; + } else { + legacyOutput << line << '\n'; + } + } + if (replacements != 1U) { + throw UpdateError{"install record has no unique version field"}; + } + + const fs::path jsonPath = root / "install.json"; + std::optional oldJson; + std::optional newJson; + if (fs::exists(jsonPath)) { + oldJson = readRegularFileNoFollow(jsonPath, 1024U * 1024U); + static const std::regex versionPattern{ + R"(("version"[[:space:]]*:[[:space:]]*")[A-Za-z0-9._-]+("))"}; + const auto begin = std::sregex_iterator{ + oldJson->begin(), oldJson->end(), versionPattern}; + const auto end = std::sregex_iterator{}; + if (std::distance(begin, end) != 1) { + throw UpdateError{ + "public install record has no unique version field"}; + } + std::smatch match; + if (!std::regex_search(*oldJson, match, versionPattern)) { + throw UpdateError{ + "cannot locate public install record version"}; + } + newJson = match.prefix().str() + match.str(1) + + std::string{version} + match.str(2) + + match.suffix().str(); + } + + atomicWrite(legacyPath, legacyOutput.str()); + try { + if (newJson.has_value()) { + atomicWrite(jsonPath, *newJson); + } + } catch (...) { + atomicWrite(legacyPath, oldLegacy); + throw; + } + } + + [[nodiscard]] Void::Semver::Version + parseRuntimeVersion(const std::string_view version) + { + auto parsed = Void::Semver::parse_strict(version); + if (!parsed.has_value() || parsed->to_string() != version) { + throw UpdateError{"runtime version is not canonical SemVer: " + + std::string{version}}; + } + return std::move(*parsed); + } + + void recordRuntimeHealthy(const fs::path& root, + const std::string_view version) + { + Void::Update::VersionStore store{root}; + if (auto recorded = store.recordHealthy(parseRuntimeVersion(version)); + !recorded) { + throw UpdateError{"cannot record healthy runtime version: " + + recorded.error().message()}; + } + } + + void recordRuntimeFailed(const fs::path& root, + const std::string_view version) + { + Void::Update::VersionStore store{root}; + if (auto recorded = store.recordFailed(parseRuntimeVersion(version)); + !recorded) { + throw UpdateError{"cannot record failed runtime version: " + + recorded.error().message()}; + } + } + + [[nodiscard]] std::vector + healthyRuntimeVersions(const fs::path& root) + { + Void::Update::VersionStore store{root}; + auto healthy = store.healthyPublishedVersions(); + if (!healthy) { + throw UpdateError{"cannot read healthy runtime versions: " + + healthy.error().message()}; + } + std::vector result; + result.reserve(healthy->size()); + std::ranges::transform(*healthy, std::back_inserter(result), + [](const Void::Semver::Version& version) { + return version.to_string(); + }); + return result; + } + + void requireHealthyRuntime(const fs::path& root, + const std::string_view version) + { + const auto healthy = healthyRuntimeVersions(root); + if (std::ranges::find(healthy, version) == healthy.end()) { + throw UpdateError{"requested runtime is not recorded healthy: " + + std::string{version}}; + } + } + + void pruneRuntimeVersions(const fs::path& root, + const std::uint32_t retainHealthyVersions) + { + Void::Update::VersionStore store{root}; + if (auto pruned = store.prune(retainHealthyVersions); !pruned) { + throw UpdateError{"cannot prune retained runtime versions: " + + pruned.error().message()}; + } + } + + void writeActivationHandoff(const fs::path& root, + UpdateDirectories& directories, + const std::string_view version, + const std::string_view previousVersion, + const std::string_view state, + const std::uint32_t retainHealthyVersions, + const std::string_view failedVersion = {}) + { + const std::string body = + "{\n \"schemaVersion\": 1,\n \"state\": \"" + jsonEscape(state) + + "\",\n \"version\": \"" + jsonEscape(version) + + "\",\n \"previousVersion\": \"" + jsonEscape(previousVersion) + + "\",\n \"retainHealthyVersions\": " + + std::to_string(retainHealthyVersions) + + ",\n \"manifestPath\": \"versions/" + jsonEscape(version) + + "/manifest.json\",\n \"currentRoot\": \"" + + jsonEscape(root.string()) + "\",\n \"updatedAt\": \"" + + jsonEscape(nowUtc()) + "\"" + + (failedVersion.empty() ? std::string{} + : ",\n \"failedVersion\": \"" + + jsonEscape(failedVersion) + "\"") + + "\n}\n"; + atomicWriteAt(directories.updates(), "activated-runtime.json", body, + 0640); + } + + [[nodiscard]] std::optional + pendingRuntime(const UpdateDirectories& directories) + { + if (!fileExistsAt(directories.updates(), "pending-runtime.json")) { + return std::nullopt; + } + return Echoion::Updater::parsePendingRuntime( + readRegularFileAt(directories.updates(), "pending-runtime.json", + kMaximumRequestBytes)); + } + + [[nodiscard]] std::chrono::system_clock::time_point + parseUtcTimestamp(const std::string_view value) + { + if (value.size() != 20U || value.back() != 'Z') { + throw UpdateError{"pending runtime activation time is invalid"}; + } + std::tm utc{}; + std::istringstream input{std::string{value}}; + input >> std::get_time(&utc, "%Y-%m-%dT%H:%M:%SZ"); + if (!input || input.peek() != std::char_traits::eof()) { + throw UpdateError{"pending runtime activation time is invalid"}; + } + const std::time_t timestamp = ::timegm(&utc); + if (timestamp < 0) { + throw UpdateError{ + "pending runtime activation time is out of range"}; + } + return std::chrono::system_clock::from_time_t(timestamp); + } + + [[nodiscard]] bool + healthGraceExpired(const Echoion::Updater::PendingRuntime& pending) + { + return std::chrono::system_clock::now() >= + parseUtcTimestamp(pending.activatedAt) + kRuntimeHealthGrace; + } + + void writePendingRuntime( + UpdateDirectories& directories, + const Echoion::Updater::RuntimeActivation& activation, + const std::string_view previousVersion) + { + const std::string body = + "{\n \"schemaVersion\": 1,\n \"state\": \"pending\",\n" + " \"candidateId\": \"" + + jsonEscape(activation.stagingId) + "\",\n \"version\": \"" + + jsonEscape(activation.version) + "\",\n \"previousVersion\": \"" + + jsonEscape(previousVersion) + "\",\n \"manifestSha256\": \"" + + jsonEscape(activation.manifestSha256) + + "\",\n \"retainHealthyVersions\": " + + std::to_string(activation.retainHealthyVersions) + + ",\n \"manifestPath\": \"versions/" + + jsonEscape(activation.version) + + "/manifest.json\",\n \"activatedAt\": \"" + jsonEscape(nowUtc()) + + "\"\n}\n"; + atomicWriteAt(directories.updates(), "pending-runtime.json", body, + 0640); + } + + [[nodiscard]] std::optional + archivePendingRuntime(UpdateDirectories& directories, + const std::string_view archiveName) + { + if (!fileExistsAt(directories.updates(), "pending-runtime.json")) { + throw UpdateError{"pending runtime journal disappeared"}; + } + requireLeafName(archiveName); + const std::string ownedArchive{archiveName}; + if (::renameat(directories.updates(), "pending-runtime.json", + directories.updates(), ownedArchive.c_str()) != 0) { + throw UpdateError{ + systemError("cannot archive pending runtime journal")}; + } + if (::fsync(directories.updates()) != 0) { + return systemError("cannot sync archived runtime journal"); + } + return std::nullopt; + } + + void writeRuntimeStatus(UpdateDirectories& directories, + const std::string_view version, + const std::string_view state, + const std::string_view detail = {}) + { + const std::string body = + "{\n \"schemaVersion\": 1,\n \"checkedAt\": \"" + + jsonEscape(nowUtc()) + "\",\n \"current\": \"" + + jsonEscape(version) + "\",\n \"state\": \"" + jsonEscape(state) + + "\"" + + (detail.empty() + ? std::string{} + : ",\n \"detail\": \"" + jsonEscape(detail) + "\"") + + "\n}\n"; + atomicWriteAt(directories.updates(), "status.json", body, 0640); + } + + [[nodiscard]] std::optional + existingActivationHandoff(const UpdateDirectories& directories) + { + if (!fileExistsAt(directories.updates(), "activated-runtime.json")) { + return std::nullopt; + } + return readRegularFileAt(directories.updates(), + "activated-runtime.json", + kMaximumRequestBytes); + } + + void restoreActivationHandoff(UpdateDirectories& directories, + const std::optional& previous) + { + if (previous.has_value()) { + atomicWriteAt(directories.updates(), "activated-runtime.json", + *previous, 0640); + } else if (fileExistsAt(directories.updates(), + "activated-runtime.json")) { + unlinkFileAt(directories.updates(), "activated-runtime.json"); + } + } + + void selectRuntime(const fs::path& root, UpdateDirectories& directories, + const std::string& selected, + const std::string_view operation, + const std::uint32_t retainHealthyVersions) + { + const std::string oldVersion = currentVersion(root); + if (selected == oldVersion) { + throw UpdateError{"requested runtime is already current"}; + } + requireHealthyRuntime(root, selected); + const fs::path release = validateRelease(root, selected); + Echoion::Updater::validateRelease(release, selected); + const auto oldHandoff = existingActivationHandoff(directories); + recordRuntimeHealthy(root, oldVersion); + activateCurrent(root, selected); + try { + updateInstallRecords(root, selected); + writeActivationHandoff(root, directories, selected, oldVersion, + "rolled-back", retainHealthyVersions); + } catch (...) { + activateCurrent(root, oldVersion); + updateInstallRecords(root, oldVersion); + restoreActivationHandoff(directories, oldHandoff); + throw; + } + std::vector warnings; + try { + appendHistory(directories, operation, "activated", + oldVersion + " -> " + selected); + } catch (const std::exception& error) { + warnings.emplace_back(std::string{"update history: "} + + error.what()); + } + try { + recordRuntimeHealthy(root, selected); + } catch (const std::exception& error) { + warnings.emplace_back(std::string{"healthy runtime history: "} + + error.what()); + } + try { + pruneRuntimeVersions(root, retainHealthyVersions); + } catch (const std::exception& error) { + warnings.emplace_back(std::string{"version retention: "} + + error.what()); + } + std::cout << "Activated " << selected + << ". The service was not started or restarted.\n"; + for (const auto& warning : warnings) { + std::cerr << kProgramName << ": warning: runtime " << selected + << " was selected, but " << warning << '\n'; + } + } + + void rollback(const fs::path& root, + const std::optional& requested, + const std::uint32_t retainHealthyVersions, + const std::string_view operation = "rollback") + { + UpdateDirectories directories{root}; + PrefixLock lock{root}; + if (pendingRuntime(directories).has_value()) { + throw UpdateError{"a runtime activation is awaiting health " + "confirmation; run reconcile first"}; + } + const std::string oldVersion = currentVersion(root); + std::string selected; + if (requested.has_value()) { + selected = *requested; + } else { + for (const auto& version : healthyRuntimeVersions(root)) { + if (version != oldVersion) { + selected = version; + break; + } + } + } + if (selected.empty()) { + throw UpdateError{ + "no different healthy installed version is available"}; + } + selectRuntime(root, directories, selected, operation, + retainHealthyVersions); + } + + [[nodiscard]] std::uint32_t + retainedVersions(const std::vector& values) + { + const auto retainValue = optionValue(values, "--retain"); + if (!retainValue.has_value()) { + return kDefaultRetainedVersions; + } + std::uint32_t retain{}; + const auto parsed = + std::from_chars(retainValue->data(), + retainValue->data() + retainValue->size(), retain); + if (parsed.ec != std::errc{} || + parsed.ptr != retainValue->data() + retainValue->size() || + retain < 1U || retain > 10U) { + throw UpdateError{"--retain must be an integer from 1 to 10"}; + } + return retain; + } + + void queueRequest(const fs::path& root, const std::string_view operation, + const std::vector& values) + { + static const std::vector operations{ + "activate-runtime", "rollback-runtime", "commit-runtime"}; + if (std::ranges::find(operations, operation) == operations.end()) { + throw UpdateError{"unsupported request operation"}; + } + const std::vector allowed{ + "--version", "--origin", "--staging", "--manifest-sha256", + "--retain"}; + ensureOnlyOptions(values, allowed); + const auto version = optionValue(values, "--version"); + const auto origin = optionValue(values, "--origin"); + const auto staging = optionValue(values, "--staging"); + const auto manifestDigest = optionValue(values, "--manifest-sha256"); + const std::uint32_t retain = retainedVersions(values); + if (operation == "activate-runtime" && + (!staging.has_value() || !version.has_value() || + !manifestDigest.has_value())) { + throw UpdateError{"activate-runtime requires --staging, --version, " + "and --manifest-sha256"}; + } + if ((operation == "rollback-runtime" || + operation == "commit-runtime") && + !version.has_value()) { + throw UpdateError{std::string{operation} + " requires --version"}; + } + for (const auto* value : {&version, &origin, &staging}) { + if (value->has_value() && !safeIdentifier(**value)) { + throw UpdateError{"request contains an unsafe identifier"}; + } + } + if (manifestDigest.has_value() && !safeDigest(*manifestDigest)) { + throw UpdateError{"manifest digest must be lowercase SHA-256"}; + } + if ((operation == "rollback-runtime" || + operation == "commit-runtime") && + (staging.has_value() || manifestDigest.has_value())) { + throw UpdateError{std::string{operation} + + " has activation-only fields"}; + } + if (operation != "activate-runtime" && + (staging.has_value() || manifestDigest.has_value())) { + throw UpdateError{"request has activation-only fields"}; + } + + const std::string id = requestId(); + std::ostringstream output; + output << "{\n \"schemaVersion\": 1,\n \"id\": \"" << id + << "\",\n \"createdAt\": \"" << jsonEscape(nowUtc()) + << "\",\n \"operation\": \"" << operation << '"'; + const auto emit = [&output](const std::string_view key, + const std::optional& value) { + if (value.has_value()) { + output << ",\n \"" << key << "\": \"" << jsonEscape(*value) + << '"'; + } + }; + emit("version", version); + emit("origin", origin); + emit("stagingId", staging); + emit("manifestSha256", manifestDigest); + output << ",\n \"retainHealthyVersions\": " << retain; + output << "\n}\n"; + if (output.str().size() > kMaximumRequestBytes) { + throw UpdateError{"update request is too large"}; + } + + UpdateDirectories directories{root}; + const std::string filename = id + ".json"; + atomicWriteAt(directories.privilegedRequests(), filename, output.str(), + 0640); + appendHistory(directories, operation, "queued", id); + std::cout + << (directories.path() / "privileged-requests" / filename).string() + << '\n'; + } + + [[nodiscard]] Echoion::Updater::RuntimeActivation + activationOptions(const std::vector& values) + { + ensureOnlyOptions( + values, + {"--staging", "--version", "--manifest-sha256", "--retain"}); + const auto staging = optionValue(values, "--staging"); + const auto version = optionValue(values, "--version"); + const auto digest = optionValue(values, "--manifest-sha256"); + if (!staging.has_value() || !version.has_value() || + !digest.has_value() || !safeIdentifier(*staging) || + !safeIdentifier(*version) || !safeDigest(*digest)) { + throw UpdateError{ + "activate-runtime requires safe --staging, --version, and " + "--manifest-sha256 values"}; + } + return { + .stagingId = *staging, + .version = *version, + .manifestSha256 = *digest, + .retainHealthyVersions = retainedVersions(values), + }; + } + + void activateRuntime(const fs::path& root, + UpdateDirectories& directories, + const Echoion::Updater::RuntimeActivation& activation) + { + PrefixLock lock{root}; + if (pendingRuntime(directories).has_value()) { + throw UpdateError{ + "a runtime activation is already awaiting health confirmation"}; + } + const FileDescriptor source{ + ::openat(directories.staged(), activation.stagingId.c_str(), + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)}; + struct stat stagedMetadata{}; + struct stat sourceMetadata{}; + if (source.get() < 0 || + ::fstat(directories.staged(), &stagedMetadata) != 0 || + ::fstat(source.get(), &sourceMetadata) != 0 || + !S_ISDIR(sourceMetadata.st_mode) || + sourceMetadata.st_uid != stagedMetadata.st_uid) { + throw UpdateError{ + "staged runtime is not a pinned, correctly owned directory"}; + } + const fs::path versions = + canonicalDirectory(root / "versions", "versions directory"); + const fs::path destination = versions / activation.version; + if (fs::exists(destination) || + fs::is_symlink(fs::symlink_status(destination))) { + throw UpdateError{"requested runtime version is already installed"}; + } + const fs::path incoming = + versions / (".incoming-" + activation.version + "-" + requestId()); + const std::string oldVersion = currentVersion(root); + const auto oldHandoff = existingActivationHandoff(directories); + recordRuntimeHealthy(root, oldVersion); + bool published{false}; + bool currentChanged{false}; + bool pendingWritten{false}; + try { + Echoion::Updater::copyAndValidateRelease(source.get(), incoming, + activation); + std::error_code error; + fs::rename(incoming, destination, error); + if (error) { + throw UpdateError{"cannot publish runtime version: " + + error.message()}; + } + published = true; + syncDirectory(versions); + writePendingRuntime(directories, activation, oldVersion); + pendingWritten = true; + activateCurrent(root, activation.version); + currentChanged = true; + updateInstallRecords(root, activation.version); + writeActivationHandoff(root, directories, activation.version, + oldVersion, "pending", + activation.retainHealthyVersions); + writeRuntimeStatus(directories, activation.version, + "pending-health", + "awaiting daemon health confirmation"); + } catch (...) { + std::error_code ignored; + bool mayRemovePublished = !currentChanged; + if (currentChanged) { + try { + activateCurrent(root, oldVersion); + updateInstallRecords(root, oldVersion); + restoreActivationHandoff(directories, oldHandoff); + mayRemovePublished = true; + } catch (...) { + // Preserve the original failure. Reconcile repairs record + // drift. + } + } + if (pendingWritten && mayRemovePublished) { + try { + unlinkFileAt(directories.updates(), "pending-runtime.json"); + } catch (const std::exception&) { + // Preserve the activation error. Reconciliation will + // process any journal that could not be removed. + } + } + if (published && mayRemovePublished) { + fs::remove_all(destination, ignored); + syncDirectory(versions); + } else if (!published) { + fs::remove_all(incoming, ignored); + } + throw; + } + std::vector warnings; + try { + Echoion::Updater::removeReleaseTreeAt(directories.staged(), + activation.stagingId); + } catch (const std::exception& error) { + warnings.emplace_back(std::string{"staged cleanup: "} + + error.what()); + } + try { + appendHistory(directories, "activate-runtime", "activated", + oldVersion + " -> " + activation.version); + } catch (const std::exception& error) { + warnings.emplace_back(std::string{"update history: "} + + error.what()); + } + std::cout + << "Activated " << activation.version + << " pending health confirmation. The service was not started or " + "restarted.\n"; + for (const auto& warning : warnings) { + std::cerr << kProgramName << ": warning: runtime " + << activation.version << " was activated, but " << warning + << '\n'; + } + } + + void commitRuntime(const fs::path& root, UpdateDirectories& directories, + const std::string& version) + { + if (!safeIdentifier(version)) { + throw UpdateError{"unsafe runtime commit version"}; + } + PrefixLock lock{root}; + const auto pending = pendingRuntime(directories); + if (!pending.has_value()) { + throw UpdateError{ + "no runtime activation is awaiting health confirmation"}; + } + if (pending->version != version) { + throw UpdateError{ + "runtime health confirmation does not match the pending " + "version"}; + } + if (currentVersion(root) != version) { + throw UpdateError{ + "current runtime does not match the pending activation"}; + } + const fs::path release = validateRelease(root, version); + Echoion::Updater::validateRelease(release, version, + pending->manifestSha256); + updateInstallRecords(root, version); + + // Renaming the pending journal is the durable commit point. A later + // status write failure must never make a health-confirmed runtime roll + // back. + std::vector warnings; + if (auto warning = + archivePendingRuntime(directories, "committed-runtime.json")) { + warnings.push_back(std::move(*warning)); + } + const auto metadata = [&warnings](const std::string_view operation, + auto&& function) { + try { + std::invoke(std::forward(function)); + } catch (const std::exception& error) { + warnings.emplace_back(std::string{operation} + ": " + + error.what()); + } + }; + metadata("activation handoff", [&] { + writeActivationHandoff(root, directories, version, + pending->previousVersion, "committed", + pending->retainHealthyVersions); + }); + metadata("runtime status", [&] { + writeRuntimeStatus(directories, version, "healthy", + "daemon health confirmed"); + }); + metadata("update history", [&] { + appendHistory(directories, "commit-runtime", "committed", version); + }); + metadata("healthy runtime history", + [&] { recordRuntimeHealthy(root, version); }); + metadata("version retention", [&] { + pruneRuntimeVersions(root, pending->retainHealthyVersions); + }); + std::cout << "Committed healthy runtime " << version << ".\n"; + for (const auto& warning : warnings) { + std::cerr << kProgramName << ": warning: runtime " << version + << " was committed, but " << warning << '\n'; + } + } + + void rollbackPendingRuntime(const fs::path& root, + UpdateDirectories& directories, + const std::string_view reason) + { + PrefixLock lock{root}; + const auto pending = pendingRuntime(directories); + if (!pending.has_value()) { + return; + } + const fs::path previousRelease = + validateRelease(root, pending->previousVersion); + Echoion::Updater::validateRelease(previousRelease, + pending->previousVersion); + const std::string selected = currentVersion(root); + if (selected != pending->version && + selected != pending->previousVersion) { + throw UpdateError{ + "current runtime diverged from the pending activation journal"}; + } + + const auto oldHandoff = existingActivationHandoff(directories); + const bool currentChanged = selected == pending->version; + std::vector warnings; + try { + if (currentChanged) { + activateCurrent(root, pending->previousVersion); + } + updateInstallRecords(root, pending->previousVersion); + const std::string failure = + "{\n \"schemaVersion\": 1,\n \"candidateId\": \"" + + jsonEscape(pending->candidateId) + "\",\n \"version\": \"" + + jsonEscape(pending->version) + + "\",\n \"previousVersion\": \"" + + jsonEscape(pending->previousVersion) + + "\",\n \"manifestPath\": \"versions/" + + jsonEscape(pending->version) + + "/manifest.json\",\n \"failedAt\": \"" + jsonEscape(nowUtc()) + + "\",\n \"reason\": \"" + jsonEscape(reason) + "\"\n}\n"; + atomicWriteAt(directories.updates(), "failed-runtime.json", failure, + 0640); + writeActivationHandoff(root, directories, pending->previousVersion, + pending->version, "rolled-back", + pending->retainHealthyVersions, + pending->version); + writeRuntimeStatus(directories, pending->previousVersion, + "rolled-back", reason); + if (auto warning = archivePendingRuntime( + directories, "failed-pending-runtime.json")) { + warnings.push_back(std::move(*warning)); + } + } catch (...) { + if (currentChanged) { + try { + activateCurrent(root, pending->version); + updateInstallRecords(root, pending->version); + restoreActivationHandoff(directories, oldHandoff); + } catch (...) { + // Keep the pending journal for the next reconciliation + // attempt. + } + } else { + try { + restoreActivationHandoff(directories, oldHandoff); + } catch (...) { + // Keep the pending journal for the next reconciliation + // attempt. + } + } + throw; + } + try { + appendHistory(directories, "activate-runtime", "rolled-back", + pending->version + " -> " + pending->previousVersion + + ": " + std::string{reason}); + } catch (const std::exception& error) { + warnings.emplace_back(std::string{"update history: "} + + error.what()); + } + try { + recordRuntimeFailed(root, pending->version); + } catch (const std::exception& error) { + warnings.emplace_back(std::string{"failed runtime history: "} + + error.what()); + } + try { + recordRuntimeHealthy(root, pending->previousVersion); + } catch (const std::exception& error) { + warnings.emplace_back(std::string{"healthy runtime history: "} + + error.what()); + } + try { + pruneRuntimeVersions(root, pending->retainHealthyVersions); + } catch (const std::exception& error) { + warnings.emplace_back(std::string{"version retention: "} + + error.what()); + } + std::cout << "Rolled back unconfirmed runtime " << pending->version + << " to " << pending->previousVersion << ".\n"; + for (const auto& warning : warnings) { + std::cerr << kProgramName + << ": warning: runtime rollback committed, but " + << warning << '\n'; + } + } + + void rollbackRuntime(const fs::path& root, UpdateDirectories& directories, + const std::string& version, + const std::uint32_t retainHealthyVersions) + { + if (!safeIdentifier(version)) { + throw UpdateError{"unsafe rollback version"}; + } + PrefixLock lock{root}; + if (pendingRuntime(directories).has_value()) { + throw UpdateError{"a runtime activation is awaiting health " + "confirmation; run reconcile first"}; + } + if (currentVersion(root) == version) { + requireHealthyRuntime(root, version); + const fs::path release = validateRelease(root, version); + Echoion::Updater::validateRelease(release, version); + recordRuntimeHealthy(root, version); + pruneRuntimeVersions(root, retainHealthyVersions); + return; + } + selectRuntime(root, directories, version, "rollback-runtime", + retainHealthyVersions); + } + + [[nodiscard]] bool safeRequestName(const std::string_view name) + { + const fs::path path{name}; + return path.extension() == ".json" && + safeIdentifier(path.stem().string()) && + path.filename() == path && name.size() <= 70U; + } + + void consumeRequests(const fs::path& root) + { + constexpr std::size_t kMaximumRequestsPerRun{32U}; + constexpr std::size_t kMaximumQueuedEntries{1024U}; + UpdateDirectories directories{root}; + std::vector requests; + for (const auto& name : directoryEntries( + directories.privilegedRequests(), kMaximumQueuedEntries)) { + if (requests.size() >= kMaximumRequestsPerRun) { + break; + } + struct stat metadata{}; + if (safeRequestName(name) && + ::fstatat(directories.privilegedRequests(), name.c_str(), + &metadata, AT_SYMLINK_NOFOLLOW) == 0 && + S_ISREG(metadata.st_mode) && metadata.st_nlink == 1) { + requests.push_back(name); + } + } + std::ranges::sort(requests); + if (const auto pending = pendingRuntime(directories); + pending.has_value()) { + const auto matchingCommit = std::ranges::find_if( + requests, [&pending, &directories](const std::string& request) { + try { + const auto parsed = + Echoion::Updater::parsePrivilegedRequest( + readRegularFileAt( + directories.privilegedRequests(), request, + kMaximumRequestBytes)); + const auto* commit = + std::get_if( + &parsed); + return commit != nullptr && + commit->version == pending->version; + } catch (const std::exception&) { + return false; + } + }); + if (matchingCommit == requests.end() && + healthGraceExpired(*pending)) { + rollbackPendingRuntime( + root, directories, + "daemon health confirmation was not received before the " + "durable grace deadline"); + } else { + if (matchingCommit != requests.end()) { + std::rotate(requests.begin(), matchingCommit, + std::next(matchingCommit)); + } + } + } + std::size_t failures{}; + for (const std::string& request : requests) { + std::string bytes; + bool claimed{false}; + try { + moveFileAt(directories.privilegedRequests(), request, + directories.processed(), request); + claimed = true; + bytes = readRegularFileAt(directories.processed(), request, + kMaximumRequestBytes); + const auto operation = + Echoion::Updater::parsePrivilegedRequest(bytes); + std::visit( + [&root, &directories](const auto& value) { + using Request = std::decay_t; + if constexpr (std::same_as) { + activateRuntime(root, directories, value); + } else if constexpr ( + std::same_as) { + rollbackRuntime(root, directories, value.version, + value.retainHealthyVersions); + } else { + commitRuntime(root, directories, value.version); + } + }, + operation); + } catch (const std::exception& error) { + ++failures; + std::cerr << kProgramName << ": rejected privileged request " + << request << ": " << error.what() << '\n'; + if (claimed && fileExistsAt(directories.processed(), request)) { + moveFileAt(directories.processed(), request, + directories.rejected(), request); + } + const std::string errorRecord = + "{\"time\":\"" + jsonEscape(nowUtc()) + "\",\"error\":\"" + + jsonEscape(error.what()) + "\"}\n"; + atomicWriteAt(directories.rejected(), request + ".error.json", + errorRecord, 0640); + appendHistory(directories, "consume", "rejected", request); + } + } + if (failures != 0U) { + throw UpdateError{std::to_string(failures) + + " privileged update request(s) were rejected"}; + } + std::cout << "Consumed " << requests.size() + << " privileged request(s).\n"; + } + + void reconcile(const fs::path& root) + { + UpdateDirectories directories{root}; + const auto unconfirmed = pendingRuntime(directories); + if (unconfirmed.has_value()) { + rollbackPendingRuntime( + root, directories, + "reconciliation found an unconfirmed runtime"); + } + PrefixLock lock{root}; + const std::string version = currentVersion(root); + const fs::path release = validateRelease(root, version); + Echoion::Updater::validateRelease(release, version); + updateInstallRecords(root, version); + const std::string_view state = + unconfirmed.has_value() ? "rolled-back" : "ready"; + writeRuntimeStatus( + directories, version, state, + unconfirmed.has_value() + ? "unconfirmed runtime was restored to the previous version" + : std::string_view{}); + appendHistory(directories, "reconcile", state, version); + std::cout << "Installation is consistent at " << version << ".\n"; + } + + void printUsage() + { + std::cout + << "Usage: echoion-updater [--root PATH] COMMAND [OPTIONS]\n\n" + "Commands:\n" + " status [--json] inspect installed releases\n" + " request OPERATION [...] queue a privileged runtime " + "request\n" + " activate-runtime --staging ID --version V --manifest-sha256 " + "HEX [--retain N]\n" + " publish a local staged " + "runtime\n" + " commit-runtime --version V [--retain N]\n" + " confirm a healthy " + "activated " + "runtime\n" + " rollback-runtime --version V [--retain N]\n" + " select a validated local " + "runtime\n" + " consume consume bounded privileged " + " rollback [--to VERSION] [--retain N]\n" + " atomically select a local " + "release\n" + " reconcile validate and journal current " + "state\n\n" + "The helper never downloads artifacts and never starts Echoion. " + "Network and\n" + "feed work is handed to the daemon through typed request " + "files.\n"; + } + +} // namespace + +int main(const int argc, char** argv) +{ + try { + if (argc == 2 && (std::string_view{argv[1]} == "--help" || + std::string_view{argv[1]} == "-h")) { + printUsage(); + return 0; + } + const ParsedArguments arguments = parseArguments(argc, argv); + if (arguments.command == "status") { + if (arguments.values.empty()) { + status(arguments.root, false); + } else if (arguments.values == std::vector{"--json"}) { + status(arguments.root, true); + } else { + throw UpdateError{"status accepts only --json"}; + } + } else if (arguments.command == "rollback") { + ensureOnlyOptions(arguments.values, {"--to", "--retain"}); + rollback(arguments.root, optionValue(arguments.values, "--to"), + retainedVersions(arguments.values)); + } else if (arguments.command == "activate-runtime") { + UpdateDirectories directories{arguments.root}; + activateRuntime(arguments.root, directories, + activationOptions(arguments.values)); + } else if (arguments.command == "rollback-runtime") { + ensureOnlyOptions(arguments.values, {"--version", "--retain"}); + const auto version = optionValue(arguments.values, "--version"); + if (!version.has_value()) { + throw UpdateError{"rollback-runtime requires --version"}; + } + const auto retain = retainedVersions(arguments.values); + UpdateDirectories directories{arguments.root}; + rollbackRuntime(arguments.root, directories, *version, retain); + } else if (arguments.command == "commit-runtime") { + ensureOnlyOptions(arguments.values, {"--version", "--retain"}); + const auto version = optionValue(arguments.values, "--version"); + if (!version.has_value()) { + throw UpdateError{"commit-runtime requires --version"}; + } + static_cast(retainedVersions(arguments.values)); + UpdateDirectories directories{arguments.root}; + commitRuntime(arguments.root, directories, *version); + } else if (arguments.command == "consume") { + if (!arguments.values.empty()) { + throw UpdateError{"consume accepts no arguments"}; + } + consumeRequests(arguments.root); + } else if (arguments.command == "reconcile") { + if (!arguments.values.empty()) { + throw UpdateError{"reconcile accepts no arguments"}; + } + reconcile(arguments.root); + } else if (arguments.command == "request") { + if (arguments.values.empty()) { + throw UpdateError{"request requires an operation"}; + } + queueRequest( + arguments.root, arguments.values.front(), + {arguments.values.begin() + 1, arguments.values.end()}); + } else { + throw UpdateError{"unknown command: " + arguments.command}; + } + return 0; + } catch (const UpdateError& error) { + std::cerr << kProgramName << ": " << error.what() << '\n'; + return 2; + } catch (const std::exception& error) { + std::cerr << kProgramName << ": unexpected error: " << error.what() + << '\n'; + return 1; + } +}