Files
EchoionUpdater/ReleaseTree.cpp
T

1260 lines
41 KiB
C++

#include "ReleaseTree.hpp"
#include <Void/Data/StrictJson.hpp>
#include <algorithm>
#include <array>
#include <cerrno>
#include <cstdint>
#include <cstring>
#include <exception>
#include <filesystem>
#include <fstream>
#include <limits>
#include <map>
#include <memory>
#include <ranges>
#include <set>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>
#include <variant>
#include <vector>
#include <dirent.h>
#include <fcntl.h>
#include <openssl/evp.h>
#include <sys/stat.h>
#include <unistd.h>
namespace Echoion::Updater
{
namespace
{
namespace fs = std::filesystem;
constexpr std::size_t kMaximumJsonBytes{16U * 1024U * 1024U};
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<DIR, DirectoryCloser>;
[[nodiscard]] std::runtime_error
systemError(const std::string_view operation)
{
return std::runtime_error{std::string{operation} + ": " +
std::strerror(errno)};
}
using Json = Void::Json::Strict::Value;
class JsonParser final
{
public:
explicit JsonParser(const std::string_view input)
: input_{input}
{
}
[[nodiscard]] Json parse() const
{
auto result = Void::Json::Strict::parse(input_);
if (!result) {
throw std::runtime_error{
"invalid JSON at byte " +
std::to_string(result.error().offset) + ": " +
result.error().message};
}
return std::move(*result);
}
private:
std::string_view input_;
};
[[nodiscard]] const Json::Object &
object(const Json &value, const std::string_view description)
{
const auto *result = std::get_if<Json::Object>(&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<Json::Array>(&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<std::string>(&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<std::int64_t>(&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<std::int64_t>(&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<std::uint32_t>(*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<unsigned char>(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<std::size_t>(size), '\0');
input.read(result.data(),
static_cast<std::streamsize>(result.size()));
if (!input || input.peek() != std::char_traits<char>::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<unsigned int>(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<std::string_view>
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<std::string_view> 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<std::string_view> 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<std::string_view> &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<unsigned int>(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<std::uintmax_t>(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 <typename Visitor>
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<std::string>
directoryEntries(const int descriptor)
{
std::vector<std::string> 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<std::size_t>(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<std::uintmax_t>(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<char, 1024U * 1024U> buffer{};
const auto expectedBytes =
static_cast<std::uintmax_t>(before.st_size);
std::uintmax_t copiedBytes{};
while (copiedBytes < expectedBytes) {
const auto remaining = expectedBytes - copiedBytes;
const auto requested = static_cast<std::size_t>(
std::min<std::uintmax_t>(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<std::size_t>(count));
copiedBytes += static_cast<std::uintmax_t>(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<char> 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<std::size_t>(count) >= buffer.size()) {
throw std::runtime_error{"staged release symlink is too long"};
}
return {buffer.data(), static_cast<std::size_t>(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<std::string_view> allowed{
"schemaVersion", "id", "createdAt",
"operation", "stagingId", "version",
"manifestSha256", "origin", "retainHealthyVersions"};
for (const auto &[key, value] : request) {
static_cast<void>(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<std::string>(&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<std::string_view> allowed{
"schemaVersion", "candidateId", "version",
"previousVersion", "manifestSha256", "manifestPath",
"activatedAt", "state", "retainHealthyVersions"};
for (const auto &[key, child] : pending) {
static_cast<void>(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<RuntimeActivation>(&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<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)> 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<char, 1024U * 1024U> buffer{};
while (input) {
input.read(buffer.data(),
static_cast<std::streamsize>(buffer.size()));
const auto count = input.gcount();
if (count > 0 &&
EVP_DigestUpdate(context.get(), buffer.data(),
static_cast<std::size_t>(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<unsigned char, EVP_MAX_MD_SIZE> 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<std::string, std::string> 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<std::uintmax_t>(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<void>(
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<std::string, std::string> 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<std::string, std::string> 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/certs/ca-certificates.crt", "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<void>(::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